commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
bbcf963452878789fdef00e5449d4a08779a1a9d | test/socket-api.test.js | test/socket-api.test.js | var assert = require('chai').assert;
var nodemock = require('nodemock');
var utils = require('./test-utils');
var express = require('express');
var socketAdaptor = require('../lib/socket-adaptor');
var Connection = require('../lib/backend-adaptor').Connection;
var client = require('socket.io-client');
suite('Socket.IO API', function() {
var server;
teardown(function() {
if (server) {
server.close();
}
server = undefined;
});
test('front to back', function() {
var connection = nodemock
.mock('on')
.takes('message', function() {})
.times(socketAdaptor.commands.length)
.mock('emitMessage')
.takes('search', { requestMessage: true }, function() {});
var application = express();
server = utils.setupServer(application);
socketAdaptor.registerHandlers(application, server, {
connection: connection
});
var clientSocket = client.connect('http://localhost:' + utils.testServerPort);
clientSocket.emit('search', { requestMessage: true });
connection.assertThrows();
});
});
| var assert = require('chai').assert;
var nodemock = require('nodemock');
var Deferred = require('jsdeferred').Deferred;
var utils = require('./test-utils');
var express = require('express');
var socketAdaptor = require('../lib/socket-adaptor');
var Connection = require('../lib/backend-adaptor').Connection;
var client = require('socket.io-client');
suite('Socket.IO API', function() {
var server;
teardown(function() {
if (server) {
server.close();
}
server = undefined;
});
test('front to back', function(done) {
var connection = nodemock
.mock('on')
.takes('message', function() {})
.times(socketAdaptor.commands.length)
.mock('emitMessage')
.takes('search', { requestMessage: true });
var application = express();
server = utils.setupServer(application);
socketAdaptor.registerHandlers(application, server, {
connection: connection
});
var clientSocket = client.connect('http://localhost:' + utils.testServerPort);
Deferred
.wait(0.1)
.next(function() {
clientSocket.emit('search', { requestMessage: true });
})
.wait(0.1)
.next(function() {
connection.assertThrows();
done();
})
.error(function(error) {
done(error);
});
});
});
| Test front-to-back communication by socket.io API correctly | Test front-to-back communication by socket.io API correctly
| JavaScript | mit | droonga/express-droonga,KitaitiMakoto/express-droonga,KitaitiMakoto/express-droonga,droonga/express-droonga | ---
+++
@@ -1,5 +1,6 @@
var assert = require('chai').assert;
var nodemock = require('nodemock');
+var Deferred = require('jsdeferred').Deferred;
var utils = require('./test-utils');
@@ -19,13 +20,13 @@
server = undefined;
});
- test('front to back', function() {
+ test('front to back', function(done) {
var connection = nodemock
.mock('on')
.takes('message', function() {})
.times(socketAdaptor.commands.length)
.mock('emitMessage')
- .takes('search', { requestMessage: true }, function() {});
+ .takes('search', { requestMessage: true });
var application = express();
server = utils.setupServer(application);
@@ -34,9 +35,20 @@
});
var clientSocket = client.connect('http://localhost:' + utils.testServerPort);
- clientSocket.emit('search', { requestMessage: true });
- connection.assertThrows();
+ Deferred
+ .wait(0.1)
+ .next(function() {
+ clientSocket.emit('search', { requestMessage: true });
+ })
+ .wait(0.1)
+ .next(function() {
+ connection.assertThrows();
+ done();
+ })
+ .error(function(error) {
+ done(error);
+ });
});
});
|
045461cc12476c6c109e3acffe2583de4fc9e641 | generators/app/templates/webpack/development.js | generators/app/templates/webpack/development.js | const { resolve } = require('path');
module.exports = {
entry: resolve(__dirname, '../src/index.js'),
output: {
path: resolve(__dirname, '../dist'),
filename: '<%= initialComponentName %>.bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.scss$/,
loaders: [
'raw-loader',
'sass-loader'
]
},
{
test: /\.(yml|yaml)$/,
include: resolve(__dirname, '../translations'),
loaders: [
'json-loader',
'yaml-loader'
]
}
]
}
};
| const { resolve } = require('path');
module.exports = {
entry: resolve(__dirname, '../src/index.js'),
output: {
path: resolve(__dirname, '../dist'),
filename: '<%= initialComponentName %>.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader'
]
},
{
test: /\.scss$/,
use: [
'raw-loader',
'sass-loader'
]
},
{
test: /\.(yml|yaml)$/,
include: resolve(__dirname, '../translations'),
use: [
'json-loader',
'yaml-loader'
]
}
]
}
};
| Update config for Webpack 2.0 | Update config for Webpack 2.0
| JavaScript | mit | alexlafroscia/generator-skatejs | ---
+++
@@ -7,15 +7,17 @@
filename: '<%= initialComponentName %>.bundle.js'
},
module: {
- loaders: [
+ rules: [
{
test: /\.js$/,
exclude: /node_modules/,
- loader: 'babel-loader'
+ use: [
+ 'babel-loader'
+ ]
},
{
test: /\.scss$/,
- loaders: [
+ use: [
'raw-loader',
'sass-loader'
]
@@ -23,7 +25,7 @@
{
test: /\.(yml|yaml)$/,
include: resolve(__dirname, '../translations'),
- loaders: [
+ use: [
'json-loader',
'yaml-loader'
] |
0b4580c176366d2b4bbc20cf1a32f4f75abb89dd | renderer-process/transcriptEditor.js | renderer-process/transcriptEditor.js | const Quill = require('quill')
const Delta = require('quill-delta')
const { findAndMatchTimestampsOnTextChange } = require('./matchTimestamps')
const customBlots = ['Timestamp']
const registerBlots = function (blotNames) {
blotNames.map(
function (blotName) {
const blotPath = `./../blots/${blotName}`
const blot = require(blotPath)
Quill.register(blot)
}
)
}
registerBlots(customBlots)
let delta1 = new Delta()
delta1.insert('hello, world!\n', { timestamp: false })
let transcriptEditor = new Quill('.transcript-editor', {
modules: {
toolbar: true // Include button in toolbar
},
theme: 'snow',
placeholder: 'Transcribe away...'
})
findAndMatchTimestampsOnTextChange(transcriptEditor)
transcriptEditor.setContents(delta1)
module.exports = transcriptEditor
| const Quill = require('quill')
const Delta = require('quill-delta')
const { findAndMatchTimestampsOnTextChange } = require('./matchTimestamps')
const customBlots = ['Timestamp']
const registerBlots = function (blotNames) {
blotNames.map(
function (blotName) {
const blotPath = `./../blots/${blotName}`
const blot = require(blotPath)
Quill.register(blot)
}
)
}
registerBlots(customBlots)
let transcriptEditor = new Quill('.transcript-editor', {
modules: {
toolbar: true // Include button in toolbar
},
theme: 'snow',
placeholder: 'Transcribe away...'
})
findAndMatchTimestampsOnTextChange(transcriptEditor)
module.exports = transcriptEditor
| Delete cruft from trying a delta-based approach | Delete cruft from trying a delta-based approach
| JavaScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -15,8 +15,6 @@
registerBlots(customBlots)
-let delta1 = new Delta()
-delta1.insert('hello, world!\n', { timestamp: false })
let transcriptEditor = new Quill('.transcript-editor', {
modules: {
@@ -27,6 +25,5 @@
})
findAndMatchTimestampsOnTextChange(transcriptEditor)
-transcriptEditor.setContents(delta1)
module.exports = transcriptEditor |
682d959e8dc7c3548cc4c4dfb0f00d663b877bc2 | ffi-extend.js | ffi-extend.js | var ffi = require('node-ffi')
, core = require('./core')
, types = require('./types')
, Pointer = ffi.Pointer
, SIZE_MAP = ffi.Bindings.TYPE_SIZE_MAP
, FUNC_MAP = ffi.TYPE_TO_POINTER_METHOD_MAP
/**
* Returns a new Pointer that points to this pointer.
* Equivalent to the "address of" operator:
* type* = &ptr
*/
Pointer.prototype.ref = function ref () {
var ptr = new Pointer(SIZE_MAP.pointer)
ptr.putPointer(this)
return ptr
}
/**
* Dereferences the pointer. Includes wrapping up id instances when necessary.
* Accepts a "type" argument, but that is attempted to be determined
* automatically by the _type prop if it exists.
* Equivalent to the "value at" operator:
* type = *ptr
*/
Pointer.prototype.deref = function deref (type) {
var t = type || this._type
, ffiType = types.map(t)
, val = this['get' + FUNC_MAP[ffiType] ]()
return core.wrapValue(val, t)
}
| var ffi = require('node-ffi')
, core = require('./core')
, types = require('./types')
, Pointer = ffi.Pointer
, SIZE_MAP = ffi.Bindings.TYPE_SIZE_MAP
, FUNC_MAP = ffi.TYPE_TO_POINTER_METHOD_MAP
/**
* Returns a new Pointer that points to this pointer.
* Equivalent to the "address of" operator:
* type* = &ptr
*/
Pointer.prototype.ref = function ref () {
var ptr = new Pointer(SIZE_MAP.pointer)
ptr.putPointer(this)
ptr._type = this._type
return ptr
}
/**
* Dereferences the pointer. Includes wrapping up id instances when necessary.
* Accepts a "type" argument, but that is attempted to be determined
* automatically by the _type prop if it exists.
* Equivalent to the "value at" operator:
* type = *ptr
*/
Pointer.prototype.deref = function deref (type) {
var t = type || this._type
, ffiType = types.map(t)
, val = this['get' + FUNC_MAP[ffiType] ]()
return core.wrapValue(val, t)
}
| Add the type here too. This isn't entirely correct, we should be adding and subtracting ^ to the type, but it makes the test work for now. | Add the type here too. This isn't entirely correct, we should be adding and subtracting ^ to the type, but it makes the test work for now.
| JavaScript | mit | TooTallNate/NodObjC,mralexgray/NodObjC,jerson/NodObjC,telerik/NodObjC,TooTallNate/NodObjC,telerik/NodObjC,mralexgray/NodObjC,jerson/NodObjC,jerson/NodObjC | ---
+++
@@ -13,6 +13,7 @@
Pointer.prototype.ref = function ref () {
var ptr = new Pointer(SIZE_MAP.pointer)
ptr.putPointer(this)
+ ptr._type = this._type
return ptr
}
|
0b570f4a0ce68be3d961b0f71da5bc2305be59e7 | client/lib/components/DataTable/component.js | client/lib/components/DataTable/component.js | import cc from 'classcat'
import React from 'react'
import PropTypes from 'prop-types'
import './style.scss'
function DataTable ({
className,
click,
cols,
records
}) {
if (!cols.length) {
return null
}
const tableClassName = cc([
'table',
'table-bordered',
'table-hover',
'DataTable',
className
])
return (
<div className="table-responsive">
<table className={tableClassName}>
<thead>
<tr>
{cols.map(({ classes, title }, index) => (
<th
key={index}
className={classes}
scope="col"
>
{title}
</th>
))}
</tr>
</thead>
<tbody>
{records.map((row, index) => (
<tr
key={index}
onClick={() => click && click(row, index)}
className="DataTable__row"
>
{cols.map(({ classes, value }, colIndex) => (
<td key={colIndex} className={classes}>{value(row)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)
}
DataTable.propTypes = {
className: PropTypes.string,
click: PropTypes.func,
cols: PropTypes.arrayOf(PropTypes.object),
records: PropTypes.arrayOf(PropTypes.object)
}
DataTable.defaultProps = {
className: undefined,
click: undefined,
cols: [],
records: []
}
export default DataTable
| import cc from 'classcat'
import React from 'react'
import PropTypes from 'prop-types'
import './style.scss'
function DataTable ({
className,
click,
cols,
records
}) {
if (!cols.length) {
return null
}
const tableClassName = cc([
'table',
'table-bordered',
{
'table-hover': !!click
},
'DataTable',
className
])
return (
<div className="table-responsive">
<table className={tableClassName}>
<thead>
<tr>
{cols.map(({ classes, title }, index) => (
<th
key={index}
className={classes}
scope="col"
>
{title}
</th>
))}
</tr>
</thead>
<tbody>
{records.map((row, index) => (
<tr
key={index}
onClick={() => click && click(row, index)}
className="DataTable__row"
>
{cols.map(({ classes, value }, colIndex) => (
<td key={colIndex} className={classes}>{value(row)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)
}
DataTable.propTypes = {
className: PropTypes.string,
click: PropTypes.func,
cols: PropTypes.arrayOf(PropTypes.object),
records: PropTypes.arrayOf(PropTypes.object)
}
DataTable.defaultProps = {
className: undefined,
click: undefined,
cols: [],
records: []
}
export default DataTable
| Enable hover table styling only if row click handler is defined | Enable hover table styling only if row click handler is defined
| JavaScript | mit | dreikanter/feeder,dreikanter/feeder,dreikanter/feeder | ---
+++
@@ -16,7 +16,9 @@
const tableClassName = cc([
'table',
'table-bordered',
- 'table-hover',
+ {
+ 'table-hover': !!click
+ },
'DataTable',
className
]) |
c0339f167b8cf9f05f1077b9160a8a5bade72234 | examples/webpack/worker-loader.js | examples/webpack/worker-loader.js | const build = require('../../tasks/serialize-workers').build;
function loader() {
const callback = this.async();
let minify = false;
// TODO: remove when https://github.com/webpack/webpack/issues/6496 is addressed
const compilation = this._compilation;
if (compilation) {
minify = compilation.compiler.options.mode === 'production';
}
build(this.resource, {minify})
.then(chunk => {
for (const filePath in chunk.modules) {
this.addDependency(filePath);
}
callback(null, chunk.code);
})
.catch(callback);
}
module.exports = loader;
| const build = require('../../tasks/serialize-workers').build;
function loader() {
const callback = this.async();
const minify = this.mode === 'production';
build(this.resource, {minify})
.then(chunk => {
for (const filePath in chunk.modules) {
this.addDependency(filePath);
}
callback(null, chunk.code);
})
.catch(callback);
}
module.exports = loader;
| Use mode from the loader context | Use mode from the loader context
See https://github.com/webpack/webpack/pull/9140.
| JavaScript | bsd-2-clause | ahocevar/openlayers,oterral/ol3,ahocevar/openlayers,stweil/ol3,adube/ol3,stweil/openlayers,ahocevar/openlayers,bjornharrtell/ol3,stweil/ol3,tschaub/ol3,ahocevar/ol3,stweil/ol3,oterral/ol3,geekdenz/openlayers,tschaub/ol3,adube/ol3,stweil/ol3,openlayers/openlayers,stweil/openlayers,geekdenz/ol3,ahocevar/ol3,openlayers/openlayers,stweil/openlayers,geekdenz/ol3,geekdenz/ol3,tschaub/ol3,oterral/ol3,adube/ol3,bjornharrtell/ol3,openlayers/openlayers,geekdenz/openlayers,geekdenz/ol3,tschaub/ol3,ahocevar/ol3,ahocevar/ol3,geekdenz/openlayers,bjornharrtell/ol3 | ---
+++
@@ -2,14 +2,7 @@
function loader() {
const callback = this.async();
-
- let minify = false;
-
- // TODO: remove when https://github.com/webpack/webpack/issues/6496 is addressed
- const compilation = this._compilation;
- if (compilation) {
- minify = compilation.compiler.options.mode === 'production';
- }
+ const minify = this.mode === 'production';
build(this.resource, {minify})
.then(chunk => { |
4a00d4d65e22268361f17aa13eb0be4247531db1 | examples/login/routes.js | examples/login/routes.js | var passport = require('passport'),
Account = require('./models/account');
module.exports = function (app) {
app.get('/', function (req, res) {
res.render('index', { user : req.user });
});
app.get('/register', function(req, res) {
res.render('register', { });
});
app.post('/register', function(req, res) {
var username = req.body.username;
Account.findOne({username : username }, function(err, existingUser) {
if (err || existingUser) {
return res.render('register', { account : account });
}
var account = new Account({ username : req.body.username });
account.setPassword(req.body.password, function(err) {
if (err) {
return res.render('register', { account : account });
}
account.save(function(err) {
if (err) {
return res.render('register', { account : account });
}
res.redirect('/');
});
});
});
});
app.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
} | var passport = require('passport'),
Account = require('./models/account');
module.exports = function (app) {
app.get('/', function (req, res) {
res.render('index', { user : req.user });
});
app.get('/register', function(req, res) {
res.render('register', { });
});
app.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
res.redirect('/');
});
});
app.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
}; | Use register helper method in examples | Use register helper method in examples
| JavaScript | mit | traedamatic/passport-local-mongoose,theanimal666/passport-local-mongoose,saintedlama/passport-local-mongoose,heitortsergent/passport-local-mongoose-email,traedamatic/passport-local-mongoose,saintedlama/passport-local-mongoose,ashertrockman/passport-local-mongoose | ---
+++
@@ -12,27 +12,12 @@
});
app.post('/register', function(req, res) {
- var username = req.body.username;
-
- Account.findOne({username : username }, function(err, existingUser) {
- if (err || existingUser) {
+ Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
+ if (err) {
return res.render('register', { account : account });
}
- var account = new Account({ username : req.body.username });
- account.setPassword(req.body.password, function(err) {
- if (err) {
- return res.render('register', { account : account });
- }
-
- account.save(function(err) {
- if (err) {
- return res.render('register', { account : account });
- }
-
- res.redirect('/');
- });
- });
+ res.redirect('/');
});
});
@@ -48,4 +33,4 @@
req.logout();
res.redirect('/');
});
-}
+}; |
25ff5ad35fc9487f7939c2e26b393cd522679a75 | main.js | main.js | dispatcher = require('edispatcher');
var component_map = {
'example': require('./component/example/example.js')
};
document.addEventListener('DOMContentLoaded', function() {
var components = document.querySelectorAll("[component]");
for (var i = 0, l = components.length; i < l; i++) {
var component = components[i];
var component_name = component.getAttribute("component");
var component_constructor = component_map[component_name];
if (typeof component_constructor === "function") {
new component_map[component_name](component);
} else {
console.warn('There is no constructor for component ' + component_name);
}
}
dispatcher.send('components_loaded', null, 'main');
});
| dispatcher = require('edispatcher');
document.addEventListener('DOMContentLoaded', function() {
var components = document.querySelectorAll("[component]");
for (var i = 0, l = components.length; i < l; i++) {
var component = components[i];
var component_name = component.getAttribute("component");
try {
var component_constructor = require('./component/' + component_name + '/' + component_name + '.js');
new component_constructor(component);
} catch (e) {
console.warn('Failed to initialize component ' + component_name + '. ' + e);
}
}
dispatcher.send('components_loaded', null, 'main');
});
| Change the way of component initialization | Change the way of component initialization
| JavaScript | mit | dmitrykuzmenkov/app-skel-flux,dmitrykuzmenkov/app-skel-flux,dmitrykuzmenkov/app-skel-flux | ---
+++
@@ -1,19 +1,15 @@
dispatcher = require('edispatcher');
-
-var component_map = {
- 'example': require('./component/example/example.js')
-};
document.addEventListener('DOMContentLoaded', function() {
var components = document.querySelectorAll("[component]");
for (var i = 0, l = components.length; i < l; i++) {
var component = components[i];
var component_name = component.getAttribute("component");
- var component_constructor = component_map[component_name];
- if (typeof component_constructor === "function") {
- new component_map[component_name](component);
- } else {
- console.warn('There is no constructor for component ' + component_name);
+ try {
+ var component_constructor = require('./component/' + component_name + '/' + component_name + '.js');
+ new component_constructor(component);
+ } catch (e) {
+ console.warn('Failed to initialize component ' + component_name + '. ' + e);
}
}
dispatcher.send('components_loaded', null, 'main'); |
002de77134c1a2a2ee4e7e966c106a7fde9a66a9 | articles/articleStore.js | articles/articleStore.js | var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongodb.password + '@' +
config.mongodb.host + '/' + config.mongodb.database +
'?authSource=' + config.mongodb.authSource;
MongoClient
.connect(mongoServerUri)
.then(function(db) {
console.log("Connected to mongodb");
dbConnection = db;
dbConnection.on("close", function(err) {
console.log("Mongodb connection closed. Reason:", err);
}).on("error", function(err) {
console.log("Mongodb error:", err);
});
resolve(dbConnection);
}, function(err) {
reject(err);
});
} else {
resolve(dbConnection);
}
});
}
module.exports.saveRawArticles = function(rawArticles) {
getDB().then(function (db) {
console.log("Received " + rawArticles.length + " articles");
rawArticles.forEach(function (article) {
article._id = article.id;
db.collection('raw-articles').insertOne(article).then(function(res) {
console.log(res.insertedCount + " raw article stored in db: " + article.id);
}, function(err) {
console.log("Mongodb error: ", err.errmsg);
});
});
});
};
| var MongoClient = require("mongodb").MongoClient;
var config = require("./config.json");
var dbConnection = null;
function getDB() {
return new Promise(function(resolve, reject) {
if (!dbConnection) {
var mongoServerUri = 'mongodb://' +
config.mongodb.user + ':' + config.mongodb.password + '@' +
config.mongodb.host + '/' + config.mongodb.database +
'?authSource=' + config.mongodb.authSource;
MongoClient
.connect(mongoServerUri)
.then(function(db) {
console.log("Connected to mongodb");
dbConnection = db;
dbConnection.on("close", function(err) {
console.log("Mongodb connection closed. Reason:", err);
}).on("error", function(err) {
console.log("Mongodb error:", err);
});
resolve(dbConnection);
}, function(err) {
reject(err);
});
} else {
resolve(dbConnection);
}
});
}
module.exports.saveRawArticles = function(rawArticles) {
getDB().then(function (db) {
console.log("Received " + rawArticles.length + " articles");
rawArticles.forEach(function (article) {
article._id = article.id;
article.timestamp = new Date();
db.collection('raw-articles').insertOne(article).then(function(res) {
console.log(res.insertedCount + " raw article stored in db: " + article.id);
}, function(err) {
console.log("Mongodb error: ", err.errmsg);
});
});
});
};
| Store timestamp also in articles | Store timestamp also in articles
| JavaScript | mit | nisargjhaveri/news-access,nisargjhaveri/news-access,nisargjhaveri/news-access,nisargjhaveri/news-access | ---
+++
@@ -38,6 +38,7 @@
console.log("Received " + rawArticles.length + " articles");
rawArticles.forEach(function (article) {
article._id = article.id;
+ article.timestamp = new Date();
db.collection('raw-articles').insertOne(article).then(function(res) {
console.log(res.insertedCount + " raw article stored in db: " + article.id); |
d5db04c823652f20f21c36609778807640375bc3 | tests/dummy/app/routes/application.js | tests/dummy/app/routes/application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'
export default Ember.Route.extend( ApplicationRouteMixin, {
init() {
this._super();
},
sessionAuthenticated(){
alert('Got authenticated!');
},
sessionInvalidated(){
alert('Got invalidated');
}
} );
| import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin'
export default Ember.Route.extend( ApplicationRouteMixin, {
init() {
this._super();
},
sessionAuthenticated(){
alert('Got authenticated!');
this._super.call(this);
},
sessionInvalidated(){
alert('Got invalidated');
this._super.call(this);
}
} );
| Call super-method from Mixin in sessionAuthenticated and sessionInvalidated | Call super-method from Mixin in sessionAuthenticated and sessionInvalidated
| JavaScript | mit | mu-semtech/ember-mu-login,mu-semtech/ember-mu-login | ---
+++
@@ -7,8 +7,10 @@
},
sessionAuthenticated(){
alert('Got authenticated!');
+ this._super.call(this);
},
sessionInvalidated(){
alert('Got invalidated');
+ this._super.call(this);
}
} ); |
4d40b5fa817f14826b4a3a81a087c4ac2d5e17ba | example/auth_approle.js | example/auth_approle.js | // file: example/approle.js
process.env.DEBUG = 'node-vault'; // switch on debug mode
const vault = require('./../src/index')();
const mountPoint = 'approle';
const roleName = 'test-role';
vault.auths()
.then((result) => {
if (result.hasOwnProperty('approle/')) return undefined;
return vault.enableAuth({
mount_point: mountPoint,
type: 'approle',
description: 'Approle auth',
});
})
.then(() => vault.addApproleRole({ role_name: roleName, policies: 'dev-policy, test-policy' }))
.then(() => Promise.all([vault.getApproleRoleId({ role_name: roleName }),
vault.getApproleRoleSecret({ role_name: roleName })])
)
.then((result) => {
const roleId = result[0].data.role_id;
const secretId = result[1].data.secret_id;
return vault.approleLogin({ role_id: roleId, secret_id: secretId });
})
.then((result) => {
console.log(result);
})
.catch((err) => console.error(err.message)); | // file: example/approle.js
process.env.DEBUG = 'node-vault'; // switch on debug mode
const vault = require('./../src/index')();
const mountPoint = 'approle';
const roleName = 'test-role';
vault.auths()
.then((result) => {
if (result.hasOwnProperty('approle/')) return undefined;
return vault.enableAuth({
mount_point: mountPoint,
type: 'approle',
description: 'Approle auth',
});
})
.then(() => vault.addApproleRole({ role_name: roleName, policies: 'dev-policy, test-policy' }))
.then(() => Promise.all([vault.getApproleRoleId({ role_name: roleName }),
vault.getApproleRoleSecret({ role_name: roleName })])
)
.then((result) => {
const roleId = result[0].data.role_id;
const secretId = result[1].data.secret_id;
return vault.approleLogin({ role_id: roleId, secret_id: secretId });
})
.then((result) => {
console.log(result);
})
.catch((err) => console.error(err.message));
| Add required newline at end of file | Add required newline at end of file
| JavaScript | mit | Aloomaio/node-vault,kr1sp1n/node-vault | |
4ba9ce952cd31c51301a27cdcda61f63428414eb | koans/AboutBase.js | koans/AboutBase.js | describe("About <SubjectName>", function () {
describe("<SubjectPart>", function () {
beforeEach(function () {});
afterEach(function () {});
before(function () {});
after(function () {});
it("should <explain what it does>", function () {
// expect().toBe();
});
});
});
| // describe("About <SubjectName>", function () {
//
// describe("<SubjectPart>", function () {
//
// beforeEach(function () {});
// afterEach(function () {});
// before(function () {});
// after(function () {});
//
// it("should <explain what it does>", function () {
// // expect().toBe();
// });
// });
// });
| Comment out template koans to stop it showing in the test runner | chore: Comment out template koans to stop it showing in the test runner
| JavaScript | mit | tawashley/es6-javascript-koans,tawashley/es6-javascript-koans,tawashley/es6-javascript-koans | ---
+++
@@ -1,14 +1,14 @@
-describe("About <SubjectName>", function () {
-
- describe("<SubjectPart>", function () {
-
- beforeEach(function () {});
- afterEach(function () {});
- before(function () {});
- after(function () {});
-
- it("should <explain what it does>", function () {
- // expect().toBe();
- });
- });
-});
+// describe("About <SubjectName>", function () {
+//
+// describe("<SubjectPart>", function () {
+//
+// beforeEach(function () {});
+// afterEach(function () {});
+// before(function () {});
+// after(function () {});
+//
+// it("should <explain what it does>", function () {
+// // expect().toBe();
+// });
+// });
+// }); |
101ae484f401543217bf2760f4c58b3e756ee494 | test/mocha/test-runner.js | test/mocha/test-runner.js | // Make async.
if (window.__karma__) {
window.__karma__.loaded = function() {};
}
// Set the application endpoint and load the configuration.
require.config({
paths: {
// Testing libraries.
"mocha": "../vendor/bower/mocha/mocha",
"chai": "../vendor/bower/chai/chai",
// Location of tests.
spec: "../test/mocha/spec",
specs: "../test/mocha/specs"
},
shim: {
"mocha": { exports: "mocha", deps: ["chai"] }
},
// Determine the baseUrl if we are in Karma or not.
baseUrl: window.__karma__ ? "base/app" : "../../app"
});
require([
"config",
"mocha"
],
function(config, mocha) {
// Set up the assertion library.
// Compatible libraries: http://visionmedia.github.io/mocha/#assertions
window.expect = require("chai").expect;
require(["specs"], function(specs) {
// Load all specs.
require(specs.specs, function() {
if (window.__karma__) {
// This will start Karma if it exists.
return window.__karma__.start();
}
// Only once the dependencies have finished loading, call mocha.run.
mocha.run();
});
});
});
| // Make async.
if (window.__karma__) {
window.__karma__.loaded = function() {};
}
// Set the application endpoint and load the configuration.
require.config({
paths: {
// Testing libraries.
"mocha": "../vendor/bower/mocha/mocha",
"chai": "../vendor/bower/chai/chai",
// Location of tests.
spec: "../test/mocha/spec",
specs: "../test/mocha/specs"
},
shim: {
"mocha": { exports: "mocha", deps: ["chai"] }
},
// Determine the baseUrl if we are in Karma or not.
baseUrl: window.__karma__ ? "base/app" : "../../app"
});
require([
"config",
"mocha"
],
function(config, mocha) {
// Set up the assertion library.
// Compatible libraries: http://visionmedia.github.io/mocha/#assertions
window.expect = require("chai").expect;
// Prefer the BDD testing style outside of Karma's runner.
if (!window.__karma__) {
mocha.setup("bdd");
}
require(["specs"], function(specs) {
// Load all specs.
require(specs.specs, function() {
if (window.__karma__) {
// This will start Karma if it exists.
return window.__karma__.start();
}
// Only once the dependencies have finished loading, call mocha.run.
mocha.run();
});
});
});
| Fix Mocha to run in browser and node tests. This is most likely a bug with karma-mocha. | Fix Mocha to run in browser and node tests. This is most likely a bug with karma-mocha.
| JavaScript | mit | JrPribs/backbone-boilerplate,MandeepRangi/doStuffMediaTest,jSanchoDev/backbone-boilerplate,adrianha/backbone-boilerplate,Hless/backbone-phonegap-boilerplate,danielabalta/albaneagra,si-ro/backbone-boilerplate-ver1,element4git/wipro,si-ro/todo-app2,codeimpossible/backbone-boilerplate,backbone-boilerplate/backbone-boilerplate,GerHobbelt/backbone-boilerplate,jSanchoDev/backbone-boilerplate,nuc-gr/backbone-boilerplate-chaplin,adrianha/backbone-boilerplate,brock/backbone-boilerplate,MandeepRangi/doStuffMediaTest,element4git/wipro,liuweifeng/backbone-boilerplate,tbranyen/backbone-boilerplate,spoonben/backbone-boilerplate,dclowd9901/single-page-todo-app-no-server,dotmpe/backbone-boilerplate,dclowd9901/single-page-todo-app-no-server,spoonben/backbone-boilerplate,backbone-boilerplate/backbone-boilerplate,dotmpe/backbone-boilerplate,gercheq/backbone-boilerplate,naveda89/backbone-boilerplate,tbranyen/backbone-boilerplate,si-ro/todo-app | ---
+++
@@ -33,6 +33,11 @@
// Compatible libraries: http://visionmedia.github.io/mocha/#assertions
window.expect = require("chai").expect;
+ // Prefer the BDD testing style outside of Karma's runner.
+ if (!window.__karma__) {
+ mocha.setup("bdd");
+ }
+
require(["specs"], function(specs) {
// Load all specs.
require(specs.specs, function() { |
23d51c822aedb56e0257455475dad58e4541bee2 | assets/src/amp-blocks.js | assets/src/amp-blocks.js | /**
* WordPress dependencies
*/
import { registerBlockType } from '@wordpress/blocks';
const context = require.context( './blocks', true, /index\.js$/ );
context.keys().forEach( ( modulePath ) => {
const { name, settings } = context( modulePath );
if ( name.includes( 'story' ) ) {
return;
}
registerBlockType( name, settings );
} );
| /**
* WordPress dependencies
*/
import { registerBlockType } from '@wordpress/blocks';
const context = require.context( './blocks', true, /((?<!story.*)\/index\.js)$/ );
context.keys().forEach( ( modulePath ) => {
const { name, settings } = context( modulePath );
registerBlockType( name, settings );
} );
| Fix regex for non-story blocks require.context | Fix regex for non-story blocks require.context
| JavaScript | apache-2.0 | ampproject/amp-toolbox-php,ampproject/amp-toolbox-php | ---
+++
@@ -3,14 +3,9 @@
*/
import { registerBlockType } from '@wordpress/blocks';
-const context = require.context( './blocks', true, /index\.js$/ );
+const context = require.context( './blocks', true, /((?<!story.*)\/index\.js)$/ );
context.keys().forEach( ( modulePath ) => {
const { name, settings } = context( modulePath );
-
- if ( name.includes( 'story' ) ) {
- return;
- }
-
registerBlockType( name, settings );
} ); |
b8408aec2f1318b6b974ac53f06525424ecdfe0f | test/index.js | test/index.js | var chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
sinonChai = require("sinon-chai");
chai.use(sinonChai);
var introject = require('../lib');
describe('injectDeps', function() {
it('should properly inject deps', function() {
var _add = function(a, b) {
return a + b;
};
var injected = introject.injectDeps(_add, {
a: 3,
b: 5
});
expect(injected()).to.equal(3 + 5);
});
});
| var chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
sinonChai = require("sinon-chai");
chai.use(sinonChai);
var introject = require('../lib');
describe('injectDeps', function() {
it('should properly inject deps', function() {
var _add = function(a, b) {
return a + b;
};
var injected = introject.injectDeps(_add, {
a: 3,
b: 5
});
expect(injected()).to.equal(3 + 5);
});
it('should try to require missing deps', function() {
var something = {};
var doSomethingWithFs = function(fs) {
something.read = fs.read;
};
var injected = introject.injectDeps(doSomethingWithFs, {});
injected();
expect(something.read).to.equal(require('fs').read);
});
});
| Add test for requiring undefined deps | Add test for requiring undefined deps
| JavaScript | mit | elvinyung/introject | ---
+++
@@ -19,4 +19,14 @@
expect(injected()).to.equal(3 + 5);
});
+
+ it('should try to require missing deps', function() {
+ var something = {};
+ var doSomethingWithFs = function(fs) {
+ something.read = fs.read;
+ };
+ var injected = introject.injectDeps(doSomethingWithFs, {});
+ injected();
+ expect(something.read).to.equal(require('fs').read);
+ });
}); |
f9217630184ad848b0325b400d2813257d8463d7 | src/files/navigation.js | src/files/navigation.js | var sidebarOpen = false;
var menuText = ["Menu", "Close"];
var menuElement = document.querySelector(".menu-link");
var sidebarElement = document.querySelector(".sidebar");
var headerElement = document.querySelector("header");
menuElement.addEventListener( "click", toggleSidebar, false );
window.addEventListener( "hashchange", toggleSidebar, false );
function toggleSidebar ( event ) {
// Don't toggle when there's nothing to hide.
if (event.type === "hashchange" && !sidebarOpen) return;
sidebarOpen = (!sidebarOpen);
menuLinkEl.textContent = menuLinkText[(sidebarOpen ? 1 : 0)];
sidebarEl.classList.toggle( "sidebar-open" );
headerEl.classList.toggle( "hidden" );
} | var sidebarOpen = false;
var menuText = ["Menu", "Close"];
var menuElement = document.querySelector(".menu-link");
var sidebarElement = document.querySelector(".sidebar");
var headerElement = document.querySelector("header");
var rAF;
menuElement.addEventListener( "click", toggleSidebar, false );
window.addEventListener( "hashchange", toggleSidebar, false );
function toggleSidebar ( event ) {
// Don't toggle when there's nothing to hide.
if (event.type === "hashchange" && !sidebarOpen) return;
sidebarOpen = (!sidebarOpen);
cancelAnimationFrame(rAF);
rAF = requestAnimationFrame(function () {
sidebarElement.classList.toggle( "sidebar-open" );
headerElement.classList.toggle( "hidden" );
menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)];
});
} | Add rAF to sidebar animation | Add rAF to sidebar animation
| JavaScript | mit | sveltejs/svelte.technology,sveltejs/svelte.technology | ---
+++
@@ -3,6 +3,7 @@
var menuElement = document.querySelector(".menu-link");
var sidebarElement = document.querySelector(".sidebar");
var headerElement = document.querySelector("header");
+var rAF;
menuElement.addEventListener( "click", toggleSidebar, false );
window.addEventListener( "hashchange", toggleSidebar, false );
@@ -12,8 +13,11 @@
if (event.type === "hashchange" && !sidebarOpen) return;
sidebarOpen = (!sidebarOpen);
- menuLinkEl.textContent = menuLinkText[(sidebarOpen ? 1 : 0)];
- sidebarEl.classList.toggle( "sidebar-open" );
- headerEl.classList.toggle( "hidden" );
+ cancelAnimationFrame(rAF);
+ rAF = requestAnimationFrame(function () {
+ sidebarElement.classList.toggle( "sidebar-open" );
+ headerElement.classList.toggle( "hidden" );
+ menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)];
+ });
} |
8e2ef3532f1101ae7bcb26b8712ca7a9323ab831 | test/users.js | test/users.js | const test = require('tape')
const miniplug = require('./mocks/mp')
const nock = require('nock')('https://plug.dj')
test('Retrieving a user', async (t) => {
t.plan(1)
nock.get('/_/users/123456').reply(200, require('./mocks/users/123456.json'))
const user = await miniplug().getUser(123456)
t.equal(user.username, 'Username')
})
test('Get the current user', async (t) => {
t.plan(1)
nock.get('/_/users/me').reply(200, require('./mocks/users/me.json'))
const user = await miniplug().getMe()
t.equal(user.username, 'ReAnna')
})
| const test = require('tape')
const miniplug = require('./mocks/mp')
const nock = require('nock')('https://plug.dj')
test('Retrieving a user', async (t) => {
t.plan(1)
nock.get('/_/users/123456').reply(200, require('./mocks/users/123456.json'))
const user = await miniplug().getUser(123456)
t.equal(user.username, 'Username')
})
test('Get the current user', async (t) => {
t.plan(1)
nock.get('/_/users/me').reply(200, require('./mocks/users/me.json'))
const user = await miniplug().getMe()
t.equal(user.username, 'ReAnna')
})
test('Get a user who is currently in the room', async (t) => {
t.plan(3)
nock.post('/_/rooms/join').reply(200, require('./mocks/rooms/join.json'))
nock.get('/_/rooms/state').reply(200, require('./mocks/rooms/state.json'))
const mp = await miniplug()
await mp.join('tastycat')
mp.emit('connected', {
id: 555555
})
t.ok(mp.user(4103894), 'should return user who is in the room')
t.notok(mp.user(123456), 'should not return user who is not in the room')
t.ok(mp.user(555555), 'should get the current user, issue #35')
})
| Add tests for `user()` method. | Add tests for `user()` method.
| JavaScript | mit | goto-bus-stop/miniplug | ---
+++
@@ -19,3 +19,21 @@
const user = await miniplug().getMe()
t.equal(user.username, 'ReAnna')
})
+
+test('Get a user who is currently in the room', async (t) => {
+ t.plan(3)
+
+ nock.post('/_/rooms/join').reply(200, require('./mocks/rooms/join.json'))
+ nock.get('/_/rooms/state').reply(200, require('./mocks/rooms/state.json'))
+
+ const mp = await miniplug()
+ await mp.join('tastycat')
+
+ mp.emit('connected', {
+ id: 555555
+ })
+
+ t.ok(mp.user(4103894), 'should return user who is in the room')
+ t.notok(mp.user(123456), 'should not return user who is not in the room')
+ t.ok(mp.user(555555), 'should get the current user, issue #35')
+}) |
32794a95b5641a7a6e19cdf67a426a7356a944a3 | app/directives/gdOnevarResults.js | app/directives/gdOnevarResults.js | inlist_module.directive('gdOnevarResults', function() { return {
require:'^ngController', //input_list_ctrl
templateUrl:'app/views/onevar_results_table.html',
link: function(scope,elem,attrs,ctrl) {
scope.$watch('inctrl.stats', function(stats) {
document.getElementById('onevar_results_main').innerHTML
= '';
innerdivstring = '';
keys = Object.keys(stats);
for(i=0; i<keys.length; i++) {
var row = document.createElement('tr');
var detail_desc = document.createElement('td');
detail_desc.innerHTML = (ctrl.detail_desc[keys[i]]);
row.appendChild(detail_desc);
var symbol_desc = document.createElement('td');
symbol_desc.innerHTML =
'<script type="math/tex">'
+ ctrl.symbolic_desc[keys[i]] + '</script>';
row.appendChild(symbol_desc);
var data = document.createElement('td');
data.innerHTML = '<script type="math/tex">' +
stats[keys[i]] + '</script>';
row.appendChild(data);
document.getElementById('onevar_results_main')
.appendChild(row);
}
MathJax.Hub.Queue(['Typeset',MathJax.Hub,'onevar_table_main']);
},true);
},
}});
| inlist_module.directive('gdOnevarResults', function() { return {
require:'^ngController', //input_list_ctrl
templateUrl:'app/views/onevar_results_table.html',
link: function(scope,elem,attrs,ctrl) {
scope.$watch('inctrl.stats', function(stats) {
document.getElementById('onevar_results_main').innerHTML
= '';
innerdivstring = '';
keys = Object.keys(stats);
for(i=0; i<keys.length; i++) {
var row = document.createElement('tr');
var detail_desc = document.createElement('td');
detail_desc.innerHTML = (ctrl.detail_desc[keys[i]]);
row.appendChild(detail_desc);
var symbol_desc = document.createElement('td');
symbol_desc.innerHTML =
'<script type="math/tex">'
+ ctrl.symbolic_desc[keys[i]] + '</script>';
row.appendChild(symbol_desc);
var data = document.createElement('td');
if(!stats[keys[i]] && stats[keys[i]] != 0) {
data.innerHTML = 'Undefined'
} else {
data.innerHTML = '<script type="math/tex">' +
stats[keys[i]] + '</script>';
}
row.appendChild(data);
document.getElementById('onevar_results_main')
.appendChild(row);
}
MathJax.Hub.Queue(['Typeset',MathJax.Hub,'onevar_table_main']);
},true);
},
}});
| Add undefined instead of nan if only one number | Add undefined instead of nan if only one number
| JavaScript | agpl-3.0 | gderecho/stats,gderecho/stats | ---
+++
@@ -18,8 +18,13 @@
+ ctrl.symbolic_desc[keys[i]] + '</script>';
row.appendChild(symbol_desc);
var data = document.createElement('td');
- data.innerHTML = '<script type="math/tex">' +
- stats[keys[i]] + '</script>';
+ if(!stats[keys[i]] && stats[keys[i]] != 0) {
+ data.innerHTML = 'Undefined'
+
+ } else {
+ data.innerHTML = '<script type="math/tex">' +
+ stats[keys[i]] + '</script>';
+ }
row.appendChild(data);
document.getElementById('onevar_results_main')
.appendChild(row); |
3cb139d8b5a4e25a98044828cff759a8c9f83879 | app/server/views/visualisation.js | app/server/views/visualisation.js | var requirejs = require('requirejs');
var View = requirejs('extensions/views/view');
module.exports = View.extend({
render: function () {
View.prototype.render.apply(this, arguments);
console.log(this.fallbackUrl);
this.$el.attr('data-src', this.fallbackUrl);
}
}); | var requirejs = require('requirejs');
var View = requirejs('extensions/views/view');
module.exports = View.extend({
render: function () {
View.prototype.render.apply(this, arguments);
this.$el.attr('data-src', this.fallbackUrl);
}
}); | Remove log left in by mistake | Remove log left in by mistake
| JavaScript | mit | keithiopia/spotlight,tijmenb/spotlight,alphagov/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight | ---
+++
@@ -6,7 +6,6 @@
render: function () {
View.prototype.render.apply(this, arguments);
- console.log(this.fallbackUrl);
this.$el.attr('data-src', this.fallbackUrl);
}
|
91621e205caa1a5d3ccaca59928dba76edd42f65 | appcomposer/templates/translator/lib.js | appcomposer/templates/translator/lib.js | // Application found and translatable!
$web_link = $(".field-name-field-app-web-link");
$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} (<a href=\"{{ link }}\">Translate this app</a>)</div></div></div>").insertAfter($web_link);
$web_link = $(".field-name-field-weblink");
$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} (<a href=\"{{ link }}\">Translate this app</a>)</div></div></div>").insertAfter($web_link);
| // Application found and translatable!
$web_link = $(".field-name-field-app-web-link");
$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} </div></div></div>").insertAfter($web_link);
$web_link = $(".field-name-field-weblink");
$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} </div></div></div>").insertAfter($web_link);
| Remove the 'Translate this app' link | Remove the 'Translate this app' link
| JavaScript | bsd-2-clause | morelab/appcomposer,go-lab/appcomposer,morelab/appcomposer,go-lab/appcomposer,go-lab/appcomposer,porduna/appcomposer,morelab/appcomposer,porduna/appcomposer,morelab/appcomposer,porduna/appcomposer,go-lab/appcomposer,porduna/appcomposer | ---
+++
@@ -1,8 +1,8 @@
// Application found and translatable!
$web_link = $(".field-name-field-app-web-link");
-$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} (<a href=\"{{ link }}\">Translate this app</a>)</div></div></div>").insertAfter($web_link);
+$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} </div></div></div>").insertAfter($web_link);
$web_link = $(".field-name-field-weblink");
-$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} (<a href=\"{{ link }}\">Translate this app</a>)</div></div></div>").insertAfter($web_link);
+$("<div class=\"field field-type-link-field field-label-inline clearfix\"><div class=\"field-label\">Available languages: </div><div class=\"field-items\"><div class=\"field-item even\">{{ translations }} </div></div></div>").insertAfter($web_link); |
e45f219a13b8d7c130fa64847026b81866e04535 | lib/Predictions.js | lib/Predictions.js | import React, { Component } from 'react';
import {
StyleSheet,
FlatList,
View
} from 'react-native';
import Prediction from './Prediction';
class Predictions extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={style.container}>
<FlatList
data={this.props.predictions}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem} />
</View>
);
}
_keyExtractor = (prediction) => {
return prediction.id;
}
_renderItem = (data) => {
return (
<Prediction
prediction={data.item}
title={data.item.description}
description={data.item.description}
onPress={this.props.onPressPrediction} />
);
}
}
export const style = StyleSheet.create({
container: {
backgroundColor: 'white',
},
});
export default Predictions;
| import React, { Component } from 'react';
import {
StyleSheet,
FlatList,
View
} from 'react-native';
import Prediction from './Prediction';
class Predictions extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={style.container}>
<FlatList
data={this.props.predictions}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem} />
</View>
);
}
_keyExtractor = (prediction) => {
return prediction.place_id;
}
_renderItem = (data) => {
return (
<Prediction
prediction={data.item}
title={data.item.structured_formatting.main_text}
description={data.item.structured_formatting.secondary_text}
onPress={this.props.onPressPrediction} />
);
}
}
export const style = StyleSheet.create({
container: {
backgroundColor: 'white',
},
});
export default Predictions;
| Use correct properties from predictions response | Use correct properties from predictions response
| JavaScript | mit | chrislam/react-native-google-place-autocomplete | ---
+++
@@ -23,15 +23,15 @@
}
_keyExtractor = (prediction) => {
- return prediction.id;
+ return prediction.place_id;
}
_renderItem = (data) => {
return (
<Prediction
prediction={data.item}
- title={data.item.description}
- description={data.item.description}
+ title={data.item.structured_formatting.main_text}
+ description={data.item.structured_formatting.secondary_text}
onPress={this.props.onPressPrediction} />
);
} |
f77d851b16f40eb6b3406b89d0ab8c12b2efbb51 | app/assets/javascripts/edsn.js | app/assets/javascripts/edsn.js | var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).val());
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = $(this).val();
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
| var EDSN_THRESHOLD = 30;
var EdsnSwitch = (function(){
var editing;
var validBaseLoads = /^(base_load|base_load_edsn)$/;
EdsnSwitch.prototype = {
enable: function(){
if(editing){
swapEdsnBaseLoadSelectBoxes();
}
},
isEdsn: function(){
return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){
swapSelectBox.call(this);
}
};
function swapEdsnBaseLoadSelectBoxes(){
$("tr.base_load_edsn select.name").each(swapSelectBox);
};
function swapSelectBox(){
var technology = $(this).val();
var self = this;
var unitSelector = $(this).parents("tr").find(".units input");
var units = parseInt(unitSelector.val());
var actual = (units > EDSN_THRESHOLD ? "base_load_edsn" : "base_load");
var select = $(".hidden select." + actual).clone(true, true);
$(this).parent().next().html(select);
$(this).find("option[value='" + technology + "']").attr('value', actual);
unitSelector.off('change').on('change', swapSelectBox.bind(self));
};
function EdsnSwitch(_editing){
editing = _editing;
};
return EdsnSwitch;
})();
| Use data attribute instead of val() | Use data attribute instead of val()
| JavaScript | mit | quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses | ---
+++
@@ -12,7 +12,7 @@
},
isEdsn: function(){
- return validBaseLoads.test($(this).val());
+ return validBaseLoads.test($(this).data('type'));
},
cloneAndAppendProfileSelect: function(){ |
bd885efa7e38addd3d975bf388fe0bc9febd4cc8 | src/createPoll.js | src/createPoll.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function createPoll(title, threadID, options, callback) {
if(!callback) {
if(utils.getType(options) == "Function") {
callback = options;
} else {
callback = function() {};
}
}
if(!options) {
options = {}; // Initial poll options are optional
}
var form = {
'target_id' : threadID,
'question_text' : title
};
// Set fields for options (and whether they are selected initially by the posting user)
var ind = 0;
for(var opt in options) {
if(options.hasOwnProperty(opt)) {
form['option_text_array[' + ind + ']'] = encodeURIComponent(opt);
form['option_is_selected_array[' + ind + ']'] = (options[opt] ? '1' : '0');
ind++;
}
}
defaultFuncs
.post("https://www.messenger.com/messaging/group_polling/create_poll/?dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.payload.status != 'success') {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("createPoll", err);
return callback(err);
});
};
};
| "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function createPoll(title, threadID, options, callback) {
if(!callback) {
if(utils.getType(options) == "Function") {
callback = options;
} else {
callback = function() {};
}
}
if(!options) {
options = {}; // Initial poll options are optional
}
var form = {
'target_id' : threadID,
'question_text' : title
};
// Set fields for options (and whether they are selected initially by the posting user)
var ind = 0;
for(var opt in options) {
if(options.hasOwnProperty(opt)) {
form['option_text_array[' + ind + ']'] = opt;
form['option_is_selected_array[' + ind + ']'] = (options[opt] ? '1' : '0');
ind++;
}
}
defaultFuncs
.post("https://www.messenger.com/messaging/group_polling/create_poll/?dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.payload.status != 'success') {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("createPoll", err);
return callback(err);
});
};
};
| Fix unnecessary encoding in poll function | Fix unnecessary encoding in poll function
| JavaScript | mit | ravkr/facebook-chat-api,Schmavery/facebook-chat-api,GAMELASTER/facebook-chat-api | ---
+++
@@ -25,7 +25,7 @@
var ind = 0;
for(var opt in options) {
if(options.hasOwnProperty(opt)) {
- form['option_text_array[' + ind + ']'] = encodeURIComponent(opt);
+ form['option_text_array[' + ind + ']'] = opt;
form['option_is_selected_array[' + ind + ']'] = (options[opt] ? '1' : '0');
ind++;
} |
548d7c5c653608c189b7d5d3143492a42e69c6c9 | imports/client/pages/AboutPage.js | imports/client/pages/AboutPage.js | import React from 'react';
import IntroBand from '../components/About/IntroBand';
import AboutBand from '../components/About/AboutBand';
import ProjectsBand from '../components/About/ProjectsBand';
class AboutPage extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
return (
<div className="about-page">
<IntroBand />
<AboutBand />
<ProjectsBand />
</div>
);
}
}
export default AboutPage;
| import React from 'react';
import IntroBand from '../components/About/IntroBand';
import AboutBand from '../components/About/AboutBand';
import ProjectsBand from '../components/About/ProjectsBand';
import ContactForm from '../components/Contact/ContactForm';
class AboutPage extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
return (
<div className="about-page">
<IntroBand />
<AboutBand />
<ProjectsBand />
<ContactForm />
</div>
);
}
}
export default AboutPage;
| Add contact form to about page | Add contact form to about page
| JavaScript | apache-2.0 | evancorl/portfolio,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio,evancorl/skate-scenes,evancorl/portfolio | ---
+++
@@ -3,6 +3,7 @@
import IntroBand from '../components/About/IntroBand';
import AboutBand from '../components/About/AboutBand';
import ProjectsBand from '../components/About/ProjectsBand';
+import ContactForm from '../components/Contact/ContactForm';
class AboutPage extends React.Component {
shouldComponentUpdate() {
@@ -15,6 +16,7 @@
<IntroBand />
<AboutBand />
<ProjectsBand />
+ <ContactForm />
</div>
);
} |
8671ba83bd37b4e43a3288af2093d19fc611a759 | app/components/Hamburger/index.js | app/components/Hamburger/index.js | import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
const StyledHamburger = styled.div`
position: relative;
width: 15px;
height: 13px;
`;
export const Bar = styled.div`
position: absolute;
height: 3px;
background: ${theme.black};
overflow: hidden;
&::after {
content: '';
display: block;
width: 100%;
height: 100%;
background: ${theme.gray};
position: absolute;
top: 0;
left: 100%;
z-index: 1;
transition: all .3s ease-in-out;
}
&:nth-child(1) {
top: 0;
width: 9px;
&::after {
transition-delay: .1s;
}
}
&:nth-child(2) {
top: 5px;
width: 15px;
&::after {
transition-delay: .2s;
}
}
&:nth-child(3) {
top: 10px;
width: 12px;
&::after {
transition-delay: .3s;
}
}
`;
class Hamburger extends React.PureComponent {
render() {
return (
<StyledHamburger>
<Bar />
<Bar />
<Bar />
</StyledHamburger>
);
}
}
export default Hamburger;
| import React from 'react';
import styled from 'styled-components';
import theme from 'theme';
const StyledHamburger = styled.div`
position: relative;
width: 15px;
height: 13px;
`;
export const Bar = styled.div`
position: absolute;
height: 3px;
background: ${theme.black};
overflow: hidden;
&::after {
content: '';
display: block;
width: 100%;
height: 100%;
background: ${theme.gray};
position: absolute;
top: 0;
left: 100%;
z-index: 1;
transition: all .3s ease-in-out;
}
&:nth-child(1) {
top: 0;
width: 9px;
&::after {
transition-delay: .1s;
}
}
&:nth-child(2) {
top: 5px;
width: 15px;
&::after {
transition-delay: .2s;
}
}
&:nth-child(3) {
top: 10px;
width: 12px;
&::after {
transition-delay: .3s;
}
}
`;
const Hamburger = () => (
<StyledHamburger>
<Bar />
<Bar />
<Bar />
</StyledHamburger>
);
export default Hamburger;
| Convert Hamburger component to stateless function | Convert Hamburger component to stateless function
| JavaScript | mit | nathanhood/mmdb,nathanhood/mmdb | ---
+++
@@ -48,16 +48,12 @@
}
`;
-class Hamburger extends React.PureComponent {
- render() {
- return (
- <StyledHamburger>
- <Bar />
- <Bar />
- <Bar />
- </StyledHamburger>
- );
- }
-}
+const Hamburger = () => (
+ <StyledHamburger>
+ <Bar />
+ <Bar />
+ <Bar />
+ </StyledHamburger>
+);
export default Hamburger; |
390bf907e581c44804ac03becbf462fcee134ea7 | app/renderer/js/components/tab.js | app/renderer/js/components/tab.js | 'use strict';
const BaseComponent = require(__dirname + '/../components/base.js');
class Tab extends BaseComponent {
constructor(props) {
super();
this.props = props;
this.webview = this.props.webview;
this.init();
}
init() {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$el);
this.registerListeners();
}
registerListeners() {
this.$el.addEventListener('click', this.props.onClick);
this.$el.addEventListener('mouseover', this.props.onHover);
this.$el.addEventListener('mouseout', this.props.onHoverOut);
}
isLoading() {
return this.webview.isLoading;
}
activate() {
this.$el.classList.add('active');
this.webview.load();
}
deactivate() {
this.$el.classList.remove('active');
this.webview.hide();
}
destroy() {
this.$el.parentNode.removeChild(this.$el);
this.webview.$el.parentNode.removeChild(this.webview.$el);
}
}
module.exports = Tab;
| 'use strict';
const BaseComponent = require(__dirname + '/../components/base.js');
class Tab extends BaseComponent {
constructor(props) {
super();
this.props = props;
this.webview = this.props.webview;
this.init();
}
init() {
this.$el = this.generateNodeFromTemplate(this.template());
this.props.$root.appendChild(this.$el);
this.registerListeners();
}
registerListeners() {
this.$el.addEventListener('click', this.props.onClick);
this.$el.addEventListener('mouseover', this.props.onHover);
this.$el.addEventListener('mouseout', this.props.onHoverOut);
}
activate() {
this.$el.classList.add('active');
this.webview.load();
}
deactivate() {
this.$el.classList.remove('active');
this.webview.hide();
}
destroy() {
this.$el.parentNode.removeChild(this.$el);
this.webview.$el.parentNode.removeChild(this.webview.$el);
}
}
module.exports = Tab;
| Remove unused isLoading function from Tab. | components: Remove unused isLoading function from Tab.
| JavaScript | apache-2.0 | zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop | ---
+++
@@ -25,10 +25,6 @@
this.$el.addEventListener('mouseout', this.props.onHoverOut);
}
- isLoading() {
- return this.webview.isLoading;
- }
-
activate() {
this.$el.classList.add('active');
this.webview.load(); |
22ab2b03693a5a188a7675c984303f5be34052a9 | src/components/SimilarPlayersCard.js | src/components/SimilarPlayersCard.js | import React from 'react';
import PlayerAvatar from './PlayerAvatar.js'
import '../style/components/SimilarPlayersCard.css';
export default function SimilarPlayersCard(props) {
const similarPlayersList = [
{
'firstName': props.firstName0,
'lastName': props.lastName0,
'img': props.img0,
'ppg': props.ppg0,
'apg': props.apg0,
'rpg': props.rpg0
},
{
'firstName': props.firstName1,
'lastName': props.lastName1,
'img': props.img1,
'ppg': props.ppg1,
'apg': props.apg1,
'rpg': props.rpg1
},
{
'firstName': props.firstName2,
'lastName': props.lastName2,
'img': props.img2,
'ppg': props.ppg2,
'apg': props.apg2,
'rpg': props.rpg2
}
];
const playerAvatarList = similarPlayersList.map((player) =>
<PlayerAvatar
key={player.firstName + '_' + player.lastName}
playerName={player.firstName + ' ' + player.lastName} img={player.img}
ppg={player.ppg} apg={player.apg} rpg={player.rpg}
/>
);
return (
<div className='SimilarPlayersCard card'>
<div className='card-title'>
Similar Players
</div>
{playerAvatarList}
</div>
);
}
| import React from 'react';
import PlayerAvatar from './PlayerAvatar.js'
import '../style/components/SimilarPlayersCard.css';
export default function SimilarPlayersCard(props) {
const similarPlayersList = [
{
'firstName': props.firstName0,
'lastName': props.lastName0,
'img': props.img0,
'ppg': props.ppg0,
'apg': props.apg0,
'rpg': props.rpg0
},
{
'firstName': props.firstName1,
'lastName': props.lastName1,
'img': props.img1,
'ppg': props.ppg1,
'apg': props.apg1,
'rpg': props.rpg1
},
{
'firstName': props.firstName2,
'lastName': props.lastName2,
'img': props.img2,
'ppg': props.ppg2,
'apg': props.apg2,
'rpg': props.rpg2
}
];
const playerAvatarList = similarPlayersList.map((player, idx) =>
<PlayerAvatar
key={idx}
playerName={player.firstName + ' ' + player.lastName} img={player.img}
ppg={player.ppg} apg={player.apg} rpg={player.rpg}
/>
);
return (
<div className='SimilarPlayersCard card'>
<div className='card-title'>
Similar Players
</div>
{playerAvatarList}
</div>
);
}
| Use idx as key for similar player avatars | Use idx as key for similar player avatars
| JavaScript | mit | iNaesu/nba-player-dashboard,iNaesu/nba-player-dashboard | ---
+++
@@ -31,9 +31,9 @@
}
];
- const playerAvatarList = similarPlayersList.map((player) =>
+ const playerAvatarList = similarPlayersList.map((player, idx) =>
<PlayerAvatar
- key={player.firstName + '_' + player.lastName}
+ key={idx}
playerName={player.firstName + ' ' + player.lastName} img={player.img}
ppg={player.ppg} apg={player.apg} rpg={player.rpg}
/> |
4a505be39079d972c6506467891e6e4958789ed7 | src/lib/substituteTailwindAtRules.js | src/lib/substituteTailwindAtRules.js | import fs from 'fs'
import _ from 'lodash'
import postcss from 'postcss'
function updateSource(nodes, source) {
return _.tap(Array.isArray(nodes) ? postcss.root({ nodes }) : nodes, tree => {
tree.walk(node => (node.source = source))
})
}
export default function(config, { components: pluginComponents, utilities: pluginUtilities }) {
return function(css) {
css.walkAtRules('tailwind', atRule => {
if (atRule.params === 'preflight') {
const preflightTree = postcss.parse(
fs.readFileSync(`${__dirname}/../../css/preflight.css`, 'utf8')
)
atRule.before(updateSource(preflightTree, atRule.source))
atRule.remove()
}
if (atRule.params === 'components') {
atRule.before(updateSource(pluginComponents, atRule.source))
atRule.remove()
}
if (atRule.params === 'utilities') {
atRule.before(updateSource(pluginUtilities, atRule.source))
atRule.remove()
}
})
}
}
| import fs from 'fs'
import _ from 'lodash'
import postcss from 'postcss'
function updateSource(nodes, source) {
return _.tap(Array.isArray(nodes) ? postcss.root({ nodes }) : nodes, tree => {
tree.walk(node => (node.source = source))
})
}
export default function(
config,
{ base: pluginBase, components: pluginComponents, utilities: pluginUtilities }
) {
return function(css) {
css.walkAtRules('tailwind', atRule => {
if (atRule.params === 'preflight') {
const preflightTree = postcss.parse(
fs.readFileSync(`${__dirname}/../../css/preflight.css`, 'utf8')
)
atRule.before(updateSource(preflightTree, atRule.source))
atRule.remove()
}
if (atRule.params === 'base') {
atRule.before(updateSource(pluginBase, atRule.source))
atRule.remove()
}
if (atRule.params === 'components') {
atRule.before(updateSource(pluginComponents, atRule.source))
atRule.remove()
}
if (atRule.params === 'utilities') {
atRule.before(updateSource(pluginUtilities, atRule.source))
atRule.remove()
}
})
}
}
| Load plugin base styles at `@tailwind base` | Load plugin base styles at `@tailwind base`
| JavaScript | mit | tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss | ---
+++
@@ -8,7 +8,10 @@
})
}
-export default function(config, { components: pluginComponents, utilities: pluginUtilities }) {
+export default function(
+ config,
+ { base: pluginBase, components: pluginComponents, utilities: pluginUtilities }
+) {
return function(css) {
css.walkAtRules('tailwind', atRule => {
if (atRule.params === 'preflight') {
@@ -17,6 +20,11 @@
)
atRule.before(updateSource(preflightTree, atRule.source))
+ atRule.remove()
+ }
+
+ if (atRule.params === 'base') {
+ atRule.before(updateSource(pluginBase, atRule.source))
atRule.remove()
}
|
ffcf591b1c59f3441206ce1c308a95d63f005766 | lib/web/middleware/basic_auth.js | lib/web/middleware/basic_auth.js | var settings = require('../../settings');
module.exports = function basic_auth(req, res, next){
var username, password, auth_token, index_of_colon, auth_header, i, user_tuple;
try{
auth_header = req.header('Authorization');
if (auth_header === undefined){
return unauthorized(res);
}
if (auth_header.slice(0, 6) !== "Basic "){
return unauthorized(res);
}
auth_token = auth_header.slice(6);
if (auth_token === ""){
return unauthorized(res);
}
auth_token = new Buffer(auth_token, "base64").toString('ascii');
index_of_colon = auth_token.indexOf(':');
if (index_of_colon === -1){
return unauthorized(res);
}
username = auth_token.slice(0, index_of_colon);
password = auth_token.slice(index_of_colon+1);
if (username === "" || password === ""){
return unauthorized(res);
}
for (i=0; i<settings.valid_users.length; i++){
user_tuple = settings.valid_users[i];
if(username === user_tuple[0] && password === user_tuple[1]){
return next();
}
}
}catch (e){
return unauthorized(res);
}
return unauthorized(res);
};
var unauthorized = function(res){
return res.send('Authorization required.', 401);
}; | var settings = require('../../settings');
module.exports = function basic_auth(req, res, next){
var username, password, auth_token, index_of_colon, auth_header, i, user_tuple;
try{
auth_header = req.header('Authorization');
if (auth_header === undefined){
return unauthorized(res);
}
if (auth_header.slice(0, 6) !== "Basic "){
return unauthorized(res);
}
auth_token = auth_header.slice(6);
if (auth_token === ""){
return unauthorized(res);
}
auth_token = new Buffer(auth_token, "base64").toString('ascii');
index_of_colon = auth_token.indexOf(':');
if (index_of_colon === -1){
return unauthorized(res);
}
username = auth_token.slice(0, index_of_colon);
password = auth_token.slice(index_of_colon+1);
if (username === "" || password === ""){
return unauthorized(res);
}
for (i=0; i<settings.valid_users.length; i++){
user_tuple = settings.valid_users[i];
if(username === user_tuple[0] && password === user_tuple[1]){
return next();
}
}
}catch (e){
return unauthorized(res);
}
return unauthorized(res);
};
var unauthorized = function(res){
res.header('WWW-Authenticate', 'Basic realm="Secure Area"');
return res.send('Authorization required.', 401);
};
| Send www-authenticate header so browsers ask for a password. | Send www-authenticate header so browsers ask for a password.
| JavaScript | apache-2.0 | racker/gutsy,racker/gutsy | ---
+++
@@ -40,5 +40,6 @@
};
var unauthorized = function(res){
+ res.header('WWW-Authenticate', 'Basic realm="Secure Area"');
return res.send('Authorization required.', 401);
}; |
cdf1c5ba3d8ef36fb4fd9a3dba0b6555596ada28 | src/rules/fr-FR/html.js | src/rules/fr-FR/html.js | import {rule, group} from '../../typography-fixer'
import html from '../html'
let frFR_HTML
/**
* The ruleset for HTML improvement on french typography
*
* It includes rules for:
*
* - Wrapping ends of common abbreviation in a `<sup>` tag so that `Mmes`
* becomes `M<sup>mes</sup>`
* - Wrapping ordinal number suffix in a `<sup>` tag
*
* Finally, the following rulesets are also included:
*
* - {@link src/rules/html.js~htmlRuleset}
*
* @type {Array<Object>}
*/
export default frFR_HTML = createRuleset().concat(html)
function createRuleset () {
return group('fr-FR.html', [
rule('abbrWithSuperText', /Mmes|Mme|Mlles|Mlle|Me|Mgr|Dr|cie|Cie|Sté/, (m) => {
return `${m[0]}<sup>${m.slice(1, m.length)}</sup>`
}),
rule('ordinalNumbers', /(\d)(res|re|es|e|èmes)/, '$1<sup class="ord">$2</sup>')
])
}
| import {rule, group} from '../../typography-fixer'
import html from '../html'
let frFR_HTML
/**
* The ruleset for HTML improvement on french typography
*
* It includes rules for:
*
* - Wrapping ends of common abbreviation in a `<sup>` tag so that `Mmes`
* becomes `M<sup>mes</sup>`
* - Wrapping ordinal number suffix in a `<sup>` tag
*
* Finally, the following rulesets are also included:
*
* - {@link src/rules/html.js~html}
*
* @type {Array<Object>}
*/
export default frFR_HTML = createRuleset().concat(html)
function createRuleset () {
return group('fr-FR.html', [
rule('abbrWithSuperText', /Mmes|Mme|Mlles|Mlle|Me|Mgr|Dr|cie|Cie|Sté/, (m) => {
return `${m[0]}<sup>${m.slice(1, m.length)}</sup>`
}),
rule('ordinalNumbers', /(\d)(res|re|es|e|èmes)/, '$1<sup class="ord">$2</sup>')
])
}
| Fix link typo in docs | :memo: Fix link typo in docs
| JavaScript | mit | abe33/typography-fixer | ---
+++
@@ -14,7 +14,7 @@
*
* Finally, the following rulesets are also included:
*
- * - {@link src/rules/html.js~htmlRuleset}
+ * - {@link src/rules/html.js~html}
*
* @type {Array<Object>}
*/ |
87b8b34f84f13c547de50533efd81345eb73570f | src/karma.conf.js | src/karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
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
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
}; | Revert "Add custom launcher for karma" | Revert "Add custom launcher for karma"
This reverts commit dd80f254f407429aeaf5ca5c4fb414363836c267.
| JavaScript | mit | dzonatan/angular2-linky,dzonatan/angular2-linky | ---
+++
@@ -26,12 +26,6 @@
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
- customLaunchers: {
- ChromeHeadlessNoSandbox: {
- base: 'ChromeHeadless',
- flags: ['--no-sandbox']
- }
- },
singleRun: false
});
}; |
c974512324fe20775db67626d15027a539ec27bb | packages/components/containers/app/createApi.js | packages/components/containers/app/createApi.js | import xhr from 'proton-shared/lib/fetch/fetch';
import configureApi from 'proton-shared/lib/api';
export default ({ CLIENT_ID, APP_VERSION, API_VERSION, API_URL }) => (UID) => {
return configureApi({
xhr,
UID,
API_URL,
CLIENT_ID,
API_VERSION,
APP_VERSION
});
};
| import xhr from 'proton-shared/lib/fetch/fetch';
import configureApi from 'proton-shared/lib/api';
export default ({ CLIENT_ID, CLIENT_SECRET, APP_VERSION, API_VERSION, API_URL }) => (UID) => {
return configureApi({
xhr,
UID,
API_URL,
CLIENT_ID,
CLIENT_SECRET,
API_VERSION,
APP_VERSION
});
};
| Add support for sending client secret from the config | Add support for sending client secret from the config
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,12 +1,13 @@
import xhr from 'proton-shared/lib/fetch/fetch';
import configureApi from 'proton-shared/lib/api';
-export default ({ CLIENT_ID, APP_VERSION, API_VERSION, API_URL }) => (UID) => {
+export default ({ CLIENT_ID, CLIENT_SECRET, APP_VERSION, API_VERSION, API_URL }) => (UID) => {
return configureApi({
xhr,
UID,
API_URL,
CLIENT_ID,
+ CLIENT_SECRET,
API_VERSION,
APP_VERSION
}); |
d76e961f639a776c837f70f02fcb767de9f4287c | src/main/power.js | src/main/power.js | "use strict";
module.exports.charging = function() {
if ( process.platform === "darwin") {
var osxBattery = require("osx-battery");
return osxBattery().then(res => {
return res.isCharging || res.fullyCharged;
});
}
else if ( process.platform === "linux") {
var linuxBattery = require("linux-battery");
// NOTE: this is not actually tested
return linuxBattery().then(res => {
return ( res.state !== "discharging" );
});
}
else {
// this code is modified from https://github.com/gillstrom/battery-level/blob/master/win.js
var p = new Promise(function(resolve, reject) {
var cmd = "WMIC";
let args = ["Path", "Win32_Battery", "Get", "BatteryStatus"];
//Other (1)
//The battery is discharging.
var exec = require("child_process").execFile;
exec(cmd, args, function(error, stdout) {
// console.log("stdout: " + stdout);
// console.log("stderr: " + stderr);
if (error !== null) {
reject(error);
}
stdout = parseInt(stdout.trim().split("\n")[1], 10);
var result = (stdout !== 1);
resolve(result);
});
});
return p;
}
};
| "use strict";
module.exports.charging = function() {
if ( process.platform === "darwin") {
var osxBattery = require("osx-battery");
return osxBattery().then(res => {
return res.isCharging || res.fullyCharged;
}).catch(() => {
return false;
});
}
else if ( process.platform === "linux") {
var linuxBattery = require("linux-battery");
// NOTE: this is not actually tested
return linuxBattery().then(res => {
return ( res.state !== "discharging" );
}).catch(() => {
return false;
});
}
else {
// this code is modified from https://github.com/gillstrom/battery-level/blob/master/win.js
var p = new Promise(function(resolve, reject) {
var cmd = "WMIC";
let args = ["Path", "Win32_Battery", "Get", "BatteryStatus"];
//Other (1)
//The battery is discharging.
var exec = require("child_process").execFile;
exec(cmd, args, function(error, stdout) {
// console.log("stdout: " + stdout);
// console.log("stderr: " + stderr);
if (error !== null) {
reject(error);
}
stdout = parseInt(stdout.trim().split("\n")[1], 10);
var result = (stdout !== 1);
resolve(result);
});
});
return p;
}
};
| Add error handling to battery check | Add error handling to battery check
| JavaScript | mit | muffinista/before-dawn,muffinista/before-dawn,muffinista/before-dawn | ---
+++
@@ -6,8 +6,9 @@
return osxBattery().then(res => {
return res.isCharging || res.fullyCharged;
+ }).catch(() => {
+ return false;
});
-
}
else if ( process.platform === "linux") {
var linuxBattery = require("linux-battery");
@@ -15,7 +16,9 @@
// NOTE: this is not actually tested
return linuxBattery().then(res => {
return ( res.state !== "discharging" );
- });
+ }).catch(() => {
+ return false;
+ });
}
else {
// this code is modified from https://github.com/gillstrom/battery-level/blob/master/win.js |
12151d148339b4ce81684720351b9bb85d217c4f | packages/@sanity/state-router/src/createRoute.js | packages/@sanity/state-router/src/createRoute.js | import isPlainObject from 'lodash/isplainobject'
function arrayify(fn) {
return (...args) => {
const ret = fn(...args)
return Array.isArray(ret)
? ret
: ret == null
? []
: [ret]
}
}
export default function createRoute(pattern, ...rest) {
let options, children
if (isPlainObject(rest[0]) || typeof rest[0] === 'string') {
[options, children] = rest
if (typeof options === 'string') {
options = {activeKey: options}
}
}
else {
options = {}
children = rest[0]
}
if (!pattern.includes(':')) {
// throw new Error(`A route must include at least one unique parameter. Please check the route "${pattern}"`)
}
return {
pattern,
options: options || {},
children: arrayify(typeof children === 'function' ? children : () => children)
}
} | import isPlainObject from 'lodash/isPlainObject'
function arrayify(fn) {
return (...args) => {
const ret = fn(...args)
return Array.isArray(ret)
? ret
: ret == null
? []
: [ret]
}
}
export default function createRoute(pattern, ...rest) {
let options, children
if (isPlainObject(rest[0]) || typeof rest[0] === 'string') {
[options, children] = rest
if (typeof options === 'string') {
options = {activeKey: options}
}
}
else {
options = {}
children = rest[0]
}
if (!pattern.includes(':')) {
// throw new Error(`A route must include at least one unique parameter. Please check the route "${pattern}"`)
}
return {
pattern,
options: options || {},
children: arrayify(typeof children === 'function' ? children : () => children)
}
} | Fix bad casing in import | Fix bad casing in import
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,4 +1,4 @@
-import isPlainObject from 'lodash/isplainobject'
+import isPlainObject from 'lodash/isPlainObject'
function arrayify(fn) {
return (...args) => { |
87ecca5fb61b6ff202c317771c6ce7e6ebdcb979 | backend/server/model-loader.js | backend/server/model-loader.js | module.exports = function modelLoader(isParent) {
'use strict';
if (isParent || process.env.MCTEST) {
console.log('using mocks/model');
return require('./mocks/model');
}
let ropts = {
db: 'materialscommons',
port: 30815
};
let r = require('rethinkdbdash')(ropts);
return require('./db/model')(r);
};
| module.exports = function modelLoader(isParent) {
'use strict';
if (isParent || process.env.MCTEST) {
return require('./mocks/model');
}
let ropts = {
db: process.env.MCDB || 'materialscommons',
port: process.env.MCPORT || 30815
};
let r = require('rethinkdbdash')(ropts);
return require('./db/model')(r);
};
| Add environment variables for testing, database and database server port. | Add environment variables for testing, database and database server port.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -2,13 +2,12 @@
'use strict';
if (isParent || process.env.MCTEST) {
- console.log('using mocks/model');
return require('./mocks/model');
}
let ropts = {
- db: 'materialscommons',
- port: 30815
+ db: process.env.MCDB || 'materialscommons',
+ port: process.env.MCPORT || 30815
};
let r = require('rethinkdbdash')(ropts); |
c99b485a0ec66a1a0c262a9dc74bbdebeab86083 | node/index.js | node/index.js | var path = require('path');
var moduleEntryPoint = require.resolve('incuna-sass');
var moduleDir = path.dirname(moduleEntryPoint);
function includePaths() {
return [moduleDir];
}
module.exports = {
includePaths: includePaths()
};
| // This index module is returned by default when this package is required
// Node module imports
var path = require('path');
// Function returns absolute system path to location that module is installed.
// This is useful for referencing the files within this package in grunt tasks
// Uses a technique copied from node-bourbon
function includePaths() {
var moduleEntryPoint = require.resolve('incuna-sass');
var entrypointDir = path.dirname(moduleEntryPoint);
// Module resolves to the main entry point - e.g. node/index.js, so we go up a
// level to get the main module root path
var moduleDir = path.join(entrypointDir, '../');
return [moduleDir];
}
module.exports = {
// run modulePath() function immediately and return result as exported value
includePaths: includePaths()
};
| Make sure the node module path is reported correctly | Make sure the node module path is reported correctly | JavaScript | mit | incuna/incuna-sass | ---
+++
@@ -1,14 +1,21 @@
+// This index module is returned by default when this package is required
+
+// Node module imports
var path = require('path');
-var moduleEntryPoint = require.resolve('incuna-sass');
-var moduleDir = path.dirname(moduleEntryPoint);
-
+// Function returns absolute system path to location that module is installed.
+// This is useful for referencing the files within this package in grunt tasks
+// Uses a technique copied from node-bourbon
function includePaths() {
- return [moduleDir];
+ var moduleEntryPoint = require.resolve('incuna-sass');
+ var entrypointDir = path.dirname(moduleEntryPoint);
+ // Module resolves to the main entry point - e.g. node/index.js, so we go up a
+ // level to get the main module root path
+ var moduleDir = path.join(entrypointDir, '../');
+ return [moduleDir];
}
module.exports = {
-
- includePaths: includePaths()
-
+ // run modulePath() function immediately and return result as exported value
+ includePaths: includePaths()
}; |
8f375eaf4e3453fee3c41907ef0016de3c11d636 | server/main.js | server/main.js | makeThumbNail = function (fileBuffer, extenstion, callback) {
var gmImageRessource = gm(fileBuffer, 'image.' + extenstion)
, newImage = {
side: 400
}
, syncSize = function (gmRessource, callback) {
gmRessource.size(callback)
}
, imageSize = Meteor.wrapAsync(syncSize)(gmImageRessource)
, imageRatio = {
width: imageSize.width / imageSize.height
, height: imageSize.height / imageSize.width
}
newImage.size = {
height: Math.round(newImage.side / imageRatio.height)
, width: Math.round(newImage.side / imageRatio.width)
}
console.log(imageSize)
newGmImageRessource = gmImageRessource.resize(newImage.size.width, newImage.size.height)
function syncToBuffer (gmRessource, callback) {
gmRessource.toBuffer(callback)
}
newImageBuffer = Meteor.wrapAsync(syncToBuffer)(newGmImageRessource)
callback(null, newImageBuffer)
} | makeThumbNail = function (fileBuffer, extenstion, callback) {
var gmImageRessource = gm(fileBuffer, 'image.' + extenstion)
, newImage = {
side: 400
}
function syncSize (gmRessource, callback) {
gmRessource.size(callback)
}
var imageSize = Meteor.wrapAsync(syncSize)(gmImageRessource)
newGmImageRessource = gmImageRessource.resize(400, 400)
function syncToBuffer (gmRessource, callback) {
gmRessource.toBuffer(callback)
}
newImageBuffer = Meteor.wrapAsync(syncToBuffer)(newGmImageRessource)
callback(null, newImageBuffer)
} | Refactor makeThumbNail to produce images with min400 x min400 | Refactor makeThumbNail to produce images with min400 x min400
| JavaScript | mit | Kriegslustig/meteor-gallery | ---
+++
@@ -3,21 +3,13 @@
, newImage = {
side: 400
}
-, syncSize = function (gmRessource, callback) {
+
+ function syncSize (gmRessource, callback) {
gmRessource.size(callback)
}
-, imageSize = Meteor.wrapAsync(syncSize)(gmImageRessource)
-, imageRatio = {
- width: imageSize.width / imageSize.height
- , height: imageSize.height / imageSize.width
- }
- newImage.size = {
- height: Math.round(newImage.side / imageRatio.height)
- , width: Math.round(newImage.side / imageRatio.width)
- }
- console.log(imageSize)
+ var imageSize = Meteor.wrapAsync(syncSize)(gmImageRessource)
- newGmImageRessource = gmImageRessource.resize(newImage.size.width, newImage.size.height)
+ newGmImageRessource = gmImageRessource.resize(400, 400)
function syncToBuffer (gmRessource, callback) {
gmRessource.toBuffer(callback) |
d0ff2e82248998d018b07d7d018b9f9747afcbc6 | src/geo/ui/widgets/category/search_paginator_view.js | src/geo/ui/widgets/category/search_paginator_view.js | var $ = require('jquery');
var _ = require('underscore');
var View = require('cdb/core/view');
var Model = require('cdb/core/model');
var PaginatorView = require('./paginator_view');
var searchTemplate = require('./search_paginator_template.tpl');
module.exports = PaginatorView.extend({
_TEMPLATE: searchTemplate,
className: 'Widget-nav is-hidden Widget-contentSpaced',
toggle: function() {
this[ !this.viewModel.isSearchEnabled() ? 'hide' : 'show' ]();
}
});
| var $ = require('jquery');
var _ = require('underscore');
var View = require('cdb/core/view');
var Model = require('cdb/core/model');
var PaginatorView = require('./paginator_view');
var searchTemplate = require('./search_paginator_template.tpl');
module.exports = PaginatorView.extend({
_TEMPLATE: searchTemplate,
className: 'Widget-nav is-hidden Widget-contentSpaced',
toggle: function() {
this[ !this.viewModel.isSearchEnabled() ? 'hide' : 'show' ]();
},
_onSearchClicked: function() {
this.options.originModel.cleanSearch();
this.viewModel.toggleSearch();
}
});
| Clean search (input, data, ...) when search view is disabled | Clean search (input, data, ...) when search view is disabled | JavaScript | bsd-3-clause | splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js | ---
+++
@@ -12,6 +12,11 @@
toggle: function() {
this[ !this.viewModel.isSearchEnabled() ? 'hide' : 'show' ]();
+ },
+
+ _onSearchClicked: function() {
+ this.options.originModel.cleanSearch();
+ this.viewModel.toggleSearch();
}
}); |
3bcf3b06bf13be57da0ef4c619da5e9c7beee4d1 | lib/extensions/error_reporting/mixin_base.js | lib/extensions/error_reporting/mixin_base.js | 'use strict';
var Mixin = require('../../utils/mixin'),
inherits = require('util').inherits;
var ErrorReportingMixinBase = module.exports = function (host, onParseError) {
Mixin.call(this, host);
this.posTracker = null;
this.onParseError = onParseError;
};
inherits(ErrorReportingMixinBase, Mixin);
ErrorReportingMixinBase.prototype._getOverriddenMethods = function (mxn) {
return {
_err: function (code) {
mxn.onParseError({
code: code,
line: mxn.posTracker.line,
col: mxn.posTracker.col,
offset: mxn.posTracker.offset
});
}
};
};
| 'use strict';
var Mixin = require('../../utils/mixin'),
inherits = require('util').inherits;
var ErrorReportingMixinBase = module.exports = function (host, onParseError) {
Mixin.call(this, host);
this.posTracker = null;
this.onParseError = onParseError;
};
inherits(ErrorReportingMixinBase, Mixin);
ErrorReportingMixinBase.prototype._getOverriddenMethods = function (mxn) {
return {
_err: function (code, details) {
mxn.onParseError({
code: code,
line: mxn.posTracker.line,
col: mxn.posTracker.col,
offset: mxn.posTracker.offset,
details: details
});
}
};
};
| Add details field to error | Add details field to error
| JavaScript | mit | HTMLParseErrorWG/parse5,HTMLParseErrorWG/parse5 | ---
+++
@@ -14,12 +14,13 @@
ErrorReportingMixinBase.prototype._getOverriddenMethods = function (mxn) {
return {
- _err: function (code) {
+ _err: function (code, details) {
mxn.onParseError({
code: code,
line: mxn.posTracker.line,
col: mxn.posTracker.col,
- offset: mxn.posTracker.offset
+ offset: mxn.posTracker.offset,
+ details: details
});
}
}; |
9c1882431b199501018c2be8cef6dd92ea7ad642 | server/auth/local/passport.js | server/auth/local/passport.js | let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
const AUTH_ERROR = {message: 'Invalid email or password.'};
let localPassport = {
localAuthenticate,
setup
};
function localAuthenticate(userService, email, password, done) {
userService.getByEmail(email.toLowerCase())
.then(user => {
if (!user) {
return done(null, false, AUTH_ERROR);
}
user.authenticate(password, function (authError, authenticated) {
if (authError) {
return done(authError);
}
if (authenticated) {
return done(null, user);
} else {
return done(null, false, AUTH_ERROR);
}
});
})
.catch(err => {
console.log('ERROR!');
done(err)
});
}
function setup(userService, config) {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password' // this is the virtual field on the model
},
function (email, password, done) {
return localAuthenticate(userService, email, password, done);
}));
}
module.exports = localPassport;
| 'use strict';
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
const AUTH_ERROR = {message: 'Invalid email or password.'};
let localPassport = {
localAuthenticate,
setup
};
function localAuthenticate(userService, email, password, done) {
userService.getByEmail(email.toLowerCase())
.then(user => {
if (!user) {
return done(null, false, AUTH_ERROR);
}
user.authenticate(password, function (authError, authenticated) {
if (authError) {
return done(authError);
}
if (authenticated) {
return done(null, user);
} else {
return done(null, false, AUTH_ERROR);
}
});
})
.catch(err => {
console.log('ERROR!');
done(err)
});
}
function setup(userService, config) {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password' // this is the virtual field on the model
},
function (email, password, done) {
return localAuthenticate(userService, email, password, done);
}));
}
module.exports = localPassport;
| Build gc-orders-server from commit bd221fb on branch master | Build gc-orders-server from commit bd221fb on branch master
| JavaScript | apache-2.0 | rrgarciach/gc-orders-server | ---
+++
@@ -1,3 +1,5 @@
+'use strict';
+
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
|
168008d7087d2505af4183e1bb8783259fa677b8 | src/modules/cluster/cluster-detail/cluster-detail.js | src/modules/cluster/cluster-detail/cluster-detail.js | (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
vm.setTab = setTab;
vm.isTabSet = isTabSet;
/* Adding clusterId in scope so that it will be accessible inside child directive */
$scope.clusterId = $stateParams.clusterId;
if (!$rootScope.clusterData) {
$state.go("cluster");
} else {
vm.clusterObj = utils.getClusterDetails($scope.clusterId);
vm.clusterName = vm.clusterObj.cluster_name || "NA";
if (vm.clusterObj.sds_name === "glusterfs") {
vm.tabList.FileShare = 2;
} else {
vm.tabList.Pool = 2;
vm.tabList.RBD = 3;
}
vm.activeTab = vm.tabList["Host"];
}
function setTab(newTab) {
vm.activeTab = newTab;
}
function isTabSet(tabNum) {
return vm.activeTab === tabNum;
}
}
})();
| (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
vm.setTab = setTab;
vm.isTabSet = isTabSet;
/* Adding clusterId in scope so that it will be accessible inside child directive */
$scope.clusterId = $stateParams.clusterId;
if (!$rootScope.clusterData) {
utils.getObjectList("Cluster")
.then(function(data) {
$rootScope.clusterData = data;
_setClusterDetail();
});
} else {
_setClusterDetail();
}
function _setClusterDetail() {
vm.clusterObj = utils.getClusterDetails($scope.clusterId);
vm.clusterName = vm.clusterObj.cluster_name || "NA";
if (vm.clusterObj.sds_name === "glusterfs") {
vm.tabList.FileShare = 2;
} else {
vm.tabList.Pool = 2;
vm.tabList.RBD = 3;
}
vm.activeTab = vm.tabList["Host"];
}
function setTab(newTab) {
vm.activeTab = newTab;
}
function isTabSet(tabNum) {
return vm.activeTab === tabNum;
}
}
})();
| Fix for cluster detail page | Fix for cluster detail page
| JavaScript | apache-2.0 | Tendrl/dashboard,cloudbehl/tendrl_frontend,Tendrl/dashboard,cloudbehl/tendrl_frontend | ---
+++
@@ -17,9 +17,17 @@
$scope.clusterId = $stateParams.clusterId;
if (!$rootScope.clusterData) {
- $state.go("cluster");
+ utils.getObjectList("Cluster")
+ .then(function(data) {
+ $rootScope.clusterData = data;
+ _setClusterDetail();
+ });
+
} else {
+ _setClusterDetail();
+ }
+ function _setClusterDetail() {
vm.clusterObj = utils.getClusterDetails($scope.clusterId);
vm.clusterName = vm.clusterObj.cluster_name || "NA";
if (vm.clusterObj.sds_name === "glusterfs") { |
25d124bc6ec471b964be401d6013ff803d8e2ddd | chrome/content/markdown-viewer.js | chrome/content/markdown-viewer.js | window.addEventListener('load', function load(event) {
window.removeEventListener('load', load, false);
MarkdownViewer.init();
}, false);
if (!MarkdownViewer) {
var MarkdownViewer = {
init: function() {
var appcontent = document.getElementById('appcontent');
if (appcontent)
appcontent.addEventListener('DOMContentLoaded', this.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var document = aEvent.originalTarget;
var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?$/i;
if (document.location.protocol !== "view-source:"
&& markdownFileExtension.test(document.location.href)) {
var content = document.firstChild;
content.innerHTML = '<!DOCTYPE html>' +
'<head>' +
' <title></title>' +
' <meta charset="utf-8" />' +
' <link rel="stylesheet" type="text/css" href="resource://mdvskin/markdown-viewer.css" />' +
'</head>' +
'<body class="container">' +
marked(content.textContent) +
'</body>';
document.title = document.body.firstChild.textContent.substr(0, 50).replace('<', '<').replace('>', '>');
}
}
};
}
| window.addEventListener('load', function load(event) {
window.removeEventListener('load', load, false);
MarkdownViewer.init();
}, false);
if (!MarkdownViewer) {
var MarkdownViewer = {
init: function() {
var appcontent = document.getElementById('appcontent');
if (appcontent)
appcontent.addEventListener('DOMContentLoaded', this.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var document = aEvent.originalTarget;
var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?(.*)$/i;
if (document.location.protocol !== "view-source:"
&& markdownFileExtension.test(document.location.href)) {
var content = document.firstChild;
content.innerHTML = '<!DOCTYPE html>' +
'<head>' +
' <title></title>' +
' <meta charset="utf-8" />' +
' <link rel="stylesheet" type="text/css" href="resource://mdvskin/markdown-viewer.css" />' +
'</head>' +
'<body class="container">' +
marked(content.textContent) +
'</body>';
document.title = document.body.firstChild.textContent.substr(0, 50).replace('<', '<').replace('>', '>');
}
}
};
}
| Fix regexp to detect markdown file (URL with GET parameters) | Fix regexp to detect markdown file (URL with GET parameters)
| JavaScript | mit | uvesten/markdown-viewer,Thiht/markdown-viewer,Thiht/markdown-viewer,K-atc/markdown-viewer,K-atc/markdown-viewer,uvesten/markdown-viewer | ---
+++
@@ -16,7 +16,7 @@
onPageLoad: function(aEvent) {
var document = aEvent.originalTarget;
- var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?$/i;
+ var markdownFileExtension = /\.m(arkdown|kdn?|d(o?wn)?)(#.*)?(.*)$/i;
if (document.location.protocol !== "view-source:"
&& markdownFileExtension.test(document.location.href)) { |
fe824c8f8412806bccfcdbc94f8d0810ef3f1441 | src/actions.js | src/actions.js | export const ADD: string = 'ADD'
export const SHOW: string = 'SHOW'
export const DISMISS: string = 'DISMISS'
export function add (item) {
return {
type: ADD,
payload: item
}
}
export function show (item) {
return {
type: SHOW,
payload: item
}
}
export function dismiss () {
return {
type: DISMISS
}
}
| export const ADD: string = 'SNACKBAR.ADD'
export const SHOW: string = 'SNACKBAR.SHOW'
export const DISMISS: string = 'SNACKBAR.DISMISS'
export function add (item) {
return {
type: ADD,
payload: item
}
}
export function show (item) {
return {
type: SHOW,
payload: item
}
}
export function dismiss () {
return {
type: DISMISS
}
}
| Add namespace for redux action for better scope | Add namespace for redux action for better scope
| JavaScript | mit | 9gag-open-source/react-native-snackbar-dialog | ---
+++
@@ -1,6 +1,6 @@
-export const ADD: string = 'ADD'
-export const SHOW: string = 'SHOW'
-export const DISMISS: string = 'DISMISS'
+export const ADD: string = 'SNACKBAR.ADD'
+export const SHOW: string = 'SNACKBAR.SHOW'
+export const DISMISS: string = 'SNACKBAR.DISMISS'
export function add (item) {
return { |
8a0dfb140f5e19044b7fd432552c38ee5d3b1ece | src/actions.js | src/actions.js | var RowConstants = require('./constants/row_constants.js'),
QueryConstants = require('./constants/query_constants.js'),
client = require('./client.js'),
Dispatcher = require('./dispatcher.js');
var actions = {
listQueries(callback) {
client.list((err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: QueryConstants.QUERY_LISTED,
value: res
});
if (callback) callback();
}
});
},
deleteQuery(id) {
client.deleteQuery(id, (err, res) => {
if (!err) {
actions.listQueries();
}
});
},
saveQuery(name, query) {
client.saveQuery(name, query, (err, res) => {
console.log(arguments);
});
},
runQuery(query) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_START
});
client.runQuery(query, (err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_DONE,
value: res
});
}
});
}
};
module.exports = actions;
| var RowConstants = require('./constants/row_constants.js'),
QueryConstants = require('./constants/query_constants.js'),
client = require('./client.js'),
Dispatcher = require('./dispatcher.js');
var actions = {
listQueries(callback) {
client.list((err, res) => {
if (!err) {
Dispatcher.handleViewAction({
actionType: QueryConstants.QUERY_LISTED,
value: res
});
if (callback) callback();
}
});
},
deleteQuery(id) {
client.deleteQuery(id, (err, res) => {
if (!err) {
actions.listQueries();
}
});
},
saveQuery(name, query) {
client.saveQuery(name, query, (err, res) => {
console.log(arguments);
});
},
runQuery(query) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_START
});
client.runQuery(query, (err, res) => {
if (!err && res) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_DONE,
value: res
});
}
});
}
};
module.exports = actions;
| Test not just that there's no error, but also that there's a result | Test not just that there's no error, but also that there's a result
| JavaScript | isc | ernestrc/stickshift,ernestrc/stickshift,tmcw/stickshift,tmcw/stickshift | ---
+++
@@ -35,7 +35,7 @@
actionType: RowConstants.QUERY_START
});
client.runQuery(query, (err, res) => {
- if (!err) {
+ if (!err && res) {
Dispatcher.handleViewAction({
actionType: RowConstants.QUERY_DONE,
value: res |
3a9815f8c89af89d3ab92c96ec3a51acb4dd024d | client/components/App.js | client/components/App.js | import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { hot } from 'react-hot-loader';
import SignUpPage from './SignUp/SignUpPage';
import LoginPage from './Login/LoginPage';
import IndexPage from './Index';
class App extends Component {
render() {
return (
<Router history = { this.props.history }>
<Switch>
<Route path = '/signup' component = { SignUpPage } />
<Route path = '/login' component = { LoginPage } />
<Route path = '/' component = { IndexPage } />
</Switch>
</Router>
);
}
}
export default hot(module)(App);
| import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { hot } from 'react-hot-loader';
import SignUpPage from './SignUp/SignUpPage';
import LoginPage from './Login/LoginPage';
import IndexPage from './Index';
import Books from './Books';
class App extends Component {
render() {
return (
<Router history = { this.props.history }>
<Switch>
<Route exact path = '/signup' component = { SignUpPage } />
<Route exact path = '/login' component = { LoginPage } />
<Route exact path = '/' component = { IndexPage } />
<Route path = '/books' component = { Books } />
</Switch>
</Router>
);
}
}
export default hot(module)(App);
| Add route for getting books | Add route for getting books
| JavaScript | mit | amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books | ---
+++
@@ -4,15 +4,17 @@
import SignUpPage from './SignUp/SignUpPage';
import LoginPage from './Login/LoginPage';
import IndexPage from './Index';
+import Books from './Books';
class App extends Component {
render() {
return (
<Router history = { this.props.history }>
<Switch>
- <Route path = '/signup' component = { SignUpPage } />
- <Route path = '/login' component = { LoginPage } />
- <Route path = '/' component = { IndexPage } />
+ <Route exact path = '/signup' component = { SignUpPage } />
+ <Route exact path = '/login' component = { LoginPage } />
+ <Route exact path = '/' component = { IndexPage } />
+ <Route path = '/books' component = { Books } />
</Switch>
</Router>
); |
74480edd7007f19bc97deed0581d14b107bc2365 | client/middlewares/call-api.js | client/middlewares/call-api.js | import liqen from 'liqen'
export const CALL_API = Symbol('call api')
export default store => next => action => {
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action)
}
const { ref, target, tag } = callAPI
// Send a pending
next({
type: 'CREATE_ANNOTATION_PENDING',
ref,
target,
tag
})
// Send to the server the update
liqen()
.annotations
.create({
article_id: 1,
target: {
type: 'TextQuoteSelector',
prefix: target.prefix,
exact: target.exact,
suffix: target.suffix
},
tags: [tag]
})
.then(({id}) => next({
type: 'CREATE_ANNOTATION_SUCCESS',
ref,
id,
target,
tag
}))
.catch(() => next({
type: 'CREATE_ANNOTATION_FAILURE',
ref,
target,
tag
}))
}
| import liqen from 'liqen'
import fakeLiqen from '../../server/local-liqen'
import cookies from 'cookies-js'
export const CALL_API = Symbol('call api')
export default store => next => action => {
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action)
}
const token = cookies.get('access_token')
let core = liqen(token)
if (process.env.NODE_ENV === 'development') {
core = fakeLiqen(token)
}
const { ref, target, tag } = callAPI
// Send a pending
next({
type: 'CREATE_ANNOTATION_PENDING',
ref,
target,
tag
})
// Send to the server the update
core
.annotations
.create({
article_id: 1,
target: {
type: 'TextQuoteSelector',
prefix: target.prefix,
exact: target.exact,
suffix: target.suffix
},
tags: [tag]
})
.then(({id}) => next({
type: 'CREATE_ANNOTATION_SUCCESS',
ref,
id,
target,
tag
}))
.catch(() => next({
type: 'CREATE_ANNOTATION_FAILURE',
ref,
target,
tag
}))
}
| Set token and fake liqen in redux middleware | Set token and fake liqen in redux middleware
| JavaScript | mit | CommonActionForum/liqen-face,exacs/liqen-face,CommonActionForum/liqen-face,exacs/liqen-face | ---
+++
@@ -1,4 +1,7 @@
import liqen from 'liqen'
+import fakeLiqen from '../../server/local-liqen'
+import cookies from 'cookies-js'
+
export const CALL_API = Symbol('call api')
export default store => next => action => {
@@ -6,6 +9,13 @@
if (typeof callAPI === 'undefined') {
return next(action)
+ }
+
+ const token = cookies.get('access_token')
+ let core = liqen(token)
+
+ if (process.env.NODE_ENV === 'development') {
+ core = fakeLiqen(token)
}
const { ref, target, tag } = callAPI
@@ -19,7 +29,7 @@
})
// Send to the server the update
- liqen()
+ core
.annotations
.create({
article_id: 1, |
b11a9a2c7297c1f56da69eccf2e52254f73f7489 | packages/rotonde-cli/src/commands/connect.js | packages/rotonde-cli/src/commands/connect.js | import Client from 'socket.io-client';
/**
* Registers the `connect` command.
*
* @param vorpal The Vorpal instance.
*/
export function connectFactory(vorpal) {
vorpal
.command('connect <host>')
.description('Connects to a Rotonde instance.')
.action(function (args, callback) {
const { host } = args;
const socket = Client(host);
socket.on('connect', () => {
this.log(`Connected to ${host}`);
});
callback();
});
}
| import Client from 'socket.io-client';
/**
* Registers the `connect` command.
*
* @param vorpal The Vorpal instance.
*/
export function connectFactory(vorpal) {
vorpal
.command('connect <instance>')
.description('Connects to a Rotonde instance.')
.action(function (args, callback) {
const { host } = args;
const socket = Client(host);
socket.on('connect', () => {
this.log(`Connected to ${host}`);
});
callback();
});
}
| Use "instance" instead of "host" | Use "instance" instead of "host"
| JavaScript | mit | merveilles/Rotonde,merveilles/Rotonde | ---
+++
@@ -7,7 +7,7 @@
*/
export function connectFactory(vorpal) {
vorpal
- .command('connect <host>')
+ .command('connect <instance>')
.description('Connects to a Rotonde instance.')
.action(function (args, callback) {
const { host } = args; |
ff52f6b8861b23e808b0853e88faf0532029eda4 | test/index.js | test/index.js | //query
import './query/ends_with';
import './query/includes';
import './query/is_alpha';
import './query/is_alpha_digit';
import './query/is_blank';
import './query/is_digit';
import './query/is_empty';
import './query/is_lower_case';
import './query/is_numeric';
import './query/is_string';
import './query/is_upper_case';
import './query/starts_with';
//manipulate
import './manipulate/trim';
import './manipulate/trim_left';
import './manipulate/trim_right'; | //query
import './query/ends_with';
import './query/includes';
import './query/is_alpha';
import './query/is_alpha_digit';
import './query/is_blank';
import './query/is_digit';
import './query/is_empty';
import './query/is_lower_case';
import './query/is_numeric';
import './query/is_string';
import './query/is_upper_case';
import './query/matches';
import './query/starts_with';
//manipulate
import './manipulate/trim';
import './manipulate/trim_left';
import './manipulate/trim_right'; | Include matches unit tests in main bundle | Include matches unit tests in main bundle
| JavaScript | mit | hyeonil/awesome-string,hyeonil/awesome-string,panzerdp/voca | ---
+++
@@ -10,6 +10,7 @@
import './query/is_numeric';
import './query/is_string';
import './query/is_upper_case';
+import './query/matches';
import './query/starts_with';
//manipulate |
884c59717350496cdc6a373cb5e4e8118277c708 | packages/components/bolt-copy-to-clipboard/src/copy-to-clipboard.standalone.js | packages/components/bolt-copy-to-clipboard/src/copy-to-clipboard.standalone.js | import {
define,
props,
withComponent,
css,
hasNativeShadowDomSupport,
withPreact,
withHyperHTML,
sanitizeBoltClasses
} from '@bolt/core';
import ClipboardJS from 'clipboard';
@define
export class BoltCopyToClipboard extends withHyperHTML() {
static is = 'bolt-copy-to-clipboard';
constructor() {
super();
}
clickHandler(event) {
event.preventDefault(); // Prevent the default link behavior
}
connecting() {
this.copyLink = this.querySelector('.js-bolt-copy-to-clipboard__default');
this.parentElem = this.querySelector('.js-bolt-copy-to-clipboard');
this.copyLink.addEventListener('click', this.clickHandler);
this.clipboardInstance = new ClipboardJS(this.copyLink); // ClipboardJS adds it's own event listener
/*
* [1] Adds a class onClick after successful copy and enables the first set of animations
* [2] Waits until the first set of animations complete and adds the last class for last animations
*/
this.clipboardInstance.on('success', () => {
this.parentElem.classList.add('is-copied'); // [1]
setTimeout(() => { // [2]
this.parentElem.classList.add('is-transitioning');
}, 2000);
});
}
disconnecting() {
this.clipboardInstance.destroy();
this.copyLink.removeEventListener('click', this.clickHandler);
}
}
| import {
define,
props,
withComponent,
css,
hasNativeShadowDomSupport,
withPreact,
BoltComponent,
sanitizeBoltClasses
} from '@bolt/core';
import ClipboardJS from 'clipboard';
@define
export class BoltCopyToClipboard extends BoltComponent() {
static is = 'bolt-copy-to-clipboard';
constructor() {
super();
}
clickHandler(event) {
event.preventDefault(); // Prevent the default link behavior
}
connecting() {
this.copyLink = this.querySelector('.js-bolt-copy-to-clipboard__default');
this.parentElem = this.querySelector('.js-bolt-copy-to-clipboard');
this.copyLink.addEventListener('click', this.clickHandler);
this.clipboardInstance = new ClipboardJS(this.copyLink); // ClipboardJS adds it's own event listener
/*
* [1] Adds a class onClick after successful copy and enables the first set of animations
* [2] Waits until the first set of animations complete and adds the last class for last animations
*/
this.clipboardInstance.on('success', () => {
this.parentElem.classList.add('is-copied'); // [1]
setTimeout(() => { // [2]
this.parentElem.classList.add('is-transitioning');
}, 2000);
});
}
disconnecting() {
this.clipboardInstance.destroy();
this.copyLink.removeEventListener('click', this.clickHandler);
}
}
| Copy to Clipboard -- Swap out withHyperHTML in favor of BoltComponent to fix console / render errors | Copy to Clipboard -- Swap out withHyperHTML in favor of BoltComponent to fix console / render errors
| JavaScript | mit | bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt,bolt-design-system/bolt | ---
+++
@@ -5,14 +5,14 @@
css,
hasNativeShadowDomSupport,
withPreact,
- withHyperHTML,
+ BoltComponent,
sanitizeBoltClasses
} from '@bolt/core';
import ClipboardJS from 'clipboard';
@define
-export class BoltCopyToClipboard extends withHyperHTML() {
+export class BoltCopyToClipboard extends BoltComponent() {
static is = 'bolt-copy-to-clipboard';
constructor() { |
9fc75f0a12404f8dbe7938e796d6c5ddfeaec1c9 | test/fixtures/collections/searchResultFields.js | test/fixtures/collections/searchResultFields.js | (function () {
'use strict';
define(function () {
return [
{
key: 'first',
labelText: 'Field One'
},
{
key: 'second',
labelText: 'Field Two'
},
{
key: 'third',
labelText: 'Field Three'
}
];
});
}());
| (function () {
'use strict';
define(function () {
return [
{
key: 'first',
labelText: 'Field One',
sort: true
},
{
key: 'second',
labelText: 'Field Two',
sort: function (value) {
return value ? value.toString().toLowerCase() : undefined;
}
},
{
key: 'third',
labelText: 'Field Three'
}
];
});
}());
| Add sort settings to fixture config. | Add sort settings to fixture config.
| JavaScript | mit | rwahs/research-frontend,rwahs/research-frontend | ---
+++
@@ -5,11 +5,15 @@
return [
{
key: 'first',
- labelText: 'Field One'
+ labelText: 'Field One',
+ sort: true
},
{
key: 'second',
- labelText: 'Field Two'
+ labelText: 'Field Two',
+ sort: function (value) {
+ return value ? value.toString().toLowerCase() : undefined;
+ }
},
{
key: 'third', |
aec799186b68bfbc5c4489750f2d26b6f0b83e51 | src/components/Todo/Todo.js | src/components/Todo/Todo.js | import React, { PropTypes } from 'react'
class Todo extends React.Component {
static propTypes = {
todo: PropTypes.any.isRequired,
deleteButtonVisible: PropTypes.bool,
onCompleted: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onDeleteButtonVisibilityChanged: PropTypes.func.isRequired
};
render () {
const textStyle = this.props.todo.completed ? {'textDecoration': 'line-through'} : {}
let deleteButtonClassName = 'delete-button close'
if (!this.props.deleteButtonVisible) {
deleteButtonClassName += ' delete-button-hidden'
}
return (
<tr className='todo'
onMouseEnter={this.handleMouseEnter.bind(this)}
onMouseLeave={this.handleMouseLeave.bind(this)}
>
<td>
<input type='checkbox' checked={this.props.todo.completed ? 'checked' : ''} onChange={() => { this.props.onCompleted(this.props.todo) } } />
</td>
<td>
<span style={textStyle}>
{this.props.todo.text}
</span>
</td>
<td>
<button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.handleDelete.bind(this)}>
<span aria-hidden='true'>×</span>
</button>
</td>
</tr>
)
}
handleMouseEnter (event) {
this.props.onDeleteButtonVisibilityChanged(this.props.todo)
}
handleMouseLeave (event) {
this.props.onDeleteButtonVisibilityChanged(undefined)
}
handleDelete () {
this.props.onDelete(this.props.todo)
}
}
export default Todo
| import React, { PropTypes } from 'react'
class Todo extends React.Component {
static propTypes = {
todo: PropTypes.any.isRequired,
deleteButtonVisible: PropTypes.bool,
onCompleted: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onDeleteButtonVisibilityChanged: PropTypes.func.isRequired
};
render () {
const textStyle = this.props.todo.completed ? {'textDecoration': 'line-through'} : {}
let deleteButtonClassName = 'delete-button close'
if (!this.props.deleteButtonVisible) {
deleteButtonClassName += ' delete-button-hidden'
}
return (
<tr className='todo'
onMouseEnter={this.props.onDeleteButtonVisibilityChanged.bind(this, this.props.todo)}
onMouseLeave={this.props.onDeleteButtonVisibilityChanged.bind(this, undefined)}
>
<td>
<input type='checkbox' checked={this.props.todo.completed ? 'checked' : ''} onChange={() => { this.props.onCompleted(this.props.todo) } } />
</td>
<td>
<span style={textStyle}>
{this.props.todo.text}
</span>
</td>
<td>
<button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.props.onDelete.bind(this, this.props.todo)}>
<span aria-hidden='true'>×</span>
</button>
</td>
</tr>
)
}
}
export default Todo
| Remove extra event handler methods from todo | Remove extra event handler methods from todo
| JavaScript | mit | stefanwille/react-todo,stefanwille/react-todo | ---
+++
@@ -17,8 +17,8 @@
}
return (
<tr className='todo'
- onMouseEnter={this.handleMouseEnter.bind(this)}
- onMouseLeave={this.handleMouseLeave.bind(this)}
+ onMouseEnter={this.props.onDeleteButtonVisibilityChanged.bind(this, this.props.todo)}
+ onMouseLeave={this.props.onDeleteButtonVisibilityChanged.bind(this, undefined)}
>
<td>
<input type='checkbox' checked={this.props.todo.completed ? 'checked' : ''} onChange={() => { this.props.onCompleted(this.props.todo) } } />
@@ -29,25 +29,13 @@
</span>
</td>
<td>
- <button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.handleDelete.bind(this)}>
+ <button type='button' className={deleteButtonClassName} aria-label='Close' onClick={this.props.onDelete.bind(this, this.props.todo)}>
<span aria-hidden='true'>×</span>
</button>
</td>
</tr>
)
}
-
- handleMouseEnter (event) {
- this.props.onDeleteButtonVisibilityChanged(this.props.todo)
- }
-
- handleMouseLeave (event) {
- this.props.onDeleteButtonVisibilityChanged(undefined)
- }
-
- handleDelete () {
- this.props.onDelete(this.props.todo)
- }
}
export default Todo |
c95310d6ab447822e2ebdc1a7fe8bfe2d7c295e7 | mix-files/index.js | mix-files/index.js | var mix = require('mix');
var path = require('path');
var vfs = require('vinyl-fs');
module.exports = function (options) {
var base = path.resolve(options.base);
var globs;
if (typeof options.globs === 'string') {
globs = [options.globs];
} else {
globs = options.globs;
}
globs = globs.map(function (g) { return path.join(base, g) });
function readTree(callback) {
var stream = vfs.src(globs, {
base: base
});
var files = [];
stream.on('data', function (file) {
files.push(file);
});
stream.on('end', function () {
callback(new mix.Tree(files.map(fileToNode)));
}.bind(this));
}
function fileToNode(file) {
return {
name: path.relative(base, file.path),
base: base,
data: file.contents,
mode: file.stat.mode
};
}
return new mix.Stream(function (sink) {
vfs.watch(globs, {}, pushNext);
pushNext();
function pushNext() {
readTree(sink.push);
}
});
};
| var mix = require('mix');
var path = require('path');
var vfs = require('vinyl-fs');
module.exports = function (options) {
var base = path.resolve(options.base);
var globs;
if (typeof options.globs === 'string') {
globs = [options.globs];
} else {
globs = options.globs;
}
globs = globs.map(function (g) { return path.join(base, g) });
function fileToNode(file) {
return {
name: path.relative(base, file.path),
base: base,
data: file.contents,
mode: file.stat.mode
};
}
return new mix.Stream(function (sink) {
var watcher = new mix.Watcher();
watcher.on('change', pushNext);
pushNext();
function pushNext() {
readTree(sink.push);
}
function readTree(callback) {
var stream = vfs.src(globs, {
base: base
});
var files = [];
stream.on('data', function (file) {
watcher.add(file.path);
files.push(file);
});
stream.on('end', function () {
callback(new mix.Tree(files.map(fileToNode)));
}.bind(this));
}
return function dispose() {
watcher.dispose();
};
});
};
| Migrate the files plugin to use Watcher | Migrate the files plugin to use Watcher
| JavaScript | mit | byggjs/bygg,byggjs/bygg-plugins | ---
+++
@@ -13,19 +13,6 @@
}
globs = globs.map(function (g) { return path.join(base, g) });
- function readTree(callback) {
- var stream = vfs.src(globs, {
- base: base
- });
- var files = [];
- stream.on('data', function (file) {
- files.push(file);
- });
- stream.on('end', function () {
- callback(new mix.Tree(files.map(fileToNode)));
- }.bind(this));
- }
-
function fileToNode(file) {
return {
name: path.relative(base, file.path),
@@ -36,11 +23,31 @@
}
return new mix.Stream(function (sink) {
- vfs.watch(globs, {}, pushNext);
+ var watcher = new mix.Watcher();
+ watcher.on('change', pushNext);
+
pushNext();
function pushNext() {
readTree(sink.push);
}
+
+ function readTree(callback) {
+ var stream = vfs.src(globs, {
+ base: base
+ });
+ var files = [];
+ stream.on('data', function (file) {
+ watcher.add(file.path);
+ files.push(file);
+ });
+ stream.on('end', function () {
+ callback(new mix.Tree(files.map(fileToNode)));
+ }.bind(this));
+ }
+
+ return function dispose() {
+ watcher.dispose();
+ };
});
}; |
3949481100244425dfdc1d478ff94101812b3de6 | tests/nightwatch/specs/current/face-to-face-page.js | tests/nightwatch/specs/current/face-to-face-page.js | 'use strict';
var util = require('util');
var common = require('../../modules/common-functions');
module.exports = {
'Start page': common.startPage,
'Categories of law (Your problem)': function(client) {
client
.assert.urlContains('/problem')
.assert.containsText('h1', 'What do you need help with?')
.click('input[name="categories"][value="clinneg"]')
.assert.attributeEquals('input[name="categories"][value="clinneg"]', 'checked', 'true')
.submitForm('form')
;
},
'Face-to-face page': function(client) {
client
.waitForElementVisible('.legal-adviser-search', 5000)
.assert.urlContains('/face-to-face')
.assert.containsText('h1', 'You may be able to get free advice from a legal adviser')
;
client.end();
}
};
| 'use strict';
var common = require('../../modules/common-functions');
module.exports = {
'Start page': common.startPage,
'Categories of law (Your problem)': function(client) {
client
.assert.urlContains('/problem')
.assert.containsText('h1', 'What do you need help with?')
.click('input[name="categories"][value="clinneg"]')
.assert.attributeEquals('input[name="categories"][value="clinneg"]', 'checked', 'true')
.submitForm('form')
;
},
'Face-to-face page': function(client) {
client
.waitForElementVisible('.legal-adviser-search', 5000)
.assert.urlContains('/face-to-face')
.assert.containsText('h1', 'You may be able to get free advice from a legal adviser')
;
},
'Find legal adviser search': function(client) {
client
.setValue('input[name="postcode"]', 'w22dd')
.submitForm('form')
.assert.urlContains('/face-to-face')
.waitForElementVisible('.search-results-container', 5000)
.assert.containsText('.results-location', 'W2 2DD')
;
client.end();
}
};
| Add simple 'Find legal adviser' search test | TEST: Add simple 'Find legal adviser' search test
| JavaScript | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | ---
+++
@@ -1,6 +1,5 @@
'use strict';
-var util = require('util');
var common = require('../../modules/common-functions');
module.exports = {
@@ -22,6 +21,16 @@
.assert.urlContains('/face-to-face')
.assert.containsText('h1', 'You may be able to get free advice from a legal adviser')
;
+ },
+
+ 'Find legal adviser search': function(client) {
+ client
+ .setValue('input[name="postcode"]', 'w22dd')
+ .submitForm('form')
+ .assert.urlContains('/face-to-face')
+ .waitForElementVisible('.search-results-container', 5000)
+ .assert.containsText('.results-location', 'W2 2DD')
+ ;
client.end();
} |
7991b9480f2c975420f9786db509d32bc1e54110 | nuxt.config.js | nuxt.config.js | module.exports = {
/*
** Headers of the page
*/
head: {
title: 'CSS Frameworks',
titleTemplate: '%s - CSS Frameworks',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Compare CSS frameworks.' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }
]
},
css: [{
src: '~assets/css/main.scss',
lang: 'scss'
}],
/*
** Customize the progress-bar color
*/
loading: { color: '#685143' },
/*
** Build configurationwebpack
*/
build: {
/*
** Run ESLINT on save
*/
extend (config, ctx) {
if (ctx.dev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
},
vendor: [
'~/assets/js/shared.js'
]
}
}
| const path = require('path')
const dataPath = path.join(__dirname, process.env.repoDataPath || 'data.json')
const frameworks = require(dataPath)
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'CSS Frameworks',
titleTemplate: '%s - CSS Frameworks',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Compare CSS frameworks.' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato' }
]
},
css: [{
src: '~assets/css/main.scss',
lang: 'scss'
}],
/*
** Customize the progress-bar color
*/
loading: { color: '#685143' },
/*
** Build configurationwebpack
*/
build: {
/*
** Run ESLINT on save
*/
extend (config, ctx) {
if (ctx.dev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
env: {
frameworks
}
}
| Change the way to load json | Change the way to load json
| JavaScript | mit | sunya9/css-frameworks,sunya9/css-frameworks | ---
+++
@@ -1,3 +1,8 @@
+const path = require('path')
+
+const dataPath = path.join(__dirname, process.env.repoDataPath || 'data.json')
+const frameworks = require(dataPath)
+
module.exports = {
/*
** Headers of the page
@@ -39,9 +44,9 @@
exclude: /(node_modules)/
})
}
- },
- vendor: [
- '~/assets/js/shared.js'
- ]
+ }
+ },
+ env: {
+ frameworks
}
} |
410f70101c4d7b21890835438e50f5e7c08d2962 | config/linked-packages.example.js | config/linked-packages.example.js | /**
* Copy this file to `local/linked-packages.js` and uncomment any modules as desired to link them
* for local development.
*
* These will be resolved as aliases in the webpack config. Note that you will need to ensure that
* the packages are installed (via `yarn install`) in each respective folder
*
* It's recommended to use the `yarn startLocal` script to run the app, as it will automatically
* start the webpack development server for the `viz` repo when needed.
*
* You may add as other modules to this list as well.
*/
var packages = {
// '@tidepool/viz': process.env.TIDEPOOL_DOCKER_VIZ_DIR || '../viz',
// 'tideline': process.env.TIDEPOOL_DOCKER_TIDELINE_DIR || '../tideline',
// 'tidepool-platform-client': process.env.TIDEPOOL_DOCKER_PLATFORM_CLIENT_DIR || '../platform-client',
};
module.exports = {
list: () => console.log(Object.keys(packages).join(',')),
packages: packages,
}
| /**
* Copy this file to `config/linked-packages.js` and uncomment any modules as desired to link them
* for local development.
*
* These will be resolved as aliases in the webpack config. Note that you will need to ensure that
* the packages are installed (via `yarn install`) in each respective folder
*
* It's recommended to use the `yarn startLocal` script to run the app, as it will automatically
* start the webpack development server for the `viz` repo when needed.
*
* You may add as other modules to this list as well.
*/
var packages = {
// '@tidepool/viz': process.env.TIDEPOOL_DOCKER_VIZ_DIR || '../viz',
// 'tideline': process.env.TIDEPOOL_DOCKER_TIDELINE_DIR || '../tideline',
// 'tidepool-platform-client': process.env.TIDEPOOL_DOCKER_PLATFORM_CLIENT_DIR || '../platform-client',
};
module.exports = {
list: () => console.log(Object.keys(packages).join(',')),
packages: packages,
}
| Fix incorrect path in linked packages instructions | Fix incorrect path in linked packages instructions
| JavaScript | bsd-2-clause | tidepool-org/blip,tidepool-org/blip,tidepool-org/blip | ---
+++
@@ -1,5 +1,5 @@
/**
- * Copy this file to `local/linked-packages.js` and uncomment any modules as desired to link them
+ * Copy this file to `config/linked-packages.js` and uncomment any modules as desired to link them
* for local development.
*
* These will be resolved as aliases in the webpack config. Note that you will need to ensure that |
23cff7eb77661c30c6449adc9a04bda5cf300e3f | karma.conf.js | karma.conf.js | var _ = require('lodash')
var webpackConfig = require('./webpack.config')
var config = {
frameworks: ['mocha', 'effroi'],
preprocessors: {
'tests/index.js': ['webpack', 'sourcemap']
},
files: [
'tests/index.js'
],
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// this watcher watches when bundled files are updated
autoWatch: true,
webpack: _.extend(webpackConfig, {
entry: undefined,
// this watcher watches when source files are updated
watch: true,
module: _.extend(webpackConfig.module, {
postLoaders: [{
test: /\.js/,
exclude: /(test|node_modules)/,
loader: 'istanbul-instrumenter'
}]
})
}),
webpackServer: {
noInfo: true
},
client: {
useIframe: true,
captureConsole: true,
mocha: {
ui: 'qunit'
}
},
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browserNoActivityTimeout: 30000,
coverageReporter: {
reporters: [
{type: 'html', dir: 'coverage/'},
{type: 'text-summary'}
]
}
}
module.exports = function (c) {
c.set(config)
}
module.exports.config = config
| var _ = require('lodash')
var webpackConfig = require('./webpack.config')
var config = {
frameworks: ['mocha', 'effroi'],
preprocessors: {
'tests/index.js': ['webpack', 'sourcemap']
},
files: [
'tests/index.js'
],
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
// this watcher watches when bundled files are updated
autoWatch: true,
webpack: _.extend(webpackConfig, {
entry: undefined,
// this watcher watches when source files are updated
watch: true,
devtool: 'inline-source-map',
module: _.extend(webpackConfig.module, {
postLoaders: [{
test: /\.js/,
exclude: /(test|node_modules)/,
loader: 'istanbul-instrumenter'
}]
})
}),
webpackServer: {
noInfo: true
},
client: {
useIframe: true,
captureConsole: true,
mocha: {
ui: 'qunit'
}
},
browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browserNoActivityTimeout: 30000,
coverageReporter: {
reporters: [
{type: 'html', dir: 'coverage/'},
{type: 'text-summary'}
]
}
}
module.exports = function (c) {
c.set(config)
}
module.exports.config = config
| Bring back source maps in tests | Bring back source maps in tests
| JavaScript | mit | QubitProducts/cherrytree,nathanboktae/cherrytree,nathanboktae/cherrytree,QubitProducts/cherrytree | ---
+++
@@ -23,6 +23,7 @@
entry: undefined,
// this watcher watches when source files are updated
watch: true,
+ devtool: 'inline-source-map',
module: _.extend(webpackConfig.module, {
postLoaders: [{
test: /\.js/, |
40e62cabfa801b44e8c43eacb0bc4510c619359c | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
files: [
'bower_components/versal-component-runtime/dist/runtime.min.js',
'index.html',
'test/*_spec.js',
{pattern: 'index.js', included: false},
{pattern: 'test/test_gadget.html', included: false}
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
autoWatch: true,
browsers: ['Firefox']
});
};
| module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai'],
files: [
'bower_components/versal-component-runtime/dist/runtime.min.js',
'index.html',
'test/*_spec.js',
{pattern: 'index.js', included: false},
{pattern: 'test/test_gadget.html', included: false}
],
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
autoWatch: true,
browsers: ['Firefox']
});
};
| Use dots reporter instead of progress | Use dots reporter instead of progress
Because of https://github.com/karma-runner/karma/issues/724 | JavaScript | mit | Versal/versal-gadget-launchers,Versal/versal-gadget-launchers | ---
+++
@@ -8,7 +8,7 @@
{pattern: 'index.js', included: false},
{pattern: 'test/test_gadget.html', included: false}
],
- reporters: ['progress'],
+ reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG |
2cd672d73c2d232fe6431cefa846b330443c7a5e | web/src/js/components/General/FullScreenProgress.js | web/src/js/components/General/FullScreenProgress.js |
import React from 'react'
import PropTypes from 'prop-types'
import CircularProgress from 'material-ui/CircularProgress'
class FullScreenProgress extends React.Component {
render () {
const {containerStyle, progressStyle} = this.props
return (
<div
style={containerStyle}>
<CircularProgress
{...progressStyle} />
</div>)
}
}
FullScreenProgress.propTypes = {
containerStyle: PropTypes.object,
progressStyle: PropTypes.object
}
FullScreenProgress.defaultProps = {
containerStyle: {
width: '100vw',
height: '100vh',
boxSizing: 'border-box',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
},
progressStyle: {
size: 60,
thickness: 7
}
}
export default FullScreenProgress
|
import React from 'react'
import PropTypes from 'prop-types'
import CircularProgress from 'material-ui/CircularProgress'
class FullScreenProgress extends React.Component {
render () {
const {containerStyle, progressStyle} = this.props
return (
<div
style={containerStyle}>
<CircularProgress
{...progressStyle} />
</div>)
}
}
FullScreenProgress.propTypes = {
containerStyle: PropTypes.object,
progressStyle: PropTypes.object
}
FullScreenProgress.defaultProps = {
containerStyle: {
width: '100vw',
height: '100vh',
maxWidth: '100%',
boxSizing: 'border-box',
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
},
progressStyle: {
size: 60,
thickness: 7
}
}
export default FullScreenProgress
| Add a max width to 100vw component to avoid horizontal scroll. | Add a max width to 100vw component to avoid horizontal scroll.
| JavaScript | mpl-2.0 | gladly-team/tab,gladly-team/tab,gladly-team/tab | ---
+++
@@ -25,6 +25,7 @@
containerStyle: {
width: '100vw',
height: '100vh',
+ maxWidth: '100%',
boxSizing: 'border-box',
display: 'flex',
justifyContent: 'center', |
1bb6e58b0e8a1e1f5ac48bdca2ab3ac0b3beaf0d | lib/control/v1/index.js | lib/control/v1/index.js | 'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.use('/v1/health', Handlers.allowed('GET'));
app.get('/v1/token/default', require('./token')(storage));
app.use('/v1/token', Handlers.allowed('GET'));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.use('/v1/secret', Handlers.allowed('GET'));
app.get('/v1/cubbyhole/:token/:path', require('./cubbyhole')(storage));
app.use('/v1/cubbyhole', Handlers.allowed('GET'));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.use('/v1/credential', Handlers.allowed('GET'));
app.use(BodyParser.json());
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Err);
};
| 'use strict';
const express = require('express');
const BodyParser = require('body-parser');
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
app.get('/v1/token/default', require('./token')(storage));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.get('/v1/cubbyhole/:token/:path', require('./cubbyhole')(storage));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.use(BodyParser.json());
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Handlers.allowed('GET'));
app.use(Err);
};
| Clean up route handling so it's more readable. | Clean up route handling so it's more readable.
| JavaScript | mit | rapid7/tokend,rapid7/tokend,rapid7/tokend | ---
+++
@@ -7,22 +7,17 @@
exports.attach = function (app, storage) {
app.get('/v1/health', require('./health'));
- app.use('/v1/health', Handlers.allowed('GET'));
app.get('/v1/token/default', require('./token')(storage));
- app.use('/v1/token', Handlers.allowed('GET'));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
- app.use('/v1/secret', Handlers.allowed('GET'));
app.get('/v1/cubbyhole/:token/:path', require('./cubbyhole')(storage));
- app.use('/v1/cubbyhole', Handlers.allowed('GET'));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
- app.use('/v1/credential', Handlers.allowed('GET'));
app.use(BodyParser.json());
-
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
+ app.use(Handlers.allowed('GET'));
app.use(Err);
}; |
cd3abcf0a72ab69da0c26a483cfddf35e35c0f03 | clientapp/models/call.js | clientapp/models/call.js | /*global app, me, client*/
"use strict";
var _ = require('underscore');
var HumanModel = require('human-model');
var logger = require('andlog');
module.exports = HumanModel.define({
type: 'call',
initialize: function (attrs) {
this.contact.onCall = true;
},
session: {
contact: 'object',
jingleSession: 'object',
state: ['string', true, 'inactive'],
multiUser: ['boolean', true, false]
},
end: function (reasonForEnding) {
var reason = reasonForEnding || 'success';
this.contact.onCall = false;
if (this.jingleSession) {
this.jingleSession.end({
condition: reason
});
}
this.collection.remove(this);
}
});
| /*global app, me, client*/
"use strict";
var _ = require('underscore');
var HumanModel = require('human-model');
var logger = require('andlog');
module.exports = HumanModel.define({
type: 'call',
initialize: function (attrs) {
this.contact.onCall = true;
},
session: {
contact: 'object',
jingleSession: 'object',
state: ['string', true, 'inactive'],
multiUser: ['boolean', true, false]
},
end: function (reasonForEnding) {
var reason = reasonForEnding || 'success';
this.contact.onCall = false;
if (this.jingleSession) {
this.jingleSession.end(reasonForEnding);
}
this.collection.remove(this);
}
});
| Fix excess reason condition wrapping | Fix excess reason condition wrapping
| JavaScript | mit | digicoop/kaiwa,lasombra/kaiwa,warcode/kaiwa,syci/kaiwa,nsg/kaiwa,rogervaas/otalk-im-client,syci/kaiwa,weiss/kaiwa,ForNeVeR/kaiwa,unam3/kaiwa,heyLu/kaiwa,ForNeVeR/kaiwa,digicoop/kaiwa,warcode/kaiwa,otalk/otalk-im-client,nsg/kaiwa,heyLu/kaiwa,ForNeVeR/kaiwa,weiss/kaiwa,lasombra/kaiwa,heyLu/kaiwa,di-stars/kaiwa,rogervaas/otalk-im-client,di-stars/kaiwa,digicoop/kaiwa,warcode/kaiwa,syci/kaiwa,weiss/kaiwa,nsg/kaiwa,birkb/kaiwa,birkb/kaiwa,ForNeVeR/kaiwa,di-stars/kaiwa,otalk/otalk-im-client,unam3/kaiwa,birkb/kaiwa,lasombra/kaiwa | ---
+++
@@ -21,9 +21,7 @@
var reason = reasonForEnding || 'success';
this.contact.onCall = false;
if (this.jingleSession) {
- this.jingleSession.end({
- condition: reason
- });
+ this.jingleSession.end(reasonForEnding);
}
this.collection.remove(this);
} |
c59942e85fd74b8794aca87ececfb8f15b368724 | helpers/helpers.js | helpers/helpers.js | module.exports = function (context) {
return {
$: function (expression) {
return expression
},
extend: {
extendables: {},
add: function (selector, cssString) {
this.extendables[selector] = {
css: cssString,
selectors: []
}
},
that: function (extendable, selector) {
if(!this.extendables[extendable]) return false
this.extendables[extendable]['selectors'].push(selector)
context.onDone.push(this.extendMaker(extendable))
},
extendMaker: function (extendable) {
var self = this
return function () {
var returnVal
if(!self.extendables[extendable]) return ''
returnVal = [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n'
self.extendables[extendable] = false
return returnVal
}
}
}
}
} | module.exports = function (context) {
return {
$: function (expression) {
return expression
},
extend: {
extendables: {},
add: function (selector, cssString) {
this.extendables[selector] = {
css: cssString,
selectors: []
}
},
that: function (extendable, selector) {
if(!this.extendables[extendable]) return false
this.extendables[extendable]['selectors'].push(selector)
context.onDone.push(this.extendMaker(extendable))
},
extendMaker: function (extendable) {
var self = this
return function () {
var returnVal
if(!self.extendables[extendable]) return ''
returnVal = [extendable].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n'
self.extendables[extendable] = false
return returnVal
}
}
}
}
} | Fix a bug in extend | Fix a bug in extend
| JavaScript | mit | Kriegslustig/jsheets | ---
+++
@@ -22,7 +22,7 @@
return function () {
var returnVal
if(!self.extendables[extendable]) return ''
- returnVal = [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n'
+ returnVal = [extendable].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n'
self.extendables[extendable] = false
return returnVal
} |
3e2cf41793074bce2338a2e4f75d2940d1f0ea30 | rest/making-calls/example-4/example-4.2.x.js | rest/making-calls/example-4/example-4.2.x.js | // Download the Node helper library from twilio.com/docs/node/install
// These vars are your accountSid and authToken from twilio.com/user/account
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: "http://demo.twilio.com/docs/voice.xml",
to: "+14155551212",
from: "+18668675309",
statusCallback: "https://www.myapp.com/events",
statusCallbackMethod: "POST",
statusCallbackEvent: ["initiated", "ringing", "answered", "completed"],
method: "GET"
}, function(err, call) {
process.stdout.write(call.sid);
});
| // Download the Node helper library from twilio.com/docs/node/install
// These vars are your accountSid and authToken from twilio.com/user/account
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: "http://demo.twilio.com/docs/voice.xml",
to: "+14155551212",
from: "+18668675309",
statusCallback: "https://www.myapp.com/events",
statusCallbackMethod: "POST",
statusCallbackEvent: "initiated ringing answered completed",
method: "GET"
}, function(err, call) {
process.stdout.write(call.sid);
});
| Update based on feedback from @nash-md | Update based on feedback from @nash-md | JavaScript | mit | TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets | ---
+++
@@ -10,7 +10,7 @@
from: "+18668675309",
statusCallback: "https://www.myapp.com/events",
statusCallbackMethod: "POST",
- statusCallbackEvent: ["initiated", "ringing", "answered", "completed"],
+ statusCallbackEvent: "initiated ringing answered completed",
method: "GET"
}, function(err, call) {
process.stdout.write(call.sid); |
4251b1b921f5e566eb571a320b64c77ca8adcc2b | src/components/Header/index.js | src/components/Header/index.js | import React, { Component } from 'react';
import { Link } from 'react-router';
import ChannelDropdown from '../../containers/ChannelDropdown/ChannelDropdown';
/* component styles */
import { styles } from './styles.scss';
export class Header extends Component {
render() {
return (
<header className={`${styles}`}>
<div className="container">
<div className="row">
<div className="col-sm-6">
<Link to="/" className="logo">
<h1>Twitch Chat Visualizer</h1>
</Link>
</div>
<div className="col-sm-6 channel-dropdown-container">
<ChannelDropdown />
</div>
</div>
</div>
</header>
);
}
}
| import React, { Component } from 'react';
import { Link } from 'react-router';
import ChannelDropdown from '../../containers/ChannelDropdown/ChannelDropdown';
/* component styles */
import { styles } from './styles.scss';
export class Header extends Component {
render() {
return (
<header className={`${styles}`}>
<div className="container">
<div className="row">
<div className="col-xs-12">
<ChannelDropdown />
</div>
</div>
</div>
</header>
);
}
}
| Move logo link out of header component and into child, simplify markup | Move logo link out of header component and into child, simplify markup
| JavaScript | mit | dramich/Chatson,dramich/twitchBot,badT/twitchBot,TerryCapan/twitchBot,dramich/Chatson,TerryCapan/twitchBot,badT/Chatson,badT/twitchBot,badT/Chatson,dramich/twitchBot | ---
+++
@@ -11,13 +11,7 @@
<header className={`${styles}`}>
<div className="container">
<div className="row">
- <div className="col-sm-6">
- <Link to="/" className="logo">
- <h1>Twitch Chat Visualizer</h1>
- </Link>
- </div>
-
- <div className="col-sm-6 channel-dropdown-container">
+ <div className="col-xs-12">
<ChannelDropdown />
</div>
</div> |
cee6b37beef9493d808f743b5af8ab64ce78809f | trait-purender.babel.js | trait-purender.babel.js | import value from 'object-path';
export const purender = ({raw}, ...values) => ({
[Symbol.toStringTag]: 'purender',
shouldComponentUpdate(...args) {
const watchlist = String.raw({raw}, ...values).split(' ');
return watchlist.reduce((m, n) => {
const [props, state] = args,
next = {props, state},
[type, ...path] = n.split('.');
return m || value.get(this[type], path) !== value.get(next[type], path);
}, false);
}
});
| import value from 'object-path';
export const purender = ({raw}, ...values) => ({
[Symbol.toStringTag]: 'purender',
shouldComponentUpdate(...args) {
const watchlist = String.raw({raw}, ...values).split(/\s+/);
return watchlist.reduce((m, n) => {
const [props, state] = args,
next = {props, state},
[type, ...path] = n.split('.');
return m || value.get(this[type], path) !== value.get(next[type], path);
}, false);
}
});
| Remove all white space characters in `watchlist` | Remove all white space characters in `watchlist`
| JavaScript | mit | gsklee/trait-purender | ---
+++
@@ -4,7 +4,7 @@
[Symbol.toStringTag]: 'purender',
shouldComponentUpdate(...args) {
- const watchlist = String.raw({raw}, ...values).split(' ');
+ const watchlist = String.raw({raw}, ...values).split(/\s+/);
return watchlist.reduce((m, n) => {
const [props, state] = args, |
8aa4df88c6df2ea5363b0ffc73f43ae0e336a5f2 | commands/discrim.js | commands/discrim.js | const Discord = require('discord.js');
let embed = new Discord.RichEmbed();
exports.run = (client, message) => {
message.delete();
let args = message.content.split(' ').splice(1).join(' ');
const res = client.users.filter(u => u.discriminator === `${args}`).map(u => u.username);
if(res.length === 0) {
embed.setAuthor(`No users found with ${args}`)
.setColor("#53A6F3")
.setTimestamp();
message.channel.send({ embed })
} else {
embed.setAuthor(`Users Found With ${args}`)
.setDescription(`${res.join('\n')}`)
.setColor("#53A6F3")
.setTimestamp();
message.channel.send({ embed })
}
}
| const Discord = require('discord.js');
let embed = new Discord.RichEmbed();
exports.run = (client, message) => {
message.delete();
let args = message.content.split(" ").splice(1).join(" ");
const res = client.users.filter(u => u.discriminator === `${args}`).map(u => u.username);
if(res.length === 0) {
embed.setAuthor(`No users found with ${args}`)
.setColor("#53A6F3")
.setTimestamp();
message.channel.send({ embed })
} else {
embed.setAuthor(`Users Found With ${args}`)
.setDescription(`${res.join('\n')}`)
.setColor("#53A6F3")
.setTimestamp();
message.channel.send({ embed })
}
}
| Fix string - Must used double quote | Fix string - Must used double quote | JavaScript | mit | JohnDoesCodes/Selfbot,JohnDoesCodes/MySelfbot | ---
+++
@@ -2,7 +2,7 @@
let embed = new Discord.RichEmbed();
exports.run = (client, message) => {
message.delete();
- let args = message.content.split(' ').splice(1).join(' ');
+ let args = message.content.split(" ").splice(1).join(" ");
const res = client.users.filter(u => u.discriminator === `${args}`).map(u => u.username);
if(res.length === 0) {
embed.setAuthor(`No users found with ${args}`) |
134cad0d006b00d073d029c7b4b9c687b3145c99 | src/lifecycle/attribute.js | src/lifecycle/attribute.js | import data from '../util/data';
export default function (opts) {
const { attribute } = opts;
return function (name, oldValue, newValue) {
const propertyName = data(this, 'attributeLinks')[name];
if (propertyName) {
const propertyData = data(this, `api/property/${propertyName}`);
if (!propertyData.settingProperty) {
const propOpts = this.constructor.properties[propertyName];
this[propertyName] = propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
}
}
if (attribute) {
attribute(this, {
name: name,
newValue: newValue === null ? undefined : newValue,
oldValue: oldValue === null ? undefined : oldValue
});
}
};
}
| import data from '../util/data';
export default function (opts) {
const { attribute } = opts;
return function (name, oldValue, newValue) {
const propertyName = data(this, 'attributeLinks')[name];
if (propertyName) {
const propertyData = data(this, `api/property/${propertyName}`);
if (!propertyData.settingProperty) {
const propOpts = this.constructor.properties[propertyName];
this[propertyName] = newValue !== null && propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
}
}
if (attribute) {
attribute(this, {
name: name,
newValue: newValue === null ? undefined : newValue,
oldValue: oldValue === null ? undefined : oldValue
});
}
};
}
| Fix issue where value might be null in which case it's safe to just set directly on the property. | Fix issue where value might be null in which case it's safe to just set directly on the property.
| JavaScript | mit | skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs | ---
+++
@@ -10,7 +10,7 @@
const propertyData = data(this, `api/property/${propertyName}`);
if (!propertyData.settingProperty) {
const propOpts = this.constructor.properties[propertyName];
- this[propertyName] = propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
+ this[propertyName] = newValue !== null && propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
}
}
|
a8a6b901289de0b918df9b9ee66f52fc534dd55b | scripts/generate-entry-i10n.js | scripts/generate-entry-i10n.js | const promise = require("bluebird");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
var db;
checkConnection();
function checkConnection() {
let config;
try {
config = parse(connectionString);
if (process.env.NODE_ENV === "test" || config.host === "localhost") {
config.ssl = false;
} else {
config.ssl = true;
}
console.log(config);
console.log()
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
db = pgp(config);
} | const promise = require("bluebird");
const { SUPPORTED_LANGUAGES } = require("./../constants.js");
const { find } = require("lodash");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
var db;
checkConnection();
getLocalizationData();
function checkConnection() {
let config;
try {
config = parse(connectionString);
if (process.env.NODE_ENV === "test" || config.host === "localhost") {
config.ssl = false;
} else {
config.ssl = true;
}
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
db = pgp(config);
}
function getLocalizationData() {
db.any(`SELECT * FROM localized_texts`)
.then(function(data) {
data.forEach(data => {
});
})
.catch(function(error) {
console.log(error);
});
} | Prepare fetching of localization data | Prepare fetching of localization data
| JavaScript | mit | participedia/api,participedia/api,participedia/api,participedia/api | ---
+++
@@ -1,4 +1,6 @@
const promise = require("bluebird");
+const { SUPPORTED_LANGUAGES } = require("./../constants.js");
+const { find } = require("lodash");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
@@ -9,6 +11,7 @@
const parse = require("pg-connection-string").parse;
var db;
checkConnection();
+getLocalizationData();
function checkConnection() {
let config;
@@ -19,11 +22,21 @@
} else {
config.ssl = true;
}
- console.log(config);
- console.log()
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
db = pgp(config);
}
+
+function getLocalizationData() {
+ db.any(`SELECT * FROM localized_texts`)
+ .then(function(data) {
+ data.forEach(data => {
+
+ });
+ })
+ .catch(function(error) {
+ console.log(error);
+ });
+} |
488e3f56b59859258a6e89c359ffa0a2ca5199c2 | Apps/server.js | Apps/server.js | /*global require,__dirname*/
var connect = require('connect');
connect.createServer(
connect.static(__dirname)
).listen(8080); | /*global require,__dirname*/
/*jshint es3:false*/
var connect = require('connect');
connect.createServer(
connect.static(__dirname)
).listen(8080); | Fix warning with new JSHint version. | Fix warning with new JSHint version.
| JavaScript | apache-2.0 | jason-crow/cesium,kiselev-dv/cesium,geoscan/cesium,denverpierce/cesium,denverpierce/cesium,hodbauer/cesium,CesiumGS/cesium,kiselev-dv/cesium,CesiumGS/cesium,kaktus40/cesium,likangning93/cesium,esraerik/cesium,AnalyticalGraphicsInc/cesium,NaderCHASER/cesium,progsung/cesium,ggetz/cesium,emackey/cesium,YonatanKra/cesium,oterral/cesium,progsung/cesium,ggetz/cesium,wallw-bits/cesium,likangning93/cesium,aelatgt/cesium,soceur/cesium,soceur/cesium,oterral/cesium,denverpierce/cesium,ggetz/cesium,josh-bernstein/cesium,omh1280/cesium,omh1280/cesium,denverpierce/cesium,wallw-bits/cesium,esraerik/cesium,jason-crow/cesium,esraerik/cesium,geoscan/cesium,AnimatedRNG/cesium,oterral/cesium,omh1280/cesium,soceur/cesium,jason-crow/cesium,jasonbeverage/cesium,jason-crow/cesium,emackey/cesium,CesiumGS/cesium,aelatgt/cesium,AnimatedRNG/cesium,CesiumGS/cesium,AnimatedRNG/cesium,NaderCHASER/cesium,ggetz/cesium,josh-bernstein/cesium,aelatgt/cesium,wallw-bits/cesium,likangning93/cesium,jasonbeverage/cesium,AnimatedRNG/cesium,aelatgt/cesium,emackey/cesium,hodbauer/cesium,likangning93/cesium,omh1280/cesium,hodbauer/cesium,AnalyticalGraphicsInc/cesium,YonatanKra/cesium,CesiumGS/cesium,kiselev-dv/cesium,esraerik/cesium,wallw-bits/cesium,kaktus40/cesium,YonatanKra/cesium,YonatanKra/cesium,emackey/cesium,NaderCHASER/cesium,kiselev-dv/cesium,likangning93/cesium | ---
+++
@@ -1,4 +1,5 @@
/*global require,__dirname*/
+/*jshint es3:false*/
var connect = require('connect');
connect.createServer(
connect.static(__dirname) |
8ad089b866785e51763bb1e2749fd1c957ef9c1e | src/main/web/florence/js/functions/_viewLogIn.js | src/main/web/florence/js/functions/_viewLogIn.js | function viewLogIn() {
var login_form = templates.login;
$('.section').html(login_form);
$('.form-login').submit(function (e) {
e.preventDefault();
var email = $('.fl-user-and-access__email').val();
var password = $('.fl-user-and-access__password').val();
postLogin(email, password);
});
}
| function viewLogIn() {
var login_form = templates.login;
$('.section').html(login_form);
$('.form-login').submit(function (e) {
e.preventDefault();
loadingBtn($('#login'));
var email = $('.fl-user-and-access__email').val();
var password = $('.fl-user-and-access__password').val();
postLogin(email, password);
});
}
| Add loading icon to login screen | Add loading icon to login screen
Former-commit-id: 90d450bf4183942e81865a20f91780d27f208994 | JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -1,13 +1,14 @@
function viewLogIn() {
- var login_form = templates.login;
- $('.section').html(login_form);
+ var login_form = templates.login;
+ $('.section').html(login_form);
- $('.form-login').submit(function (e) {
- e.preventDefault();
- var email = $('.fl-user-and-access__email').val();
- var password = $('.fl-user-and-access__password').val();
- postLogin(email, password);
- });
+ $('.form-login').submit(function (e) {
+ e.preventDefault();
+ loadingBtn($('#login'));
+ var email = $('.fl-user-and-access__email').val();
+ var password = $('.fl-user-and-access__password').val();
+ postLogin(email, password);
+ });
}
|
2f19d1c6b2d39958e59afaca72cc66a1e55daf58 | app/components/preheatPresets/index.js | app/components/preheatPresets/index.js | import React from 'react';
import { forEach } from 'lodash'
import ControllButton from '../controllButton';
import { getUniqueId } from '../../lib/utils';
const PreheatPresets = ({ presets, onClick }) => (
<div>
{Object.keys(presets).map(preset => {
return (<div>
<ControllButton onClick={() => { onClick(presets[preset].value); }}>{preset}</ControllButton>
</div>);
})}
</div>
);
export default PreheatPresets;
| import React from 'react';
import { forEach } from 'lodash'
import ControllButton from '../controllButton';
import { getUniqueId } from '../../lib/utils';
const PreheatPresets = ({ presets, onClick }) => (
<div>
{Object.keys(presets).map(preset => {
return (<div>
<ControllButton onClick={() => { onClick(presets[preset].value); }}>{presets[preset].name}</ControllButton>
</div>);
})}
</div>
);
export default PreheatPresets;
| Fix wrong name being used at temperature preset component | Fix wrong name being used at temperature preset component
| JavaScript | agpl-3.0 | MakersLab/farm-client,MakersLab/farm-client | ---
+++
@@ -8,7 +8,7 @@
<div>
{Object.keys(presets).map(preset => {
return (<div>
- <ControllButton onClick={() => { onClick(presets[preset].value); }}>{preset}</ControllButton>
+ <ControllButton onClick={() => { onClick(presets[preset].value); }}>{presets[preset].name}</ControllButton>
</div>);
})}
</div> |
b96c549fcdaa39ab03704fa064bd4c6852fb2249 | src/full-observation-widget.js | src/full-observation-widget.js | import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue((newVnode) => {
getScheduler().updateDocument(() => {
if (this.domNode) {
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
| import createElement from 'virtual-dom/create-element'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import VText from 'virtual-dom/vnode/vtext'
import { getScheduler } from './scheduler-assignment'
export default class FullObservationWidget {
constructor (observation) {
this.type = 'Widget'
this.observation = observation
this.domNode = null
this.vnode = null
this.observationSubscription = null
}
init () {
this.trackObservation()
this.vnode = this.getObservationValue()
this.domNode = createElement(this.vnode)
return this.domNode
}
update (previous, domNode) {
this.domNode = domNode
this.trackObservation()
this.vnode = this.getObservationValue()
patch(domNode, diff(previous.vnode, this.vnode))
previous.destroy()
}
destroy () {
this.observationSubscription.dispose()
this.observationSubscription = null
this.domNode = null
this.vnode = null
}
getObservationValue () {
let value = this.observation.getValue()
if (typeof value === 'string') {
return new VText(value)
} else {
return value
}
}
trackObservation () {
this.observationSubscription = this.observation.onDidChangeValue(() => {
getScheduler().updateDocument(() => {
if (this.domNode) {
let newVnode = this.getObservationValue()
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
}
})
})
}
}
| Convert strings to VText nodes | Convert strings to VText nodes | JavaScript | mit | lee-dohm/etch,atom/etch,nathansobo/etch,smashwilson/etch | ---
+++
@@ -45,9 +45,10 @@
}
trackObservation () {
- this.observationSubscription = this.observation.onDidChangeValue((newVnode) => {
+ this.observationSubscription = this.observation.onDidChangeValue(() => {
getScheduler().updateDocument(() => {
if (this.domNode) {
+ let newVnode = this.getObservationValue()
patch(this.domNode, diff(this.vnode, newVnode))
this.vnode = newVnode
} |
bfbf2dcdbd2e0a2eb56391a903204ec6b8b4e9c1 | src/in-view.js | src/in-view.js | import Registry from './registry';
const initInView = () => {
const getElements = (selector) =>
[].slice.call(document.querySelectorAll(selector));
const inViewport = (element, offset = 0) => {
let bounds = element.getBoundingClientRect();
return bounds.bottom > offset
&& bounds.right > offset
&& window.innerWidth - bounds.left > offset
&& window.innerHeight - bounds.top > offset;
};
const throttle = (fn, threshold, context) => {
let prev = 0;
return () => {
let now = new Date().getTime();
if (now - prev > threshold) {
fn.call(context);
prev = now;
}
};
};
let catalog = { history: [] };
let inView = (selector) => {
let elements = getElements(selector);
if (catalog.history.indexOf(selector) > -1) {
catalog[selector].elements = elements;
} else {
catalog[selector] = new Registry(elements);
catalog.history.push(selector);
}
return catalog[selector];
};
inView.is = inViewport;
return inView;
};
export default initInView();
| import Registry from './registry';
const inView = () => {
const getElements = (selector) =>
[].slice.call(document.querySelectorAll(selector));
const inViewport = (element, offset = 0) => {
let bounds = element.getBoundingClientRect();
return bounds.bottom > offset
&& bounds.right > offset
&& window.innerWidth - bounds.left > offset
&& window.innerHeight - bounds.top > offset;
};
const throttle = (fn, threshold, context) => {
let prev = 0;
return () => {
let now = new Date().getTime();
if (now - prev > threshold) {
fn.call(context);
prev = now;
}
};
};
let catalog = { history: [] };
let control = (selector) => {
let elements = getElements(selector);
if (catalog.history.indexOf(selector) > -1) {
catalog[selector].elements = elements;
} else {
catalog[selector] = new Registry(elements);
catalog.history.push(selector);
}
return catalog[selector];
};
control.is = inViewport;
return control;
};
export default inView();
| Rename returned interface to control and init to inView | Rename returned interface to control and init to inView
| JavaScript | mit | kudago/in-view,camwiegert/in-view | ---
+++
@@ -1,6 +1,6 @@
import Registry from './registry';
-const initInView = () => {
+const inView = () => {
const getElements = (selector) =>
[].slice.call(document.querySelectorAll(selector));
@@ -26,7 +26,7 @@
let catalog = { history: [] };
- let inView = (selector) => {
+ let control = (selector) => {
let elements = getElements(selector);
if (catalog.history.indexOf(selector) > -1) {
catalog[selector].elements = elements;
@@ -37,10 +37,10 @@
return catalog[selector];
};
- inView.is = inViewport;
+ control.is = inViewport;
- return inView;
+ return control;
};
-export default initInView();
+export default inView(); |
6f88697b24891b6f97077de1806e40412f4da6a8 | server/game/cards/01-Core/AdeptOfTheWaves.js | server/game/cards/01-Core/AdeptOfTheWaves.js | const DrawCard = require('../../drawcard.js');
class AdeptOfTheWaves extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Grant Covert to a character',
target: {
cardType: 'character',
cardCondition: card => card.location === 'play area'
},
handler: context => {
this.game.addMessage('{0} uses {1} to grant Covet during Water conflicts to {2}', this.controller, this, context.target);
this.untilEndOfPhase(ability => ({
match: context.target,
condition: () => this.game.currentConflict && this.game.currentConflict.conflictRing === 'water',
effect: ability.effects.addKeyword('covert')
}));
}
});
}
}
AdeptOfTheWaves.id = 'adept-of-the-waves';
module.exports = AdeptOfTheWaves;
| const DrawCard = require('../../drawcard.js');
class AdeptOfTheWaves extends DrawCard {
setupCardAbilities() {
this.action({
title: 'Grant Covert to a character',
target: {
cardType: 'character',
cardCondition: card => card.location === 'play area'
},
handler: context => {
this.game.addMessage('{0} uses {1} to grant Covert during Water conflicts to {2}', this.controller, this, context.target);
this.untilEndOfPhase(ability => ({
match: context.target,
condition: () => this.game.currentConflict && this.game.currentConflict.conflictRing === 'water',
effect: ability.effects.addKeyword('covert')
}));
}
});
}
}
AdeptOfTheWaves.id = 'adept-of-the-waves';
module.exports = AdeptOfTheWaves;
| Fix typo on Adept of the Waves | Fix typo on Adept of the Waves
| JavaScript | mit | jeremylarner/ringteki,gryffon/ringteki,gryffon/ringteki,jeremylarner/ringteki,jeremylarner/ringteki,gryffon/ringteki | ---
+++
@@ -9,7 +9,7 @@
cardCondition: card => card.location === 'play area'
},
handler: context => {
- this.game.addMessage('{0} uses {1} to grant Covet during Water conflicts to {2}', this.controller, this, context.target);
+ this.game.addMessage('{0} uses {1} to grant Covert during Water conflicts to {2}', this.controller, this, context.target);
this.untilEndOfPhase(ability => ({
match: context.target,
condition: () => this.game.currentConflict && this.game.currentConflict.conflictRing === 'water', |
f25e3d3b233d81a65604266722378be813affd29 | src/app/includes/js/geolocation/geolocation.js | src/app/includes/js/geolocation/geolocation.js | (function($) {
$.fn.geoLocation = function(callback) {
if (callback && typeof(callback) === 'function') {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0 //Always request the current location
};
function success(position) {
callback({
success: true,
position: position.coords
})
}
function error(err) {
callback({
success: false,
error: err
})
};
if ('geolocation' in navigator) { //Verify basic support
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
error({code: 999, message: 'Geopositioning is not supported by the current device'})
}
} else {
console.log('No callback function provided')
}
}
}(jQuery)); | (function($) {
$.fn.geoLocation = function(callback, data) {
if (callback && typeof(callback) === 'function') {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0 //Always request the current location
}
function success(position) {
callback({
success: true,
position: position.coords
}, data)
}
function error(err) {
callback({
success: false,
error: err
}, data)
}
if ('geolocation' in navigator) { //Verify basic support
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
error({
success: false,
error: 'Geopositioning is not supported by the current device'
}, data)
}
} else {
console.log('No callback function provided')
}
}
}(jQuery)); | Add option to pass data back to callback | Add option to pass data back to callback
| JavaScript | unlicense | Vegosvar/Vegosvar,Vegosvar/Vegosvar,Vegosvar/Vegosvar | ---
+++
@@ -1,33 +1,36 @@
(function($) {
- $.fn.geoLocation = function(callback) {
- if (callback && typeof(callback) === 'function') {
- var options = {
- enableHighAccuracy: true,
- timeout: 5000,
- maximumAge: 0 //Always request the current location
- };
+ $.fn.geoLocation = function(callback, data) {
+ if (callback && typeof(callback) === 'function') {
+ var options = {
+ enableHighAccuracy: true,
+ timeout: 5000,
+ maximumAge: 0 //Always request the current location
+ }
- function success(position) {
- callback({
- success: true,
- position: position.coords
- })
- }
+ function success(position) {
+ callback({
+ success: true,
+ position: position.coords
+ }, data)
+ }
- function error(err) {
- callback({
- success: false,
- error: err
- })
- };
+ function error(err) {
+ callback({
+ success: false,
+ error: err
+ }, data)
+ }
- if ('geolocation' in navigator) { //Verify basic support
- navigator.geolocation.getCurrentPosition(success, error, options);
- } else {
- error({code: 999, message: 'Geopositioning is not supported by the current device'})
- }
- } else {
- console.log('No callback function provided')
- }
+ if ('geolocation' in navigator) { //Verify basic support
+ navigator.geolocation.getCurrentPosition(success, error, options);
+ } else {
+ error({
+ success: false,
+ error: 'Geopositioning is not supported by the current device'
+ }, data)
+ }
+ } else {
+ console.log('No callback function provided')
}
+ }
}(jQuery)); |
478adc6cddce5001819006a2628aba7033da7990 | modules/map/services/measure/measure.factory.js | modules/map/services/measure/measure.factory.js | (function () {
'use strict';
angular
.module('dpMap')
.factory('measure', measureFactory);
measureFactory.$inject = ['$document', 'L', 'MEASURE_CONFIG'];
function measureFactory ($document, L, MEASURE_CONFIG) {
return {
initialize: initialize
};
function initialize (leafletMap) {
var measureControl = new L.Control.Measure(MEASURE_CONFIG),
leafletMeasureHtml;
measureControl.addTo(leafletMap);
leafletMeasureHtml = measureControl.getContainer();
//Add a class to leaflet-measure control
leafletMeasureHtml.className += ' s-leaflet-measure';
$document[0].querySelector('.js-leaflet-measure').appendChild(leafletMeasureHtml);
}
}
})(); | (function () {
'use strict';
angular
.module('dpMap')
.factory('measure', measureFactory);
measureFactory.$inject = ['$document', '$rootScope', 'L', 'MEASURE_CONFIG', 'store', 'ACTIONS'];
function measureFactory ($document, $rootScope, L, MEASURE_CONFIG, store, ACTIONS) {
return {
initialize: initialize
};
function initialize (leafletMap) {
var measureControl = new L.Control.Measure(MEASURE_CONFIG),
leafletMeasureHtml;
measureControl.addTo(leafletMap);
leafletMeasureHtml = measureControl.getContainer();
leafletMeasureHtml.className += ' s-leaflet-measure';
$document[0].querySelector('.js-leaflet-measure').appendChild(leafletMeasureHtml);
leafletMap.on('measurestart', function () {
$rootScope.$applyAsync(function () {
store.dispatch({
type: ACTIONS.HIDE_ACTIVE_OVERLAYS
});
});
});
}
}
})(); | Hide the active overlays on 'measurestart'. | Hide the active overlays on 'measurestart'.
| JavaScript | mpl-2.0 | DatapuntAmsterdam/atlas,Amsterdam/atlas,DatapuntAmsterdam/atlas,DatapuntAmsterdam/atlas,DatapuntAmsterdam/atlas_prototype,Amsterdam/atlas,Amsterdam/atlas,Amsterdam/atlas,DatapuntAmsterdam/atlas_prototype | ---
+++
@@ -5,9 +5,9 @@
.module('dpMap')
.factory('measure', measureFactory);
- measureFactory.$inject = ['$document', 'L', 'MEASURE_CONFIG'];
+ measureFactory.$inject = ['$document', '$rootScope', 'L', 'MEASURE_CONFIG', 'store', 'ACTIONS'];
- function measureFactory ($document, L, MEASURE_CONFIG) {
+ function measureFactory ($document, $rootScope, L, MEASURE_CONFIG, store, ACTIONS) {
return {
initialize: initialize
};
@@ -19,11 +19,16 @@
measureControl.addTo(leafletMap);
leafletMeasureHtml = measureControl.getContainer();
+ leafletMeasureHtml.className += ' s-leaflet-measure';
+ $document[0].querySelector('.js-leaflet-measure').appendChild(leafletMeasureHtml);
- //Add a class to leaflet-measure control
- leafletMeasureHtml.className += ' s-leaflet-measure';
-
- $document[0].querySelector('.js-leaflet-measure').appendChild(leafletMeasureHtml);
+ leafletMap.on('measurestart', function () {
+ $rootScope.$applyAsync(function () {
+ store.dispatch({
+ type: ACTIONS.HIDE_ACTIVE_OVERLAYS
+ });
+ });
+ });
}
}
})(); |
9dc3dc91ee48137f7f72cae93fd770ba2b12ac33 | website/static/js/pages/home-page.js | website/static/js/pages/home-page.js | /**
* Initialization code for the home page.
*/
'use strict';
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var quickSearchProject = require('js/quickProjectSearchPlugin');
var newAndNoteworthy = require('js/newAndNoteworthyPlugin');
var meetingsAndConferences = require('js/meetingsAndConferencesPlugin');
var m = require('mithril');
$(document).ready(function(){
m.mount(document.getElementById('addQuickProjectSearchWrap'), m.component(quickSearchProject, {}));
m.mount(document.getElementById('newAndNoteworthyWrap'), m.component(newAndNoteworthy, {}));
m.mount(document.getElementById('hostingAMeetingWrap'), m.component(meetingsAndConferences, {}));
}); | /**
* Initialization code for the home page.
*/
'use strict';
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var quickSearchProject = require('js/quickProjectSearchPlugin');
var newAndNoteworthy = require('js/newAndNoteworthyPlugin');
var meetingsAndConferences = require('js/meetingsAndConferencesPlugin');
var m = require('mithril');
$(document).ready(function(){
m.mount(document.getElementById('newAndNoteworthyWrap'), m.component(newAndNoteworthy, {}));
m.mount(document.getElementById('hostingAMeetingWrap'), m.component(meetingsAndConferences, {}));
m.mount(document.getElementById('addQuickProjectSearchWrap'), m.component(quickSearchProject, {}));
}); | Reorder mounted elements. QuickSearch needs to load last. | Reorder mounted elements. QuickSearch needs to load last.
| JavaScript | apache-2.0 | abought/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,zamattiac/osf.io,caneruguz/osf.io,binoculars/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,TomHeatwole/osf.io,mattclark/osf.io,mfraezz/osf.io,aaxelb/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,binoculars/osf.io,cslzchen/osf.io,caneruguz/osf.io,cslzchen/osf.io,mfraezz/osf.io,erinspace/osf.io,saradbowman/osf.io,sloria/osf.io,alexschiller/osf.io,binoculars/osf.io,hmoco/osf.io,samchrisinger/osf.io,cwisecarver/osf.io,kwierman/osf.io,leb2dg/osf.io,jnayak1/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,zachjanicki/osf.io,zachjanicki/osf.io,pattisdr/osf.io,asanfilippo7/osf.io,adlius/osf.io,mattclark/osf.io,adlius/osf.io,mluke93/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,crcresearch/osf.io,SSJohns/osf.io,Johnetordoff/osf.io,RomanZWang/osf.io,chennan47/osf.io,mluke93/osf.io,asanfilippo7/osf.io,doublebits/osf.io,zamattiac/osf.io,RomanZWang/osf.io,monikagrabowska/osf.io,hmoco/osf.io,amyshi188/osf.io,TomHeatwole/osf.io,rdhyee/osf.io,amyshi188/osf.io,acshi/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,chrisseto/osf.io,jnayak1/osf.io,kwierman/osf.io,icereval/osf.io,zachjanicki/osf.io,kch8qx/osf.io,alexschiller/osf.io,sloria/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,felliott/osf.io,adlius/osf.io,laurenrevere/osf.io,kch8qx/osf.io,adlius/osf.io,baylee-d/osf.io,emetsger/osf.io,rdhyee/osf.io,jnayak1/osf.io,cslzchen/osf.io,alexschiller/osf.io,mluke93/osf.io,mluo613/osf.io,crcresearch/osf.io,cslzchen/osf.io,kch8qx/osf.io,felliott/osf.io,leb2dg/osf.io,acshi/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,jnayak1/osf.io,zachjanicki/osf.io,kwierman/osf.io,monikagrabowska/osf.io,emetsger/osf.io,Johnetordoff/osf.io,erinspace/osf.io,DanielSBrown/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,caneruguz/osf.io,Nesiehr/osf.io,doublebits/osf.io,emetsger/osf.io,zamattiac/osf.io,mluo613/osf.io,mattclark/osf.io,wearpants/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,chennan47/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,rdhyee/osf.io,saradbowman/osf.io,abought/osf.io,doublebits/osf.io,chrisseto/osf.io,kch8qx/osf.io,baylee-d/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,mluo613/osf.io,kch8qx/osf.io,caseyrollins/osf.io,SSJohns/osf.io,wearpants/osf.io,cwisecarver/osf.io,erinspace/osf.io,SSJohns/osf.io,amyshi188/osf.io,pattisdr/osf.io,hmoco/osf.io,aaxelb/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,doublebits/osf.io,icereval/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,laurenrevere/osf.io,sloria/osf.io,acshi/osf.io,DanielSBrown/osf.io,mluo613/osf.io,baylee-d/osf.io,leb2dg/osf.io,rdhyee/osf.io,leb2dg/osf.io,alexschiller/osf.io,felliott/osf.io,asanfilippo7/osf.io,felliott/osf.io,samchrisinger/osf.io,samchrisinger/osf.io,SSJohns/osf.io,emetsger/osf.io,asanfilippo7/osf.io,acshi/osf.io,kwierman/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,chrisseto/osf.io,abought/osf.io,pattisdr/osf.io,abought/osf.io,mluke93/osf.io,acshi/osf.io,doublebits/osf.io,wearpants/osf.io,icereval/osf.io,alexschiller/osf.io,amyshi188/osf.io,caseyrollins/osf.io,crcresearch/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,wearpants/osf.io,Nesiehr/osf.io | ---
+++
@@ -12,7 +12,8 @@
var m = require('mithril');
$(document).ready(function(){
- m.mount(document.getElementById('addQuickProjectSearchWrap'), m.component(quickSearchProject, {}));
m.mount(document.getElementById('newAndNoteworthyWrap'), m.component(newAndNoteworthy, {}));
m.mount(document.getElementById('hostingAMeetingWrap'), m.component(meetingsAndConferences, {}));
+ m.mount(document.getElementById('addQuickProjectSearchWrap'), m.component(quickSearchProject, {}));
+
}); |
e0eec4f09fd0bf6eb73f8ba2803ef25c5f61e007 | src/clients/appinsights/AppInsightsClient.js | src/clients/appinsights/AppInsightsClient.js | const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;
let client;
function setup() {
if (appInsightsKey) {
const appInsights = require('applicationinsights');
appInsights.setup(appInsightsKey);
appInsights.start();
client = appInsights.getClient(appInsightsKey);
}
}
function trackDependency(promiseFunc, dependencyName, callName) {
if (!client) {
console.log('Application insights not enabled');
return promiseFunc;
}
function dependencyTracker(...args) {
return new Promise((resolve, reject) => {
const start = new Date();
promiseFunc(...args)
.then(returnValue => {
const duration = new Date() - start;
const success = true;
client.trackDependency(dependencyName, callName, duration, success);
resolve(returnValue);
})
.catch(err => {
const duration = new Date() - start;
const success = false;
client.trackDependency(dependencyName, callName, duration, success);
reject(err);
});
});
}
return dependencyTracker;
}
module.exports = {
trackDependency: trackDependency,
setup: setup
};
| const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;
let client;
let consoleLog = console.log;
let consoleError = console.error;
let consoleWarn = console.warn;
function setup() {
if (appInsightsKey) {
const appInsights = require('applicationinsights');
appInsights.setup(appInsightsKey);
appInsights.start();
client = appInsights.getClient(appInsightsKey);
console.log = trackTrace(/* INFO */ 1, consoleLog);
console.error = trackTrace(/* ERROR */ 3, consoleError);
console.warn = trackTrace(/* WARNING */ 2, consoleWarn);
}
}
function trackTrace(level, localLogger) {
return (message) => {
if (client) {
client.trackTrace(message, level);
}
localLogger(message);
};
}
function trackDependency(promiseFunc, dependencyName, callName) {
if (!client) return promiseFunc;
function dependencyTracker(...args) {
return new Promise((resolve, reject) => {
const start = new Date();
promiseFunc(...args)
.then(returnValue => {
const duration = new Date() - start;
const success = true;
client.trackDependency(dependencyName, callName, duration, success);
resolve(returnValue);
})
.catch(err => {
const duration = new Date() - start;
const success = false;
client.trackDependency(dependencyName, callName, duration, success);
reject(err);
});
});
}
return dependencyTracker;
}
module.exports = {
trackDependency: trackDependency,
setup: setup
};
| Send all console calls to app insights as traces | Send all console calls to app insights as traces
| JavaScript | mit | CatalystCode/project-fortis-services,CatalystCode/project-fortis-services | ---
+++
@@ -1,6 +1,9 @@
const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;
let client;
+let consoleLog = console.log;
+let consoleError = console.error;
+let consoleWarn = console.warn;
function setup() {
if (appInsightsKey) {
@@ -8,14 +11,23 @@
appInsights.setup(appInsightsKey);
appInsights.start();
client = appInsights.getClient(appInsightsKey);
+ console.log = trackTrace(/* INFO */ 1, consoleLog);
+ console.error = trackTrace(/* ERROR */ 3, consoleError);
+ console.warn = trackTrace(/* WARNING */ 2, consoleWarn);
}
}
+function trackTrace(level, localLogger) {
+ return (message) => {
+ if (client) {
+ client.trackTrace(message, level);
+ }
+ localLogger(message);
+ };
+}
+
function trackDependency(promiseFunc, dependencyName, callName) {
- if (!client) {
- console.log('Application insights not enabled');
- return promiseFunc;
- }
+ if (!client) return promiseFunc;
function dependencyTracker(...args) {
return new Promise((resolve, reject) => { |
51f6d5ff9122f6752fae62f1d2a070b837920178 | app/src/controllers/plugins/uiExtensions/selectors.js | app/src/controllers/plugins/uiExtensions/selectors.js | import { createSelector } from 'reselect';
import { enabledPluginNamesSelector } from '../selectors';
import { EXTENSION_TYPE_SETTINGS_TAB } from './constants';
import { uiExtensionMap } from './uiExtensionStorage';
export const createUiExtensionSelectorByType = (type) =>
createSelector(enabledPluginNamesSelector, (pluginNames) =>
Array.from(uiExtensionMap.entries())
.filter(([name]) => pluginNames.includes(name))
.map(([, extensions]) => extensions)
.reduce((acc, val) => acc.concat(val), [])
.filter((extension) => extension.type === type),
);
export const uiExtensionSettingsTabsSelector = createUiExtensionSelectorByType(
EXTENSION_TYPE_SETTINGS_TAB,
);
| import { createSelector } from 'reselect';
import { EXTENSION_TYPE_SETTINGS_TAB } from './constants';
import { enabledPluginNamesSelector } from '../selectors';
import { uiExtensionMap } from './uiExtensionStorage';
export const createUiExtensionSelectorByType = (type) =>
createSelector(enabledPluginNamesSelector, (pluginNames) =>
Array.from(uiExtensionMap.entries())
.filter(([name]) => pluginNames.includes(name))
.map(([, extensions]) => extensions)
.reduce((acc, val) => acc.concat(val), [])
.filter((extension) => extension.type === type),
);
export const uiExtensionSettingsTabsSelector = createUiExtensionSelectorByType(
EXTENSION_TYPE_SETTINGS_TAB,
);
| Allow plugins to add own tabs to project settings | EPMRPP-47707: Allow plugins to add own tabs to project settings
| JavaScript | apache-2.0 | reportportal/service-ui,reportportal/service-ui,reportportal/service-ui | ---
+++
@@ -1,6 +1,6 @@
import { createSelector } from 'reselect';
+import { EXTENSION_TYPE_SETTINGS_TAB } from './constants';
import { enabledPluginNamesSelector } from '../selectors';
-import { EXTENSION_TYPE_SETTINGS_TAB } from './constants';
import { uiExtensionMap } from './uiExtensionStorage';
export const createUiExtensionSelectorByType = (type) => |
717199f14ccbd4bedf15568e935c4d9c7da2e5df | src/mui/layout/Notification.js | src/mui/layout/Notification.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { hideNotification as hideNotificationAction } from '../../actions/notificationActions' ;
class Notification extends React.Component {
handleRequestClose = () => {
this.props.hideNotification();
};
render() {
const style = {};
if (this.props.type === 'warning') {
style.backgroundColor = '#ff4081';
}
if (this.props.type === 'confirm') {
style.backgroundColor = '#00bcd4';
}
return (<Snackbar
open={!!this.props.message}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.handleRequestClose}
bodyStyle={style}
/>);
}
}
Notification.propTypes = {
message: PropTypes.string,
type: PropTypes.string.isRequired,
hideNotification: PropTypes.func.isRequired,
};
Notification.defaultProps = {
type: 'info',
};
const mapStateToProps = (state) => ({
message: state.admin.notification.text,
type: state.admin.notification.type,
});
export default connect(
mapStateToProps,
{ hideNotification: hideNotificationAction },
)(Notification);
| import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { hideNotification as hideNotificationAction } from '../../actions/notificationActions' ;
function getStyles(context) {
if (!context) return { primary1Color: '#00bcd4', accent1Color: '#ff4081' };
const {
muiTheme: {
baseTheme: {
palette: {
primary1Color,
accent1Color,
},
},
},
} = context;
return { primary1Color, accent1Color };
}
class Notification extends React.Component {
handleRequestClose = () => {
this.props.hideNotification();
};
render() {
const style = {};
const { primary1Color, accent1Color } = getStyles(this.context);
if (this.props.type === 'warning') {
style.backgroundColor = accent1Color;
}
if (this.props.type === 'confirm') {
style.backgroundColor = primary1Color;
}
return (<Snackbar
open={!!this.props.message}
message={this.props.message}
autoHideDuration={4000}
onRequestClose={this.handleRequestClose}
bodyStyle={style}
/>);
}
}
Notification.propTypes = {
message: PropTypes.string,
type: PropTypes.string.isRequired,
hideNotification: PropTypes.func.isRequired,
};
Notification.defaultProps = {
type: 'info',
};
Notification.contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
message: state.admin.notification.text,
type: state.admin.notification.type,
});
export default connect(
mapStateToProps,
{ hideNotification: hideNotificationAction },
)(Notification);
| Use theme colors in notifications | Use theme colors in notifications
Closes #177
| JavaScript | mit | marmelab/admin-on-rest,matteolc/admin-on-rest,marmelab/admin-on-rest,matteolc/admin-on-rest | ---
+++
@@ -2,6 +2,21 @@
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { hideNotification as hideNotificationAction } from '../../actions/notificationActions' ;
+
+function getStyles(context) {
+ if (!context) return { primary1Color: '#00bcd4', accent1Color: '#ff4081' };
+ const {
+ muiTheme: {
+ baseTheme: {
+ palette: {
+ primary1Color,
+ accent1Color,
+ },
+ },
+ },
+ } = context;
+ return { primary1Color, accent1Color };
+}
class Notification extends React.Component {
handleRequestClose = () => {
@@ -10,11 +25,12 @@
render() {
const style = {};
+ const { primary1Color, accent1Color } = getStyles(this.context);
if (this.props.type === 'warning') {
- style.backgroundColor = '#ff4081';
+ style.backgroundColor = accent1Color;
}
if (this.props.type === 'confirm') {
- style.backgroundColor = '#00bcd4';
+ style.backgroundColor = primary1Color;
}
return (<Snackbar
open={!!this.props.message}
@@ -36,6 +52,10 @@
type: 'info',
};
+Notification.contextTypes = {
+ muiTheme: PropTypes.object.isRequired,
+};
+
const mapStateToProps = (state) => ({
message: state.admin.notification.text,
type: state.admin.notification.type, |
42cca2bd3411e45f38c0419faed5ccd9e5b01dcf | src/release/make-bower.json.js | src/release/make-bower.json.js | #!/usr/bin/env node
// Renders the bower.json template and prints it to stdout
var template = {
name: "graphlib",
version: require("../../package.json").version,
main: [ "dist/graphlib.core.js", "dist/graphlib.core.min.js" ],
ignore: [
".*",
"README.md",
"CHANGELOG.md",
"Makefile",
"browser.js",
"dist/graphlib.js",
"dist/graphlib.min.js",
"index.js",
"karma*",
"lib/**",
"package.json",
"src/**",
"test/**"
],
dependencies: {
"lodash": "^2.4.1"
}
};
console.log(JSON.stringify(template, null, 2));
| #!/usr/bin/env node
// Renders the bower.json template and prints it to stdout
var packageJson = require("../../package.json");
var template = {
name: packageJson.name,
version: packageJson.version,
main: ["dist/" + packageJson.name + ".core.js", "dist/" + packageJson.name + ".core.min.js"],
ignore: [
".*",
"README.md",
"CHANGELOG.md",
"Makefile",
"browser.js",
"dist/" + packageJson.name + ".js",
"dist/" + packageJson.name + ".min.js",
"index.js",
"karma*",
"lib/**",
"package.json",
"src/**",
"test/**"
],
dependencies: packageJson.dependencies
};
console.log(JSON.stringify(template, null, 2));
| Check in improved bower generation script | Check in improved bower generation script
| JavaScript | mit | cpettitt/graphlib,dagrejs/graphlib,dagrejs/graphlib,kdawes/graphlib,cpettitt/graphlib,kdawes/graphlib,dagrejs/graphlib,gardner/graphlib,gardner/graphlib,leMaik/graphlib,leMaik/graphlib | ---
+++
@@ -2,18 +2,20 @@
// Renders the bower.json template and prints it to stdout
+var packageJson = require("../../package.json");
+
var template = {
- name: "graphlib",
- version: require("../../package.json").version,
- main: [ "dist/graphlib.core.js", "dist/graphlib.core.min.js" ],
+ name: packageJson.name,
+ version: packageJson.version,
+ main: ["dist/" + packageJson.name + ".core.js", "dist/" + packageJson.name + ".core.min.js"],
ignore: [
".*",
"README.md",
"CHANGELOG.md",
"Makefile",
"browser.js",
- "dist/graphlib.js",
- "dist/graphlib.min.js",
+ "dist/" + packageJson.name + ".js",
+ "dist/" + packageJson.name + ".min.js",
"index.js",
"karma*",
"lib/**",
@@ -21,9 +23,7 @@
"src/**",
"test/**"
],
- dependencies: {
- "lodash": "^2.4.1"
- }
+ dependencies: packageJson.dependencies
};
console.log(JSON.stringify(template, null, 2)); |
05aa4e055ff496566b5ea8301851bfb312a5aea9 | src/prepare.js | src/prepare.js | /**
* Prepare request configuration, deeply merging some specific keys
*/
var assign = require('./assign')
var toArray = require('./toArray')
var DEFAULTS = {
baseURL : '/',
basePath : '',
body : undefined,
params : undefined,
headers : {
'Accept': 'application/json'
},
method : 'GET',
path : '',
query : {},
timeout : 15000,
type : 'application/json',
buildQuery : function(query) { return query },
beforeSend : function(ajax) { return ajax },
onResponse : function(response) { return response.body },
onError : function(error) { return error },
Promise : global.Promise
}
module.exports = function prepare (/* options list */) {
var options = [ DEFAULTS ].concat(toArray(arguments))
return options.reduce(function (memo, next) {
return next ? assign(memo, next, {
body : next.body ? assign(memo.body, next.body) : next.body,
params : assign(memo.params, next.params),
query : assign(memo.query, next.query),
headers : assign(memo.headers, next.headers)
}) : memo
}, {})
}
| /**
* Prepare request configuration, deeply merging some specific keys
*/
var assign = require('./assign')
var toArray = require('./toArray')
var DEFAULTS = {
baseURL : '/',
basePath : '',
params : undefined,
headers : {
'Accept': 'application/json'
},
method : 'GET',
path : '',
query : {},
timeout : 15000,
type : 'application/json',
buildQuery : function(query) { return query },
beforeSend : function(ajax) { return ajax },
onResponse : function(response) { return response.body },
onError : function(error) { return error },
Promise : global.Promise
}
module.exports = function prepare (/* options list */) {
var options = [ DEFAULTS ].concat(toArray(arguments))
return options.reduce(function (memo, next) {
return next ? assign(memo, next, {
params : assign(memo.params, next.params),
query : assign(memo.query, next.query),
headers : assign(memo.headers, next.headers)
}) : memo
}, {})
}
| Remove body from configuration options | Remove body from configuration options
Merging `body` with defaults was problematic since `body`
is not always an object. For example, it might be `FormData`.
| JavaScript | mit | vigetlabs/gangway | ---
+++
@@ -8,7 +8,6 @@
var DEFAULTS = {
baseURL : '/',
basePath : '',
- body : undefined,
params : undefined,
headers : {
'Accept': 'application/json'
@@ -31,7 +30,6 @@
return options.reduce(function (memo, next) {
return next ? assign(memo, next, {
- body : next.body ? assign(memo.body, next.body) : next.body,
params : assign(memo.params, next.params),
query : assign(memo.query, next.query),
headers : assign(memo.headers, next.headers) |
b678b02650046b6fbd8a74485158bec0e43ca851 | src/sandbox.js | src/sandbox.js | /* eslint-env mocha */
import Chai from 'chai';
import ChaiString from 'chai-string';
import Sinon from 'sinon';
import SinonChai from 'sinon-chai';
Chai.use(ChaiString);
Chai.use(SinonChai);
beforeEach(function() {
this.sandbox = Sinon.sandbox.create({
injectInto: this,
properties: ['spy', 'stub', 'mock'],
useFakeTimers: false,
useFakeServer: false
});
});
afterEach(function() {
this.sandbox.restore();
});
| /* eslint-env mocha */
import Chai from 'chai';
import ChaiString from 'chai-string';
import Sinon from 'sinon';
import SinonChai from 'sinon-chai';
Chai.use(ChaiString);
Chai.use(SinonChai);
beforeEach(function() {
this.sandbox = Sinon.sandbox.create({
injectInto: this,
properties: ['spy', 'stub', 'mock'],
useFakeTimers: false,
useFakeServer: false
});
});
afterEach(function() {
this.sandbox.restore();
});
process.on('unhandledRejection', (err) => {
throw err;
});
| Throw unhandled rejections in mocha tests | Throw unhandled rejections in mocha tests
Only works under >= 3.x, but will still help us potentially catch issues in test. | JavaScript | mit | kpdecker/linoleum-node,kpdecker/linoleum-electron,kpdecker/linoleum,kpdecker/linoleum-webpack,kpdecker/linoleum-electron | ---
+++
@@ -19,3 +19,6 @@
this.sandbox.restore();
});
+process.on('unhandledRejection', (err) => {
+ throw err;
+}); |
0014d16e589aecb8cbaeb5832fa73bc70cf86485 | lib/control/v1/index.js | lib/control/v1/index.js | 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
const rp = require('request-promise');
// Hit the Vault health check endpoint to see if we're actually working with a Vault server
/**
* Checks whether there is an actual Vault server running at the Vault endpoint
*
* @returns {Promise}
*/
const checkVault = function() {
const VAULT_ENDPOINT = Config.get('vault:endpoint');
return rp({uri: `${VAULT_ENDPOINT}/sys/health`, json: true})
.then(() => true)
.catch(() => false);
};
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
const KMS = new AWS.KMS({region: Config.get('aws:region')});
if (Config.get('aws:key')) {
return res.render('index', {title: 'ACS'});
}
return new Promise((resolve, reject) => {
KMS.listAliases({}, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
}).then((keys) => {
res.render('index', {title: 'ACS', kms: keys.Aliases});
}).catch((err) => {
next(err);
});
});
app.post('/v1/vault', upload.none(), require('./vault')());
app.post('/v1/kms', upload.none(), require('./kms')());
app.use(Err);
};
| 'use strict';
const AWS = require('aws-sdk');
const Err = require('./error');
const upload = require('multer')();
const rp = require('request-promise');
// Hit the Vault health check endpoint to see if we're actually working with a Vault server
/**
* Checks whether there is an actual Vault server running at the Vault endpoint
*
* @returns {Promise}
*/
const checkVault = function() {
const VAULT_ENDPOINT = Config.get('vault:endpoint');
return rp({uri: `${VAULT_ENDPOINT}/sys/health`, json: true})
.then(() => true)
.catch(() => false);
};
/**
* Gets a list of KMS keys and their aliases
*
* @returns {Promise}
*/
const getKmsKeys = function() {
const KMS = new AWS.KMS({region: Config.get('aws:region')});
if (Config.get('aws:key')) {
return Promise.resolve([]);
}
return new Promise((resolve, reject) => {
KMS.listAliases({}, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
};
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
}).catch((err) => {
next(err);
});
});
app.post('/v1/vault', upload.none(), require('./vault')());
app.post('/v1/kms', upload.none(), require('./kms')());
app.use(Err);
};
| Move KMS key retrieval to its own function. | Move KMS key retrieval to its own function.
| JavaScript | mit | rapid7/acs,rapid7/acs,rapid7/acs | ---
+++
@@ -21,25 +21,32 @@
.catch(() => false);
};
+/**
+ * Gets a list of KMS keys and their aliases
+ *
+ * @returns {Promise}
+ */
+const getKmsKeys = function() {
+ const KMS = new AWS.KMS({region: Config.get('aws:region')});
+
+ if (Config.get('aws:key')) {
+ return Promise.resolve([]);
+ }
+
+ return new Promise((resolve, reject) => {
+ KMS.listAliases({}, (err, data) => {
+ if (err) {
+ reject(err);
+ }
+
+ resolve(data);
+ });
+ });
+};
module.exports = function Index(app) {
app.get('/', function(req, res, next) {
- const KMS = new AWS.KMS({region: Config.get('aws:region')});
- if (Config.get('aws:key')) {
- return res.render('index', {title: 'ACS'});
- }
-
- return new Promise((resolve, reject) => {
- KMS.listAliases({}, (err, data) => {
- if (err) {
- reject(err);
- }
-
- resolve(data);
- });
- }).then((keys) => {
- res.render('index', {title: 'ACS', kms: keys.Aliases});
}).catch((err) => {
next(err);
}); |
4a9ddc5c33572606b1ddc48bceabc5310069db84 | src/api-gateway-websocket/WebSocketServer.js | src/api-gateway-websocket/WebSocketServer.js | import { Server } from 'ws'
import debugLog from '../debugLog.js'
import LambdaFunctionPool from '../lambda/index.js'
import serverlessLog from '../serverlessLog.js'
import { createUniqueId } from '../utils/index.js'
export default class WebSocketServer {
constructor(options, webSocketClients, sharedServer) {
this._lambdaFunctionPool = new LambdaFunctionPool()
this._options = options
this._server = new Server({
server: sharedServer,
})
this._webSocketClients = webSocketClients
this._init()
}
_init() {
this._server.on('connection', (webSocketClient /* request */) => {
console.log('received connection')
const connectionId = createUniqueId()
debugLog(`connect:${connectionId}`)
this._webSocketClients.addClient(webSocketClient, connectionId)
})
}
addRoute(functionName, functionObj, route) {
this._webSocketClients.addRoute(functionName, functionObj, route)
// serverlessLog(`route '${route}'`)
}
async start() {
const { host, httpsProtocol, websocketPort } = this._options
serverlessLog(
`Offline [websocket] listening on ws${
httpsProtocol ? 's' : ''
}://${host}:${websocketPort}`,
)
}
// no-op, we're re-using the http server
stop() {}
}
| import { Server } from 'ws'
import debugLog from '../debugLog.js'
import serverlessLog from '../serverlessLog.js'
import { createUniqueId } from '../utils/index.js'
export default class WebSocketServer {
constructor(options, webSocketClients, sharedServer) {
this._options = options
this._server = new Server({
server: sharedServer,
})
this._webSocketClients = webSocketClients
this._init()
}
_init() {
this._server.on('connection', (webSocketClient /* request */) => {
console.log('received connection')
const connectionId = createUniqueId()
debugLog(`connect:${connectionId}`)
this._webSocketClients.addClient(webSocketClient, connectionId)
})
}
addRoute(functionName, functionObj, route) {
this._webSocketClients.addRoute(functionName, functionObj, route)
// serverlessLog(`route '${route}'`)
}
async start() {
const { host, httpsProtocol, websocketPort } = this._options
serverlessLog(
`Offline [websocket] listening on ws${
httpsProtocol ? 's' : ''
}://${host}:${websocketPort}`,
)
}
// no-op, we're re-using the http server
stop() {}
}
| Remove unused lambda function pool from websocket server | Remove unused lambda function pool from websocket server
| JavaScript | mit | dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline,dherault/serverless-offline | ---
+++
@@ -1,12 +1,10 @@
import { Server } from 'ws'
import debugLog from '../debugLog.js'
-import LambdaFunctionPool from '../lambda/index.js'
import serverlessLog from '../serverlessLog.js'
import { createUniqueId } from '../utils/index.js'
export default class WebSocketServer {
constructor(options, webSocketClients, sharedServer) {
- this._lambdaFunctionPool = new LambdaFunctionPool()
this._options = options
this._server = new Server({ |
96bc5c0b0bddf63d729116a55288621b00b1401c | test/helpers/fixtures/index.js | test/helpers/fixtures/index.js | var fixtures = require('node-require-directory')(__dirname);
exports.load = function *(specificFixtures) {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
try {
yield exports.unload();
var keys = Object.keys(fixtures).filter(function(key) {
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
});
for (var i = 0; i < keys.length; ++i) {
exports[keys[i]] = yield fixtures[keys[i]].load();
}
} catch (e) {
console.error(e);
}
};
exports.unload = function *() {
yield sequelize.sync({ force: true });
};
| var fixtures = require('node-require-directory')(__dirname);
exports.load = function *(specificFixtures) {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var prevSetting = sequelize.options.logging;
sequelize.options.logging = false;
try {
yield exports.unload();
var keys = Object.keys(fixtures).filter(function(key) {
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
});
for (var i = 0; i < keys.length; ++i) {
exports[keys[i]] = yield fixtures[keys[i]].load();
}
} catch (e) {
console.error(e);
}
sequelize.options.logging = prevSetting;
};
exports.unload = function *() {
var prevSetting = sequelize.options.logging;
sequelize.options.logging = false;
yield sequelize.sync({ force: true });
sequelize.options.logging = prevSetting;
};
| Disable logging sql when creating tables | Disable logging sql when creating tables
| JavaScript | mit | wikilab/wikilab-api | ---
+++
@@ -5,6 +5,8 @@
specificFixtures = [specificFixtures];
}
+ var prevSetting = sequelize.options.logging;
+ sequelize.options.logging = false;
try {
yield exports.unload();
@@ -20,8 +22,12 @@
} catch (e) {
console.error(e);
}
+ sequelize.options.logging = prevSetting;
};
exports.unload = function *() {
+ var prevSetting = sequelize.options.logging;
+ sequelize.options.logging = false;
yield sequelize.sync({ force: true });
+ sequelize.options.logging = prevSetting;
}; |
9a024fcf6cf762ae7a335daf642171a12f4e05f5 | src/state/markerReducer.js | src/state/markerReducer.js | import { Map } from 'immutable';
import {
SIZE_3,
BLACK
} from './markerConstants';
export const initialMarker = Map({
size: SIZE_3,
color: BLACK
});
import { CHANGE_COLOR, CHANGE_SIZE } from './../../src/client/app/toolbar/toolbarActions';
const markerReducer = (state = initialMarker, action) => {
switch (action.type) {
case CHANGE_COLOR:
return state.set('color', action.color);
case CHANGE_SIZE:
return state.set('size', action.size);
default:
return state;
}
};
export default markerReducer;
| import { Map } from 'immutable';
import {
BLACK,
SIZE_3,
DRAW
} from './markerConstants';
export const initialMarker = Map({
color: BLACK,
size: SIZE_3,
mode: DRAW
});
import {
CHANGE_COLOR,
CHANGE_SIZE,
CHANGE_MODE
} from './../../src/client/app/toolbar/toolbarActions';
const markerReducer = (state = initialMarker, action) => {
switch (action.type) {
case CHANGE_COLOR:
return state.set('color', action.color);
case CHANGE_SIZE:
return state.set('size', action.size);
case CHANGE_MODE:
return state.set('size', action.size);
default:
return state;
}
};
export default markerReducer;
| Add mode field to marker state, add reducer case for CHANGE_MODE | Add mode field to marker state, add reducer case for CHANGE_MODE
| JavaScript | bsd-3-clause | jackrzhang/boardsession,jackrzhang/boardsession | ---
+++
@@ -1,16 +1,22 @@
import { Map } from 'immutable';
import {
+ BLACK,
SIZE_3,
- BLACK
+ DRAW
} from './markerConstants';
export const initialMarker = Map({
+ color: BLACK,
size: SIZE_3,
- color: BLACK
+ mode: DRAW
});
-import { CHANGE_COLOR, CHANGE_SIZE } from './../../src/client/app/toolbar/toolbarActions';
+import {
+ CHANGE_COLOR,
+ CHANGE_SIZE,
+ CHANGE_MODE
+} from './../../src/client/app/toolbar/toolbarActions';
const markerReducer = (state = initialMarker, action) => {
switch (action.type) {
@@ -18,6 +24,8 @@
return state.set('color', action.color);
case CHANGE_SIZE:
return state.set('size', action.size);
+ case CHANGE_MODE:
+ return state.set('size', action.size);
default:
return state;
} |
96d5a31937f2cbcef7c62d5551a5c633743a677f | lib/elements/helpers.js | lib/elements/helpers.js | 'use babel'
/* @flow */
import type { Message } from '../types'
export function visitMessage(message: Message) {
const messageFile = message.version === 1 ? message.filePath : message.location.file
const messageRange = message.version === 1 ? message.range : message.location.position
atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() {
const textEditor = atom.workspace.getActiveTextEditor()
if (textEditor && textEditor.getPath() === messageFile) {
textEditor.setCursorBufferPosition(messageRange.start)
}
})
}
export function htmlToText(html: any) {
const element = document.createElement('div')
if (typeof html === 'string') {
element.innerHTML = html
} else {
element.appendChild(html.cloneNode(true))
}
/* eslint-disable no-irregular-whitespace */
// NOTE: Convert to regular whitespace
return element.textContent.replace(/ /g, ' ')
/* eslint-enable no-irregular-whitespace */
}
| 'use babel'
/* @flow */
import type { Message } from '../types'
const nbsp = String.fromCodePoint(160)
export function visitMessage(message: Message) {
const messageFile = message.version === 1 ? message.filePath : message.location.file
const messageRange = message.version === 1 ? message.range : message.location.position
atom.workspace.open(messageFile, { searchAllPanes: true }).then(function() {
const textEditor = atom.workspace.getActiveTextEditor()
if (textEditor && textEditor.getPath() === messageFile) {
textEditor.setCursorBufferPosition(messageRange.start)
}
})
}
export function htmlToText(html: any) {
const element = document.createElement('div')
if (typeof html === 'string') {
element.innerHTML = html
} else {
element.appendChild(html.cloneNode(true))
}
// NOTE: Convert to regular whitespace
return element.textContent.replace(new RegExp(nbsp, 'g'), ' ')
}
| Use a non-hacky way to replace nbsp | :art: Use a non-hacky way to replace nbsp
| JavaScript | mit | AtomLinter/linter-ui-default,steelbrain/linter-ui-default,steelbrain/linter-ui-default | ---
+++
@@ -3,6 +3,8 @@
/* @flow */
import type { Message } from '../types'
+
+const nbsp = String.fromCodePoint(160)
export function visitMessage(message: Message) {
const messageFile = message.version === 1 ? message.filePath : message.location.file
@@ -22,8 +24,6 @@
} else {
element.appendChild(html.cloneNode(true))
}
- /* eslint-disable no-irregular-whitespace */
// NOTE: Convert to regular whitespace
- return element.textContent.replace(/ /g, ' ')
- /* eslint-enable no-irregular-whitespace */
+ return element.textContent.replace(new RegExp(nbsp, 'g'), ' ')
} |
14c5bfeee4b331919ebf34379ebb52b834cc8f36 | lib/helpers/retrieve.js | lib/helpers/retrieve.js | 'use strict';
/**
* @file Retrieve files for the account
*/
/**
* Download all files from the specified Google Account.
*
* @param {String} refreshToken Refresh_token to identify the account
* @param {Date} since Retrieve contacts updated since this date
* @param {Function} cb Callback. First parameter is the error (if any), second an array of all the contacts.
*/
module.exports = function retrieveFiles(client, oauth2Client, options, changes, cb) {
client.drive.changes
.list(options)
.withAuthClient(oauth2Client)
.execute(function(err, res) {
if(err) {
return cb(err);
}
changes = changes.concat(res.items);
if(res.nextPageToken) {
options.pageToken = res.nextPageToken;
retrieveFiles(client, oauth2Client, options, changes, cb);
}
else {
cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : null, changes);
}
});
};
| 'use strict';
/**
* @file Retrieve files for the account
*/
/**
* Download all files from the specified Google Account.
*
* @param {String} refreshToken Refresh_token to identify the account
* @param {Date} since Retrieve contacts updated since this date
* @param {Function} cb Callback. First parameter is the error (if any), second an array of all the contacts.
*/
module.exports = function retrieveFiles(client, oauth2Client, options, changes, cb) {
client.drive.changes
.list(options)
.withAuthClient(oauth2Client)
.execute(function(err, res) {
if(err) {
return cb(err);
}
changes = changes.concat(res.items);
if(res.nextPageToken) {
options.pageToken = res.nextPageToken;
retrieveFiles(client, oauth2Client, options, changes, cb);
}
else {
cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : options.startChangeId, changes);
}
});
};
| Fix a little bug with cursor | Fix a little bug with cursor
| JavaScript | mit | AnyFetch/gdrive-provider.anyfetch.com | ---
+++
@@ -26,7 +26,7 @@
retrieveFiles(client, oauth2Client, options, changes, cb);
}
else {
- cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : null, changes);
+ cb(null, res.items.length > 0 ? res.items[res.items.length - 1].id : options.startChangeId, changes);
}
});
}; |
d73ee560d6acfb497ac6fbca433b574e86c0399a | core/src/utils/system.js | core/src/utils/system.js | import { zeroArray } from './arrays';
//=========================================================
// System utilities
//=========================================================
detectEndianness(); /* Extra call to disable inlining of this function by closure compiler.
The inlined value is incorrect. */
export const ENDIANNESS = detectEndianness();
export function detectEndianness() {
var buffer = new ArrayBuffer(4);
var u32 = new Uint32Array(buffer);
var u8 = new Uint8Array(buffer);
u32[0] = 0xFF;
return (u8[0] === 0xFF) ? 'LE' : 'BE';
}
export function newByteArray(size) {
return new Uint8ClampedArray(size);
}
export function newUintArray(size) {
// For some strange reason, Uint32Array is much slower
// than ordinary array in Chrome.
var data = new Array(size);
zeroArray(data);
return data;
}
| import { zeroArray } from './arrays';
//=========================================================
// System utilities
//=========================================================
detectEndianness(); /* Extra call to disable inlining of this function by closure compiler.
The inlined value is incorrect. */
export const ENDIANNESS = detectEndianness();
export function detectEndianness() {
var buffer = new ArrayBuffer(4);
var u32 = new Uint32Array(buffer);
var u8 = new Uint8Array(buffer);
u32[0] = 0xFF;
return (u8[0] === 0xFF) ? 'LE' : 'BE';
}
export function newByteArray(size) {
return new Uint8Array(size);
}
export function newUintArray(size) {
// For some strange reason, Uint32Array is much slower
// than ordinary array in Chrome.
var data = new Array(size);
zeroArray(data);
return data;
}
| Use Uint8Array instead of Uint8ClampedArray. | Use Uint8Array instead of Uint8ClampedArray.
| JavaScript | mit | jpikl/cfxnes,jpikl/cfxnes | ---
+++
@@ -18,7 +18,7 @@
}
export function newByteArray(size) {
- return new Uint8ClampedArray(size);
+ return new Uint8Array(size);
}
export function newUintArray(size) { |
df5d7d39519382440574e9f210895089e75b0d6a | src/elements/CustomHTMLAnchorElement-impl.js | src/elements/CustomHTMLAnchorElement-impl.js | import { setTheInput } from './URLUtils-impl.js';
import { setAll as setPrivateMethods } from './private-methods.js';
export default class CustomHTMLAnchorElementImpl {
createdCallback() {
doSetTheInput(this);
}
attributeChangedCallback(name) {
if (name === 'href') {
doSetTheInput(this);
}
}
get text() {
return this.textContent;
}
set text(v) {
this.textContent = v;
}
}
setPrivateMethods('CustomHTMLAnchorElement', {
// Required by URLUtils
getTheBase() {
return this.baseURI;
},
updateSteps(value) {
this.setAttribute('href', value);
}
});
function doSetTheInput(el) {
var urlInput = el.hasAttribute('href') ? el.getAttribute('href') : '';
setTheInput(el, urlInput);
}
| import { setTheInput } from './URLUtils-impl.js';
import { setAll as setPrivateMethods } from './private-methods.js';
export default class CustomHTMLAnchorElementImpl {
createdCallback() {
doSetTheInput(this);
addDefaultEventListener(this, 'click', () => window.location.href = this.href);
}
attributeChangedCallback(name) {
if (name === 'href') {
doSetTheInput(this);
}
}
get text() {
return this.textContent;
}
set text(v) {
this.textContent = v;
}
}
setPrivateMethods('CustomHTMLAnchorElement', {
// Required by URLUtils
getTheBase() {
return this.baseURI;
},
updateSteps(value) {
this.setAttribute('href', value);
}
});
function doSetTheInput(el) {
var urlInput = el.hasAttribute('href') ? el.getAttribute('href') : '';
setTheInput(el, urlInput);
}
// This might be more generally useful; if so factor it out into its own file.
function addDefaultEventListener(eventTarget, eventName, listener) {
eventTarget.addEventListener(eventName, e => {
setTimeout(() => {
if (!e.defaultPrevented) {
listener(e);
}
}, 0);
});
}
| Add behavior to navigate to the new URL! | Add behavior to navigate to the new URL!
| JavaScript | apache-2.0 | zenorocha/html-as-custom-elements,zenorocha/html-as-custom-elements,valmzetvn/html-as-custom-elements,domenic/html-as-custom-elements,valmzetvn/html-as-custom-elements,domenic/html-as-custom-elements,domenic/html-as-custom-elements,valmzetvn/html-as-custom-elements | ---
+++
@@ -4,6 +4,8 @@
export default class CustomHTMLAnchorElementImpl {
createdCallback() {
doSetTheInput(this);
+
+ addDefaultEventListener(this, 'click', () => window.location.href = this.href);
}
attributeChangedCallback(name) {
@@ -34,3 +36,14 @@
var urlInput = el.hasAttribute('href') ? el.getAttribute('href') : '';
setTheInput(el, urlInput);
}
+
+// This might be more generally useful; if so factor it out into its own file.
+function addDefaultEventListener(eventTarget, eventName, listener) {
+ eventTarget.addEventListener(eventName, e => {
+ setTimeout(() => {
+ if (!e.defaultPrevented) {
+ listener(e);
+ }
+ }, 0);
+ });
+} |
c04f1d42eee5fb1ad6aa397059a9a647a5da057b | tasks/index.js | tasks/index.js | import gulp from 'gulp'
import { fonts } from './fonts'
import { images } from './images'
import { scripts } from './webpack'
import { styles } from './styles'
export function watch() {
gulp.watch('./resources/assets/sass/**/*.scss', styles);
gulp.watch('./resources/js/**/*.js', scripts);
gulp.watch('./resources/js/**/*.vue', scripts);
};
export const dev = gulp.series(fonts, images, scripts, styles);
export default dev; | import gulp from 'gulp'
import { fonts } from './fonts'
import { images } from './images'
import { scripts } from './webpack'
import { styles } from './styles'
function watch_task() {
gulp.watch('./resources/assets/sass/**/*.scss', styles);
gulp.watch('./resources/js/**/*.js', scripts);
gulp.watch('./resources/js/**/*.vue', scripts);
};
export const dev = gulp.series(fonts, images, scripts, styles);
export const watch = gulp.series(dev, watch_task);
export default dev; | Make watch task compile everything first | Make watch task compile everything first
| JavaScript | mit | OParl/dev-website,OParl/dev-website,OParl/dev-website | ---
+++
@@ -5,12 +5,13 @@
import { scripts } from './webpack'
import { styles } from './styles'
-export function watch() {
+function watch_task() {
gulp.watch('./resources/assets/sass/**/*.scss', styles);
gulp.watch('./resources/js/**/*.js', scripts);
gulp.watch('./resources/js/**/*.vue', scripts);
};
export const dev = gulp.series(fonts, images, scripts, styles);
+export const watch = gulp.series(dev, watch_task);
export default dev; |
769f69a05366f37150e5b94240eb60586f162f19 | imports/api/database-controller/graduation-requirement/graduationRequirement.js | imports/api/database-controller/graduation-requirement/graduationRequirement.js | import { mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
class GraduationRequirementCollection extends Mongo.Collection {}
const GraduationRequirements = new GraduationRequirementCollection('gradiationRequirement');
const gradRequirementSchema = {
requirementName: {
type: String
},
requirementModules: {
type: [object],
optional: true
}
}
GraduationRequirements.attachSchema(gradRequirementSchema);
| import { mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
/// This Component handles the initialization of the graduation requirement collection
/// requirementModule should be in he following format :
/// module code: boolean true/false
/// e.g : CS1231: false
/// the boolean is to indicate in the logic section if the following module requirement has been fulfilled
class GraduationRequirementCollection extends Mongo.Collection {}
const GraduationRequirements = new GraduationRequirementCollection('graduationRequirement');
const gradRequirementSchema = {
requirementName: {
type: String
},
requirementModules: {
type: [Object],
optional: true
}
}
GraduationRequirements.attachSchema(gradRequirementSchema);
| ADD collection description to the graduation Requirement database | ADD collection description to the graduation Requirement database
| JavaScript | mit | nus-mtp/nus-oracle,nus-mtp/nus-oracle | ---
+++
@@ -1,16 +1,22 @@
import { mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
+/// This Component handles the initialization of the graduation requirement collection
+/// requirementModule should be in he following format :
+/// module code: boolean true/false
+/// e.g : CS1231: false
+/// the boolean is to indicate in the logic section if the following module requirement has been fulfilled
+
class GraduationRequirementCollection extends Mongo.Collection {}
-const GraduationRequirements = new GraduationRequirementCollection('gradiationRequirement');
+const GraduationRequirements = new GraduationRequirementCollection('graduationRequirement');
const gradRequirementSchema = {
requirementName: {
type: String
},
requirementModules: {
- type: [object],
+ type: [Object],
optional: true
}
} |
47ff4ef345faf3fcf2dc2ab2c57f460df3719b96 | week-7/game.js | week-7/game.js | // Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission: Create madlibs game!
// Goals: Prompt user for input for various nouns, adjectives, and names. Set up alert that shows small bits of storyline with user input inserted.
// Characters: N/A
// Objects: Story
// Functions: Prompt user for input, alert user with storyline.
// Pseudocode
//
//
//
//
//
// Initial Code
// Refactored Code
// Reflection
//
//
//
//
//
//
//
// | // Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission: Create madlibs game!
// Goals: Prompt user for input for various nouns, adjectives, and names. Insert selected keywords into story-line, and print completed script.
// Characters: NA
// Objects: Field boxes, Story
// Functions: Prompt user for input, return with storyline
// Pseudocode
// Create html for content on landing page, and outline
// Stylize content with css stylesheet
// Write methods to prompt user for input,
// and to insert selected keywords into storyline
// Return completed mad lib!
// Initial Code
function madLibs() {
var storyDiv = document.getElementById("story");
var name = document.getElementById("name").value;
var adjective = document.getElementById("adjective").value;
var noun = document.getElementById("noun").value;
storyDiv.innerHTML = name + " has a " + adjective + " " + noun + " and can't make it to the party!";
}
var libButton = document.getElementById("button");
libButton.addEventListener("click", madLibs);
// Reflection
// What was the most difficult part of this challenge?
/*Figuring out during the Pseudocode process exactly which functions you be required to make this task smooth. My first inclination was to make a word jumble game, but I quickly found out there were far more components to making that work than I had intended, so I decided to go with something simpler.*/
// What did you learn about creating objects and functions that interact with one another?
// It just solidified the idea of creating these objects, to create methods you will perform by incoporating the objects.
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// You can see by the code that the document.getElementById was used heavily! This gives the property an "id" that you can later access in methods/functions to perform tasks you'd like them to do.
// How can you access and manipulate properties of objects?
// By creating a function and using getElementById("example property") to access the properties, see above! | Add reflection to solo challenge | Add reflection to solo challenge
| JavaScript | mit | sharonjean/phase-0,sharonjean/phase-0,sharonjean/phase-0 | ---
+++
@@ -4,38 +4,46 @@
// Your mission description:
// Overall mission: Create madlibs game!
-// Goals: Prompt user for input for various nouns, adjectives, and names. Set up alert that shows small bits of storyline with user input inserted.
-// Characters: N/A
-// Objects: Story
-// Functions: Prompt user for input, alert user with storyline.
+// Goals: Prompt user for input for various nouns, adjectives, and names. Insert selected keywords into story-line, and print completed script.
+// Characters: NA
+// Objects: Field boxes, Story
+// Functions: Prompt user for input, return with storyline
// Pseudocode
-//
-//
-//
-//
-//
+// Create html for content on landing page, and outline
+// Stylize content with css stylesheet
+// Write methods to prompt user for input,
+// and to insert selected keywords into storyline
+// Return completed mad lib!
// Initial Code
+function madLibs() {
+ var storyDiv = document.getElementById("story");
+ var name = document.getElementById("name").value;
+ var adjective = document.getElementById("adjective").value;
+ var noun = document.getElementById("noun").value;
-// Refactored Code
+ storyDiv.innerHTML = name + " has a " + adjective + " " + noun + " and can't make it to the party!";
+ }
-
-
-
+var libButton = document.getElementById("button");
+libButton.addEventListener("click", madLibs);
// Reflection
-//
-//
-//
-//
-//
-//
-//
-//
+// What was the most difficult part of this challenge?
+/*Figuring out during the Pseudocode process exactly which functions you be required to make this task smooth. My first inclination was to make a word jumble game, but I quickly found out there were far more components to making that work than I had intended, so I decided to go with something simpler.*/
+
+// What did you learn about creating objects and functions that interact with one another?
+// It just solidified the idea of creating these objects, to create methods you will perform by incoporating the objects.
+
+// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
+// You can see by the code that the document.getElementById was used heavily! This gives the property an "id" that you can later access in methods/functions to perform tasks you'd like them to do.
+
+// How can you access and manipulate properties of objects?
+// By creating a function and using getElementById("example property") to access the properties, see above! |
568418926c9ce41e85afaa9ed57b1f8c670d297c | test/build.js | test/build.js | const test = require('ava')
const { tmpdir } = require('os')
const { join } = require('path')
const rollup = require('rollup')
const config = require('../rollup.config')
test('build: creates a valid bundle', async assert => {
const bundle = await rollup.rollup(config)
const file = join(tmpdir(), 'bundle.js')
await bundle.write({
...config.output.find(object => object.file === 'dist/index.min.js'),
file
})
const AbstractSyntaxTree = require(file)
const tree = new AbstractSyntaxTree('const foo = 42')
assert.truthy(tree)
})
| const test = require('ava')
const { tmpdir } = require('os')
const { join } = require('path')
const rollup = require('rollup')
const config = require('../rollup.config')
test.skip('build: creates a valid bundle', async assert => {
const bundle = await rollup.rollup(config)
const file = join(tmpdir(), 'bundle.js')
await bundle.write({
...config.output.find(object => object.file === 'dist/index.min.js'),
file
})
const AbstractSyntaxTree = require(file)
const tree = new AbstractSyntaxTree('const foo = 42')
const literal = tree.find('Literal')
assert.truthy(literal)
})
| Add a failing test case | Add a failing test case
| JavaScript | mit | buxlabs/ast | ---
+++
@@ -4,7 +4,7 @@
const rollup = require('rollup')
const config = require('../rollup.config')
-test('build: creates a valid bundle', async assert => {
+test.skip('build: creates a valid bundle', async assert => {
const bundle = await rollup.rollup(config)
const file = join(tmpdir(), 'bundle.js')
await bundle.write({
@@ -13,5 +13,6 @@
})
const AbstractSyntaxTree = require(file)
const tree = new AbstractSyntaxTree('const foo = 42')
- assert.truthy(tree)
+ const literal = tree.find('Literal')
+ assert.truthy(literal)
}) |
573e68252c868d450fee7764fbf1d49143b4e4c5 | test.js | test.js | var set = require('./index.js');
var assert = require('assert');
describe('mocha-let', function() {
var object = {};
set('object', () => object);
it("allows accessing the return value of the given function as the specified property on `this`", function() {
assert.equal(this.object, object);
});
});
| var set = require('./index.js');
var assert = require('assert');
describe('mocha-let', function() {
var object = {};
set('object', () => object);
context("in a sub-context", function() {
var aDifferentObject = {};
set('object', () => aDifferentObject);
it("allows overriding the value of an existing property", function() {
assert.equal(this.object, aDifferentObject);
});
});
it("allows accessing the return value of the given function as the specified property on `this`", function() {
assert.equal(this.object, object);
});
});
| Allow overriding previously set values | Allow overriding previously set values
| JavaScript | mit | Ajedi32/mocha-let | ---
+++
@@ -5,6 +5,15 @@
var object = {};
set('object', () => object);
+ context("in a sub-context", function() {
+ var aDifferentObject = {};
+ set('object', () => aDifferentObject);
+
+ it("allows overriding the value of an existing property", function() {
+ assert.equal(this.object, aDifferentObject);
+ });
+ });
+
it("allows accessing the return value of the given function as the specified property on `this`", function() {
assert.equal(this.object, object);
}); |
cc5de7a5340ab8eb590d2bcfebad67ff8012983c | util.js | util.js | const fs = require("fs");
function evalTemplate(template, scope) {
with(scope) {
try {
return eval(`\`${template.replace(/`/g, '\\`')}\``);
} catch (error) {
console.log("Error encountered while evaluating a template:");
console.log(`Message: ${error.message}`);
console.log(`Stack trace: \n${error.stack}`);
}
}
}
function hexToRGB(hex) {
let bigint = parseInt(hex, 16);
return new RGB((bigint >> 16) & 255, (bigint >> 8) & 255, bigint & 255);
}
function loadJSON(path) {
return JSON.parse(fs.readFileSync(path));
}
function saveJSON(path, object) {
return fs.writeFileSync(path, JSON.stringify(object));
}
module.exports = {
evalTemplate,
hexToRGB,
loadJSON,
saveJSON
}
| const fs = require("fs");
function evalTemplate(template, scope) {
with(scope) {
try {
return eval(`\`${template.replace(/`/g, '\\`')}\``);
} catch (error) {
console.log("Error encountered while evaluating a template:");
console.log(`Message: ${error.message}`);
console.log(`Stack trace: \n${error.stack}`);
}
}
}
function hexToRGB(hex) {
let bigint = parseInt(hex, 16);
return new RGB((bigint >> 16) & 255, (bigint >> 8) & 255, bigint & 255);
}
function loadJSON(path) {
return JSON.parse(fs.readFileSync(path));
}
function saveJSON(path, object) {
return fs.writeFileSync(path, JSON.stringify(object, null, 4));
}
module.exports = {
evalTemplate,
hexToRGB,
loadJSON,
saveJSON
}
| Add indents in saved config | Add indents in saved config
| JavaScript | mit | md678685/justcord-3 | ---
+++
@@ -22,7 +22,7 @@
}
function saveJSON(path, object) {
- return fs.writeFileSync(path, JSON.stringify(object));
+ return fs.writeFileSync(path, JSON.stringify(object, null, 4));
}
module.exports = { |
f5d0ab8fed19b9f61f089c1cd7ff01d457e33e93 | springfox-swagger-ui/src/web/js/springfox.js | springfox-swagger-ui/src/web/js/springfox.js | $(function() {
var springfox = {
"baseUrl": function() {
var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
return urlMatches[1];
},
"securityConfig": function(cb) {
$.getJSON(this.baseUrl() + "/configuration/security", function(data) {
cb(data);
});
},
"uiConfig": function(cb) {
$.getJSON(this.baseUrl() + "/configuration/ui", function(data) {
cb(data);
});
}
};
window.springfox = springfox;
window.oAuthRedirectUrl = springfox.baseUrl() + '/o2c.html'
$('#select_baseUrl').change(function() {
window.swaggerUi.headerView.trigger('update-swagger-ui', {
url: $('#select_baseUrl').val()
});
});
$(document).ready(function() {
var relativeLocation = springfox.baseUrl();
$('#input_baseUrl').hide();
$.getJSON(relativeLocation + "/swagger-resources", function(data) {
var $urlDropdown = $('#select_baseUrl');
$urlDropdown.empty();
$.each(data, function(i, resource) {
var option = $('<option></option>')
.attr("value", relativeLocation + resource.location)
.text(resource.name + " (" + resource.location + ")");
$urlDropdown.append(option);
});
$urlDropdown.change();
});
});
});
| $(function() {
var springfox = {
"baseUrl": function() {
var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
return urlMatches[1];
},
"securityConfig": function(cb) {
$.getJSON(this.baseUrl() + "/configuration/security", function(data) {
cb(data);
});
},
"uiConfig": function(cb) {
$.getJSON(this.baseUrl() + "/configuration/ui", function(data) {
cb(data);
});
}
};
window.springfox = springfox;
window.oAuthRedirectUrl = springfox.baseUrl() + '/o2c.html'
$('#select_baseUrl').change(function() {
window.swaggerUi.headerView.trigger('update-swagger-ui', {
url: $('#select_baseUrl').val()
});
});
function maybePrefix(location, withRelativePath) {
var pat = /^https?:\/\//i;
if (pat.test(location)) {
return location;
}
return withRelativePath + location;
}
$(document).ready(function() {
var relativeLocation = springfox.baseUrl();
$('#input_baseUrl').hide();
$.getJSON(relativeLocation + "/swagger-resources", function(data) {
var $urlDropdown = $('#select_baseUrl');
$urlDropdown.empty();
$.each(data, function(i, resource) {
var option = $('<option></option>')
.attr("value", maybePrefix(resource.location, relativeLocation))
.text(resource.name + " (" + resource.location + ")");
$urlDropdown.append(option);
});
$urlDropdown.change();
});
});
});
| Allow loading of external urls specified in the swagger resource location | Allow loading of external urls specified in the swagger resource location
resolves #843
| JavaScript | apache-2.0 | erikthered/springfox,springfox/springfox,RobWin/springfox,maksimu/springfox,RobWin/springfox,vmarusic/springfox,vmarusic/springfox,thomsonreuters/springfox,acourtneybrown/springfox,thomasdarimont/springfox,thomsonreuters/springfox,zorosteven/springfox,zorosteven/springfox,choiapril6/springfox,vmarusic/springfox,RobWin/springfox,jlstrater/springfox,kevinconaway/springfox,yelhouti/springfox,erikthered/springfox,thomsonreuters/springfox,choiapril6/springfox,yelhouti/springfox,kevinconaway/springfox,acourtneybrown/springfox,erikthered/springfox,izeye/springfox,jlstrater/springfox,jlstrater/springfox,yelhouti/springfox,maksimu/springfox,namkee/springfox,arshadalisoomro/springfox,izeye/springfox,springfox/springfox,zhiqinghuang/springfox,namkee/springfox,cbornet/springfox,thomasdarimont/springfox,wjc133/springfox,izeye/springfox,arshadalisoomro/springfox,choiapril6/springfox,maksimu/springfox,zorosteven/springfox,zhiqinghuang/springfox,arshadalisoomro/springfox,acourtneybrown/springfox,cbornet/springfox,springfox/springfox,springfox/springfox,kevinconaway/springfox,wjc133/springfox,thomasdarimont/springfox,namkee/springfox,wjc133/springfox,zhiqinghuang/springfox,cbornet/springfox | ---
+++
@@ -24,6 +24,14 @@
});
});
+ function maybePrefix(location, withRelativePath) {
+ var pat = /^https?:\/\//i;
+ if (pat.test(location)) {
+ return location;
+ }
+ return withRelativePath + location;
+ }
+
$(document).ready(function() {
var relativeLocation = springfox.baseUrl();
@@ -35,7 +43,7 @@
$urlDropdown.empty();
$.each(data, function(i, resource) {
var option = $('<option></option>')
- .attr("value", relativeLocation + resource.location)
+ .attr("value", maybePrefix(resource.location, relativeLocation))
.text(resource.name + " (" + resource.location + ")");
$urlDropdown.append(option);
}); |
c2618f02b207a1c9a93638d2209532fd60d5805a | karma.conf.ci.js | karma.conf.ci.js | module.exports = function(config) {
require("./karma.conf")(config);
config.set({
customLaunchers: {
SL_Chrome: {
base: 'SauceLabs',
browserName: 'chrome',
version: '35'
},
SL_Firefox: {
base: 'SauceLabs',
browserName: 'firefox',
version: '30'
},
SL_Safari: {
base: 'SauceLabs',
browserName: 'safari',
version: '9'
},
SL_IE8: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '8',
platform: 'Windows XP'
},
SL_IE9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9',
platform: 'Windows 7'
},
SL_IE10: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '10',
platform: 'Windows 8'
},
SL_IE11: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11',
platform: 'Windows 10'
}
},
browsers: [
'SL_IE8',
'SL_IE9',
'SL_IE10',
'SL_IE11'
],
sauceLabs: {
recordVideo: false
},
captureTimeout: 120000,
browserNoActivityTimeout: 300000
});
};
| module.exports = function(config) {
require("./karma.conf")(config);
config.set({
customLaunchers: {
SL_Chrome: {
base: 'SauceLabs',
browserName: 'chrome',
version: '35'
},
SL_Firefox: {
base: 'SauceLabs',
browserName: 'firefox',
version: '30'
},
SL_Safari: {
base: 'SauceLabs',
browserName: 'safari',
version: '9'
},
SL_IE8: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '8',
platform: 'Windows XP'
},
SL_IE9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9',
platform: 'Windows 7'
},
SL_IE10: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '10',
platform: 'Windows 8'
},
SL_IE11: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11',
platform: 'Windows 10'
}
},
browsers: [
'SL_IE8',
'SL_IE9',
'SL_IE10',
'SL_IE11'
],
sauceLabs: {
testName: 'Script Loader Tests',
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
startConnect: false,
recordVideo: false
},
captureTimeout: 120000,
browserNoActivityTimeout: 300000
});
};
| Set startConnect: false and tunnelIdentifier | Set startConnect: false and tunnelIdentifier
Reference: https://github.com/karma-runner/karma-sauce-launcher/issues/73
| JavaScript | mit | exogen/script-atomic-onload | ---
+++
@@ -49,6 +49,9 @@
'SL_IE11'
],
sauceLabs: {
+ testName: 'Script Loader Tests',
+ tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
+ startConnect: false,
recordVideo: false
},
captureTimeout: 120000, |
a87dfa91ebfe7816cfdd2770903a09719b7710d6 | biz/webui/cgi-bin/lookup-tunnel-dns.js | biz/webui/cgi-bin/lookup-tunnel-dns.js | var url = require('url');
var properties = require('../lib/properties');
var rules = require('../lib/proxy').rules;
var util = require('../lib/util');
module.exports = function(req, res) {
var tunnelUrl = properties.get('showHostIpInResHeaders') ? req.query.url : null;
if (typeof tunnelUrl != 'string') {
tunnelUrl = null;
} else if (tunnelUrl) {
tunnelUrl = url.parse(tunnelUrl);
tunnelUrl = tunnelUrl.host ? 'https://' + tunnelUrl.host : null;
}
if (!tunnelUrl) {
return res.json({ec: 2, em: 'server busy'});
}
var _rules = rules.resolveRules(tunnelUrl);
if (_rules.rule) {
var _url = util.setProtocol(util.rule.getMatcher(_rules.rule), true);
if (/^https:/i.test(_url)) {
tunnelUrl = _url;
}
}
rules.resolveHost(tunnelUrl, function(err, host) {
if (err) {
res.json({ec: 2, em: 'server busy'});
} else {
res.json({ec: 0, em: 'success', host: host});
}
});
};
| var url = require('url');
var properties = require('../lib/properties');
var rules = require('../lib/proxy').rules;
var util = require('../lib/util');
module.exports = function(req, res) {
var tunnelUrl = properties.get('showHostIpInResHeaders') ? req.query.url : null;
if (typeof tunnelUrl != 'string') {
tunnelUrl = null;
} else if (tunnelUrl) {
tunnelUrl = url.parse(tunnelUrl);
tunnelUrl = tunnelUrl.host ? 'https://' + tunnelUrl.host : null;
}
if (!tunnelUrl) {
return res.json({ec: 2, em: 'server busy'});
}
var rule = rules.resolveRule(tunnelUrl);
if (rule) {
var _url = util.setProtocol(util.rule.getMatcher(rule), true);
if (/^https:/i.test(_url)) {
tunnelUrl = _url;
}
}
rules.resolveHost(tunnelUrl, function(err, host) {
if (err) {
res.json({ec: 2, em: 'server busy'});
} else {
res.json({ec: 0, em: 'success', host: host});
}
});
};
| Use resolveRule instead of resolveRules | refactor: Use resolveRule instead of resolveRules
| JavaScript | mit | avwo/whistle,avwo/whistle | ---
+++
@@ -15,9 +15,9 @@
if (!tunnelUrl) {
return res.json({ec: 2, em: 'server busy'});
}
- var _rules = rules.resolveRules(tunnelUrl);
- if (_rules.rule) {
- var _url = util.setProtocol(util.rule.getMatcher(_rules.rule), true);
+ var rule = rules.resolveRule(tunnelUrl);
+ if (rule) {
+ var _url = util.setProtocol(util.rule.getMatcher(rule), true);
if (/^https:/i.test(_url)) {
tunnelUrl = _url;
} |
daa89751125bd9d00502f80fbae96fcd032092e2 | webpack.config.js | webpack.config.js | var version = require('./package.json').version;
module.exports = {
entry: './lib',
output: {
filename: './dist/index.js',
library: ['jupyter', 'services'],
libraryTarget: 'umd',
publicPath: 'https://npmcdn.com/jupyter-js-services@' + version + '/dist/'
},
devtool: 'source-map'
};
| var version = require('./package.json').version;
module.exports = {
entry: './lib',
output: {
filename: './dist/index.js',
library: 'jupyter-js-services',
libraryTarget: 'umd',
umdNamedDefine: true,
publicPath: 'https://npmcdn.com/jupyter-js-services@' + version + '/dist/'
},
devtool: 'source-map'
};
| Unify the library name and export the amd name | Unify the library name and export the amd name
| JavaScript | bsd-3-clause | jupyterlab/services,blink1073/jupyter-js-services,blink1073/services,jupyterlab/services,jupyter/jupyter-js-services,blink1073/services,blink1073/jupyter-js-services,blink1073/jupyter-js-services,blink1073/services,jupyter/jupyter-js-services,blink1073/services,jupyter/jupyter-js-services,jupyterlab/services,jupyter/jupyter-js-services,blink1073/jupyter-js-services,jupyterlab/services | ---
+++
@@ -4,8 +4,9 @@
entry: './lib',
output: {
filename: './dist/index.js',
- library: ['jupyter', 'services'],
+ library: 'jupyter-js-services',
libraryTarget: 'umd',
+ umdNamedDefine: true,
publicPath: 'https://npmcdn.com/jupyter-js-services@' + version + '/dist/'
},
devtool: 'source-map' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.