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 |
|---|---|---|---|---|---|---|---|---|---|---|
150f734f4aae7a73a9fd3a6e6dd6017fc07cdd4d | imports/server/seed-data/seed-posts.js | imports/server/seed-data/seed-posts.js | import moment from 'moment';
import { Posts } from '../../api/collections';
const seedPosts = () => {
const postCount = Posts.find().count();
if (postCount === 0) {
for (let i = 0; i < 50; i++) {
Posts.insert({
createdAt: moment().utc().toDate(),
userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Video',
source: 'Facebook',
thumb: '/images/feeds.jpg',
url: 'https://www.meteor.com/',
},
totalViews: 30,
totalLikes: 14,
totalShares: 3,
totalComments: 3,
});
Posts.insert({
createdAt: moment().utc().toDate(),
userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Photo',
source: 'Instagram',
thumb: '/images/feeds-2.jpg',
url: 'https://www.meteor.com/',
},
totalViews: 30,
totalLikes: 14,
totalShares: 3,
totalComments: 3,
});
}
}
};
export default seedPosts;
| import moment from 'moment';
import { Posts } from '../../api/collections';
const seedPosts = () => {
const post = Posts.findOne();
if (!post) {
for (let i = 0; i < 50; i++) {
Posts.insert({
userId: 'QBgyG7MsqswQmvm7J',
username: 'evancorl',
createdAt: moment().utc().toDate(),
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Video',
source: 'YouTube',
thumbnail: '/images/feeds.jpg',
url: 'https://www.meteor.com/',
},
likeCount: 14,
commentCount: 3,
});
Posts.insert({
userId: 'QBgyG7MsqswQmvm7J',
username: 'evancorl',
createdAt: moment().utc().toDate(),
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Photo',
thumbnail: '/images/feeds-2.jpg',
url: 'https://www.meteor.com/',
},
likeCount: 14,
commentCount: 3,
});
}
}
};
export default seedPosts;
| Reformat posts in seed data | Reformat posts in seed data
| JavaScript | apache-2.0 | evancorl/portfolio,evancorl/skate-scenes,evancorl/portfolio,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio | ---
+++
@@ -3,44 +3,41 @@
import { Posts } from '../../api/collections';
const seedPosts = () => {
- const postCount = Posts.find().count();
+ const post = Posts.findOne();
- if (postCount === 0) {
+ if (!post) {
for (let i = 0; i < 50; i++) {
Posts.insert({
+ userId: 'QBgyG7MsqswQmvm7J',
+ username: 'evancorl',
createdAt: moment().utc().toDate(),
- userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Video',
- source: 'Facebook',
- thumb: '/images/feeds.jpg',
+ source: 'YouTube',
+ thumbnail: '/images/feeds.jpg',
url: 'https://www.meteor.com/',
},
- totalViews: 30,
- totalLikes: 14,
- totalShares: 3,
- totalComments: 3,
+ likeCount: 14,
+ commentCount: 3,
});
Posts.insert({
+ userId: 'QBgyG7MsqswQmvm7J',
+ username: 'evancorl',
createdAt: moment().utc().toDate(),
- userId: 'QBgyG7MsqswQmvm7J',
message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' +
'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' +
'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.',
media: {
type: 'Photo',
- source: 'Instagram',
- thumb: '/images/feeds-2.jpg',
+ thumbnail: '/images/feeds-2.jpg',
url: 'https://www.meteor.com/',
},
- totalViews: 30,
- totalLikes: 14,
- totalShares: 3,
- totalComments: 3,
+ likeCount: 14,
+ commentCount: 3,
});
}
} |
00d756fce1fc1f4baa3a0698fcba18421027b119 | vue.config.js | vue.config.js | const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { NewLineKind } = require('typescript');
module.exports = {
transpileDependencies: ['vuetify'],
outputDir: './nest_desktop/app',
// https://stackoverflow.com/questions/55258355/vue-clis-type-checking-service-ignores-memory-limits#55810460
// and https://cli.vuejs.org/config/#parallel
configureWebpack: config => {
// save the current ForkTsCheckerWebpackPlugin
const existingForkTsChecker = config.plugins.filter(
plugin => plugin instanceof ForkTsCheckerWebpackPlugin
)[0];
// remove it
config.plugins = config.plugins.filter(
plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin)
);
// copy the options from the original ones, but modify memory and CPUs
const newForkTsCheckerOptions = existingForkTsChecker.options;
newForkTsCheckerOptions.memoryLimit = 8192;
newForkTsCheckerOptions.workers = require('os').cpus().length - 1;
config.plugins.push(
new ForkTsCheckerWebpackPlugin(newForkTsCheckerOptions)
);
},
};
| const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const { NewLineKind } = require('typescript');
module.exports = {
productionSourceMap: false,
transpileDependencies: ['vuetify'],
outputDir: './nest_desktop/app',
// https://stackoverflow.com/questions/55258355/vue-clis-type-checking-service-ignores-memory-limits#55810460
// and https://cli.vuejs.org/config/#parallel
configureWebpack: config => {
// save the current ForkTsCheckerWebpackPlugin
const existingForkTsChecker = config.plugins.filter(
plugin => plugin instanceof ForkTsCheckerWebpackPlugin
)[0];
// remove it
config.plugins = config.plugins.filter(
plugin => !(plugin instanceof ForkTsCheckerWebpackPlugin)
);
// copy the options from the original ones, but modify memory and CPUs
const newForkTsCheckerOptions = existingForkTsChecker.options;
newForkTsCheckerOptions.memoryLimit = 8192;
newForkTsCheckerOptions.workers = require('os').cpus().length - 1;
config.plugins.push(
new ForkTsCheckerWebpackPlugin(newForkTsCheckerOptions)
);
},
};
| Disable source map for production | Disable source map for production
| JavaScript | mit | babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop,babsey/nest-desktop | ---
+++
@@ -2,6 +2,7 @@
const { NewLineKind } = require('typescript');
module.exports = {
+ productionSourceMap: false,
transpileDependencies: ['vuetify'],
outputDir: './nest_desktop/app',
// https://stackoverflow.com/questions/55258355/vue-clis-type-checking-service-ignores-memory-limits#55810460 |
f93e268e7b5a809b28061ff2815121950c896cb4 | src/models/comment.es6.js | src/models/comment.es6.js | import Base from './base';
import process from 'reddit-text-js';
class Comment extends Base {
_type = 'Comment';
constructor(props) {
super(props);
var comment = this;
this.validators = {
body: function() {
return Base.validators.minLength(this.get('body'), 1);
}.bind(comment),
thingId: function() {
var thingId = this.get('thingId');
return Base.validators.thingId(thingId);
}.bind(comment),
};
}
get bodyHtml () {
return process(this.get('body'));
}
toJSON () {
var props = this.props;
props._type = this.type;
props.bodyHtml = this.bodyHtml;
return props;
}
};
export default Comment;
| import Base from './base';
import process from 'reddit-text-js';
class Comment extends Base {
_type = 'Comment';
constructor(props) {
super(props);
var comment = this;
this.validators = {
body: function() {
return Base.validators.minLength(this.get('body'), 1);
}.bind(comment),
thingId: function() {
var thingId = this.get('thingId');
return Base.validators.thingId(thingId);
}.bind(comment),
};
}
get bodyHtml () {
return process(this.get('body'));
}
toJSON () {
var props = this.props;
props._type = this._type;
props.bodyHtml = this.bodyHtml;
return props;
}
};
export default Comment;
| Fix missing underscore in comment type | Fix missing underscore in comment type
| JavaScript | mit | reddit/node-api-client,curioussavage/snoode,reddit/snoode,schwers/snoode,curioussavage/snoode | ---
+++
@@ -27,7 +27,7 @@
toJSON () {
var props = this.props;
- props._type = this.type;
+ props._type = this._type;
props.bodyHtml = this.bodyHtml;
|
53990bb3625947fc37c643b33842e7f3ba8340f7 | lib/urlresolver.js | lib/urlresolver.js | var standardPageTypes = {
'event': /^(19|20)[0-9]{2}\//
};
var resolveUrl = function(urlFragment) {
return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, '');
};
var shortenUrl = function(url) {
return url.replace(/^(http:\/\/){1}(www\.)?(lanyrd\.com\/){1}|\//, '');
};
var resolvePageType = function(url, types) {
url = resolveUrl(url);
types = types || standardPageTypes;
var matches = Object.keys(types).filter(function(type) {
var urlRegExp = types[type];
return urlRegExp.test(url);
});
return matches.length ? matches[0] : null;
};
module.exports = {
resolveUrl: resolveUrl,
shortenUrl: shortenUrl,
resolvePageType: resolvePageType
}; | var standardPageTypes = {
'event': /^(19|20)[0-9]{2}\//
};
var resolveUrl = function(urlFragment) {
return (/^http:\/\//).test(urlFragment) ? urlFragment : 'http://lanyrd.com/' + urlFragment.replace(/^\//, '');
};
var shortenUrl = function(url) {
return url.replace(/^(http:\/\/.*?)?\//, '');
};
var resolvePageType = function(url, types) {
url = resolveUrl(url);
types = types || standardPageTypes;
var matches = Object.keys(types).filter(function(type) {
var urlRegExp = types[type];
return urlRegExp.test(url);
});
return matches.length ? matches[0] : null;
};
module.exports = {
resolveUrl: resolveUrl,
shortenUrl: shortenUrl,
resolvePageType: resolvePageType
}; | Make URL shortener more forgiving | Make URL shortener more forgiving
| JavaScript | mit | markdalgleish/node-lanyrd-scraper | ---
+++
@@ -7,7 +7,7 @@
};
var shortenUrl = function(url) {
- return url.replace(/^(http:\/\/){1}(www\.)?(lanyrd\.com\/){1}|\//, '');
+ return url.replace(/^(http:\/\/.*?)?\//, '');
};
var resolvePageType = function(url, types) { |
b3d6d0ea244499c44eb0d3f8c50b1b4ddc3625f8 | src/controllers/SpotifyController.js | src/controllers/SpotifyController.js | controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
frameSelector: '#main, #app-player',
playStateSelector: '#play, #play-pause',
playStateClass: 'playing',
playPauseSelector: '#play, #play-pause',
nextSelector: '#next',
previousSelector: '#previous',
titleSelector: '.caption .track, #track-name',
artistSelector: '.caption .artist, #track-artist'
});
controller.override('getAlbumArt', function() {
return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image, #cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
});
| if (!!document.querySelector('#app-player')) { // Old Player
controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
frameSelector: '#app-player',
playStateSelector: '#play-pause',
playStateClass: 'playing',
playPauseSelector: '#play-pause',
nextSelector: '#next',
previousSelector: '#previous',
titleSelector: '#track-name',
artistSelector: '#track-artist'
});
controller.override('getAlbumArt', function() {
return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
});
} else { // New Player
controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
frameSelector: '#main',
playStateSelector: '#play',
playStateClass: 'playing',
playPauseSelector: '#play',
nextSelector: '#next',
previousSelector: '#previous',
titleSelector: '.caption .track',
artistSelector: '.caption .artist'
});
controller.override('getAlbumArt', function() {
return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1);
});
}
| Support New and Old Spotify | Support New and Old Spotify
| JavaScript | agpl-3.0 | cwal/chrome-media-keys,ahmedalsudani/chrome-media-keys,msfeldstein/chrome-media-keys,PeterMinin/chrome-media-keys,ahmedalsudani/chrome-media-keys,PeterMinin/chrome-media-keys,cwal/chrome-media-keys | ---
+++
@@ -1,20 +1,43 @@
-controller = new BasicController({
- supports: {
+if (!!document.querySelector('#app-player')) { // Old Player
+ controller = new BasicController({
+ supports: {
playpause: true,
next: true,
previous: true
- },
- useLazyObserving: true,
- frameSelector: '#main, #app-player',
- playStateSelector: '#play, #play-pause',
- playStateClass: 'playing',
- playPauseSelector: '#play, #play-pause',
- nextSelector: '#next',
- previousSelector: '#previous',
- titleSelector: '.caption .track, #track-name',
- artistSelector: '.caption .artist, #track-artist'
-});
+ },
+ useLazyObserving: true,
+ frameSelector: '#app-player',
+ playStateSelector: '#play-pause',
+ playStateClass: 'playing',
+ playPauseSelector: '#play-pause',
+ nextSelector: '#next',
+ previousSelector: '#previous',
+ titleSelector: '#track-name',
+ artistSelector: '#track-artist'
+ });
-controller.override('getAlbumArt', function() {
- return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image, #cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
-});
+ controller.override('getAlbumArt', function() {
+ return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
+ });
+} else { // New Player
+ controller = new BasicController({
+ supports: {
+ playpause: true,
+ next: true,
+ previous: true
+ },
+ useLazyObserving: true,
+ frameSelector: '#main',
+ playStateSelector: '#play',
+ playStateClass: 'playing',
+ playPauseSelector: '#play',
+ nextSelector: '#next',
+ previousSelector: '#previous',
+ titleSelector: '.caption .track',
+ artistSelector: '.caption .artist'
+ });
+
+ controller.override('getAlbumArt', function() {
+ return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1);
+ });
+} |
9b5908c0bd5bd35a092b7a3b6400f90a73ff38b7 | app/assets/javascripts/forest/admin/partials/forest_tables.js | app/assets/javascripts/forest/admin/partials/forest_tables.js | // Forest tables
$(document).on('mouseenter', '.forest-table tbody tr', function() {
var $row = $(this);
$row.addClass('active');
$(document).one('turbolinks:before-cache.forestTables', function() {
$row.removeClass('active');
});
});
$(document).on('mouseleave', '.forest-table tbody tr', function() {
var $row = $(this);
$row.removeClass('active');
});
$(document).on('click', '.forest-table tbody tr', function(e) {
var $row = $(this);
if ( !$(e.target).closest('a').length ) {
var $button = $row.find('a.forest-table__link:first');
if ( !$button.length ) {
$button = $row.find('a.btn-primary:first');
}
var url = $button.attr('href');
if ( url ) {
if ( e.metaKey || e.ctrlKey ) {
window.open( url, '_blank' );
} else if ( e.shiftKey ) {
window.open( url, '_blank' );
window.focus();
} else {
Turbolinks.visit(url);
}
}
}
});
| // Forest tables
$(document).on('mouseenter', '.forest-table tbody tr', function() {
var $row = $(this);
$row.addClass('active');
$(document).one('turbolinks:before-cache.forestTables', function() {
$row.removeClass('active');
});
});
$(document).on('mouseleave', '.forest-table tbody tr', function() {
var $row = $(this);
$row.removeClass('active');
});
$(document).on('click', '.forest-table tbody tr', function(e) {
var $row = $(this);
if ( !$(e.target).closest('a, input').length ) {
var $button = $row.find('a.forest-table__link:first');
if ( !$button.length ) {
$button = $row.find('a.btn-primary:first');
}
var url = $button.attr('href');
if ( url ) {
if ( e.metaKey || e.ctrlKey ) {
window.open( url, '_blank' );
} else if ( e.shiftKey ) {
window.open( url, '_blank' );
window.focus();
} else {
Turbolinks.visit(url);
}
}
}
});
| Allow inputs inside forest tables | Allow inputs inside forest tables
| JavaScript | mit | dylanfisher/forest,dylanfisher/forest,dylanfisher/forest | ---
+++
@@ -19,7 +19,7 @@
$(document).on('click', '.forest-table tbody tr', function(e) {
var $row = $(this);
- if ( !$(e.target).closest('a').length ) {
+ if ( !$(e.target).closest('a, input').length ) {
var $button = $row.find('a.forest-table__link:first');
if ( !$button.length ) { |
cb906f55fa6f5ad491d0828a343a6d407cdd8e80 | client/src/app.js | client/src/app.js | import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import transactionReducer from './reducers'
import { applyMiddleware, createStore } from 'redux';
import { render } from 'react-dom';
import React from 'react';
import Main from './components/Main';
import { Provider } from 'react-redux';
const store = createStore(
transactionReducer,
applyMiddleware(thunk),
applyMiddleware(createLogger())
);
render(
<Provider store={store} >
<Main />
</Provider>,
document.getElementById('app')
);
| import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import transactionReducer from './reducers'
import { applyMiddleware, createStore } from 'redux';
import { render } from 'react-dom';
import React from 'react';
import Main from './components/Main';
import { Provider } from 'react-redux';
const store = createStore(
transactionReducer,
applyMiddleware(thunk, createLogger())
);
render(
<Provider store={store} >
<Main />
</Provider>,
document.getElementById('app')
);
| Fix middlewares order for proper thunk logging | Fix middlewares order for proper thunk logging
| JavaScript | mit | Nauktis/inab,Nauktis/inab,Nauktis/inab | ---
+++
@@ -10,8 +10,7 @@
const store = createStore(
transactionReducer,
- applyMiddleware(thunk),
- applyMiddleware(createLogger())
+ applyMiddleware(thunk, createLogger())
);
render( |
10fd21e05457f0225d39102002565cff2fff264f | src/util/filters.js | src/util/filters.js | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
return exactMatches.concat(substringMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]);
if (currentFilters.length) {
filtered = filtered.filter(j => currentFilters.includes(j.filterable[i]));
}
});
return filtered;
} | export function filterByText(data, textFilter) {
if (textFilter === '') {
return data;
}
// case-insensitive
textFilter = textFilter.toLowerCase();
const exactMatches = [];
const substringMatches = [];
data.forEach(i => {
const name = i.name.toLowerCase();
if (name.split(' ').includes(textFilter)) {
exactMatches.push(i);
} else if (name.includes(textFilter)) {
substringMatches.push(i);
}
});
// return in ascending order
return substringMatches.concat(exactMatches);
}
export function filterByCheckbox(data, checkboxFilters) {
let filtered = data;
Object.keys(checkboxFilters).forEach(i => {
const currentFilters = Object.keys(checkboxFilters[i]).filter(j => checkboxFilters[i][j]);
if (currentFilters.length) {
filtered = filtered.filter(j => currentFilters.includes(j.filterable[i]));
}
});
return filtered;
} | Return exact results by default | Return exact results by default
| JavaScript | agpl-3.0 | Johj/cqdb,Johj/cqdb | ---
+++
@@ -16,7 +16,8 @@
}
});
- return exactMatches.concat(substringMatches);
+ // return in ascending order
+ return substringMatches.concat(exactMatches);
}
export function filterByCheckbox(data, checkboxFilters) { |
c0a1c31d1b49fddcdb790897176d9e5802da117e | client/config/bootstrap.js | client/config/bootstrap.js | /**
* Client entry point
*/
// Polyfills
import 'babel-polyfill'
// Styles
import 'components/styles/resets.css'
// Modules
import { browserHistory } from 'react-router'
import React from 'react'
import ReactDOM from 'react-dom'
import Relay from 'react-relay'
import { RelayRouter } from 'react-router-relay'
// Routes
import routes from './routes'
// Configure Relay's network layer to include cookies
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin'
})
)
// Create the app node appended to the body
const app = document.body.appendChild(document.createElement('div'))
// Mount the app
ReactDOM.render(
<RelayRouter
history={browserHistory}
routes={routes}
/>,
app
)
| /**
* Client entry point
*/
// Polyfills
import 'babel-polyfill'
// Styles
import 'components/styles/resets.css'
// Modules
import { browserHistory } from 'react-router'
import React from 'react'
import ReactDOM from 'react-dom'
import Relay from 'react-relay'
import { RelayRouter } from 'react-router-relay'
// Routes
import routes from './routes'
// Configure Relay's network layer to include cookies
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin'
})
)
// Configure Relay's task scheduler to spread out task execution
import raf from 'raf'
Relay.injectTaskScheduler(task => raf(task))
// Create the app node appended to the body
const app = document.body.appendChild(document.createElement('div'))
// Mount the app
ReactDOM.render(
<RelayRouter
history={browserHistory}
routes={routes}
/>,
app
)
| Use raf for Relay's task scheduler | Use raf for Relay's task scheduler
| JavaScript | apache-2.0 | cesarandreu/bshed,cesarandreu/bshed | ---
+++
@@ -25,6 +25,10 @@
})
)
+// Configure Relay's task scheduler to spread out task execution
+import raf from 'raf'
+Relay.injectTaskScheduler(task => raf(task))
+
// Create the app node appended to the body
const app = document.body.appendChild(document.createElement('div'))
|
88a806cb56dadead5f48eb1a7cdec6a26fc4d166 | www/submit.js | www/submit.js | $('#task').on('change', function() {
if ( $(this).val() == 'custom') {
$('#custom_videos').removeClass('hidden');
} else {
$('#custom_videos').addClass('hidden');
}
});
| $('#task').on('change', function() {
if ( $(this).val() == 'custom') {
$('#custom_videos').removeClass('hidden');
} else {
$('#custom_videos').addClass('hidden');
}
});
$('#task').trigger('change');
| Make sure UI is consistent on load | Make sure UI is consistent on load
| JavaScript | mit | mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,mdinger/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy | ---
+++
@@ -5,3 +5,5 @@
$('#custom_videos').addClass('hidden');
}
});
+
+$('#task').trigger('change'); |
af2827c0ce2fdca4c095fb160d3fa1437fb400a6 | webpack.config.babel.js | webpack.config.babel.js | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget: 'umd',
},
externals: {
most: {
root: 'most',
commonjs2: 'most',
commonjs: 'most',
amd: 'most',
},
redux: {
root: 'Redux',
commonjs2: 'redux',
commonjs: 'redux',
amd: 'redux',
},
},
resolve: {
extensions: ['.js'],
mainFields: ['module', 'main', 'jsnext:main'],
},
}
const devConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'development'
}),
],
}
const prodConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.min.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'production'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
comments: false,
}),
],
}
module.exports = [devConfig, prodConfig]
| /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget: 'umd',
},
externals: {
most: {
root: 'most',
commonjs2: 'most',
commonjs: 'most',
amd: 'most',
},
redux: {
root: 'Redux',
commonjs2: 'redux',
commonjs: 'redux',
amd: 'redux',
},
},
resolve: {
extensions: ['.js'],
mainFields: ['module', 'main', 'jsnext:main'],
},
}
const devConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'development',
}),
],
}
const prodConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.min.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'production',
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
comments: false,
}),
],
}
module.exports = [devConfig, prodConfig]
| Add missing trailing commas in new webpack config | Add missing trailing commas in new webpack config
| JavaScript | mit | joshburgess/redux-most | ---
+++
@@ -45,7 +45,7 @@
},
plugins: [
new webpack.EnvironmentPlugin({
- 'NODE_ENV': 'development'
+ 'NODE_ENV': 'development',
}),
],
}
@@ -58,7 +58,7 @@
},
plugins: [
new webpack.EnvironmentPlugin({
- 'NODE_ENV': 'production'
+ 'NODE_ENV': 'production',
}),
new webpack.optimize.UglifyJsPlugin({
compress: { |
66037a236a0f1b099c8e06f094a7070ab37be363 | src/users/usersActions.js | src/users/usersActions.js | /* @flow strict-local */
import differenceInSeconds from 'date-fns/difference_in_seconds';
import type { Dispatch, GetState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
let lastReportPresence = new Date();
let lastTypingStart = new Date();
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async (
dispatch: Dispatch,
getState: GetState,
) => {
const auth = tryGetAuth(getState());
if (!auth) {
return; // not logged in
}
if (differenceInSeconds(new Date(), lastReportPresence) < 60) {
return;
}
lastReportPresence = new Date();
const response = await api.reportPresence(auth, hasFocus, newUserInput);
dispatch({
type: PRESENCE_RESPONSE,
presence: response.presences,
serverTimestamp: response.server_timestamp,
});
};
export const sendTypingEvent = (narrow: Narrow) => async (
dispatch: Dispatch,
getState: GetState,
) => {
if (!isPrivateOrGroupNarrow(narrow)) {
return;
}
if (differenceInSeconds(new Date(), lastTypingStart) > 15) {
const auth = getAuth(getState());
api.typing(auth, narrow[0].operand, 'start');
lastTypingStart = new Date();
}
};
| /* @flow strict-local */
import differenceInSeconds from 'date-fns/difference_in_seconds';
import type { Dispatch, GetState, Narrow } from '../types';
import * as api from '../api';
import { PRESENCE_RESPONSE } from '../actionConstants';
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
let lastReportPresence = new Date(0);
let lastTypingStart = new Date();
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async (
dispatch: Dispatch,
getState: GetState,
) => {
const auth = tryGetAuth(getState());
if (!auth) {
return; // not logged in
}
if (differenceInSeconds(new Date(), lastReportPresence) < 60) {
return;
}
lastReportPresence = new Date();
const response = await api.reportPresence(auth, hasFocus, newUserInput);
dispatch({
type: PRESENCE_RESPONSE,
presence: response.presences,
serverTimestamp: response.server_timestamp,
});
};
export const sendTypingEvent = (narrow: Narrow) => async (
dispatch: Dispatch,
getState: GetState,
) => {
if (!isPrivateOrGroupNarrow(narrow)) {
return;
}
if (differenceInSeconds(new Date(), lastTypingStart) > 15) {
const auth = getAuth(getState());
api.typing(auth, narrow[0].operand, 'start');
lastTypingStart = new Date();
}
};
| Initialize lastReportPresence as "long ago", not "now". | presence: Initialize lastReportPresence as "long ago", not "now".
Before we were setting it as `new Date()`. So when app was opened, this
variable was initialized as `new Date()` and we call `reportPresence`
from `fetchActions`. As diff is not >= 60, so `reportPresence` returns
without reporting to the server. And one cycle of reporting to server
was missed, which was resulting in delay marking user as active.
Now initialize it as `new Date(0)`, means last presence reported was
long time back, which will result in reporting promptly on app launch.
Fixes: #3590
| JavaScript | apache-2.0 | vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile | ---
+++
@@ -7,7 +7,7 @@
import { getAuth, tryGetAuth } from '../selectors';
import { isPrivateOrGroupNarrow } from '../utils/narrow';
-let lastReportPresence = new Date();
+let lastReportPresence = new Date(0);
let lastTypingStart = new Date();
export const reportPresence = (hasFocus: boolean = true, newUserInput: boolean = false) => async ( |
df21faead2b427c56152eca744f12ce8fcc1e0ca | package/index.js | package/index.js | /* eslint global-require: 0 */
/* eslint import/no-dynamic-require: 0 */
const Environment = require('./environment')
const { existsSync } = require('fs')
function createEnvironment() {
const path = `./environments/${process.env.NODE_ENV}`
const constructor = existsSync(path) ? require(path) : Environment
return new constructor()
}
const environment = createEnvironment()
module.exports = { environment, Environment }
| /* eslint global-require: 0 */
/* eslint import/no-dynamic-require: 0 */
const Environment = require('./environment')
const { resolve } = require('path')
const { existsSync } = require('fs')
function createEnvironment() {
const path = resolve(__dirname, 'environments', `${process.env.NODE_ENV}.js`)
const constructor = existsSync(path) ? require(path) : Environment
return new constructor()
}
const environment = createEnvironment()
module.exports = { environment, Environment }
| Resolve full file path + name to fix existsSync check | Resolve full file path + name to fix existsSync check
| JavaScript | mit | gauravtiwari/webpacker,gauravtiwari/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,rails/webpacker,usertesting/webpacker,rails/webpacker,rossta/webpacker,rossta/webpacker,usertesting/webpacker,gauravtiwari/webpacker | ---
+++
@@ -2,10 +2,11 @@
/* eslint import/no-dynamic-require: 0 */
const Environment = require('./environment')
+const { resolve } = require('path')
const { existsSync } = require('fs')
function createEnvironment() {
- const path = `./environments/${process.env.NODE_ENV}`
+ const path = resolve(__dirname, 'environments', `${process.env.NODE_ENV}.js`)
const constructor = existsSync(path) ? require(path) : Environment
return new constructor()
} |
be877f2c612fa5a4049e563193feed3f349dca75 | static/js/pedido.js | static/js/pedido.js | $(document).ready(function () {
$("#id_type_1").click(function () {
$("#id_inbound_date").parents('.row').hide();
$("#id_inbound_date_preference").parents('.row').hide();
});
$("#id_type_0").click(function () {
$("#id_inbound_date").parents('.row').show();
$("#id_inbound_date_preference").parents('.row').show();
});
}); | $(document).ready(function () {
$("#id_type_1").click(function () {
$("#id_inbound_date").parents('.row').hide();
$("#id_inbound_date_preference").parents('.row').hide();
});
$("#id_type_0").click(function () {
$("#id_inbound_date").parents('.row').show();
$("#id_inbound_date_preference").parents('.row').show();
});
if (id_type_1.checked){
$("#id_inbound_date").parents('.row').hide();
$("#id_inbound_date_preference").parents('.row').hide();
}
}); | Hide or show inbound date according with type of trip selected | Hide or show inbound date according with type of trip selected
| JavaScript | mpl-2.0 | neuromat/nira,neuromat/nira,neuromat/nira | ---
+++
@@ -7,4 +7,8 @@
$("#id_inbound_date").parents('.row').show();
$("#id_inbound_date_preference").parents('.row').show();
});
+ if (id_type_1.checked){
+ $("#id_inbound_date").parents('.row').hide();
+ $("#id_inbound_date_preference").parents('.row').hide();
+ }
}); |
a8ad29163c1021ccc7055f06745d8b1a43623f3e | helper_functions/price_discount.js | helper_functions/price_discount.js | // priceDiscount function
// Discounts sale price by 15% is price is > $8,000
module.exports.priceDiscount = (price) => {
if (price > 8000) {
return price * .15
}
return price;
}; | // priceDiscount function
// Discounts sale price by 15% is price is > $8,000
module.exports.priceDiscount = (price) => {
if (price > 8000) {
return price / 1.15
}
return price;
}; | Fix function so it properly deducts 15% from price | Fix function so it properly deducts 15% from price
| JavaScript | mit | dshaps10/full-stack-demo-site,dshaps10/full-stack-demo-site | ---
+++
@@ -2,7 +2,7 @@
// Discounts sale price by 15% is price is > $8,000
module.exports.priceDiscount = (price) => {
if (price > 8000) {
- return price * .15
+ return price / 1.15
}
return price;
}; |
86b19d7030564176a56d2c1ab20ebe16df33066f | src/countdown/countdown.js | src/countdown/countdown.js | angular.module('ngIdle.countdown', ['ngIdle.idle'])
.directive('idleCountdown', ['Idle', function(Idle) {
return {
restrict: 'A',
scope: {
value: '=idleCountdown'
},
link: function($scope) {
// Initialize the scope's value to the configured timeout.
$scope.value = Idle._options().timeout;
$scope.$on('IdleWarn', function(e, countdown) {
$scope.$apply(function() {
$scope.value = countdown;
});
});
$scope.$on('IdleTimeout', function() {
$scope.$apply(function() {
$scope.value = 0;
});
});
}
};
}]);
| angular.module('ngIdle.countdown', ['ngIdle.idle'])
.directive('idleCountdown', ['Idle', function(Idle) {
return {
restrict: 'A',
scope: {
value: '=idleCountdown'
},
link: function($scope) {
// Initialize the scope's value to the configured timeout.
$scope.value = Idle.getTimeout();
$scope.$on('IdleWarn', function(e, countdown) {
$scope.$apply(function() {
$scope.value = countdown;
});
});
$scope.$on('IdleTimeout', function() {
$scope.$apply(function() {
$scope.value = 0;
});
});
}
};
}]);
| Use Idle.getTimeout() instead of internal _options() | Use Idle.getTimeout() instead of internal _options()
| JavaScript | mit | dgoncalves1/ng-idle,JCherryhomes/ng-idle,HackedByChinese/ng-idle,koitoer/ng-idle,MasterFacilityList/ng-idle,JCherryhomes/ng-idle,koitoer/ng-idle,karthilxg/ng-idle,MasterFacilityList/ng-idle,karthilxg/ng-idle,msuresu/ng-idle,seegno-forks/ng-idle,jpribesh/ng-idle,dgoncalves1/ng-idle,seegno-forks/ng-idle,msuresu/ng-idle,jpribesh/ng-idle | ---
+++
@@ -7,7 +7,7 @@
},
link: function($scope) {
// Initialize the scope's value to the configured timeout.
- $scope.value = Idle._options().timeout;
+ $scope.value = Idle.getTimeout();
$scope.$on('IdleWarn', function(e, countdown) {
$scope.$apply(function() { |
d36c1654f985684fc798cb703f1c5b24f10f102d | gulpfile.babel.js | gulpfile.babel.js | import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myConfig = {
...config,
plugins: config.plugins.concat(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
),
};
webpack(myConfig, (err, stats) => {
if (err) {
throw new gutil.PluginError('webpack:build', err);
}
gutil.log('[webpack:build]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task('webpack-dev-server', callback => {
var myConfig = {
...config,
debug: true,
};
new WebpackDevServer(webpack(myConfig), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true,
},
}).listen(8080, 'localhost', err => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
gutil.log('[webpack-dev-server]', 'http://localhost:3000');
});
});
| import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
import gulp from 'gulp';
import gutil from 'gulp-util';
import webpack from 'webpack';
gulp.task('default', ['webpack-dev-server']);
gulp.task('build', ['webpack:build']);
gulp.task('webpack:build', callback => {
const myConfig = {
...config,
plugins: config.plugins.concat(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
),
};
webpack(myConfig, (err, stats) => {
if (err) {
throw new gutil.PluginError('webpack:build', err);
}
gutil.log('[webpack:build]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task('webpack-dev-server', callback => {
var myConfig = {
...config,
debug: true,
};
new WebpackDevServer(webpack(myConfig), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true,
},
}).listen(3000, 'localhost', err => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
gutil.log('[webpack-dev-server]', 'http://localhost:3000');
});
});
| Use the right port number | Use the right port number
I find this makes all the difference...
| JavaScript | mit | wincent/hextrapolate,cpojer/hextrapolate,wincent/hextrapolate,cpojer/hextrapolate,cpojer/hextrapolate,wincent/hextrapolate | ---
+++
@@ -46,7 +46,7 @@
stats: {
colors: true,
},
- }).listen(8080, 'localhost', err => {
+ }).listen(3000, 'localhost', err => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
} |
d377b7d8bfaf88408fdf3ef3182fb15df4689924 | src/configs/webpack/project-config.js | src/configs/webpack/project-config.js | 'use strict';
var tmpl = require('blueimp-tmpl').tmpl;
var path = require('path');
var readTemplate = require('../../utils/read-template');
var projectName = require('project-name');
function buildProjectWebpackConfig(options) {
var params = options || {};
var config = {};
if (params.env !== 'development' && params.env !== 'test' && params.env !== 'production') {
throw new Error('INVALID ENVIROMENT: ' + params.env + '. Supported: [development, test, production]');
}
config = {
env: params.env
};
config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group);
return config;
}
module.exports = function generateWebpackConfig(options) {
var source = path.resolve(__dirname, '../../templates/project-webpack.js.tmpl');
var webpackTemplate = readTemplate(source);
var webpackConfig = buildProjectWebpackConfig(options);
var template = tmpl(webpackTemplate, webpackConfig);
return {
template: template,
json: webpackConfig
};
};
| 'use strict';
var tmpl = require('blueimp-tmpl').tmpl;
var path = require('path');
var readTemplate = require('../../utils/read-template');
var projectName = require('project-name');
function buildProjectWebpackConfig(options) {
var params = options || {};
var config = {};
if (params.env !== 'development' && params.env !== 'test' && params.env !== 'production') {
throw new Error('INVALID ENVIROMENT: ' + params.env + '. Supported: [development, test, production]');
}
config = {
env: params.env
};
config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group, 'project-webpack.config.' + options.env + '.js');
return config;
}
module.exports = function generateWebpackConfig(options) {
var source = path.resolve(__dirname, '../../templates/project-webpack.js.tmpl');
var webpackTemplate = readTemplate(source);
var webpackConfig = buildProjectWebpackConfig(options);
var template = tmpl(webpackTemplate, webpackConfig);
return {
template: template,
json: webpackConfig
};
};
| Update webpack project config path | Update webpack project config path
| JavaScript | mit | mikechau/js-config-gen,mikechau/js-config-gen | ---
+++
@@ -18,7 +18,7 @@
env: params.env
};
- config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group);
+ config.webpackConfigPath = './' + path.join('node_modules', projectName(process.cwd()), 'dist', params.group, 'project-webpack.config.' + options.env + '.js');
return config;
} |
8fd75333771f1fd3170c0796740c730b2f0eb807 | test/graphics/iconSpec.js | test/graphics/iconSpec.js | define(["sugar-web/graphics/icon"], function (icon) {
describe("icon", function () {
var wasLoaded;
var iconUrlResult;
it("should be able to change icon more than once", function () {
var elem = document.createElement('div');
var iconUrl;
function callback(url) {
iconUrlResult = url;
wasLoaded = true;
}
runs(function () {
wasLoaded = false;
iconUrl = "graphics/icons/actions/dialog-ok-active.svg";
iconInfo = {
"uri": iconUrl,
"strokeColor": '#B20008',
"fillColor": '#FF2B34'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
runs(function () {
wasLoaded = false;
iconUrl = iconUrlResult;
iconInfo = {
"uri": iconUrl,
"strokeColor": '#FF2B34',
"fillColor": '#B20008'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
});
});
});
| define(["sugar-web/graphics/icon"], function (icon) {
describe("icon", function () {
var wasLoaded;
var iconUrlResult;
it("should be able to change icon more than once", function () {
var elem = document.createElement('div');
var iconUrl;
function callback(url) {
iconUrlResult = url;
wasLoaded = true;
}
runs(function () {
wasLoaded = false;
iconUrl = "/base/graphics/icons/actions/dialog-ok-active.svg";
iconInfo = {
"uri": iconUrl,
"strokeColor": '#B20008',
"fillColor": '#FF2B34'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
runs(function () {
wasLoaded = false;
iconUrl = iconUrlResult;
iconInfo = {
"uri": iconUrl,
"strokeColor": '#FF2B34',
"fillColor": '#B20008'
};
icon.load(iconInfo, callback);
});
waitsFor(function () {
return wasLoaded;
}, "icon loaded");
runs(function () {
expect(iconUrlResult).not.toBe(iconUrl);
});
});
});
});
| Use /base in the SVG path | Use /base in the SVG path
Unfortunatly we need that.
| JavaScript | apache-2.0 | godiard/sugar-web,sugarlabs/sugar-web | ---
+++
@@ -14,7 +14,7 @@
runs(function () {
wasLoaded = false;
- iconUrl = "graphics/icons/actions/dialog-ok-active.svg";
+ iconUrl = "/base/graphics/icons/actions/dialog-ok-active.svg";
iconInfo = {
"uri": iconUrl,
"strokeColor": '#B20008', |
55474b5c3cb32f1cc53fe56b82d21c04a98a560e | app/assets/javascripts/evZoom.js | app/assets/javascripts/evZoom.js | $(function() {
$('#zoom_01').elevateZoom();
});
| $(function() {
$('#zoom_01').elevateZoom();
$('.zoom').each(function(element) {
$(this).elevateZoom()
});
});
| Update ElevateZoom uses class .zoom | Update ElevateZoom uses class .zoom | JavaScript | mit | gouf/test_elevate_zoom,gouf/test_elevate_zoom | ---
+++
@@ -1,3 +1,7 @@
$(function() {
$('#zoom_01').elevateZoom();
+
+ $('.zoom').each(function(element) {
+ $(this).elevateZoom()
+ });
}); |
37a73986d3d36353a30e661b3989dcd8a646bc39 | 04/jjhampton-ch4-list.js | 04/jjhampton-ch4-list.js | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const arrayLength = array.length;
let list = null;
for (let i = array.length - 1; i >= 0; i-- ) {
list = {
value: array[i],
rest: list
};
}
return list;
}
const theArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arrayToList(theArray));
function listToArray(list) {
console.log(list);
const array = [
list.value,
list.rest.value,
list.rest.rest.value
];
return array;
}
// const theList = arrayToList([1, 2, 3]);
// console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
function prepend(element, list) {
let newList;
// do some stuff here
return newList;
} | // Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element.
function arrayToList(array) {
const arrayLength = array.length;
let list = null;
for (let i = array.length - 1; i >= 0; i-- ) {
list = {
value: array[i],
rest: list
};
}
return list;
}
const theArray = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(arrayToList(theArray));
function listToArray(list) {
let array = [];
for (let currentNode = list; currentNode; currentNode = currentNode.rest) {
array.push(currentNode.value);
}
return array;
}
const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
function prepend(element, list) {
let newList;
// do some stuff here
return newList;
} | Refactor listToArray to work with list parameters of dynamic sizes | Refactor listToArray to work with list parameters of dynamic sizes
| JavaScript | mit | OperationCode/eloquent-js | ---
+++
@@ -16,17 +16,15 @@
console.log(arrayToList(theArray));
function listToArray(list) {
- console.log(list);
- const array = [
- list.value,
- list.rest.value,
- list.rest.rest.value
- ];
+ let array = [];
+ for (let currentNode = list; currentNode; currentNode = currentNode.rest) {
+ array.push(currentNode.value);
+ }
return array;
}
-// const theList = arrayToList([1, 2, 3]);
-// console.log(listToArray(theList));
+const theList = arrayToList([1, 2, 3, 4, 5, 6, 7, 8]);
+console.log(listToArray(theList));
// write helper function 'prepend', which takes an element and a list and creates a new list that adds the element to the front of the input list
|
338634c1d6baeb464d3f723452427a8cd0d60929 | test/smoke-tests.js | test/smoke-tests.js | var assert = require('assert')
// , expresso = require('expresso')
, dustx = require('dust-x')
module.exports = {
'test 1': function(end) {
assert.ok(true, 'pre-test')
end(function() {
assert.ok(false, 'post-test')
})
}
}
| var assert = require('assert')
, app = require('../example/app')
module.exports = {
'GET /': function() {
assert.response(app,
{ url: '/' },
{ status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' }},
function(res) {
assert.includes(res.body, '<title>Dust-X Demo</title>');
}
)
}
}
| Fix smoke-test to do something useful. | Fix smoke-test to do something useful.
| JavaScript | mit | laurie71/dust-x | ---
+++
@@ -1,13 +1,14 @@
var assert = require('assert')
- // , expresso = require('expresso')
- , dustx = require('dust-x')
-
+ , app = require('../example/app')
+
module.exports = {
- 'test 1': function(end) {
- assert.ok(true, 'pre-test')
-
- end(function() {
- assert.ok(false, 'post-test')
- })
+ 'GET /': function() {
+ assert.response(app,
+ { url: '/' },
+ { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' }},
+ function(res) {
+ assert.includes(res.body, '<title>Dust-X Demo</title>');
+ }
+ )
}
} |
4a189c3a3dd1f0304a788c280d1839d94c40dc47 | tests/acceptance.js | tests/acceptance.js | var assert = require('chai').assert;
var http = require('http');
var mathServer = require('../lib/mathServer.js');
var request = require('supertest');
process.env.NODE_ENV = 'test';
describe('Acceptance test', function () {
var port = 8006;
var server;
before(function () {
process.on('stdout', function(data) {
console.log('**' + data);
});
process.on('stderr', function(data) {
console.log('**' + data);
});
server = mathServer.MathServer({
port: port,
CONTAINERS: './dummy_containers.js'
});
server.listen();
});
after(function (done) {
server.close();
done();
});
describe('As basic behavior we', function () {
it('should be able to create server and get title from html body', function (done) {
http.get("http://127.0.0.1:" + port, function (res) {
res.on('data', function (body) {
var str = body.toString('utf-8');
var n = str.match(/<title>\s*([^\s]*)\s*<\/title>/);
assert.equal(n[1], 'Macaulay2');
done();
});
});
});
it('should show title', function (done) {
request = request('http://localhost:' + port);
request.get('/').expect(200).end(function(error, result) {
assert.match(result.text, /<title>\s*Macaulay2\s*<\/title>/);
done();
});
});
});
});
| var assert = require('chai').assert;
var http = require('http');
var mathServer = require('../lib/mathServer.js');
var request = require('supertest');
process.env.NODE_ENV = 'test';
describe.only('Acceptance test', function () {
var port = 8006;
var server;
before(function () {
server = mathServer.MathServer({
port: port,
CONTAINERS: './dummy_containers.js'
});
server.listen();
request = request('http://localhost:' + port);
});
after(function (done) {
server.close();
done();
});
describe('As basic behavior we', function () {
it('should be able to create server and get title from html body', function (done) {
http.get("http://127.0.0.1:" + port, function (res) {
res.on('data', function (body) {
var str = body.toString('utf-8');
var n = str.match(/<title>\s*([^\s]*)\s*<\/title>/);
assert.equal(n[1], 'Macaulay2');
done();
});
});
});
it('should show title', function (done) {
request.get('/').expect(200).end(function(error, result) {
assert.match(result.text, /<title>\s*Macaulay2\s*<\/title>/);
done();
});
});
});
});
| Fix supertest to not overwrite request | Fix supertest to not overwrite request
| JavaScript | mit | antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell | ---
+++
@@ -5,22 +5,17 @@
process.env.NODE_ENV = 'test';
-describe('Acceptance test', function () {
+describe.only('Acceptance test', function () {
var port = 8006;
var server;
before(function () {
- process.on('stdout', function(data) {
- console.log('**' + data);
- });
- process.on('stderr', function(data) {
- console.log('**' + data);
- });
server = mathServer.MathServer({
port: port,
CONTAINERS: './dummy_containers.js'
});
server.listen();
+ request = request('http://localhost:' + port);
});
after(function (done) {
@@ -40,13 +35,10 @@
});
});
it('should show title', function (done) {
- request = request('http://localhost:' + port);
-
request.get('/').expect(200).end(function(error, result) {
assert.match(result.text, /<title>\s*Macaulay2\s*<\/title>/);
done();
});
-
});
});
}); |
15eb9523a92822b762a6e2c1cdc2a3d1f8426a8e | tests/test-utils.js | tests/test-utils.js | import { underscore } from '@ember/string';
export function serializer(payload) {
const serializedPayload = {};
Object.keys(payload.attrs).map((_key) => {
serializedPayload[underscore(_key)] = payload[_key];
});
return serializedPayload;
}
| import { underscore } from '@ember/string';
function _serialize_object(payload) {
const serializedPayload = {};
Object.keys(payload.attrs).map((_key) => {
serializedPayload[underscore(_key)] = payload[_key];
});
return serializedPayload;
}
export function serializer(data, many = false) {
if (many == true) {
return {
count: data.length,
next: null,
previous: null,
results: data.models.map((d) => {
return _serialize_object(d);
}),
};
} else {
return _serialize_object(data);
}
}
| Refactor serializer to support list | Refactor serializer to support list
| JavaScript | agpl-3.0 | appknox/irene,appknox/irene,appknox/irene | ---
+++
@@ -1,9 +1,24 @@
import { underscore } from '@ember/string';
-export function serializer(payload) {
+function _serialize_object(payload) {
const serializedPayload = {};
Object.keys(payload.attrs).map((_key) => {
serializedPayload[underscore(_key)] = payload[_key];
});
return serializedPayload;
}
+
+export function serializer(data, many = false) {
+ if (many == true) {
+ return {
+ count: data.length,
+ next: null,
+ previous: null,
+ results: data.models.map((d) => {
+ return _serialize_object(d);
+ }),
+ };
+ } else {
+ return _serialize_object(data);
+ }
+} |
61f824798c65b00721bda812228c5357e83bbcd7 | karma.conf.js | karma.conf.js | // Karma configuration
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'test/components/angular/angular.js',
'test/components/angular-mocks/angular-mocks.js',
'src/scripts/*.js',
'src/scripts/**/*.js',
'test/spec/**/*.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: dots || progress || growl
reporters = ['progress'];
// web server port
port = 8080;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_DEBUG;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 5000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
| // Karma configuration
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'test/components/angular/angular.js',
'test/components/angular-mocks/angular-mocks.js',
'src/scripts/*.js',
'src/scripts/**/*.js',
'test/spec/**/*.js'
];
// list of files to exclude
exclude = [];
// test results reporter to use
// possible values: dots || progress || growl
reporters = ['progress'];
// web server port
port = 8080;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 5000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
| Use log level of INFO for karma | test: Use log level of INFO for karma
| JavaScript | mit | Malkiat-Singh/angular-snap.js,kzganesan/angular-snap.js,jtrussell/angular-snap.js,Malkiat-Singh/angular-snap.js,kzganesan/angular-snap.js,jtrussell/angular-snap.js | ---
+++
@@ -34,7 +34,7 @@
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
-logLevel = LOG_DEBUG;
+logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true; |
1060df09e87e63a0a14e5cfa9d206721fa6d14cf | katas/tags.js | katas/tags.js | export const SPECIFICATION = 'spec';
export const MDN = 'mdn';
export const VIDEO = 'video';
export const ARTICLE = 'article';
export const DOCS = 'docs';
export const ANNOUNCEMENT = 'announcement';
export const BOOK = 'book';
export const QUOTE = 'quote';
export const DISCUSSION = 'discussion';
| export const SPECIFICATION = 'spec';
export const MDN = 'mdn';
export const VIDEO = 'video';
export const ARTICLE = 'article';
export const DOCS = 'docs';
export const ANNOUNCEMENT = 'announcement';
export const BOOK = 'book';
export const QUOTE = 'quote';
export const DISCUSSION = 'discussion';
export const WIKIPEDIA = 'wikipedia';
| Add wikipedia as a tag. | Add wikipedia as a tag. | JavaScript | mit | tddbin/katas,tddbin/katas,tddbin/katas | ---
+++
@@ -7,3 +7,4 @@
export const BOOK = 'book';
export const QUOTE = 'quote';
export const DISCUSSION = 'discussion';
+export const WIKIPEDIA = 'wikipedia'; |
9fe0c1a5abd33fdbf4e2c90dd60874ec56b1e58c | src/js/xhr.js | src/js/xhr.js | var Q = require("../vendor/q/q");
exports.post = function (url, data) {
console.log('posting to', url);
var defer = Q.defer();
var xhr = new XMLHttpRequest();
xhr.onerror = function(err) {
console.log('XMLHttpRequest error: ' + err);
defer.reject(err);
};
xhr.onreadystatechange = function () {
console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
defer.resolve(JSON.parse(xhr.responseText));
} else if (this.readyState === 4 && this.status === 401) {
console.log('HTTP 401 returned');
defer.reject({code: 401});
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.setRequestHeader("X-Accept", "application/json");
xhr.send(data || null);
console.log('HTTP req sent to', url, data);
return defer.promise;
};
| var Q = require("../vendor/q/q");
exports.post = function (url, data) {
console.log('posting to', url);
var defer = Q.defer();
var xhr = new XMLHttpRequest();
xhr.onerror = function(err) {
console.log('XMLHttpRequest error: ' + err);
defer.reject(err);
};
xhr.onreadystatechange = function () {
console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
if(xhr.responseType === 'json') {
defer.resolve(xhr.response);
} else {
// backward compatibility with previous versions of Kitt
defer.resolve(JSON.parse(xhr.responseText));
}
} else if (this.readyState === 4 && this.status === 401) {
console.log('HTTP 401 returned');
defer.reject({code: 401});
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.setRequestHeader("X-Accept", "application/json");
xhr.send(data || null);
console.log('HTTP req sent to', url, data);
return defer.promise;
};
| Make XHR compatible with new Kitt implementation | Make XHR compatible with new Kitt implementation | JavaScript | apache-2.0 | kitt-browser/pocket,kitt-browser/pocket | ---
+++
@@ -13,7 +13,12 @@
xhr.onreadystatechange = function () {
console.log('ready state change, state:' + xhr.readyState + ' ' + xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
- defer.resolve(JSON.parse(xhr.responseText));
+ if(xhr.responseType === 'json') {
+ defer.resolve(xhr.response);
+ } else {
+ // backward compatibility with previous versions of Kitt
+ defer.resolve(JSON.parse(xhr.responseText));
+ }
} else if (this.readyState === 4 && this.status === 401) {
console.log('HTTP 401 returned');
defer.reject({code: 401}); |
3f1b7263c9f33ff205ac5ca3fa1466532906b3d1 | client/common/actions/index.js | client/common/actions/index.js | import types from '../constants/ActionTypes'
import utils from '../../shared/utils'
function replaceUserInfo(userInfo) {
return {
type: types.REPLACE_USER_INFO,
userInfo
}
}
function fetchUserInfo() {
return dispatch => {
utils.ajax({url: '/api/user/getUserInfo'}).then(res => {
dispatch(replaceUserInfo(res))
})
}
}
export default {
replaceUserInfo,
fetchUserInfo,
clearUserInfo
}
| import types from '../constants/ActionTypes'
import utils from '../../shared/utils'
function replaceUserInfo(userInfo) {
return {
type: types.REPLACE_USER_INFO,
userInfo
}
}
function clearUserInfo() {
return {type: types.CLEAR_USER_INFO}
}
function fetchUserInfo() {
return dispatch => {
utils.ajax({url: '/api/user/getUserInfo'}).then(res => {
dispatch(replaceUserInfo(res))
})
}
}
export default {
replaceUserInfo,
fetchUserInfo,
clearUserInfo
}
| Add plain object action clearUserInfo | Add plain object action clearUserInfo
| JavaScript | mit | chikara-chan/react-isomorphic-boilerplate,qiuye1027/screenInteraction,qiuye1027/screenInteraction,chikara-chan/react-isomorphic-boilerplate | ---
+++
@@ -6,6 +6,10 @@
type: types.REPLACE_USER_INFO,
userInfo
}
+}
+
+function clearUserInfo() {
+ return {type: types.CLEAR_USER_INFO}
}
function fetchUserInfo() { |
e5ce6180efaea8382a8514501ebb7bae88c3b541 | views/crud-model.js | views/crud-model.js | var app = require('ridge');
module.exports = require('ridge/view').extend({
events: {
'click button': function(e) {
e.preventDefault();
e.stopPropagation();
},
'click button[data-command="publish"]': 'publish',
'click button[data-command="unpublish"]': 'unpublish',
'click button[data-command="delete"]': 'delete'
},
delete: function(e) {
if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) {
this.model.destroy();
this.remove();
}
},
unpublish: function(e) {
this.model.save({ datePublished: null }, { patch: true, wait: true });
},
publish: function(e) {
this.model.save({ datePublished: new Date() }, { patch: true, wait: true });
},
initialize: function(options) {
this.listenTo(this.model, 'sync', this.render);
this.listenTo(this.model, 'destroy', this.remove);
this.listenTo(this.model, 'change:datePublished', function(model, value) {
this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value);
});
}
});
| var app = require('ridge');
module.exports = require('ridge/view').extend({
events: {
'click button,select,input': function(e) {
e.stopPropagation();
},
'click button': function(e) {
e.preventDefault();
},
'click button[data-command="publish"]': 'publish',
'click button[data-command="unpublish"]': 'unpublish',
'click button[data-command="delete"]': 'delete'
},
delete: function(e) {
if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) {
this.model.destroy();
this.remove();
}
},
unpublish: function(e) {
this.model.save({ datePublished: null }, { patch: true, wait: true });
},
publish: function(e) {
this.model.save({ datePublished: new Date() }, { patch: true, wait: true });
},
initialize: function(options) {
this.listenTo(this.model, 'sync', this.render);
this.listenTo(this.model, 'destroy', this.remove);
this.listenTo(this.model, 'change:datePublished', function(model, value) {
this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value);
});
}
});
| Stop propagation for clicks (since a click on model view can toggle more information. | Stop propagation for clicks (since a click on model view can toggle more information.
| JavaScript | mit | thecodebureau/ridge | ---
+++
@@ -2,9 +2,11 @@
module.exports = require('ridge/view').extend({
events: {
+ 'click button,select,input': function(e) {
+ e.stopPropagation();
+ },
'click button': function(e) {
e.preventDefault();
- e.stopPropagation();
},
'click button[data-command="publish"]': 'publish',
'click button[data-command="unpublish"]': 'unpublish', |
e033d945329bb146ee82fc9d51f04665b950aa6b | src/server.js | src/server.js | let Path = require('path');
let Hapi = require('hapi');
var Good = require('good');
let server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
}
}
});
server.connection({ port: 3000 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file('index.html');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply.file('index.html');
}
});
// Serve everythign else from the public folder
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: './'
}
}
});
server.register({
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
events: {
response: '*',
log: '*'
}
}]
}
}, function (err) {
if (err) {
throw err; // something bad happened loading the plugin
}
server.start(function () {
server.log('info', 'Server running at: ' + server.info.uri);
});
});
| let Path = require('path');
let Hapi = require('hapi');
var Good = require('good');
let server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
}
}
});
server.connection({ port: 3000 });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file('index.html');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply.file('index.html');
}
});
server.route({
method: 'GET',
path: '/blog/{name}',
handler: function (request, reply) {
reply.file('index.html');
}
});
// Serve everythign else from the public folder
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: {
path: './'
}
}
});
server.register({
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
events: {
response: '*',
log: '*'
}
}]
}
}, function (err) {
if (err) {
throw err; // something bad happened loading the plugin
}
server.start(function () {
server.log('info', 'Server running at: ' + server.info.uri);
});
});
| Add handler for blog path | Add handler for blog path
| JavaScript | mit | bbondy/brianbondy.node,bbondy/brianbondy.node,bbondy/brianbondy.node | ---
+++
@@ -24,6 +24,14 @@
server.route({
method: 'GET',
path: '/{name}',
+ handler: function (request, reply) {
+ reply.file('index.html');
+ }
+});
+
+server.route({
+ method: 'GET',
+ path: '/blog/{name}',
handler: function (request, reply) {
reply.file('index.html');
} |
fa60bd7e2d0eec674595bff231c05d364f4d4aa1 | lib/helper.js | lib/helper.js | var helper = exports;
var copyDir = helper.copyDir = function (source, target) {
var fs = require('fs');
var dir = fs.readdirSync(source);
dir.forEach(function(item){
var s = fs.statSync(source + '/' + item);
if(s.isDirectory()) {
try {
fs.mkdirSync(target + '/' + item);
} catch (err) { // do nothing
}
copyDir(source + '/' + item, target + '/' + item);
} else {
var file = fs.readFileSync(source + '/' + item, 'utf8');
fs.writeFileSync(target + '/' + item, file);
}
});
};
//
// Ascertain the root folder of the user's application.
//
var appDir = helper.appDir = (function () {
var path = require('path'),
fs = require('fs'),
p;
//
// This is a list of the paths node looks through when resolving modules.
// They should be in order of precedence.
//
process.mainModule.paths.some(function (q) {
//
// Look to see if big is installed in this node_modules folder, or
// alternately if the folder actually belongs to big itself.
//
var bigIsInstalled = fs.existsSync(path.resolve(q, 'big')),
thisIsBig = fs.existsSync(path.resolve(q, '..', 'big.js'));
if (bigIsInstalled || thisIsBig) {
p = q;
// short circuit
return true;
}
});
// p is the node_modules folder, so we should return the folder *above* it.
return path.resolve(p, '..');
})();
| var helper = exports;
var copyDir = helper.copyDir = function (source, target) {
var fs = require('fs');
var dir = fs.readdirSync(source);
dir.forEach(function(item){
var s = fs.statSync(source + '/' + item);
if(s.isDirectory()) {
try {
fs.mkdirSync(target + '/' + item);
} catch (err) { // do nothing
}
copyDir(source + '/' + item, target + '/' + item);
} else {
var file = fs.readFileSync(source + '/' + item, 'utf8');
fs.writeFileSync(target + '/' + item, file);
}
});
};
//
// Determine the root folder of the user's application
//
var appDir = helper.appDir = (function () {
var path = require('path'),
fs = require('fs'),
p = process.cwd();
//
// If we're in the repl, use process.cwd
//
if (!process.mainModule) {
return p;
}
//
// This is a list of the paths node looks through when resolving modules,
// they should be in order of precedence.
//
process.mainModule.paths.some(function (q) {
if (fs.existsSync(path.resolve(q, 'resource'))) {
p = path.resolve(q, '..');
// short circuit
return true;
}
});
return p;
})(); | Remove references to "big" in resource installing code. Resources should now install to the correct application directory. | [fix] Remove references to "big" in resource installing code. Resources should now install to the correct application directory. | JavaScript | mit | bigcompany/resource | ---
+++
@@ -18,33 +18,32 @@
};
//
-// Ascertain the root folder of the user's application.
+// Determine the root folder of the user's application
//
var appDir = helper.appDir = (function () {
- var path = require('path'),
+ var path = require('path'),
fs = require('fs'),
- p;
+ p = process.cwd();
//
- // This is a list of the paths node looks through when resolving modules.
- // They should be in order of precedence.
+ // If we're in the repl, use process.cwd
+ //
+ if (!process.mainModule) {
+ return p;
+ }
+
+ //
+ // This is a list of the paths node looks through when resolving modules,
+ // they should be in order of precedence.
//
process.mainModule.paths.some(function (q) {
- //
- // Look to see if big is installed in this node_modules folder, or
- // alternately if the folder actually belongs to big itself.
- //
- var bigIsInstalled = fs.existsSync(path.resolve(q, 'big')),
- thisIsBig = fs.existsSync(path.resolve(q, '..', 'big.js'));
-
- if (bigIsInstalled || thisIsBig) {
- p = q;
+ if (fs.existsSync(path.resolve(q, 'resource'))) {
+ p = path.resolve(q, '..');
// short circuit
return true;
}
});
- // p is the node_modules folder, so we should return the folder *above* it.
- return path.resolve(p, '..');
-
+ return p;
+
})(); |
3dcafb57bbc59709e5722fbdac07ad9493db4949 | CalcuMan/src/classes/SoundsManager.js | CalcuMan/src/classes/SoundsManager.js | /**
* @flow
*/
import {default as Sound} from 'react-native-sound'
export default class SoundsManager {
constructor (onChangeCallback) {
this.muted = false
this.sounds = {}
this.onChangeCallback = onChangeCallback
this.loadSound('toggle_on')
this.loadSound('toggle_off')
this.loadSound('timeout')
}
loadSound (key) {
this.sounds[key] = new Sound(`${key}.mp3`, Sound.MAIN_BUNDLE)
}
play (key) {
if (!this.muted) {
this.sounds[key].play()
}
}
setMuted (muted) {
this.muted = muted
this.onChangeCallback(muted)
}
}
| /**
* @flow
*/
import {default as Sound} from 'react-native-sound'
export default class SoundsManager {
constructor (onChangeCallback) {
this.muted = false
this.sounds = {}
this.onChangeCallback = onChangeCallback
this.lastPlayed = null
this.loadSound('toggle_on')
this.loadSound('toggle_off')
this.loadSound('timeout')
}
loadSound (key) {
this.sounds[key] = new Sound(`${key}.mp3`, Sound.MAIN_BUNDLE)
}
play (key) {
if (!this.muted) {
if (this.lastPlayed && this.lastPlayed.stop) {
this.lastPlayed.stop()
}
this.lastPlayed = this.sounds[key]
this.sounds[key].play()
}
}
setMuted (muted) {
this.muted = muted
this.onChangeCallback(muted)
}
}
| Stop previous sound before play new one | Stop previous sound before play new one
| JavaScript | mit | antonfisher/game-calcuman,antonfisher/game-calcuman,antonfisher/game-calcuman | ---
+++
@@ -9,6 +9,7 @@
this.muted = false
this.sounds = {}
this.onChangeCallback = onChangeCallback
+ this.lastPlayed = null
this.loadSound('toggle_on')
this.loadSound('toggle_off')
@@ -21,6 +22,10 @@
play (key) {
if (!this.muted) {
+ if (this.lastPlayed && this.lastPlayed.stop) {
+ this.lastPlayed.stop()
+ }
+ this.lastPlayed = this.sounds[key]
this.sounds[key].play()
}
} |
185e50fb0d94bbde6abb94c47e36046746912306 | .gificiency/.gificiency.js | .gificiency/.gificiency.js | var Gificiency = (function() {
'use strict';
var search = function(filter) {
$('a').each(function() {
var elem = $(this);
if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
elem.hide();
} else {
elem.show();
}
});
};
var getHash = function() {
var filter;
if (window.location.hash != '') {
filter = window.location.hash.substring(1);
} else {
filter = false;
}
return filter;
};
var clearImages = function() {
$('img').each(function() {
$(this).remove();
});
};
var popup = function(image) {
return $('<img src="'+ image +'" />');
};
var Gificiency = {
init: function() {
if ( getHash() ) {
search( getHash() );
}
$('.search').on('keyup', function() {
search( $(this).val() );
});
$('li').on('mouseover', function() {
var elem = $(this).find('a'), image = elem.attr('href');
elem.parent().append( popup(image) );
}).on('mouseout', function() {
clearImages();
});
}
};
return Gificiency;
})();
| var Gificiency = (function() {
'use strict';
var searchField = $('.search');
var items = $('li');
var links = $('a');
var search = function(filter) {
links.each(function() {
var elem = $(this);
if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
elem.hide();
} else {
elem.show();
}
});
};
var getHash = function() {
var filter;
if (window.location.hash != '') {
filter = window.location.hash.substring(1);
} else {
filter = false;
}
return filter;
};
var clearImages = function() {
$('img').each(function() {
$(this).remove();
});
};
var popup = function(image) {
return $('<img src="'+ image +'" />');
};
var Gificiency = {
init: function() {
if ( getHash() ) {
search( getHash() );
}
Gificiency.events();
},
events: function() {
searchField.on('keyup', function() {
search( $(this).val() );
});
items.on('mouseover', function() {
var elem = $(this).find('a'), image = elem.attr('href');
elem.parent().append( popup(image) );
}).on('mouseout', function() {
clearImages();
});
}
};
return Gificiency;
})();
| Set private vars, move events to public function | Set private vars, move events to public function
| JavaScript | mit | drewbarontini/gificiency,drewbarontini/gificiency,drewbarontini/gificiency | ---
+++
@@ -1,8 +1,12 @@
var Gificiency = (function() {
'use strict';
+ var searchField = $('.search');
+ var items = $('li');
+ var links = $('a');
+
var search = function(filter) {
- $('a').each(function() {
+ links.each(function() {
var elem = $(this);
if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
elem.hide();
@@ -35,20 +39,28 @@
var Gificiency = {
init: function() {
+
if ( getHash() ) {
search( getHash() );
}
- $('.search').on('keyup', function() {
+ Gificiency.events();
+
+ },
+
+ events: function() {
+
+ searchField.on('keyup', function() {
search( $(this).val() );
});
- $('li').on('mouseover', function() {
+ items.on('mouseover', function() {
var elem = $(this).find('a'), image = elem.attr('href');
elem.parent().append( popup(image) );
}).on('mouseout', function() {
clearImages();
});
+
}
}; |
a29a99b9a2bfedd5528be677ff24c4db2b19115a | backend/app/assets/javascripts/spree/backend/product_picker.js | backend/app/assets/javascripts/spree/backend/product_picker.js | $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(',')
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
| $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(','),
token: Spree.api_key
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
| Add missing api key in product picker. | Add missing api key in product picker.
Fixes #6185
| JavaScript | bsd-3-clause | jasonfb/spree,mindvolt/spree,alvinjean/spree,adaddeo/spree,jspizziri/spree,sfcgeorge/spree,gregoryrikson/spree-sample,beni55/spree,JDutil/spree,rajeevriitm/spree,radarseesradar/spree,jparr/spree,JuandGirald/spree,useiichi/spree,CJMrozek/spree,ayb/spree,priyank-gupta/spree,builtbybuffalo/spree,Engeltj/spree,tancnle/spree,pulkit21/spree,groundctrl/spree,jaspreet21anand/spree,grzlus/spree,madetech/spree,welitonfreitas/spree,shekibobo/spree,pervino/spree,vulk/spree,archSeer/spree,brchristian/spree,alejandromangione/spree,jimblesm/spree,dafontaine/spree,gregoryrikson/spree-sample,sfcgeorge/spree,yiqing95/spree,TrialGuides/spree,rakibulislam/spree,useiichi/spree,APohio/spree,tomash/spree,imella/spree,alvinjean/spree,quentinuys/spree,JuandGirald/spree,alejandromangione/spree,thogg4/spree,Ropeney/spree,calvinl/spree,hifly/spree,piousbox/spree,hoanghiep90/spree,JDutil/spree,berkes/spree,patdec/spree,vinayvinsol/spree,KMikhaylovCTG/spree,orenf/spree,gregoryrikson/spree-sample,jaspreet21anand/spree,Lostmyname/spree,vcavallo/spree,SadTreeFriends/spree,nooysters/spree,jspizziri/spree,raow/spree,Hawaiideveloper/shoppingcart,fahidnasir/spree,edgward/spree,jaspreet21anand/spree,hoanghiep90/spree,abhishekjain16/spree,zaeznet/spree,mleglise/spree,DarkoP/spree,siddharth28/spree,gautamsawhney/spree,priyank-gupta/spree,abhishekjain16/spree,odk211/spree,camelmasa/spree,CiscoCloud/spree,Boomkat/spree,lyzxsc/spree,piousbox/spree,sunny2601/spree,FadliKun/spree,joanblake/spree,builtbybuffalo/spree,patdec/spree,SadTreeFriends/spree,ramkumar-kr/spree,azranel/spree,alejandromangione/spree,omarsar/spree,zamiang/spree,Kagetsuki/spree,Lostmyname/spree,AgilTec/spree,SadTreeFriends/spree,ramkumar-kr/spree,volpejoaquin/spree,shaywood2/spree,azranel/spree,agient/agientstorefront,FadliKun/spree,karlitxo/spree,zamiang/spree,zaeznet/spree,omarsar/spree,Engeltj/spree,zamiang/spree,jeffboulet/spree,camelmasa/spree,abhishekjain16/spree,vinayvinsol/spree,maybii/spree,shekibobo/spree,cutefrank/spree,beni55/spree,tesserakt/clean_spree,caiqinghua/spree,Lostmyname/spree,reidblomquist/spree,abhishekjain16/spree,orenf/spree,kewaunited/spree,jspizziri/spree,tesserakt/clean_spree,DynamoMTL/spree,zaeznet/spree,rajeevriitm/spree,thogg4/spree,DynamoMTL/spree,reidblomquist/spree,DarkoP/spree,NerdsvilleCEO/spree,agient/agientstorefront,jimblesm/spree,piousbox/spree,tancnle/spree,madetech/spree,vulk/spree,KMikhaylovCTG/spree,DynamoMTL/spree,TrialGuides/spree,yiqing95/spree,locomotivapro/spree,TrialGuides/spree,NerdsvilleCEO/spree,AgilTec/spree,priyank-gupta/spree,tomash/spree,gautamsawhney/spree,SadTreeFriends/spree,jparr/spree,archSeer/spree,dafontaine/spree,miyazawatomoka/spree,vulk/spree,odk211/spree,NerdsvilleCEO/spree,moneyspyder/spree,welitonfreitas/spree,edgward/spree,calvinl/spree,vmatekole/spree,CiscoCloud/spree,progsri/spree,FadliKun/spree,fahidnasir/spree,TimurTarasenko/spree,nooysters/spree,robodisco/spree,robodisco/spree,builtbybuffalo/spree,njerrywerry/spree,jasonfb/spree,jeffboulet/spree,tesserakt/clean_spree,CiscoCloud/spree,madetech/spree,archSeer/spree,azranel/spree,ramkumar-kr/spree,lsirivong/spree,quentinuys/spree,jparr/spree,hifly/spree,hifly/spree,volpejoaquin/spree,radarseesradar/spree,beni55/spree,sunny2601/spree,Ropeney/spree,siddharth28/spree,sfcgeorge/spree,KMikhaylovCTG/spree,karlitxo/spree,firman/spree,vinsol/spree,dafontaine/spree,adaddeo/spree,lsirivong/spree,carlesjove/spree,karlitxo/spree,vinsol/spree,adaddeo/spree,njerrywerry/spree,jspizziri/spree,berkes/spree,robodisco/spree,quentinuys/spree,calvinl/spree,edgward/spree,ayb/spree,siddharth28/spree,volpejoaquin/spree,patdec/spree,yiqing95/spree,trigrass2/spree,Ropeney/spree,TimurTarasenko/spree,hifly/spree,AgilTec/spree,wolfieorama/spree,vinsol/spree,lsirivong/spree,CJMrozek/spree,rakibulislam/spree,edgward/spree,Kagetsuki/spree,lyzxsc/spree,pervino/spree,sunny2601/spree,jparr/spree,fahidnasir/spree,Kagetsuki/spree,Lostmyname/spree,alejandromangione/spree,yushine/spree,tancnle/spree,rajeevriitm/spree,sliaquat/spree,madetech/spree,zamiang/spree,joanblake/spree,lyzxsc/spree,useiichi/spree,pulkit21/spree,KMikhaylovCTG/spree,mleglise/spree,ahmetabdi/spree,vinayvinsol/spree,reidblomquist/spree,miyazawatomoka/spree,softr8/spree,mindvolt/spree,DynamoMTL/spree,Ropeney/spree,nooysters/spree,CJMrozek/spree,carlesjove/spree,brchristian/spree,omarsar/spree,azranel/spree,grzlus/spree,FadliKun/spree,locomotivapro/spree,CJMrozek/spree,jasonfb/spree,DarkoP/spree,vulk/spree,pulkit21/spree,hoanghiep90/spree,Boomkat/spree,JuandGirald/spree,vcavallo/spree,tomash/spree,yiqing95/spree,vinsol/spree,wolfieorama/spree,thogg4/spree,piousbox/spree,yushine/spree,caiqinghua/spree,shekibobo/spree,orenf/spree,berkes/spree,ahmetabdi/spree,robodisco/spree,ramkumar-kr/spree,raow/spree,agient/agientstorefront,ayb/spree,TrialGuides/spree,dafontaine/spree,rajeevriitm/spree,vmatekole/spree,kewaunited/spree,Hawaiideveloper/shoppingcart,gregoryrikson/spree-sample,jeffboulet/spree,berkes/spree,NerdsvilleCEO/spree,maybii/spree,caiqinghua/spree,moneyspyder/spree,firman/spree,yushine/spree,raow/spree,cutefrank/spree,softr8/spree,vmatekole/spree,progsri/spree,cutefrank/spree,cutefrank/spree,groundctrl/spree,thogg4/spree,imella/spree,imella/spree,calvinl/spree,groundctrl/spree,omarsar/spree,njerrywerry/spree,sfcgeorge/spree,mindvolt/spree,softr8/spree,shaywood2/spree,gautamsawhney/spree,firman/spree,trigrass2/spree,agient/agientstorefront,zaeznet/spree,tancnle/spree,tomash/spree,mleglise/spree,priyank-gupta/spree,carlesjove/spree,adaddeo/spree,beni55/spree,pervino/spree,APohio/spree,moneyspyder/spree,groundctrl/spree,brchristian/spree,TimurTarasenko/spree,gautamsawhney/spree,sunny2601/spree,APohio/spree,TimurTarasenko/spree,maybii/spree,jimblesm/spree,moneyspyder/spree,kewaunited/spree,Engeltj/spree,pulkit21/spree,builtbybuffalo/spree,mleglise/spree,maybii/spree,tesserakt/clean_spree,patdec/spree,sliaquat/spree,brchristian/spree,kewaunited/spree,jaspreet21anand/spree,welitonfreitas/spree,camelmasa/spree,radarseesradar/spree,raow/spree,alvinjean/spree,mindvolt/spree,CiscoCloud/spree,volpejoaquin/spree,vcavallo/spree,progsri/spree,Boomkat/spree,JDutil/spree,fahidnasir/spree,rakibulislam/spree,jimblesm/spree,progsri/spree,odk211/spree,quentinuys/spree,rakibulislam/spree,odk211/spree,jasonfb/spree,pervino/spree,Engeltj/spree,shaywood2/spree,vinayvinsol/spree,joanblake/spree,grzlus/spree,shaywood2/spree,sliaquat/spree,radarseesradar/spree,siddharth28/spree,softr8/spree,shekibobo/spree,orenf/spree,APohio/spree,DarkoP/spree,miyazawatomoka/spree,miyazawatomoka/spree,trigrass2/spree,ayb/spree,locomotivapro/spree,Hawaiideveloper/shoppingcart,Boomkat/spree,archSeer/spree,lyzxsc/spree,grzlus/spree,useiichi/spree,AgilTec/spree,sliaquat/spree,vcavallo/spree,wolfieorama/spree,welitonfreitas/spree,karlitxo/spree,lsirivong/spree,yushine/spree,JDutil/spree,camelmasa/spree,vmatekole/spree,ahmetabdi/spree,reidblomquist/spree,Kagetsuki/spree,carlesjove/spree,trigrass2/spree,caiqinghua/spree,firman/spree,nooysters/spree,hoanghiep90/spree,njerrywerry/spree,locomotivapro/spree,jeffboulet/spree,joanblake/spree,Hawaiideveloper/shoppingcart,ahmetabdi/spree,wolfieorama/spree,JuandGirald/spree,alvinjean/spree | ---
+++
@@ -10,7 +10,8 @@
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
- ids: element.val().split(',')
+ ids: element.val().split(','),
+ token: Spree.api_key
}, function (data) {
callback(multiple ? data.products : data.products[0]);
}); |
90dd6b7b21c519c7c8fffd9833992e9de4cf8d95 | web/editor.js | web/editor.js | import { getQueryStringParam, substanceGlobals, platform } from 'substance'
import { TextureWebApp } from 'substance-texture'
window.addEventListener('load', () => {
substanceGlobals.DEBUG_RENDERING = platform.devtools
let app = TextureWebApp.mount({
archiveId: getQueryStringParam('archive') || 'kitchen-sink',
storageType: getQueryStringParam('storage') || 'vfs',
storageUrl: getQueryStringParam('storageUrl') || '/archives'
}, window.document.body)
// put the archive and some more things into global scope, for debugging
setTimeout(() => {
window.app = app
}, 500)
})
| import {
getQueryStringParam, substanceGlobals, platform, VfsStorageClient, HttpStorageClient, InMemoryDarBuffer
} from 'substance'
import { TextureWebApp, TextureArchive } from 'substance-texture'
window.addEventListener('load', () => {
substanceGlobals.DEBUG_RENDERING = platform.devtools
let app = DevTextureWebApp.mount({
archiveId: getQueryStringParam('archive') || 'kitchen-sink',
storageType: getQueryStringParam('storage') || 'vfs',
storageUrl: getQueryStringParam('storageUrl') || '/archives'
}, window.document.body)
// put the archive and some more things into global scope, for debugging
setTimeout(() => {
window.app = app
}, 500)
})
// This uses a monkey-patched VfsStorageClient that checks immediately
// if the stored data could be loaded again, or if there is a bug in
// Textures exporter
class DevTextureWebApp extends TextureWebApp {
_loadArchive(archiveId, context) {
let storage
if (this.props.storageType==='vfs') {
storage = new VfsStorageClient(window.vfs, './data/')
// monkey patch VfsStorageClient so that we can check if the stored data
// can be loaded
storage.write = (archiveId, rawArchive) => {
console.log(rawArchive)
return storage.read(archiveId)
.then((originalRawArchive) => {
Object.assign(rawArchive.resources, originalRawArchive.resources)
let testArchive = new TextureArchive()
try {
debugger
testArchive._ingest(rawArchive)
} catch (error) {
window.alert('Exported TextureArchive is corrupt') //eslint-disable-line no-alert
console.error(error)
}
})
.then(() => {
return false
})
}
} else {
storage = new HttpStorageClient(this.props.storageUrl)
}
let buffer = new InMemoryDarBuffer()
let archive = new TextureArchive(storage, buffer, context)
return archive.load(archiveId)
}
} | Add a hook to the web version that checks on save if the archive can be loaded again. | Add a hook to the web version that checks on save if the archive can be loaded again.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -1,9 +1,11 @@
-import { getQueryStringParam, substanceGlobals, platform } from 'substance'
-import { TextureWebApp } from 'substance-texture'
+import {
+ getQueryStringParam, substanceGlobals, platform, VfsStorageClient, HttpStorageClient, InMemoryDarBuffer
+} from 'substance'
+import { TextureWebApp, TextureArchive } from 'substance-texture'
window.addEventListener('load', () => {
substanceGlobals.DEBUG_RENDERING = platform.devtools
- let app = TextureWebApp.mount({
+ let app = DevTextureWebApp.mount({
archiveId: getQueryStringParam('archive') || 'kitchen-sink',
storageType: getQueryStringParam('storage') || 'vfs',
storageUrl: getQueryStringParam('storageUrl') || '/archives'
@@ -14,3 +16,40 @@
window.app = app
}, 500)
})
+
+// This uses a monkey-patched VfsStorageClient that checks immediately
+// if the stored data could be loaded again, or if there is a bug in
+// Textures exporter
+class DevTextureWebApp extends TextureWebApp {
+ _loadArchive(archiveId, context) {
+ let storage
+ if (this.props.storageType==='vfs') {
+ storage = new VfsStorageClient(window.vfs, './data/')
+ // monkey patch VfsStorageClient so that we can check if the stored data
+ // can be loaded
+ storage.write = (archiveId, rawArchive) => {
+ console.log(rawArchive)
+ return storage.read(archiveId)
+ .then((originalRawArchive) => {
+ Object.assign(rawArchive.resources, originalRawArchive.resources)
+ let testArchive = new TextureArchive()
+ try {
+ debugger
+ testArchive._ingest(rawArchive)
+ } catch (error) {
+ window.alert('Exported TextureArchive is corrupt') //eslint-disable-line no-alert
+ console.error(error)
+ }
+ })
+ .then(() => {
+ return false
+ })
+ }
+ } else {
+ storage = new HttpStorageClient(this.props.storageUrl)
+ }
+ let buffer = new InMemoryDarBuffer()
+ let archive = new TextureArchive(storage, buffer, context)
+ return archive.load(archiveId)
+ }
+} |
cc5aa2d5902750420cb9dfde1acec0893e22df40 | test/spec/react-loader-test.js | test/spec/react-loader-test.js | /** @jsx React.DOM */
var React = require('react');
var Loader = require('../../lib/react-loader');
var expect = require('chai').expect;
var loader;
describe('Loader', function () {
describe('before loaded', function () {
beforeEach(function () {
loader = <Loader loaded={false}>Welcome</Loader>;
React.renderComponent(loader, document.body);
});
it('renders the loader', function () {
expect(document.body.innerHTML).to.match(/<div class="loader"/);
});
it('does not render the content', function () {
expect(document.body.innerHTML).to.not.match(/Welcome/);
});
});
describe('after loaded', function () {
beforeEach(function () {
loader = <Loader loaded={true}>Welcome</Loader>;
React.renderComponent(loader, document.body);
});
it('does not render the loader', function () {
expect(document.body.innerHTML).to.not.match(/<div class="loader"/);
});
it('renders the content', function () {
expect(document.body.innerHTML).to.match(/Welcome/);
});
});
});
| /** @jsx React.DOM */
var React = require('react');
var Loader = require('../../lib/react-loader');
var expect = require('chai').expect;
describe('Loader', function () {
var testCases = [{
description: 'loading is in progress',
options: { loaded: false },
expectedOutput: /<div class="loader".*<div class="spinner"/
},
{
description: 'loading is in progress with spinner options',
options: { loaded: false, radius: 17, width: 900 },
expectedOutput: /<div class="loader"[^>]*?><div class="spinner"[^>]*?>.*translate\(17px, 0px\).*style="[^"]*?height: 900px;/
},
{
describe: 'loading is complete',
options: { loaded: true },
expectedOutput: /<div[^>]*>Welcome<\/div>/
}];
testCases.forEach(function (testCase) {
describe(testCase.description, function () {
beforeEach(function () {
var loader = new Loader(testCase.options, 'Welcome');
React.renderComponent(loader, document.body);
});
it('renders the correct output', function () {
expect(document.body.innerHTML).to.match(testCase.expectedOutput);
})
});
});
});
| Update test suite to ensure spinner and spinner options are rendered as expected | Update test suite to ensure spinner and spinner options are rendered as expected
| JavaScript | mit | CarLingo/react-loader,gokulkrishh/react-loader,alengel/react-loader,aparticka/react-loader,CarLingo/react-loader,quickleft/react-loader,CognizantStudio/react-loader,CognizantStudio/react-loader,aparticka/react-loader,quickleft/react-loader,gokulkrishh/react-loader,dallonf/react-loader,insekkei/react-loader,dallonf/react-loader,alengel/react-loader,insekkei/react-loader | ---
+++
@@ -4,36 +4,33 @@
var Loader = require('../../lib/react-loader');
var expect = require('chai').expect;
-var loader;
+describe('Loader', function () {
+ var testCases = [{
+ description: 'loading is in progress',
+ options: { loaded: false },
+ expectedOutput: /<div class="loader".*<div class="spinner"/
+ },
+ {
+ description: 'loading is in progress with spinner options',
+ options: { loaded: false, radius: 17, width: 900 },
+ expectedOutput: /<div class="loader"[^>]*?><div class="spinner"[^>]*?>.*translate\(17px, 0px\).*style="[^"]*?height: 900px;/
+ },
+ {
+ describe: 'loading is complete',
+ options: { loaded: true },
+ expectedOutput: /<div[^>]*>Welcome<\/div>/
+ }];
-describe('Loader', function () {
- describe('before loaded', function () {
- beforeEach(function () {
- loader = <Loader loaded={false}>Welcome</Loader>;
- React.renderComponent(loader, document.body);
- });
+ testCases.forEach(function (testCase) {
+ describe(testCase.description, function () {
+ beforeEach(function () {
+ var loader = new Loader(testCase.options, 'Welcome');
+ React.renderComponent(loader, document.body);
+ });
- it('renders the loader', function () {
- expect(document.body.innerHTML).to.match(/<div class="loader"/);
- });
-
- it('does not render the content', function () {
- expect(document.body.innerHTML).to.not.match(/Welcome/);
- });
- });
-
- describe('after loaded', function () {
- beforeEach(function () {
- loader = <Loader loaded={true}>Welcome</Loader>;
- React.renderComponent(loader, document.body);
- });
-
- it('does not render the loader', function () {
- expect(document.body.innerHTML).to.not.match(/<div class="loader"/);
- });
-
- it('renders the content', function () {
- expect(document.body.innerHTML).to.match(/Welcome/);
+ it('renders the correct output', function () {
+ expect(document.body.innerHTML).to.match(testCase.expectedOutput);
+ })
});
});
}); |
64038fb9752955742180bc734fb8686dede22662 | app/index.js | app/index.js | import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import users from 'redux/modules/users'
import thunk from 'redux-thunk'
import { checkIfAuthed } from 'helpers/auth'
const store = createStore(users, applyMiddleware(thunk))
function checkAuth (nextState, replace) {
const isAuthed = checkIfAuthed(store)
const nextPathName = nextState.location.pathname
if (nextPathName === '/' || nextPathName === '/auth') {
if (isAuthed === true) {
replace('/feed')
}
} else {
if (isAuthed !== true) {
replace('/auth')
}
}
}
ReactDOM.render(
<Provider store={store}>
{getRoutes(checkAuth)}
</Provider>,
document.getElementById('app')
)
| import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import users from 'redux/modules/users'
import thunk from 'redux-thunk'
import { checkIfAuthed } from 'helpers/auth'
const store = createStore(users, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : (f) => f
))
function checkAuth (nextState, replace) {
const isAuthed = checkIfAuthed(store)
const nextPathName = nextState.location.pathname
if (nextPathName === '/' || nextPathName === '/auth') {
if (isAuthed === true) {
replace('/feed')
}
} else {
if (isAuthed !== true) {
replace('/auth')
}
}
}
ReactDOM.render(
<Provider store={store}>
{getRoutes(checkAuth)}
</Provider>,
document.getElementById('app')
)
| Include redux devtools through compose | Include redux devtools through compose
| JavaScript | mit | StuartPearlman/duckr,StuartPearlman/duckr | ---
+++
@@ -1,13 +1,16 @@
import React from 'react'
import ReactDOM from 'react-dom'
import getRoutes from './config/routes'
-import { createStore, applyMiddleware } from 'redux'
+import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import users from 'redux/modules/users'
import thunk from 'redux-thunk'
import { checkIfAuthed } from 'helpers/auth'
-const store = createStore(users, applyMiddleware(thunk))
+const store = createStore(users, compose(
+ applyMiddleware(thunk),
+ window.devToolsExtension ? window.devToolsExtension() : (f) => f
+))
function checkAuth (nextState, replace) {
const isAuthed = checkIfAuthed(store) |
bf669b035df93e5e27b5683ad59c3b68e0ac5fdb | client/partials/mybilltable.js | client/partials/mybilltable.js | Template.mybilltable.created = function(){
Session.set('message', '');
};
Template.mybilltable.helpers({
onReady: function(){
//Meteor.subscribe("mybills");
},
bill: function(){
return bills.find({ registeredby: Meteor.userId() });
},
nobills: function(){
var thebills = bills.find({ registeredby: Meteor.userId() }).fetch();
if (thebills.length === 0){
Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="{{ pathFor "newbill" }}">Register your first bill!</a></div>');
return Session.get('message');
}
}
});
| Template.mybilltable.created = function(){
Session.set('message', '');
};
Template.mybilltable.helpers({
onReady: function(){
//Meteor.subscribe("mybills");
},
bill: function(){
return bills.find({ registeredby: Meteor.userId() });
},
nobills: function(){
var thebills = bills.find({ registeredby: Meteor.userId() }).fetch();
if (thebills.length === 0){
Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="/new-bill">Register your first bill!</a></div>');
return Session.get('message');
}
}
});
| Fix link in Profile error message. | Fix link in Profile error message.
| JavaScript | mit | celsom3/undocumoney,celsom3/undocumoney | ---
+++
@@ -14,7 +14,7 @@
nobills: function(){
var thebills = bills.find({ registeredby: Meteor.userId() }).fetch();
if (thebills.length === 0){
- Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="{{ pathFor "newbill" }}">Register your first bill!</a></div>');
+ Session.set('message','<div class="no-data alert alert-danger">You haven\'t registered any bills! <a href="/new-bill">Register your first bill!</a></div>');
return Session.get('message');
}
|
09e3525e15e891760bcb737c9948d774aa12f061 | frontend/src/sub-components/translate.js | frontend/src/sub-components/translate.js | import privateInfo from "../../../../../credentials/token.json";
/**
* Fetches translated text using the Google Translate API
*/
export function getTranslation(term, fromLang, toLang) {
const response = fetch("/translation", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
rawText: `${term}`,
toLang: `${toLang}`,
fromLang: `${fromLang}`,
}),
})
.then((res) => res.json())
.then((result) => {
console.log(result);
return result.translation;
})
.catch((error) => {
return "Could not Translate";
});
}
| import privateInfo from "../../../../../credentials/token.json";
/**
* Fetches translated text using the Google Translate API
*/
export function getTranslation(term, fromLang, toLang) {
const response = fetch("/translation", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
rawText: `${term}`,
toLang: `${toLang}`,
fromLang: `${fromLang}`,
}),
})
.then((res) => res.json())
.then((result) => {
return result.translation;
})
.catch((error) => {
return "Could not Translate";
});
}
| Remove console.log from all files | Remove console.log from all files
| JavaScript | apache-2.0 | google/step197-2020,google/step197-2020,google/step197-2020,google/step197-2020 | ---
+++
@@ -18,7 +18,6 @@
})
.then((res) => res.json())
.then((result) => {
- console.log(result);
return result.translation;
})
.catch((error) => { |
89180adaf71fda52a3879cace74c66a7fb8677fd | __tests__/e2e/01_StarRating.test.js | __tests__/e2e/01_StarRating.test.js | import test from 'tape-async'
import helper from 'tipsi-appium-helper'
const { driver, select, idFromXPath } = helper
test('<StarRating />', async (t) => {
const starsAndTextId = select({
ios: idFromXPath(`//
XCUIElementTypeScrollView/*/*/XCUIElementTypeOther[2]/
XCUIElementTypeOther/XCUIElementTypeStaticText
`),
android: idFromXPath(`//
android.widget.ScrollView[1]/android.view.ViewGroup[1]/*/
android.widget.TextView
`),
})
try {
await helper.openExampleFor('<StarRating />')
const elements = await driver
.waitForVisible(starsAndTextId, 5000)
.elements(starsAndTextId)
t.same(
elements.value.length,
27,
'Should render five <StarRating /> components'
)
} catch (error) {
await helper.screenshot()
await helper.source()
throw error
}
})
| import test from 'tape-async'
import helper from 'tipsi-appium-helper'
const { driver, select, idFromXPath } = helper
test('<StarRating />', async (t) => {
const starsAndTextId = select({
ios: idFromXPath(`//
XCUIElementTypeScrollView/*/*/XCUIElementTypeOther[2]/
XCUIElementTypeOther/XCUIElementTypeStaticText
`),
android: idFromXPath(`//
android.widget.ScrollView[1]/android.view.ViewGroup[1]/*/
android.widget.TextView
`),
})
try {
await helper.openExampleFor('<StarRating />')
const elements = await driver
.waitForVisible(starsAndTextId, 20000)
.elements(starsAndTextId)
t.same(
elements.value.length,
27,
'Should render five <StarRating /> components'
)
} catch (error) {
await helper.screenshot()
await helper.source()
throw error
}
})
| Update timer for star rating | Update timer for star rating
| JavaScript | mit | tipsi/tipsi-ui-kit,tipsi/tipsi-ui-kit,tipsi/tipsi-ui-kit,tipsi/tipsi-ui-kit | ---
+++
@@ -18,7 +18,7 @@
try {
await helper.openExampleFor('<StarRating />')
const elements = await driver
- .waitForVisible(starsAndTextId, 5000)
+ .waitForVisible(starsAndTextId, 20000)
.elements(starsAndTextId)
t.same( |
959ab8d9aa78c7fc931a25d94c3721585368d6f5 | addon/-private/ember-environment.js | addon/-private/ember-environment.js | import Ember from 'ember';
import { defer } from 'rsvp';
import { Environment } from './external/environment';
import { assert } from '@ember/debug';
import { join, next, once } from '@ember/runloop';
export class EmberEnvironment extends Environment {
assert(...args) {
assert(...args);
}
async(callback) {
join(() => once(null, callback));
}
reportUncaughtRejection(error) {
next(null, function () {
if (Ember.onerror) {
Ember.onerror(error);
} else {
throw error;
}
});
}
defer() {
return defer();
}
globalDebuggingEnabled() {
return Ember.ENV.DEBUG_TASKS;
}
}
export const EMBER_ENVIRONMENT = new EmberEnvironment();
| import Ember from 'ember';
import { defer } from 'rsvp';
import { Environment } from './external/environment';
import { assert } from '@ember/debug';
import { join, next, schedule } from '@ember/runloop';
export class EmberEnvironment extends Environment {
assert(...args) {
assert(...args);
}
async(callback) {
join(() => schedule('actions', callback));
}
reportUncaughtRejection(error) {
next(null, function () {
if (Ember.onerror) {
Ember.onerror(error);
} else {
throw error;
}
});
}
defer() {
return defer();
}
globalDebuggingEnabled() {
return Ember.ENV.DEBUG_TASKS;
}
}
export const EMBER_ENVIRONMENT = new EmberEnvironment();
| Fix inefficient use of run.once by EmberEnvironment.async | Fix inefficient use of run.once by EmberEnvironment.async
| JavaScript | mit | machty/ember-concurrency,machty/ember-concurrency,machty/ember-concurrency,machty/ember-concurrency | ---
+++
@@ -2,7 +2,7 @@
import { defer } from 'rsvp';
import { Environment } from './external/environment';
import { assert } from '@ember/debug';
-import { join, next, once } from '@ember/runloop';
+import { join, next, schedule } from '@ember/runloop';
export class EmberEnvironment extends Environment {
assert(...args) {
@@ -10,7 +10,7 @@
}
async(callback) {
- join(() => once(null, callback));
+ join(() => schedule('actions', callback));
}
reportUncaughtRejection(error) { |
30f098e5baab15c95a111050d02ec4e9a16ffcbe | test/postgres-sql-loader.js | test/postgres-sql-loader.js | // Test that loading SQL files for PostgreSQL works.
'use strict';
var Code = require('code');
var Lab = require('lab');
var Querious = require('../index');
var path = require('path');
var lab = module.exports.lab = Lab.script();
lab.experiment('PostgreSQL sql file loading', function () {
lab.test('it works with a basic query', function (done) {
var instance = new Querious({
cache_sql: false,
dialect: 'postgresql',
sql_folder: path.resolve(__dirname, 'sql/postgresql')
});
instance.loadSql('basic-query', function (err, sql) {
Code.expect(err).to.not.exist();
Code.expect(sql).to.equal("SELECT 2+2;\n");
done();
});
});
lab.test('it works with a basic query in a .pgsql file', function (done) {
var instance = new Querious({
dialect: 'postgresql',
sql_folder: path.resolve(__dirname, 'sql/postgresql')
});
instance.loadSql('pi-approximation', function (err, sql) {
Code.expect(err).to.not.exist();
Code.expect(sql).to.equal("SELECT 22/7;\n");
done();
});
});
});
| // Test that loading SQL files for PostgreSQL works.
'use strict';
var Code = require('code');
var Lab = require('lab');
var Querious = require('../index');
var path = require('path');
var lab = module.exports.lab = Lab.script();
lab.experiment('PostgreSQL sql file loading', function () {
lab.test('it works with a basic query', function (done) {
var instance = new Querious({
cache_sql: false,
dialect: 'postgresql',
sql_folder: path.resolve(__dirname, 'sql/postgresql')
});
instance.loadSql('basic-query', function (err, sql) {
Code.expect(err).to.not.exist();
Code.expect(sql).to.equal("SELECT 2+2;\n");
done();
});
});
lab.test('it works with a basic query in a .pgsql file', function (done) {
var instance = new Querious({
dialect: 'postgresql',
sql_folder: path.resolve(__dirname, 'sql/postgresql')
});
instance.loadSql('pi-approximation', function (err, sql) {
Code.expect(err).to.not.exist();
Code.expect(sql).to.equal("SELECT 22/7;\n");
done();
});
});
lab.test('it fails when loading a non-existing file', function (done) {
var instance = new Querious({
dialect: 'postgresql',
sql_folder: path.resolve(__dirname, 'sql/postgresql')
});
instance.loadSql('does-not-exist', function (err, sql) {
Code.expect(err.slice(0, 42)).to.equal("Querious: No file matching `does-not-exist");
Code.expect(sql).to.not.exist();
done();
});
});
});
| Test for ambigous file loading. | Test for ambigous file loading.
| JavaScript | isc | mikl/querious | ---
+++
@@ -38,4 +38,18 @@
done();
});
});
+
+ lab.test('it fails when loading a non-existing file', function (done) {
+ var instance = new Querious({
+ dialect: 'postgresql',
+ sql_folder: path.resolve(__dirname, 'sql/postgresql')
+ });
+
+ instance.loadSql('does-not-exist', function (err, sql) {
+ Code.expect(err.slice(0, 42)).to.equal("Querious: No file matching `does-not-exist");
+ Code.expect(sql).to.not.exist();
+
+ done();
+ });
+ });
}); |
42a38b012ae01477845ef926d4620b12f0a418f6 | prime/index.test.js | prime/index.test.js | /* eslint-env node, jest */
const shogi = require('./index.js');
const Slack = require('../lib/slackMock.js');
jest.mock('../achievements/index.ts');
let slack = null;
beforeEach(() => {
slack = new Slack();
process.env.CHANNEL_SANDBOX = slack.fakeChannel;
shogi(slack);
});
describe('shogi', () => {
it('responds to "素数大富豪"', async () => {
const {username, text} = await slack.getResponseTo('素数大富豪');
expect(username).toBe('primebot');
expect(text).toContain('手札');
});
});
| /* eslint-env node, jest */
jest.mock('../achievements/index.ts');
const shogi = require('./index.js');
const Slack = require('../lib/slackMock.js');
let slack = null;
beforeEach(() => {
slack = new Slack();
process.env.CHANNEL_SANDBOX = slack.fakeChannel;
shogi(slack);
});
describe('shogi', () => {
it('responds to "素数大富豪"', async () => {
const {username, text} = await slack.getResponseTo('素数大富豪');
expect(username).toBe('primebot');
expect(text).toContain('手札');
});
});
| Fix order of invokation of achievement mocking | Fix order of invokation of achievement mocking
| JavaScript | mit | tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot,tsg-ut/slackbot | ---
+++
@@ -1,9 +1,9 @@
/* eslint-env node, jest */
+
+jest.mock('../achievements/index.ts');
const shogi = require('./index.js');
const Slack = require('../lib/slackMock.js');
-
-jest.mock('../achievements/index.ts');
let slack = null;
|
5b9aca9656e2456b7060d5cdbb62226d7b8d1ea0 | lib/generators/jasmine/examples/templates/spec/javascripts/helpers/SpecHelper.js | lib/generators/jasmine/examples/templates/spec/javascripts/helpers/SpecHelper.js | beforeEach(function() {
this.addMatchers({
toBePlaying: function(expectedSong) {
var player = this.actual;
return player.currentlyPlayingSong === expectedSong
&& player.isPlaying;
}
})
});
| beforeEach(function() {
addMatchers({
toBePlaying: function(expectedSong) {
var player = this.actual;
return player.currentlyPlayingSong === expectedSong
&& player.isPlaying;
}
})
});
| Update spechelper in the rails 2 generator to reflect that addMatchers is exposed on the global namespace | Update spechelper in the rails 2 generator to reflect that addMatchers is exposed on the global namespace
| JavaScript | mit | mavenlink/jasmine-gem,tjgrathwell/jasmine-gem,mavenlink/jasmine-gem,kapost/jasmine-gem,brigade/jasmine-gem,amandamholl/jasmine-gem,amandamholl/jasmine-gem,brigade/jasmine-gem,mavenlink/jasmine-gem,kapost/jasmine-gem,amandamholl/jasmine-gem,brigade/jasmine-gem,tjgrathwell/jasmine-gem | ---
+++
@@ -1,5 +1,5 @@
beforeEach(function() {
- this.addMatchers({
+ addMatchers({
toBePlaying: function(expectedSong) {
var player = this.actual;
return player.currentlyPlayingSong === expectedSong |
c690ddf5bbcbc0fd9bedfe547d924f1621dcd76c | app/assets/javascripts/letter_opener_web/application.js | app/assets/javascripts/letter_opener_web/application.js | //= require jquery-1.8.3.min
//= require_tree .
jQuery(function($) {
$('.letter-opener').on('click', 'tr', function() {
var $this = $(this);
$('iframe').attr('src', $this.find('a').attr('href'));
$this.parent().find('.active').removeClass('active');
$this.addClass('active');
});
$('.refresh').click(function(e) {
e.preventDefault();
var table = $('.letter-opener');
table.find('tbody').empty().append('<tr><td colspan="2">Loading...</td></tr>');
table.load(table.data('letters-path') + ' .letter-opener');
});
});
| //= require jquery-1.8.3.min
//= require_tree .
jQuery(function($) {
$('.letter-opener').on('click', 'tr', function() {
var $this = $(this);
$('iframe').attr('src', $this.find('a').attr('href'));
$this.parent().find('.active').removeClass('active');
$this.addClass('active');
});
$('.refresh').click(function(e) {
e.preventDefault();
var table = $('.letter-opener');
table.find('tbody').empty().append('<tr><td colspan="2">Loading...</td></tr>');
table.load(table.data('letters-path') + ' .letter-opener', function() {
$('iframe').attr('src', $('.letter-opener tbody a:first-child()').attr('href'));
});
});
});
| Refresh letters content on <iframe> when reloading letters list | Refresh letters content on <iframe> when reloading letters list
| JavaScript | mit | ProctorU/letter_opener_web,sergey-verevkin/letter_opener_web,fgrehm/letter_opener_web,sergey-verevkin/letter_opener_web,fgrehm/letter_opener_web,fgrehm/letter_opener_web,ProctorU/letter_opener_web,fgrehm/letter_opener_web,sergey-verevkin/letter_opener_web,ProctorU/letter_opener_web,ProctorU/letter_opener_web | ---
+++
@@ -14,6 +14,8 @@
var table = $('.letter-opener');
table.find('tbody').empty().append('<tr><td colspan="2">Loading...</td></tr>');
- table.load(table.data('letters-path') + ' .letter-opener');
+ table.load(table.data('letters-path') + ' .letter-opener', function() {
+ $('iframe').attr('src', $('.letter-opener tbody a:first-child()').attr('href'));
+ });
});
}); |
5443aa9f1a393557af8dc833d10a051b631c7e79 | dilute.js | dilute.js | module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
}
const next = iterator.next()
if (next.done) {
return { done: true }
}
const gathered = []
ITEMS: for (const item of next.value) {
switch (filter(item)) {
case -1:
break
case 0:
gathered.push(item)
break
case 1:
done = true
break ITEMS
}
}
return { done: false, value: gathered }
}
}
}
| module.exports = function (paginator, filter) {
const iterator = paginator[Symbol.asyncIterator]()
let done = false
return {
[Symbol.asyncIterator]: function () {
return this
},
next: async function () {
if (done) {
return { done: true }
}
const next = await iterator.next()
if (next.done) {
return { done: true }
}
const gathered = []
ITEMS: for (const item of next.value) {
switch (filter(item)) {
case -1:
break
case 0:
gathered.push(item)
break
case 1:
done = true
break ITEMS
}
}
return { done: false, value: gathered }
}
}
}
| Add missing `await` to outer iterator `next` call. | Add missing `await` to outer iterator `next` call.
Closes #73.
| JavaScript | mit | bigeasy/dilute,bigeasy/dilute | ---
+++
@@ -11,7 +11,7 @@
if (done) {
return { done: true }
}
- const next = iterator.next()
+ const next = await iterator.next()
if (next.done) {
return { done: true }
} |
920d357a257d13cec80f227d1637a437070d7557 | app/scripts/components/experts/requests/create/expert-contract-form.js | app/scripts/components/experts/requests/create/expert-contract-form.js | import template from './expert-contract-form.html';
const expertContract = {
template,
bindings: {
model: '=',
form: '<',
contractTemplate: '<',
expert: '<',
errors: '<',
},
controller: class ExpertContractController {
$onInit() {
this.loading = true;
let sortedOptions = {};
angular.forEach(this.expert.order, name => {
sortedOptions[name] = this.expert.options[name];
});
this.expert.options = sortedOptions;
this.tabs = [this.createTab(gettext('Details'), this.expert.options)];
angular.forEach(this.contractTemplate.order, tabName => {
let tab = this.contractTemplate.options[tabName];
this.tabs.push(this.createTab(tab.label, tab.options));
angular.forEach(tab.options, (option, name) => {
option.name = name;
if (option.default) {
this.model[name] = option.default;
}
});
});
this.loading = false;
}
createTab(name, options) {
return {
label: name,
options: options,
required: Object.keys(options).some(name => options[name].required),
};
}
}
};
export default expertContract;
| import template from './expert-contract-form.html';
const expertContract = {
template,
bindings: {
model: '=',
form: '<',
contractTemplate: '<',
expert: '<',
errors: '<',
},
controller: class ExpertContractController {
$onInit() {
this.loading = true;
let sortedOptions = {};
angular.forEach(this.expert.order, name => {
sortedOptions[name] = this.expert.options[name];
});
this.expert.options = sortedOptions;
this.tabs = [this.createTab(gettext('Details'), this.expert.options)];
angular.forEach(this.contractTemplate.order, tabName => {
let tab = this.contractTemplate.options[tabName];
this.tabs.push(this.createTab(tab.label, tab.options));
angular.forEach(tab.options, (option, name) => {
option.name = name;
if (this.expert.options_overrides[name] && this.expert.options_overrides[name].default_value !== undefined) {
this.model[name] = this.expert.options_overrides[name].default_value;
}
else if (option.default) {
this.model[name] = option.default;
}
});
});
this.loading = false;
}
createTab(name, options) {
return {
label: name,
options: options,
required: Object.keys(options).some(name => options[name].required),
};
}
}
};
export default expertContract;
| Allow to override specific contract template values | Allow to override specific contract template values
- CS-208
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -27,7 +27,10 @@
angular.forEach(tab.options, (option, name) => {
option.name = name;
- if (option.default) {
+ if (this.expert.options_overrides[name] && this.expert.options_overrides[name].default_value !== undefined) {
+ this.model[name] = this.expert.options_overrides[name].default_value;
+ }
+ else if (option.default) {
this.model[name] = option.default;
}
}); |
a52733b4a7396ac1f8da75abd3ce0a49e4f89f8a | NodeJS/HttpJsonApi/httpjsonapi.js | NodeJS/HttpJsonApi/httpjsonapi.js | var http = require('http');
var url = require('url');
// return a JSON object with the hour minute and second
function parseTime(time){
return {
hour: time.getHours,
minute: time.getMinutes(),
second: time.getSeconds(),
}
}
// returns a JSON response with time in unix
function unixTime(time){
return {unixtime: time.getTime()};
}
var server = http.createServer((request, response) => {
var parseUrl = url.parse(request.url, true);
var time = new Date(parseUrl.query.iso);
var result;
if (/^\/api\/parsetime/.test(request.url))
result = parseTime(time);
else if (/^\/api\/unixtime/.test(request.url))
result = unixTime(time);
if (result) {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify(result));
} else {
response.writeHead(404);
response.end();
}
});
server.listen(+process.argv(2)); | Add HTTP json api logic | Add HTTP json api logic
| JavaScript | mit | BrianLusina/JS-Snippets | ---
+++
@@ -0,0 +1,38 @@
+var http = require('http');
+var url = require('url');
+
+// return a JSON object with the hour minute and second
+function parseTime(time){
+ return {
+ hour: time.getHours,
+ minute: time.getMinutes(),
+ second: time.getSeconds(),
+ }
+}
+
+// returns a JSON response with time in unix
+function unixTime(time){
+ return {unixtime: time.getTime()};
+}
+
+var server = http.createServer((request, response) => {
+ var parseUrl = url.parse(request.url, true);
+ var time = new Date(parseUrl.query.iso);
+ var result;
+
+ if (/^\/api\/parsetime/.test(request.url))
+ result = parseTime(time);
+ else if (/^\/api\/unixtime/.test(request.url))
+ result = unixTime(time);
+
+ if (result) {
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(JSON.stringify(result));
+ } else {
+ response.writeHead(404);
+ response.end();
+ }
+});
+
+
+server.listen(+process.argv(2)); | |
62c0a2cde5383d927fa8d45a26b04f5237030818 | push-clients/service-worker.js | push-clients/service-worker.js | self.addEventListener('push', function(event) {
event.waitUntil(clients.matchAll().then(function(clientList) {
var focused = false;
for (var i = 0; i < clientList.length; i++) {
if (clientList[i].focused) {
focused = true;
break;
}
}
return self.registration.showNotification('ServiceWorker Cookbook', {
body: focused ? 'You\'re still here, thanks!' : 'Click me, please!',
});
}));
});
self.addEventListener('notificationclick', function(event) {
event.waitUntil(clients.matchAll().then(function(clientList) {
if (clientList.length > 0) {
return clientList[0].focus();
} else {
return clients.openWindow('./push-clients/index.html');
}
}));
});
| self.addEventListener('push', function(event) {
event.waitUntil(clients.matchAll().then(function(clientList) {
var focused = false;
for (var i = 0; i < clientList.length; i++) {
if (clientList[i].focused) {
focused = true;
break;
}
}
var notificationMessage;
if (focused) {
notificationMessage = 'You\'re still here, thanks!';
} else if (clientList.length > 0) {
notificationMessage = 'You haven\'t closed the page, click here to focus it!';
} else {
notificationMessage = 'You have closed the page, click here to re-open it!';
}
return self.registration.showNotification('ServiceWorker Cookbook', {
body: notificationMessage,
});
}));
});
self.addEventListener('notificationclick', function(event) {
event.waitUntil(clients.matchAll().then(function(clientList) {
if (clientList.length > 0) {
return clientList[0].focus();
} else {
return clients.openWindow('./push-clients/index.html');
}
}));
});
| Use different notification messages when the tab is focused, unfocused, closed | Use different notification messages when the tab is focused, unfocused, closed
| JavaScript | mit | TimAbraldes/serviceworker-cookbook,mozilla/serviceworker-cookbook,mozilla/serviceworker-cookbook,TimAbraldes/serviceworker-cookbook | ---
+++
@@ -8,8 +8,17 @@
}
}
+ var notificationMessage;
+ if (focused) {
+ notificationMessage = 'You\'re still here, thanks!';
+ } else if (clientList.length > 0) {
+ notificationMessage = 'You haven\'t closed the page, click here to focus it!';
+ } else {
+ notificationMessage = 'You have closed the page, click here to re-open it!';
+ }
+
return self.registration.showNotification('ServiceWorker Cookbook', {
- body: focused ? 'You\'re still here, thanks!' : 'Click me, please!',
+ body: notificationMessage,
});
}));
}); |
bed927e07e502c94127a2e2646294bb5bb64f5ca | src/index.js | src/index.js | import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
saga && sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 1)[1]]: value }), {}),
}
}
| import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
saga && sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 2)[1]]: value }), {}),
}
}
| Fix bug: Action name should be split into 2 elements (not 1) | Fix bug: Action name should be split into 2 elements (not 1)
| JavaScript | mit | moducks/moducks | ---
+++
@@ -24,6 +24,6 @@
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
- .reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 1)[1]]: value }), {}),
+ .reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 2)[1]]: value }), {}),
}
} |
ea1907a5efc980997dde8b34bff7557a106ad9cd | src/index.js | src/index.js | // @flow
/* Transform a Promise-returning function into a function that can optionally
* take a callback as the last parameter instead.
*
* @param {Function} fn a function that returns a Promise
* @param {Object} self (optional) `this` to be used when applying fn
* @return {Function} a function that can take callbacks as well.
*/
function optionalCallback(fn, self) {
if (!self) {
self = this;
}
return function() {
var last = arguments[arguments.length - 1];
if (typeof last === 'function') {
return fn.apply(self, arguments).then(function(){
last.apply(self, arguments);
}).catch(function(err){
last(err);
});
} else {
return fn.apply(self, arguments);
}
};
}
module.exports = optionalCallback;
| // @flow
/* Transform a Promise-returning function into a function that can optionally
* take a callback as the last parameter instead.
*
* @param {Function} fn a function that returns a Promise
* @param {Object} self (optional) `this` to be used when applying fn
* @return {Function} a function that can take callbacks as well.
*/
function optionalCallback(fn, self) {
return function() {
if (!self) {
self = this;
}
var last = arguments[arguments.length - 1];
if (typeof last === 'function') {
return fn.apply(self, arguments).then(function(){
last.apply(self, arguments);
}).catch(function(err){
last(err);
});
} else {
return fn.apply(self, arguments);
}
};
}
module.exports = optionalCallback;
| Resolve the value of self later | Resolve the value of self later
| JavaScript | mit | DimensionSoftware/optional-callback | ---
+++
@@ -8,10 +8,10 @@
* @return {Function} a function that can take callbacks as well.
*/
function optionalCallback(fn, self) {
- if (!self) {
- self = this;
- }
return function() {
+ if (!self) {
+ self = this;
+ }
var last = arguments[arguments.length - 1];
if (typeof last === 'function') {
return fn.apply(self, arguments).then(function(){ |
6b01912d1aea129a28262435ff1d1700a257a4d8 | configs/fast-config.js | configs/fast-config.js | anyware_config = {
DEBUG: {
status: true, // Persistent status icons
debugView: true, // Show game debug view
console: false, // Javascript console debug output
},
// The sequence of the games to be run. The first game is run on startup
GAMES_SEQUENCE: [ "mole", "disk", "simon", ],
MOLE_GAME: {
GAME_END: 3,
},
DISK_GAME: {
LEVELS: [
{ rule: 'absolute', disks: { disk0: -10, disk1: 10, disk2: 10 } },
],
},
SIMON_GAME: {
PATTERN_LEVELS: [
// level 0 sequence
{
stripId: '2',
// Each array of panel IDs is lit up one at a time
// Each array within this array is called a "frame" in the "sequence"
panelSequences: [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
],
frameDelay: 750 // Overriding default frame delay to make first level slower
},
],
}
};
| anyware_config = {
DEBUG: {
status: true, // Persistent status icons
debugView: true, // Show game debug view
console: false, // Javascript console debug output
},
// The sequence of the games to be run. The first game is run on startup
GAMES_SEQUENCE: [ "mole", "disk", "simon", ],
SPACE_BETWEEN_GAMES_SECONDS: 2,
MOLE_GAME: {
GAME_END: 3,
},
DISK_GAME: {
LEVELS: [
{ rule: 'absolute', disks: { disk0: -10, disk1: 10, disk2: 10 } },
],
},
SIMON_GAME: {
PATTERN_LEVELS: [
// level 0 sequence
{
stripId: '2',
// Each array of panel IDs is lit up one at a time
// Each array within this array is called a "frame" in the "sequence"
panelSequences: [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
],
frameDelay: 750 // Overriding default frame delay to make first level slower
},
],
}
};
| Make fast config have less space between games | Make fast config have less space between games
| JavaScript | mit | anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client | ---
+++
@@ -7,6 +7,8 @@
// The sequence of the games to be run. The first game is run on startup
GAMES_SEQUENCE: [ "mole", "disk", "simon", ],
+
+ SPACE_BETWEEN_GAMES_SECONDS: 2,
MOLE_GAME: {
GAME_END: 3, |
9246a44a065a046293492edeccafc376a9aa628f | src/utils.js | src/utils.js | import fs from "fs";
import InputStream from "./InputStream";
export function isGreyspace(string) {
if (string === "" ||
string === " " ||
string === "\n" ||
/^\s*$/.test(string)) {
return true;
}
if (string === undefined || string === null)
throw new Error("passed undefined or null to isGreyspace");
let stream = new InputStream(string);
// Consume shebang
stream.consume(/#!.*\n/);
while (!stream.atEnd()) {
let consumed = stream.consume(/\s+/) ||
stream.consume(/\/\/[^\n]*/) ||
stream.consume(/\/\*[\W\S]*?\*\//);
if (!consumed) return false;
}
return stream.atEnd();
}
export function log(...messages) {
let data = messages.join(" ") + "\n";
try {
fs.writeSync(3, data);
} catch (error) {
if (error.code === "EBADF") {
return;
} else {
throw error;
}
}
}
| import fs from "fs";
import InputStream from "./InputStream";
const whitespaceRe = /\s+/;
const shebangRe = /#!.*\n/;
const lineCommentRe = /\/\/[^\n]*/;
const blockCommentRe = /\/\*[\W\S]*?\*\//;
export function isGreyspace(string) {
if (string === "" ||
string === " " ||
string === "\n" ||
/^\s*$/.test(string)) {
return true;
}
if (string === undefined || string === null)
throw new Error("passed undefined or null to isGreyspace");
let stream = new InputStream(string);
// Consume shebang
stream.consume(shebangRe);
while (!stream.atEnd()) {
let consumed = stream.consume(whitespaceRe) ||
stream.consume(lineCommentRe) ||
stream.consume(blockCommentRe);
if (!consumed) return false;
}
return stream.atEnd();
}
export function parseGreyspace(string) {
if (string === undefined || string === null)
throw new Error("passed undefined or null to isGreyspace");
let parsedNodes = [];
let stream = new InputStream(string);
while (!stream.atEnd()) {
if (stream.consume(whitespaceRe)) {
parsedNodes.push({ type: "whitespace", value: stream.consumed });
} else if (stream.consume(lineCommentRe)) {
parsedNodes.push({ type: "lineComment", value: stream.consumed });
} else if (stream.consume(blockCommentRe)) {
parsedNodes.push({ type: "blockComment", value: stream.consumed });
} else if (stream.consume(shebangRe)) {
parsedNodes.push({ type: "shebang", value: stream.consumed });
} else {
// Takes care of assertion that string is greyspace
throw new Error("string is not greyspace");
}
}
return parsedNodes;
}
export function log(...messages) {
let data = messages.join(" ") + "\n";
try {
fs.writeSync(3, data);
} catch (error) {
if (error.code === "EBADF") {
return;
} else {
throw error;
}
}
}
| Create greyspace parser function to allow for splitting greyspace by type. | Create greyspace parser function to allow for splitting greyspace
by type.
| JavaScript | mit | Mark-Simulacrum/pretty-generator,Mark-Simulacrum/attractifier | ---
+++
@@ -1,5 +1,10 @@
import fs from "fs";
import InputStream from "./InputStream";
+
+const whitespaceRe = /\s+/;
+const shebangRe = /#!.*\n/;
+const lineCommentRe = /\/\/[^\n]*/;
+const blockCommentRe = /\/\*[\W\S]*?\*\//;
export function isGreyspace(string) {
if (string === "" ||
@@ -15,16 +20,42 @@
let stream = new InputStream(string);
// Consume shebang
- stream.consume(/#!.*\n/);
+ stream.consume(shebangRe);
while (!stream.atEnd()) {
- let consumed = stream.consume(/\s+/) ||
- stream.consume(/\/\/[^\n]*/) ||
- stream.consume(/\/\*[\W\S]*?\*\//);
+ let consumed = stream.consume(whitespaceRe) ||
+ stream.consume(lineCommentRe) ||
+ stream.consume(blockCommentRe);
if (!consumed) return false;
}
return stream.atEnd();
+}
+
+export function parseGreyspace(string) {
+ if (string === undefined || string === null)
+ throw new Error("passed undefined or null to isGreyspace");
+
+ let parsedNodes = [];
+
+ let stream = new InputStream(string);
+
+ while (!stream.atEnd()) {
+ if (stream.consume(whitespaceRe)) {
+ parsedNodes.push({ type: "whitespace", value: stream.consumed });
+ } else if (stream.consume(lineCommentRe)) {
+ parsedNodes.push({ type: "lineComment", value: stream.consumed });
+ } else if (stream.consume(blockCommentRe)) {
+ parsedNodes.push({ type: "blockComment", value: stream.consumed });
+ } else if (stream.consume(shebangRe)) {
+ parsedNodes.push({ type: "shebang", value: stream.consumed });
+ } else {
+ // Takes care of assertion that string is greyspace
+ throw new Error("string is not greyspace");
+ }
+ }
+
+ return parsedNodes;
}
export function log(...messages) { |
62081fa8127cce340675fb462a83ee9c457e13a3 | src/utils.js | src/utils.js | // @flow
// Recursively remove undefined, null, empty objects and empty arrays
export const compact = (obj: any): any => {
if (obj === null) {
return undefined;
}
if (Array.isArray(obj)) {
const compacted = obj.map(v => compact(v)).filter(
v => typeof v !== 'undefined'
);
return compacted.length === 0 ? undefined : compacted;
}
if (typeof obj === 'object') {
const compacted = Object.keys(obj).reduce((acc, key) => {
const nested = compact(obj[key]);
if (typeof nested === 'undefined') {
return acc;
} else {
return {
...acc,
[key]: nested
};
}
}, {});
return Object.keys(compacted).length === 0 ? undefined : compacted;
}
return obj;
};
| // @flow
// Recursively remove undefined, null, empty objects and empty arrays
export const compact = (value: any): any => {
if (value === null) {
return undefined;
}
if (Array.isArray(value)) {
const compacted = value.map(v => compact(v)).filter(
v => typeof v !== 'undefined'
);
return compacted.length === 0 ? undefined : compacted;
}
if (typeof value === 'object') {
const compacted = Object.keys(value).reduce((acc, key) => {
const nested = compact(value[key]);
if (typeof nested === 'undefined') {
return acc;
} else {
return {
...acc,
[key]: nested
};
}
}, {});
return Object.keys(compacted).length === 0 ? undefined : compacted;
}
return value;
};
| Rename 'obj' to 'value' for clarity | Rename 'obj' to 'value' for clarity
| JavaScript | apache-2.0 | contactlab/contacthub-sdk-nodejs | ---
+++
@@ -1,22 +1,22 @@
// @flow
// Recursively remove undefined, null, empty objects and empty arrays
-export const compact = (obj: any): any => {
- if (obj === null) {
+export const compact = (value: any): any => {
+ if (value === null) {
return undefined;
}
- if (Array.isArray(obj)) {
- const compacted = obj.map(v => compact(v)).filter(
+ if (Array.isArray(value)) {
+ const compacted = value.map(v => compact(v)).filter(
v => typeof v !== 'undefined'
);
return compacted.length === 0 ? undefined : compacted;
}
- if (typeof obj === 'object') {
- const compacted = Object.keys(obj).reduce((acc, key) => {
- const nested = compact(obj[key]);
+ if (typeof value === 'object') {
+ const compacted = Object.keys(value).reduce((acc, key) => {
+ const nested = compact(value[key]);
if (typeof nested === 'undefined') {
return acc;
@@ -31,5 +31,5 @@
return Object.keys(compacted).length === 0 ? undefined : compacted;
}
- return obj;
+ return value;
}; |
00f48eb9ab3f99883fea421afab2ddd875f32cf3 | node_modules/c9/manifest.js | node_modules/c9/manifest.js | var git = require("./git");
var hostname = require("./hostname");
exports.load = function(root) {
var manifest = require(root + "/package.json");
manifest.revision =
manifest.revision ||
git.getHeadRevisionSync(root);
manifest.hostname = hostname.get();
return manifest;
};
| var git = require("./git");
var hostname = require("./hostname");
var os = require("os");
exports.load = function(root) {
var manifest = require(root + "/package.json");
manifest.revision =
manifest.revision ||
git.getHeadRevisionSync(root);
manifest.hostname = hostname.get();
manifest.internalIP = os.networkInterfaces().eth0 && os.networkInterfaces().eth0[0].address;
return manifest;
};
| Store internal IP in docker host | Store internal IP in docker host
| JavaScript | bsd-3-clause | humberto-garza/VideoJuegos,humberto-garza/VideoJuegos | ---
+++
@@ -1,5 +1,6 @@
var git = require("./git");
var hostname = require("./hostname");
+var os = require("os");
exports.load = function(root) {
var manifest = require(root + "/package.json");
@@ -8,6 +9,7 @@
git.getHeadRevisionSync(root);
manifest.hostname = hostname.get();
+ manifest.internalIP = os.networkInterfaces().eth0 && os.networkInterfaces().eth0[0].address;
return manifest;
}; |
15c69f68a85e0bffca04e8c67b81b7260198f1c8 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require tether
//= require toastr
//= require_tree .
$(function () {
$(".sticky").sticky({
topSpacing: 90
, zIndex: -0
, stopper: "#you_shall_not_pass"
});
});
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require tether
//= require toastr
//= require_tree .
document.addEventListener("turbolinks:load", function() {
$(function () {
$(".sticky").sticky({
topSpacing: 90
, zIndex: -0
, stopper: "#you_shall_not_pass"
});
});
})
| Update js for sticky content | Update js for sticky content
| JavaScript | mit | bdisney/eShop,bdisney/eShop,bdisney/eShop | ---
+++
@@ -17,12 +17,13 @@
//= require toastr
//= require_tree .
+document.addEventListener("turbolinks:load", function() {
+ $(function () {
+ $(".sticky").sticky({
+ topSpacing: 90
+ , zIndex: -0
+ , stopper: "#you_shall_not_pass"
+ });
+ });
+})
-$(function () {
- $(".sticky").sticky({
- topSpacing: 90
- , zIndex: -0
- , stopper: "#you_shall_not_pass"
- });
-});
- |
de7309b150f877e59c8303748f84fd9a9e96c472 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | //= require libs/jquery/jquery-ui-1.8.16.custom.min
//= require libs/jquery/plugins/jquery.base64
//= require libs/jquery/plugins/jquery.mustache.js
//= require core
//= require devolution
//= require popup
//= require geo-locator
//= require welcome
//= require browse
//= require search
//= require jquery.history
//= require jquery.tabs
//= require mobile
//= require js-stick-at-top-when-scrolling
//= require stop-related-scrolling
| //= require libs/jquery/jquery-ui-1.8.16.custom.min
//= require libs/jquery/plugins/jquery.base64
//= require libs/jquery/plugins/jquery.mustache.js
//= require core
//= require devolution
//= require popup
//= require geo-locator
//= require welcome
//= require browse
//= require search
//= require jquery.history
//= require jquery.tabs
//= require mobile
//= require govuk_toolkit | Remove unused javascript requirements and add frontend toolkit | Remove unused javascript requirements and add frontend toolkit | JavaScript | mit | alphagov/static,tadast/static,tadast/static,kalleth/static,robinwhittleton/static,kalleth/static,tadast/static,robinwhittleton/static,alphagov/static,tadast/static,alphagov/static,robinwhittleton/static,kalleth/static,robinwhittleton/static,kalleth/static | ---
+++
@@ -11,5 +11,4 @@
//= require jquery.history
//= require jquery.tabs
//= require mobile
-//= require js-stick-at-top-when-scrolling
-//= require stop-related-scrolling
+//= require govuk_toolkit |
b1e3644c1eb0f68ec02325fca257198a276c4133 | generators/template-engine/modules/nunjucks/nunjucks-express.js | generators/template-engine/modules/nunjucks/nunjucks-express.js | // view engine setup
nunjucks.configure('views', {
autoescape: true,
express: app
});
|
// view engine setup
nunjucks.configure('views', {
autoescape: true,
express: app
});
app.set('view engine', 'html');
| Set default extension (html) for nunjucks | Set default extension (html) for nunjucks
| JavaScript | mit | sahat/boilerplate,sahat/megaboilerplate,sahat/megaboilerplate,sahat/megaboilerplate,sahat/boilerplate | ---
+++
@@ -1,5 +1,7 @@
+
// view engine setup
nunjucks.configure('views', {
autoescape: true,
express: app
});
+app.set('view engine', 'html'); |
ea82d61def4d3e9be56cc4a3c8f2b01c5ff4c3e1 | server/app.js | server/app.js | export default {};
var Twitter = require('twit-stream');
var keys =require('./authentication.js');
var stream = new Twitter(keys).stream('statuses/sample');
/// connection configuration for stream object to connect to API
stream.on('connected', function(msg) {
console.log('Connection successful.');
});
stream.on('reconnect', function(req, res, interval) {
console.log('Reconnecting in ' + (interval / 1e3) + ' seconds.');
});
stream.on('disconnect', function(msg) {
console.log('Twitter disconnection message');
console.log(msg);
});
| export default {};
var Twitter = require('twit-stream');
var keys =require('./authentication.js');
var stream = new Twitter(keys).stream('statuses/sample');
/// connection configuration for stream object to connect to API
stream.on('connected', function(msg) {
console.log('Connection successful.');
});
stream.on('reconnect', function(req, res, interval) {
console.log('Reconnecting in ' + (interval / 1e3) + ' seconds.');
});
stream.on('disconnect', function(msg) {
console.log('Twitter disconnection message');
console.log(msg);
});
// connection returns if twitter cuts off connection and why
stream.on('warning', function(message) {
console.warning('Yikes! a Warning message:');
console.warning(message);
});
stream.on('limit', function(message) {
console.log('WOAH! issued a limit message:');
console.log(message)
})
stream.on('disconnect', function(message) {
console.log('NOPE! disconnection message');
console.log(message);
});
| Add event return listeners for Twitter warning,limit and discnct | Add event return listeners for Twitter warning,limit and discnct
considering the amount of information you will be processing it
is more imperative for you to take into account and work on being
able to keep track of what twitters feedback is going to be. Thus
created a series of event listeners for message feedback from
twitter in the case.
| JavaScript | isc | edwardpark/d3withtwitterstream,edwardpark/d3withtwitterstream | ---
+++
@@ -20,3 +20,20 @@
console.log('Twitter disconnection message');
console.log(msg);
});
+
+
+// connection returns if twitter cuts off connection and why
+stream.on('warning', function(message) {
+ console.warning('Yikes! a Warning message:');
+ console.warning(message);
+});
+
+stream.on('limit', function(message) {
+ console.log('WOAH! issued a limit message:');
+ console.log(message)
+})
+
+stream.on('disconnect', function(message) {
+ console.log('NOPE! disconnection message');
+ console.log(message);
+}); |
d02e4db2e4ab9e359f04c4d5315d01e55679e471 | routes/index.js | routes/index.js | /**
* Basic route controller
*/
var pages = require('./pages');
var formidable = require('formidable');
module.exports = function(app, io) {
app.get('/', pages.index);
app.post('/', function(req, res, next){
var form = new formidable.IncomingForm();
form.uploadDir = "./images";
form.type = 'multipart';
form.multiples = true;
form.parse(req, function(err, fields, files) {
//TODO : redirect to analysis
});
form.on('progress', function(bytesReceived, bytesExpected) {
var progress = (bytesReceived * 100) / bytesExpected;
io.sockets.in('sessionId').emit('uploadProgress', progress);
});
form.on('error', function(err) {
console.log("Error: ", err);
io.sockets.in('sessionId').emit('error', err);
});
});
}; | /**
* Basic route controller
*/
var pages = require('./pages');
var formidable = require('formidable');
var fs = require('fs');
var Parse = require('csv-parse');
function parseFile(filePath, res){
var output = [];
function onNewRecord(record){
output.push(record);
}
function onError(error){
res.send(error);
}
function done(linesRead){
res.send(200, output);
console.log("parsed:" + filePath);
}
var columns = true;
parseCSVFile(filePath, columns, onNewRecord, onError, done);
}
function parseCSVFile(sourceFilePath, columns, onNewRecord, handleError, done){
var source = fs.createReadStream(sourceFilePath);
var parser = Parse({
delimiter: ',',
columns:columns
});
parser.on("readable", function(){
var record;
while (record = parser.read()) {
onNewRecord(record);
}
});
parser.on("error", function(error){
handleError(error)
});
parser.on("finish", function(){
done();
});
source.pipe(parser);
}
module.exports = function(app, io) {
app.get('/', pages.index);
app.post('/', function(req, res, next){
var form = new formidable.IncomingForm();
form.uploadDir = "./images";
form.type = 'multipart';
form.multiples = true;
form.parse(req, function(err, fields, files) {
//TODO : redirect to analysis
if(err){
res.send(400);
res.redirect('/');
console.log("Error: ", err);
io.sockets.in('sessionId').emit('error', err);
}
console.log(files.csv1.path + " " + files.csv2.path);
parseFile(files.csv1.path, res);
});
form.on('progress', function(bytesReceived, bytesExpected) {
var progress = (bytesReceived * 100) / bytesExpected;
io.sockets.in('sessionId').emit('uploadProgress', progress);
});
});
}; | Handle parsing errors on parse completion. Stream file and parse the list into JSON objs and dump onto the res | Handle parsing errors on parse completion.
Stream file and parse the list into JSON objs and dump onto the res
| JavaScript | mit | Midnight-Coder/DerangedCSVs,Midnight-Coder/DerangedCSVs | ---
+++
@@ -3,7 +3,55 @@
*/
var pages = require('./pages');
var formidable = require('formidable');
+var fs = require('fs');
+var Parse = require('csv-parse');
+function parseFile(filePath, res){
+
+
+ var output = [];
+ function onNewRecord(record){
+ output.push(record);
+ }
+
+ function onError(error){
+ res.send(error);
+ }
+
+ function done(linesRead){
+ res.send(200, output);
+ console.log("parsed:" + filePath);
+ }
+
+ var columns = true;
+ parseCSVFile(filePath, columns, onNewRecord, onError, done);
+
+}
+
+function parseCSVFile(sourceFilePath, columns, onNewRecord, handleError, done){
+ var source = fs.createReadStream(sourceFilePath);
+
+ var parser = Parse({
+ delimiter: ',',
+ columns:columns
+ });
+
+ parser.on("readable", function(){
+ var record;
+ while (record = parser.read()) {
+ onNewRecord(record);
+ }
+ });
+
+ parser.on("error", function(error){
+ handleError(error)
+ });
+
+ parser.on("finish", function(){
+ done();
+ });
+ source.pipe(parser);
+}
module.exports = function(app, io) {
app.get('/', pages.index);
@@ -15,17 +63,20 @@
form.parse(req, function(err, fields, files) {
//TODO : redirect to analysis
+ if(err){
+ res.send(400);
+ res.redirect('/');
+ console.log("Error: ", err);
+ io.sockets.in('sessionId').emit('error', err);
+ }
+ console.log(files.csv1.path + " " + files.csv2.path);
+
+ parseFile(files.csv1.path, res);
});
form.on('progress', function(bytesReceived, bytesExpected) {
var progress = (bytesReceived * 100) / bytesExpected;
io.sockets.in('sessionId').emit('uploadProgress', progress);
});
-
- form.on('error', function(err) {
- console.log("Error: ", err);
- io.sockets.in('sessionId').emit('error', err);
- });
-
});
}; |
589e86a2a94e05f30cd8b39bbdb8c2c109a56427 | js/console-save.js | js/console-save.js | //Source:
//https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
//http://bgrins.github.io/devtools-snippets/#console-save
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return;
}
if(!filename) filename = 'console.json';
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
})(console);
| //Source:
//https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
//http://bgrins.github.io/devtools-snippets/#console-save
//A simple way to save objects as .json files from the console
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data');
return;
}
if(!filename) filename = 'console.json';
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4);
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
};
})(console);
| Add import and export buttons | Add import and export buttons
| JavaScript | mit | sjbuysse/sessions-map,sjbuysse/sessions-map | ---
+++
@@ -1,6 +1,7 @@
//Source:
//https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
//http://bgrins.github.io/devtools-snippets/#console-save
+//A simple way to save objects as .json files from the console
(function(console){
console.save = function(data, filename){ |
c2957291d4db4a30fc1fa427fb179cd0c30c6001 | server/app.js | server/app.js | var log = require("./log.js");
var app =
{
// io: null
};
app.init = function init(httpServer)
{
// TODO: add WebSocket (socket.io) endpoints or other light non-HTTP backend connections here as necessary (or move to a real app framework for Node like Express)
// app.io = require("socket.io")(httpServer);
// ...
log("Web application initialized");
};
module.exports.init = app.init;
| // var io = require("socket.io")();
var log = require("./log.js");
function init(httpServer)
{
// TODO: add WebSocket (socket.io) endpoints or other light non-HTTP backend connections here as necessary (or move to a real app framework for Node like Express)
// io.attach(httpServer);
log("Web application initialized");
};
/*
io.on("connection", function (socket)
{
// ...
});
*/
module.exports.init = init;
| Update to proper Node module scope conventions | Update to proper Node module scope conventions
| JavaScript | mit | frog/packaged-node-web-server,frog/packaged-node-web-server,frog/packaged-node-web-server | ---
+++
@@ -1,17 +1,20 @@
+// var io = require("socket.io")();
+
var log = require("./log.js");
-var app =
-{
- // io: null
-};
-
-app.init = function init(httpServer)
+function init(httpServer)
{
// TODO: add WebSocket (socket.io) endpoints or other light non-HTTP backend connections here as necessary (or move to a real app framework for Node like Express)
- // app.io = require("socket.io")(httpServer);
- // ...
+ // io.attach(httpServer);
log("Web application initialized");
};
-module.exports.init = app.init;
+/*
+io.on("connection", function (socket)
+{
+ // ...
+});
+*/
+
+module.exports.init = init; |
6a1098ef55e3723447d336384d0273f7f0a8dc00 | misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js | misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js | // ==UserScript==
// @name Remove concourse elements
// @namespace cloudpipeline.digital
// @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens.
// @include https://deployer.*.cloudpipeline.digital/*
// @include https://deployer.cloud.service.gov.uk/*
// @include https://deployer.london.cloud.service.gov.uk/*
// @version 1
// @grant none
// ==/UserScript==
const readyStateCheckInterval = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(readyStateCheckInterval);
console.log('Monitor mode is go');
const $legend = document.querySelector('.legend');
$legend.style.display = 'none';
const $infoBox = document.querySelector('.lower-right-info');
$infoBox.style.display = 'none';
const $topBar = document.querySelector('#top-bar-app');
$topBar.style.display = 'none';
const $groupsBar = document.querySelector('.groups-bar');
$groupsBar.style.display = 'none';
const $bottom = document.querySelector('.bottom');
// Remove the padding because the top bar isn't there any more.
$bottom.style.paddingTop = '0';
const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', '');
document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`);
}
}, 2000);
| // ==UserScript==
// @name Remove concourse elements
// @namespace cloudpipeline.digital
// @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens.
// @include https://deployer.*.cloudpipeline.digital/*
// @include https://deployer.cloud.service.gov.uk/*
// @include https://deployer.london.cloud.service.gov.uk/*
// @version 1
// @grant none
// ==/UserScript==
const readyStateCheckInterval = setInterval(() => {
if (document.readyState === 'complete') {
clearInterval(readyStateCheckInterval);
console.log('Monitor mode is go');
const $legend = document.querySelector('#legend');
$legend.style.display = 'none';
const $infoBox = document.querySelector('.lower-right-info');
$infoBox.style.display = 'none';
const $topBar = document.querySelector('#top-bar-app');
$topBar.style.display = 'none';
const $groupsBar = document.querySelector('#groups-bar');
$groupsBar.style.display = 'none';
const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', '');
document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`);
}
}, 2000);
| Update chrome clean pipelines plugin to work with concourse 5 | Update chrome clean pipelines plugin to work with concourse 5
This commit updates the divs that we wish to remove from the pipeline view.
| JavaScript | mit | alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf,alphagov/paas-cf | ---
+++
@@ -13,7 +13,7 @@
clearInterval(readyStateCheckInterval);
console.log('Monitor mode is go');
- const $legend = document.querySelector('.legend');
+ const $legend = document.querySelector('#legend');
$legend.style.display = 'none';
const $infoBox = document.querySelector('.lower-right-info');
@@ -22,12 +22,8 @@
const $topBar = document.querySelector('#top-bar-app');
$topBar.style.display = 'none';
- const $groupsBar = document.querySelector('.groups-bar');
+ const $groupsBar = document.querySelector('#groups-bar');
$groupsBar.style.display = 'none';
-
- const $bottom = document.querySelector('.bottom');
- // Remove the padding because the top bar isn't there any more.
- $bottom.style.paddingTop = '0';
const hostname = window.location.hostname.replace('deployer.', '').replace('.cloudpipeline.digital', '');
document.body.insertAdjacentHTML('beforeend', `<div style="bottom: 0; font-size: 24px; padding: 16px; position: absolute;">${hostname}</div>`); |
7d792bb25af6236a0fa53c561c7aa416129561b7 | client/widgets/sharing/sharing.js | client/widgets/sharing/sharing.js | import Shariff from '/imports/ui/lib/shariff/shariff';
Template.sharing.onRendered(function() {
this.autorun(() => {
this.shariff = new Shariff(this.find('.shariff'), {
lang: Session.get('locale'),
services: [
'twitter',
'facebook',
'whatsapp',
'googleplus',
'diaspora',
'mail',
'info',
]
});
// Remove href and target from mail button. Instead install a click
// event handler which opens a mail form.
const mailAction = this.find('.shariff-button.mail a');
if (mailAction) {
mailAction.removeAttribute('target');
mailAction.removeAttribute('href');
}
});
});
Template.sharing.events({
'click .shariff-button.mail a'(event) {
event.stopPropagation();
console.log('e-mail button clicked! FIXME: open modal or something.')
}
});
| import Shariff from '/imports/ui/lib/shariff/shariff';
Template.sharing.onRendered(function() {
this.autorun(() => {
this.shariff = new Shariff(this.find('.shariff'), {
lang: Session.get('locale'),
mailtoUrl: 'mailto:',
services: [
'twitter',
'facebook',
'whatsapp',
'googleplus',
'diaspora',
'mail',
'info',
]
});
});
});
| Use mailto: for the moment | Use mailto: for the moment
| JavaScript | agpl-3.0 | schuel/hmmm,schuel/hmmm,Openki/Openki,schuel/hmmm,Openki/Openki,Openki/Openki | ---
+++
@@ -4,6 +4,7 @@
this.autorun(() => {
this.shariff = new Shariff(this.find('.shariff'), {
lang: Session.get('locale'),
+ mailtoUrl: 'mailto:',
services: [
'twitter',
'facebook',
@@ -14,20 +15,5 @@
'info',
]
});
-
- // Remove href and target from mail button. Instead install a click
- // event handler which opens a mail form.
- const mailAction = this.find('.shariff-button.mail a');
- if (mailAction) {
- mailAction.removeAttribute('target');
- mailAction.removeAttribute('href');
- }
});
});
-
-Template.sharing.events({
- 'click .shariff-button.mail a'(event) {
- event.stopPropagation();
- console.log('e-mail button clicked! FIXME: open modal or something.')
- }
-}); |
f569688bc7ce880a1339697d3b775d67528d1eb8 | static/scripts/helpers/form_bug_text.js | static/scripts/helpers/form_bug_text.js | /* eslint-disable max-len */
export default `Ich als [Nutzerrolle]
habe auf der Seite [???]
die Funktion [???]
aufgrund des Fehlers/der Fehlermeldung "[???]"
nicht benutzen können.
Tritt der Fehler auch bei anderen/ ähnlichen Bereichen (z.B. andere Kurse oder Nutzer) auf?
Wie genau äußert sich das Problem?
Wenn mehrere Schritte notwendig sind, um das Problem nachzuvollziehen, diese hier bitte so kurz und klar wie möglich beschreiben.
`;
| /* eslint-disable max-len */
export default `Ich als [Nutzerrolle]
habe auf der Seite [???]
die Funktion [???]
aufgrund des Fehlers/der Fehlermeldung "[???]"
nicht benutzen können.
Tritt der Fehler auch bei anderen/ ähnlichen Bereichen (z.B. andere Kurse oder Nutzer) auf?
Wie genau äußert sich das Problem?
Wann trat der Fehler genau auf (Datum, Uhrzeit), damit wir gezielt in den Logs schauen können?
Wenn mehrere Schritte notwendig sind, um das Problem nachzuvollziehen, diese hier bitte so kurz und klar wie möglich beschreiben.
`;
| Add a new question regarding datetime | Add a new question regarding datetime
| JavaScript | agpl-3.0 | schul-cloud/schulcloud-client,schul-cloud/schulcloud-client,schul-cloud/schulcloud-client | ---
+++
@@ -7,5 +7,6 @@
Tritt der Fehler auch bei anderen/ ähnlichen Bereichen (z.B. andere Kurse oder Nutzer) auf?
Wie genau äußert sich das Problem?
+Wann trat der Fehler genau auf (Datum, Uhrzeit), damit wir gezielt in den Logs schauen können?
Wenn mehrere Schritte notwendig sind, um das Problem nachzuvollziehen, diese hier bitte so kurz und klar wie möglich beschreiben.
`; |
25b2d06fe260f734ef6944062f410a74c3100bb5 | sound-wave.js | sound-wave.js | const fs = require('fs');
const sampleRate = 44100,
resolution = 16;
const maxLevel = Math.pow(2, resolution - 1) - 1,
BinaryArray = {
8: Int8Array,
16: Int16Array,
32: Int32Array
}[resolution];
function sineWave(frequency, duration) {
var samplesCount = duration * sampleRate,
array = new BinaryArray(samplesCount);
for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) {
var currentTime = sampleNumber / sampleRate,
signal = Math.sin(2 * Math.PI * frequency * currentTime),
level = Math.floor(signal * maxLevel);
array[sampleNumber] = level;
}
return array;
}
function writePCM(filename, frequency, duration) {
var array = sineWave(frequency, duration),
buffer = new Buffer(array);
fs.writeFile(filename, buffer, 'binary');
}
writePCM('440hz.pcm', 440, 10); | const fs = require('fs');
const sampleRate = 44100,
resolution = 16;
const maxLevel = Math.pow(2, resolution - 1) - 1,
BinaryArray = {
8: Int8Array,
16: Int16Array,
32: Int32Array
}[resolution];
function sineWave(frequency, duration) {
var samplesCount = Math.floor(duration * sampleRate),
array = new BinaryArray(samplesCount);
for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) {
var currentTime = sampleNumber / sampleRate,
signal = Math.sin(2 * Math.PI * frequency * currentTime),
level = Math.floor(signal * maxLevel);
array[sampleNumber] = level;
}
return array;
}
function writePCM(filename, frequency, duration) {
var array = sineWave(frequency, duration),
buffer = new Buffer(array.buffer);
fs.writeFile(filename, buffer, 'binary');
}
writePCM('440hz.pcm', 440, 10); | Use array.buffer so that TypedArray and Buffer share the same memory | Use array.buffer so that TypedArray and Buffer share the same memory
| JavaScript | mit | aqrln/sound-wave | ---
+++
@@ -11,7 +11,7 @@
}[resolution];
function sineWave(frequency, duration) {
- var samplesCount = duration * sampleRate,
+ var samplesCount = Math.floor(duration * sampleRate),
array = new BinaryArray(samplesCount);
for (var sampleNumber = 0; sampleNumber < samplesCount; sampleNumber++) {
@@ -26,7 +26,7 @@
function writePCM(filename, frequency, duration) {
var array = sineWave(frequency, duration),
- buffer = new Buffer(array);
+ buffer = new Buffer(array.buffer);
fs.writeFile(filename, buffer, 'binary');
}
|
4080e7daa4b5a9e7e37273036ac9e489bea226b9 | spec/support/fixtures/stripejs-mock.js | spec/support/fixtures/stripejs-mock.js | class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.classList.add('StripeElement');
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM / YY" size="6" type="text">
<input name="cvc" placeholder="CVC" size="3" type="text">
`;
}
addEventListener(event) {
return true;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
createPaymentMethod: () => {
return new Promise(resolve => {
resolve({
paymentMethod: {
id: "pm_123",
card: {
brand: 'visa',
last4: fetchLastFour(),
exp_month: "10",
exp_year: "2050"
}
}
});
});
},
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
| // StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects.
// Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js
// The original has been adapted to work with OFN (see commit history for details).
class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.classList.add('StripeElement');
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM / YY" size="6" type="text">
<input name="cvc" placeholder="CVC" size="3" type="text">
`;
}
addEventListener(event) {
return true;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
createPaymentMethod: () => {
return new Promise(resolve => {
resolve({
paymentMethod: {
id: "pm_123",
card: {
brand: 'visa',
last4: fetchLastFour(),
exp_month: "10",
exp_year: "2050"
}
}
});
});
},
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
| Add comments in StripeJS mock | Add comments in StripeJS mock
| JavaScript | agpl-3.0 | lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,lin-d-hop/openfoodnetwork,Matt-Yorkley/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,mkllnk/openfoodnetwork,openfoodfoundation/openfoodnetwork,lin-d-hop/openfoodnetwork,openfoodfoundation/openfoodnetwork,Matt-Yorkley/openfoodnetwork,mkllnk/openfoodnetwork | ---
+++
@@ -1,3 +1,7 @@
+// StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects.
+// Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js
+// The original has been adapted to work with OFN (see commit history for details).
+
class Element {
mount(el) {
if (typeof el === "string") { |
6f83ef247f86a8581c9b66841cdea826a6fd90ed | server/config/db.js | server/config/db.js | var connection = {
client: 'mysql',
connection: {
host: process.env.HOST,
database: process.env.APP_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
charset: 'utf8'
}
};
var knex = require('knex')(connection);
connection.database = process.env.APP_NAME;
var db = require('bookshelf')(knex);
module.exports = db; | var connection = {
client: 'mysql',
connection: {
host: 'localhost',
database: process.env.APP_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
charset: 'utf8'
}
};
var knex = require('knex')(connection);
connection.database = process.env.APP_NAME;
var db = require('bookshelf')(knex);
module.exports = db; | Adjust database host to always be localhost | Adjust database host to always be localhost
| JavaScript | mit | chkakaja/sentimize,formidable-coffee/masterfully,formidable-coffee/masterfully,chkakaja/sentimize | ---
+++
@@ -1,7 +1,7 @@
var connection = {
client: 'mysql',
connection: {
- host: process.env.HOST,
+ host: 'localhost',
database: process.env.APP_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD, |
7f6e9e09e064c6d8b51960a579375684d660ecc9 | src/client.js | src/client.js | import React from 'react'
import ReactDOM from 'react-dom'
/* Create a simple component without JSX
<div>
React Tutorial
</div>
*/
const App = function() {
return React.createElement('div', null, 'React Tutorial');
}
ReactDOM.render(<App />, document.getElementById('app')) | import React from 'react'
import ReactDOM from 'react-dom'
/* Create a simple component without JSX
<div>
React Tutorial
</div>
*/
const App = function() {
// return React.createElement('div', null, 'React Tutorial');
return <div>React Tutorial</div>;
}
ReactDOM.render(<App />, document.getElementById('app')) | Create a simple component with JSX | Create a simple component with JSX
| JavaScript | mit | suranartnc/react-tutorial | ---
+++
@@ -7,7 +7,8 @@
</div>
*/
const App = function() {
- return React.createElement('div', null, 'React Tutorial');
+ // return React.createElement('div', null, 'React Tutorial');
+ return <div>React Tutorial</div>;
}
ReactDOM.render(<App />, document.getElementById('app')) |
27e809275ab1132260bf0327b6134d60e095844c | src/dollrs.js | src/dollrs.js | import create from './create';
export default function $$(ufo, context) {
if (typeof ufo === 'string') {
// if it seems to be HTML, create an elements
if (/^\s*</.test(ufo)) {
return create(ufo);
}
if (context) {
return $$(context)
.reduce((result, element) => result.concat($$(element.querySelectorAll(ufo))), []);
}
return $$(document.querySelectorAll(ufo));
} else if (ufo instanceof Node) {
return [ufo];
} else if (ufo instanceof Array) {
return ufo;
} else if (ufo instanceof NodeList || ufo instanceof HTMLCollection) {
return Array.prototype.slice.call(ufo);
}
return [];
}
| import create from './create';
export default function $$(ufo, context) {
if (typeof ufo === 'string') {
// if it seems to be HTML, create an elements
if (/^\s*</.test(ufo)) {
return $$(create(ufo));
}
if (context) {
return $$(context)
.reduce((result, element) => result.concat($$(element.querySelectorAll(ufo))), []);
}
return $$(document.querySelectorAll(ufo));
} else if (ufo instanceof Node) {
return [ufo];
} else if (ufo instanceof Array) {
return ufo;
} else if (ufo instanceof NodeList || ufo instanceof HTMLCollection) {
return Array.from(ufo);
}
return [];
}
| Return array when creating from string and better conversion to array | Return array when creating from string and better conversion to array
| JavaScript | mit | lohfu/dollr | ---
+++
@@ -4,7 +4,7 @@
if (typeof ufo === 'string') {
// if it seems to be HTML, create an elements
if (/^\s*</.test(ufo)) {
- return create(ufo);
+ return $$(create(ufo));
}
if (context) {
@@ -18,7 +18,7 @@
} else if (ufo instanceof Array) {
return ufo;
} else if (ufo instanceof NodeList || ufo instanceof HTMLCollection) {
- return Array.prototype.slice.call(ufo);
+ return Array.from(ufo);
}
return []; |
c1a494f0250e742d548c1585bb71ed16730ab45a | lib/spawnHelper.js | lib/spawnHelper.js | var childProcess = require('child_process');
var q = require('q');
var runCommand = function(command) {
var deferred = q.defer();
console.log('Running command: [%s]', command);
var commandArray = command.split(/\s/);
// First arg: command, then pass arguments as array.
var child = childProcess.spawn(commandArray[0], commandArray.slice(1));
child.stdout.on('data', function(data) {
var line = data.toString();
process.stdout.write(line);
// Wait until the port is ready to resolve the promise.
if (line.match(/Server listening on/g)) {
deferred.resolve();
}
});
// The process uses stderr for debugging info. Ignore errors.
child.stderr.on('data', process.stderr.write);
return deferred.promise;
};
module.exports = {
runCommand: runCommand
};
| var childProcess = require('child_process');
var q = require('q');
/**
* Spawn a child process given a command. Wait for the process to start given
* a regexp that will be matched against stdout.
*
* @param {string} command The command to execute.
* @param {RegExp} waitRegexp An expression used to test when the process has
* started.
* @return {Q.promise} A promise that resolves when the process has stated.
*/
var runCommand = function(command, waitRegexp) {
var deferred = q.defer();
console.log('Running command: [%s]', command);
var commandArray = command.split(/\s/);
// First arg: command, then pass arguments as array.
var child = childProcess.spawn(commandArray[0], commandArray.slice(1));
child.stdout.on('data', function(data) {
var line = data.toString();
process.stdout.write(line);
// Wait until the port is ready to resolve the promise.
if (line.match(waitRegexp)) {
deferred.resolve();
}
});
// The process uses stderr for debugging info. Ignore errors.
child.stderr.on('data', process.stderr.write);
return deferred.promise;
};
module.exports = {
runCommand: runCommand
};
| Add waitRegexp as an argument. | Add waitRegexp as an argument.
| JavaScript | mit | andresdominguez/elementor,andresdominguez/elementor | ---
+++
@@ -1,7 +1,16 @@
var childProcess = require('child_process');
var q = require('q');
-var runCommand = function(command) {
+/**
+ * Spawn a child process given a command. Wait for the process to start given
+ * a regexp that will be matched against stdout.
+ *
+ * @param {string} command The command to execute.
+ * @param {RegExp} waitRegexp An expression used to test when the process has
+ * started.
+ * @return {Q.promise} A promise that resolves when the process has stated.
+ */
+var runCommand = function(command, waitRegexp) {
var deferred = q.defer();
console.log('Running command: [%s]', command);
@@ -16,7 +25,7 @@
process.stdout.write(line);
// Wait until the port is ready to resolve the promise.
- if (line.match(/Server listening on/g)) {
+ if (line.match(waitRegexp)) {
deferred.resolve();
}
}); |
c2fc624fd9d7d836a4f423baf8c64b0a053bb24f | src/kinvey.js | src/kinvey.js | import { Promise } from 'es6-promise';
import { Kinvey as CoreKinvey, isDefined, KinveyError } from 'kinvey-js-sdk/dist/export';
import { Client } from './client';
export class Kinvey extends CoreKinvey {
static initialize(config) {
const client = Kinvey.init(config);
return Promise.resolve(client.getActiveUser());
}
static init(options = {}) {
if (!isDefined(options.appKey)) {
throw new KinveyError('No App Key was provided.'
+ ' Unable to create a new Client without an App Key.');
}
if (!isDefined(options.appSecret) && !isDefined(options.masterSecret)) {
throw new KinveyError('No App Secret or Master Secret was provided.'
+ ' Unable to create a new Client without an App Key.');
}
return Client.init(options);
}
}
| import { Promise } from 'es6-promise';
import url from 'url';
import {
Kinvey as CoreKinvey,
isDefined,
KinveyError,
CacheRequest,
RequestMethod
} from 'kinvey-js-sdk/dist/export';
import { Client } from './client';
const USERS_NAMESPACE = 'user';
const ACTIVE_USER_COLLECTION_NAME = 'kinvey_active_user';
export class Kinvey extends CoreKinvey {
static initialize(config) {
const client = Kinvey.init(config);
const activeUser = client.getActiveUser();
if (isDefined(activeUser)) {
return Promise.resolve(activeUser);
}
const request = new CacheRequest({
method: RequestMethod.GET,
url: url.format({
protocol: client.apiProtocol,
host: client.apiHost,
pathname: `/${USERS_NAMESPACE}/${client.appKey}/${ACTIVE_USER_COLLECTION_NAME}`
})
});
return request.execute()
.then(response => response.data)
.then((activeUsers) => {
if (activeUsers.length > 0) {
return activeUsers[0];
}
return null;
})
.then((activeUser) => {
if (isDefined(activeUser)) {
return client.setActiveUser(activeUser);
}
return activeUser;
});
}
static init(options = {}) {
if (!isDefined(options.appKey)) {
throw new KinveyError('No App Key was provided.'
+ ' Unable to create a new Client without an App Key.');
}
if (!isDefined(options.appSecret) && !isDefined(options.masterSecret)) {
throw new KinveyError('No App Secret or Master Secret was provided.'
+ ' Unable to create a new Client without an App Secret.');
}
return Client.init(options);
}
}
| Load the active user using the previous stored location if an active user does not exist | Load the active user using the previous stored location if an active user does not exist
| JavaScript | apache-2.0 | Kinvey/kinvey-html5-lib | ---
+++
@@ -1,11 +1,50 @@
import { Promise } from 'es6-promise';
-import { Kinvey as CoreKinvey, isDefined, KinveyError } from 'kinvey-js-sdk/dist/export';
+import url from 'url';
+import {
+ Kinvey as CoreKinvey,
+ isDefined,
+ KinveyError,
+ CacheRequest,
+ RequestMethod
+} from 'kinvey-js-sdk/dist/export';
import { Client } from './client';
+
+const USERS_NAMESPACE = 'user';
+const ACTIVE_USER_COLLECTION_NAME = 'kinvey_active_user';
export class Kinvey extends CoreKinvey {
static initialize(config) {
const client = Kinvey.init(config);
- return Promise.resolve(client.getActiveUser());
+ const activeUser = client.getActiveUser();
+
+ if (isDefined(activeUser)) {
+ return Promise.resolve(activeUser);
+ }
+
+ const request = new CacheRequest({
+ method: RequestMethod.GET,
+ url: url.format({
+ protocol: client.apiProtocol,
+ host: client.apiHost,
+ pathname: `/${USERS_NAMESPACE}/${client.appKey}/${ACTIVE_USER_COLLECTION_NAME}`
+ })
+ });
+ return request.execute()
+ .then(response => response.data)
+ .then((activeUsers) => {
+ if (activeUsers.length > 0) {
+ return activeUsers[0];
+ }
+
+ return null;
+ })
+ .then((activeUser) => {
+ if (isDefined(activeUser)) {
+ return client.setActiveUser(activeUser);
+ }
+
+ return activeUser;
+ });
}
static init(options = {}) {
@@ -16,7 +55,7 @@
if (!isDefined(options.appSecret) && !isDefined(options.masterSecret)) {
throw new KinveyError('No App Secret or Master Secret was provided.'
- + ' Unable to create a new Client without an App Key.');
+ + ' Unable to create a new Client without an App Secret.');
}
return Client.init(options); |
85518b0b853f9feee2822df289501508c7af6d19 | transformers/browserchannel/server.js | transformers/browserchannel/server.js | 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus
, query = {};
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server({
base: primus.pathname
}, function connection(socket) {
var spark = new Spark(
socket.headers // HTTP request headers.
, socket.address // IP address.
, query // Query string, not allowed by browser channel.
, socket.id // Unique connection id.
);
spark.on('outgoing::end', function end() {
socket.close();
}).on('outgoing::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
| 'use strict';
/**
* Minimum viable Browserchannel server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var browserchannel = require('browserchannel')
, Spark = this.Spark
, primus = this.primus
, query = {};
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service = browserchannel.server({
base: primus.pathname
}, function connection(socket) {
var spark = new Spark(
socket.headers // HTTP request headers.
, socket.address // IP address.
, query // Query string, not allowed by browser channel.
, socket.id // Unique connection id.
);
spark.on('outgoing::end', function end() {
socket.stop();
}).on('outgoing::data', function write(data) {
socket.send(data);
});
socket.on('close', spark.emits('end'));
socket.on('message', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('request', function request(req, res, next) {
//
// The browser.channel returns a middleware layer.
//
this.service(req, res, next);
});
};
| Use stop instead of close, it fixes, things. | [minor] Use stop instead of close, it fixes, things.
| JavaScript | mit | primus/primus,basarat/primus,dercodebearer/primus,colinbate/primus,modulexcite/primus,basarat/primus,colinbate/primus,STRML/primus,colinbate/primus,beni55/primus,dercodebearer/primus,dercodebearer/primus,clanwqq/primus,beni55/primus,modulexcite/primus,modulexcite/primus,clanwqq/primus,primus/primus,primus/primus,basarat/primus,STRML/primus,STRML/primus,clanwqq/primus,beni55/primus | ---
+++
@@ -29,7 +29,7 @@
);
spark.on('outgoing::end', function end() {
- socket.close();
+ socket.stop();
}).on('outgoing::data', function write(data) {
socket.send(data);
}); |
75e74cf1d434f564535fd1fef06ab18963a57277 | src/resource/RefraxParameters.js | src/resource/RefraxParameters.js | /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* A RefraxStore is a wrapper around the RefraxFragmentCache object that offers
* a Subscribable interface to resource mutations.
*/
class RefraxParameters {
constructor(params) {
this.params = params;
}
}
export default RefraxParameters;
| /**
* Copyright (c) 2015-present, Joshua Hollenbeck
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
const RefraxTools = require('RefraxTools');
/**
* A RefraxParameters is a wrapper around an object to identify it as a
* set of parameters.
*/
class RefraxParameters {
constructor(params) {
RefraxTools.extend(this, params);
}
}
export default RefraxParameters;
| Update Parameters to be self extending vs containing to conform to Options | Update Parameters to be self extending vs containing to conform to Options
| JavaScript | bsd-3-clause | netarc/refrax,netarc/refrax | ---
+++
@@ -5,14 +5,16 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
+const RefraxTools = require('RefraxTools');
+
/**
- * A RefraxStore is a wrapper around the RefraxFragmentCache object that offers
- * a Subscribable interface to resource mutations.
+ * A RefraxParameters is a wrapper around an object to identify it as a
+ * set of parameters.
*/
class RefraxParameters {
constructor(params) {
- this.params = params;
+ RefraxTools.extend(this, params);
}
}
|
b08bdaf5628bb9c1a13c20110f7cae593c6c66c5 | test/helpers.js | test/helpers.js | // ----------------------------------------------------------------------------
//
// helpers.js
//
// ----------------------------------------------------------------------------
var dyno = require('../dyno-leveldb.js');
function newDyno() {
return dyno('/tmp/' + (new Date()).toISOString());
};
// ----------------------------------------------------------------------------
function pad(str, length) {
while ( str.length < length ) {
str = '0' + str;
}
return str;
}
// first thing to do is make a simple timestamp function
var i = 0;
function timestamp() {
i++;
return (new Date()).toISOString() + '-' + pad(i, 16);
}
// ----------------------------------------------------------------------------
module.exports.timestamp = timestamp;
module.exports.newDyno = newDyno;
// ----------------------------------------------------------------------------
| // ----------------------------------------------------------------------------
//
// helpers.js
//
// ----------------------------------------------------------------------------
var dyno = require('../dyno-leveldb.js');
function newDyno() {
return dyno('/tmp/' + (new Date()).toISOString());
};
// ----------------------------------------------------------------------------
function pad(str, length) {
str = '' + str;
while ( str.length < length ) {
str = '0' + str;
}
return str;
}
// first thing to do is make a simple timestamp function
var i = 0;
function timestamp() {
i++;
return (new Date()).toISOString() + '-' + pad(i, 8);
}
// ----------------------------------------------------------------------------
module.exports.timestamp = timestamp;
module.exports.newDyno = newDyno;
// ----------------------------------------------------------------------------
| Make sure the pad() function works correctly | Make sure the pad() function works correctly
| JavaScript | mit | chilts/modb-dyno-leveldb | ---
+++
@@ -12,6 +12,7 @@
// ----------------------------------------------------------------------------
function pad(str, length) {
+ str = '' + str;
while ( str.length < length ) {
str = '0' + str;
}
@@ -22,7 +23,7 @@
var i = 0;
function timestamp() {
i++;
- return (new Date()).toISOString() + '-' + pad(i, 16);
+ return (new Date()).toISOString() + '-' + pad(i, 8);
}
// ---------------------------------------------------------------------------- |
4dca2713e1cd68f08177a62e06f8ba1bfe6dc925 | src/native/index.js | src/native/index.js | import 'babel-polyfill';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { AppRegistry } from 'react-native';
import { NativeRouter } from 'react-router-native';
import config from 'react-native-config';
import Raven from 'raven-js';
import RavenRNPlugin from 'raven-js/plugins/react-native';
import App from './components/App';
import client from './configs/apollo';
import store from './store';
// Initialize Sentry error reporting
RavenRNPlugin(Raven);
Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID });
console.disableYellowBox = true;
// All of our configuration level stuff - routing, GraphQL, Native-Base theme
const Root = () => (
<ApolloProvider client={client} store={store}>
<NativeRouter>
<App />
</NativeRouter>
</ApolloProvider>
);
AppRegistry.registerComponent('strap', () => Root);
| import 'babel-polyfill';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { AppRegistry } from 'react-native';
import { NativeRouter } from 'react-router-native';
import config from 'react-native-config';
import Raven from 'raven-js';
import RavenRNPlugin from 'raven-js/plugins/react-native';
import App from './components/App';
import client from './configs/apollo';
import store from './store';
// Initialize Sentry error reporting
RavenRNPlugin(Raven);
Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID }).install();
console.disableYellowBox = true;
// All of our configuration level stuff - routing, GraphQL, Native-Base theme
const Root = () => (
<ApolloProvider client={client} store={store}>
<NativeRouter>
<App />
</NativeRouter>
</ApolloProvider>
);
AppRegistry.registerComponent('strap', () => Root);
| Add missing install call to raven config | feat(native): Add missing install call to raven config
| JavaScript | mit | meatwallace/strap,meatwallace/strap,meatwallace/strap | ---
+++
@@ -12,7 +12,7 @@
// Initialize Sentry error reporting
RavenRNPlugin(Raven);
-Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID });
+Raven.config(config.SENTRY_DSN, { release: config.RELEASE_ID }).install();
console.disableYellowBox = true;
|
78476fd9e92f986e641c5bb8d07ec37451d04fe9 | test/karma.js | test/karma.js | import karma from '../src/karma';
describe('karma config', function() {
it('should generate config', function() {
// Success is not throwing at this point. The simple karma tests
// will do the actual verification
karma({set() {}});
});
});
| /* eslint-disable no-process-env */
import karma from '../src/karma';
import {expect} from 'chai';
describe('karma config', function() {
const KARMA_BROWSER = process.env.KARMA_BROWSER;
afterEach(function() {
if (KARMA_BROWSER) {
process.env.KARMA_BROWSER = KARMA_BROWSER;
} else {
delete process.env.KARMA_BROWSER;
}
});
it('should generate config', function() {
// Success is not throwing at this point. The simple karma tests
// will do the actual verification
karma({set() {}});
});
it('should default to chrome browser', function() {
process.env.KARMA_BROWSER = '';
let config;
karma({set(_config) { config = _config; }});
expect(config.browsers).to.eql(['Chrome']);
});
it('should allow custom browser', function() {
process.env.KARMA_BROWSER = 'test!';
let config;
karma({set(_config) { config = _config; }});
expect(config.browsers).to.eql(['test!']);
});
});
| Add missing coverage for KARMA_BROWSER flag | Add missing coverage for KARMA_BROWSER flag | JavaScript | mit | kpdecker/linoleum-node,kpdecker/linoleum-electron,kpdecker/linoleum-electron,kpdecker/linoleum-webpack,kpdecker/linoleum | ---
+++
@@ -1,9 +1,36 @@
+/* eslint-disable no-process-env */
import karma from '../src/karma';
+import {expect} from 'chai';
+
describe('karma config', function() {
+ const KARMA_BROWSER = process.env.KARMA_BROWSER;
+ afterEach(function() {
+ if (KARMA_BROWSER) {
+ process.env.KARMA_BROWSER = KARMA_BROWSER;
+ } else {
+ delete process.env.KARMA_BROWSER;
+ }
+ });
+
it('should generate config', function() {
// Success is not throwing at this point. The simple karma tests
// will do the actual verification
karma({set() {}});
});
+
+ it('should default to chrome browser', function() {
+ process.env.KARMA_BROWSER = '';
+
+ let config;
+ karma({set(_config) { config = _config; }});
+ expect(config.browsers).to.eql(['Chrome']);
+ });
+ it('should allow custom browser', function() {
+ process.env.KARMA_BROWSER = 'test!';
+
+ let config;
+ karma({set(_config) { config = _config; }});
+ expect(config.browsers).to.eql(['test!']);
+ });
}); |
2307e2272e30d580b62ca2006dc99045cd63a9e8 | test/suite.js | test/suite.js | var siteName = "tlks.io";
// http://tlks.io/
casper.test.begin('Testing tlks.io UI', 2, function(test) {
var url = "http://tlks.io/";
casper.start(url);
casper.then(function() {
this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
});
casper.then(function() {
this.test.assertHttpStatus(200, siteName + ' is up');
});
casper.run(function() {
this.test.done();
this.exit();
});
});
| var siteName = "tlks.io";
// http://tlks.io/
casper.test.begin('Testing tlks.io UI', 2, function(test) {
var url = "http://tlks.io/";
casper.start(url);
casper.then(function() {
this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
});
casper.then(function() {
this.test.assertHttpStatus(200, siteName + ' is up');
});
casper.run(function() {
this.test.done();
});
});
// http://tlks.io/about
casper.test.begin('Testing tlks.io : About UI', 2, function(test) {
var url = "http://tlks.io/about";
casper.start(url);
casper.then(function() {
this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
});
casper.then(function() {
this.test.assertHttpStatus(200, siteName + ' is up');
});
casper.run(function() {
this.test.done();
this.exit();
});
});
| Test About for HTTP 200 | Test About for HTTP 200
| JavaScript | mit | tlksio/front,tlksio/front | ---
+++
@@ -17,6 +17,27 @@
casper.run(function() {
this.test.done();
+ });
+
+});
+
+// http://tlks.io/about
+casper.test.begin('Testing tlks.io : About UI', 2, function(test) {
+
+ var url = "http://tlks.io/about";
+
+ casper.start(url);
+
+ casper.then(function() {
+ this.test.assert(this.getCurrentUrl() === url, 'url is the one expected');
+ });
+
+ casper.then(function() {
+ this.test.assertHttpStatus(200, siteName + ' is up');
+ });
+
+ casper.run(function() {
+ this.test.done();
this.exit();
});
|
b4030f75471af2309f3bd4a75fff708f8cbc0eb5 | test/types.js | test/types.js | import test from 'ava';
import whenDomReady from '../';
test('whenDomReady is a function', t => {
t.is(typeof whenDomReady, 'function');
});
test('whenDomReady returns a Promise', t => {
t.true(whenDomReady() instanceof Promise);
});
test('whenDomReady.resume is a function', t => {
t.is(typeof whenDomReady.resume, 'function');
});
test('whenDomReady.resume returns a function that returns a promise', t => {
const returnValue = whenDomReady.resume();
t.is(typeof returnValue, 'function');
t.true(returnValue() instanceof Promise);
});
| import test from 'ava';
import jsdom from 'jsdom';
import whenDomReady from '../';
test('whenDomReady is a function', t => {
t.is(typeof whenDomReady, 'function');
});
test('whenDomReady returns a Promise', t => {
t.true(whenDomReady() instanceof Promise);
});
test('whenDomReady.resume is a function', t => {
t.is(typeof whenDomReady.resume, 'function');
});
test('whenDomReady.resume returns a function that returns a promise', t => {
const returnValue = whenDomReady.resume();
t.is(typeof returnValue, 'function');
t.true(returnValue() instanceof Promise);
});
test.cb('Promise value always resolves to undefined', t => {
t.plan(2);
const config = {
html: '',
onload: window => {
const promises = [];
promises.push(whenDomReady(() => 'foo', window.document).then(val => t.is(val, undefined)));
promises.push(whenDomReady(window.document).then(val => t.is(val, undefined)));
Promise.all(promises).then(() => t.end());
}
};
jsdom.env(config);
});
| Test Promise value always resolves to undefined | Test Promise value always resolves to undefined
| JavaScript | mit | lukechilds/when-dom-ready | ---
+++
@@ -1,4 +1,5 @@
import test from 'ava';
+import jsdom from 'jsdom';
import whenDomReady from '../';
test('whenDomReady is a function', t => {
@@ -18,3 +19,17 @@
t.is(typeof returnValue, 'function');
t.true(returnValue() instanceof Promise);
});
+
+test.cb('Promise value always resolves to undefined', t => {
+ t.plan(2);
+ const config = {
+ html: '',
+ onload: window => {
+ const promises = [];
+ promises.push(whenDomReady(() => 'foo', window.document).then(val => t.is(val, undefined)));
+ promises.push(whenDomReady(window.document).then(val => t.is(val, undefined)));
+ Promise.all(promises).then(() => t.end());
+ }
+ };
+ jsdom.env(config);
+}); |
3429aee6bfedfdce9498f73aab55f1039c59190b | examples/dev-kits/main.js | examples/dev-kits/main.js | module.exports = {
stories: ['./stories/*.*'],
webpack: async (config, { configType }) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
};
| module.exports = {
stories: ['./stories/*.*'],
webpack: async (config, { configType }) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
managerWebpack: async config => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /manager\.js$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
}),
};
| FIX manager using ESM in dev-kits example | FIX manager using ESM in dev-kits example
| JavaScript | mit | storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/storybook | ---
+++
@@ -20,4 +20,20 @@
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
+ managerWebpack: async config => ({
+ ...config,
+ module: {
+ ...config.module,
+ rules: [
+ ...config.module.rules,
+ {
+ test: /manager\.js$/,
+ loader: require.resolve('babel-loader'),
+ options: {
+ presets: [['react-app', { flow: false, typescript: true }]],
+ },
+ },
+ ],
+ },
+ }),
}; |
f16f1eae610c1bc78e8b0ebb3aca7bd4b717db19 | db/sequelizeConnect.js | db/sequelizeConnect.js | var Sequelize = require('sequelize'),
pg = require('pg').native;
module.exports = function(opts) {
if (!opts.DATABASE_URL) {
throw(new Error('Must specify DATABASE_URL in config.json or as environment variable'));
}
// TODO Support other databases
var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
db = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false,
native: true,
define: {
underscored: true
}
});
db.authenticate()
.error(function(err){
throw(new Error('Cannot connect to postgres db: ' + err));
})
.success(function(){
console.log('Connected to PostgreSQL db');
});
return db;
};
| var Sequelize = require('sequelize'),
pg = require('pg').native;
module.exports = function(opts) {
if (!opts.DATABASE_URL) {
throw(new Error('Must specify DATABASE_URL in config.json or as environment variable'));
}
// TODO Support other databases
var match = opts.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
db = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres',
port: match[4],
host: match[3],
logging: false,
native: true,
define: {
underscored: true
}
});
db.authenticate()
.error(function(err){
throw(new Error('Cannot connect to postgres db: ' + err));
})
.success(function(){
console.log('Connected to PostgreSQL db');
});
return db;
};
| Fix error where DATABASE_URL does not exist in environment | Fix error where DATABASE_URL does not exist in environment
| JavaScript | isc | bankonme/ripple-rest,ripple/ripple-rest,dmathewwws/my-ripple-rest,sparro/ripple-rest,lumberj/ripple-rest,xdv/ripple-rest,radr/radr-rest,sparro/ripple-rest,Treefunder/ripple-rest,dmathewwws/my-ripple-rest,hserang/ripple-rest,dmathewwws/my-ripple-rest,dinexcode/ripple-rest-dinex | ---
+++
@@ -8,7 +8,7 @@
// TODO Support other databases
- var match = process.env.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
+ var match = opts.DATABASE_URL.match(/postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/),
db = new Sequelize(match[5], match[1], match[2], {
dialect: 'postgres',
protocol: 'postgres', |
c971930ec987ae24f392f47c2b1b9b731f0cb4e9 | web/app/scripts/services/userservice.js | web/app/scripts/services/userservice.js | 'use strict';
/**
* @ngdoc service
* @name dormManagementToolApp.userService
* @description
* # userService
* Service in the dormManagementToolApp.
*/
angular.module('dormManagementToolApp')
.service('UserService', function () {
var mv = this;
this.user = JSON.parse(localStorage.getItem('user'));
this.getName = function () {
return mv.user.name;
};
this.getId = function () {
return mv.user.id;
};
this.getDormId = function () {
return mv.user.dorm_id;
};
});
| 'use strict';
/**
* @ngdoc service
* @name dormManagementToolApp.userService
* @description
* # userService
* Service in the dormManagementToolApp.
*/
angular.module('dormManagementToolApp')
.service('UserService', function () {
var mv = this;
this.user = JSON.parse(localStorage.getItem('user'));
this.getName = function () {
if (localStorage.getItem('user'))
if (mv.user != null)
return mv.user.name;
else {
mv.user = JSON.parse(localStorage.getItem('user'));
return mv.user.name
}
else
return null
};
this.getId = function () {
if (localStorage.getItem('user'))
if (mv.user != null)
return mv.user.id;
else {
mv.user = JSON.parse(localStorage.getItem('user'));
return mv.user.id
}
else
return null
};
this.getDormId = function () {
if (localStorage.getItem('user'))
if (mv.user != null)
return mv.user.dorm_id;
else {
mv.user = JSON.parse(localStorage.getItem('user'));
return mv.user.dorm_id
}
else
return null
};
});
| Check whether object exists before retrieving | Check whether object exists before retrieving
| JavaScript | mit | TomGijselinck/dorm-management-tool,TomGijselinck/dorm-management-tool,TomGijselinck/dorm-management-tool | ---
+++
@@ -12,12 +12,36 @@
var mv = this;
this.user = JSON.parse(localStorage.getItem('user'));
this.getName = function () {
- return mv.user.name;
+ if (localStorage.getItem('user'))
+ if (mv.user != null)
+ return mv.user.name;
+ else {
+ mv.user = JSON.parse(localStorage.getItem('user'));
+ return mv.user.name
+ }
+ else
+ return null
};
this.getId = function () {
- return mv.user.id;
+ if (localStorage.getItem('user'))
+ if (mv.user != null)
+ return mv.user.id;
+ else {
+ mv.user = JSON.parse(localStorage.getItem('user'));
+ return mv.user.id
+ }
+ else
+ return null
};
this.getDormId = function () {
- return mv.user.dorm_id;
+ if (localStorage.getItem('user'))
+ if (mv.user != null)
+ return mv.user.dorm_id;
+ else {
+ mv.user = JSON.parse(localStorage.getItem('user'));
+ return mv.user.dorm_id
+ }
+ else
+ return null
};
}); |
e05522cee60dd4d4baaadeee80869f063add486f | src/middleware/parsePayload.js | src/middleware/parsePayload.js | import getRawBody from 'raw-body'
export default (limit) => {
limit = (limit || '512kb')
return (req, res, next) => {
// Parse payload into buffer
getRawBody(req, {
length: req.headers['content-length'],
limit,
}, function (err, buffer) {
if (err) return next(err)
if (buffer.length) {
req.buffer = buffer
return next()
}
res.writeHead(204)
res.end('No binary payload provided.')
})
}
}
| import getRawBody from 'raw-body'
export default (limit) => {
limit = (limit || '512kb')
return (req, res, next) => {
// Parse payload into buffer
getRawBody(req, {
length: req.headers['content-length'],
limit,
}, function (err, buffer) {
if (err) return next(err)
if (buffer.length) {
req.buffer = buffer
return next()
}
res.writeHead(400)
res.end('No binary payload provided.')
})
}
}
| Fix error code for missing payload. | Fix error code for missing payload.
| JavaScript | mit | kukua/concava | ---
+++
@@ -16,7 +16,7 @@
return next()
}
- res.writeHead(204)
+ res.writeHead(400)
res.end('No binary payload provided.')
})
} |
7f4a80cbc397353af2d89199567a2db12179f9fa | components/widgets/psi/index.js | components/widgets/psi/index.js | import { Component } from 'react'
import 'isomorphic-fetch'
export default class PageSpeedInsights extends Component {
static defaultProps = {
filter_third_party_resources: true,
locale: 'de_DE',
strategy: 'desktop'
}
state = {
score: 0
}
async componentDidMount () {
let url = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
url += `?url=${this.props.url}`
url += `&filter_third_party_resources=${this.props.filter_third_party_resources}`
url += `&locale=${this.props.locale}`
url += `&strategy=${this.props.strategy}`
const res = await fetch(url) // eslint-disable-line no-undef
const json = await res.json()
this.setState({ score: json.ruleGroups.SPEED.score })
}
render () {
return (
<div>
<h3>PageSpeed Score</h3>
<p>{this.state.score}</p>
</div>
)
}
}
| import { Component } from 'react'
import 'isomorphic-fetch'
import Progress from '../../progress'
import Widget from '../../widget'
export default class PageSpeedInsights extends Component {
static defaultProps = {
filter_third_party_resources: true,
locale: 'de_DE',
strategy: 'desktop'
}
state = {
score: 0
}
async componentDidMount () {
const { url, filter_third_party_resources, locale, strategy } = this.props
let requestUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
requestUrl += `?url=${url}`
// eslint-disable-next-line camelcase
requestUrl += `&filter_third_party_resources=${filter_third_party_resources}`
requestUrl += `&locale=${locale}`
requestUrl += `&strategy=${strategy}`
// eslint-disable-next-line no-undef
const res = await fetch(requestUrl)
const json = await res.json()
this.setState({ score: json.ruleGroups.SPEED.score })
}
render () {
const { score } = this.state
return (
<Widget title='PageSpeed Score'>
<Progress value={score} />
</Widget>
)
}
}
| Use widget and progress component | Use widget and progress component
| JavaScript | mit | danielbayerlein/dashboard,danielbayerlein/dashboard | ---
+++
@@ -1,5 +1,7 @@
import { Component } from 'react'
import 'isomorphic-fetch'
+import Progress from '../../progress'
+import Widget from '../../widget'
export default class PageSpeedInsights extends Component {
static defaultProps = {
@@ -13,24 +15,28 @@
}
async componentDidMount () {
- let url = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
- url += `?url=${this.props.url}`
- url += `&filter_third_party_resources=${this.props.filter_third_party_resources}`
- url += `&locale=${this.props.locale}`
- url += `&strategy=${this.props.strategy}`
+ const { url, filter_third_party_resources, locale, strategy } = this.props
- const res = await fetch(url) // eslint-disable-line no-undef
+ let requestUrl = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed'
+ requestUrl += `?url=${url}`
+ // eslint-disable-next-line camelcase
+ requestUrl += `&filter_third_party_resources=${filter_third_party_resources}`
+ requestUrl += `&locale=${locale}`
+ requestUrl += `&strategy=${strategy}`
+
+ // eslint-disable-next-line no-undef
+ const res = await fetch(requestUrl)
const json = await res.json()
this.setState({ score: json.ruleGroups.SPEED.score })
}
render () {
+ const { score } = this.state
return (
- <div>
- <h3>PageSpeed Score</h3>
- <p>{this.state.score}</p>
- </div>
+ <Widget title='PageSpeed Score'>
+ <Progress value={score} />
+ </Widget>
)
}
} |
b1efa119cce7e6d14c7315221282402df6810f85 | src/chain.js | src/chain.js | import animate from './animate';
import {assign} from './utils';
const helpers = {
delay(msec) {
this._opts.delay = msec;
return this;
},
progress(fn, tween = null) {
this._props.tween = tween || this._props.tween || [1, 0];
this._opts.progress = fn;
return this;
}
};
export default function chain(el, props, opts) {
const fn = function fn(done) {
fn._opts.complete = done;
animate(fn._el, fn._props, fn._opts);
};
fn._el = el;
fn._props = props;
fn._opts = opts;
assign(fn, helpers);
return fn;
}
| import animate from './animate';
import {assign} from './utils';
const helpers = {
delay(msec) {
this._opts.delay = msec;
return this;
},
duration(msec) {
this._opts.duration = msec;
return this;
},
easing(name) {
this._opts.easing = name;
return this;
},
progress(fn, tween = null) {
this._props.tween = tween || this._props.tween || [1, 0];
this._opts.progress = fn;
return this;
},
display(value) {
this._opts.display = value;
return this;
},
visibility(value) {
this._opts.visibility = value;
return this;
},
loop(count) {
this._opts.loop = count;
return this;
}
};
export default function chain(el, props, opts) {
const fn = function fn(done) {
fn._opts.complete = done;
animate(fn._el, fn._props, fn._opts);
};
fn._el = el;
fn._props = props;
fn._opts = opts;
assign(fn, helpers);
return fn;
}
| Add helper functions to update velocity options | Add helper functions to update velocity options
| JavaScript | mit | ktsn/vq | ---
+++
@@ -7,9 +7,34 @@
return this;
},
+ duration(msec) {
+ this._opts.duration = msec;
+ return this;
+ },
+
+ easing(name) {
+ this._opts.easing = name;
+ return this;
+ },
+
progress(fn, tween = null) {
this._props.tween = tween || this._props.tween || [1, 0];
this._opts.progress = fn;
+ return this;
+ },
+
+ display(value) {
+ this._opts.display = value;
+ return this;
+ },
+
+ visibility(value) {
+ this._opts.visibility = value;
+ return this;
+ },
+
+ loop(count) {
+ this._opts.loop = count;
return this;
}
}; |
b247bd12cf14b573d098603d948fea9ab3199d2d | groups.js | groups.js | const groupRe = /^((:?\w|\-|,|, )+):\s*/i
, reverts = require('./reverts')
function toGroups (summary) {
summary = reverts.cleanSummary(summary)
var m = summary.match(groupRe)
return (m && m[1]) || ''
}
function cleanSummary (summary) {
return (summary || '').replace(groupRe, '')
}
function isReleaseCommit (summary) {
return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary)
|| /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Stable|LTS|Maintenance)\)/.test(summary)
|| /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary)
|| /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit
}
module.exports.toGroups = toGroups
module.exports.cleanSummary = cleanSummary
module.exports.isReleaseCommit = isReleaseCommit
| const groupRe = /^((:?\w|\-|,|, )+):\s*/i
, reverts = require('./reverts')
function toGroups (summary) {
summary = reverts.cleanSummary(summary)
var m = summary.match(groupRe)
return (m && m[1]) || ''
}
function cleanSummary (summary) {
return (summary || '').replace(groupRe, '')
}
function isReleaseCommit (summary) {
return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary)
|| /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Current|Stable|LTS|Maintenance)\)/.test(summary)
|| /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary)
|| /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit
}
module.exports.toGroups = toGroups
module.exports.cleanSummary = cleanSummary
module.exports.isReleaseCommit = isReleaseCommit
| Rename Node.js "Stable" releases to "Current" | Rename Node.js "Stable" releases to "Current"
| JavaScript | mit | rvagg/changelog-maker | ---
+++
@@ -16,7 +16,7 @@
function isReleaseCommit (summary) {
return /^Working on v?\d{1,2}\.\d{1,3}\.\d{1,3}$/.test(summary)
- || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Stable|LTS|Maintenance)\)/.test(summary)
+ || /^\d{4}-\d{2}-\d{2},? Version \d{1,2}\.\d{1,3}\.\d{1,3} (["'][A-Za-z ]+["'] )?\((Current|Stable|LTS|Maintenance)\)/.test(summary)
|| /^\d{4}-\d{2}-\d{2},? io.js v\d{1,2}\.\d{1,3}\.\d{1,3} Release/.test(summary)
|| /^\d+\.\d+\.\d+$/.test(summary) // `npm version X` style commit
} |
3e2e1baeb0208be9c40d6d208c31792a4cc8e842 | src/index.js | src/index.js | require("./stylesheets/main.less");
var settings = require("./settings");
var commands = codebox.require("core/commands");
var manager = new codebox.tabs.Manager({
tabMenu: false
});
manager.$el.addClass("component-panels");
// Add tabs to grid
codebox.app.grid.addView(manager, {
width: 20,
at: 0
});
// Render the tabs manager
manager.render();
// Toggle panels display
commands.register({
id: "view.panels.toggle",
title: "View: Toggle Side Bar",
run: function() {
settings.data.set("visible", !settings.data.get("visible"));
codebox.settings.save();
}
});
// Update visibility
settings.data.on("change:visible", function() {
manager._gridOptions.enabled = settings.data.get("visible");
codebox.app.grid.update();
});
// Make the tab manager global
codebox.panels = manager;
| require("./stylesheets/main.less");
var settings = require("./settings");
var commands = codebox.require("core/commands");
var manager = new codebox.tabs.Manager({
tabMenu: false
});
manager.$el.addClass("component-panels");
// Add tabs to grid
codebox.app.grid.addView(manager, {
width: 20,
at: 0
});
// Render the tabs manager
manager.render();
// Toggle panels display
commands.register({
id: "view.panels.toggle",
title: "View: Toggle Side Bar",
run: function() {
settings.data.set("visible", !settings.data.get("visible"));
codebox.settings.save();
}
});
// Update visibility
settings.data.on("change:visible", function() {
manager._gridOptions.enabled = settings.data.get("visible");
codebox.app.grid.update();
});
// Add to View menu
if (codebox.menubar) {
codebox.menubar.createMenu("view", {
caption: "Toggle Side Bar",
command: "view.panels.toggle"
});
}
// Make the tab manager global
codebox.panels = manager;
| Add command in view menu | Add command in view menu
| JavaScript | apache-2.0 | etopian/codebox-package-panels,CodeboxIDE/package-panels | ---
+++
@@ -33,5 +33,14 @@
codebox.app.grid.update();
});
+// Add to View menu
+if (codebox.menubar) {
+ codebox.menubar.createMenu("view", {
+ caption: "Toggle Side Bar",
+ command: "view.panels.toggle"
+ });
+}
+
+
// Make the tab manager global
codebox.panels = manager; |
eb04bb23e4d5496a8870a810ad201551915d11dd | src/index.js | src/index.js | import 'babel-polyfill';
const window = (typeof window !== 'undefined') ? window : {};
// Default config values.
const defaultConfig = {
loggingFunction: () => true,
loadInWorker: true, // FIXME cambia il nome
};
// Config used by the module.
const config = {};
// ***** Private functions *****
const formatError = (error = {}) => error;
// Public function.
const funcExecutor = (funcToCall, args = [], scope = undefined) => {
try {
funcToCall.apply(scope, ...args);
} catch (e) {
// TODO trova modo per fare la compose nativa
config.loggingFunction(formatError(e));
throw e;
}
};
// FIXME capire se è permesso avere la window come default
const attachGlobalHandler = (scope = window) => {
scope.onerror = () => {
// TODO trova modo per fare la compose nativa
config.loggingFunction(formatError({ ...arguments }));
return false;
};
};
export default function LogIt(userConfig = defaultConfig) {
Object.assign(config, userConfig);
return {
funcExecutor,
attachGlobalHandler,
};
}
| import 'babel-polyfill';
import Catcher from './catcher';
import Logger from './logger';
// Default config values.
const defaultConfig = {
scope: (typeof window !== 'undefined') ? window : {},
loggingFunction: () => true,
useWorker: true,
errorBuffer: 5,
};
// Config used by the module.
let config = {};
const sendErrorToLogger = formattedError => formattedError;
export default function LogIt(userConfig = {}) {
// TODO npm i --save-dev babel-preset-stage-2
config = { ...defaultConfig, ...userConfig };
return {
...Catcher,
};
}
| Move cathing functions to catch file | Move cathing functions to catch file
| JavaScript | mit | mattiaocchiuto/log-it | ---
+++
@@ -1,46 +1,26 @@
import 'babel-polyfill';
-const window = (typeof window !== 'undefined') ? window : {};
+import Catcher from './catcher';
+import Logger from './logger';
// Default config values.
const defaultConfig = {
+ scope: (typeof window !== 'undefined') ? window : {},
loggingFunction: () => true,
- loadInWorker: true, // FIXME cambia il nome
+ useWorker: true,
+ errorBuffer: 5,
};
// Config used by the module.
-const config = {};
+let config = {};
-// ***** Private functions *****
-const formatError = (error = {}) => error;
+const sendErrorToLogger = formattedError => formattedError;
-// Public function.
-const funcExecutor = (funcToCall, args = [], scope = undefined) => {
- try {
- funcToCall.apply(scope, ...args);
- } catch (e) {
- // TODO trova modo per fare la compose nativa
- config.loggingFunction(formatError(e));
-
- throw e;
- }
-};
-
-// FIXME capire se è permesso avere la window come default
-const attachGlobalHandler = (scope = window) => {
- scope.onerror = () => {
- // TODO trova modo per fare la compose nativa
- config.loggingFunction(formatError({ ...arguments }));
-
- return false;
- };
-};
-
-export default function LogIt(userConfig = defaultConfig) {
- Object.assign(config, userConfig);
+export default function LogIt(userConfig = {}) {
+ // TODO npm i --save-dev babel-preset-stage-2
+ config = { ...defaultConfig, ...userConfig };
return {
- funcExecutor,
- attachGlobalHandler,
+ ...Catcher,
};
} |
46f2979acf5216df541f0dcc1bbb969cba43aef9 | src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route } from 'react-router-dom';
import promise from 'redux-promise'
import PostsIndex from './components/posts_index';
import PostsNew from './components/posts_new';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Route path="/" component={PostsIndex} />
<Route path="/posts/new" component={PostsNew} />
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
| import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise'
import PostsIndex from './components/posts_index';
import PostsNew from './components/posts_new';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Switch>
<Route path="/posts/new" component={PostsNew} />
<Route path="/" component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
| Fix bug by adding Switch to the routes and more specific routes shown first in code | Fix bug by adding Switch to the routes and more specific routes shown first in code
| JavaScript | mit | kevinw123/ReduxBlog,kevinw123/ReduxBlog | ---
+++
@@ -2,7 +2,7 @@
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
-import { BrowserRouter, Route } from 'react-router-dom';
+import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise'
import PostsIndex from './components/posts_index';
@@ -15,8 +15,10 @@
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
- <Route path="/" component={PostsIndex} />
- <Route path="/posts/new" component={PostsNew} />
+ <Switch>
+ <Route path="/posts/new" component={PostsNew} />
+ <Route path="/" component={PostsIndex} />
+ </Switch>
</div>
</BrowserRouter>
</Provider> |
5205cc041e05ed01258681d88b438cbe58c464d2 | src/index.js | src/index.js | 'use strict';
var Promise = require('bluebird');
var sinon = require('sinon');
function thenable (promiseFactory) {
return Object.keys(Promise.prototype)
.filter(function (method) {
return Promise.prototype.hasOwnProperty(method) && method !== 'then';
})
.reduce(function (acc, method) {
acc[method] = function () {
var args = arguments;
var promise = this.then();
return promise[method].apply(promise, args);
};
return acc;
},
{
then: function (resolve, reject) {
return promiseFactory().then(resolve, reject);
}
});
}
function resolves (value) {
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve) {
resolve(value);
});
}));
}
sinon.stub.resolves = resolves;
sinon.behavior.resolves = resolves;
function rejects (err) {
if (typeof err === 'string') {
err = new Error(err);
}
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve, reject) {
reject(err);
});
}));
}
sinon.stub.rejects = rejects;
sinon.behavior.rejects = rejects;
module.exports = function (_Promise_) {
if (typeof _Promise_ !== 'function') {
throw new Error('A Promise constructor must be provided');
}
else {
Promise = _Promise_;
}
return sinon;
};
| 'use strict';
var Promise = require('bluebird');
var sinon = require('sinon');
function thenable (promiseFactory) {
return Object.getOwnPropertyNames(Promise.prototype)
.filter(function (method) {
return method !== 'then';
})
.reduce(function (acc, method) {
acc[method] = function () {
var args = arguments;
var promise = this.then();
return promise[method].apply(promise, args);
};
return acc;
},
{
then: function (resolve, reject) {
return promiseFactory().then(resolve, reject);
}
});
}
function resolves (value) {
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve) {
resolve(value);
});
}));
}
sinon.stub.resolves = resolves;
sinon.behavior.resolves = resolves;
function rejects (err) {
if (typeof err === 'string') {
err = new Error(err);
}
/*jshint validthis:true */
return this.returns(thenable(function () {
return new Promise(function (resolve, reject) {
reject(err);
});
}));
}
sinon.stub.rejects = rejects;
sinon.behavior.rejects = rejects;
module.exports = function (_Promise_) {
if (typeof _Promise_ !== 'function') {
throw new Error('A Promise constructor must be provided');
}
else {
Promise = _Promise_;
}
return sinon;
};
| Use Object.getOwnPropertyNames for compatibility with native promises | Use Object.getOwnPropertyNames for compatibility with native promises
| JavaScript | mit | bendrucker/sinon-as-promised,hongkheng/sinon-as-promised | ---
+++
@@ -4,9 +4,9 @@
var sinon = require('sinon');
function thenable (promiseFactory) {
- return Object.keys(Promise.prototype)
+ return Object.getOwnPropertyNames(Promise.prototype)
.filter(function (method) {
- return Promise.prototype.hasOwnProperty(method) && method !== 'then';
+ return method !== 'then';
})
.reduce(function (acc, method) {
acc[method] = function () { |
7d7f578ad3d163da121ffdd3d8ee4fd6500da318 | src/index.js | src/index.js | function createDynamicFunction(customAction) {
return Function('action', 'return function (){ return action.apply(this, [...arguments]) };')(customAction);
}
function formatFunctionName(type) {
let formattedName = '';
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
type.split('_').map((val, i) => {
if (i === 0) {
formattedName += val.toLowerCase();
} else {
formattedName += capitalizeFirstLetter(val.toLowerCase());
}
return true;
});
return formattedName;
}
function generalFactory(type, payloadTranslator) {
return function nomeDaSostituire(data) {
const action = {
type,
};
if (data) {
switch (typeof payloadTranslator) {
case 'function':
action.payload = payloadTranslator(data);
break;
default:
action.payload = data;
break;
}
}
return action;
};
}
module.exports = function actionsCreatorFactory(actionsConfig) {
const funcToExport = {};
actionsConfig.map((config) => {
let type = null;
let payload = null;
if (typeof config === 'string') {
type = config;
} else {
type = config.type;
payload = config.payload;
}
const functionName = formatFunctionName(type);
const customFunction = generalFactory(type, payload);
const customStringFunction = createDynamicFunction(customFunction);
funcToExport[functionName] = customStringFunction;
return true;
});
return funcToExport;
};
| function formatFunctionName(type) {
let formattedName = '';
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
type.split('_').map((val, i) => {
if (i === 0) {
formattedName += val.toLowerCase();
} else {
formattedName += capitalizeFirstLetter(val.toLowerCase());
}
return true;
});
return formattedName;
}
function generalFactory(type, payloadTranslator) {
return function nomeDaSostituire(data) {
const action = {
type,
};
if (data) {
switch (typeof payloadTranslator) {
case 'function':
action.payload = payloadTranslator(data);
break;
default:
action.payload = data;
break;
}
}
return action;
};
}
module.exports = function actionsCreatorFactory(actionsConfig) {
const funcToExport = {};
actionsConfig.map((config) => {
let type = null;
let payload = null;
if (typeof config === 'string') {
type = config;
} else {
type = config.type;
payload = config.payload;
}
const functionName = formatFunctionName(type);
const customFunction = generalFactory(type, payload);
const customStringFunction = customFunction;
funcToExport[functionName] = customStringFunction;
return true;
});
return funcToExport;
};
| Remove not useful function creator | Remove not useful function creator
| JavaScript | mit | mattiaocchiuto/actions-creator-factory | ---
+++
@@ -1,7 +1,3 @@
-function createDynamicFunction(customAction) {
- return Function('action', 'return function (){ return action.apply(this, [...arguments]) };')(customAction);
-}
-
function formatFunctionName(type) {
let formattedName = '';
@@ -60,7 +56,7 @@
const functionName = formatFunctionName(type);
const customFunction = generalFactory(type, payload);
- const customStringFunction = createDynamicFunction(customFunction);
+ const customStringFunction = customFunction;
funcToExport[functionName] = customStringFunction;
|
f406e16d6084c38a714fa532f93eccffe1a826b1 | js/simple_lottery.js | js/simple_lottery.js | let possibilites = 1;
for (let i = 53; i >= 48; i--) {
possibilites *= i;
}
console.log('The odds are %d to 1', possibilites);
| let possibilites = 1;
for (let i = 53; i >= 48; i--) {
possibilites *= i;
}
console.log('The odds are %d to 1', possibilites);
| Use standard JS indent width | Use standard JS indent width
| JavaScript | mit | rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple | ---
+++
@@ -1,5 +1,5 @@
let possibilites = 1;
for (let i = 53; i >= 48; i--) {
- possibilites *= i;
+ possibilites *= i;
}
console.log('The odds are %d to 1', possibilites); |
25ed756722fb765e3900d8b409b2b09a592fd310 | src/timer.js | src/timer.js | var Timer = (function(Event, Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime = undefined, endTime = undefined, solveTime = undefined;
var intervalID = undefined;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onWaiting() {
endTime = undefined;
}
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Waiting: onWaiting(); break;
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit("timer/running");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return (endTime || Util.getMilli()) - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
if (typeof module !== 'undefined')
module.exports = Timer;
| var Timer = (function(Event, Util) {
'use strict';
// Internal constants for the various timer states.
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
var startTime, endTime, solveTime;
var intervalID;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; }
function isRunning() { return state === Running; }
function onWaiting() {
endTime = undefined;
}
function onRunning() {
startTime = Util.getMilli();
intervalID = Util.setInterval(runningEmitter, 100);
}
function onStopped() {
endTime = Util.getMilli();
Util.clearInterval(intervalID);
setState(Waiting);
}
function setState(new_state) {
state = new_state;
switch(state) {
case Waiting: onWaiting(); break;
case Running: onRunning(); break;
case Stopped: onStopped(); break;
}
}
function runningEmitter() {
Event.emit("timer/running");
}
function triggerDown() {
if (isWaiting()) {
setState(Ready);
} else if (isRunning()) {
setState(Stopped);
}
}
function triggerUp() {
if (isReady()) {
setState(Running);
}
}
function getCurrent() {
return (endTime || Util.getMilli()) - startTime;
}
return {
triggerDown: triggerDown,
triggerUp: triggerUp,
getCurrent: getCurrent
};
});
if (typeof module !== 'undefined')
module.exports = Timer;
| Remove explicit assignment to undefined. | Remove explicit assignment to undefined.
jshint complains about these.
| JavaScript | mit | jjtimer/jjtimer-core | ---
+++
@@ -5,8 +5,8 @@
var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Stopped = 4;
var state = Waiting;
- var startTime = undefined, endTime = undefined, solveTime = undefined;
- var intervalID = undefined;
+ var startTime, endTime, solveTime;
+ var intervalID;
function isWaiting() { return state === Waiting; }
function isReady() { return state === Ready; } |
b4ded385e4cc520cc90ef46d3491ff0927d6ada8 | package/environments/development.js | package/environments/development.js | const Environment = require('../environment')
const { dev_server } = require('../config')
const assetHost = require('../asset_host')
const webpack = require('webpack')
module.exports = class extends Environment {
constructor() {
super()
if (dev_server.hmr) {
this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin())
this.plugins.set('NamedModules', new webpack.NamedModulesPlugin())
}
}
toWebpackConfig() {
const result = super.toWebpackConfig()
if (dev_server.hmr) {
result.output.filename = '[name]-[hash].js'
}
result.output.pathinfo = true
result.devtool = 'cheap-eval-source-map'
result.devServer = {
host: dev_server.host,
port: dev_server.port,
https: dev_server.https,
hot: dev_server.hmr,
contentBase: assetHost.path,
publicPath: assetHost.publicPath,
clientLogLevel: 'none',
compress: true,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': '*'
},
watchOptions: {
ignored: /node_modules/
},
stats: {
errorDetails: true
}
}
return result
}
}
| const Environment = require('../environment')
const { dev_server } = require('../config')
const assetHost = require('../asset_host')
const webpack = require('webpack')
module.exports = class extends Environment {
constructor() {
super()
if (dev_server.hmr) {
this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin())
this.plugins.set('NamedModules', new webpack.NamedModulesPlugin())
}
}
toWebpackConfig() {
const result = super.toWebpackConfig()
if (dev_server.hmr) {
result.output.filename = '[name]-[hash].js'
}
result.output.pathinfo = true
result.devtool = 'cheap-eval-source-map'
result.devServer = {
host: dev_server.host,
port: dev_server.port,
https: dev_server.https,
hot: dev_server.hmr,
contentBase: assetHost.path,
publicPath: assetHost.publicPath,
clientLogLevel: 'none',
compress: true,
historyApiFallback: true,
headers: {
'Access-Control-Allow-Origin': '*'
},
overlay: true,
watchContentBase: true,
watchOptions: {
ignored: /node_modules/
},
stats: {
errorDetails: true
}
}
return result
}
}
| Add overlay option for debugging | Add overlay option for debugging
| JavaScript | mit | rails/webpacker,usertesting/webpacker,gauravtiwari/webpacker,rails/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,usertesting/webpacker,rossta/webpacker,rossta/webpacker,gauravtiwari/webpacker,gauravtiwari/webpacker | ---
+++
@@ -33,6 +33,8 @@
headers: {
'Access-Control-Allow-Origin': '*'
},
+ overlay: true,
+ watchContentBase: true,
watchOptions: {
ignored: /node_modules/
}, |
8dc057b796b34150de611314f27800da70df690a | src/tizen/SplashScreenProxy.js | src/tizen/SplashScreenProxy.js | var exec = require('cordova/exec');
module.exports = {
splashscreen: {
win: null,
show: function() {
win= window.open('splashscreen.html');
},
hide: function() {
win.close();
win = null;
}
}
};
require("cordova/tizen/commandProxy").add("SplashScreen", module.exports);
| ( function() {
win = null;
module.exports = {
show: function() {
if ( win === null ) {
win = window.open('splashscreen.html');
}
},
hide: function() {
if ( win !== null ) {
win.close();
win = null;
}
}
};
require("cordova/tizen/commandProxy").add("SplashScreen", module.exports);
})();
| Correct structure, and only ever create one splashscreen window. | Proxy: Correct structure, and only ever create one splashscreen window.
| JavaScript | apache-2.0 | Panajev/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,petermetz/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,hebert-nr/spin,petermetz/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,hebert-nr/spin,hebert-nr/spin,petermetz/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,bamlab/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,Panajev/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,apache/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,bamlab/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,corimf/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,blackberry-webworks/cordova-plugin-splashscreen,purplecabbage/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,dpolivy/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,Choppel/cordova-plugin-splashscreen,kitmaxdevelop/cordova-plugin-splashscreen,journeyapps/cordova-splashscreen,Icenium/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,caseywebdev/cordova-plugin-splashscreen,Seedstars/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,petermetz/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,corimf/cordova-plugin-splashscreen,editweb/cordova-plugin-splashscreen,hebert-nr/spin,bamlab/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,Icenium/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,jfrumar/cordova-plugin-splashscreen,chrskrchr/cordova-plugin-splashscreen,Lazza/cordova-plugin-splashscreen,Newstex/cordova-plugin-splashscreen,IWAtech/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,Choppel/cordova-plugin-splashscreen,polyvi/cordova-plugin-splashscreen,asiFarran/cordova-plugin-splashscreen,hebert-nr/spin,Lazza/cordova-plugin-splashscreen,bamlab/cordova-plugin-splashscreen,revolunet/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen,sportstech/cordova-plugin-splashscreen | ---
+++
@@ -1,14 +1,16 @@
-var exec = require('cordova/exec');
+( function() {
+
+win = null;
module.exports = {
- splashscreen: {
- win: null,
+ show: function() {
+ if ( win === null ) {
+ win = window.open('splashscreen.html');
+ }
+ },
- show: function() {
- win= window.open('splashscreen.html');
- },
-
- hide: function() {
+ hide: function() {
+ if ( win !== null ) {
win.close();
win = null;
}
@@ -16,3 +18,5 @@
};
require("cordova/tizen/commandProxy").add("SplashScreen", module.exports);
+
+})(); |
69a0f5204ff7132e244e2866f69f3f7375e19318 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require bootstrap
// Replace link targets with JavaScript handlers to prevent iOS fullscreen web
// app from opening links in extra browser app
if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) {
$(function() {
$('body a[href]').click(function(e) {
e.preventDefault();
top.location.href = this;
});
});
}
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
//= require bootstrap
// Replace link targets with JavaScript handlers to prevent iOS fullscreen web
// app from opening links in extra browser app
if (navigator.userAgent.match(/(ipod|iphone|ipad)/i)) {
$(function() {
$('body a[href]').click(function(e) {
e.preventDefault();
top.location.href = this;
});
});
}
//hide notification bars after a few seconds
$('.alert').delay(10000).fadeOut('slow');
| Hide notification bars after a few seconds. | Hide notification bars after a few seconds.
Former-commit-id: 8dc17c173ff496666879f82c6544e0826d8d36f5 | JavaScript | mit | chaosdorf/mete,chaosdorf/mete,YtvwlD/mete,YtvwlD/mete,YtvwlD/mete,chaosdorf/mete,chaosdorf/mete,YtvwlD/mete | ---
+++
@@ -25,3 +25,6 @@
});
});
}
+
+//hide notification bars after a few seconds
+$('.alert').delay(10000).fadeOut('slow'); |
e69b09323f232fe2982ca8e764b432dbf39457c2 | web/static/js/app.js | web/static/js/app.js |
/*
VENDOR
*/
require( "material-design-lite" );
/*
APPLICATION
*/
const { initTerms } = require( "./term.js" );
initTerms();
|
/*
VENDOR
*/
require( "material-design-lite" );
import "phoenix_html"
/*
APPLICATION
*/
const { initTerms } = require( "./term.js" );
initTerms();
| Add import of phoenix_html back | Add import of phoenix_html back
Without this import the delete links stopped working
| JavaScript | mit | digitalnatives/course_planner,digitalnatives/course_planner,digitalnatives/course_planner | ---
+++
@@ -5,6 +5,8 @@
require( "material-design-lite" );
+ import "phoenix_html"
+
/*
APPLICATION
*/ |
e0a369fec549498071504e19070bfdd69c49478b | packages/react-jsx-highcharts/src/components/PlotBandLine/UsePlotBandLineLifecycle.js | packages/react-jsx-highcharts/src/components/PlotBandLine/UsePlotBandLineLifecycle.js | import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLineLifecycle(props, plotType) {
const { id = uuid, axisId, children, ...rest } = props;
const axis = useAxis(axisId);
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if (!plotbandline || modifiedProps !== false) {
if (!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
if (plotbandline) axis.removePlotBandOrLine(idRef.current);
axis.addPlotBandOrLine(opts, plotType);
setPlotbandline({
id: myId,
getPlotBandLine: () => {
const plotbandlineObject = axis.object.plotLinesAndBands.find(
plb => plb.id === myId
);
return plotbandlineObject;
}
});
}
});
useEffect(() => {
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
}, []);
return plotbandline;
}
| import React, { useRef, useEffect, useState } from 'react';
import uuid from 'uuid/v4';
import { attempt } from 'lodash-es';
import useModifiedProps from '../UseModifiedProps';
import useAxis from '../UseAxis';
export default function usePlotBandLineLifecycle(props, plotType) {
const { id = uuid, axisId, children, ...rest } = props;
const axis = useAxis(axisId);
const idRef = useRef();
const [plotbandline, setPlotbandline] = useState(null);
const modifiedProps = useModifiedProps(rest);
useEffect(() => {
if (!axis) return;
if (!plotbandline || modifiedProps !== false) {
if (!plotbandline) {
idRef.current = typeof id === 'function' ? id() : id;
}
const myId = idRef.current;
const opts = {
id: myId,
...rest
};
if (plotbandline) axis.removePlotBandOrLine(idRef.current);
axis.addPlotBandOrLine(opts, plotType);
setPlotbandline({
id: myId,
getPlotBandLine: () => {
if (axis && axis.object && axis.object.plotLinesAndBands) {
const plotbandlineObject = axis.object.plotLinesAndBands.find(
plb => plb.id === myId
);
return plotbandlineObject;
}
}
});
}
});
useEffect(() => {
return () => {
attempt(axis.removePlotBandOrLine, idRef.current);
};
}, []);
return plotbandline;
}
| Fix plotband label unmount crashing | Fix plotband label unmount crashing
| JavaScript | mit | whawker/react-jsx-highcharts,whawker/react-jsx-highcharts | ---
+++
@@ -29,10 +29,12 @@
setPlotbandline({
id: myId,
getPlotBandLine: () => {
- const plotbandlineObject = axis.object.plotLinesAndBands.find(
- plb => plb.id === myId
- );
- return plotbandlineObject;
+ if (axis && axis.object && axis.object.plotLinesAndBands) {
+ const plotbandlineObject = axis.object.plotLinesAndBands.find(
+ plb => plb.id === myId
+ );
+ return plotbandlineObject;
+ }
}
});
} |
3abec636fa6b84f8813855cbfca5c03cbbd8f9b7 | src/helper.js | src/helper.js | var fs = require("fs");
var path = require("path");
var Helper = module.exports = {
getConfig: function () {
var filename = process.env.SHOUT_CONFIG;
if(!filename || !fs.exists(filename)) {
filename = this.resolveHomePath("config.js");
if(!fs.exists(filename)) {
filename = path.resolve(__dirname, "..", "config");
}
}
return require(filename);
},
getHomeDirectory: function () {
return (
(process.env.SHOUT_CONFIG && fs.exists(process.env.SHOUT_CONFIG) && this.getConfig().home)
|| process.env.SHOUT_HOME
|| path.resolve(process.env.HOME, ".shout")
);
},
resolveHomePath: function () {
var fragments = [ Helper.HOME ].concat([].slice.apply(arguments));
return path.resolve.apply(path, fragments);
}
};
Helper.HOME = Helper.getHomeDirectory()
| var fs = require("fs");
var path = require("path");
var Helper = module.exports = {
getConfig: function () {
var filename = process.env.SHOUT_CONFIG;
if(!filename || !fs.existsSync(filename)) {
filename = this.resolveHomePath("config.js");
if(!fs.existsSync(filename)) {
filename = path.resolve(__dirname, "..", "config");
}
}
return require(filename);
},
getHomeDirectory: function () {
return (
(process.env.SHOUT_CONFIG && fs.existsSync(process.env.SHOUT_CONFIG) && this.getConfig().home)
|| process.env.SHOUT_HOME
|| path.resolve(process.env.HOME, ".shout")
);
},
resolveHomePath: function () {
var fragments = [ Helper.HOME ].concat([].slice.apply(arguments));
return path.resolve.apply(path, fragments);
}
};
Helper.HOME = Helper.getHomeDirectory()
| Fix fs.exists to existsSync where necessary | Fix fs.exists to existsSync where necessary
| JavaScript | mit | FryDay/lounge,realies/lounge,erming/shout,nickel715/shout,harishanand95/shout_irc_bouncer_openshift,rockhouse/lounge,cha2maru/shout,astorije/shout,metsjeesus/lounge,williamboman/shout,sebastiencs/lounge,williamboman/lounge,williamboman/lounge,thelounge/lounge,ScoutLink/lounge,metsjeesus/lounge,astorije/shout,olivierlambert/shout,libertysoft3/lounge-autoconnect,busseyl/shout,karen-irc/karen,run-project/shout,MaxLeiter/lounge,FryDay/lounge,ScoutLink/lounge,williamboman/lounge,Audio/shout,ScoutLink/lounge,MaxLeiter/shout,rockhouse/lounge,realies/lounge,harishanand95/shout_irc_bouncer_openshift,erming/shout,run-project/shout,FryDay/lounge,MaxLeiter/shout,metsjeesus/lounge,rockhouse/lounge,busseyl/shout,libertysoft3/lounge-autoconnect,cha2maru/shout,diddledan/shout,MaxLeiter/lounge,williamboman/shout,floogulinc/Shuo,togusafish/floogulinc-_-Shuo,MaxLeiter/lounge,Calinou/shout,diddledan/shout,togusafish/floogulinc-_-Shuo,nickel715/shout,Audio/shout,floogulinc/Shuo,sebastiencs/lounge,olivierlambert/shout,sebastiencs/lounge,thelounge/lounge,realies/lounge,libertysoft3/lounge-autoconnect,karen-irc/karen,Calinou/shout | ---
+++
@@ -4,9 +4,9 @@
var Helper = module.exports = {
getConfig: function () {
var filename = process.env.SHOUT_CONFIG;
- if(!filename || !fs.exists(filename)) {
+ if(!filename || !fs.existsSync(filename)) {
filename = this.resolveHomePath("config.js");
- if(!fs.exists(filename)) {
+ if(!fs.existsSync(filename)) {
filename = path.resolve(__dirname, "..", "config");
}
}
@@ -15,7 +15,7 @@
getHomeDirectory: function () {
return (
- (process.env.SHOUT_CONFIG && fs.exists(process.env.SHOUT_CONFIG) && this.getConfig().home)
+ (process.env.SHOUT_CONFIG && fs.existsSync(process.env.SHOUT_CONFIG) && this.getConfig().home)
|| process.env.SHOUT_HOME
|| path.resolve(process.env.HOME, ".shout")
); |
aa323b4dbd0a372c02db1e63757c8127226fcabb | example/future/src/channelTitleEditor/render.js | example/future/src/channelTitleEditor/render.js |
module.exports = (model, dispatch) => {
const root = document.createElement('div');
if (model.channelOnEdit === null) {
return root;
}
const c = model.channelOnEdit;
const title = model.channels[c].title;
const row = document.createElement('div');
row.classList.add('row');
row.classList.add('row-input');
const form = document.createElement('form');
const text = document.createElement('input');
text.type = 'text';
text.value = title;
form.appendChild(text);
const okBtn = document.createElement('button');
okBtn.innerHTML = 'OK';
okBtn.addEventListener('click', ev => {
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
form.appendChild(okBtn);
row.appendChild(form);
root.appendChild(row);
return root;
}
|
module.exports = (model, dispatch) => {
const root = document.createElement('div');
if (model.channelOnEdit === null) {
return root;
}
const c = model.channelOnEdit;
const title = model.channels[c].title;
const row = document.createElement('div');
row.classList.add('row');
row.classList.add('row-input');
const form = document.createElement('form');
const text = document.createElement('input');
text.type = 'text';
text.value = title;
form.appendChild(text);
const okBtn = document.createElement('button');
okBtn.type = 'button';
okBtn.innerHTML = 'OK';
form.appendChild(okBtn);
row.appendChild(form);
root.appendChild(row);
// Events
setTimeout(() => {
text.focus();
}, 200);
form.addEventListener('submit', ev => {
ev.preventDefault();
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
okBtn.addEventListener('click', ev => {
dispatch({
type: 'EDIT_CHANNEL_TITLE',
channel: c,
title: text.value
});
});
return root;
}
| Enable form submit by pressing enter | Enable form submit by pressing enter
| JavaScript | mit | axelpale/lately,axelpale/lately | ---
+++
@@ -18,11 +18,31 @@
const text = document.createElement('input');
text.type = 'text';
text.value = title;
-
form.appendChild(text);
const okBtn = document.createElement('button');
+ okBtn.type = 'button';
okBtn.innerHTML = 'OK';
+ form.appendChild(okBtn);
+
+ row.appendChild(form);
+ root.appendChild(row);
+
+ // Events
+
+ setTimeout(() => {
+ text.focus();
+ }, 200);
+
+ form.addEventListener('submit', ev => {
+ ev.preventDefault();
+ dispatch({
+ type: 'EDIT_CHANNEL_TITLE',
+ channel: c,
+ title: text.value
+ });
+ });
+
okBtn.addEventListener('click', ev => {
dispatch({
type: 'EDIT_CHANNEL_TITLE',
@@ -30,10 +50,6 @@
title: text.value
});
});
- form.appendChild(okBtn);
-
- row.appendChild(form);
- root.appendChild(row);
return root;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.