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 |
|---|---|---|---|---|---|---|---|---|---|---|
7294b89a6bb296bf35f338c12fe5b8cc82504cb6 | scrapper/index.js | scrapper/index.js | // Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore')
// Your Google Cloud Platform project ID
const projectId = 'pirula-time'
// Instantiates a client
const datastore = Datastore({
projectId: projectId
})
// The kind for the new entity
const kind = 'time'
// The name/ID for the new entity
const name = 'average'
// The Cloud Datastore key for the new entity
const key = datastore.key([kind, name])
function scrape() {
const data = {
average: 3200,
}
return data
}
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event The Cloud Functions event.
* @param {!Function} The callback function.
*/
exports.subscribe = function subscribe(event, callback) {
console.log("START")
// The Cloud Pub/Sub Message object.
const pubsubMessage = event.data
const data = scrape()
// Prepares the new entity
const average = {
key: key,
data: {
val: data.average
}
}
// Saves the entity
datastore.save(average)
.then(() => {
console.log(`Saved ${average.key.name}: ${average.data}`)
})
.catch((err) => {
console.error('ERROR:', err)
})
// Don't forget to call the callback.
callback()
}; | const Datastore = require('@google-cloud/datastore')
const projectId = 'pirula-time'
const datastore = Datastore({
projectId: projectId
})
const kind = 'time'
const averageKey = datastore.key([kind, 'average'])
function scrape() {
const data = {
average: 1800,
}
return data
}
exports.doIt = function doIt(req, res) {
console.log("DOIN' IT!")
const message = req.body.message
const data = scrape()
const saveData = {
key: averageKey,
data: {
val: data.average
}
}
datastore.save(saveData)
.then(() => {
res.status(200).send(`Saved ${JSON.stringify(saveData)}`)
})
.catch((err) => {
res.status(500).send('Error: ' + err.toString())
})
} | Change scrapper trigger to http request | Change scrapper trigger to http request
| JavaScript | mit | firefueled/pirula-time,firefueled/pirula-time,firefueled/pirula-time,firefueled/pirula-time,firefueled/pirula-time | ---
+++
@@ -1,58 +1,37 @@
-// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore')
-
-// Your Google Cloud Platform project ID
const projectId = 'pirula-time'
-
-// Instantiates a client
const datastore = Datastore({
projectId: projectId
})
-// The kind for the new entity
const kind = 'time'
-// The name/ID for the new entity
-const name = 'average'
-// The Cloud Datastore key for the new entity
-const key = datastore.key([kind, name])
+const averageKey = datastore.key([kind, 'average'])
function scrape() {
const data = {
- average: 3200,
+ average: 1800,
}
return data
}
-/**
- * Triggered from a message on a Cloud Pub/Sub topic.
- *
- * @param {!Object} event The Cloud Functions event.
- * @param {!Function} The callback function.
- */
-exports.subscribe = function subscribe(event, callback) {
- console.log("START")
- // The Cloud Pub/Sub Message object.
- const pubsubMessage = event.data
+exports.doIt = function doIt(req, res) {
+ console.log("DOIN' IT!")
+ const message = req.body.message
const data = scrape()
- // Prepares the new entity
- const average = {
- key: key,
+ const saveData = {
+ key: averageKey,
data: {
val: data.average
}
}
- // Saves the entity
- datastore.save(average)
+ datastore.save(saveData)
.then(() => {
- console.log(`Saved ${average.key.name}: ${average.data}`)
+ res.status(200).send(`Saved ${JSON.stringify(saveData)}`)
})
.catch((err) => {
- console.error('ERROR:', err)
+ res.status(500).send('Error: ' + err.toString())
})
-
- // Don't forget to call the callback.
- callback()
-};
+} |
43dddfa13f3738d4436b25972b8c22ee8a0ae165 | js/models/article.js | js/models/article.js | Kpcc.Article = DS.Model.extend({
title : DS.attr(),
short_title : DS.attr(),
published_at : DS.attr(),
byline : DS.attr(),
teaser : DS.attr(),
body : DS.attr(),
public_url : DS.attr(),
assets : DS.hasMany('asset'),
audio : DS.hasMany("audio"),
category : DS.belongsTo('category'),
});
Kpcc.ArticleSerializer = Kpcc.ApplicationSerializer.extend(
DS.EmbeddedRecordsMixin, {
attrs: {
assets : { embedded: 'always' },
category : { embedded: 'always' },
audio : { embedded: 'always' }
}
}
)
| Kpcc.Article = DS.Model.extend({
title : DS.attr(),
short_title : DS.attr(),
published_at : DS.attr(),
byline : DS.attr(),
teaser : DS.attr(),
body : DS.attr(),
public_url : DS.attr(),
assets : DS.hasMany('asset'),
audio : DS.attr(),
category : DS.belongsTo('category'),
});
Kpcc.ArticleSerializer = Kpcc.ApplicationSerializer.extend(
DS.EmbeddedRecordsMixin, {
attrs: {
assets : { embedded: 'always' },
category : { embedded: 'always' }
}
}
)
| Fix Reader to support non-model audio (no ID) | Fix Reader to support non-model audio (no ID)
| JavaScript | mit | SCPR/kpcc-reader,SCPR/kpcc-reader,SCPR/kpcc-reader | ---
+++
@@ -7,7 +7,7 @@
body : DS.attr(),
public_url : DS.attr(),
assets : DS.hasMany('asset'),
- audio : DS.hasMany("audio"),
+ audio : DS.attr(),
category : DS.belongsTo('category'),
});
@@ -15,8 +15,7 @@
DS.EmbeddedRecordsMixin, {
attrs: {
assets : { embedded: 'always' },
- category : { embedded: 'always' },
- audio : { embedded: 'always' }
+ category : { embedded: 'always' }
}
}
) |
acb8969398c27fd29dd849e9b5072ac5df1997fc | app/assets/javascripts/frontend/text-character-count.js | app/assets/javascripts/frontend/text-character-count.js | // Gets character limit and allows no more
$(function() {
// Creates the character count elements
$(".js-char-count").wrap("<div class='char-count'></div>")
$(".js-char-count").after("<div class='char-text'>Character count: <span class='current-count'>0</span></div>");
// Includes charact limit if there is one
$(".js-char-count").each(function(){
var maxlength = $(this).attr('maxlength');
if (maxlength) {
$(this).closest(".char-count").find(".char-text").append("/<span class='total-count'>" +maxlength+ "</span>")
}
});
// On keydown, gets character count
$(".js-char-count").on('keyup', function () {
content = $(this).val().replace(/(\r\n|\n|\r)/gm," ");
$(this).closest(".char-count").find(".char-text .current-count").text(content.length);
// If character count is over the limit then show error
if (content.length > $(this).attr('maxlength')) {
$(this).closest(".char-count").addClass("char-over");
} else {
$(this).closest(".char-count").removeClass("char-over");
}
});
});
| // Gets character limit and allows no more
$(function() {
// Creates the character count elements
$(".js-char-count").wrap("<div class='char-count'></div>")
$(".js-char-count").after("<div class='char-text'>Character count: <span class='current-count'>0</span></div>");
// Includes charact limit if there is one
$(".js-char-count").each(function(){
var maxlength = $(this).attr('maxlength');
if (maxlength) {
$(this).closest(".char-count").find(".char-text").append("/<span class='total-count'>" +maxlength+ "</span>")
}
});
// On keydown, gets character count
$(".js-char-count").on('keyup', function () {
// Webkit counts a new line as a two characters
// IE doesn't use maxlength
var newline = " ";
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
// Firefox counts a new line as a singular character
newline = " ";
}
content = $(this).val().replace(/(\r\n|\n|\r)/gm," ");
$(this).closest(".char-count").find(".char-text .current-count").text(content.length);
// If character count is over the limit then show error
if (content.length > $(this).attr('maxlength')) {
$(this).closest(".char-count").addClass("char-over");
} else {
$(this).closest(".char-count").removeClass("char-over");
}
});
});
| Fix char count for Firefox | Fix char count for Firefox
| JavaScript | mit | bitzesty/qae,bitzesty/qae,bitzesty/qae,bitzesty/qae | ---
+++
@@ -14,6 +14,15 @@
// On keydown, gets character count
$(".js-char-count").on('keyup', function () {
+ // Webkit counts a new line as a two characters
+ // IE doesn't use maxlength
+ var newline = " ";
+
+ if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
+ // Firefox counts a new line as a singular character
+ newline = " ";
+ }
+
content = $(this).val().replace(/(\r\n|\n|\r)/gm," ");
$(this).closest(".char-count").find(".char-text .current-count").text(content.length);
|
768db2ae414700b751dafd2e159ec40251d4beed | lib/graceful-exit.js | lib/graceful-exit.js | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() {
clearPlayers(radiodan.cache.players).then(
function() {
process.exit(0);
},
function() {
process.exit(1);
}
);
function clearPlayers(players) {
var playerIds = Object.keys(players),
resolved = utils.promise.resolve();
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
};
};
| var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = function(radiodan){
return function() { return gracefulExit(radiodan); }
};
function gracefulExit(radiodan) {
// if promise does not resolve quickly enough, exit anyway
setTimeout(exitWithCode(2), 3000);
return clearPlayers(radiodan.cache.players)
.then(exitWithCode(0), exitWithCode(1));
};
function clearPlayers(players) {
var resolved = utils.promise.resolve(),
playerIds = Object.keys(players || {});
if(playerIds.length === 0){
return resolved;
}
return Object.keys(players).reduce(function(previous, current){
return previous.then(players[current].clear);
}, resolved);
}
function exitWithCode(exitCode) {
return function() {
process.exit(exitCode);
return utils.promise.resolve();
}
}
| Exit process if clearing process does not finish within 3 seconds | Exit process if clearing process does not finish within 3 seconds
App would previously refuse to exit if it could not send a successful
clear message to each player.
| JavaScript | apache-2.0 | radiodan/magic-button,radiodan/magic-button | ---
+++
@@ -2,27 +2,34 @@
logger = utils.logger(__filename);
module.exports = function(radiodan){
+ return function() { return gracefulExit(radiodan); }
+};
+
+function gracefulExit(radiodan) {
+ // if promise does not resolve quickly enough, exit anyway
+ setTimeout(exitWithCode(2), 3000);
+
+ return clearPlayers(radiodan.cache.players)
+ .then(exitWithCode(0), exitWithCode(1));
+};
+
+function clearPlayers(players) {
+ var resolved = utils.promise.resolve(),
+ playerIds = Object.keys(players || {});
+
+ if(playerIds.length === 0){
+ return resolved;
+ }
+
+ return Object.keys(players).reduce(function(previous, current){
+ return previous.then(players[current].clear);
+ }, resolved);
+}
+
+function exitWithCode(exitCode) {
return function() {
- clearPlayers(radiodan.cache.players).then(
- function() {
- process.exit(0);
- },
- function() {
- process.exit(1);
- }
- );
+ process.exit(exitCode);
- function clearPlayers(players) {
- var playerIds = Object.keys(players),
- resolved = utils.promise.resolve();
-
- if(playerIds.length === 0){
- return resolved;
- }
-
- return Object.keys(players).reduce(function(previous, current){
- return previous.then(players[current].clear);
- }, resolved);
- }
- };
-};
+ return utils.promise.resolve();
+ }
+} |
1750b24540c65f4a0a29c2f5905aa885039db602 | lib/platform.js | lib/platform.js | var isNode = require('is-node');
module.exports = (function () {
if (typeof Deno !== 'undefined') {
var env = Deno.permissions().env ? Deno.env() : {};
return {
argv: Deno.args,
color: !Deno.noColor ? 1 : 0,
env: env,
runtime: 'deno'
};
} else if (isNode) {
var os = require('os');
return {
argv: process.argv,
env: process.env,
runtime: 'node',
getNodeRelease: os.release
};
} else {
return {
argv: [],
env: {},
runtime: 'browser'
};
}
})();
| /*globals Deno*/
var isNode = require('is-node');
module.exports = (function () {
if (typeof Deno !== 'undefined') {
var env = Deno.permissions().env ? Deno.env() : {};
return {
argv: Deno.args,
color: !Deno.noColor ? 1 : 0,
env: env,
runtime: 'deno'
};
} else if (isNode) {
var os = require('os');
return {
argv: process.argv,
env: process.env,
runtime: 'node',
getNodeRelease: os.release
};
} else {
return {
argv: [],
env: {},
runtime: 'browser'
};
}
})();
| Add a int exception for the check for Deno. | Add a int exception for the check for Deno.
| JavaScript | mit | sunesimonsen/magicpen | ---
+++
@@ -1,3 +1,4 @@
+/*globals Deno*/
var isNode = require('is-node');
module.exports = (function () { |
fc51b12766d2be8fef8889bca13a2459f8f63d24 | api/index.js | api/index.js | module.exports = function (config, next) {
require('../db')(config, function (err, client) {
if (err) { return next(err); }
var messaging = require('../db/messaging')(config);
var keyspace = config.keyspace || 'seguir';
// TODO: Refactor out into iteration over array of modules
var auth = require('./auth');
var common = require('./common');
var user = require('./user');
var post = require('./post');
var like = require('./like');
var feed = require('./feed');
var friend = require('./friend');
var follow = require('./follow');
var migrations = require('../db/migrations');
var api = {};
api.client = client;
api.config = config;
api.messaging = messaging;
// Auth and migrations both run on core keyspace
api.auth = auth(keyspace, api);
api.migrations = migrations(keyspace, api);
// Other APIs get their keyspace with each api request
api.common = common(api);
api.follow = follow(api);
api.feed = feed(api);
api.friend = friend(api);
api.like = like(api);
api.post = post(api);
api.user = user(api);
next(null, api);
});
};
| var path = require('path');
module.exports = function (config, next) {
require('../db')(config, function (err, client) {
if (err) { return next(err); }
var messaging = require('../db/messaging')(config);
var api = {};
api.client = client;
api.config = config;
api.messaging = messaging;
var modules = ['auth', 'common', 'user', 'post', 'like', 'feed', 'friend', 'follow', '../db/migrations'];
modules.forEach(function (module) {
var moduleName = path.basename(module);
api[moduleName] = require(path.resolve(__dirname, module))(api);
});
next(null, api);
});
};
| Make api initialisation more modular | Make api initialisation more modular
| JavaScript | mit | gajjargaurav/seguir,cliftonc/seguir,tes/seguir | ---
+++
@@ -1,3 +1,5 @@
+var path = require('path');
+
module.exports = function (config, next) {
require('../db')(config, function (err, client) {
@@ -5,36 +7,17 @@
if (err) { return next(err); }
var messaging = require('../db/messaging')(config);
- var keyspace = config.keyspace || 'seguir';
-
- // TODO: Refactor out into iteration over array of modules
- var auth = require('./auth');
- var common = require('./common');
- var user = require('./user');
- var post = require('./post');
- var like = require('./like');
- var feed = require('./feed');
- var friend = require('./friend');
- var follow = require('./follow');
- var migrations = require('../db/migrations');
var api = {};
api.client = client;
api.config = config;
api.messaging = messaging;
- // Auth and migrations both run on core keyspace
- api.auth = auth(keyspace, api);
- api.migrations = migrations(keyspace, api);
-
- // Other APIs get their keyspace with each api request
- api.common = common(api);
- api.follow = follow(api);
- api.feed = feed(api);
- api.friend = friend(api);
- api.like = like(api);
- api.post = post(api);
- api.user = user(api);
+ var modules = ['auth', 'common', 'user', 'post', 'like', 'feed', 'friend', 'follow', '../db/migrations'];
+ modules.forEach(function (module) {
+ var moduleName = path.basename(module);
+ api[moduleName] = require(path.resolve(__dirname, module))(api);
+ });
next(null, api);
|
5c31bef28451412a09bcc100fb08c2b41709d0ce | client/src/store/rootReducer.js | client/src/store/rootReducer.js | import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {
organization,
starredBoard,
notification,
modals,
board,
home
} from '../app/routes/home/modules/index';
import { signUp } from '../app/routes/signUp/modules/index';
import { login } from '../app/routes/login/modules/index';
import {
popOver,
app
} from '../app/modules/index';
import {
boardView,
card
} from '../app/routes/home/routes/boardView/modules/index';
const rootReducer = combineReducers({
organization,
starredBoard,
notification,
modals,
board,
home,
signUp,
login,
popOver,
app,
boardView,
card,
form: formReducer,
routing: routerReducer
})
export default rootReducer; | import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {
organization,
starredBoard,
notification,
modals,
board,
home
} from '../app/routes/home/modules/index';
import { signUp } from '../app/routes/signUp/modules/index';
import { login } from '../app/routes/login/modules/index';
import {
boardsMenu,
popOver,
app
} from '../app/modules/index';
import {
boardView,
card
} from '../app/routes/home/routes/boardView/modules/index';
const rootReducer = combineReducers({
organization,
starredBoard,
notification,
modals,
board,
home,
signUp,
login,
boardsMenu,
popOver,
app,
boardView,
card,
form: formReducer,
routing: routerReducer
})
export default rootReducer; | Add boardsMenu reducer to the store | Add boardsMenu reducer to the store
| JavaScript | mit | Madmous/madClones,Madmous/Trello-Clone,Madmous/Trello-Clone,Madmous/madClones,Madmous/Trello-Clone,Madmous/madClones,Madmous/madClones | ---
+++
@@ -15,6 +15,7 @@
import { login } from '../app/routes/login/modules/index';
import {
+ boardsMenu,
popOver,
app
} from '../app/modules/index';
@@ -35,6 +36,7 @@
signUp,
login,
+ boardsMenu,
popOver,
app,
|
5bdf8dd75843b06b72c3bee3dbe4dbefc7def43c | apps/main.js | apps/main.js | import React from 'react';
import { registerComponent } from 'react-native-playground';
import {
StyleSheet,
Text,
View,
} from 'react-native';
class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.instructions}>
Edit and save with Cmd+S (Mac) or Ctrl+S (Windows). Changes will
be reflected immediately in the simulator or on your device.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
instructions: {
fontSize: 16,
textAlign: 'center',
margin: 15,
},
});
registerComponent(App);
| import React from 'react';
import { registerComponent } from 'react-native-playground';
import {
StatusBar,
StyleSheet,
Text,
View,
} from 'react-native';
class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.instructions}>
Edit and save with Cmd+S (Mac) or Ctrl+S (Windows). Changes will
be reflected immediately in the simulator or on your device.
</Text>
<StatusBar barStyle="default" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
instructions: {
fontSize: 16,
textAlign: 'center',
margin: 15,
},
});
registerComponent(App);
| Use default barStyle in starter app | Use default barStyle in starter app
| JavaScript | mit | rnplay/rnplay-web,rnplay/rnplay-web,rnplay/rnplay-web,rnplay/rnplay-web | ---
+++
@@ -1,6 +1,7 @@
import React from 'react';
import { registerComponent } from 'react-native-playground';
import {
+ StatusBar,
StyleSheet,
Text,
View,
@@ -14,6 +15,8 @@
Edit and save with Cmd+S (Mac) or Ctrl+S (Windows). Changes will
be reflected immediately in the simulator or on your device.
</Text>
+
+ <StatusBar barStyle="default" />
</View>
);
} |
9975351407a528dad840fda8309acfa132b9b431 | service/security.js | service/security.js | /*
* Copyright 2015 Mark Eschbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Security
*/
var passport = require("passport");
var passportHttp = require("passport-http");
function authenticate_user(username, password, done) {
var user = this.users[username];
if ( !user ) { return done( null, false ); }
if ( !user.password ) { return done( null, false ); }
if ( user.password != password ) { return done( null, false ); }
done( null, user );
}
function assemble(container, config) {
var authenticator = authenticate_user.bind(config);
passport.use(new passportHttp.BasicStrategy( authenticator ));
container.require_user = [
passport.initialize(),
passport.authenticate('basic', { session: false })
];
}
exports.assemble = assemble;
| /*
* Copyright 2015 Mark Eschbach
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Security
*/
var passport = require("passport");
var passportHttp = require("passport-http");
function authenticate_user(username, password, done) {
if( !this.users ){ return done(null,{ }); }
var user = this.users[username];
if ( !user ) { return done( null, false ); }
if ( !user.password ) { return done( null, false ); }
if ( user.password != password ) { return done( null, false ); }
done( null, user );
}
function assemble(container, config) {
var authenticator = authenticate_user.bind(config);
passport.use(new passportHttp.BasicStrategy( authenticator ));
container.require_user = [
passport.initialize(),
passport.authenticate('basic', { session: false })
];
}
exports.assemble = assemble;
| Allow for no user states | Allow for no user states
| JavaScript | apache-2.0 | meschbach/onomate,meschbach/onomate,meschbach/onomate | ---
+++
@@ -1,12 +1,12 @@
/*
* Copyright 2015 Mark Eschbach
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,6 +19,7 @@
var passportHttp = require("passport-http");
function authenticate_user(username, password, done) {
+ if( !this.users ){ return done(null,{ }); }
var user = this.users[username];
if ( !user ) { return done( null, false ); }
if ( !user.password ) { return done( null, false ); } |
654d58e164240d3ef35f5b2b3e3903f9eb554fa8 | internals/testing/karma.conf.js | internals/testing/karma.conf.js | const webpackConfig = require('../webpack/webpack.test.config');
const path = require('path');
module.exports = (config) => {
config.set({
frameworks: ['mocha', 'sinon-chai'],
reporters: ['coverage', 'mocha'],
browsers: ['Chrome'],
autoWatch: false,
singleRun: true,
/**
* Define the karma file.
*
* @type {Array}
*/
files: [{
pattern: './test-bundler.js',
watched: false,
served: true,
included: true,
}],
// Setup the preprocessors
preprocessors: {
['./test-bundler.js']: ['webpack', 'sourcemap'],
},
// Load the webpack configuration
webpack: webpackConfig,
// Prevent webpack spamming
webpackMiddleware: {
noInfo: true,
stats: 'errors-only',
},
// customLaunchers: {
// ChromeTravis: {
// base: 'Chrome',
// flags: ['--no-sandbox'],
// },
// },
coverageReporter: {
dir: path.join(process.cwd(), 'coverage'),
reporters: [
{ type: 'lcov', subdir: 'lcov' },
{ type: 'html', subdir: 'html' },
{ type: 'text-summary' },
],
},
});
};
| const webpackConfig = require('../webpack/webpack.test.config');
const path = require('path');
module.exports = (config) => {
config.set({
frameworks: ['mocha', 'sinon-chai'],
reporters: ['coverage', 'mocha'],
browsers: process.env.TRAVIS
? ['ChromeTravis']
: ['Chrome'],
autoWatch: false,
singleRun: true,
/**
* Define the karma file.
*
* @type {Array}
*/
files: [{
pattern: './test-bundler.js',
watched: false,
served: true,
included: true,
}],
// Setup the preprocessors
preprocessors: {
['./test-bundler.js']: ['webpack', 'sourcemap'],
},
// Load the webpack configuration
webpack: webpackConfig,
// Prevent webpack spamming
webpackMiddleware: {
noInfo: true,
stats: 'errors-only',
},
customLaunchers: {
ChromeTravis: {
base: 'Chrome',
flags: ['--no-sandbox'],
},
},
coverageReporter: {
dir: path.join(process.cwd(), 'coverage'),
reporters: [
{ type: 'lcov', subdir: 'lcov' },
{ type: 'html', subdir: 'html' },
{ type: 'text-summary' },
],
},
});
};
| Set up test support for travis. | Set up test support for travis.
| JavaScript | mit | reauv/persgroep-app,reauv/persgroep-app | ---
+++
@@ -5,7 +5,9 @@
config.set({
frameworks: ['mocha', 'sinon-chai'],
reporters: ['coverage', 'mocha'],
- browsers: ['Chrome'],
+ browsers: process.env.TRAVIS
+ ? ['ChromeTravis']
+ : ['Chrome'],
autoWatch: false,
singleRun: true,
@@ -34,15 +36,14 @@
webpackMiddleware: {
noInfo: true,
stats: 'errors-only',
-
},
- // customLaunchers: {
- // ChromeTravis: {
- // base: 'Chrome',
- // flags: ['--no-sandbox'],
- // },
- // },
+ customLaunchers: {
+ ChromeTravis: {
+ base: 'Chrome',
+ flags: ['--no-sandbox'],
+ },
+ },
coverageReporter: {
dir: path.join(process.cwd(), 'coverage'), |
a51ddfe38c359c4127c19d1096966f5090ca73e4 | config/express.js | config/express.js | // Create the application and define middleware.
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var router = require('./../app/routes')();
module.exports = function () {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use('/api/v1/', router);
return app;
};
| // Create the application and define middleware.
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var router = require('./../app/files/routes')();
module.exports = function () {
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use('/api/v1/', router);
return app;
};
| Fix reference to the routes folder of the files module. | Fix reference to the routes folder of the files module.
| JavaScript | mit | andela-ioraelosi/hackshub-file-service | ---
+++
@@ -5,7 +5,7 @@
var express = require('express');
var bodyParser = require('body-parser');
-var router = require('./../app/routes')();
+var router = require('./../app/files/routes')();
module.exports = function () {
|
bb7eb52313831da6a8c12324d220875fd25f68bf | routes/index.js | routes/index.js | var express = require('express');
var router = express.Router();
router.get('/checkouts/new', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
| var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/checkouts/new', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
| Update root route to point to new checkouts page | Update root route to point to new checkouts page
| JavaScript | mit | braintree/braintree_express_example,braintree/braintree_express_example,ashutosh37/nodejs-braintree-firebase,ashutosh37/nodejs-braintree-firebase | ---
+++
@@ -1,5 +1,9 @@
var express = require('express');
var router = express.Router();
+
+router.get('/', function(req, res, next) {
+ res.render('index', { title: 'Express' });
+});
router.get('/checkouts/new', function(req, res, next) {
res.render('index', { title: 'Express' }); |
a970aad03a6e0730e08caf98982caf4fe5eb5e29 | test/unit/game_of_life.support.spec.js | test/unit/game_of_life.support.spec.js | describe('Support module', function () {
var S = GameOfLife.Support;
describe('For parsing canvas', function () {
it('throws InvalidArgument if given other than canvas element', function () {
expect(function () {
S.parseCanvas($('<p>foo</p>'));
}).toThrow(new S.InvalidArgument('Not a canvas element'));
});
});
});
| describe('Support module', function () {
var S = GameOfLife.Support;
describe('For validating canvas', function () {
it('throws InvalidArgument if given other than a canvas element', function () {
expect(function () {
S.validateCanvas($('<p>foo</p>')[0]);
}).toThrow(new S.InvalidArgument('Not a canvas element'));
});
it('returns the given element if the element is a canvas', function () {
expect(S.validateCanvas($('<canvas></canvas>')[0]).getContext).toBeFunction();
});
});
});
| Add unit tests for canvas validation | Add unit tests for canvas validation
| JavaScript | mit | tkareine/game_of_life,tkareine/game_of_life,tkareine/game_of_life | ---
+++
@@ -1,11 +1,15 @@
describe('Support module', function () {
var S = GameOfLife.Support;
- describe('For parsing canvas', function () {
- it('throws InvalidArgument if given other than canvas element', function () {
+ describe('For validating canvas', function () {
+ it('throws InvalidArgument if given other than a canvas element', function () {
expect(function () {
- S.parseCanvas($('<p>foo</p>'));
+ S.validateCanvas($('<p>foo</p>')[0]);
}).toThrow(new S.InvalidArgument('Not a canvas element'));
+ });
+
+ it('returns the given element if the element is a canvas', function () {
+ expect(S.validateCanvas($('<canvas></canvas>')[0]).getContext).toBeFunction();
});
});
}); |
89da8456cb272201d66ba059b8d6e63af6c13a97 | spec/util/config.js | spec/util/config.js | window.respokeTestConfig = {
baseURL: 'http://testing.digiumlabs.com:3001'
};
respoke.log.setLevel('silent');
window.doneOnceBuilder = function (done) {
var called = false;
return function (err) {
if (!called) {
called = true;
done(err);
}
};
};
window.doneCountBuilder = function (num, done) {
return (function () {
var called = false;
var count = 0;
if (!num || num < 0) {
throw new Error('First argument must be a positive integer.');
}
return function (err) {
if (called === true) {
return;
}
count += 1;
if (count === num || err) {
called = true;
done(err);
}
};
})();
};
| window.respokeTestConfig = {
baseURL: 'http://testing.digiumlabs.com:3001'
};
respoke.log.setLevel('silent');
window.doneOnceBuilder = function (done) {
var called = false;
return function (err) {
if (!called) {
called = true;
done(err);
}
};
};
// build a function which calls the done callback according to the following rules:
// 1. immediately if there is an error passed to it
// 2. when the function has been called $num times.
window.doneCountBuilder = function (num, done) {
return (function () {
var called = false;
var count = 0;
if (!num || num < 0) {
throw new Error('First argument must be a positive integer.');
}
return function (err) {
if (called === true) {
return;
}
count += 1;
if (count === num || err) {
called = true;
done(err);
}
};
})();
};
| Add an explanation detailing behavior of doneCountBuilder. | Add an explanation detailing behavior of doneCountBuilder.
| JavaScript | mit | respoke/respoke,respoke/respoke,respoke/respoke | ---
+++
@@ -12,6 +12,9 @@
};
};
+// build a function which calls the done callback according to the following rules:
+// 1. immediately if there is an error passed to it
+// 2. when the function has been called $num times.
window.doneCountBuilder = function (num, done) {
return (function () {
var called = false; |
4f0f14323f546e72e1d58c86710fc80b8c6129a3 | drops/strider/index.js | drops/strider/index.js | module.exports = function(scope, argv) {
return {
install: function (done) {
scope.applyConfig({
create: {
Image: "niallo/strider:latest",
},
start: {
PublishAllPorts: !!argv.publish
}
}, function (err) {
if (err) throw err;
scope.inspectContainer(function (err, data) {
if (err) throw err;
else {
var ip = data.NetworkSettings.IPAddress;
done(null, JSON.stringify({
ip_address: ip,
ports: data.NetworkSettings.Ports,
app: {
url: "http://"+ip+":3000",
email: "test@example.com",
password: "dontlook"
},
ssh: {
port: 22,
username: "strider",
password: "str!der",
notes: "Root access is prohibited by default through ssh. To get root access login as strider and su to root."
}
}, null, 2))
}
});
});
}
}
}
| module.exports = function(scope, argv) {
return {
install: function (done) {
scope.applyConfig({
create: {
Image: "niallo/strider:latest",
Env: {
/* https://github.com/Strider-CD/strider#configuring */
}
},
start: {
PublishAllPorts: !!argv.publish
}
}, function (err) {
if (err) throw err;
scope.inspectContainer(function (err, data) {
if (err) throw err;
else {
var ip = data.NetworkSettings.IPAddress;
done(null, JSON.stringify({
ip_address: ip,
ports: data.NetworkSettings.Ports,
app: {
url: "http://"+ip+":3000",
email: "test@example.com",
password: "dontlook"
},
ssh: {
port: 22,
username: "strider",
password: "str!der",
notes: "Root access is prohibited by default through ssh. To get root access login as strider and su to root."
}
}, null, 2))
}
});
});
}
}
}
| Add a note on env configuration | Add a note on env configuration
| JavaScript | isc | keyvanfatehi/ydm,kfatehi/ydm | ---
+++
@@ -4,6 +4,9 @@
scope.applyConfig({
create: {
Image: "niallo/strider:latest",
+ Env: {
+ /* https://github.com/Strider-CD/strider#configuring */
+ }
},
start: {
PublishAllPorts: !!argv.publish |
0b273ace2c3681814c9ca799f12482d99c27c015 | src/schema/rpc.js | src/schema/rpc.js | 'use strict';
const { reduceAsync, identity } = require('../utilities');
const { rpcHandlers } = require('../rpc');
// Returns a reducer function that takes the schema as input and output,
// and iterate over rpc-specific reduce functions
const getRpcReducer = function (name, postProcess) {
const processors = getProcessors({ name });
return rpcReducer.bind(null, { processors, postProcess });
};
const getProcessors = function ({ name }) {
return Object.values(rpcHandlers)
.map(rpcHandler => rpcHandler[name])
.filter(handler => handler);
};
const rpcReducer = function (
{ processors, postProcess = identity },
{ schema },
) {
return reduceAsync(
processors,
(schemaA, func) => func(schemaA),
schema,
(schemaA, schemaB) => postProcess({ ...schemaA, ...schemaB }),
);
};
// Apply rpc-specific compile-time logic
const rpcSchema = getRpcReducer('compileSchema');
// Apply rpc-specific startup logic
const rpcStartServer = getRpcReducer('startServer', schema => ({ schema }));
module.exports = {
rpcSchema,
rpcStartServer,
};
| 'use strict';
const { reduceAsync, identity } = require('../utilities');
const { rpcHandlers } = require('../rpc');
// Reducer function that takes the schema as input and output,
// and iterate over rpc-specific reduce functions
const rpcReducer = function ({ schema, processors, postProcess = identity }) {
return reduceAsync(
processors,
(schemaA, func) => func(schemaA),
schema,
(schemaA, schemaB) => postProcess({ ...schemaA, ...schemaB }),
);
};
// Apply rpc-specific compile-time logic
const rpcSchema = function ({ schema }) {
const processors = getProcessors({ name: 'compileSchema' });
return rpcReducer({ schema, processors });
};
// Apply rpc-specific startup logic
const rpcStartServer = function ({ schema }) {
const processors = getProcessors({ name: 'startServer' });
return rpcReducer({ schema, processors, postProcess: rpcStartServerProcess });
};
const getProcessors = function ({ name }) {
return Object.values(rpcHandlers)
.map(rpcHandler => rpcHandler[name])
.filter(handler => handler);
};
const rpcStartServerProcess = schema => ({ schema });
module.exports = {
rpcSchema,
rpcStartServer,
};
| Fix function names being lost in binding | Fix function names being lost in binding
| JavaScript | apache-2.0 | autoserver-org/autoserver,autoserver-org/autoserver | ---
+++
@@ -3,23 +3,9 @@
const { reduceAsync, identity } = require('../utilities');
const { rpcHandlers } = require('../rpc');
-// Returns a reducer function that takes the schema as input and output,
+// Reducer function that takes the schema as input and output,
// and iterate over rpc-specific reduce functions
-const getRpcReducer = function (name, postProcess) {
- const processors = getProcessors({ name });
- return rpcReducer.bind(null, { processors, postProcess });
-};
-
-const getProcessors = function ({ name }) {
- return Object.values(rpcHandlers)
- .map(rpcHandler => rpcHandler[name])
- .filter(handler => handler);
-};
-
-const rpcReducer = function (
- { processors, postProcess = identity },
- { schema },
-) {
+const rpcReducer = function ({ schema, processors, postProcess = identity }) {
return reduceAsync(
processors,
(schemaA, func) => func(schemaA),
@@ -29,10 +15,24 @@
};
// Apply rpc-specific compile-time logic
-const rpcSchema = getRpcReducer('compileSchema');
+const rpcSchema = function ({ schema }) {
+ const processors = getProcessors({ name: 'compileSchema' });
+ return rpcReducer({ schema, processors });
+};
// Apply rpc-specific startup logic
-const rpcStartServer = getRpcReducer('startServer', schema => ({ schema }));
+const rpcStartServer = function ({ schema }) {
+ const processors = getProcessors({ name: 'startServer' });
+ return rpcReducer({ schema, processors, postProcess: rpcStartServerProcess });
+};
+
+const getProcessors = function ({ name }) {
+ return Object.values(rpcHandlers)
+ .map(rpcHandler => rpcHandler[name])
+ .filter(handler => handler);
+};
+
+const rpcStartServerProcess = schema => ({ schema });
module.exports = {
rpcSchema, |
e53bbb5735497395d1ea4cb5a6c13db69792bd19 | scripts/nvim.js | scripts/nvim.js | /* eslint no-console:0 */
/**
* Spawns an embedded neovim instance and returns Neovim API
*/
const cp = require('child_process');
const attach = require('../attach');
// const inspect = require('util').inspect;
module.exports = (async function() {
let proc;
let socket;
if (process.env.NVIM_LISTEN_ADDRESS) {
socket = process.env.NVIM_LISTEN_ADDRESS;
} else {
proc = cp.spawn('nvim', ['-u', 'NONE', '-N', '--embed'], {
cwd: __dirname,
});
}
const nvim = await attach({ proc, socket });
return nvim;
}());
| /* eslint no-console:0 */
/**
* Spawns an embedded neovim instance and returns Neovim API
*/
const cp = require('child_process');
const attach = require('../').attach;
// const inspect = require('util').inspect;
module.exports = (async function() {
let proc;
let socket;
if (process.env.NVIM_LISTEN_ADDRESS) {
socket = process.env.NVIM_LISTEN_ADDRESS;
} else {
proc = cp.spawn('nvim', ['-u', 'NONE', '-N', '--embed'], {
cwd: __dirname,
});
}
const nvim = await attach({ proc, socket });
return nvim;
})();
| Fix import for api script | Fix import for api script
| JavaScript | mit | rhysd/node-client,neovim/node-client,neovim/node-client | ---
+++
@@ -5,7 +5,7 @@
*/
const cp = require('child_process');
-const attach = require('../attach');
+const attach = require('../').attach;
// const inspect = require('util').inspect;
module.exports = (async function() {
@@ -22,4 +22,4 @@
const nvim = await attach({ proc, socket });
return nvim;
-}());
+})(); |
ec886703ac80b1a5fef912123dd3a64411aab320 | bin/index.js | bin/index.js | #!/usr/bin/env node
'use strict';
// foreign modules
const meow = require('meow');
// local modules
const error = require('../lib/error.js');
const logger = require('../lib/utils/logger.js');
const main = require('../index.js');
// this module
const cli = meow({
help: main.help,
version: true
}, {
boolean: [
'only',
'prune',
'remote'
],
defaults: {
only: false,
prune: false,
remote: false
},
type: [ 'type' ]
});
main(cli.input, cli.flags)
.catch((err) => {
error.handle404(err);
error.handleOnlyNoMatches(err);
error.handleScopeContentMismatch(err);
error.handleScopeInvalid(err);
error.handleScopeNotSet(err);
logger.error(err);
process.exit(1);
});
| #!/usr/bin/env node
'use strict';
// foreign modules
const meow = require('meow');
// local modules
const error = require('../lib/error.js');
const logger = require('../lib/utils/logger.js');
const main = require('../index.js');
// this module
const cli = meow({
help: main.help,
version: true
}, {
flags: {
only: {type: 'boolean', default: false},
prune: {type: 'boolean', default: false},
remote: {type: 'boolean', default: false},
type: {type: 'string', default: 'madl'}
}
});
main(cli.input, cli.flags)
.catch((err) => {
error.handle404(err);
error.handleOnlyNoMatches(err);
error.handleScopeContentMismatch(err);
error.handleScopeInvalid(err);
error.handleScopeNotSet(err);
logger.error(err);
process.exit(1);
});
| Update meow options to be in line with v4.0.0 | Update meow options to be in line with v4.0.0
| JavaScript | bsd-3-clause | blinkmobile/bmp-cli | ---
+++
@@ -17,17 +17,12 @@
help: main.help,
version: true
}, {
- boolean: [
- 'only',
- 'prune',
- 'remote'
- ],
- defaults: {
- only: false,
- prune: false,
- remote: false
- },
- type: [ 'type' ]
+ flags: {
+ only: {type: 'boolean', default: false},
+ prune: {type: 'boolean', default: false},
+ remote: {type: 'boolean', default: false},
+ type: {type: 'string', default: 'madl'}
+ }
});
main(cli.input, cli.flags) |
9c9365a8dbefe86a2275311b6c54a552c9640816 | lib/rules/echidna/editor-ids.js | lib/rules/echidna/editor-ids.js | 'use strict';
exports.name = "echidna.editor-ids";
exports.check = function (sr, done) {
var editorIDs = sr.$('dd[data-editor-id]').map(function(index, element) {
var strId = sr.$(element).attr('data-editor-id');
// If the ID is not a digit-only string, it gets filtered out
if (/\d+/.test(strId)) return parseInt(strId, 10);
}).toArray();
sr.metadata('editorIDs', editorIDs);
if (editorIDs.length === 0) sr.error(exports.name, 'no-editor-id');
done();
};
| 'use strict';
exports.name = "echidna.editor-ids";
exports.check = function (sr, done) {
var editorIDs = sr.$('dd[data-editor-id]').map(function(index, element) {
var strId = sr.$(element).attr('data-editor-id');
// If the ID is not a digit-only string, it gets filtered out
if (/\d+/.test(strId)) return parseInt(strId, 10);
}).get();
sr.metadata('editorIDs', editorIDs);
if (editorIDs.length === 0) sr.error(exports.name, 'no-editor-id');
done();
};
| Replace cheerio's deprecated toArray() with get() | Replace cheerio's deprecated toArray() with get()
| JavaScript | mit | w3c/specberus,dontcallmedom/specberus,w3c/specberus,w3c/specberus,dontcallmedom/specberus | ---
+++
@@ -8,7 +8,7 @@
// If the ID is not a digit-only string, it gets filtered out
if (/\d+/.test(strId)) return parseInt(strId, 10);
- }).toArray();
+ }).get();
sr.metadata('editorIDs', editorIDs);
|
0a302a6a1f5bc93c999d25a3b9fdda9aa09b61ba | source/merge.js | source/merge.js | function merge(...args) {
let output = null,
items = [...args];
while (items.length > 0) {
const nextItem = items.shift();
if (!output) {
output = Object.assign({}, nextItem);
} else {
output = mergeObjects(output, nextItem);
}
}
return output;
}
function mergeObjects(obj1, obj2) {
const output = Object.assign({}, obj1);
Object.keys(obj2).forEach(key => {
if (!output.hasOwnProperty(key)) {
output[key] = obj2[key];
return;
}
if (Array.isArray(obj2[key])) {
output[key] = Array.isArray(output[key]) ? [...output[key], ...obj2[key]] : [...obj2[key]];
} else if (typeof obj2[key] === "object" && !!obj2[key]) {
output[key] =
typeof output[key] === "object" && !!output[key]
? mergeObjects(output[key], obj2[key])
: Object.assign({}, obj2[key]);
} else {
output[key] = obj2[key];
}
});
return output;
}
module.exports = {
merge
};
| function clone(obj) {
return Object.setPrototypeOf(Object.assign({}, obj), Object.getPrototypeOf(obj));
}
function merge(...args) {
let output = null,
items = [...args];
while (items.length > 0) {
const nextItem = items.shift();
if (!output) {
output = clone(nextItem);
} else {
output = mergeObjects(output, nextItem);
}
}
return output;
}
function mergeObjects(obj1, obj2) {
const output = clone(obj1);
Object.keys(obj2).forEach(key => {
if (!output.hasOwnProperty(key)) {
output[key] = obj2[key];
return;
}
if (Array.isArray(obj2[key])) {
output[key] = Array.isArray(output[key]) ? [...output[key], ...obj2[key]] : [...obj2[key]];
} else if (typeof obj2[key] === "object" && !!obj2[key]) {
output[key] =
typeof output[key] === "object" && !!output[key]
? mergeObjects(output[key], obj2[key])
: clone(obj2[key]);
} else {
output[key] = obj2[key];
}
});
return output;
}
module.exports = {
merge
};
| Fix merging objects with prototypes | Fix merging objects with prototypes
| JavaScript | mit | perry-mitchell/webdav-client,perry-mitchell/webdav-client | ---
+++
@@ -1,10 +1,14 @@
+function clone(obj) {
+ return Object.setPrototypeOf(Object.assign({}, obj), Object.getPrototypeOf(obj));
+}
+
function merge(...args) {
let output = null,
items = [...args];
while (items.length > 0) {
const nextItem = items.shift();
if (!output) {
- output = Object.assign({}, nextItem);
+ output = clone(nextItem);
} else {
output = mergeObjects(output, nextItem);
}
@@ -13,7 +17,7 @@
}
function mergeObjects(obj1, obj2) {
- const output = Object.assign({}, obj1);
+ const output = clone(obj1);
Object.keys(obj2).forEach(key => {
if (!output.hasOwnProperty(key)) {
output[key] = obj2[key];
@@ -25,7 +29,7 @@
output[key] =
typeof output[key] === "object" && !!output[key]
? mergeObjects(output[key], obj2[key])
- : Object.assign({}, obj2[key]);
+ : clone(obj2[key]);
} else {
output[key] = obj2[key];
} |
54aa153de51b8dffe6fa3c609b5727d843c81219 | app/ShoppingListController.js | app/ShoppingListController.js | angular.module('shoppingList').controller(
'ShoppingListController', ['$scope', '$window', function($scope, $window) {
'use strict';
var blankItem = {
name: '',
category: '',
quantity: '',
unit: '',
notes: ''
};
$scope.categories = [
'Baking',
'Beverages',
'Bread/Bakery',
'Canned Goods',
'Cereal/Breakfast',
'Condiments',
'Dairy',
'Deli',
'Frozen Foods',
'Meats',
'Non-Food',
'Pasta/Rice',
'Produce',
'Snacks',
'Spices'
];
$scope.categories.sort();
$scope.isEditing = true;
var now = new Date();
$scope.name = 'Shopping ' + now.getMonth() + '/' + now.getDate() + '/' + now.getFullYear();
$scope.listItems = [
angular.copy(blankItem)
];
$scope.addItem = function() {
$scope.listItems.push(angular.copy(blankItem));
};
$scope.removeItem = function(index) {
if ($window.confirm('Delete this item?')) {
$scope.listItems.splice(index, 1);
}
};
$scope.setEditMode = function(bool) {
$scope.isEditing = !!bool;
};
}]
);
| angular.module('shoppingList').controller(
'ShoppingListController', ['$scope', '$window', function($scope, $window) {
'use strict';
var blankItem = {
name: '',
category: '',
quantity: '',
unit: '',
notes: ''
};
$scope.categories = [
'Baking',
'Beverages',
'Bread/Bakery',
'Canned Goods',
'Cereal/Breakfast',
'Condiments',
'Dairy',
'Deli',
'Frozen Foods',
'Meats',
'Non-Food',
'Pasta/Rice',
'Produce',
'Snacks',
'Spices'
];
$scope.categories.sort();
$scope.isEditing = true;
var now = new Date();
$scope.name = 'Shopping ' + (now.getMonth() + 1) + '/' + now.getDate() + '/' + now.getFullYear();
$scope.listItems = [
angular.copy(blankItem)
];
$scope.addItem = function() {
$scope.listItems.push(angular.copy(blankItem));
};
$scope.removeItem = function(index) {
if ($window.confirm('Delete this item?')) {
$scope.listItems.splice(index, 1);
}
};
$scope.setEditMode = function(bool) {
$scope.isEditing = !!bool;
};
}]
);
| Fix month in list name. | Fix month in list name.
| JavaScript | apache-2.0 | eheikes/shopping-list,eheikes/shopping-list | ---
+++
@@ -32,7 +32,7 @@
$scope.isEditing = true;
var now = new Date();
- $scope.name = 'Shopping ' + now.getMonth() + '/' + now.getDate() + '/' + now.getFullYear();
+ $scope.name = 'Shopping ' + (now.getMonth() + 1) + '/' + now.getDate() + '/' + now.getFullYear();
$scope.listItems = [
angular.copy(blankItem) |
2984c139a235a206c25b5c959edca77d2a10fe97 | ui/spec/utils/formattingSpec.js | ui/spec/utils/formattingSpec.js | import {formatBytes, formatRPDuration} from 'utils/formatting';
describe('Formatting helpers', () => {
describe('formatBytes', () => {
it('returns null when passed a falsey value', () => {
const actual = formatBytes(null);
expect(actual).to.equal(null);
});
it('returns the correct value when passed 0', () => {
const actual = formatBytes(0);
expect(actual).to.equal('0 Bytes');
});
it('converts a raw byte value into it\'s most appropriate unit', () => {
expect(formatBytes(1000)).to.equal('1 KB');
expect(formatBytes(1000000)).to.equal('1 MB');
expect(formatBytes(1000000000)).to.equal('1 GB');
});
});
describe('formatRPDuration', () => {
it("returns 'infinite' for a retention policy with a value of '0'", () => {
const actual = formatRPDuration('0')
expect(actual).to.equal('infinite');
});
it('correctly formats retention policy durations', () => {
expect(formatRPDuration('24h0m0s')).to.equal('24h');
expect(formatRPDuration('168h0m0s')).to.equal('7d');
expect(formatRPDuration('200h32m3s')).to.equal('8d8h32m3s');
});
});
});
| import {formatBytes, formatRPDuration} from 'utils/formatting';
describe('Formatting helpers', () => {
describe('formatBytes', () => {
it('returns null when passed a falsey value', () => {
const actual = formatBytes(null);
expect(actual).to.equal(null);
});
it('returns the correct value when passed 0', () => {
const actual = formatBytes(0);
expect(actual).to.equal('0 Bytes');
});
it('converts a raw byte value into it\'s most appropriate unit', () => {
expect(formatBytes(1000)).to.equal('1 KB');
expect(formatBytes(1000000)).to.equal('1 MB');
expect(formatBytes(1000000000)).to.equal('1 GB');
});
});
describe('formatRPDuration', () => {
it("returns 'infinite' for a retention policy with a value of '0'", () => {
const actual = formatRPDuration('0')
expect(actual).to.equal('∞');
});
it('correctly formats retention policy durations', () => {
expect(formatRPDuration('24h0m0s')).to.equal('24h');
expect(formatRPDuration('168h0m0s')).to.equal('7d');
expect(formatRPDuration('200h32m3s')).to.equal('8d8h32m3s');
});
});
});
| Fix test to use ∞ | Fix test to use ∞
| JavaScript | agpl-3.0 | brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf | ---
+++
@@ -25,7 +25,7 @@
it("returns 'infinite' for a retention policy with a value of '0'", () => {
const actual = formatRPDuration('0')
- expect(actual).to.equal('infinite');
+ expect(actual).to.equal('∞');
});
it('correctly formats retention policy durations', () => { |
ecdd9c40790cfde9aa3e723d9cb206f61f8fa9f4 | ui/src/common/services/index.js | ui/src/common/services/index.js | import alertsSvc from './Alerts.js';
import auditLogsSvc from './AuditLogs.js';
import authSvc from './Authorization.js';
import exportSvc from './ExportService.js';
import exprUtil from './ExpressionUtil.js';
import fieldFactory from './FieldFactory.js';
import formUtil from './FormUtil.js';
import http from './HttpClient.js';
import itemsSvc from './ItemsHolder.js';
import pluginLoader from './PluginLoader.js';
import pluginViews from './PluginViewsRegistry.js';
import routerSvc from './Router.js';
import utility from './Utility.js';
export default {
install(app) {
let osSvc = app.config.globalProperties.$osSvc = app.config.globalProperties.$osSvc || {};
Object.assign(osSvc, {
alertsSvc: alertsSvc,
auditLogsSvc: auditLogsSvc,
authSvc: authSvc,
exportSvc: exportSvc,
exprUtil: exprUtil,
fieldFactory: fieldFactory,
formUtil: formUtil,
http: http,
itemsSvc: itemsSvc,
pluginLoader: pluginLoader,
pluginViews: pluginViews,
routerSvc: routerSvc,
utility: utility
});
}
}
| import alertsSvc from './Alerts.js';
import auditLogsSvc from './AuditLogs.js';
import authSvc from './Authorization.js';
import exportSvc from './ExportService.js';
import exprUtil from './ExpressionUtil.js';
import fieldFactory from './FieldFactory.js';
import formUtil from './FormUtil.js';
import http from './HttpClient.js';
import itemsSvc from './ItemsHolder.js';
import pluginLoader from './PluginLoader.js';
import pluginViews from './PluginViewsRegistry.js';
import routerSvc from './Router.js';
export default {
install(app) {
let osSvc = app.config.globalProperties.$osSvc = app.config.globalProperties.$osSvc || {};
Object.assign(osSvc, {
alertsSvc: alertsSvc,
auditLogsSvc: auditLogsSvc,
authSvc: authSvc,
exportSvc: exportSvc,
exprUtil: exprUtil,
fieldFactory: fieldFactory,
formUtil: formUtil,
http: http,
itemsSvc: itemsSvc,
pluginLoader: pluginLoader,
pluginViews: pluginViews,
routerSvc: routerSvc
});
}
}
| Build fixes. Removed the unused utility class. | Build fixes.
Removed the unused utility class.
| JavaScript | bsd-3-clause | krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen | ---
+++
@@ -10,7 +10,6 @@
import pluginLoader from './PluginLoader.js';
import pluginViews from './PluginViewsRegistry.js';
import routerSvc from './Router.js';
-import utility from './Utility.js';
export default {
install(app) {
@@ -27,8 +26,7 @@
itemsSvc: itemsSvc,
pluginLoader: pluginLoader,
pluginViews: pluginViews,
- routerSvc: routerSvc,
- utility: utility
+ routerSvc: routerSvc
});
}
} |
5e4c0f322cfa7a776e6c12807e7c1b67e3846234 | geogoose/util.js | geogoose/util.js | var mongoose = require('mongoose'),
_ = require('cloneextend'),
adHocModels = {};
var adHocModel = function(collectionName, Schema, options) {
if (!adHocModels[collectionName]) {
var options = options || {};
if (options.strict == undefined) {
options.strict = false;
}
var Schema = Schema || new mongoose.Schema({}, options);
adHocModels[collectionName] = mongoose.model(
'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName);
}
return adHocModels[collectionName];
};
/*
Modifies the JSON object to be sent to the client as GeoJSON
*/
var toGeoJSON = function(obj)
{
delete obj.bounds2d;
return obj;
};
module.exports = {
adHocModel: adHocModel,
toGeoJSON: toGeoJSON
}; | var mongoose = require('mongoose'),
_ = require('cloneextend'),
adHocModels = {};
var adHocModel = function(collectionName, Schema, options) {
if (!adHocModels[collectionName]) {
var options = options || {};
if (options.strict == undefined) {
options.strict = false;
}
var Schema = Schema || new mongoose.Schema({}, options);
adHocModels[collectionName] = mongoose.model(
'adhoc_' + new mongoose.Types.ObjectId().toString(), Schema, collectionName);
}
return adHocModels[collectionName];
};
/*
Modifies the JSON object to be sent to the client as GeoJSON
*/
var toGeoJSON = function(obj)
{
delete obj.bounds2d;
if (obj.bbox && !obj.bbox.length && obj.geometry.type == 'Point') {
obj.bbox = [
obj.geometry.coordinates[0], obj.geometry.coordinates[1],
obj.geometry.coordinates[0], obj.geometry.coordinates[1]
];
}
return obj;
};
module.exports = {
adHocModel: adHocModel,
toGeoJSON: toGeoJSON
}; | Send bbox for Point features | Send bbox for Point features
| JavaScript | mit | nickbenes/GeoSense,nickbenes/GeoSense,nickbenes/GeoSense,nickbenes/GeoSense,nickbenes/GeoSense,nickbenes/GeoSense | ---
+++
@@ -22,6 +22,12 @@
var toGeoJSON = function(obj)
{
delete obj.bounds2d;
+ if (obj.bbox && !obj.bbox.length && obj.geometry.type == 'Point') {
+ obj.bbox = [
+ obj.geometry.coordinates[0], obj.geometry.coordinates[1],
+ obj.geometry.coordinates[0], obj.geometry.coordinates[1]
+ ];
+ }
return obj;
};
|
30f4b78c463b42973eef5779dfabea760232f22d | lib/util/createTransition.js | lib/util/createTransition.js | /* @flow */
import matchRoutePattern from 'match-route-pattern'
import type {
Screen,
Transition,
TransitionHandler,
Location,
QueryParameters
} from '../types'
export default function createTransition(pattern: string, handler: TransitionHandler): Transition {
return function transition(location: Location): Promise<?Screen> {
var queryParameters: ?QueryParameters = matchRoutePattern(pattern, location.pathname + location.search)
if (!queryParameters) {
return Promise.resolve(undefined)
}
return handler(queryParameters)
.then(screen => screen) // Flow fix
}
}
| /* @flow */
import matchRoutePattern from 'match-route-pattern'
import type {
Screen,
Transition,
TransitionHandler,
Location,
QueryParameters
} from '../types'
export default function createTransition(pattern: string, handler: TransitionHandler): Transition {
return function transition(location: Location): Promise<?Screen> {
var queryParameters: ?QueryParameters = matchRoutePattern(pattern, location.pathname + location.search)
if (!queryParameters) {
return Promise.resolve(undefined)
}
return Promise.resolve(handler(queryParameters))
.then(screen => screen) // Flow fix
}
}
| Allow to return raw data from transition handler | Allow to return raw data from transition handler
| JavaScript | mit | vslinko/vstack-router | ---
+++
@@ -18,7 +18,7 @@
return Promise.resolve(undefined)
}
- return handler(queryParameters)
+ return Promise.resolve(handler(queryParameters))
.then(screen => screen) // Flow fix
}
} |
2439e002bf97aa5dd2086bc9d6cccc500b35a07f | load/mediator/tcp-handler.js | load/mediator/tcp-handler.js | 'use strict'
const BodyStream = require('./body-stream')
exports.handleBodyRequest = (conn) => {
new BodyStream(1024).pipe(conn)
}
| 'use strict'
const BodyStream = require('./body-stream')
exports.handleBodyRequest = (conn) => {
const length = 1024 * 1024
conn.write('HTTP/1.1 200 OK\n')
conn.write('Content-Type: text/plain\n')
conn.write('\n')
new BodyStream(length).pipe(conn)
}
| Send HTTP response on TCP channel | Send HTTP response on TCP channel
The load testing tools don't support plain TCP.
OHM-556
| JavaScript | mpl-2.0 | jembi/openhim-core-js,jembi/openhim-core-js | ---
+++
@@ -3,5 +3,9 @@
const BodyStream = require('./body-stream')
exports.handleBodyRequest = (conn) => {
- new BodyStream(1024).pipe(conn)
+ const length = 1024 * 1024
+ conn.write('HTTP/1.1 200 OK\n')
+ conn.write('Content-Type: text/plain\n')
+ conn.write('\n')
+ new BodyStream(length).pipe(conn)
} |
4aabc4665ec47172415ea66e2593840a50b08ceb | scripts/test-e2e.js | scripts/test-e2e.js | const _ = require('lodash');
const exec = require('shell-utils').exec;
const android = _.includes(process.argv, '--android');
const release = _.includes(process.argv, '--release');
const skipBuild = _.includes(process.argv, '--skipBuild');
run();
function run() {
const platform = android ? `android` : `ios`;
const prefix = android ? `android.emu` : `ios.sim`;
const suffix = release ? `release` : `debug`;
const configuration = `${prefix}.${suffix}`;
const cleanup = process.env.JENKINS_CI ? `--cleanup` : ``;
if (!skipBuild) {
exec.execSync(`detox build --configuration ${configuration}`);
}
exec.execSync(`detox test --configuration ${configuration} --platform ${platform} ${cleanup}`);
}
| const _ = require('lodash');
const exec = require('shell-utils').exec;
const android = _.includes(process.argv, '--android');
const release = _.includes(process.argv, '--release');
const skipBuild = _.includes(process.argv, '--skipBuild');
const headless = _.includes(process.argv, '--headless');
run();
function run() {
const platform = android ? `android` : `ios`;
const prefix = android ? `android.emu` : `ios.sim`;
const suffix = release ? `release` : `debug`;
const configuration = `${prefix}.${suffix}`;
const cleanup = process.env.CI ? `--cleanup` : ``;
const headless$ = android ? headless ? `--headless` : `` : ``;
if (!skipBuild) {
exec.execSync(`detox build --configuration ${configuration}`);
}
exec.execSync(`detox test --configuration ${configuration} --platform ${platform} ${cleanup} ${headless$}`);
}
| Add headless option to e2e android | Add headless option to e2e android
| JavaScript | mit | ceyhuno/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,guyca/react-native-navigation,Jpoliachik/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,3sidedcube/react-native-navigation,3sidedcube/react-native-navigation,chicojasl/react-native-navigation,guyca/react-native-navigation,3sidedcube/react-native-navigation,Jpoliachik/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,Jpoliachik/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,Jpoliachik/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation | ---
+++
@@ -4,18 +4,20 @@
const android = _.includes(process.argv, '--android');
const release = _.includes(process.argv, '--release');
const skipBuild = _.includes(process.argv, '--skipBuild');
+const headless = _.includes(process.argv, '--headless');
run();
function run() {
- const platform = android ? `android` : `ios`;
- const prefix = android ? `android.emu` : `ios.sim`;
- const suffix = release ? `release` : `debug`;
- const configuration = `${prefix}.${suffix}`;
- const cleanup = process.env.JENKINS_CI ? `--cleanup` : ``;
+ const platform = android ? `android` : `ios`;
+ const prefix = android ? `android.emu` : `ios.sim`;
+ const suffix = release ? `release` : `debug`;
+ const configuration = `${prefix}.${suffix}`;
+ const cleanup = process.env.CI ? `--cleanup` : ``;
+ const headless$ = android ? headless ? `--headless` : `` : ``;
- if (!skipBuild) {
- exec.execSync(`detox build --configuration ${configuration}`);
- }
- exec.execSync(`detox test --configuration ${configuration} --platform ${platform} ${cleanup}`);
+ if (!skipBuild) {
+ exec.execSync(`detox build --configuration ${configuration}`);
+ }
+ exec.execSync(`detox test --configuration ${configuration} --platform ${platform} ${cleanup} ${headless$}`);
} |
0b527145181bc9f8aecf6a3f49eac23bccfba7eb | src/index.js | src/index.js | /* eslint-env browser */
import {findSingleNode, getFindDOMNode} from './helpers';
let findDOMNode = findDOMNode || (global && global.findDOMNode);
function haveComponentWithXpath(component, expression) {
findDOMNode = findDOMNode || getFindDOMNode();
const domNode = findDOMNode(component);
document.body.appendChild(domNode);
const xpathNode = findSingleNode(expression, domNode.parentNode);
document.body.removeChild(domNode);
return xpathNode !== null;
}
export default function haveXpath(Chai) {
Chai.Assertion.addMethod('xpath', function evaluateXpath(xpath) {
findDOMNode = findDOMNode || getFindDOMNode();
const dom = findDOMNode(this._obj).outerHTML;
this.assert(
haveComponentWithXpath(this._obj, xpath),
'Expected "' + dom + '" to have xpath \'' + xpath + '\'',
'Expected "' + dom + '" to not have xpath \'' + xpath + '\''
);
});
}
| /* eslint-env browser */
import {findSingleNode, getFindDOMNode} from './helpers';
let findDOMNode = findDOMNode || (global && global.findDOMNode);
function haveDomNodeWithXpath(domNode, expression) {
document.body.appendChild(domNode);
const xpathNode = findSingleNode(expression, domNode.parentNode);
document.body.removeChild(domNode);
return xpathNode !== null;
}
export default function haveXpath(Chai) {
Chai.Assertion.addMethod('xpath', function evaluateXpath(xpath) {
findDOMNode = findDOMNode || getFindDOMNode();
const domNode = findDOMNode(this._obj);
this.assert(
haveDomNodeWithXpath(domNode, xpath),
'Expected "' + domNode.outerHTML + '" to have xpath \'' + xpath + '\'',
'Expected "' + domNode.outerHTML + '" to not have xpath \'' + xpath + '\''
);
});
}
| Remove unnecessary call to findDOMNode | fix: Remove unnecessary call to findDOMNode
| JavaScript | mit | relekang/chai-have-xpath,davija/chai-have-xpath | ---
+++
@@ -3,10 +3,7 @@
let findDOMNode = findDOMNode || (global && global.findDOMNode);
-function haveComponentWithXpath(component, expression) {
- findDOMNode = findDOMNode || getFindDOMNode();
- const domNode = findDOMNode(component);
-
+function haveDomNodeWithXpath(domNode, expression) {
document.body.appendChild(domNode);
const xpathNode = findSingleNode(expression, domNode.parentNode);
document.body.removeChild(domNode);
@@ -18,12 +15,12 @@
Chai.Assertion.addMethod('xpath', function evaluateXpath(xpath) {
findDOMNode = findDOMNode || getFindDOMNode();
- const dom = findDOMNode(this._obj).outerHTML;
+ const domNode = findDOMNode(this._obj);
this.assert(
- haveComponentWithXpath(this._obj, xpath),
- 'Expected "' + dom + '" to have xpath \'' + xpath + '\'',
- 'Expected "' + dom + '" to not have xpath \'' + xpath + '\''
+ haveDomNodeWithXpath(domNode, xpath),
+ 'Expected "' + domNode.outerHTML + '" to have xpath \'' + xpath + '\'',
+ 'Expected "' + domNode.outerHTML + '" to not have xpath \'' + xpath + '\''
);
});
} |
a0651499089a9cb5648b08713dc6f298ea667f94 | src/index.js | src/index.js | import Client from './client'
import PullRequests from './pulls'
import Repositories from './repos'
import PageLinks from './paging'
export default function (config) {
return new Client(config, {
PullRequests,
Repositories,
PageLinks
})
}
| import Client from './client'
import Branches from './branches'
import Issues from './issues'
import PullRequests from './pulls'
import Repositories from './repos'
import PageLinks from './paging'
export default function (config) {
return new Client(config, {
Branches,
Issues,
PullRequests,
Repositories,
PageLinks
})
}
| Add branches and issues to the api | Add branches and issues to the api
| JavaScript | mit | jamsinclair/github-lite | ---
+++
@@ -1,10 +1,14 @@
import Client from './client'
+import Branches from './branches'
+import Issues from './issues'
import PullRequests from './pulls'
import Repositories from './repos'
import PageLinks from './paging'
export default function (config) {
return new Client(config, {
+ Branches,
+ Issues,
PullRequests,
Repositories,
PageLinks |
6b8328476ac25514dba5204ee3e3fbe423539fd0 | src/index.js | src/index.js | import React, { Component } from 'react';
import ReactDom from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
// const API_KEY = 'PLACE_YOUR_API_KEY_HERE';
class App extends Component {
constructor (props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => {
console.log(videos);
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render () {
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
videos={this.state.videos}
onVideoSelect={selectedVideo => this.setState({selectedVideo})}
/>
</div>
);
}
}
ReactDom.render(<App />, document.querySelector('.container')); | import React, { Component } from 'react';
import ReactDom from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
import file from './variables.js';
// const API_KEY = 'PLACE_YOUR_API_KEY_HERE';
const API_KEY = file.data;
class App extends Component {
constructor (props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
YTSearch({key: API_KEY, term: 'dragonball super'}, (videos) => {
console.log(videos);
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render () {
return (
<div>
<SearchBar />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
videos={this.state.videos}
onVideoSelect={selectedVideo => this.setState({selectedVideo})}
/>
</div>
);
}
}
ReactDom.render(<App />, document.querySelector('.container')); | Add import for variables file, set a const API_KEY as the data from variables file. | Add import for variables file, set a const API_KEY as the data from variables file.
| JavaScript | mit | JosephLeon/redux-simple-starter-tutorial,JosephLeon/redux-simple-starter-tutorial | ---
+++
@@ -4,7 +4,9 @@
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
+import file from './variables.js';
// const API_KEY = 'PLACE_YOUR_API_KEY_HERE';
+const API_KEY = file.data;
class App extends Component {
constructor (props) { |
1b3b3c836cf46b5dcf108560d116d9555860c835 | src/input.js | src/input.js | // Kind of like a singleton
const Keyboard = {
"KEY_UP": 38,
"KEY_DOWN": 40,
"KEY_LEFT": 37,
"KEY_RIGHT": 39,
"KEY_W": 87,
"KEY_A": 65,
"KEY_D": 68,
"KEY_SPACE": 32,
"keys": [],
"keydown_handler": function(evt) {
Keyboard.keys[evt.keyCode] = true;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
evt.keyCode == Keyboard.KEY_LEFT ||
evt.keyCode == Keyboard.KEY_RIGHT
)
evt.preventDefault();
},
"keyup_handler": function(evt) {
//TODO: Remove from array to minimise memory consumption.
Keyboard.keys[evt.keyCode] = false;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
evt.keyCode == Keyboard.KEY_LEFT ||
evt.keyCode == Keyboard.KEY_RIGHT
)
evt.preventDefault();
},
"pressed": function(keyCode) {
return Keyboard.keys[keyCode] === true;
}
}
| // Kind of like a singleton
const Keyboard = {
"KEY_ESC": 27,
"KEY_UP": 38,
"KEY_DOWN": 40,
"KEY_LEFT": 37,
"KEY_RIGHT": 39,
"KEY_W": 87,
"KEY_A": 65,
"KEY_D": 68,
"KEY_SPACE": 32,
"keys": [],
"nKeysDown": 0,
"keydown_handler": function(evt) {
Keyboard.nKeysDown ++;
Keyboard.keys[evt.keyCode] = true;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
evt.keyCode == Keyboard.KEY_LEFT ||
evt.keyCode == Keyboard.KEY_RIGHT
)
evt.preventDefault();
},
"keyup_handler": function(evt) {
//TODO: Remove from array to minimise memory consumption.
this.nKeysDown --;
Keyboard.keys[evt.keyCode] = false;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
evt.keyCode == Keyboard.KEY_LEFT ||
evt.keyCode == Keyboard.KEY_RIGHT
)
evt.preventDefault();
},
"pressed": function(keyCode) {
return Keyboard.keys[keyCode] === true;
},
"anyKeyDown": function() {
return Keyboard.nKeysDown > 0;
}
}
| Add any key test and ESC constant | Add any key test and ESC constant
| JavaScript | mpl-2.0 | nikosandronikos/spacebattle,nikosandronikos/spacebattle | ---
+++
@@ -1,5 +1,6 @@
// Kind of like a singleton
const Keyboard = {
+ "KEY_ESC": 27,
"KEY_UP": 38,
"KEY_DOWN": 40,
"KEY_LEFT": 37,
@@ -9,7 +10,9 @@
"KEY_D": 68,
"KEY_SPACE": 32,
"keys": [],
+ "nKeysDown": 0,
"keydown_handler": function(evt) {
+ Keyboard.nKeysDown ++;
Keyboard.keys[evt.keyCode] = true;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
@@ -20,6 +23,7 @@
},
"keyup_handler": function(evt) {
//TODO: Remove from array to minimise memory consumption.
+ this.nKeysDown --;
Keyboard.keys[evt.keyCode] = false;
if (evt.keyCode == Keyboard.KEY_UP ||
evt.keyCode == Keyboard.KEY_DOWN ||
@@ -30,5 +34,8 @@
},
"pressed": function(keyCode) {
return Keyboard.keys[keyCode] === true;
+ },
+ "anyKeyDown": function() {
+ return Keyboard.nKeysDown > 0;
}
} |
9d90cb8c5f2b2b38c85bb80fe96cab2b6037d35c | lib/kill-ring.js | lib/kill-ring.js | /* global atom:true */
const _ = require('underscore-plus');
const clipboard = atom.clipboard;
module.exports =
class KillRing {
constructor(limit=16) {
this.buffer = [];
this.sealed = true;
this.limit = limit;
}
put(texts, forward=true) {
if(this.sealed)
this.push(texts);
else
this.update(texts, forward);
}
seal() {
this.sealed = true;
}
push(texts) {
this.buffer.push(texts);
clipboard.write(texts.join('\n'));
if(this.buffer.length > this.limit) this.buffer.shift();
this.sealed = false;
}
update(texts, forward) {
const lasts = this.buffer.pop();
const newTexts = texts.map((t,i) => forward ? lasts[i]+(t?t:'') : (t?t:'')+lasts[i]);
this.push(newTexts);
}
top() {
this.updateBuffer();
return this.buffer.slice(-1)[0];
}
updateBuffer() {
const lasts = this.buffer.slice(-1)[0];
if(clipboard.md5(lasts?lasts.join('\n'):'') != clipboard.signatureForMetadata)
this.push(clipboard.read());
}
};
| /* global atom:true */
const clipboard = atom.clipboard;
module.exports =
class KillRing {
constructor(limit=16) {
this.buffer = [];
this.sealed = true;
this.limit = limit;
}
put(texts, forward=true) {
if(this.sealed)
this.push(texts);
else
this.update(texts, forward);
}
seal() {
this.sealed = true;
}
push(texts) {
this.buffer.push(texts);
clipboard.write(texts.join('\n'));
if(this.buffer.length > this.limit) this.buffer.shift();
this.sealed = false;
}
update(texts, forward) {
const lasts = this.buffer.pop();
const newTexts = texts.map((t,i) => forward ? lasts[i]+(t?t:'') : (t?t:'')+lasts[i]);
this.push(newTexts);
}
top() {
this.updateBuffer();
return this.buffer.slice(-1)[0];
}
updateBuffer() {
const lasts = this.buffer.slice(-1)[0];
if(clipboard.md5(lasts?lasts.join('\n'):'') != clipboard.signatureForMetadata)
this.push(clipboard.read());
}
};
| Remove the requirement no longer being used | Remove the requirement no longer being used
| JavaScript | mit | yasuyuky/transient-emacs,yasuyuky/transient-emacs | ---
+++
@@ -1,5 +1,4 @@
/* global atom:true */
-const _ = require('underscore-plus');
const clipboard = atom.clipboard;
module.exports = |
535f14e8f463ce81d360204fde459c3ca3e49f97 | src/elemental.js | src/elemental.js | (function(ns) {
var namespaces = [this];
var attachBehavior = function($element, behavior) {
var fn = namespaces;
behavior.replace(/([^.]+)/g, function(object) {
if(fn === namespaces) {
for(var nextFn, index = 0; index < fn.length; ++index) {
nextFn = fn[index][object];
if(nextFn) {
fn = nextFn;
break;
}
}
} else if(typeof fn === 'object') {
fn = fn[object];
}
});
if(typeof fn === 'function') {
return fn($element);
} else {
if (window.console && console.warn) {
console.warn("elementalJS: Unable to find behavior:", behavior);
}
}
};
ns.load = function(container) {
var $selector;
if (container === document) {
$selector = $('[data-behavior]');
}
else {
$selector = $(container).find("*").andSelf().filter("[data-behavior]");
}
$selector.each(function(index, element) {
var $element = $(element);
var behaviors = $element.data('behavior');
behaviors.replace(/([^ ]+)/g, function(behavior) {
attachBehavior($element, behavior);
});
});
};
ns.addNamespace = function(namespace) {
namespaces.push(namespace);
};
})(window.Elemental = {});
| (function(ns) {
var namespaces = [this];
var attachBehavior = function($element, behavior) {
var fn = namespaces;
behavior.replace(/([^.]+)/g, function(object) {
if(fn === namespaces) {
for(var nextFn, index = 0; index < fn.length; ++index) {
nextFn = fn[index][object];
if(nextFn) {
fn = nextFn;
break;
}
}
} else if(typeof fn === 'object') {
fn = fn[object];
}
});
if(typeof fn === 'function') {
return fn($element);
} else {
if (window.console && console.warn) {
console.warn("elementalJS: Unable to find behavior:", behavior);
}
}
};
ns.load = function(container) {
var $selector;
$selector = $('[data-behavior]', container)
if ($(container).data('behavior')) {
$selector = $selector.add(container);
}
$selector.each(function(index, element) {
var $element = $(element);
var behaviors = $element.data('behavior');
behaviors.replace(/([^ ]+)/g, function(behavior) {
attachBehavior($element, behavior);
});
});
};
ns.addNamespace = function(namespace) {
namespaces.push(namespace);
};
})(window.Elemental = {});
| Improve perfomance on large DOMs when container is not whole document. | Improve perfomance on large DOMs when container is not whole document.
| JavaScript | mit | elementaljs/elementaljs,elementaljs/elementaljs | ---
+++
@@ -30,11 +30,10 @@
ns.load = function(container) {
var $selector;
- if (container === document) {
- $selector = $('[data-behavior]');
- }
- else {
- $selector = $(container).find("*").andSelf().filter("[data-behavior]");
+ $selector = $('[data-behavior]', container)
+
+ if ($(container).data('behavior')) {
+ $selector = $selector.add(container);
}
$selector.each(function(index, element) { |
822a4132d2bb0e85372e8f7790b9bd4db9c5f17e | test/pnut.js | test/pnut.js | const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const nock = require('nock');
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;
const pnut = require('../lib/pnut');
describe('The pnut API wrapper', function () {
before(function() {
let root = 'https://api.pnut.io'
nock(root)
.get('/v0')
.reply(200, {})
nock(root)
.get('/v0/posts/streams/global')
.reply(200, {posts: 1})
});
after(function() {
nock.cleanAll();
});
it('should get the global timeline', function() {;
return pnut.global().should.become({'posts': 1})
});
}); | const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const nock = require('nock');
chai.use(chaiAsPromised);
chai.should();
const expect = chai.expect;
const pnut = require('../lib/pnut');
describe('The pnut API wrapper', function () {
before(function() {
let base = 'https://api.pnut.io';
nock(base)
.get('/v0')
.reply(200, {})
nock(base)
.get('/v0/posts/streams/global')
.reply(200, {posts: 1})
});
after(function() {
nock.cleanAll();
});
it('should get the global timeline', function() {;
return pnut.global().should.become({'posts': 1})
});
}); | Rename variable for more consitency | Rename variable for more consitency
| JavaScript | mit | kaiwood/pnut-butter | ---
+++
@@ -11,12 +11,13 @@
describe('The pnut API wrapper', function () {
before(function() {
- let root = 'https://api.pnut.io'
- nock(root)
+ let base = 'https://api.pnut.io';
+
+ nock(base)
.get('/v0')
.reply(200, {})
- nock(root)
+ nock(base)
.get('/v0/posts/streams/global')
.reply(200, {posts: 1})
}); |
ee239ef4415590d899a71d8e42038a8bcd831f18 | test/test.js | test/test.js | var assert = require('assert');
var configMergeLoader = require('../index.js');
describe('configMergeLoader', function() {
it('should return an function', function() {
assert.equal(typeof configMergeLoader, 'function');
});
});
| var assert = require('assert');
var configMergeLoader = require('../index.js');
describe('configMergeLoader', function() {
it('should return an function', function() {
assert.equal(typeof configMergeLoader, 'function');
});
describe('the function', function() {
var mergedObj = configMergeLoader();
it('should return an object', function() {
assert.equal(typeof mergedObj, 'object');
});
});
});
| Test that function returns and object | Test that function returns and object
| JavaScript | mit | bitfyre/config-merge-loader | ---
+++
@@ -5,4 +5,12 @@
it('should return an function', function() {
assert.equal(typeof configMergeLoader, 'function');
});
+
+ describe('the function', function() {
+ var mergedObj = configMergeLoader();
+
+ it('should return an object', function() {
+ assert.equal(typeof mergedObj, 'object');
+ });
+ });
}); |
7b13df50ef46ddad708f0fd38c5d7f2891a1c56b | src/application/application.js | src/application/application.js | import $ from 'jquery';
import Radio from 'backbone.radio';
import nprogress from 'nprogress';
import Application from '../common/application';
import LayoutView from './layout-view';
let routerChannel = Radio.channel('router');
nprogress.configure({
showSpinner: false
});
export default Application.extend({
initialize() {
this.$body = $(document.body);
this.layout = new LayoutView();
this.layout.render();
this.listenTo(routerChannel, {
'before:enter:route' : this.onBeforeEnterRoute,
'enter:route' : this.onEnterRoute,
'error:route' : this.onErrorRoute
});
},
onBeforeEnterRoute() {
this.transitioning = true;
// Don't show for synchronous route changes
setTimeout(() => {
if (this.transitioning) {
nprogress.start();
}
}, 0);
},
onEnterRoute() {
this.transitioning = false;
this.$body.scrollTop(0);
nprogress.done();
},
onErrorRoute() {
this.transitioning = false;
nprogress.done(true);
}
});
| import $ from 'jquery';
import _ from 'lodash';
import Radio from 'backbone.radio';
import nprogress from 'nprogress';
import Application from '../common/application';
import LayoutView from './layout-view';
let routerChannel = Radio.channel('router');
nprogress.configure({
showSpinner: false
});
export default Application.extend({
initialize() {
this.$body = $(document.body);
this.layout = new LayoutView();
this.layout.render();
this.listenTo(routerChannel, {
'before:enter:route' : this.onBeforeEnterRoute,
'enter:route' : this.onEnterRoute,
'error:route' : this.onErrorRoute
});
},
onBeforeEnterRoute() {
this.transitioning = true;
// Don't show for synchronous route changes
_.defer(() => {
if (this.transitioning) {
nprogress.start();
}
});
},
onEnterRoute() {
this.transitioning = false;
this.$body.scrollTop(0);
nprogress.done();
},
onErrorRoute() {
this.transitioning = false;
nprogress.done(true);
}
});
| Use _.defer instead of setTimeout | Use _.defer instead of setTimeout
| JavaScript | isc | paulfalgout/marionette-strings,onelovelyname/marionette-wires,paulfalgout/marionette-strings,batpad/marionette-wires-tada,yuya-takeyama/marionette-wires,thejameskyle/marionette-wires,onelovelyname/marionette-wires,jkappers/marionette-wires,yuya-takeyama/marionette-wires,thejameskyle/marionette-wires,batpad/marionette-wires-tada,jkappers/marionette-wires | ---
+++
@@ -1,4 +1,5 @@
import $ from 'jquery';
+import _ from 'lodash';
import Radio from 'backbone.radio';
import nprogress from 'nprogress';
import Application from '../common/application';
@@ -26,11 +27,11 @@
onBeforeEnterRoute() {
this.transitioning = true;
// Don't show for synchronous route changes
- setTimeout(() => {
+ _.defer(() => {
if (this.transitioning) {
nprogress.start();
}
- }, 0);
+ });
},
onEnterRoute() { |
0e1a7d0eccd55f3a45f39794e17c4cfea6912b3b | examples/hierarchical/index.js | examples/hierarchical/index.js | import Finity from '../../src';
const submachineConfig = Finity
.configure()
.initialState('substate1')
.getConfig();
const stateMachine = Finity
.configure()
.initialState('state1')
.on('event1').transitionTo('state2')
.state('state2')
.submachine(submachineConfig)
.global()
.onStateEnter(state => console.log(`Entering state '${state}'`))
.start();
stateMachine.handle('event1');
| import Finity from '../../src';
const handleStateEnter = (state) => console.log(`Entering state '${state}'`);
const handleStateExit = (state) => console.log(`Exiting state '${state}'`);
const submachineConfig = Finity
.configure()
.initialState('substate2A')
.on('event2').transitionTo('substate2B')
.global()
.onStateEnter(handleStateEnter)
.onStateExit(handleStateExit)
.getConfig();
const stateMachine = Finity
.configure()
.initialState('state1')
.on('event1').transitionTo('state2')
.state('state2')
.on('event3').transitionTo('state3')
.submachine(submachineConfig)
.global()
.onStateEnter(handleStateEnter)
.onStateExit(handleStateExit)
.start();
for (let i = 1; i <= 3; i++) {
stateMachine.handle(`event${i}`);
}
| Update hierarchical state machine example | Update hierarchical state machine example
| JavaScript | mit | nickuraltsev/fluent-state-machine,nickuraltsev/finity,nickuraltsev/finity | ---
+++
@@ -1,8 +1,15 @@
import Finity from '../../src';
+
+const handleStateEnter = (state) => console.log(`Entering state '${state}'`);
+const handleStateExit = (state) => console.log(`Exiting state '${state}'`);
const submachineConfig = Finity
.configure()
- .initialState('substate1')
+ .initialState('substate2A')
+ .on('event2').transitionTo('substate2B')
+ .global()
+ .onStateEnter(handleStateEnter)
+ .onStateExit(handleStateExit)
.getConfig();
const stateMachine = Finity
@@ -10,9 +17,13 @@
.initialState('state1')
.on('event1').transitionTo('state2')
.state('state2')
+ .on('event3').transitionTo('state3')
.submachine(submachineConfig)
.global()
- .onStateEnter(state => console.log(`Entering state '${state}'`))
+ .onStateEnter(handleStateEnter)
+ .onStateExit(handleStateExit)
.start();
-stateMachine.handle('event1');
+for (let i = 1; i <= 3; i++) {
+ stateMachine.handle(`event${i}`);
+} |
b9cd5acaaf55baaac93f859699dc1fcbdb244dc5 | test/testIndex.js | test/testIndex.js | "use strict";
var request = require("supertest");
var app = require("../js/server/app.js");
describe("App backend server", function () {
it("should serve the index page", function (done) {
request(app)
.get("/index.html")
.expect(200, done);
});
});
| "use strict";
var request = require("supertest");
var mongodb = require("mongodb");
var mongoUrl = "mongodb://mongodb:27017/myproject";
var app = require("../js/server/app.js");
describe("App backend server", function () {
it("should serve the index page", function (done) {
request(app)
.get("/index.html")
.expect(200, done);
});
describe("List", function () {
describe("Saving", function () {
var data = {
_id: "my-test-id",
tasks: [
{
title: "One",
done: false
},
{
title: "two",
done: true
}
]
};
beforeEach(function () {
mongodb.MongoClient.connect(mongoUrl, function (err, db) {
var collection = db.collection("documents");
collection.drop();
db.close();
});
});
it("should accept the request", function (done) {
request(app)
.put("/list/my-test-id")
.set("Accept", "application/json")
.send(data)
.expect(200, done);
});
it("should save and reload the data", function (done) {
request(app)
.put("/list/my-test-id")
.set("Accept", "application/json")
.send(data)
.end(function (err, res) {
request(app)
.get("/list/my-test-id")
.set("Accept", "application/json")
.expect(JSON.stringify(data))
.expect(200, done);
});
});
});
});
});
| Test for simple save/reload of a List | Test for simple save/reload of a List
Gotcha: there is no test DB separation yet, running the tests will drop
the entire collection before each test.
| JavaScript | mit | pixelistik/alreadydone,pixelistik/alreadydone,pixelistik/alreadydone | ---
+++
@@ -1,6 +1,9 @@
"use strict";
var request = require("supertest");
+var mongodb = require("mongodb");
+
+var mongoUrl = "mongodb://mongodb:27017/myproject";
var app = require("../js/server/app.js");
@@ -10,4 +13,54 @@
.get("/index.html")
.expect(200, done);
});
+
+ describe("List", function () {
+ describe("Saving", function () {
+ var data = {
+ _id: "my-test-id",
+ tasks: [
+ {
+ title: "One",
+ done: false
+ },
+ {
+ title: "two",
+ done: true
+ }
+ ]
+ };
+
+ beforeEach(function () {
+ mongodb.MongoClient.connect(mongoUrl, function (err, db) {
+ var collection = db.collection("documents");
+
+ collection.drop();
+
+ db.close();
+ });
+ });
+
+ it("should accept the request", function (done) {
+ request(app)
+ .put("/list/my-test-id")
+ .set("Accept", "application/json")
+ .send(data)
+ .expect(200, done);
+ });
+
+ it("should save and reload the data", function (done) {
+ request(app)
+ .put("/list/my-test-id")
+ .set("Accept", "application/json")
+ .send(data)
+ .end(function (err, res) {
+ request(app)
+ .get("/list/my-test-id")
+ .set("Accept", "application/json")
+ .expect(JSON.stringify(data))
+ .expect(200, done);
+ });
+ });
+ });
+ });
}); |
5d7794078d159157860b76c93f1550be9418731d | src/title/TitleStream.js | src/title/TitleStream.js | /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import type { Narrow, Stream } from '../types';
import StreamIcon from '../streams/StreamIcon';
import { isTopicNarrow } from '../utils/narrow';
const styles = StyleSheet.create({
wrapper: {
alignItems: 'flex-start',
flex: 1,
},
streamRow: {
flexDirection: 'row',
},
streamText: {
marginLeft: 4,
fontSize: 18,
},
topic: {
fontSize: 13,
opacity: 0.8,
},
});
type Props = {
narrow: Narrow,
stream: Stream,
color: string,
};
export default class TitleStream extends PureComponent<Props> {
props: Props;
render() {
const { narrow, stream, color } = this.props;
return (
<View style={styles.wrapper}>
<View style={styles.streamRow}>
<StreamIcon
isMuted={!stream.in_home_view}
isPrivate={stream.invite_only}
color={color}
size={20}
/>
<Text style={[styles.streamText, { color }]} numberOfLines={1} ellipsizeMode="tail">
{stream.name}
</Text>
</View>
{isTopicNarrow(narrow) && (
<Text style={[styles.topic, { color }]} numberOfLines={1} ellipsizeMode="tail">
{narrow[1].operand}
</Text>
)}
</View>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import type { Narrow, Stream } from '../types';
import StreamIcon from '../streams/StreamIcon';
import { isTopicNarrow } from '../utils/narrow';
const styles = StyleSheet.create({
wrapper: {
alignItems: 'flex-start',
flex: 1,
},
streamRow: {
flexDirection: 'row',
alignItems: 'center',
},
streamText: {
marginLeft: 4,
fontSize: 18,
},
topic: {
fontSize: 13,
opacity: 0.8,
},
});
type Props = {
narrow: Narrow,
stream: Stream,
color: string,
};
export default class TitleStream extends PureComponent<Props> {
props: Props;
render() {
const { narrow, stream, color } = this.props;
return (
<View style={styles.wrapper}>
<View style={styles.streamRow}>
<StreamIcon
isMuted={!stream.in_home_view}
isPrivate={stream.invite_only}
color={color}
size={20}
/>
<Text style={[styles.streamText, { color }]} numberOfLines={1} ellipsizeMode="tail">
{stream.name}
</Text>
</View>
{isTopicNarrow(narrow) && (
<Text style={[styles.topic, { color }]} numberOfLines={1} ellipsizeMode="tail">
{narrow[1].operand}
</Text>
)}
</View>
);
}
}
| Fix Stream title alignment issue on Android | Fix Stream title alignment issue on Android
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -13,6 +13,7 @@
},
streamRow: {
flexDirection: 'row',
+ alignItems: 'center',
},
streamText: {
marginLeft: 4, |
338d11b74b6ebcbc841688d21e17a296288dba1d | src/encoding/markdownToHTML.js | src/encoding/markdownToHTML.js | import marked from 'marked';
import htmlclean from 'htmlclean';
import he from 'he';
const renderer = new marked.Renderer();
renderer.listitem = (text) => {
if (/<input[^>]+type="checkbox"/.test(text)) {
return `<li class="task-list-item">${text}</li>\n`;
}
return `<li>${text}</li>\n`;
};
renderer.code = (code, language) => {
const escapedCode = he.escape(code);
return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>`;
};
renderer.paragraph = (text) => `<div>${text}</div>\n`;
renderer.blockquote = (text) => {
return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>`;
};
marked.setOptions({
gfm: true,
smartLists: true,
xhtml: true,
renderer
});
const markdownToHTML = (markdown) => htmlclean(marked(markdown));
export default markdownToHTML;
| import marked from 'marked';
import htmlclean from 'htmlclean';
import he from 'he';
const renderer = new marked.Renderer();
renderer.listitem = (text) => {
if (/<input[^>]+type="checkbox"/.test(text)) {
return `<li class="task-list-item">${text}</li>\n`;
}
return `<li>${text}</li>\n`;
};
renderer.code = (code, language) => {
const escapedCode = he.escape(code);
return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>\n`;
};
renderer.paragraph = (text) => `<div>${text}</div>\n`;
renderer.blockquote = (text) => {
return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>\n`;
};
marked.setOptions({
gfm: true,
smartLists: true,
xhtml: true,
renderer
});
const markdownToHTML = (markdown) => htmlclean(marked(markdown));
export default markdownToHTML;
| Add line break code at end of marked custom parser result | Add line break code at end of marked custom parser result
| JavaScript | mit | oneteam-dev/draft-js-oneteam-rte-plugin,oneteam-dev/draft-js-oneteam-rte-plugin | ---
+++
@@ -13,13 +13,13 @@
renderer.code = (code, language) => {
const escapedCode = he.escape(code);
- return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>`;
+ return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>\n`;
};
renderer.paragraph = (text) => `<div>${text}</div>\n`;
renderer.blockquote = (text) => {
- return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>`;
+ return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>\n`;
};
marked.setOptions({ |
e91fac319f8c5254569163f83908a676c6141f94 | spec/AddressBookSpec.js | spec/AddressBookSpec.js | describe('Address Book', function() {
var addressB,
thisContact;
beforeEach(function() {
addressB = new addressBook();
thisContact = new Contact();
});
it('should be able to add a contact', function() {
addressB.addContact(thisContact);
expect(addressB.getContact(0)).toBe(thisContact);
});
it('should be able to delete a contact', function() {
addressB.addContact(thisContact);
addressB.deleteContact(0);
expect(addressB.getContact(0)).not.toBeDefined();
});
}); | describe('Address Book', function() {
var addressB,
thisContact;
beforeEach(function() {
addressB = new addressBook();
thisContact = new Contact();
});
it('should be able to add a contact', function() {
addressB.addContact(thisContact);
expect(addressB.getContact(0)).toBe(thisContact);
});
it('should be able to delete a contact', function() {
addressB.addContact(thisContact);
addressB.deleteContact(0);
expect(addressB.getContact(0)).not.toBeDefined();
});
});
describe('Async Address Book', function() {
var addressB = new addressBook();
/*
* the func getAsyncContacts should take as param
* a callback func and invokes it gets a response
*/
beforeEach(function(done) {
addressB.getAsyncContacts(function() {
done();
});
});
it('should get the contacts async', function(done) {
expect(addressB.asyncCompleted).toBe(true);
done();
});
}); | Add test for async address book | Add test for async address book
| JavaScript | mit | AthinaB/js-testing-jasmine,AthinaB/js-testing-jasmine | ---
+++
@@ -18,3 +18,22 @@
expect(addressB.getContact(0)).not.toBeDefined();
});
});
+
+describe('Async Address Book', function() {
+ var addressB = new addressBook();
+
+ /*
+ * the func getAsyncContacts should take as param
+ * a callback func and invokes it gets a response
+ */
+ beforeEach(function(done) {
+ addressB.getAsyncContacts(function() {
+ done();
+ });
+ });
+
+ it('should get the contacts async', function(done) {
+ expect(addressB.asyncCompleted).toBe(true);
+ done();
+ });
+}); |
1a12cf0c190e077d623f9a1fcad3f91cde5915c8 | src/js/app/data_utils/store.js | src/js/app/data_utils/store.js | App.Store = DS.Store.extend({
findQuery: function(type, id){
id = id || {};
id.api_key = App.API_KEY;
return this._super(type, id);
},
allRecords: function(){
var typeMaps = this.get('typeMaps'),
records = [];
for (var key in typeMaps){
records = records.concat(typeMaps[key].records);
}
return records;
},
unloadAllRecords: function(){
var records = this.allRecords(),
record;
while (record = records.pop()){
record.unloadRecord();
}
},
modelFor: function(type){
if (type === 'post'){
this.Post.typeKey = 'post';
return this.Post;
} else {
return this._super(type);
}
},
Post: DS.Model.extend(App.PostMixin)
});
| App.Store = DS.Store.extend({
findQuery: function(type, query){
query = query || {};
if (!this.container.lookup('router:main').namespace.AuthManager.isAuthenticated()){
query.api_key = 'a3yqP8KA1ztkIbq4hpokxEOwnUkleu2AMv0XsBWC0qLBKVL7pA';
}
return this._super(type, query);
},
allRecords: function(){
var typeMaps = this.get('typeMaps'),
records = [];
for (var key in typeMaps){
records = records.concat(typeMaps[key].records);
}
return records;
},
unloadAllRecords: function(){
var records = this.allRecords(),
record;
while (record = records.pop()){
record.unloadRecord();
}
},
modelFor: function(type){
if (type === 'post'){
this.Post.typeKey = 'post';
return this.Post;
} else {
return this._super(type);
}
},
Post: DS.Model.extend(App.PostMixin)
});
| Add the api_key to the query only if we're not authenticated some other way | Add the api_key to the query only if we're not authenticated some other way
| JavaScript | mit | Mause/tumblr-ember | ---
+++
@@ -1,9 +1,12 @@
App.Store = DS.Store.extend({
- findQuery: function(type, id){
- id = id || {};
- id.api_key = App.API_KEY;
+ findQuery: function(type, query){
+ query = query || {};
- return this._super(type, id);
+ if (!this.container.lookup('router:main').namespace.AuthManager.isAuthenticated()){
+ query.api_key = 'a3yqP8KA1ztkIbq4hpokxEOwnUkleu2AMv0XsBWC0qLBKVL7pA';
+ }
+
+ return this._super(type, query);
},
allRecords: function(){ |
75d150dcbe15649754248f8628e136a7c40f7eab | scripts/ci-clean.js | scripts/ci-clean.js | /**
* `npm run ci:clean`
*
* Cross-platform script to remove report directory for CI.
*/
const process = require('process');
const script = require('./script');
const reportDirPath = process.env.npm_package_config_report_dir_path;
script.run(`rimraf ${reportDirPath}`);
| /**
* `npm run ci:clean`
*
* Cross-platform script to remove report directory for CI.
*/
const process = require('process');
const script = require('./script');
const reportDirPath = process.env.npm_package_config_report_dir_path;
script.run(`rimraf ${reportDirPath}`);
// Remove generated `.nyc_output/` because it may get large over time.
// See https://github.com/istanbuljs/nyc/issues/197
script.run('rimraf .nyc_output/');
| Remove .nyc_output to prevent this dir from getting too large. | Remove .nyc_output to prevent this dir from getting too large.
| JavaScript | mit | choonchernlim/front-end-stack,choonchernlim/front-end-stack | ---
+++
@@ -9,3 +9,7 @@
const reportDirPath = process.env.npm_package_config_report_dir_path;
script.run(`rimraf ${reportDirPath}`);
+
+// Remove generated `.nyc_output/` because it may get large over time.
+// See https://github.com/istanbuljs/nyc/issues/197
+script.run('rimraf .nyc_output/'); |
27e7db50ae93d77c8578a4b104efe3f56fce064e | src/childrensize.js | src/childrensize.js | var computedStyle = require('computed-style');
module.exports = function(container) {
if (!container) { return; }
var children = [].slice.call(container.children, 0).filter(function (el) {
var pos = computedStyle(el, 'position');
el.rect = el.getBoundingClientRect(); // store rect for later
return !(
(pos === 'absolute' || pos === 'fixed') ||
(el.rect.width === 0 && el.rect.height === 0)
);
});
if (children.length === 0) {
return { width: 0, height: 0 };
}
var totRect = children.reduce(function (tot, el) {
return (!tot ?
el.rect :
{
top : Math.min(tot.top, el.rect.top),
left : Math.min(tot.left, el.rect.left),
right : Math.max(tot.right, el.rect.right),
bottom : Math.max(tot.bottom, el.rect.bottom)
});
}, null);
return {
width: totRect.right - totRect.left,
height: totRect.bottom - totRect.top
};
};
| var computedStyle = require('computed-style');
function toArray (nodeList) {
var arr = [];
for (var i=0, l=nodeList.length; i<l; i++) { arr.push(nodeList[i]); }
return arr;
}
module.exports = function(container) {
if (!container) { return; }
var children = toArray(container.children).filter(function (el) {
var pos = computedStyle(el, 'position');
el.rect = el.getBoundingClientRect(); // store rect for later
return !(
(pos === 'absolute' || pos === 'fixed') ||
(el.rect.width === 0 && el.rect.height === 0)
);
});
if (children.length === 0) {
return { width: 0, height: 0 };
}
var totRect = children.reduce(function (tot, el) {
return (!tot ?
el.rect :
{
top : Math.min(tot.top, el.rect.top),
left : Math.min(tot.left, el.rect.left),
right : Math.max(tot.right, el.rect.right),
bottom : Math.max(tot.bottom, el.rect.bottom)
});
}, null);
return {
width: totRect.right - totRect.left,
height: totRect.bottom - totRect.top
};
};
| Fix IE8 error when converting NodeList to Array | Fix IE8 error when converting NodeList to Array
| JavaScript | mit | gardr/ext,gardr/ext | ---
+++
@@ -1,9 +1,15 @@
var computedStyle = require('computed-style');
+
+function toArray (nodeList) {
+ var arr = [];
+ for (var i=0, l=nodeList.length; i<l; i++) { arr.push(nodeList[i]); }
+ return arr;
+}
module.exports = function(container) {
if (!container) { return; }
- var children = [].slice.call(container.children, 0).filter(function (el) {
+ var children = toArray(container.children).filter(function (el) {
var pos = computedStyle(el, 'position');
el.rect = el.getBoundingClientRect(); // store rect for later
return !( |
02e71c3c22b5563f05910a92bc1c7efa9cc7a3a9 | src/background.js | src/background.js | var RESET_TIME = 3000;
var timeout;
var lastPress = Date.now();
var average = 0;
var iterations = 1;
chrome.browserAction.onClicked.addListener(function() {
var elapsedTime = Date.now() - lastPress;
lastPress = Date.now();
if (elapsedTime > RESET_TIME) {
average = 0;
iterations = 1;
} else {
average = (average * (iterations - 1) + elapsedTime) / iterations;
iterations += 1;
var bpm = Math.round(60000 / average);
chrome.browserAction.setBadgeText({ text: bpm.toString() });
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
chrome.browserAction.setBadgeText({ text: "" });
}, RESET_TIME);
}); | var RESET_TIME = 3000;
var timeout;
var lastPress = performance.now();
var average = 0;
var iterations = 1;
chrome.browserAction.onClicked.addListener(function() {
var elapsedTime = performance.now() - lastPress;
lastPress = performance.now();
if (elapsedTime > RESET_TIME) {
average = 0;
iterations = 1;
} else {
average = (average * (iterations - 1) + elapsedTime) / iterations;
iterations += 1;
var bpm = Math.round(60000 / average);
chrome.browserAction.setBadgeText({ text: bpm.toString() });
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
chrome.browserAction.setBadgeText({ text: "" });
}, RESET_TIME);
}); | Use performance.now for better accuracy | Use performance.now for better accuracy
| JavaScript | mit | chrisblazek/bpm-tapper,chrisblazek/bpm-tapper,chrisblazek/bpm-tapper | ---
+++
@@ -1,12 +1,12 @@
var RESET_TIME = 3000;
var timeout;
-var lastPress = Date.now();
+var lastPress = performance.now();
var average = 0;
var iterations = 1;
chrome.browserAction.onClicked.addListener(function() {
- var elapsedTime = Date.now() - lastPress;
- lastPress = Date.now();
+ var elapsedTime = performance.now() - lastPress;
+ lastPress = performance.now();
if (elapsedTime > RESET_TIME) {
average = 0; |
968fae71469a3bb8a010f74c2c8244a4d26f429d | protractor.conf.js | protractor.conf.js | // @AngularClass
exports.config = {
baseUrl: 'http://localhost:8080/',
allScriptsTimeout: 11000,
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 60000,
showTiming: true
},
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['show-fps-counter=true']
}
},
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: [
'test/**/*.e2e.js'
],
onPrepare: function() {
browser.ignoreSynchronization = true;
}
};
| // @AngularClass
exports.config = {
baseUrl: 'http://localhost:3000/',
allScriptsTimeout: 11000,
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 60000,
showTiming: true
},
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['show-fps-counter=true']
}
},
seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',
specs: [
'test/**/*.e2e.js'
],
onPrepare: function() {
browser.ignoreSynchronization = true;
}
};
| Change baseUrl to listen to port 3000; remove seleniumAddress and define seleniumServerJar instead to get selenium running | Change baseUrl to listen to port 3000; remove seleniumAddress and define seleniumServerJar instead to get selenium running
| JavaScript | mit | burgerga/angular2-webpack-starter,benjaminleetmaa/hsoemRepo,psamit/angular-starter,Yaroslav-Andryushchenkov/epam-angular2,JerrolKrause/angular-ultimate-starter,vamurov/lazyImageLoad,bryant-pham/easyjudge,shattar/test-ng2-submodule-routing,stepkraft/factory-queue,DigitalGeek/angular2-webpack-starter,davidstellini/bvl-pay,refaelgold/angular2-webpack-starter,ng2-dev/angular-quick-starter,donkebap/habicht-app,olegskIT/ng2-transfer,interlocal/deadhome,joachimprinzbach/ng2-camp,tb/angular2-reactive-examples,forty-two-labs/angular2-webpack-starter,ShadowMinhja/materialize-angular2,sebastianhaas/medical-appointment-scheduling,jhuntoo/angular2-webpack-starter,abdulhaq-e/angular2-webpack-starter,chriscurnow/angular2-webpack-starter,abner/angular2-webpack-starter,dartavion/angular-planning-poker,ShadowMinhja/materialize-angular2,milenkovic/lost-consulting,ng2-developers/angular2-webpack-starter,spawnius/angular2-webpack-starter,zxqian1991/angular2-build,AngularClass/angular2-webpack-starter,abner/angular2-webpack-starter,KubaJastrz/angular-password-generator,SekibOmazic/angular2-webpack-starter,liveweird/gossip-ng2,interlocal/deadhome,jffjs/hs-deckbuilder,dotcs/angular2-webpack-starter,roski/devroks,DmitriyLamzin/angular2_try,dreamer99x/ceb,silbermm/silbersoft.io,ng2-developers/angular2-webpack-starter,juristr/angular2-webpack-starter,CNSKnight/angular2-webpack-starter,DigitalGeek/angular2-webpack-starter,jelluz/pimatic-angular2-frontend,CarmenRosas/TestPortal,thecortex/angular2-webpack-starter,specialstandard/stockchartguru,dlevkov/TenTvFront,vjcspy/retail-cloud,Milan03/stefan-site,benjaminleetmaa/hsOemV3,Tribilik/Pictu-r,silbermm/silbersoft.io,prasadc82/GitGames,manuelhuber/LostColonies,AngularClass/angular2-webpack-starter,mitchellcmurphy/touristBingo,Nighthawk14/angular2-webpack-starter,ronencamera/clientv2,refaelgold/angular2-webpack-starter,zdenkotudor/eli,viktorianheathen/hillel,wishtack/wt-training-angular2,PavelVak/sell-it,Baqend/angular2-starter,angular-class/angular2-webpack-starter,jimthedev/angular2-webpack-starter,jffjs/hs-deckbuilder,shortgiraffe4/angular2,miedziana/angular2-webpack-starter,miedziana/angular2-webpack-starter,artfoundry/billing,benjaminleetmaa/oemRepo,prasadc82/GitGames,dlevkov/TenTvFinal,lorenlew/PuzzleGame,ng2-developers/angular2-webpack-starter,wishtack/wt-training-angular2,chriscurnow/angular2-webpack-starter,cherurg/audaily,shattar/test-ng2-submodule-routing,un33k/angular2-webpack-starter,vjcspy/retail-cloud,dl988/quedro,swga/website,bave8672/angular2-finder,24hours/vinegar,tsoposki/angular2-webpack-starter,swga/website,airbnbbkk/airbnbbkk.github.io,abhilash-shrivastava/Meet-the-Need-v2,carathorys/TestRepo,imdeakin/yunxi-admin,jiverson/angular2-webpack-starter,adrhc/angular2-webpack-starter,jsec516/ng2-location-tracker,dreamer99x/ceb,paynoattn/ng2-weather-app,dimkk/cccfix,humphreymburu/FutureSteps,russellf9/ng-2-webpack-playground,ronencamera/clientv2,dlevkov/TenTvFront,dlevkov/TenTvFinal,jimthedev/angular2-webpack-starter,abhilash-shrivastava/Meet-the-Need-v2,SekibOmazic/angular2-webpack-starter,Luchillo/Luchillo-tech-showcase,zxqian1991/angular2-build,colinskow/angular-electron-dream-starter,6Kbrouette/POEC_TP,remakeelectric/etactica-frontend,chriscurnow/angular2-webpack-starter,JerrolKrause/angular-ultimate-starter,Draccoz/zalamo-starter,imdeakin/yunxi-admin,shekhra400/wheather-report-app,ancor-dev/chronology-client,airbnbbkk/airbnbbkk.github.io,donkebap/habicht-app,wishtack/wt-training-angular2,inchingorg/xdata-web,ForsetiSWE/VigiFlow,StefH/angular2-webpack-starter,psamit/angular-starter,jeaber/frontierproperties,stepkraft/factory-queue,benjaminleetmaa/hsOemV3,jacobjojan/angular2-webpack-starter,mdarif-k/angular2-webpack,lorenlew/PuzzleGame,shortgiraffe4/angular2,Atrosh/REPET-FRONT,joachimprinzbach/ng2-camp,ExchangeEffect/ExchangeEffect.github.io,lorenlew/PuzzleGame,jacobjojan/angular2-webpack-starter,zishe/angular2-finances,6Kbrouette/POEC_TP,vjcspy/retail-cloud,silbermm/silbersoft.io,Niaro/trood-demo,Milan03/stefan-site,San4oPanso/angular2-webpack-starter,zishe/angular2-finances,team-playalong/playalong-angular2,dartavion/angular-planning-poker,ForsetiSWE/VigiFlow,abhilash-shrivastava/Meet-the-Need-v2,NathanWalker/angular2-webpack-starter,PavelVak/sell-it,anthonybrown/angular2-webpack-starter,anthonybrown/angular2-webpack-starter,NathanWalker/angular2-webpack-starter,dimkk/cccfix,browseros/browser,artfoundry/billing,Luchillo/Ng2-Pro-webpack-starter,sebastianhaas/medical-appointment-scheduling,dgreensp/angular2-webpack-starter,MinxianLi/angular2-webpack-starter,ExchangeEffect/ExchangeEffect.github.io,timmyg/mary-tim-wedding-webapp,6Kbrouette/POEC_TP,jhuntoo/angular2-webpack-starter,dl988/quedro,dgreensp/angular2-webpack-starter,jsec516/ng2-location-tracker,un33k/angular2-webpack-starter,egucciar/angular2-webpack-starter-primeng-working,viktorianheathen/hillel,davidstellini/bvl-pay,Ta-Moon-A/ng-webpack-starter,arun-nyllabs/angularAlpha,hieudt/angular2-webpack-starter,SmallGress/learn-ng2,rwaldvogel/angular2-rabbitmq,CNSKnight/angular2-webpack-starter,remakeelectric/etactica-frontend,forty-two-labs/angular2-webpack-starter,Nebulis/angular2-firebase,redaikidoka/SistemaE3,jffjs/hs-deckbuilder,mitchellcmurphy/filterFunctions,websublime/kong-console,Baqend/angular-starter,benjaminleetmaa/oemRepo,team-playalong/playalong-angular2,ng2-dev/angular-quick-starter,downeyfe/angular2-webpack-starter,JamesUlph/angular2-webpack-starter,dweitz43/angular2-webpack-starter,iSystemPlus/ng2-webpack-play,inchingorg/xdata-web,jimitndiaye/ionic2test,donkebap/habicht-app,downeyfe/angular2-webpack-starter,manuelhuber/LostColonies,jimthedev/angular2-webpack-starter,Draccoz/zalamo-starter,louisscruz/freedom-mortgage,StefH/angular2-webpack-starter,davidstellini/bvl-pay,wishtack/wt-angular2-boilerplate,JamesUlph/angular2-webpack-starter,agilethought/ObservableExample,Alex-Barbier/angular2,louisscruz/freedom-mortgage,rwaldvogel/angular2-rabbitmq,chriscurnow/angular2-webpack-starter,marta-tatiana/angular2-webpack-starter,serenity-frontstack/angular-component-seed,dotcs/angular2-webpack-starter,websublime/kong-console,mitchellcmurphy/touristBingo,louisscruz/freedom-mortgage,lohiarahul/angular-sub-starter,shortgiraffe4/angular2,egucciar/angular2-webpack-starter-primeng-working,specialstandard/stockchartguru,bave8672/angular2-finder,manuelhuber/LostColonies,DigitalGeek/angular2-webpack-starter,KubaJastrz/angular-password-generator,s-robertson/things-angular,Tribilik/Pictu-r,redaikidoka/SistemaE3,timathon/sgz010,phucps89/angular2-starter-webpack,Neverbalnost/angular2,benjaminleetmaa/hsOemV3,jhuntoo/angular2-webpack-starter,zdenkotudor/eli,joachimprinzbach/ng2-camp,mitchellcmurphy/filterFunctions,dsebastien/angularjs-webpack-starter,wohugb/d3f,liveweird/gossip-ng2,dlevkov/TenTvFinal,s-robertson/things-angular,AngularClass/angular-starter,zm1994/gallery,jiverson/angular2-webpack-starter,russellf9/ng-2-webpack-playground,Aggelost1/moviefinder,AngularClass/angular2-webpack-starter,Tribilik/Pictu-r,phammans/angular-2,wishtack/wt-angular2-boilerplate,cherurg/audaily,MinxianLi/angular2-webpack-starter,MinxianLi/angular2-webpack-starter,angular-class/angular2-webpack-starter,Luchillo/Ng2-Pro-webpack-starter,dgreensp/angular2-webpack-starter,Luchillo/Ng2-Pro-webpack-starter,forty-two-labs/angular2-webpack-starter,AngularClass/angular-starter,downeyfe/angular2-webpack-starter,adrhc/angular2-webpack-starter,brummell/angular2-webpack-starter,jeffplourd/jeffplourd,peternguyen88/gmat-zeth,mitchellcmurphy/touristBingo,StefH/angular2-webpack-starter,dreamer99x/ceb,Draccoz/zalamo-starter,dbollaer/angular2-starter,spawnius/angular2-webpack-starter,NathanWalker/angular2-webpack-starter,zxqian1991/angular2-build,jiverson/angular2-webpack-starter,itoufo/stoq-web2,Nebulis/angular2-firebase,krimple/angular2-webpack-demo-routing-and-http,roski/devroks,sebastianhaas/medical-appointment-scheduling,carathorys/TestRepo,phammans/angular-2,redaikidoka/SistemaE3,psamit/angular-starter,ronencamera/clientv2,jimitndiaye/ionic2test,dbollaer/angular2-starter,CarmenRosas/TestPortal,itoufo/stoq-web2,timmyg/mary-tim-wedding-webapp,airbnbbkk/airbnbbkk.github.io,sebastianhaas/medical-appointment-scheduling,adrhc/angular2-webpack-starter,benjaminleetmaa/hsoemRepo,celador/Angular2-Webpack-Start,phucps89/angular2-starter-webpack,milenkovic/lost-consulting,liveweird/gossip-ng2,prasadc82/GitGames,CNSKnight/angular2-webpack-starter,Nighthawk14/angular2-webpack-starter,Nighthawk14/angular2-webpack-starter,artfoundry/billing,thecortex/angular2-webpack-starter,jelluz/pimatic-angular2-frontend,hieudt/angular2-webpack-starter,celador/Angular2-Webpack-Start,JerrolKrause/angular-seed-complete,nijk/hat-selector,imdeakin/yunxi-admin,Milan03/stefan-site,juristr/angular2-webpack-starter,hess-google/angular2-webpack-starter,24hours/vinegar,Atrosh/REPET-FRONT,olegskIT/ng2-transfer,zishe/angular2-finances,Baqend/angular-starter,humphreymburu/FutureSteps,nasiUduk/qi-project-test,HipsterZipster/angular2-webpack-starter,peternguyen88/gmat-zeth,lohiarahul/angular-sub-starter,jeffplourd/jeffplourd,JonnyBGod/angular2-webpack-advance-starter,krimple/angular2-webpack-demo-routing-and-http,jeffplourd/jeffplourd,burgerga/angular2-webpack-starter,mszczepaniak/angular2-webpack-starter,PavelVak/sell-it,dweitz43/angular2-webpack-starter,Gabriel0402/angular2-webpack-starter,nijk/hat-selector,arun-nyllabs/angularAlpha,dsebastien/angularjs-webpack-starter,inchingorg/xdata-web,nijk/hat-selector,abdulhaq-e/angular2-webpack-starter,Ta-Moon-A/ng-webpack-starter,milenkovic/lost-consulting,DmitriyLamzin/angular2_try,zm1994/gallery,itoufo/stoq-web2,dartavion/angular-planning-poker,dotcs/angular2-webpack-starter,ancor-dev/chronology-client,tsoposki/angular2-webpack-starter,JamesUlph/angular2-webpack-starter,wishtack/wt-angular2-boilerplate,wiikviz/webpack-angular2-bs4-sass,remakeelectric/etactica-frontend,JonnyBGod/angular2-webpack-advance-starter,egucciar/angular2-webpack-starter-primeng-working,Gabriel0402/angular2-webpack-starter,brummell/angular2-webpack-starter,dweitz43/angular2-webpack-starter,ShadowMinhja/materialize-angular2,cherurg/audaily,tsoposki/angular2-webpack-starter,hieudt/angular2-webpack-starter,HipsterZipster/angular2-webpack-starter,jelluz/pimatic-angular2-frontend,Aggelost1/moviefinder,browseros/browser,wohugb/d3f,mszczepaniak/angular2-webpack-starter,viktorianheathen/hillel,Baqend/angular2-starter,Michaelzvu/ArounSee,bryant-pham/easyjudge,kovalevmax/ang2,russellf9/ng-2-webpack-playground,iSystemPlus/ng2-webpack-play,bave8672/angular2-finder,mdarif-k/angular2-webpack,CarmenRosas/TestPortal,angular-class/angular2-webpack-starter,browseros/browser,shekhra400/wheather-report-app,tellurS/op,HipsterZipster/angular2-webpack-starter,Luchillo/Luchillo-tech-showcase,zishe/angular2-finances,SekibOmazic/angular2-webpack-starter,marta-tatiana/angular2-webpack-starter,Neverbalnost/angular2,Alex-Barbier/angular2,swga/website,burgerga/angular2-webpack-starter,timathon/sgz010,zxqian1991/angular2-build,arun-nyllabs/angularAlpha,JonnyBGod/angular2-webpack-advance-starter,Alex-Barbier/angular2,hess-google/angular2-webpack-starter,team-playalong/playalong-angular2,nasiUduk/qi-project-test,redaikidoka/SistemaE3,jacobjojan/angular2-webpack-starter,Baqend/angular-starter,hess-google/angular2-webpack-starter,dbollaer/angular2-starter,wiikviz/webpack-angular2-bs4-sass,tellurS/op,paynoattn/ng2-weather-app,benjaminleetmaa/hsoemRepo,refaelgold/angular2-webpack-starter,agilethought/ObservableExample,ForsetiSWE/VigiFlow,agilethought/ObservableExample,tb/angular2-reactive-examples,thecortex/angular2-webpack-starter,mszczepaniak/angular2-webpack-starter,JerrolKrause/angular-seed-complete,dimkk/cccfix,joachimprinzbach/ng2-camp,vamurov/lazyImageLoad,24hours/vinegar,ng2-dev/angular-quick-starter,jsec516/ng2-location-tracker,Luchillo/Luchillo-tech-showcase,AngularClass/angular-starter,abner/angular2-webpack-starter,benjaminleetmaa/oemRepo,miedziana/angular2-webpack-starter,JerrolKrause/angular-seed-complete,dlevkov/TenTvFront,tb/angular2-reactive-examples,websublime/kong-console,olegskIT/ng2-transfer,KubaJastrz/angular-password-generator,Michaelzvu/ArounSee,Neverbalnost/angular2,San4oPanso/angular2-webpack-starter,jeaber/frontierproperties,agilethought/ObservableExample,jeaber/frontierproperties,zm1994/gallery,SmallGress/learn-ng2,bave8672/angular2-finder,San4oPanso/angular2-webpack-starter,ancor-dev/chronology-client,zdenkotudor/eli,juristr/angular2-webpack-starter,mdarif-k/angular2-webpack,Niaro/trood-demo,mitchellcmurphy/filterFunctions,peternguyen88/gmat-zeth,Yaroslav-Andryushchenkov/epam-angular2,krimple/angular2-webpack-demo-routing-and-http,stepkraft/factory-queue,Ta-Moon-A/ng-webpack-starter,JerrolKrause/angular-ultimate-starter,phucps89/angular2-starter-webpack,kovalevmax/ang2,Aggelost1/moviefinder,jimitndiaye/ionic2test,Nebulis/angular2-firebase,timmyg/mary-tim-wedding-webapp,Baqend/angular2-starter,humphreymburu/FutureSteps,dl988/quedro,shekhra400/wheather-report-app,brummell/angular2-webpack-starter,itoufo/stoq-web2,Niaro/trood-demo,tellurS/op,nasiUduk/qi-project-test,celador/Angular2-Webpack-Start,Atrosh/REPET-FRONT,Yaroslav-Andryushchenkov/epam-angular2,un33k/angular2-webpack-starter,adrhc/angular2-webpack-starter,bryant-pham/easyjudge,milenkovic/lost-consulting,wiikviz/webpack-angular2-bs4-sass,serenity-frontstack/angular-component-seed,vamurov/lazyImageLoad,s-robertson/things-angular,colinskow/angular-electron-dream-starter,louisscruz/freedom-mortgage,rwaldvogel/angular2-rabbitmq,SmallGress/learn-ng2,anthonybrown/angular2-webpack-starter,lohiarahul/angular-sub-starter,DmitriyLamzin/angular2_try,marta-tatiana/angular2-webpack-starter,specialstandard/stockchartguru,shattar/test-ng2-submodule-routing,iSystemPlus/ng2-webpack-play,dsebastien/angularjs-webpack-starter,carathorys/TestRepo,colinskow/angular-electron-dream-starter,Gabriel0402/angular2-webpack-starter,timathon/sgz010,Michaelzvu/ArounSee,spawnius/angular2-webpack-starter,abdulhaq-e/angular2-webpack-starter,kovalevmax/ang2,interlocal/deadhome,wohugb/d3f,phammans/angular-2,s-robertson/things-angular,serenity-frontstack/angular-component-seed,ExchangeEffect/ExchangeEffect.github.io,roski/devroks,paynoattn/ng2-weather-app | ---
+++
@@ -1,7 +1,7 @@
// @AngularClass
exports.config = {
- baseUrl: 'http://localhost:8080/',
+ baseUrl: 'http://localhost:3000/',
allScriptsTimeout: 11000,
@@ -19,7 +19,7 @@
}
},
- seleniumAddress: 'http://localhost:4444/wd/hub',
+ seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar',
specs: [
'test/**/*.e2e.js' |
b3b75a6855b143e1e5fb208419eea2b8819b618d | src/utils/__tests__/isExportsOrModuleAssignment-test.js | src/utils/__tests__/isExportsOrModuleAssignment-test.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { statement } from '../../../tests/utils';
import isExportsOrModuleAssignment from '../isExportsOrModuleAssignment';
describe('isExportsOrModuleAssignment', () => {
it('detects "module.exports = ...;"', () => {
expect(
isExportsOrModuleAssignment(statement('module.exports = foo;')),
).toBe(true);
});
it('detects "exports.foo = ..."', () => {
expect(isExportsOrModuleAssignment(statement('exports.foo = foo;'))).toBe(
true,
);
});
it('does not accept "exports = foo;"', () => {
// That doesn't actually export anything
expect(isExportsOrModuleAssignment(statement('exports = foo;'))).toBe(
false,
);
});
});
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { statement, noopImporter } from '../../../tests/utils';
import isExportsOrModuleAssignment from '../isExportsOrModuleAssignment';
describe('isExportsOrModuleAssignment', () => {
it('detects "module.exports = ...;"', () => {
expect(
isExportsOrModuleAssignment(
statement('module.exports = foo;'),
noopImporter,
),
).toBe(true);
});
it('detects "exports.foo = ..."', () => {
expect(
isExportsOrModuleAssignment(
statement('exports.foo = foo;'),
noopImporter,
),
).toBe(true);
});
it('does not accept "exports = foo;"', () => {
// That doesn't actually export anything
expect(
isExportsOrModuleAssignment(statement('exports = foo;'), noopImporter),
).toBe(false);
});
});
| Add noop importer to isExportsOrModuleAssignment tests | Add noop importer to isExportsOrModuleAssignment tests
| JavaScript | mit | reactjs/react-docgen,reactjs/react-docgen,reactjs/react-docgen | ---
+++
@@ -6,26 +6,32 @@
*
*/
-import { statement } from '../../../tests/utils';
+import { statement, noopImporter } from '../../../tests/utils';
import isExportsOrModuleAssignment from '../isExportsOrModuleAssignment';
describe('isExportsOrModuleAssignment', () => {
it('detects "module.exports = ...;"', () => {
expect(
- isExportsOrModuleAssignment(statement('module.exports = foo;')),
+ isExportsOrModuleAssignment(
+ statement('module.exports = foo;'),
+ noopImporter,
+ ),
).toBe(true);
});
it('detects "exports.foo = ..."', () => {
- expect(isExportsOrModuleAssignment(statement('exports.foo = foo;'))).toBe(
- true,
- );
+ expect(
+ isExportsOrModuleAssignment(
+ statement('exports.foo = foo;'),
+ noopImporter,
+ ),
+ ).toBe(true);
});
it('does not accept "exports = foo;"', () => {
// That doesn't actually export anything
- expect(isExportsOrModuleAssignment(statement('exports = foo;'))).toBe(
- false,
- );
+ expect(
+ isExportsOrModuleAssignment(statement('exports = foo;'), noopImporter),
+ ).toBe(false);
});
}); |
ee81febc89910ea3bd5954e3ebf2b41bd400c604 | src/decorators.js | src/decorators.js | // Debounce decorator for methods.
//
// See: https://github.com/wycats/javascript-decorators
export const debounce = (duration) => (target, name, descriptor) => {
const {value: fn} = descriptor
let wrapper
let lastCall = 0
function debounced () {
const now = Date.now()
if (now > lastCall + duration) {
lastCall = now
try {
const result = fn.apply(this, arguments)
wrapper = () => result
} catch (error) {
wrapper = () => { throw error }
}
}
return wrapper()
}
debounced.reset = () => { lastCall = 0 }
descriptor.value = debounced
return descriptor
}
| // Debounce decorator for methods.
//
// See: https://github.com/wycats/javascript-decorators
export const debounce = (duration) => (target, name, descriptor) => {
const {value: fn} = descriptor
// This symbol is used to store the related data directly on the
// current object.
const s = Symbol()
function debounced () {
let data = this[s] || (this[s] = {
lastCall: 0,
wrapper: null
})
const now = Date.now()
if (now > data.lastCall + duration) {
data.lastCall = now
try {
const result = fn.apply(this, arguments)
data.wrapper = () => result
} catch (error) {
data.wrapper = () => { throw error }
}
}
return data.wrapper()
}
debounced.reset = (obj) => { delete obj[s] }
descriptor.value = debounced
return descriptor
}
| Fix @debounce to work correctly with multiple instances. | Fix @debounce to work correctly with multiple instances.
| JavaScript | agpl-3.0 | lmcro/xo-web,lmcro/xo-web,lmcro/xo-web,vatesfr/xo-web,vatesfr/xo-web | ---
+++
@@ -4,22 +4,29 @@
export const debounce = (duration) => (target, name, descriptor) => {
const {value: fn} = descriptor
- let wrapper
- let lastCall = 0
+ // This symbol is used to store the related data directly on the
+ // current object.
+ const s = Symbol()
+
function debounced () {
+ let data = this[s] || (this[s] = {
+ lastCall: 0,
+ wrapper: null
+ })
+
const now = Date.now()
- if (now > lastCall + duration) {
- lastCall = now
+ if (now > data.lastCall + duration) {
+ data.lastCall = now
try {
const result = fn.apply(this, arguments)
- wrapper = () => result
+ data.wrapper = () => result
} catch (error) {
- wrapper = () => { throw error }
+ data.wrapper = () => { throw error }
}
}
- return wrapper()
+ return data.wrapper()
}
- debounced.reset = () => { lastCall = 0 }
+ debounced.reset = (obj) => { delete obj[s] }
descriptor.value = debounced
return descriptor |
3adfb577f9b4a5d7f28ccac40f17c867a6f7913c | lib/is-js-module.js | lib/is-js-module.js | 'use strict';
var deferred = require('deferred')
, fs = require('fs')
, extname = require('path').extname
, hasNodeSheBang = RegExp.prototype.test.bind(/^#![\u0021-\uffff]+(?:\/node|\/env node)\s/)
, promisify = deferred.promisify
, read = promisify(fs.read)
, open = promisify(fs.open), close = promisify(fs.close);
module.exports = function (filename) {
var ext = extname(filename);
if (ext === '.js') return deferred(true);
if (ext) return deferred(false);
return open(filename, 'r')(function (fd) {
var buffer = new Buffer(100);
return read(fd, buffer, 0, 100, null)(function () {
close(fd);
return hasNodeSheBang(String(buffer));
});
});
};
| 'use strict';
var deferred = require('deferred')
, fs = require('fs')
, extname = require('path').extname
, hasNodeSheBang = RegExp.prototype.test.bind(/^#![\u0021-\uffff]+(?:\/node|\/env node)\s/)
, promisify = deferred.promisify
, read = promisify(fs.read)
, open = promisify(fs.open), close = promisify(fs.close);
module.exports = function (filename) {
var ext = extname(filename);
if (ext === '.js') return deferred(true);
if (ext === '.json') return deferred(true);
if (ext) return deferred(false);
return open(filename, 'r')(function (fd) {
var buffer = new Buffer(100);
return read(fd, buffer, 0, 100, null)(function () {
close(fd);
return hasNodeSheBang(String(buffer));
});
});
};
| Support JSOM as js module | Support JSOM as js module
| JavaScript | isc | medikoo/movejs,medikoo/rename-module | ---
+++
@@ -12,6 +12,7 @@
module.exports = function (filename) {
var ext = extname(filename);
if (ext === '.js') return deferred(true);
+ if (ext === '.json') return deferred(true);
if (ext) return deferred(false);
return open(filename, 'r')(function (fd) { |
7cb07d2328863847644887eff660978e0699e22b | lib/post-manager.js | lib/post-manager.js | var _ = require('lodash-node/modern')
// TODO: consider passing the taxonomy types to the constructor
function PostManager() {
this.posts = []
}
PostManager.prototype.all = function() {
return posts
}
PostManager.prototype.each = function(cb) {
_.each(this.posts, cb)
}
PostManager.prototype.reset = function() {
this.posts = []
}
module.exports = PostManager
| var _ = require('lodash-node/modern')
var natural = require('natural')
var inflector = new natural.NounInflector()
// TODO: consider passing the taxonomy types to the constructor
function PostManager(taxonomyTypes) {
this.posts = []
this.taxonomyTypes = taxonomyTypes
this.taxonomies = {}
_.each(this.taxonomyTypes, function(taxonomyType) {
this.taxonomies[taxonomyType] = {}
}, this)
}
PostManager.prototype.add = function(post) {
this.posts.push(post)
_.each(this.taxonomyTypes, function(taxonomyType) {
var taxonomyTypePlural = inflector.pluralize(taxonomyType)
if (post[taxonomyTypePlural]) {
_.each(post[taxonomyTypePlural], function(taxonomyValue) {
this.taxonomies[taxonomyType][taxonomyValue]
|| (this.taxonomies[taxonomyType][taxonomyValue] = [])
this.taxonomies[taxonomyType].posts.push(post)
}, this)
}
}, this)
}
PostManager.prototype.all = function() {
return posts
}
PostManager.prototype.each = function(cb) {
_.each(this.posts, cb)
}
PostManager.prototype.reset = function() {
this.posts = []
}
module.exports = PostManager
| Add a method to add posts to the post manager that also categorizes them by taxonomy. | Add a method to add posts to the post manager that also categorizes them by taxonomy.
| JavaScript | mit | philipwalton/ingen | ---
+++
@@ -1,8 +1,32 @@
var _ = require('lodash-node/modern')
+var natural = require('natural')
+var inflector = new natural.NounInflector()
// TODO: consider passing the taxonomy types to the constructor
-function PostManager() {
+function PostManager(taxonomyTypes) {
this.posts = []
+ this.taxonomyTypes = taxonomyTypes
+ this.taxonomies = {}
+ _.each(this.taxonomyTypes, function(taxonomyType) {
+ this.taxonomies[taxonomyType] = {}
+ }, this)
+}
+
+PostManager.prototype.add = function(post) {
+ this.posts.push(post)
+ _.each(this.taxonomyTypes, function(taxonomyType) {
+ var taxonomyTypePlural = inflector.pluralize(taxonomyType)
+ if (post[taxonomyTypePlural]) {
+ _.each(post[taxonomyTypePlural], function(taxonomyValue) {
+
+ this.taxonomies[taxonomyType][taxonomyValue]
+ || (this.taxonomies[taxonomyType][taxonomyValue] = [])
+ this.taxonomies[taxonomyType].posts.push(post)
+
+ }, this)
+ }
+ }, this)
+
}
PostManager.prototype.all = function() { |
c59d6500c9bad9d0c2b3745c71010797c4a107fc | lib/query-parser.js | lib/query-parser.js | 'use strict'
/**
* @license
* node-scrapy <https://github.com/eeshi/node-scrapy>
* Copyright Stefan Maric, Adrian Obelmejias, and other contributors <https://github.com/eeshi/node-scrapy/graphs/contributors>
* Released under MIT license <https://github.com/eeshi/node-scrapy/blob/master/LICENSE>
*/
module.exports = exports = queryParser
function queryParser (query) {
return {
selector: extractSelector(query),
getter: extractGetter(query),
filters: extractFilters(query)
}
}
function extractSelector (query) {
return query.split(/\s*=>\s*/)[0]
}
function extractGetter (query) {
let matches = query.match(/=>([^|]+)/)
return matches ? matches[1].replace(/\s/g, '') : null
}
function extractFilters (query) {
return query.split(/\s*\|\s*/).slice(1).map(extractFilter)
}
function extractFilter (filterString) {
return {
name: filterString.match(/^\w+/)[0],
args: filterString.split(/:/).slice(1)
}
}
| 'use strict'
/**
* @license
* node-scrapy <https://github.com/eeshi/node-scrapy>
* Copyright Stefan Maric, Adrian Obelmejias, and other contributors <https://github.com/eeshi/node-scrapy/graphs/contributors>
* Released under MIT license <https://github.com/eeshi/node-scrapy/blob/master/LICENSE>
*/
module.exports = exports = queryParser
function queryParser (query) {
return {
selector: extractSelector(query),
getter: extractGetter(query),
filters: extractFilters(query)
}
}
function extractSelector (query) {
return query.split(/\s*(=>|\|)\s*/)[0]
}
function extractGetter (query) {
let matches = query.match(/=>([^|]+)/)
return matches ? matches[1].replace(/\s/g, '') : null
}
function extractFilters (query) {
return query.split(/\s*\|\s*/).slice(1).map(extractFilter)
}
function extractFilter (filterString) {
return {
name: filterString.match(/^\w+/)[0],
args: filterString.split(/:/).slice(1)
}
}
| Exclude filter expression from selector | Exclude filter expression from selector
| JavaScript | mit | eeshi/node-scrapy | ---
+++
@@ -18,7 +18,7 @@
}
function extractSelector (query) {
- return query.split(/\s*=>\s*/)[0]
+ return query.split(/\s*(=>|\|)\s*/)[0]
}
function extractGetter (query) { |
daf3d146f9049a2ecc6cd732742fbc6d1b5ca2fc | lib/storeQuery/when.js | lib/storeQuery/when.js | var Statuses = require('../internalConstants').Statuses;
function when(handlers) {
handlers || (handlers = {});
var status = this.status;
var handler = handlers[status.toLowerCase()];
if (!handler) {
throw new Error('Could not find a ' + status + ' handler');
}
switch (status) {
case Statuses.PENDING:
return handler();
case Statuses.FAILED:
return handler(this.error);
case Statuses.DONE:
return handler(this.result);
}
}
module.exports = when; | var Statuses = require('../internalConstants').Statuses;
function when(handlers) {
handlers || (handlers = {});
var status = this.status;
var handler = handlers[status.toLowerCase()];
if (!handler) {
throw new Error('Could not find a ' + status + ' handler');
}
switch (status) {
case Statuses.PENDING:
return handler.call(handlers);
case Statuses.FAILED:
return handler.call(handlers, this.error);
case Statuses.DONE:
return handler.call(handlers, this.result);
}
}
module.exports = when; | Allow you to call other handler from a handler | Allow you to call other handler from a handler
| JavaScript | mit | kwangkim/marty,oliverwoodings/marty,bigardone/marty,martyjs/marty,kwangkim/marty,Driftt/marty,martyjs/marty,CumpsD/marty-lib,thredup/marty-lib,thredup/marty,bigardone/marty,kwangkim/marty,goldensunliu/marty-lib,martyjs/marty-lib,bigardone/marty,oliverwoodings/marty,Driftt/marty,gmccrackin/marty-lib,thredup/marty,KeKs0r/marty-lib | ---
+++
@@ -12,11 +12,11 @@
switch (status) {
case Statuses.PENDING:
- return handler();
+ return handler.call(handlers);
case Statuses.FAILED:
- return handler(this.error);
+ return handler.call(handlers, this.error);
case Statuses.DONE:
- return handler(this.result);
+ return handler.call(handlers, this.result);
}
}
|
19ba468f68bab037a04277edae68fc94e89378e5 | lib/ui/dashboard.js | lib/ui/dashboard.js | var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var serveStatic = require('serve-static');
var errorhandler = require('errorhandler');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, bodyParser());
application.use(prefix, methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, serveStatic(path.join(topDirectory, 'public')));
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
application.use(prefix, errorhandler());
}
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
| var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var serveStatic = require('serve-static');
var errorhandler = require('errorhandler');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, bodyParser.json());
application.use(prefix, methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, serveStatic(path.join(topDirectory, 'public')));
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
application.use(prefix, errorhandler());
}
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
| Use bodyParser.json() instead of bodyParser itself. | Use bodyParser.json() instead of bodyParser itself.
See: http://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4
| JavaScript | mit | KitaitiMakoto/express-droonga,droonga/express-droonga,droonga/express-droonga,KitaitiMakoto/express-droonga | ---
+++
@@ -16,7 +16,7 @@
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
- application.use(prefix, bodyParser());
+ application.use(prefix, bodyParser.json());
application.use(prefix, methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, serveStatic(path.join(topDirectory, 'public'))); |
c8c85828f4a82f45484d868efed645041b698536 | app/js/lib/graph_sketcher/bezier.js | app/js/lib/graph_sketcher/bezier.js | define(['../math.js', '../../app/directives/graph_sketcher/GraphUtils.js'], function(m, graphUtils) {
return {
numOfPts: 100,
lineStyle: function(pts) {
let n = pts.length - 1;
let comb = [];
let r;
for (let r = 0; r <= n; r += 1) {
// from the other math library!!!! not the same as Math!!!!
comb.push(m.combinations(n, r));
}
let step = 1 / this.numOfPts;
let bezier = [];
let u;
let i;
let tmp1;
let tmp2;
let tmp3;
for (let i = 0; i < this.numOfPts; i += 1) {
u = i * step;
let sx = 0;
let sy = 0;
for (r = 0; r <= n; r += 1) {
tmp1 = Math.pow(u, r);
tmp2 = Math.pow(1 - u, n - r);
tmp3 = comb[r] * tmp1 * tmp2;
sx += tmp3 * pts[r].x;
sy += tmp3 * pts[r].y;
}
bezier.push(graphUtils.createPoint(sx, sy, i));
}
bezier.push(pts[pts.length - 1]);
return bezier;
}
}
});
| define(['../math.js', '../../app/directives/graph_sketcher/GraphUtils.js'], function(m, graphUtils) {
return {
numOfPts: 100,
lineStyle: function(pts) {
let n = pts.length - 1;
let comb = [];
for (let r = 0; r <= n; r += 1) {
// from the other math library!!!! not the same as Math!!!!
comb.push(m.combinations(n, r));
}
let step = 1 / this.numOfPts;
let bezier = [];
let u;
let tmp1;
let tmp2;
let tmp3;
for (let i = 0; i < this.numOfPts; i += 1) {
u = i * step;
let sx = 0;
let sy = 0;
for (let r = 0; r <= n; r += 1) {
tmp1 = Math.pow(u, r);
tmp2 = Math.pow(1 - u, n - r);
tmp3 = comb[r] * tmp1 * tmp2;
sx += tmp3 * pts[r].x;
sy += tmp3 * pts[r].y;
}
bezier.push(graphUtils.createPoint(sx, sy, i));
}
bezier.push(pts[pts.length - 1]);
return bezier;
}
}
});
| Add additional 'let' decleration for inner loop and clean up | Add additional 'let' decleration for inner loop and clean up
| JavaScript | mit | ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app,ucam-cl-dtg/isaac-app | ---
+++
@@ -6,7 +6,6 @@
let n = pts.length - 1;
let comb = [];
- let r;
for (let r = 0; r <= n; r += 1) {
// from the other math library!!!! not the same as Math!!!!
comb.push(m.combinations(n, r));
@@ -16,7 +15,6 @@
let bezier = [];
let u;
- let i;
let tmp1;
let tmp2;
let tmp3;
@@ -25,7 +23,7 @@
u = i * step;
let sx = 0;
let sy = 0;
- for (r = 0; r <= n; r += 1) {
+ for (let r = 0; r <= n; r += 1) {
tmp1 = Math.pow(u, r);
tmp2 = Math.pow(1 - u, n - r);
tmp3 = comb[r] * tmp1 * tmp2; |
135011f4551a81e7f57ad373ca8c25cdfde49032 | vue-typescript.js | vue-typescript.js | /* eslint-env node */
module.exports = {
extends: [ "@vue/typescript", "./typescript.js" ],
parser: require.resolve("vue-eslint-parser"),
parserOptions: {
parser: "@typescript-eslint/parser",
sourceType: "module",
ecmaFeatures: { jsx: true },
warnOnUnsupportedTypeScriptVersion: false
},
rules: {}
};
| /* eslint-env node */
module.exports = {
extends: [ "./typescript.js" ],
parser: require.resolve("vue-eslint-parser"),
parserOptions: {
parser: "@typescript-eslint/parser",
sourceType: "module",
ecmaFeatures: { jsx: true },
warnOnUnsupportedTypeScriptVersion: false,
project: "./tsconfig.json",
extraFileExtensions: [ ".vue" ]
},
rules: {}
};
| Fix for recent changes to typescript plugin | Fix for recent changes to typescript plugin
| JavaScript | mit | launchbadge/eslint-config-launchbadge | ---
+++
@@ -1,12 +1,14 @@
/* eslint-env node */
module.exports = {
- extends: [ "@vue/typescript", "./typescript.js" ],
+ extends: [ "./typescript.js" ],
parser: require.resolve("vue-eslint-parser"),
parserOptions: {
parser: "@typescript-eslint/parser",
sourceType: "module",
ecmaFeatures: { jsx: true },
- warnOnUnsupportedTypeScriptVersion: false
+ warnOnUnsupportedTypeScriptVersion: false,
+ project: "./tsconfig.json",
+ extraFileExtensions: [ ".vue" ]
},
rules: {}
}; |
84cddaa35ebcd2a80313f715598e6fd07e964ec5 | js/src/forum/addLockControl.js | js/src/forum/addLockControl.js | import { extend } from 'flarum/extend';
import DiscussionControls from 'flarum/utils/DiscussionControls';
import DiscussionPage from 'flarum/components/DiscussionPage';
import Button from 'flarum/components/Button';
export default function addLockControl() {
extend(DiscussionControls, 'moderationControls', function(items, discussion) {
if (discussion.canLock()) {
items.add('lock', Button.component({
children: app.translator.trans(discussion.isLocked() ? 'flarum-lock.forum.discussion_controls.unlock_button' : 'flarum-lock.forum.discussion_controls.lock_button'),
icon: 'fas fa-lock',
onclick: this.lockAction.bind(discussion)
}));
}
});
DiscussionControls.lockAction = function() {
this.save({isLocked: !this.isLocked()}).then(() => {
if (app.current instanceof DiscussionPage) {
app.current.stream.update();
}
m.redraw();
});
};
}
| import { extend } from 'flarum/extend';
import DiscussionControls from 'flarum/utils/DiscussionControls';
import DiscussionPage from 'flarum/components/DiscussionPage';
import Button from 'flarum/components/Button';
export default function addLockControl() {
extend(DiscussionControls, 'moderationControls', function(items, discussion) {
if (discussion.canLock()) {
items.add('lock', Button.component({
children: app.translator.trans(discussion.isLocked() ? 'flarum-lock.forum.discussion_controls.unlock_button' : 'flarum-lock.forum.discussion_controls.lock_button'),
icon: 'fas fa-lock',
onclick: this.lockAction.bind(discussion)
}));
}
});
DiscussionControls.lockAction = function() {
this.save({isLocked: !this.isLocked()}).then(() => {
if (app.current.matches(DiscussionPage)) {
app.current.get('stream').update();
}
m.redraw();
});
};
}
| Fix extension to work with latest state changes | Fix extension to work with latest state changes
Refs flarum/core#2156.
| JavaScript | mit | flarum/flarum-ext-lock,flarum/flarum-ext-lock | ---
+++
@@ -16,8 +16,8 @@
DiscussionControls.lockAction = function() {
this.save({isLocked: !this.isLocked()}).then(() => {
- if (app.current instanceof DiscussionPage) {
- app.current.stream.update();
+ if (app.current.matches(DiscussionPage)) {
+ app.current.get('stream').update();
}
m.redraw(); |
02310d90f950e0e4a5fdd493f57978fae681a429 | webpack.config.js | webpack.config.js | 'use strict';
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['babel-polyfill', './src/js/reactTest.jsx'],
output: {
path: './public/js',
filename: 'reactTest.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src/js/'),
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
}
]
}
}; | 'use strict';
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['babel-polyfill', './src/js/reactTest.jsx'],
output: {
path: path.resolve(__dirname, 'public/js'),
filename: 'reactTest.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src/js/'),
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
}
]
}
}; | Use absolute path for output folder of webpack | Use absolute path for output folder of webpack
| JavaScript | agpl-3.0 | BreakOutEvent/breakout-frontend | ---
+++
@@ -5,7 +5,7 @@
module.exports = {
entry: ['babel-polyfill', './src/js/reactTest.jsx'],
output: {
- path: './public/js',
+ path: path.resolve(__dirname, 'public/js'),
filename: 'reactTest.js'
},
module: { |
1a9912ec8f7579ddc1f440015933f905070b3974 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack')
module.exports = {
module: {
rules: [
{
test: /\.html$/,
use: 'raw-loader'
}
]
},
resolve: {
modules: ['public/js', 'views/current', 'node_modules']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
entry: './public/js/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
| const path = require('path');
const webpack = require('webpack');
module.exports = {
module: {
rules: [
{
test: /\.html$/,
use: 'raw-loader'
}
]
},
resolve: {
modules: ['public/js', 'views/current', 'node_modules']
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.optimize.UglifyJsPlugin()
],
entry: './public/js/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'eval-source-map'
};
| Add source maps and uglifyjs | Webpack: Add source maps and uglifyjs
| JavaScript | mit | iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher | ---
+++
@@ -1,5 +1,5 @@
const path = require('path');
-const webpack = require('webpack')
+const webpack = require('webpack');
module.exports = {
module: {
@@ -17,11 +17,13 @@
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
- })
+ }),
+ new webpack.optimize.UglifyJsPlugin()
],
entry: './public/js/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
- }
+ },
+ devtool: 'eval-source-map'
}; |
811816ad35cda5c1baa16d00ed20276faa052401 | webpack.config.js | webpack.config.js | var webpack = require("webpack");
/* eslint-disable no-undef */
var environment = process.env["NODE_ENV"] || "development";
module.exports = {
entry: "./src/game",
output: {
path: __dirname + "/build",
filename: "index.js"
},
module: {
preLoaders: [
// { test: /\.js$/, exclude: /node_modules/, loader: "eslint" }
],
loaders: [
{ test: /\.json$/, loader: "json" },
{
test: /src\/images\/.*\.(jpe?g|png|gif|svg)$/i,
loaders: [
"file?hash=sha512&digest=hex&name=images/[name].[ext]",
"image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false"
]
},
{
test: /src\/sounds\/.*\.(mp3|ogg|wav)$/i,
loader: "file?hash=sha512&digest=hex&name=sounds/[name].[ext]"
},
{
test: /src\/index.html$/i,
loader: "file?hash=sha512&digest=hex&name=[name].[ext]"
}
]
},
plugins: [
new webpack.DefinePlugin({
__PRODUCTION__: environment === "production",
__TEST__: environment === "test",
__DEVELOPMENT__: environment === "development"
})
]
};
| var webpack = require("webpack");
/* eslint-disable no-undef */
var environment = process.env["NODE_ENV"] || "development";
module.exports = {
entry: "./src/game",
output: {
path: __dirname + "/build",
filename: "index.js"
},
module: {
preLoaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "eslint-loader" }
],
loaders: [
{ test: /\.json$/, loader: "json" },
{
test: /src\/images\/.*\.(jpe?g|png|gif|svg)$/i,
loaders: [
"file?hash=sha512&digest=hex&name=images/[name].[ext]",
"image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false"
]
},
{
test: /src\/sounds\/.*\.(mp3|ogg|wav)$/i,
loader: "file?hash=sha512&digest=hex&name=sounds/[name].[ext]"
},
{
test: /src\/index.html$/i,
loader: "file?hash=sha512&digest=hex&name=[name].[ext]"
}
]
},
plugins: [
new webpack.DefinePlugin({
__PRODUCTION__: environment === "production",
__TEST__: environment === "test",
__DEVELOPMENT__: environment === "development"
})
]
};
| Use eslint inside of webpack | Use eslint inside of webpack
| JavaScript | mit | RiseAndShineGames/BugCatcher,RiseAndShineGames/LudumDare35,RiseAndShineGames/Polymorphic,RiseAndShineGames/Polymorphic,RiseAndShineGames/BugCatcher,CaldwellYSR/Bug_Catcher,RiseAndShineGames/LudumDare35,SplatJS/splat-ecs-starter-project,SplatJS/splat-ecs-starter-project,CaldwellYSR/Bug_Catcher | ---
+++
@@ -11,7 +11,7 @@
},
module: {
preLoaders: [
- // { test: /\.js$/, exclude: /node_modules/, loader: "eslint" }
+ { test: /\.js$/, exclude: /node_modules/, loader: "eslint-loader" }
],
loaders: [
{ test: /\.json$/, loader: "json" }, |
7f52d1670b86f9e750ada848b39a5e94417ed7ff | webpack.config.js | webpack.config.js | var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: [
'./js/index.js'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader'
]
},
{
test: /\.less$/,
loader: 'style!css!less!'
},
{
test: /\.json$/,
loader: "json-loader"
},
{
test: /\.(png|jpg|gif)$/,
// inline base64 URLs for <=8k images, direct URLs for the rest
loader: 'url-loader?limit=8192'
},
{
// Support ?123 suffix, e.g. ../fonts/m4d-icons.eot?3179539#iefix in react-responsive-carousel.less
test: /\.(eot|ttf|woff|woff2|svg)((\?|\#).*)?$/,
loader: 'url-loader?limit=8192'
}
]
},
plugins: [
new CopyWebpackPlugin([
{from: 'public'}
])
]
};
| var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: [
'./js/index.js'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel'
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader'
]
},
{
test: /\.less$/,
loader: 'style!css!less!'
},
{
test: /\.json$/,
loader: "json-loader"
},
{
test: /\.(png|jpg|gif)$/,
// inline base64 URLs for <=8k images, direct URLs for the rest
loader: 'url-loader?limit=8192'
},
{
// Support ?123 suffix, e.g. ../fonts/m4d-icons.eot?3179539#iefix in react-responsive-carousel.less
test: /\.(eot|ttf|woff|woff2|svg)((\?|\#).*)?$/,
loader: 'url-loader?limit=8192'
}
]
},
devtool: "source-map",
plugins: [
new CopyWebpackPlugin([
{from: 'public'}
])
]
};
| Use source maps in developer mode. | Use source maps in developer mode.
| JavaScript | mit | concord-consortium/portal-report,concord-consortium/portal-report,concord-consortium/portal-report,concord-consortium/portal-report | ---
+++
@@ -44,6 +44,7 @@
}
]
},
+ devtool: "source-map",
plugins: [
new CopyWebpackPlugin([
{from: 'public'} |
964f13a57f83d8418e8a9b82a0a93b5886862ff8 | webpack.config.js | webpack.config.js | module.exports = {
entry: {
javascript: "./app/app.jsx"
},
output: {
path: __dirname,
filename: "bundle.js"
},
resolve: {
extensions: ["", ".json", ".js", ".jsx"]
},
module: {
noParse: [/autoit.js/],
loaders: [
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.jsx$/,
loaders: ["react-hot", "babel-loader"]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
]
},
devtool: "#inline-source-map"
}
| module.exports = {
entry: {
javascript: "./app/app.jsx"
},
output: {
path: __dirname,
filename: "bundle.js"
},
resolve: {
extensions: ["", ".json", ".js", ".jsx"]
},
module: {
noParse: [/autoit.js/],
loaders: [
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.jsx$/,
loaders: ["react-hot", "babel-loader"]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
]
},
devtool: 'source-map'
}
| Fix sourcemap for dev mode | Fix sourcemap for dev mode
| JavaScript | apache-2.0 | anildigital/ruby-operators,anildigital/ruby-operators | ---
+++
@@ -30,5 +30,5 @@
]
},
- devtool: "#inline-source-map"
+ devtool: 'source-map'
} |
d151aed6079c78314f2192a551c49d3fbd2e44d5 | webpack.config.js | webpack.config.js | 'use strict';
const webpack = require('webpack');
const env = process.env.NODE_ENV || 'development';
const isDev = env === 'development';
const devtool = isDev ? '#inline-source-map' : null;
const uglify = isDev ? null : new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
dead_code: true, // eslint-disable-line camelcase
warnings: false
}
});
const plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(env)
}
}),
uglify
].filter(v => v);
module.exports = {
cache: true,
entry: [
'babel-polyfill',
'./renderer/index.js'
],
debug: env === 'development',
devtool,
output: {
path: `${__dirname}/dist`,
filename: 'bundle.js'
},
plugins,
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel?cacheDirectory',
exclude: /node_modules/
}
]
}
};
| 'use strict';
const webpack = require('webpack');
const env = process.env.NODE_ENV || 'development';
const isDev = env === 'development';
const devtool = isDev ? '#inline-source-map' : null;
const uglify = isDev ? null : new webpack.optimize.UglifyJsPlugin({
output: {
comments: false
},
compress: {
dead_code: true, // eslint-disable-line camelcase
warnings: false
}
});
const plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(env)
}
}),
uglify
].filter(v => v);
module.exports = {
cache: true,
entry: [
'babel-polyfill',
'./renderer/index.js'
],
debug: env === 'development',
target: 'electron',
devtool,
output: {
path: `${__dirname}/dist`,
filename: 'bundle.js'
},
plugins,
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel?cacheDirectory',
exclude: /node_modules/
}
]
}
};
| Add renderer setting for electron | Add renderer setting for electron
| JavaScript | mit | akameco/PixivDeck,akameco/PixivDeck | ---
+++
@@ -31,6 +31,7 @@
'./renderer/index.js'
],
debug: env === 'development',
+ target: 'electron',
devtool,
output: {
path: `${__dirname}/dist`, |
9697b8d10a8312fb9e07009ce62a8e380e68bc76 | test/js/organismDetailsSpec.js | test/js/organismDetailsSpec.js | describe("Test the organismDetails file", function() {
it("Test for getBestName", function() {
expect(getBestName({})).toBe('');
});
}); | describe("Test the organismDetails file", function() {
it("Test for getBestName on empty set", function() {
expect(getBestName({})).toBe('');
});
it("Test for getBestName with only sciname", function() {
expect(getBestName({'scientificName': 'Mus musculus'})).toBe('Mus musculus');
expect(getBestName({'scientificName': 'Vulpes zerda', 'vernacularNames': []})).toBe('Vulpes zerda');
});
it("Test for getBestName with common names (no preffered name)", function() {
expect(getBestName({'scientificName': 'Vulpes zerda', 'vernacularNames': [{'language': 'en', 'vernacularName': 'Fennec'}]})).toBe('Fennec');
});
it("Test for getBestName with common names (preffered name)", function() {
expect(getBestName({})).toBe('');
});
}); | Expand test case for getBestName | Expand test case for getBestName
| JavaScript | mit | molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec,molbiodiv/fennec | ---
+++
@@ -1,6 +1,16 @@
describe("Test the organismDetails file", function() {
- it("Test for getBestName", function() {
+ it("Test for getBestName on empty set", function() {
+ expect(getBestName({})).toBe('');
+ });
+ it("Test for getBestName with only sciname", function() {
+ expect(getBestName({'scientificName': 'Mus musculus'})).toBe('Mus musculus');
+ expect(getBestName({'scientificName': 'Vulpes zerda', 'vernacularNames': []})).toBe('Vulpes zerda');
+ });
+ it("Test for getBestName with common names (no preffered name)", function() {
+ expect(getBestName({'scientificName': 'Vulpes zerda', 'vernacularNames': [{'language': 'en', 'vernacularName': 'Fennec'}]})).toBe('Fennec');
+ });
+ it("Test for getBestName with common names (preffered name)", function() {
expect(getBestName({})).toBe('');
});
}); |
17455c2529c6dcbbee0fc21c8a89546be9472790 | src/ol/colorlike.js | src/ol/colorlike.js | /**
* @module ol/colorlike
*/
import {asString} from './color.js';
/**
* @param {ol.Color|ol.ColorLike} color Color.
* @return {ol.ColorLike} The color as an ol.ColorLike
* @api
*/
export function asColorLike(color) {
if (isColorLike(color)) {
return /** @type {string|CanvasPattern|CanvasGradient} */ (color);
} else {
return asString(/** @type {ol.Color} */ (color));
}
}
/**
* @param {?} color The value that is potentially an ol.ColorLike
* @return {boolean} Whether the color is an ol.ColorLike
*/
export function isColorLike(color) {
return (
typeof color === 'string' ||
color instanceof CanvasPattern ||
color instanceof CanvasGradient
);
}
| /**
* @module ol/colorlike
*/
import {toString} from './color.js';
/**
* @param {ol.Color|ol.ColorLike} color Color.
* @return {ol.ColorLike} The color as an ol.ColorLike
* @api
*/
export function asColorLike(color) {
if (isColorLike(color)) {
return /** @type {string|CanvasPattern|CanvasGradient} */ (color);
} else {
return toString(/** @type {ol.Color} */ (color));
}
}
/**
* @param {?} color The value that is potentially an ol.ColorLike
* @return {boolean} Whether the color is an ol.ColorLike
*/
export function isColorLike(color) {
return (
typeof color === 'string' ||
color instanceof CanvasPattern ||
color instanceof CanvasGradient
);
}
| Use toString instead of asString in asColorLike | Use toString instead of asString in asColorLike
To avoid the double `typeof color === 'string'` check
| JavaScript | bsd-2-clause | ahocevar/ol3,stweil/openlayers,fredj/ol3,gingerik/ol3,mzur/ol3,openlayers/openlayers,stweil/ol3,oterral/ol3,stweil/openlayers,adube/ol3,ahocevar/ol3,stweil/ol3,geekdenz/ol3,mzur/ol3,fredj/ol3,tschaub/ol3,bjornharrtell/ol3,geekdenz/openlayers,fredj/ol3,geekdenz/openlayers,geekdenz/ol3,stweil/openlayers,tschaub/ol3,oterral/ol3,gingerik/ol3,tschaub/ol3,adube/ol3,adube/ol3,geekdenz/openlayers,tschaub/ol3,gingerik/ol3,openlayers/openlayers,ahocevar/openlayers,mzur/ol3,openlayers/openlayers,stweil/ol3,ahocevar/openlayers,oterral/ol3,fredj/ol3,mzur/ol3,geekdenz/ol3,ahocevar/ol3,ahocevar/ol3,bjornharrtell/ol3,bjornharrtell/ol3,geekdenz/ol3,ahocevar/openlayers,stweil/ol3,gingerik/ol3 | ---
+++
@@ -1,7 +1,7 @@
/**
* @module ol/colorlike
*/
-import {asString} from './color.js';
+import {toString} from './color.js';
/**
@@ -13,7 +13,7 @@
if (isColorLike(color)) {
return /** @type {string|CanvasPattern|CanvasGradient} */ (color);
} else {
- return asString(/** @type {ol.Color} */ (color));
+ return toString(/** @type {ol.Color} */ (color));
}
}
|
83cb7f4c548d02de3d0ef1157e9a412e9a92f1f9 | npm/test-lint.js | npm/test-lint.js | #!/usr/bin/env node
require('shelljs/global');
require('colors');
var async = require('async'),
ESLintCLIEngine = require('eslint').CLIEngine,
LINT_SOURCE_DIRS = [
'./lib/runner',
'./lib/authorizer',
'./lib/uvm/*.js',
'./lib/backpack',
'./test/system',
'./test/unit',
'./test/integration',
'./npm/*.js',
'./index.js'
];
module.exports = function (exit) {
// banner line
console.log('\nLinting files using eslint...'.yellow.bold);
async.waterfall([
// execute the CLI engine
function (next) {
next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS));
},
// output results
function (report, next) {
var errorReport = ESLintCLIEngine.getErrorResults(report.results);
// log the result to CLI
console.log(ESLintCLIEngine.getFormatter()(report.results));
// log the success of the parser if it has no errors
(errorReport && !errorReport.length) && console.log('eslint ok!'.green);
// ensure that the exit code is non zero in case there was an error
next(Number(errorReport && errorReport.length) || 0);
}
], exit);
};
// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
| #!/usr/bin/env node
require('shelljs/global');
require('colors');
var async = require('async'),
ESLintCLIEngine = require('eslint').CLIEngine,
LINT_SOURCE_DIRS = [
'./lib',
'./test/system',
'./test/unit',
'./test/integration',
'./npm/*.js',
'./index.js'
];
module.exports = function (exit) {
// banner line
console.log('\nLinting files using eslint...'.yellow.bold);
async.waterfall([
// execute the CLI engine
function (next) {
next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS));
},
// output results
function (report, next) {
var errorReport = ESLintCLIEngine.getErrorResults(report.results);
// log the result to CLI
console.log(ESLintCLIEngine.getFormatter()(report.results));
// log the success of the parser if it has no errors
(errorReport && !errorReport.length) && console.log('eslint ok!'.green);
// ensure that the exit code is non zero in case there was an error
next(Number(errorReport && errorReport.length) || 0);
}
], exit);
};
// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
| Add all directories under lib to eslint config | Add all directories under lib to eslint config
| JavaScript | apache-2.0 | postmanlabs/postman-runtime,postmanlabs/postman-runtime | ---
+++
@@ -6,10 +6,7 @@
ESLintCLIEngine = require('eslint').CLIEngine,
LINT_SOURCE_DIRS = [
- './lib/runner',
- './lib/authorizer',
- './lib/uvm/*.js',
- './lib/backpack',
+ './lib',
'./test/system',
'./test/unit',
'./test/integration', |
743f896c562cd8cc9089937fc69c2d89e62f2466 | src/bin/scry-css.js | src/bin/scry-css.js | #! /usr/bin/env node
const program = require('commander')
const PipelineRunner = require('../pipeline/runner')
program
.version('scry-css 0.2.0')
.usage('[options] <type> <dir> <file...>')
.option('-r --reporter [reporter]', 'Reporter', /^(console|json)$/i)
.parse(process.argv)
if (!program.args.length) {
program.help()
} else {
PipelineRunner.run(program.reporter || 'console', ...program.args).then((summary) => {
console.log(summary) // eslint-disable-line no-console
})
}
| #! /usr/bin/env node
const program = require('commander')
const PipelineRunner = require('../pipeline/runner')
program
.version('scry-css 0.2.1')
.usage('[options] <type> <dir> <file...>')
.option(
'-r --reporter [reporter]',
'reporter (json/console), defaults to console', /^(console|json)$/i
)
.parse(process.argv)
if (!program.args.length) {
program.help()
} else {
PipelineRunner.run(program.reporter || 'console', ...program.args).then((summary) => {
console.log(summary) // eslint-disable-line no-console
})
}
| Fix version and improve help message. | Fix version and improve help message.
| JavaScript | mit | ovidiubute/scry-css | ---
+++
@@ -4,9 +4,12 @@
const PipelineRunner = require('../pipeline/runner')
program
- .version('scry-css 0.2.0')
+ .version('scry-css 0.2.1')
.usage('[options] <type> <dir> <file...>')
- .option('-r --reporter [reporter]', 'Reporter', /^(console|json)$/i)
+ .option(
+ '-r --reporter [reporter]',
+ 'reporter (json/console), defaults to console', /^(console|json)$/i
+ )
.parse(process.argv)
if (!program.args.length) { |
6a654de28eee0b37505e7623ddffcd3d1164a07d | middleware/index.js | middleware/index.js | var fs = require('fs'),
path = require('path')
files = fs.readdirSync(__dirname);
// load in each file within this directory and attach it to exports
files.forEach(function(file) {
var name = path.basename(file, '.js');
if (name === 'index') return;
module.exports[name] = require('./' + name);
}); | var fs = require('fs'),
path = require('path')
files = fs.readdirSync(__dirname);
// load in each file within this directory and attach it to exports
files.forEach(function(file) {
var name = path.basename(file, '.js'),
regex = new RegExp(/^_/);
if (name === 'index' || name.match(regex) !== null) {
return;
}
module.exports[name] = require('./' + name);
});
| Update middleware loader to ignore any files with a leading '_'. | Update middleware loader to ignore any files with a leading '_'.
| JavaScript | mit | linzjs/linz,linzjs/linz,linzjs/linz | ---
+++
@@ -4,10 +4,13 @@
// load in each file within this directory and attach it to exports
files.forEach(function(file) {
-
- var name = path.basename(file, '.js');
-
- if (name === 'index') return;
+
+ var name = path.basename(file, '.js'),
+ regex = new RegExp(/^_/);
+
+ if (name === 'index' || name.match(regex) !== null) {
+ return;
+ }
module.exports[name] = require('./' + name);
|
763798205711ef7b14876f47cda4dd63aaf21427 | devmgmtV2/index.js | devmgmtV2/index.js | "use strict"
let express = require("express");
let bodyParser = require('body-parser');
let cors = require('cors');
let app = express();
let { exec } = require('child_process')
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
require('./routes/auth.routes.js')(app);
require('./routes/users.routes.js')(app);
require('./routes/upgrade.routes.js')(app);
require('./routes/dashboard.routes.js')(app);
require('./routes/filemgmt.routes.js')(app);
require('./routes/ssid.routes.js')(app);
require('./routes/captive.routes.js')(app);
app.listen(8080, err => {
if (err)
console.log(err);
else {
console.log("server running on port 8080");
exec('mysql -u root -p < ./init.sql', (err, stdout, stderr) => {
if (err) {
console.log("error in init script");
} else {
console.log("init script success");
}
});
}
});
| "use strict"
let express = require("express");
let bodyParser = require('body-parser');
let cors = require('cors');
let app = express();
let { exec } = require('child_process')
app.use(cors())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
require('./routes/auth.routes.js')(app);
require('./routes/users.routes.js')(app);
require('./routes/upgrade.routes.js')(app);
require('./routes/dashboard.routes.js')(app);
require('./routes/filemgmt.routes.js')(app);
require('./routes/ssid.routes.js')(app);
require('./routes/captive.routes.js')(app);
app.listen(8080, err => {
if (err)
console.log(err);
else {
console.log("server running on port 8080");
exec('mysql -u root -proot < ./init.sql', (err, stdout, stderr) => {
if (err) {
console.log(err);
console.log("error in init script");
} else {
console.log("init script success");
}
});
exec('NODE_PATH=$NODE_PATH:"/opt/opencdn/" node writeToDB.js', (err, stdout, stderr) => {
if (err) {
console.log(err);
console.log("DB Initialization error");
} else {
console.log(stdout);
}
});
}
});
| Fix init scripts and add NODE_PATH | Fix init scripts and add NODE_PATH
| JavaScript | mit | projectOpenRAP/OpenRAP,projectOpenRAP/OpenRAP,projectOpenRAP/OpenRAP,projectOpenRAP/OpenRAP,projectOpenRAP/OpenRAP | ---
+++
@@ -26,12 +26,21 @@
console.log(err);
else {
console.log("server running on port 8080");
- exec('mysql -u root -p < ./init.sql', (err, stdout, stderr) => {
+ exec('mysql -u root -proot < ./init.sql', (err, stdout, stderr) => {
if (err) {
+ console.log(err);
console.log("error in init script");
} else {
console.log("init script success");
}
});
+ exec('NODE_PATH=$NODE_PATH:"/opt/opencdn/" node writeToDB.js', (err, stdout, stderr) => {
+ if (err) {
+ console.log(err);
+ console.log("DB Initialization error");
+ } else {
+ console.log(stdout);
+ }
+ });
}
}); |
f1e796076afa93d9f8a4e0b44434cd20695f3e29 | template/_footer.js | template/_footer.js | // Expose Raven to the world
window.Raven = Raven;
})(window);
|
// Expose Raven to the world
if (typeof define === 'function' && define.amd) {
define(function() { return Raven; });
} else {
window.Raven = Raven;
}
})(this);
| Make Raven compatible with CommonJS | Make Raven compatible with CommonJS
| JavaScript | bsd-3-clause | samgiles/raven-js,clara-labs/raven-js,PureBilling/raven-js,grelas/raven-js,danse/raven-js,getsentry/raven-js,danse/raven-js,getsentry/raven-js,samgiles/raven-js,benoitg/raven-js,eaglesjava/raven-js,housinghq/main-raven-js,getsentry/raven-js,vladikoff/raven-js,clara-labs/raven-js,Mappy/raven-js,hussfelt/raven-js,iodine/raven-js,iodine/raven-js,janmisek/raven-js,getsentry/raven-js,benoitg/raven-js,Mappy/raven-js,chrisirhc/raven-js,hussfelt/raven-js,malandrew/raven-js,Mappy/raven-js,janmisek/raven-js,housinghq/main-raven-js,housinghq/main-raven-js,PureBilling/raven-js,vladikoff/raven-js,grelas/raven-js,eaglesjava/raven-js,chrisirhc/raven-js,malandrew/raven-js | ---
+++
@@ -1,4 +1,9 @@
+
// Expose Raven to the world
-window.Raven = Raven;
+if (typeof define === 'function' && define.amd) {
+ define(function() { return Raven; });
+} else {
+ window.Raven = Raven;
+}
-})(window);
+})(this); |
61506b4ba4eb6ed3aadb5a02d802a92dfd520d36 | client/src/components/main/index.js | client/src/components/main/index.js | import React, { Component } from 'react';
import { connect } from 'react-redux'
import SearchBar from 'material-ui-search-bar'
import _ from 'lodash'
import './index.css'
import SearchResults from '../searchresults'
import { searchTomos } from '../../redux/ducks/tomos'
class Main extends Component {
onChange = (searchText) => {
this.setState({
searchText
})
}
onRequestSearch = () => {
const text = this.state.searchText.toLowerCase();
if (_.isString(text) && !_.isEmpty(text)) {
this.props.dispatch(searchTomos(text.split(/\s/)))
}
}
render = () => {
const searchBarStyle = {
margin: '20px auto',
maxWidth: 800
};
return (
<div>
<SearchBar
hintText={'Search by author, paper, microscope, atomic species'}
onChange={this.onChange}
onRequestSearch={this.onRequestSearch}
style={searchBarStyle}
/>
<SearchResults/>
</div>
);
}
}
function mapStateToProps(state) {
return {};
}
export default connect(mapStateToProps)(Main)
| import React, { Component } from 'react';
import { connect } from 'react-redux'
import SearchBar from 'material-ui-search-bar'
import _ from 'lodash'
import './index.css'
import SearchResults from '../searchresults'
import { searchTomos } from '../../redux/ducks/tomos'
class Main extends Component {
constructor(props)
{
super(props)
this.state = {
searchText: null
}
}
componentWillMount = () => {
this.props.dispatch(searchTomos());
}
onChange = (searchText) => {
this.setState({
searchText
})
}
onRequestSearch = () => {
if (_.isString(this.state.searchText) && !_.isEmpty(this.state.searchText)) {
const text = this.state.searchText.toLowerCase();
this.props.dispatch(searchTomos(text.split(/\s/)))
}
else {
this.props.dispatch(searchTomos());
}
}
render = () => {
const searchBarStyle = {
margin: '20px auto',
maxWidth: 800
};
return (
<div>
<SearchBar
hintText={'Search by author, paper, microscope, atomic species'}
onChange={this.onChange}
onRequestSearch={this.onRequestSearch}
style={searchBarStyle}
/>
<SearchResults/>
</div>
);
}
}
function mapStateToProps(state) {
return {};
}
export default connect(mapStateToProps)(Main)
| Load all datasets by default | Load all datasets by default
| JavaScript | bsd-3-clause | OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank,OpenChemistry/materialsdatabank | ---
+++
@@ -9,6 +9,18 @@
class Main extends Component {
+ constructor(props)
+ {
+ super(props)
+ this.state = {
+ searchText: null
+ }
+ }
+
+ componentWillMount = () => {
+ this.props.dispatch(searchTomos());
+ }
+
onChange = (searchText) => {
this.setState({
searchText
@@ -16,11 +28,17 @@
}
onRequestSearch = () => {
- const text = this.state.searchText.toLowerCase();
- if (_.isString(text) && !_.isEmpty(text)) {
+
+ if (_.isString(this.state.searchText) && !_.isEmpty(this.state.searchText)) {
+ const text = this.state.searchText.toLowerCase();
this.props.dispatch(searchTomos(text.split(/\s/)))
}
+ else {
+ this.props.dispatch(searchTomos());
+ }
}
+
+
render = () => {
|
4ae5004078a0e79ce44b61f8f63d88cb87c6fab2 | toc_view.js | toc_view.js | "use strict";
var View = require("substance-application").View;
var $$ = require("substance-application").$$;
var Data = require("substance-data");
var Index = Data.Graph.Index;
var _ = require("underscore");
// Substance.TOC.View
// ==========================================================================
var TOCView = function(docCtrl) {
View.call(this);
this.docCtrl = docCtrl;
// Sniff into headings
// --------
//
this.headings = _.filter(this.docCtrl.getNodes(), function(node) {
return node.type === "heading";
});
this.$el.addClass("toc");
};
TOCView.Prototype = function() {
// Renderer
// --------
this.render = function() {
this.el.innerHTML = "";
if (this.headings.length <= 2) return this;
_.each(this.headings, function(heading) {
this.el.appendChild($$('a.heading-ref.level-'+heading.level, {
id: "toc_"+heading.id,
text: heading.content,
"sbs-click": "jumpToNode("+heading.id+")"
}));
}, this);
return this;
};
// Renderer
// --------
//
this.setActiveNode = function(nodeId) {
this.$('.heading-ref.active').removeClass('active');
this.$('#toc_'+nodeId).addClass('active');
};
};
TOCView.Prototype.prototype = View.prototype;
TOCView.prototype = new TOCView.Prototype();
module.exports = TOCView;
| "use strict";
var View = require("substance-application").View;
var $$ = require("substance-application").$$;
var Data = require("substance-data");
var Index = Data.Graph.Index;
var _ = require("underscore");
// Substance.TOC.View
// ==========================================================================
var TOCView = function(docCtrl) {
View.call(this);
this.docCtrl = docCtrl;
this.$el.addClass("toc");
};
TOCView.Prototype = function() {
// Renderer
// --------
this.render = function() {
this.el.innerHTML = "";
this.headings = _.filter(this.docCtrl.getNodes(), function(node) {
return node.type === "heading";
});
if (this.headings.length <= 2) return this;
_.each(this.headings, function(heading) {
this.el.appendChild($$('a.heading-ref.level-'+heading.level, {
id: "toc_"+heading.id,
text: heading.content,
"sbs-click": "jumpToNode("+heading.id+")"
}));
}, this);
return this;
};
// Renderer
// --------
//
this.setActiveNode = function(nodeId) {
this.$('.heading-ref.active').removeClass('active');
this.$('#toc_'+nodeId).addClass('active');
};
};
TOCView.Prototype.prototype = View.prototype;
TOCView.prototype = new TOCView.Prototype();
module.exports = TOCView;
| Read document structure dynamically to be able to react on structural changes. | Read document structure dynamically to be able to react on structural changes.
| JavaScript | mit | substance/toc | ---
+++
@@ -13,14 +13,6 @@
View.call(this);
this.docCtrl = docCtrl;
- // Sniff into headings
- // --------
- //
-
- this.headings = _.filter(this.docCtrl.getNodes(), function(node) {
- return node.type === "heading";
- });
-
this.$el.addClass("toc");
};
@@ -31,6 +23,10 @@
this.render = function() {
this.el.innerHTML = "";
+
+ this.headings = _.filter(this.docCtrl.getNodes(), function(node) {
+ return node.type === "heading";
+ });
if (this.headings.length <= 2) return this;
_.each(this.headings, function(heading) { |
bf6d7c1082b2a9c7e80fdce81f2b3c159f4bc61a | custom/loggers/winston/index.js | custom/loggers/winston/index.js | //Winston Logger Module
const winston = require('winston');
let logLevel = "info"; //default
if (process.env.NODE_ENV === "production") {
logLevel = "error"; //logs error
}
else if (process.env.NODE_ENV === "staging") {
logLevel = "info"; //logs info and error
}
const logger = new winston.Logger({
transports: [
new winston.transports.Console({ //write prettified logs to console
colorize: true,
timestamp: true,
level: logLevel
}),
new winston.transports.File({ //write logs to a file as well
level: logLevel,
name: 'policy_logs',
filename: 'policy_logs.log'
})
],
exitOnError: false
});
module.exports = {
//required functions to implement
//normal message. log to file and to the console as an "info" message
info: function (msg) {
logger.info(msg);
},
//error message. log to file and to the console as an "error" message
error: function (msg) {
logger.error(msg);
}
} | //Winston Logger Module
const winston = require('winston');
let logLevel = "info"; //default
if (process.env.NODE_ENV === "production") {
logLevel = "error"; //logs error
}
else if (process.env.NODE_ENV === "staging") {
logLevel = "info"; //logs info and error
}
const logger = new winston.Logger({
transports: [
new winston.transports.Console({ //write prettified logs to console
colorize: true,
timestamp: true,
level: logLevel
}),
/*
new winston.transports.File({ //write logs to a file as well
level: logLevel,
name: 'policy_logs',
filename: 'policy_logs.log'
})
*/
],
exitOnError: false
});
module.exports = {
//required functions to implement
//normal message. log to file and to the console as an "info" message
info: function (msg) {
logger.info(msg);
},
//error message. log to file and to the console as an "error" message
error: function (msg) {
logger.error(msg);
}
} | Disable file logging by default | Disable file logging by default
| JavaScript | bsd-3-clause | renonick87/sdl_server,smartdevicelink/sdl_server,smartdevicelink/sdl_server,smartdevicelink/sdl_server,renonick87/sdl_server | ---
+++
@@ -16,11 +16,13 @@
timestamp: true,
level: logLevel
}),
+ /*
new winston.transports.File({ //write logs to a file as well
level: logLevel,
name: 'policy_logs',
filename: 'policy_logs.log'
})
+ */
],
exitOnError: false
}); |
a27f39fbdb3a23d2d4a8264bfa4f3ee4f7b2c701 | lib/commands/ember-cli-yuidoc.js | lib/commands/ember-cli-yuidoc.js | 'use strict';
var Y = require('yuidocjs');
var rsvp = require('rsvp');
var optsGenerator = require('../options');
module.exports = {
name: 'ember-cli-yuidoc',
description: 'Generates html documentation using YUIDoc',
run: function(opts, rawArgs) {
var options = optsGenerator.generate();
var yuidocCompiler = new Y.YUIDoc(options);
var json = yuidocCompiler.run();
var builder = new Y.DocBuilder(options, json);
return new rsvp.Promise(function(resolve) {
builder.compile(function() { resolve(); });
});
}
}
| 'use strict';
module.exports = {
name: 'ember-cli-yuidoc',
description: 'Generates html documentation using YUIDoc',
run: function(opts, rawArgs) {
var Y = require('yuidocjs');
var rsvp = require('rsvp');
var optsGenerator = require('../options');
var options = optsGenerator.generate();
var yuidocCompiler = new Y.YUIDoc(options);
var json = yuidocCompiler.run();
var builder = new Y.DocBuilder(options, json);
return new rsvp.Promise(function(resolve) {
builder.compile(function() { resolve(); });
});
}
}
| Move require statements to the run command | Move require statements to the run command
Yuidoc now requires an internet connection to work, and since this addon
is required even if you're not using it at the moment, it was preventing
users to work offline.
TODO: Fix yuidoc itself. Having local assets would also fix #14
| JavaScript | mit | cibernox/ember-cli-yuidoc,cibernox/ember-cli-yuidoc,mixonic/ember-cli-yuidoc,mixonic/ember-cli-yuidoc,greyhwndz/ember-cli-yuidoc,greyhwndz/ember-cli-yuidoc,VladimirTyrin/ember-cli-yuidoc,VladimirTyrin/ember-cli-yuidoc | ---
+++
@@ -1,8 +1,5 @@
'use strict';
-var Y = require('yuidocjs');
-var rsvp = require('rsvp');
-var optsGenerator = require('../options');
module.exports = {
name: 'ember-cli-yuidoc',
@@ -10,7 +7,10 @@
description: 'Generates html documentation using YUIDoc',
run: function(opts, rawArgs) {
- var options = optsGenerator.generate();
+ var Y = require('yuidocjs');
+ var rsvp = require('rsvp');
+ var optsGenerator = require('../options');
+ var options = optsGenerator.generate();
var yuidocCompiler = new Y.YUIDoc(options);
var json = yuidocCompiler.run(); |
70b48677ffeb89bdc83cfd6dd0e645a613d2593c | website/src/components/Home.js | website/src/components/Home.js | import React from 'react';
import LoadingContainer from '../containers/LoadingContainer';
import PathResultsContainer from '../containers/PathResultsContainer';
import ErrorMessageContainer from '../containers/ErrorMessageContainer';
import SearchButtonContainer from '../containers/SearchButtonContainer';
import ToArticleInputContainer from '../containers/ToArticleInputContainer';
import FromArticleInputContainer from '../containers/FromArticleInputContainer';
import logo from '../images/logo.png';
import {P, Logo, InputFlexContainer, MainContent} from './Home.styles';
export default () => (
<div>
<Logo src={logo} alt="Six Degrees of Wikipedia Logo" />
<MainContent>
<P>Find the shortest paths from</P>
<InputFlexContainer>
<ToArticleInputContainer />
<P style={{margin: '20px 24px'}}>to</P>
<FromArticleInputContainer />
</InputFlexContainer>
<SearchButtonContainer />
<LoadingContainer />
<PathResultsContainer />
<ErrorMessageContainer />
</MainContent>
</div>
);
| import React from 'react';
import LoadingContainer from '../containers/LoadingContainer';
import PathResultsContainer from '../containers/PathResultsContainer';
import ErrorMessageContainer from '../containers/ErrorMessageContainer';
import SearchButtonContainer from '../containers/SearchButtonContainer';
import ToArticleInputContainer from '../containers/ToArticleInputContainer';
import FromArticleInputContainer from '../containers/FromArticleInputContainer';
import logo from '../images/logo.png';
import {P, Logo, InputFlexContainer, MainContent} from './Home.styles';
export default () => (
<div>
<Logo src={logo} alt="Six Degrees of Wikipedia Logo" />
<MainContent>
<P>Find the shortest paths from</P>
<InputFlexContainer>
<FromArticleInputContainer />
<P style={{margin: '20px 24px'}}>to</P>
<ToArticleInputContainer />
</InputFlexContainer>
<SearchButtonContainer />
<LoadingContainer />
<PathResultsContainer />
<ErrorMessageContainer />
</MainContent>
</div>
);
| Fix wrong input component order | Fix wrong input component order
| JavaScript | mit | jwngr/sdow,jwngr/sdow,jwngr/sdow,jwngr/sdow | ---
+++
@@ -17,9 +17,9 @@
<MainContent>
<P>Find the shortest paths from</P>
<InputFlexContainer>
+ <FromArticleInputContainer />
+ <P style={{margin: '20px 24px'}}>to</P>
<ToArticleInputContainer />
- <P style={{margin: '20px 24px'}}>to</P>
- <FromArticleInputContainer />
</InputFlexContainer>
<SearchButtonContainer /> |
6adaa4847545b2ba7564bfc952a542d1ac9d5629 | web/static/codesearch.js | web/static/codesearch.js | "use strict";
var Codesearch = function() {
return {
socket: null,
delegate: null,
connect: function(delegate) {
if (Codesearch.socket !== null)
return;
console.log("Connecting...");
Codesearch.remote = null;
Codesearch.delegate = delegate;
var socket = io.connect(document.location.host.replace(/:\d+$/, '') + ":8910");
socket.on('connect', function () {
Codesearch.socket = socket;
if (Codesearch.delegate.on_connect)
Codesearch.delegate.on_connect();
});
socket.on('regex_error', Codesearch.delegate.error);
socket.on('match', Codesearch.delegate.match);
socket.on('search_done', Codesearch.delegate.search_done);
},
new_search: function(re, file, id) {
if (Codesearch.socket !== null)
Codesearch.socket.emit('new_search', re, file, id);
}
};
}();
| "use strict";
var Codesearch = function() {
return {
socket: null,
delegate: null,
connect: function(delegate) {
if (Codesearch.socket !== null)
return;
console.log("Connecting...");
Codesearch.remote = null;
Codesearch.delegate = delegate;
var socket = io.connect("http://" + document.location.host.replace(/:\d+$/, '') + ":8910");
socket.on('connect', function () {
Codesearch.socket = socket;
if (Codesearch.delegate.on_connect)
Codesearch.delegate.on_connect();
});
socket.on('regex_error', Codesearch.delegate.error);
socket.on('match', Codesearch.delegate.match);
socket.on('search_done', Codesearch.delegate.search_done);
},
new_search: function(re, file, id) {
if (Codesearch.socket !== null)
Codesearch.socket.emit('new_search', re, file, id);
}
};
}();
| Use a full URL for socket.io. | Use a full URL for socket.io.
| JavaScript | bsd-2-clause | lekkas/livegrep,paulproteus/livegrep,wfxiang08/livegrep,wfxiang08/livegrep,paulproteus/livegrep,wfxiang08/livegrep,lekkas/livegrep,lekkas/livegrep,lekkas/livegrep,lekkas/livegrep,paulproteus/livegrep,paulproteus/livegrep,lekkas/livegrep,paulproteus/livegrep,paulproteus/livegrep,wfxiang08/livegrep,wfxiang08/livegrep,wfxiang08/livegrep | ---
+++
@@ -9,7 +9,7 @@
console.log("Connecting...");
Codesearch.remote = null;
Codesearch.delegate = delegate;
- var socket = io.connect(document.location.host.replace(/:\d+$/, '') + ":8910");
+ var socket = io.connect("http://" + document.location.host.replace(/:\d+$/, '') + ":8910");
socket.on('connect', function () {
Codesearch.socket = socket;
if (Codesearch.delegate.on_connect) |
6a04d1e2fee23066f9647a4caa38bea3395a4bf2 | tools/pre-commit.js | tools/pre-commit.js | 'use strict';
var exec = require('child_process').exec;
function fail() {
process.stdout.write(
'Style check failed (see the above output).\n' +
'If you still wish to commit your code, run git commit -n to skip this check.\n'
);
process.exit(1);
}
exec('git diff --staged --name-status', function (error, stdout, stderr) {
if (error) {
process.stdout.write(stderr + '\nCould not get list of modified files: ' + error);
fail();
}
var expression = /^[MA]\s+([\w-\\\/]+\.js)$/gm;
var files = [];
var match;
while (match = expression.exec(stdout)) {
files.push(match[1]);
}
if (files.length === 0) {
process.exit(0);
}
var child = exec('node_modules/.bin/jshint --reporter=tools/jshint-reporter.js ' + files.join(' '));
child.stdout.on('data', function (data) {
process.stdout.write(data);
});
child.stderr.on('data', function (data) {
process.stderr.write(data);
});
child.on('exit', function (code) {
if (code !== 0) {
fail();
} else {
process.exit(0);
}
});
});
| 'use strict';
var exec = require('child_process').exec;
var path = require('path');
function fail() {
process.stdout.write(
'Style check failed (see the above output).\n' +
'If you still wish to commit your code, run git commit -n to skip this check.\n'
);
process.exit(1);
}
exec('git diff --staged --name-status', function (error, stdout, stderr) {
if (error) {
process.stdout.write(stderr + '\nCould not get list of modified files: ' + error);
fail();
}
var expression = /^[MA]\s+([\w-\\\/]+\.js)$/gm;
var files = [];
var match;
while (match = expression.exec(stdout)) {
files.push(match[1]);
}
if (files.length === 0) {
process.exit(0);
}
var command = path.resolve('./node_modules/.bin/jshint');
var child = exec(command + ' --reporter=tools/jshint-reporter.js ' + files.join(' '));
child.stdout.on('data', function (data) {
process.stdout.write(data);
});
child.stderr.on('data', function (data) {
process.stderr.write(data);
});
child.on('exit', function (code) {
if (code !== 0) {
fail();
} else {
process.exit(0);
}
});
});
| Convert Unix path to Windows path in jshint command (in node_modules) | Convert Unix path to Windows path in jshint command (in node_modules)
Story #103
| JavaScript | mit | GooTechnologies/goojs,GooTechnologies/goojs,GooTechnologies/goojs | ---
+++
@@ -1,6 +1,7 @@
'use strict';
var exec = require('child_process').exec;
+var path = require('path');
function fail() {
process.stdout.write(
@@ -26,7 +27,8 @@
process.exit(0);
}
- var child = exec('node_modules/.bin/jshint --reporter=tools/jshint-reporter.js ' + files.join(' '));
+ var command = path.resolve('./node_modules/.bin/jshint');
+ var child = exec(command + ' --reporter=tools/jshint-reporter.js ' + files.join(' '));
child.stdout.on('data', function (data) {
process.stdout.write(data); |
70dbfc53eecaa00ffc91c1b4c7dc63ae9a4ac653 | test/unit/layout.js | test/unit/layout.js |
describe('layout tests', function () {
it('Should have MaterialLayout globally available', function () {
expect(MaterialLayout).to.be.a('function');
});
it('Should be upgraded to a MaterialLayout successfully', function () {
var el = document.createElement('div');
el.innerHTML = '<div class="wsk-layout__header"></div>' +
'<div class="wsk-layout__drawer"></div>' +
'<div class="wsk-layout__content"></div>';
var parent = document.createElement('div');
parent.appendChild(el); // MaterialLayout.init() expects a parent
componentHandler.upgradeElement(el, 'MaterialLayout');
var upgraded = el.getAttribute('data-upgraded');
expect(upgraded).to.contain('MaterialLayout');
});
});
|
describe('layout tests', function () {
it('Should have MaterialLayout globally available', function () {
expect(MaterialLayout).to.be.a('function');
});
it('Should be upgraded to a MaterialLayout successfully', function () {
var el = document.createElement('div');
el.innerHTML = '<div class="wsk-layout__header"></div>' +
'<div class="wsk-layout__drawer"></div>' +
'<div class="wsk-layout__content"></div>';
var parent = document.createElement('div');
parent.appendChild(el); // MaterialLayout.init() expects a parent
componentHandler.upgradeElement(el, 'MaterialLayout');
expect($(el)).to.have.data('upgraded', ',MaterialLayout');
});
});
| Update MaterialLayout unit test with chai-jquery | Update MaterialLayout unit test with chai-jquery
| JavaScript | apache-2.0 | Ubynano/material-design-lite,NaveenNs123/material-design-lite,wonder-coders/material-design-lite,Mannaio/javascript-course,manohartn/material-design-lite,francisco-filho/material-design-lite,Creepypastas/material-design-lite,Ninir/material-design-lite,suman28/material-design-lite,rvanmarkus/material-design-lite,samthor/material-design-lite,afonsopacifer/material-design-lite,hassanabidpk/material-design-lite,gshireesh/material-design-lite,KageKirin/material-design-lite,Saber-Kurama/material-design-lite,ganglee/material-design-lite,voumir/material-design-lite,innovand/material-design-lite,wendaleruan/material-design-lite,katchoua/material-design-lite,Yizhachok/material-components-web,unya-2/material-design-lite,hanachin/material-design-lite,peiche/material-design-lite,shairez/material-design-lite,udhayam/material-design-lite,pauloedspinho20/material-design-lite,tornade0913/material-design-lite,tahaipek/material-design-lite,glizer/material-design-lite,JacobDorman/material-design-lite,ryancford/material-design-lite,thunsaker/material-design-lite,listatt/material-design-lite,eidehua/material-design-lite,vluong/material-design-lite,gbn972/material-design-lite,nickretallack/material-design-lite,marc-f/material-design-lite,UmarMughal/material-design-lite,billychappell/material-design-lite,chaimanat/material-design-lite,MaxvonStein/material-design-lite,fizzvr/material-design-lite,CreevDesign/material-design-lite,pedroha/material-design-lite,abhishekgahlot/material-design-lite,tangposmarvin/material-design-lite,GilFewster/material-design-lite,lucianna/material-design-lite,dMagsAndroid/material-design-lite,leomiranda92/material-design-lite,ElvisMoVi/material-design-lite,chinasb/material-design-lite,gs-akhan/material-design-lite,material-components/material-components-web,fchuks/material-design-lite,tschiela/material-design-lite,b-cuts/material-design-lite,OoNaing/material-design-lite,kenlojt/material-design-lite,zlotas/material-design-lite,qiujuer/material-design-lite,Daiegon/material-design-lite,devbeta/material-design-lite,SeasonFour/material-design-lite,killercup/material-design-lite,AliMD/material-design-lite,marekswiecznik/material-design-lite,anton-kachurin/material-components-web,francisco-filho/material-design-lite,zckrs/material-design-lite,pj19060/material-design-lite,manisoni28/material-design-lite,scrapp-uk/material-design-lite,Treevil/material-design-lite,pauloedspinho20/material-design-lite,WritingPanda/material-design-lite,sangupandi/material-design-lite,mike-north/material-design-lite,serdimoa/material-design-lite,nandollorella/material-design-lite,WeRockStar/material-design-lite,lahmizzar/material-design-lite,levonter/material-design-lite,two9seven/material-design-lite,JonReppDoneD/google-material-design-lite,Kabele/material-design-lite,afonsopacifer/material-design-lite,NaokiMiyata/material-design-lite,EllieAdam/material-design-lite,levonter/material-design-lite,nandollorella/material-design-lite,Wyvan/material-design-lite,dgrubelic/material-design-lite,nikhil2kulkarni/material-design-lite,ahmadhmoud/material-design-lite,leeleo26/material-design-lite,rawrsome/material-design-lite,Kekanto/material-design-lite,coraxster/material-design-lite,callumlocke/material-design-lite,NicolasJEngler/material-design-lite,gshireesh/material-design-lite,sraskin/material-design-lite,voumir/material-design-lite,koddsson/material-design-lite,weiwei695/material-design-lite,jorgeucano/material-design-lite,howtomake/material-design-lite,AliMD/material-design-lite,lahmizzar/material-design-lite,wilsson/material-design-lite,Mannaio/javascript-course,JonReppDoneD/google-material-design-lite,praveenscience/material-design-lite,LuanNg/material-design-lite,tainanboy/material-design-lite,daviddenbigh/material-design-lite,mibcadet/material-design-lite,palimadra/material-design-lite,billychappell/material-design-lite,s4050855/material-design-lite,hebbet/material-design-lite,StephanieMak/material-design-lite,joyouscob/material-design-lite,CreevDesign/material-design-lite,citypeople/material-design-lite,ForsakenNGS/material-design-lite,ithinkihaveacat/material-design-lite,hobbyquaker/material-design-lite,mroell/material-design-lite,scrapp-uk/material-design-lite,snice/material-design-lite,andyyou/material-design-lite,hsnunes/material-design-lite,ProgLan/material-design-lite,sbrieuc/material-design-lite,modulexcite/material-design-lite,huoxudong125/material-design-lite,rschmidtz/material-design-lite,lintangarief/material-design-lite,tvoli/material-design-zero,Messi10AP/material-design-lite,weiwei695/material-design-lite,martnga/material-design-lite,cbmeeks/material-design-lite,howtomake/material-design-lite,rtoya/material-design-lite,danbenn93/material-design-lite,sejr/material-design-lite,jvkops/material-design-lite,stevewithington/material-design-lite,chalermporn/material-design-lite,mayhem-ahmad/material-design-lite,NaveenNs123/material-design-lite,quannt/material-design-lite,fjvalencian/material-design-lite,Ycfx/material-design-lite,warshanks/material-design-lite,WritingPanda/material-design-lite,pgbross/material-components-web,stevenliuit/material-design-lite,WPG/material-design-lite,alisterlf/material-design-lite,vasiliy-pdk/material-design-lite,marc-f/material-design-lite,ganglee/material-design-lite,DeXterMarten/material-design-lite,nakamuraagatha/material-design-lite,yongxu/material-design-lite,sangupandi/material-design-lite,katchoua/material-design-lite,vladikoff/material-design-lite,stealba/mdl,it-andy-hou/material-design-lite,rmccutcheon/material-design-lite,ston380/material-design-lite,rtoya/material-design-lite,alitedi/material-design-lite,poljeff/material-design-lite,nickretallack/material-design-lite,Yizhachok/material-components-web,leeleo26/material-design-lite,tschiela/material-design-lite,libinbensin/material-design-lite,wilsson/material-design-lite,ominux/material-design-lite,urandu/material-design-lite,victorhaggqvist/material-design-lite,kidGodzilla/material-design-lite,ebulay/material-design-lite,dgrubelic/material-design-lite,stevenliuit/material-design-lite,mattbutlar/mattbutlar.github.io,imskojs/material-design-lite,gwokudasam/material-design-lite,glizer/material-design-lite,sylvesterwillis/material-design-lite,dgash/material-design-lite,codephillip/material-design-lite,Vincent2015/material-design-lite,ZNosX/material-design-lite,bendroid/material-design-lite,xumingjie1658/material-design-lite,zeroxfire/material-design-lite,elizad/material-design-lite,KMikhaylovCTG/material-design-lite,peterblazejewicz/material-design-lite,alanpassos/material-design-lite,JonFerrera/material-design-lite,rrenwick/material-design-lite,iamrudra/material-design-lite,NaokiMiyata/material-design-lite,modulexcite/material-design-lite,jahnaviancha/material-design-lite,samccone/material-design-lite,ObviouslyGreen/material-design-lite,material-components/material-components-web,ProgLan/material-design-lite,glebm/material-design-lite,ElvisMoVi/material-design-lite,2947721120/material-design-lite,johannchen/material-design-lite,DeXterMarten/material-design-lite,jackielii/material-design-lite,FredrikAppelros/material-design-lite,BrUn3y/material-design-lite,chaimanat/material-design-lite,chinovian/material-design-lite,anton-kachurin/material-components-web,iamrudra/material-design-lite,nakamuraagatha/material-design-lite,stevewithington/material-design-lite,shoony86/material-design-lite,mailtoharshit/material-design-lite,rohanthacker/material-design-lite,eidehua/material-design-lite,dylannnn/material-design-lite,i9-Technologies/material-design-lite,pj19060/material-design-lite,peterblazejewicz/material-design-lite,pudgereyem/material-design-lite,tornade0913/material-design-lite,thanhnhan2tn/material-design-lite,AntonGulkevich/material-design-lite,DCSH2O/material-design-lite,material-components/material-components-web,fonai/material-design-lite,JacobDorman/material-design-lite,silvolu/material-design-lite,basicsharp/material-design-lite,2947721120/material-design-lite,DigitalCoder/material-design-lite,ananthmysore/material-design-lite,mailtoharshit/material-design-lite,haapanen/material-design-lite,Sahariar/material-design-lite,andrewpetrovic/material-design-lite,chinasb/material-design-lite,kwangkim/material-design-lite,youknow0709/material-design-lite,gxcnupt08/material-design-lite,vrajakishore/material-design-lite,kamilik26/material-design-lite,Heart2009/material-design-lite,stealba/mdl,fhernandez173/material-design-lite,david84/material-design-lite,mlc0202/material-design-lite,mroell/material-design-lite,hassanabidpk/material-design-lite,listatt/material-design-lite,tangposmarvin/material-design-lite,Ubynano/material-design-lite,WebRTL/material-design-lite-rtl,google/material-design-lite,WeRockStar/material-design-lite,domingossantos/material-design-lite,ArmendGashi/material-design-lite,zlotas/material-design-lite,glebm/material-design-lite,rkmax/material-design-lite,razchiriac/material-design-lite,paulirish/material-design-lite,Wyvan/material-design-lite,thanhnhan2tn/material-design-lite,chunwei/material-design-lite,killercup/material-design-lite,Endika/material-design-lite,bright-sparks/material-design-lite,diegodsgarcia/material-design-lite,fernandoPalaciosGit/material-design-lite,urandu/material-design-lite,ArmendGashi/material-design-lite,gbn972/material-design-lite,JuusoV/material-design-lite,kamilik26/material-design-lite,lebas/material-design-lite,coreyaus/material-design-lite,ForsakenNGS/material-design-lite,fhernandez173/material-design-lite,shardul-cr7/DazlingCSS,tradeserve/material-design-lite,BrUn3y/material-design-lite,alisterlf/material-design-lite,mlc0202/material-design-lite,imskojs/material-design-lite,hdolinski/material-design-lite,poljeff/material-design-lite,sejr/material-design-lite,peiche/material-design-lite,sylvesterwillis/material-design-lite,johannchen/material-design-lite,mweimerskirch/material-design-lite,hcxiong/material-design-lite,fonai/material-design-lite,pedroha/material-design-lite,narendrashetty/material-design-lite,chunwei/material-design-lite,chalermporn/material-design-lite,xiezhe/material-design-lite,DCSH2O/material-design-lite,Zagorakiss/material-design-lite,jahnaviancha/material-design-lite,rawrsome/material-design-lite,lijanele/material-design-lite,genmacg/material-design-lite,palimadra/material-design-lite,odin3/material-design-lite,warshanks/material-design-lite,kenlojt/material-design-lite,Saber-Kurama/material-design-lite,gxcnupt08/material-design-lite,shairez/material-design-lite,srinivashappy/material-design-lite,Kekanto/material-design-lite,erickacevedor/material-design-lite,craicoverflow/material-design-lite,xdissent/material-design-lite,i9-Technologies/material-design-lite,sbrieuc/material-design-lite,l0rd0fwar/material-design-lite,wendaleruan/material-design-lite,Sahariar/material-design-lite,ithinkihaveacat/material-design-lite,yongxu/material-design-lite,jorgeucano/material-design-lite,two9seven/material-design-lite,leomiranda92/material-design-lite,luisbrito/material-design-lite,Kabele/material-design-lite,fchuks/material-design-lite,Heart2009/material-design-lite,xdissent/material-design-lite,quannt/material-design-lite,dMagsAndroid/material-design-lite,ominux/material-design-lite,mweimerskirch/material-design-lite,alihalabyah/material-design-lite,MaxvonStein/material-design-lite,LuanNg/material-design-lite,UmarMughal/material-design-lite,Endika/material-design-lite,achalv/material-design-lite,Vincent2015/material-design-lite,praveenscience/material-design-lite,Creepypastas/material-design-lite,Zodiase/material-design-lite,it-andy-hou/material-design-lite,david84/material-design-lite,mibcadet/material-design-lite,cbmeeks/material-design-lite,milkcreation/material-design-lite,garylgh/material-design-lite,elizad/material-design-lite,eboominathan/material-design-lite,xiezhe/material-design-lite,afvieira/material-design-lite,jermspeaks/material-design-lite,koddsson/material-design-lite,coraxster/material-design-lite,gabimanea/material-design-lite,snice/material-design-lite,NicolasJEngler/material-design-lite,codephillip/material-design-lite,Kushmall/material-design-lite,alitedi/material-design-lite,puncoz/material-design-lite,rschmidtz/material-design-lite,MuZT3/material-design-lite,coreyaus/material-design-lite,hairychris/material-design-lite,innovand/material-design-lite,alihalabyah/material-design-lite,ProfNandaa/material-design-lite,KMikhaylovCTG/material-design-lite,fernandoPalaciosGit/material-design-lite,diegodsgarcia/material-design-lite,Franklin-vaz/material-design-lite,rkmax/material-design-lite,tradeserve/material-design-lite,bruninja/material-design-lite,alanpassos/material-design-lite,callumlocke/material-design-lite,citypeople/material-design-lite,shardul-cr7/DazlingCSS,puncoz/material-design-lite,ovaskevich/material-design-lite,ovaskevich/material-design-lite,victorhaggqvist/material-design-lite,unya-2/material-design-lite,Victorgichohi/material-design-lite,mdixon47/material-design-lite,gs-akhan/material-design-lite,udhayam/material-design-lite,b-cuts/material-design-lite,fjvalencian/material-design-lite,gabimanea/material-design-lite,suman28/material-design-lite,ebulay/material-design-lite,zckrs/material-design-lite,samccone/material-design-lite,razchiriac/material-design-lite,genmacg/material-design-lite,lebas/material-design-lite,Zodiase/material-design-lite,ojengwa/material-design-lite,Victorgichohi/material-design-lite,jbnicolai/material-design-lite,google/material-design-lite,pudgereyem/material-design-lite,Zagorakiss/material-design-lite,davidjahns/material-design-lite,pandoraui/material-design-lite,hairychris/material-design-lite,zeroxfire/material-design-lite,andrect/material-design-lite,lucianna/material-design-lite,egobrightan/material-design-lite,nikhil2kulkarni/material-design-lite,ObviouslyGreen/material-design-lite,yinxufeng/material-design-lite,dylannnn/material-design-lite,ryancford/material-design-lite,andyyou/material-design-lite,hobbyquaker/material-design-lite,serdimoa/material-design-lite,garylgh/material-design-lite,kidGodzilla/material-design-lite,jermspeaks/material-design-lite,ctuwuzida/material-design-lite,ChipCastleDotCom/material-design-lite,mayhem-ahmad/material-design-lite,trendchaser4u/material-design-lite,Kushmall/material-design-lite,dgash/material-design-lite,lawhump/material-design-lite,samthor/material-design-lite,ProfNandaa/material-design-lite,afvieira/material-design-lite,gwokudasam/material-design-lite,yinxufeng/material-design-lite,mikepuerto/material-design-lite,codeApeFromChina/material-design-lite,lijanele/material-design-lite,daviddenbigh/material-design-lite,achalv/material-design-lite,Frankistan/material-design-lite,chinovian/material-design-lite,yonjar/material-design-lite,jvkops/material-design-lite,vasiliy-pdk/material-design-lite,StephanieMak/material-design-lite,rvanmarkus/material-design-lite,bendroid/material-design-lite,manisoni28/material-design-lite,yonjar/material-design-lite,kwangkim/material-design-lite,narendrashetty/material-design-lite,luisbrito/material-design-lite,FredrikAppelros/material-design-lite,TejaSedate/material-design-lite,lintangarief/material-design-lite,vladikoff/material-design-lite,ctuwuzida/material-design-lite,gaurav1981/material-design-lite,egobrightan/material-design-lite,devbeta/material-design-lite,youprofit/material-design-lite,andrewpetrovic/material-design-lite,jjj117/material-design-lite,danbenn93/material-design-lite,mikepuerto/material-design-lite,AntonGulkevich/material-design-lite,codeApeFromChina/material-design-lite,WebRTL/material-design-lite-rtl,trendchaser4u/material-design-lite,s4050855/material-design-lite,bright-sparks/material-design-lite,EllieAdam/material-design-lite,rogerhu/material-design-lite,ananthmysore/material-design-lite,hanachin/material-design-lite,libinbensin/material-design-lite,Jonekee/material-design-lite,vrajakishore/material-design-lite,manohartn/material-design-lite,pierr/material-design-lite,thechampanurag/material-design-lite,thechampanurag/material-design-lite,Franklin-vaz/material-design-lite,marlcome/material-design-lite,youknow0709/material-design-lite,JuusoV/material-design-lite,domingossantos/material-design-lite,silvolu/material-design-lite,davidjahns/material-design-lite,sindhusrao/material-design-lite,erickacevedor/material-design-lite,bruninja/material-design-lite,youprofit/material-design-lite,l0rd0fwar/material-design-lite,tomatau/material-design-lite,abhishekgahlot/material-design-lite,yamingd/material-design-lite,mike-north/material-design-lite,DigitalCoder/material-design-lite,wonder-coders/material-design-lite,fizzvr/material-design-lite,rogerhu/material-design-lite,ThiagoGarciaAlves/material-design-lite,Frankistan/material-design-lite,milkcreation/material-design-lite,tahaipek/material-design-lite,huoxudong125/material-design-lite,timkrins/material-design-lite,eboominathan/material-design-lite,thunsaker/material-design-lite,rmccutcheon/material-design-lite,pgbross/material-components-web,ojengwa/material-design-lite,haapanen/material-design-lite,pierr/material-design-lite,tomatau/material-design-lite,andrect/material-design-lite,icdev/material-design-lite,GilFewster/material-design-lite,Ycfx/material-design-lite,wengqi/material-design-lite,Messi10AP/material-design-lite,qiujuer/material-design-lite,hdolinski/material-design-lite,marlcome/material-design-lite,ZNosX/material-design-lite,Ninir/material-design-lite,miragshin/material-design-lite,martnga/material-design-lite,miragshin/material-design-lite,vluong/material-design-lite,tainanboy/material-design-lite,hcxiong/material-design-lite,rrenwick/material-design-lite,sraskin/material-design-lite,ChipCastleDotCom/material-design-lite,ThiagoGarciaAlves/material-design-lite,ilovezy/material-design-lite,srinivashappy/material-design-lite,Treevil/material-design-lite,paulirish/material-design-lite,jbnicolai/material-design-lite,Mararesliu/material-design-lite,wengqi/material-design-lite,schobiwan/material-design-lite,schobiwan/material-design-lite,OoNaing/material-design-lite,mdixon47/material-design-lite,Jonekee/material-design-lite,tvoli/material-design-zero,Mararesliu/material-design-lite,craicoverflow/material-design-lite,KageKirin/material-design-lite,jjj117/material-design-lite,icdev/material-design-lite,basicsharp/material-design-lite,TejaSedate/material-design-lite,hsnunes/material-design-lite,shoony86/material-design-lite,lawhump/material-design-lite,jackielii/material-design-lite,yamingd/material-design-lite,SeasonFour/material-design-lite,rohanthacker/material-design-lite,sindhusrao/material-design-lite,odin3/material-design-lite,joyouscob/material-design-lite,ston380/material-design-lite,marekswiecznik/material-design-lite,ilovezy/material-design-lite,hebbet/material-design-lite,ahmadhmoud/material-design-lite,gaurav1981/material-design-lite,xumingjie1658/material-design-lite,pandoraui/material-design-lite,Daiegon/material-design-lite,JonFerrera/material-design-lite,MuZT3/material-design-lite,timkrins/material-design-lite,WPG/material-design-lite | ---
+++
@@ -15,7 +15,6 @@
parent.appendChild(el); // MaterialLayout.init() expects a parent
componentHandler.upgradeElement(el, 'MaterialLayout');
- var upgraded = el.getAttribute('data-upgraded');
- expect(upgraded).to.contain('MaterialLayout');
+ expect($(el)).to.have.data('upgraded', ',MaterialLayout');
});
}); |
0cf9aa8f61ccfc3720de7a2d9d017c97c1b79205 | filter-truncate.js | filter-truncate.js | /**
* Return a truncated version of a string
* @param {string} input
* @param {integer} length
* @param {boolean} killwords
* @param {string} end
* @return {string}
*/
PolymerExpressions.prototype.truncate = function (input, length, killwords, end) {
var orig = input;
length = length || 255;
if (input.length <= length)
return input;
if (killwords) {
input = input.substring(0, length);
} else {
var idx = input.lastIndexOf(' ', length);
if (idx === -1) {
idx = length;
}
input = input.substring(0, idx);
}
input += (end !== undefined && end !== null) ? end : '...';
return input;
}; | /**
* Return a truncated version of a string
* @param {string} input
* @param {integer} length
* @param {boolean} killwords
* @param {string} end
* @return {string}
*/
PolymerExpressions.prototype.truncate = function (input, length, killwords, end) {
var orig = input;
length = length || 255;
if(!input) {
return;
}
if (input.length <= length)
return input;
if (killwords) {
input = input.substring(0, length);
} else {
var idx = input.lastIndexOf(' ', length);
if (idx === -1) {
idx = length;
}
input = input.substring(0, idx);
}
input += (end !== undefined && end !== null) ? end : '...';
return input;
};
| Add check to ensure truncate does not error | Add check to ensure truncate does not error
- check if input exists before acting on it
- silences thrown error
- spirit of template filter, do nothing rather than fail if input is incorrect
| JavaScript | apache-2.0 | addyosmani/polymer-filters,eumendoza/polymer-filters,addyosmani/polymer-filters,eumendoza/polymer-filters | ---
+++
@@ -1,15 +1,17 @@
/**
* Return a truncated version of a string
- * @param {string} input
- * @param {integer} length
- * @param {boolean} killwords
- * @param {string} end
- * @return {string}
+ * @param {string} input
+ * @param {integer} length
+ * @param {boolean} killwords
+ * @param {string} end
+ * @return {string}
*/
PolymerExpressions.prototype.truncate = function (input, length, killwords, end) {
var orig = input;
length = length || 255;
-
+ if(!input) {
+ return;
+ }
if (input.length <= length)
return input;
|
94e178e8e3cea8c4f0ebd32b7b47ffea9da6ee78 | src/RowSizeControls/index.js | src/RowSizeControls/index.js | import React, { Component } from 'react';
class RowSizeControls extends Component {
render() {
return (
<div style={{textAlign: 'center'}}>
<label>Images per row</label>
<input
style={{
display: 'block',
margin: '0 auto',
}}
type="range"
min="1"
max="10"
value={this.props.value}
onChange={this.props.onChange} />
<span>{this.props.value}</span>
</div>
);
}
}
export default RowSizeControls;
| import React, { Component } from 'react';
class RowSizeControls extends Component {
render() {
return (
<div style={{textAlign: 'center'}}>
<label>{this.props.value} images per row</label>
<input
style={{
display: 'block',
margin: '0 auto',
}}
type="range"
min="1"
max="10"
value={this.props.value}
onChange={this.props.onChange} />
</div>
);
}
}
export default RowSizeControls;
| Add rowLength to slider label | Add rowLength to slider label
| JavaScript | mit | stevula/gallery,stevula/gallery | ---
+++
@@ -4,7 +4,7 @@
render() {
return (
<div style={{textAlign: 'center'}}>
- <label>Images per row</label>
+ <label>{this.props.value} images per row</label>
<input
style={{
display: 'block',
@@ -15,7 +15,6 @@
max="10"
value={this.props.value}
onChange={this.props.onChange} />
- <span>{this.props.value}</span>
</div>
);
} |
6053b42bcf2d2cfe9604f9923b06b9a0151f3b15 | lib/index.js | lib/index.js | 'use strict';
module.exports = function(html, attachments) {
attachments.forEach(function(attachment) {
attachment.applied = false;
var regexps = [
(attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName + '[@"\'][^>]*>', 'ig') : undefined,
(attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId + '[@"\'][^>]*>', 'ig') : undefined,
];
var content = Buffer.isBuffer(attachment.content) ? attachment.content.toString('base64') : attachment.content;
var extension = attachment.fileName.substr(attachment.fileName.lastIndexOf('.') + 1);
if(extension === 'jpeg') {
extension = 'jpg';
}
regexps.forEach(function(regexp) {
if(regexp && regexp.test(html)) {
attachment.applied = true;
html = html.replace(regexp, '<img src="data:image/' + extension + ';base64,' + content + '" />');
}
});
});
return html.replace(/<img[^>]*cid[^>]*>/ig, '');
}; | 'use strict';
module.exports = function(html, attachments) {
attachments.forEach(function(attachment) {
attachment.applied = false;
var regexps = [
(attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
(attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
];
var content = Buffer.isBuffer(attachment.content) ? attachment.content.toString('base64') : attachment.content;
var extension = attachment.fileName.substr(attachment.fileName.lastIndexOf('.') + 1);
if(extension === 'jpeg') {
extension = 'jpg';
}
regexps.forEach(function(regexp) {
if(regexp && regexp.test(html)) {
attachment.applied = true;
html = html.replace(regexp, '<img src="data:image/' + extension + ';base64,' + content + '" />');
}
});
});
return html.replace(/<img[^>]*cid:[^>]*>/ig, '');
}; | Fix a bug in removing cid img without attachments | Fix a bug in removing cid img without attachments
| JavaScript | mit | AnyFetch/npm-cid | ---
+++
@@ -5,8 +5,8 @@
attachment.applied = false;
var regexps = [
- (attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName + '[@"\'][^>]*>', 'ig') : undefined,
- (attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId + '[@"\'][^>]*>', 'ig') : undefined,
+ (attachment.fileName) ? new RegExp('<img[^>]*cid:' + attachment.fileName.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
+ (attachment.contentId) ? new RegExp('<img[^>]*cid:' + attachment.contentId.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") + '[@"\'][^>]*>', 'ig') : undefined,
];
var content = Buffer.isBuffer(attachment.content) ? attachment.content.toString('base64') : attachment.content;
@@ -24,5 +24,5 @@
});
});
- return html.replace(/<img[^>]*cid[^>]*>/ig, '');
+ return html.replace(/<img[^>]*cid:[^>]*>/ig, '');
}; |
f114a28c3c2d724712d992f7a81efa3604bcc224 | lib/index.js | lib/index.js | 'use strict'
const _ = require('lodash')
const hasLoop = (flow) => {
if (Array.isArray(flow)) {
return _validate(flow)
} else if (flow.states) {
return _validate(flow.states)
}
return {
status: "error",
message: "Flow not found!"
}
}
const _validate = (states) => {
const paths = states.reduce((acc, state) => {
if (state.automatic) {
acc.push({ from: state.name, to: state.transitions[0].to })
return acc
}
}, [])
while (paths.length > 0) {
if (validatePath(paths.pop(), paths)) {
return {
status: ERROR,
message: "LOOP"
}
}
}
return {
status: SUCCESS,
message: "OK"
}
}
const validatePath = (root, path, stack = []) => {
stack.push(root)
if (_.find(stack, { from: root.to })) {
return true
}
const next = _.find(path, { from: root.to })
const newPath = _.remove(path, { from: root.to })
if (!next) {
return false
}
return validatePath(next, newPath, stack)
}
const ERROR = "error"
const SUCCESS = "sucess"
module.exports = {
hasLoop,
ERROR,
SUCCESS
} | 'use strict'
const _ = require('lodash')
const hasLoop = (flow) => {
if (Array.isArray(flow)) {
return _validate(flow)
} else if (flow.states) {
return _validate(flow.states)
}
return {
status: "error",
message: "Flow not found!"
}
}
const _validate = (states) => {
const paths = states.reduce((acc, state) => {
if (state.automatic) {
acc.push({ from: state.name, to: state.transitions[0].to })
}
return acc
}, [])
while (paths.length > 0) {
if (validatePath(paths.pop(), paths)) {
return {
status: ERROR,
message: "LOOP"
}
}
}
return {
status: SUCCESS,
message: "OK"
}
}
const validatePath = (root, path, stack = []) => {
stack.push(root)
if (_.find(stack, { from: root.to })) {
return true
}
const next = _.find(path, { from: root.to })
const newPath = _.remove(path, { from: root.to })
if (!next) {
return false
}
return validatePath(next, newPath, stack)
}
const ERROR = "error"
const SUCCESS = "sucess"
module.exports = {
hasLoop,
ERROR,
SUCCESS
} | Fix return acc when not push a state | [UPDATE] Fix return acc when not push a state
| JavaScript | mit | josemanu/flowx-loop-validator | ---
+++
@@ -19,8 +19,8 @@
const paths = states.reduce((acc, state) => {
if (state.automatic) {
acc.push({ from: state.name, to: state.transitions[0].to })
- return acc
}
+ return acc
}, [])
while (paths.length > 0) { |
28a68feafafc98c1fa981751785c4319fd64ac60 | lib/index.js | lib/index.js | var debug = require('debug')('metalsmith-copy'),
path = require('path'),
cloneDeep = require('lodash').cloneDeep;
minimatch = require('minimatch');
module.exports = plugin;
function plugin(options) {
return function(files, metalsmith, done) {
if (!options.directory && !options.extension && !options.transform) return done(new Error('metalsmith-copy: "directory" or "extension" option required'));
var matcher = minimatch.Minimatch(options.pattern);
Object.keys(files).forEach(function (file) {
debug('checking file: ' + file);
if (!matcher.match(file)) return;
var newName = file;
// transform filename
if (options.transform) {
newName = options.transform(file);
} else {
if (options.extension) {
var currentExt = path.extname(file);
newName = path.join(path.dirname(file), path.basename(file, currentExt) + options.extension);
}
if (options.directory) {
newName = path.join(options.directory, path.basename(newName));
}
}
if (files[newName]) return done(new Error('metalsmith-copy: copying ' + file + ' to ' + newName + ' would overwrite file'));
debug('copying file: ' + newName);
files[newName] = cloneDeep(files[file], function(value) {
if (value instanceof Buffer) {
return new Buffer(value);
}
});
if (options.move) {
delete files[file];
}
});
done();
}
}
| var debug = require('debug')('metalsmith-copy'),
path = require('path'),
cloneDeep = require('lodash').cloneDeep,
minimatch = require('minimatch');
module.exports = plugin;
function plugin(options) {
return function(files, metalsmith, done) {
if (!options.directory && !options.extension && !options.transform) return done(new Error('metalsmith-copy: "directory" or "extension" option required'));
var matcher = minimatch.Minimatch(options.pattern);
Object.keys(files).forEach(function (file) {
debug('checking file: ' + file);
if (!matcher.match(file)) return;
var newName = file;
// transform filename
if (options.transform) {
newName = options.transform(file);
} else {
if (options.extension) {
var currentExt = path.extname(file);
newName = path.join(path.dirname(file), path.basename(file, currentExt) + options.extension);
}
if (options.directory) {
newName = path.join(options.directory, path.basename(newName));
}
}
if (files[newName]) return done(new Error('metalsmith-copy: copying ' + file + ' to ' + newName + ' would overwrite file'));
debug('copying file: ' + newName);
files[newName] = cloneDeep(files[file], function(value) {
if (value instanceof Buffer) {
return new Buffer(value);
}
});
if (options.move) {
delete files[file];
}
});
done();
}
}
| Fix imports that broke when running in strict mode | Fix imports that broke when running in strict mode
The badly place semicolon triggered "undefined variable" errors.
| JavaScript | mit | mattwidmann/metalsmith-copy | ---
+++
@@ -1,6 +1,6 @@
var debug = require('debug')('metalsmith-copy'),
path = require('path'),
- cloneDeep = require('lodash').cloneDeep;
+ cloneDeep = require('lodash').cloneDeep,
minimatch = require('minimatch');
module.exports = plugin; |
ffcf2e2ff94d8abc2e2b047ccd975be7449ee198 | lib/index.js | lib/index.js | var easymongo = require('easymongo');
module.exports = function(options) {
var mongo = new easymongo(options);
return {
find: function(collection, params, options) {
return function(fn) {
mongo.find(collection, params, options, fn);
};
},
save: function(collection, params) {
return function(fn) {
mongo.save(collection, params, fn);
};
},
remove: function(collection, id) {
return function(fn) {
mongo.removeById(collection, id, fn);
};
}
};
}; | var EasyMongo = require('easymongo');
module.exports = function(server, options) {
var mongo = new EasyMongo(server, options);
return {
find: function(table, params, options) {
return function(fn) {
mongo.find(table, params, options, fn);
};
},
findById: function(table, id) {
return function(fn) {
mongo.findById(table, id, fn);
};
},
save: function(table, params) {
return function(fn) {
mongo.save(table, params, fn);
};
},
remove: function(table, params) {
return function(fn) {
mongo.remove(table, params, fn);
};
},
removeById: function(table, id) {
return function(fn) {
mongo.removeById(table, id, fn);
};
},
count: function(table, params) {
return function(fn) {
mongo.count(table, params, fn);
};
}
};
}; | Add constructor arguments. Fix deprecated API. Add findById, removeById and count methods. | Add constructor arguments. Fix deprecated API. Add findById, removeById and count methods.
| JavaScript | mit | meritt/co-easymongo | ---
+++
@@ -1,24 +1,42 @@
-var easymongo = require('easymongo');
+var EasyMongo = require('easymongo');
-module.exports = function(options) {
- var mongo = new easymongo(options);
+module.exports = function(server, options) {
+ var mongo = new EasyMongo(server, options);
return {
- find: function(collection, params, options) {
+ find: function(table, params, options) {
return function(fn) {
- mongo.find(collection, params, options, fn);
+ mongo.find(table, params, options, fn);
};
},
- save: function(collection, params) {
+ findById: function(table, id) {
return function(fn) {
- mongo.save(collection, params, fn);
+ mongo.findById(table, id, fn);
};
},
- remove: function(collection, id) {
+ save: function(table, params) {
return function(fn) {
- mongo.removeById(collection, id, fn);
+ mongo.save(table, params, fn);
+ };
+ },
+
+ remove: function(table, params) {
+ return function(fn) {
+ mongo.remove(table, params, fn);
+ };
+ },
+
+ removeById: function(table, id) {
+ return function(fn) {
+ mongo.removeById(table, id, fn);
+ };
+ },
+
+ count: function(table, params) {
+ return function(fn) {
+ mongo.count(table, params, fn);
};
}
}; |
6c527183631acd6398ed279cb2f054a8672600c1 | tests/specs/extensible/auto-transport/main.js | tests/specs/extensible/auto-transport/main.js |
seajs.on('compiled', function(mod) {
if (mod.uri.indexOf('jquery.js') > -1) {
window.jQuery = window.$ = mod.exports
}
})
seajs.on('compile', function(mod) {
if (mod.uri.indexOf('cookie.js') > -1) {
mod.exports = $.cookie
}
})
seajs.config({
preload: ['./auto-transport/jquery']
}).use('./auto-transport/init')
|
seajs.on('compiled', function(mod) {
if (mod.uri.indexOf('jquery.js') > -1) {
global.jQuery = global.$ = mod.exports
}
})
seajs.on('compile', function(mod) {
if (mod.uri.indexOf('cookie.js') > -1) {
mod.exports = $.cookie
}
})
seajs.config({
preload: ['./auto-transport/jquery']
}).use('./auto-transport/init')
| Change window to global for Node.js | Change window to global for Node.js
| JavaScript | mit | coolyhx/seajs,yern/seajs,longze/seajs,MrZhengliang/seajs,lee-my/seajs,baiduoduo/seajs,liupeng110112/seajs,ysxlinux/seajs,yern/seajs,angelLYK/seajs,wenber/seajs,evilemon/seajs,wenber/seajs,miusuncle/seajs,lee-my/seajs,yuhualingfeng/seajs,LzhElite/seajs,121595113/seajs,judastree/seajs,wenber/seajs,twoubt/seajs,eleanors/SeaJS,lovelykobe/seajs,angelLYK/seajs,treejames/seajs,imcys/seajs,uestcNaldo/seajs,eleanors/SeaJS,moccen/seajs,lianggaolin/seajs,hbdrawn/seajs,chinakids/seajs,longze/seajs,13693100472/seajs,tonny-zhang/seajs,MrZhengliang/seajs,zaoli/seajs,hbdrawn/seajs,mosoft521/seajs,kaijiemo/seajs,liupeng110112/seajs,AlvinWei1024/seajs,lee-my/seajs,tonny-zhang/seajs,moccen/seajs,jishichang/seajs,uestcNaldo/seajs,twoubt/seajs,FrankElean/SeaJS,seajs/seajs,PUSEN/seajs,evilemon/seajs,kuier/seajs,PUSEN/seajs,Lyfme/seajs,zaoli/seajs,lianggaolin/seajs,Gatsbyy/seajs,lovelykobe/seajs,sheldonzf/seajs,coolyhx/seajs,zwh6611/seajs,Lyfme/seajs,sheldonzf/seajs,judastree/seajs,treejames/seajs,kuier/seajs,13693100472/seajs,imcys/seajs,MrZhengliang/seajs,chinakids/seajs,evilemon/seajs,yuhualingfeng/seajs,seajs/seajs,liupeng110112/seajs,tonny-zhang/seajs,treejames/seajs,JeffLi1993/seajs,yern/seajs,zwh6611/seajs,uestcNaldo/seajs,zaoli/seajs,zwh6611/seajs,imcys/seajs,Gatsbyy/seajs,eleanors/SeaJS,miusuncle/seajs,kaijiemo/seajs,mosoft521/seajs,PUSEN/seajs,LzhElite/seajs,jishichang/seajs,Lyfme/seajs,baiduoduo/seajs,baiduoduo/seajs,JeffLi1993/seajs,moccen/seajs,lovelykobe/seajs,AlvinWei1024/seajs,mosoft521/seajs,yuhualingfeng/seajs,judastree/seajs,JeffLi1993/seajs,AlvinWei1024/seajs,FrankElean/SeaJS,miusuncle/seajs,seajs/seajs,longze/seajs,jishichang/seajs,ysxlinux/seajs,sheldonzf/seajs,twoubt/seajs,lianggaolin/seajs,angelLYK/seajs,Gatsbyy/seajs,kaijiemo/seajs,121595113/seajs,kuier/seajs,coolyhx/seajs,ysxlinux/seajs,FrankElean/SeaJS,LzhElite/seajs | ---
+++
@@ -1,7 +1,7 @@
seajs.on('compiled', function(mod) {
if (mod.uri.indexOf('jquery.js') > -1) {
- window.jQuery = window.$ = mod.exports
+ global.jQuery = global.$ = mod.exports
}
})
|
1610d0389c7e0a7a10988d191e6dd3a08ea8712d | src/js/modules_enabled.js | src/js/modules_enabled.js | /*=include modules/accessor.js */
/*=include modules/ajax.js */
/*=include modules/calculation_colums.js */
/*=include modules/clipboard.js */
/*=include modules/download.js */
/*=include modules/edit.js */
/*=include modules/filter.js */
/*=include modules/format.js */
/*=include modules/frozen_columns.js */
/*=include modules/frozen_rows.js */
/*=include modules/group_rows.js */
/*=include modules/history.js */
/*=include modules/html_table_import.js */
/*=include modules/Keybindings.js */
/*=include modules/moveable_columns.js */
/*=include modules/moveable_rows.js */
/*=include modules/mutator.js */
/*=include modules/page.js */
/*=include modules/persistence.js */
/*=include modules/resize_columns.js */
/*=include modules/resize_rows.js */
/*=include modules/resize_table.js */
/*=include modules/responsive_layout.js */
/*=include modules/select_row.js */
/*=include modules/sort.js */
/*=include modules/validate.js */ | /*=include modules/accessor.js */
/*=include modules/ajax.js */
/*=include modules/calculation_colums.js */
/*=include modules/clipboard.js */
/*=include modules/download.js */
/*=include modules/edit.js */
/*=include modules/filter.js */
/*=include modules/format.js */
/*=include modules/frozen_columns.js */
/*=include modules/frozen_rows.js */
/*=include modules/group_rows.js */
/*=include modules/history.js */
/*=include modules/html_table_import.js */
/*=include modules/keybindings.js */
/*=include modules/moveable_columns.js */
/*=include modules/moveable_rows.js */
/*=include modules/mutator.js */
/*=include modules/page.js */
/*=include modules/persistence.js */
/*=include modules/resize_columns.js */
/*=include modules/resize_rows.js */
/*=include modules/resize_table.js */
/*=include modules/responsive_layout.js */
/*=include modules/select_row.js */
/*=include modules/sort.js */
/*=include modules/validate.js */ | Fix improper case from 'KeyBindings' to keybindings causing build failures on linux. | Fix improper case from 'KeyBindings' to keybindings causing build failures on linux.
| JavaScript | mit | olifolkerd/tabulator | ---
+++
@@ -11,7 +11,7 @@
/*=include modules/group_rows.js */
/*=include modules/history.js */
/*=include modules/html_table_import.js */
-/*=include modules/Keybindings.js */
+/*=include modules/keybindings.js */
/*=include modules/moveable_columns.js */
/*=include modules/moveable_rows.js */
/*=include modules/mutator.js */ |
0a2be4064b2ec75d428f55861f2c8d35727a0ee5 | lib/tools.js | lib/tools.js |
var tools = module.exports = exports = {},
debug = require('debug')('turnkey');
tools.default_cfg = function() {
var cfg = {
// Required Options --------------------------------------------------------
router: undefined, /* Express JS Router */
model: undefined, /* Mongoose model */
// Options with defaults ---------------------------------------------------
hash_length: 256,
hash_iterations: 12288,
logger: console.log.bind(console),
username_key: 'username',
min_length: 8,
forgot_limit: 1000 * 60 * 60, // 1 hour
deserialize: function(id, cb) {
cfg.model.findOne({ _id: id }, function(e, d) {
d = (d && d.toJSON) ? d.toJSON({ getters: true }) : d;
cb(e, d);
});
},
serialize: function(u, cb) {
return cb(null, String(u._id));
},
find_user: function(body, cb) {
var uname = body && body[cfg.username_key] &&
body[cfg.username_key].toLowerCase(),
q = {};
debug('find user: %s', uname);
q[cfg.username_key] = uname;
cfg.model.findOne(q, function(e, d) {
d = (d && d.toJSON) ? d.toJSON({ getters: true }) : d;
cb(e, d);
});
},
// Optionals ---------------------------------------------------------------
forgot_mailer: undefined /* Mailer when forgot password */
};
return cfg;
}
|
var tools = module.exports = exports = {},
debug = require('debug')('turnkey');
tools.default_cfg = function() {
var cfg = {
// Required Options --------------------------------------------------------
router: undefined, /* Express JS Router */
model: undefined, /* Mongoose model */
// Options with defaults ---------------------------------------------------
hash_length: 256,
hash_iterations: 12288,
logger: console.log.bind(console),
username_key: 'username',
min_length: 8,
forgot_limit: 1000 * 60 * 60, // 1 hour
deserialize: function(id, cb) {
cfg.model.findById(id).lean().exec(cb);
},
serialize: function(u, cb) {
return cb(null, String(u._id));
},
find_user: function(body, cb) {
var uname = body && body[cfg.username_key] &&
body[cfg.username_key].toLowerCase(),
q = {};
debug('find user: %s', uname);
q[cfg.username_key] = uname;
cfg.model.findOne(q, function(e, d) {
d = (d && d.toJSON) ? d.toJSON({ getters: true }) : d;
cb(e, d);
});
},
// Optionals ---------------------------------------------------------------
forgot_mailer: undefined /* Mailer when forgot password */
};
return cfg;
}
| Modify default deserialize user function | Modify default deserialize user function
| JavaScript | mit | uhray/turnkey | ---
+++
@@ -17,10 +17,7 @@
forgot_limit: 1000 * 60 * 60, // 1 hour
deserialize: function(id, cb) {
- cfg.model.findOne({ _id: id }, function(e, d) {
- d = (d && d.toJSON) ? d.toJSON({ getters: true }) : d;
- cb(e, d);
- });
+ cfg.model.findById(id).lean().exec(cb);
},
serialize: function(u, cb) { |
038c140deb2618833172bd48c59adb7f21e49205 | gulp/tasks/configure.sandbox.js | gulp/tasks/configure.sandbox.js | 'use strict';
const gulp = require('gulp');
const helper = require('gulp/helper');
gulp.task('configure:sandbox', cb => {
const isNotEmpty = helper.validators.isNotEmpty;
const questions = [
{
type: 'input',
name: 'url',
message: 'What is your Profile URL address?',
default: 'https://webtask.it.auth0.com',
validate: isNotEmpty
},
{
type: 'input',
name: 'container',
message: 'What is your container name?',
validate: isNotEmpty
},
{
type: 'input',
name: 'token',
message: 'What is your token value?',
validate: isNotEmpty
}
];
helper.prompt(questions).then(input => {
helper.updateConfig('sandbox', input).then(cb).catch(cb);
}).catch(cb);
});
| 'use strict';
const gulp = require('gulp');
const helper = require('gulp/helper');
gulp.task('configure:sandbox', cb => {
const isNotEmpty = helper.validators.isNotEmpty;
const questions = [
{
type: 'input',
name: 'url',
message: 'What is your Profile URL address?',
default: 'https://webtask.it.auth0.com',
validate: isNotEmpty
},
{
type: 'input',
name: 'container',
message: 'What is your container name?',
validate: isNotEmpty
},
{
type: 'password',
name: 'token',
message: 'What is your token value?',
validate: isNotEmpty
}
];
helper.prompt(questions).then(input => {
helper.updateConfig('sandbox', input).then(cb).catch(cb);
}).catch(cb);
});
| Use 'password' type for a field with a token value. | Use 'password' type for a field with a token value.
| JavaScript | mit | radekk/webtask-mfa-monitor,radekk/mfa-monitor,radekk/webtask-tfa-monitor | ---
+++
@@ -20,7 +20,7 @@
validate: isNotEmpty
},
{
- type: 'input',
+ type: 'password',
name: 'token',
message: 'What is your token value?',
validate: isNotEmpty |
9dcfc85a24e0ea81397c7a7541375d6f8aac98a3 | src/es6/Machete.js | src/es6/Machete.js | export class Machete {
// TODO: Implement polyfills
/**
* Utility function to get an element from the DOM.
* It is needed because everytime we get an element from the DOM,
* we reset its style to make sure code works as needed.
* @param string selector CSS selector
* @return Element Selected element
*/
static getDOMElement(selector) {
let element = document.querySelector(selector),
style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width;
element.style.height = style.height;
element.style.transform = style.transform;
return element;
}
}
| export class Machete {
// TODO: Implement polyfills
/**
* Utility function to get an element from the DOM.
* It is needed because everytime we get an element from the DOM,
* we reset its style to make sure code works as needed.
* @param string selector CSS selector
* @return Element Selected element
*/
static getDOMElement(selector) {
return Machete.resetStyles(document.querySelector(selector));
}
static resetStyles(element) {
let style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width;
element.style.height = style.height;
element.style.transform = style.transform;
return element;
}
}
| Split DOM element selection and style reset | machete: Split DOM element selection and style reset
| JavaScript | mpl-2.0 | Technohacker/machete | ---
+++
@@ -9,8 +9,11 @@
* @return Element Selected element
*/
static getDOMElement(selector) {
- let element = document.querySelector(selector),
- style = window.getComputedStyle(element);
+ return Machete.resetStyles(document.querySelector(selector));
+ }
+
+ static resetStyles(element) {
+ let style = window.getComputedStyle(element);
element.style.left = style.left;
element.style.top = style.top;
element.style.width = style.width; |
263f22fb4a56ede32e07f455db8a0e5a02e5dab2 | .eslintrc.js | .eslintrc.js | /* eslint-env node */
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2020,
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'jest', 'react-hooks', 'prettier'],
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'prettier/react',
],
settings: {
react: {
version: 'detect',
},
},
rules: {
'react/prop-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
},
overrides: [
{
files: ['*.test.ts', '*.test.tsx'],
env: {
'jest/globals': true,
},
},
{
files: ['*.tsx'],
rules: {
'react/react-in-jsx-scope': 'error',
},
},
],
}
| /* eslint-env node */
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2020,
sourceType: 'module',
},
plugins: ['@typescript-eslint', 'jest', 'react-hooks', 'prettier'],
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'prettier',
],
settings: {
react: {
version: 'detect',
},
},
rules: {
'react/prop-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
},
overrides: [
{
files: ['*.test.ts', '*.test.tsx'],
env: {
'jest/globals': true,
},
},
{
files: ['*.tsx'],
rules: {
'react/react-in-jsx-scope': 'error',
},
},
],
}
| Use updated prettier ESLint config | Use updated prettier ESLint config
| JavaScript | mit | hugo/hugo.github.com,hugo/hugo.github.com | ---
+++
@@ -17,7 +17,7 @@
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
- 'prettier/react',
+ 'prettier',
],
settings: {
react: { |
f581907321b60c1bfc0db9dff09b9028a8b7f0f6 | src/styles/theme.js | src/styles/theme.js | const theme = {
color: {
grey: '#DDDDDD',
black: '#111111',
},
font: {
sans: `'Lora', sans-serif`,
serif: `'Raleway', serif`,
},
};
export default theme;
| const theme = {
color: {
grey: '#DDDDDD',
black: '#111111',
},
font: {
sans: `'Lora', sans-serif`,
serif: `'Raleway', serif`,
},
sizes: {
mobileS: '320px',
mobileM: '375px',
mobileL: '425px',
tablet: '768px',
laptop: '1024px',
laptopL: '1440px',
desktop: '2560px',
},
};
export default theme;
| Add sizes to make it easier @medias | Add sizes to make it easier @medias
| JavaScript | mit | raulfdm/cv | ---
+++
@@ -7,6 +7,15 @@
sans: `'Lora', sans-serif`,
serif: `'Raleway', serif`,
},
+ sizes: {
+ mobileS: '320px',
+ mobileM: '375px',
+ mobileL: '425px',
+ tablet: '768px',
+ laptop: '1024px',
+ laptopL: '1440px',
+ desktop: '2560px',
+ },
};
export default theme; |
25a08afe9810fdd9299e5f8a51445344de560e11 | src/lib/expand-department.js | src/lib/expand-department.js | const departments = new Map(Object.entries({
AR: 'ART',
AS: 'ASIAN',
BI: 'BIO',
CH: 'CHEM',
CS: 'CSCI',
EC: 'ECON',
ES: 'ENVST',
HI: 'HIST',
MU: 'MUSIC',
PH: 'PHIL',
PS: 'PSCI',
RE: 'REL',
SA: 'SOAN',
}))
export default function expandDepartment(dept) {
if (departments.has(dept)) {
return departments.get(dept)
}
else {
throw new TypeError(`expandDepartment(): "${dept}" is not a valid department shorthand`)
}
}
| const departments = new Map(Object.entries({
AR: 'ART',
AS: 'ASIAN',
BI: 'BIO',
CH: 'CHEM',
CS: 'CSCI',
EC: 'ECON',
EN: 'ENGL',
ES: 'ENVST',
HI: 'HIST',
MU: 'MUSIC',
PH: 'PHIL',
PS: 'PSCI',
RE: 'REL',
SA: 'SOAN',
}))
export default function expandDepartment(dept) {
if (departments.has(dept)) {
return departments.get(dept)
}
else {
throw new TypeError(`expandDepartment(): "${dept}" is not a valid department shorthand`)
}
}
| Add "EN" as a valid department shorthand | Add "EN" as a valid department shorthand
for the EN/LI 250 course. | JavaScript | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -5,6 +5,7 @@
CH: 'CHEM',
CS: 'CSCI',
EC: 'ECON',
+ EN: 'ENGL',
ES: 'ENVST',
HI: 'HIST',
MU: 'MUSIC', |
2fd60c6d2599d991c8d05ad101844ea840bc1528 | js/style-select.js | js/style-select.js | /*
* style-select.js
* https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js
*
* Changes the stylesheet chooser links to a <select>
*
* Released under the MIT license
* Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
*
* Usage:
* $config['additional_javascript'][] = 'js/jquery.min.js';
* $config['additional_javascript'][] = 'js/style-select.js';
*
*/
onready(function(){
var stylesDiv = $('div.styles');
var stylesSelect = $('<select></select>');
var i = 1;
stylesDiv.children().each(function() {
stylesSelect.append(
$('<option></option>')
.text(this.innerText.replace(/(^\[|\]$)/g, ''))
.val(i)
);
$(this).attr('id', 'style-select-' + i);
i++;
});
stylesSelect.change(function() {
$('#style-select-' + $(this).val()).click();
});
stylesDiv.hide();
stylesDiv.after(
$('<div style="float:right;margin-bottom:10px"></div>')
.text(_('Style: '))
.append(stylesSelect)
);
});
| /*
* style-select.js
* https://github.com/savetheinternet/Tinyboard/blob/master/js/style-select.js
*
* Changes the stylesheet chooser links to a <select>
*
* Released under the MIT license
* Copyright (c) 2013 Michael Save <savetheinternet@tinyboard.org>
*
* Usage:
* $config['additional_javascript'][] = 'js/jquery.min.js';
* $config['additional_javascript'][] = 'js/style-select.js';
*
*/
onready(function(){
var stylesDiv = $('div.styles');
var stylesSelect = $('<select></select>');
var i = 1;
stylesDiv.children().each(function() {
var opt = $('<option></option>')
.text(this.innerText.replace(/(^\[|\]$)/g, ''))
.val(i);
if ($(this).hasClass('selected'))
opt.attr('selected', true);
stylesSelect.append(opt);
$(this).attr('id', 'style-select-' + i);
i++;
});
stylesSelect.change(function() {
$('#style-select-' + $(this).val()).click();
});
stylesDiv.hide();
stylesDiv.after(
$('<div style="float:right;margin-bottom:10px"></div>')
.text(_('Style: '))
.append(stylesSelect)
);
});
| Select chosen stylesheet on load | Select chosen stylesheet on load
| JavaScript | mit | kimoi/Tinyboard,savetheinternet/Tinyboard,kimoi/Tinyboard,kimoi/Tinyboard,savetheinternet/Tinyboard,savetheinternet/Tinyboard,kimoi/Tinyboard | ---
+++
@@ -19,11 +19,12 @@
var i = 1;
stylesDiv.children().each(function() {
- stylesSelect.append(
- $('<option></option>')
- .text(this.innerText.replace(/(^\[|\]$)/g, ''))
- .val(i)
- );
+ var opt = $('<option></option>')
+ .text(this.innerText.replace(/(^\[|\]$)/g, ''))
+ .val(i);
+ if ($(this).hasClass('selected'))
+ opt.attr('selected', true);
+ stylesSelect.append(opt);
$(this).attr('id', 'style-select-' + i);
i++;
}); |
e661eea9ec561302f48d24dd6b8ed05d262240ad | add-jira-links-to-description.js | add-jira-links-to-description.js | (() => {
const $input = document.querySelector('#pull_request_body');
if (!$input || $input.textLength > 0) {
return;
}
jiraLinks = [];
document.querySelectorAll('.commit-message').forEach((commitMessage) => {
commitMessage.textContent.match(/BSD-\d+/g).forEach((jiraId) => {
jiraLinks.push(`[${jiraId}](https://buildout.atlassian.net/browse/${jiraId})`);
})
});
if (jiraLinks.length > 0) {
$input.value = jiraLinks.join("\n") + "\n\n"
}
})();
| (() => {
const $title = document.querySelector('#pull_request_title');
const $description = document.querySelector('#pull_request_body');
if (!$title || !$description) {
return;
}
const idSet = new Set()
document.querySelectorAll('.commit-message').forEach((commitMessage) => {
match = commitMessage.textContent.match(/BSD-\d+/g);
if (match) {
match.forEach((id) => idSet.add(id));
}
});
if (idSet.size > 0) {
const ids = [];
let anyIdsInTitle = false;
let description = "";
idSet.forEach((id) => {
ids.push(id);
description += `[${id}](https://buildout.atlassian.net/browse/${id})\n`;
if ($title.value.indexOf(id) > -1) {
anyIdsInTitle = true;
}
});
if (!anyIdsInTitle) {
$title.value = `${ids.join(", ")}: `;
}
if ($description.textLength === 0) {
$description.value = `${description}\n`;
}
}
})();
| Fix title handling for multiple tags | Fix title handling for multiple tags
| JavaScript | mit | marionm/pivotal-github-chrome,marionm/pivotal-github-chrome | ---
+++
@@ -1,17 +1,39 @@
(() => {
- const $input = document.querySelector('#pull_request_body');
- if (!$input || $input.textLength > 0) {
+ const $title = document.querySelector('#pull_request_title');
+ const $description = document.querySelector('#pull_request_body');
+ if (!$title || !$description) {
return;
}
- jiraLinks = [];
+ const idSet = new Set()
document.querySelectorAll('.commit-message').forEach((commitMessage) => {
- commitMessage.textContent.match(/BSD-\d+/g).forEach((jiraId) => {
- jiraLinks.push(`[${jiraId}](https://buildout.atlassian.net/browse/${jiraId})`);
- })
+ match = commitMessage.textContent.match(/BSD-\d+/g);
+ if (match) {
+ match.forEach((id) => idSet.add(id));
+ }
});
- if (jiraLinks.length > 0) {
- $input.value = jiraLinks.join("\n") + "\n\n"
+ if (idSet.size > 0) {
+ const ids = [];
+
+ let anyIdsInTitle = false;
+ let description = "";
+
+ idSet.forEach((id) => {
+ ids.push(id);
+ description += `[${id}](https://buildout.atlassian.net/browse/${id})\n`;
+
+ if ($title.value.indexOf(id) > -1) {
+ anyIdsInTitle = true;
+ }
+ });
+
+ if (!anyIdsInTitle) {
+ $title.value = `${ids.join(", ")}: `;
+ }
+
+ if ($description.textLength === 0) {
+ $description.value = `${description}\n`;
+ }
}
})(); |
e67bf05ecc75244b5b54020939f177b715168f70 | src/components/Checkbox.js | src/components/Checkbox.js | import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => {
onToggle(id)
}
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked} className='pointer'
onChange={handleChange} />
<label className='ml2'>{key}</label>
</li>}
{childIds.length ?
(<ul className='list'>
{childIds.map((childId) => {
return (<Checkbox key={childId} id={childId}
nodes={nodes} onToggle={onToggle} />)
})}
</ul>)
:
null}
</React.Fragment>
)
} | import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => onToggle(id)
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked} className='pointer'
onChange={handleChange} />
<label className='ml2'>{key}</label>
</li>}
{childIds.length ?
(<ul className='list'>
{childIds.map((childId) => {
return (<Checkbox key={childId} id={childId}
nodes={nodes} onToggle={onToggle} />)
})}
</ul>)
:
null}
</React.Fragment>
)
} | Remove braces for one line functions | Remove braces for one line functions
| JavaScript | mit | joelgeorgev/react-checkbox-tree,joelgeorgev/react-checkbox-tree | ---
+++
@@ -4,9 +4,7 @@
const node = nodes[id]
const { key, childIds, checked } = node
- const handleChange = () => {
- onToggle(id)
- }
+ const handleChange = () => onToggle(id)
return (
<React.Fragment key={id}> |
e06d0ff85d4989a0e981fb33f836baef23d1bc3d | app/assets/javascripts/events.js | app/assets/javascripts/events.js | $(document).ready(function() {
$('#upload_form').change(function () {
$('#upload_form_label').hide();
$('#upload_form').hide();
$('#upload_progress').show();
$('#upload_form').submit();
});
$('#propagate_races').live('ajax:beforeSend', function() {
$('#propagate_races').hide();
$('#propagate_races_progress').show();
});
$('#destroy_races').live('ajax:beforeSend', function() {
$('#destroy_races').hide();
$('#destroy_races_progress').show();
});
$('#edit_promoter_link').click(function() {
window.location.href = '/admin/people/' + $('#event_promoter_id').val() + '/edit?event_id=' + $('#edit_promoter_link').attr('data-event-id');
return false;
});
});
| $(document).ready(function() {
$('#upload_form').change(function () {
$('#upload_form_label').hide();
$('#upload_form').hide();
$('#upload_progress').show();
$('#upload_form').submit();
});
$('#propagate_races').bind('ajax:beforeSend', function() {
$('#propagate_races').hide();
$('#propagate_races_progress').show();
});
$('#destroy_races').bind('ajax:beforeSend', function() {
$('#destroy_races').hide();
$('#destroy_races_progress').show();
});
$('#edit_promoter_link').click(function() {
window.location.href = '/admin/people/' + $('#event_promoter_id').val() + '/edit?event_id=' + $('#edit_promoter_link').attr('data-event-id');
return false;
});
});
| Use jquery-rails bind() in place of live() | Use jquery-rails bind() in place of live()
| JavaScript | mit | scottwillson/racing_on_rails,scottwillson/racing_on_rails,scottwillson/racing_on_rails,scottwillson/racing_on_rails | ---
+++
@@ -6,12 +6,12 @@
$('#upload_form').submit();
});
- $('#propagate_races').live('ajax:beforeSend', function() {
+ $('#propagate_races').bind('ajax:beforeSend', function() {
$('#propagate_races').hide();
$('#propagate_races_progress').show();
});
- $('#destroy_races').live('ajax:beforeSend', function() {
+ $('#destroy_races').bind('ajax:beforeSend', function() {
$('#destroy_races').hide();
$('#destroy_races_progress').show();
}); |
73464c8f531da3aa082f681fc263c1debcc7ad3f | app/reducers/modal/index.test.js | app/reducers/modal/index.test.js | import reducer from './';
describe('Modal reducer', () => {
let initialState;
let state;
let actionType;
let payload;
const callReducer = () => reducer(state, { type: actionType, payload });
beforeEach(() => {
initialState = {
isOpen: false,
modalName: '',
modalOptions: {}
};
});
it('returns initial state', () => {
expect(callReducer()).toEqual(initialState);
});
context('when state is present', () => {
beforeEach(() => {
state = initialState;
payload = {
name: 'Awesome Modal',
someOption: 'Some option value'
};
});
describe('OPEN_MODAL', () => {
beforeEach(() => {
actionType = 'OPEN_MODAL';
});
it('returns new state', () => {
expect(callReducer()).toEqual({
isOpen: true,
modalName: 'Awesome Modal',
modalOptions: {
someOption: 'Some option value'
}
});
});
});
describe('CLOSE_MODAL', () => {
beforeEach(() => {
actionType = 'CLOSE_MODAL';
state = {
isOpen: true,
modalName: 'Awesome Modal',
modalOptions: {
someOption: 'Some option value'
}
};
});
it('returns initial state', () => {
expect(callReducer()).toEqual({
isOpen: false,
modalName: '',
modalOptions: {}
});
});
});
});
});
| import reducer from './';
describe('Modal reducer', () => {
let initialState;
let state;
let actionType;
let payload;
const callReducer = () => reducer(state, { type: actionType, payload });
beforeEach(() => {
initialState = {
isOpen: false,
modalName: '',
modalOptions: {}
};
});
it('returns initial state', () => {
expect(callReducer()).toEqual(initialState);
});
context('when state is present', () => {
beforeEach(() => {
state = initialState;
payload = {
name: 'Awesome Modal',
someOption: 'Some option value'
};
});
describe('OPEN_MODAL', () => {
beforeEach(() => {
actionType = 'OPEN_MODAL';
});
it('returns new state', () => {
expect(callReducer()).toEqual({
isOpen: true,
modalName: 'Awesome Modal',
modalOptions: {
someOption: 'Some option value'
}
});
});
});
describe('CLOSE_MODAL', () => {
beforeEach(() => {
actionType = 'CLOSE_MODAL';
state = {
isOpen: true,
modalName: 'Awesome Modal',
modalOptions: {
someOption: 'Some option value'
}
};
});
it('returns initial state', () => {
expect(callReducer()).toEqual(initialState);
});
});
});
});
| Use initialState in Modal reducer spec | Use initialState in Modal reducer spec
| JavaScript | mit | fs/react-base,fs/react-base,fs/react-base | ---
+++
@@ -60,11 +60,7 @@
});
it('returns initial state', () => {
- expect(callReducer()).toEqual({
- isOpen: false,
- modalName: '',
- modalOptions: {}
- });
+ expect(callReducer()).toEqual(initialState);
});
});
}); |
354ace46a5860a938fb163b316e9c86dc60deae7 | build/dev.sugar.js | build/dev.sugar.js | // webpack config file for develop sugar.js
module.exports = {
'entry': './src/main/index',
'output': {
'path': './bundle',
'library': 'Sugar',
'libraryTarget': 'umd',
'filename': 'sugar.js'
},
'module': {
'loaders': [
{
'test': /\.js$/,
'exclude': /(node_modules|bower_components)/,
'loader': 'babel', // 'babel-loader' is also a legal name to reference
'query': {
'presets': ['es2015']
}
}
]
},
'devtool': 'inline-source-map'
} | // webpack config file for develop sugar.js
module.exports = {
'entry': './src/main/index',
'output': {
'path': './bundle',
'library': 'Sugar',
'libraryTarget': 'umd',
'filename': 'sugar.js'
},
'module': {
'loaders': [
{
'test': /\.js$/,
'exclude': /(node_modules|bower_components)/,
'loader': 'babel', // 'babel-loader' is also a legal name to reference
'query': {
'presets': ['es2015']
}
}
]
},
'devtool': 'source-map'
} | Change webpack devtool to source-map. | Change webpack devtool to source-map.
| JavaScript | mit | tangbc/sugar,tangbc/sugar,tangbc/sugar | ---
+++
@@ -20,5 +20,5 @@
}
]
},
- 'devtool': 'inline-source-map'
+ 'devtool': 'source-map'
} |
c593ba742b86fceb8fdb13a7aac7adfa0ea9a95f | lib/environment.js | lib/environment.js | daysUntilExpiration = function() {
var daysToWait = 1;
var daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate()-daysToWait);
return daysAgo;
} | daysUntilExpiration = function() {
var daysToWait = 90;
var daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate()-daysToWait);
return daysAgo;
} | Change expiration to 90 days | Change expiration to 90 days
| JavaScript | mit | tizol/wework,kaoskeya/wework,BENSEBTI/wework,chrisshayan/wework,num3a/wework,inderpreetsingh/wework,kaoskeya/wework,tizol/wework,EtherCasts/wework,nate-strauser/wework,princesust/wework,princesust/wework,chrisshayan/wework,BENSEBTI/wework,nate-strauser/wework,inderpreetsingh/wework,num3a/wework,EtherCasts/wework | ---
+++
@@ -1,5 +1,5 @@
daysUntilExpiration = function() {
- var daysToWait = 1;
+ var daysToWait = 90;
var daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate()-daysToWait);
return daysAgo; |
9de35c415a1cb7d976e674cffe46d9e5fac7f149 | web/assets/scripts/index.js | web/assets/scripts/index.js | /**
* Created by ogiba on 20.08.2017.
*/
window.addEventListener("DOMContentLoaded", function () {
setupScrollListener();
setupAlertListener();
});
function setupScrollListener() {
var navBar = $('#nav-bar');
var titleBar = $('.app-title');
var distance = navBar.offset().top;
var titleBarDistane = titleBar.offset().top;
$(window).scroll(function () {
if ($(this).scrollTop() >= distance) {
navBar.addClass("fixed-top");
} else {
navBar.removeClass("fixed-top");
}
});
}
function setupAlertListener() {
$("#cookieInfo").on("close.bs.alert", function () {
updateCookieInfo();
});
}
function selectPage(pageNumber) {
console.log(pageNumber);
$.get("/?postPage=" + pageNumber, function (data) {
$("#postsContainer").html("").html(data);
});
}
function updateCookieInfo() {
setCookies("cookieInfo", "displayed");
}
function getCookie(key) {
let cookies = document.cookie;
if (!cookies.includes(key)) {
return null;
}
let values = cookies.split(";");
let cookieValue = values.find(t => t.trim().startsWith(key));
return cookieValue.replace(key, "");
}
function setCookies(key, value) {
document.cookie = `${key}=${value}`;
return document.cookie.includes(key);
}
| /**
* Created by ogiba on 20.08.2017.
*/
window.addEventListener("DOMContentLoaded", function () {
setupScrollListener();
setupAlertListener();
});
function setupScrollListener() {
var navBar = $('#nav-bar');
var titleBar = $('.app-title');
var distance = navBar.offset().top;
var titleBarDistane = titleBar.offset().top;
$(window).scroll(function () {
if ($(this).scrollTop() >= distance) {
navBar.addClass("fixed-top");
} else {
navBar.removeClass("fixed-top");
}
});
}
function setupAlertListener() {
let cookieALert = $("#cookieInfo");
if (cookieALert.length) {
cookieALert.on("close.bs.alert", function () {
updateCookieInfo();
});
}
}
function selectPage(pageNumber) {
console.log(pageNumber);
$.get("/?postPage=" + pageNumber, function (data) {
$("#postsContainer").html("").html(data);
});
}
function updateCookieInfo() {
setCookies("cookieInfo", "displayed");
}
function getCookie(key) {
let cookies = document.cookie;
if (!cookies.includes(key)) {
return null;
}
let values = cookies.split(";");
let cookieValue = values.find(t => t.trim().startsWith(key));
return cookieValue.replace(key, "");
}
function setCookies(key, value) {
document.cookie = `${key}=${value}`;
return document.cookie.includes(key);
}
| Fix setting close event error that ocurred when alert was not placed in view | [CookiesInfo] Fix setting close event error that ocurred when alert was not placed in view
| JavaScript | bsd-2-clause | ogiba/FamilyTree,ogiba/FamilyTree,ogiba/FamilyTree | ---
+++
@@ -23,9 +23,13 @@
}
function setupAlertListener() {
- $("#cookieInfo").on("close.bs.alert", function () {
- updateCookieInfo();
- });
+ let cookieALert = $("#cookieInfo");
+
+ if (cookieALert.length) {
+ cookieALert.on("close.bs.alert", function () {
+ updateCookieInfo();
+ });
+ }
}
function selectPage(pageNumber) { |
1eb106bba3da496ff732ccf02a69e72c43d55e58 | client/app/match/match.js | client/app/match/match.js | angular.module( 'moviematch.match', [] )
.controller( 'MatchController', function( $scope, Match ) {
$scope.movie = {};
$scope.session = {};
$scope.user = {};
$scope.user.name = "Julie";
$scope.session.name = "Girls Night Out";
$scope.movie = {
name: "Gone With The Wind",
year: "1939",
rating: "G",
runtime: "3h 58m",
genres: [ "Drama", "Romance", "War" ],
country: "USA",
poster_path: "https://www.movieposter.com/posters/archive/main/30/MPW-15446",
summary: "A manipulative southern belle carries on a turbulent affair with a blockade runner during the American Civil War.",
director: "Victor Fleming",
cast: "Clark Cable, Vivian Leigh, Thomas Mitchell"
}
$scope.yes = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true );
$scope.no = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false );
} );
| angular.module( 'moviematch.match', [] )
.controller( 'MatchController', function( $scope, Match ) {
$scope.movie = {};
$scope.session = {};
$scope.user = {};
$scope.user.name = "Julie";
$scope.session.name = "Girls Night Out";
$scope.movie = {
name: "Gone With The Wind",
year: "1939",
rating: "G",
runtime: "3h 58m",
genres: [ "Drama", "Romance", "War" ],
country: "USA",
poster_path: "https://www.movieposter.com/posters/archive/main/30/MPW-15446",
summary: "A manipulative southern belle carries on a turbulent affair with a blockade runner during the American Civil War.",
director: "Victor Fleming",
cast: "Clark Cable, Vivian Leigh, Thomas Mitchell"
}
$scope.yes = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true ); }
$scope.no = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false ); }
} );
| Make yes/no function definitions rather than function executions | Make yes/no function definitions rather than function executions
| JavaScript | mpl-2.0 | RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer | ---
+++
@@ -22,6 +22,6 @@
cast: "Clark Cable, Vivian Leigh, Thomas Mitchell"
}
- $scope.yes = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true );
- $scope.no = Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false );
+ $scope.yes = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, true ); }
+ $scope.no = function() { Match.sendVote( $scope.session.id, $scope.user.id, $scope.movie.id, false ); }
} ); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.