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 |
|---|---|---|---|---|---|---|---|---|---|---|
84c100bbd0fb6749fdcef577690d85beb7aebd34 | Gruntfile.js | Gruntfile.js | /*
* Copyright 2013, All Rights Reserved.
*
* Code licensed under the BSD License:
* https://github.com/node-gh/gh/blob/master/LICENSE.md
*
* @author Zeno Rocha <zno.rocha@gmail.com>
* @author Eduardo Lundgren <zno.rocha@gmail.com>
*/
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.initConfig({
jsbeautifier: {
files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'],
options: {
config: '.jsbeautifyrc'
}
}
});
grunt.registerTask('format', ['jsbeautifier']);
};
| /*
* Copyright 2013, All Rights Reserved.
*
* Code licensed under the BSD License:
* https://github.com/node-gh/gh/blob/master/LICENSE.md
*
* @author Zeno Rocha <zno.rocha@gmail.com>
* @author Eduardo Lundgren <zno.rocha@gmail.com>
*/
module.exports = function(grunt) {
grunt.initConfig({
jsbeautifier: {
files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'],
options: {
config: '.jsbeautifyrc'
}
},
jshint: {
options: grunt.file.readJSON('.jshintrc'),
gruntfile: 'Gruntfile.js',
files: {
src: [
'bin/*.js',
'lib/**/*.js'
]
},
test: {
options: {
globals: {
describe: true,
it: true,
beforeEach: true,
afterEach: true,
before: true,
after: true
}
},
src: 'test/**/*.js'
}
},
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.registerTask('format', ['jsbeautifier']);
};
| Add jshint as grunt task | Add jshint as grunt task
| JavaScript | bsd-3-clause | henvic/gh,TomzxForks/gh,modulexcite/gh,oouyang/gh,oouyang/gh,TomzxForks/gh,tomzx/gh,dustinryerson/gh,modulexcite/gh,henvic/gh,tomzx/gh,dustinryerson/gh | ---
+++
@@ -10,16 +10,41 @@
module.exports = function(grunt) {
- grunt.loadNpmTasks('grunt-jsbeautifier');
-
grunt.initConfig({
jsbeautifier: {
files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'],
options: {
config: '.jsbeautifyrc'
}
+ },
+
+ jshint: {
+ options: grunt.file.readJSON('.jshintrc'),
+ gruntfile: 'Gruntfile.js',
+ files: {
+ src: [
+ 'bin/*.js',
+ 'lib/**/*.js'
+ ]
+ },
+ test: {
+ options: {
+ globals: {
+ describe: true,
+ it: true,
+ beforeEach: true,
+ afterEach: true,
+ before: true,
+ after: true
+ }
+ },
+ src: 'test/**/*.js'
+ }
+ },
}
});
+ grunt.loadNpmTasks('grunt-contrib-jshint');
+ grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.registerTask('format', ['jsbeautifier']);
}; |
2818b0138520fbb0e9702cddef9e5d121b8f5ad1 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON( 'package.json' ),
env: {
casper: {
BASEURL: "http://www.google.com",
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:./node_modules/.bin",
PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs"
}
},
casperjs: {
options: {
includes: ['includes/include1.js'],
test: true
},
files: ['tests/**/*.js']
}
});
// casperJS Frontend tests
grunt.loadNpmTasks( 'grunt-casperjs' );
grunt.loadNpmTasks( 'grunt-env' );
// grunt for Frontend testing
grunt.registerTask('default', [ 'env:casper', 'casperjs']);
};
| module.exports = function(grunt) {
grunt.initConfig({
pkg : grunt.file.readJSON( 'package.json' ),
env: {
casper: {
BASEURL: "http://www.google.com",
PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs"
}
},
casperjs: {
options: {
includes: ['includes/include1.js'],
test: true
},
files: ['tests/**/*.js']
}
});
// casperJS Frontend tests
grunt.loadNpmTasks( 'grunt-casperjs' );
grunt.loadNpmTasks( 'grunt-env' );
grunt.registerTask('extendPATH', 'Add the npm bin dir to PATH', function() {
var pathDelimiter = ':';
var extPath = 'node_modules/.bin';
var pathArray = process.env.PATH.split( pathDelimiter );
pathArray.unshift( extPath );
process.env.PATH = pathArray.join( pathDelimiter );
grunt.log.writeln('Extending PATH to be ' + process.env.PATH);
});
// grunt for Frontend testing
grunt.registerTask('default', [ 'env:casper', 'extendPATH', 'casperjs']);
};
| Extend the PATH env var instead of replacing it | Extend the PATH env var instead of replacing it
| JavaScript | mit | smlgbl/grunt-casperjs-extra | ---
+++
@@ -4,7 +4,6 @@
env: {
casper: {
BASEURL: "http://www.google.com",
- PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:./node_modules/.bin",
PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs"
}
},
@@ -20,6 +19,15 @@
grunt.loadNpmTasks( 'grunt-casperjs' );
grunt.loadNpmTasks( 'grunt-env' );
+ grunt.registerTask('extendPATH', 'Add the npm bin dir to PATH', function() {
+ var pathDelimiter = ':';
+ var extPath = 'node_modules/.bin';
+ var pathArray = process.env.PATH.split( pathDelimiter );
+ pathArray.unshift( extPath );
+ process.env.PATH = pathArray.join( pathDelimiter );
+ grunt.log.writeln('Extending PATH to be ' + process.env.PATH);
+ });
+
// grunt for Frontend testing
- grunt.registerTask('default', [ 'env:casper', 'casperjs']);
+ grunt.registerTask('default', [ 'env:casper', 'extendPATH', 'casperjs']);
}; |
b68b04de0eec208ca389f93b271a52b3db5b8ed7 | Tester/src/Tester.js | Tester/src/Tester.js | /* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */
"use strict";
import {spawn} from 'child_process';
const EXPOSE_TEST_SCRIPT = './scripts/analyse';
class Tester {
constructor(file) {
this.file = file;
this.out = "";
}
build(done) {
let env = process.env;
env.EXPOSE_EXPECTED_PC = this.file.expectPaths;
let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], {
env: env
});
prc.stdout.setEncoding('utf8');
prc.stderr.setEncoding('utf8');
prc.stdout.on('data', data => this.out += data.toString());
prc.stderr.on('data', data => this.out += data.toString());
prc.on('close', code => done(code));
}
}
export default Tester;
| /* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */
"use strict";
import {spawn} from 'child_process';
const EXPOSE_TEST_SCRIPT = './scripts/analyse';
class Tester {
constructor(file) {
this.file = file;
this.out = "";
}
build(done) {
let env = process.env;
env.EXPOSE_EXPECTED_PC = this.file.expectPaths;
let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], {
env: env
});
prc.stdout.setEncoding('utf8');
prc.stderr.setEncoding('utf8');
prc.stdout.on('data', data => this.out += data.toString());
prc.stderr.on('data', data => this.out += data.toString());
const SECOND = 1000;
const TIME_WARNING = 30;
let longRunningMessage = setTimeout(() => console.log(`\rTEST WARNING: Test case ${this.file.path} is taking an excessive amount of time to complete (over ${TIME_WARNING}s)`), TIME_WARNING * SECOND);
prc.on('close', code => {
clearTimeout(longRunningMessage);
done(code)
});
}
}
export default Tester;
| Print warnings when tests are taking ages so we can see which ones it is | Print warnings when tests are taking ages so we can see which ones it is
| JavaScript | mit | ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE | ---
+++
@@ -27,7 +27,14 @@
prc.stdout.on('data', data => this.out += data.toString());
prc.stderr.on('data', data => this.out += data.toString());
- prc.on('close', code => done(code));
+ const SECOND = 1000;
+ const TIME_WARNING = 30;
+ let longRunningMessage = setTimeout(() => console.log(`\rTEST WARNING: Test case ${this.file.path} is taking an excessive amount of time to complete (over ${TIME_WARNING}s)`), TIME_WARNING * SECOND);
+
+ prc.on('close', code => {
+ clearTimeout(longRunningMessage);
+ done(code)
+ });
}
}
|
af38d84173285c9ee1203a4cb468a068ae15e2d7 | src/scripts/content/visualstudio.js | src/scripts/content/visualstudio.js | /*jslint indent: 2, plusplus: true */
/*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */
'use strict';
// Individual Work Item & Backlog page
togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () {
var link,
description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value,
project = $('.menu-item.l1-navigation-text.drop-visible .text').textContent.trim(),
container = $('.work-item-form-header-controls-container'),
vs_activeClassContent = $('.hub-list .menu-item.currently-selected').textContent.trim();
link = togglbutton.createTimerLink({
className: 'visual-studio-online',
description: description,
projectName: project
});
if (vs_activeClassContent === "Work Items*" || vs_activeClassContent === "Backlogs") {
container.appendChild(link);
}
});
| /*jslint indent: 2, plusplus: true */
/*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */
'use strict';
// Individual Work Item & Backlog page
togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () {
var link,
description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value,
project = $('.tfs-selector span').innerText,
container = $('.work-item-form-header-controls-container'),
vs_activeClassContent = $('.commandbar.header-bottom > .commandbar-item > .displayed').innerText;
link = togglbutton.createTimerLink({
className: 'visual-studio-online',
description: description,
projectName: project
});
if (vs_activeClassContent === "Work Items" || vs_activeClassContent === "Backlogs") {
container.appendChild(link);
}
});
| Change VSTS integration for markup change | Change VSTS integration for markup change
| JavaScript | bsd-3-clause | glensc/toggl-button,glensc/toggl-button,glensc/toggl-button | ---
+++
@@ -6,9 +6,9 @@
togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () {
var link,
description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value,
- project = $('.menu-item.l1-navigation-text.drop-visible .text').textContent.trim(),
+ project = $('.tfs-selector span').innerText,
container = $('.work-item-form-header-controls-container'),
- vs_activeClassContent = $('.hub-list .menu-item.currently-selected').textContent.trim();
+ vs_activeClassContent = $('.commandbar.header-bottom > .commandbar-item > .displayed').innerText;
link = togglbutton.createTimerLink({
className: 'visual-studio-online',
@@ -16,7 +16,7 @@
projectName: project
});
- if (vs_activeClassContent === "Work Items*" || vs_activeClassContent === "Backlogs") {
+ if (vs_activeClassContent === "Work Items" || vs_activeClassContent === "Backlogs") {
container.appendChild(link);
}
}); |
d4ca275b1229942dca73b4c4ed27a50f893dd6c9 | src/touch-action.js | src/touch-action.js | (function() {
function selector(v) {
return '[touch-action="' + v + '"]';
}
function rule(v) {
return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
}
var attrib2css = [
{
rule: 'none',
selectors: [
'none',
'user'
]
},
'pan-x',
'pan-y',
{
rule: 'pan-x pan-y',
selectors: [
'scroll',
'pan-x pan-y',
'pan-y pan-x'
]
}
];
var styles = '';
attrib2css.forEach(function(r) {
if (String(r) === r) {
styles += selector(r) + rule(r);
} else {
styles += r.selectors.map(selector) + rule(r.rule);
}
});
var el = document.createElement('style');
el.textContent = styles;
document.head.appendChild(el);
})();
| (function() {
function selector(v) {
return '[touch-action="' + v + '"]';
}
function rule(v) {
return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
}
var attrib2css = [
{
rule: 'none',
selectors: [
'none',
'user'
]
},
'pan-x',
'pan-y',
{
rule: 'pan-x pan-y',
selectors: [
'scroll',
'pan-x pan-y',
'pan-y pan-x'
]
}
];
var styles = '';
attrib2css.forEach(function(r) {
if (String(r) === r) {
styles += selector(r) + rule(r);
} else {
styles += r.selectors.map(selector) + rule(r.rule);
}
});
var el = document.createElement('style');
el.textContent = styles;
// Use querySelector instead of document.head to ensure that in
// ShadowDOM Polyfill that we have a wrapped head to append to.
var h = document.querySelector('head');
// document.write + document.head.appendChild = crazytown
// use insertBefore instead for correctness in ShadowDOM Polyfill
h.insertBefore(el, h.firstChild);
})();
| Fix inserting touch action stylesheet for Shadow DOM Polyfill | Fix inserting touch action stylesheet for Shadow DOM Polyfill
| JavaScript | bsd-3-clause | roblarsen/pointer-events.js | ---
+++
@@ -34,5 +34,10 @@
});
var el = document.createElement('style');
el.textContent = styles;
- document.head.appendChild(el);
+ // Use querySelector instead of document.head to ensure that in
+ // ShadowDOM Polyfill that we have a wrapped head to append to.
+ var h = document.querySelector('head');
+ // document.write + document.head.appendChild = crazytown
+ // use insertBefore instead for correctness in ShadowDOM Polyfill
+ h.insertBefore(el, h.firstChild);
})(); |
b7fcfc3e333218e30e10187523176d45b6bd297d | lib/Chunk.js | lib/Chunk.js | let zlib = require('zlib'),
NBT = require('kld-nbt'),
Tag = NBT.Tag,
ReadBuffer = NBT.ReadBuffer;
module.exports = class Chunk {
constructor() {
this.data = null;
}
static loadCompressedChunk(compressedData, compressionFormat) {
var data;
if (compressionFormat == 1) {
data = zlib.gunzipSync(compressedData);
}
else if (compressionFormat == 2) {
data = zlib.unzipSync(compressedData);
}
else {
throw new Error("Unrecognized chunk compression format: " + compressionFormat);
}
let readBuffer = new ReadBuffer(data);
let result = new Chunk();
result.data = Tag.readFromBuffer(readBuffer);
result.data.loadFromBuffer(readBuffer);
return result;
}
};
| let zlib = require('zlib'),
NBT = require('kld-nbt'),
Tag = NBT.Tag,
ReadBuffer = NBT.ReadBuffer,
utils = require('./utils');
module.exports = class Chunk {
constructor() {
this.data = null;
}
static loadCompressedChunk(compressedData, compressionFormat) {
var data;
if (compressionFormat == 1) {
data = zlib.gunzipSync(compressedData);
}
else if (compressionFormat == 2) {
data = zlib.unzipSync(compressedData);
}
else {
throw new Error("Unrecognized chunk compression format: " + compressionFormat);
}
let readBuffer = new ReadBuffer(data);
let result = new Chunk();
result.data = Tag.readFromBuffer(readBuffer);
result.data.loadFromBuffer(readBuffer);
return result;
}
getBlockType(position) {
let section = this.getSection(position);
var result = null;
if (section !== null) {
let blocks = section.findTag("Blocks");
let data = section.findTag("Data");
if (blocks !== null && data != null) {
let blockOffset = utils.blockOffsetFromPosition(position);
let type = blocks.byteValues[blockOffset];
let dataByte = blocks.byteValues[blockOffset >> 1];
let data = (blockOffset % 2 == 0) ? dataByte & 0x0F : (dataByte >> 4) & 0x0F;
result = {
type: type,
data: data
};
}
}
return result;
}
getSection(position) {
var result = null;
if (this.data !== null && 0 <= position.y && position.y < 256) {
let chunkY = position.y >> 4;
let level = this.data.findTag("Level");
let sections = level.findTag("Sections");
for (var i = 0; i < sections.elements.length; i++) {
let candidate = sections.elements[i];
let yIndex = candidate.findTag("Y");
if (yIndex !== null && yIndex.byteValue === chunkY) {
result = candidate;
break;
}
}
}
// TODO: generate new empty section for y index
return result;
}
};
| Add ability to get block type for a position | Add ability to get block type for a position
| JavaScript | bsd-3-clause | thelonious/kld-mc-world | ---
+++
@@ -1,7 +1,8 @@
let zlib = require('zlib'),
NBT = require('kld-nbt'),
Tag = NBT.Tag,
- ReadBuffer = NBT.ReadBuffer;
+ ReadBuffer = NBT.ReadBuffer,
+ utils = require('./utils');
module.exports = class Chunk {
constructor() {
@@ -29,4 +30,53 @@
return result;
}
+
+ getBlockType(position) {
+ let section = this.getSection(position);
+ var result = null;
+
+ if (section !== null) {
+ let blocks = section.findTag("Blocks");
+ let data = section.findTag("Data");
+
+ if (blocks !== null && data != null) {
+ let blockOffset = utils.blockOffsetFromPosition(position);
+
+ let type = blocks.byteValues[blockOffset];
+ let dataByte = blocks.byteValues[blockOffset >> 1];
+ let data = (blockOffset % 2 == 0) ? dataByte & 0x0F : (dataByte >> 4) & 0x0F;
+
+ result = {
+ type: type,
+ data: data
+ };
+ }
+ }
+
+ return result;
+ }
+
+ getSection(position) {
+ var result = null;
+
+ if (this.data !== null && 0 <= position.y && position.y < 256) {
+ let chunkY = position.y >> 4;
+ let level = this.data.findTag("Level");
+ let sections = level.findTag("Sections");
+
+ for (var i = 0; i < sections.elements.length; i++) {
+ let candidate = sections.elements[i];
+ let yIndex = candidate.findTag("Y");
+
+ if (yIndex !== null && yIndex.byteValue === chunkY) {
+ result = candidate;
+ break;
+ }
+ }
+ }
+
+ // TODO: generate new empty section for y index
+
+ return result;
+ }
}; |
e0a5f7e093df4ec140a6cc7828633bb6949e0475 | client/models/areaOfStudy.js | client/models/areaOfStudy.js | var _ = require('lodash');
var React = require('react');
var RequirementSet = require("./requirementSet");
var AreaOfStudy = React.createClass({
render: function() {
console.log('area-of-study render')
var areaDetails = []//getAreaOfStudy(this.props.name, this.props.type);
var requirementSets = _.map(areaDetails.sets, function(reqset) {
return RequirementSet( {key:reqset.description,
name: reqset.description,
needs: reqset.needs,
count: reqset.count,
requirements: reqset.reqs,
courses: this.props.courses});
}, this);
return React.DOM.article( {id:areaDetails.id, className:"area-of-study"},
React.DOM.details(null,
React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)),
requirementSets
)
);
}
});
module.exports = AreaOfStudy
| var _ = require('lodash');
var React = require('react');
var RequirementSet = require("./requirementSet");
var AreaOfStudy = React.createClass({
render: function() {
console.log('area-of-study render')
var areaDetails = this.props;//getAreaOfStudy(this.props.name, this.props.type);
var requirementSets = _.map(areaDetails.sets, function(reqset) {
return RequirementSet({
key:reqset.description,
name: reqset.description,
needs: reqset.needs,
count: reqset.count,
requirements: reqset.reqs,
courses: this.props.courses
});
}, this);
return React.DOM.article( {id:areaDetails.id, className:"area-of-study"},
React.DOM.details(null,
React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)),
requirementSets
)
);
}
});
module.exports = AreaOfStudy
| Clean up the area of study headings | Clean up the area of study headings
| JavaScript | agpl-3.0 | hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook | ---
+++
@@ -7,15 +7,17 @@
render: function() {
console.log('area-of-study render')
- var areaDetails = []//getAreaOfStudy(this.props.name, this.props.type);
+ var areaDetails = this.props;//getAreaOfStudy(this.props.name, this.props.type);
var requirementSets = _.map(areaDetails.sets, function(reqset) {
- return RequirementSet( {key:reqset.description,
+ return RequirementSet({
+ key:reqset.description,
name: reqset.description,
needs: reqset.needs,
count: reqset.count,
requirements: reqset.reqs,
- courses: this.props.courses});
+ courses: this.props.courses
+ });
}, this);
return React.DOM.article( {id:areaDetails.id, className:"area-of-study"}, |
a73401e5c10457066171a9ee5060363163ea4e7b | public/modules/core/directives/display-trial-data.client.directive.js | public/modules/core/directives/display-trial-data.client.directive.js | 'use strict';
// Display Trial Data for debugging
angular.module('core').directive('displayTrialData', function() {
return {
restrict: 'AE',
template: '<div><h3>Trial Data</h3><pre>Subject: {{trialDataJson()}}</pre></div>'
}
}); | 'use strict';
// Display Trial Data for debugging
angular.module('core').directive('displayTrialData', function() {
return {
restrict: 'AE',
template: '<div><h3>Trial Data</h3><pre>{{trialDataJson()}}</pre></div>'
}
}); | Remove 'Subject:' from displayTrialData text | Remove 'Subject:' from displayTrialData text
| JavaScript | mit | brennon/eim,brennon/eim,brennon/eim,brennon/eim | ---
+++
@@ -4,6 +4,6 @@
angular.module('core').directive('displayTrialData', function() {
return {
restrict: 'AE',
- template: '<div><h3>Trial Data</h3><pre>Subject: {{trialDataJson()}}</pre></div>'
+ template: '<div><h3>Trial Data</h3><pre>{{trialDataJson()}}</pre></div>'
}
}); |
899639def4990c5524d0ca462ebf8f6ab4ca59f5 | postcss.config.js | postcss.config.js | module.exports = () => ({
plugins: {
'postcss-easy-import': {
extensions: [
'.pcss',
'.css',
'.postcss',
'.sss'
]
},
'stylelint': {
configFile: '.stylelintrc'
},
'postcss-mixins': {},
'postcss-nesting': {},
'postcss-custom-media': {},
'postcss-selector-not': {},
'postcss-discard-comments': {},
'autoprefixer': {
browsers: [
'> 1%',
'last 2 versions',
'Firefox ESR',
'not ie <= 11'
]
},
'cssnano': {
preset: 'default'
},
'postcss-reporter': {
clearReportedMessages: true,
noPlugin: true
}
}
});
| module.exports = () => ({
plugins: {
'postcss-easy-import': {
extensions: [
'.pcss',
'.css',
'.postcss',
'.sss'
]
},
stylelint: {
configFile: '.stylelintrc'
},
'postcss-mixins': {},
'postcss-nesting': {},
'postcss-custom-media': {},
'postcss-selector-not': {},
'postcss-discard-comments': {},
autoprefixer: {
browsers: [
'> 1%',
'last 2 versions',
'Firefox ESR',
'not ie <= 11'
]
},
cssnano: {
preset: 'default'
},
'postcss-reporter': {
clearReportedMessages: true,
noPlugin: true
}
}
});
| Fix quoted postcss plugins name | chore: Fix quoted postcss plugins name
| JavaScript | mit | PolymerX/polymer-skeleton,PolymerX/polymer-skeleton | ---
+++
@@ -8,7 +8,7 @@
'.sss'
]
},
- 'stylelint': {
+ stylelint: {
configFile: '.stylelintrc'
},
'postcss-mixins': {},
@@ -16,7 +16,7 @@
'postcss-custom-media': {},
'postcss-selector-not': {},
'postcss-discard-comments': {},
- 'autoprefixer': {
+ autoprefixer: {
browsers: [
'> 1%',
'last 2 versions',
@@ -24,7 +24,7 @@
'not ie <= 11'
]
},
- 'cssnano': {
+ cssnano: {
preset: 'default'
},
'postcss-reporter': { |
46dd15ee2eef96cd693cea63d4a06b1056533356 | app/config/routes.js | app/config/routes.js | export default (app, route) => {
route.named('hello')
.maps('/hello')
.to('hello:index')
route.named('foo').maps('/foo/{bar}').to(async (req, res, {bar}) => {
res.end(`Foo: ${bar}`)
})
route.mounted('/bar', route => {
route.named('bar_index').maps('/').to(async (req, res) => {
res.end("Bar Index")
})
route.named('bar_create').maps('/create').to(async (req, res) => {
res.end("Bar Create")
})
})
route.named('missing').maps('/missing').to('default:missingRoute')
route.named('default').maps('/').to('default:index')
}
| export default (app, route) => {
route.named('hello')
.maps('/hello')
.to('hello:index')
route.named('foo').maps('/foo/{bar}').to(async ({req, res}, {bar}) => {
res.end(`Foo: ${bar}`)
})
route.mounted('/bar', route => {
route.named('bar_index').maps('/').to(async ({req, res}) => {
res.end("Bar Index")
})
route.named('bar_create').maps('/create').to(async ({req, res}) => {
res.end("Bar Create")
})
})
route.named('missing').maps('/missing').to('default:missingRoute')
route.named('default').maps('/').to('default:index')
}
| Fix args of inline controllers to use context | Fix args of inline controllers to use context
| JavaScript | mit | CHH/learning-node,CHH/learning-node | ---
+++
@@ -3,16 +3,16 @@
.maps('/hello')
.to('hello:index')
- route.named('foo').maps('/foo/{bar}').to(async (req, res, {bar}) => {
+ route.named('foo').maps('/foo/{bar}').to(async ({req, res}, {bar}) => {
res.end(`Foo: ${bar}`)
})
route.mounted('/bar', route => {
- route.named('bar_index').maps('/').to(async (req, res) => {
+ route.named('bar_index').maps('/').to(async ({req, res}) => {
res.end("Bar Index")
})
- route.named('bar_create').maps('/create').to(async (req, res) => {
+ route.named('bar_create').maps('/create').to(async ({req, res}) => {
res.end("Bar Create")
})
}) |
c40d33e07a2e835f67bbe10e0bad9ceb66bbbf67 | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require('webpack');
const WebpackNotifierPlugin = require('webpack-notifier');
const styleLintPlugin = require('stylelint-webpack-plugin');
const autoprefixer = require('autoprefixer');
const env = process.env.NODE_ENV;
module.exports = {
devtool: env === 'production' ? 'source-map' : 'eval',
entry: './src',
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js',
publicPath: '/',
},
plugins: env === 'production' ? [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
// dead_code: true,
},
}),
] : [
new styleLintPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: 'Next-gen Build' }),
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' },
{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
],
// noParse: /babel/,
},
postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
};
| const path = require('path');
const webpack = require('webpack');
const WebpackNotifierPlugin = require('webpack-notifier');
const styleLintPlugin = require('stylelint-webpack-plugin');
const env = process.env.NODE_ENV;
module.exports = {
devtool: env === 'production' ? 'source-map' : 'eval',
entry: './src',
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js',
},
plugins: env === 'production' ? [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
] : [
new styleLintPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: 'Next-gen Build' }),
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' },
],
},
};
| Simplify webpack, unsuccessfull at fixing sourcemap output | Simplify webpack, unsuccessfull at fixing sourcemap output
| JavaScript | mit | nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen | ---
+++
@@ -2,7 +2,6 @@
const webpack = require('webpack');
const WebpackNotifierPlugin = require('webpack-notifier');
const styleLintPlugin = require('stylelint-webpack-plugin');
-const autoprefixer = require('autoprefixer');
const env = process.env.NODE_ENV;
@@ -12,7 +11,6 @@
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js',
- publicPath: '/',
},
plugins: env === 'production' ? [
new webpack.DefinePlugin({
@@ -21,11 +19,7 @@
},
}),
new webpack.optimize.DedupePlugin(),
- new webpack.optimize.UglifyJsPlugin({
- compress: {
- // dead_code: true,
- },
- }),
+ new webpack.optimize.UglifyJsPlugin()
] : [
new styleLintPlugin(),
new webpack.HotModuleReplacementPlugin(),
@@ -35,10 +29,8 @@
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
+ { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' },
- { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
],
- // noParse: /babel/,
},
- postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
}; |
a7a6a8b5ea4a82660bb0ac7ed290e3d7a6b5c89b | src/store/checkout-store.js | src/store/checkout-store.js | import { Store } from 'consus-core/flux';
import StudentStore from './student-store';
let checkouts = [];
let checkoutsByActionId = new Object(null);
class CheckoutStore extends Store {
getCheckoutByActionId(actionId) {
return checkoutsByActionId[actionId];
}
}
const store = new CheckoutStore();
store.registerHandler('NEW_CHECKOUT', data => {
let checkout = {
studentId: data.studentId,
itemAddresses: data.itemAddresses
};
if (StudentStore.hasOverdueItem(data.studentId)){
throw new Error('Student has overdue item');
}else {
checkoutsByActionId[data.actionId] = checkout;
checkouts.push(checkout);
}
});
export default store;
| import { Store } from 'consus-core/flux';
import StudentStore from './student-store';
import ItemStore from './item-store';
let checkouts = [];
let checkoutsByActionId = new Object(null);
class CheckoutStore extends Store {
getCheckoutByActionId(actionId) {
return checkoutsByActionId[actionId];
}
}
const store = new CheckoutStore();
store.registerHandler('NEW_CHECKOUT', data => {
let checkout = {
studentId: data.studentId,
itemAddresses: data.itemAddresses
};
data.itemAddresses.forEach(itemAddress => {
if (ItemStore.getItemByAddress(itemAddress).status !== 'AVAILABLE') {
throw new Error('An item in the cart is not available for checkout.');
}
});
if (StudentStore.hasOverdueItem(data.studentId)) {
throw new Error('Student has overdue item');
} else {
checkoutsByActionId[data.actionId] = checkout;
checkouts.push(checkout);
}
});
export default store;
| Verify that the cart does not contain an unavailable item | Verify that the cart does not contain an unavailable item
| JavaScript | unlicense | TheFourFifths/consus,TheFourFifths/consus | ---
+++
@@ -1,5 +1,6 @@
import { Store } from 'consus-core/flux';
import StudentStore from './student-store';
+import ItemStore from './item-store';
let checkouts = [];
let checkoutsByActionId = new Object(null);
@@ -19,10 +20,14 @@
studentId: data.studentId,
itemAddresses: data.itemAddresses
};
-
- if (StudentStore.hasOverdueItem(data.studentId)){
+ data.itemAddresses.forEach(itemAddress => {
+ if (ItemStore.getItemByAddress(itemAddress).status !== 'AVAILABLE') {
+ throw new Error('An item in the cart is not available for checkout.');
+ }
+ });
+ if (StudentStore.hasOverdueItem(data.studentId)) {
throw new Error('Student has overdue item');
- }else {
+ } else {
checkoutsByActionId[data.actionId] = checkout;
checkouts.push(checkout);
} |
49b7b66ac4c3c40893e53e244a2cba7d915d235d | gulp/unit-tests.js | gulp/unit-tests.js | 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep');
gulp.task('test', function () {
var bowerDeps = wiredep({
directory: 'app/bower_components',
exclude: ['bootstrap-sass-official'],
dependencies: true,
devDependencies: true
});
var testFiles = bowerDeps.js.concat([
'app/scripts/**/*.js',
'test/unit/**/*.js'
]);
return gulp.src(testFiles)
.pipe($.karma({
configFile: 'test/karma.conf.js',
action: 'run'
}))
.on('error', function (err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
| 'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var wiredep = require('wiredep');
var bowerDeps = wiredep({
directory: 'app/bower_components',
exclude: ['bootstrap-sass-official'],
dependencies: true,
devDependencies: true
});
var testFiles = bowerDeps.js.concat([
'app/scripts/**/*.js',
'test/unit/**/*.js'
]);
gulp.task('test', function () {
return gulp.src(testFiles)
.pipe($.karma({
configFile: 'test/karma.conf.js',
action: 'run'
}))
.on('error', function (err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
gulp.task('watch:test', function () {
return gulp.src(testFiles)
.pipe($.karma({
configFile: 'test/karma.conf.js',
action: 'watch'
}))
.on('error', function (err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
| Refactor unit tests, add watch task. | Refactor unit tests, add watch task.
| JavaScript | mit | tvararu/angular-famous-playground | ---
+++
@@ -6,19 +6,19 @@
var wiredep = require('wiredep');
+var bowerDeps = wiredep({
+ directory: 'app/bower_components',
+ exclude: ['bootstrap-sass-official'],
+ dependencies: true,
+ devDependencies: true
+});
+
+var testFiles = bowerDeps.js.concat([
+ 'app/scripts/**/*.js',
+ 'test/unit/**/*.js'
+]);
+
gulp.task('test', function () {
- var bowerDeps = wiredep({
- directory: 'app/bower_components',
- exclude: ['bootstrap-sass-official'],
- dependencies: true,
- devDependencies: true
- });
-
- var testFiles = bowerDeps.js.concat([
- 'app/scripts/**/*.js',
- 'test/unit/**/*.js'
- ]);
-
return gulp.src(testFiles)
.pipe($.karma({
configFile: 'test/karma.conf.js',
@@ -29,3 +29,15 @@
throw err;
});
});
+
+gulp.task('watch:test', function () {
+ return gulp.src(testFiles)
+ .pipe($.karma({
+ configFile: 'test/karma.conf.js',
+ action: 'watch'
+ }))
+ .on('error', function (err) {
+ // Make sure failed tests cause gulp to exit non-zero
+ throw err;
+ });
+}); |
92e0b46c931e5aa3189db50ad758d5db00cbda9f | server/src/services/scripts/scripts-model.js | server/src/services/scripts/scripts-model.js | 'use strict';
// scripts-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const scriptsSchema = new Schema({
text: { type: String, required: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now }
});
const scriptsModel = mongoose.model('scripts', scriptsSchema);
module.exports = scriptsModel; | 'use strict';
// scripts-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const scriptsSchema = new Schema({
issue: { type: String, required: true },
title: { type: String, required: true },
text: { type: String, required: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now }
});
const scriptsModel = mongoose.model('scripts', scriptsSchema);
module.exports = scriptsModel; | Add script issue and title fields | Add script issue and title fields
| JavaScript | mit | andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps | ---
+++
@@ -9,6 +9,8 @@
const Schema = mongoose.Schema;
const scriptsSchema = new Schema({
+ issue: { type: String, required: true },
+ title: { type: String, required: true },
text: { type: String, required: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now } |
feabc4db34f6a1b15972f1c77306e83a53d61914 | src/AsyncCreatable.js | src/AsyncCreatable.js | import React from 'react';
import Select from './Select';
function reduce(obj, props = {}){
return Object.keys(obj)
.reduce((props, key) => {
const value = obj[key];
if (value !== undefined) props[key] = value;
return props;
}, props);
}
const AsyncCreatable = React.createClass({
displayName: 'AsyncCreatableSelect',
focus () {
this.select.focus();
},
render () {
return (
<Select.Async {...this.props}>
{(asyncProps) => (
<Select.Creatable {...this.props}>
{(creatableProps) => (
<Select
{...reduce(asyncProps, reduce(creatableProps, {}))}
onInputChange={(input) => {
creatableProps.onInputChange(input);
return asyncProps.onInputChange(input);
}}
ref={(ref) => {
this.select = ref;
creatableProps.ref(ref);
asyncProps.ref(ref);
}}
/>
)}
</Select.Creatable>
)}
</Select.Async>
);
}
});
module.exports = AsyncCreatable;
| import React from 'react';
import createClass from 'create-react-class';
import Select from './Select';
function reduce(obj, props = {}){
return Object.keys(obj)
.reduce((props, key) => {
const value = obj[key];
if (value !== undefined) props[key] = value;
return props;
}, props);
}
const AsyncCreatable = createClass({
displayName: 'AsyncCreatableSelect',
focus () {
this.select.focus();
},
render () {
return (
<Select.Async {...this.props}>
{(asyncProps) => (
<Select.Creatable {...this.props}>
{(creatableProps) => (
<Select
{...reduce(asyncProps, reduce(creatableProps, {}))}
onInputChange={(input) => {
creatableProps.onInputChange(input);
return asyncProps.onInputChange(input);
}}
ref={(ref) => {
this.select = ref;
creatableProps.ref(ref);
asyncProps.ref(ref);
}}
/>
)}
</Select.Creatable>
)}
</Select.Async>
);
}
});
module.exports = AsyncCreatable;
| Migrate rest of src overto createClass pkg | Migrate rest of src overto createClass pkg
| JavaScript | mit | submittable/react-select,serkanozer/react-select,OpenGov/react-select,mmpro/react-select,f-camacho/react-select,JedWatson/react-select,mobile5dev/react-select,JedWatson/react-select | ---
+++
@@ -1,4 +1,5 @@
import React from 'react';
+import createClass from 'create-react-class';
import Select from './Select';
function reduce(obj, props = {}){
@@ -10,7 +11,7 @@
}, props);
}
-const AsyncCreatable = React.createClass({
+const AsyncCreatable = createClass({
displayName: 'AsyncCreatableSelect',
focus () { |
3a1ea1dce763b04c46d2e13e39782d3249aa493f | example/src/main.js | example/src/main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Router from 'vue-router'
import App from './App'
import Home from './Home'
import Eagle from 'eagle.js'
import slideshows from './slideshows/slideshows.js'
/* eslint-disable no-new */
Vue.use(Eagle)
Vue.use(Router)
var routes = []
slideshows.list.forEach(function (slideshow) {
routes.push({
path: '/' + slideshow.infos.path,
component: slideshow
})
})
routes.push({ path: '*', component: Home })
routes.push({
path: '/',
name: 'Home',
component: Home
})
console.log(routes)
var router = new Router({
routes
// hashbang: true
// mode: 'history'
})
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
| // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Router from 'vue-router'
import App from './App'
import Home from './Home'
import Eagle from 'eagle.js'
import 'eagle.js/dist/eagle.css'
import slideshows from './slideshows/slideshows.js'
/* eslint-disable no-new */
Vue.use(Eagle)
Vue.use(Router)
var routes = []
slideshows.list.forEach(function (slideshow) {
routes.push({
path: '/' + slideshow.infos.path,
component: slideshow
})
})
routes.push({ path: '*', component: Home })
routes.push({
path: '/',
name: 'Home',
component: Home
})
console.log(routes)
var router = new Router({
routes
// hashbang: true
// mode: 'history'
})
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
| Load dist css file in example | Load dist css file in example
| JavaScript | isc | Zulko/eagle.js | ---
+++
@@ -6,6 +6,7 @@
import Home from './Home'
import Eagle from 'eagle.js'
+import 'eagle.js/dist/eagle.css'
import slideshows from './slideshows/slideshows.js'
/* eslint-disable no-new */ |
9bb7d328e9e64eead6af6bb0ff06dc147ceed2d0 | js/responsive-overlay-menu.js | js/responsive-overlay-menu.js | $(document).ready(function () {
$(".menu-btn a").click(function () {
$(".overlay").fadeToggle(200);
$(this).toggleClass('btn-open').toggleClass('btn-close');
});
$('.overlay').on('click', function () {
$(".overlay").fadeToggle(200);
$(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
});
$('.menu a').on('click', function () {
$(".overlay").fadeToggle(200);
$(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
});
}); | (function ($) {
$(".menu-btn a").click(function () {
event.preventDefault();
$(".overlay").fadeToggle(200);
$(this).toggleClass('btn-open').toggleClass('btn-close');
});
$('.overlay').on('click', function () {
$(".overlay").fadeToggle(200);
$(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
});
$('.menu a').on('click', function () {
event.preventDefault();
$(".overlay").fadeToggle(200);
$(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
});
}(jQuery));
| Fix js to preventDefault and work more places | Fix js to preventDefault and work more places | JavaScript | mit | marioloncarek/responsive-overlay-menu,marioloncarek/responsive-overlay-menu | ---
+++
@@ -1,6 +1,7 @@
-$(document).ready(function () {
+(function ($) {
$(".menu-btn a").click(function () {
+ event.preventDefault();
$(".overlay").fadeToggle(200);
$(this).toggleClass('btn-open').toggleClass('btn-close');
});
@@ -11,8 +12,9 @@
});
$('.menu a').on('click', function () {
+ event.preventDefault();
$(".overlay").fadeToggle(200);
$(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
});
-});
+}(jQuery)); |
1e615e33dc380729cfcf7ab52177c6a38dcf8b36 | lib/frame.js | lib/frame.js | /*
requestFrame / cancelFrame
*/"use strict"
var array = require("prime/es5/array")
var requestFrame = global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function(callback){
return setTimeout(callback, 1e3 / 60)
}
var callbacks = []
var iterator = function(time){
var split = callbacks.splice(0)
for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date)))
}
var cancel = function(callback){
var io = array.indexOf(callbacks, callback)
if (io > -1) callbacks.splice(io, 1)
}
var request = function(callback){
var i = callbacks.push(callback)
if (i === 1) requestFrame(iterator)
return function(){
cancel(callback)
}
}
exports.request = request
exports.cancel = cancel
| /*
requestFrame / cancelFrame
*/"use strict"
var array = require("prime/es5/array")
var requestFrame = global.requestAnimationFrame ||
global.webkitRequestAnimationFrame ||
global.mozRequestAnimationFrame ||
global.oRequestAnimationFrame ||
global.msRequestAnimationFrame ||
function(callback){
return setTimeout(callback, 1e3 / 60)
}
var callbacks = []
var iterator = function(time){
var split = callbacks.splice(0, callbacks.length)
for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date)))
}
var cancel = function(callback){
var io = array.indexOf(callbacks, callback)
if (io > -1) callbacks.splice(io, 1)
}
var request = function(callback){
var i = callbacks.push(callback)
if (i === 1) requestFrame(iterator)
return function(){
cancel(callback)
}
}
exports.request = request
exports.cancel = cancel
| Fix requestFrame in IE, where splice requires the deleteCount argument. | Fix requestFrame in IE, where splice requires the deleteCount argument.
| JavaScript | mit | dehenne/moofx,dehenne/moofx,kamicane/moofx | ---
+++
@@ -16,7 +16,7 @@
var callbacks = []
var iterator = function(time){
- var split = callbacks.splice(0)
+ var split = callbacks.splice(0, callbacks.length)
for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date)))
}
|
2ee1a0be3b01cc2a3cfbf8d6bc0f17f12dffbecc | eloquent_js/chapter04/ch04_ex04.js | eloquent_js/chapter04/ch04_ex04.js | function deepEqual(obj1, obj2) {
if (typeof obj1 != "object" || obj1 == null ||
typeof obj2 != "object" || obj2 == null) return obj1 === obj2;
let keys1 = Object.keys(obj1), keys2 = Object.keys(obj2);
if (keys1.length != keys2.length) return false;
for (let key of keys1) {
if (!(keys2.includes(key) &&
deepEqual(obj1[key], obj2[key]))) return false;
}
return true;
}
| function deepEqual(a, b) {
if (!(isObject(a) && isObject(b))) return a === b;
for (let key of Object.keys(a)) {
if (!(key in b)) return false;
if (!deepEqual(a[key], b[key])) return false;
}
return true;
}
function isObject(a) {
return typeof a == "object" && a != null;
}
| Add chapter 4, exercise 4 | Add chapter 4, exercise 4
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,14 +1,14 @@
-function deepEqual(obj1, obj2) {
- if (typeof obj1 != "object" || obj1 == null ||
- typeof obj2 != "object" || obj2 == null) return obj1 === obj2;
+function deepEqual(a, b) {
+ if (!(isObject(a) && isObject(b))) return a === b;
- let keys1 = Object.keys(obj1), keys2 = Object.keys(obj2);
+ for (let key of Object.keys(a)) {
+ if (!(key in b)) return false;
+ if (!deepEqual(a[key], b[key])) return false;
+ }
- if (keys1.length != keys2.length) return false;
+ return true;
+}
- for (let key of keys1) {
- if (!(keys2.includes(key) &&
- deepEqual(obj1[key], obj2[key]))) return false;
- }
- return true;
+function isObject(a) {
+ return typeof a == "object" && a != null;
} |
1ab6ab7f1e72bad5f39c55110ba65991f23c9df8 | examples/ruleset.js | examples/ruleset.js | var
EchoRule = require('../lib/rules/echo.js'),
Heartbeat = require('../lib/rules/heartbeat.js')
;
var rules = [];
rules.push(new EchoRule());
rules.push(new Heartbeat());
module.exports = rules;
| var
EchoRule = require('../lib/rules/echo.js'),
Heartbeat = require('../lib/rules/heartbeat.js'),
LoadAverage = require('../lib/rules/load-average.js')
;
var rules = [];
rules.push(new EchoRule());
rules.push(new Heartbeat());
rules.push(new LoadAverage({
warn: {
1: 1.5,
5: 0.9,
15: 0.7
},
critical: {
1: 1.5,
5: 1.5,
15: 1.5
}
}));
module.exports = rules;
| Add the `LoadAverage` rule to the example | Add the `LoadAverage` rule to the example
| JavaScript | isc | ceejbot/numbat-analyzer,npm/numbat-analyzer,numbat-metrics/numbat-analyzer | ---
+++
@@ -1,11 +1,24 @@
var
EchoRule = require('../lib/rules/echo.js'),
- Heartbeat = require('../lib/rules/heartbeat.js')
+ Heartbeat = require('../lib/rules/heartbeat.js'),
+ LoadAverage = require('../lib/rules/load-average.js')
;
var rules = [];
rules.push(new EchoRule());
rules.push(new Heartbeat());
+rules.push(new LoadAverage({
+ warn: {
+ 1: 1.5,
+ 5: 0.9,
+ 15: 0.7
+ },
+ critical: {
+ 1: 1.5,
+ 5: 1.5,
+ 15: 1.5
+ }
+}));
module.exports = rules; |
936735753f179190f6391f1b2105246e4d10cdab | public/js/view.js | public/js/view.js | (function() {
"use strict";
var lastKeys = "";
function fetchRedlines() {
var baseUrl = $('#baseUrl').val();
var artworkUrl = $('#artworkUrl').val();
$.get(baseUrl + 'index').done(function(keys) {
if (lastKeys === keys) {
return;
}
lastKeys = keys;
var items = [];
var requests = $.map(keys.split('\n'), function(key) {
return $.get(baseUrl + key).done(function(data) {
var json = JSON.parse(data);
var feedback = $('<div/>').text(json.feedback).addClass('feedback');
var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl))
.append($('<img/>').attr('src', json.image).addClass('redline'))
.addClass('drawing');
var item = $('<div/>').append(feedback)
.append(artwork)
.attr('id', key);
items.push(item);
}).fail(function() {
console.log('Failed to fetch data for key ' + key);
});
});
$.when.apply($, requests).done(function () {
$('#items').empty();
$.each(items, function(i, item) {
$('#items').append(item);
});
$('#submissions').text(items.length);
});
}).fail(function() {
console.log('Failed to fetch index file');
});
}
$(function() {
fetchRedlines();
setInterval(fetchRedlines, 1000);
});
})();
| (function() {
"use strict";
var lastKeys = "";
function fetchRedlines() {
var baseUrl = $('#baseUrl').val();
var artworkUrl = $('#artworkUrl').val();
$.get(baseUrl + 'index').done(function(keys) {
if (lastKeys === keys) {
return;
}
lastKeys = keys;
var items = [];
var requests = $.map(keys.split('\n'), function(key) {
return $.get(baseUrl + key).done(function(data) {
var json = JSON.parse(data);
var feedback = $('<div/>').text(json.feedback).addClass('feedback');
var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl))
.append($('<img/>').attr('src', json.image).addClass('redline'))
.addClass('drawing');
var item = $('<div/>').append(feedback)
.append(artwork)
.attr('id', key);
items.push(item);
}).fail(function() {
console.log('Failed to fetch data for key ' + key);
});
});
$.when.apply($, requests).done(function () {
$('#items').empty();
$.each(items, function(i, item) {
$('#items').append(item);
});
$('#submissions').text(items.length);
});
}).fail(function() {
console.log('Failed to fetch index file');
});
}
$(function() {
fetchRedlines();
setInterval(fetchRedlines, 5000);
});
})();
| Increase interval to 5 seconds | Increase interval to 5 seconds
| JavaScript | bsd-3-clause | Nullreff/redline,Nullreff/redline,Nullreff/redline | ---
+++
@@ -43,6 +43,6 @@
$(function() {
fetchRedlines();
- setInterval(fetchRedlines, 1000);
+ setInterval(fetchRedlines, 5000);
});
})(); |
36b78042d3f5d38bb7ca96adb6cb1c0ae40deb49 | main.js | main.js | var electron = require('electron'); // Module to control application life.
var process = require('process');
const {app} = electron;
const {BrowserWindow} = electron;
let win; // Ensure that our win isn't garbage collected
app.on('ready', function() {
// Create the browser window.
if (process.platform == 'win32')
win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false});
else
win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false});
// Load the main interface
win.loadURL('file://' + __dirname + '/index.html');
// Uncomment this line to open the DevTools upon launch.
//win.webContents.openDevTools({'mode':'undocked'});
win.on('closed', function() {
// Dereference the window object so our app exits
win = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
| var electron = require('electron'); // Module to control application life.
var process = require('process');
const {app} = electron;
const {BrowserWindow} = electron;
let win; // Ensure that our win isn't garbage collected
app.on('ready', function() {
// Create the browser window.
if (process.platform == 'win32')
win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false});
else
win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false});
// Load the main interface
win.loadURL('file://' + __dirname + '/index.html');
// Uncomment this line to open the DevTools upon launch.
//win.webContents.openDevTools({'mode':'undocked'});
//Disable the menubar for dev versions
win.setMenu(null);
win.on('closed', function() {
// Dereference the window object so our app exits
win = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
| Disable the menubar when running from source | Disable the menubar when running from source
| JavaScript | mit | NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher | ---
+++
@@ -17,6 +17,9 @@
// Uncomment this line to open the DevTools upon launch.
//win.webContents.openDevTools({'mode':'undocked'});
+ //Disable the menubar for dev versions
+ win.setMenu(null);
+
win.on('closed', function() {
// Dereference the window object so our app exits
win = null; |
e8f93882daad04d6a74c864ac2c32d301c199254 | lib/index.js | lib/index.js | var browserify = require('browserify-middleware')
var babelify = require('babelify')
module.exports = function (entries, brOptions, baOptions) {
brOptions = brOptions || {}
brOptions.transform = brOptions.transform || []
baOptions = baOptions || {}
baOptions.stage = baOptions.stage || 1
brOptions.transform.unshift(babelify.configure(baOptions))
return browserify(entries, brOptions)
}
| var browserify = require('browserify-middleware')
var babelify = require('babelify')
function babelifyMiddleware(entries, brOptions, baOptions) {
brOptions = brOptions || {}
brOptions.transform = brOptions.transform || []
baOptions = baOptions || {}
baOptions.stage = baOptions.stage || 1
brOptions.transform.unshift(babelify.configure(baOptions))
return browserify(entries, brOptions)
}
babelifyMiddleware.browserifySettings = browserify.settings
module.exports = babelifyMiddleware
| Make browserify default settings accessible | Make browserify default settings accessible
| JavaScript | mit | luisfarzati/express-babelify-middleware,luisfarzati/express-babelify-middleware | ---
+++
@@ -1,7 +1,7 @@
var browserify = require('browserify-middleware')
var babelify = require('babelify')
-module.exports = function (entries, brOptions, baOptions) {
+function babelifyMiddleware(entries, brOptions, baOptions) {
brOptions = brOptions || {}
brOptions.transform = brOptions.transform || []
baOptions = baOptions || {}
@@ -10,3 +10,7 @@
return browserify(entries, brOptions)
}
+
+babelifyMiddleware.browserifySettings = browserify.settings
+
+module.exports = babelifyMiddleware |
649c9c09c9a66e085b33346f5062976801543423 | examples/routing/src/reducers/user.js | examples/routing/src/reducers/user.js | /* Define your initial state here.
*
* If you change the type from object to something else, do not forget to update
* src/container/App.js accordingly.
*/
const initialState = {};
module.exports = function(state = initialState, action) {
/* Keep the reducer clean - do not mutate the original state. */
//let nextState = Object.assign({}, state);
switch(action.type) {
/*
case 'YOUR_ACTION': {
// Modify next state depending on the action and return it
return nextState;
} break;
*/
default: {
/* Return original state if no actions were consumed. */
return state;
}
}
}
| import {LOGIN} from '../actions/const';
/* Define your initial state here.
*
* If you change the type from object to something else, do not forget to update
* src/container/App.js accordingly.
*/
const initialState = {
login: false
};
module.exports = function(state = initialState, action) {
/* Keep the reducer clean - do not mutate the original state. */
let nextState = Object.assign({}, state);
switch(action.type) {
case LOGIN: {
nextState.login = true;
return nextState;
}
default: {
/* Return original state if no actions were consumed. */
return state;
}
}
}
| Change login state When LOGIN action was triggered. | Change login state When LOGIN action was triggered.
| JavaScript | mit | stylesuxx/generator-react-webpack-redux,stylesuxx/generator-react-webpack-redux | ---
+++
@@ -1,21 +1,24 @@
+import {LOGIN} from '../actions/const';
+
/* Define your initial state here.
*
* If you change the type from object to something else, do not forget to update
* src/container/App.js accordingly.
*/
-const initialState = {};
+const initialState = {
+ login: false
+};
module.exports = function(state = initialState, action) {
/* Keep the reducer clean - do not mutate the original state. */
- //let nextState = Object.assign({}, state);
+ let nextState = Object.assign({}, state);
switch(action.type) {
- /*
- case 'YOUR_ACTION': {
- // Modify next state depending on the action and return it
+ case LOGIN: {
+ nextState.login = true;
return nextState;
- } break;
- */
+ }
+
default: {
/* Return original state if no actions were consumed. */
return state; |
e3e031e4634522e0764a722ad37791c9913ce1cd | domStorage.js | domStorage.js | function DomStorage() {
var cache = {};
function getFromCache(selector){
if(!cache[selector]){
cache[selector] = $(selector);
}
return cache[selector];
}
function updateInCache(selector){
if(!cache[selector]){
throw new TypeError("The selector you want to update does not exist in cache");
}
else{
cache[selector] = $(selector);
}
}
function getCache(){
return cache;
}
function flushCache(){
cache = {};
}
return {
get:getFromCache,
update:updateInCache,
getCache:getCache,
flush:flushCache
};
}
| function DomStorage() {
var cache = {};
function getFromCache(selector){
if(!selector)
throw new TypeError("Please provide a selector");
if(!cache[selector]){
cache[selector] = $(selector);
}
return cache[selector];
}
function updateInCache(selector){
if(!selector)
throw new TypeError("Please provide a selector");
if(!cache[selector]){
throw new TypeError("The selector you want to update does not exist in cache");
}
else{
cache[selector] = $(selector);
}
}
function getCache(){
return cache;
}
function flushCache(){
cache = {};
}
return {
get:getFromCache,
update:updateInCache,
getCache:getCache,
flush:flushCache
};
}
class DomCache{
constructor{
}
} | Check if a user has given a valid selector when trying to get or update | Check if a user has given a valid selector when trying to get or update
| JavaScript | mit | kounelios13/Dom-Storage,kounelios13/Dom-Storage | ---
+++
@@ -1,12 +1,16 @@
function DomStorage() {
var cache = {};
function getFromCache(selector){
+ if(!selector)
+ throw new TypeError("Please provide a selector");
if(!cache[selector]){
cache[selector] = $(selector);
}
return cache[selector];
}
function updateInCache(selector){
+ if(!selector)
+ throw new TypeError("Please provide a selector");
if(!cache[selector]){
throw new TypeError("The selector you want to update does not exist in cache");
}
@@ -27,3 +31,8 @@
flush:flushCache
};
}
+class DomCache{
+ constructor{
+
+ }
+} |
3ff467f3c1a3c5c9ea911403373229650760850e | bin/server.js | bin/server.js | import config from '../config'
import server from '../server/main'
import _debug from 'debug'
const debug = _debug('app:bin:server')
const port = config.server_port
const host = config.server_host
server.listen(port)
debug(`Server is now running at ${host}:${port}.`)
| import config from '../config'
import server from '../server/main'
import _debug from 'debug'
const debug = _debug('app:bin:server')
const port = config.server_port
const host = config.server_host
server.listen(port)
debug(`Server is now running at http://${host}:${port}.`)
| Make the app link clickable | chore(compile): Make the app link clickable
This small change makes the link clickable in some terminal emulators (like xfce-terminal), which makes it easier to open the app in a browser.
| JavaScript | mit | josedab/react-redux-i18n-starter-kit,josedab/react-redux-i18n-starter-kit | ---
+++
@@ -7,5 +7,5 @@
const host = config.server_host
server.listen(port)
-debug(`Server is now running at ${host}:${port}.`)
+debug(`Server is now running at http://${host}:${port}.`) |
e1ee7a46a12715ce5d8bcfc7bf3180a6b254f228 | client/common/layout/layout.js | client/common/layout/layout.js | 'use strict';
var _ = require('lodash');
//
// Observe quicksearch focus to tweak icon style
//
N.wire.once('navigate.done', function () {
$('.navbar-search .search-query')
.focus(function () { $(this).next('div').addClass('focused'); })
.blur(function () { $(this).next('div').removeClass('focused'); });
});
//
// Update "active" tab of the navbar_menu when moving to another page.
//
N.wire.on('navigate.done', function navbar_menu_change_active(target) {
var apiPath = target.apiPath, tabs, active;
function matchLengthOf(subject) {
var index = 0
, length = Math.min(apiPath.length, subject.length);
while (index < length &&
subject.charCodeAt(index) === apiPath.charCodeAt(index)) {
index += 1;
}
return index;
}
tabs = $('#navbar_menu').find('[data-api-path]');
tabs.removeClass('active');
// Select the most specific tab - with the longest API path match.
active = _.max(tabs, function (tab) {
return matchLengthOf($(tab).attr('data-api-path'));
});
$(active).addClass('active');
});
| 'use strict';
var _ = require('lodash');
//
// Observe quicksearch focus to tweak icon style
//
N.wire.once('navigate.done', function () {
$('.navbar-search .search-query')
.focus(function () { $(this).next('div').addClass('focused'); })
.blur(function () { $(this).next('div').removeClass('focused'); });
});
//
// Update "active" tab of the navbar_menu when moving to another page.
//
N.wire.on('navigate.done', function navbar_menu_change_active(target) {
var targetPath = target.apiPath.split('.'), tabs, active;
tabs = $('#navbar_menu').find('[data-api-path]');
tabs.removeClass('active');
// Select the most specific tab - with the longest API path match.
active = _.max(tabs, function (tab) {
var tabPath = $(tab).data('apiPath').split('.')
, index = -1
, length = Math.min(tabPath.length, targetPath.length);
do { index += 1; }
while (index < length && tabPath[index] === targetPath[index]);
return index;
});
$(active).addClass('active');
});
| Fix tab selection on the navbar. | Fix tab selection on the navbar.
Split API paths by dots to prevent matching of the dots.
| JavaScript | mit | nodeca/nodeca.core,nodeca/nodeca.core | ---
+++
@@ -18,26 +18,21 @@
// Update "active" tab of the navbar_menu when moving to another page.
//
N.wire.on('navigate.done', function navbar_menu_change_active(target) {
- var apiPath = target.apiPath, tabs, active;
-
- function matchLengthOf(subject) {
- var index = 0
- , length = Math.min(apiPath.length, subject.length);
-
- while (index < length &&
- subject.charCodeAt(index) === apiPath.charCodeAt(index)) {
- index += 1;
- }
-
- return index;
- }
+ var targetPath = target.apiPath.split('.'), tabs, active;
tabs = $('#navbar_menu').find('[data-api-path]');
tabs.removeClass('active');
// Select the most specific tab - with the longest API path match.
active = _.max(tabs, function (tab) {
- return matchLengthOf($(tab).attr('data-api-path'));
+ var tabPath = $(tab).data('apiPath').split('.')
+ , index = -1
+ , length = Math.min(tabPath.length, targetPath.length);
+
+ do { index += 1; }
+ while (index < length && tabPath[index] === targetPath[index]);
+
+ return index;
});
$(active).addClass('active'); |
94863a27ba7fccb8236592c5b046ad32d7b48341 | source/Vibrato/core/RegExp.js | source/Vibrato/core/RegExp.js | // -------------------------------------------------------------------------- \\
// File: RegExp.js \\
// Module: Core \\
// Requires: Core.js \\
// Author: Neil Jenkins \\
// License: © 2010–2011 Opera Software ASA. All rights reserved. \\
// -------------------------------------------------------------------------- \\
"use strict";
/**
Property: RegExp.email
Type: RegExp
A regular expression for detecting an email address.
*/
RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i;
/**
Property: RegExp.url
Type: RegExp
A regular expression for detecting a url. Regexp by John Gruber, see
<http://daringfireball.net/2010/07/improved_regex_for_matching_urls>
*/
RegExp.url = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i; | // -------------------------------------------------------------------------- \\
// File: RegExp.js \\
// Module: Core \\
// Requires: Core.js \\
// Author: Neil Jenkins \\
// License: © 2010–2011 Opera Software ASA. All rights reserved. \\
// -------------------------------------------------------------------------- \\
"use strict";
/**
Property: RegExp.email
Type: RegExp
A regular expression for detecting an email address.
*/
RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i;
/**
Property: RegExp.url
Type: RegExp
A regular expression for detecting a url. Regexp by John Gruber, see
<http://daringfireball.net/2010/07/improved_regex_for_matching_urls>
*/
RegExp.url = /\b(?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/i; | Remove capture group from URL reg exp. | Remove capture group from URL reg exp.
You get the whole match anyway. And now you can more easily use the source of
the regexp as a part for constructing more complicated regular expressions.
e.g. var x = new RegExp( RegExp.url.source + "|" + RegExp.email.source, 'i' );
| JavaScript | mit | adityab/overture,Hokua/overture,linagora/overture,linagora/overture,fastmail/overture | ---
+++
@@ -23,4 +23,4 @@
A regular expression for detecting a url. Regexp by John Gruber, see
<http://daringfireball.net/2010/07/improved_regex_for_matching_urls>
*/
-RegExp.url = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
+RegExp.url = /\b(?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/i; |
fc1a61eb29f6cd38f1694fda155a8173432d1999 | tasks/help/index.js | tasks/help/index.js | module.exports = function(target) {
if (tasks[target])
console.log(tasks[target].help)
else
console.log("No help documentation exists for " + target + ".")
} | var fs = require('fs')
module.exports = function(target) {
fs.readFile('doc/' + target + '.md', function(err, data) {
if (err)
console.log("No help documentation exists for " + target + ".")
else
console.log(data)
})
} | Load markdown docs in help command | Load markdown docs in help command
Signed-off-by: Nathan Stier <013f9af474b4ba6f842b41368c6f02c1ee9e9e08@gmail.com>
| JavaScript | mit | YWebCA/ywca-cli | ---
+++
@@ -1,6 +1,9 @@
+var fs = require('fs')
module.exports = function(target) {
- if (tasks[target])
- console.log(tasks[target].help)
- else
- console.log("No help documentation exists for " + target + ".")
+ fs.readFile('doc/' + target + '.md', function(err, data) {
+ if (err)
+ console.log("No help documentation exists for " + target + ".")
+ else
+ console.log(data)
+ })
} |
88a4ce42993665dba7eef5798334419954f55a67 | lib/gulp-index-file-stream.js | lib/gulp-index-file-stream.js | var Readable = require('stream').Readable;
var path = require('path-posix');
var util = require('util');
var File = require('vinyl');
// Because the index.html files in our site don't necessarily
// come from individual files, it's easiest for us to just
// create a stream that emits Vinyl File objects rather than
// using gulp.src().
function IndexFileStream(indexStatic) {
Readable.call(this, {
objectMode: true
});
this._baseDir = __dirname;
this._indexStatic = indexStatic;
this._urls = indexStatic.URLS.slice();
}
util.inherits(IndexFileStream, Readable);
IndexFileStream.prototype._read = function() {
if (this._urls.length == 0)
return this.push(null);
var url = this._urls.pop();
var indexFile = path.join(
this._baseDir,
path.join.apply(path, url.split('/').slice(1, -1)),
'index.html'
);
this.push(new File({
cwd: this._baseDir,
base: this._baseDir,
path: indexFile,
contents: new Buffer(this._indexStatic.generate(url, {
baseURL: path.relative(url, '/')
}))
}));
};
module.exports = IndexFileStream;
| var Readable = require('stream').Readable;
var posixPath = require('path-posix');
var util = require('util');
var File = require('vinyl');
// Because the index.html files in our site don't necessarily
// come from individual files, it's easiest for us to just
// create a stream that emits Vinyl File objects rather than
// using gulp.src().
function IndexFileStream(indexStatic) {
Readable.call(this, {
objectMode: true
});
this._baseDir = __dirname;
this._indexStatic = indexStatic;
this._urls = indexStatic.URLS.slice();
}
util.inherits(IndexFileStream, Readable);
IndexFileStream.prototype._read = function() {
if (this._urls.length == 0)
return this.push(null);
var url = this._urls.pop();
var indexFile = posixPath.join(
this._baseDir,
posixPath.join.apply(posixPath, url.split('/').slice(1, -1)),
'index.html'
);
this.push(new File({
cwd: this._baseDir,
base: this._baseDir,
path: indexFile,
contents: new Buffer(this._indexStatic.generate(url, {
baseURL: posixPath.relative(url, '/')
}))
}));
};
module.exports = IndexFileStream;
| Change path name to posixPath | Change path name to posixPath
| JavaScript | mpl-2.0 | Pomax/teach.mozilla.org,fredericksilva/teach.webmaker.org,PaulaPaul/teach.mozilla.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,AnthonyBobsin/teach.webmaker.org,cadecairos/teach.mozilla.org,fredericksilva/teach.webmaker.org,emmairwin/teach.webmaker.org,mozilla/teach.webmaker.org,ScottDowne/teach.webmaker.org,asdofindia/teach.webmaker.org,alicoding/teach.webmaker.org,Pomax/teach.webmaker.org,emmairwin/teach.webmaker.org,mmmavis/teach.webmaker.org,mozilla/learning.mozilla.org,mrinaljain/teach.webmaker.org,Pomax/teach.mozilla.org,mmmavis/teach.webmaker.org,alicoding/teach.webmaker.org,ScottDowne/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,PaulaPaul/teach.mozilla.org,mozilla/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,asdofindia/teach.webmaker.org,Pomax/teach.webmaker.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,cadecairos/teach.mozilla.org,mrinaljain/teach.webmaker.org,AnthonyBobsin/teach.webmaker.org | ---
+++
@@ -1,5 +1,5 @@
var Readable = require('stream').Readable;
-var path = require('path-posix');
+var posixPath = require('path-posix');
var util = require('util');
var File = require('vinyl');
@@ -22,9 +22,9 @@
if (this._urls.length == 0)
return this.push(null);
var url = this._urls.pop();
- var indexFile = path.join(
+ var indexFile = posixPath.join(
this._baseDir,
- path.join.apply(path, url.split('/').slice(1, -1)),
+ posixPath.join.apply(posixPath, url.split('/').slice(1, -1)),
'index.html'
);
this.push(new File({
@@ -32,7 +32,7 @@
base: this._baseDir,
path: indexFile,
contents: new Buffer(this._indexStatic.generate(url, {
- baseURL: path.relative(url, '/')
+ baseURL: posixPath.relative(url, '/')
}))
}));
}; |
d77f875ffaf501002c30c49ab7c433730a8fce8e | src/modules/lists/components/connector/jsomConnector.service.js | src/modules/lists/components/connector/jsomConnector.service.js | angular
.module('ngSharepoint.Lists')
.factory('JSOMConnector', function($q, $sp) {
return ({
getLists: function() {
return $q(function(resolve, reject) {
var context = $sp.getContext();
var lists = context.get_web().get_lists();
context.load(lists);
context.executeQueryAsync(function(sender, args) {
var result = [];
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var list = lists.get_current();
result.push(list);
}
resolve(result);
}, reject);
});
}
});
});
| angular
.module('ngSharepoint.Lists')
.factory('JSOMConnector', function($q, $sp) {
return ({
getLists: function() {
return $q(function(resolve, reject) {
var context = $sp.getContext();
var lists = context.get_web().get_lists();
context.load(lists);
context.executeQueryAsync(function() {
var result = [];
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
var list = listEnumerator.get_current();
result.push(list);
}
resolve(result);
}, reject);
});
}
});
});
| Use enumerator instead of lists | Use enumerator instead of lists
| JavaScript | apache-2.0 | maxjoehnk/ngSharepoint | ---
+++
@@ -7,11 +7,11 @@
var context = $sp.getContext();
var lists = context.get_web().get_lists();
context.load(lists);
- context.executeQueryAsync(function(sender, args) {
+ context.executeQueryAsync(function() {
var result = [];
var listEnumerator = lists.getEnumerator();
while (listEnumerator.moveNext()) {
- var list = lists.get_current();
+ var list = listEnumerator.get_current();
result.push(list);
}
resolve(result); |
6e73dbf020236063f8db213f2459c4d56fa2f661 | lib/components/Application.js | lib/components/Application.js | import React, { Component } from 'react'
import firebase, { reference, signIn } from '../firebase';
import { pick, map, extend } from 'lodash';
import Input from './Input';
import MessageContainer from './MessageContainer';
// import Search from './Search';
// import Users from './Users';
export default class Application extends Component {
constructor() {
super();
this.state = {
messages: [],
}
}
// componentDidMount() {
// firebase.database().ref('messages').on('value', (snapshot) => {
// });
// }
storeMessage(message) {
firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() }));
this.state.messages.push(Object.assign(message, { id: Date.now() }))
this.setState({ messages: this.state.messages })
}
render() {
return (
<div className="application">
<header className="headerSection">
{/* <Search /> */}
</header>
<div className="messageSection">
<MessageContainer messages={this.state.messages}/>
</div>
<aside className="usersSection">
{/* <Users /> */}
</aside>
<div>
<Input sendMessage={this.storeMessage.bind(this)}/>
</div>
</div>
)
}
}
| import React, { Component } from 'react'
import firebase, { reference, signIn } from '../firebase';
import { pick, map, extend } from 'lodash';
import Input from './Input';
import MessageContainer from './MessageContainer';
// import Search from './Search';
// import Users from './Users';
export default class Application extends Component {
constructor() {
super();
this.state = {
messages: [],
}
}
componentDidMount() {
firebase.database().ref('messages').on('value', (snapshot) => {
const itemsFromFirebase = this.createArrayFromFB(snapshot.val());
this.setState({ messages: itemsFromFirebase ? itemsFromFirebase : [] })
});
}
createArrayFromFB(object) {
const firebaseKeys = object ? Object.keys(object) : [];
const messages = [];
firebaseKeys.map((key) => {
let singleMessage = object[key]
singleMessage['firebaseId'] = key
messages.push(singleMessage);
});
return messages
}
storeMessage(message) {
firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() }));
this.state.messages.push(Object.assign(message, { id: Date.now() }))
this.setState({ messages: this.state.messages })
}
render() {
return (
<div className="application">
<header className="headerSection">
{/* <Search /> */}
</header>
<div className="messageSection">
<MessageContainer messages={this.state.messages}/>
</div>
<aside className="usersSection">
{/* <Users /> */}
</aside>
<div>
<Input sendMessage={this.storeMessage.bind(this)}/>
</div>
</div>
)
}
}
| Add items to firebase and repopulate on page load or refresh | Add items to firebase and repopulate on page load or refresh
| JavaScript | mit | mlimberg/shoot-the-breeze,mlimberg/shoot-the-breeze | ---
+++
@@ -15,10 +15,23 @@
}
}
- // componentDidMount() {
- // firebase.database().ref('messages').on('value', (snapshot) => {
- // });
- // }
+ componentDidMount() {
+ firebase.database().ref('messages').on('value', (snapshot) => {
+ const itemsFromFirebase = this.createArrayFromFB(snapshot.val());
+ this.setState({ messages: itemsFromFirebase ? itemsFromFirebase : [] })
+ });
+ }
+
+ createArrayFromFB(object) {
+ const firebaseKeys = object ? Object.keys(object) : [];
+ const messages = [];
+ firebaseKeys.map((key) => {
+ let singleMessage = object[key]
+ singleMessage['firebaseId'] = key
+ messages.push(singleMessage);
+ });
+ return messages
+ }
storeMessage(message) {
firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() })); |
521eed5e6a64f1bf28210d03372cdbb353bb019e | scripts/script.js | scripts/script.js | (function(document, MazeGenerator, MazePainter, MazeInteraction) {
'use strict';
// DOM Elements
var canvas = document.getElementById('maze');
var bGenerate = document.getElementById('bGenerate');
var bSolve = document.getElementById('bSolve');
// Start painting loop
MazePainter.startPainting();
bGenerate.addEventListener('click', function() {
// Initialize modules
MazeGenerator.init(canvas.width, canvas.height, 20);
MazePainter.init(canvas, 20, '#fff', '#f00', '#000', '#0f0', '#0f0', '#0f0', '#00f');
MazeGenerator.generate();
MazeGenerator.selectEntry();
MazeGenerator.selectExit();
MazeInteraction.init(canvas, 20, MazeGenerator.getMaze());
MazeInteraction.startListeningUserEvents();
});
bSolve.addEventListener('click', function() {
if (MazePainter.isMazePainted()) {
MazeGenerator.solve();
}
});
}(document, MazeGenerator, MazePainter, MazeInteraction));
| (function(document, MazeGenerator, MazePainter, MazeInteraction) {
'use strict';
// DOM Elements
var canvas = document.getElementById('maze');
var bGenerate = document.getElementById('bGenerate');
var bSolve = document.getElementById('bSolve');
// Initialization variables
var cellSize = 20;
var cellColor = '#fff';
var frontierColor = '#f00';
var wallColor = '#000';
var entryColor = '#0f0';
var exitColor = '#0f0';
var solutionColor = '#0f0';
var userSolutionColor = '#00f';
// Start painting loop
MazePainter.startPainting();
bGenerate.addEventListener('click', function() {
// Initialize modules
MazeGenerator.init(canvas.width, canvas.height, cellSize);
MazePainter.init(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor);
MazeGenerator.generate();
MazeGenerator.selectEntry();
MazeGenerator.selectExit();
MazeInteraction.init(canvas, cellSize, MazeGenerator.getMaze());
MazeInteraction.startListeningUserEvents();
});
bSolve.addEventListener('click', function() {
if (MazePainter.isMazePainted()) {
MazeGenerator.solve();
}
});
}(document, MazeGenerator, MazePainter, MazeInteraction));
| Use variables to initialize the maze | Use variables to initialize the maze
| JavaScript | mit | jghinestrosa/maze-generator,jghinestrosa/maze-generator | ---
+++
@@ -6,19 +6,29 @@
var bGenerate = document.getElementById('bGenerate');
var bSolve = document.getElementById('bSolve');
+ // Initialization variables
+ var cellSize = 20;
+ var cellColor = '#fff';
+ var frontierColor = '#f00';
+ var wallColor = '#000';
+ var entryColor = '#0f0';
+ var exitColor = '#0f0';
+ var solutionColor = '#0f0';
+ var userSolutionColor = '#00f';
+
// Start painting loop
MazePainter.startPainting();
bGenerate.addEventListener('click', function() {
// Initialize modules
- MazeGenerator.init(canvas.width, canvas.height, 20);
- MazePainter.init(canvas, 20, '#fff', '#f00', '#000', '#0f0', '#0f0', '#0f0', '#00f');
+ MazeGenerator.init(canvas.width, canvas.height, cellSize);
+ MazePainter.init(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor);
MazeGenerator.generate();
MazeGenerator.selectEntry();
MazeGenerator.selectExit();
- MazeInteraction.init(canvas, 20, MazeGenerator.getMaze());
+ MazeInteraction.init(canvas, cellSize, MazeGenerator.getMaze());
MazeInteraction.startListeningUserEvents();
});
|
c3da45397839ff6e5857b6413471ca64fac99b54 | src/article/models/Heading.js | src/article/models/Heading.js | import { TextNode, TEXT } from 'substance'
export default class Heading extends TextNode {}
Heading.schema = {
type: 'heading',
level: { type: 'number', default: 1 },
content: TEXT()
}
| import { TextNode, TEXT } from 'substance'
import { RICH_TEXT_ANNOS, EXTENDED_FORMATTING, LINKS_AND_XREFS, INLINE_NODES } from './modelConstants'
export default class Heading extends TextNode {}
Heading.schema = {
type: 'heading',
level: { type: 'number', default: 1 },
content: TEXT(RICH_TEXT_ANNOS.concat(EXTENDED_FORMATTING).concat(LINKS_AND_XREFS).concat(INLINE_NODES).concat(['break']))
}
| Allow annotations and line-breaks in headings. | Allow annotations and line-breaks in headings.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -1,8 +1,9 @@
import { TextNode, TEXT } from 'substance'
+import { RICH_TEXT_ANNOS, EXTENDED_FORMATTING, LINKS_AND_XREFS, INLINE_NODES } from './modelConstants'
export default class Heading extends TextNode {}
Heading.schema = {
type: 'heading',
level: { type: 'number', default: 1 },
- content: TEXT()
+ content: TEXT(RICH_TEXT_ANNOS.concat(EXTENDED_FORMATTING).concat(LINKS_AND_XREFS).concat(INLINE_NODES).concat(['break']))
} |
ee3544448dc1755c99b10e0afe52d295deffbdd8 | script/postinstall.js | script/postinstall.js | #!/usr/bin/env node
var cp = require('child_process')
var fs = require('fs')
var path = require('path')
var script = path.join(__dirname, 'postinstall')
if (process.platform === 'win32') {
script += '.cmd'
} else {
script += '.sh'
}
// Read + execute permission
fs.chmodSync(script, fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true })
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stdout)
| #!/usr/bin/env node
var cp = require('child_process')
var fs = require('fs')
var path = require('path')
var script = path.join(__dirname, 'postinstall')
if (process.platform === 'win32') {
script += '.cmd'
} else {
script += '.sh'
}
// Make sure all the scripts have the necessary permissions when we execute them
// (npm does not preserve permissions when publishing packages on Windows,
// so this is especially needed to allow apm to be published successfully on Windows)
fs.chmodSync(script, 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), 0o755)
var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true })
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stdout)
| Mark all scripts as 0o755 | Mark all scripts as 0o755
This gives execute permission for everyone even if Atom is installed as root:
https://github.com/atom/atom/issues/19367
| JavaScript | mit | atom/apm,atom/apm,atom/apm,atom/apm | ---
+++
@@ -11,11 +11,13 @@
script += '.sh'
}
-// Read + execute permission
-fs.chmodSync(script, fs.constants.S_IRUSR | fs.constants.S_IXUSR)
-fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
-fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
-fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
+// Make sure all the scripts have the necessary permissions when we execute them
+// (npm does not preserve permissions when publishing packages on Windows,
+// so this is especially needed to allow apm to be published successfully on Windows)
+fs.chmodSync(script, 0o755)
+fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), 0o755)
+fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), 0o755)
+fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), 0o755)
var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true })
child.stderr.pipe(process.stderr) |
36d7c61c7d6f7c6dc4e9bb9191f20890ab148e8c | lib/support/browser_script.js | lib/support/browser_script.js | 'use strict';
let fs = require('fs'),
path = require('path'),
Promise = require('bluebird'),
filters = require('./filters');
Promise.promisifyAll(fs);
/*
Find and parse any browser scripts in rootFolder.
Returns a Promise that resolves to an array of scripts.
Each script is represented by an object with the following keys:
- default: true if script is bundled with Browsertime.
- path: the path to the script file on disk
- source: the javascript source
*/
function parseBrowserScripts(rootFolder, isDefault) {
function toFullPath(filename) {
return path.join(rootFolder, filename);
}
function fileToScriptObject(filepath) {
return fs.readFileAsync(filepath, 'utf8')
.then((contents) => {
return {
default: isDefault,
path: filepath,
source: contents
};
});
}
return fs.readdirAsync(rootFolder)
.map(toFullPath)
.filter(filters.onlyFiles)
.filter(filters.onlyWithExtension('.js'))
.map(fileToScriptObject);
}
module.exports = {
parseBrowserScripts: parseBrowserScripts,
defaultScripts: parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts'))
};
| 'use strict';
let fs = require('fs'),
path = require('path'),
Promise = require('bluebird'),
filters = require('./filters');
Promise.promisifyAll(fs);
/*
Find and parse any browser scripts in rootFolder.
Returns a Promise that resolves to an array of scripts.
Each script is represented by an object with the following keys:
- default: true if script is bundled with Browsertime.
- path: the path to the script file on disk
- source: the javascript source
*/
function parseBrowserScripts(rootFolder, isDefault) {
function toFullPath(filename) {
return path.join(rootFolder, filename);
}
function fileToScriptObject(filepath) {
return fs.readFileAsync(filepath, 'utf8')
.then((contents) => {
return {
default: isDefault,
path: filepath,
source: contents
};
});
}
return fs.readdirAsync(rootFolder)
.map(toFullPath)
.filter(filters.onlyFiles)
.filter(filters.onlyWithExtension('.js'))
.map(fileToScriptObject);
}
module.exports = {
parseBrowserScripts: parseBrowserScripts,
get defaultScripts() {
return parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts'));
}
};
| Configure Bluebird before first use of Promise. | Configure Bluebird before first use of Promise.
Turn browser_scripts#defaultScripts into a get property, so it's not executed when the file is being required. This to avoid:
Error: cannot enable long stack traces after promises have been created
| JavaScript | apache-2.0 | sitespeedio/browsertime,tobli/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime | ---
+++
@@ -40,5 +40,7 @@
module.exports = {
parseBrowserScripts: parseBrowserScripts,
- defaultScripts: parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts'))
+ get defaultScripts() {
+ return parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts'));
+ }
}; |
83d2edc294966aa1c5d29ef16ddf623f6983cce7 | index.js | index.js | "use strict";
/**
* Properties to prefix.
*/
var postcss = require("postcss"),
props = [
"hyphens",
"line-break",
"text-align-last",
"text-emphasis",
"text-emphasis-color",
"text-emphasis-style",
"word-break",
// writing modes
"writing-mode",
"text-orientation",
"text-combine-upright"
];
/**
* PostCSS plugin to prefix ePub3 properties.
* @param {Object} style
*/
function plugin(style) {
style.eachDecl(function(decl) {
if (decl.value) {
if (props.indexOf(decl.prop) >= 0) {
decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop}));
}
}
});
}
/*
* ...and export for use...
*/
module.exports = {
postcss: plugin,
process: function(css, opts) {
return postcss(plugin).process(css, opts).css;
}
};
| "use strict";
/**
* Properties to prefix.
*/
var postcss = require("postcss"),
props = [
// text
"hyphens",
"line-break",
"text-align-last",
"text-emphasis",
"text-emphasis-color",
"text-emphasis-style",
"word-break",
// writing modes
"writing-mode",
"text-orientation",
"text-combine-upright",
// text to speech
"cue",
"cue-before",
"cue-after",
"pause",
"rest",
"speak",
"speak-as",
"voice-family"
];
/**
* PostCSS plugin to prefix ePub3 properties.
* @param {Object} style
*/
function plugin(style) {
style.eachDecl(function(decl) {
if (decl.value) {
if (props.indexOf(decl.prop) >= 0) {
decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop}));
}
}
});
}
/*
* ...and export for use...
*/
module.exports = {
postcss: plugin,
process: function(css, opts) {
return postcss(plugin).process(css, opts).css;
}
};
| Add speech prefixes - still required in 2012, so should be left in due to reader issues | Add speech prefixes - still required in 2012, so should be left in due to reader issues
| JavaScript | mit | Rycochet/postcss-epub,antyakushev/postcss-epub | ---
+++
@@ -5,6 +5,7 @@
*/
var postcss = require("postcss"),
props = [
+ // text
"hyphens",
"line-break",
"text-align-last",
@@ -15,7 +16,16 @@
// writing modes
"writing-mode",
"text-orientation",
- "text-combine-upright"
+ "text-combine-upright",
+ // text to speech
+ "cue",
+ "cue-before",
+ "cue-after",
+ "pause",
+ "rest",
+ "speak",
+ "speak-as",
+ "voice-family"
];
/** |
68d0f077935e3d54d08556cb9ec646b30e443acf | index.js | index.js | var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
var host = parts[0];
var port = parts[1];
var client = net.connect({host: host, port: port}, function () {
var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n';
client.write(metricReport);
client.destroy();
});
};
MonitoringPlugin.prototype.getTasksLeft = function () {
return this.engine.nTasksLeft;
};
MonitoringPlugin.prototype.init = function (rcl, wflib, engine) {
if (this.hasOwnProperty('initialized') && this.initialized === true) {
return;
}
this.rcl = rcl;
this.wflib = wflib;
this.engine = engine;
var that = this;
setInterval(function () {
that.sendMetrics();
}, 1000);
this.initialized = true;
};
module.exports = MonitoringPlugin; | var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
var host = parts[0];
var port = 9001;
if (parts.length > 1) {
port = parseInt(parts[1]);
}
var client = net.connect({host: host, port: port}, function () {
var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n';
client.write(metricReport);
client.destroy();
});
};
MonitoringPlugin.prototype.getTasksLeft = function () {
return this.engine.nTasksLeft;
};
MonitoringPlugin.prototype.init = function (rcl, wflib, engine) {
if (this.hasOwnProperty('initialized') && this.initialized === true) {
return;
}
this.rcl = rcl;
this.wflib = wflib;
this.engine = engine;
var that = this;
setInterval(function () {
that.sendMetrics();
}, 1000);
this.initialized = true;
};
module.exports = MonitoringPlugin; | Handle supplying metric collector by env var. | Handle supplying metric collector by env var.
| JavaScript | mit | dice-cyfronet/hyperflow-monitoring-plugin | ---
+++
@@ -9,7 +9,10 @@
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
var host = parts[0];
- var port = parts[1];
+ var port = 9001;
+ if (parts.length > 1) {
+ port = parseInt(parts[1]);
+ }
var client = net.connect({host: host, port: port}, function () {
var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n';
client.write(metricReport); |
92b28424a9d10ded0ebf59ef2a044596d99627cd | index.js | index.js | const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config.local');
new WebpackDevServer(webpack(webpackConfig), {
publicPath: '/dist/',
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log(`Webpack dev server listening at localhost:3000`);
});
| const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const args = process.argv;
const webpackConfig = require(`./webpack.config.${args[2].substring(2)}`);
new WebpackDevServer(webpack(webpackConfig), {
publicPath: '/dist/',
hot: true,
historyApiFallback: true
}).listen(3000, 'localhost', (err) => {
if (err) {
console.log(err);
}
console.log(`Webpack dev server listening at localhost:3000`);
});
| Add option to choose between local and npm | [server] Add option to choose between local and npm
| JavaScript | mit | KleeGroup/focus-showcase | ---
+++
@@ -1,6 +1,7 @@
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
-const webpackConfig = require('./webpack.config.local');
+const args = process.argv;
+const webpackConfig = require(`./webpack.config.${args[2].substring(2)}`);
new WebpackDevServer(webpack(webpackConfig), {
publicPath: '/dist/', |
04ff61e25b17b68a417908758529e2fbb829ac8d | test/ui/fixtures.js | test/ui/fixtures.js | import m from 'mithril';
import AppComponent from '../../app/scripts/components/app.js';
import AIPlayer from '../../app/scripts/models/ai-player.js';
import { qs } from './utils.js';
export function _before() {
// Minimize the transition duration to speed up tests (interestingly, a
// duration of 0ms will prevent transitionEnd from firing)
const style = document.createElement('style');
style.innerHTML = '* {transition-duration: 200ms !important;}';
document.head.appendChild(style);
// Also zero out the AI Player's delay between each swift movement
AIPlayer.waitDelay = 0;
}
export function _beforeEach() {
document.body.appendChild(document.createElement('main'));
m.mount(qs('main'), AppComponent);
}
export function _afterEach() {
m.mount(qs('main'), null);
}
| import m from 'mithril';
import AppComponent from '../../app/scripts/components/app.js';
import AIPlayer from '../../app/scripts/models/ai-player.js';
import { qs } from './utils.js';
export function _before() {
// Minimize the transition duration to speed up tests (interestingly, a
// duration of 0ms will prevent transitionEnd from firing)
const style = document.createElement('style');
style.innerHTML = '* {transition-duration: 100ms !important;}';
document.head.appendChild(style);
// Also zero out the AI Player's delay between each swift movement
AIPlayer.waitDelay = 0;
}
export function _beforeEach() {
document.body.appendChild(document.createElement('main'));
m.mount(qs('main'), AppComponent);
}
export function _afterEach() {
m.mount(qs('main'), null);
}
| Reduce test transition-delay from 200ms to 100ms | Reduce test transition-delay from 200ms to 100ms
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -7,7 +7,7 @@
// Minimize the transition duration to speed up tests (interestingly, a
// duration of 0ms will prevent transitionEnd from firing)
const style = document.createElement('style');
- style.innerHTML = '* {transition-duration: 200ms !important;}';
+ style.innerHTML = '* {transition-duration: 100ms !important;}';
document.head.appendChild(style);
// Also zero out the AI Player's delay between each swift movement
AIPlayer.waitDelay = 0; |
9579909492ac9d80cfec0d9c9858ce7d89760aa1 | examples/flux-chat/js/app.js | examples/flux-chat/js/app.js | /**
* This file is provided by Facebook for testing and evaluation purposes
* only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @jsx React.DOM
*/
// This file bootstraps the entire application.
var ChatApp = require('./components/ChatApp.react');
var ChatExampleData = require('./ChatExampleData');
var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils');
var React = require('react');
ChatExampleData.init(); // load example data into localstorage
ChatWebAPIUtils.getAllMessages();
React.renderComponent(
<ChatApp />,
document.getElementById('react')
);
| /**
* This file is provided by Facebook for testing and evaluation purposes
* only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @jsx React.DOM
*/
// This file bootstraps the entire application.
var ChatApp = require('./components/ChatApp.react');
var ChatExampleData = require('./ChatExampleData');
var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils');
var React = require('react');
window.React = React; // export for http://fb.me/react-devtools
ChatExampleData.init(); // load example data into localstorage
ChatWebAPIUtils.getAllMessages();
React.renderComponent(
<ChatApp />,
document.getElementById('react')
);
| Enable React devtools by exposing React (setting window.React) | Enable React devtools by exposing React (setting window.React)
| JavaScript | bsd-3-clause | eclectriq/flux,ludiculous/flux,ayarulin/flux,nikhyl/flux,debbas/ChatV2,JanChw/flux,crsr/flux,keikun17/flux,jmandel/flux,gfogle/elm-todomvc,Chen-Han/flux,ephetic/flux,ayarulin/flux,superphung/flux,prabhash1785/flux,rstefek/flux,UIKit0/flux-1,Demian-Moschin/flux,avinnakota/flux,mircle/flux,viviancpy/flux,alexeybondarenko/flux,vl-lapikov/flux,cold-brew-coding/flux,bilboJ/flux,JanChw/flux,wandrejevic/flux,thebergamo/flux,gnoesiboe/flux,zshift/flux,vl-lapikov/flux,ludiculous/flux,oopchoi/flux,Binzzzz/flux,dingdingvsjj/flux,glitch100/flux,Eric-Vandenberg/flux,maximvl/flux,knrm/flux,kris1226/flux,viviancpy/flux,amoskyler/flux,MykolaBova/flux,jinkea/flux,maksymshtyria/flux,cjmanetta/flux,thadiggitystank/flux,yanarchy/flux,Zagorakiss/flux,zhanglingkang/flux,steveleec/flux,cgack/flux,tungmv7/flux,bilboJ/flux,jeremyhu9/flux,ayarulin/flux,rohannair/flux,bertomartin/flux,dmlinn/flux,prabhash1785/flux,pj8063/flux,noahlt/flux,lifebeyondfife/flux-todomvc,usufruct/flux,ksivam/flux,alemontree/flux,fauzan182/flux,hokennethk/flux,slapheadted/flux-nukebox,bartcharbon/flux,alexeygusak/flux,ataker/flux,zhanglingkang/flux,chenrui2014/flux,keikun17/flux,maksymshtyria/flux,Jonekee/flux,haruair/flux,birendra-ideas2it/flux,thewarpaint/flux,kiopl/flux,aaron-goshine/flux,jeremyhu9/flux,ShannonStoner/flux,MykolaBova/flux,danielchatfield/flux,kiopl/flux,fauzan182/flux,harrykiselev/flux,danielchatfield/flux,hoozi/flux,akhilxavierm/flux,pj8063/flux,crzidea/flux,chrismoulton/flux,DimitarRuskov/flux,andela-cijeomah/flux,alexeybondarenko/flux,JunyaOnishi/flux,stevemao/flux,jeffj/flux,bartcharbon/flux,tungmv7/flux,hanan198501/flux,justin3737/flux,gaurav1981/flux,sibinx7/flux,kwangkim/flux,rkho/flux,lilien1010/flux,haruair/flux,micahlmartin/flux,kwangkim/flux,rstefek/flux,alucas/flux,harrykiselev/flux,harrykiselev/flux,djfm/flux,andela-cijeomah/flux,thewarpaint/flux,cold-brew-coding/flux,chienchienchen/flux,garylgh/flux,runn1ng/flux,tinygrasshopper/flux,nvoron23/flux,jarl-alejandro/flux,mcanthony/flux,tcxq42aa/flux,kris1226/flux,bartcharbon/flux,crsr/flux,crzidea/flux,tungmv7/flux,jarl-alejandro/flux,dingdingvsjj/flux,noahlt/flux,latkins/flux,mandaltapesh/flux,keikun17/flux,jdholdren/flux,ShannonStoner/flux,crsgypin/flux,Chen-Han/flux,Eric-Vandenberg/flux,davidgbe/flux,chienchienchen/flux,jugend/flux,venkateshdaram434/flux,noahlt/flux,steveleec/flux,djfm/flux,gnoesiboe/flux,sahat/flux,prabhash1785/flux,james4388/flux,kangkot/flux,mzbac/flux,magus0219/flux,zhzenghui/flux,nvoron23/flux,baiwyc119/flux,siddhartharay007/flux,Eric-Vandenberg/flux,mandaltapesh/flux,mzbac/flux,RomanTsopin/flux,baijuachari/flux,chenckang/flux,crsgypin/flux,oopchoi/flux,rtfeldman/flux,Zagorakiss/flux,knrm/flux,gaurav1981/flux,Zagorakiss/flux,reinaldo13/flux,hoozi/flux,unidevel/flux,roshow/flux,RomanTsopin/flux,fauzan182/flux,lishengzxc/flux,gfogle/elm-todomvc,Aweary/flux,cgack/flux,ksivam/flux,cgack/flux,latkins/flux,rkho/flux,yanarchy/flux,ephetic/flux,gnoesiboe/flux,unidevel/flux,thewarpaint/flux,tom-mats/flux,soulcm/flux,bertomartin/flux,DimitarRuskov/flux,knrm/flux,lishengzxc/flux,chrismoulton/flux,avinnakota/flux,nikhyl/flux,gajus/flux,stevemao/flux,lgvalle/flux,latkins/flux,kaushik94/flux,YakovAvramenko/flux,tinygrasshopper/flux,magus0219/flux,Aweary/flux,DimitarRuskov/flux,tbutman/flux,nikhyl/flux,baiwyc119/flux,venkateshdaram434/flux,lgvalle/flux,georgetoothman/flux-todo,CedarLogic/flux,lifebeyondfife/flux-todomvc,rtfeldman/flux,alexeygusak/flux,Aweary/flux,doron2402/flux,thebergamo/flux,runn1ng/flux,yejodido/flux,ataker/flux,taylorhxu/flux,taylorhxu/flux,juliangamble/flux,lauramoore/flux,zshift/flux,usufruct/flux,gaurav1981/flux,briantopping/flux,aaron-goshine/flux,robhogfeldt-fron15/flux,lauramoore/flux,shunyitian/flux,mattvanhorn/flux,jonathanpeterwu/flux,amoskyler/flux,jarl-alejandro/flux,davidgbe/flux,songguangyu/flux,tcxq42aa/flux,gajus/flux,tom-mats/flux,albi34/flux,unidevel/flux,djfm/flux,doxiaodong/flux,nvoron23/flux,thadiggitystank/flux,hokennethk/flux,grandsong/flux,aecca/flux,wrrnwng/flux,birendra-ideas2it/flux,blazenko/flux,kaushik94/flux,lyip1992/flux,ruistime/flux,lifebeyondfife/flux-todomvc,dmlinn/flux,viviancpy/flux,lishengzxc/flux,baijuachari/flux,tcat/flux,james4388/flux,bilboJ/flux,UIKit0/flux-1,oopchoi/flux,crsgypin/flux,gold3bear/flux,maksymshtyria/flux,jmandel/flux,0rangeT1ger/flux,doron2402/flux,tom-mats/flux,0rangeT1ger/flux,lilien1010/flux,alexeybondarenko/flux,UIKit0/flux-1,dbenson24/flux,micahlmartin/flux,tcxq42aa/flux,tcat/flux,robhogfeldt-fron15/flux,superphung/flux,danielchatfield/flux,monkeyFeathers/flux,wrrnwng/flux,rachidmrad/flux,haruair/flux,vijayasingh523/flux,alemontree/flux,ruistime/flux,justin3737/flux,chikamichi/flux,jugend/flux,dbenson24/flux,gajus/flux,juliangamble/flux,alucas/flux,steveleec/flux,Binzzzz/flux,MjAbuz/flux,doxiaodong/flux,zshift/flux,aijiekj/flux,ruistime/flux,debbas/ChatV2,johan/flux,jinkea/flux,eclectriq/flux,icefoggy/flux,crzidea/flux,garylgh/flux,lgvalle/flux,reinaldo13/flux,kangkot/flux,topogigiovanni/flux,Chen-Han/flux,vijayasingh523/flux,rkho/flux,songguangyu/flux,mircle/flux,jonathanpeterwu/flux,zachwooddoughty/flux,slapheadted/flux-nukebox,Lhuihui/flux,hanan198501/flux,sibinx7/flux,chenckang/flux,v2018z/flux,alemontree/flux,rachidmrad/flux,debbas/ChatV2,gougouGet/flux,ephetic/flux,JunyaOnishi/flux,mcanthony/flux,siddhartharay007/flux,zhzenghui/flux,sahat/flux,v2018z/flux,micahlmartin/flux,CedarLogic/flux,juliangamble/flux,grandsong/flux,akhilxavierm/flux,jeffj/flux,YakovAvramenko/flux,LeeChSien/flux,kris1226/flux,maximvl/flux,soulcm/flux,albi34/flux,Lhuihui/flux,avinnakota/flux,icefoggy/flux,ataker/flux,lyip1992/flux,chikamichi/flux,zachwooddoughty/flux,johan/flux,rohannair/flux,shunyitian/flux,rtfeldman/flux,chenrui2014/flux,roshow/flux,topogigiovanni/flux,Jonekee/flux,gougouGet/flux,blazenko/flux,mattvanhorn/flux,LeeChSien/flux,monkeyFeathers/flux,tbutman/flux,wandrejevic/flux,chenckang/flux,georgetoothman/flux-todo,MjAbuz/flux,glitch100/flux,amoskyler/flux,slapheadted/flux-nukebox,jdholdren/flux,chienchienchen/flux,Demian-Moschin/flux,aijiekj/flux,yejodido/flux,tcat/flux,reinaldo13/flux,cjmanetta/flux,briantopping/flux,aecca/flux,gold3bear/flux,crsr/flux | ---
+++
@@ -18,6 +18,7 @@
var ChatExampleData = require('./ChatExampleData');
var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils');
var React = require('react');
+window.React = React; // export for http://fb.me/react-devtools
ChatExampleData.init(); // load example data into localstorage
|
5bc3d461c0837f1300baeb39c47062d15b2676d7 | client/app/bundles/Index/containers/TableHeadCell.js | client/app/bundles/Index/containers/TableHeadCell.js | import { connect } from 'react-redux'
import merge from 'lodash/merge'
import clone from 'lodash/clone'
import pickBy from 'lodash/pickBy'
import { encode } from 'querystring'
import TableHeadCell from '../components/TableHeadCell'
const mapStateToProps = (state, ownProps) => {
const { params, field } = ownProps
const currentDirection = params.sort_direction
const isCurrentSortField = (
params.sort_field == field.field && params.sort_model == field.model
)
let linkParams = merge(clone(params), {
sort_field: field.field, sort_model: field.model
})
if (isCurrentSortField) {
linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC'
}
let href = `/${ownProps.model}?${encode(pickBy(linkParams))}`
const displayName = field.name.split('_').join(' ')
return {
href,
isCurrentSortField,
currentDirection,
displayName,
}
}
const mapDispatchToProps = (dispatch, ownProps) => ({})
export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
| import { connect } from 'react-redux'
import merge from 'lodash/merge'
import clone from 'lodash/clone'
import pickBy from 'lodash/pickBy'
import { encode } from 'querystring'
import TableHeadCell from '../components/TableHeadCell'
const mapStateToProps = (state, ownProps) => {
const { params, field } = ownProps
const currentDirection = params.sort_direction
const isCurrentSortField = (
params.sort_field == field.field && (field.relation == 'own' || params.sort_model == field.model)
)
let linkParams = merge(clone(params), {
sort_field: field.field, sort_model: (field.relation == 'own' ? null : field.model)
})
if (isCurrentSortField) {
linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC'
}
let href = `/${ownProps.model}?${encode(pickBy(linkParams))}`
const displayName = field.name.split('_').join(' ')
return {
href,
isCurrentSortField,
currentDirection,
displayName,
}
}
const mapDispatchToProps = (dispatch, ownProps) => ({})
export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
| Fix for broken sorting on own fields: remove sort_model from params if the field relation is own | Fix for broken sorting on own fields: remove sort_model from params if the field relation is own
| JavaScript | mit | clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin | ---
+++
@@ -10,11 +10,11 @@
const currentDirection = params.sort_direction
const isCurrentSortField = (
- params.sort_field == field.field && params.sort_model == field.model
+ params.sort_field == field.field && (field.relation == 'own' || params.sort_model == field.model)
)
-
+
let linkParams = merge(clone(params), {
- sort_field: field.field, sort_model: field.model
+ sort_field: field.field, sort_model: (field.relation == 'own' ? null : field.model)
})
if (isCurrentSortField) {
linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC' |
fb845792abc681eb600b9a17da11120c8064bd07 | packages/strapi-plugin-users-permissions/config/layout.js | packages/strapi-plugin-users-permissions/config/layout.js | module.exports = {
user: {
actions: {
create: 'User.create', // Use the User plugin's controller.
update: 'User.update',
destroy: 'User.destroy',
deleteall: 'User.destroyAll',
},
attributes: {
username: {
className: 'col-md-6'
},
email: {
className: 'col-md-6'
},
provider: {
className: 'd-none'
},
resetPasswordToken: {
className: 'd-none'
},
role: {
className: 'd-none'
}
}
}
};
| module.exports = {
user: {
actions: {
create: 'User.create', // Use the User plugin's controller.
update: 'User.update',
destroy: 'User.destroy',
deleteall: 'User.destroyAll',
},
attributes: {
username: {
className: 'col-md-6'
},
email: {
className: 'col-md-6'
},
resetPasswordToken: {
className: 'd-none'
},
role: {
className: 'd-none'
}
}
}
};
| Fix to allow provider to be shown in the content manager | Fix to allow provider to be shown in the content manager
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -13,9 +13,6 @@
email: {
className: 'col-md-6'
},
- provider: {
- className: 'd-none'
- },
resetPasswordToken: {
className: 'd-none'
}, |
0c2e09addecb2384efe3bc310c0afee033586d86 | index.js | index.js | 'use strict';
var execFile = require('child_process').execFile;
module.exports = function (str, cb) {
execFile('osascript', ['-e', str], function (err, stdout) {
if (err) {
cb(err);
return;
}
cb(err, stdout.trim());
});
};
| 'use strict';
var execFile = require('child_process').execFile;
module.exports = function (str, cb) {
if (process.platform !== 'darwin') {
throw new Error('Only OS X systems are supported');
}
execFile('osascript', ['-e', str], function (err, stdout) {
if (err) {
cb(err);
return;
}
cb(err, stdout.trim());
});
};
| Throw error if used on another OS than OS X | Throw error if used on another OS than OS X
| JavaScript | mit | sindresorhus/run-applescript | ---
+++
@@ -2,6 +2,10 @@
var execFile = require('child_process').execFile;
module.exports = function (str, cb) {
+ if (process.platform !== 'darwin') {
+ throw new Error('Only OS X systems are supported');
+ }
+
execFile('osascript', ['-e', str], function (err, stdout) {
if (err) {
cb(err); |
032243593b312553e384dc068255abc5aea77473 | index.js | index.js | "use strict";
var util = require('util');
var minimist = require('minimist');
/**
* Parse arguments and return command object
* @param {array} argv Command line arguments
* @param {object} opts Argument parsing options and commands
* @return {object} Command object
*/
module.exports = function(argv, opts) {
if (!argv) argv = process.argv.slice(2);
opts = opts || {};
opts.commands = opts.commands || {};
opts.stopEarly = true;
var global_args = minimist(argv, opts);
var command = global_args._[0];
var options = opts.commands[command] || {};
var callback = options.callback || options.cb;
if (opts.inheritCommon) {
options = util._extend(opts, options);
}
var args = minimist(global_args._.slice(1), options);
function execCommand() {
if (typeof callback === 'function') {
return callback.apply(null, [args].concat(arguments));
}
return false;
};
return {
name: command,
common: global_args,
args: args,
exec: execCommand,
};
};
| "use strict";
var util = require('util');
var minimist = require('minimist');
/**
* Parse arguments and return command object
* @param {array} argv Command line arguments
* @param {object} opts Argument parsing options and commands
* @return {object} Command object
*/
module.exports = function(argv, opts) {
if (!argv) argv = process.argv.slice(2);
opts = opts || {};
opts.commands = opts.commands || {};
opts.stopEarly = true;
var global_args = minimist(argv, opts);
var command = global_args._[0];
var options = opts.commands[command] || {};
var callback = options.callback || options.cb;
if (opts.inheritCommon) {
options = util._extend(opts, options);
}
var args = minimist(global_args._.slice(1), options);
return {
name: command,
common: global_args,
args: args,
exec: callback && callback.bind(null, args),
};
};
| Use bind instead of intermediate function | Use bind instead of intermediate function
Exec method is 'undefined' if no command callback were defined.
Signed-off-by: Harri Kovalainen <2ecf1d4f49b9d136d53b819dc389c152487e9e18@gmail.com>
| JavaScript | mit | hakovala/node-simpleton | ---
+++
@@ -27,17 +27,10 @@
var args = minimist(global_args._.slice(1), options);
- function execCommand() {
- if (typeof callback === 'function') {
- return callback.apply(null, [args].concat(arguments));
- }
- return false;
- };
-
return {
name: command,
common: global_args,
args: args,
- exec: execCommand,
+ exec: callback && callback.bind(null, args),
};
}; |
fe52ed79a76c1fa2a3368da23722ce9f5959e227 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-inject-asset-map',
// Add asset map hash to asset-map controller
postBuild: function (results) {
console.log('Injecting asset map hash...');
var fs = require('fs'),
path = require('path'),
assetMap = results['graph']['tree']['assetMap'],
jsPath = path.join(results.directory, assetMap['assets/art19.js']); // TODO: allow specifying name of js file
// TODO: I'd love a cleaner way to do this, but I'm not sure sure how since this has to be done after build.
var js = fs.readFileSync(jsPath, 'utf-8'),
assetMapKey = 'assetMapHash',
hackedJs = js.replace(new RegExp(assetMapKey + ': undefined'), assetMapKey + ': ' + JSON.stringify(assetMap)),
hackedCompressed = js.replace(new RegExp(assetMapKey + ':void 0'), assetMapKey + ':' + JSON.stringify(assetMap));
// Inject in temp
fs.writeFileSync(jsPath, hackedJs, 'utf-8');
// Inject in dist (this assumes dist is using JS compression.)
fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), hackedCompressed, 'utf-8');
console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.');
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-inject-asset-map',
// Add asset map hash to asset-map controller
postBuild: function (results) {
var fs = require('fs'),
path = require('path'),
colors = require('colors'),
tree = results['graph']['tree'],
assetMap = tree._inputNodes[0].assetMap,
jsPath = path.join(results.directory, assetMap['assets/art19.js']), // TODO: allow specifying name of js file
js = fs.readFileSync(jsPath, 'utf-8'),
assetMapKey = 'assetMapHash',
expression = new RegExp(assetMapKey + ':\\s?(void 0|undefined)'),
injectedJs = js.replace(expression, assetMapKey + ': ' + JSON.stringify(assetMap));
console.log('\nInjecting asset map hash...'.rainbow);
// Write to temp and dist
fs.writeFileSync(jsPath, injectedJs, 'utf-8');
fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), injectedJs, 'utf-8');
console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'.rainbow);
}
};
| Update to work with new versions of ember-cli | Update to work with new versions of ember-cli
| JavaScript | mit | jcaffey/ember-cli-inject-asset-map,jcaffey/ember-cli-inject-asset-map | ---
+++
@@ -6,26 +6,24 @@
// Add asset map hash to asset-map controller
postBuild: function (results) {
- console.log('Injecting asset map hash...');
+ var fs = require('fs'),
+ path = require('path'),
+ colors = require('colors'),
+ tree = results['graph']['tree'],
+ assetMap = tree._inputNodes[0].assetMap,
+ jsPath = path.join(results.directory, assetMap['assets/art19.js']), // TODO: allow specifying name of js file
+ js = fs.readFileSync(jsPath, 'utf-8'),
+ assetMapKey = 'assetMapHash',
+ expression = new RegExp(assetMapKey + ':\\s?(void 0|undefined)'),
+ injectedJs = js.replace(expression, assetMapKey + ': ' + JSON.stringify(assetMap));
- var fs = require('fs'),
- path = require('path'),
- assetMap = results['graph']['tree']['assetMap'],
- jsPath = path.join(results.directory, assetMap['assets/art19.js']); // TODO: allow specifying name of js file
+ console.log('\nInjecting asset map hash...'.rainbow);
- // TODO: I'd love a cleaner way to do this, but I'm not sure sure how since this has to be done after build.
- var js = fs.readFileSync(jsPath, 'utf-8'),
- assetMapKey = 'assetMapHash',
- hackedJs = js.replace(new RegExp(assetMapKey + ': undefined'), assetMapKey + ': ' + JSON.stringify(assetMap)),
- hackedCompressed = js.replace(new RegExp(assetMapKey + ':void 0'), assetMapKey + ':' + JSON.stringify(assetMap));
+ // Write to temp and dist
+ fs.writeFileSync(jsPath, injectedJs, 'utf-8');
+ fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), injectedJs, 'utf-8');
- // Inject in temp
- fs.writeFileSync(jsPath, hackedJs, 'utf-8');
-
- // Inject in dist (this assumes dist is using JS compression.)
- fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), hackedCompressed, 'utf-8');
-
- console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.');
+ console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'.rainbow);
}
};
|
d49e5b628ef3c352e6664ab290b831b68bd65e3b | notifications/SiteDownNotification.js | notifications/SiteDownNotification.js | "use strict";
var Mail = require('./channels/Mail');
var Console = require('./channels/Console');
class SiteDownNotification {
constructor(site)
{
this.site = site;
this.message = site.getAttribute('url') + ' is down!';
}
toMail()
{
return new Mail().setBody(this.message);
}
toConsole()
{
return new Console().setBody(this.message);
}
via()
{
return ['mail', 'console'];
}
}
module.exports = SiteDownNotification; | "use strict";
var Mail = require('./channels/Mail');
var Console = require('./channels/Console');
class SiteDownNotification {
constructor(site)
{
this.site = site;
this.message = site.getAttribute('url') + ' is down!';
}
toMail()
{
return new Mail().setBody(this.message);
}
toConsole()
{
return new Console().setBody(this.message);
}
via()
{
return (this.site.notifications) ? this.site.notifications : ['console'];
}
}
module.exports = SiteDownNotification; | Send notification based on the sites settings | Send notification based on the sites settings
| JavaScript | mit | jonathandey/uptime-monitor,jonathandey/uptime-monitor | ---
+++
@@ -24,7 +24,7 @@
via()
{
- return ['mail', 'console'];
+ return (this.site.notifications) ? this.site.notifications : ['console'];
}
} |
7c39d6c44216d85785e064c724f1b11ce0b46745 | index.js | index.js | #!/usr/bin/env node
var cli = require('cli').enable('version');
var fs = require('fs');
var path = require('path');
var cwd = process.cwd();
var options = cli.parse({
'append': ['a', 'append to the given FILEs, do not overwrite'],
'ignore-interrupts': ['i', 'ignore interrupt signals'],
'suppress': ['s', 'do NOT output to stdout']
});
var fsWriteFunc = options.append ? 'appendFile' : 'writeFile';
function writeToFiles (data, files) {
if (!files.length) {
return output(data);
}
fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) {
if (err) throw err;
writeToFiles(data, files);
});
}
function output (data) {
if (!options.suppress) {
cli.output(data);
}
}
function interceptInt () {
if (!options['ignore-interrupts']) {
process.exit();
}
}
process.on('SIGINT', interceptInt);
cli.withStdin(function (stdin) {
writeToFiles(stdin, cli.args);
}); | #!/usr/bin/env node
var cli = require('cli').enable('version').setApp('./package.json');
var fs = require('fs');
var path = require('path');
var cwd = process.cwd();
var options = cli.parse({
'append': ['a', 'append to the given FILEs, do not overwrite'],
'ignore-interrupts': ['i', 'ignore interrupt signals'],
'suppress': ['s', 'do NOT output to stdout']
});
var fsWriteFunc = options.append ? 'appendFile' : 'writeFile';
function writeToFiles (data, files) {
if (!files.length) {
return output(data);
}
fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) {
if (err) throw err;
writeToFiles(data, files);
});
}
function output (data) {
if (!options.suppress) {
cli.output(data);
}
}
function interceptInt () {
if (!options['ignore-interrupts']) {
process.exit();
}
}
process.on('SIGINT', interceptInt);
cli.withStdin(function (stdin) {
writeToFiles(stdin, cli.args);
}); | Fix ntee -h/--help not showing right name and version and showing cli's ones instead | Fix ntee -h/--help not showing right name and version and showing cli's ones instead
| JavaScript | mit | stefanmaric/ntee | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-var cli = require('cli').enable('version');
+var cli = require('cli').enable('version').setApp('./package.json');
var fs = require('fs');
var path = require('path');
var cwd = process.cwd(); |
cfe3214bc9f571c7e428c85dcd4fcb4845ad5832 | index.js | index.js | module.exports = Storage
function Storage () {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
}
Storage.prototype.put = function (index, buf, cb) {
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
cb(err, val)
})
}
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
var offset = opts.offset || 0
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
| module.exports = Storage
function Storage (chunkLength) {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
this.chunkLength = Number(chunkLength)
this.closed = false
if (!this.chunkLength) throw new Error('First argument must be a chunk length')
}
Storage.prototype.put = function (index, buf, cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
if (buf.length !== this.chunkLength) {
return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength))
}
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
var offset = opts.offset || 0
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
Storage.prototype.close = Storage.prototype.destroy = function (cb) {
if (this.closed) return nextTick(cb, new Error('Storage is closed'))
this.closed = true
this.chunks = null
nextTick(cb, null)
}
function nextTick (cb, err, val) {
process.nextTick(function () {
if (cb) cb(err, val)
})
}
| Add close and destroy; force fixed chunk length | Add close and destroy; force fixed chunk length
| JavaScript | mit | mafintosh/memory-chunk-store | ---
+++
@@ -1,23 +1,25 @@
module.exports = Storage
-function Storage () {
+function Storage (chunkLength) {
if (!(this instanceof Storage)) return new Storage()
this.chunks = []
+ this.chunkLength = Number(chunkLength)
+ this.closed = false
+ if (!this.chunkLength) throw new Error('First argument must be a chunk length')
}
Storage.prototype.put = function (index, buf, cb) {
+ if (this.closed) return nextTick(cb, new Error('Storage is closed'))
+ if (buf.length !== this.chunkLength) {
+ return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength))
+ }
this.chunks[index] = buf
if (cb) process.nextTick(cb)
}
-function nextTick (cb, err, val) {
- process.nextTick(function () {
- cb(err, val)
- })
-}
-
Storage.prototype.get = function (index, opts, cb) {
if (typeof opts === 'function') return this.get(index, null, opts)
+ if (this.closed) return nextTick(cb, new Error('Storage is closed'))
var buf = this.chunks[index]
if (!buf) return nextTick(cb, new Error('Chunk not found'))
if (!opts) return nextTick(cb, null, buf)
@@ -25,3 +27,16 @@
var len = opts.length || (buf.length - offset)
nextTick(cb, null, buf.slice(offset, len + offset))
}
+
+Storage.prototype.close = Storage.prototype.destroy = function (cb) {
+ if (this.closed) return nextTick(cb, new Error('Storage is closed'))
+ this.closed = true
+ this.chunks = null
+ nextTick(cb, null)
+}
+
+function nextTick (cb, err, val) {
+ process.nextTick(function () {
+ if (cb) cb(err, val)
+ })
+} |
eea34dcd016c2b497ff5af29c149d3e97530e566 | index.js | index.js | 'use strict';
var consecutiveSlash = /(:)?\/+/g;
var endsWithExtension = /[^\/]*\.[^\/]+$/g;
var fn = function(match, c) {
return c ? '://' : '/';
};
var pppath = function(parts, filename) {
if (typeof parts === 'string') {
parts = [parts];
}
if (filename && !endsWithExtension.test(parts[parts.length-1])) {
parts.push(filename);
}
return parts.join('/').replace(consecutiveSlash, fn);
};
module.exports = exports = pppath;
| 'use strict';
var consecutiveSlash = /(:)?\/+/g;
var endsWithExtension = /[^\/]*\.[^\/]+$/g;
var fn = function(match, c) {
return c ? '://' : '/';
};
var pppath = function(parts, filename) {
if (typeof parts === 'string') {
parts = [parts];
}
if (filename && parts[parts.length-1].search(endsWithExtension) === -1) {
parts.push(filename);
}
return parts.join('/').replace(consecutiveSlash, fn);
};
module.exports = exports = pppath;
| Use `String.search` instead of `RegExp.test` | Use `String.search` instead of `RegExp.test`
| JavaScript | mit | yuanqing/pppath | ---
+++
@@ -11,7 +11,7 @@
if (typeof parts === 'string') {
parts = [parts];
}
- if (filename && !endsWithExtension.test(parts[parts.length-1])) {
+ if (filename && parts[parts.length-1].search(endsWithExtension) === -1) {
parts.push(filename);
}
return parts.join('/').replace(consecutiveSlash, fn); |
869ba7c3b24aa0d8b3d15481df4a7de5327a64e9 | lib/white.js | lib/white.js | var generatePairs = function(string) {
var pairs = [];
string = string.toLowerCase();
for (var i = 0; i < string.length - 1; i++) {
pair = string.substr(i, 2);
if (!/\s/.test(pair)) {
pairs.push(pair);
}
}
return pairs;
}
var whiteSimilarity = function(string1, string2) {
string1 = string1.toUpperCase()
.replace(/[^A-Z]+/g, '');
string2 = string1.toUpperCase()
.replace(/[^A-Z]+/g, '');
var pairs1 = generatePairs(string1);
var pairs2 = generatePairs(string2);
var union = pairs1.length + pairs2.length;
var hitCount = 0;
for (x in pairs1) {
for (y in pairs2) {
if (pairs1[x] == pairs2[y]) {
hitCount++;
}
}
}
score = ((2.0 * hitCount) / union).toFixed(2);
return score;
}
module.exports = whiteSimilarity;
| var generatePairs = function(string) {
superPairs = string.toUpperCase()
.replace(/[^A-Z ]+/g, '')
.split(/\s+/);
superPairs = superPairs
.map(function(word) {
breaks = [];
for (var i = 0; i < word.length - 1; i++) {
breaks.push(word.slice(i, i + 2));
}
return breaks;
});
pairs = [].concat.apply([], superPairs);
return pairs;
}
var whiteSimilarity = function(string1, string2) {
var pairs1 = generatePairs(string1);
var pairs2 = generatePairs(string2);
var union = pairs1.length + pairs2.length;
var hitCount = 0;
for (x in pairs1) {
for (y in pairs2) {
if (pairs1[x] == pairs2[y]) {
hitCount++;
pairs2[y] = '';
}
}
}
score = ((2.0 * hitCount) / union).toFixed(2);
return score;
}
module.exports = whiteSimilarity;
| Make pair generation extensible to multiple words | Make pair generation extensible to multiple words
| JavaScript | mit | sanchitgera/Lingual | ---
+++
@@ -1,21 +1,21 @@
var generatePairs = function(string) {
- var pairs = [];
- string = string.toLowerCase();
- for (var i = 0; i < string.length - 1; i++) {
- pair = string.substr(i, 2);
- if (!/\s/.test(pair)) {
- pairs.push(pair);
- }
- }
+ superPairs = string.toUpperCase()
+ .replace(/[^A-Z ]+/g, '')
+ .split(/\s+/);
+
+ superPairs = superPairs
+ .map(function(word) {
+ breaks = [];
+ for (var i = 0; i < word.length - 1; i++) {
+ breaks.push(word.slice(i, i + 2));
+ }
+ return breaks;
+ });
+ pairs = [].concat.apply([], superPairs);
return pairs;
}
var whiteSimilarity = function(string1, string2) {
- string1 = string1.toUpperCase()
- .replace(/[^A-Z]+/g, '');
- string2 = string1.toUpperCase()
- .replace(/[^A-Z]+/g, '');
-
var pairs1 = generatePairs(string1);
var pairs2 = generatePairs(string2);
var union = pairs1.length + pairs2.length;
@@ -24,6 +24,7 @@
for (y in pairs2) {
if (pairs1[x] == pairs2[y]) {
hitCount++;
+ pairs2[y] = '';
}
}
} |
62c1b14f0e0da04c0952865a74ede42b21ae864b | index.js | index.js | module.exports = function (paths, ignores) {
let result = []
let edge = String.prototype
for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) {
let ignore = ignores[i]
if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) {
edge = edge.endsWith
} else {
edge = edge.startsWith
}
for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) {
let path = paths[j]
if (!edge.call(path, ignore)) {
result[result.length] = path
}
}
}
return result
}
| function startsWith (value, start) {
return value.slice(0, start.length) === start
}
function endsWith (value, end) {
return value.slice(value.length - end.length) === end
}
module.exports = function (paths, ignores) {
let result = []
let edge
for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) {
let ignore = ignores[i]
if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) {
edge = endsWith
} else {
edge = startsWith
}
for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) {
let path = paths[j]
if (!edge(path, ignore)) {
result[result.length] = path
}
}
}
return result
}
| Use startsWith and endsWith functions | Use startsWith and endsWith functions
| JavaScript | mit | whaaaley/path-ignore | ---
+++
@@ -1,20 +1,28 @@
+function startsWith (value, start) {
+ return value.slice(0, start.length) === start
+}
+
+function endsWith (value, end) {
+ return value.slice(value.length - end.length) === end
+}
+
module.exports = function (paths, ignores) {
let result = []
- let edge = String.prototype
+ let edge
for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) {
let ignore = ignores[i]
if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) {
- edge = edge.endsWith
+ edge = endsWith
} else {
- edge = edge.startsWith
+ edge = startsWith
}
for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) {
let path = paths[j]
- if (!edge.call(path, ignore)) {
+ if (!edge(path, ignore)) {
result[result.length] = path
}
} |
5b057575255fc56845c37bae3289da0a72fe93a4 | src/routerViewPort.js | src/routerViewPort.js | import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating';
import {Injector, Inject} from 'di';
@TemplateDirective({selector: 'router-view-port'})
export class RouterViewPort {
@Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs)
constructor(viewFactory, viewPort, executionContext, attrs) {
this.viewFactory = viewFactory;
this.viewPort = viewPort;
this.executionContext = executionContext;
this.view = null;
if ('router' in this.executionContext) {
this.executionContext.router.registerViewPort(this, attrs.name);
}
}
createComponentView(directive, providers){
return this.viewFactory.createComponentView({
component: directive,
providers: providers,
viewPort: this.viewPort
});
}
process(viewPortInstruction) {
this.tryRemoveView();
this.view = viewPortInstruction.component;
this.viewPort.append(this.view);
}
tryRemoveView() {
if (this.view) {
this.view.remove();
this.view = null;
}
}
}
| import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating';
import {Injector, Inject} from 'di';
@TemplateDirective({selector: 'router-view-port'})
export class RouterViewPort {
@Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs)
constructor(viewFactory, viewPort, executionContext, attrs) {
this.viewFactory = viewFactory;
this.viewPort = viewPort;
this.executionContext = executionContext;
this.view = null;
if ('router' in this.executionContext) {
this.executionContext.router.registerViewPort(this, attrs.name);
}
}
createComponentView(directive, providers){
return this.viewFactory.createComponentView({
component: directive,
providers: providers,
viewPort: this.viewPort
});
}
process(viewPortInstruction) {
this.tryRemoveView();
this.view = viewPortInstruction.component;
this.view.appendTo(this.viewPort);
}
tryRemoveView() {
if (this.view) {
this.view.remove();
this.view = null;
}
}
}
| Update the newest templating API | chore(templating): Update the newest templating API | JavaScript | apache-2.0 | shangyilim/router,JanPietrzyk/router,rakeshbhavsar/router,excellalabs/router,shangyilim/router,loomio/router,kyroskoh/router,angular/router,excellalabs/router,JanPietrzyk/router,kyroskoh/router,IgorMinar/router,AyogoHealth/router,rakeshbhavsar/router,AyogoHealth/router,shangyilim/router,IgorMinar/router,IgorMinar/router,loomio/router | ---
+++
@@ -26,7 +26,7 @@
process(viewPortInstruction) {
this.tryRemoveView();
this.view = viewPortInstruction.component;
- this.viewPort.append(this.view);
+ this.view.appendTo(this.viewPort);
}
tryRemoveView() { |
02b11e3eef293f87a32bae4ff747dcf4f66d436b | index.js | index.js | var path = require('path'),
servestatic = require('serve-static');
var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json'));
module.exports = {
setup: function (app, options) {
options = options || {};
options.path = options.path || '/govuk-assets';
app.use(options.path, servestatic(path.join(basedir, './assets'), options));
app.use(function (req, res, next) {
res.locals.govukAssetPath = options.path + '/';
res.locals.partials = res.locals.partials || {};
res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
next();
});
}
};
| var path = require('path'),
servestatic = require('serve-static');
var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json'));
module.exports = {
setup: function (app, options) {
options = options || {};
options.path = options.path || '/govuk-assets';
app.use(options.path, servestatic(path.join(basedir, './assets'), options));
app.use(function (req, res, next) {
res.locals.govukAssetPath = req.baseUrl + options.path + '/';
res.locals.partials = res.locals.partials || {};
res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
next();
});
}
};
| Include req.baseUrl is asset path | Include req.baseUrl is asset path
If app is namespaced under another route then this needs to be taken into account when importing assets
| JavaScript | mit | UKHomeOffice/govuk-template-compiler,UKHomeOffice/govuk-template-compiler | ---
+++
@@ -11,7 +11,7 @@
app.use(options.path, servestatic(path.join(basedir, './assets'), options));
app.use(function (req, res, next) {
- res.locals.govukAssetPath = options.path + '/';
+ res.locals.govukAssetPath = req.baseUrl + options.path + '/';
res.locals.partials = res.locals.partials || {};
res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template');
next(); |
288b361b388a23e4b4ea9aef10f659e5ba65a6ca | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-power-select'
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-power-select',
contentFor: function(type /*, config */) {
if (type === 'body-footer') {
return `<div id="ember-power-select-wormhole"></div>`
}
}
};
| Add the wormhole destination in the {{content-for “body-footer”}} | Add the wormhole destination in the {{content-for “body-footer”}} | JavaScript | mit | cibernox/ember-power-select,Dremora/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,Dremora/ember-power-select | ---
+++
@@ -2,5 +2,10 @@
'use strict';
module.exports = {
- name: 'ember-power-select'
+ name: 'ember-power-select',
+ contentFor: function(type /*, config */) {
+ if (type === 'body-footer') {
+ return `<div id="ember-power-select-wormhole"></div>`
+ }
+ }
}; |
1e9c43f190abf3cddc7e7704e918abde3368a2ee | index.js | index.js | 'use strict';
/*
* Dependencies..
*/
var Ware;
Ware = require('ware');
/*
* Components.
*/
var parse,
stringify;
parse = require('./lib/parse.js');
stringify = require('./lib/stringify.js');
/**
* Construct an MDAST instance.
*
* @constructor {MDAST}
*/
function MDAST() {
this.parser = new Ware();
}
/**
* Parse a value and apply plugins.
*
* @return {Root}
*/
function runParse(_, options) {
var node;
node = parse.apply(parse, arguments);
this.parser.run(node, options);
return node;
}
/**
* Construct an MDAST instance and use a plugin.
*
* @return {MDAST}
*/
function use(plugin) {
var self;
self = this;
if (!(self instanceof MDAST)) {
self = new MDAST();
}
self.parser.use(plugin);
return self;
}
/*
* Prototype.
*/
MDAST.prototype.parse = runParse;
MDAST.prototype.stringify = stringify;
MDAST.prototype.use = use;
/*
* Expose `mdast`.
*/
module.exports = {
'parse': parse,
'stringify': stringify,
'use': use
};
| 'use strict';
/*
* Dependencies..
*/
var Ware;
Ware = require('ware');
/*
* Components.
*/
var parse,
stringify;
parse = require('./lib/parse.js');
stringify = require('./lib/stringify.js');
/**
* Construct an MDAST instance.
*
* @constructor {MDAST}
*/
function MDAST() {
this.ware = new Ware();
}
/**
* Parse a value and apply plugins.
*
* @return {Root}
*/
function runParse(_, options) {
var node;
node = parse.apply(parse, arguments);
this.ware.run(node, options);
return node;
}
/**
* Construct an MDAST instance and use a plugin.
*
* @return {MDAST}
*/
function use(plugin) {
var self;
self = this;
if (!(self instanceof MDAST)) {
self = new MDAST();
}
self.ware.use(plugin);
return self;
}
/*
* Prototype.
*/
MDAST.prototype.parse = runParse;
MDAST.prototype.stringify = stringify;
MDAST.prototype.use = use;
/*
* Expose `mdast`.
*/
module.exports = {
'parse': parse,
'stringify': stringify,
'use': use
};
| Rename `ware` internally from `parser` to `ware` | Rename `ware` internally from `parser` to `ware`
| JavaScript | mit | eush77/remark,tanzania82/remarks,yukkurisinai/mdast,chcokr/mdast,ulrikaugustsson/mdast,yukkurisinai/mdast,ulrikaugustsson/mdast,eush77/remark,wooorm/remark,chcokr/mdast | ---
+++
@@ -24,7 +24,7 @@
* @constructor {MDAST}
*/
function MDAST() {
- this.parser = new Ware();
+ this.ware = new Ware();
}
/**
@@ -37,7 +37,7 @@
node = parse.apply(parse, arguments);
- this.parser.run(node, options);
+ this.ware.run(node, options);
return node;
}
@@ -56,7 +56,7 @@
self = new MDAST();
}
- self.parser.use(plugin);
+ self.ware.use(plugin);
return self;
} |
068ce6d6a58dceb64c32173c37483f821ae8c31e | index.js | index.js | 'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');
var template = _.template(multiline(function() {
/*
<a href="<%= url %>" title="<%= title %>" class="fancybox">
<img src="<%= url %>" alt="<%= title %>"></img>
</a>
*/
}));
module.exports = {
book: {
assets: './assets',
js: [
'jquery.min.js',
'jquery.fancybox.pack.js',
'jquery.fancybox-buttons.js',
'plugin.js'
],
css: [
'jquery.fancybox.css',
'jquery.fancybox-buttons.css'
]
},
hooks: {
page: function(page) {
var $ = cheerio.load(page.content);
$('img').each(function(index, img) {
var $img = $(img);
$img.replaceWith(template({
url: $img.attr('src'),
title: $img.attr('alt')
}));
});
page.content = $.html();
return page;
}
}
};
| 'use strict';
var cheerio = require('cheerio');
var _ = require('underscore');
var multiline = require('multiline');
var template = _.template(multiline(function() {
/*
<a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox">
<img src="<%= url %>" alt="<%= title %>"></img>
</a>
*/
}));
module.exports = {
book: {
assets: './assets',
js: [
'jquery.min.js',
'jquery.fancybox.pack.js',
'jquery.fancybox-buttons.js',
'plugin.js'
],
css: [
'jquery.fancybox.css',
'jquery.fancybox-buttons.css'
]
},
hooks: {
page: function(page) {
var $ = cheerio.load(page.content);
$('img').each(function(index, img) {
var $img = $(img);
$img.replaceWith(template({
url: $img.attr('src'),
title: $img.attr('alt')
}));
});
page.content = $.html();
return page;
}
}
};
| Add target attribute to a.fancybox to prevent default theme's links following | Add target attribute to a.fancybox to prevent default theme's links following
| JavaScript | mit | ly-tools/gitbook-plugin-fancybox,LingyuCoder/gitbook-plugin-fancybox | ---
+++
@@ -5,7 +5,7 @@
var template = _.template(multiline(function() {
/*
- <a href="<%= url %>" title="<%= title %>" class="fancybox">
+ <a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox">
<img src="<%= url %>" alt="<%= title %>"></img>
</a>
*/ |
203d8265d7410a3a8c65366db265569c516f3f12 | index.js | index.js | 'use strict';
const got = require('got');
const awaitUrl = (url, option) => {
const config = Object.assign({}, option, {
interval : 1000,
tries : 60
});
return new Promise((resolve, reject) => {
const attempt = async (tries) => {
const res = await got(url, {
followRedirect : false,
timeout : 5000
});
if (res.statusCode === 200) {
resolve();
}
else if (Math.max(1, tries) > 1) {
setTimeout(attempt, config.interval, tries - 1);
}
else {
reject(new RangeError(`Expected 200 response but got ${res.statusCode}`));
}
};
attempt(config.tries).catch(reject);
});
};
module.exports = awaitUrl;
| 'use strict';
const got = require('got');
const awaitUrl = (url, option) => {
const config = Object.assign({}, option, {
interval : 1000,
tries : 60
});
return new Promise((resolve, reject) => {
const attempt = async (tries) => {
const res = await got(url, {
followRedirect : false,
timeout : {
connect : 10000,
socket : 10000,
request : 10000
}
});
if (res.statusCode === 200) {
resolve();
}
else if (Math.max(1, tries) > 1) {
setTimeout(attempt, config.interval, tries - 1);
}
else {
reject(new RangeError(`Expected 200 response but got ${res.statusCode}`));
}
};
attempt(config.tries).catch(reject);
});
};
module.exports = awaitUrl;
| Increase timeouts for very slow servers | Increase timeouts for very slow servers
| JavaScript | mpl-2.0 | sholladay/await-url | ---
+++
@@ -12,7 +12,11 @@
const attempt = async (tries) => {
const res = await got(url, {
followRedirect : false,
- timeout : 5000
+ timeout : {
+ connect : 10000,
+ socket : 10000,
+ request : 10000
+ }
});
if (res.statusCode === 200) {
resolve(); |
c7ac887023341250eb1c4c6e9bb70ae5138b23f9 | index.js | index.js | var es6tr = require("es6-transpiler");
var createES6TranspilerPreprocessor = function(args, config, logger, helper) {
config = config || {};
var log = logger.create('preprocessor.es6-transpiler');
var defaultOptions = {
};
var options = helper.merge(defaultOptions, args.options || {}, config.options || {});
var transformPath = args.transformPath || config.transformPath || function(filepath) {
return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js');
};
return function(content, file, done) {
log.info('Processing "%s".', file.originalPath);
file.path = transformPath(file.originalPath);
options.filename = file.originalPath;
var result = es6tr.run({
filename: options.filename
});
var transpiledContent = result.src;
result.errors.forEach(function(err) {
log.error(err);
});
if (result.errors.length) {
return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n')));
}
// TODO: add sourceMap to transpiledContent
return done(null, transpiledContent);
};
};
createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper'];
// export es6-transpiler preprocessor
module.exports = {
'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor]
};
| var es6tr = require("es6-transpiler");
var createES6TranspilerPreprocessor = function(args, config, logger, helper) {
config = config || {};
var log = logger.create('preprocessor.es6-transpiler');
var defaultOptions = {
};
var options = helper.merge(defaultOptions, args.options || {}, config.options || {});
var transformPath = args.transformPath || config.transformPath || function(filepath) {
return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js');
};
return function(content, file, done) {
log.info('Processing "%s".', file.originalPath);
file.path = transformPath(file.originalPath);
options.filename = file.originalPath;
var result = es6tr.run(options);
var transpiledContent = result.src;
result.errors.forEach(function(err) {
log.error(err);
});
if (result.errors.length) {
return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n')));
}
// TODO: add sourceMap to transpiledContent
return done(null, transpiledContent);
};
};
createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper'];
// export es6-transpiler preprocessor
module.exports = {
'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor]
};
| Fix options passed to es6-transpiler | Fix options passed to es6-transpiler
Otherwise, `options` is useless. | JavaScript | bsd-3-clause | ouhouhsami/karma-es6-transpiler-preprocessor | ---
+++
@@ -16,9 +16,7 @@
file.path = transformPath(file.originalPath);
options.filename = file.originalPath;
- var result = es6tr.run({
- filename: options.filename
- });
+ var result = es6tr.run(options);
var transpiledContent = result.src;
result.errors.forEach(function(err) { |
3651031dc09ea89f35ffc67363af07f444f2caf7 | index.js | index.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
var emitThen = function (event) {
var args = Array.prototype.slice.call(arguments, 1);
return Promise
.bind(this)
.return(this)
.call('listeners', event)
.map(function (listener) {
var a1 = args[0], a2 = args[1];
switch (args.length) {
case 0: return listener.call(this);
case 1: return listener.call(this, a1)
case 2: return listener.call(this, a1, a2);
default: return listener.apply(this, args);
}
})
.return(null);
};
emitThen.register = function () {
EventEmitter.prototype.emitThen = emitThen;
};
module.exports = emitThen; | 'use strict';
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
function emitThen (event) {
var args = Array.prototype.slice.call(arguments, 1);
/* jshint validthis:true */
return Promise
.bind(this)
.return(this)
.call('listeners', event)
.map(function (listener) {
var a1 = args[0], a2 = args[1];
switch (args.length) {
case 0: return listener.call(this);
case 1: return listener.call(this, a1)
case 2: return listener.call(this, a1, a2);
default: return listener.apply(this, args);
}
})
.return(null);
}
emitThen.register = function () {
EventEmitter.prototype.emitThen = emitThen;
};
module.exports = emitThen; | Use a named function instead of anon | Use a named function instead of anon
| JavaScript | mit | bendrucker/emit-then | ---
+++
@@ -3,8 +3,9 @@
var EventEmitter = require('events').EventEmitter;
var Promise = require('bluebird');
-var emitThen = function (event) {
+function emitThen (event) {
var args = Array.prototype.slice.call(arguments, 1);
+ /* jshint validthis:true */
return Promise
.bind(this)
.return(this)
@@ -19,7 +20,7 @@
}
})
.return(null);
-};
+}
emitThen.register = function () {
EventEmitter.prototype.emitThen = emitThen; |
8fd6bc21784da5a9cb1bb22ba515b85fb9f8f1a3 | index.js | index.js | var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization"
};
var proxy = httpProxy.createProxyServer();
http.createServer(function(req, res) {
if (req.method === 'OPTIONS') {
// Respond to OPTIONS requests advertising we support full CORS for *
res.writeHead(200, CORS_HEADERS);
res.end();
return
}
// Remove our original host so it doesn't mess up Google's header parsing.
delete req.headers.host;
proxy.web(req, res, {
target: 'https://spreadsheets.google.com:443',
xfwd: false
});
// Add CORS headers to every other request also.
proxy.on('proxyRes', function(proxyRes, req, res) {
for (var key in CORS_HEADERS) {
proxyRes.headers[key] = CORS_HEADERS[key];
}
});
}).listen(process.env.PORT || 5000);
| var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization"
};
var proxy = httpProxy.createProxyServer();
// Add CORS headers to every other request also.
proxy.on('proxyRes', function(proxyRes, req, res) {
for (var key in CORS_HEADERS) {
proxyRes.headers[key] = CORS_HEADERS[key];
}
});
proxy.on('error', function(err, req, res) {
console.log(err);
var json = { error: 'proxy_error', reason: err.message };
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
res.end(JSON.stringify(json));
});
http.createServer(function(req, res) {
if (req.method === 'OPTIONS') {
// Respond to OPTIONS requests advertising we support full CORS for *
res.writeHead(200, CORS_HEADERS);
res.end();
return
}
// Remove our original host so it doesn't mess up Google's header parsing.
delete req.headers.host;
proxy.web(req, res, {
target: 'https://spreadsheets.google.com:443',
xfwd: false
});
}).listen(process.env.PORT || 5000);
| Move proxyRes out of request handler; trap errors | Move proxyRes out of request handler; trap errors
| JavaScript | mpl-2.0 | yourcelf/gspreadsheets-cors-proxy | ---
+++
@@ -10,6 +10,20 @@
var proxy = httpProxy.createProxyServer();
+// Add CORS headers to every other request also.
+proxy.on('proxyRes', function(proxyRes, req, res) {
+ for (var key in CORS_HEADERS) {
+ proxyRes.headers[key] = CORS_HEADERS[key];
+ }
+});
+proxy.on('error', function(err, req, res) {
+ console.log(err);
+ var json = { error: 'proxy_error', reason: err.message };
+ if (!res.headersSent) {
+ res.writeHead(500, {'content-type': 'application/json'});
+ }
+ res.end(JSON.stringify(json));
+});
http.createServer(function(req, res) {
if (req.method === 'OPTIONS') {
// Respond to OPTIONS requests advertising we support full CORS for *
@@ -23,10 +37,4 @@
target: 'https://spreadsheets.google.com:443',
xfwd: false
});
- // Add CORS headers to every other request also.
- proxy.on('proxyRes', function(proxyRes, req, res) {
- for (var key in CORS_HEADERS) {
- proxyRes.headers[key] = CORS_HEADERS[key];
- }
- });
}).listen(process.env.PORT || 5000); |
10280069a4c1ecf5cbaebd8b0f9b67f3d9c219d2 | index.js | index.js | 'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'sudo';
var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid];
var ret;
execFile(cmd, args, function (err, stdout) {
if (err) {
cb(err);
return;
}
ret = /^\s*psk=(.+)\s*$/gm.exec(stdout);
ret = ret && ret.length ? ret[1] : null;
if (!ret) {
cb(new Error('Could not get password'));
return;
}
cb(null, ret);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'linux') {
throw new Error('Only Linux systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
| 'use strict';
var execFile = require('child_process').execFile;
var wifiName = require('wifi-name');
function getPassword(ssid, cb) {
var cmd = 'sudo';
var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid];
var ret;
execFile(cmd, args, function (err, stdout) {
if (err) {
cb(err);
return;
}
ret = /^\s*(?:psk|password)=(.+)\s*$/gm.exec(stdout);
ret = ret && ret.length ? ret[1] : null;
if (!ret) {
cb(new Error('Could not get password'));
return;
}
cb(null, ret);
});
}
module.exports = function (ssid, cb) {
if (process.platform !== 'linux') {
throw new Error('Only Linux systems are supported');
}
if (ssid && typeof ssid !== 'function') {
getPassword(ssid, cb);
return;
} else if (ssid && !cb) {
cb = ssid;
}
wifiName(function (err, name) {
if (err) {
cb(err);
return;
}
getPassword(name, cb);
});
};
| Add support for WPA2 Enterprise | Add support for WPA2 Enterprise
Fixes #1.
| JavaScript | mit | kevva/linux-wifi-password | ---
+++
@@ -13,7 +13,7 @@
return;
}
- ret = /^\s*psk=(.+)\s*$/gm.exec(stdout);
+ ret = /^\s*(?:psk|password)=(.+)\s*$/gm.exec(stdout);
ret = ret && ret.length ? ret[1] : null;
if (!ret) { |
4683e61d4d3eb6fb696f5e5672831b1f0de0d3db | index.js | index.js | 'use strict';
const EventEmitter = require('events');
const devtools = require('./lib/devtools.js');
const Chrome = require('./lib/chrome.js');
function CDP(options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
const notifier = new EventEmitter();
if (typeof callback === 'function') {
// allow to register the error callback later
process.nextTick(() => {
new Chrome(options, notifier);
});
return notifier.once('connect', callback);
} else {
return new Promise((fulfill, reject) => {
notifier.once('connect', fulfill);
notifier.once('error', reject);
new Chrome(options, notifier);
});
}
}
module.exports = CDP;
module.exports.Protocol = devtools.Protocol;
module.exports.List = devtools.List;
module.exports.New = devtools.New;
module.exports.Activate = devtools.Activate;
module.exports.Close = devtools.Close;
module.exports.Version = devtools.Version;
| 'use strict';
const EventEmitter = require('events');
const dns = require('dns');
const devtools = require('./lib/devtools.js');
const Chrome = require('./lib/chrome.js');
// XXX reset the default that has been changed in
// (https://github.com/nodejs/node/pull/39987) to prefer IPv4. since
// implementations alway bind on 127.0.0.1 this solution should be fairly safe
// (see #467)
dns.setDefaultResultOrder('ipv4first');
function CDP(options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
const notifier = new EventEmitter();
if (typeof callback === 'function') {
// allow to register the error callback later
process.nextTick(() => {
new Chrome(options, notifier);
});
return notifier.once('connect', callback);
} else {
return new Promise((fulfill, reject) => {
notifier.once('connect', fulfill);
notifier.once('error', reject);
new Chrome(options, notifier);
});
}
}
module.exports = CDP;
module.exports.Protocol = devtools.Protocol;
module.exports.List = devtools.List;
module.exports.New = devtools.New;
module.exports.Activate = devtools.Activate;
module.exports.Close = devtools.Close;
module.exports.Version = devtools.Version;
| Revert the default DNS lookup order to IPv4-first | Revert the default DNS lookup order to IPv4-first
Fix #467
| JavaScript | mit | cyrus-and/chrome-remote-interface,cyrus-and/chrome-remote-interface | ---
+++
@@ -1,9 +1,16 @@
'use strict';
const EventEmitter = require('events');
+const dns = require('dns');
const devtools = require('./lib/devtools.js');
const Chrome = require('./lib/chrome.js');
+
+// XXX reset the default that has been changed in
+// (https://github.com/nodejs/node/pull/39987) to prefer IPv4. since
+// implementations alway bind on 127.0.0.1 this solution should be fairly safe
+// (see #467)
+dns.setDefaultResultOrder('ipv4first');
function CDP(options, callback) {
if (typeof options === 'function') { |
864ce5aa89a99b17051bb41ce243490b8be0d4a1 | index.js | index.js | 'use strict'
var postcss = require('postcss')
var isVendorPrefixed = require('is-vendor-prefixed')
module.exports = postcss.plugin('postcss-remove-prefixes', function (options) {
if (!options) {
options = {};
}
var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : [];
if (ignore === false) {
throw TypeError("options.ignore must be an array")
}
for (var i = 0; i < ignore.length; ++i) {
var value = ignore[i];
if (typeof value === "string") {
value = new RegExp(value + "$", "i")
} else if (value instanceof RegExp) {
} else {
throw TypeError("options.ignore values can either be a string or a regular expression")
}
ignore[i] = value;
}
return function removePrefixes(root, result) {
root.walkDecls(function (declaration) {
if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) {
var isIgnored = false;
for (var i = 0; i < ignore.length; ++i) {
var value = ignore[i];
if (value.test(declaration.prop)) {
isIgnored = true;
break;
}
}
if (!isIgnored) {
declaration.remove()
}
}
})
}
})
| 'use strict'
var postcss = require('postcss')
var isVendorPrefixed = require('is-vendor-prefixed')
module.exports = postcss.plugin('postcss-remove-prefixes', function (options) {
if (!options) {
options = {
ignore: []
}
}
if (!Array.isArray(options.ignore)) {
throw TypeError("options.ignore must be an array")
}
var ignore = options.ignore.map(function (value) {
if (typeof value === 'string') {
return new RegExp(value + '$', 'i')
} else if (value instanceof RegExp) {
return value
} else {
throw TypeError('options.ignore values can either be a string or a regular expression')
}
})
return function removePrefixes(root, result) {
root.walkDecls(function (declaration) {
if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) {
var isIgnored = false;
for (var i = 0; i < ignore.length; ++i) {
var value = ignore[i];
if (value.test(declaration.prop)) {
isIgnored = true;
break;
}
}
if (!isIgnored) {
declaration.remove()
}
}
})
}
})
| Change code as per @johnotander's suggestion | Change code as per @johnotander's suggestion
| JavaScript | mit | johnotander/postcss-remove-prefixes | ---
+++
@@ -5,28 +5,24 @@
module.exports = postcss.plugin('postcss-remove-prefixes', function (options) {
if (!options) {
- options = {};
+ options = {
+ ignore: []
+ }
}
- var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : [];
-
- if (ignore === false) {
+ if (!Array.isArray(options.ignore)) {
throw TypeError("options.ignore must be an array")
}
- for (var i = 0; i < ignore.length; ++i) {
- var value = ignore[i];
-
- if (typeof value === "string") {
- value = new RegExp(value + "$", "i")
+ var ignore = options.ignore.map(function (value) {
+ if (typeof value === 'string') {
+ return new RegExp(value + '$', 'i')
} else if (value instanceof RegExp) {
-
+ return value
} else {
- throw TypeError("options.ignore values can either be a string or a regular expression")
+ throw TypeError('options.ignore values can either be a string or a regular expression')
}
-
- ignore[i] = value;
- }
+ })
return function removePrefixes(root, result) {
root.walkDecls(function (declaration) { |
48db09838c934b349250efbada6aadcc95fece9c | index.js | index.js | /* jshint node: true */
'use strict';
var path = require('path');
var filterInitializers = require('fastboot-filter-initializers');
var VersionChecker = require('ember-cli-version-checker');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-head',
treeForApp: function(defaultTree) {
var checker = new VersionChecker(this);
var emberVersion = checker.for('ember', 'bower');
var trees = [defaultTree];
// 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not)
// 2.10.0-beta.1+ includes glimmer2
if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) {
trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10')));
}
var tree = mergeTrees(trees, { overwrite: true });
return filterInitializers(tree);
}
};
| /* jshint node: true */
'use strict';
var path = require('path');
var filterInitializers = require('fastboot-filter-initializers');
var VersionChecker = require('ember-cli-version-checker');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-head',
treeForApp: function(defaultTree) {
var checker = new VersionChecker(this);
var emberVersion = checker.for('ember-source', 'npm');
if (!emberVersion.version) {
emberVersion = checker.for('ember', 'bower');
}
var trees = [defaultTree];
// 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not)
// 2.10.0-beta.1+ includes glimmer2
if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) {
trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10')));
}
var tree = mergeTrees(trees, { overwrite: true });
return filterInitializers(tree);
}
};
| Check ember-source version from NPM, if not found use ember from bower | Check ember-source version from NPM, if not found use ember from bower
| JavaScript | mit | ronco/ember-cli-head,ronco/ember-cli-head | ---
+++
@@ -11,7 +11,11 @@
treeForApp: function(defaultTree) {
var checker = new VersionChecker(this);
- var emberVersion = checker.for('ember', 'bower');
+ var emberVersion = checker.for('ember-source', 'npm');
+
+ if (!emberVersion.version) {
+ emberVersion = checker.for('ember', 'bower');
+ }
var trees = [defaultTree];
|
28e666a0419b17cfa85a8e340927fd9cd691d045 | index.js | index.js | module.exports = function (path) {
var req = require;
return function (module_name) {
try {
return req(module_name);
} catch (err) {
var resolve = null;
req.main.paths.some(function (item) {
if (resolve) return true;
item = item.replace('node_modules', path);
try {
var main = req(item + '/' + module_name + '/package.json').main;
main = item + '/' + module_name + '/' + main;
req(main);
resolve = main;
} catch (e) {} // do nothing
});
if (!resolve) throw err;
return req(resolve)
}
};
};
| var path = require('path');
module.exports = function (pathname) {
var req = require;
return function (module_name) {
try {
return req(module_name);
} catch (err) {
var resolve = null;
req.main.paths.some(function (item) {
if (resolve) return true;
item = item.replace('node_modules', pathname);
try {
var main = path.join(item, module_name, 'package.json');
main = req(main).main;
main = path.join(item, module_name, main);
req(main);
resolve = main;
} catch (e) {} // do nothing
});
if (!resolve) throw err;
return req(resolve)
}
};
};
| Add path for supporting Windows | Add path for supporting Windows
| JavaScript | mit | watilde/graceful-require | ---
+++
@@ -1,4 +1,5 @@
-module.exports = function (path) {
+var path = require('path');
+module.exports = function (pathname) {
var req = require;
return function (module_name) {
try {
@@ -7,10 +8,11 @@
var resolve = null;
req.main.paths.some(function (item) {
if (resolve) return true;
- item = item.replace('node_modules', path);
+ item = item.replace('node_modules', pathname);
try {
- var main = req(item + '/' + module_name + '/package.json').main;
- main = item + '/' + module_name + '/' + main;
+ var main = path.join(item, module_name, 'package.json');
+ main = req(main).main;
+ main = path.join(item, module_name, main);
req(main);
resolve = main;
} catch (e) {} // do nothing |
955c5abe4bc2843df9c88124776207e83292d157 | index.js | index.js | import bluebird from 'bluebird'
import consoleStamp from 'console-stamp'
import 'newrelic';
import { getSingleton as initApp } from './app/app'
global.Promise = bluebird
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l')
initApp()
.then((app) => {
app.logger.info(`Server initialization is complete`)
})
.catch((e) => {
process.stderr.write(`FATAL ERROR\n`)
process.stderr.write(`${e.message}\n`)
process.stderr.write(`${e.stack}\n`)
process.exit(1)
})
| import { statSync } from 'fs';
import bluebird from 'bluebird'
import consoleStamp from 'console-stamp'
import { getSingleton as initApp } from './app/app'
try {
statSync(`${__dirname}/newrelic.js`);
require('newrelic');
} catch (e) {
// No newrelic's config found. Won't report stats to them
}
global.Promise = bluebird
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
consoleStamp(console, 'yyyy/mm/dd HH:MM:ss.l')
initApp()
.then((app) => {
app.logger.info(`Server initialization is complete`)
})
.catch((e) => {
process.stderr.write(`FATAL ERROR\n`)
process.stderr.write(`${e.message}\n`)
process.stderr.write(`${e.stack}\n`)
process.exit(1)
})
| Enable newrelic only if config exists | Enable newrelic only if config exists
| JavaScript | mit | FreeFeed/freefeed-server,SiTLar/freefeed-server,SiTLar/freefeed-server,golozubov/freefeed-server,golozubov/freefeed-server,FreeFeed/freefeed-server | ---
+++
@@ -1,9 +1,17 @@
+import { statSync } from 'fs';
+
import bluebird from 'bluebird'
import consoleStamp from 'console-stamp'
-import 'newrelic';
import { getSingleton as initApp } from './app/app'
+
+try {
+ statSync(`${__dirname}/newrelic.js`);
+ require('newrelic');
+} catch (e) {
+ // No newrelic's config found. Won't report stats to them
+}
global.Promise = bluebird
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; }); |
346b58a0e4693f9bb25ca4271e7518a3a027983d | index.js | index.js | var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = { from: file, to: file };
if ( params.safe ) opts.safe = true;
var processors = this.options.postcss;
if ( params.pack ) {
processors = processors[params.pack];
} else if ( !Array.isArray(processors) ) {
processors = processors.defaults;
}
var processed = postcss.apply(postcss, processors).process(source, opts);
this.callback(null, processed.css, processed.map);
};
| var loaderUtils = require('loader-utils');
var postcss = require('postcss');
module.exports = function (source, map) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
var opts = { from: file, to: file, map: { prev: map, inline: false } };
if ( params.safe ) opts.safe = true;
var processors = this.options.postcss;
if ( params.pack ) {
processors = processors[params.pack];
} else if ( !Array.isArray(processors) ) {
processors = processors.defaults;
}
var processed = postcss.apply(postcss, processors).process(source, opts);
this.callback(null, processed.css, processed.map);
};
| Use previous source map and don't inline the source maps. | Use previous source map and don't inline the source maps.
This fixes source mapping when used with sass-loader.
Also, we don't want to map to the postcss generated source, we want to map to the pre-postcss source.
| JavaScript | mit | mokevnin/postcss-loader | ---
+++
@@ -1,13 +1,13 @@
var loaderUtils = require('loader-utils');
var postcss = require('postcss');
-module.exports = function (source) {
+module.exports = function (source, map) {
if ( this.cacheable ) this.cacheable();
var file = loaderUtils.getRemainingRequest(this);
var params = loaderUtils.parseQuery(this.query);
- var opts = { from: file, to: file };
+ var opts = { from: file, to: file, map: { prev: map, inline: false } };
if ( params.safe ) opts.safe = true;
var processors = this.options.postcss; |
2b8f476de5049d3d0933ca1712f1c22190a250cf | index.js | index.js | var toc = require('markdown-toc');
module.exports = {
book: {},
hooks: {
"page:before": function (page) {
page.content = toc.insert(page.content, {
slugify: function (str) {
return encodeURI(str.toLowerCase()).replace(/%20/g, '-').replace(/[\.,\-\(\)]/g,'');
}
});
if (this.options.pluginsConfig.atoc.addClass) {
var className = this.options.pluginsConfig.atoc.className || 'atoc';
page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>';
}
return page;
}
}
};
| var toc = require('markdown-toc');
module.exports = {
book: {},
hooks: {
"page:before": function (page) {
page.content = toc.insert(page.content, {
slugify: function (str) {
return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-');
}
});
if (this.options.pluginsConfig.atoc.addClass) {
var className = this.options.pluginsConfig.atoc.className || 'atoc';
page.content = page.content + '\n\n\n<script type="text/javascript">var targetUl = document.getElementsByClassName(\'page-inner\')[0].getElementsByTagName(\'ul\')[0];if(targetUl&&targetUl.getElementsByTagName(\'a\').length>0){targetUl.className=\'' + className + '\';}</script>';
}
return page;
}
}
};
| Fix every case a special character is suppressed | Fix every case a special character is suppressed
I refer to https://github.com/jonschlinkert/remarkable/blob/dev/lib/common/utils.js#L45 for regex writing. | JavaScript | mit | willin/gitbook-plugin-atoc | ---
+++
@@ -6,7 +6,7 @@
"page:before": function (page) {
page.content = toc.insert(page.content, {
slugify: function (str) {
- return encodeURI(str.toLowerCase()).replace(/%20/g, '-').replace(/[\.,\-\(\)]/g,'');
+ return encodeURI(str.toLowerCase().replace(/[\\!"#$%&'()*+,.\/:;<=>?@[\]^_`{|}~-]/g,'')).replace(/%20/g, '-');
}
});
if (this.options.pluginsConfig.atoc.addClass) { |
f681c2e21fe5b84d97d22a909103ddd64db5b1e1 | index.js | index.js | const createUrl = require('./lib/create-url');
const downloadAndSave = require('./lib/download-and-save');
const parsePage = require('./lib/parse-page');
module.exports = save;
/**
* @param {string} urlOrMediaId
* @return {Promise}
*/
function save(urlOrMediaId, dir) {
return new Promise((resolve, reject) => {
const url = createUrl(urlOrMediaId);
parsePage(url)
.then(post => {
const downloadUrl = post.downloadUrl;
const filename = post.filename;
const isVideo = post.isVideo;
const mimeType = post.mimeType;
const file = `${dir}/${filename}`;
downloadAndSave(downloadUrl, filename).then(() => {
return resolve({
file,
mimeType,
url,
label: isVideo ? 'video' : 'photo',
source: downloadUrl
});
});
})
.catch(err => {
return reject({
url,
error: err,
message: `Download failed`
});
});
});
}
| const createUrl = require('./lib/create-url');
const downloadAndSave = require('./lib/download-and-save');
const parsePage = require('./lib/parse-page');
module.exports = save;
/**
* @param {string} urlOrMediaId
* @return {Promise}
*/
function save(urlOrMediaId, dir) {
return new Promise((resolve, reject) => {
const url = createUrl(urlOrMediaId);
parsePage(url)
.then(post => {
const downloadUrl = post.downloadUrl;
const filename = post.filename;
const isVideo = post.isVideo;
const mimeType = post.mimeType;
const file = `${dir}/${filename}`;
downloadAndSave(downloadUrl, file).then(() => {
return resolve({
file,
mimeType,
url,
label: isVideo ? 'video' : 'photo',
source: downloadUrl
});
});
})
.catch(err => {
return reject({
url,
error: err,
message: `Download failed`
});
});
});
}
| Fix for dir being ignored when supplied and files always saved to cwd. | Fix for dir being ignored when supplied and files always saved to cwd.
| JavaScript | mit | ericnishio/instagram-save | ---
+++
@@ -20,7 +20,7 @@
const mimeType = post.mimeType;
const file = `${dir}/${filename}`;
- downloadAndSave(downloadUrl, filename).then(() => {
+ downloadAndSave(downloadUrl, file).then(() => {
return resolve({
file,
mimeType, |
9fc664fcacbd8149b06a6b80e62f7a1d4e8609e4 | index.js | index.js | var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
var objectAssign = require('object-assign');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var queryOptions = loaderUtils.parseQuery(this.query);
var options;
if (queryOptions) {
options = objectAssign({}, queryOptions);
}
var creator = new DtsCreator(options);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
// Emit the created content as well
this.emitFile(this.resourcePath + '.d.ts', content.contents || ['']);
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
var objectAssign = require('object-assign');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var queryOptions = loaderUtils.parseQuery(this.query);
var options;
if (queryOptions) {
options = objectAssign({}, queryOptions);
}
var creator = new DtsCreator(options);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
// Emit the created content as well
this.emitFile(content.outputFilePath, content.contents || [''], map);
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| Use content.outputFilePath and use pass sourcemap | Use content.outputFilePath and use pass sourcemap | JavaScript | mit | olegstepura/typed-css-modules-loader | ---
+++
@@ -21,7 +21,7 @@
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
// Emit the created content as well
- this.emitFile(this.resourcePath + '.d.ts', content.contents || ['']);
+ this.emitFile(content.outputFilePath, content.contents || [''], map);
content.writeFile().then(_ => {
callback(null, source, map);
}); |
185c90d862bccb2061f00bf2f4e6858cbb0eb660 | index.js | index.js | 'use strict'
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
config = require('./libs/config'),
email = require('./libs/email')
app.use(bodyParser.json())
app.post('/subscribe', email.subscribe)
app.listen(config.port)
| 'use strict'
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
config = require('./libs/config'),
email = require('./libs/email')
app.use(bodyParser.json())
app.post('/subscribe', email.subscribe)
app.listen(process.env.PORT || config.port)
| Allow PORT to be set from cli | Allow PORT to be set from cli | JavaScript | mit | MakerFaireOrlando/mfo-server | ---
+++
@@ -9,4 +9,4 @@
app.post('/subscribe', email.subscribe)
-app.listen(config.port)
+app.listen(process.env.PORT || config.port) |
0d62962e33a670ae3459d936ea7b95d2782eb340 | index.js | index.js | /* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
if (!process.env.TOKEN || !process.env.PORT) {
console.log('Error: Specify token and port in environment');
process.exit(1);
}
var config = {}
if(process.env.MONGOLAB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_bot/',
};
}
var controller = Botkit.slackbot(config);
controller.spawn({
token: process.env.TOKEN
}).startRTM(function(err) {
if (err) {
throw new Error(err);
}
});
// BEGIN EDITING HERE!
controller.hears('hello','direct_message',function(bot,message) {
bot.reply(message,'Hello!');
});
controller.hears('^stop','direct_message',function(bot,message) {
bot.reply(message,'Goodbye');
bot.rtm.close();
});
controller.on('direct_message,mention,direct_mention',function(bot,message) {
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: 'robot_face',
},function(err) {
if (err) { console.log(err) }
bot.reply(message,'I heard you loud and clear boss.');
});
});
| /* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
if (!process.env.TOKEN) {
console.log('Error: Missing environment variable TOKEN. Please Specify your Slack token in environment');
process.exit(1);
}
var config = {}
if(process.env.MONGOLAB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_bot/',
};
}
var controller = Botkit.slackbot(config);
controller.spawn({
token: process.env.TOKEN
}).startRTM(function(err) {
if (err) {
throw new Error(err);
}
});
// BEGIN EDITING HERE!
controller.hears('hello','direct_message',function(bot,message) {
bot.reply(message,'Hello!');
});
// An example of what could be...
//
//controller.on('direct_message,mention,direct_mention',function(bot,message) {
// bot.api.reactions.add({
// timestamp: message.ts,
// channel: message.channel,
// name: 'robot_face',
// },function(err) {
// if (err) { console.log(err) }
// bot.reply(message,'I heard you loud and clear boss.');
// });
//});
| Tidy things up, remove requirement for PORT env var | Tidy things up, remove requirement for PORT env var
| JavaScript | mit | slackhq/easy-peasy-bot-custom-integration | ---
+++
@@ -1,8 +1,8 @@
/* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
-if (!process.env.TOKEN || !process.env.PORT) {
- console.log('Error: Specify token and port in environment');
+if (!process.env.TOKEN) {
+ console.log('Error: Missing environment variable TOKEN. Please Specify your Slack token in environment');
process.exit(1);
}
@@ -35,19 +35,17 @@
bot.reply(message,'Hello!');
});
-controller.hears('^stop','direct_message',function(bot,message) {
- bot.reply(message,'Goodbye');
- bot.rtm.close();
-});
-controller.on('direct_message,mention,direct_mention',function(bot,message) {
- bot.api.reactions.add({
- timestamp: message.ts,
- channel: message.channel,
- name: 'robot_face',
- },function(err) {
- if (err) { console.log(err) }
- bot.reply(message,'I heard you loud and clear boss.');
- });
-});
+// An example of what could be...
+//
+//controller.on('direct_message,mention,direct_mention',function(bot,message) {
+// bot.api.reactions.add({
+// timestamp: message.ts,
+// channel: message.channel,
+// name: 'robot_face',
+// },function(err) {
+// if (err) { console.log(err) }
+// bot.reply(message,'I heard you loud and clear boss.');
+// });
+//});
|
172ffddb3645f508093fac4e6d2d355c0c3e7d5a | index.js | index.js | var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
callback(null, data);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
}; | var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var yaml = require('js-yaml');
// const s3EnvVars = require('s3-env-vars');
// var doc = s3EnvVars("mybucketname", "folderpathinbucket", "filename", function(err, data) {
// if(err) console.log(err);
// else console.log(data);
// });
module.exports = function(bucket, path, filename, callback) {
var s3Params = {
Bucket: bucket,
Key: path + "/" + filename
};
s3.getObject(s3Params, function(err, data) {
if (err) callback(err, err.stack); // an error occurred
else {
try {
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
callback(null, doc);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
}
}
});
}; | Send back the doc not the s3 object | Send back the doc not the s3 object
| JavaScript | mit | Referly/lambda-s3-yml | ---
+++
@@ -19,7 +19,7 @@
console.log('info: ', "Retrieved s3 object.");
var doc = yaml.safeLoad(data.Body);
console.log('data: ', "yml file contents: ", doc);
- callback(null, data);
+ callback(null, doc);
} catch (e) {
callback(err, err.stack); // an error occurred reading the yml file
} |
8b2da192dbc26d7354ec1db9d101ae4c927b1bc6 | src/state/middleware.js | src/state/middleware.js | import dataComplete from './actions/dataComplete';
import preprocessData from './actions/preprocessData';
import readFile from '../functions/file/readFile';
import preprocessFile from '../functions/file/preprocessFile';
import { PREPROCESSDATA, READDATA } from './constants';
const middleware = store => next => action => {
const state = store.getState();
switch (action.type) {
case READDATA:
if (!state.coordIn || !state.fileIn) {
console.error('Input fields not filled properly!');
break;
}
next(action);
readFile(state.fileInList)
.then(data => {
store.dispatch(preprocessData(data));
}).catch(error => {
console.error(error.message);
});
break;
case PREPROCESSDATA:
preprocessFile(action.payload)
.then(data => {
store.dispatch(dataComplete(data));
}).catch(error => {
console.error(error.message);
});
break;
default:
next(action);
}
};
export default middleware;
| import dataComplete from './actions/dataComplete';
import preprocessData from './actions/preprocessData';
import readFile from '../functions/file/readFile';
import preprocessFile from '../functions/file/preprocessFile';
import parseCoordinates from '../functions/parseCoordinates';
import issetCoordinates from '../functions/issetCoordinates';
import { PREPROCESSDATA, READDATA } from './constants';
const checkCoordinates = coordinates => issetCoordinates(parseCoordinates(coordinates));
const middleware = store => next => action => {
const state = store.getState();
switch (action.type) {
case READDATA:
if (!state.coordIn || !state.fileIn || !checkCoordinates(state.coordIn)) {
console.error('Input fields not filled properly!');
break;
}
next(action);
readFile(state.fileInList)
.then(data => {
store.dispatch(preprocessData(data));
}).catch(error => {
console.error(error.message);
});
break;
case PREPROCESSDATA:
preprocessFile(action.payload)
.then(data => {
store.dispatch(dataComplete(data));
}).catch(error => {
console.error(error.message);
});
break;
default:
next(action);
}
};
export default middleware;
| Check passed coordinates to be correct | Check passed coordinates to be correct
| JavaScript | mit | krajvy/nearest-coordinates,krajvy/nearest-coordinates,krajvy/nearest-coordinates | ---
+++
@@ -2,15 +2,19 @@
import preprocessData from './actions/preprocessData';
import readFile from '../functions/file/readFile';
import preprocessFile from '../functions/file/preprocessFile';
+import parseCoordinates from '../functions/parseCoordinates';
+import issetCoordinates from '../functions/issetCoordinates';
import { PREPROCESSDATA, READDATA } from './constants';
+
+const checkCoordinates = coordinates => issetCoordinates(parseCoordinates(coordinates));
const middleware = store => next => action => {
const state = store.getState();
switch (action.type) {
case READDATA:
- if (!state.coordIn || !state.fileIn) {
+ if (!state.coordIn || !state.fileIn || !checkCoordinates(state.coordIn)) {
console.error('Input fields not filled properly!');
break;
} |
c2c4730b4554357f394c3ecb9bae3e465cc4a154 | lib/middleware/campaign-keyword.js | lib/middleware/campaign-keyword.js | 'use strict';
const Campaigns = require('../../app/models/Campaign');
module.exports = function getCampaignForKeyword() {
return (req, res, next) => {
if (req.reply.template) {
return next();
}
return Campaigns.findByKeyword(req.userCommand)
.then((campaign) => {
if (! campaign) {
return next();
}
req.campaign = campaign;
req.keyword = req.userCommand;
return next();
});
};
};
| 'use strict';
const Campaigns = require('../../app/models/Campaign');
module.exports = function getCampaignForKeyword() {
return (req, res, next) => {
if (req.reply.template) {
return next();
}
// Did User send a Campaign keyword?
return Campaigns.findByKeyword(req.userCommand)
.then((campaign) => {
if (! campaign) {
return next();
}
req.campaign = campaign;
req.keyword = req.userCommand;
// Gambit to handle the Confirmation/Continue reply.
req.reply.template = 'gambit';
return next();
});
};
};
| Fix Campaign keyword, send Gambit reply | Fix Campaign keyword, send Gambit reply
| JavaScript | mit | DoSomething/gambit,DoSomething/gambit | ---
+++
@@ -8,6 +8,7 @@
return next();
}
+ // Did User send a Campaign keyword?
return Campaigns.findByKeyword(req.userCommand)
.then((campaign) => {
if (! campaign) {
@@ -16,6 +17,8 @@
req.campaign = campaign;
req.keyword = req.userCommand;
+ // Gambit to handle the Confirmation/Continue reply.
+ req.reply.template = 'gambit';
return next();
}); |
823ecb6eb0f78d51b950fbe382b73769c8502c58 | build-prod.js | build-prod.js | ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| ({
mainConfigFile: './requirejs.conf.js',
paths: {
jquery: 'lib/jquery/jquery.min',
almond: 'lib/almond/almond'
},
baseUrl: '.',
name: "streamhub-map",
exclude: ['streamhub-sdk', 'almond'],
stubModules: ['text', 'hgn', 'json'],
out: "./dist/streamhub-map.min.js",
namespace: 'Livefyre',
pragmasOnSave: {
excludeHogan: true
},
cjsTranslate: true,
optimize: "uglify2",
uglify2: {
compress: {
unsafe: true
},
mangle: true
},
onBuildRead: function(moduleName, path, contents) {
if (moduleName == "jquery") {
contents = "define([], function(require, exports, module) {" + contents + "});";
}
return contents;
}
})
| Add 'cjsTranslate' config option to build profile | Add 'cjsTranslate' config option to build profile
| JavaScript | mit | cheung31/streamhub-map,Livefyre/streamhub-map,Livefyre/streamhub-map | ---
+++
@@ -13,6 +13,7 @@
pragmasOnSave: {
excludeHogan: true
},
+ cjsTranslate: true,
optimize: "uglify2",
uglify2: {
compress: { |
af0c5f7cbbfb29a962477160976f8a048eb493d1 | cache-bust.js | cache-bust.js | /** @license MIT License (c) copyright 2014 original authors */
/** @author Brian Cavalier */
/** @author John Hann */
define(['curl/_privileged'], function (priv) {
var loadScript = priv['core'].loadScript;
priv['core'].loadScript = function (def, success, failure) {
var urlArgs = priv['config']()['urlArgs'];
if (urlArgs) {
def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs;
}
return loadScript(def, success, failure);
};
});
| /** @license MIT License (c) copyright 2014 original authors */
/** @author John Hann */
define(/*==='curl-cache-bust/cache-bust',===*/ ['curl/_privileged'], function (priv) {
var loadScript = priv['core'].loadScript;
priv['core'].loadScript = function (def, success, failure) {
var urlArgs = priv['config']()['urlArgs'];
if (urlArgs) {
def.url += (def.url.indexOf('?') >= 0 ? '&' : '?') + urlArgs;
}
return loadScript(def, success, failure);
};
});
| Add replaceable module id for curl's make utility. | Add replaceable module id for curl's make utility.
| JavaScript | mit | unscriptable/curl-cache-bust | ---
+++
@@ -1,8 +1,7 @@
/** @license MIT License (c) copyright 2014 original authors */
-/** @author Brian Cavalier */
/** @author John Hann */
-define(['curl/_privileged'], function (priv) {
+define(/*==='curl-cache-bust/cache-bust',===*/ ['curl/_privileged'], function (priv) {
var loadScript = priv['core'].loadScript;
priv['core'].loadScript = function (def, success, failure) { |
9493463612fae494ee5f1f644e379b876b8c5655 | app/routes.js | app/routes.js | import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store from 'lib/store';
import App from 'components/app';
import AdminDashboard from 'components/admin-dashboard';
import ImportPanel from 'components/import';
import ExportPanel from 'components/export';
import LoggedIn from 'components/logged-in';
export default (
<Provider store={ store }>
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute component={ LoggedIn } />
<Route path="/admin" component={ AdminDashboard } />
<Route path="/import" component={ ImportPanel } />
<Route path="/export" component={ ExportPanel } />
</Route>
</Router>
</Provider>
);
| import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store from 'lib/store';
import App from 'components/app';
import ImportPanel from 'components/import';
import ExportPanel from 'components/export';
import LoggedIn from 'components/logged-in';
export default (
<Provider store={ store }>
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute component={ LoggedIn } />
<Route path="/import" component={ ImportPanel } />
<Route path="/export" component={ ExportPanel } />
</Route>
</Router>
</Provider>
);
| Remove admin dashboard for now | Remove admin dashboard for now
| JavaScript | mit | sirbrillig/voyageur-js-client,sirbrillig/voyageur-js-client | ---
+++
@@ -3,7 +3,6 @@
import { Provider } from 'react-redux';
import store from 'lib/store';
import App from 'components/app';
-import AdminDashboard from 'components/admin-dashboard';
import ImportPanel from 'components/import';
import ExportPanel from 'components/export';
import LoggedIn from 'components/logged-in';
@@ -13,7 +12,6 @@
<Router history={ browserHistory }>
<Route path="/" component={ App }>
<IndexRoute component={ LoggedIn } />
- <Route path="/admin" component={ AdminDashboard } />
<Route path="/import" component={ ImportPanel } />
<Route path="/export" component={ ExportPanel } />
</Route> |
91266e20e67cb920c86c014202a906af55b387bd | src/renderer/reducers/connections.js | src/renderer/reducers/connections.js | import * as types from '../actions/connections';
export default function(state = {}, action) {
switch (action.type) {
case types.CONNECTION_REQUEST: {
const { server, database } = action;
return { connected: false, connecting: true, server, database };
}
case types.CONNECTION_SUCCESS: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: true, connecting: false };
}
case types.CONNECTION_FAILURE: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: false, connecting: false, error: action.error };
}
default : return state;
}
}
function _isSameConnection (state, action) {
return state.server === action.server
&& state.database === action.database;
}
| import * as types from '../actions/connections';
const INITIAL_STATE = {};
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case types.CONNECTION_REQUEST: {
const { server, database } = action;
return { connected: false, connecting: true, server, database };
}
case types.CONNECTION_SUCCESS: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: true, connecting: false };
}
case types.CONNECTION_FAILURE: {
if (!_isSameConnection(state, action)) return state;
return { ...state, connected: false, connecting: false, error: action.error };
}
default : return state;
}
}
function _isSameConnection (state, action) {
return state.server === action.server
&& state.database === action.database;
}
| Move connection initial state to variable | Move connection initial state to variable | JavaScript | mit | sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui | ---
+++
@@ -1,7 +1,10 @@
import * as types from '../actions/connections';
-export default function(state = {}, action) {
+const INITIAL_STATE = {};
+
+
+export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case types.CONNECTION_REQUEST: {
const { server, database } = action; |
5c3cc5bce58b5c5b0dd7861b993b25d865e95aee | src/scripts/common/utils/platform.js | src/scripts/common/utils/platform.js | export default {
isDarwin: process.platform === 'darwin',
isNonDarwin: process.platform !== 'darwin',
isWindows: process.platform === 'win32',
isLinux: process.platform === 'linux',
isWindows7: process.platform === 'win32' &&
navigator && !!navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
};
| export default {
isDarwin: process.platform === 'darwin',
isNonDarwin: process.platform !== 'darwin',
isWindows: process.platform === 'win32',
isLinux: process.platform === 'linux',
isWindows7: process.platform === 'win32' && window.navigator &&
!!window.navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
};
| Fix detection of Windows 7 | Fix detection of Windows 7
| JavaScript | mit | Aluxian/Messenger-for-Desktop,Aluxian/Messenger-for-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp | ---
+++
@@ -3,6 +3,6 @@
isNonDarwin: process.platform !== 'darwin',
isWindows: process.platform === 'win32',
isLinux: process.platform === 'linux',
- isWindows7: process.platform === 'win32' &&
- navigator && !!navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
+ isWindows7: process.platform === 'win32' && window.navigator &&
+ !!window.navigator.userAgent.match(/(Windows 7|Windows NT 6\.1)/)
}; |
f841fdaa19aeb5e35251af3c709f9893fc83cc68 | routes2/api/auth.js | routes2/api/auth.js | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = "secret_key_PLEASE_CHANGE";
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; | const _ = require("lodash");
const express = require("express");
const router = express.Router();
const session = require("express-session");
const connect = require("../../utils/database.js");
const restrict = require("../../utils/middlewares/restrict.js");
const auth = require("../../utils/auth.js");
const jwt = require('jsonwebtoken');
const CharError = require("../../utils/charError.js");
const Promise = require("bluebird");
Promise.promisifyAll(jwt);
require('dotenv').config();
const secret = process.env.JWT_SECRET;
// Catch all for authentication (temporary)
router.use(function(req, res, next){
// Anonymous access to API
if(typeof req.token == "undefined" && process.env.ALLOW_ANNONYMOUS_TOKENS == "true"){
req.user = {
username: "Anonymous",
role: "anonymous"
};
next();
return;
}
// Authenticate here and also set the logged in users role accordingly
// Verify auth token
jwt.verifyAsync(req.token, secret).then(function(payload){
req.user = {
username: payload.username,
role: payload.role
};
next();
}).catch(function(err){
next(new CharError("Auth Token Invalid", err.message, 403));
});
});
module.exports = router; | Use .env to store secret | Use .env to store secret
| JavaScript | bsd-3-clause | limzykenneth/char,limzykenneth/char | ---
+++
@@ -11,7 +11,7 @@
Promise.promisifyAll(jwt);
require('dotenv').config();
-const secret = "secret_key_PLEASE_CHANGE";
+const secret = process.env.JWT_SECRET;
// Catch all for authentication (temporary)
router.use(function(req, res, next){ |
3735ae8afefd31831fa5d8d8445412b0f55ac41a | packages/razzle/config/paths.js | packages/razzle/config/paths.js | 'use strict';
const path = require('path');
const fs = require('fs');
const nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
function resolveApp(relativePath) {
return path.resolve(fs.realpathSync(process.cwd()), relativePath);
}
function resolveOwn(relativePath) {
return path.resolve(__dirname, '..', relativePath);
}
module.exports = {
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appBuildPublic: resolveApp('build/public'),
appManifest: resolveApp('build/assets.json'),
appPublic: resolveApp('public'),
appNodeModules: resolveApp('node_modules'),
appSrc: resolveApp('src'),
appServerIndexJs: resolveApp('src/index.js'),
appClientIndexJs: resolveApp('src/client'),
appBabelRc: resolveApp('.babelrc'),
appRazzleConfig: resolveApp('razzle.config.js'),
nodePaths: nodePaths,
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'),
};
| 'use strict';
const path = require('path');
const fs = require('fs');
const nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
function ensureSlash(path, needsSlash) {
const hasSlash = path.endsWith('/');
if (hasSlash && !needsSlash) {
return path.substr(path, path.length - 1);
} else if (!hasSlash && needsSlash) {
return `${path}/`;
} else {
return path;
}
}
function resolveApp(relativePath) {
return path.resolve(fs.realpathSync(process.cwd()), relativePath);
}
function resolveOwn(relativePath) {
return path.resolve(__dirname, '..', relativePath);
}
module.exports = {
appPath: resolveApp('.'),
appBuild: resolveApp('build'),
appBuildPublic: resolveApp('build/public'),
appManifest: resolveApp('build/assets.json'),
appPublic: resolveApp('public'),
appNodeModules: resolveApp('node_modules'),
appSrc: resolveApp('src'),
appServerIndexJs: resolveApp('src'),
appClientIndexJs: resolveApp('src/client'),
appBabelRc: resolveApp('.babelrc'),
appRazzleConfig: resolveApp('razzle.config.js'),
nodePaths: nodePaths,
ownPath: resolveOwn('.'),
ownNodeModules: resolveOwn('node_modules'),
};
| Make path to server more TS friendly by removing strict file type | Make path to server more TS friendly by removing strict file type
| JavaScript | mit | jaredpalmer/razzle,jaredpalmer/razzle,jaredpalmer/react-production-starter | ---
+++
@@ -36,7 +36,7 @@
appPublic: resolveApp('public'),
appNodeModules: resolveApp('node_modules'),
appSrc: resolveApp('src'),
- appServerIndexJs: resolveApp('src/index.js'),
+ appServerIndexJs: resolveApp('src'),
appClientIndexJs: resolveApp('src/client'),
appBabelRc: resolveApp('.babelrc'),
appRazzleConfig: resolveApp('razzle.config.js'), |
3f463786c52254f353e5bb9c22155441146f8eef | docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js | docs/src/app/components/pages/components/RaisedButton/ExampleComplex.js | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
| import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const styles = {
button: {
margin: 12,
},
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const RaisedButtonExampleComplex = () => (
<div>
<RaisedButton
label="Choose an Image"
labelPosition="before"
style={styles.button}
containerElement="label"
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton>
<RaisedButton
label="Label before"
labelPosition="before"
primary={true}
icon={<ActionAndroid />}
style={styles.button}
/>
<RaisedButton
label="Github Link"
href="https://github.com/callemall/material-ui"
secondary={true}
style={styles.button}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default RaisedButtonExampleComplex;
| Update file input RaisedButton example | Update file input RaisedButton example
This shows how to correctly embed a file input file into a RaisedButton ensuring that the file input remains clickable cross browser #3689 #4983 #1178 | JavaScript | mit | janmarsicek/material-ui,mit-cml/iot-website-source,hwo411/material-ui,ichiohta/material-ui,w01fgang/material-ui,igorbt/material-ui,hwo411/material-ui,mtsandeep/material-ui,pancho111203/material-ui,manchesergit/material-ui,lawrence-yu/material-ui,frnk94/material-ui,ichiohta/material-ui,hai-cea/material-ui,mtsandeep/material-ui,ArcanisCz/material-ui,mmrtnz/material-ui,ArcanisCz/material-ui,janmarsicek/material-ui,pancho111203/material-ui,frnk94/material-ui,kittyjumbalaya/material-components-web,mmrtnz/material-ui,manchesergit/material-ui,janmarsicek/material-ui,janmarsicek/material-ui,lawrence-yu/material-ui,w01fgang/material-ui,igorbt/material-ui,hai-cea/material-ui,mit-cml/iot-website-source,verdan/material-ui,verdan/material-ui,mit-cml/iot-website-source,kittyjumbalaya/material-components-web | ---
+++
@@ -25,6 +25,7 @@
label="Choose an Image"
labelPosition="before"
style={styles.button}
+ containerElement="label"
>
<input type="file" style={styles.exampleImageInput} />
</RaisedButton> |
915acf8a0b9012f04825846b91c68c1ac0ed9df1 | packages/storybook/jest.config.js | packages/storybook/jest.config.js | module.exports = {
collectCoverageFrom: [
"**/src/**/*.{js,jsx}",
"!**/index.js",
],
coverageDirectory: "<rootDir>/packages/storybook/coverage",
coveragePathIgnorePatterns: [
"node_modules",
"packages\/vanilla",
"src\/playground",
"examples\/redux",
"__stories__",
"__gemini__"
],
coverageThreshold: {
global: {
branches: 60,
functions: 60,
lines: 60,
statements: 60
}
},
moduleNameMapper: {
"\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js"
},
modulePaths: ["node_modules"],
moduleFileExtensions: ["js", "jsx", "json"],
rootDir: "../../",
setupFiles: ["raf/polyfill"],
setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js",
testPathIgnorePatterns: ["<rootDir>/packages/vanilla"],
unmockedModulePathPatterns: ["node_modules"]
};
| module.exports = {
collectCoverageFrom: [
"**/src/**/*.{js,jsx}"
],
coverageDirectory: "<rootDir>/packages/storybook/coverage",
coveragePathIgnorePatterns: [
"node_modules",
"packages\/vanilla",
"src\/playground",
"examples\/redux",
"__stories__",
"__gemini__"
],
coverageThreshold: {
global: {
branches: 60,
functions: 60,
lines: 60,
statements: 60
}
},
moduleNameMapper: {
"\\.(css|scss|svg)$": "<rootDir>/packages/storybook/support/jest/fileMock.js"
},
modulePaths: ["node_modules"],
moduleFileExtensions: ["js", "jsx", "json"],
rootDir: "../../",
setupFiles: ["raf/polyfill"],
setupTestFrameworkScriptFile: "<rootDir>/packages/storybook/support/jest/setupTests.js",
testPathIgnorePatterns: ["<rootDir>/packages/vanilla"],
unmockedModulePathPatterns: ["node_modules"]
};
| Include coverage for index files | Include coverage for index files
| JavaScript | apache-2.0 | Autodesk/hig,Autodesk/hig,Autodesk/hig | ---
+++
@@ -1,7 +1,6 @@
module.exports = {
collectCoverageFrom: [
- "**/src/**/*.{js,jsx}",
- "!**/index.js",
+ "**/src/**/*.{js,jsx}"
],
coverageDirectory: "<rootDir>/packages/storybook/coverage",
coveragePathIgnorePatterns: [ |
94ae410220b3006290526484c25ae18405cb5f1e | frontend/src/state/store.js | frontend/src/state/store.js | const createLogger = require('redux-logger');
const enableBatching = require('redux-batched-actions').enableBatching;
const promiseMiddleware = require('redux-promise-middleware').default;
const redux = require('redux');
const thunk = require('redux-thunk').default;
const createReducer = require('@state/reducers');
const {
createStore,
compose,
applyMiddleware
} = redux;
module.exports = (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
compose(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk
)
)
);
};
| const createLogger = require('redux-logger');
const enableBatching = require('redux-batched-actions').enableBatching;
const promiseMiddleware = require('redux-promise-middleware').default;
const redux = require('redux');
const thunk = require('redux-thunk').default;
const createReducer = require('@state/reducers');
const {
createStore,
compose,
applyMiddleware
} = redux;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
module.exports = (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
composeEnhancers(
applyMiddleware(
createLogger(),
promiseMiddleware(),
thunk
)
)
);
};
| Add Redux devtool extension connection - will need to only be available in dev in the future | Add Redux devtool extension connection - will need to only be available in dev in the future
| JavaScript | mpl-2.0 | yldio/joyent-portal,yldio/copilot,geek/joyent-portal,yldio/copilot,yldio/joyent-portal,yldio/copilot,geek/joyent-portal | ---
+++
@@ -12,11 +12,13 @@
applyMiddleware
} = redux;
+const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+
module.exports = (state = Object.freeze({})) => {
return createStore(
enableBatching(createReducer()),
state,
- compose(
+ composeEnhancers(
applyMiddleware(
createLogger(),
promiseMiddleware(), |
b7af36180873e1bb8bf201ae3dd7a2d765519ce0 | dev/app/components/main/projects/projects.controller.js | dev/app/components/main/projects/projects.controller.js | ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ];
function ProjectsController(TbUtils, projects, $rootScope) {
const vm = this;
vm.searchObj = term => { return { Name: term }; };
vm.searchResults = [];
vm.pageSize = 9;
vm.get = projects.getProjectsWithPagination;
vm.getAll = projects.getProjects;
vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length;
vm.projects = [];
vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); };
vm.goToNewProject = project => { TbUtils.go('main.addproject'); };
vm.goToEdit = project => { TbUtils.go('main.editproject', { project: JSON.stringify(project) }); };
vm.loading = true;
vm.removeProjectClicked = removeProjectClicked;
vm.toTitleCase = TbUtils.toTitleCase;
TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize);
function removeProjectClicked(project) {
TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`,
resolve => {
if (resolve) {
vm.loading = true;
TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects,
() => { vm.loading = false; });
}
});
}
}
module.exports = {
name: 'ProjectsController',
ctrl: ProjectsController
}; | ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ];
function ProjectsController(TbUtils, projects, $rootScope) {
const vm = this;
vm.searchObj = term => { return { Name: term }; };
vm.searchResults = [];
vm.pageSize = 9;
vm.get = projects.getProjectsWithPagination;
vm.getAll = projects.getProjects;
vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length;
vm.projects = [];
vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); };
vm.goToNewProject = project => { TbUtils.go('main.new-project'); };
vm.goToEdit = project => { TbUtils.go('main.edit-project', { project: btoa(JSON.stringify(project)) }); };
vm.loading = true;
vm.removeProjectClicked = removeProjectClicked;
vm.toTitleCase = TbUtils.toTitleCase;
TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize);
function removeProjectClicked(project) {
TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`,
resolve => {
if (resolve) {
vm.loading = true;
TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects,
() => { vm.loading = false; });
}
});
}
}
module.exports = { name: 'ProjectsController', ctrl: ProjectsController }; | Change redirects to project form | Change redirects to project form
| JavaScript | mit | Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC | ---
+++
@@ -14,8 +14,8 @@
vm.projects = [];
vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); };
- vm.goToNewProject = project => { TbUtils.go('main.addproject'); };
- vm.goToEdit = project => { TbUtils.go('main.editproject', { project: JSON.stringify(project) }); };
+ vm.goToNewProject = project => { TbUtils.go('main.new-project'); };
+ vm.goToEdit = project => { TbUtils.go('main.edit-project', { project: btoa(JSON.stringify(project)) }); };
vm.loading = true;
@@ -37,7 +37,4 @@
}
-module.exports = {
- name: 'ProjectsController',
- ctrl: ProjectsController
-};
+module.exports = { name: 'ProjectsController', ctrl: ProjectsController }; |
6a06c6ffcaf5d3456ffa0830aee5efbeed19f540 | server/db/config.js | server/db/config.js | var mysql = require('mysql');
exports.connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'uncovery'
});
exports.initialize = function(callback) {
exports.connection.connect();
};
| var mysql = require('mysql');
exports.connection = mysql.createConnection({
host: 'localhost',
user: 'tony',
database: 'uncovery'
});
exports.initialize = function(callback) {
exports.connection.connect();
};
| Update Schema to change userIds to userTokens | Update Schema to change userIds to userTokens
| JavaScript | mit | team-oath/uncovery,team-oath/uncovery,team-oath/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery,scottdixon/uncovery,team-oath/uncovery | ---
+++
@@ -2,7 +2,7 @@
exports.connection = mysql.createConnection({
host: 'localhost',
- user: 'root',
+ user: 'tony',
database: 'uncovery'
});
|
3b7f243a6e663129e98d2551163e2ac01248cbf3 | public/javascripts/application.js | public/javascripts/application.js | $(document).ready(function() {
if (window.location.href.search(/query=/) == -1) {
$('#query').one('click, focus', function() {
$(this).val('');
});
}
$(document).bind('keyup', function(event) {
if ($(event.target).is(':input')) {
return;
}
if (event.which == 83) {
$('#query').focus();
}
});
$('#version_for_stats').change(function() {
window.location.href = $(this).val();
});
});
| $(document).ready(function() {
$('#version_for_stats').change(function() {
window.location.href = $(this).val();
});
});
| Remove JS that handled not-quite-placeholder. | Remove JS that handled not-quite-placeholder.
| JavaScript | mit | sonalkr132/rubygems.org,hrs113355/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,farukaydin/rubygems.org,iSC-Labs/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,childbamboo/rubygems.org,krainboltgreene/rubygems.org,davydovanton/rubygems.org,iRoxxDotOrg/rubygems.org,spk/rubygems.org,farukaydin/rubygems.org,wallin/rubygems.org,sonalkr132/rubygems.org,iRoxxDotOrg/rubygems.org,maclover7/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,davydovanton/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,rubygems/rubygems.org,algolia/rubygems.org,huacnlee/rubygems.org,Ch4s3/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,JuanitoFatas/rubygems.org,hrs113355/rubygems.org,childbamboo/rubygems.org,Ch4s3/rubygems.org,olivierlacan/rubygems.org,rubygems/rubygems.org,davydovanton/rubygems.org,Ch4s3/rubygems.org,rubygems/rubygems.org,krainboltgreene/rubygems.org,arthurnn/rubygems.org,spk/rubygems.org,polamjag/rubygems.org,arthurnn/rubygems.org,iRoxxDotOrg/rubygems.org,andrew/rubygems.org,Elffers/rubygems.org,olivierlacan/rubygems.org,iSC-Labs/rubygems.org,algolia/rubygems.org,wallin/rubygems.org,iRoxxDotOrg/rubygems.org,davydovanton/rubygems.org,farukaydin/rubygems.org,childbamboo/rubygems.org,polamjag/rubygems.org,jamelablack/rubygems.org,Elffers/rubygems.org,fotanus/rubygems.org,fotanus/rubygems.org,kbrock/rubygems.org,fotanus/rubygems.org,knappe/rubygems.org,JuanitoFatas/rubygems.org,krainboltgreene/rubygems.org,rubygems/rubygems.org,hrs113355/rubygems.org,huacnlee/rubygems.org,JuanitoFatas/rubygems.org,iSC-Labs/rubygems.org,iSC-Labs/rubygems.org,knappe/rubygems.org,Ch4s3/rubygems.org,andrew/rubygems.org,arthurnn/rubygems.org,Exeia/rubygems.org,JuanitoFatas/rubygems.org,spk/rubygems.org,hrs113355/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,knappe/rubygems.org,childbamboo/rubygems.org,wallin/rubygems.org,wallin/rubygems.org,fotanus/rubygems.org,huacnlee/rubygems.org,jamelablack/rubygems.org,sonalkr132/rubygems.org,olivierlacan/rubygems.org,Exeia/rubygems.org,Exeia/rubygems.org,kbrock/rubygems.org,krainboltgreene/rubygems.org,knappe/rubygems.org,kbrock/rubygems.org,andrew/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,maclover7/rubygems.org,Elffers/rubygems.org,algolia/rubygems.org,farukaydin/rubygems.org,Elffers/rubygems.org | ---
+++
@@ -1,22 +1,5 @@
$(document).ready(function() {
- if (window.location.href.search(/query=/) == -1) {
- $('#query').one('click, focus', function() {
- $(this).val('');
- });
- }
-
- $(document).bind('keyup', function(event) {
- if ($(event.target).is(':input')) {
- return;
- }
-
- if (event.which == 83) {
- $('#query').focus();
- }
- });
-
$('#version_for_stats').change(function() {
window.location.href = $(this).val();
});
-
}); |
fbd4d6a6a34a13f7d3b506baf6e7687364707a5e | src/test/resources/positive/i205-ref-disambiguation-II.js | src/test/resources/positive/i205-ref-disambiguation-II.js | defaultScope(4);
intRange(-8, 7);
c10_Car = Clafer("c10_Car").withCard(4, 4);
c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1);
c21_Person = Clafer("c21_Person").withCard(4, 4);
c11_owner.refToUnique(c21_Person);
Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(join(c1, c11_owner), join(c2, c11_owner))));
| defaultScope(4);
intRange(-8, 7);
c10_Car = Clafer("c10_Car").withCard(4, 4);
c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1);
c21_Person = Clafer("c21_Person").withCard(4, 4);
c11_owner.refToUnique(c21_Person);
Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(joinRef(join(c1, c11_owner)), joinRef(join(c2, c11_owner)))));
| Add explicit refs to test case. | Add explicit refs to test case.
| JavaScript | mit | gsdlab/chocosolver,gsdlab/chocosolver | ---
+++
@@ -5,4 +5,4 @@
c11_owner = c10_Car.addChild("c11_owner").withCard(1, 1);
c21_Person = Clafer("c21_Person").withCard(4, 4);
c11_owner.refToUnique(c21_Person);
-Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(join(c1, c11_owner), join(c2, c11_owner))));
+Constraint(all([disjDecl([c1 = local("c1"), c2 = local("c2")], global(c10_Car))], notEqual(joinRef(join(c1, c11_owner)), joinRef(join(c2, c11_owner))))); |
987a064c7ee618788b74709d49ea9727a4bfa2e2 | src/views/HomeView/RoomChart.js | src/views/HomeView/RoomChart.js | import React, { PropTypes } from 'react'
import {LineChart} from 'react-d3-basic'
import classes from './RoomChart.scss'
class RoomChart extends React.Component {
static propTypes = {
data: PropTypes.object
};
render () {
const {data} = this.props
let activity = []
if (data && data.activity) {
activity = data.activity
}
const chartData = activity.map((chunk) => {
return {
timestamp: new Date(chunk[0] * 1000),
messages: chunk[1]
}
})
const width = 550
return (
<LineChart
data={chartData}
width={width}
height={300}
margins={{
top: 25,
bottom: 60,
right: 25,
left: 50
}}
chartSeries={[
{
field: 'messages',
name: 'Messages',
color: '#ff7600',
style: {
'stroke-width': 2.5
}
}
]}
x={(d) => d.timestamp}
xScale='time'
innerTickSize={20}
/>
)
}
}
export default RoomChart
| import React, { PropTypes } from 'react'
import {LineChart} from 'react-d3-basic'
class RoomChart extends React.Component {
static propTypes = {
data: PropTypes.object
};
render () {
const {data} = this.props
let activity = []
if (data && data.activity) {
activity = data.activity
}
const chartData = activity.map((chunk) => {
return {
timestamp: new Date(chunk[0] * 1000),
messages: chunk[1]
}
})
const width = 550
return (
<LineChart
data={chartData}
width={width}
height={300}
margins={{
top: 25,
bottom: 60,
right: 25,
left: 50
}}
chartSeries={[
{
field: 'messages',
name: 'Messages',
color: '#ff7600',
style: {
'stroke-width': 2.5
}
}
]}
x={(d) => d.timestamp}
xScale='time'
innerTickSize={20}
/>
)
}
}
export default RoomChart
| Remove unused var to fix lint error | Remove unused var to fix lint error
| JavaScript | mit | seriallos/hubot-stats-web,seriallos/hubot-stats-web | ---
+++
@@ -1,7 +1,5 @@
import React, { PropTypes } from 'react'
import {LineChart} from 'react-d3-basic'
-
-import classes from './RoomChart.scss'
class RoomChart extends React.Component {
static propTypes = { |
5b5df02c9120d9d13616f9dcabda1a959191ee19 | packages/truffle-box/test/unbox.js | packages/truffle-box/test/unbox.js | var path = require("path");
var fs = require("fs-extra");
var assert = require("assert");
var Box = require("../");
var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git";
describe("Unbox", function() {
var destination = path.join(__dirname, ".truffle_test_tmp");
before("mkdir", function(done) {
fs.ensureDir(destination, done);
});
before("remove tmp dir", function(done) {
fs.remove(destination, done);
});
it("unboxes truffle box from github", function() {
this.timeout(5000);
return Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function (truffleConfig) {
assert.ok(truffleConfig);
assert(
fs.existsSync(path.join(destination, "truffle.js")),
"Unboxed project should have truffle config."
);
});
});
});
| var path = require("path");
var fs = require("fs-extra");
var assert = require("assert");
var Box = require("../");
var TRUFFLE_BOX_DEFAULT = "git@github.com:trufflesuite/truffle-init-default.git";
describe("Unbox", function() {
var destination = path.join(__dirname, ".truffle_test_tmp");
before("mkdir", function(done) {
fs.ensureDir(destination, done);
});
after("remove tmp dir", function(done) {
fs.remove(destination, done);
});
it("unboxes truffle box from github", function() {
this.timeout(5000);
return Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function (truffleConfig) {
assert.ok(truffleConfig);
assert(
fs.existsSync(path.join(destination, "truffle.js")),
"Unboxed project should have truffle config."
);
});
});
it("won't re-init if truffle.js file exists", function(done) {
this.timeout(5000);
var contracts_directory = path.join(destination, "contracts");
// Assert our precondition
assert(fs.existsSync(contracts_directory), "contracts directory should exist for this test to be meaningful");
fs.remove(contracts_directory, function(err) {
if (err) return done(err);
Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
.then(function(boxConfig) {
assert(
fs.existsSync(contracts_directory) == false,
"Contracts directory got recreated when it shouldn't have"
);
done();
})
.catch(function(e) {
if (e.message.indexOf("A Truffle project already exists at the destination.") >= 0) {
done();
} else {
done(new Error("Unknown error received: " + e.stack));
}
});
});
});
});
| Add project collision test from truffle-init | Add project collision test from truffle-init
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -13,7 +13,7 @@
fs.ensureDir(destination, done);
});
- before("remove tmp dir", function(done) {
+ after("remove tmp dir", function(done) {
fs.remove(destination, done);
});
@@ -30,4 +30,33 @@
);
});
});
+
+ it("won't re-init if truffle.js file exists", function(done) {
+ this.timeout(5000);
+
+ var contracts_directory = path.join(destination, "contracts");
+
+ // Assert our precondition
+ assert(fs.existsSync(contracts_directory), "contracts directory should exist for this test to be meaningful");
+
+ fs.remove(contracts_directory, function(err) {
+ if (err) return done(err);
+
+ Box.unbox(TRUFFLE_BOX_DEFAULT, destination)
+ .then(function(boxConfig) {
+ assert(
+ fs.existsSync(contracts_directory) == false,
+ "Contracts directory got recreated when it shouldn't have"
+ );
+ done();
+ })
+ .catch(function(e) {
+ if (e.message.indexOf("A Truffle project already exists at the destination.") >= 0) {
+ done();
+ } else {
+ done(new Error("Unknown error received: " + e.stack));
+ }
+ });
+ });
+ });
}); |
761c016727331da4a252f4936390c2fd11097bc0 | src/overrides/HasMany.js | src/overrides/HasMany.js | Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
storeName = that.storeName,
foreignKey = that.foreignKey,
primaryKey = that.primaryKey,
filterProperty = that.filterProperty,
autoLoad = that.autoLoad,
storeConfig = that.storeConfig || {};
return function() {
var me = this,
config, filter,
modelDefaults = {};
if (me[storeName] === undefined) {
if (filterProperty) {
filter = {
property : filterProperty,
value : me.get(filterProperty),
exactMatch: true
};
} else {
filter = {
property : foreignKey,
value : me.get(primaryKey),
exactMatch: true
};
}
if (!storeConfig.filters) storeConfig.filters = [];
storeConfig.filters.push(filter);
modelDefaults[foreignKey] = me.get(primaryKey);
config = Ext.apply({}, storeConfig, {
model : associatedModel,
remoteFilter : false,
modelDefaults: modelDefaults,
disableMetaChangeEvent: true
});
me[storeName] = Ext.data.AbstractStore.create(config);
if (autoLoad) {
me[storeName].load();
}
}
return me[storeName];
};
}
});
| Ext.define('Densa.overrides.HasMany', {
override: 'Ext.data.association.HasMany',
/**
* Allow filters in storeConfig
*
* Original overrides filters with filter
*/
createStore: function() {
var that = this,
associatedModel = that.associatedModel,
storeName = that.storeName,
foreignKey = that.foreignKey,
primaryKey = that.primaryKey,
filterProperty = that.filterProperty,
autoLoad = that.autoLoad,
storeConfig = that.storeConfig || {};
return function() {
var me = this,
config, filter,
modelDefaults = {};
if (me[storeName] === undefined) {
if (filterProperty) {
filter = {
property : filterProperty,
value : me.get(filterProperty),
exactMatch: true
};
} else {
filter = {
property : foreignKey,
value : me.get(primaryKey),
exactMatch: true
};
}
var localStoreConfig = Ext.clone(storeConfig);
if (!localStoreConfig.filters) localStoreConfig.filters = [];
localStoreConfig.filters.push(filter);
modelDefaults[foreignKey] = me.get(primaryKey);
config = Ext.apply({}, localStoreConfig, {
model : associatedModel,
remoteFilter : false,
modelDefaults: modelDefaults,
disableMetaChangeEvent: true
});
me[storeName] = Ext.data.AbstractStore.create(config);
if (autoLoad) {
me[storeName].load();
}
}
return me[storeName];
};
}
});
| Fix filters in storeConfig: they where shared across multiple stores | Fix filters in storeConfig: they where shared across multiple stores
Problem was that storeConfig is an object and thus modified by reference
| JavaScript | bsd-2-clause | koala-framework/densajs,Ben-Ho/densajs | ---
+++
@@ -34,12 +34,15 @@
exactMatch: true
};
}
- if (!storeConfig.filters) storeConfig.filters = [];
- storeConfig.filters.push(filter);
+
+ var localStoreConfig = Ext.clone(storeConfig);
+ if (!localStoreConfig.filters) localStoreConfig.filters = [];
+ localStoreConfig.filters.push(filter);
+
modelDefaults[foreignKey] = me.get(primaryKey);
- config = Ext.apply({}, storeConfig, {
+ config = Ext.apply({}, localStoreConfig, {
model : associatedModel,
remoteFilter : false,
modelDefaults: modelDefaults, |
2601364bb01ba8b3bce372440c48f20e41e2c6f0 | jobs/index.js | jobs/index.js | "use strict";
var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);
module.exports = function(app) {
var queue = app.get('queue');
var store = app.get('keyValueStore');
delete jobs.index;
for(var job in jobs) {
debug('wait for job type', job);
// create new job processor
queue.process(job, app.get('concurrency'), jobs[job](app));
}
queue.on('job complete', function(id, result) {
var afToken;
async.waterfall([
function getJob(cb) {
kue.Job.get(id, cb);
},
function setCursor(job, cb) {
afToken = job.anyfetchToken;
store.hset('cursor', afToken, result, cb);
},
function setLastUpdate(status, cb) {
store.hset('lastUpdate', afToken, Date.now().toString(), cb);
},
function unlockUpdate(status, cb) {
store.hdel('status', afToken, cb);
}
], function throwErrs(err) {
if(err) {
throw err;
}
});
});
};
| "use strict";
var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
var rarity = require('rarity');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);
module.exports = function(app) {
var queue = app.get('queue');
var store = app.get('keyValueStore');
delete jobs.index;
for(var job in jobs) {
debug('wait for job type', job);
// create new job processor
queue.process(job, app.get('concurrency'), jobs[job](app));
}
queue.on('job complete', function(id, result) {
async.waterfall([
function getJob(cb) {
kue.Job.get(id, cb);
},
function removeJob(job, cb) {
var anyfetchToken = job.data.anyfetchToken;
job.remove(rarity.carry([anyfetchToken], cb));
},
function setCursor(anyfetchToken, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hset('cursor', anyfetchToken, result, rarity.carry([anyfetchToken], cb));
},
function setLastUpdate(anyfetchToken, status, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hset('lastUpdate', anyfetchToken, Date.now().toString(), rarity.carry([anyfetchToken], cb));
},
function unlockUpdate(anyfetchToken, status, cb) {
if(!anyfetchToken) {
return cb(null, null, null);
}
store.hdel('status', anyfetchToken, cb);
}
], function throwErrs(err) {
if(err) {
throw err;
}
});
});
};
| Clean redis after succeeded jobs | Clean redis after succeeded jobs
| JavaScript | mit | AnyFetch/gdrive-provider.anyfetch.com | ---
+++
@@ -3,6 +3,7 @@
var autoload = require('auto-load');
var kue = require('kue');
var async = require('async');
+var rarity = require('rarity');
var debug = require('debug')('kue:boot');
var jobs = autoload(__dirname);
@@ -18,21 +19,31 @@
}
queue.on('job complete', function(id, result) {
- var afToken;
async.waterfall([
function getJob(cb) {
kue.Job.get(id, cb);
},
- function setCursor(job, cb) {
- afToken = job.anyfetchToken;
-
- store.hset('cursor', afToken, result, cb);
+ function removeJob(job, cb) {
+ var anyfetchToken = job.data.anyfetchToken;
+ job.remove(rarity.carry([anyfetchToken], cb));
},
- function setLastUpdate(status, cb) {
- store.hset('lastUpdate', afToken, Date.now().toString(), cb);
+ function setCursor(anyfetchToken, cb) {
+ if(!anyfetchToken) {
+ return cb(null, null, null);
+ }
+ store.hset('cursor', anyfetchToken, result, rarity.carry([anyfetchToken], cb));
},
- function unlockUpdate(status, cb) {
- store.hdel('status', afToken, cb);
+ function setLastUpdate(anyfetchToken, status, cb) {
+ if(!anyfetchToken) {
+ return cb(null, null, null);
+ }
+ store.hset('lastUpdate', anyfetchToken, Date.now().toString(), rarity.carry([anyfetchToken], cb));
+ },
+ function unlockUpdate(anyfetchToken, status, cb) {
+ if(!anyfetchToken) {
+ return cb(null, null, null);
+ }
+ store.hdel('status', anyfetchToken, cb);
}
], function throwErrs(err) {
if(err) { |
bbdf0c9d323e17a31f9e2e1d6442012fd1e47fdf | lib/slack-gateway.js | lib/slack-gateway.js | var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
icon_url: 'https://github.com/identicons/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
| var _ = require('lodash');
var logger = require('winston');
var request = require('superagent');
function SlackGateway(incomingURL, channelMapping) {
this.incomingURL = incomingURL;
this.invertedMapping = _.invert(channelMapping);
}
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
icon_url: 'http://api.adorable.io/avatars/48/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
};
request
.post(this.incomingURL)
.send(payload)
.set('Accept', 'application/json')
.end(function(err, res) {
if (err) return logger.error('Couldn\'t post message to Slack', err);
logger.debug('Posted message to Slack', res.body, res.statusCode);
});
};
module.exports = SlackGateway;
| Change icon_url to use adorable.io | Change icon_url to use adorable.io | JavaScript | mit | ekmartin/slack-irc,tcr/slack-irc,andreaja/slack-irc,lmtierney/slack-irc,leeopop/slack-irc,umegaya/slack-irc,zabirauf/slack-irc,php-ug/slack-irc,reactiflux/discord-irc,robertkety/slack-irc,erikdesjardins/slack-irc,xbmc/slack-irc,chipx86/slack-irc,mxm/slack-irc | ---
+++
@@ -10,7 +10,7 @@
SlackGateway.prototype.sendToSlack = function(author, ircChannel, message) {
var payload = {
username: author,
- icon_url: 'https://github.com/identicons/' + author + '.png',
+ icon_url: 'http://api.adorable.io/avatars/48/' + author + '.png',
channel: this.invertedMapping[ircChannel],
text: message
}; |
e6f6f94480582504c4ff1293e9c5b00e8b450000 | js/scripts.js | js/scripts.js | var pingPongOutput = function(inputNumber) {
if(inputNumber % 3 === 0) {
return "ping";
} else {
return inputNumber;
}
};
| var pingPongOutput = function(inputNumber) {
if(inputNumber % 3 === 0) {
return "ping";
} else if (inputNumber % 5 === 0) {
return "pong";
} else {
return inputNumber;
}
};
| Implement numbers divisible by 5 | Implement numbers divisible by 5
| JavaScript | mit | JeffreyRuder/ping-pong-app,JeffreyRuder/ping-pong-app | ---
+++
@@ -1,6 +1,8 @@
var pingPongOutput = function(inputNumber) {
if(inputNumber % 3 === 0) {
return "ping";
+ } else if (inputNumber % 5 === 0) {
+ return "pong";
} else {
return inputNumber;
} |
84639f7c85a9ae4109dee5b042e44fecc16c02dd | js/scripts.js | js/scripts.js | var pingPong = function(i) {
if (isPingPong(i)) {
return pingPongType(i)
} else {
return false;
}
}
var pingPongType = function(i) {
if ((i % 3 === 0) && (i % 5 != 0)) {
return "ping";
} else if ((i % 5 === 0) && (i % 3 !=0)) {
return "pong";
} else if (i % 15 === 0){
return "pingpong";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)){
return true;
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (pingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| var pingPongType = function(i) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 5 === 0) {
return "pong";
} else {
return "ping";
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
return pingPongType(i);
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
if (isPingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
| Remove code for pingPong, leaving pingPongType and isPingPong as functions | Remove code for pingPong, leaving pingPongType and isPingPong as functions
| JavaScript | mit | kcmdouglas/pingpong,kcmdouglas/pingpong | ---
+++
@@ -1,24 +1,16 @@
-var pingPong = function(i) {
- if (isPingPong(i)) {
- return pingPongType(i)
+var pingPongType = function(i) {
+ if (i % 15 === 0) {
+ return "pingpong";
+ } else if (i % 5 === 0) {
+ return "pong";
} else {
- return false;
+ return "ping";
}
}
-var pingPongType = function(i) {
- if ((i % 3 === 0) && (i % 5 != 0)) {
- return "ping";
- } else if ((i % 5 === 0) && (i % 3 !=0)) {
- return "pong";
- } else if (i % 15 === 0){
- return "pingpong";
- }
- }
-
var isPingPong = function(i) {
- if ((i % 5 === 0) || (i % 3 === 0)){
- return true;
+ if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
+ return pingPongType(i);
} else {
return false;
}
@@ -32,7 +24,7 @@
var whichPingPong = pingPongType(i)
for (var i = 1; i <= number; i += 1) {
- if (pingPong(i)) {
+ if (isPingPong(i)) {
$('#outputList').append("<li>" + whichPingPong + "</li>");
} else {
$('#outputList').append("<li>" + i + "</li>"); |
2fadeb3eaf5c182bd29380edc7b7c5666b37177e | lib/extend.js | lib/extend.js | 'use strict';
var _ = require('underscore');
module.exports = function extend (Superclass, prototypeFragment) {
prototypeFragment = prototypeFragment || {};
var Subclass = function () {
if (_.isFunction(prototypeFragment.initialize)) {
prototypeFragment.initialize.apply(this, arguments);
} else {
Superclass.apply(this, arguments);
}
};
Subclass.prototype = Object.create(Superclass.prototype);
_.extend(Subclass.prototype, prototypeFragment);
return Subclass;
};
| 'use strict';
var _ = require('underscore');
module.exports = function extend (Superclass, prototypeFragment) {
prototypeFragment = prototypeFragment || {};
var Subclass = function () {
Superclass.apply(this, arguments);
if (_.isFunction(prototypeFragment.initialize)) {
prototypeFragment.initialize.apply(this, arguments);
}
};
Subclass.prototype = Object.create(Superclass.prototype);
_.extend(Subclass.prototype, prototypeFragment);
return Subclass;
};
| Fix the issue by calling constructor and checking for initialize | [Green] Fix the issue by calling constructor and checking for initialize
| JavaScript | mit | ImpactFlow/flow | ---
+++
@@ -6,10 +6,9 @@
prototypeFragment = prototypeFragment || {};
var Subclass = function () {
+ Superclass.apply(this, arguments);
if (_.isFunction(prototypeFragment.initialize)) {
prototypeFragment.initialize.apply(this, arguments);
- } else {
- Superclass.apply(this, arguments);
}
};
Subclass.prototype = Object.create(Superclass.prototype); |
cb7b7847c3324bb5dbbea5b9e185cece8eaf2b96 | lib/mincer.js | lib/mincer.js | 'use strict';
// internal
var mixin = require('./mincer/common');
module.exports = {
VERSION: '0.0.0',
EngineTemplate: require('./mincer/engine_template'),
Environment: require('./mincer/environment'),
Manifest: require('./mincer/manifest')
};
mixin(module.exports, require('./mincer/engines'));
mixin(module.exports, require('./mincer/paths'));
| 'use strict';
// internal
var mixin = require('./mincer/common').mixin;
var prop = require('./mincer/common').prop;
module.exports = {
VERSION: '0.0.0',
EngineTemplate: require('./mincer/engine_template'),
Environment: require('./mincer/environment'),
Manifest: require('./mincer/manifest')
};
prop(module.exports, '__engines__', {});
mixin(module.exports, require('./mincer/engines'));
mixin(module.exports, require('./mincer/paths'));
| Add some mixins to main lib | Add some mixins to main lib
| JavaScript | mit | rhyzx/mincer,mcanthony/mincer,nodeca/mincer,inukshuk/mincer | ---
+++
@@ -2,7 +2,8 @@
// internal
-var mixin = require('./mincer/common');
+var mixin = require('./mincer/common').mixin;
+var prop = require('./mincer/common').prop;
module.exports = {
@@ -14,5 +15,8 @@
};
+prop(module.exports, '__engines__', {});
+
+
mixin(module.exports, require('./mincer/engines'));
mixin(module.exports, require('./mincer/paths')); |
d968bcfd42463bcbc4cddf891ae76df85c45d6f2 | src/redux/createStore.js | src/redux/createStore.js | import { createStore as _createStore, applyMiddleware } from 'redux';
import fetchMiddleware from './middleware/fetchMiddleware';
import reducer from './modules/reducer';
export default function createStore(client, data) {
const middlewares = [fetchMiddleware(client)];
const finalCreateStore = applyMiddleware(...middlewares)(_createStore);
const store = finalCreateStore(reducer, data);
/* global module, require */
if (module.hot) {
module.hot.accept('./modules/reducer', () => {
store.replaceReducer(require('./modules/reducer'));
});
}
return store;
}
| import { createStore as _createStore, applyMiddleware } from 'redux';
import { browserHistory } from 'react-router';
import { routerMiddleware, } from 'react-router-redux';
import fetchMiddleware from './middleware/fetchMiddleware';
import reducer from './modules/reducer';
export default function createStore(client, data) {
const middlewares = [
fetchMiddleware(client),
routerMiddleware(browserHistory),
];
const finalCreateStore = applyMiddleware(...middlewares)(_createStore);
const store = finalCreateStore(reducer, data);
/* global module, require */
if (module.hot) {
module.hot.accept('./modules/reducer', () => {
store.replaceReducer(require('./modules/reducer'));
});
}
return store;
}
| Connect router history to redux. | Connect router history to redux.
| JavaScript | agpl-3.0 | ahoereth/lawly,ahoereth/lawly,ahoereth/lawly | ---
+++
@@ -1,11 +1,16 @@
import { createStore as _createStore, applyMiddleware } from 'redux';
+import { browserHistory } from 'react-router';
+import { routerMiddleware, } from 'react-router-redux';
import fetchMiddleware from './middleware/fetchMiddleware';
import reducer from './modules/reducer';
export default function createStore(client, data) {
- const middlewares = [fetchMiddleware(client)];
+ const middlewares = [
+ fetchMiddleware(client),
+ routerMiddleware(browserHistory),
+ ];
const finalCreateStore = applyMiddleware(...middlewares)(_createStore);
const store = finalCreateStore(reducer, data);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.