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 |
|---|---|---|---|---|---|---|---|---|---|---|
67a92bb20333d5aca9d8b02f76ba9c6d94795fd6 | src/Footer.js | src/Footer.js | import React from 'react';
import './scss/footer.scss';
const Footer = () => {
return (
<footer>
<p>© 2016 Michael Kohler - JavaScript frontend and backend developer
with a passion for Web Standards</p>
</footer>
);
};
export default Footer;
| import React from 'react';
import './scss/footer.scss';
const Footer = () => {
return (
<footer>
<p>© 2016 Michael Kohler - Data accurate from 2013 onwards, before some are missing..</p>
</footer>
);
};
export default Footer;
| Add data accuracy note in footer | Add data accuracy note in footer
| JavaScript | mpl-2.0 | MichaelKohler/where,MichaelKohler/where | ---
+++
@@ -4,8 +4,7 @@
const Footer = () => {
return (
<footer>
- <p>© 2016 Michael Kohler - JavaScript frontend and backend developer
- with a passion for Web Standards</p>
+ <p>© 2016 Michael Kohler - Data accurate from 2013 onwards, before some are missing..</p>
</footer>
);
}; |
dae0c1ce82b2c0abfde8b633728dd393b094e0c1 | lib/widgets/host_details_panel.js | lib/widgets/host_details_panel.js | 'use strict';
let blessed = require('blessed');
let _ = require('lodash');
let config = require('../../config/config');
module.exports = function () {
let hostDetailsPanel = blessed.list({
top: 5,
bottom: 5,
left: '30%',
tags: true,
border: {type: 'line'},
keys: true,
scrollable: true,
style: config.styles.main
});
hostDetailsPanel.updateItems = function (host) {
let items = [];
_.forEach(host, function (val, key) {
if (_.isArray(val)) val = val.join(', ');
let content = '{bold}' + key + '{/bold} : ' + val + '\n';
items.push(content);
});
this.setItems(items);
};
return hostDetailsPanel;
};
| 'use strict';
let blessed = require('blessed');
let _ = require('lodash');
let config = require('../../config/config');
module.exports = function () {
let hostDetailsPanel = blessed.list({
top: 5,
bottom: 5,
left: '30%',
tags: true,
border: {type: 'line'},
keys: true,
scrollable: true,
style: config.styles.main
});
hostDetailsPanel.updateItems = function (host) {
let items = [];
_.forEach(host, function (val, key) {
if (_.isArray(val)) val = val.join(', ');
key = key[0].toUpperCase() + key.slice(1);
let content = '{bold}' + key + '{/bold} : ' + val + '\n';
items.push(content);
});
this.setItems(items);
};
return hostDetailsPanel;
};
| Fix keys case into details panel | Fix keys case into details panel
| JavaScript | mit | etissieres/ssh-config-ui | ---
+++
@@ -21,6 +21,7 @@
let items = [];
_.forEach(host, function (val, key) {
if (_.isArray(val)) val = val.join(', ');
+ key = key[0].toUpperCase() + key.slice(1);
let content = '{bold}' + key + '{/bold} : ' + val + '\n';
items.push(content);
}); |
a2e6df5e9dee79f636b21016c8a5b1b810679e19 | consumer-ui/src/app/config/angular-translate.js | consumer-ui/src/app/config/angular-translate.js | angular.module('nnConsumerUi')
.config(function($translateProvider) {
$translateProvider.translations('fi', {
'REQUIRED_FIELD': 'Pakollinen kenttä',
'CHARACTERS_LEFT': 'Merkkiä jäljellä',
'CHOOSE_FILE': 'Valitse tiedosto',
'PRINT_BUTTON': 'Tulosta',
'SEND_MAIL_BUTTON': 'Lähetä sähköpostiin',
'MAIL_SENT_TEXT': 'Sähköposti lähetetty'
});
$translateProvider.translations('sv', {
'REQUIRED_FIELD': 'Obligatoriskt fält',
'CHARACTERS_LEFT': 'Tecken kvar',
'CHOOSE_FILE': 'Välj fil',
'PRINT_BUTTON': 'Skriv ut',
'SEND_MAIL_BUTTON': 'Skicka till e-post',
'MAIL_SENT_TEXT': 'E-post skickad'
});
$translateProvider.translations('en', {
'REQUIRED_FIELD': 'Required field',
'CHARACTERS_LEFT': 'Characters left',
'CHOOSE_FILE': 'Choose file',
'PRINT_BUTTON': 'Print',
'SEND_MAIL_BUTTON': 'Send to e-mail',
'MAIL_SENT_TEXT': 'E-mail sent'
});
$translateProvider.preferredLanguage('fi');
$translateProvider.useSanitizeValueStrategy(null);
});
| angular.module('nnConsumerUi')
.config(function($translateProvider) {
$translateProvider.translations('fi', {
'REQUIRED_FIELD': 'Pakollinen kenttä',
'CHARACTERS_LEFT': 'Merkkiä jäljellä',
'CHOOSE_FILE': 'Valitse tiedosto',
'PRINT_BUTTON': 'Tulosta',
'SEND_MAIL_BUTTON': 'Lähetä sähköpostiin',
'MAIL_SENT_TEXT': 'Sähköposti lähetetty',
'NEXT_TEXT': 'Seuraava'
});
$translateProvider.translations('sv', {
'REQUIRED_FIELD': 'Obligatoriskt fält',
'CHARACTERS_LEFT': 'Tecken kvar',
'CHOOSE_FILE': 'Välj fil',
'PRINT_BUTTON': 'Skriv ut',
'SEND_MAIL_BUTTON': 'Skicka till e-post',
'MAIL_SENT_TEXT': 'E-post skickad',
'NEXT_TEXT': 'Nästa'
});
$translateProvider.translations('en', {
'REQUIRED_FIELD': 'Required field',
'CHARACTERS_LEFT': 'Characters left',
'CHOOSE_FILE': 'Choose file',
'PRINT_BUTTON': 'Print',
'SEND_MAIL_BUTTON': 'Send to e-mail',
'MAIL_SENT_TEXT': 'E-mail sent',
'NEXT_TEXT': 'Next'
});
$translateProvider.preferredLanguage('fi');
$translateProvider.useSanitizeValueStrategy(null);
});
| Add missing translation to consumer-ui | Add missing translation to consumer-ui
| JavaScript | mit | nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja,nordsoftware/nettineuvoja | ---
+++
@@ -6,7 +6,8 @@
'CHOOSE_FILE': 'Valitse tiedosto',
'PRINT_BUTTON': 'Tulosta',
'SEND_MAIL_BUTTON': 'Lähetä sähköpostiin',
- 'MAIL_SENT_TEXT': 'Sähköposti lähetetty'
+ 'MAIL_SENT_TEXT': 'Sähköposti lähetetty',
+ 'NEXT_TEXT': 'Seuraava'
});
$translateProvider.translations('sv', {
@@ -15,7 +16,8 @@
'CHOOSE_FILE': 'Välj fil',
'PRINT_BUTTON': 'Skriv ut',
'SEND_MAIL_BUTTON': 'Skicka till e-post',
- 'MAIL_SENT_TEXT': 'E-post skickad'
+ 'MAIL_SENT_TEXT': 'E-post skickad',
+ 'NEXT_TEXT': 'Nästa'
});
$translateProvider.translations('en', {
@@ -24,7 +26,8 @@
'CHOOSE_FILE': 'Choose file',
'PRINT_BUTTON': 'Print',
'SEND_MAIL_BUTTON': 'Send to e-mail',
- 'MAIL_SENT_TEXT': 'E-mail sent'
+ 'MAIL_SENT_TEXT': 'E-mail sent',
+ 'NEXT_TEXT': 'Next'
});
$translateProvider.preferredLanguage('fi'); |
5e456f6017c550a56d685963f007b8f73563fb57 | tasks/jscs.js | tasks/jscs.js | "use strict";
var Vow = require( "vow" );
module.exports = function( grunt ) {
var filter = Array.prototype.filter,
JSCS = require( "./lib/jscs" ).init( grunt );
grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() {
var done = this.async(),
options = this.options({
config: null
}),
jscs = new JSCS( options ),
checks = this.filesSrc.map(function( path ) {
return jscs.check( path );
});
Vow.allResolved( checks ).spread(function() {
// Filter unsuccessful promises
var results = filter.call( arguments, function( promise ) {
return promise.isFulfilled();
// Make array of errors
}).map(function( promise ) {
return promise.valueOf()[ 0 ];
});
jscs.setErrors( results ).report().notify();
done( options.force || !jscs.count() );
});
});
};
| "use strict";
var Vow = require( "vow" );
module.exports = function( grunt ) {
var filter = Array.prototype.filter,
JSCS = require( "./lib/jscs" ).init( grunt );
grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() {
var done = this.async(),
options = this.options({
// null is a default value, but its equivalent to `true`,
// with this way it's easy to distinguish specified value
config: null
}),
jscs = new JSCS( options ),
checks = this.filesSrc.map(function( path ) {
return jscs.check( path );
});
Vow.allResolved( checks ).spread(function() {
// Filter unsuccessful promises
var results = filter.call( arguments, function( promise ) {
return promise.isFulfilled();
// Make array of errors
}).map(function( promise ) {
return promise.valueOf()[ 0 ];
});
jscs.setErrors( results ).report().notify();
done( options.force || !jscs.count() );
});
});
};
| Add comment for null as default value | Add comment for null as default value
| JavaScript | mit | markelog/grunt-checker | ---
+++
@@ -10,6 +10,9 @@
grunt.registerMultiTask( "jscs", "JavaScript Code Style checker", function() {
var done = this.async(),
options = this.options({
+
+ // null is a default value, but its equivalent to `true`,
+ // with this way it's easy to distinguish specified value
config: null
}),
|
5525d5f5d22faf3a65324de927de277cbb877e94 | app/utils/george-foreman.js | app/utils/george-foreman.js | export default class GeorgeForeman {
constructor() {
}
}
| export default class GeorgeForeman {
constructor() {
this.generation = GeorgeForeman.addGeneration();
}
name() {
return `George Foreman ${this.formatGeneration()}`;
}
formatGeneration() {
switch (this.generation) {
case 2:
return "II";
default:
return "";
}
}
static addGeneration() {
if(!this.generation && this.generation !== 1) {
this.generation = 1;
} else {
this.generation += 1;
}
return this.generation;
}
}
| Implement class/static method for George | Implement class/static method for George
| JavaScript | mit | Riverside-Ruby/learning-es6,Riverside-Ruby/learning-es6 | ---
+++
@@ -1,4 +1,28 @@
export default class GeorgeForeman {
constructor() {
+ this.generation = GeorgeForeman.addGeneration();
}
+
+ name() {
+ return `George Foreman ${this.formatGeneration()}`;
+ }
+
+ formatGeneration() {
+ switch (this.generation) {
+ case 2:
+ return "II";
+ default:
+ return "";
+ }
+ }
+
+ static addGeneration() {
+ if(!this.generation && this.generation !== 1) {
+ this.generation = 1;
+ } else {
+ this.generation += 1;
+ }
+ return this.generation;
+ }
+
} |
a89ea164e9bc1a883283bd9c610a8f0738c53828 | Kwc/Statistics/OptBox/Component.defer.js | Kwc/Statistics/OptBox/Component.defer.js | var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var cookieOpt = require('kwf/cookie-opt');
onReady.onRender('.kwcClass', function (el, config) {
if (!cookieOpt.isSetOpt()) {
if (config.showBanner) {
setTimeout(function(){
$('body').addClass('kwfUp-showCookieBanner');
}, 1000);
}
el.show();
el.find('.kwcBem__accept').click(function(e) {
e.preventDefault();
cookieOpt.setOpt('in');
el.hide();
$('body').removeClass('kwfUp-showCookieBanner');
});
}
});
cookieOpt.onOptChange(function(value) {
$('body').find('.kwcClass').hide();
});
| var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var cookieOpt = require('kwf/cookie-opt');
onReady.onRender('.kwcClass', function (el, config) {
if (!cookieOpt.isSetOpt()) {
if (config.showBanner) {
setTimeout(function(){
$('body').addClass('kwfUp-showCookieBanner');
onReady.callOnContentReady($('body'), { action: 'widthChange' });
}, 1000);
}
el.show();
el.find('.kwcBem__accept').click(function(e) {
e.preventDefault();
cookieOpt.setOpt('in');
el.hide();
$('body').removeClass('kwfUp-showCookieBanner');
onReady.callOnContentReady($('body'), { action: 'widthChange' });
});
}
});
cookieOpt.onOptChange(function(value) {
$('body').find('.kwcClass').hide();
});
| Call resizeevent on body when cookiebanner change visibility Make it possible to change something in web after the visibility of the cookiebanner changed. For example to move fixed content, if the cookiebanner appears on top of the page. | Call resizeevent on body when cookiebanner change visibility
Make it possible to change something in web after the visibility of the cookiebanner changed. For example to move fixed content, if the cookiebanner appears on top of the page.
| JavaScript | bsd-2-clause | koala-framework/koala-framework,koala-framework/koala-framework | ---
+++
@@ -7,6 +7,7 @@
if (config.showBanner) {
setTimeout(function(){
$('body').addClass('kwfUp-showCookieBanner');
+ onReady.callOnContentReady($('body'), { action: 'widthChange' });
}, 1000);
}
el.show();
@@ -15,6 +16,7 @@
cookieOpt.setOpt('in');
el.hide();
$('body').removeClass('kwfUp-showCookieBanner');
+ onReady.callOnContentReady($('body'), { action: 'widthChange' });
});
}
}); |
b0b89a45029eff805828dda77c1e2c19ff7b991e | gulpfile.js | gulpfile.js | var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var nodemon = require('nodemon');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('compile-js', function() {
return browserify('client/main.js')
.transform(babelify)
.bundle()
.pipe(source('scripts.min.js'))
.pipe(buffer())
.pipe(gulpif(process.env.NODE_ENV === 'production', uglify()))
.pipe(gulp.dest('public'))
}
);
gulp.task('server', ['compile-js'], function() {
browserSync.create().init({
files: ['public/**'],
port: 3001,
proxy: 'http://localhost:3000',
ui: { port: 3002 },
open: false,
});
gulp.watch(['client/*.js'], ['compile-js']);
return nodemon({
script: 'server/index.js',
env: { 'NODE_ENV': 'development' },
watch: ['server/**/*'],
});
});
| var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var nodemon = require('nodemon');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('compile-js', function() {
return browserify('client/main.js')
.transform(babelify)
.bundle()
.pipe(source('scripts.min.js'))
.pipe(buffer())
.pipe(gulpif(process.env.NODE_ENV === 'production', uglify()))
.pipe(gulp.dest('public'))
}
);
gulp.task('server', ['compile-js'], function() {
browserSync.create().init({
files: ['public/**'],
port: 3001,
proxy: 'http://localhost:3000',
ui: { port: 3002 },
open: false,
});
gulp.watch(['client/**/*.js'], ['compile-js']);
return nodemon({
script: 'server/index.js',
env: { 'NODE_ENV': 'development' },
watch: ['server/**/*'],
});
});
| Fix Gulp not watching subdirectories of client | Fix Gulp not watching subdirectories of client
| JavaScript | mit | DevelopersGuild/lollipop-fantastyland,DevelopersGuild/lollipop-fantastyland | ---
+++
@@ -29,7 +29,7 @@
open: false,
});
- gulp.watch(['client/*.js'], ['compile-js']);
+ gulp.watch(['client/**/*.js'], ['compile-js']);
return nodemon({
script: 'server/index.js', |
85cd4f35e321082c407bb41ab6ea6f22b7bf1017 | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var config = {
namespace: 'braintree',
src: {
js: {
all: './src/**/*.js',
main: './index.js',
watch: './public/js/**/*.js',
output: 'app.built.js',
min: 'app.built.min.js'
}
},
dist: {js: 'dist/js'}
};
gulp.task('js', function () {
return browserify(config.src.js.main)
.bundle()
.pipe(source(config.src.js.output))
.pipe(streamify(size()))
.pipe(gulp.dest(config.dist.js))
.pipe(streamify(uglify()))
.pipe(streamify(size()))
.pipe(rename(config.src.js.min))
.pipe(gulp.dest(config.dist.js));
});
gulp.task('watch', ['js'], function () {
gulp.watch(config.src.js.watch, ['js']);
});
gulp.task('clean', function (done) {
del([config.dist.js], done);
});
gulp.task('build', ['clean', 'js']);
| 'use strict';
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');
var config = {
src: {
js: {
all: './src/**/*.js',
main: './index.js',
watch: './public/js/**/*.js',
output: 'app.built.js',
min: 'app.built.min.js'
}
},
options: {
standalone: 'creditCardType'
},
dist: {js: 'dist/js'}
};
gulp.task('js', function () {
return browserify(config.src.js.main, config.options)
.bundle()
.pipe(source(config.src.js.output))
.pipe(streamify(size()))
.pipe(gulp.dest(config.dist.js))
.pipe(streamify(uglify()))
.pipe(streamify(size()))
.pipe(rename(config.src.js.min))
.pipe(gulp.dest(config.dist.js));
});
gulp.task('watch', ['js'], function () {
gulp.watch(config.src.js.watch, ['js']);
});
gulp.task('clean', function (done) {
del([config.dist.js], done);
});
gulp.task('build', ['clean', 'js']);
| Add standalone field to browserify build | Add standalone field to browserify build
closes #29
| JavaScript | mit | braintree/credit-card-type | ---
+++
@@ -10,7 +10,6 @@
var del = require('del');
var config = {
- namespace: 'braintree',
src: {
js: {
all: './src/**/*.js',
@@ -20,11 +19,14 @@
min: 'app.built.min.js'
}
},
+ options: {
+ standalone: 'creditCardType'
+ },
dist: {js: 'dist/js'}
};
gulp.task('js', function () {
- return browserify(config.src.js.main)
+ return browserify(config.src.js.main, config.options)
.bundle()
.pipe(source(config.src.js.output))
.pipe(streamify(size())) |
9839b8526e45a1f5d8b99ffab99a37e06f3f6598 | client/js/directives/header-entry-directive.js | client/js/directives/header-entry-directive.js | "use strict";
angular.module("hikeio").
directive("headerEntry", function() {
return {
scope: {
align: "@",
label: "@",
url: "@"
},
template: "<a href='{{url}}'>" +
"<div style='float:{{align}}' >" +
"<div class='header-separator' data-ng-show='align == \"right\"'></div>" +
"<div class='header-entry' data-ng-transclude>" +
"<span class='label' data-ng-show='label'>{{label}}</span>" +
"</div>" +
"<div class='header-separator' data-ng-show='align == \"left\"'></div>" +
"</div>" +
"</a>",
transclude: true
};
}); | "use strict";
angular.module("hikeio").
directive("headerEntry", function() {
return {
scope: {
align: "@",
label: "@",
url: "@"
},
template: "<a href='{{url}}'>" +
"<div data-ng-style='{float:align}' >" +
"<div class='header-separator' data-ng-show='align == \"right\"'></div>" +
"<div class='header-entry' data-ng-transclude>" +
"<span class='label' data-ng-show='label'>{{label}}</span>" +
"</div>" +
"<div class='header-separator' data-ng-show='align == \"left\"'></div>" +
"</div>" +
"</a>",
transclude: true
};
}); | Use ng-style to fix header float issue on ie10. | Use ng-style to fix header float issue on ie10.
| JavaScript | mit | zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io | ---
+++
@@ -9,7 +9,7 @@
url: "@"
},
template: "<a href='{{url}}'>" +
- "<div style='float:{{align}}' >" +
+ "<div data-ng-style='{float:align}' >" +
"<div class='header-separator' data-ng-show='align == \"right\"'></div>" +
"<div class='header-entry' data-ng-transclude>" +
"<span class='label' data-ng-show='label'>{{label}}</span>" + |
6d21a74c5da48b36cde147993fe9d0e8154a9457 | gulpfile.js | gulpfile.js | var elixir = require('laravel-elixir');
require('laravel-elixir-vue');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss')
.webpack('app.js');
});
| const elixir = require('laravel-elixir');
require('laravel-elixir-vue');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss')
.webpack('app.js');
});
| Use const instead of var in require | Use const instead of var in require
| JavaScript | agpl-3.0 | zeropingheroes/lanyard,slimkit/thinksns-plus,zhiyicx/thinksns-plus,zeropingheroes/lanyard,cbnuke/FilesCollection,remxcode/laravel-base,remxcode/laravel-base,beautifultable/phpwind,zeropingheroes/lanyard,orckid-lab/dashboard,cbnuke/FilesCollection,hackel/laravel,zhiyicx/thinksns-plus,hackel/laravel,tinywitch/laravel,slimkit/thinksns-plus,beautifultable/phpwind,hackel/laravel,orckid-lab/dashboard | ---
+++
@@ -1,4 +1,4 @@
-var elixir = require('laravel-elixir');
+const elixir = require('laravel-elixir');
require('laravel-elixir-vue');
|
8f4e0f16a0985578c49462475df6abf89540c673 | gulpfile.js | gulpfile.js | /*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey
* http://scratchdisk.com/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
var gulp = require('gulp'),
qunit = require('gulp-qunit');
gulp.task('test', function() {
return gulp.src('./test/index.html')
.pipe(qunit());
});
| /*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey
* http://scratchdisk.com/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
var gulp = require('gulp'),
qunit = require('gulp-qunit');
gulp.task('test', function() {
return gulp.src('./test/index.html')
.pipe(qunit({ timeout: 10 }));
});
| Increase QUnit timeout to 10s, as Travis doesn't finish in time. | Increase QUnit timeout to 10s, as Travis doesn't finish in time.
| JavaScript | mit | lehni/paper.js,iconexperience/paper.js,lehni/paper.js,iconexperience/paper.js,lehni/paper.js,iconexperience/paper.js | ---
+++
@@ -15,5 +15,5 @@
gulp.task('test', function() {
return gulp.src('./test/index.html')
- .pipe(qunit());
+ .pipe(qunit({ timeout: 10 }));
}); |
845280ecb6b8ad4c97ca248a6f7322e1fd38da25 | lib/api.js | lib/api.js | var parse = require('./parse');
module.exports = function(data) {
this.token = data.token;
};
module.exports.prototype = {
get: function() {
query = parse.query(arguments);
callback = parse.callback(arguments);
},
post: function() {
},
put: function() {
},
del: function() {
}
};
| var parse = require('./parse');
module.exports = function(data) {
this.token = data.token;
};
module.exports.prototype = {
get: function() {
query = parse.query(arguments);
callback = parse.callback(arguments);
},
post: function() {
query = parse.query(arguments);
callback = parse.callback(arguments);
},
put: function() {
query = parse.query(arguments);
callback = parse.callback(arguments);
},
del: function() {
query = parse.query(arguments);
callback = parse.callback(arguments);
}
};
| Add query and callback parsing to get/post/put/del | Add query and callback parsing to get/post/put/del
| JavaScript | apache-2.0 | phonegap/node-phonegap-build-api | ---
+++
@@ -10,10 +10,16 @@
callback = parse.callback(arguments);
},
post: function() {
+ query = parse.query(arguments);
+ callback = parse.callback(arguments);
},
put: function() {
+ query = parse.query(arguments);
+ callback = parse.callback(arguments);
},
del: function() {
+ query = parse.query(arguments);
+ callback = parse.callback(arguments);
}
};
|
1c1f3d90b4b66f335351ae4d66c86ca98cb8b339 | packages/react-app-rewired/index.js | packages/react-app-rewired/index.js | const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf("babel-loader/") != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
| const path = require('path');
const babelLoaderMatcher = function(rule) {
return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1;
}
const getLoader = function(rules, matcher) {
var loader;
rules.some(rule => {
return loader = matcher(rule)
? rule
: getLoader(rule.use || rule.oneOf || [], matcher);
});
return loader;
};
const getBabelLoader = function(rules) {
return getLoader(rules, babelLoaderMatcher);
}
const injectBabelPlugin = function(pluginName, config) {
const loader = getBabelLoader(config.module.rules);
if (!loader) {
console.log("babel-loader not found");
return config;
}
loader.options.plugins = [pluginName].concat(loader.options.plugins || []);
return config;
};
module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
| Fix plugin injection on Windows | Fix plugin injection on Windows
| JavaScript | mit | timarney/react-app-rewired,timarney/react-app-rewired | ---
+++
@@ -1,5 +1,7 @@
+const path = require('path');
+
const babelLoaderMatcher = function(rule) {
- return rule.loader && rule.loader.indexOf("babel-loader/") != -1;
+ return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1;
}
const getLoader = function(rules, matcher) { |
893bfb091ed0e6f9f46672ca280334171098defe | src/config.js | src/config.js | let userConfig;
try {
userConfig = require('../config');
} catch (e) {
throw new Error(`Config file could not be found or read! The error given was: ${e.message}`);
}
const defaultConfig = {
"token": null,
"mailGuildId": null,
"mainGuildId": null,
"logChannelId": null,
"prefix": "!",
"snippetPrefix": "!!",
"status": "Message me for help!",
"responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.",
"inboxServerPermission": null,
"alwaysReply": false,
"alwaysReplyAnon": false,
"useNicknames": false,
"ignoreAccidentalThreads": false,
"enableGreeting": false,
"greetingMessage": "The message the bot sends to a new user",
"greetingAttachment": "Put a file path here",
"port": 8890,
"url": null
};
const finalConfig = Object.assign({}, defaultConfig);
for (const [prop, value] of Object.entries(userConfig)) {
if (! defaultConfig.hasOwnProperty(prop)) {
throw new Error(`Invalid option: ${prop}`);
}
finalConfig[prop] = value;
}
if (! finalConfig.token) throw new Error('Missing token!');
if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!');
if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!');
module.exports = finalConfig;
| let userConfig;
try {
userConfig = require('../config');
} catch (e) {
throw new Error(`Config file could not be found or read! The error given was: ${e.message}`);
}
const defaultConfig = {
"token": null,
"mailGuildId": null,
"mainGuildId": null,
"logChannelId": null,
"prefix": "!",
"snippetPrefix": "!!",
"status": "Message me for help!",
"responseMessage": "Thank you for your message! Our mod team will reply to you here as soon as possible.",
"inboxServerPermission": null,
"alwaysReply": false,
"alwaysReplyAnon": false,
"useNicknames": false,
"ignoreAccidentalThreads": false,
"enableGreeting": false,
"greetingMessage": null,
"greetingAttachment": null,
"port": 8890,
"url": null
};
const finalConfig = Object.assign({}, defaultConfig);
for (const [prop, value] of Object.entries(userConfig)) {
if (! defaultConfig.hasOwnProperty(prop)) {
throw new Error(`Invalid option: ${prop}`);
}
finalConfig[prop] = value;
}
if (! finalConfig.token) throw new Error('Missing token!');
if (! finalConfig.mailGuildId) throw new Error('Missing mailGuildId (inbox server id)!');
if (! finalConfig.mainGuildId) throw new Error('Missing mainGuildId!');
module.exports = finalConfig;
| Set greeting defaults to null | Set greeting defaults to null
| JavaScript | mit | Dragory/modmailbot | ---
+++
@@ -25,8 +25,8 @@
"ignoreAccidentalThreads": false,
"enableGreeting": false,
- "greetingMessage": "The message the bot sends to a new user",
- "greetingAttachment": "Put a file path here",
+ "greetingMessage": null,
+ "greetingAttachment": null,
"port": 8890,
"url": null |
4a84fb7aa778541683143cad87f442defe50e001 | app/scripts/components/slurm/details/module.js | app/scripts/components/slurm/details/module.js | import slurmAllocationDetailsDialog from './slurm-allocation-details-dialog';
import slurmAllocationUsageChart from './slurm-allocation-usage-chart';
import slurmAllocationUsageTable from './slurm-allocation-usage-table';
import SlurmAllocationUsageService from './slurm-allocation-usage-service';
import { SlurmAllocationSummary } from './SlurmAllocationSummary';
import * as ResourceSummary from '@waldur/resource/summary/registry';
export default module => {
ResourceSummary.register('Slurm.Allocation', SlurmAllocationSummary);
module.component('slurmAllocationDetailsDialog', slurmAllocationDetailsDialog);
module.directive('slurmAllocationUsageChart', slurmAllocationUsageChart);
module.component('slurmAllocationUsageTable', slurmAllocationUsageTable);
module.service('SlurmAllocationUsageService', SlurmAllocationUsageService);
};
| import slurmAllocationDetailsDialog from './slurm-allocation-details-dialog';
import slurmAllocationUsageChart from './slurm-allocation-usage-chart';
import slurmAllocationUsageTable from './slurm-allocation-usage-table';
import SlurmAllocationUsageService from './slurm-allocation-usage-service';
import { SlurmAllocationSummary } from './SlurmAllocationSummary';
import * as ResourceSummary from '@waldur/resource/summary/registry';
export default module => {
ResourceSummary.register('SLURM.Allocation', SlurmAllocationSummary);
module.component('slurmAllocationDetailsDialog', slurmAllocationDetailsDialog);
module.directive('slurmAllocationUsageChart', slurmAllocationUsageChart);
module.component('slurmAllocationUsageTable', slurmAllocationUsageTable);
module.service('SlurmAllocationUsageService', SlurmAllocationUsageService);
};
| Fix SLURM allocation details summary. | Fix SLURM allocation details summary.
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -6,7 +6,7 @@
import * as ResourceSummary from '@waldur/resource/summary/registry';
export default module => {
- ResourceSummary.register('Slurm.Allocation', SlurmAllocationSummary);
+ ResourceSummary.register('SLURM.Allocation', SlurmAllocationSummary);
module.component('slurmAllocationDetailsDialog', slurmAllocationDetailsDialog);
module.directive('slurmAllocationUsageChart', slurmAllocationUsageChart);
module.component('slurmAllocationUsageTable', slurmAllocationUsageTable); |
13c8749224dd2d7014953acd295cb582bbefaf10 | display-stats.js | display-stats.js | // ==UserScript==
// @name Display Stats
// @namespace https://github.com/EFox2413/initiumGrease
// @version 0.1
// @description try to take over the world!
// @author EFox2413
// @match https://www.playinitium.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
var $ = window.jQuery;
var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' );
var statsItems;
var statsID = ["S", "D", "I", "W"];
var href = $( '.character-display-box').children().first().attr( "rel" );
$.ajax({
url: href,
type: "GET",
success: function(data) {
statsItems = $(data).find('.main-item-subnote');
statsItems.each(function( index ) {
if ( index > 0 ) {
charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>");
}
});
}
});
| // ==UserScript==
// @name Display Stats
// @namespace https://github.com/EFox2413/initiumGrease
// @version 0.1
// @description try to take over the world!
// @author EFox2413
// @match https://www.playinitium.com/*
// @match http://www.playinitium.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */
'use strict';
var $ = window.jQuery;
var charDiv = $('.character-display-box').children(" div:nth-child(3)").children( 'a' );
var statsItems;
var statsID = ["S", "D", "I", "W"];
var href = $( '.character-display-box').children().first().attr( "rel" );
$.ajax({
url: href,
type: "GET",
success: function(data) {
statsItems = $(data).find('.main-item-subnote');
statsItems.each(function( index ) {
if ( index > 0 ) {
charDiv.append( " <span style=\"font-size:small\"> " + statsID[index - 1] + ":" + $( this ).text().split(" ")[0] + " </span>");
}
});
}
});
| Add an additional match line for http | Add an additional match line for http
Add an additional match line for http so the script script runs on http/s. | JavaScript | mit | EFox2413/initiumGrease | ---
+++
@@ -5,6 +5,7 @@
// @description try to take over the world!
// @author EFox2413
// @match https://www.playinitium.com/*
+// @match http://www.playinitium.com/*
// @grant none
// ==/UserScript==
/* jshint -W097 */ |
d08eeb39468740085f1488e7e031e8122dba0124 | gulpfile.js | gulpfile.js | ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("default", ["scripts", "watch"])
| ///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("default", ["scripts", "watch"])
var buildBranch = require("buildbranch")
gulp.task("publish", function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) {
throw err
}
console.log(pkg.name + " published.")
cb()
})
})
| Add publish task (for gh-pages) | Add publish task (for gh-pages)
| JavaScript | mit | MoOx/parallaxify,MoOx/parallaxify | ---
+++
@@ -30,3 +30,15 @@
})
gulp.task("default", ["scripts", "watch"])
+
+var buildBranch = require("buildbranch")
+gulp.task("publish", function(cb) {
+ buildBranch({folder: "src"}
+ , function(err) {
+ if (err) {
+ throw err
+ }
+ console.log(pkg.name + " published.")
+ cb()
+ })
+}) |
5e709349ce99b83a6b443db20b6d317adbf5e17f | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var zip = require('gulp-zip');
// Release
gulp.task('release', function () {
var zippedFiles = [
'controller.php',
'css/**/*',
'vendor/**/*',
'LICENSE',
'README.md',
'icon.png',
];
// get current version
var version = require('./package.json').version;
return gulp.src(zippedFiles, {base: '..'})
.pipe(zip('kint-debug-v' + version + '.zip'))
.pipe(gulp.dest('dist'));
});
| 'use strict';
var gulp = require('gulp');
var zip = require('gulp-zip');
// Release
gulp.task('release', function () {
var zippedFiles = [
'controller.php',
'css/**/*',
'vendor/**/*',
'README.md',
'icon.png',
];
// get current version
var version = require('./package.json').version;
return gulp.src(zippedFiles, {base: '..'})
.pipe(zip('kint-debug-v' + version + '.zip'))
.pipe(gulp.dest('dist'));
});
| Remove the license from the package export | Remove the license from the package export
Already present in the downloaded package
| JavaScript | mit | dorian-marchal/concrete5-kint-debug,dorian-marchal/concrete5-kint-debug | ---
+++
@@ -10,7 +10,6 @@
'controller.php',
'css/**/*',
'vendor/**/*',
- 'LICENSE',
'README.md',
'icon.png',
]; |
9dc4e7c955b0252f1e5b0a89f2dc1cfbaf030088 | lib/cartodb/middleware/context/db-conn-setup.js | lib/cartodb/middleware/context/db-conn-setup.js | const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('setDBConn');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) {
err.http_status = 404;
}
return next(err);
}
_.defaults(res.locals, {
dbuser: global.environment.postgres.user,
dbpassword: global.environment.postgres.password,
dbhost: global.environment.postgres.host,
dbport: global.environment.postgres.port
});
res.set('X-Served-By-DB-Host', res.locals.dbhost);
next();
});
};
};
| const _ = require('underscore');
module.exports = function dbConnSetup (pgConnection) {
return function dbConnSetupMiddleware (req, res, next) {
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
req.profiler.done('dbConnSetup');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) {
err.http_status = 404;
}
return next(err);
}
_.defaults(res.locals, {
dbuser: global.environment.postgres.user,
dbpassword: global.environment.postgres.password,
dbhost: global.environment.postgres.host,
dbport: global.environment.postgres.port
});
res.set('X-Served-By-DB-Host', res.locals.dbhost);
next();
});
};
};
| Use the right step name for profiling | Use the right step name for profiling
| JavaScript | bsd-3-clause | CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb | ---
+++
@@ -5,7 +5,7 @@
const { user } = res.locals;
pgConnection.setDBConn(user, res.locals, (err) => {
- req.profiler.done('setDBConn');
+ req.profiler.done('dbConnSetup');
if (err) {
if (err.message && -1 !== err.message.indexOf('name not found')) { |
bdfc949f40eef5f43febb7e1fb2e53874fad399f | source/assets/javascripts/syntax-highlight.js | source/assets/javascripts/syntax-highlight.js | import hljs from 'highlight.js/lib/highlight';
import javascript from 'highlight.js/lib/languages/javascript';
import ruby from 'highlight.js/lib/languages/ruby';
import elixir from 'highlight.js/lib/languages/elixir';
import shell from 'highlight.js/lib/languages/shell';
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
import nginx from 'highlight.js/lib/languages/nginx';
import json from 'highlight.js/lib/languages/json';
const languages = {
javascript,
ruby,
elixir,
shell,
bash,
css,
nginx,
json,
};
Object.entries(languages).forEach(([name, language]) => {
hljs.registerLanguage(name, language);
});
hljs.initHighlightingOnLoad();
| import highlight from 'highlight.js/lib/highlight';
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
import elixir from 'highlight.js/lib/languages/elixir';
import html from 'highlight.js/lib/languages/html';
import javascript from 'highlight.js/lib/languages/javascript';
import json from 'highlight.js/lib/languages/json';
import nginx from 'highlight.js/lib/languages/nginx';
import ruby from 'highlight.js/lib/languages/ruby';
import shell from 'highlight.js/lib/languages/shell';
import yaml from 'highlight.js/lib/languages/yaml';
const languages = {
bash,
css,
elixir,
html,
javascript,
json,
nginx,
ruby,
shell,
yaml,
};
Object.entries(languages).forEach(([name, language]) => {
highlight.registerLanguage(name, language);
});
highlight.initHighlightingOnLoad();
| Add more languages to highlight | Add more languages to highlight
| JavaScript | mit | rossta/rossta.github.com,rossta/rossta.github.com,rossta/rossta.github.com | ---
+++
@@ -1,26 +1,31 @@
-import hljs from 'highlight.js/lib/highlight';
-import javascript from 'highlight.js/lib/languages/javascript';
-import ruby from 'highlight.js/lib/languages/ruby';
-import elixir from 'highlight.js/lib/languages/elixir';
-import shell from 'highlight.js/lib/languages/shell';
+import highlight from 'highlight.js/lib/highlight';
+
import bash from 'highlight.js/lib/languages/bash';
import css from 'highlight.js/lib/languages/css';
+import elixir from 'highlight.js/lib/languages/elixir';
+import html from 'highlight.js/lib/languages/html';
+import javascript from 'highlight.js/lib/languages/javascript';
+import json from 'highlight.js/lib/languages/json';
import nginx from 'highlight.js/lib/languages/nginx';
-import json from 'highlight.js/lib/languages/json';
+import ruby from 'highlight.js/lib/languages/ruby';
+import shell from 'highlight.js/lib/languages/shell';
+import yaml from 'highlight.js/lib/languages/yaml';
const languages = {
- javascript,
- ruby,
- elixir,
- shell,
bash,
css,
+ elixir,
+ html,
+ javascript,
+ json,
nginx,
- json,
+ ruby,
+ shell,
+ yaml,
};
Object.entries(languages).forEach(([name, language]) => {
- hljs.registerLanguage(name, language);
+ highlight.registerLanguage(name, language);
});
-hljs.initHighlightingOnLoad();
+highlight.initHighlightingOnLoad(); |
c9707e7a63d446ae1c60814c705d48b604b9ddca | htteepee.js | htteepee.js | /*globals module, require*/
var stack = require('stack'),
http = require('http'),
_hs = http.createServer;
http.createServer = function createServer () {
'use strict';
return _hs.call(http,
stack.apply(stack, Array.prototype.slice.call(arguments))
);
};
http.createMiddlewareServer = function (mws) {
'use strict';
mws = typeof mws === 'function' ? [mws] : mws;
return function () {
return _hs.call(http,
stack.apply(stack, mws.concat(Array.prototype.slice.call(arguments)))
);
};
};
module.exports = http;
| /*globals module, require*/
var stack = require('stack'),
http = require('http'),
_hs = http.createServer;
http.createServer = function createServer () {
'use strict';
return _hs.call(http,
stack.apply(stack, Array.prototype.slice.call(arguments))
);
};
http.createMiddlewareServer = function (mws) {
'use strict';
mws = Array.prototype.slice.call(arguments);
return function () {
return _hs.call(http,
stack.apply(stack, mws.concat(Array.prototype.slice.call(arguments)))
);
};
};
module.exports = http;
| Change away froma accepting array to accepting arguments like our own createServer | Change away froma accepting array to accepting arguments like our own createServer
| JavaScript | mit | brettz9/htteepee | ---
+++
@@ -13,7 +13,7 @@
http.createMiddlewareServer = function (mws) {
'use strict';
- mws = typeof mws === 'function' ? [mws] : mws;
+ mws = Array.prototype.slice.call(arguments);
return function () {
return _hs.call(http,
stack.apply(stack, mws.concat(Array.prototype.slice.call(arguments))) |
e1703b576feb0fadab897da7a8b8ee697f7f4f67 | app/services/raven.js | app/services/raven.js | import RavenService from 'ember-cli-sentry/services/raven';
import { inject as service } from '@ember/service';
import config from '../config/environment';
import { versionRegExp } from 'ember-cli-app-version/utils/regexp';
export default RavenService.extend({
iliosConfig: service(),
/**
* Override default service to add configuration check
* before attempting to capture anything.
*/
ignoreError() {
return !this.iliosConfig.errorCaptureEnabled;
},
release: config.APP.version.match(versionRegExp),
});
| import RavenService from 'ember-cli-sentry/services/raven';
import { inject as service } from '@ember/service';
import config from '../config/environment';
import { versionRegExp } from 'ember-cli-app-version/utils/regexp';
export default RavenService.extend({
iliosConfig: service(),
/**
* Override default service to add configuration check
* before attempting to capture anything.
*/
ignoreError() {
return !this.iliosConfig.errorCaptureEnabled;
},
release: config.APP.version.match(versionRegExp)[0],
});
| Fix version in error reports | Fix version in error reports
We need to return a string here, but match() is an array.
| JavaScript | mit | djvoa12/frontend,djvoa12/frontend,jrjohnson/frontend,thecoolestguy/frontend,ilios/frontend,thecoolestguy/frontend,dartajax/frontend,ilios/frontend,dartajax/frontend,jrjohnson/frontend | ---
+++
@@ -14,5 +14,5 @@
return !this.iliosConfig.errorCaptureEnabled;
},
- release: config.APP.version.match(versionRegExp),
+ release: config.APP.version.match(versionRegExp)[0],
}); |
c5f148c6ec29c86671471bcde50cea809479b5c6 | client/app/mirage/config.js | client/app/mirage/config.js | export default function() {
}
| export default function() {
this.get('/orders', function(db, request) {
return {
data: [
{
id: 1,
type: "order",
attributes: {
organizerName: "Пицца Темпо",
orderTime: "14:00",
moneyRequired: 300000,
moneyCurrent: 100000
}
},
]
};
});
}
| Add test endpoint for /orders | Add test endpoint for /orders
| JavaScript | mit | yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time | ---
+++
@@ -1,2 +1,20 @@
export default function() {
+
+ this.get('/orders', function(db, request) {
+ return {
+ data: [
+ {
+ id: 1,
+ type: "order",
+ attributes: {
+ organizerName: "Пицца Темпо",
+ orderTime: "14:00",
+ moneyRequired: 300000,
+ moneyCurrent: 100000
+ }
+ },
+ ]
+ };
+ });
+
} |
d54755756243d651f6274c41e461e9fc62f79592 | addons/dexie-export-import/test/karma.conf.js | addons/dexie-export-import/test/karma.conf.js | // Include common configuration
const {karmaCommon, getKarmaConfig, defaultBrowserMatrix} = require('../../../test/karma.common');
module.exports = function (config) {
const cfg = getKarmaConfig({
// I get error from browserstack/karma (not our code) when trying bs_iphone7.
// If trying bs_safari it just times out.
// Unit tests have been manually tested on Safari 12 though.
ci: defaultBrowserMatrix.ci.filter(b => b !== 'bs_iphone7'),
local: ["bs_ie11"], // Uncomment to use browserstack browsers from home
// bs_iphone bails out before running any test at all.
pre_npm_publish: defaultBrowserMatrix.pre_npm_publish.filter(b => !/bs_iphone7/i.test(b))
}, {
// Base path should point at the root
basePath: '../../../',
files: karmaCommon.files.concat([
'dist/dexie.js',
'addons/dexie-export-import/dist/dexie-export-import.js',
'addons/dexie-export-import/test/bundle.js',
{ pattern: 'addons/dexie-export-import/test/*.map', watched: false, included: false },
{ pattern: 'addons/dexie-export-import/dist/*.map', watched: false, included: false }
])
});
config.set(cfg);
}
| // Include common configuration
const {karmaCommon, getKarmaConfig, defaultBrowserMatrix} = require('../../../test/karma.common');
module.exports = function (config) {
const cfg = getKarmaConfig({
// I get error from browserstack/karma (not our code) when trying bs_iphone7.
// If trying bs_safari it just times out.
// Unit tests have been manually tested on Safari 12 though.
ci: defaultBrowserMatrix.ci.filter(b => b !== 'bs_iphone7'),
//local: ["bs_ie11"], // Uncomment to use browserstack browsers from home
// bs_iphone bails out before running any test at all.
pre_npm_publish: defaultBrowserMatrix.pre_npm_publish.filter(b => !/bs_iphone7/i.test(b))
}, {
// Base path should point at the root
basePath: '../../../',
files: karmaCommon.files.concat([
'dist/dexie.js',
'addons/dexie-export-import/dist/dexie-export-import.js',
'addons/dexie-export-import/test/bundle.js',
{ pattern: 'addons/dexie-export-import/test/*.map', watched: false, included: false },
{ pattern: 'addons/dexie-export-import/dist/*.map', watched: false, included: false }
])
});
config.set(cfg);
}
| Comment local unit testing from using browserstack | Comment local unit testing from using browserstack
| JavaScript | apache-2.0 | dfahlander/Dexie.js,dfahlander/Dexie.js,dfahlander/Dexie.js,jimmywarting/Dexie.js,dfahlander/Dexie.js,jimmywarting/Dexie.js,jimmywarting/Dexie.js,jimmywarting/Dexie.js | ---
+++
@@ -7,7 +7,7 @@
// If trying bs_safari it just times out.
// Unit tests have been manually tested on Safari 12 though.
ci: defaultBrowserMatrix.ci.filter(b => b !== 'bs_iphone7'),
- local: ["bs_ie11"], // Uncomment to use browserstack browsers from home
+ //local: ["bs_ie11"], // Uncomment to use browserstack browsers from home
// bs_iphone bails out before running any test at all.
pre_npm_publish: defaultBrowserMatrix.pre_npm_publish.filter(b => !/bs_iphone7/i.test(b))
}, { |
622c972dd4d23923b40799cf945206c0c774b5bb | helper.js | helper.js | Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
return new Handlebars.SafeString(html);
});
| Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash['class']) {
html_class = " " + options.hash['class']
} else {
html_class = ""
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control" + html_class + "' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
return new Handlebars.SafeString(html);
});
| Add support for adding classes to the select box | Add support for adding classes to the select box
| JavaScript | mit | meteorclub/simple-form | ---
+++
@@ -3,6 +3,12 @@
_this = this;
if (!field) {
return;
+ }
+
+ if (options.hash['class']) {
+ html_class = " " + options.hash['class']
+ } else {
+ html_class = ""
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
@@ -16,7 +22,7 @@
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
- html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
+ html = "<select class='form-control" + html_class + "' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
|
a4e52e3d9c017cacaa688de5b8a747a08c98d478 | src/forecastDaily/forecastDailyReducer.js | src/forecastDaily/forecastDailyReducer.js | import dotProp from 'dot-prop-immutable'
import * as types from './forecastDailyActionTypes'
const initialState = {
forecastDaily: {
data: [],
app: {
locationId: 5128581 // nyc usa
},
ui: {}
}
}
const updateAppIsFetching = (state, action, value) => {
return dotProp.set(state, 'forecastDaily.app.isFetching', value)
}
const updateData = (state, action) => {
const { payload: { list } } = action
const data = list.map(x => {
return {
date: new Date(x.dt).toString(),
tempMin: x.temp.min,
tempMax: x.temp.max,
weatherDescription: x.weather[0].description
}
})
return dotProp.set(state, 'forecastDaily.data', data)
}
function forecastDailyReducer (state = initialState, action) {
switch (action.type) {
case types.GET_FORECAST_DAILY_PENDING:
return updateAppIsFetching(state, action, true)
case types.GET_FORECAST_DAILY_FULFILLED:
updateAppIsFetching(state, action, false)
return updateData(state, action)
default:
return state
}
}
export default forecastDailyReducer
| import dotProp from 'dot-prop-immutable'
import * as types from './forecastDailyActionTypes'
const initialState = {
forecastDaily: {
data: [],
app: {
locationId: 5128581 // nyc usa
},
ui: {}
}
}
const updateAppIsFetching = (state, action, value) => {
return dotProp.set(state, 'forecastDaily.app.isFetching', value)
}
const updateData = (state, action) => {
const { payload: { list } } = action
const data = list.map(x => {
return {
date: new Date(x.dt * 1000).toString(),
tempMin: x.temp.min,
tempMax: x.temp.max,
weatherDescription: x.weather[0].description
}
})
return dotProp.set(state, 'forecastDaily.data', data)
}
function forecastDailyReducer (state = initialState, action) {
switch (action.type) {
case types.GET_FORECAST_DAILY_PENDING:
return updateAppIsFetching(state, action, true)
case types.GET_FORECAST_DAILY_FULFILLED:
updateAppIsFetching(state, action, false)
return updateData(state, action)
default:
return state
}
}
export default forecastDailyReducer
| Add fix issue with linux time | Add fix issue with linux time
| JavaScript | mit | gibbok/react-redux-weather-app,gibbok/react-redux-weather-app | ---
+++
@@ -19,7 +19,7 @@
const { payload: { list } } = action
const data = list.map(x => {
return {
- date: new Date(x.dt).toString(),
+ date: new Date(x.dt * 1000).toString(),
tempMin: x.temp.min,
tempMax: x.temp.max,
weatherDescription: x.weather[0].description |
4b027289b5f1aebca17f64b7fe240bfe0a0c2930 | build-regular-expression.js | build-regular-expression.js | var captureDigit = '([1-9][0-9]*)'
var EUCD = new RegExp(
'^' +
captureDigit + 'e' +
optional(captureDigit + 'u') +
optional(captureDigit + 'c') +
optional(captureDigit + 'd') +
'$')
function optional(reString) {
return ( '(?:' + reString + ')?' ) }
process.stdout.write(( 'module.exports = ' + EUCD + '\n' ))
| var captureDigit = '([1-9][0-9]*)'
var regularExpression = new RegExp(
'^' +
captureDigit + 'e' +
optional(captureDigit + 'u') +
optional(captureDigit + 'c') +
optional(captureDigit + 'd') +
'$')
function optional(reString) {
return ( '(?:' + reString + ')?' ) }
process.stdout.write(( 'module.exports = ' + regularExpression + '\n' ))
| Rename variable in regular expression build script | Rename variable in regular expression build script
| JavaScript | mit | kemitchell/reviewers-edition-parse.js | ---
+++
@@ -1,6 +1,6 @@
var captureDigit = '([1-9][0-9]*)'
-var EUCD = new RegExp(
+var regularExpression = new RegExp(
'^' +
captureDigit + 'e' +
optional(captureDigit + 'u') +
@@ -11,4 +11,4 @@
function optional(reString) {
return ( '(?:' + reString + ')?' ) }
-process.stdout.write(( 'module.exports = ' + EUCD + '\n' ))
+process.stdout.write(( 'module.exports = ' + regularExpression + '\n' )) |
96d80da6ba02307d4b4c115f9f9ffea8ef998d2c | chrome-cordova/plugins/chrome-common/errors.js | chrome-cordova/plugins/chrome-common/errors.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
try {
var runtime = require('org.chromium.runtime.runtime');
} catch(e) {}
// Typical Usage:
//
// if (fail_condition)
// return callbackWithError('You should blah blah', fail, optional_args_to_fail...)
function callbackWithError(msg, callback) {
if (typeof callback !== 'function') {
console.error(msg);
return;
}
try {
if (typeof runtime !== 'undefined') {
runtime.lastError = { 'message' : msg };
} else {
console.error(msg);
}
callback.apply(null, Array.prototype.slice.call(arguments, 2));
} finally {
if (typeof runtime !== 'undefined')
delete runtime.lastError;
}
}
module.exports = {
callbackWithError: callbackWithError
};
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
try {
var runtime = require('org.chromium.runtime.runtime');
} catch(e) {}
// Typical Usage:
//
// if (fail_condition)
// return callbackWithError('You should blah blah', fail, optional_args_to_fail...)
function callbackWithError(msg, callback) {
var err;
if (typeof msg == 'string') {
err = { 'message' : msg };
} else {
err = msg;
}
if (typeof callback !== 'function') {
console.error(err.message);
return;
}
try {
if (typeof runtime !== 'undefined') {
runtime.lastError = err;
} else {
console.error(err.message);
}
callback.apply(null, Array.prototype.slice.call(arguments, 2));
} finally {
if (typeof runtime !== 'undefined')
delete runtime.lastError;
}
}
module.exports = {
callbackWithError: callbackWithError
};
| Allow setting error.code as well as error.message for callbackWithError() | Allow setting error.code as well as error.message for callbackWithError()
| JavaScript | bsd-3-clause | chirilo/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,wudkj/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps,guozanhua/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,wudkj/mobile-chrome-apps,chirilo/mobile-chrome-apps,chirilo/mobile-chrome-apps,wudkj/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,MobileChromeApps/mobile-chrome-apps,guozanhua/mobile-chrome-apps,chirilo/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,liqingzhu/mobile-chrome-apps,wudkj/mobile-chrome-apps,xiaoyanit/mobile-chrome-apps | ---
+++
@@ -11,16 +11,23 @@
// if (fail_condition)
// return callbackWithError('You should blah blah', fail, optional_args_to_fail...)
function callbackWithError(msg, callback) {
+ var err;
+ if (typeof msg == 'string') {
+ err = { 'message' : msg };
+ } else {
+ err = msg;
+ }
+
if (typeof callback !== 'function') {
- console.error(msg);
+ console.error(err.message);
return;
}
try {
if (typeof runtime !== 'undefined') {
- runtime.lastError = { 'message' : msg };
+ runtime.lastError = err;
} else {
- console.error(msg);
+ console.error(err.message);
}
callback.apply(null, Array.prototype.slice.call(arguments, 2)); |
581ca42c1e0c35fbeef9fffc501292d10e15974d | app/assets/javascripts/georgia/application.js | app/assets/javascripts/georgia/application.js | //= require jquery
//= require jquery.ui.all
//= require georgia/jquery.ui.touch-punch
//= require jquery_ujs
//= require jquery-fileupload
//= require twitter/bootstrap
//= require select2
//= require shadowbox
//= require mousetrap
//= require georgia/keybindings
//= require georgia/jquery.mjs.nestedSortable
//= require georgia/tags
//= require georgia/pages
//= require georgia/media
//= require georgia/form-actions
//= require ckeditor/init
//= require handlebars.runtime
//= require underscore
//= require backbone
//= require .//backbone-relational
//= require .//panels
//= require_tree ./../../templates/
//= require_tree .//models
//= require_tree .//collections
//= require_tree .//views
//= require_tree .//routers
//= require_tree . | //= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require jquery-fileupload
//= require twitter/bootstrap
//= require select2
//= require shadowbox
//= require mousetrap
//= require ckeditor/init
//= require_tree .//ckeditor
//= require handlebars.runtime
//= require underscore
//= require backbone
//= require_tree ./../../templates/
//= require_tree .//models
//= require_tree .//collections
//= require_tree .//views
//= require_tree .//routers
//= require .//backbone-relational
//= require .//bootstrap
//= require .//featured-image
//= require .//form-actions
//= require .//jquery.mjs.nestedSortable
//= require .//jquery.ui.touch-punch
//= require .//keybindings
//= require .//media
//= require .//pages
//= require .//panels
//= require .//tags | Fix double inclusion of jquery | Fix double inclusion of jquery
| JavaScript | mit | georgia-cms/georgia,georgia-cms/georgia,georgia-cms/georgia | ---
+++
@@ -1,27 +1,32 @@
//= require jquery
//= require jquery.ui.all
-//= require georgia/jquery.ui.touch-punch
//= require jquery_ujs
//= require jquery-fileupload
//= require twitter/bootstrap
//= require select2
//= require shadowbox
//= require mousetrap
-//= require georgia/keybindings
-//= require georgia/jquery.mjs.nestedSortable
-//= require georgia/tags
-//= require georgia/pages
-//= require georgia/media
-//= require georgia/form-actions
+
//= require ckeditor/init
+//= require_tree .//ckeditor
+
//= require handlebars.runtime
//= require underscore
//= require backbone
-//= require .//backbone-relational
-//= require .//panels
//= require_tree ./../../templates/
//= require_tree .//models
//= require_tree .//collections
//= require_tree .//views
//= require_tree .//routers
-//= require_tree .
+
+//= require .//backbone-relational
+//= require .//bootstrap
+//= require .//featured-image
+//= require .//form-actions
+//= require .//jquery.mjs.nestedSortable
+//= require .//jquery.ui.touch-punch
+//= require .//keybindings
+//= require .//media
+//= require .//pages
+//= require .//panels
+//= require .//tags |
8f233b5f65981b79ef88f2c1dad315fe6e9e34d3 | js/mock-sensor.js | js/mock-sensor.js | // This mock sensor implementation triggers an event with some data every once in a while
var emitter = require( "events" ).EventEmitter,
possibleStrings = [
"Helsinki",
"Espoo",
"Tampere",
"Oulu",
"Mikkeli",
"Ii"
];
// Return a random integer between 0 and @upperLimit
function randomInteger( upperLimit ) {
return Math.round( ( 1 + Math.random() ) * upperLimit );
}
module.exports = function mockSensor() {
var returnValue = new emitter(),
trigger = function() {
returnValue.emit( "change", {
someValue: Math.round( Math.random() * 42 ),
someOtherValue: possibleStrings[ randomInteger( possibleStrings.length - 1 ) ] } );
setTimeout( trigger, randomInteger( 1000 ) + 1000 );
};
setTimeout( trigger, randomInteger( 1000 ) + 1000 );
return returnValue;
};
| // This mock sensor implementation triggers an event with some data every once in a while
var emitter = require( "events" ).EventEmitter,
possibleStrings = [
"Helsinki",
"Espoo",
"Tampere",
"Oulu",
"Mikkeli",
"Ii"
];
// Return a random integer between 0 and @upperLimit
function randomInteger( upperLimit ) {
return Math.round( Math.random() * upperLimit );
}
module.exports = function mockSensor() {
var returnValue = new emitter(),
trigger = function() {
var someValue = Math.round( Math.random() * 42 ),
someOtherValue = possibleStrings[ randomInteger( possibleStrings.length - 1 ) ];
returnValue.emit( "change", { someValue: someValue, someOtherValue: someOtherValue } );
setTimeout( trigger, randomInteger( 1000 ) + 1000 );
};
setTimeout( trigger, randomInteger( 1000 ) + 1000 );
return returnValue;
};
| Fix mock sensor randomization code | Examples: Fix mock sensor randomization code
| JavaScript | mit | zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zqzhang/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node | ---
+++
@@ -12,15 +12,16 @@
// Return a random integer between 0 and @upperLimit
function randomInteger( upperLimit ) {
- return Math.round( ( 1 + Math.random() ) * upperLimit );
+ return Math.round( Math.random() * upperLimit );
}
module.exports = function mockSensor() {
var returnValue = new emitter(),
trigger = function() {
- returnValue.emit( "change", {
- someValue: Math.round( Math.random() * 42 ),
- someOtherValue: possibleStrings[ randomInteger( possibleStrings.length - 1 ) ] } );
+ var someValue = Math.round( Math.random() * 42 ),
+ someOtherValue = possibleStrings[ randomInteger( possibleStrings.length - 1 ) ];
+
+ returnValue.emit( "change", { someValue: someValue, someOtherValue: someOtherValue } );
setTimeout( trigger, randomInteger( 1000 ) + 1000 );
};
|
40add9e89540f99aa95273637d8dce007d6ca4e9 | src/github/to/pivotal.js | src/github/to/pivotal.js | import { R, BPromise } from "../../utils";
import { Github } from "../../github";
import { Mentor } from "../../mentor";
import { Pivotal } from "../../pivotal";
export class GithubToPivotal {
constructor(keys, options) {
this.mentor = new Mentor (options);
this.pivotal = new Pivotal(keys.pivotal_api_key, this.mentor.options.pivotal);
this.github = new Github (keys.github_secret_key);
}
run(repositories) {
if (R.isNil(repositories) && R.isEmpty(repositories)) {
throw new Error(`\`repositories\` undefined or invalid: ${repositories}`);
}
return BPromise.coroutine(function* () {
for (var i in repositories) {
var repository = yield this.github.repoByUrl(repositories[i]);
var params = { state: 'open', per_page: '1' };
var issues = yield this.github.issuesWithCommentsByRepo(repository, params);
var stories = this.mentor.normalizeAllIssue(issues, repository);
stories = yield this.pivotal.createStories(stories);
// console.log(JSON.stringify(stories, null, 2));
console.log('Success sent', stories.length, 'stories.');
}
}.bind(this))();
}
}
| import { R, BPromise } from "../../utils";
import { Github } from "../../github";
import { Mentor } from "../../mentor";
import { Pivotal } from "../../pivotal";
export class GithubToPivotal {
constructor(keys, options) {
this.mentor = new Mentor (options);
this.pivotal = new Pivotal(keys.pivotal_api_key, this.mentor.options.pivotal);
this.github = new Github (keys.github_secret_key);
}
run(repositories) {
if (R.isNil(repositories) && R.isEmpty(repositories)) {
throw new Error(`\`repositories\` undefined or invalid: ${repositories}`);
}
return BPromise.coroutine(function* () {
for (var i in repositories) {
var repository = yield this.github.repoByUrl(repositories[i]);
var params = { state: 'open', per_page: '100' };
var issues = yield this.github.issuesWithCommentsByRepo(repository, params);
var stories = this.mentor.normalizeAllIssue(issues, repository);
stories = yield this.pivotal.createStories(stories);
// console.log(JSON.stringify(stories, null, 2));
console.log('Success sent', stories.length, 'stories.');
}
}.bind(this))();
}
}
| Change number of issues per page to 100 | Change number of issues per page to 100
| JavaScript | apache-2.0 | azukiapp/github-pivotal,azukiapp/github-pivotal | ---
+++
@@ -18,7 +18,7 @@
return BPromise.coroutine(function* () {
for (var i in repositories) {
var repository = yield this.github.repoByUrl(repositories[i]);
- var params = { state: 'open', per_page: '1' };
+ var params = { state: 'open', per_page: '100' };
var issues = yield this.github.issuesWithCommentsByRepo(repository, params);
var stories = this.mentor.normalizeAllIssue(issues, repository);
stories = yield this.pivotal.createStories(stories); |
ecbb97b5d0b9698de4ceb47a94cd7499460cbf11 | lib/transactional-email.js | lib/transactional-email.js | const REQUIRED_FIELDS = Object.freeze(['to']);
const OPTIONAL_FIELDS = Object.freeze([
'customer_id',
'transactional_message_id',
'message_data',
'from',
'from_id',
'reply_to',
'reply_to_id',
'bcc',
'subject',
'body',
'plaintext_body',
'amp_body',
'fake_bcc',
'hide_body',
]);
module.exports = class TransactionalEmail {
headers = {};
attachments = {};
constructor(opts) {
REQUIRED_FIELDS.forEach((field) => {
this[field] = opts[field];
});
OPTIONAL_FIELDS.forEach((field) => {
this[field] = opts[field];
});
}
attach(name, data) {
if (data instanceof Buffer) {
this.attachments[name] = data.toString('base64');
} else if (typeof data === 'string') {
this.attachments[name] = fs.readFileSync(data, 'base64');
} else {
throw new Error(`unknown attachment type: ${typeof data}`);
}
}
toObject() {
let attrs = {
attachments: this.attachments,
headers: this.headers,
};
[...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => {
attrs[prop] = this[prop];
});
return attrs;
}
};
| const REQUIRED_FIELDS = Object.freeze(['to']);
const OPTIONAL_FIELDS = Object.freeze([
'customer_id',
'transactional_message_id',
'message_data',
'from',
'from_id',
'reply_to',
'reply_to_id',
'bcc',
'subject',
'body',
'plaintext_body',
'amp_body',
'fake_bcc',
'hide_body',
]);
module.exports = class TransactionalEmail {
constructor(opts) {
REQUIRED_FIELDS.forEach((field) => {
this[field] = opts[field];
});
OPTIONAL_FIELDS.forEach((field) => {
this[field] = opts[field];
});
this.headers = {};
this.attachments = {};
}
attach(name, data) {
if (data instanceof Buffer) {
this.attachments[name] = data.toString('base64');
} else if (typeof data === 'string') {
this.attachments[name] = fs.readFileSync(data, 'base64');
} else {
throw new Error(`unknown attachment type: ${typeof data}`);
}
}
toObject() {
let attrs = {
attachments: this.attachments,
headers: this.headers,
};
[...REQUIRED_FIELDS, ...OPTIONAL_FIELDS].forEach((prop) => {
attrs[prop] = this[prop];
});
return attrs;
}
};
| Fix syntax for node 10 | Fix syntax for node 10
| JavaScript | mit | customerio/customerio-node,customerio/customerio-node,customerio/customerio-node | ---
+++
@@ -17,9 +17,6 @@
]);
module.exports = class TransactionalEmail {
- headers = {};
- attachments = {};
-
constructor(opts) {
REQUIRED_FIELDS.forEach((field) => {
this[field] = opts[field];
@@ -28,6 +25,9 @@
OPTIONAL_FIELDS.forEach((field) => {
this[field] = opts[field];
});
+
+ this.headers = {};
+ this.attachments = {};
}
attach(name, data) { |
5fbac9e0eb03fdb32f052a732e280a888fd0a0b3 | content/firediff/cssReps.js | content/firediff/cssReps.js | /* See license.txt for terms of usage */
FBL.ns(function() { with (FBL) {
var Fireformat = {},
Formatters;
try {
Components.utils.import("resource://fireformat/formatters.jsm", Fireformat);
Formatters = Fireformat.Formatters;
} catch (err) {
}
var CSSRuleCloneRep = domplate(Firebug.Rep, {
supportsObject: function(object, type) {
return object instanceof FireDiff.CSSModel.CSSStyleRuleClone
|| object instanceof FireDiff.CSSModel.CSSMediaRuleClone
|| object instanceof FireDiff.CSSModel.CSSFontFaceRuleClone
|| object instanceof FireDiff.CSSModel.CSSImportRuleClone
|| object instanceof FireDiff.CSSModel.CSSCharsetRuleClone
|| object instanceof FireDiff.CSSModel.CSSRuleClone;
},
copyRuleDeclaration: function(cssSelector) {
copyToClipboard(Formatters.getCSSFormatter().format(cssSelector));
},
getContextMenuItems: function(object, target, context) {
if (Formatters) {
return [
{label: "Copy Rule Declaration", command: bindFixed(this.copyRuleDeclaration, this, object) },
];
}
}
});
Firebug.registerRep(CSSRuleCloneRep);
}}); | /* See license.txt for terms of usage */
FBL.ns(function() { with (FBL) {
var Fireformat = {},
Formatters;
try {
Components.utils.import("resource://fireformat/formatters.jsm", Fireformat);
Formatters = Fireformat.Formatters;
} catch (err) {
}
var CSSRuleCloneRep = domplate(Firebug.Rep, {
supportsObject: function(object, type) {
return object instanceof FireDiff.CSSModel.CSSStyleRuleClone
|| object instanceof FireDiff.CSSModel.CSSMediaRuleClone
|| object instanceof FireDiff.CSSModel.CSSFontFaceRuleClone
|| object instanceof FireDiff.CSSModel.CSSImportRuleClone
|| object instanceof FireDiff.CSSModel.CSSCharsetRuleClone
|| object instanceof FireDiff.CSSModel.CSSRuleClone
|| object instanceof CSSStyleRule
|| object instanceof CSSMediaRule
|| object instanceof CSSFontFaceRule
|| object instanceof CSSImportRule
|| object instanceof CSSCharsetRule
|| object instanceof CSSUnknownRule;
},
copyRuleDeclaration: function(cssSelector) {
copyToClipboard(Formatters.getCSSFormatter().format(cssSelector));
},
getContextMenuItems: function(object, target, context) {
if (Formatters) {
return [
{label: "Copy Rule Declaration", command: bindFixed(this.copyRuleDeclaration, this, object) },
];
}
}
});
Firebug.registerRep(CSSRuleCloneRep);
}}); | Include normal CSS types in the copy rep | Include normal CSS types in the copy rep
git-svn-id: 35c6607454e245926b27e417202055c242b00e84@8608 e969d3be-0e28-0410-a27f-dd5c76401a8b
| JavaScript | bsd-3-clause | kpdecker/firediff | ---
+++
@@ -12,13 +12,20 @@
}
var CSSRuleCloneRep = domplate(Firebug.Rep, {
+
supportsObject: function(object, type) {
return object instanceof FireDiff.CSSModel.CSSStyleRuleClone
|| object instanceof FireDiff.CSSModel.CSSMediaRuleClone
|| object instanceof FireDiff.CSSModel.CSSFontFaceRuleClone
|| object instanceof FireDiff.CSSModel.CSSImportRuleClone
|| object instanceof FireDiff.CSSModel.CSSCharsetRuleClone
- || object instanceof FireDiff.CSSModel.CSSRuleClone;
+ || object instanceof FireDiff.CSSModel.CSSRuleClone
+ || object instanceof CSSStyleRule
+ || object instanceof CSSMediaRule
+ || object instanceof CSSFontFaceRule
+ || object instanceof CSSImportRule
+ || object instanceof CSSCharsetRule
+ || object instanceof CSSUnknownRule;
},
copyRuleDeclaration: function(cssSelector) { |
0e3abf3fd573780b0898240ba06b1a19a4e2f1b4 | controllers/transactions.js | controllers/transactions.js | 'use strict';
var mongoose = require('mongoose');
var Transaction = require('../models/Transaction');
mongoose.Promise = global.Promise;
module.exports = mongoose.connection;
var index = function (req, res, next) {
Transaction.find({}).exec().then(function (trans) {
res.json(trans);
}).catch(function(error){
next(error);
});
};
var show = function (req, res, next) {
Transaction.find({"_id": req.params.id}).exec()
.then(function(trans){
res.json(trans);
}).catch(function(error){
next(error);
});
};
var create = function (req, res, next) {
Transaction.create({
user_id: req.body.user_id,
product_id: req.body.product_id,
status: req.body.status,
qty: req.body.qty
}).then(function(trans){
res.json(trans);
})
.catch(function(error){
next(error);
});
};
var update = function (req, res, next) {
// Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) {
// //console.log(person.toJSON());
// })
// .catch(console.error)
};
module.exports = {
index,
show,
create,
update
};
| 'use strict';
var mongoose = require('mongoose');
var Transaction = require('../models/Transaction');
mongoose.Promise = global.Promise;
module.exports = mongoose.connection;
var index = function (req, res, next) {
Transaction.find({}).exec().then(function (trans) {
res.json(trans);
}).catch(function(error){
next(error);
});
};
var show = function (req, res, next) {
Transaction.find({"_id": req.params.id}).exec()
.then(function(trans){
res.json(trans);
}).catch(function(error){
next(error);
});
};
var create = function (req, res, next) {
// console.log(req.get('Content-Type'));
// res.json(req.body.user_id);
Transaction.create({
"user_id": req.body.user_id,
"product_id": req.body.product_id,
"status": req.body.status,
"qty": req.body.qty
}).then(function(trans){
res.json(trans);
})
.catch(function(error){
next(error);
});
};
var update = function (req, res, next) {
// Transaction.findByIdAndUpdate(req.params.id, { $set: modify }, { new: true }).exec().then(function(trans) {
// //console.log(person.toJSON());
// })
// .catch(console.error)
};
module.exports = {
index,
show,
create,
update
};
| Add create method in Transcation controller. -cwc | Add create method in Transcation controller. -cwc
Next thing to do is add update method.
| JavaScript | mit | Church-ill/project3-back,Church-ill/project3-back,Church-ill/project3-back | ---
+++
@@ -23,11 +23,13 @@
};
var create = function (req, res, next) {
+ // console.log(req.get('Content-Type'));
+ // res.json(req.body.user_id);
Transaction.create({
- user_id: req.body.user_id,
- product_id: req.body.product_id,
- status: req.body.status,
- qty: req.body.qty
+ "user_id": req.body.user_id,
+ "product_id": req.body.product_id,
+ "status": req.body.status,
+ "qty": req.body.qty
}).then(function(trans){
res.json(trans);
}) |
c2de65fb35c1e621e711527b7d2f357d1c4c3885 | chat-plugins/development.js | chat-plugins/development.js | /**
* Development commands plugin
*
* This houses the bot's development commands.
* These commands should only be used if the operator knows what their doing.
*
* @license MIT license
*/
'use strict';
exports.commands = {
js: 'eval',
eval: function (target, room, user, cmd) {
if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`);
try {
Chat.send(room, eval(target));
} catch (e) {
Chat.send(room, e.stack);
}
},
reload: 'hotpatch',
hotpatch: function (target, room, user) {
try {
Chat.reload();
Chat.send(room, 'Chat has been hotpatched successfully.');
} catch (e) {
Chat.send(room, `Failed to hotpatch chat:\n${e.stack}`);
}
},
};
| /**
* Development commands plugin
*
* This houses the bot's development commands.
* These commands should only be used if the operator knows what their doing.
*
* @license MIT license
*/
'use strict';
exports.commands = {
js: 'eval',
eval: function (target, room, user, cmd) {
if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`);
try {
Chat.send(room, `Javascript\n${eval(target)}`);
} catch (e) {
Chat.send(room, `Javascript\n${e.stack}`);
}
},
reload: 'hotpatch',
hotpatch: function (target, room, user) {
try {
Chat.reload();
Chat.send(room, 'Chat has been hotpatched successfully.');
} catch (e) {
Chat.send(room, `Javascript\nFailed to hotpatch chat:\n${e.stack}`);
}
},
};
| Enable Javascript syntax highlighting in some cmds | Enable Javascript syntax highlighting in some cmds
| JavaScript | mit | panpawn/Discord-Bot | ---
+++
@@ -13,9 +13,9 @@
eval: function (target, room, user, cmd) {
if (!target) return Chat.send(room, `Usage: ${Config.cmdchar}${cmd} [target]`);
try {
- Chat.send(room, eval(target));
+ Chat.send(room, `Javascript\n${eval(target)}`);
} catch (e) {
- Chat.send(room, e.stack);
+ Chat.send(room, `Javascript\n${e.stack}`);
}
},
reload: 'hotpatch',
@@ -24,7 +24,7 @@
Chat.reload();
Chat.send(room, 'Chat has been hotpatched successfully.');
} catch (e) {
- Chat.send(room, `Failed to hotpatch chat:\n${e.stack}`);
+ Chat.send(room, `Javascript\nFailed to hotpatch chat:\n${e.stack}`);
}
},
}; |
cf18968b1115f67dbb48c36834d1ba08e32aeb8d | js/nalyt.js | js/nalyt.js | $(document).ready(function(){
if (analytics) {
$('a[target=_blank]').click(function (e) {
var url = this.getAttribute("href") || this.getAttribute("xlink:href");
analytics.track("externalLink", {url: url});
});
window.onpopstate = function (event) {
analytics.page("Slide", {url: location.href});
}
}
}); | $(document).ready(function(){
if (analytics) {
$('a[target=_blank]').click(function (e) {
var url = this.getAttribute("href") || this.getAttribute("xlink:href");
analytics.track("Clicked External Link", {url: url});
});
window.onpopstate = function (event) {
analytics.page("Slide", {url: location.href});
}
}
});
| Change name of the event | Change name of the event
| JavaScript | mit | cyberFund/cyberep.cyber.fund,cyberFund/cyberep.cyber.fund | ---
+++
@@ -2,7 +2,7 @@
if (analytics) {
$('a[target=_blank]').click(function (e) {
var url = this.getAttribute("href") || this.getAttribute("xlink:href");
- analytics.track("externalLink", {url: url});
+ analytics.track("Clicked External Link", {url: url});
});
window.onpopstate = function (event) { |
202b819f2e1f1caa1c00f4503900de2ceef1d3bb | app/gbi_server/static/js/admin/create_user.js | app/gbi_server/static/js/admin/create_user.js | $(document).ready(function() {
$('#verified').click(function() {
if($(this).attr("checked")) {
$('#activate').removeAttr('disabled');
} else {
$('#activate').attr('disabled', 'disabled');
}
});
$('#activate').attr('disabled', 'disabled');
}); | $(document).ready(function() {
$('#verified').click(function() {
if($(this).attr("checked")) {
$('#activate').removeAttr('disabled');
} else {
$('#activate').attr('disabled', 'disabled');
}
});
$('#activate').attr('disabled', 'disabled');
$('#type').change(function() {
if($(this).val() != 0) {
$('#florlp_name').parents('div.control-group:first').hide();
} else {
$('#florlp_name').parents('div.control-group:first').show();
}
});
}); | Hide florlp_name when type not 0 | Hide florlp_name when type not 0
| JavaScript | apache-2.0 | omniscale/gbi-server,omniscale/gbi-server,omniscale/gbi-server | ---
+++
@@ -7,4 +7,11 @@
}
});
$('#activate').attr('disabled', 'disabled');
+ $('#type').change(function() {
+ if($(this).val() != 0) {
+ $('#florlp_name').parents('div.control-group:first').hide();
+ } else {
+ $('#florlp_name').parents('div.control-group:first').show();
+ }
+ });
}); |
d7bfb87ea5580463c9fc058ea0718ac90a3f32f1 | src/auth/authApi.service.js | src/auth/authApi.service.js | (function (angular) {
'use strict';
angular
.module('movieClub.auth')
.factory('authApi', authApi);
function authApi($firebaseAuth, usersApi, firebaseRef) {
var factory = {
login: login,
logout: logout,
onAuth: onAuth,
register: register
},
authRef = $firebaseAuth(firebaseRef);
return factory;
function login(email, password) {
var credentials = {
email: email,
password: password
};
return authRef.$authWithPassword(credentials);
}
function logout() {
authRef.$unauth();
}
function onAuth(func) {
return authRef.$onAuth(func);
}
function register(username, email, password) {
var credentials = {
email: email,
password: password
};
return authRef.$createUser(credentials)
.then(function () {
return login(email, password)
.then(function (auth) {
var user = usersApi.getById(auth.uid);
user.username = username;
user.$save();
return user.$loaded();
});
});
}
}
}(window.angular));
| (function (angular) {
'use strict';
angular
.module('movieClub.auth')
.factory('authApi', authApi);
function authApi($firebaseAuth, usersApi, firebaseRef) {
var factory = {
login: login,
logout: logout,
onAuth: onAuth,
register: register
},
authRef = $firebaseAuth(firebaseRef);
return factory;
function login(email, password) {
return authRef.$authWithPassword({email: email, password: password});
}
function logout() {
authRef.$unauth();
}
function register(username, email, password) {
return authRef.$createUser({email: email, password: password})
.then(_.partial(login, email, password))
.then(_.partialRight(addUsername, username));
}
function onAuth(func) {
return authRef.$onAuth(func);
}
function addUsername(auth, username) {
var user = usersApi.getById(auth.uid);
user.username = username;
user.$save();
return user.$loaded();
}
}
}(window.angular));
| Use promise chaining during registration | Use promise chaining during registration
| JavaScript | mit | charwking/movie-club,charwking/movie-club,charwking/movie-club | ---
+++
@@ -16,37 +16,28 @@
return factory;
function login(email, password) {
- var credentials = {
- email: email,
- password: password
- };
- return authRef.$authWithPassword(credentials);
+ return authRef.$authWithPassword({email: email, password: password});
}
function logout() {
authRef.$unauth();
}
+ function register(username, email, password) {
+ return authRef.$createUser({email: email, password: password})
+ .then(_.partial(login, email, password))
+ .then(_.partialRight(addUsername, username));
+ }
+
function onAuth(func) {
return authRef.$onAuth(func);
}
- function register(username, email, password) {
- var credentials = {
- email: email,
- password: password
- };
-
- return authRef.$createUser(credentials)
- .then(function () {
- return login(email, password)
- .then(function (auth) {
- var user = usersApi.getById(auth.uid);
- user.username = username;
- user.$save();
- return user.$loaded();
- });
- });
+ function addUsername(auth, username) {
+ var user = usersApi.getById(auth.uid);
+ user.username = username;
+ user.$save();
+ return user.$loaded();
}
}
|
d527917af4d2213d23cf5165b15d30ff50a976ac | lib/tape/test.js | lib/tape/test.js | 'use strict';
// MODULES //
var tape = require( 'tape' );
var lib = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( typeof lib === 'function', 'main export is a function' );
t.end();
});
| 'use strict';
// MODULES //
var tape = require( 'tape' );
var lib = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.equal( typeof lib, 'function', 'main export is a function' );
t.end();
});
| Use equality in tape template | Use equality in tape template
| JavaScript | mit | kgryte/test-snippet | ---
+++
@@ -9,6 +9,6 @@
// TESTS //
tape( 'main export is a function', function test( t ) {
- t.ok( typeof lib === 'function', 'main export is a function' );
+ t.equal( typeof lib, 'function', 'main export is a function' );
t.end();
}); |
1024e5132e2f39fdaa46ee9f538046ef6e9d17ff | grunt/config/css-mqpacker.js | grunt/config/css-mqpacker.js | module.exports = function(grunt) {
grunt.config('css_mqpacker', {
options: {
map: false, // enable/disable source maps
},
main: {
src: '<%= project.styles_dev %>/main.dev.css',
dest: '<%= project.styles_dev %>/main.dev.css',
},
mobile: {
src: '<%= project.styles_dev %>/mobile.dev.css',
dest: '<%= project.styles_dev %>/mobile.dev.css',
},
});
};
| module.exports = function(grunt) {
grunt.config('css_mqpacker', {
options: {
map: false, // enable/disable source maps
sort: true,
},
main: {
src: '<%= project.styles_dev %>/main.dev.css',
dest: '<%= project.styles_dev %>/main.dev.css',
},
mobile: {
src: '<%= project.styles_dev %>/mobile.dev.css',
dest: '<%= project.styles_dev %>/mobile.dev.css',
},
});
};
| Add sort media queries to Grunt mqpacker config. | Add sort media queries to Grunt mqpacker config.
| JavaScript | mit | jolantis/altair,jolantis/altair | ---
+++
@@ -3,6 +3,7 @@
grunt.config('css_mqpacker', {
options: {
map: false, // enable/disable source maps
+ sort: true,
},
main: {
src: '<%= project.styles_dev %>/main.dev.css', |
8294c6af9e0b469de05b044655fd6e354945c85b | bin/castpipe.js | bin/castpipe.js | #!/usr/bin/env node
'use strict';
var serveStdIn = require('./lib/serveStdIn.js');
var launchChromecastStreamingApp = require('./lib/sendChromecast.js');
var argv = require('yargs')
.usage('Usage: $0 --localIP [--port]')
.option( "localIP", {demand: true, describe: "IP address of computer", type: "string" } )
.option( "port", { demand: false, describe: "Port for server to listen on" } )
.argv;
var server = argv.localIP;
var port = argv.port || 1338;
/*launchChromecastStreamingApp({
title: 'Pipecast',
server: server,
port: port
}, function startServer() {
serveStdIn({
listenOn: server,
port: port
});
});*/
| #!/usr/bin/env node
'use strict';
var serveStdIn = require('../lib/serveStdIn.js');
var launchChromecastStreamingApp = require('../lib/sendChromecast.js');
var argv = require('yargs')
.usage('Usage: $0 --localIP [--port]')
.option( "localIP", {demand: true, describe: "IP address of computer", type: "string" } )
.option( "port", { demand: false, describe: "Port for server to listen on" } )
.argv;
var server = argv.localIP;
var port = argv.port || 1338;
launchChromecastStreamingApp({
title: 'Pipecast',
server: server,
port: port
}, function startServer() {
serveStdIn({
listenOn: server,
port: port
});
});
| Change require to new path. Removed comment that prevents pipecast from working :sweat: | Change require to new path. Removed comment that prevents pipecast from working :sweat:
| JavaScript | mit | fbngrmr/castpipe | ---
+++
@@ -2,8 +2,8 @@
'use strict';
-var serveStdIn = require('./lib/serveStdIn.js');
-var launchChromecastStreamingApp = require('./lib/sendChromecast.js');
+var serveStdIn = require('../lib/serveStdIn.js');
+var launchChromecastStreamingApp = require('../lib/sendChromecast.js');
var argv = require('yargs')
.usage('Usage: $0 --localIP [--port]')
.option( "localIP", {demand: true, describe: "IP address of computer", type: "string" } )
@@ -13,7 +13,7 @@
var server = argv.localIP;
var port = argv.port || 1338;
-/*launchChromecastStreamingApp({
+launchChromecastStreamingApp({
title: 'Pipecast',
server: server,
port: port
@@ -22,4 +22,4 @@
listenOn: server,
port: port
});
-});*/
+}); |
5aa574897c21a5f39d6c66768ea5653c14b869a0 | packages/fyndiq-component-tooltip/src/index.js | packages/fyndiq-component-tooltip/src/index.js | import React from 'react'
import PropTypes from 'prop-types'
import Dropdown from 'fyndiq-component-dropdown'
import styles from '../styles.less'
const Tooltip = ({ text, children, position }) => (
<Dropdown
button={<span>{children}</span>}
hoverMode
noWrapperStyle
position={position}
>
<div
className={`
${styles.tooltip}
${styles['position-' + position]}
`}
>
{text}
</div>
</Dropdown>
)
Tooltip.propTypes = {
text: PropTypes.string,
children: PropTypes.string,
position: Dropdown.propTypes.position,
}
Tooltip.defaultProps = {
text: '',
children: '',
position: 'bc',
}
export default Tooltip
| import React from 'react'
import PropTypes from 'prop-types'
import Dropdown from 'fyndiq-component-dropdown'
import styles from '../styles.less'
const Tooltip = ({ text, children, position }) => (
<Dropdown
button={<span>{children}</span>}
hoverMode
noWrapperStyle
position={position}
>
<div
className={`
${styles.tooltip}
${styles['position-' + position]}
`}
>
{text}
</div>
</Dropdown>
)
Tooltip.propTypes = {
text: PropTypes.string,
children: PropTypes.node,
position: Dropdown.propTypes.position,
}
Tooltip.defaultProps = {
text: '',
children: '',
position: 'bc',
}
export default Tooltip
| Change children propType for tooltip | Change children propType for tooltip
| JavaScript | mit | fyndiq/fyndiq-ui,fyndiq/fyndiq-ui | ---
+++
@@ -24,7 +24,7 @@
Tooltip.propTypes = {
text: PropTypes.string,
- children: PropTypes.string,
+ children: PropTypes.node,
position: Dropdown.propTypes.position,
}
|
8c9231fd97425de77c41764be8f779e7cb07493b | public/js/language-select.js | public/js/language-select.js | const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && urlPathMeta[3] !== 'edit') {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
| const toArray = nodelist => Array.prototype.slice.call(nodelist);
const things = ['method', 'case', 'organization'];
const languageSelect = {
redirectUrl: null,
isThingDetailsPageWithLanguageParam: false,
init(tracking) {
this.tracking = tracking;
this.generateRedirectPath();
const selectEls = document.querySelectorAll(".js-language-select");
if (!selectEls) return;
toArray(selectEls).forEach(select => {
select.addEventListener("change", e => {
this.tracking.sendWithCallback("language", "language_dropdown", e.target.value, () => {
this.handleSelectChange(e);
});
});
});
},
handleSelectChange(e) {
let redirectUrl = this.isThingDetailsPageWithLanguageParam ? `${this.redirectUrl}/${e.target.value}` : this.redirectUrl;
location.href =
`/set-locale?locale=${e.target.value}` +
`&redirectTo=${redirectUrl}`;
},
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && (urlPathMeta[3] !== 'edit')) {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
}
}
};
export default languageSelect;
| Refactor syntax language selector redirect url | Refactor syntax language selector redirect url
| JavaScript | mit | participedia/api,participedia/api,participedia/api,participedia/api | ---
+++
@@ -30,7 +30,7 @@
generateRedirectPath() {
this.redirectUrl = window.location.pathname;
let urlPathMeta = window.location.pathname.split('/');
- if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && urlPathMeta[3] !== 'edit') {
+ if (urlPathMeta[1] && things.indexOf(urlPathMeta[1]) >= 0 && urlPathMeta[3] && (urlPathMeta[3] !== 'edit')) {
this.redirectUrl = `/${urlPathMeta[1]}/${urlPathMeta[2]}`;
this.isThingDetailsPageWithLanguageParam = true;
} |
e9841437c4834710354bf0c00ccf5d7c9eb8ffaa | src/components/App/index.js | src/components/App/index.js | import React from 'react'
const App = () => (
<h1>Hello from React</h1>
)
export default App
| import React from 'react'
import Counter from '../../containers/Counter'
const App = () => (
<div>
<Counter />
</div>
)
export default App
| Put the Counter into App | Put the Counter into App
| JavaScript | mit | epicsharp/react-boilerplate,RSS-Dev/live-html,epicsharp/react-boilerplate,RSS-Dev/live-html | ---
+++
@@ -1,7 +1,11 @@
import React from 'react'
+import Counter from '../../containers/Counter'
+
const App = () => (
- <h1>Hello from React</h1>
+ <div>
+ <Counter />
+ </div>
)
export default App |
4aa4466ac5f30870be92724a571c557dc48dc4ed | src/repl/main.js | src/repl/main.js | import Repl from './Repl.html';
import examples from './examples.js';
function tryParseData ( encoded ) {
try {
return JSON.parse( decodeURIComponent( atob( encoded ) ) );
} catch ( err ) {
return {};
}
}
if ( typeof svelte !== 'undefined' ) {
const dataMatch = /data=(.+)$/.exec( window.location.search );
const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {};
const gistMatch = /gist=(.+)$/.exec( window.location.search );
const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist );
const repl = new Repl({
target: document.querySelector( 'main' ),
data: {
gist,
source,
data
}
});
window.repl = repl;
} else {
document.querySelector( 'main' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
}
| import Repl from './Repl.html';
import examples from './examples.js';
function tryParseData ( encoded ) {
try {
return JSON.parse( decodeURIComponent( atob( encoded ) ) );
} catch ( err ) {
return {};
}
}
if ( typeof svelte !== 'undefined' ) {
const dataMatch = /data=(.+)$/.exec( window.location.search );
const { source, data } = dataMatch ? tryParseData( dataMatch[1] ) : {};
const gistMatch = /gist=(.+)$/.exec( window.location.search );
const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist );
const repl = new Repl({
target: document.querySelector( '.repl' ),
data: {
gist,
source,
data
}
});
window.repl = repl;
} else {
document.querySelector( '.repl' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
}
| Adjust REPL component target element | Adjust REPL component target element
| JavaScript | mit | sveltejs/svelte.technology,sveltejs/svelte.technology | ---
+++
@@ -17,7 +17,7 @@
const gist = gistMatch ? gistMatch[1] : ( source ? null : examples[0].gist );
const repl = new Repl({
- target: document.querySelector( 'main' ),
+ target: document.querySelector( '.repl' ),
data: {
gist,
source,
@@ -27,5 +27,5 @@
window.repl = repl;
} else {
- document.querySelector( 'main' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
+ document.querySelector( '.repl' ).innerHTML = `<p style='text-align: center; margin: 0; padding: 4em 3em 8em 3em; line-height: 1.5;'>Svelte generates components that work in all modern JavaScript environments, but the Svelte compiler only runs in Node 6+ and browsers that support ES2015 features. Please reopen this page in a different browser such as Chrome.</p>`;
} |
ec23be002f6658e2743f02a673e30cacd704b34c | src/components/Nav/index.js | src/components/Nav/index.js | import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import nav from '../icons/nav';
import styles from './index.module.less';
export default class index extends Component {
constructor() {
super();
this.state = {};
}
render() {
const { routerData } = this.props;
return (
<div className={styles.nav}>
{this.props.menuData.map((item, idx) => {
let icon = item.icon;
if (Object.keys(nav).includes(icon)) {
icon = nav[icon];
}
if (/^https?:(?:\/\/)?/.test(item.path)) {
return <a key={idx} target="__blank" href={item.path}>{icon}</a>;
}
let noPath = null;
if (!routerData[item.path] && item.children && item.children.length > 0) {
noPath = item.children[0].path;
}
return <NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}>{icon}</NavLink>;
})}
</div>
);
}
}
| import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import { Tooltip } from '@uiw/core';
import nav from '../icons/nav';
import styles from './index.module.less';
export default class index extends Component {
constructor() {
super();
this.state = {};
}
render() {
const { routerData } = this.props;
return (
<div className={styles.nav}>
{this.props.menuData.map((item, idx) => {
let icon = item.icon;
if (Object.keys(nav).includes(icon)) {
icon = nav[icon];
}
if (/^https?:(?:\/\/)?/.test(item.path)) {
return (
<a key={idx} target="__blank" href={item.path}>
<Tooltip placement="right" content={item.name}>
{icon}
</Tooltip>
</a>
);
}
let noPath = null;
if (!routerData[item.path] && item.children && item.children.length > 0) {
noPath = item.children[0].path;
}
return (
<NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}>
<Tooltip placement="right" content={item.name}>
{icon}
</Tooltip>
</NavLink>
);
})}
</div>
);
}
}
| Modify the website nav style. | docs: Modify the website nav style.
| JavaScript | mit | uiw-react/uiw,uiw-react/uiw | ---
+++
@@ -1,5 +1,6 @@
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
+import { Tooltip } from '@uiw/core';
import nav from '../icons/nav';
import styles from './index.module.less';
@@ -18,13 +19,25 @@
icon = nav[icon];
}
if (/^https?:(?:\/\/)?/.test(item.path)) {
- return <a key={idx} target="__blank" href={item.path}>{icon}</a>;
+ return (
+ <a key={idx} target="__blank" href={item.path}>
+ <Tooltip placement="right" content={item.name}>
+ {icon}
+ </Tooltip>
+ </a>
+ );
}
let noPath = null;
if (!routerData[item.path] && item.children && item.children.length > 0) {
noPath = item.children[0].path;
}
- return <NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}>{icon}</NavLink>;
+ return (
+ <NavLink activeClassName={styles.selected} key={idx} to={noPath || item.path}>
+ <Tooltip placement="right" content={item.name}>
+ {icon}
+ </Tooltip>
+ </NavLink>
+ );
})}
</div>
); |
b0609358beb1785b07e1eb2b643a9e25a8b500a4 | js/app.js | js/app.js | (function() {
'use strict';
// Model
var Task = Backbone.Model.extend({
defaults: {
title: 'do something!',
completed: false
},
validate: function (attr) {
if (_.isEmpty(attr.title)) {
return 'title must not be empty!';
}
},
toggle: function () {
this.set('completed', !this.get('completed'));
}
});
var task1 = new Task({
completed: true
});
// setter
// task1.set('title', 'newTitle');
// console.log(task1.toJSON());
// getter
// var title = task1.get('title');
// console.log(title);
// validattion
console.log(task1.toJSON().title);
task1.set({title: ''}, {validate: true});
console.log(task1.toJSON().title);
}());
| (function() {
'use strict';
// Model
var Task = Backbone.Model.extend({
defaults: {
title: 'do something!',
completed: false
}
});
var task = new Task();
// View
var TaskView = Backbone.View.extend({
tagName: 'li'
});
var taskView = new TaskView({
model: task
});
console.log(taskView.$el);
}());
| Create list tag in View. | Create list tag in View.
| JavaScript | mit | shgtkshruch/dotinstall-backbone | ---
+++
@@ -7,32 +7,21 @@
defaults: {
title: 'do something!',
completed: false
- },
- validate: function (attr) {
- if (_.isEmpty(attr.title)) {
- return 'title must not be empty!';
- }
- },
- toggle: function () {
- this.set('completed', !this.get('completed'));
}
});
- var task1 = new Task({
- completed: true
+ var task = new Task();
+
+ // View
+
+ var TaskView = Backbone.View.extend({
+ tagName: 'li'
});
- // setter
- // task1.set('title', 'newTitle');
- // console.log(task1.toJSON());
+ var taskView = new TaskView({
+ model: task
+ });
- // getter
- // var title = task1.get('title');
- // console.log(title);
+ console.log(taskView.$el);
- // validattion
- console.log(task1.toJSON().title);
- task1.set({title: ''}, {validate: true});
- console.log(task1.toJSON().title);
-
}()); |
230e7fa0663afc90df0359c574309afe8d018749 | app/services/interceptor/api-interceptor.service.js | app/services/interceptor/api-interceptor.service.js | (function () {
'use strict';
angular
.module('doleticApp')
.service('APIInterceptorService', APIInterceptorService);
APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', 'store'];
function APIInterceptorService($rootScope, $q, AuthService) {
var service = this;
service.request = function (config) {
var access_token = AuthService.getAccessToken();
var token_type = AuthService.getTokenType();
if (access_token && token_type) {
config.headers.Authorization = token_type + " " + access_token;
}
return config;
};
service.responseError = function (rejection) {
return $q.reject(rejection);
};
service.requestError = function (rejection) {
//SharedVariables.messageBox.show = true;
return $q.reject(rejection);
};
}
})(); | (function () {
'use strict';
angular
.module('doleticApp')
.service('APIInterceptorService', APIInterceptorService);
APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', '$injector', 'MessageBoxService'];
function APIInterceptorService($rootScope, $q, AuthService, $injector, MessageBoxService) {
var service = this;
service.request = function (config) {
var access_token = AuthService.getAccessToken();
var token_type = AuthService.getTokenType();
if (access_token && token_type) {
config.headers.Authorization = token_type + " " + access_token;
}
return config;
};
service.responseError = function(response) {
if (response.status == 401){
MessageBoxService.showError('Erreur 401',response.statusText);
logout();
}
return $q.reject(response);
};
service.requestError = function (rejection) {
//SharedVariables.messageBox.show = true;
return $q.reject(rejection);
};
function logout() {
AuthService.setLogged(false);
AuthService.setAccessToken(null);
$injector.get('$state').go('login');
// event.preventDefault();
}
}
})(); | Add api 401 unauthorized interception and redirect to login | Add api 401 unauthorized interception and redirect to login
| JavaScript | mit | JuCN/DoleticRESTClient,ETICINSATechnologies/DoleticRESTClient,nsorin/DoleticRESTClient,JuCN/DoleticRESTClient,ETICINSATechnologies/DoleticRESTClient,nsorin/DoleticRESTClient | ---
+++
@@ -5,9 +5,9 @@
.module('doleticApp')
.service('APIInterceptorService', APIInterceptorService);
- APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', 'store'];
+ APIInterceptorService.$inject = ['$rootScope', '$q', 'AuthService', '$injector', 'MessageBoxService'];
- function APIInterceptorService($rootScope, $q, AuthService) {
+ function APIInterceptorService($rootScope, $q, AuthService, $injector, MessageBoxService) {
var service = this;
service.request = function (config) {
var access_token = AuthService.getAccessToken();
@@ -17,13 +17,24 @@
}
return config;
};
- service.responseError = function (rejection) {
- return $q.reject(rejection);
+ service.responseError = function(response) {
+ if (response.status == 401){
+ MessageBoxService.showError('Erreur 401',response.statusText);
+ logout();
+ }
+ return $q.reject(response);
};
service.requestError = function (rejection) {
//SharedVariables.messageBox.show = true;
return $q.reject(rejection);
};
+
+ function logout() {
+ AuthService.setLogged(false);
+ AuthService.setAccessToken(null);
+ $injector.get('$state').go('login');
+ // event.preventDefault();
+ }
}
})(); |
ee03bf731294a55a6c59d567f4540dc7e8d88d16 | package.js | package.js | Package.describe({
summary: "Meteor unit testing framework for packages",
name: "spacejamio:munit",
version: "1.0.0",
git: "https://github.com/spacejamio/meteor-munit.git"
});
Package.onUse(function (api, where) {
api.versionsFrom('0.9.0');
api.use(["coffeescript", "underscore"]);
api.use(["tinytest","test-helpers"]);
api.use(["spacejamio:chai","spacejamio:sinon"]);
api.imply(["tinytest","test-helpers"]);
api.imply(["spacejamio:chai","spacejamio:sinon"]);
api.addFiles("namespaces.js");
api.addFiles("async_multi.js");
api.addFiles("Munit.coffee");
api.addFiles("Helpers.coffee");
api.addFiles("Describe.coffee");
api.export(['lvTestAsyncMulti']);
api.export(['Munit', 'chai']);
api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']);
});
Package.onTest(function(api) {
api.use(["coffeescript", "spacejamio:munit"]);
api.addFiles("tests/TestRunnerTest.coffee");
api.addFiles("tests/HelpersTest.coffee");
api.addFiles("tests/DescribeTest.coffee");
});
| Package.describe({
summary: "Meteor unit testing framework for packages",
name: "spacejamio:munit",
version: "1.0.0",
git: "https://github.com/spacejamio/meteor-munit.git"
});
Package.onUse(function (api, where) {
api.versionsFrom('0.9.0');
api.use(["coffeescript", "underscore"]);
api.use(["tinytest","test-helpers"]);
api.use(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]);
api.imply(["tinytest","test-helpers"]);
api.imply(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]);
api.addFiles("namespaces.js");
api.addFiles("async_multi.js");
api.addFiles("Munit.coffee");
api.addFiles("Helpers.coffee");
api.addFiles("Describe.coffee");
api.export(['lvTestAsyncMulti']);
api.export(['Munit', 'chai']);
api.export(['describe', 'it', 'beforeAll', 'beforeEach', 'afterEach', 'afterAll']);
});
Package.onTest(function(api) {
api.use(["coffeescript", "spacejamio:munit"]);
api.addFiles("tests/TestRunnerTest.coffee");
api.addFiles("tests/HelpersTest.coffee");
api.addFiles("tests/DescribeTest.coffee");
});
| Add version contraints for sinon and chai | Add version contraints for sinon and chai
| JavaScript | mit | awatson1978/clinical-verification,practicalmeteor/meteor-munit | ---
+++
@@ -10,10 +10,10 @@
api.use(["coffeescript", "underscore"]);
api.use(["tinytest","test-helpers"]);
- api.use(["spacejamio:chai","spacejamio:sinon"]);
+ api.use(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]);
api.imply(["tinytest","test-helpers"]);
- api.imply(["spacejamio:chai","spacejamio:sinon"]);
+ api.imply(["spacejamio:chai@1.0.0", "spacejamio:sinon@1.0.0"]);
api.addFiles("namespaces.js");
api.addFiles("async_multi.js"); |
801a263ea3a7aac846b860b8933669a728af06d0 | src/contexts/NodeContext.js | src/contexts/NodeContext.js | const {JsContext} = require('stencila')
/**
* A Node.js context for executing Javascript code
*/
class NodeContext extends JsContext {}
NodeContext.spec = {
name: 'NodeContext',
base: 'Context',
aliases: ['js', 'node']
}
module.exports = NodeContext
| const {JsContext} = require('stencila')
/**
* A Node.js context for executing Javascript code
*/
class NodeContext extends JsContext {}
NodeContext.spec = {
name: 'NodeContext',
client: 'ContextHttpClient',
aliases: ['js', 'node']
}
module.exports = NodeContext
| Switch to new spec protocol | Switch to new spec protocol
| JavaScript | apache-2.0 | stencila/node,stencila/node | ---
+++
@@ -7,7 +7,7 @@
NodeContext.spec = {
name: 'NodeContext',
- base: 'Context',
+ client: 'ContextHttpClient',
aliases: ['js', 'node']
}
|
9a7d99c50367f8b9e0fcf31d5e326ac622672850 | src/shapes.js | src/shapes.js | /**
* Values suitable for use within `propTypes` of components.
*
* @module higherform
*/
import { PropTypes } from 'react';
export const FormShape = PropTypes.shape({
validate: PropTypes.func,
errors: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
});
export const FieldShape = PropTypes.object;
export const FieldsShape = PropTypes.objectOf(FieldShape);
| /**
* Values suitable for use within `propTypes` of components.
*
* @module higherform
*/
import { PropTypes } from 'react';
export const FormShape = PropTypes.shape({
submit: PropTypes.func,
errors: PropTypes.object,
});
export const FieldShape = PropTypes.object;
export const FieldsShape = PropTypes.objectOf(FieldShape);
| Use the Correct PropTypes for the FormShape | Use the Correct PropTypes for the FormShape
| JavaScript | mit | AgencyPMG/higherform,AgencyPMG/higherform | ---
+++
@@ -7,8 +7,8 @@
import { PropTypes } from 'react';
export const FormShape = PropTypes.shape({
- validate: PropTypes.func,
- errors: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
+ submit: PropTypes.func,
+ errors: PropTypes.object,
});
export const FieldShape = PropTypes.object; |
d8c5d622facc6459b1e97f99bac8d9cc1819480f | abstract.js | abstract.js | 'use strict';
var assign = require('es5-ext/object/assign')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d')
, captureStackTrace = Error.captureStackTrace
, AbstractError;
AbstractError = function AbstractError(message/*, code, ext*/) {
var ext, code;
if (!(this instanceof AbstractError)) {
return new AbstractError(message, code, arguments[2]);
}
code = arguments[1];
ext = arguments[2];
if (ext == null) {
if (code && (typeof code === 'object')) {
ext = code;
code = null;
}
}
if (ext != null) assign(this, ext);
this.message = String(message);
if (code != null) this.code = String(code);
this.name = this.constructor.name;
if (captureStackTrace) captureStackTrace(this, this.constructor);
};
if (setPrototypeOf) setPrototypeOf(AbstractError, Error);
AbstractError.prototype = Object.create(Error.prototype, {
constructor: d(AbstractError)
});
module.exports = AbstractError;
| 'use strict';
var assign = require('es5-ext/object/assign')
, setPrototypeOf = require('es5-ext/object/set-prototype-of')
, d = require('d')
, captureStackTrace = Error.captureStackTrace
, AbstractError;
AbstractError = function AbstractError(message/*, code, ext*/) {
var ext, code;
if (!(this instanceof AbstractError)) {
return new AbstractError(message, arguments[1], arguments[2]);
}
code = arguments[1];
ext = arguments[2];
if (ext == null) {
if (code && (typeof code === 'object')) {
ext = code;
code = null;
}
}
if (ext != null) assign(this, ext);
this.message = String(message);
if (code != null) this.code = String(code);
this.name = this.constructor.name;
if (captureStackTrace) captureStackTrace(this, this.constructor);
};
if (setPrototypeOf) setPrototypeOf(AbstractError, Error);
AbstractError.prototype = Object.create(Error.prototype, {
constructor: d(AbstractError)
});
module.exports = AbstractError;
| Fix pass of arguments issue | Fix pass of arguments issue
| JavaScript | mit | medikoo/error-create | ---
+++
@@ -10,7 +10,7 @@
AbstractError = function AbstractError(message/*, code, ext*/) {
var ext, code;
if (!(this instanceof AbstractError)) {
- return new AbstractError(message, code, arguments[2]);
+ return new AbstractError(message, arguments[1], arguments[2]);
}
code = arguments[1];
ext = arguments[2]; |
b9be6a6fccd7558f3aa704972c4ac53e377c43c1 | src/foam/dao/DAOProperty.js | src/foam/dao/DAOProperty.js | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
foam.CLASS({
package: 'foam.dao',
name: 'DAOProperty',
extends: 'Property',
documentation: 'Property for storing a reference to a DAO.',
requires: [ 'foam.dao.ProxyDAO' ],
properties: [
{
name: 'view',
value: {class: 'foam.comics.InlineBrowserView'},
}
],
methods: [
function installInProto(proto) {
this.SUPER(proto);
var name = this.name;
var prop = this;
Object.defineProperty(proto, name + '$proxy', {
get: function daoProxyGetter() {
var proxy = prop.ProxyDAO.create({delegate: this[name]});
this[name + '$proxy'] = proxy;
this.sub('propertyChange', name, function(_, __, ___, s) {
proxy.delegate = s.get();
});
return proxy;
},
configurable: true
});
}
]
});
| /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
foam.CLASS({
package: 'foam.dao',
name: 'DAOProperty',
extends: 'FObjectProperty',
documentation: 'Property for storing a reference to a DAO.',
requires: [ 'foam.dao.ProxyDAO' ],
properties: [
{
name: 'view',
value: {class: 'foam.comics.InlineBrowserView'},
},
['of', 'foam.dao.DAO']
],
methods: [
function installInProto(proto) {
this.SUPER(proto);
var name = this.name;
var prop = this;
Object.defineProperty(proto, name + '$proxy', {
get: function daoProxyGetter() {
var proxy = prop.ProxyDAO.create({delegate: this[name]});
this[name + '$proxy'] = proxy;
this.sub('propertyChange', name, function(_, __, ___, s) {
proxy.delegate = s.get();
});
return proxy;
},
configurable: true
});
}
]
});
| Fix java generatino of DAOSink. | Fix java generatino of DAOSink.
| JavaScript | apache-2.0 | foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm | ---
+++
@@ -18,7 +18,7 @@
foam.CLASS({
package: 'foam.dao',
name: 'DAOProperty',
- extends: 'Property',
+ extends: 'FObjectProperty',
documentation: 'Property for storing a reference to a DAO.',
@@ -28,7 +28,8 @@
{
name: 'view',
value: {class: 'foam.comics.InlineBrowserView'},
- }
+ },
+ ['of', 'foam.dao.DAO']
],
methods: [ |
b8eedc06fef0a78f6d58a49c0efec766d186d67e | db/controllers/bookmarks.js | db/controllers/bookmarks.js | var Bookmark = require('../models/index.js').Bookmark;
var create = function(props, callback) {
Bookmark.build(props)
.save()
.then(function(bookmark) {
callback(bookmark);
}).catch(function(err) {
console.log(err);
});
};
var findAll = function(callback) {
Bookmark.findAll().then(function(bookmarks) {
callback(bookmarks);
}).catch(function(err) {
console.log(err);
});
};
var findOne = function(query, callback) {
Bookmark.findOne(query).done(function(bookmark) {
console.log(bookmark, 'BOOOKMARK');
callback(bookmark);
});
};
exports.create = create;
exports.findAll = findAll;
exports.findOne = findOne; | var Bookmark = require('../models/index.js').Bookmark;
var create = function(props, callback) {
Bookmark.build(props)
.save()
.then(function(bookmark) {
callback(bookmark);
}).catch(function(err) {
console.log(err);
});
};
var findAll = function(callback) {
Bookmark.findAll().then(function(bookmarks) {
callback(bookmarks);
}).catch(function(err) {
console.log(err);
});
};
var findOne = function(query, callback) {
Bookmark.findOne(query).done(function(bookmark) {
console.log('🍊 Found one bookmark in db:', query);
callback(bookmark);
});
};
exports.create = create;
exports.findAll = findAll;
exports.findOne = findOne; | Improve conciseness of console.log messages | Improve conciseness of console.log messages
| JavaScript | mit | francoabaroa/escape-reality,lowtalkers/escape-reality,lowtalkers/escape-reality,francoabaroa/escape-reality | ---
+++
@@ -20,8 +20,8 @@
var findOne = function(query, callback) {
Bookmark.findOne(query).done(function(bookmark) {
- console.log(bookmark, 'BOOOKMARK');
- callback(bookmark);
+ console.log('🍊 Found one bookmark in db:', query);
+ callback(bookmark);
});
};
|
eb4b103186cc77f543b463fe3b2f9a5e79676c2d | lib/search-contents-for-titles.js | lib/search-contents-for-titles.js | /**
* Searches a content string for titles by the keyword
* @param {string} contents - File contents as a utf8 string
* @param {object} cfg - Config object
* @param {string} [title] - Title to search for
*/
module.exports = (contents, cfg, title) => {
const regexFlags = cfg.caseSensitive ? 'g' : 'gi'
const re = new RegExp(`${cfg.keyword}\\s?${title || '(.*)'}`, regexFlags)
const matches = contents.match(re)
if (matches) {
return matches.map(title => title.replace(new RegExp(`${cfg.keyword} ?`, regexFlags), ''))
}
}
| /**
* Searches a content string for titles by the keyword
* @param {string} contents - File contents as a utf8 string
* @param {object} cfg - Config object
* @param {string} [title] - Title to search for
*/
module.exports = (contents, cfg, title) => {
const regexFlags = cfg.caseSensitive ? 'g' : 'gi'
const re = new RegExp(`${cfg.keyword}:?\\s?${title || '(.*)'}`, regexFlags)
const matches = contents.match(re)
if (matches) {
return matches.map(title => title.replace(new RegExp(`${cfg.keyword} ?`, regexFlags), ''))
}
}
| Tweak RegEx to add colon | Tweak RegEx to add colon
| JavaScript | isc | JasonEtco/todo | ---
+++
@@ -6,7 +6,7 @@
*/
module.exports = (contents, cfg, title) => {
const regexFlags = cfg.caseSensitive ? 'g' : 'gi'
- const re = new RegExp(`${cfg.keyword}\\s?${title || '(.*)'}`, regexFlags)
+ const re = new RegExp(`${cfg.keyword}:?\\s?${title || '(.*)'}`, regexFlags)
const matches = contents.match(re)
if (matches) { |
02a3f5b3fb131e05b10a4dc0fe868ea28b275f61 | lib/BaseObject.js | lib/BaseObject.js | module.exports = exports = function BaseObject(key, myRedis, options) {
this.key = key;
if (myRedis && !options) {
options = myRedis;
myRedis = null;
}
if (!options) options = {};
this.options = options;
this.myRedis = myRedis;
};
exports.prototype.redis = function() {
return this.myRedis || require('../index').connect();
};
exports.prototype.inspect = function() {
return '#<' + this.constructor.name + ' key: ' + this.key + ' opts: ' + JSON.stringify(this.options) + '>';
};
require('./serialize').mixin(exports);
| module.exports = exports = function BaseObject(key, myRedis, options) {
this.key = key;
if (myRedis && !options) {
options = myRedis;
myRedis = null;
}
if (!options) options = {};
this.options = options;
this.myRedis = myRedis;
};
exports.prototype.redis = function() {
return this.myRedis || require('../index').connect();
};
exports.prototype.clear = function(callback) {
this.redis().del(this.key, callback);
};
exports.prototype.inspect = function() {
return '#<' + this.constructor.name + ' key: ' + this.key + '>';
};
require('./serialize').mixin(exports);
| Add clear command to base object, and simplify inspect | Add clear command to base object, and simplify inspect
| JavaScript | mit | hfwang/node-redis-objects | ---
+++
@@ -15,8 +15,12 @@
return this.myRedis || require('../index').connect();
};
+exports.prototype.clear = function(callback) {
+ this.redis().del(this.key, callback);
+};
+
exports.prototype.inspect = function() {
- return '#<' + this.constructor.name + ' key: ' + this.key + ' opts: ' + JSON.stringify(this.options) + '>';
+ return '#<' + this.constructor.name + ' key: ' + this.key + '>';
};
require('./serialize').mixin(exports); |
ad002ab21ef7400ef8df3314ac739a544e1220d3 | both/router/routes.js | both/router/routes.js | /*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
Router.configure({
layoutTemplate: 'MasterLayout',
loadingTemplate: 'Loading',
notFoundTemplate: 'NotFound'
});
Router.route('/', {
name: 'marketing'
});
Router.route('/pages', {
name: 'pages.index'
});
Router.route('/pages/new', {
name: 'pages.new'
});
Router.route('/pages/:_id', {
name: 'pages.show'
});
Router.route('/settings', {
name: 'settings.index'
});
Router.route('/users/:_id', {
name: 'users.show'
});
Router.route('/users/:_id/edit', {
name:'users.edit'
});
var requireLogin = function () {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('AccessDenied');
}
} else {
this.next();
}
};
Router.onBeforeAction('dataNotFound');
Router.onBeforeAction(requireLogin, {
only: [
'pages.index',
'pages.new',
'settings.index',
'users.show',
'users.edit'
]
});
| /*****************************************************************************/
/* Client and Server Routes */
/*****************************************************************************/
Router.configure({
layoutTemplate: 'MasterLayout',
loadingTemplate: 'Loading',
notFoundTemplate: 'NotFound'
});
Router.route('/', {
name: 'marketing'
});
Router.route('/pages', {
name: 'pages.index'
});
Router.route('/pages/new', {
name: 'pages.new'
});
Router.route('/pages/:_id', {
name: 'pages.show'
});
Router.route('/settings', {
name: 'settings.index'
});
Router.route('/users/:_id', {
name: 'users.show'
});
Router.route('/users/:_id/edit', {
name:'users.edit'
});
var requireLogin = function () {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('AccessDenied');
}
} else {
this.next();
}
};
Router.onBeforeAction('dataNotFound');
Router.onBeforeAction(requireLogin, {
except: [
'marketing',
'pages.show'
]
});
| Use route whitelist method for security | Use route whitelist method for security
| JavaScript | mit | bojicas/letterhead,bojicas/letterhead | ---
+++
@@ -49,11 +49,8 @@
Router.onBeforeAction('dataNotFound');
Router.onBeforeAction(requireLogin, {
- only: [
- 'pages.index',
- 'pages.new',
- 'settings.index',
- 'users.show',
- 'users.edit'
+ except: [
+ 'marketing',
+ 'pages.show'
]
}); |
cf17c59c7ad1848edd16c10cfcbf493aa6640b0f | lib/env_loader.js | lib/env_loader.js | 'use strict';
var os = require('os');
var path = require('path');
var dotenv = require('dotenv');
var defaultMappings = {
username: 'SCS_USERNAME',
password: 'SCS_PASSWORD'
};
module.exports = {
/**
* @param {Object} program
* @param {Object} argumentMappings - optional
*/
loadConfig(program, argumentMappings) {
// Try to load the config from the user home
dotenv.config({
path: path.resolve(os.homedir(), '.scs-commander'),
silent: true
});
// Copy env values to the program, but don't overwrite passed arguments
var mappings = argumentMappings || defaultMappings;
Object.keys(mappings).forEach(argKey => {
var envKey = mappings[argKey];
if (envKey in process.env && !(argKey in program)) {
program[argKey] = process.env[envKey];
}
});
}
}
| 'use strict';
var os = require('os');
var path = require('path');
var dotenv = require('dotenv');
var defaultMappings = {
username: 'SCS_USERNAME',
password: 'SCS_PASSWORD'
};
module.exports = {
/**
* @param {Object} program
* @param {Object} argumentMappings - optional
*/
loadConfig(program, argumentMappings) {
// Try to load the config from the user home
dotenv.config({
path: path.resolve(os.homedir(), '.scs-commander'),
silent: true
});
// Check for a 'username' passed as an argument to the program, because we don't
// want to set the password from the .env file, if a different username was passed
var originalUsername = program.username;
// Copy env values to the program, but don't overwrite passed arguments
var mappings = argumentMappings || defaultMappings;
Object.keys(mappings).forEach(argKey => {
var envKey = mappings[argKey];
if (envKey in process.env && !(argKey in program)) {
program[argKey] = process.env[envKey];
}
});
// Reset the password set in the porogram, if the passed username and the one
// now in the program don't match. This allows to overwrite the account to be
// used, even if all account data is set in the .env file.
if (originalUsername && originalUsername.length > 0 && process.env[defaultMappings.username] != originalUsername) {
delete program.password;
}
}
}
| Fix overwriting of username by passing ‘-u|—username’ | Fix overwriting of username by passing ‘-u|—username’
| JavaScript | mit | VIISON/scs-commander | ---
+++
@@ -22,6 +22,10 @@
silent: true
});
+ // Check for a 'username' passed as an argument to the program, because we don't
+ // want to set the password from the .env file, if a different username was passed
+ var originalUsername = program.username;
+
// Copy env values to the program, but don't overwrite passed arguments
var mappings = argumentMappings || defaultMappings;
Object.keys(mappings).forEach(argKey => {
@@ -30,6 +34,13 @@
program[argKey] = process.env[envKey];
}
});
+
+ // Reset the password set in the porogram, if the passed username and the one
+ // now in the program don't match. This allows to overwrite the account to be
+ // used, even if all account data is set in the .env file.
+ if (originalUsername && originalUsername.length > 0 && process.env[defaultMappings.username] != originalUsername) {
+ delete program.password;
+ }
}
} |
36ddabe8adc90b4a4dcc8da7a91c5724fba47c5d | root/include/news_look_up.js | root/include/news_look_up.js |
function yql_lookup(query, cb_function) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';
//alert(url);
$.getJSON(url, cb_function);
}
function look_up_news() {
var feed_url = 'http://www.mediacloud.org/feed/';
//alert(google_url);
yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {
var results = response.query.results;
var news_items = $('#news_items');
//console.log(results);
news_items.children().remove();
news_items.html('');
$.each(results.item, function (index, element) {
var title = element.title;
var link = element.link;
news_items.append($('<a/>', {
'href': link
}).text(title)).append('<br/>');
});
});
}
|
function yql_lookup(query, cb_function) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';
//alert(url);
$.getJSON(url, cb_function);
}
function look_up_news() {
var feed_url = 'http://mediacloud.org/blog/feed/';
//alert(google_url);
yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {
var results = response.query.results;
var news_items = $('#news_items');
//console.log(results);
news_items.children().remove();
news_items.html('');
$.each(results.item, function (index, element) {
var title = element.title;
var link = element.link;
news_items.append($('<a/>', {
'href': link
}).text(title)).append('<br/>');
});
});
}
| Update to use new blog location. | Update to use new blog location.
| JavaScript | agpl-3.0 | AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud | ---
+++
@@ -9,7 +9,7 @@
function look_up_news() {
- var feed_url = 'http://www.mediacloud.org/feed/';
+ var feed_url = 'http://mediacloud.org/blog/feed/';
//alert(google_url);
yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { |
7a25a4d2236ddc7cee625ba2137b086614bb15a6 | src/main/webapp/gulpfile.js | src/main/webapp/gulpfile.js | 'use strict';
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var csslint = require('gulp-csslint');
gulp.task('lint', ['jshint', 'csslint']);
gulp.task('jshint', function() {
return gulp.src('./js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('csslint', function() {
return gulp.src('./css/*.css')
.pipe(csslint())
.pipe(csslint.reporter('checkstyle-xml'));
});
| // jshint ignore:start
'use strict';
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var csslint = require('gulp-csslint');
gulp.task('lint', ['jshint', 'csslint']);
gulp.task('jshint', function() {
return gulp.src('./js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('checkstyle'));
});
gulp.task('csslint', function() {
return gulp.src('./css/*.css')
.pipe(csslint())
.pipe(csslint.reporter('checkstyle-xml'));
});
| Use checkstyle output from jshint reporter | [TECG-125] Use checkstyle output from jshint reporter
| JavaScript | apache-2.0 | ciandt-dev/tech-gallery,ciandt-dev/tech-gallery,ciandt-dev/tech-gallery | ---
+++
@@ -1,3 +1,4 @@
+// jshint ignore:start
'use strict';
var gulp = require('gulp');
@@ -9,7 +10,7 @@
gulp.task('jshint', function() {
return gulp.src('./js/*.js')
.pipe(jshint())
- .pipe(jshint.reporter('jshint-stylish'));
+ .pipe(jshint.reporter('checkstyle'));
});
gulp.task('csslint', function() { |
34b352a0a6bae910dfb825ee74ec8c15848e5cfc | batch/pubsub/queue-seeker.js | batch/pubsub/queue-seeker.js | 'use strict';
var QUEUE = require('../job_queue').QUEUE;
function QueueSeeker(pool) {
this.pool = pool;
}
module.exports = QueueSeeker;
QueueSeeker.prototype.seek = function (callback) {
var initialCursor = ['0'];
var users = {};
var self = this;
this.pool.acquire(QUEUE.DB, function(err, client) {
if (err) {
return callback(err);
}
self._seek(client, initialCursor, users, function(err, users) {
self.pool.release(QUEUE.DB, client);
return callback(err, Object.keys(users));
});
});
};
QueueSeeker.prototype._seek = function (client, cursor, users, callback) {
var self = this;
var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*'];
client.scan(redisParams, function(err, currentCursor) {
if (err) {
return callback(null, users);
}
var queues = currentCursor[1];
if (queues) {
queues.forEach(function (queue) {
var user = queue.substr(QUEUE.PREFIX.length);
users[user] = true;
});
}
var hasMore = currentCursor[0] !== '0';
if (!hasMore) {
return callback(null, users);
}
self._seek(client, currentCursor, users, callback);
});
};
| 'use strict';
var QUEUE = require('../job_queue').QUEUE;
var MAX_SCAN_ATTEMPTS = 50;
function QueueSeeker(pool) {
this.pool = pool;
}
module.exports = QueueSeeker;
QueueSeeker.prototype.seek = function (callback) {
var initialCursor = ['0'];
var attemps = 0;
var users = {};
var self = this;
this.pool.acquire(QUEUE.DB, function(err, client) {
if (err) {
return callback(err);
}
self._seek(client, initialCursor, users, attemps, function(err, users) {
self.pool.release(QUEUE.DB, client);
return callback(err, Object.keys(users));
});
});
};
QueueSeeker.prototype._seek = function (client, cursor, users, attemps, callback) {
var self = this;
var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*'];
client.scan(redisParams, function(err, currentCursor) {
if (err) {
return callback(null, users);
}
var queues = currentCursor[1];
if (queues) {
queues.forEach(function (queue) {
var user = queue.substr(QUEUE.PREFIX.length);
users[user] = true;
});
}
var hasMore = currentCursor[0] !== '0' && attemps < MAX_SCAN_ATTEMPTS;
if (!hasMore) {
return callback(null, users);
}
attemps += 1;
self._seek(client, currentCursor, users, attemps, callback);
});
};
| Use max number of attempts to scan user queues | Use max number of attempts to scan user queues
| JavaScript | bsd-3-clause | CartoDB/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API | ---
+++
@@ -1,6 +1,7 @@
'use strict';
var QUEUE = require('../job_queue').QUEUE;
+var MAX_SCAN_ATTEMPTS = 50;
function QueueSeeker(pool) {
this.pool = pool;
@@ -10,6 +11,7 @@
QueueSeeker.prototype.seek = function (callback) {
var initialCursor = ['0'];
+ var attemps = 0;
var users = {};
var self = this;
@@ -17,14 +19,14 @@
if (err) {
return callback(err);
}
- self._seek(client, initialCursor, users, function(err, users) {
+ self._seek(client, initialCursor, users, attemps, function(err, users) {
self.pool.release(QUEUE.DB, client);
return callback(err, Object.keys(users));
});
});
};
-QueueSeeker.prototype._seek = function (client, cursor, users, callback) {
+QueueSeeker.prototype._seek = function (client, cursor, users, attemps, callback) {
var self = this;
var redisParams = [cursor[0], 'MATCH', QUEUE.PREFIX + '*'];
@@ -41,11 +43,13 @@
});
}
- var hasMore = currentCursor[0] !== '0';
+ var hasMore = currentCursor[0] !== '0' && attemps < MAX_SCAN_ATTEMPTS;
if (!hasMore) {
return callback(null, users);
}
- self._seek(client, currentCursor, users, callback);
+ attemps += 1;
+
+ self._seek(client, currentCursor, users, attemps, callback);
});
}; |
41f93f380688849092f036a37a0f0a40d94ef473 | test/primitives/amount.js | test/primitives/amount.js | // Import AVA
import test from 'ava'
// Imports
import Amount from '../../src/primitives/amount'
import BigNumber from 'bignumber.js'
// Test data
const testNumber = 78953286724
const testValue = '78953286724'
/**
* Value must be BigNumber.
*/
test('value must be BigNumber', t => {
const number = 8
t.throws(() => {
new Amount(number)
})
})
/**
* Create a new amount.
*/
test('create', t => {
const value = new BigNumber('8')
t.notThrows(() => {
new Amount(value)
})
})
/**
* Access value in wei.
*/
test('access wei', t => {
const value = new BigNumber(testValue)
const amount = new Amount(value)
t.true(amount.wei.equals(value))
})
| // Import AVA
import test from 'ava'
// Imports
import Amount from '../../src/primitives/amount'
import BigNumber from 'bignumber.js'
// Test data
const testNumber = 78953286724
const testValue = '78953286724'
/**
* Value must be BigNumber.
*/
test('value must be BigNumber', t => {
t.throws(() => {
new Amount(testNumber)
})
})
/**
* Create a new amount.
*/
test('create', t => {
const value = new BigNumber(testValue)
t.notThrows(() => {
new Amount(value)
})
})
/**
* Access value in wei.
*/
test('access wei', t => {
const value = new BigNumber(testValue)
const amount = new Amount(value)
t.true(amount.wei.equals(value))
})
| Use centralized test data for Amount tests | Use centralized test data for Amount tests
| JavaScript | unlicense | jestcrows/ethtaint,jestcrows/ethtaint | ---
+++
@@ -13,9 +13,8 @@
* Value must be BigNumber.
*/
test('value must be BigNumber', t => {
- const number = 8
t.throws(() => {
- new Amount(number)
+ new Amount(testNumber)
})
})
@@ -23,7 +22,7 @@
* Create a new amount.
*/
test('create', t => {
- const value = new BigNumber('8')
+ const value = new BigNumber(testValue)
t.notThrows(() => {
new Amount(value)
}) |
c30d406e330c1c69877cd80e9f3b9ba3cdddc983 | src/direct-linking/content_script/rendering.js | src/direct-linking/content_script/rendering.js | import { retryUntil } from '../utils'
import { descriptorToRange, markRange } from './annotations'
import styles from './styles.css'
export async function highlightAnnotation({ annotation }) {
// console.log('highlighting')
const descriptor = annotation.anchors[0].descriptor
const range = await retryUntil(
() => descriptorToRange({ descriptor }),
range => range !== null,
{
intervalMiliseconds: 200,
timeoutMiliseconds: 5000,
},
)
console.log('Memex - found range:', range, range.toString())
markRange({ range, cssClass: styles['memex-highlight'] })
}
| import * as AllRaven from 'raven-js'
import { retryUntil } from '../utils'
import { descriptorToRange, markRange } from './annotations'
import styles from './styles.css'
const Raven = AllRaven['default']
export async function highlightAnnotation({ annotation }) {
// console.log('highlighting')
await Raven.context(async () => {
const descriptor = annotation.anchors[0].descriptor
Raven.captureBreadcrumb({
message: 'annotation-selector-received',
category: 'annotations',
data: annotation,
})
const range = await retryUntil(
() => descriptorToRange({ descriptor }),
range => range !== null,
{
intervalMiliseconds: 200,
timeoutMiliseconds: 5000,
},
)
console.log('Memex - found range:', range, range.toString())
markRange({ range, cssClass: styles['memex-highlight'] })
})
}
| Add annotation selector breacrumb for Direct Linking | Add annotation selector breacrumb for Direct Linking
| JavaScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -1,19 +1,31 @@
+import * as AllRaven from 'raven-js'
import { retryUntil } from '../utils'
import { descriptorToRange, markRange } from './annotations'
import styles from './styles.css'
+const Raven = AllRaven['default']
+
export async function highlightAnnotation({ annotation }) {
// console.log('highlighting')
- const descriptor = annotation.anchors[0].descriptor
- const range = await retryUntil(
- () => descriptorToRange({ descriptor }),
- range => range !== null,
- {
- intervalMiliseconds: 200,
- timeoutMiliseconds: 5000,
- },
- )
- console.log('Memex - found range:', range, range.toString())
- markRange({ range, cssClass: styles['memex-highlight'] })
+ await Raven.context(async () => {
+ const descriptor = annotation.anchors[0].descriptor
+ Raven.captureBreadcrumb({
+ message: 'annotation-selector-received',
+ category: 'annotations',
+ data: annotation,
+ })
+
+ const range = await retryUntil(
+ () => descriptorToRange({ descriptor }),
+ range => range !== null,
+ {
+ intervalMiliseconds: 200,
+ timeoutMiliseconds: 5000,
+ },
+ )
+ console.log('Memex - found range:', range, range.toString())
+
+ markRange({ range, cssClass: styles['memex-highlight'] })
+ })
} |
cf93826d032895946baf0bfc9742b45dc8623a46 | test/index.js | test/index.js | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
require('./tcurl.js');
require('./as-json.js');
require('./as-http.js');
require('./health.js');
| // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
require('./tcurl.js');
require('./as-thrift.js');
require('./as-json.js');
require('./as-http.js');
require('./health.js');
| Add as thrift test to suite | Add as thrift test to suite
| JavaScript | mit | uber/tcurl,uber/tcurl,benfleis/tcurl,bobegir/tcurl | ---
+++
@@ -21,6 +21,7 @@
'use strict';
require('./tcurl.js');
+require('./as-thrift.js');
require('./as-json.js');
require('./as-http.js');
require('./health.js'); |
bd8e1369263d865f8457ef47c592876279db8be7 | lib/util.js | lib/util.js | const Q = require('q');
// Regex to test if the string is likely a facebook user ID
const USER_ID_REGEX = /^\d+$/;
async function getFBUserInfoByID(api, id) {
return await Q.nfcall(api.getUserInfo, id);
}
async function findFBUser(api, search_str, allowNonFriends) {
let userID = search_str;
// If the search string isnt a userID, we should search
// for the user by name
if (!USER_ID_REGEX.test(search_str)) {
let userData = await Q.nfcall(api.getUserID, name);
userID = userData[0].userID;
}
const userInfoMap = await getFBUserInfoByID(api, userID);
const userInfo = userInfoMap[userID];
if (!userInfo.isFriend && !allowNonFriends)
throw new Error(
'User not your friend, they may not be your top ' +
name +
", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use"
);
// The userinfo object doesnt have an id with it, so add it as its useful
userID.id = userID;
return userInfo;
}
module.exports = {
findFBUser,
};
| const Q = require('q');
// Regex to test if the string is likely a facebook user ID
const USER_ID_REGEX = /^\d+$/;
async function getFBUserInfoByID(api, id) {
return await Q.nfcall(api.getUserInfo, id);
}
async function findFBUser(api, search_str, allowNonFriends) {
let userID = search_str;
// If the search string isnt a userID, we should search
// for the user by name
if (!USER_ID_REGEX.test(search_str)) {
let userData = await Q.nfcall(api.getUserID, search_str);
userID = userData[0].userID;
}
const userInfoMap = await getFBUserInfoByID(api, userID);
const userInfo = userInfoMap[userID];
if (!userInfo.isFriend && !allowNonFriends)
throw new Error(
'User not your friend, they may not be your top ' +
name +
", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use"
);
// The userinfo object doesnt have an id with it, so add it as its useful
userInfo.id = userID;
return userInfo;
}
module.exports = {
findFBUser,
};
| Fix issues with findUser refactor | Fix issues with findUser refactor
| JavaScript | mit | Weetbix/facebot | ---
+++
@@ -13,7 +13,7 @@
// If the search string isnt a userID, we should search
// for the user by name
if (!USER_ID_REGEX.test(search_str)) {
- let userData = await Q.nfcall(api.getUserID, name);
+ let userData = await Q.nfcall(api.getUserID, search_str);
userID = userData[0].userID;
}
@@ -28,7 +28,7 @@
);
// The userinfo object doesnt have an id with it, so add it as its useful
- userID.id = userID;
+ userInfo.id = userID;
return userInfo;
} |
a2a86fb46d2d170675dbab2145835871933bad01 | common/models/user.js | common/models/user.js | 'use strict';
module.exports = function(User) {
if (process.env.NODE_ENV !== 'testing') {
User.afterRemote('create', async (context, user) => {
const options = {
type: 'email',
protocol: process.env.PROTOCOL || 'http',
port: process.env.DISPLAY_PORT || 3000,
host: process.env.HOSTNAME || 'localhost',
to: user.email,
from: 'noreply@redborder.com',
user: user,
};
user.verify(options, (err, response) => {
if (err) {
User.deleteById(user.id);
throw err;
}
});
});
}
};
| 'use strict';
class StubMailer {
static send(options, context, cb) {
cb(null, null);
}
}
module.exports = function(User) {
User.afterRemote('create', async (context, user) => {
let options = null;
if (process.env.NODE_ENV === 'testing') {
options = {
type: 'email',
from: 'test',
mailer: StubMailer,
};
} else {
options = {
type: 'email',
protocol: process.env.PROTOCOL || 'http',
port: process.env.DISPLAY_PORT || 3000,
host: process.env.HOSTNAME || 'localhost',
to: user.email,
from: 'noreply@redborder.com',
user: user,
};
}
user.verify(options, (err, response) => {
if (err) {
User.deleteById(user.id);
throw err;
}
});
});
};
| Use fake mailer on tests | :sparkes: Use fake mailer on tests
| JavaScript | agpl-3.0 | redBorder/license-manager-api | ---
+++
@@ -1,9 +1,23 @@
'use strict';
+class StubMailer {
+ static send(options, context, cb) {
+ cb(null, null);
+ }
+}
+
module.exports = function(User) {
- if (process.env.NODE_ENV !== 'testing') {
- User.afterRemote('create', async (context, user) => {
- const options = {
+ User.afterRemote('create', async (context, user) => {
+ let options = null;
+
+ if (process.env.NODE_ENV === 'testing') {
+ options = {
+ type: 'email',
+ from: 'test',
+ mailer: StubMailer,
+ };
+ } else {
+ options = {
type: 'email',
protocol: process.env.PROTOCOL || 'http',
port: process.env.DISPLAY_PORT || 3000,
@@ -12,13 +26,13 @@
from: 'noreply@redborder.com',
user: user,
};
+ }
- user.verify(options, (err, response) => {
- if (err) {
- User.deleteById(user.id);
- throw err;
- }
- });
+ user.verify(options, (err, response) => {
+ if (err) {
+ User.deleteById(user.id);
+ throw err;
+ }
});
- }
+ });
}; |
18c04888ea69acaa86bf43246a1aa135c50c03df | app/utils/query-converter.js | app/utils/query-converter.js | /* global URI */
/**
* QueryConverter stores a list of string to string pairs
* as a hash (Embereño for POJO) and can export that list as a JSON string,
* a URL query string, or a hash.
* We will use the JSON string representation as an ID for Ember Data.
* To ensure a 1-1 mapping from queries to IDs,
* ID representation of a query must be sorted alphabetically by key.
*/
export default function QueryConverter() {
this.fromId = function(id){
this.hash = JSON.parse(id);
};
this.fromHash = function(hash){
this.hash = hash;
};
this.fromQueryString = function(qString){
this.hash = URI(qString).query(true);
};
this.toId = function(){
// JS objects maintain insertion ordering! Woah.
// http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605
var orderedHash = {};
var unorderedHash = this.hash;
Object.keys(this.hash).sort().forEach(function(key){
orderedHash[key] = unorderedHash[key];
});
return JSON.stringify(orderedHash);
};
this.toHash = function(){
return this.hash;
};
this.toQueryString = function(){
return URI('').addQuery(this.hash).toString();
};
}
| /* global URI */
/**
* QueryConverter stores a list of string to string pairs
* as a hash (Embereño for POJO) and can export that list as a JSON string,
* a URL query string, or a hash.
* We will use the JSON string representation as an ID for Ember Data.
* To ensure a 1-1 mapping from queries to IDs,
* ID representation of a query must be sorted alphabetically by key.
*/
export default function QueryConverter() {
this.fromId = function(id){
this.hash = JSON.parse(id);
return this;
};
this.fromHash = function(hash){
this.hash = hash;
return this;
};
this.fromQueryString = function(qString){
this.hash = URI(qString).query(true);
return this;
};
this.toId = function(){
// JS objects maintain insertion ordering! Woah.
// http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605
var orderedHash = {};
var unorderedHash = this.hash;
console.log(unorderedHash);
Object.keys(this.hash).sort().forEach(function(key){
orderedHash[key] = unorderedHash[key];
});
return JSON.stringify(orderedHash);
};
this.toHash = function(){
return this.hash;
};
this.toQueryString = function(){
return URI('').addQuery(this.hash).toString();
};
}
| Allow method chaining in QueryConverter | Allow method chaining in QueryConverter
| JavaScript | mit | UrbanCCD-UChicago/plenario-explorer,UrbanCCD-UChicago/plenario-explorer,UrbanCCD-UChicago/plenario-explorer | ---
+++
@@ -11,26 +11,35 @@
export default function QueryConverter() {
this.fromId = function(id){
this.hash = JSON.parse(id);
+ return this;
};
+
this.fromHash = function(hash){
this.hash = hash;
+ return this;
};
+
this.fromQueryString = function(qString){
this.hash = URI(qString).query(true);
+ return this;
};
+
this.toId = function(){
// JS objects maintain insertion ordering! Woah.
// http://stackoverflow.com/questions/5467129/sort-javascript-object-by-key/31102605#31102605
var orderedHash = {};
var unorderedHash = this.hash;
+ console.log(unorderedHash);
Object.keys(this.hash).sort().forEach(function(key){
orderedHash[key] = unorderedHash[key];
});
return JSON.stringify(orderedHash);
};
+
this.toHash = function(){
return this.hash;
};
+
this.toQueryString = function(){
return URI('').addQuery(this.hash).toString();
}; |
5554134cd1b7f4170a8f100672969ed856a3a929 | src/sprites/Common/index.js | src/sprites/Common/index.js | import Phaser from 'phaser';
import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles';
import { clone } from '../../utils';
import objectPool from '../../object-pool';
import tween from './tween';
export default class extends Phaser.Image {
constructor(game, x, y, sprite, frame, id, objectType) {
const alignedCoords = alignToGrid({ x, y });
x = alignedCoords.x;
y = alignedCoords.y;
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
// use a bunch of different properties to hopefully achieve a unique id
this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1);
this.objectType = objectType || 'generic';
this.timers = [];
this.tile = {};
this.setTile();
}
move(nextPixelCoord, callback) {
this.moving = true;
tween.call(this, nextPixelCoord, 35, function() {
this.moving = false;
this.setTile();
if (callback) callback.call(this);
});
}
setTile() {
this.tile = tile.call(this);
}
resetObject() {
this.setTile();
this.timers = [];
}
destroy() {
this.kill();
this.destroyed = true;
objectPool.remove(this);
}
}
| import Phaser from 'phaser';
import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles';
import { clone } from '../../utils';
import objectPool from '../../object-pool';
import tween from './tween';
export default class extends Phaser.Image {
constructor(game, x, y, sprite, frame, id, objectType) {
const alignedCoords = alignToGrid({ x, y });
x = alignedCoords.x;
y = alignedCoords.y;
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
// use a bunch of different properties to hopefully achieve a unique id
this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1);
this.objectType = objectType || 'generic';
this.timers = [];
this.tile = {};
this.setTile();
}
move(nextPixelCoord, callback) {
this.moving = true;
tween.call(this, nextPixelCoord, 35, function() {
this.moving = false;
this.setTile();
if (callback) callback.call(this);
});
}
setTile() {
this.tile = tile.call(this);
}
resetObject() {
this.setTile();
this.timers = [];
this.destroyed = false;
}
destroy() {
this.kill();
this.destroyed = true;
objectPool.remove(this);
}
}
| Reset destroyed flag on reset | Reset destroyed flag on reset
| JavaScript | mit | ThomasMays/incremental-forest,ThomasMays/incremental-forest | ---
+++
@@ -48,6 +48,7 @@
resetObject() {
this.setTile();
this.timers = [];
+ this.destroyed = false;
}
destroy() { |
f0c283b2c50c8bc43798efa188feef58c61f0415 | src/store/configureStore.js | src/store/configureStore.js | import {createStore, applyMiddleware, compose} from 'redux';
import { routerMiddleware } from 'react-router-redux';
import throttle from 'lodash/throttle';
import recipes from './data/recipes';
import { loadState, saveState } from './localStorage';
import rootReducer from './reducers';
const devtools = window.devToolsExtension || (f => f);
export default function configureStore(history, initialState) {
const middlewares = [
routerMiddleware(history),
];
const enhancers = [
applyMiddleware(...middlewares),
devtools(),
];
const localState = loadState() || recipes;
const store = createStore(
rootReducer,
initialState || localState,
compose(...enhancers)
);
store.subscribe(throttle(() => {
const state = store.getState();
saveState({
recipes: state.recipes,
likes: state.likes
});
}, 1000));
if (module.hot && process.env.NODE_ENV !== 'production') {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./reducers', () => {
const nextReducer = require('./reducers'); // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
| import {createStore, applyMiddleware, compose} from 'redux';
import { routerMiddleware } from 'react-router-redux';
import throttle from 'lodash/throttle';
import recipes from './data/recipes';
import { loadState, saveState } from './localStorage';
import rootReducer from './reducers';
const devtools = window.devToolsExtension || (() => f => f);
export default function configureStore(history, initialState) {
const middlewares = [
routerMiddleware(history),
];
const enhancers = [
applyMiddleware(...middlewares),
devtools(),
];
const localState = loadState() || recipes;
const store = createStore(
rootReducer,
initialState || localState,
compose(...enhancers)
);
store.subscribe(throttle(() => {
const state = store.getState();
saveState({
recipes: state.recipes,
likes: state.likes
});
}, 1000));
if (module.hot && process.env.NODE_ENV !== 'production') {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./reducers', () => {
const nextReducer = require('./reducers'); // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
| Fix issue when redux dev tool extension is not available | Fix issue when redux dev tool extension is not available
| JavaScript | mit | blitze/fcc-react-recipebox,blitze/fcc-react-recipebox | ---
+++
@@ -5,7 +5,7 @@
import { loadState, saveState } from './localStorage';
import rootReducer from './reducers';
-const devtools = window.devToolsExtension || (f => f);
+const devtools = window.devToolsExtension || (() => f => f);
export default function configureStore(history, initialState) {
const middlewares = [ |
a896071d4c282a23662e6aa3cfcaaf4a69cb901a | test/tzset.js | test/tzset.js | var should = require('should')
, time = require('../')
describe('tzset()', function () {
beforeEach(function () {
process.env.TZ = 'UTC'
})
it('should work with no arguments', function () {
process.env.TZ = 'US/Pacific'
time.tzset()
time.currentTimezone.should.equal('US/Pacific')
})
it('should work with 1 argument', function () {
time.tzset('US/Pacific')
time.currentTimezone.should.equal('US/Pacific')
})
it('should return a "zoneinfo" object', function () {
var info = time.tzset()
info.should.have.property('tzname').with.lengthOf(2)
info.should.have.property('timezone')
info.should.have.property('daylight')
})
it('should set `process.env.TZ`', function () {
time.tzset('US/Pacific')
process.env.TZ.should.equal('US/Pacific')
})
})
| var should = require('should')
, time = require('../')
describe('tzset()', function () {
beforeEach(function () {
process.env.TZ = 'UTC'
})
it('should work with no arguments', function () {
process.env.TZ = 'US/Pacific'
time.tzset()
time.currentTimezone.should.equal('US/Pacific')
})
it('should work with 1 argument', function () {
time.tzset('US/Pacific')
time.currentTimezone.should.equal('US/Pacific')
})
it('should return a "zoneinfo" object', function () {
var info = time.tzset()
info.should.have.property('tzname').with.lengthOf(2)
info.should.have.property('timezone')
info.should.have.property('daylight')
})
it('should set `process.env.TZ`', function () {
time.tzset('US/Pacific')
process.env.TZ.should.equal('US/Pacific')
})
it('should work with known values', function () {
var info
info = time.tzset('UTC')
info.tzname[0].should.equal('UTC')
info.timezone.should.equal(0)
info.daylight.should.equal(0)
info = time.tzset('America/Los_Angeles')
info.tzname[0].should.equal('PST')
info.tzname[1].should.equal('PDT')
info.timezone.should.not.equal(0)
info = time.tzset('America/Phoenix')
info.tzname[0].should.equal('MST')
info.tzname[1].should.equal('MDT')
info.timezone.should.not.equal(0)
info = time.tzset('Europe/Copenhagen')
info.tzname[0].should.equal('CET')
info.tzname[1].should.equal('CEST')
info.timezone.should.not.equal(0)
})
})
| Add a test testing some known timezone values. | Add a test testing some known timezone values.
| JavaScript | mit | TooTallNate/node-time,TooTallNate/node-time,santigimeno/node-time,santigimeno/node-time,santigimeno/node-time,TooTallNate/node-time | ---
+++
@@ -30,4 +30,28 @@
process.env.TZ.should.equal('US/Pacific')
})
+ it('should work with known values', function () {
+ var info
+
+ info = time.tzset('UTC')
+ info.tzname[0].should.equal('UTC')
+ info.timezone.should.equal(0)
+ info.daylight.should.equal(0)
+
+ info = time.tzset('America/Los_Angeles')
+ info.tzname[0].should.equal('PST')
+ info.tzname[1].should.equal('PDT')
+ info.timezone.should.not.equal(0)
+
+ info = time.tzset('America/Phoenix')
+ info.tzname[0].should.equal('MST')
+ info.tzname[1].should.equal('MDT')
+ info.timezone.should.not.equal(0)
+
+ info = time.tzset('Europe/Copenhagen')
+ info.tzname[0].should.equal('CET')
+ info.tzname[1].should.equal('CEST')
+ info.timezone.should.not.equal(0)
+ })
+
}) |
60d2770c762811bcd21ab9324d683ea9daedb27c | _src-js/home.js | _src-js/home.js | import window from 'global/window';
import document from 'global/document';
import $ from 'jquery';
import videojs from 'video.js';
const player = window.player = videojs('preview-player', {
fluid: true,
plugins: {
mux: {
data: {
property_key: 'VJSISBEST',
video_title: 'The Boids!',
video_id: 1
}
}
}
});
player.on('ready', function() {
player.removeClass('placeholder');
});
const overlay = $('.videojs-hero-overlay');
player.on(['play', 'playing'], function() {
overlay.addClass('transparent');
});
player.on(['pause'], function() {
overlay.removeClass('transparent');
});
// Poor man's lazy loading the iframe content to speed up homeage loading
setTimeout(function(){
Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){
const src = ifrm.getAttribute('temp-src');
if (src) {
ifrm.setAttribute('src', src);
}
});
}, 1000);
| import window from 'global/window';
import document from 'global/document';
import $ from 'jquery';
import videojs from 'video.js';
const player = window.player = videojs('preview-player', {
fluid: true,
plugins: {
mux: {
data: {
property_key: 'VJSISBEST',
video_title: 'Disney\'s Oceans',
video_id: 1
}
}
}
});
player.on('ready', function() {
player.removeClass('placeholder');
});
const overlay = $('.videojs-hero-overlay');
player.on(['play', 'playing'], function() {
overlay.addClass('transparent');
});
player.on(['pause'], function() {
overlay.removeClass('transparent');
});
// Poor man's lazy loading the iframe content to speed up homeage loading
setTimeout(function(){
Array.prototype.forEach.call(document.querySelectorAll('iframe'), function(ifrm){
const src = ifrm.getAttribute('temp-src');
if (src) {
ifrm.setAttribute('src', src);
}
});
}, 1000);
| Fix the title of the main video | Fix the title of the main video
| JavaScript | mit | videojs/videojs.com | ---
+++
@@ -9,7 +9,7 @@
mux: {
data: {
property_key: 'VJSISBEST',
- video_title: 'The Boids!',
+ video_title: 'Disney\'s Oceans',
video_id: 1
}
} |
0268292f245fe5f46119fb24384af1b5a529070f | slack-events-api-router/src/respond-on-error.js | slack-events-api-router/src/respond-on-error.js | const invokeLambdaFunction = require('../src/lambda-invoke-function');
function respondOnError(error) {
const payload = {
message: error.message,
};
return invokeLambdaFunction(payload, 'need-to-write-this');
}
module.exports = respondOnError;
| const invokeLambdaFunction = require('../src/lambda-invoke-function');
function respondOnError(error) {
const payload = {
message: error.message,
};
console.error(`Responding to user with error: ${error.message}`);
// @todo Write the Lambda function that responds if there is an error.
// return invokeLambdaFunction(payload, 'need-to-write-this');
return Promise.resolve('OK');
}
module.exports = respondOnError;
| Mark response bot as @todo. | Mark response bot as @todo.
| JavaScript | mit | Quartz/quackbot | ---
+++
@@ -5,7 +5,12 @@
message: error.message,
};
- return invokeLambdaFunction(payload, 'need-to-write-this');
+ console.error(`Responding to user with error: ${error.message}`);
+
+ // @todo Write the Lambda function that responds if there is an error.
+ // return invokeLambdaFunction(payload, 'need-to-write-this');
+
+ return Promise.resolve('OK');
}
module.exports = respondOnError; |
b6c8c4c49aa05e66504efbae37a2838ddf046564 | public_records_portal/static/js/all_requests.js | public_records_portal/static/js/all_requests.js | $(document).ready(function(){
Modernizr.load({
test: Modernizr.inputtypes.date,
nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js', 'jquery-ui.css'],
complete: function () {
$('input[type=date]').datepicker({
dateFormat: 'yy-mm-dd'
});
}
});
});
| $(document).ready(function(){
Modernizr.load({
test: Modernizr.inputtypes.date,
nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/jquery-ui.css'],
complete: function () {
$('input[type=date]').datepicker({
dateFormat: 'yy-mm-dd'
});
}
});
});
| Update to use correct jquery-ui.css file | Update to use correct jquery-ui.css file
| JavaScript | apache-2.0 | CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords | ---
+++
@@ -1,7 +1,7 @@
$(document).ready(function(){
Modernizr.load({
test: Modernizr.inputtypes.date,
- nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js', 'jquery-ui.css'],
+ nope: ['http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/base/jquery-ui.css'],
complete: function () {
$('input[type=date]').datepicker({
dateFormat: 'yy-mm-dd' |
e35487c6fb979c0931cd2a3505f4c9063705c702 | lib/prefork.js | lib/prefork.js |
var prefork = require('../build/Release/prefork').prefork,
fs = require('fs');
module.exports = function (options) {
options = options || {};
var outfd, errfd;
if (Array.isArray(options.customFds) && options.customFds.length < 3) {
options.customFds.unshift(-1);
}
if (options.stdout && typeof options.stdout === 'string') {
outfd = fs.openSync(options.stdout, 'a');
}
if (options.stderr && typeof options.stderr === 'string') {
errfd = fs.openSync(options.stderr, 'a');
}
else if (outfd) {
errfd = outfd;
}
if (outfd && errfd) {
options.customFds = [
-1,
outfd,
errfd
];
}
prefork(options);
};
|
var prefork = require('../build/Release/prefork').prefork,
fs = require('fs');
module.exports = function (options) {
options = options || {};
var infd = -1, outfd = -1, errfd = -1,
customFds;
if (options.stdin && typeof options.stdin === 'string') {
infd = fs.openSync(options.stdin, 'r');
}
if (options.stdout && typeof options.stdout === 'string') {
outfd = fs.openSync(options.stdout, 'a');
}
if (options.stderr && typeof options.stderr === 'string') {
errfd = fs.openSync(options.stderr, 'a');
}
else if (outfd) {
errfd = outfd;
}
if (Array.isArray(options.customFds)) {
customFds = options.customFds;
}
else {
customFds = [
infd,
outfd,
errfd
];
}
prefork(customFds);
};
| Add options.stdin, clean up options logic. | [api] Add options.stdin, clean up options logic.
| JavaScript | mit | AvianFlu/node-prefork,AvianFlu/node-prefork,AvianFlu/node-prefork | ---
+++
@@ -4,10 +4,11 @@
module.exports = function (options) {
options = options || {};
- var outfd, errfd;
+ var infd = -1, outfd = -1, errfd = -1,
+ customFds;
- if (Array.isArray(options.customFds) && options.customFds.length < 3) {
- options.customFds.unshift(-1);
+ if (options.stdin && typeof options.stdin === 'string') {
+ infd = fs.openSync(options.stdin, 'r');
}
if (options.stdout && typeof options.stdout === 'string') {
outfd = fs.openSync(options.stdout, 'a');
@@ -18,12 +19,15 @@
else if (outfd) {
errfd = outfd;
}
- if (outfd && errfd) {
- options.customFds = [
- -1,
+ if (Array.isArray(options.customFds)) {
+ customFds = options.customFds;
+ }
+ else {
+ customFds = [
+ infd,
outfd,
errfd
];
}
- prefork(options);
+ prefork(customFds);
}; |
9b34ee7d9ab3d2cacedcf549273fbca9c6465cb3 | api/test/api.js | api/test/api.js | var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var should = chai.should();
// var expect = chai.expect;
// var request = require("request");
describe("Date-a-Dog Server", function() {
describe("Rest API tests", function() {
it('Should return user profile for test user on /api/loginTest', function(done) {
chai.request(server)
.post('/api/loginTest')
.end(function(err, res){
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('id');
res.body.id.should.equal('119889308491710');
done();
});
});
});
});
| var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../app');
var should = chai.should();
// var expect = chai.expect;
// var request = require("request");
chai.use(chaiHttp);
describe("Date-a-Dog Server", function() {
describe("Rest API tests", function() {
it('Should return user profile for test user on /api/loginTest', function(done) {
chai.request(server)
.post('/api/loginTest')
.end(function(err, res){
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('id');
res.body.id.should.equal('119889308491710');
done();
});
});
});
});
| Update to first Rest API test | Update to first Rest API test
| JavaScript | mit | Date-a-Dog/Date-a-Dog,Date-a-Dog/Date-a-Dog,jammua/dog-dating-app,Date-a-Dog/Date-a-Dog | ---
+++
@@ -4,6 +4,8 @@
var should = chai.should();
// var expect = chai.expect;
// var request = require("request");
+
+chai.use(chaiHttp);
describe("Date-a-Dog Server", function() {
describe("Rest API tests", function() { |
51167144a5be785042ff15a9435f6ea8c75d6c53 | pages/_app.js | pages/_app.js | import '@/css/tailwind.css'
import '@/css/prism.css'
import { ThemeProvider } from 'next-themes'
import Head from 'next/head'
import siteMetadata from '@/data/siteMetadata'
import Analytics from '@/components/analytics'
import LayoutWrapper from '@/components/LayoutWrapper'
import { ClientReload } from '@/components/ClientReload'
const isDevelopment = process.env.NODE_ENV === 'development'
const isSocket = process.env.SOCKET
export default function App({ Component, pageProps }) {
return (
<ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}>
<Head>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</Head>
{isDevelopment && isSocket && <ClientReload />}
<Analytics />
<LayoutWrapper>
<Component {...pageProps} />
</LayoutWrapper>
</ThemeProvider>
)
}
| import '@/css/tailwind.css'
import '@/css/prism.css'
import { ThemeProvider } from 'next-themes'
import Head from 'next/head'
import moment from 'moment'
import siteMetadata from '@/data/siteMetadata'
import Analytics from '@/components/analytics'
import LayoutWrapper from '@/components/LayoutWrapper'
import { ClientReload } from '@/components/ClientReload'
const isDevelopment = process.env.NODE_ENV === 'development'
const isSocket = process.env.SOCKET
const { version } = require('../package.json')
const build = moment().format('YYYYMMDDHHmmss')
export default function App({ Component, pageProps }) {
return (
<ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="version" content={version + '.' + build} />
</Head>
{isDevelopment && isSocket && <ClientReload />}
<Analytics />
<LayoutWrapper>
<Component {...pageProps} />
</LayoutWrapper>
</ThemeProvider>
)
}
| Add meta version for build version | Add meta version for build version
| JavaScript | mit | ravuthz/ravuthz.github.io,ravuthz/ravuthz.github.io | ---
+++
@@ -3,6 +3,7 @@
import { ThemeProvider } from 'next-themes'
import Head from 'next/head'
+import moment from 'moment'
import siteMetadata from '@/data/siteMetadata'
import Analytics from '@/components/analytics'
@@ -12,11 +13,15 @@
const isDevelopment = process.env.NODE_ENV === 'development'
const isSocket = process.env.SOCKET
+const { version } = require('../package.json')
+const build = moment().format('YYYYMMDDHHmmss')
+
export default function App({ Component, pageProps }) {
return (
<ThemeProvider attribute="class" defaultTheme={siteMetadata.theme}>
<Head>
- <meta content="width=device-width, initial-scale=1" name="viewport" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="version" content={version + '.' + build} />
</Head>
{isDevelopment && isSocket && <ClientReload />}
<Analytics /> |
3eaf3d248b0118353260a4c9b2f8ecdc23fff359 | test/suites/080-dataview.js | test/suites/080-dataview.js | describe('Dataview', function () {
this.bail(true)
this.timeout(20 * 1000)
it('Switch to "Dataview" tab', function (done) {
eTT().tab('Dataview').click(done)
})
it('Click on second "customDataviewReference" dataview item', function (done) {
eTT().dataview('customDataviewReference').select(1, done)
})
it('Click on first "customDataviewReference1" dataview item with itemCls', function (done) {
eTT().dataview('customDataviewReference1').select(0, done, 'name-item');
})
})
| describe('Dataview', function () {
this.bail(true)
this.timeout(20 * 1000)
it('Switch to "Dataview" tab', function (done) {
eTT().tab('Dataview').click(done)
})
it('Click on second "customDataviewReference" dataview item', function (done) {
eTT().dataview('customDataviewReference').select(1, done)
})
it('Click on first "customDataviewReference1" dataview item with itemCls', function (done) {
eTT().dataview('customDataviewReference1').select(0, done);
})
})
| Remove cls and swap args | Remove cls and swap args
| JavaScript | mit | antonfisher/extjs-testing-tool,antonfisher/extjs-testing-tool,antonfisher/node-mocha-extjs,antonfisher/node-mocha-extjs,antonfisher/mocha-extjs,antonfisher/node-mocha-extjs,antonfisher/extjs-testing-tool,antonfisher/mocha-extjs,antonfisher/mocha-extjs | ---
+++
@@ -11,7 +11,7 @@
})
it('Click on first "customDataviewReference1" dataview item with itemCls', function (done) {
- eTT().dataview('customDataviewReference1').select(0, done, 'name-item');
+ eTT().dataview('customDataviewReference1').select(0, done);
})
})
|
a1f68d943eed3335fc3620dbb6088186b2b05a29 | logic/subcampaign/writeSubcampainModelLogic.js | logic/subcampaign/writeSubcampainModelLogic.js | var configuration = require('../../config/configuration.json')
var utility = require('../../public/method/utility')
module.exports = {
setSubcampaignModel: function (redisClient, accountHashID, payload, callback) {
var tableName, tempTable
var subcampaignHashID = utility.generateUniqueHashID()
var score = utility.getUnixTimeStamp()
var multi = redisClient.multi()
/* Add to SubcampaignModel:subcampaignHashID */
tableName = configuration.TableMASubcampaignModel + subcampaignHashID
multi.hmset(tableName,
configuration.ConstantSCMMinBudget, payload[configuration.ConstantSCMMinBudget],
configuration.ConstantSCMSubcampaignName, payload[configuration.ConstantSCMSubcampaignName],
configuration.ConstantSCMSubcampaignStyle, payload[configuration.ConstantSCMSubcampaignStyle],
configuration.ConstantSCMSubcampaignPlan, payload[configuration.ConstantSCMSubcampaignPlan],
configuration.ConstantSCMSubcampaignPrice, payload[configuration.ConstantSCMSubcampaignPrice],
configuration.ConstantSCMFileURL, payload[configuration.ConstantSCMFileURL]
)
/* Add to CampaignModel:SubcampaignModel:SubcampaignStyleType:accountHashID */
tempTable = configuration.TableModel.general.SubcampaignModel
tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignStyle]) + accountHashID
multi.zadd(tableName, score, subcampaignHashID)
/* Add to CampaignModel:SubcampaignModel:SubcampaignPlanType:accountHashID */
tempTable = configuration.TableModel.general.CampaignModel
tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignPlan]) + accountHashID
multi.zadd(tableName, score, subcampaignHashID)
/* Add to CampaignModel:SubcampaignModel:SubcampaignStyleType: */
tempTable = configuration.TableModel.general.SubcampaignModel
tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignStyle])
multi.zadd(tableName, score, subcampaignHashID)
/* Add to CampaignModel:SubcampaignModel:SubcampaignPlanType: */
tempTable = configuration.TableModel.general.CampaignModel
tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignPlan])
multi.zadd(tableName, score, subcampaignHashID)
/* Add to CampaignModel:SubcampaignModel:campaignHashID */
tableName = configuration.TableMSCampaignModelSubcampaignModel + campaignHashID
multi.zadd(tableName, score, subcampaignHashID)
multi.exec(function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, configuration.message.campaign.set.successful)
})
},
} | Implement Set SubcampaignModel Function (Create) | Implement Set SubcampaignModel Function (Create)
| JavaScript | mit | Flieral/Announcer-Service,Flieral/Announcer-Service | ---
+++
@@ -0,0 +1,55 @@
+var configuration = require('../../config/configuration.json')
+var utility = require('../../public/method/utility')
+
+module.exports = {
+ setSubcampaignModel: function (redisClient, accountHashID, payload, callback) {
+ var tableName, tempTable
+ var subcampaignHashID = utility.generateUniqueHashID()
+ var score = utility.getUnixTimeStamp()
+ var multi = redisClient.multi()
+
+ /* Add to SubcampaignModel:subcampaignHashID */
+ tableName = configuration.TableMASubcampaignModel + subcampaignHashID
+ multi.hmset(tableName,
+ configuration.ConstantSCMMinBudget, payload[configuration.ConstantSCMMinBudget],
+ configuration.ConstantSCMSubcampaignName, payload[configuration.ConstantSCMSubcampaignName],
+ configuration.ConstantSCMSubcampaignStyle, payload[configuration.ConstantSCMSubcampaignStyle],
+ configuration.ConstantSCMSubcampaignPlan, payload[configuration.ConstantSCMSubcampaignPlan],
+ configuration.ConstantSCMSubcampaignPrice, payload[configuration.ConstantSCMSubcampaignPrice],
+ configuration.ConstantSCMFileURL, payload[configuration.ConstantSCMFileURL]
+ )
+
+ /* Add to CampaignModel:SubcampaignModel:SubcampaignStyleType:accountHashID */
+ tempTable = configuration.TableModel.general.SubcampaignModel
+ tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignStyle]) + accountHashID
+ multi.zadd(tableName, score, subcampaignHashID)
+
+ /* Add to CampaignModel:SubcampaignModel:SubcampaignPlanType:accountHashID */
+ tempTable = configuration.TableModel.general.CampaignModel
+ tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignPlan]) + accountHashID
+ multi.zadd(tableName, score, subcampaignHashID)
+
+ /* Add to CampaignModel:SubcampaignModel:SubcampaignStyleType: */
+ tempTable = configuration.TableModel.general.SubcampaignModel
+ tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignStyle])
+ multi.zadd(tableName, score, subcampaignHashID)
+
+ /* Add to CampaignModel:SubcampaignModel:SubcampaignPlanType: */
+ tempTable = configuration.TableModel.general.CampaignModel
+ tableName = utility.stringReplace(tempTable, '@', payload[configuration.ConstantSCMSubcampaignPlan])
+ multi.zadd(tableName, score, subcampaignHashID)
+
+ /* Add to CampaignModel:SubcampaignModel:campaignHashID */
+ tableName = configuration.TableMSCampaignModelSubcampaignModel + campaignHashID
+ multi.zadd(tableName, score, subcampaignHashID)
+
+ multi.exec(function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ callback(null, configuration.message.campaign.set.successful)
+ })
+ },
+
+} | |
e44aba0a81f3eaef631290c10776d94d033c74d9 | src/templates/interactions/interaction-list.js | src/templates/interactions/interaction-list.js | import { bindable, inject } from 'aurelia-framework';
import imagesLoaded from 'imagesloaded';
import Masonry from 'masonry-layout';
import { EventAggregator } from 'aurelia-event-aggregator';
import { RefreshView } from 'resources/messages';
@inject(EventAggregator)
export class InteractionListCustomElement {
@bindable interactions = null;
constructor(ea) {
this.ea = ea;
this.refreshView = ea.subscribe(RefreshView, msg => this.createMasonry());
}
isAttached = false;
attached() {
this.isAttached = true;
this.createMasonry();
}
createMasonry() {
var container = document.querySelector('#posts');
imagesLoaded(container, function () {
var msnry = new Masonry(container, {
columnWidth: ".post",
itemSelector: '.post',
percentPosition: true,
gutter: 10
});
});
}
postsChanged() {
if (this.isAttached) {
this.createMasonry();
}
}
} | import { bindable, inject } from 'aurelia-framework';
import Masonry from 'masonry-layout';
import { EventAggregator } from 'aurelia-event-aggregator';
import { RefreshedView } from 'resources/messages';
import { Router } from 'aurelia-router';
@inject(EventAggregator, Router)
export class InteractionListCustomElement {
@bindable interactions = null;
constructor(ea, router) {
this.ea = ea;
this.theRouter = router;
this.viewRefreshed = ea.subscribe(RefreshedView, msg => this.createMasonry());
}
isAttached = false;
attached() {
this.isAttached = true;
this.createMasonry();
}
detached() {
this.viewRefreshed();
this.msnry.destroy();
}
loadUserRoute(user) {
this.theRouter.navigateToRoute("userprofile", { user_id: user });
}
createMasonry() {
var container = document.querySelector('#posts');
this.msnry = new Masonry(container, {
columnWidth: ".post",
itemSelector: '.post',
percentPosition: true,
gutter: 10
});
}
postsChanged() {
if (this.isAttached) {
this.createMasonry();
}
}
} | Update interactions, removed image and added in the correct event | Update interactions, removed image and added in the correct event
| JavaScript | mit | mttmccb/dark_social,mttmccb/dark_social,mttmccb/dark_social | ---
+++
@@ -1,16 +1,17 @@
import { bindable, inject } from 'aurelia-framework';
-import imagesLoaded from 'imagesloaded';
import Masonry from 'masonry-layout';
import { EventAggregator } from 'aurelia-event-aggregator';
-import { RefreshView } from 'resources/messages';
+import { RefreshedView } from 'resources/messages';
+import { Router } from 'aurelia-router';
-@inject(EventAggregator)
+@inject(EventAggregator, Router)
export class InteractionListCustomElement {
@bindable interactions = null;
-
- constructor(ea) {
+
+ constructor(ea, router) {
this.ea = ea;
- this.refreshView = ea.subscribe(RefreshView, msg => this.createMasonry());
+ this.theRouter = router;
+ this.viewRefreshed = ea.subscribe(RefreshedView, msg => this.createMasonry());
}
isAttached = false;
@@ -20,22 +21,29 @@
this.createMasonry();
}
+ detached() {
+ this.viewRefreshed();
+ this.msnry.destroy();
+ }
+
+ loadUserRoute(user) {
+ this.theRouter.navigateToRoute("userprofile", { user_id: user });
+ }
+
createMasonry() {
var container = document.querySelector('#posts');
- imagesLoaded(container, function () {
- var msnry = new Masonry(container, {
- columnWidth: ".post",
- itemSelector: '.post',
- percentPosition: true,
- gutter: 10
- });
+ this.msnry = new Masonry(container, {
+ columnWidth: ".post",
+ itemSelector: '.post',
+ percentPosition: true,
+ gutter: 10
});
}
-
+
postsChanged() {
if (this.isAttached) {
- this.createMasonry();
+ this.createMasonry();
}
}
} |
fee15f1ba4479c2cbfa2005cea0f46bf53b9604c | src/article/TableCellNode.js | src/article/TableCellNode.js | import { XMLTextElement } from 'substance'
import { TEXT } from '../kit'
export default class TableCellNode extends XMLTextElement {
constructor (...args) {
super(...args)
this.rowIdx = -1
this.colIdx = -1
}
get rowspan () {
return _parseSpan(this.getAttribute('rowspan'))
}
get colspan () {
return _parseSpan(this.getAttribute('colspan'))
}
isShadowed () {
return this.shadowed
}
getMasterCell () {
return this.masterCell
}
}
TableCellNode.type = 'table-cell'
TableCellNode.schema = {
content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula')
}
function _parseSpan (str) {
let span = parseInt(str, 10)
if (isFinite(span)) {
return Math.max(span, 1)
} else {
return 1
}
}
| import { XMLTextElement } from 'substance'
import { TEXT } from '../kit'
export default class TableCellNode extends XMLTextElement {
constructor (...args) {
super(...args)
this.rowIdx = -1
this.colIdx = -1
}
get rowspan () {
return _parseSpan(this.getAttribute('rowspan'))
}
get colspan () {
return _parseSpan(this.getAttribute('colspan'))
}
isShadowed () {
return this.shadowed
}
getMasterCell () {
return this.masterCell
}
}
TableCellNode.type = 'table-cell'
TableCellNode.schema = {
content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula', 'inline-graphic')
}
function _parseSpan (str) {
let span = parseInt(str, 10)
if (isFinite(span)) {
return Math.max(span, 1)
} else {
return 1
}
}
| Allow for inline-graphic in table cell. | Allow for inline-graphic in table cell.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -29,7 +29,7 @@
TableCellNode.type = 'table-cell'
TableCellNode.schema = {
- content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula')
+ content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula', 'inline-graphic')
}
function _parseSpan (str) { |
9163d9dbc4f58aefbc620934c3db961f0bbf0477 | mocks/index.js | mocks/index.js | var config = require('../lib/config'),
cors = require('../lib/cors'),
fs = require('fs');
var paths = [],
len = 0;
exports.init = function() {
if (config.mocksEnabled) {
console.log("Mock server enabled");
var pathSource = require('./paths');
for (var name in pathSource) {
paths.push({
regex: new RegExp(name),
source: pathSource[name]
});
}
len = paths.length;
}
};
exports.provider = function(req, res, next) {
if (config.mocksEnabled) {
var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?');
for (var i = 0; i < len; i++) {
var path = paths[i];
if (path.regex.test(replaceUrl)) {
console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback'));
cors.applyCORS(req.headers.host, res);
if (req.method !== 'HEAD') {
req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking
}
if (typeof path.source === 'function') {
res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1)));
} else {
res.sendfile(__dirname + '/' + path.source);
}
return;
}
}
}
next();
};
| var config = require('../lib/config'),
cors = require('../lib/cors'),
fs = require('fs');
var paths = [],
len = 0;
exports.init = function() {
if (config.mocksEnabled) {
console.log("Mock server enabled");
}
var pathSource = require('./paths');
for (var name in pathSource) {
paths.push({
regex: new RegExp(name),
source: pathSource[name]
});
}
len = paths.length;
};
exports.provider = function(req, res, next) {
if (config.mocksEnabled) {
var replaceUrl = req.url.replace(/\?username=mobile&password=1111&/, '?');
for (var i = 0; i < len; i++) {
var path = paths[i];
if (path.regex.test(replaceUrl)) {
console.log('Mocking url', req.url, 'to', (typeof path.source !== 'function' ? 'file' + path.source : 'callback'));
cors.applyCORS(req.headers.host, res);
if (req.method !== 'HEAD') {
req.method = 'GET'; // The static provider which this eventually uses does not like the options command, which breaks the mocking
}
if (typeof path.source === 'function') {
res.send(path.source.apply(path.source, Array.prototype.slice.call(replaceUrl.match(path.regex), 1)));
} else {
res.sendfile(__dirname + '/' + path.source);
}
return;
}
}
}
next();
};
| Allow runtime toggling of mocks | Allow runtime toggling of mocks | JavaScript | mit | walmartlabs/mock-server,walmartlabs/mock-server | ---
+++
@@ -6,20 +6,20 @@
len = 0;
exports.init = function() {
- if (config.mocksEnabled) {
- console.log("Mock server enabled");
+ if (config.mocksEnabled) {
+ console.log("Mock server enabled");
+ }
- var pathSource = require('./paths');
+ var pathSource = require('./paths');
- for (var name in pathSource) {
- paths.push({
- regex: new RegExp(name),
- source: pathSource[name]
- });
- }
+ for (var name in pathSource) {
+ paths.push({
+ regex: new RegExp(name),
+ source: pathSource[name]
+ });
+ }
- len = paths.length;
- }
+ len = paths.length;
};
exports.provider = function(req, res, next) { |
41e38cf5affb703233b4aa0097af8e7d10e4e817 | config/deprecation-workflow.js | config/deprecation-workflow.js | /* global window */
window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
workflow: [
{ handler: 'silence', matchId: 'ember-metal.get-with-default' },
{ handler: 'silence', matchId: 'manager-capabilities.modifiers-3-13' }, //https://github.com/emberjs/ember-render-modifiers/issues/32
{ handler: 'silence', matchId: 'this-property-fallback' },
{ handler: 'silence', matchId: 'ember-lifeline-deprecated-addeventlistener' },
{ handler: 'silence', matchId: 'ember-test-helpers.setup-rendering-context.render' },
{ handler: 'silence', matchId: 'routing.transition-methods' },
{ handler: 'silence', matchId: 'ember-cli-page-object.is-property' },
],
};
| /* global window */
window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
workflow: [
{ handler: 'silence', matchId: 'manager-capabilities.modifiers-3-13' }, //https://github.com/emberjs/ember-render-modifiers/issues/32
{ handler: 'silence', matchId: 'this-property-fallback' },
{ handler: 'silence', matchId: 'ember-lifeline-deprecated-addeventlistener' },
{ handler: 'silence', matchId: 'ember-test-helpers.setup-rendering-context.render' },
{ handler: 'silence', matchId: 'routing.transition-methods' },
{ handler: 'silence', matchId: 'ember-cli-page-object.is-property' },
],
};
| Remove get with default deprecation | Remove get with default deprecation
This is cleared in our app, we don't need to silence it anymore.
| JavaScript | mit | jrjohnson/frontend,dartajax/frontend,ilios/frontend,ilios/frontend,dartajax/frontend,jrjohnson/frontend | ---
+++
@@ -3,7 +3,6 @@
window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
workflow: [
- { handler: 'silence', matchId: 'ember-metal.get-with-default' },
{ handler: 'silence', matchId: 'manager-capabilities.modifiers-3-13' }, //https://github.com/emberjs/ember-render-modifiers/issues/32
{ handler: 'silence', matchId: 'this-property-fallback' },
{ handler: 'silence', matchId: 'ember-lifeline-deprecated-addeventlistener' }, |
af6cdec03b5ff9934466b7625e887d76f0a862ce | script.js | script.js | (() => {
'use strict';
var player = "O";
var moves = [];
var winningCombos = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
["1", "5", "9"],
["3", "5", "7"],
["1", "4", "7"],
["2", "5", "8"],
["3", "6", "9"]];
window.play = (sq) => {
if (sq.innerHTML !== "O" && sq.innerHTML !== "X") {
drawMark(sq);
saveMove(sq);
if (isWinner()) {
colourWinner();
};
changePlayer();
}
};
var drawMark = td => td.innerHTML = player;
var saveMove = td => moves[td.id] = player;
var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0);
var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3);
var colourWinner = () => winningCombos.filter(isWinningCombo).map(colourCombo);
var colourCombo = combo => combo.map(sq => document.getElementById(sq + "").style.backgroundColor = "green");
var changePlayer = () => (player === "O") ? player = "X" : player = "O";
})(); | (() => {
'use strict';
var player = "O";
var moves = [];
var winningCombos = [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
["1", "5", "9"],
["3", "5", "7"],
["1", "4", "7"],
["2", "5", "8"],
["3", "6", "9"]];
window.play = (sq) => {
if (sq.innerHTML !== "O" && sq.innerHTML !== "X") {
drawMark(sq);
saveMove(sq);
if (isWinner()) {
colourWinner();
};
changePlayer();
}
};
var drawMark = td => td.innerHTML = player;
var saveMove = td => moves[td.id] = player;
var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0);
var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3);
var colourWinner = () => winningCombos.filter(isWinningCombo).forEach(colourCombo);
var colourCombo = combo => combo.forEach(sq => document.getElementById(sq + "").style.backgroundColor = "green");
var changePlayer = () => (player === "O") ? player = "X" : player = "O";
})(); | Change from map to forEach. | Change from map to forEach.
| JavaScript | mit | olillevik/olillevik.github.io,olillevik/olillevik.github.io | ---
+++
@@ -32,9 +32,9 @@
var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3);
- var colourWinner = () => winningCombos.filter(isWinningCombo).map(colourCombo);
+ var colourWinner = () => winningCombos.filter(isWinningCombo).forEach(colourCombo);
- var colourCombo = combo => combo.map(sq => document.getElementById(sq + "").style.backgroundColor = "green");
+ var colourCombo = combo => combo.forEach(sq => document.getElementById(sq + "").style.backgroundColor = "green");
var changePlayer = () => (player === "O") ? player = "X" : player = "O";
|
6d0b782f76d6c05a5a2bb6c085de8a8767cf3b06 | app/assets/javascripts/tenon/tenon_manifest.js | app/assets/javascripts/tenon/tenon_manifest.js | //= require jquery
//= require jquery_ujs
// -- Plugins, in alphabetical order
//= require backstretch
//= require bootstrap
//= require bootstrap.collapse
//= require bootstrap.modal
//= require bootstrap.tabs
//= require canvasjs.min
//= require cocoon
//= require imagesloaded
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require jquery.debounce
//= require jquery.equalHeights
//= require jquery.hoverIntent
//= require jquery.Jcrop
//= require jquery.mousewheel
//= require jquery.radioSlider
//= require jquery.twoLevelSort
//= require jquery.ui.sortable
//= require medium-editor
//= require select2
// -- Plugins that need to be loaded in order
//= require moment
//= require bootstrap.datetimepicker
//= require lodash
//= require underscore.string
//= require underscore.inflection
// -- Tenon things, don't mess with the order
//= require ./tenon
//= require ./tenon_dispatcher
//= require_tree ./templates
//= require_tree ./controllers
//= require_tree ./features
//= require_self
$(function() {
Tenon.init();
});
| //= require jquery
//= require jquery_ujs
// -- Plugins, in alphabetical order
//= require backstretch
//= require bootstrap
//= require bootstrap.collapse
//= require bootstrap.modal
//= require bootstrap.tabs
//= require canvasjs.min
//= require cocoon
//= require imagesloaded
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require jquery.debounce
//= require jquery.equalHeights
//= require jquery.hoverIntent
//= require jquery.Jcrop
//= require jquery.mousewheel
//= require jquery.radioSlider
//= require jquery.twoLevelSort
//= require jquery.ui.sortable
//= require medium-editor
//= require select2
// -- Plugins that need to be loaded in order
//= require moment
//= require bootstrap.datetimepicker
//= require lodash
//= require underscore.string
//= require underscore.inflection
// -- Tenon things, don't mess with the order
//= require ./tenon
//= require ./tenon_dispatcher
//= require_tree ./templates
//= require_tree ./controllers
//= require_tree ./features
//= require tenon_addons
//= require_self
$(function() {
Tenon.init();
});
| Call the custom tenon files | Call the custom tenon files
| JavaScript | mit | factore/tenon,factore/tenon,factore/tenon,factore/tenon | ---
+++
@@ -38,6 +38,7 @@
//= require_tree ./templates
//= require_tree ./controllers
//= require_tree ./features
+//= require tenon_addons
//= require_self
|
0df84d28c5767cfd17c54d3eff5d338ad5c31768 | src/components/status-tag.js | src/components/status-tag.js | import React from 'react';
import PropTypes from 'prop-types';
import {css} from 'react-emotion';
const wipStyle = css`
background-color: tomato;
color: ivory;
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
`;
const expStyle = css`
background-color: deepskyblue;
color: ivory;
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
`;
const StatusTag = ({label}) => {
switch (label) {
case 'wip':
return <small className={wipStyle}>wip</small>;
case 'exp':
return <small className={expStyle}>exp</small>;
default:
return null;
}
};
StatusTag.propTypes = {
label: PropTypes.string,
};
export default StatusTag;
| import React from 'react';
import PropTypes from 'prop-types';
import {css} from 'react-emotion';
const wipStyle = css`
background-color: tomato;
color: ivory;
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
font-size: 12px;
border-bottom: none;
`;
const expStyle = css`
background-color: deepskyblue;
color: ivory;
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
font-size: 12px;
border-bottom: none;
`;
const StatusTag = ({label}) => {
switch (label) {
case 'wip':
return <abbr title="work in progress" className={wipStyle}>wip</abbr>;
case 'exp':
return <abbr className={expStyle} title="experimental">exp</abbr>;
default:
return null;
}
};
StatusTag.propTypes = {
label: PropTypes.string,
};
export default StatusTag;
| Use abbr for status tags | style: Use abbr for status tags
Signed-off-by: Arnau Siches <3ce1c0b0b7032cdfdae7820ed353835a9a8f94c3@digital.cabinet-office.gov.uk>
| JavaScript | mit | openregister/specification | ---
+++
@@ -8,6 +8,8 @@
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
+ font-size: 12px;
+ border-bottom: none;
`;
const expStyle = css`
@@ -16,14 +18,16 @@
font-variant: small-caps;
line-height: 1.1;
padding: 0 2px;
+ font-size: 12px;
+ border-bottom: none;
`;
const StatusTag = ({label}) => {
switch (label) {
case 'wip':
- return <small className={wipStyle}>wip</small>;
+ return <abbr title="work in progress" className={wipStyle}>wip</abbr>;
case 'exp':
- return <small className={expStyle}>exp</small>;
+ return <abbr className={expStyle} title="experimental">exp</abbr>;
default:
return null;
} |
90d29f9b4968cb4b3f2175847954cb76bee9825b | app/selectors/containers/searchPageSelector.js | app/selectors/containers/searchPageSelector.js | import { createSelector } from 'reselect';
import ActionTypes from 'constants/ActionTypes';
import searchFiltersSelector from 'selectors/searchFiltersSelector';
import searchResultsSelector from 'selectors/searchResultsSelector';
import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory';
const unitsSelector = (state) => state.data.units;
const searchPageSelector = createSelector(
requestIsActiveSelectorFactory(ActionTypes.API.RESOURCES_GET_REQUEST),
searchFiltersSelector,
searchResultsSelector,
unitsSelector,
(
isFetchingSearchResults,
searchFilters,
searchResults,
units
) => {
return {
filters: searchFilters,
isFetchingSearchResults,
results: searchResults,
units,
};
}
);
export default searchPageSelector;
| import { createSelector } from 'reselect';
import ActionTypes from 'constants/ActionTypes';
import searchFiltersSelector from 'selectors/searchFiltersSelector';
import searchResultsSelector from 'selectors/searchResultsSelector';
import requestIsActiveSelectorFactory from 'selectors/factories/requestIsActiveSelectorFactory';
const unitsSelector = (state) => state.data.units;
const searchPageSelector = createSelector(
requestIsActiveSelectorFactory(ActionTypes.API.SEARCH_RESULTS_GET_REQUEST),
searchFiltersSelector,
searchResultsSelector,
unitsSelector,
(
isFetchingSearchResults,
searchFilters,
searchResults,
units
) => {
return {
filters: searchFilters,
isFetchingSearchResults,
results: searchResults,
units,
};
}
);
export default searchPageSelector;
| Fix search page loading spinner | Fix search page loading spinner
| JavaScript | mit | fastmonkeys/respa-ui | ---
+++
@@ -8,7 +8,7 @@
const unitsSelector = (state) => state.data.units;
const searchPageSelector = createSelector(
- requestIsActiveSelectorFactory(ActionTypes.API.RESOURCES_GET_REQUEST),
+ requestIsActiveSelectorFactory(ActionTypes.API.SEARCH_RESULTS_GET_REQUEST),
searchFiltersSelector,
searchResultsSelector,
unitsSelector, |
94a36fed0967ce47563c8b7b0dd31261bc4253e4 | data/bouquets-data.js | data/bouquets-data.js | const Basedata = require('./base-data');
const BouquetModel = require('./models/bouquete-model');
class BouquetsData extends Basedata {
constructor(db) {
super(db, BouquetModel, BouquetModel);
}
}
module.exports = BouquetsData;
| const Basedata = require('./base-data');
const BouquetModel = require('./models/bouquete-model');
class BouquetsData extends Basedata {
constructor(db) {
super(db, BouquetModel, BouquetModel);
}
// override base
create(bouqueteModel) {
bouqueteModel.dateCreated = new Date();
bouqueteModel.viewsCount = 0;
return super.create(bouqueteModel);
}
}
module.exports = BouquetsData;
| Set new properties on bouquets | Set new properties on bouquets
| JavaScript | mit | viktoria-flowers/ViktoriaFlowers,viktoria-flowers/ViktoriaFlowers | ---
+++
@@ -3,7 +3,14 @@
class BouquetsData extends Basedata {
constructor(db) {
- super(db, BouquetModel, BouquetModel);
+ super(db, BouquetModel, BouquetModel);
+ }
+
+ // override base
+ create(bouqueteModel) {
+ bouqueteModel.dateCreated = new Date();
+ bouqueteModel.viewsCount = 0;
+ return super.create(bouqueteModel);
}
}
|
b3972a05472f510278dbd5d94e95bde4ae14e6cc | packages/vulcan-admin/lib/modules/fragments.js | packages/vulcan-admin/lib/modules/fragments.js | import { registerFragment } from 'meteor/vulcan:lib';
// ------------------------------ Vote ------------------------------ //
// note: fragment used by default on the UsersProfile fragment
registerFragment(`
fragment UsersAdmin on User {
_id
username
createdAt
isAdmin
displayName
email
emailHash
slug
groups
services
avatarUrl
}
`);
| import { registerFragment } from 'meteor/vulcan:lib';
// ------------------------------ Vote ------------------------------ //
// note: fragment used by default on the UsersProfile fragment
registerFragment(`
fragment UsersAdmin on User {
_id
username
createdAt
isAdmin
displayName
email
emailHash
slug
groups
services
avatarUrl
pageUrl
pagePath
}
`);
| Add pageUrl and pagePath to user fragment; | Add pageUrl and pagePath to user fragment;
| JavaScript | mit | VulcanJS/Vulcan,VulcanJS/Vulcan | ---
+++
@@ -16,5 +16,7 @@
groups
services
avatarUrl
+ pageUrl
+ pagePath
}
`); |
3b2be9fe350de22a5a4e466287dade2ab983c9ac | lib/component.js | lib/component.js | !function(exports) {
'use strict';
var RunQueue = exports.RunQueue;
function Component() {
this.next = new RunQueue;
this.end = new RunQueue;
}
Component.extend = function(constructorFn) {
var scope = this;
if(!constructorFn) constructorFn = function() { scope.call(this); };
constructorFn.prototype = new Component;
constructorFn.prototype.constructor = constructorFn;
constructorFn.prototype.proto = constructorFn.prototype;
return constructorFn;
}
Component.prototype.init = stub();
Component.prototype.destroy = stub();
Component.prototype.before = stub();
Component.prototype.update = stub();
Component.prototype.after = stub();
Component.prototype.preprocess = stub();
Component.prototype.render = stub();
Component.prototype.postprocess = stub();
function stub() { return function(delta, x, y, z) {}; }
/*
* Export
* ------
*/
exports.Component = Component;
}(seine);
| !function(exports) {
'use strict';
var RunQueue = exports.RunQueue;
function Component() {
this.next = new RunQueue;
this.end = new RunQueue;
}
Component.extend = function(constructorFn) {
var prop, scope = this;
if(!constructorFn) constructorFn = function() { scope.call(this); };
constructorFn.prototype = new Component;
constructorFn.prototype.constructor = constructorFn;
constructorFn.prototype.proto = constructorFn.prototype;
for(prop in scope) {
if(scope.hasOwnProperty(prop)) constructorFn[prop] = scope[prop];
}
return constructorFn;
}
Component.prototype.init = stub();
Component.prototype.destroy = stub();
Component.prototype.before = stub();
Component.prototype.update = stub();
Component.prototype.after = stub();
Component.prototype.preprocess = stub();
Component.prototype.render = stub();
Component.prototype.postprocess = stub();
function stub() { return function(delta, x, y, z) {}; }
/*
* Export
* ------
*/
exports.Component = Component;
}(seine);
| Include class methods in extend() | [FIX] Include class methods in extend()
| JavaScript | mit | reissbaker/gamekernel,reissbaker/gamekernel | ---
+++
@@ -9,12 +9,17 @@
}
Component.extend = function(constructorFn) {
- var scope = this;
+ var prop, scope = this;
if(!constructorFn) constructorFn = function() { scope.call(this); };
constructorFn.prototype = new Component;
constructorFn.prototype.constructor = constructorFn;
constructorFn.prototype.proto = constructorFn.prototype;
+
+ for(prop in scope) {
+ if(scope.hasOwnProperty(prop)) constructorFn[prop] = scope[prop];
+ }
+
return constructorFn;
}
|
7bca0c33e145e79e368f0a2dd216ea424130c312 | installer/app/src/router.js | installer/app/src/router.js | import Router from 'marbles/router';
import WizardComponent from './views/wizard';
import Dispatcher from './dispatcher';
var MainRouter = Router.createClass({
routes: [
{ path: '', handler: 'landingPage' },
{ path: '/install/:install_id', handler: 'landingPage' }
],
willInitialize: function () {
Dispatcher.register(this.handleEvent.bind(this));
},
beforeHandler: function (event) {
Dispatcher.dispatch({
name: 'LOAD_INSTALL',
id: event.params[0].install_id || ''
});
},
landingPage: function (params, opts, context) {
var props = {
dataStore: context.dataStore
};
context.render(WizardComponent, props);
},
handleEvent: function (event) {
var installID;
switch (event.name) {
case 'INSTALL_EXISTS':
installID = this.history.pathParams[0].install_id;
if ( !event.exists && (!event.id || event.id === installID) ) {
this.history.navigate('/');
} else if (event.exists && installID !== event.id) {
this.history.navigate('/install/'+ event.id);
}
break;
case 'LAUNCH_INSTALL_SUCCESS':
installID = event.res.id;
this.history.navigate('/install/'+ installID);
break;
}
}
});
export default MainRouter;
| import Router from 'marbles/router';
import WizardComponent from './views/wizard';
import Dispatcher from './dispatcher';
var MainRouter = Router.createClass({
routes: [
{ path: '', handler: 'landingPage' },
{ path: '/install/:install_id', handler: 'landingPage' }
],
willInitialize: function () {
Dispatcher.register(this.handleEvent.bind(this));
},
beforeHandler: function (event) {
Dispatcher.dispatch({
name: 'LOAD_INSTALL',
id: event.params[0].install_id || ''
});
},
landingPage: function (params, opts, context) {
var props = {
dataStore: context.dataStore
};
context.render(WizardComponent, props);
},
handleEvent: function (event) {
var installID;
switch (event.name) {
case 'INSTALL_EXISTS':
installID = this.history.pathParams[0].install_id;
if ( !event.exists && (!event.id || event.id === installID) ) {
this.history.navigate('/', { replace: true });
} else if (event.exists && installID !== event.id) {
this.history.navigate('/install/'+ event.id, { replace: true });
}
break;
case 'LAUNCH_INSTALL_SUCCESS':
installID = event.res.id;
this.history.navigate('/install/'+ installID, { replace: true });
break;
}
}
});
export default MainRouter;
| Use replaceState for updating the URL | installer: Use replaceState for updating the URL
Disables back button. The other option is to allow navigating between
steps using the browser's back/forward, but that overlaps with the
current behaviour of picking up an existing install process using the
base URL. This is a temporary fix and will be revisited soon.
refs #1337
Signed-off-by: Jesse Stuart <a5c95b3d7cb4d0ae05a15c79c79ab458dc2c8f9e@jessestuart.ca>
| JavaScript | bsd-3-clause | Brandywine2161/flynn,felixrieseberg/flynn,benbjohnson/flynn,whouses/flynn,shads196770/flynn,lmars/flynn,ozum/flynn,rikur/flynn,tonicbupt/flynn,josephglanville/flynn,arekkas/flynn,josephglanville/flynn,ozum/flynn,benbjohnson/flynn,jzila/flynn,rikur/flynn,schatt/flynn,kgrz/flynn,shads196770/flynn,GrimDerp/flynn,justintung/flynn,pkdevbox/flynn,supermario/flynn,Brandywine2161/flynn,schatt/flynn,schatt/flynn,Brandywine2161/flynn,felixrieseberg/flynn,kgrz/flynn,justintung/flynn,whouses/flynn,tonicbupt/flynn,justintung/flynn,jzila/flynn,flynn/flynn,justintung/flynn,justintung/flynn,jzila/flynn,josephglanville/flynn,GrimDerp/flynn,flynn/flynn,shads196770/flynn,rikur/flynn,flynn/flynn,josephglanville/flynn,kgrz/flynn,arekkas/flynn,benbjohnson/flynn,philiplb/flynn,supermario/flynn,josephglanville/flynn,clifff/flynn,tonicbupt/flynn,TribeMedia/flynn,whouses/flynn,supermario/flynn,GrimDerp/flynn,jzila/flynn,philiplb/flynn,schatt/flynn,jzila/flynn,clifff/flynn,benbjohnson/flynn,pkdevbox/flynn,TribeMedia/flynn,pkdevbox/flynn,justintung/flynn,shads196770/flynn,Brandywine2161/flynn,philiplb/flynn,whouses/flynn,ozum/flynn,technosophos/flynn,GrimDerp/flynn,pkdevbox/flynn,whouses/flynn,clifff/flynn,rikur/flynn,GrimDerp/flynn,felixrieseberg/flynn,flynn/flynn,philiplb/flynn,supermario/flynn,arekkas/flynn,technosophos/flynn,clifff/flynn,tonicbupt/flynn,shads196770/flynn,clifff/flynn,lmars/flynn,Brandywine2161/flynn,philiplb/flynn,pkdevbox/flynn,TribeMedia/flynn,kgrz/flynn,benbjohnson/flynn,technosophos/flynn,rikur/flynn,supermario/flynn,tonicbupt/flynn,josephglanville/flynn,flynn/flynn,arekkas/flynn,rikur/flynn,shads196770/flynn,technosophos/flynn,lmars/flynn,ozum/flynn,TribeMedia/flynn,supermario/flynn,jzila/flynn,TribeMedia/flynn,pkdevbox/flynn,whouses/flynn,TribeMedia/flynn,lmars/flynn,benbjohnson/flynn,GrimDerp/flynn,Brandywine2161/flynn,schatt/flynn,clifff/flynn,ozum/flynn,ozum/flynn,kgrz/flynn,felixrieseberg/flynn,felixrieseberg/flynn,technosophos/flynn,lmars/flynn,kgrz/flynn,schatt/flynn,arekkas/flynn | ---
+++
@@ -32,15 +32,15 @@
case 'INSTALL_EXISTS':
installID = this.history.pathParams[0].install_id;
if ( !event.exists && (!event.id || event.id === installID) ) {
- this.history.navigate('/');
+ this.history.navigate('/', { replace: true });
} else if (event.exists && installID !== event.id) {
- this.history.navigate('/install/'+ event.id);
+ this.history.navigate('/install/'+ event.id, { replace: true });
}
break;
case 'LAUNCH_INSTALL_SUCCESS':
installID = event.res.id;
- this.history.navigate('/install/'+ installID);
+ this.history.navigate('/install/'+ installID, { replace: true });
break;
}
} |
406332aa98abddd4ce4d910c23cd596cf7912dab | src/main/webapp/js/objEntrySetup.js | src/main/webapp/js/objEntrySetup.js | /*
Copyright 2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.
You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/
/*global jQuery, window, cspace*/
var demo = demo || {};
(function ($) {
demo.setup = function () {
var csid = cspace.util.getUrlParameter("csid");
var isLocal = cspace.util.isLocal();
var oeOpts = {
alternateFields: ["accessionNumber", "objectTitle"],
uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema",
};
if (csid) {
oeOpts.csid = csid;
}
if (isLocal) {
oeOpts.dataContext = cspace.util.setupTestDataContext("collection-object");
}
var objEntry = cspace.dataEntry(".csc-object-entry-container", oeOpts);
};
})(jQuery);
| /*
Copyright 2009 University of Toronto
Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.
You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/
/*global jQuery, window, cspace*/
var demo = demo || {};
(function ($) {
demo.setup = function () {
var csid = cspace.util.getUrlParameter("csid");
var isLocal = cspace.util.isLocal();
var oeOpts = {
alternateFields: ["accessionNumber", "objectTitle"],
uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema"
};
if (csid) {
oeOpts.csid = csid;
}
if (isLocal) {
oeOpts.dataContext = cspace.util.setupTestDataContext("collection-object");
}
var objEntry = cspace.dataEntry(".csc-object-entry-container", oeOpts);
};
})(jQuery);
| Remove an extra comma that was causing IE to fail to load the page. | CSPACE-649: Remove an extra comma that was causing IE to fail to load the page.
| JavaScript | apache-2.0 | cspace-deployment/ui,cspace-deployment/ui,cherryhill/collectionspace-ui,cspace-deployment/ui,cspace-deployment/ui,cherryhill/collectionspace-ui,cspace-deployment/ui,cherryhill/collectionspace-ui,cherryhill/collectionspace-ui | ---
+++
@@ -19,7 +19,7 @@
var isLocal = cspace.util.isLocal();
var oeOpts = {
alternateFields: ["accessionNumber", "objectTitle"],
- uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema",
+ uiSpecUrl: isLocal ? "./schemas/collection-object/schema.json" : "../../chain/objects/schema"
};
if (csid) {
oeOpts.csid = csid; |
48c27bbb46634c75d02bcfb60f89b327232fc913 | client/app/models/package.js | client/app/models/package.js | (function () {
app.models.Package = Backbone.Model.extend({
initialize : function () {
}
});
})();
| (function () {
app.models.Package = Backbone.Model.extend({
initialize : function () {
},
// TODO super inefficient search -- probably should cut down
// on search scope
matches : function ( query ) {
var
params = query.split(' '),
valid = false,
pkg = this;
params = _.map( params, function ( param ) {
return new RegExp( param, 'gi' );
});
_.each( params, function ( param ) {
if (
_.any( pkg.get('keywords') || [], function ( keyword ) {
return keyword.match( param );
}) ||
pkg.get('description').match( param ) ||
pkg.get('name').match( param )
) {
valid = true;
}
});
return valid;
}
});
})();
| Use client-side browsing for modules | Use client-side browsing for modules
| JavaScript | mit | web-audio-components/component.fm-old | ---
+++
@@ -1,7 +1,35 @@
(function () {
app.models.Package = Backbone.Model.extend({
+
initialize : function () {
+ },
+
+ // TODO super inefficient search -- probably should cut down
+ // on search scope
+ matches : function ( query ) {
+ var
+ params = query.split(' '),
+ valid = false,
+ pkg = this;
+
+ params = _.map( params, function ( param ) {
+ return new RegExp( param, 'gi' );
+ });
+
+ _.each( params, function ( param ) {
+ if (
+ _.any( pkg.get('keywords') || [], function ( keyword ) {
+ return keyword.match( param );
+ }) ||
+ pkg.get('description').match( param ) ||
+ pkg.get('name').match( param )
+ ) {
+ valid = true;
+ }
+ });
+
+ return valid;
}
});
})(); |
413d998e9a23cf6dea7653a87fef26e52773a622 | client/core/collaborators.js | client/core/collaborators.js | define([
'hr/utils',
'hr/hr',
'collections/users'
], function (_, hr, Users) {
// Collection for all current collaborators
var collaborators = new Users();
return collaborators;
}); | define([
'hr/utils',
'hr/hr',
'collections/users',
'utils/alerts'
], function (_, hr, Users, alerts) {
// Collection for all current collaborators
var collaborators = new Users();
collaborators.on("add", function(user) {
alerts.show(user.get("name")+" just joined the workspace", 5000);
});
collaborators.on("remove", function(user) {
alerts.show(user.get("name")+" just left the workspace", 5000);
});
return collaborators;
}); | Add alert message when users joined and left the workspace | Add alert message when users joined and left the workspace
| JavaScript | apache-2.0 | nobutakaoshiro/codebox,CodeboxIDE/codebox,nobutakaoshiro/codebox,Ckai1991/codebox,rodrigues-daniel/codebox,rajthilakmca/codebox,lcamilo15/codebox,code-box/codebox,etopian/codebox,kustomzone/codebox,smallbal/codebox,kustomzone/codebox,quietdog/codebox,ahmadassaf/Codebox,ronoaldo/codebox,rodrigues-daniel/codebox,Ckai1991/codebox,ahmadassaf/Codebox,listepo/codebox,lcamilo15/codebox,ronoaldo/codebox,LogeshEswar/codebox,rajthilakmca/codebox,LogeshEswar/codebox,blubrackets/codebox,fly19890211/codebox,etopian/codebox,blubrackets/codebox,code-box/codebox,listepo/codebox,indykish/codebox,CodeboxIDE/codebox,fly19890211/codebox,indykish/codebox,smallbal/codebox,quietdog/codebox | ---
+++
@@ -1,10 +1,19 @@
define([
'hr/utils',
'hr/hr',
- 'collections/users'
-], function (_, hr, Users) {
+ 'collections/users',
+ 'utils/alerts'
+], function (_, hr, Users, alerts) {
// Collection for all current collaborators
var collaborators = new Users();
+ collaborators.on("add", function(user) {
+ alerts.show(user.get("name")+" just joined the workspace", 5000);
+ });
+
+ collaborators.on("remove", function(user) {
+ alerts.show(user.get("name")+" just left the workspace", 5000);
+ });
+
return collaborators;
}); |
39a25f48ec2728f756ae65836d51f15ff7c0f866 | examples/public/examples.js | examples/public/examples.js |
$(function () {
(function fixControlsLength () {
$('.form-group').each(function (index) {
$('.control-label', this)
.addClass('col-xs-4').css({'text-align':'right'})
.next().addClass('col-xs-5')
.next().addClass('col-xs-3');
});
$('.control-label:contains(upload)')
.next().removeClass('col-xs-5').addClass('col-xs-3')
.next().removeClass('col-xs-3').addClass('col-xs-5').css({'overflow':'hidden'});
$('.control-label:contains(textarea)')
.removeClass('col-xs-4')
.next().removeClass('col-xs-5');
}());
(function disableLinks () {
$('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) {
return false;
});
}());
(function fixButtons () {
$('#controls button').each(function (index) {
$(this).attr('style', 'width: auto !important');
});
}());
});
|
$(function () {
(function disableLinks () {
$('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) {
return false;
});
}());
if (!(window.location != window.parent.location)) return;
(function fixControlsLength () {
$('.form-group').each(function (index) {
$('.control-label', this)
.addClass('col-xs-4').css({'text-align':'right'})
.next().addClass('col-xs-5')
.next().addClass('col-xs-3');
});
$('.control-label:contains(upload)')
.next().removeClass('col-xs-5').addClass('col-xs-3')
.next().removeClass('col-xs-3').addClass('col-xs-5').css({'overflow':'hidden'});
$('.control-label:contains(textarea)')
.removeClass('col-xs-4')
.next().removeClass('col-xs-5');
}());
(function fixButtons () {
$('#controls button').each(function (index) {
$(this).attr('style', 'width: auto !important');
});
}());
});
| Disable bootstrap responsive only inside an iframe | Disable bootstrap responsive only inside an iframe
| JavaScript | mit | simov/express-admin-site | ---
+++
@@ -1,5 +1,13 @@
$(function () {
+
+ (function disableLinks () {
+ $('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) {
+ return false;
+ });
+ }());
+
+ if (!(window.location != window.parent.location)) return;
(function fixControlsLength () {
$('.form-group').each(function (index) {
@@ -18,12 +26,6 @@
.next().removeClass('col-xs-5');
}());
- (function disableLinks () {
- $('.navbar-brand, .breadcrumb a, #controls .btn, footer .text-muted').on('click', function (e) {
- return false;
- });
- }());
-
(function fixButtons () {
$('#controls button').each(function (index) {
$(this).attr('style', 'width: auto !important'); |
54f3ce25289725244ff7945559223c7d9cd12cca | src/app/lobby/lobby.controller.js | src/app/lobby/lobby.controller.js | class LobbyController {
constructor($scope, $log, $location, GameService, SocketService) {
'ngInject';
this.$log = $log;
this.$scope = $scope;
this.GameService = GameService;
this.SocketService = SocketService;
this.game_id = GameService.game_id;
this.password = GameService.roomName;
this.players = GameService.players;
this.mobileAddress = 'fpmobile.bitballoon.com';
SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if(message.type === 'join_room') {
this.players.push({
name: message.name,
id: message.id
});
$scope.$apply( () =>{
$scope.players = this.players;
});
}
//TODO: handle player disconnect
};
SocketService.createRoom(this.password);
});
}
isPlayerConnected(number) {
return this.players[number] != null;
}
}
export default LobbyController;
| class LobbyController {
constructor(_, $scope, toastr, $log, $location, GameService, SocketService) {
'ngInject';
this._ = _;
this.$log = $log;
this.$scope = $scope;
this.toastr = toastr;
this.GameService = GameService;
this.SocketService = SocketService;
this.game_id = GameService.game_id;
this.password = GameService.roomName;
this.players = GameService.players;
this.mobileAddress = 'fpmobile.bitballoon.com';
SocketService.connect().then((result) => {
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
if (message.type === 'join_room') {
this.players.push({
name: message.name,
id: message.id
});
toastr.success(message.name + ' has connected.');
$scope.$apply(() => {
$scope.players = this.players;
});
}
if (message.type === 'player_disconnect') {
const _ = this._;
const index = _.chain(this.players)
.map((n) => n.id)
.indexOf(message.id)
.value();
if (index != -1) {
toastr.warning(this.players[index].name + ' has disconnected.');
_.remove(this.players, (n) => n.id === message.id);
$scope.$apply(() => {
$scope.players = this.players;
});
} else {
this.$log.error('Player with id ' + message.id + ' not found!');
}
}
};
SocketService.createRoom(this.password);
});
}
isPlayerConnected(number) {
return this.players[number] != null;
}
}
export default LobbyController;
| Modify players list when player disconnects | Modify players list when player disconnects
| JavaScript | mit | hendryl/Famous-Places-Web,hendryl/Famous-Places-Web | ---
+++
@@ -1,9 +1,11 @@
class LobbyController {
- constructor($scope, $log, $location, GameService, SocketService) {
+ constructor(_, $scope, toastr, $log, $location, GameService, SocketService) {
'ngInject';
+ this._ = _;
this.$log = $log;
this.$scope = $scope;
+ this.toastr = toastr;
this.GameService = GameService;
this.SocketService = SocketService;
@@ -17,17 +19,37 @@
this.$log.log('success');
this.SocketService.extendedHandler = (message) => {
- if(message.type === 'join_room') {
+ if (message.type === 'join_room') {
this.players.push({
name: message.name,
id: message.id
});
- $scope.$apply( () =>{
+
+ toastr.success(message.name + ' has connected.');
+
+ $scope.$apply(() => {
$scope.players = this.players;
});
}
- //TODO: handle player disconnect
+ if (message.type === 'player_disconnect') {
+ const _ = this._;
+ const index = _.chain(this.players)
+ .map((n) => n.id)
+ .indexOf(message.id)
+ .value();
+
+ if (index != -1) {
+ toastr.warning(this.players[index].name + ' has disconnected.');
+ _.remove(this.players, (n) => n.id === message.id);
+
+ $scope.$apply(() => {
+ $scope.players = this.players;
+ });
+ } else {
+ this.$log.error('Player with id ' + message.id + ' not found!');
+ }
+ }
};
SocketService.createRoom(this.password); |
ba53cf9d780c86286ae53b38fbd28fd904ad8273 | app/app.js | app/app.js | require('http').createServer(function(req, res) {
res.end(require('package.json').version);
}).listen(process.env.PORT || 3000); | require('http').createServer(function(req, res) {
res.end(require('./package.json').version);
}).listen(process.env.PORT || 3000); | Correct path to package file | Correct path to package file
| JavaScript | mit | proofme/grunt-awsebtdeploy,endrec/grunt-awsebtdeploy,metacommunications/grunt-awsebtdeploy,nathanwelch/grunt-awsebtdeploy,simoneb/grunt-awsebtdeploy | ---
+++
@@ -1,3 +1,3 @@
require('http').createServer(function(req, res) {
- res.end(require('package.json').version);
+ res.end(require('./package.json').version);
}).listen(process.env.PORT || 3000); |
36d6a9c69feb8b13289c8f15ab517a0667b60fdb | addons/storyshots/storyshots-core/src/index.js | addons/storyshots/storyshots-core/src/index.js | import Stories2SnapsConverter from './Stories2SnapsConverter';
import api from './api';
export * from './test-bodies';
export { Stories2SnapsConverter };
export default api;
| import Stories2SnapsConverter from './Stories2SnapsConverter';
import api from './api';
import {
snapshotWithOptions,
multiSnapshotWithOptions,
renderOnly,
renderWithOptions,
shallowSnapshot,
snapshot,
} from './test-bodies';
export {
Stories2SnapsConverter,
snapshotWithOptions,
multiSnapshotWithOptions,
renderOnly,
renderWithOptions,
shallowSnapshot,
snapshot,
};
export default api;
| Change "export * from x" to manually importing and exporting named exports. | Change "export * from x" to manually importing and exporting named exports.
| JavaScript | mit | storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook | ---
+++
@@ -1,7 +1,22 @@
import Stories2SnapsConverter from './Stories2SnapsConverter';
import api from './api';
+import {
+ snapshotWithOptions,
+ multiSnapshotWithOptions,
+ renderOnly,
+ renderWithOptions,
+ shallowSnapshot,
+ snapshot,
+} from './test-bodies';
-export * from './test-bodies';
-export { Stories2SnapsConverter };
+export {
+ Stories2SnapsConverter,
+ snapshotWithOptions,
+ multiSnapshotWithOptions,
+ renderOnly,
+ renderWithOptions,
+ shallowSnapshot,
+ snapshot,
+};
export default api; |
118261e590c58a5c69daced92aae03144a98500b | frappe/public/js/frappe/form/controls/html.js | frappe/public/js/frappe/form/controls/html.js | frappe.ui.form.ControlHTML = frappe.ui.form.Control.extend({
make: function() {
this._super();
this.disp_area = this.wrapper;
},
refresh_input: function() {
var content = this.get_content();
if(content) this.$wrapper.html(content);
},
get_content: function() {
return this.df.options || "";
},
html: function(html) {
this.$wrapper.html(html || this.get_content());
},
set_value: function(html) {
if(html.appendTo) {
// jquery object
html.appendTo(this.$wrapper.empty());
} else {
// html
this.df.options = html;
this.html(html);
}
}
});
| frappe.ui.form.ControlHTML = frappe.ui.form.Control.extend({
make: function() {
this._super();
this.disp_area = this.wrapper;
this.frm.$wrapper.on('blur change', () => {
setTimeout(() => this.refresh_input(), 500);
});
},
refresh_input: function() {
var content = this.get_content();
if(content) this.$wrapper.html(content);
},
get_content: function() {
var content = this.df.options || "";
return frappe.render(content, this);
},
html: function(html) {
this.$wrapper.html(html || this.get_content());
},
set_value: function(html) {
if(html.appendTo) {
// jquery object
html.appendTo(this.$wrapper.empty());
} else {
// html
this.df.options = html;
this.html(html);
}
}
});
| Enable using templates inside ControlHTML | Enable using templates inside ControlHTML
This change would enable showing computed data based on other fields in the same doc, without storing the computed data (which avoid unnecessary redundancy).
| JavaScript | mit | yashodhank/frappe,manassolanki/frappe,paurosello/frappe,frappe/frappe,neilLasrado/frappe,tmimori/frappe,vjFaLk/frappe,RicardoJohann/frappe,saurabh6790/frappe,ESS-LLP/frappe,mhbu50/frappe,ESS-LLP/frappe,mhbu50/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,mbauskar/frappe,tundebabzy/frappe,yashodhank/frappe,yashodhank/frappe,maxtorete/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,paurosello/frappe,paurosello/frappe,vjFaLk/frappe,maxtorete/frappe,chdecultot/frappe,manassolanki/frappe,vjFaLk/frappe,bohlian/frappe,tundebabzy/frappe,saurabh6790/frappe,frappe/frappe,mbauskar/frappe,bohlian/frappe,RicardoJohann/frappe,maxtorete/frappe,frappe/frappe,neilLasrado/frappe,mbauskar/frappe,StrellaGroup/frappe,mhbu50/frappe,adityahase/frappe,RicardoJohann/frappe,manassolanki/frappe,tmimori/frappe,almeidapaulopt/frappe,bohlian/frappe,tmimori/frappe,adityahase/frappe,saurabh6790/frappe,manassolanki/frappe,vjFaLk/frappe,bohlian/frappe,ESS-LLP/frappe,tmimori/frappe,paurosello/frappe,mbauskar/frappe,chdecultot/frappe,yashodhank/frappe,chdecultot/frappe,RicardoJohann/frappe,ESS-LLP/frappe,adityahase/frappe,neilLasrado/frappe,chdecultot/frappe,maxtorete/frappe,saurabh6790/frappe,tundebabzy/frappe,tundebabzy/frappe,adityahase/frappe,neilLasrado/frappe,StrellaGroup/frappe,mhbu50/frappe | ---
+++
@@ -2,13 +2,17 @@
make: function() {
this._super();
this.disp_area = this.wrapper;
+ this.frm.$wrapper.on('blur change', () => {
+ setTimeout(() => this.refresh_input(), 500);
+ });
},
refresh_input: function() {
var content = this.get_content();
if(content) this.$wrapper.html(content);
},
get_content: function() {
- return this.df.options || "";
+ var content = this.df.options || "";
+ return frappe.render(content, this);
},
html: function(html) {
this.$wrapper.html(html || this.get_content()); |
85b2d4790c23204545d0c12d145b6aea1e0f408d | server/app.js | server/app.js |
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
|
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
// catch all which sends all urls to index page, thus starting our app
// @note that because Express routes are registered in order, and we already defined our api routes
// this catch all will not effect prior routes.
app.use(function(req, res, next) {
app.get('*', function(req, res, next) {
//return res.ok('catch all');
res.redirect('/#' + req.url);
});
}); | Add a catch-all route to the server, which converts non-hash routes into hashed routes. | Add a catch-all route to the server, which converts non-hash routes into hashed routes.
| JavaScript | mit | brettshollenberger/rootstrikers,brettshollenberger/rootstrikers | ---
+++
@@ -23,3 +23,14 @@
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
+
+
+// catch all which sends all urls to index page, thus starting our app
+// @note that because Express routes are registered in order, and we already defined our api routes
+// this catch all will not effect prior routes.
+app.use(function(req, res, next) {
+ app.get('*', function(req, res, next) {
+ //return res.ok('catch all');
+ res.redirect('/#' + req.url);
+ });
+}); |
93664c46cc6d4c98ba1143016df5915d685a1c5a | web_external/views/widgets/DatasetInfoWidget.js | web_external/views/widgets/DatasetInfoWidget.js | import View from '../view';
import template from '../../templates/widgets/datasetInfoWidget.pug';
import '../../stylesheets/widgets/datasetInfoWidget.styl';
/**
* This widget is used to diplay minerva metadata for a dataset.
*/
const DatasetInfoWidget = View.extend({
initialize: function (settings) {
this.dataset = settings.dataset;
this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this);
},
render: function () {
var modal = this.$el.html(template(this))
.girderModal(this);
modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal }));
return this;
},
normalizeMetaInfo() {
var meta = this.dataset.get('meta').minerva;
var name = meta.original_files ? meta.original_files[0].name : meta.geojson_file.name;
var output = {
Name: name,
Source: 'file'
};
switch (meta.dataset_type) {
case 'geojson':
output.Type = 'GeoJSON';
if (meta.postgresGeojson) {
output.Source = 'PostgreSQL';
}
break;
case 'geotiff':
output.Type = 'GeoTiff';
break;
}
return output;
}
});
export default DatasetInfoWidget;
| import View from '../view';
import template from '../../templates/widgets/datasetInfoWidget.pug';
import '../../stylesheets/widgets/datasetInfoWidget.styl';
/**
* This widget is used to diplay minerva metadata for a dataset.
*/
const DatasetInfoWidget = View.extend({
initialize: function (settings) {
this.dataset = settings.dataset;
this.normalizeMetaInfo = this.normalizeMetaInfo.bind(this);
},
render: function () {
var modal = this.$el.html(template(this))
.girderModal(this);
modal.trigger($.Event('ready.girder.modal', { relatedTarget: modal }));
return this;
},
normalizeMetaInfo() {
var meta = this.dataset.get('meta').minerva;
var output = {
Name: this.dataset.get('name'),
Source: 'file'
};
if (meta.original_files && meta.original_files[0] && meta.original_files[0].name) {
output['Original name'] = meta.original_files[0].name;
} else if (meta.geojson_file && meta.geojson_file.name) {
output['Original name'] = meta.geojson_file.name;
}
switch (meta.dataset_type) {
case 'geojson':
output.Type = 'GeoJSON';
if (meta.postgresGeojson) {
output.Source = 'PostgreSQL';
}
break;
case 'geotiff':
output.Type = 'GeoTiff';
break;
}
return output;
}
});
export default DatasetInfoWidget;
| Make the query of dataset name more reliable on different kind datasets | Make the query of dataset name more reliable on different kind datasets
Some datasets are created at runtime, so it could be missing fields
Also prepare for dataset rename feature
| JavaScript | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva | ---
+++
@@ -20,11 +20,15 @@
},
normalizeMetaInfo() {
var meta = this.dataset.get('meta').minerva;
- var name = meta.original_files ? meta.original_files[0].name : meta.geojson_file.name;
var output = {
- Name: name,
+ Name: this.dataset.get('name'),
Source: 'file'
};
+ if (meta.original_files && meta.original_files[0] && meta.original_files[0].name) {
+ output['Original name'] = meta.original_files[0].name;
+ } else if (meta.geojson_file && meta.geojson_file.name) {
+ output['Original name'] = meta.geojson_file.name;
+ }
switch (meta.dataset_type) {
case 'geojson':
output.Type = 'GeoJSON'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.