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 |
|---|---|---|---|---|---|---|---|---|---|---|
4156b07d63af7e23ac8138bc233747727310d407 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]))
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
| 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
var package_info = require('./package.json')
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build-all', shell.task([
'electron-packager . --overwrite --platform=all --arch=all --prune=true --out=release_builds'
]));
gulp.task('build-mac', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]));
gulp.task('zip', shell.task([
`zip -FSr release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop-${package_info.version}-macos-x64.zip release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop.app`
]));
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
| Make builds platform specific and add zipping | Make builds platform specific and add zipping
| JavaScript | apache-2.0 | opsdroid/opsdroid-desktop,opsdroid/opsdroid-desktop | ---
+++
@@ -4,6 +4,7 @@
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
+var package_info = require('./package.json')
gulp.task('serve', function () {
@@ -23,9 +24,17 @@
});
});
-gulp.task('build', shell.task([
+gulp.task('build-all', shell.task([
+ 'electron-packager . --overwrite --platform=all --arch=all --prune=true --out=release_builds'
+]));
+
+gulp.task('build-mac', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
-]))
+]));
+
+gulp.task('zip', shell.task([
+ `zip -FSr release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop-${package_info.version}-macos-x64.zip release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop.app`
+]));
gulp.task('sass', function () {
return gulp.src('./*.scss') |
f7bd0b4865f0dadc77a33c1168c5239916b05614 | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del');
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
gulp.task('default', ['watch', 'scripts']);
| var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
karma = require('karma').server;
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
// Run test once and exit
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
// Watch for file changes and re-run tests on each change
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
gulp.task('default', ['tdd']);
| Add tasks test and tdd | Add tasks test and tdd
| JavaScript | mit | mkawalec/latte-art | ---
+++
@@ -3,7 +3,8 @@
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
- del = require('del');
+ del = require('del'),
+ karma = require('karma').server;
var paths = {
scripts: ['source/**/*.coffee']
@@ -28,4 +29,20 @@
gulp.watch(paths.scripts, ['scripts']);
});
-gulp.task('default', ['watch', 'scripts']);
+// Run test once and exit
+gulp.task('test', function (done) {
+ karma.start({
+ configFile: __dirname + '/karma.conf.js',
+ singleRun: true
+ }, done);
+});
+
+// Watch for file changes and re-run tests on each change
+gulp.task('tdd', function (done) {
+ karma.start({
+ configFile: __dirname + '/karma.conf.js'
+ }, done);
+});
+
+gulp.task('default', ['tdd']);
+ |
b7d67f8a8581df15bf526f0e493b9ab626cab924 | Resources/public/js/select24entity.js | Resources/public/js/select24entity.js | $(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true,
tags: false
}
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
}); | $(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
tags: false
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
});
| Fix place of "tags" option in the default options | Fix place of "tags" option in the default options | JavaScript | mit | sharky98/select24entity-bundle,sharky98/select24entity-bundle,sharky98/select24entity-bundle | ---
+++
@@ -13,9 +13,9 @@
results: data
};
},
- cache: true,
- tags: false
- }
+ cache: true
+ },
+ tags: false
};
// Extend the parameters array with the one in arguments |
b46ae05b9622867dfdbfe30402f2848b2770fee8 | test/DOM/main.js | test/DOM/main.js | // This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="..">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
| // This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="../index.html">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
| Make the link work from a "file://" URI. | Make the link work from a "file://" URI.
| JavaScript | mit | TooTallNate/ModuleJS | ---
+++
@@ -10,7 +10,7 @@
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
- foo.update('It Works! <a href="..">Go Back</a>');
+ foo.update('It Works! <a href="../index.html">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo); |
5f8631362875b2cafe042c7121cc293615cfffe0 | test/test-app.js | test/test-app.js | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bower.json',
'package.json',
'.editorconfig',
'.jshintrc'
]);
});
});
| /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bin/hubot',
'bin/hubot.cmd',
'Procfile',
'README.md',
'external-scripts.json',
'hubot-scripts.json',
'.gitignore',
'package.json',
'scripts/example.coffee',
'.editorconfig',
]);
});
});
| Fix assertion for not existing files | Fix assertion for not existing files
| JavaScript | mit | ArLEquiN64/generator-hubot-gulp,m-seldin/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,ArLEquiN64/generator-hubot-gulp,zarqin/generator-hubot,github/generator-hubot,mal/generator-hubot,zarqin/generator-hubot,mal/generator-hubot,m-seldin/generator-hubot-enterprise,ClaudeBot/generator-hubot,ClaudeBot/generator-hubot,github/generator-hubot | ---
+++
@@ -19,10 +19,16 @@
it('creates files', function () {
assert.file([
- 'bower.json',
+ 'bin/hubot',
+ 'bin/hubot.cmd',
+ 'Procfile',
+ 'README.md',
+ 'external-scripts.json',
+ 'hubot-scripts.json',
+ '.gitignore',
'package.json',
+ 'scripts/example.coffee',
'.editorconfig',
- '.jshintrc'
]);
});
}); |
66b15d29269455a5cf24164bd1982f7f01c323f3 | src/parse/expr.js | src/parse/expr.js | var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.item = function() { return 'event.vg.item'; };
fn.group = 'event.vg.getGroup';
fn.mouseX = 'event.vg.getX';
fn.mouseY = 'event.vg.getY';
fn.mouse = 'event.vg.getXY';
return fn;
}
});
| var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.eventItem = function() { return 'event.vg.item'; };
fn.eventGroup = 'event.vg.getGroup';
fn.eventX = 'event.vg.getX';
fn.eventY = 'event.vg.getY';
return fn;
}
});
| Update to revised event methods. | Update to revised event methods.
| JavaScript | bsd-3-clause | chiu/vega,smclements/vega,seyfert/vega,mathisonian/vega-browserify,carabina/vega,mcanthony/vega,shaunstanislaus/vega,Jerrythafast/vega,Jerrythafast/vega,cesine/vega,shaunstanislaus/vega,lgrammel/vega,Applied-Duality/vega,smclements/vega,smartpcr/vega,smartpcr/vega,mcanthony/vega,mathisonian/vega-browserify,pingjiang/vega,timelyportfolio/vega,jsanch/vega,uwdata/vega,smclements/vega,nyurik/vega,pingjiang/vega,nyurik/vega,gdseller/vega,jsanch/vega,carabina/vega,gdseller/vega,cesine/vega,Jerrythafast/vega,cesine/vega,mcanthony/vega,gdseller/vega,Applied-Duality/vega,seyfert/vega,shaunstanislaus/vega,uwdata/vega,vega/vega,smartpcr/vega,carabina/vega,pingjiang/vega,timelyportfolio/vega,linearregression/vega,nyurik/vega,mathisonian/vega-browserify,jsanch/vega,vega/vega,linearregression/vega,linearregression/vega,chiu/vega,seyfert/vega,Applied-Duality/vega,vega/vega,vega/vega,chiu/vega | ---
+++
@@ -7,11 +7,10 @@
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
- fn.item = function() { return 'event.vg.item'; };
- fn.group = 'event.vg.getGroup';
- fn.mouseX = 'event.vg.getX';
- fn.mouseY = 'event.vg.getY';
- fn.mouse = 'event.vg.getXY';
+ fn.eventItem = function() { return 'event.vg.item'; };
+ fn.eventGroup = 'event.vg.getGroup';
+ fn.eventX = 'event.vg.getX';
+ fn.eventY = 'event.vg.getY';
return fn;
}
}); |
02475ac2b8ca9832733bbf01fbf49c80c8f5c66a | src/lang-proto.js | src/lang-proto.js | // Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
keywords: (
'bool bytes default double enum extend extensions false fixed32 '
+ 'fixed64 float group import int32 int64 max message option '
+ 'optional package repeated required returns rpc service '
+ 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 '
+ 'uint64'),
cStyleComments: true
}), ['proto']);
| // Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
'keywords': (
'bytes,default,double,enum,extend,extensions,false,'
+ 'group,import,max,message,option,'
+ 'optional,package,repeated,required,returns,rpc,service,'
+ 'syntax,to,true'),
'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,
'cStyleComments': true
}), ['proto']);
| Fix proto lang handler to work minified and to use the type style for types like uint32. | Fix proto lang handler to work minified and to use the type style for types like uint32.
| JavaScript | apache-2.0 | ebidel/google-code-prettify,tcollard/google-code-prettify,tcollard/google-code-prettify,ebidel/google-code-prettify,tcollard/google-code-prettify | ---
+++
@@ -25,11 +25,11 @@
*/
PR['registerLangHandler'](PR['sourceDecorator']({
- keywords: (
- 'bool bytes default double enum extend extensions false fixed32 '
- + 'fixed64 float group import int32 int64 max message option '
- + 'optional package repeated required returns rpc service '
- + 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 '
- + 'uint64'),
- cStyleComments: true
+ 'keywords': (
+ 'bytes,default,double,enum,extend,extensions,false,'
+ + 'group,import,max,message,option,'
+ + 'optional,package,repeated,required,returns,rpc,service,'
+ + 'syntax,to,true'),
+ 'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,
+ 'cStyleComments': true
}), ['proto']); |
e89d777b928d212b95ce639256de4e38c1788a77 | src/routes/api.js | src/routes/api.js | // Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
module.exports = router;
| // Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
router.get('/users/:username', function (req, res) {
db.select().from('User').where({active: true, 'username': req.param('username')}).all()
.then(function (user) {
res.json({
user
});
});
});
module.exports = router;
| Add get one user in API | Add get one user in API
| JavaScript | mit | AnimalTracker/AnimalTracker,AnimalTracker/AnimalTracker | ---
+++
@@ -21,4 +21,13 @@
});
});
+router.get('/users/:username', function (req, res) {
+ db.select().from('User').where({active: true, 'username': req.param('username')}).all()
+ .then(function (user) {
+ res.json({
+ user
+ });
+ });
+});
+
module.exports = router; |
53a27ad98440fb40c5d13f0415ee0ac348289ca1 | app/extension-scripts/main.js | app/extension-scripts/main.js | (function() {
chrome.browserAction.onClicked.addListener(function() {
var newURL = "chrome-extension://" + chrome.runtime.id + "/index.html";
chrome.tabs.create({ url: newURL });
});
})();
| (function() {
chrome.browserAction.onClicked.addListener(function() {
var appUrl = chrome.extension.getURL('index.html');
chrome.tabs.create({ url: appUrl });
});
})();
| Use builtin to build url | Use builtin to build url
| JavaScript | mit | chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,48klocs/DIM,bhollis/DIM,delphiactual/DIM,chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,LouisFettet/DIM,48klocs/DIM,delphiactual/DIM,bhollis/DIM,LouisFettet/DIM,DestinyItemManager/DIM,chrisfried/DIM,48klocs/DIM,delphiactual/DIM,chrisfried/DIM,delphiactual/DIM,DestinyItemManager/DIM | ---
+++
@@ -1,6 +1,6 @@
(function() {
chrome.browserAction.onClicked.addListener(function() {
- var newURL = "chrome-extension://" + chrome.runtime.id + "/index.html";
- chrome.tabs.create({ url: newURL });
+ var appUrl = chrome.extension.getURL('index.html');
+ chrome.tabs.create({ url: appUrl });
});
})(); |
5f336dc64d8d7137e22e30e8799be6215fd9d45e | packages/custom-elements/tests/safari-gc-bug-workaround.js | packages/custom-elements/tests/safari-gc-bug-workaround.js | export function safariGCBugWorkaround() {
if (customElements.polyfillWrapFlushCallback === undefined) {
console.warn('The custom elements polyfill was reinstalled.');
window.__CE_installPolyfill();
}
}
| /**
* @license
* Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// Some distributions of Safari 10 and 11 contain a bug where non-native
// properties added to certain globals very early in the lifetime of the page
// are not considered reachable and might be garbage collected. This happens
// randomly and appears to affect not only the `customElements` global but also
// the wrapper functions it attaches to other globals, like `Node.prototype`,
// effectively removing the polyfill. To work around this, this function checks
// if the polyfill is missing before running the tests. If so, it uses a
// special global function added by the polyfill during tests (which doesn't
// get collected) to reinstall it.
//
// https://bugs.webkit.org/show_bug.cgi?id=172575
export function safariGCBugWorkaround() {
if (customElements.polyfillWrapFlushCallback === undefined) {
window.__CE_installPolyfill();
console.warn('The custom elements polyfill was reinstalled.');
}
}
| Add license and comment describing the Safari GC bug workaround. | Add license and comment describing the Safari GC bug workaround.
| JavaScript | bsd-3-clause | webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills | ---
+++
@@ -1,6 +1,27 @@
+/**
+ * @license
+ * Copyright (c) 2019 The Polymer Project Authors. All rights reserved.
+ * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
+ * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
+ * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
+ * Code distributed by Google as part of the polymer project is also
+ * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
+ */
+
+// Some distributions of Safari 10 and 11 contain a bug where non-native
+// properties added to certain globals very early in the lifetime of the page
+// are not considered reachable and might be garbage collected. This happens
+// randomly and appears to affect not only the `customElements` global but also
+// the wrapper functions it attaches to other globals, like `Node.prototype`,
+// effectively removing the polyfill. To work around this, this function checks
+// if the polyfill is missing before running the tests. If so, it uses a
+// special global function added by the polyfill during tests (which doesn't
+// get collected) to reinstall it.
+//
+// https://bugs.webkit.org/show_bug.cgi?id=172575
export function safariGCBugWorkaround() {
if (customElements.polyfillWrapFlushCallback === undefined) {
+ window.__CE_installPolyfill();
console.warn('The custom elements polyfill was reinstalled.');
- window.__CE_installPolyfill();
}
} |
b7f05eeb90ceeb53ce14d2a23ee73300cce61f92 | lib/querystring.js | lib/querystring.js | // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (obj.constructor == Array) {
return stringifyArray(obj, prefix);
} else if (obj !== null && typeof obj == 'object') {
return stringifyObject(obj, prefix);
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
| // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
var toString = Object.prototype.toString;
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (toString.call(obj) == '[object Array]') {
return stringifyArray(obj, prefix);
} else if (toString.call(obj) == '[object Object]') {
return stringifyObject(obj, prefix);
} else if (toString.call(obj) == '[object Date]') {
return obj.toISOString();
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
| Add support for Dates to stringify, also improve stringify Object and Array | Add support for Dates to stringify, also improve stringify Object and Array
| JavaScript | mit | tomas/needle,tomas/needle | ---
+++
@@ -1,13 +1,17 @@
// based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
+
+var toString = Object.prototype.toString;
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
- } else if (obj.constructor == Array) {
+ } else if (toString.call(obj) == '[object Array]') {
return stringifyArray(obj, prefix);
- } else if (obj !== null && typeof obj == 'object') {
+ } else if (toString.call(obj) == '[object Object]') {
return stringifyObject(obj, prefix);
+ } else if (toString.call(obj) == '[object Date]') {
+ return obj.toISOString();
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign |
7b6f45b5970766e1ce85c51c0e3d471b41f6a7d6 | app/helpers/takeScreenshot.js | app/helpers/takeScreenshot.js | import { remote } from 'electron'
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
win.loadURL(`data:text/html, ${html}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
| import { remote } from 'electron'
import path from 'path'
import os from 'os'
import { fsWriteFile } from 'helpers/fs'
const TMP_DIR = os.tmpdir()
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(async resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
const tmpFileName = path.join(TMP_DIR, 'tpm-mjml-preview.html')
await fsWriteFile(tmpFileName, html)
win.loadURL(`file://${tmpFileName}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
| Use file to generate screenshot | Use file to generate screenshot
| JavaScript | mit | mjmlio/mjml-app,mjmlio/mjml-app,mjmlio/mjml-app | ---
+++
@@ -1,13 +1,22 @@
import { remote } from 'electron'
+import path from 'path'
+import os from 'os'
+
+import { fsWriteFile } from 'helpers/fs'
+
+const TMP_DIR = os.tmpdir()
export default async function takeScreenshot (html, deviceWidth) {
- return new Promise(resolve => {
+ return new Promise(async resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
- win.loadURL(`data:text/html, ${html}`)
+ const tmpFileName = path.join(TMP_DIR, 'tpm-mjml-preview.html')
+ await fsWriteFile(tmpFileName, html)
+
+ win.loadURL(`file://${tmpFileName}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()... |
ca3c29206187ec6a892e36c649602f39648b445c | src/decode/objectify.js | src/decode/objectify.js | var Struct = require('../base/Struct');
var Data = require('../base/Data');
var Text = require('../base/Text');
var List = require('../base/List');
var AnyPointer = require('../base/AnyPointer');
/*
* Primary use case is testing. AnyPointers map to `'[AnyPointer]'` not a nice
* dump for general use, but good for testing. Circular reference will bring
* this crashing down too.
*/
var objectify = function (reader) {
var object = {};
for (var key in reader) {
var v = reader[key];
if (v instanceof Struct) {
object[key] = objectify(v);
} else if (v instanceof List) {
if (v instanceof Data) {
object[key] = v.raw;
} else if (v instanceof Text) {
object[key] = v.string;
} else {
/* TODO: map for list types. */
object[key] = v.map(objectify);
}
} else if (v instanceof AnyPointer) {
object[key] = '[AnyPointer]';
} else {
object[key] = v;
}
}
return object;
};
module.exports = objectify;
| var Struct = require('../base/Struct');
var Data = require('./list/Data');
var Text = require('./list/Text');
var List = require('../base/List');
var AnyPointer = require('../base/AnyPointer');
/*
* Primary use case is testing. AnyPointers map to `'[AnyPointer]'` not a nice
* dump for general use, but good for testing. Circular reference will bring
* this crashing down too.
*/
var objectify = function (reader) {
var object = {};
for (var key in reader) {
if (key[0] !== '$') continue;
var v = reader[key];
if (v instanceof Struct) {
object[key] = objectify(v);
} else if (v instanceof List) {
if (v instanceof Data) {
object[key] = v.raw;
} else if (v instanceof Text) {
object[key] = v.string;
} else {
/* TODO: map for list types. */
object[key] = v.map(objectify);
}
} else if (v instanceof AnyPointer) {
object[key] = '[AnyPointer]';
} else {
object[key] = v;
}
}
return object;
};
module.exports = objectify;
| Determine enumerability by $ prefix | Determine enumerability by $ prefix
| JavaScript | mit | xygroup/node-capnp-plugin | ---
+++
@@ -1,6 +1,6 @@
var Struct = require('../base/Struct');
-var Data = require('../base/Data');
-var Text = require('../base/Text');
+var Data = require('./list/Data');
+var Text = require('./list/Text');
var List = require('../base/List');
var AnyPointer = require('../base/AnyPointer');
@@ -12,7 +12,10 @@
var objectify = function (reader) {
var object = {};
for (var key in reader) {
+ if (key[0] !== '$') continue;
+
var v = reader[key];
+
if (v instanceof Struct) {
object[key] = objectify(v);
} else if (v instanceof List) {
@@ -30,7 +33,6 @@
object[key] = v;
}
}
-
return object;
};
|
2106cfa5b5905945ae2899441995c6c6451717ab | src/apps/interactions/macros/kind-form.js | src/apps/interactions/macros/kind-form.js | module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [
{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
/*, {
value: 'policy_feedback',
label: 'Policy feedback',
hint: 'For example, when a company wants to give UK government policy feedback',
} */
],
},
],
}
}
| module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
{
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, and issue or comment on government policy from a company',
}],
}],
}
}
| Enable policy feedback in interaction creation selection | Enable policy feedback in interaction creation selection | JavaScript | mit | uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend | ---
+++
@@ -5,28 +5,25 @@
return {
buttonText: 'Continue',
errors,
- children: [
+ children: [{
+ macroName: 'MultipleChoiceField',
+ type: 'radio',
+ label: 'What would you like to record?',
+ name: 'kind',
+ options: [{
+ value: 'interaction',
+ label: 'A standard interaction',
+ hint: 'For example, an email, phone call or meeting',
+ }, {
+ value: 'service_delivery',
+ label: 'A service that you have provided',
+ hint: 'For example, account management, a significant assist or an event',
+ },
{
- macroName: 'MultipleChoiceField',
- type: 'radio',
- label: 'What would you like to record?',
- name: 'kind',
- options: [{
- value: 'interaction',
- label: 'A standard interaction',
- hint: 'For example, an email, phone call or meeting',
- }, {
- value: 'service_delivery',
- label: 'A service that you have provided',
- hint: 'For example, account management, a significant assist or an event',
- },
- /*, {
- value: 'policy_feedback',
- label: 'Policy feedback',
- hint: 'For example, when a company wants to give UK government policy feedback',
- } */
- ],
- },
- ],
+ value: 'policy_feedback',
+ label: 'Capture policy feedback',
+ hint: 'For example, and issue or comment on government policy from a company',
+ }],
+ }],
}
} |
0734e87bfa82d268366a46b29d3f54f14754d09d | js/swipe.js | js/swipe.js | $(document).ready(function(){
$('.swipeGal').each(function(i, obj){
});
});
| flickrParser = function(json){
var imageList = []
$(json.items).each(function(i, image){
imageList.push({
'title':image.title,
'artist':image.author,
'url':image.link,
'image':image.media.m});
})
return imageList;
}
$(document).ready(function(){
$('.swipeGal').each(function(i, obj){
var feedid = $(obj).data('feed-id');
var url = 'http://ycpi.api.flickr.com/services/feeds/groups_pool.gne?id='+feedid+'&jsoncallback=?';
$.getJSON(url, {format: "json"})
.done(function(data){
parsedImages = flickrParser(data);
//console.log(parsedImages);
});
});
});
| Make request to flickr for group images and parse results into a standard json format. | Make request to flickr for group images and parse results into a standard json format.
| JavaScript | mit | neilvallon/Swipe-Gallery,neilvallon/Swipe-Gallery | ---
+++
@@ -1,5 +1,24 @@
+flickrParser = function(json){
+ var imageList = []
+ $(json.items).each(function(i, image){
+ imageList.push({
+ 'title':image.title,
+ 'artist':image.author,
+ 'url':image.link,
+ 'image':image.media.m});
+ })
+ return imageList;
+}
+
$(document).ready(function(){
$('.swipeGal').each(function(i, obj){
+ var feedid = $(obj).data('feed-id');
+ var url = 'http://ycpi.api.flickr.com/services/feeds/groups_pool.gne?id='+feedid+'&jsoncallback=?';
+ $.getJSON(url, {format: "json"})
+ .done(function(data){
+ parsedImages = flickrParser(data);
+ //console.log(parsedImages);
+ });
});
}); |
0ceb155aad0bad3d343194227b82fa8e074f7b07 | src/js/collections/pool.js | src/js/collections/pool.js | define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
| define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'] + ':' + opts['aggregation'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
| Use aggregation to namespace the connection id | Use aggregation to namespace the connection id
re #506
| JavaScript | agpl-3.0 | dataseed/dataseed-visualisation.js,dataseed/dataseed-visualisation.js | ---
+++
@@ -34,7 +34,7 @@
return opts['type'] + ':' + opts['dimension'];
case 'observations':
- return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'];
+ return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'] + ':' + opts['aggregation'];
default:
return _.uniqueId('conn_'); |
1ec78af6c450fabb206e4da6035d1b69696c9e77 | src/js/apis/todo-api.js | src/js/apis/todo-api.js | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; | var $ = require('jquery');
var _ = require('lodash');
var BASE_URL = '/api/todos/';
var TodoApi = {
create: function(todo, success, failure) {
$.ajax({
url: BASE_URL,
type: 'POST',
dataType: 'json',
data: todo,
success: function() {
success();
},
error: function() {
failure();
}
});
},
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'DELETE',
dataType: 'json',
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
getAll: function(success, failure) {
$.ajax({
url: BASE_URL,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
get: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
dataType: 'json',
success: function(data) {
success(data);
},
error: function(xhr, status, error) {
failure(error);
}
});
},
update: function(_id, props, success, failure) {
$.ajax({
url: BASE_URL + _id,
type: 'PUT',
dataType: 'json',
data: props,
success: function() {
success();
},
error: function(xhr, status, error) {
failure(error);
}
});
},
};
module.exports = TodoApi; | Add create method to Todo Api | Add create method to Todo Api
| JavaScript | mit | haner199401/React-Node-Project-Seed,mattpetrie/React-Node-Project-Seed,mattpetrie/React-Node-Project-Seed,haner199401/React-Node-Project-Seed | ---
+++
@@ -4,6 +4,21 @@
var BASE_URL = '/api/todos/';
var TodoApi = {
+ create: function(todo, success, failure) {
+ $.ajax({
+ url: BASE_URL,
+ type: 'POST',
+ dataType: 'json',
+ data: todo,
+ success: function() {
+ success();
+ },
+ error: function() {
+ failure();
+ }
+ });
+ },
+
destroy: function(_id, success, failure) {
$.ajax({
url: BASE_URL + _id,
@@ -17,6 +32,7 @@
}
});
},
+
getAll: function(success, failure) {
$.ajax({
url: BASE_URL, |
46ca249428c86877ee515c89ccfc6bdf81a43f79 | vis/Code/Remotery.js | vis/Code/Remotery.js |
//
// TODO: Window resizing needs finer-grain control
// TODO: Take into account where user has moved the windows
// TODO: Controls need automatic resizing within their parent windows
//
Remotery = (function()
{
function Remotery()
{
this.WindowManager = new WM.WindowManager();
this.Server = new WebSocketConnection();
// Create the console up front as everything reports to it
this.Console = new Console(this.WindowManager, this.Server);
// Create required windows
this.TitleWindow = new TitleWindow(this.WindowManager, this.Server);
// Kick-off the auto-connect loop
AutoConnect(this);
// Hook up resize event handler
DOM.Event.AddHandler(window, "resize", Bind(OnResizeWindow, this));
OnResizeWindow(this);
}
function AutoConnect(self)
{
// Only attempt to connect if there isn't already a connection or an attempt to connect
if (!self.Server.Connected())
self.Server.Connect("ws://127.0.0.1:17815/remotery");
// Always schedule another check
window.setTimeout(Bind(AutoConnect, self), 5000);
}
function OnResizeWindow(self)
{
// Resize windows
var w = window.innerWidth;
var h = window.innerHeight;
self.Console.WindowResized(w, h);
self.TitleWindow.WindowResized(w, h);
}
return Remotery;
})(); |
//
// TODO: Window resizing needs finer-grain control
// TODO: Take into account where user has moved the windows
// TODO: Controls need automatic resizing within their parent windows
//
Remotery = (function()
{
function Remotery()
{
this.WindowManager = new WM.WindowManager();
this.Server = new WebSocketConnection();
// Create the console up front as everything reports to it
this.Console = new Console(this.WindowManager, this.Server);
// Create required windows
this.TitleWindow = new TitleWindow(this.WindowManager, this.Server);
// Kick-off the auto-connect loop
AutoConnect(this);
// Hook up resize event handler
DOM.Event.AddHandler(window, "resize", Bind(OnResizeWindow, this));
OnResizeWindow(this);
}
function AutoConnect(self)
{
// Only attempt to connect if there isn't already a connection or an attempt to connect
if (!self.Server.Connected())
self.Server.Connect("ws://127.0.0.1:17815/remotery");
// Always schedule another check
window.setTimeout(Bind(AutoConnect, self), 2000);
}
function OnResizeWindow(self)
{
// Resize windows
var w = window.innerWidth;
var h = window.innerHeight;
self.Console.WindowResized(w, h);
self.TitleWindow.WindowResized(w, h);
}
return Remotery;
})(); | Reduce auto-connect loop to 2 seconds. | Reduce auto-connect loop to 2 seconds.
| JavaScript | apache-2.0 | nil-ableton/Remotery,floooh/Remotery,dougbinks/Remotery,nil-ableton/Remotery,island-org/Remotery,nil-ableton/Remotery,dougbinks/Remotery,Celtoys/Remotery,floooh/Remotery,island-org/Remotery,Celtoys/Remotery,island-org/Remotery,barrettcolin/Remotery,dougbinks/Remotery,island-org/Remotery,barrettcolin/Remotery,dougbinks/Remotery,floooh/Remotery,barrettcolin/Remotery,Celtoys/Remotery,nil-ableton/Remotery,barrettcolin/Remotery,floooh/Remotery | ---
+++
@@ -34,7 +34,7 @@
self.Server.Connect("ws://127.0.0.1:17815/remotery");
// Always schedule another check
- window.setTimeout(Bind(AutoConnect, self), 5000);
+ window.setTimeout(Bind(AutoConnect, self), 2000);
}
|
a0501d86dcee4ef1ddad9e7e65db93b7e0b8b10b | src/events.js | src/events.js | var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget, eventName = 'on' + name;
if (!element.domLayerNode || !element.domLayerNode.events || !element.domLayerNode.events[eventName]) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
return element.domLayerNode.events[eventName](e, value, element.domLayerNode);
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
| var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget;
if (!element.domLayerNode || !element.domLayerNode.events) {
return;
}
var events = []
var mouseClickEventName;
var bail = false;
if (name.substr(name.length - 5) === 'click') {
mouseClickEventName = 'onmouse' + name;
if (element.domLayerNode.events[mouseClickEventName]) {
events.push(mouseClickEventName);
}
// Do not call the `click` handler if it's not a left click.
if (e.button !== 0) {
bail = true;
}
}
var eventName;
if (!bail) {
eventName = 'on' + name;
if (element.domLayerNode.events[eventName]) {
events.push(eventName);
}
}
if (!events.length) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
for (var i = 0, len = events.length; i < len ; i++) {
element.domLayerNode.events[events[i]](e, value, element.domLayerNode);
}
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
| Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click. | Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click.
| JavaScript | mit | crysalead-js/dom-layer,crysalead-js/dom-layer | ---
+++
@@ -4,8 +4,35 @@
var eventManager;
function eventHandler(name, e) {
- var element = e.delegateTarget, eventName = 'on' + name;
- if (!element.domLayerNode || !element.domLayerNode.events || !element.domLayerNode.events[eventName]) {
+ var element = e.delegateTarget;
+ if (!element.domLayerNode || !element.domLayerNode.events) {
+ return;
+ }
+
+ var events = []
+ var mouseClickEventName;
+ var bail = false;
+
+ if (name.substr(name.length - 5) === 'click') {
+ mouseClickEventName = 'onmouse' + name;
+ if (element.domLayerNode.events[mouseClickEventName]) {
+ events.push(mouseClickEventName);
+ }
+ // Do not call the `click` handler if it's not a left click.
+ if (e.button !== 0) {
+ bail = true;
+ }
+ }
+
+ var eventName;
+ if (!bail) {
+ eventName = 'on' + name;
+ if (element.domLayerNode.events[eventName]) {
+ events.push(eventName);
+ }
+ }
+
+ if (!events.length) {
return;
}
@@ -13,7 +40,10 @@
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
- return element.domLayerNode.events[eventName](e, value, element.domLayerNode);
+
+ for (var i = 0, len = events.length; i < len ; i++) {
+ element.domLayerNode.events[events[i]](e, value, element.domLayerNode);
+ }
}
function getManager() { |
b9e61516e633e79909371d6c185818e3579085d2 | languages.js | languages.js | module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'}
];
| module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'JSON', mode:'json'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'},
{name:'XML', mode:'xml'}
];
| Add XML and JSON modes | Add XML and JSON modes
| JavaScript | unlicense | briangreenery/gist | ---
+++
@@ -3,10 +3,12 @@
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
+ {name:'JSON', mode:'json'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
- {name:'Text', mode:'text'}
+ {name:'Text', mode:'text'},
+ {name:'XML', mode:'xml'}
]; |
94a0a48971adbd1583707bd4ed9f874db0b82385 | test/dispose.js | test/dispose.js | describe('asking if a visible div scrolled', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
}); | describe('using the watcher API to dispose and watch again', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
}); | Rename the test on watcher API to have something more specific | Rename the test on watcher API to have something more specific
| JavaScript | mit | tzi/in-viewport,tzi/in-viewport,vvo/in-viewport,vvo/in-viewport,fasterize/in-viewport,fasterize/in-viewport,ipy/in-viewport,ipy/in-viewport | ---
+++
@@ -1,4 +1,4 @@
-describe('asking if a visible div scrolled', function() {
+describe('using the watcher API to dispose and watch again', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean); |
5cb52c0c7d5149048fdc0f36c18e033a48f33fad | src/scripts/browser/components/auto-launcher/impl-win32.js | src/scripts/browser/components/auto-launcher/impl-win32.js | import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, callback);
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
| import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, (err) => {
const notFound = err.message == 'The system was unable to find the specified registry key or value.';
if (notFound) {
callback();
} else {
callback(err);
}
});
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
| Handle not found error in win32 auto launcher | Handle not found error in win32 auto launcher
| JavaScript | mit | Hadisaeed/test-build,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Hadisaeed/test-build,Hadisaeed/test-build,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,Aluxian/Messenger-for-Desktop | ---
+++
@@ -21,7 +21,14 @@
disable(callback) {
log('removing registry key for', manifest.productName);
- Win32AutoLauncher.REG_KEY.remove(manifest.productName, callback);
+ Win32AutoLauncher.REG_KEY.remove(manifest.productName, (err) => {
+ const notFound = err.message == 'The system was unable to find the specified registry key or value.';
+ if (notFound) {
+ callback();
+ } else {
+ callback(err);
+ }
+ });
}
isEnabled(callback) { |
b989f178fe4fa05a7422a5f36a0b8291d35bb621 | src/mailer.js | src/mailer.js | var email = require('emailjs')
, debug = require('debug')('wifi-chat:mailer')
var config = null
, server = null
var connect = function() {
debug('Connecting to mail server', config.email.connection)
server = email.server.connect(config.email.connection)
}
var setConfig = function(configuration) {
config = configuration
connect()
}
var sendMail = function(to, subject, template, substitutions, callback) {
var content = template.replace(new RegExp('%url%', 'g'), config.url)
Object.keys(substitutions || {}).forEach(function(key) {
content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key])
})
var message = {
text: content,
from: config.email.sendAddress,
to: to,
subject: subject
}
debug('Sending password reset email', message)
server.send(message, callback)
}
module.exports = {
setConfig: setConfig,
sendMail: sendMail
} | var email = require('emailjs')
, debug = require('debug')('wifi-chat:mailer')
var config = null
, server = null
var connect = function() {
debug('Connecting to mail server', config.email.connection)
server = email.server.connect(config.email.connection)
}
var setConfig = function(configuration) {
config = configuration
connect()
}
var sendMail = function(to, subject, template, substitutions, callback) {
var content = template.replace(new RegExp('%url%', 'g'), config.url)
Object.keys(substitutions || {}).forEach(function(key) {
content = content.replace(new RegExp('%' + key + '%', 'g'), substitutions[key])
})
var message = {
text: content,
from: config.email.sendAddress,
to: to,
subject: subject
}
debug('Sending email', message)
server.send(message, callback)
}
module.exports = {
setConfig: setConfig,
sendMail: sendMail
} | Update debug message to be less incorrect | Update debug message to be less incorrect
| JavaScript | apache-2.0 | project-isizwe/wifi-chat,webhost/wifi-chat,project-isizwe/wifi-chat,project-isizwe/wifi-chat,webhost/wifi-chat,webhost/wifi-chat | ---
+++
@@ -25,7 +25,7 @@
to: to,
subject: subject
}
- debug('Sending password reset email', message)
+ debug('Sending email', message)
server.send(message, callback)
}
|
099d30fdb02e4e69edc07529b9630f51b9e2dc4e | www/script.js | www/script.js | HandlebarsIntl.registerWith(Handlebars);
$(function() {
window.state = {};
var source = $("#stats-template").html();
var template = Handlebars.compile(source);
refreshStats(template);
setInterval(function() {
refreshStats(template);
}, 5000)
});
function refreshStats(template) {
$.getJSON("/stats", function(stats) {
$("#alert").addClass('hide');
// Sort miners by ID
if (stats.miners) {
stats.miners = stats.miners.sort(compare)
}
var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15
stats.nextEpoch = stats.now + epochOffset
// Repaint stats
var html = template(stats);
$('#stats').html(html);
}).fail(function() {
$("#alert").removeClass('hide');
});
}
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
| HandlebarsIntl.registerWith(Handlebars);
$(function() {
window.state = {};
var source = $("#stats-template").html();
var template = Handlebars.compile(source);
refreshStats(template);
setInterval(function() {
refreshStats(template);
}, 5000)
});
function refreshStats(template) {
$.getJSON("/stats", function(stats) {
$("#alert").addClass('hide');
// Sort miners by ID
if (stats.miners) {
stats.miners = stats.miners.sort(compare)
}
var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 14.4
stats.nextEpoch = stats.now + epochOffset
// Repaint stats
var html = template(stats);
$('#stats').html(html);
}).fail(function() {
$("#alert").removeClass('hide');
});
}
function compare(a, b) {
if (a.name < b.name)
return -1;
if (a.name > b.name)
return 1;
return 0;
}
| Adjust block time to 14.4 seconds | Adjust block time to 14.4 seconds
| JavaScript | mit | sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy,sammy007/ether-proxy | ---
+++
@@ -20,7 +20,7 @@
stats.miners = stats.miners.sort(compare)
}
- var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 15
+ var epochOffset = (30000 - (stats.height % 30000)) * 1000 * 14.4
stats.nextEpoch = stats.now + epochOffset
// Repaint stats |
3e89abf57c2242f8bef493eb0dc8fa053bec9e48 | lib/index.js | lib/index.js | /**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number')
number = Number(number)
// NaN => 0
if (isNaN(number))
number = 0
// Return Infinity immediately
if (!isFinite(number))
return '' + number
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0)
result.push(separator)
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0)
result.push('-')
return result
.reverse()
.join('')
}
| /**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number') {
number = Number(number)
}
// NaN => 0
if (isNaN(number)) {
number = 0
}
// Return Infinity immediately
if (!isFinite(number)) {
return '' + number
}
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0) {
result.push(separator)
}
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0) {
result.push('-')
}
return result
.reverse()
.join('')
}
| Update code to follow standard style | Update code to follow standard style
| JavaScript | mit | cesarandreu/comma-number | ---
+++
@@ -8,16 +8,19 @@
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
- if (typeof number !== 'number')
+ if (typeof number !== 'number') {
number = Number(number)
+ }
// NaN => 0
- if (isNaN(number))
+ if (isNaN(number)) {
number = 0
+ }
// Return Infinity immediately
- if (!isFinite(number))
+ if (!isFinite(number)) {
return '' + number
+ }
var stringNumber = ('' + Math.abs(number))
.split('')
@@ -25,14 +28,16 @@
var result = []
for (var i = 0; i < stringNumber.length; i++) {
- if (i && i % 3 === 0)
+ if (i && i % 3 === 0) {
result.push(separator)
+ }
result.push(stringNumber[i])
}
// Handle negative numbers
- if (number < 0)
+ if (number < 0) {
result.push('-')
+ }
return result
.reverse() |
2a1121c856f387c164e5239e6a7dacf2d2f29330 | test/test-main.js | test/test-main.js | 'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'jquery': '../lib/jquery/jquery',
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
}); | 'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
}); | Remove jQuery dependency, not used | TEST: Remove jQuery dependency, not used
| JavaScript | mit | goliatone/gsocket | ---
+++
@@ -18,7 +18,6 @@
baseUrl: '/base/src',
paths: {
- 'jquery': '../lib/jquery/jquery',
'extend': '../lib/gextend/extend'
},
|
7e71970b1cb76c8a916e365491ca07252a61a208 | src/server.js | src/server.js | import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
//app.set('view engine', 'html');
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.send(html);
/*var router = Router.create({location: req.url, routes: routes})
router.run(function(Handler, state) {
var html = ReactDOMServer.renderToString(<Handler/>)
return res.render('react_page', {html: html})
})*/
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('../public'));
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.render('index', {html: html});
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
| Handle initial page laod via express | Handle initial page laod via express
| JavaScript | agpl-3.0 | voidxnull/libertysoil-site,Lokiedu/libertysoil-site,voidxnull/libertysoil-site,Lokiedu/libertysoil-site | ---
+++
@@ -9,7 +9,11 @@
let app = express();
//app.engine('html', require('ejs').renderFile);
-//app.set('view engine', 'html');
+
+app.set('views', __dirname + '/views');
+app.set('view engine', 'ejs');
+
+app.use(express.static('../public'));
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
@@ -20,13 +24,8 @@
</Router>
);
- return res.send(html);
+ return res.render('index', {html: html});
- /*var router = Router.create({location: req.url, routes: routes})
- router.run(function(Handler, state) {
- var html = ReactDOMServer.renderToString(<Handler/>)
- return res.render('react_page', {html: html})
- })*/
});
|
14e97545ba507765cd186b549981e0ebc55f1dff | javascript/NocaptchaField.js | javascript/NocaptchaField.js | var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
grecaptcha.render(field, options);
}
}
| var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
var widget_id = grecaptcha.render(field, options);
field.setAttribute("data-widgetid", widget_id);
}
}
| Store widget_id on field element | Store widget_id on field element
This allows the captcha element to be targeted via the js api in situations where there is more than one nocaptcha widget on the page. See examples referencing `opt_widget_id` here https://developers.google.com/recaptcha/docs/display#js_api | JavaScript | bsd-3-clause | UndefinedOffset/silverstripe-nocaptcha,UndefinedOffset/silverstripe-nocaptcha | ---
+++
@@ -11,6 +11,7 @@
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
- grecaptcha.render(field, options);
+ var widget_id = grecaptcha.render(field, options);
+ field.setAttribute("data-widgetid", widget_id);
}
} |
2ebe898d9f2284ee0f25d8ac927bef4e7bb730de | lib/store.js | lib/store.js | var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
limit.date = now;
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
| var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
if (resetInner) {
limit.date = now;
}
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
| Fix bug with inner reset time | Fix bug with inner reset time | JavaScript | mit | StevenThuriot/express-rate-limiter | ---
+++
@@ -26,7 +26,9 @@
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
- limit.date = now;
+ if (resetInner) {
+ limit.date = now;
+ }
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate); |
df1807f823332d076a0dff7e6ec0b49b8a42e8ad | config-SAMPLE.js | config-SAMPLE.js | /* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
| /* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/muni',
position: 'top_left',
config: {
stops: ['48|3463']
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
apiKey: 'MUST_PUT_KEY_HERE',
latLng: '37.700000,-122.400000'
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
| Update sample config for new modules. | Update sample config for new modules.
| JavaScript | apache-2.0 | jhurstus/mirror,jhurstus/mirror | ---
+++
@@ -20,9 +20,18 @@
}
},
{
+ module: 'hurst/muni',
+ position: 'top_left',
+ config: {
+ stops: ['48|3463']
+ }
+ },
+ {
module: 'hurst/weather',
position: 'top_right',
config: {
+ apiKey: 'MUST_PUT_KEY_HERE',
+ latLng: '37.700000,-122.400000'
}
}
] |
ead9142a9701300da3021e79155a9717ec4c3683 | app/src/components/RobotSettings/AttachedInstrumentsCard.js | app/src/components/RobotSettings/AttachedInstrumentsCard.js | // @flow
// RobotSettings card for wifi status
import * as React from 'react'
import {type StateInstrument} from '../../robot'
import InstrumentInfo from './InstrumentInfo'
import {Card} from '@opentrons/components'
type Props = {
left: StateInstrument,
right: StateInstrument
}
const TITLE = 'Pipettes'
export default function AttachedInstrumentsCard (props: Props) {
// TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes
// here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo
// delete channels and volume in either elft or right to view value and button message change
// apologies for the messy logic, hard to anticipate what is returned just yet
const attachedInstruments = {
left: {
mount: 'left',
channels: 8,
volume: 300
},
right: {
mount: 'right',
channels: 1,
volume: 10
}
}
return (
<Card title={TITLE} >
<InstrumentInfo {...attachedInstruments.left}/>
<InstrumentInfo {...attachedInstruments.right} />
</Card>
)
}
| // RobotSettings card for wifi status
import * as React from 'react'
import InstrumentInfo from './InstrumentInfo'
import {Card} from '@opentrons/components'
const TITLE = 'Pipettes'
export default function AttachedInstrumentsCard (props) {
// TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes
// here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo
// delete channels and volume in either elft or right to view value and button message change
// apologies for the messy logic, hard to anticipate what is returned just yet
const attachedInstruments = {
left: {
mount: 'left',
channels: 8,
volume: 300
},
right: {
mount: 'right',
channels: 1,
volume: 10
}
}
return (
<Card title={TITLE} >
<InstrumentInfo {...attachedInstruments.left}/>
<InstrumentInfo {...attachedInstruments.right} />
</Card>
)
}
| Remove flow typchecking from InstrumentCard | Remove flow typchecking from InstrumentCard
- Removed typchecking from AttachedInstrumentCard since mock data is currently being used.
| JavaScript | apache-2.0 | OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,Opentrons/labware,OpenTrons/opentrons_sdk | ---
+++
@@ -1,17 +1,11 @@
-// @flow
// RobotSettings card for wifi status
import * as React from 'react'
-import {type StateInstrument} from '../../robot'
import InstrumentInfo from './InstrumentInfo'
import {Card} from '@opentrons/components'
-type Props = {
- left: StateInstrument,
- right: StateInstrument
-}
const TITLE = 'Pipettes'
-export default function AttachedInstrumentsCard (props: Props) {
+export default function AttachedInstrumentsCard (props) {
// TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes
// here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo
// delete channels and volume in either elft or right to view value and button message change |
761977b9c98bd5f92d6c90981fff16fec2df4893 | src/components/svg/SVGComponents.js | src/components/svg/SVGComponents.js | import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size = '40' }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: null,
}
| import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: 40,
}
| Set the default size to 40 on SVGBoxes | Set the default size to 40 on SVGBoxes
The null value was causing some weird rendering issues on a few icons
| JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -28,7 +28,7 @@
onClick: null,
}
-export const SVGBox = ({ children, className, size = '40' }) =>
+export const SVGBox = ({ children, className, size }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
@@ -42,6 +42,6 @@
size: PropTypes.string,
}
SVGBox.defaultProps = {
- size: null,
+ size: 40,
}
|
904ec5fd379bf47f66794af36ffcd5ecbf5d3ec5 | blueprints/ember-flexberry/index.js | blueprints/ember-flexberry/index.js | /* globals module */
module.exports = {
afterInstall: function () {
this.addBowerPackageToProject('git://github.com/BreadMaker/semantic-ui-daterangepicker.git#5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be');
this.addBowerPackageToProject('datatables');
},
normalizeEntityName: function () {}
}; | /* globals module */
module.exports = {
afterInstall: function () {
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'datatables', target: '~1.10.8' }
]);
},
normalizeEntityName: function () {}
}; | Fix bower packages installation for addon | Fix bower packages installation for addon
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -1,8 +1,10 @@
/* globals module */
module.exports = {
afterInstall: function () {
- this.addBowerPackageToProject('git://github.com/BreadMaker/semantic-ui-daterangepicker.git#5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be');
- this.addBowerPackageToProject('datatables');
+ return this.addBowerPackagesToProject([
+ { name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
+ { name: 'datatables', target: '~1.10.8' }
+ ]);
},
normalizeEntityName: function () {} |
ae5d7724d279e3d1feb1c696d70f6a030407053e | test/patch.js | test/patch.js | var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
});
patch(host, server, true).listen("address"); | var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
}).on("error", console.log);
patch(host, server, true).listen("address"); | Add error listener to test | Add error listener to test
| JavaScript | mit | buschtoens/distroy | ---
+++
@@ -29,5 +29,5 @@
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
- });
+ }).on("error", console.log);
patch(host, server, true).listen("address"); |
a7b3e2edaa8f1f2791f3cf8c88d210ca7f3b06c1 | webpack.config.js | webpack.config.js | 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
| 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
cache: true,
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
fix: true,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
| Improve ESLint options for Webpack | Improve ESLint options for Webpack | JavaScript | mit | planttheidea/moize,planttheidea/moize | ---
+++
@@ -21,9 +21,11 @@
],
loader: 'eslint-loader',
options: {
+ cache: true,
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
+ fix: true,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/ |
fcaba4d5f8df8562dabeacbdcdb4f20abe9fcafd | webpack.config.js | webpack.config.js | const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
| const path = require('path');
const webpack = require("webpack");
const DEBUG = process.argv.includes('--debug'); // `webpack --debug` or NOT
const plugins = [
new webpack.optimize.OccurrenceOrderPlugin(),
];
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: '"production"' }
})
);
}
module.exports = {
entry: "./src/js/ipcalc.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "public/js")
},
plugins: plugins,
devtool: DEBUG ? "#cheap-module-eval-source-map" : "#cheap-module-source-map",
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
}
}
| Add vue.js release build option | Add vue.js release build option
| JavaScript | mit | stereocat/ipcalc_js,stereocat/ipcalc_js | ---
+++
@@ -8,7 +8,10 @@
if (!DEBUG) {
plugins.push(
new webpack.optimize.UglifyJsPlugin(),
- new webpack.optimize.AggressiveMergingPlugin()
+ new webpack.optimize.AggressiveMergingPlugin(),
+ new webpack.DefinePlugin({
+ 'process.env': { NODE_ENV: '"production"' }
+ })
);
}
|
06296e083225aab969d009cb0bf312872a18e504 | blueprints/ember-table/index.js | blueprints/ember-table/index.js | module.exports = {
normalizeEntityName: function() {},
afterInstall: function(options) {
// We assume that handlebars, ember, and jquery already exist
// FIXME(azirbel): Do we need to install lodash too?
return this.addBowerPackagesToProject([
{
'name': 'git@github.com:azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
},
{
'name': 'jquery-mousewheel',
'target': '~3.1.4'
},
{
'name': 'jquery-ui',
// FIXME(azirbel): Can we use a newer version?
'target': '1.10.1'
}
]);
}
};
| module.exports = {
normalizeEntityName: function() {},
afterInstall: function(options) {
// We assume that handlebars, ember, and jquery already exist
// FIXME(azirbel): Do we need to install lodash too?
return this.addBowerPackagesToProject([
{
'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
},
{
'name': 'jquery-mousewheel',
'target': '~3.1.4'
},
{
'name': 'jquery-ui',
// FIXME(azirbel): Can we use a newer version?
'target': '1.10.1'
}
]);
}
};
| Use more general bower syntax to import antiscroll | Use more general bower syntax to import antiscroll
| JavaScript | mit | zenefits/ember-table-addon,Addepar/ember-table-addon,zenefits/ember-table-addon,Addepar/ember-table-addon | ---
+++
@@ -6,7 +6,7 @@
// FIXME(azirbel): Do we need to install lodash too?
return this.addBowerPackagesToProject([
{
- 'name': 'git@github.com:azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
+ 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356'
},
{
'name': 'jquery-mousewheel', |
349bad1afc06c0af44ff42ab7358e393f3ec4fd9 | lib/ipc-helpers/dump-node.js | lib/ipc-helpers/dump-node.js | #!/usr/bin/env node
process.on('exit', function sendCoverage() {
process.send({'coverage': global.__coverage__});
});
| #!/usr/bin/env node
process.on('beforeExit', function sendCovereageBeforeExit() {
process.send({'coverage': global.__coverage__});
});
| Use beforeExit event to send coverage | Use beforeExit event to send coverage
| JavaScript | mit | rtsao/unitest | ---
+++
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-process.on('exit', function sendCoverage() {
+process.on('beforeExit', function sendCovereageBeforeExit() {
process.send({'coverage': global.__coverage__});
}); |
7d8145fce09a92004fbf302953d37863d2bc202b | lib/matrices.js | lib/matrices.js |
function Matrix(options) {
options = options || {};
var values;
if (options.values)
values = options.values;
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
|
function Matrix(options) {
options = options || {};
var values;
if (options.values) {
values = options.values.slice();
for (var k = 0; k < values.length; k++)
values[k] = values[k].slice();
}
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
| Refactor matrix creation to use values slice | Refactor matrix creation to use values slice
| JavaScript | mit | ajlopez/MathelJS | ---
+++
@@ -4,8 +4,12 @@
var values;
- if (options.values)
- values = options.values;
+ if (options.values) {
+ values = options.values.slice();
+
+ for (var k = 0; k < values.length; k++)
+ values[k] = values[k].slice();
+ }
if (options.rows && options.columns && !values) {
values = []; |
61f575559be7c973e2fa4bb816221dc63112bffd | test/TestServer/config/UnitTest.js | test/TestServer/config/UnitTest.js | 'use strict';
// Default amount of devices required to run tests.
module.exports = {
devices: {
// This is a list of required platforms.
// All required platform should have minDevices entry.
// So all required platforms should be listed in desired platform list.
ios: -1,
android: -1,
desktop: -1
},
minDevices: {
// This is a list of desired platforms.
ios: 2,
android: 0,
desktop: 0
},
// if 'devices[platform]' is -1 we wont limit the amount of devices.
// We will wait some amount of time before tests.
waiting_for_devices_timeout: 5 * 1000
};
| 'use strict';
// Default amount of devices required to run tests.
module.exports = {
devices: {
// This is a list of required platforms.
// All required platform should have minDevices entry.
// So all required platforms should be listed in desired platform list.
ios: -1,
android: -1,
desktop: -1
},
minDevices: {
// This is a list of desired platforms.
ios: 3,
android: 3,
desktop: 3
},
// if 'devices[platform]' is -1 we wont limit the amount of devices.
// We will wait some amount of time before tests.
waiting_for_devices_timeout: 5 * 1000
};
| Revert "Reduce the min number of devices to test." | Revert "Reduce the min number of devices to test."
This reverts commit 90e5494b3212350d7cb7ef946c5b9d8fa62189d5.
| JavaScript | mit | thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin,thaliproject/Thali_CordovaPlugin | ---
+++
@@ -13,9 +13,9 @@
},
minDevices: {
// This is a list of desired platforms.
- ios: 2,
- android: 0,
- desktop: 0
+ ios: 3,
+ android: 3,
+ desktop: 3
},
// if 'devices[platform]' is -1 we wont limit the amount of devices.
// We will wait some amount of time before tests. |
c29d3a670722b2f4d0a394e6a72ecb647687893a | .storybook/main.js | .storybook/main.js | module.exports = {
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
| module.exports = {
stories: ['../**/*.stories.js'],
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
| Define where to find the component stories | Define where to find the component stories
| JavaScript | mit | teamleadercrm/teamleader-ui | ---
+++
@@ -1,3 +1,4 @@
module.exports = {
+ stories: ['../**/*.stories.js'],
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
}; |
ade0cebb2c7edcacb2f0e83a103e55529fa024cc | lib/user-data.js | lib/user-data.js | //
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
data.path = ipc.sendSync('getUserSavedDir', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
| //
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
savedDir.path = ipc.sendSync('getUserSavedDir', null)
savedDir.contents = JSON.parse(fs.readFileSync(savedDir.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.getSavedDir = getSavedDir
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
| Fix having not set this up correctly | Fix having not set this up correctly
| JavaScript | bsd-2-clause | jlord/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron | ---
+++
@@ -15,8 +15,8 @@
var getSavedDir = function () {
var savedDir = {}
- data.path = ipc.sendSync('getUserSavedDir', null)
- data.contents = JSON.parse(fs.readFileSync(data.path))
+ savedDir.path = ipc.sendSync('getUserSavedDir', null)
+ savedDir.contents = JSON.parse(fs.readFileSync(savedDir.path))
return savedDir
}
@@ -42,5 +42,6 @@
}
module.exports.getData = getData
+module.exports.getSavedDir = getSavedDir
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory |
b1da47403f4871313e0759a21091ace04151cb84 | src/renderer/actions/connections.js | src/renderer/actions/connections.js | import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const [ server, config ] = await* [
servers.items.find(srv => srv.id === id),
sqlectron.config.get(),
];
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
await dbSession.connect(server, database);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
| import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const server = servers.items.find(srv => srv.id === id);
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
const [, config ] = await Promise.all([
dbSession.connect(server, database),
sqlectron.config.get(),
]);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
| Use promise all at the right place in the server connecting action | Use promise all at the right place in the server connecting action | JavaScript | mit | sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui | ---
+++
@@ -12,14 +12,14 @@
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
- const [ server, config ] = await* [
- servers.items.find(srv => srv.id === id),
- sqlectron.config.get(),
- ];
+ const server = servers.items.find(srv => srv.id === id);
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
- await dbSession.connect(server, database);
+ const [, config ] = await Promise.all([
+ dbSession.connect(server, database),
+ sqlectron.config.get(),
+ ]);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error }); |
0ebb23201bc8364368cb77c5b502a345d3144f0e | www/pg-plugin-fb-connect.js | www/pg-plugin-fb-connect.js | PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(function(e) {
console.log("init: " + e);
}, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
try {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
//FB.Auth.setSession(e.session, 'connected'); // never gets called because the plugin spawns Mobile Safari/Facebook app
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
} catch (e) {
alert(e);
}
},
logout: function(cb) {
try {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
} catch (e) {
alert(e);
}
},
getLoginStatus: function(cb) {
try {
PhoneGap.exec(function(e) {
if (cb) cb(e);
console.log("getLoginStatus: " + e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
} catch (e) {
alert(e);
}
}
};
| PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(null, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
FB.Auth.setSession(e.session, 'connected');
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
},
logout: function(cb) {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
},
getLoginStatus: function(cb) {
PhoneGap.exec(function(e) {
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
}
}; | Update the JS to remove alerts etc and login now has to have its success method called | Update the JS to remove alerts etc and login now has to have its success method called
| JavaScript | mit | barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect | ---
+++
@@ -1,39 +1,24 @@
PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
- PhoneGap.exec(function(e) {
- console.log("init: " + e);
- }, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
+ PhoneGap.exec(null, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
- try {
- b = b || { perms: '' };
- PhoneGap.exec(function(e) { // login
- //FB.Auth.setSession(e.session, 'connected'); // never gets called because the plugin spawns Mobile Safari/Facebook app
- if (a) a(e);
- }, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
- } catch (e) {
- alert(e);
- }
+ b = b || { perms: '' };
+ PhoneGap.exec(function(e) { // login
+ FB.Auth.setSession(e.session, 'connected');
+ if (a) a(e);
+ }, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
},
logout: function(cb) {
- try {
- PhoneGap.exec(function(e) {
- FB.Auth.setSession(null, 'notConnected');
- if (cb) cb(e);
- }, null, 'com.facebook.phonegap.Connect', 'logout', []);
- } catch (e) {
- alert(e);
- }
+ PhoneGap.exec(function(e) {
+ FB.Auth.setSession(null, 'notConnected');
+ if (cb) cb(e);
+ }, null, 'com.facebook.phonegap.Connect', 'logout', []);
},
getLoginStatus: function(cb) {
- try {
- PhoneGap.exec(function(e) {
- if (cb) cb(e);
- console.log("getLoginStatus: " + e);
- }, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
- } catch (e) {
- alert(e);
- }
+ PhoneGap.exec(function(e) {
+ if (cb) cb(e);
+ }, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
}
}; |
a7dd9961d9350fc38ad2ad679c6e6b1d1e85e6e9 | packages/core/lib/commands/help.js | packages/core/lib/commands/help.js | var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function(options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function(selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
commandHelp.options.forEach(option => {
console.log(` ${option.option}`);
console.log(` ${option.description}`);
});
}
console.log("");
}
};
module.exports = command;
| var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function (options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function (selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
for (const option of commandHelp.options) {
if (option.internal) {
continue;
}
console.log(` ${option.option}`);
console.log(` ${option.description}`);
}
}
console.log("");
}
};
module.exports = command;
| Allow commands to define internal options | Allow commands to define internal options
So those options don't appear in the help output
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -12,7 +12,7 @@
]
},
builder: {},
- run: function(options, callback) {
+ run: function (options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
@@ -33,7 +33,7 @@
return callback();
}
},
- displayCommandHelp: function(selectedCommand) {
+ displayCommandHelp: function (selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
@@ -41,10 +41,14 @@
if (commandHelp.options.length > 0) {
console.log(` Options: `);
- commandHelp.options.forEach(option => {
+ for (const option of commandHelp.options) {
+ if (option.internal) {
+ continue;
+ }
+
console.log(` ${option.option}`);
console.log(` ${option.description}`);
- });
+ }
}
console.log("");
} |
00d07f1f24af00950908b79e8670697d3b8f3a17 | webpack.config.js | webpack.config.js | var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': 'lodash',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
}; | var webpack = require('webpack')
, glob = require('glob').sync
, ExtractTextPlugin = require('extract-text-webpack-plugin');
// Find all the css files but sort the common ones first
var cssFiles = glob('./src/common/**/*.css').concat(glob('./src/!(common)/**/*.css'));
module.exports = {
entry: {
'sir-trevor-blocks.js' : './src/entry.js',
'sir-trevor-blocks.css' : cssFiles
},
output: {
path: __dirname,
filename: '[name]'
},
module: {
loaders: [
{ test: /\.html$/, loader: 'html' },
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
]
},
plugins: [
new ExtractTextPlugin('[name]'),
],
externals: {
'lodash': '_',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n',
'highlightjs': 'hljs',
'ckeditor': 'CKEDITOR'
}
}; | Fix webpack lodash external require | Fix webpack lodash external require
| JavaScript | mit | Upplication/sir-trevor-blocks,Upplication/sir-trevor-blocks | ---
+++
@@ -24,7 +24,7 @@
new ExtractTextPlugin('[name]'),
],
externals: {
- 'lodash': 'lodash',
+ 'lodash': '_',
'jquery': 'jQuery',
'sir-trevor-js': 'SirTrevor',
'i18n': 'i18n', |
d2eeb477b2925e6e83e63f75b497cc2b24d5e9d5 | webpack.config.js | webpack.config.js | const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
} | const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
}
]
}
} | Add style to Webpack rules. | Add style to Webpack rules.
| JavaScript | mit | sheamunion/fem_intro_react_code_along,sheamunion/fem_intro_react_code_along | ---
+++
@@ -21,6 +21,18 @@
{
test: /\.js$/,
loader: 'babel-loader'
+ },
+ {
+ test: /\.css$/,
+ use: [
+ 'style-loader',
+ {
+ loader: 'css-loader',
+ options: {
+ url: false
+ }
+ }
+ ]
}
]
} |
e1495b4a57c88e50ad1cb817372502f59c51b596 | lib/MultiSelection/OptionsListWrapper.js | lib/MultiSelection/OptionsListWrapper.js | import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter()} {...props} ref={ref} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
| import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter({ ref })} {...props} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
| Fix ref on downshift element | Fix ref on downshift element
| JavaScript | apache-2.0 | folio-org/stripes-components,folio-org/stripes-components | ---
+++
@@ -13,7 +13,7 @@
...props
}, ref) => {
if (useLegacy) {
- return <div {...menuPropGetter()} {...props} ref={ref} hidden={!isOpen}>{children}</div>;
+ return <div {...menuPropGetter({ ref })} {...props} hidden={!isOpen}>{children}</div>;
}
const { |
3b4ee7102882f6e629828ac1e3e44d8f343d4012 | src/features/home/redux/initialState.js | src/features/home/redux/initialState.js | const initialState = {
count: 0,
redditReactjsList: [],
// navTreeData: null,
// projectData: null,
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: true,
};
export default initialState;
| const initialState = {
count: 0,
redditReactjsList: [],
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: false,
};
export default initialState;
| Hide demo alert by default. | Hide demo alert by default.
| JavaScript | mit | supnate/rekit-portal,supnate/rekit-portal | ---
+++
@@ -1,8 +1,6 @@
const initialState = {
count: 0,
redditReactjsList: [],
- // navTreeData: null,
- // projectData: null,
elementById: {},
fileContentById: {},
features: null,
@@ -13,7 +11,7 @@
fetchFileContentPending: false,
fetchFileContentError: null,
- demoAlertVisible: true,
+ demoAlertVisible: false,
};
export default initialState; |
35c3457c31087a85103c9729279343775511c7e4 | packages/lesswrong/lib/reactRouterWrapper.js | packages/lesswrong/lib/reactRouterWrapper.js | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "function")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or functions, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) | /*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "object")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or objects, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
}) | Fix dumb bug in link-props handling | Fix dumb bug in link-props handling
| JavaScript | mit | Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2 | ---
+++
@@ -24,9 +24,9 @@
}
export const Link = (props) => {
- if (!(typeof props.to === "string" || typeof props.to === "function")) {
+ if (!(typeof props.to === "string" || typeof props.to === "object")) {
// eslint-disable-next-line no-console
- console.error("Props 'to' for Link components only accepts strings or functions, passed type: ", typeof props.to)
+ console.error("Props 'to' for Link components only accepts strings or objects, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/> |
0e1e23a2754c56869c9abf1ec058f69ac047905b | FrontEndCreator/questions.js | FrontEndCreator/questions.js | //must have a blank option one for question of type dropdown
standard('qTypes',["","Drop Down", "Multidrop-down", "Number Fillin", "Essay", "Code"]);
standard('qTypes2',["","dropdowns", "multidropdowns", "numfillins", "essays", "codes"]);
standard('correct',["Correct","Incorrect"]);
standard('incorrect',["Incorrect","Correct"]);
quiz([
question("dropdown","Type of Question:",choices['qTypes'],'Choose a type...',choices['qTypes2']),
question("essay","Question Text:",3,30,'Your text here...'),
questionSet("dropdowns multidropdowns",[
question("essay","Placeholder Text:",3,30,'Your text here...'),
question("multiquestion","",[
question("essay","Answer Choice 1:",3,30,'Your text here...'),
question("dropdown","",choices['correct'])
]),
question("multiquestion","",[
question("essay","Answer Choice 2:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
]),
question("multiquestion","",[
question("essay","Answer Choice 3:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
])
]),
questionSet("codes",[
question("essay","Base Code:",3,30,'Your base code here...')
]),
questionSet("numfillins essays",[
question("essay","Placeholder Text:",3,30,'Your placeholder text here...')
])
]);
| var config = {
'.chosen-select' : {},
};
for (var selector in config) {
$(selector).chosen(config[selector]);
}
for(var k = 0; k < showHideList.length; k++){
// alert(showHide);
var showHide=showHideList[k];
for(var i = 0; i < showHide.length; i++){
// alert(showHide[i]);
if(showHide[i].length>0)
$("."+showHide[i]).hide();
}
}
function SUBMIT_ONE_QUIZ(quiz){
var i = 0;
var allSend = "";
$(quiz).find(".question").each(function(){
if(!$(this).hasClass("nonquestion")){
if(i>0)
allSend+=",\n";
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
//BTW we will escape the val of each answer so that students can't mess server parsing up
allSend+=("{q"+i+": "+val+"}");
i++;
}
});
alert(allSend);
}
/*Will send all quizes if need be
$("#sendAll").on("click",function(){
var i = 0;
$(".quiz").find(".question").each(function(){
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
alert("q"+i+": "+val);
i++;
});
});
*/
| Update methods to send object params | Update methods to send object params | JavaScript | mit | stephenjoro/QuizEngine | ---
+++
@@ -1,36 +1,56 @@
-//must have a blank option one for question of type dropdown
+var config = {
+ '.chosen-select' : {},
+};
+for (var selector in config) {
+ $(selector).chosen(config[selector]);
+}
-standard('qTypes',["","Drop Down", "Multidrop-down", "Number Fillin", "Essay", "Code"]);
+for(var k = 0; k < showHideList.length; k++){
+ // alert(showHide);
+ var showHide=showHideList[k];
+ for(var i = 0; i < showHide.length; i++){
+ // alert(showHide[i]);
+ if(showHide[i].length>0)
+ $("."+showHide[i]).hide();
+ }
+}
-standard('qTypes2',["","dropdowns", "multidropdowns", "numfillins", "essays", "codes"]);
-standard('correct',["Correct","Incorrect"]);
-standard('incorrect',["Incorrect","Correct"]);
+function SUBMIT_ONE_QUIZ(quiz){
+ var i = 0;
+ var allSend = "";
+ $(quiz).find(".question").each(function(){
+ if(!$(this).hasClass("nonquestion")){
+ if(i>0)
+ allSend+=",\n";
+ var val = $(this).val();
+ if(val==null){
+ val = "No Answer";
+ }
+ if(val.length < 1){
+ val = "No Answer";
+ }
+ //BTW we will escape the val of each answer so that students can't mess server parsing up
+ allSend+=("{q"+i+": "+val+"}");
+ i++;
+ }
+ });
+ alert(allSend);
+}
+/*Will send all quizes if need be
+$("#sendAll").on("click",function(){
+var i = 0;
+$(".quiz").find(".question").each(function(){
+var val = $(this).val();
+if(val==null){
+val = "No Answer";
+}
+if(val.length < 1){
+val = "No Answer";
+}
+alert("q"+i+": "+val);
+i++;
+});
-quiz([
-
- question("dropdown","Type of Question:",choices['qTypes'],'Choose a type...',choices['qTypes2']),
- question("essay","Question Text:",3,30,'Your text here...'),
- questionSet("dropdowns multidropdowns",[
- question("essay","Placeholder Text:",3,30,'Your text here...'),
- question("multiquestion","",[
- question("essay","Answer Choice 1:",3,30,'Your text here...'),
- question("dropdown","",choices['correct'])
- ]),
- question("multiquestion","",[
- question("essay","Answer Choice 2:",3,30,'Your text here...'),
- question("dropdown","",choices['incorrect'])
- ]),
- question("multiquestion","",[
- question("essay","Answer Choice 3:",3,30,'Your text here...'),
- question("dropdown","",choices['incorrect'])
- ])
- ]),
- questionSet("codes",[
- question("essay","Base Code:",3,30,'Your base code here...')
- ]),
- questionSet("numfillins essays",[
- question("essay","Placeholder Text:",3,30,'Your placeholder text here...')
- ])
-]);
-
+});
+*/ |
618bef5d2607cf6bc854c94fcea5095f31844d71 | preset/index.js | preset/index.js | /* eslint-env commonjs */
/* eslint-disable global-require */
module.exports = function buildPreset () {
return {
presets: [
require('babel-preset-env').default(null, {
targets: {
browsers: ['last 2 versions', 'ie 11'],
node: '6.8',
},
}),
require('babel-preset-react'),
],
plugins: [
require('babel-plugin-transform-object-rest-spread'),
require('babel-plugin-transform-class-properties'),
require('babel-plugin-transform-export-extensions'),
],
};
};
| /* eslint-env commonjs */
/* eslint-disable global-require */
module.exports = function buildPreset () {
return {
presets: [
require('babel-preset-env').default(null, {
targets: {
browsers: ['last 2 versions', 'ie 11'],
node: '8.9.4',
},
}),
require('babel-preset-react'),
],
plugins: [
require('babel-plugin-transform-object-rest-spread'),
require('babel-plugin-transform-class-properties'),
require('babel-plugin-transform-export-extensions'),
],
};
};
| Update node version in babel preset | Update node version in babel preset
| JavaScript | bsd-3-clause | salesforce/design-system-react,salesforce/design-system-react,salesforce/design-system-react | ---
+++
@@ -7,7 +7,7 @@
require('babel-preset-env').default(null, {
targets: {
browsers: ['last 2 versions', 'ie 11'],
- node: '6.8',
+ node: '8.9.4',
},
}),
require('babel-preset-react'), |
b56a1cc01d007d1221c3ec5ac66cbd2fc50fc601 | public/index.js | public/index.js | import restate from 'regular-state';
import { Component } from 'nek-ui';
import App from './modules/app';
import Home from './modules/home';
import Detail from './modules/detail';
import Setting from './modules/setting';
const stateman = restate({ Component });
stateman
.state('app', App, '')
.state('app.home', Home, '')
.state('app.detail', Detail, 'detail')
.state('app.setting', Setting, 'setting')
.on('notfound', () => {
this.go('app.home', { replace: true });
})
.start({ html5: false, root: '/', prefix: '!' });
| import restate from 'regular-state';
import { Component } from 'nek-ui';
import App from './modules/app';
import Home from './modules/home';
import Detail from './modules/detail';
import Setting from './modules/setting';
const stateman = restate({ Component });
stateman
.state('app', App, '')
.state('app.home', Home, '')
.state('app.detail', Detail, 'detail')
.state('app.setting', Setting, 'setting')
.on('notfound', () => {
stateman.go('app.home', { replace: true });
})
.start({ html5: false, root: '/', prefix: '!' });
| Fix <this> is not valid | Fix <this> is not valid
| JavaScript | mit | kaola-fed/nek-server,kaola-fed/nek-server | ---
+++
@@ -13,6 +13,6 @@
.state('app.detail', Detail, 'detail')
.state('app.setting', Setting, 'setting')
.on('notfound', () => {
- this.go('app.home', { replace: true });
+ stateman.go('app.home', { replace: true });
})
.start({ html5: false, root: '/', prefix: '!' }); |
fa48474a1860ab76a38cb0de737e48262dcd1bef | api/routes/auth.js | api/routes/auth.js | const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
const arns = req.user['https://aws.amazon.com/SAML/Attributes/Role'].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
| const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
roles = req.user['https://aws.amazon.com/SAML/Attributes/Role']
if (!Array.isArray(roles)) {
roles = [roles]
}
const arns = roles[0].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
| Add support for multiple role assertions | Add support for multiple role assertions
The `https://aws.amazon.com/SAML/Attributes/Role` attribute supports
single or multiple values. This fixes Awsaml to work when a
multiple-value attribute is passed.
Currently, the first role is always used. Support for selecting from
the roles may be added later.
GH-105
| JavaScript | mit | rapid7/awsaml,rapid7/awsaml,rapid7/awsaml | ---
+++
@@ -8,7 +8,13 @@
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
- const arns = req.user['https://aws.amazon.com/SAML/Attributes/Role'].split(',');
+
+ roles = req.user['https://aws.amazon.com/SAML/Attributes/Role']
+ if (!Array.isArray(roles)) {
+ roles = [roles]
+ }
+
+ const arns = roles[0].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse; |
37822557c035ca41a6e9243f77d03a69351fc65c | examples/simple.js | examples/simple.js | var jerk = require( '../lib/jerk' ), sys=require('sys');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
sys.puts("User: " + message.user + " has left");
});
}).connect( options );
| var jerk = require( '../lib/jerk' ), util = require('util');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
util.puts("User: " + message.user + " has left");
});
}).connect( options );
| Use util instead of sys in example. | Use util instead of sys in example.
Make sure the example Jerk script continues to work in future node.js
releases. The node.js `sys` library has been a pointer to `util` since
0.3 and has now been removed completely in the node.js development
branch.
| JavaScript | unlicense | gf3/Jerk | ---
+++
@@ -1,4 +1,4 @@
-var jerk = require( '../lib/jerk' ), sys=require('sys');
+var jerk = require( '../lib/jerk' ), util = require('util');
var options =
{ server: 'localhost'
, port: 6667
@@ -20,7 +20,7 @@
});
j.user_leave(function(message) {
- sys.puts("User: " + message.user + " has left");
+ util.puts("User: " + message.user + " has left");
});
}).connect( options );
|
20fbda8f219d58a64380841ddd972e59b0eb416e | app/scripts/app.js | app/scripts/app.js | 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'fr', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
| 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'en', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
| Change default language : en | Change default language : en
| JavaScript | mit | foxdog05000/serina,foxdog05000/serina | ---
+++
@@ -41,7 +41,7 @@
window.i18next.init({
debug: true,
- lng: 'fr', // If not given, i18n will detect the browser language.
+ lng: 'en', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json' |
c671f90b3877273d18ba22351e1e8b9a63a925c3 | shp/concat.js | shp/concat.js | export default function(a, b) {
var ab = new a.constructor(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
| export default function(a, b) {
var ab = new Uint8Array(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
| Fix for older versions of Node. | Fix for older versions of Node.
Older versions of Node had a conflicting implementation of buffer.set.
| JavaScript | bsd-3-clause | mbostock/shapefile | ---
+++
@@ -1,5 +1,5 @@
export default function(a, b) {
- var ab = new a.constructor(a.length + b.length);
+ var ab = new Uint8Array(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab; |
1dfde5055467da45665db268a68e72866aef60e2 | lib/networking/ws/BaseSocket.js | lib/networking/ws/BaseSocket.js | "use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
heartbeat.delete(this);
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
}
module.exports = BaseSocket;
| "use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
this.unsetHeartbeat();
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
unsetHeartbeat() {
var handle = heartbeat.get(this);
if (handle !== undefined) clearInterval(handle);
heartbeat.delete(this);
}
close() {
super.close();
this.unsetHeartbeat();
// release websocket resources without waiting for close frame from Discord
if (this._closeTimer && this._closeTimer._onTimeout)
this._closeTimer._onTimeout();
clearTimeout(this._closeTimer);
}
}
module.exports = BaseSocket;
| Fix heartbeat sender timer handle cleanup | Fix heartbeat sender timer handle cleanup
| JavaScript | bsd-2-clause | qeled/discordie | ---
+++
@@ -12,7 +12,7 @@
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
- heartbeat.delete(this);
+ this.unsetHeartbeat();
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
@@ -41,6 +41,20 @@
this.send(opcode, new Date().getTime());
}, msec));
}
+ unsetHeartbeat() {
+ var handle = heartbeat.get(this);
+ if (handle !== undefined) clearInterval(handle);
+ heartbeat.delete(this);
+ }
+ close() {
+ super.close();
+ this.unsetHeartbeat();
+
+ // release websocket resources without waiting for close frame from Discord
+ if (this._closeTimer && this._closeTimer._onTimeout)
+ this._closeTimer._onTimeout();
+ clearTimeout(this._closeTimer);
+ }
}
module.exports = BaseSocket; |
e1c49c2c2c1e8e8661a079b6e7acd598bd6123d3 | pliers-npm-security-check.js | pliers-npm-security-check.js | var fs = require('fs')
, request = require('request')
module.exports = function (pliers) {
pliers('npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
| var fs = require('fs')
, request = require('request')
module.exports = function (pliers, name) {
pliers(name || 'npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
| Add task name override functionality | Add task name override functionality
| JavaScript | bsd-3-clause | pliersjs/pliers-npm-security-check | ---
+++
@@ -1,9 +1,9 @@
var fs = require('fs')
, request = require('request')
-module.exports = function (pliers) {
+module.exports = function (pliers, name) {
- pliers('npmSecurityCheck', function (done) {
+ pliers(name || 'npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service')) |
8031a913ef64945e15d6cd4e06c91dfbfa16e27c | routes/trips.js | routes/trips.js | var express = require('express');
var router = express.Router();
var trip = require('../lib/trip')
router.post('/', function(req, res, next) {
var trip_path = trip.generate_trip(req.body.startPoint, req.body.endPoint);
res.send(trip_path);
});
| var express = require('express');
var router = express.Router();
var trip = require('../lib/trip')
router.post('/', function(req, res, next) {
var trip_path = trip.generate_trip(req.body.startPoint, req.body.endPoint);
res.send(trip_path);
});
module.exports = router;
| Fix trip router (forget to export module) | Fix trip router (forget to export module)
| JavaScript | mit | Ecotaco/bumblebee-bot,Ecotaco/bumblebee-bot | ---
+++
@@ -6,3 +6,5 @@
var trip_path = trip.generate_trip(req.body.startPoint, req.body.endPoint);
res.send(trip_path);
});
+
+module.exports = router; |
42a81f023f954e4eb01f5c0b32e3575dc22d7654 | routes/users.js | routes/users.js | var
express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
res.json(["users"]);
return next();
});
module.exports = router;
| var
express = require('express'),
router = express.Router();
// GET /users
router.get('/', function (req, res, next) {
res.json(["users"]);
return next();
});
// GET /users/:id
router.get('/:id', function (req, res, next) {
res.json({id: req.params.id, name: "John Doe"});
return next();
})
module.exports = router;
| Add simple sample for user router | Add simple sample for user router
| JavaScript | mit | givery-technology/bloom-backend | ---
+++
@@ -2,9 +2,16 @@
express = require('express'),
router = express.Router();
+// GET /users
router.get('/', function (req, res, next) {
res.json(["users"]);
return next();
});
+// GET /users/:id
+router.get('/:id', function (req, res, next) {
+ res.json({id: req.params.id, name: "John Doe"});
+ return next();
+})
+
module.exports = router; |
7e5e14847e2232fd89e2dcd18cce2c16b05e88fc | app/navbar/navbar.js | app/navbar/navbar.js | angular.module('h54sNavbar', ['sasAdapter', 'h54sDebugWindow'])
.controller('NavbarCtrl', ['$scope', 'sasAdapter', '$rootScope', '$sce', function($scope, sasAdapter, $rootScope, $sce) {
$scope.openDebugWindow = function() {
$rootScope.showDebugWindow = true;
};
$scope.toggleDebugging = function() {
sasAdapter.toggleDebugMode();
};
$scope.debug = sasAdapter.isDebugMode();
sasAdapter.onRemoteConfigUpdate(function() {
$scope.debug = sasAdapter.isDebugMode();
});
}]);
| angular.module('h54sNavbar', ['sasAdapter', 'h54sDebugWindow'])
.controller('NavbarCtrl', ['$scope', 'sasAdapter', '$rootScope', '$sce', function($scope, sasAdapter, $rootScope, $sce) {
$scope.openDebugWindow = function() {
$rootScope.showDebugWindow = true;
};
$scope.toggleDebugging = function() {
sasAdapter.toggleDebugMode();
};
$scope.debug = sasAdapter.isDebugMode();
sasAdapter.onRemoteConfigUpdate(function() {
$scope.$apply(function() {
$scope.debug = sasAdapter.isDebugMode();
});
});
}]);
| Debug mode not set sometimes issue fixed | Debug mode not set sometimes issue fixed
| JavaScript | mit | Boemska/sas-hot-editor,Boemska/sas-hot-editor | ---
+++
@@ -12,7 +12,9 @@
$scope.debug = sasAdapter.isDebugMode();
sasAdapter.onRemoteConfigUpdate(function() {
- $scope.debug = sasAdapter.isDebugMode();
+ $scope.$apply(function() {
+ $scope.debug = sasAdapter.isDebugMode();
+ });
});
}]); |
bcad6341b9d6bf85712de73bbe8e19990d174633 | sampleConfig.js | sampleConfig.js | var global = {
host: 'http://subdomain.yourdomain.com',
port: 8461,
secretUrlSuffix: 'putSomeAlphanumericSecretCharsHere'
};
var projects = [
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-source-repo-name',
sshPrivKeyPath: '/home/youruser/.ssh/id_rsa'
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
}
];
module.exports = {
global: global,
projects: projects
};
| var global = {
host: 'http://subdomain.yourdomain.com',
port: 8461,
secretUrlSuffix: 'putSomeAlphanumericSecretCharsHere'
};
var projects = [
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-private-repo-name',
url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-private-repo-name.git',
sshPrivKeyPath: '/home/youruser/.ssh/id_rsa'
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
},
{
repo: {
owner: 'yourbitbucketusername',
slug: 'your-bitbucket-public-repo-name',
url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-public-repo-name.git',
},
dest: {
host: 'yourstaticwebhost.com',
username: 'yourusername',
password: 'yourpassword',
path: '/home/youruser/html_dest/'
}
}
];
module.exports = {
global: global,
projects: projects
};
| Add a public repo example | Add a public repo example
| JavaScript | mit | mplewis/statichook | ---
+++
@@ -8,8 +8,22 @@
{
repo: {
owner: 'yourbitbucketusername',
- slug: 'your-bitbucket-source-repo-name',
+ slug: 'your-bitbucket-private-repo-name',
+ url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-private-repo-name.git',
sshPrivKeyPath: '/home/youruser/.ssh/id_rsa'
+ },
+ dest: {
+ host: 'yourstaticwebhost.com',
+ username: 'yourusername',
+ password: 'yourpassword',
+ path: '/home/youruser/html_dest/'
+ }
+ },
+ {
+ repo: {
+ owner: 'yourbitbucketusername',
+ slug: 'your-bitbucket-public-repo-name',
+ url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-public-repo-name.git',
},
dest: {
host: 'yourstaticwebhost.com', |
c8d5aeca835d8ddd53c8026620561f6568d29041 | BrowserExtension/scripts/steamdb.js | BrowserExtension/scripts/steamdb.js | 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
| 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/(app|sub)\/([0-9]{1,7})/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
| Improve regex for getting appid | Improve regex for getting appid
| JavaScript | bsd-3-clause | GoeGaming/SteamDatabase,i3ongmeester/SteamDatabase,GoeGaming/SteamDatabase,SteamDatabase/SteamDatabase,SteamDatabase/SteamDatabase,i3ongmeester/SteamDatabase,i3ongmeester/SteamDatabase,GoeGaming/SteamDatabase,SteamDatabase/SteamDatabase | ---
+++
@@ -5,7 +5,7 @@
{
if( !CurrentAppID )
{
- CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ );
+ CurrentAppID = location.pathname.match( /\/(app|sub)\/([0-9]{1,7})/ );
if( CurrentAppID )
{ |
a72cc8137b0159b1d0246eb0e5aecf338cbd19f0 | input/_relation.js | input/_relation.js | 'use strict';
var Db = require('dbjs')
, relation = module.exports = require('dbjs/lib/_relation');
require('./base');
relation.set('toDOMInputBox', function (document/*, options*/) {
var box, options = arguments[1];
box = this.ns.toDOMInputBox(document, options);
box.set(this.objectValue);
box.setAttribute('name', this._id_);
if (this.required && (!options || (options.type !== 'checkbox'))) {
box.setAttribute('required', true);
}
this.on('change', function () { box.set(this.objectValue); });
return box;
});
relation.set('toDOMInput', Db.Base.prototype.toDOMInput);
relation.get('fieldHint').ns = Db.String;
relation.set('DOMId', function () {
return this._id_.replace(/:/g, '-');
});
| 'use strict';
var Db = require('dbjs')
, relation = module.exports = require('dbjs/lib/_relation');
require('./base');
relation.set('toDOMInputBox', function (document/*, options*/) {
var box, options = Object(arguments[1]);
box = this.ns.toDOMInputBox(document, options);
box.set(this.objectValue);
box.setAttribute('name', this._id_);
if (this.required && ((options.type !== 'checkbox') && !options.required)) {
box.setAttribute('required', true);
}
this.on('change', function () { box.set(this.objectValue); });
return box;
});
relation.set('toDOMInput', Db.Base.prototype.toDOMInput);
relation.get('fieldHint').ns = Db.String;
relation.set('DOMId', function () {
return this._id_.replace(/:/g, '-');
});
| Allow to override 'required' value | Allow to override 'required' value
| JavaScript | mit | medikoo/dbjs-dom | ---
+++
@@ -6,11 +6,11 @@
require('./base');
relation.set('toDOMInputBox', function (document/*, options*/) {
- var box, options = arguments[1];
+ var box, options = Object(arguments[1]);
box = this.ns.toDOMInputBox(document, options);
box.set(this.objectValue);
box.setAttribute('name', this._id_);
- if (this.required && (!options || (options.type !== 'checkbox'))) {
+ if (this.required && ((options.type !== 'checkbox') && !options.required)) {
box.setAttribute('required', true);
}
this.on('change', function () { box.set(this.objectValue); }); |
3a0a5f2f9e2b2ba62da6013ba238c3783039c71c | src/client/actions/StatusActions.js | src/client/actions/StatusActions.js | import Axios from 'axios';
import {
PROVIDER_CHANGE,
FILTER_BOARD, FILTER_THREAD,
SERACH_BOARD, SEARCH_THREAD,
STATUS_UPDATE
} from '../constants';
// TODO: Filter + Search actions
export function changeProvider( provider ) {
return (dispatch, getState) => {
if (shouldChangeProvider(getState(), provider)) {
console.info("Action changeProvider() to " + provider);
dispatch({
type: PROVIDER_CHANGE,
payload: provider
})
}
}
}
function shouldChangeProvider( {status}, provider) {
return status.provider !== provider
}
export function alertMessage( message ) {
console.info(`Action alertMessage(): ${message}`);
console.warn(message);
return {
type: STATUS_UPDATE,
payload: message
}
}
export function clearStatus() {
console.info(`Action clearStatus()`);
return {
type: STATUS_UPDATE,
payload: ""
}
}
| import Axios from 'axios';
import {
PROVIDER_CHANGE,
FILTER_BOARD, FILTER_THREAD,
SERACH_BOARD, SEARCH_THREAD,
ALERT_MESSAGE
} from '../constants';
// TODO: Filter + Search actions
export function changeProvider( provider ) {
return (dispatch, getState) => {
if (shouldChangeProvider(getState(), provider)) {
console.info("Action changeProvider() to " + provider);
dispatch({
type: PROVIDER_CHANGE,
payload: provider
})
}
}
}
function shouldChangeProvider( {status}, provider) {
return status.provider !== provider
}
export function alertMessage( message ) {
console.info(`Action alertMessage(): ${message.message}`);
return {
type: ALERT_MESSAGE,
payload: message
}
}
| Remove clearStatus action; not in use | Remove clearStatus action; not in use
| JavaScript | mit | AdamSalma/Lurka,AdamSalma/Lurka | ---
+++
@@ -3,7 +3,7 @@
PROVIDER_CHANGE,
FILTER_BOARD, FILTER_THREAD,
SERACH_BOARD, SEARCH_THREAD,
- STATUS_UPDATE
+ ALERT_MESSAGE
} from '../constants';
// TODO: Filter + Search actions
@@ -24,19 +24,10 @@
}
export function alertMessage( message ) {
- console.info(`Action alertMessage(): ${message}`);
- console.warn(message);
+ console.info(`Action alertMessage(): ${message.message}`);
return {
- type: STATUS_UPDATE,
+ type: ALERT_MESSAGE,
payload: message
}
}
-
-export function clearStatus() {
- console.info(`Action clearStatus()`);
- return {
- type: STATUS_UPDATE,
- payload: ""
- }
-} |
5b6f3ac716e37b9d03bff3da826dca24826b24eb | jasmine/spec/inverted-index-test.js | jasmine/spec/inverted-index-test.js | describe ("Read book data",function(){
it("assert JSON file is not empty",function(){
var isNotEmpty = function IsJsonString(filePath) {
try {
JSON.parse(filePath);
} catch (e) {
return false;
}
return true;
};
expect(isNotEmpty).toBe(true).because('The JSON file should be a valid JSON array');
});
});
describe ("Populate Index",function(){
beforeEach(function() {
var myIndexPopulate=JSON.parse(filePath);
var myIndexGet=getIndex(myIndexPopulate);
});
it("index should be created after reading",function(){
expect(myIndexGet).not.toBe(null).because('Index should be created after reading the file');
});
it("index maps string keys to correct obj", function(){
var myFunction= function() {
var testArray=['a','1'];
var a=createIndex(testArray);
var b=getIndex(a);
return b;
}
expect(myFunction).toBe(['a']).because('Index should return corresponding key');
});
});
describe ("Search Index", function(){
beforeEach(function(){
var testArray=["a","b","c"];
var mySearchIndex= searchIndex(testArray);
});
it("searching should returns array of correct indices", function(){
expect(mySearchIndex).toContain("a","b","c");
});
})
| describe("Read book data", function() {
beforeEach(function(){
var file = filePath.files[0];
var reader = new FileReader();
});
it("assert JSON file is not empty",function(){
var fileNotEmpty = JSON.parse(reader.result);
var fileNotEmptyResult = function(fileNotEmpty){
if (fileNotEmpty = null){
return false;
}
else{
return true;
}
};
expect(fileNotEmptyResult).toBe(true);
});
});
describe("Populate Index", function(){
beforeEach(function() {
checkEmpty = new createIndex();
//test using spies to check if methods are exectued
spyOn(checkEmpty, 'push');
});
it('should have called and created this function', function(){
//calling the function to see if the code has been executed
checkempty.push(term);
expect(checkEmpty.push).toHaveBeenCalled();
//because if this method is called the index has been created.
});
it("should map string keys to correct objects", function(){
//calling function to see if it is executed in code
expect(display.innerText).toBe('Index Created');
});
});
| Change the read book test and populate index test | Change the read book test and populate index test
| JavaScript | mit | andela-pbirir/inverted-index,andela-pbirir/inverted-index | ---
+++
@@ -1,53 +1,46 @@
-describe ("Read book data",function(){
+describe("Read book data", function() {
+ beforeEach(function(){
+ var file = filePath.files[0];
+ var reader = new FileReader();
+ });
+ it("assert JSON file is not empty",function(){
- it("assert JSON file is not empty",function(){
- var isNotEmpty = function IsJsonString(filePath) {
- try {
- JSON.parse(filePath);
- } catch (e) {
- return false;
- }
- return true;
- };
- expect(isNotEmpty).toBe(true).because('The JSON file should be a valid JSON array');
+ var fileNotEmpty = JSON.parse(reader.result);
+ var fileNotEmptyResult = function(fileNotEmpty){
+ if (fileNotEmpty = null){
+ return false;
+ }
+ else{
+ return true;
+ }
+ };
+
+ expect(fileNotEmptyResult).toBe(true);
+ });
+
+
+});
+
+describe("Populate Index", function(){
+ beforeEach(function() {
+
+ checkEmpty = new createIndex();
+ //test using spies to check if methods are exectued
+ spyOn(checkEmpty, 'push');
+ });
+ it('should have called and created this function', function(){
+
+ //calling the function to see if the code has been executed
+ checkempty.push(term);
+
+ expect(checkEmpty.push).toHaveBeenCalled();
+ //because if this method is called the index has been created.
+ });
+ it("should map string keys to correct objects", function(){
+ //calling function to see if it is executed in code
+
+ expect(display.innerText).toBe('Index Created');
});
});
-describe ("Populate Index",function(){
- beforeEach(function() {
- var myIndexPopulate=JSON.parse(filePath);
- var myIndexGet=getIndex(myIndexPopulate);
-
-
- });
- it("index should be created after reading",function(){
-
-
- expect(myIndexGet).not.toBe(null).because('Index should be created after reading the file');
-
- });
- it("index maps string keys to correct obj", function(){
-
- var myFunction= function() {
- var testArray=['a','1'];
- var a=createIndex(testArray);
- var b=getIndex(a);
- return b;
- }
- expect(myFunction).toBe(['a']).because('Index should return corresponding key');
-
- });
-});
-describe ("Search Index", function(){
- beforeEach(function(){
- var testArray=["a","b","c"];
- var mySearchIndex= searchIndex(testArray);
-
- });
- it("searching should returns array of correct indices", function(){
-
- expect(mySearchIndex).toContain("a","b","c");
- });
-
-}) |
221f6da58e1190b97ab3c6310d3e9b699e512ea0 | ProgressBar.js | ProgressBar.js | var React = require('react-native');
var {
Animated,
Easing,
StyleSheet,
View
} = React;
var styles = StyleSheet.create({
background: {
backgroundColor: '#bbbbbb',
height: 5,
overflow: 'hidden'
},
fill: {
backgroundColor: '#3b5998',
height: 5
}
});
var ProgressBar = React.createClass({
getDefaultProps() {
return {
style: styles,
easing: Easing.inOut(Easing.ease),
easingDuration: 500
};
},
getInitialState() {
return {
progress: new Animated.Value(0)
};
},
componentDidUpdate(prevProps, prevState) {
if (this.props.progress >= 0 && this.props.progress != prevProps.progress) {
this.update();
}
},
render() {
var fillWidth = this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [0 * this.props.style.width, 1 * this.props.style.width],
});
return (
<View style={[styles.background, this.props.backgroundStyle, this.props.style]}>
<Animated.View style={[styles.fill, this.props.fillStyle, { width: fillWidth }]}/>
</View>
);
},
update() {
Animated.timing(this.state.progress, {
easing: this.props.easing,
duration: this.props.easingDuration,
toValue: this.props.progress
}).start();
}
});
module.exports = ProgressBar;
| var React = require('react-native');
var {
Animated,
Easing,
StyleSheet,
View
} = React;
var styles = StyleSheet.create({
background: {
backgroundColor: '#bbbbbb',
height: 5,
overflow: 'hidden'
},
fill: {
backgroundColor: '#3b5998',
height: 5
}
});
var ProgressBar = React.createClass({
getDefaultProps() {
return {
style: styles,
easing: Easing.inOut(Easing.ease),
easingDuration: 500
};
},
getInitialState() {
return {
progress: new Animated.Value(this.props.initialProgress || 0)
};
},
componentDidUpdate(prevProps, prevState) {
if (this.props.progress >= 0 && this.props.progress != prevProps.progress) {
this.update();
}
},
render() {
var fillWidth = this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [0 * this.props.style.width, 1 * this.props.style.width],
});
return (
<View style={[styles.background, this.props.backgroundStyle, this.props.style]}>
<Animated.View style={[styles.fill, this.props.fillStyle, { width: fillWidth }]}/>
</View>
);
},
update() {
Animated.timing(this.state.progress, {
easing: this.props.easing,
duration: this.props.easingDuration,
toValue: this.props.progress
}).start();
}
});
module.exports = ProgressBar;
| Add initialProgress property to make start from the given value | Add initialProgress property to make start from the given value
| JavaScript | mit | lwansbrough/react-native-progress-bar | ---
+++
@@ -31,7 +31,7 @@
getInitialState() {
return {
- progress: new Animated.Value(0)
+ progress: new Animated.Value(this.props.initialProgress || 0)
};
},
|
fab2943412258c0a55c7d127cc67798f30587551 | test/bootstrap.js | test/bootstrap.js | /**
* require dependencies
*/
WebdriverIO = require('webdriverio');
WebdriverCSS = require('../index.js');
fs = require('fs-extra');
gm = require('gm');
glob = require('glob');
async = require('async');
should = require('chai').should();
expect = require('chai').expect;
capabilities = {logLevel: 'silent',desiredCapabilities:{browserName: 'phantomjs'}};
testurl = 'http://localhost:8080/test/site/index.html';
testurlTwo = 'http://localhost:8080/test/site/two.html';
testurlThree = 'http://localhost:8080/test/site/three.html';
testurlFour = 'http://localhost:8080/test/site/four.html';
/**
* set some fix test variables
*/
screenshotRootDefault = 'webdrivercss';
failedComparisonsRootDefault = 'webdrivercss/diff';
screenshotRootCustom = '__screenshotRoot__';
failedComparisonsRootCustom = '__failedComparisonsRoot__';
afterHook = function(done) {
var browser = this.browser;
/**
* close browser and clean up created directories
*/
async.parallel([
function(done) { browser.end(done); },
function(done) { fs.remove(failedComparisonsRootDefault,done); },
function(done) { fs.remove(screenshotRootDefault,done); },
function(done) { fs.remove(failedComparisonsRootCustom,done); },
function(done) { fs.remove(screenshotRootCustom,done); }
], done);
};
| /**
* require dependencies
*/
WebdriverIO = require('webdriverio');
WebdriverCSS = require('../index.js');
fs = require('fs-extra');
gm = require('gm');
glob = require('glob');
async = require('async');
should = require('chai').should();
expect = require('chai').expect;
capabilities = {logLevel: 'silent',desiredCapabilities:{browserName: 'phantomjs'}};
testurl = 'http://localhost:8080/test/site/index.html';
testurlTwo = 'http://localhost:8080/test/site/two.html';
testurlThree = 'http://localhost:8080/test/site/three.html';
testurlFour = 'http://localhost:8080/test/site/four.html';
/**
* set some fix test variables
*/
screenshotRootDefault = 'webdrivercss';
failedComparisonsRootDefault = 'webdrivercss/diff';
screenshotRootCustom = '__screenshotRoot__';
failedComparisonsRootCustom = '__failedComparisonsRoot__';
afterHook = function(done) {
var browser = this.browser;
/**
* close browser and clean up created directories
*/
async.parallel([
function(done) { browser.end(done); },
// function(done) { fs.remove(failedComparisonsRootDefault,done); },
// function(done) { fs.remove(screenshotRootDefault,done); },
// function(done) { fs.remove(failedComparisonsRootCustom,done); },
// function(done) { fs.remove(screenshotRootCustom,done); }
], done);
};
| Disable test cleanup for debugging | Disable test cleanup for debugging
| JavaScript | mit | JustinTulloss/webdrivercss,JustinTulloss/webdrivercss | ---
+++
@@ -32,10 +32,10 @@
*/
async.parallel([
function(done) { browser.end(done); },
- function(done) { fs.remove(failedComparisonsRootDefault,done); },
- function(done) { fs.remove(screenshotRootDefault,done); },
- function(done) { fs.remove(failedComparisonsRootCustom,done); },
- function(done) { fs.remove(screenshotRootCustom,done); }
+ // function(done) { fs.remove(failedComparisonsRootDefault,done); },
+ // function(done) { fs.remove(screenshotRootDefault,done); },
+ // function(done) { fs.remove(failedComparisonsRootCustom,done); },
+ // function(done) { fs.remove(screenshotRootCustom,done); }
], done);
}; |
86d8c0168182a23b75bdd62135231b9292b881af | test/plugin.spec.js | test/plugin.spec.js | import BabelRootImportPlugin from '../plugin';
import * as babel from 'babel-core';
describe('Babel Root Import - Plugin', () => {
describe('Babel Plugin', () => {
it('transforms the relative path into an absolute path', () => {
const targetRequire = `${process.cwd()}/some/example.js`;
const transformedCode = babel.transform("import SomeExample from '~/some/example.js';", {
plugins: [BabelRootImportPlugin]
});
expect(transformedCode.code).to.contain(targetRequire);
});
});
});
| import BabelRootImportPlugin from '../plugin';
import * as babel from 'babel-core';
describe('Babel Root Import - Plugin', () => {
describe('Babel Plugin', () => {
it('transforms the relative path into an absolute path', () => {
const targetRequire = `${process.cwd()}/some/example.js`;
const transformedCode = babel.transform("import SomeExample from '~/some/example.js';", {
plugins: [BabelRootImportPlugin]
});
expect(transformedCode.code).to.contain(targetRequire);
});
it('transforms the relative path into an absolute path with the configured root-path', () => {
const targetRequire = `some/custom/root/some/example.js`;
const transformedCode = babel.transform("import SomeExample from '~/some/example.js';", {
plugins: [[
BabelRootImportPlugin, {
rootPathSuffix: 'some/custom/root'
}
]]
});
expect(transformedCode.code).to.contain(targetRequire);
});
});
});
| Add test for custom root (setted by babelrc) | Add test for custom root (setted by babelrc)
| JavaScript | mit | michaelzoidl/babel-root-import,Quadric/babel-plugin-inline-import | ---
+++
@@ -11,5 +11,18 @@
expect(transformedCode.code).to.contain(targetRequire);
});
+
+ it('transforms the relative path into an absolute path with the configured root-path', () => {
+ const targetRequire = `some/custom/root/some/example.js`;
+ const transformedCode = babel.transform("import SomeExample from '~/some/example.js';", {
+ plugins: [[
+ BabelRootImportPlugin, {
+ rootPathSuffix: 'some/custom/root'
+ }
+ ]]
+ });
+
+ expect(transformedCode.code).to.contain(targetRequire);
+ });
});
}); |
fdd9ce07ece40caee51c093254ec232348ef2908 | api/models/User.js | api/models/User.js | /**
* User
*
* @module :: Model
* @description :: A short summary of how this model works and what it represents.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
email: 'STRING',
name: 'STRING'
/* e.g.
nickname: 'string'
*/
}
};
| /**
* User
*
* @module :: Model
* @description :: A short summary of how this model works and what it represents.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
email: {
type: 'email',
required: true
}
name: 'STRING'
/* e.g.
nickname: 'string'
*/
}
};
| Add some validation to my model | Add some validation to my model
| JavaScript | mit | thomaslangston/sailsnode | ---
+++
@@ -9,7 +9,10 @@
module.exports = {
attributes: {
- email: 'STRING',
+ email: {
+ type: 'email',
+ required: true
+ }
name: 'STRING'
/* e.g.
nickname: 'string' |
1a4c8c303dcfa0e9a49ff554ba540da638a8a6ab | app/controllers/index.js | app/controllers/index.js | /**
* Global Navigation Handler
*/
Alloy.Globals.Navigator = {
/**
* Handle to the Navigation Controller
*/
navGroup: $.nav,
open: function(controller, payload){
var win = Alloy.createController(controller, payload || {}).getView();
if(OS_IOS){
$.nav.openWindow(win);
}
else if(OS_MOBILEWEB){
$.nav.open(win);
}
else {
// added this property to the payload to know if the window is a child
if (payload.displayHomeAsUp){
win.addEventListener('open',function(evt){
var activity=win.activity;
activity.actionBar.displayHomeAsUp=payload.displayHomeAsUp;
activity.actionBar.onHomeIconItemSelected=function(){
evt.source.close();
};
});
}
win.open();
}
}
};
/**
* Lets add a loading animation - Just for Fun!
*/
var loadingView = Alloy.createController("form");
loadingView.getView().open(); | /**
* Global Navigation Handler
*/
Alloy.Globals.Navigator = {
/**
* Handle to the Navigation Controller
*/
navGroup: $.nav,
open: function(controller, payload){
var win = Alloy.createController(controller, payload || {}).getView();
if(OS_IOS){
$.nav.openWindow(win);
}
else if(OS_MOBILEWEB){
$.nav.open(win);
}
else {
// added this property to the payload to know if the window is a child
if (payload.displayHomeAsUp){
win.addEventListener('open',function(evt){
var activity=win.activity;
activity.actionBar.displayHomeAsUp=payload.displayHomeAsUp;
activity.actionBar.onHomeIconItemSelected=function(){
evt.source.close();
};
});
}
win.open();
}
}
};
if(OS_IOS){
$.nav.open()
}
else if(OS_MOBILEWEB){
$.index.open();
}
else{
$.index.getView().open();
} | Fix para iphone al abrir controlador | Fix para iphone al abrir controlador
Al abrir el controlador de forms no se veia el window title
| JavaScript | apache-2.0 | egregori/HADA,egregori/HADA | ---
+++
@@ -36,8 +36,12 @@
};
-/**
- * Lets add a loading animation - Just for Fun!
- */
-var loadingView = Alloy.createController("form");
-loadingView.getView().open();
+if(OS_IOS){
+ $.nav.open()
+}
+else if(OS_MOBILEWEB){
+ $.index.open();
+}
+else{
+ $.index.getView().open();
+} |
2861764dfaff112ccea7a574ccf75710528b1b9f | lib/transitions/parseTransitions.js | lib/transitions/parseTransitions.js | var getInterpolation = require('interpolation-builder');
var createTransitions = require('./createTransitions');
module.exports = function(driver, states, transitions) {
// go through each transition and setup kimi with a function that works
// with values between 0 and 1
transitions.forEach( function(transition, i) {
var from = transition.from || throwError('from', i, transition);
var to = transition.to || throwError('to', i, transition);
var animation = transition.animation || {};
var animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
// else build the the transition
if(typeof animation == 'object') {
// this
animation = getInterpolation(
animationDefinition.transitions
);
}
// animation will either be a function passed in or generated from an object definition
driver.fromTo(from, to, animationDefinition.duration, animation);
});
};
function throwError(type, idx, transition) {
throw new Error(
'For the transition at ' + idx + ':\n' +
JSON.stringify(transition, unanimationined, ' ') + '\n' +
'you did not animationine ' + type + '\n\n'
);
} | var getInterpolation = require('interpolation-builder');
var createTransitions = require('./createTransitions');
module.exports = function(driver, states, transitions) {
// go through each transition and setup kimi with a function that works
// with values between 0 and 1
transitions.forEach( function(transition, i) {
var from = transition.from || throwError('from', i, transition);
var to = transition.to || throwError('to', i, transition);
var animation = transition.animation;
var duration;
var animationDefinition;
// if animation is an object then it's a Tween like definition
// otherwise we'll assume that animation is a function and we can simply
// pass that to the driver
if(typeof animation == 'object') {
animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
// this
animation = getInterpolation(
animationDefinition.transitions
);
duration = animationDefinition.duration;
} else {
duration = animation.duration;
}
// animation will either be a function passed in or generated from an object definition
driver.fromTo(from, to, duration, animation);
});
};
function throwError(type, idx, transition) {
throw new Error(
'For the transition at ' + idx + ':\n' +
JSON.stringify(transition, unanimationined, ' ') + '\n' +
'you did not animationine ' + type + '\n\n'
);
} | Put back in handling for animation being a function for transition definitions | Put back in handling for animation being a function for transition definitions
| JavaScript | mit | Jam3/f1 | ---
+++
@@ -9,20 +9,30 @@
var from = transition.from || throwError('from', i, transition);
var to = transition.to || throwError('to', i, transition);
- var animation = transition.animation || {};
- var animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
+ var animation = transition.animation;
+ var duration;
+ var animationDefinition;
- // else build the the transition
+
+ // if animation is an object then it's a Tween like definition
+ // otherwise we'll assume that animation is a function and we can simply
+ // pass that to the driver
if(typeof animation == 'object') {
+ animationDefinition = createTransitions(animation, states[ from ], states[ to ]);
// this
animation = getInterpolation(
animationDefinition.transitions
);
+
+ duration = animationDefinition.duration;
+ } else {
+
+ duration = animation.duration;
}
// animation will either be a function passed in or generated from an object definition
- driver.fromTo(from, to, animationDefinition.duration, animation);
+ driver.fromTo(from, to, duration, animation);
});
};
|
9a5cdc88c83364d9ca91be189b9b36828b35ede2 | steam_user_review_filter.user.js | steam_user_review_filter.user.js | // ==UserScript==
// @name Steam Review filter
// @namespace https://github.com/somoso/steam_user_review_filter/raw/master/steam_user_review_filter.user.js
// @version 0.31
// @description try to filter out the crap on steam
// @author You
// @match http://store.steampowered.com/app/*
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
/* jshint -W097 */
'use strict';
var searchStr = ".review_box";
console.log("Starting steam user review filter");
var reviews = $(searchStr);
for (i = 0; i < reviews.length; i++) {
if ($(reviews[i]).hasClass('partial')) {
continue;
}
var urgh = reviews[i].innerText;
if (urgh.includes('10/10')) {
$(reviews[i]).remove();
} else if (urgh.match(/\bign\b/i)) {
$(reviews[i]).remove();
}
}
console.log("Ending steam user review filter");
| // ==UserScript==
// @name Steam Review filter
// @namespace https://github.com/somoso/steam_user_review_filter/raw/master/steam_user_review_filter.user.js
// @version 0.31
// @description try to filter out the crap on steam
// @author You
// @match http://store.steampowered.com/app/*
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
/* jshint -W097 */
'use strict';
var searchStr = ".review_box";
console.log("Starting steam user review filter");
var reviews = $(searchStr);
for (i = 0; i < reviews.length; i++) {
if ($(reviews[i]).hasClass('partial')) {
continue;
}
var filterReview = false;
var urgh = reviews[i].innerText;
if (urgh.includes('10/10')) {
filterReview = true;
} else if (urgh.match(/\bign\b/i)) {
filterReview = true;
} else if (urgh.match(/\bbest ([A-Za-z0-9_-]+ ){1,3}ever( made)?\b/i)) {
filterReview = true;
}
if (filterReview) {
$(reviews[i]).remove();
}
})
}
console.log("Ending steam user review filter");
| Add filtering for "Best BLAHBLAHBLAH ever made" | Add filtering for "Best BLAHBLAHBLAH ever made" | JavaScript | unlicense | somoso/steam_user_review_filter,somoso/steam_user_review_filter | ---
+++
@@ -21,12 +21,22 @@
if ($(reviews[i]).hasClass('partial')) {
continue;
}
+ var filterReview = false;
+
var urgh = reviews[i].innerText;
if (urgh.includes('10/10')) {
+ filterReview = true;
+ } else if (urgh.match(/\bign\b/i)) {
+ filterReview = true;
+ } else if (urgh.match(/\bbest ([A-Za-z0-9_-]+ ){1,3}ever( made)?\b/i)) {
+ filterReview = true;
+ }
+
+ if (filterReview) {
$(reviews[i]).remove();
- } else if (urgh.match(/\bign\b/i)) {
- $(reviews[i]).remove();
- }
+ }
+
+ })
}
|
94701f09422ed9536463afc7dc2e48463af2301e | app/config/config.js | app/config/config.js | const dotenv = require('dotenv');
dotenv.config({silent: true});
const config = {
"development": {
"username": process.env.DB_DEV_USER,
"password": process.env.DB_DEV_PASS,
"database": process.env.DB_DEV_NAME,
"host": process.env.DB_DEV_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres"
},
"test": {
"username": process.env.DB_TEST_USER,
"password": process.env.DB_TEST_PASS,
"database": process.env.DB_TEST_NAME,
"host": process.env.DB_TEST_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres",
"logging": false
},
"production": {
"username": process.env.DB_USER,
"password": process.env.DB_PASS,
"database": process.env.DB_NAME,
"host": process.env.DB_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres",
"logging": false
}
};
if(process.env.NODE_ENV === 'production'){
module.exports = config.production;
}else if(process.env.NODE_ENV === 'test'){
module.exports = config.test;
}else{
module.exports = config.development;
} | const dotenv = require('dotenv');
dotenv.config({silent: true});
const config = {
"development": {
"username": process.env.DB_DEV_USER,
"password": process.env.DB_DEV_PASS,
"database": process.env.DB_DEV_NAME,
"host": process.env.DB_DEV_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres"
},
"test": {
"username": process.env.DB_TEST_USER,
"password": process.env.DB_TEST_PASS,
"database": process.env.DB_TEST_NAME,
"host": process.env.DB_TEST_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres",
},
"production": {
"username": process.env.DB_USER,
"password": process.env.DB_PASS,
"database": process.env.DB_NAME,
"host": process.env.DB_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres",
"logging": false
}
};
if(process.env.NODE_ENV === 'production'){
module.exports = config.production;
}else if(process.env.NODE_ENV === 'test'){
module.exports = config.test;
}else{
module.exports = config.development;
} | Enable logging for test environment | Enable logging for test environment
| JavaScript | mit | cyrielo/document-manager | ---
+++
@@ -16,7 +16,7 @@
"host": process.env.DB_TEST_HOST,
"secrete": process.env.AUTH_SECRETE,
"dialect": "postgres",
- "logging": false
+
},
"production": {
"username": process.env.DB_USER, |
7f45b377171d4cffb3f83602b4a6f4025a58ac11 | app/settings/settings.js | app/settings/settings.js | const mapbox_token = 'pk.eyJ1IjoiaG90IiwiYSI6ImNpbmx4bWN6ajAwYTd3OW0ycjh3bTZvc3QifQ.KtikS4sFO95Jm8nyiOR4gQ'
export default {
'vt-source': 'http://osm-analytics.vizzuality.com', // source of current vector tiles
'vt-hist-source': 'http://osm-analytics.vizzuality.com', // source of historic vector tiles for compare feature
'map-background-tile-layer': 'https://api.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token=' + mapbox_token,
'map-attribution': '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>',
}
| const mapbox_token = 'pk.eyJ1IjoiaG90IiwiYSI6ImNpbmx4bWN6ajAwYTd3OW0ycjh3bTZvc3QifQ.KtikS4sFO95Jm8nyiOR4gQ'
export default {
'vt-source': 'https://osm-analytics.vizzuality.com', // source of current vector tiles
'vt-hist-source': 'https://osm-analytics.vizzuality.com', // source of historic vector tiles for compare feature
'map-background-tile-layer': 'https://api.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token=' + mapbox_token,
'map-attribution': '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>',
}
| Revert "https doesn't work at the moment for osma tiles served from vizzuality" | Revert "https doesn't work at the moment for osma tiles served from vizzuality"
This reverts commit 96c3024ca822cbe801a6c2af43eae5b12c3fa9a4.
| JavaScript | bsd-3-clause | hotosm/osm-analytics,hotosm/osm-analytics,hotosm/osm-analytics | ---
+++
@@ -1,8 +1,8 @@
const mapbox_token = 'pk.eyJ1IjoiaG90IiwiYSI6ImNpbmx4bWN6ajAwYTd3OW0ycjh3bTZvc3QifQ.KtikS4sFO95Jm8nyiOR4gQ'
export default {
- 'vt-source': 'http://osm-analytics.vizzuality.com', // source of current vector tiles
- 'vt-hist-source': 'http://osm-analytics.vizzuality.com', // source of historic vector tiles for compare feature
+ 'vt-source': 'https://osm-analytics.vizzuality.com', // source of current vector tiles
+ 'vt-hist-source': 'https://osm-analytics.vizzuality.com', // source of historic vector tiles for compare feature
'map-background-tile-layer': 'https://api.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token=' + mapbox_token,
'map-attribution': '© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>',
} |
591b86fc35858a16337b6fcd75c9575770eaa68a | static/js/front.js | static/js/front.js | var getThat = {};
getThat.controller = function() {
};
getThat.header = function() {
return m('.row', [
m('.col-md-10', [
m('.jumbotron', [
m('h1', [
m('a[href="//getthat.email"]', 'Get That Email')
])
])
])
]);
};
getThat.input = function() {
return m('.row', [
m('.col-md-10', [
m('.input-group', [
m('input.form-control[type="text"'),
m('.input-group-btn', [
m('button.btn.btn-success[type="button"', [
m('span.glyphicon.glyphicon-credit-card'),
' Get It!'
])
])
])
])
]);
};
getThat.view = function() {
return m('.container', [
this.header(),
this.input()
]);
};
//initialize
m.module(document.body, getThat);
| var getThat = {};
getThat.controller = function() {
};
getThat.header = function() {
return m('.row', [
m('.col-md-10', [
m('.jumbotron', [
m('h1', [
m('a[href="//getthat.email"]', 'Get That Email')
])
])
])
]);
};
getThat.emailSelectBtn = function() {
return m('button.btn.btn-default.dropdown-toggle[type="button"][data-toggle="dropdown"]', [
'Select a Domain ',
m('span.caret'),
]);
};
getThat.emailSelectDropdown = function() {
return m('ul.dropdown-menu[role="menu"]', [
m('li', [
m('a[href="#"]', 'Test')
])
]);
};
getThat.input = function() {
return m('.row', [
m('.col-md-10', [
m('.input-group', [
m('input.form-control[type="text"'),
m('.input-group-btn', [
this.emailSelectBtn(),
this.emailSelectDropdown(),
m('button.btn.btn-success[type="button"]', [
m('span.glyphicon.glyphicon-credit-card'),
' Get It!'
])
])
])
])
]);
};
getThat.view = function() {
return m('.container', [
this.header(),
this.input()
]);
};
//initialize
m.module(document.body, getThat);
| Update the email selection UI | Update the email selection UI
| JavaScript | mit | chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy | ---
+++
@@ -16,13 +16,30 @@
]);
};
+getThat.emailSelectBtn = function() {
+ return m('button.btn.btn-default.dropdown-toggle[type="button"][data-toggle="dropdown"]', [
+ 'Select a Domain ',
+ m('span.caret'),
+ ]);
+};
+
+getThat.emailSelectDropdown = function() {
+ return m('ul.dropdown-menu[role="menu"]', [
+ m('li', [
+ m('a[href="#"]', 'Test')
+ ])
+ ]);
+};
+
getThat.input = function() {
return m('.row', [
m('.col-md-10', [
m('.input-group', [
m('input.form-control[type="text"'),
m('.input-group-btn', [
- m('button.btn.btn-success[type="button"', [
+ this.emailSelectBtn(),
+ this.emailSelectDropdown(),
+ m('button.btn.btn-success[type="button"]', [
m('span.glyphicon.glyphicon-credit-card'),
' Get It!'
]) |
8ac385bc002cf517f0542d71ffdbc5c73bc6a9c5 | app/test/client.js | app/test/client.js | window.requirejs = window.yaajs;
window.history.replaceState(null, document.title = 'Piki Test Mode', '/');
define(function(require, exports, module) {
var koru = require('koru/main-client');
require('koru/session/main-client');
require('koru/test/client');
koru.onunload(module, 'reload');
require(['koru/session'], function (session) {
session.connect();
});
});
| window.requirejs = window.yaajs;
window.history.replaceState(null, document.title = 'Piki Test Mode', '/');
define(function(require, exports, module) {
var koru = require('koru/main-client');
require('koru/test/client');
koru.onunload(module, 'reload');
});
| Fix test starting two connections to server | Fix test starting two connections to server
| JavaScript | agpl-3.0 | jacott/piki-scoreboard,jacott/piki-scoreboard,jacott/piki-scoreboard | ---
+++
@@ -5,11 +5,6 @@
define(function(require, exports, module) {
var koru = require('koru/main-client');
- require('koru/session/main-client');
require('koru/test/client');
koru.onunload(module, 'reload');
-
- require(['koru/session'], function (session) {
- session.connect();
- });
}); |
dc3c20f6dbfddb315932a49d6f7a54e5d8b1043d | app/assets/javascripts/accordion.js | app/assets/javascripts/accordion.js | $(function() {
$('.accordion_head').each( function() {
$(this).after('<ul style="display: none;"></ul>');
});
$(document).on("click", '.accordion_head', function() {
var ul = $(this).next();
if (ul.text() == '') {
term = $(this).data('term');
$.getJSON("/children_graph?term=" + term, function(data) {
$.each(data, function(i,item) {
ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ "</a></div><ul style='dispaly: none;'><ul></li>");
});
});
ul.slideToggle();
} else {
ul.slideToggle();
}
}).next().hide();
});
| $(function() {
$('.accordion_head').each( function() {
$(this).after('<ul style="display: none;"></ul>');
});
$(document).on("click", '.accordion_head', function() {
var ul = $(this).next();
if (ul.text() == '') {
term = $(this).data('term');
$.getJSON("/children_graph?term=" + term)
.done(function(data) {
$.each(data, function(i,item) {
ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ '</a></div><ul style="display: none;"></ul></li>');
});
ul.hide().slideToggle();
});
} else {
ul.slideToggle();
}
}).next().hide();
});
| Use `done` callback for smooth animation | Use `done` callback for smooth animation
| JavaScript | mit | yohoushi/yohoushi,yohoushi/yohoushi,yohoushi/yohoushi | ---
+++
@@ -7,12 +7,13 @@
var ul = $(this).next();
if (ul.text() == '') {
term = $(this).data('term');
- $.getJSON("/children_graph?term=" + term, function(data) {
+ $.getJSON("/children_graph?term=" + term)
+ .done(function(data) {
$.each(data, function(i,item) {
- ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ "</a></div><ul style='dispaly: none;'><ul></li>");
+ ul.append('<li><div class="accordion_head" data-term="' + item.path + '"><a href="' + item.uri + '" >' + item.basename+ '</a></div><ul style="display: none;"></ul></li>');
});
+ ul.hide().slideToggle();
});
- ul.slideToggle();
} else {
ul.slideToggle();
} |
7421477c92380fa88a3910e4707046ce9daf5a71 | tests/acceptance/sidebar_test.js | tests/acceptance/sidebar_test.js | var App;
module("Acceptances - Index", {
setup: function(){
var sampleDataUrl = '';
if (typeof __karma__ !== 'undefined')
sampleDataUrl = '/base';
sampleDataUrl = sampleDataUrl + '/tests/support/api.json';
App = startApp({apiDataUrl: sampleDataUrl});
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
test("sidebar renders list of modules/classes", function(){
expect(2);
visit('/').then(function(){
debugger;
ok(exists("a:contains('Ember.Application')"));
ok(exists("a:contains('Ember.run')"));
});
});
| var App;
module("Acceptances - Sidebar", {
setup: function(){
var sampleDataUrl = '';
if (typeof __karma__ !== 'undefined')
sampleDataUrl = '/base';
sampleDataUrl = sampleDataUrl + '/tests/support/api.json';
App = startApp({apiDataUrl: sampleDataUrl});
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
test("sidebar renders list of modules/classes", function(){
expect(2);
visit('/').then(function(){
debugger;
ok(exists("a:contains('Ember.Application')"));
ok(exists("a:contains('Ember.run')"));
});
});
| Fix name of sidebar acceptance test. | Fix name of sidebar acceptance test.
[ci skip]
| JavaScript | mit | rwjblue/ember-live-api | ---
+++
@@ -1,6 +1,6 @@
var App;
-module("Acceptances - Index", {
+module("Acceptances - Sidebar", {
setup: function(){
var sampleDataUrl = '';
|
fb9d61439a75481c1f1d9349f6f0cda2eaf02d6c | collections/server/collections.js | collections/server/collections.js | Letterpress.Collections.Pages = new Mongo.Collection('pages');
Letterpress.Collections.Pages.before.insert(function (userId, doc) {
doc.path = doc.path || doc.title.replace(/ /g, '-').toLowerCase();
if (doc.path[0] !== '/') {
doc.path = '/' + doc.path;
}
});
Meteor.publish("pages", function () {
return Letterpress.Collections.Pages.find();
});
Letterpress.Collections.Audit = new Mongo.Collection('audit'); | Letterpress.Collections.Pages = new Mongo.Collection('pages');
Letterpress.Collections.Pages.before.insert(function (userId, doc) {
doc.path = doc.path || doc.title.replace(/ /g, '-').toLowerCase();
if (doc.path[0] !== '/') {
doc.path = '/' + doc.path;
}
});
Meteor.publish("pages", function () {
var fields = {title: 1, path: 1, template: 1, content: 1};
if (this.userId)
fields.premiumContent = 1;
return Letterpress.Collections.Pages.find({}, {fields: fields});
});
Letterpress.Collections.Audit = new Mongo.Collection('audit');
| Add a publication restriction to not share premium content unless the user is signed in. | Add a publication restriction to not share premium content unless the user is signed in.
| JavaScript | mit | liangsun/Letterpress,dandv/Letterpress,shrop/Letterpress,FleetingClouds/Letterpress,chrisdamba/Letterpress,chrisdamba/Letterpress,cp612sh/Letterpress,nhantamdo/Letterpress,nhantamdo/Letterpress,shrop/Letterpress,xolvio/Letterpress,chrisdamba/Letterpress,cp612sh/Letterpress,dandv/Letterpress,dandv/Letterpress,FleetingClouds/Letterpress,FleetingClouds/Letterpress,cp612sh/Letterpress,shrop/Letterpress,nhantamdo/Letterpress,xolvio/Letterpress,liangsun/Letterpress,xolvio/Letterpress,liangsun/Letterpress | ---
+++
@@ -7,7 +7,10 @@
});
Meteor.publish("pages", function () {
- return Letterpress.Collections.Pages.find();
+ var fields = {title: 1, path: 1, template: 1, content: 1};
+ if (this.userId)
+ fields.premiumContent = 1;
+ return Letterpress.Collections.Pages.find({}, {fields: fields});
});
|
89dd2ec4add8840e5e8cda0e37a0162d66ec560b | src/loadNode.js | src/loadNode.js | var context = require('vm').createContext({
options: {
server: true,
version: 'dev'
},
Canvas: require('canvas'),
console: console,
require: require,
include: function(uri) {
var source = require('fs').readFileSync(__dirname + '/' + uri);
// For relative includes, we save the current directory and then add
// the uri directory to __dirname:
var oldDirname = __dirname;
__dirname = __dirname + '/' + uri.replace(/[^/]+$/, '');
require('vm').runInContext(source, context, uri);
__dirname = oldDirname;
}
});
context.include('paper.js');
context.Base.each(context, function(val, key) {
if (val && val.prototype instanceof context.Base) {
val._name = key;
// Export all classes through PaperScope:
context.PaperScope.prototype[key] = val;
}
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
module.exports = new context.PaperScope(); | var fs = require('fs'),
vm = require('vm'),
path = require('path');
// Create the context within which we will run the source files:
var context = vm.createContext({
options: {
server: true,
version: 'dev'
},
// Node Canvas library: https://github.com/learnboost/node-canvas
Canvas: require('canvas'),
// Copy over global variables:
console: console,
require: require,
__dirname: __dirname,
__filename: __filename,
// Used to load and run source files within the same context:
include: function(uri) {
var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
// For relative includes, we save the current directory and then
// add the uri directory to __dirname:
var oldDirname = __dirname;
__dirname = path.resolve(__dirname, path.dirname(uri));
vm.runInContext(source, context, uri);
__dirname = oldDirname;
}
});
context.include('paper.js');
context.Base.each(context, function(val, key) {
if (val && val.prototype instanceof context.Base) {
val._name = key;
// Export all classes through PaperScope:
context.PaperScope.prototype[key] = val;
}
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
require.extensions['.pjs'] = function(module, uri) {
var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
'var __filename = \'' + uri + '\';';
vm.runInContext(envVars, context);
var scope = new context.PaperScope();
context.PaperScript.evaluate(source, scope);
module.exports = scope;
};
module.exports = new context.PaperScope(); | Support running of PaperScript .pjs files. | Support running of PaperScript .pjs files.
| JavaScript | mit | NHQ/paper,NHQ/paper | ---
+++
@@ -1,18 +1,28 @@
-var context = require('vm').createContext({
+var fs = require('fs'),
+ vm = require('vm'),
+ path = require('path');
+
+// Create the context within which we will run the source files:
+var context = vm.createContext({
options: {
server: true,
version: 'dev'
},
+ // Node Canvas library: https://github.com/learnboost/node-canvas
Canvas: require('canvas'),
+ // Copy over global variables:
console: console,
require: require,
+ __dirname: __dirname,
+ __filename: __filename,
+ // Used to load and run source files within the same context:
include: function(uri) {
- var source = require('fs').readFileSync(__dirname + '/' + uri);
- // For relative includes, we save the current directory and then add
- // the uri directory to __dirname:
+ var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
+ // For relative includes, we save the current directory and then
+ // add the uri directory to __dirname:
var oldDirname = __dirname;
- __dirname = __dirname + '/' + uri.replace(/[^/]+$/, '');
- require('vm').runInContext(source, context, uri);
+ __dirname = path.resolve(__dirname, path.dirname(uri));
+ vm.runInContext(source, context, uri);
__dirname = oldDirname;
}
});
@@ -28,4 +38,14 @@
});
context.PaperScope.prototype['Canvas'] = context.Canvas;
+require.extensions['.pjs'] = function(module, uri) {
+ var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
+ var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
+ 'var __filename = \'' + uri + '\';';
+ vm.runInContext(envVars, context);
+ var scope = new context.PaperScope();
+ context.PaperScript.evaluate(source, scope);
+ module.exports = scope;
+};
+
module.exports = new context.PaperScope(); |
7a5dffb138349c3e6b2a1503fc6a6c82877c0bdc | lib/tab-stop-list.js | lib/tab-stop-list.js | /** @babel */
import TabStop from './tab-stop';
class TabStopList {
constructor (snippet) {
this.snippet = snippet;
this.list = {};
}
get length () {
return Object.keys(this.list).length;
}
findOrCreate({ index, snippet }) {
if (!this.list[index]) {
this.list[index] = new TabStop({ index, snippet });
}
return this.list[index];
}
forEachIndex (iterator) {
let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2);
indices.forEach(iterator);
}
getInsertions () {
let results = [];
this.forEachIndex(index => {
results.push(...this.list[index].insertions);
});
return results;
}
toArray () {
let results = [];
this.forEachIndex(index => {
let tabStop = this.list[index];
if (!tabStop.isValid()) return;
results.push(tabStop);
});
return results;
}
}
export default TabStopList;
| const TabStop = require('./tab-stop')
class TabStopList {
constructor (snippet) {
this.snippet = snippet
this.list = {}
}
get length () {
return Object.keys(this.list).length
}
findOrCreate ({ index, snippet }) {
if (!this.list[index]) {
this.list[index] = new TabStop({ index, snippet })
}
return this.list[index]
}
forEachIndex (iterator) {
let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2)
indices.forEach(iterator)
}
getInsertions () {
let results = []
this.forEachIndex(index => {
results.push(...this.list[index].insertions)
})
return results
}
toArray () {
let results = []
this.forEachIndex(index => {
let tabStop = this.list[index]
if (!tabStop.isValid()) return
results.push(tabStop)
})
return results
}
}
module.exports = TabStopList
| Remove Babel dependency and convert to standard code style | Remove Babel dependency and convert to standard code style
| JavaScript | mit | atom/snippets | ---
+++
@@ -1,46 +1,44 @@
-/** @babel */
-
-import TabStop from './tab-stop';
+const TabStop = require('./tab-stop')
class TabStopList {
constructor (snippet) {
- this.snippet = snippet;
- this.list = {};
+ this.snippet = snippet
+ this.list = {}
}
get length () {
- return Object.keys(this.list).length;
+ return Object.keys(this.list).length
}
- findOrCreate({ index, snippet }) {
+ findOrCreate ({ index, snippet }) {
if (!this.list[index]) {
- this.list[index] = new TabStop({ index, snippet });
+ this.list[index] = new TabStop({ index, snippet })
}
- return this.list[index];
+ return this.list[index]
}
forEachIndex (iterator) {
- let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2);
- indices.forEach(iterator);
+ let indices = Object.keys(this.list).sort((a1, a2) => a1 - a2)
+ indices.forEach(iterator)
}
getInsertions () {
- let results = [];
+ let results = []
this.forEachIndex(index => {
- results.push(...this.list[index].insertions);
- });
- return results;
+ results.push(...this.list[index].insertions)
+ })
+ return results
}
toArray () {
- let results = [];
+ let results = []
this.forEachIndex(index => {
- let tabStop = this.list[index];
- if (!tabStop.isValid()) return;
- results.push(tabStop);
- });
- return results;
+ let tabStop = this.list[index]
+ if (!tabStop.isValid()) return
+ results.push(tabStop)
+ })
+ return results
}
}
-export default TabStopList;
+module.exports = TabStopList |
08f1f9d972bdd71891e7e24a529c44fae1bfa687 | lib/util/getRoles.js | lib/util/getRoles.js | // Dependencies
var request = require('request');
//Define
module.exports = function(group, rank, callbacks) {
request.get('http://www.roblox.com/api/groups/' + group + '/RoleSets/', function(err, res, body) {
if (callbacks.always)
callbacks.always();
if (err) {
if (callbacks.failure)
callbacks.failure(err);
if (callbacks.always)
callbacks.always();
return console.error('GetRoles request failed:' + err);
}
var response = JSON.parse(body);
if (rank) {
for (var i = 0; i < body.length; i++) {
if (response[i].Rank == rank) {
response = response[i].ID;
break;
}
}
}
if (callbacks.success)
callbacks.success(response);
return response;
});
};
| // Dependencies
var request = require('request');
// Define
module.exports = function(group, callbacks) {
request.get('http://www.roblox.com/api/groups/' + group + '/RoleSets/', function(err, res, body) {
if (callbacks.always)
callbacks.always();
if (err) {
if (callbacks.failure)
callbacks.failure(err);
if (callbacks.always)
callbacks.always();
return console.error('GetRoles request failed:' + err);
}
if (callbacks.success)
callbacks.success(JSON.parse(body));
});
};
| Move getRole to separate file | Move getRole to separate file
Work better with cache
| JavaScript | mit | FroastJ/roblox-js,OnlyTwentyCharacters/roblox-js,sentanos/roblox-js | ---
+++
@@ -1,8 +1,8 @@
// Dependencies
var request = require('request');
-//Define
-module.exports = function(group, rank, callbacks) {
+// Define
+module.exports = function(group, callbacks) {
request.get('http://www.roblox.com/api/groups/' + group + '/RoleSets/', function(err, res, body) {
if (callbacks.always)
callbacks.always();
@@ -13,17 +13,7 @@
callbacks.always();
return console.error('GetRoles request failed:' + err);
}
- var response = JSON.parse(body);
- if (rank) {
- for (var i = 0; i < body.length; i++) {
- if (response[i].Rank == rank) {
- response = response[i].ID;
- break;
- }
- }
- }
if (callbacks.success)
- callbacks.success(response);
- return response;
+ callbacks.success(JSON.parse(body));
});
}; |
cf765d21e235c686ef2546cf24e5399ea6e348c2 | lib/reddit/base.js | lib/reddit/base.js | var Snoocore = require('snoocore');
var pkg = require('../../package.json');
var uaString = "QIKlaxonBot/" + pkg.version + ' (by /u/StuartPBentley)';
module.exports = function(cfg, duration, scopes){
return new Snoocore({
userAgent: uaString,
decodeHtmlEntities: true,
oauth: {
type: 'explicit',
duration: duration,
consumerKey: cfg.appId,
consumerSecret: cfg.secret,
redirectUri: 'https://qiklaxonbot.redditbots.com/auth/reddit',
scope: scopes
}
});
};
| var Snoocore = require('snoocore');
var pkg = require('../../package.json');
var uaString = "QIKlaxonBot/" + pkg.version + ' (by /u/StuartPBentley)';
module.exports = function(cfg, duration, scopes){
return new Snoocore({
userAgent: uaString,
decodeHtmlEntities: true,
oauth: {
type: 'explicit',
duration: duration,
consumerKey: cfg.appId,
consumerSecret: cfg.secret,
redirectUri: 'https://' +
(cfg.domain || 'qiklaxonbot.redditbots.com') +
'/auth/reddit',
scope: scopes
}
});
};
| Add support for non-default domains | Add support for non-default domains
| JavaScript | mit | stuartpb/QIKlaxonBot,stuartpb/QIKlaxonBot | ---
+++
@@ -13,7 +13,9 @@
duration: duration,
consumerKey: cfg.appId,
consumerSecret: cfg.secret,
- redirectUri: 'https://qiklaxonbot.redditbots.com/auth/reddit',
+ redirectUri: 'https://' +
+ (cfg.domain || 'qiklaxonbot.redditbots.com') +
+ '/auth/reddit',
scope: scopes
}
}); |
97fdbebde2c762d0f3ce1ab0a8529000a71dd92f | template.js | template.js | (function (<bridge>) {
// unsafeWindow
with ({ unsafeWindow: window, document: window.document, location: window.location, window: undefined }) {
// define GM functions
var GM_log = function (s) {
unsafeWindow.console.log('GM_log: ' + s);
return <bridge>.gmLog_(s);
};
var GM_getValue = function (k, d) {
return <bridge>.gmValueForKey_defaultValue_scriptName_namespace_(k, d, "<name>", "<namespace>");
};
var GM_setValue = function (k, v) {
return <bridge>.gmSetValue_forKey_scriptName_namespace_(v, k, "<name>", "<namespace>");
};
/* Not implemented yet
var GM_registerMenuCommand = function (t, c) {
<bridge>.gmRegisterMenuCommand_callback_(t, c);
}
*/
var GM_xmlhttpRequest = function (d) {
return <bridge>.gmXmlhttpRequest_(d);
};
<body>;
}
});
| (function (<bridge>) {
with ({ document: window.document, location: window.location, }) {
// define GM functions
var GM_log = function (s) {
window.console.log('GM_log: ' + s);
return <bridge>.gmLog_(s);
};
var GM_getValue = function (k, d) {
return <bridge>.gmValueForKey_defaultValue_scriptName_namespace_(k, d, "<name>", "<namespace>");
};
var GM_setValue = function (k, v) {
return <bridge>.gmSetValue_forKey_scriptName_namespace_(v, k, "<name>", "<namespace>");
};
/* Not implemented yet
var GM_registerMenuCommand = function (t, c) {
<bridge>.gmRegisterMenuCommand_callback_(t, c);
}
*/
var GM_xmlhttpRequest = function (d) {
return <bridge>.gmXmlhttpRequest_(d);
};
<body>;
}
});
| Remove fake-unsafeWindow because it's too buggy. | Remove fake-unsafeWindow because it's too buggy.
| JavaScript | mit | sohocoke/greasekit,tbodt/greasekit,kzys/greasekit,chrismessina/greasekit | ---
+++
@@ -1,9 +1,8 @@
(function (<bridge>) {
- // unsafeWindow
- with ({ unsafeWindow: window, document: window.document, location: window.location, window: undefined }) {
+ with ({ document: window.document, location: window.location, }) {
// define GM functions
var GM_log = function (s) {
- unsafeWindow.console.log('GM_log: ' + s);
+ window.console.log('GM_log: ' + s);
return <bridge>.gmLog_(s);
};
var GM_getValue = function (k, d) { |
b57115294999bc2292ccee19c948bbf555fd6077 | tests/helpers/start-app.js | tests/helpers/start-app.js | import { merge } from '@ember/polyfills';
import { run } from '@ember/runloop'
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
let attributes = merge({}, config.APP);
attributes = merge(attributes, attrs); // use defaults, but you can override;
run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| import { assign } from '@ember/polyfills';
import { run } from '@ember/runloop'
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
let attributes = assign({}, config.APP);
attributes = assign(attributes, attrs); // use defaults, but you can override;
run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| Update test helper due to deprecated function | Update test helper due to deprecated function
| JavaScript | apache-2.0 | ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend,ExplorViz/explorviz-ui-frontend | ---
+++
@@ -1,4 +1,4 @@
-import { merge } from '@ember/polyfills';
+import { assign } from '@ember/polyfills';
import { run } from '@ember/runloop'
import Application from '../../app';
import config from '../../config/environment';
@@ -6,8 +6,8 @@
export default function startApp(attrs) {
let application;
- let attributes = merge({}, config.APP);
- attributes = merge(attributes, attrs); // use defaults, but you can override;
+ let attributes = assign({}, config.APP);
+ attributes = assign(attributes, attrs); // use defaults, but you can override;
run(() => {
application = Application.create(attributes); |
61a0a3c5b600bc3b52d006aba46a4d144d4ab0dd | collections/List.js | collections/List.js | List = new Meteor.Collection( 'List' );
List.allow({
insert: (userId, document) => true,
update: (userId, document) => document.owner_id === Meteor.userId(),
remove: (userId, document) => false
});
List.deny({
insert: (userId, document) => false,
update: (userId, document) => false,
remove: (userId, document) => false
});
List.schema = new SimpleSchema({
title: {
type: String,
label: 'Title',
optional: false,
min: 5,
},
description: {
type: String,
label: 'Details',
optional: true,
max: 1000,
autoform: {
type: 'markdown',
rows: 10,
}
},
owner_id: {
type: String,
optional: true,
autoform: {
omit: true,
}
},
date_created: {
type: Date,
optional: true,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
}
});
List.attachSchema( List.schema );
| List = new Meteor.Collection( 'List' );
List.allow({
insert: (userId, document) => true,
update: (userId, document) => document.owner_id === Meteor.userId(),
remove: (userId, document) => false
});
List.deny({
insert: (userId, document) => false,
update: (userId, document) => false,
remove: (userId, document) => false
});
List.schema = new SimpleSchema({
title: {
type: String,
label: 'Title',
optional: false,
min: 5,
},
description: {
type: String,
label: 'Details',
optional: true,
max: 1000,
autoform: {
type: 'markdown',
rows: 10,
}
},
owner_id: {
type: String,
optional: true,
autoValue: function() {
const userId = Meteor.userId() || '';
if (this.isInsert) {
return userId;
} else if (this.isUpsert) {
return {$setOnInsert: userId};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
},
date_created: {
type: Date,
optional: true,
autoValue: function() {
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return {$setOnInsert: new Date()};
} else {
this.unset(); // Prevent user from supplying their own value
}
},
autoform: {
omit: true,
}
}
});
List.attachSchema( List.schema );
| Set owner_id on new post. | Set owner_id on new post.
| JavaScript | mit | lnwKodeDotCom/WeCode,lnwKodeDotCom/WeCode | ---
+++
@@ -35,6 +35,16 @@
owner_id: {
type: String,
optional: true,
+ autoValue: function() {
+ const userId = Meteor.userId() || '';
+ if (this.isInsert) {
+ return userId;
+ } else if (this.isUpsert) {
+ return {$setOnInsert: userId};
+ } else {
+ this.unset(); // Prevent user from supplying their own value
+ }
+ },
autoform: {
omit: true,
} |
f9221c7e28915de2fd3f253c78c1f7f24e960937 | shared/common-adapters/avatar.desktop.js | shared/common-adapters/avatar.desktop.js | // @flow
import React, {Component} from 'react'
import resolveRoot from '../../desktop/resolve-root'
import type {Props} from './avatar'
const noAvatar = `file:///${resolveRoot('shared/images/no-avatar@2x.png')}`
export default class Avatar extends Component {
props: Props;
render () {
return (
<img
style={{width: this.props.size, height: this.props.size, borderRadius: this.props.size / 2, ...this.props.style}}
src={this.props.url}
onError={event => (event.target.src = noAvatar)}/>)
}
}
Avatar.propTypes = {
size: React.PropTypes.number.isRequired,
url: React.PropTypes.string,
style: React.PropTypes.object
}
| // @flow
import React, {Component} from 'react'
import resolveRoot from '../../desktop/resolve-root'
import type {Props} from './avatar'
const noAvatar = `file:///${resolveRoot('shared/images/icons/placeholder-avatar@2x.png')}`
export default class Avatar extends Component {
props: Props;
render () {
return (
<img
style={{width: this.props.size, height: this.props.size, borderRadius: this.props.size / 2, ...this.props.style}}
src={this.props.url}
onError={event => (event.target.src = noAvatar)}/>)
}
}
Avatar.propTypes = {
size: React.PropTypes.number.isRequired,
url: React.PropTypes.string,
style: React.PropTypes.object
}
| Add grey no avatar image | Add grey no avatar image
| JavaScript | bsd-3-clause | keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client | ---
+++
@@ -4,7 +4,7 @@
import resolveRoot from '../../desktop/resolve-root'
import type {Props} from './avatar'
-const noAvatar = `file:///${resolveRoot('shared/images/no-avatar@2x.png')}`
+const noAvatar = `file:///${resolveRoot('shared/images/icons/placeholder-avatar@2x.png')}`
export default class Avatar extends Component {
props: Props; |
42d206a5364616aa6b32f4cc217fcc57fa223d2a | src/components/markdown-render/inlineCode.js | src/components/markdown-render/inlineCode.js | import React from 'react';
import Highlight, { defaultProps } from 'prism-react-renderer';
import darkTheme from 'prism-react-renderer/themes/duotoneDark';
const InlineCode = ({ children, className, additionalPreClasses, theme }) => {
className = className ? '' : className;
const language = className.replace(/language-/, '');
return (
<Highlight
{...defaultProps}
code={children}
language={language}
theme={theme || darkTheme}
>
{({ className, style, tokens, getLineProps, getTokenProps }) => (
<pre
className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`}
style={{ ...style }}
>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({ line, key: i })}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({ token, key })} />
))}
</div>
))}
</pre>
)}
</Highlight>
);
};
export default InlineCode;
| import React from 'react';
import Highlight, { defaultProps } from 'prism-react-renderer';
import darkTheme from 'prism-react-renderer/themes/duotoneDark';
const InlineCode = ({ children, className, additionalPreClasses, theme }) => {
className = className ? className : '';
const language = className.replace(/language-/, '');
return (
<Highlight
{...defaultProps}
code={children}
language={language}
theme={theme || darkTheme}
>
{({ className, style, tokens, getLineProps, getTokenProps }) => (
<pre
className={`docs-code sprk-u-Measure ${className} ${additionalPreClasses}`}
style={{ ...style }}
>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({ line, key: i })}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({ token, key })} />
))}
</div>
))}
</pre>
)}
</Highlight>
);
};
export default InlineCode;
| Fix code snippet codetype so it passes in correctly | Fix code snippet codetype so it passes in correctly
| JavaScript | mit | sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system | ---
+++
@@ -3,7 +3,7 @@
import darkTheme from 'prism-react-renderer/themes/duotoneDark';
const InlineCode = ({ children, className, additionalPreClasses, theme }) => {
- className = className ? '' : className;
+ className = className ? className : '';
const language = className.replace(/language-/, '');
return (
<Highlight |
4f09ecf3fc15a2ca29ac3b9605046c5a84012664 | mods/gen3/scripts.js | mods/gen3/scripts.js | exports.BattleScripts = {
inherit: 'gen5',
gen: 3,
init: function () {
for (var i in this.data.Pokedex) {
delete this.data.Pokedex[i].abilities['H'];
}
var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
var newCategory = '';
for (var i in this.data.Movedex) {
if (this.data.Movedex[i].category === 'Status') continue;
newCategory = specialTypes[this.data.Movedex[i].type] ? 'Special' : 'Physical';
if (newCategory !== this.data.Movedex[i].category) {
this.modData('Movedex', i).category = newCategory;
}
}
},
faint: function (pokemon, source, effect) {
pokemon.faint(source, effect);
this.queue = [];
}
};
| exports.BattleScripts = {
inherit: 'gen5',
gen: 3,
init: function () {
for (var i in this.data.Pokedex) {
delete this.data.Pokedex[i].abilities['H'];
}
var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1};
var newCategory = '';
for (var i in this.data.Movedex) {
if (this.data.Movedex[i].category === 'Status') continue;
newCategory = specialTypes[this.data.Movedex[i].type] ? 'Special' : 'Physical';
if (newCategory !== this.data.Movedex[i].category) {
this.modData('Movedex', i).category = newCategory;
}
}
}
};
| Revert "Gen 3: A faint ends the turn just like in gens 1 and 2" | Revert "Gen 3: A faint ends the turn just like in gens 1 and 2"
This reverts commit ebfaf1e8340db1187b9daabcb6414ee3329d882b.
| JavaScript | mit | kubetz/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,yashagl/pokemon,Nineage/Origin,Irraquated/EOS-Master,ehk12/bigbangtempclone,danpantry/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,Atwar/server-epilogueleague.rhcloud.com,DesoGit/TsunamiPS,PrimalGallade45/Lumen-Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,lFernanl/Zero-Pokemon-Showdown,MayukhKundu/Pokemon-Domain,Mystifi/Exiled,TheFenderStory/Pokemon-Showdown,jd4564/Pokemon-Showdown,comedianchameleon/test,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,lAlejandro22/lolipoop,Articuno-I/Pokemon-Showdown,SerperiorBae/Bae-Showdown,ShowdownHelper/Saffron,Hidden-Mia/Roleplay-PS,Parukia/Pokemon-Showdown,KaitoV4X/Showdown,hayleysworld/serenityc9,MasterFloat/LQP-Server-Showdown,SkyeTheFemaleSylveon/Mudkip-Server,BuzzyOG/Pokemon-Showdown,Firestatics/Firestatics46,TheFenderStory/Pokemon-Showdown,TheManwithskills/COC,javi501/Lumen-Pokemon-Showdown,Flareninja/Showdown-Boilerplate,xCrystal/Pokemon-Showdown,SkyeTheFemaleSylveon/Mudkip-Server,brettjbush/Pokemon-Showdown,psnsVGC/Wish-Server,SkyeTheFemaleSylveon/Pokemon-Showdown,Hidden-Mia/Roleplay-PS,TheManwithskills/New-boiler-test,kupochu/Pokemon-Showdown,AustinXII/Pokemon-Showdown,gustavo515/final,brettjbush/Pokemon-Showdown,KewlStatics/Alliance,BuzzyOG/Pokemon-Showdown,Extradeath/psserver,MayukhKundu/Flame-Savior,CreaturePhil/Showdown-Boilerplate,Pablo000/aaa,Yggdrasil-League/Yggdrasil,hayleysworld/serenity,sama2/Universe-Pokemon-Showdown,sama2/Lumen-Pokemon-Showdown,DB898/theregalias,Zipzapadam/Server,hayleysworld/Showdown-Boilerplate,urkerab/Pokemon-Showdown,JellalTheMage/Jellals-Server,Git-Worm/City-PS,panpawn/Pokemon-Showdown,ZeroParadox/ugh,Flareninja/Lumen-Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,MayukhKundu/Technogear,CharizardtheFireMage/Showdown-Boilerplate,ZestOfLife/PSserver,xfix/Pokemon-Showdown,AbsolitoSweep/Absol-server,kuroscafe/Paradox,KewlStatics/Alliance,theodelhay/test,TheFenderStory/Showdown-Boilerplate,arkanox/MistShowdown,Irraquated/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,Zarel/Pokemon-Showdown,zczd/enculer,psnsVGC/Wish-Server,svivian/Pokemon-Showdown,zek7rom/SpacialGaze,SerperiorBae/Bae-Showdown-2,AnaRitaTorres/Pokemon-Showdown,Lauc1an/Perulink-Showdown,KewlStatics/Pokeindia-Codes,ehk12/coregit,zek7rom/SpacialGaze,jumbowhales/Pokemon-Showdown,abrulochp/Lumen-Pokemon-Showdown,Sora-League/Sora,Firestatics/omega,Sora-Server/Sora,Darkshadow6/PokeMoon-Creation,Disaster-Area/Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,Neosweiss/Pokemon-Showdown,kotarou3/Krister-Pokemon-Showdown,Raina4uberz/Light-server,gustavo515/final,Ecuacion/Pokemon-Showdown,panpawn/Gold-Server,Tesarand/Pokemon-Showdown,miahjennatills/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,Disaster-Area/Pokemon-Showdown,UniversalMan12/Universe-Server,ShowdownHelper/Saffron,hayleysworld/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,Breakfastqueen/advanced,Pablo000/aaa,SilverTactic/Showdown-Boilerplate,TheManwithskills/Creature-phil-boiler,LightningStormServer/Lightning-Storm,hayleysworld/harmonia,kupochu/Pokemon-Showdown,TheManwithskills/Creature-phil-boiler,TheManwithskills/Server,superman8900/Pokemon-Showdown,ankailou/Pokemon-Showdown,Pikachuun/Joimmon-Showdown,bai2/Dropp,abrulochp/Dropp-Pokemon-Showdown,TheDiabolicGift/Lumen-Pokemon-Showdown,KewlStatics/Shit,abrulochp/Dropp-Pokemon-Showdown,AustinXII/Pokemon-Showdown,svivian/Pokemon-Showdown,TheManwithskills/Server---Thermal,gustavo515/batata,sama2/Universe-Pokemon-Showdown,megaslowbro1/Showdown-Server-again,Ecuacion/Lumen-Pokemon-Showdown,sirDonovan/Pokemon-Showdown,SilverTactic/Pokemon-Showdown,SerperiorBae/BaeShowdown,Irraquated/Pokemon-Showdown,KewlStatics/Pokeindia-Codes,lFernanl/Pokemon-Showdown,Pikachuun/Pokemon-Showdown-SMCMDM,cadaeic/Pokemon-Showdown,danpantry/Pokemon-Showdown,scotchkorean27/Pokemon-Showdown,Breakfastqueen/advanced,xfix/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown-1,Pokemon-Devs/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,HoeenCoder/SpacialGaze,TheManwithskills/serenity,zczd/enculer,gustavo515/gashoro,EmmaKitty/Pokemon-Showdown,FakeSloth/Infinite,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,sama2/Lumen-Pokemon-Showdown,Alpha-Devs/Alpha-Server,Zarel/Pokemon-Showdown,CreaturePhil/Showdown-Boilerplate,SerperiorBae/Pokemon-Showdown,PauLucario/LQP-Server-Showdown,Lauc1an/Perulink-Showdown,ehk12/clone,Volcos/SpacialGaze,hayleysworld/asdfasdf,xCrystal/Pokemon-Showdown,TogeSR/Lumen-Pokemon-Showdown,CharizardtheFireMage/Showdown-Boilerplate,xCrystal/Pokemon-Showdown,Atwar/ServerClassroom,sama2/Dropp-Pokemon-Showdown,piiiikachuuu/Pokemon-Showdown,Ridukuo/Test,ZeroParadox/ugh,BlazingAura/Showdown-Boilerplate,hayleysworld/serenity,kotarou3/Krister-Pokemon-Showdown,panpawn/Gold-Server,xfix/Pokemon-Showdown,JellalTheMage/Jellals-Server,lFernanl/Lumen-Pokemon-Showdown,KewlStatics/Showdown-Template,Syurra/Pokemon-Showdown,Sora-Server/Sora,SerperiorBae/Bae-Showdown-2,ScottehMax/Pokemon-Showdown,Ransei1/Alt,jumbowhales/Pokemon-Showdown,TheFenderStory/Showdown-Boilerplate,Guernouille/Pokemon-Showdown,Firestatics/Firestatics46,LightningStormServer/Lightning-Storm,ZestOfLife/FestiveLife,Flareninja/Hispano-Pokemon-Showdown,comedianchameleon/test,abrulochp/Lumen-Pokemon-Showdown,Wando94/Spite,azum4roll/Pokemon-Showdown,FakeSloth/Infinite,Lord-Haji/SpacialGaze,Darkshadow6/PokeMoon-Creation,Guernouille/Pokemon-Showdown,Irraquated/Showdown-Boilerplate,MasterFloat/Pokemon-Showdown,JennyPRO/Jenny,HoeenCoder/SpacialGaze,Pikachuun/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,JellalTheMage/PS-,aakashrajput/Pokemon-Showdown,PauLucario/LQP-Server-Showdown,yashagl/pokecommunity,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,SkyeTheFemaleSylveon/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Ransei1/Alt,CreaturePhil/Showdown-Boilerplate,Extradeath/advanced,Mystifi/Exiled,hayleysworld/Pokemon-Showdown,urkerab/Pokemon-Showdown,PS-Spectral/Spectral,LegendBorned/PS-Boilerplate,Firestatics/Omega-Alpha,ZeroParadox/BlastBurners,svivian/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,DarkSuicune/Pokemon-Showdown,lAlejandro22/lolipoop,Lord-Haji/SpacialGaze,hayleysworld/harmonia,SSJGVegito007/Vegito-s-Server,Volcos/SpacialGaze,JennyPRO/Jenny,KewlStatics/Shit,catanatron/pokemon-rebalance,Irraquated/Showdown-Boilerplate,DarkSuicune/Kakuja-2.0,johtooo/PS,ehk12/bigbangtempclone,SerperiorBae/Pokemon-Showdown-1,Flareninja/Pokemon-Showdown,TheDiabolicGift/Lumen-Pokemon-Showdown,FakeSloth/wulu,Zarel/Pokemon-Showdown,panpawn/Gold-Server,Kevinxzllz/PS-Openshift-Server,Atwar/ServerClassroom,theodelhay/test,yashagl/pokemon,svivian/Pokemon-Showdown,yashagl/yash-showdown,Stroke123/POKEMON,MeliodasBH/Articuno-Land,NoahVSGamingYT/Pokemon-Showdown,abulechu/Dropp-Pokemon-Showdown,megaslowbro1/Pokemon-Showdown,TheManwithskills/COC,SerperiorBae/Pokemon-Showdown,azum4roll/Pokemon-Showdown,KewlStatics/Showdown-Template,Breakfastqueen/advanced,gustavo515/batata,Pokemon-Devs/Pokemon-Showdown,Evil-kun/Pokemon-Showdown,SerperiorBae/Bae-Showdown-2,kuroscafe/Paradox,Stroke123/POKEMON,BlazingAura/Showdown-Boilerplate,SilverTactic/Pokemon-Showdown,panpawn/Pokemon-Showdown,Sora-League/Sora,Extradeath/psserver,SubZeroo99/Pokemon-Showdown,PrimalGallade45/Dropp-Pokemon-Showdown,PS-Spectral/Spectral,lFernanl/Mudkip-Server,Atwar/server-epilogueleague.rhcloud.com,Kokonoe-san/Glacia-PS,SilverTactic/Showdown-Boilerplate,MayukhKundu/Technogear-Final,SilverTactic/Dragotica-Pokemon-Showdown,gustavo515/test,Kill-The-Noise/BlakJack-Boilerplate,AWailOfATail/awoat,Wando94/Pokemon-Showdown,AbsolitoSweep/Absol-server,kubetz/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,hayleysworld/serenityc9,TbirdClanWish/Pokemon-Showdown,ScottehMax/Pokemon-Showdown,comedianchameleon/test,Elveman/RPCShowdownServer,anubhabsen/Pokemon-Showdown,forbiddennightmare/Pokemon-Showdown-1,arkanox/MistShowdown,yashagl/pokemon-showdown,Ridukuo/Test,DesoGit/Tsunami_PS,Ecuacion/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,Legit99/Lightning-Storm-Server,Pikachuun/Pokemon-Showdown-SMCMDM,SerperiorBae/BaeShowdown,Vacate/Pokemon-Showdown,Elveman/RPCShowdownServer,Flareninja/Pokemon-Showdown,Articuno-I/Pokemon-Showdown,Mystifi/Exiled,hayleysworld/serenityserver,sirDonovan/Pokemon-Showdown,Nineage/Origin,SerperiorBae/Bae-Showdown,SerperiorBae/Bae-Showdown,Enigami/Pokemon-Showdown,Parukia/Pokemon-Showdown,ShowdownHelper/Saffron,abulechu/Dropp-Pokemon-Showdown,Firestatics/Omega-Alpha,Alpha-Devs/OmegaRuby-Server,MayukhKundu/Technogear,TbirdClanWish/Pokemon-Showdown,catanatron/pokemon-rebalance,AWailOfATail/awoat,UniversalMan12/Universe-Server,Wando94/Spite,Enigami/Pokemon-Showdown,UniversalMan12/Universe-Server,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,ehk12/coregit,abulechu/Lumen-Pokemon-Showdown,DesoGit/TsunamiPS,piiiikachuuu/Pokemon-Showdown,kuroscafe/Showdown-Boilerplate,Git-Worm/City-PS,TogeSR/Lumen-Pokemon-Showdown,KaitoV4X/Showdown,lFernanl/Pokemon-Showdown,hayleysworld/asdfasdf,lFernanl/Lumen-Pokemon-Showdown,DB898/theregalias,MayukhKundu/Mudkip-Server,svivian/Pokemon-Showdown,Enigami/Pokemon-Showdown,lFernanl/Mudkip-Server,Sora-Server/Sora,LegendBorned/PS-Boilerplate,TheManwithskills/New-boiler-test,TheManwithskills/Server,SSJGVegito007/Vegito-s-Server,MayukhKundu/Mudkip-Server,Ecuacion/Lumen-Pokemon-Showdown,TheManwithskills/Server---Thermal,EienSeiryuu/Pokemon-Showdown,Bryan-0/Pokemon-Showdown,yashagl/yash-showdown,PS-Spectral/Spectral,yashagl/pokecommunity,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,anubhabsen/Pokemon-Showdown,Zipzapadam/Server,Kill-The-Noise/BlakJack-Boilerplate,ankailou/Pokemon-Showdown,LustyAsh/EOS-Master,RustServer/Pokemon-Showdown,ZestOfLife/FestiveLife,hayleysworld/Showdown-Boilerplate,BuzzyOG/Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,TheManwithskills/serenity,SilverTactic/Dragotica-Pokemon-Showdown,MeliodasBH/Articuno-Land,cadaeic/Pokemon-Showdown,Enigami/Pokemon-Showdown,Sora-League/Sora,DarkSuicune/Pokemon-Showdown,Celecitia/Plux-Pokemon-Showdown,DalleTest/Pokemon-Showdown,TheManwithskills/DS,Flareninja/Lumen-Pokemon-Showdown,superman8900/Pokemon-Showdown,MasterFloat/Pokemon-Showdown,Darkshadow6/PokeMoon-Creation,EienSeiryuu/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,k3naan/Pokemon-Showdown,Extradeath/advanced,urkerab/Pokemon-Showdown,miahjennatills/Pokemon-Showdown,DalleTest/Pokemon-Showdown,DesoGit/Tsunami_PS,xfix/Pokemon-Showdown,DarkSuicune/Kakuja-2.0,Firestatics/omega,Tesarand/Pokemon-Showdown,PrimalGallade45/Dropp-Pokemon-Showdown,Bryan-0/Pokemon-Showdown,Wando94/Pokemon-Showdown,HoeenCoder/SpacialGaze,Pikachuun/Joimmon-Showdown,jd4564/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,hayleysworld/serenityserver,scotchkorean27/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,TheDiabolicGift/Showdown-Boilerplate,Evil-kun/Pokemon-Showdown,Raina4uberz/Light-server,aakashrajput/Pokemon-Showdown,Neosweiss/Pokemon-Showdown,HoeenCoder/SpacialGaze,gustavo515/gashoro,LustyAsh/EOS-Master,xfix/Pokemon-Showdown,asdfghjklohhnhn/Pokemon-Showdown,ZestOfLife/PSserver,TheDiabolicGift/Showdown-Boilerplate,abulechu/Lumen-Pokemon-Showdown,kuroscafe/Showdown-Boilerplate,Flareninja/Hispano-Pokemon-Showdown,megaslowbro1/Showdown-Server-again,JellalTheMage/PS-,jumbowhales/Pokemon-Showdown,Alpha-Devs/OmegaRuby-Server,MayukhKundu/Pokemon-Domain,DesoGit/Tsunami_PS,MayukhKundu/Technogear-Final,TheManwithskills/DS,lFernanl/Zero-Pokemon-Showdown,Syurra/Pokemon-Showdown,Kevinxzllz/PS-Openshift-Server,InvalidDN/Pokemon-Showdown,Kill-The-Noise/BlakJack-Boilerplate,yashagl/pokemon-showdown,Irraquated/EOS-Master,Lord-Haji/SpacialGaze,bai2/Dropp,MayukhKundu/Flame-Savior,Parukia/Pokemon-Showdown,SerperiorBae/BaeShowdown,AnaRitaTorres/Pokemon-Showdown,RustServer/Pokemon-Showdown,ZeroParadox/BlastBurners,SerperiorBae/Pokemon-Showdown-1,EmmaKitty/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,gustavo515/test,Legit99/Lightning-Storm-Server,Vacate/Pokemon-Showdown,Irraquated/Pokemon-Showdown,ehk12/clone,megaslowbro1/Pokemon-Showdown,LightningStormServer/Lightning-Storm,sama2/Dropp-Pokemon-Showdown,SubZeroo99/Pokemon-Showdown,Celecitia/Plux-Pokemon-Showdown,MasterFloat/LQP-Server-Showdown,Yggdrasil-League/Yggdrasil,MeliodasBH/boarhat,johtooo/PS,k3naan/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,Alpha-Devs/Alpha-Server,javi501/Lumen-Pokemon-Showdown,forbiddennightmare/Pokemon-Showdown-1,Tesarand/Pokemon-Showdown,Kokonoe-san/Glacia-PS,asdfghjklohhnhn/Pokemon-Showdown,MeliodasBH/boarhat,InvalidDN/Pokemon-Showdown | ---
+++
@@ -14,9 +14,5 @@
this.modData('Movedex', i).category = newCategory;
}
}
- },
- faint: function (pokemon, source, effect) {
- pokemon.faint(source, effect);
- this.queue = [];
}
}; |
a3d8e35c1b438bfe7671375aca48863ca91acc90 | src/scripts/browser/utils/logger.js | src/scripts/browser/utils/logger.js | import colors from 'colors/safe';
export function printDebug() {
console.log(...arguments);
const fileLogger = require('browser/utils/file-logger');
fileLogger.writeLog(...arguments);
}
export function printError(namespace, isFatal, err) {
const errorPrefix = `[${new Date().toUTCString()}] ${namespace}:`;
if (isFatal) {
console.error(colors.white.bold.bgMagenta(errorPrefix), err);
} else {
console.error(colors.white.bold.bgRed(errorPrefix), err);
}
const fileLogger = require('browser/utils/file-logger');
fileLogger.writeLog(errorPrefix, err);
}
| import colors from 'colors/safe';
function getCleanISODate() {
return new Date().toISOString().replace(/[TZ]/g, ' ').trim();
}
export function printDebug() {
console.log(...arguments);
const fileLogger = require('browser/utils/file-logger');
fileLogger.writeLog(`DEBUG [${getCleanISODate()}]`, ...arguments);
}
export function printError(namespace, isFatal, err) {
const errorPrefix = `${isFatal ? 'FATAL' : 'ERROR'} [${getCleanISODate()}] ${namespace}:`;
if (isFatal) {
console.error(colors.white.bold.bgMagenta(errorPrefix), err);
} else {
console.error(colors.white.bold.bgRed(errorPrefix), err);
}
const fileLogger = require('browser/utils/file-logger');
fileLogger.writeLog(errorPrefix, err);
}
| Improve logging (timestamp and level) | Improve logging (timestamp and level)
| JavaScript | mit | Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,rafael-neri/whatsapp-webapp,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Messenger-for-Desktop | ---
+++
@@ -1,13 +1,17 @@
import colors from 'colors/safe';
+
+function getCleanISODate() {
+ return new Date().toISOString().replace(/[TZ]/g, ' ').trim();
+}
export function printDebug() {
console.log(...arguments);
const fileLogger = require('browser/utils/file-logger');
- fileLogger.writeLog(...arguments);
+ fileLogger.writeLog(`DEBUG [${getCleanISODate()}]`, ...arguments);
}
export function printError(namespace, isFatal, err) {
- const errorPrefix = `[${new Date().toUTCString()}] ${namespace}:`;
+ const errorPrefix = `${isFatal ? 'FATAL' : 'ERROR'} [${getCleanISODate()}] ${namespace}:`;
if (isFatal) {
console.error(colors.white.bold.bgMagenta(errorPrefix), err);
} else { |
09f1a06bb726af840ced3c4e3d0e1cd3e2794025 | modules/youtube.js | modules/youtube.js | /**
* To use this module, add youtube.key to your config.json
* You need the key for the Youtube Data API:
* https://console.developers.google.com/apis/credentials
*/
var yt = require( 'youtube-search' );
module.exports = {
commands: {
yt: {
help: 'Searches YouTube for a query string',
aliases: [ 'youtube' ],
command: function ( bot, msg ) {
msg.args.shift();
var query = msg.args.join( ' ' );
var opts = bot.config.youtube || {};
opts.maxResults = 1;
yt( query, opts, function ( err, results ) {
if ( err ) {
return bot.say( msg.to, msg.nick + ': ' + err );
}
var result = results[0];
bot.say( msg.to, msg.nick + ': ' + result.link + ' ' + result.title );
} );
}
}
}
};
| /**
* To use this module, add youtube.key to your config.json
* You need the key for the Youtube Data API:
* https://console.developers.google.com/apis/credentials
*/
var yt = require( 'youtube-search' );
module.exports = {
commands: {
yt: {
help: 'Searches YouTube for a query string',
aliases: [ 'youtube' ],
command: function ( bot, msg ) {
msg.args.shift();
var query = msg.args.join( ' ' );
var opts = bot.config.youtube || {};
opts.maxResults = 1;
opts.type = 'video,channel';
yt( query, opts, function ( err, results ) {
if ( err ) {
return bot.say( msg.to, msg.nick + ': ' + err );
}
var result = results[0];
bot.say( msg.to, msg.nick + ': ' + result.link + ' ' + result.title );
} );
}
}
}
};
| Add workaround for bad YouTube results | Add workaround for bad YouTube results
The upstream module used for YouTube search breaks when results are
neither videos nor channels. This commit forces YouTube to return only
videos and channels, in order to work around the bug.
Bug: MaxGfeller/youtube-search#15
| JavaScript | isc | zuzakistan/civilservant,zuzakistan/civilservant | ---
+++
@@ -14,6 +14,7 @@
var query = msg.args.join( ' ' );
var opts = bot.config.youtube || {};
opts.maxResults = 1;
+ opts.type = 'video,channel';
yt( query, opts, function ( err, results ) {
if ( err ) {
return bot.say( msg.to, msg.nick + ': ' + err ); |
4a51369bf5b24c263ceac5199643ace5597611d3 | lib/assure-seamless-styles.js | lib/assure-seamless-styles.js | 'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = function (nodes) {
var styleSheets = [], container, document;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
| 'use strict';
var isParentNode = require('dom-ext/parent-node/is')
, isStyleSheet = require('html-dom-ext/link/is-style-sheet')
, forEach = Array.prototype.forEach;
module.exports = exports = function (nodes) {
var styleSheets = [], container, document;
if (!exports.enabled) return;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
return;
}
if (!isParentNode(node)) return;
if (node.getElementsByTagName) {
forEach.call(node.getElementsByTagName('link'), function (link) {
if (!isStyleSheet(link)) return;
if (link.hasAttribute('href')) styleSheets.push(node);
});
return;
}
forEach.call(node.childNodes, self);
});
if (!styleSheets.length) return;
document = styleSheets[0].ownerDocument;
container = document.documentElement.insertBefore(document.createElement('div'),
document.documentElement.firstChild);
container.className = 'ie-stylesheets-unload-workaround';
styleSheets.forEach(function (styleSheet) {
styleSheet = styleSheet.cloneNode(true);
container.appendChild(styleSheet);
styleSheet.setAttribute('href', styleSheet.getAttribute('href'));
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
exports.enabled = true;
| Allow external disable of stylesheets hack | Allow external disable of stylesheets hack
| JavaScript | mit | medikoo/site-tree | ---
+++
@@ -5,8 +5,9 @@
, forEach = Array.prototype.forEach;
-module.exports = function (nodes) {
+module.exports = exports = function (nodes) {
var styleSheets = [], container, document;
+ if (!exports.enabled) return;
forEach.call(nodes, function self(node) {
if (isStyleSheet(node)) {
if (node.hasAttribute('href')) styleSheets.push(node);
@@ -35,3 +36,5 @@
});
setTimeout(function () { document.documentElement.removeChild(container); }, 0);
};
+
+exports.enabled = true; |
efe31ffd074aa24cb6d92fdb265fdcb7bbccbc30 | src/core/keyboard/compare.js | src/core/keyboard/compare.js | import dEqual from 'fast-deep-equal';
// Compares two possible objects
export function compareKbdCommand(c1, c2) {
return dEqual(c1, c2);
}
| import dEqual from 'fast-deep-equal';
// Compares two possible objects
export function compareKbdCommand(c1, c2) {
if (Array.isArray(c1)) {
return dEqual(c1[0], c1[1]);
}
return dEqual(c1, c2);
}
| Handle array case in keyboard command comparison | Handle array case in keyboard command comparison
| JavaScript | mit | reblws/tab-search,reblws/tab-search | ---
+++
@@ -2,5 +2,8 @@
// Compares two possible objects
export function compareKbdCommand(c1, c2) {
+ if (Array.isArray(c1)) {
+ return dEqual(c1[0], c1[1]);
+ }
return dEqual(c1, c2);
} |
5b867ada55e138a1a73da610dc2dec4c98c8b442 | app/scripts/models/player.js | app/scripts/models/player.js | // An abstract base model representing a player in a game
function Player(args) {
// The name of the player (e.g. 'Human 1')
this.name = args.name;
// The player's chip color (supported colors are black, blue, and red)
this.color = args.color;
// The player's total number of wins across all games
this.score = 0;
}
export default Player;
| // An abstract base model representing a player in a game
class Player {
constructor(args) {
// The name of the player (e.g. 'Human 1')
this.name = args.name;
// The player's chip color (supported colors are black, blue, and red)
this.color = args.color;
// The player's total number of wins across all games
this.score = 0;
}
}
export default Player;
| Convert Player base model to ES6 class | Convert Player base model to ES6 class
| JavaScript | mit | caleb531/connect-four | ---
+++
@@ -1,11 +1,15 @@
// An abstract base model representing a player in a game
-function Player(args) {
- // The name of the player (e.g. 'Human 1')
- this.name = args.name;
- // The player's chip color (supported colors are black, blue, and red)
- this.color = args.color;
- // The player's total number of wins across all games
- this.score = 0;
+class Player {
+
+ constructor(args) {
+ // The name of the player (e.g. 'Human 1')
+ this.name = args.name;
+ // The player's chip color (supported colors are black, blue, and red)
+ this.color = args.color;
+ // The player's total number of wins across all games
+ this.score = 0;
+ }
+
}
export default Player; |
3d9fc84c280ed14cfd980ca443c30a4a30ecffd5 | lib/assets/javascripts/cartodb/models/tile_json_model.js | lib/assets/javascripts/cartodb/models/tile_json_model.js | /**
* Model to representing a TileJSON endpoint
* See https://github.com/mapbox/tilejson-spec/tree/master/2.1.0 for details
*/
cdb.admin.TileJSON = cdb.core.Model.extend({
idAttribute: 'url',
url: function() {
return this.get('url');
},
save: function() {
// no-op, obviously no write privileges ;)
},
newTileLayer: function() {
if (!this._isFetched()) throw new Error('no tiles, have fetch been called and returned a successful resultset?');
var layer = new cdb.admin.TileLayer({
urlTemplate: this._urlTemplate(),
name: this.get('name'),
attribution: this.get('attribution'),
maxZoom: this.get('maxzoom'),
minZoom: this.get('minzoom'),
bounding_boxes: this.get('bounds')
});
return layer;
},
_isFetched: function() {
return this.get('tiles').length > 0;
},
_urlTemplate: function() {
return this.get('tiles')[0];
}
});
| /**
* Model to representing a TileJSON endpoint
* See https://github.com/mapbox/tilejson-spec/tree/master/2.1.0 for details
*/
cdb.admin.TileJSON = cdb.core.Model.extend({
idAttribute: 'url',
url: function() {
return this.get('url');
},
save: function() {
// no-op, obviously no write privileges ;)
},
newTileLayer: function() {
if (!this._isFetched()) throw new Error('no tiles, have fetch been called and returned a successful resultset?');
var layer = new cdb.admin.TileLayer({
urlTemplate: this._urlTemplate(),
name: this._name(),
attribution: this.get('attribution'),
maxZoom: this.get('maxzoom'),
minZoom: this.get('minzoom'),
bounding_boxes: this.get('bounds')
});
return layer;
},
_isFetched: function() {
return this.get('tiles').length > 0;
},
_urlTemplate: function() {
return this.get('tiles')[0];
},
_name: function() {
return this.get('name') || this.get('description');
}
});
| Set description as fallback for name | Set description as fallback for name
Both are optional, so might be empty or undefined, for which depending
on use-case might need to handle (for basemap will get a custom name)
| JavaScript | bsd-3-clause | future-analytics/cartodb,splashblot/dronedb,dbirchak/cartodb,DigitalCoder/cartodb,dbirchak/cartodb,thorncp/cartodb,raquel-ucl/cartodb,DigitalCoder/cartodb,DigitalCoder/cartodb,raquel-ucl/cartodb,thorncp/cartodb,splashblot/dronedb,future-analytics/cartodb,DigitalCoder/cartodb,nyimbi/cartodb,CartoDB/cartodb,nuxcode/cartodb,nyimbi/cartodb,CartoDB/cartodb,UCL-ShippingGroup/cartodb-1,future-analytics/cartodb,CartoDB/cartodb,UCL-ShippingGroup/cartodb-1,nyimbi/cartodb,nuxcode/cartodb,codeandtheory/cartodb,dbirchak/cartodb,UCL-ShippingGroup/cartodb-1,CartoDB/cartodb,dbirchak/cartodb,splashblot/dronedb,bloomberg/cartodb,splashblot/dronedb,nyimbi/cartodb,splashblot/dronedb,codeandtheory/cartodb,raquel-ucl/cartodb,bloomberg/cartodb,dbirchak/cartodb,raquel-ucl/cartodb,thorncp/cartodb,future-analytics/cartodb,nuxcode/cartodb,nyimbi/cartodb,DigitalCoder/cartodb,bloomberg/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,bloomberg/cartodb,UCL-ShippingGroup/cartodb-1,future-analytics/cartodb,UCL-ShippingGroup/cartodb-1,raquel-ucl/cartodb,nuxcode/cartodb,CartoDB/cartodb,bloomberg/cartodb,thorncp/cartodb,thorncp/cartodb,nuxcode/cartodb,codeandtheory/cartodb | ---
+++
@@ -19,7 +19,7 @@
var layer = new cdb.admin.TileLayer({
urlTemplate: this._urlTemplate(),
- name: this.get('name'),
+ name: this._name(),
attribution: this.get('attribution'),
maxZoom: this.get('maxzoom'),
minZoom: this.get('minzoom'),
@@ -35,5 +35,9 @@
_urlTemplate: function() {
return this.get('tiles')[0];
+ },
+
+ _name: function() {
+ return this.get('name') || this.get('description');
}
}); |
145b8c979cb7800cf3eb6ff2ad30037e4b19c51d | applications/firefox/user.js | applications/firefox/user.js | user_pref("accessibility.typeaheadfind", 1);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtab.url", "https://www.google.co.nz");
user_pref("browser.pocket.enabled", false);
user_pref("browser.tabs.tabClipWidth", 1);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("general.useragent.locale", "en-GB");
user_pref("keyword.enabled", true);
user_pref("layout.spellcheckDefault", 2);
user_pref("loop.enabled", false);
user_pref("plugins.click_to_play", true);
user_pref("spellchecker.dictionary", "en-GB");
user_pref("toolkit.telemetry.enabled", false);
| user_pref("browser.ctrlTab.previews", true);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtab.url", "https://www.google.co.nz");
user_pref("browser.pocket.enabled", false);
user_pref("browser.tabs.tabClipWidth", 1);
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("general.useragent.locale", "en-GB");
user_pref("layout.spellcheckDefault", 2);
user_pref("loop.enabled", false);
user_pref("plugins.click_to_play", true);
user_pref("spellchecker.dictionary", "en-GB");
user_pref("toolkit.telemetry.enabled", false);
| Tidy up firefox prefs, and added CTRL+TAB through tabs :) | Tidy up firefox prefs, and added CTRL+TAB through tabs :)
| JavaScript | mit | craighurley/dotfiles,craighurley/dotfiles,craighurley/dotfiles | ---
+++
@@ -1,4 +1,4 @@
-user_pref("accessibility.typeaheadfind", 1);
+user_pref("browser.ctrlTab.previews", true);
user_pref("browser.fixup.alternate.enabled", false);
user_pref("browser.newtab.url", "https://www.google.co.nz");
user_pref("browser.pocket.enabled", false);
@@ -6,7 +6,6 @@
user_pref("datareporting.healthreport.service.enabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("general.useragent.locale", "en-GB");
-user_pref("keyword.enabled", true);
user_pref("layout.spellcheckDefault", 2);
user_pref("loop.enabled", false);
user_pref("plugins.click_to_play", true); |
af6314d64914d4450ceabb197b2c451e97ac2a62 | server/websocket.js | server/websocket.js |
var ds = require('./discovery')
var rb = require('./rubygems')
var sc = require('./scrape')
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({host: 'localhost', port: 3001})
var clients = {}
wss.on('connection', (ws) => {
ws.on('message', (data) => {
var req = JSON.parse(data)
if (req.message === 'ping') {
ws.id = req.id
clients[ws.id] = ws
clients[ws.id].send(JSON.stringify({message: 'pong'}))
}
else if (req.message === 'gems') {
ds.run(req.gem,
(gem) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({message: 'node', gem: gem}))
},
(err, gems) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({message: 'done', gems: gems}))
}
)
}
else if (req.message === 'owners') {
sc.owners('gems/' + req.gem, (err, owners) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({
message: 'owners', owners: owners, gem: req.gem
}))
})
}
})
ws.on('close', () => delete clients[ws.id])
})
exports.clients = clients
|
var ds = require('./discovery')
var rb = require('./rubygems')
var sc = require('./scrape')
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({host: 'localhost', port: 3001})
var clients = {}
wss.on('connection', (ws) => {
ws.on('message', (data) => {
var req = JSON.parse(data)
if (req.message === 'ping') {
ws.id = req.id
clients[ws.id] = ws
clients[ws.id].send(JSON.stringify({message: 'pong', id: ws.id}))
}
else if (req.message === 'gems') {
ds.run(req.gem,
(gem) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({message: 'node', gem: gem}))
},
(err, gems) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({message: 'done', gems: gems}))
}
)
}
else if (req.message === 'owners') {
sc.owners('gems/' + req.gem, (err, owners) => {
if (!clients[req.id]) {
return true
}
clients[req.id].send(JSON.stringify({
message: 'owners', owners: owners, gem: req.gem
}))
})
}
})
ws.on('close', () => delete clients[ws.id])
})
exports.clients = clients
| Send back the socket id with the pong message | Send back the socket id with the pong message
| JavaScript | mit | simov/rubinho,simov/rubinho | ---
+++
@@ -16,7 +16,7 @@
if (req.message === 'ping') {
ws.id = req.id
clients[ws.id] = ws
- clients[ws.id].send(JSON.stringify({message: 'pong'}))
+ clients[ws.id].send(JSON.stringify({message: 'pong', id: ws.id}))
}
else if (req.message === 'gems') {
ds.run(req.gem, |
976aed3d7a14c176e369ceb600baf61260daeed2 | packages/shared/lib/api/logs.js | packages/shared/lib/api/logs.js | export const queryLogs = ({ Page, PageSize } = {}) => ({
method: 'get',
url: 'logs/auth',
params: { Page, PageSize }
});
export const clearLogs = () => ({
method: 'delete',
url: 'logs/auth'
});
| export const queryLogs = (params) => ({
method: 'get',
url: 'logs/auth',
params
});
export const clearLogs = () => ({
method: 'delete',
url: 'logs/auth'
});
| Allow queryLogs to be without params | Allow queryLogs to be without params
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -1,7 +1,7 @@
-export const queryLogs = ({ Page, PageSize } = {}) => ({
+export const queryLogs = (params) => ({
method: 'get',
url: 'logs/auth',
- params: { Page, PageSize }
+ params
});
export const clearLogs = () => ({ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.