commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
f63afc46d2d8d8168a3bbc97915ce9bc96815b55
deprecate forward function
service.js
service.js
var assert = require('assert'); var norma = require('norma'); var debug = require('debug')('waif:service'); var _ = require('lodash'); var EventEmitter = require('events').EventEmitter; var request = require('request'); var express = require('express'); var util = require('util'); var Uri = require('./state/uri'); var Status = require('./state/status'); /** * Service constructor. * * Instances will contain a map to all of the * services that have been mounted onto the * system. */ function Service(name) { debug('new service: %s', name); assert(name, "service not supplied with name"); this.name = name; this.middleware = []; this.uri = new Uri(); this.status = new Status(); this.initialize(); return this; } util.inherits(Service, EventEmitter); Service.prototype.setWaif = function(waif) { this.waif = waif; return this; }; Service.prototype.initialize = function() {}; Service.prototype.start = function () { debug('start listening on service: %s', this.name); // new express server this.server = express(); // mount middleware _(this.middleware).each(this.mount, this); // listen on whatever url we need to var listenArgs = this.uri.listenUrl(); listenArgs.push(listenFn.bind(this)); this.server.listen.apply(this.server, listenArgs); return this; //// helpers function listenFn(err) { debug('%s: start listening on %o', this.name, this.uri.get()); this.emit('start'); this.status.state().go('Running'); } }; Service.prototype.stop = function() { debug('%s: stop forwarding to %s', this.name, this.uri.get()); this.emit('stop'); this.status.state().go('start'); }; Service.prototype.mount = function mount(mw) { var _args = []; mw.path && _args.push(mw.path); _args.push(_initHandler.call(this, mw)); this.server.use.apply(this.server, _args); function _initHandler(mw) { if (!mw.options) { return mw.handler; } var context = { waif: this.waif, service: this }; return mw.handler.apply(context, mw.options); } }; Service.prototype.use = function() { var args = norma('{path:s?, handler:f, options:.*}', arguments); this.middleware.push(args); debug('use middlware on service: %s', this.name); return this; }; Service.prototype.forward = function(url) { this.uri.set(url); return this; }; Service.prototype.listen = function(url) { this.uri.set(url); return this; }; Service.prototype.request = function() { var args = norma('path:s?, opts:o?, cb:f?', arguments); var cb = args.cb || null; var opts = args.opts || {}; var path = args.path || opts.url || opts.uri; opts.uri = this.uri.requestUrl(path); opts.url = null; _.defaults(opts, { json: true }); debug('request on service: %s, %o', this.name, args); return request.apply(request, _.compact([opts, cb])); }; // Each service is also an event emitter, // to allow you to get notifications of // start, stop and configure. Service.createInstance = function(name, waif) { var _service = new Service(name); _service.setWaif(waif); // called directly var fn = function() { debug('request proxy on service: %s', name); return _service.request.apply(_service, arguments); }; fn.instance = _service; var proxyMethods = [ 'request', 'listen', 'use', 'start', 'stop', 'on' ]; _(proxyMethods).each(function(method) { fn[method] = function() { _service[method].apply(_service, arguments); return fn; }; }); fn.requestUrl = _service.uri.requestUrl.bind(_service.uri); return fn; }; module.exports = Service;
JavaScript
0.998522
@@ -1236,16 +1236,42 @@ need to%0A + if (this.listening) %7B%0A var li @@ -1303,16 +1303,18 @@ nUrl();%0A + listen @@ -1341,24 +1341,26 @@ ind(this));%0A + this.serve @@ -1395,24 +1395,28 @@ listenArgs); +%0A %7D %0A%0A return t @@ -2412,40 +2412,125 @@ %7B%0A -this.uri.set(url);%0A return this +console.log(%22Forward has been deprecated.%22);%0A console.log(%22Instead do '.use(pipe, %5C%22http://domain.com%5C%22).listen()'%22) ;%0A%7D; @@ -2570,24 +2570,49 @@ tion(url) %7B%0A + this.listening = true;%0A this.uri.s
0ebe3a5f57e5f457b442850829c0414404488aa0
update ListStep
src/ListStep/ListStep.js
src/ListStep/ListStep.js
/** * @file ListStep component * @author chao([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import ListStepItem from '../_ListStepItem'; class ListStep extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { activatedStep: props.activatedStep, finishedStep: props.finishedStep }; this.touchTapHandler = ::this.touchTapHandler; } touchTapHandler(activatedStep) { const {onChange} = this.props; this.setState({ activatedStep }, () => { onChange && onChange({ activatedStep, finishedStep: this.state.finishedStep }); }); } componentWillReceiveProps(nextProps) { if (nextProps.activatedStep !== this.state.activatedStep || nextProps.finishedStep !== this.state.finishedStep) { this.setState({ activatedStep: nextProps.activatedStep, finishedStep: nextProps.finishedStep }); } } render() { const {className, style, steps} = this.props; const {activatedStep, finishedStep} = this.state; return ( <div className={`list-step ${className}`} style={style}> { steps.map((item, index) => { return ( <ListStepItem key={index} index={index} className={item.className} style={{ ...item.style, zIndex: steps.length - index }} activatedStep={activatedStep} finishedStep={finishedStep} data={item} onTouchTap={this.touchTapHandler}/> ); }) } </div> ); } } ListStep.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The render content of step. */ steps: PropTypes.arrayOf(PropTypes.shape({ /** * The CSS class name of step element. */ className: PropTypes.string, /** * Override the styles of the step element. */ style: PropTypes.object, /** * The text value of step. */ title: PropTypes.string })).isRequired, /** * Sets the step as active. */ activatedStep: PropTypes.number, /** * The final step. */ finishedStep: PropTypes.number, /** * Callback function fired when step change. */ onChange: PropTypes.func }; ListStep.defaultProps = { className: '', style: null, steps: [], activatedStep: 0, finishedStep: 0 }; export default ListStep;
JavaScript
0.000001
@@ -147,16 +147,53 @@ -types'; +%0Aimport classNames from 'classnames'; %0A%0Aimport @@ -1252,17 +1252,17 @@ is.props -; +, %0A @@ -1262,21 +1262,19 @@ -const + %7Bactiva @@ -1308,16 +1308,126 @@ is.state +,%0A%0A stepClassName = classNames('list-step', %7B%0A %5BclassName%5D: className%0A %7D) ;%0A%0A @@ -1470,22 +1470,13 @@ me=%7B -%60list-step $%7Bc +stepC lass @@ -1484,10 +1484,8 @@ ame%7D -%60%7D %0A @@ -1582,48 +1582,9 @@ ) =%3E - %7B %0A - return (%0A @@ -1667,20 +1667,16 @@ - index=%7Bi @@ -1673,36 +1673,32 @@ index=%7Bindex%7D%0A - @@ -1780,28 +1780,24 @@ - style=%7B%7B%0A @@ -1793,20 +1793,16 @@ tyle=%7B%7B%0A - @@ -1892,20 +1892,16 @@ - zIndex: @@ -1963,19 +1963,11 @@ - - %7D%7D%0A - @@ -2060,36 +2060,32 @@ - finishedStep=%7Bfi @@ -2134,20 +2134,16 @@ - data=%7Bit @@ -2184,20 +2184,16 @@ - - onTouchT @@ -2244,36 +2244,8 @@ - );%0A %7D )%0A
78b5d5779388301fad48d63646a215ac01a0f1fc
Apply uglifyify transfrom only in the `prepublish` task
Gulpfile.js
Gulpfile.js
var gulp = require('gulp') var autoprefixer = require('gulp-autoprefixer') var browserify = require('browserify') var concat = require('gulp-concat') var del = require('del') var exorcist = require('exorcist') var fs = require('fs') var KarmaServer = require('karma').Server var minifyCSS = require('gulp-minify-css') var source = require('vinyl-source-stream') var standard = require('gulp-standard') var shell = require('gulp-shell') var ts = require('gulp-typescript') var tsify = require('tsify') var tslint = require('gulp-tslint') var watchify = require('watchify') var argv = require('yargs').argv var browserSync = require('browser-sync').create() var paths = { mapillaryjs: 'mapillaryjs', css: './styles/**/*.css', build: './build', ts: { src: './src/**/*.ts', tests: './spec/**/*.ts', dest: 'build', testDest: 'build/spec' }, js: { src: './build/**/*.js', tests: './spec/**/*.js' }, sourceMaps: './build/bundle.js.map', sourceMapsDist: './dist/mapillary-js.map' } var config = { browserify: { entries: ['./src/Mapillary.ts'], debug: true, standalone: 'Mapillary', cache: {}, packageCache: {} }, uglifyify: { global: true, ignore: ['**/node_modules/rest/*', '**/node_modules/rest/**/*', '**/node_modules/when/*', '**/node_modules/when/**/*' ] }, ts: JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8')).compilerOptions, typedoc: { includes: [ './src/Mapillary.ts' ], options: { target: 'ES5', module: 'commonjs', theme: 'minimal', mode: 'file', out: './docs-out', name: 'mapillary-js' } } } gulp.task('clean', function () { return del([ 'docs/ts/**/*', 'build/**/*', 'debug/**/*.js' ]) }) var parsedOptions = [] for (var key in config.typedoc.options) { parsedOptions.push('--' + key + ' ' + config.typedoc.options[key]) } gulp.task('documentation', shell.task('./node_modules/typedoc/bin/typedoc ' + parsedOptions.join(' ') + ' ' + config.typedoc.includes.join(' ') )) gulp.task('js-lint', function () { return gulp.src('./Gulpfile.js') .pipe(standard()) .pipe(standard.reporter('default', { breakOnError: true })) }) gulp.task('serve', ['ts'], function () { browserSync.init({ server: { baseDir: './debug', routes: { '/dist': 'dist', '/build': 'build' } }, logFileChanges: false }) }) gulp.task('test', function (done) { var config if (argv.grep) { config = extendKarmaConfig(__dirname + '/karma.conf.js', { client: { args: ['--grep', argv.grep] }, singleRun: true }) } else { config = extendKarmaConfig(__dirname + '/karma.conf.js', { singleRun: true }) } new KarmaServer(config, function (exitCode) { if (exitCode) { process.exit(exitCode) } }, done).start() }) gulp.task('test-watch', function (done) { var config if (argv.grep) { config = extendKarmaConfig(__dirname + '/karma.conf.js', { client: { args: ['--grep', argv.grep] }, singleRun: false }) } else { config = extendKarmaConfig(__dirname + '/karma.conf.js', { singleRun: false }) } new KarmaServer(config, function (exitCode) { if (exitCode) { process.exit(exitCode) } }, done).start() }) gulp.task('ts-lint', function (cb) { var stream = gulp.src(paths.ts.src) .pipe(tslint()) .pipe(tslint.report('verbose')) return stream }) gulp.task('tsd', shell.task('./node_modules/tsd/build/cli.js install')) gulp.task('typescript', ['ts-lint', 'typescript-src', 'typescript-test'], function (cb) { cb() }) gulp.task('typescript-src', function () { var stream = gulp.src(paths.ts.src) .pipe(ts(config.ts)) .pipe(gulp.dest(paths.ts.dest)) return stream }) gulp.task('watch', ['css'], function () { gulp.watch([paths.ts.src, paths.ts.tests], ['dev:ts']) gulp.watch([paths.css], ['css']) }) gulp.task('default', ['serve', 'watch']) // Helpers function extendKarmaConfig (path, conf) { conf.configFile = path return conf } gulp.task('prepublish', ['ts-lint', 'css'], function () { browserify(config.browserify) .plugin(tsify, config.ts) .transform('brfs') .transform('envify') .transform(config.uglifyify, 'uglifyify') .bundle() .on('error', function (error) { console.error(error.toString()) }) .pipe(exorcist(paths.sourceMapsDist)) .pipe(source('mapillary-js.min.js')) .pipe(gulp.dest('./dist')) }) // TODO: Refine this task gulp.task('ts', ['ts-lint'], function () { return browserify(config.browserify) .plugin(watchify) .plugin(tsify, config.ts) .transform('brfs') .transform('envify') .transform(config.uglifyify, 'uglifyify') .bundle() .on('error', function (error) { console.error(error.toString()) }) .pipe(exorcist(paths.sourceMaps)) .pipe(source('bundle.js')) .pipe(gulp.dest('./build')) }) gulp.task('dev:ts', ['ts --env=DEV'], function () { browserSync.reload() }) gulp.task('copy-style-assets', function () { gulp.src('styles/**/!(*.css)') .pipe(gulp.dest('dist')) }) gulp.task('css', ['copy-style-assets'], function () { gulp.src([ 'styles/mapillary-js.css', 'styles/**/!(mapillary-js)*.css' ]) .pipe(autoprefixer('last 2 version', 'safari 7', 'ie 11')) .pipe(minifyCSS()) .pipe(concat('mapillary-js.min.css')) .pipe(gulp.dest('dist')) .pipe(browserSync.stream()) })
JavaScript
0.000001
@@ -4949,54 +4949,8 @@ y')%0A - .transform(config.uglifyify, 'uglifyify')%0A
9b49abac30f1ee74d8ef40c03233eab2430225d6
Update TInyPNG token
Gulpfile.js
Gulpfile.js
var gulp = require('gulp'), concat = require('gulp-concat-css'), jshint = require('gulp-jshint'), minifycss = require('gulp-minify-css'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), imageResize = require('gulp-image-resize'), tinypng = require('gulp-tinypng'); /* * To use the gulp-image-resize, it needs of some dependencies: * https://www.npmjs.com/package/gulp-image-resize * * Or, install: * * Ubuntu: * apt-get install imagemagick * apt-get install graphicsmagick * * Mac: * brew install imagemagick * brew install graphicsmagick * * Windows & others: * http://www.imagemagick.org/script/binary-releases.php * */ var tinypngToken = '8eNoFlUv4wHzam_8GleKHdhH2YFk9xAd'; var dist = { location: 'dist/' }; var images = { content: '*.*', location: 'img/' }; images.largePhotos = { content: '*.*', location: images.location + 'largePhotos/' }; var cssfiles = 'css/*.css', imgfiles = 'img/*', jsfiles = 'js/*.js'; imgfiles = 'img/*'; gulp.task('oai', function() { gulp.src(cssfiles) .pipe(concat('oai.css')) .pipe(gulp.dest('dist/css')); }); gulp.task('minifyCss', function () { gulp.src('dist/css/oai.css') .pipe(minifycss()) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('dist/css')); }); gulp.task('js', function() { gulp.src(jsfiles) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(gulp.dest('dist/js')); gulp.src(['dist/js/dist.js']) .pipe(rename({ extname: '.min.js' })) .pipe(uglify({ preserveComments: 'some' })) .pipe(gulp.dest('dist/js')); }); gulp.task('resizeLargePhotos', function () { gulp.src(images.largePhotos.location + images.largePhotos.content) .pipe(imageResize({ height : 1080, upscale : false })) .pipe(gulp.dest(dist.location + images.largePhotos.location)); }); gulp.task('tinyImages', function () { gulp.src(images.location + images.content) .pipe(tinypng(tinypngToken)) .pipe(gulp.dest(images.location)); }); gulp.task('tinyLargePhotos', function () { gulp.src(images.largePhotos.location + images.largePhotos.content) .pipe(tinypng(tinypngToken)) .pipe(gulp.dest(images.largePhotos.location)); }); gulp.task('tiny', ['tinyImages', 'tinyLargePhotos']); gulp.task('watch', function () { gulp.watch(cssfiles, ['oai']); }); gulp.task('default', ['watch']);
JavaScript
0
@@ -682,40 +682,40 @@ = ' -8eNoFlUv4wHzam_8GleKHdhH2YFk9xAd +hHrU0V0DGG3tNna6R1sqNNOqqU-x1S4u ';%0A%0A
2b42494df5600236ed6e2d130e4303dbd3235b66
copy views to dist
Gulpfile.js
Gulpfile.js
var gulp = require('gulp') , browserSync = require('browser-sync') , jshint = require('gulp-jshint') , inject = require('gulp-inject') , wiredep = require('wiredep').stream , templateCache = require('gulp-angular-templatecache') , gulpif = require('gulp-if') , minifyCss = require('gulp-minify-css') , useref = require('gulp-useref') , uglify = require('gulp-uglify') , uncss = require('gulp-uncss'); gulp.task('webserver', function(){ browserSync({ server: { baseDir: __dirname + '/app/', directory: true }, ghostMode: false, notify: false, debounce: 200, port: 8901, startPath: 'index.html' }); gulp.watch([ __dirname + '/app/**/*.{js,html,css,svg,png,gif,jpg,jpeg}' ], { debounceDelay: 400 }, function() { browserSync.reload(); }); }); gulp.task('dist-server', function(){ browserSync({ server: { baseDir: __dirname + '/app/', directory: true }, ghostMode: false, notify: false, debounce: 200, port: 8901, startPath: 'index.html' }); gulp.watch([ __dirname + '/app/**/*.{js,html,css,svg,png,gif,jpg,jpeg}' ], { debounceDelay: 400 }, function() { browserSync.reload(); }); }); gulp.task('inject', function() { var sources = gulp.src(['./app/js/**/*.js','./app/styles/**/*.css']); return gulp.src('index.html', {cwd: './app'}) .pipe(inject(sources, { read: false, ignorePath: '/app' })) .pipe(gulp.dest('./app')); }); gulp.task('wiredep', function () { gulp.src('./app/index.html') .pipe(wiredep({ directory: './app/lib' })) .pipe(gulp.dest('./app')); }); gulp.task('reload', function(){ gulp.src('./app/**/*.{html,js,css}'); }); gulp.task('templates', function(){ gulp.src('./app/views/**/*.html') .pipe(templateCache({ root: 'views/', module: 'psAdvance.templates', standalone: true })) .pipe(gulp.dest('./app/js/templates')); }); gulp.task('compress', function(){ gulp.src('./app/index.html') .pipe(useref.assets()) .pipe(gulpif('*.js', uglify({mangle: false}))) .pipe(gulpif('*.css', minifyCss())) .pipe(gulp.dest('./dist')); }); gulp.task('copy', function(){ gulp.src('./app/index.html') .pipe(useref()) .pipe(gulp.dest('./dist')); gulp.src('./app/img/**') .pipe(gulp.dest('./dist/img')); gulp.src('./app/fonts/**') .pipe(gulp.dest('./dist/fonts')); gulp.src('./app/fonts/**') .pipe(gulp.dest('./dist/fonts')); gulp.src('./app/style/**') .pipe(gulp.dest('./dist/style')); gulp.src('./app/lib/angular-motion/**') .pipe(gulp.dest('./dist/lib/angular-motion')); gulp.src('./app/lib/angular-loading-bar/**') .pipe(gulp.dest('./dist/lib/angular-loading-bar')); gulp.src('./app/lib/components-font-awesome/**') .pipe(gulp.dest('./dist/lib/components-font-awesome')); gulp.src('./app/lib/angular-datepicker/**') .pipe(gulp.dest('./dist/lib/angular-datepicker')); }); gulp.task('watch', function(){ gulp.watch(['./app/**/*.{html,js,css}'], ['reload']); gulp.watch(['./bower.json'], ['wiredep']); gulp.watch(['./app/js/**/*.js'], ['inject']); gulp.watch(['./app/views/**/*.html'], ['templates']); }); gulp.task('prepare', ['wiredep', 'inject', 'templates']); gulp.task('build', ['prepare', 'compress', 'copy']); gulp.task('default', ['prepare', 'webserver', 'watch', 'inject', 'wiredep']);
JavaScript
0
@@ -2523,24 +2523,93 @@ './dist'));%0A + gulp.src('./app/views/**')%0A .pipe(gulp.dest('./dist/views'));%0A gulp.src
e2d51e6ecc3bd06ffa16fed5aeed5dc4b5935a63
add 'test-client-dev' gulp task (#1464)
Gulpfile.js
Gulpfile.js
const babel = require('babel-core'); const gulpBabel = require('gulp-babel'); const del = require('del'); const eslint = require('gulp-eslint'); const fs = require('fs'); const gulp = require('gulp'); const qunitHarness = require('gulp-qunit-harness'); const mocha = require('gulp-mocha'); const mustache = require('gulp-mustache'); const rename = require('gulp-rename'); const webmake = require('gulp-webmake'); const Promise = require('pinkie'); const uglify = require('gulp-uglify'); const gulpif = require('gulp-if'); const util = require('gulp-util'); const ll = require('gulp-ll'); const path = require('path'); ll .tasks('lint') .onlyInDebug([ 'server-scripts', 'client-scripts-bundle' ]); const CLIENT_TESTS_SETTINGS = { basePath: './test/client/fixtures', port: 2000, crossDomainPort: 2001, scripts: [ { src: '/hammerhead.js', path: './lib/client/hammerhead.js' }, { src: '/before-test.js', path: './test/client/before-test.js' } ], configApp: require('./test/client/config-qunit-server-app') }; const CLIENT_TESTS_BROWSERS = [ { platform: 'Windows 10', browserName: 'MicrosoftEdge' }, { platform: 'Windows 10', browserName: 'chrome' }, // NOTE: version: 'beta' don't work anymore // { // platform: 'Windows 10', // browserName: 'chrome', // version: 'beta' // }, { platform: 'Windows 10', browserName: 'firefox' }, { platform: 'Windows 10', browserName: 'internet explorer', version: '11.0' }, { browserName: 'safari', platform: 'OS X 10.12', version: '11.0' }, { browserName: 'Safari', deviceName: 'iPhone 7 Plus Simulator', platformVersion: '10.3', platformName: 'iOS' }, { browserName: 'android', platform: 'Linux', version: '6.0', deviceName: 'Android Emulator' }, { browserName: 'chrome', platform: 'OS X 10.11' }, { browserName: 'firefox', platform: 'OS X 10.11' } ]; const SAUCELABS_SETTINGS = { username: process.env.SAUCE_USERNAME, accessKey: process.env.SAUCE_ACCESS_KEY, build: process.env.TRAVIS_JOB_ID || '', tags: [process.env.TRAVIS_BRANCH || 'master'], browsers: CLIENT_TESTS_BROWSERS, name: 'testcafe-hammerhead client tests', timeout: 300 }; function hang () { return new Promise(() => { // NOTE: Hang forever. }); } // Build gulp.task('clean', cb => { del(['./lib'], cb); }); gulp.task('templates', ['clean'], () => { return gulp .src('./src/client/task.js.mustache', { silent: false }) .pipe(gulp.dest('./lib/client')); }); gulp.task('client-scripts', ['client-scripts-bundle'], () => { return gulp.src('./src/client/index.js.wrapper.mustache') .pipe(mustache({ source: fs.readFileSync('./lib/client/hammerhead.js').toString() })) .pipe(rename('hammerhead.js')) .pipe(gulpif(!util.env.dev, uglify())) .pipe(gulp.dest('./lib/client')); }); gulp.task('client-scripts-bundle', ['clean'], () => { return gulp.src('./src/client/index.js') .pipe(webmake({ sourceMap: false, transform: (filename, code) => { const transformed = babel.transform(code, { sourceMap: false, filename: filename, ast: false, // NOTE: force usage of client .babelrc for all // files, regardless of their location babelrc: false, extends: path.join(__dirname, './src/client/.babelrc') }); // HACK: babel-plugin-transform-es2015-modules-commonjs forces // 'use strict' insertion. We need to remove it manually because // of https://github.com/DevExpress/testcafe/issues/258 return { code: transformed.code.replace(/^('|")use strict('|");?/, '') }; } })) .pipe(rename('hammerhead.js')) .pipe(gulp.dest('./lib/client')); }); gulp.task('server-scripts', ['clean'], () => { return gulp.src(['./src/**/*.js', '!./src/client/**/*.js']) .pipe(gulpBabel()) .pipe(gulp.dest('lib/')); }); gulp.task('lint', () => { return gulp .src([ './src/**/*.js', './test/server/*.js', './test/client/fixtures/**/*.js', 'Gulpfile.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('build', ['client-scripts', 'server-scripts', 'templates', 'lint']); // Test gulp.task('test-server', ['build'], () => { return gulp.src('./test/server/*-test.js', { read: false }) .pipe(mocha({ ui: 'bdd', reporter: 'spec', // NOTE: Disable timeouts in debug mode. timeout: typeof v8debug === 'undefined' ? 2000 : Infinity, fullTrace: true })); }); gulp.task('test-client', ['build'], () => { gulp.watch('./src/**', ['build']); return gulp .src('./test/client/fixtures/**/*-test.js') .pipe(qunitHarness(CLIENT_TESTS_SETTINGS)); }); gulp.task('test-client-travis', ['build'], () => { return gulp .src('./test/client/fixtures/**/*-test.js') .pipe(qunitHarness(CLIENT_TESTS_SETTINGS, SAUCELABS_SETTINGS)); }); gulp.task('playground', ['set-dev-mode', 'build'], () => { require('./test/playground/server.js').start(); return hang(); }); gulp.task('travis', [process.env.GULP_TASK || '']); gulp.task('set-dev-mode', function () { util.env.dev = true; });
JavaScript
0
@@ -4984,17 +4984,16 @@ nt'%5D);%0A%0A -%0A // Test%0A @@ -5556,32 +5556,96 @@ ETTINGS));%0A%7D);%0A%0A +gulp.task('test-client-dev', %5B'set-dev-mode', 'test-client'%5D);%0A%0A gulp.task('test-
258586fb0cb2e411d5ac3b9c10783150a0659515
Fix prettyPrintXML
xml/prettyPrintXML.js
xml/prettyPrintXML.js
import { DefaultDOMElement as DOM } from '../dom' import { isString } from '../util' import _isTextNodeEmpty from './_isTextNodeEmpty' /* Schema drive pretty-printer, that inserts indentation for structural elements, and preserves white-spaces for text nodes and inline-elements */ export default function prettyPrintXML(xml) { let dom if (isString(xml)) { dom = DOM.parseXML(xml) } else { dom = xml } const result = [] dom.children.forEach((el) => { _prettyPrint(result, el, 0) }) return result.join('\n') } function _prettyPrint(result, el, level) { let indent = new Array(level*2).join(' ') if (el.isElementNode()) { const isMixed = _isMixed(el) if (isMixed) { result.push(indent + el.outerHTML) } else { let children = el.children const tagName = el.tagName let tagStr = [`<${tagName}`] el.getAttributes().forEach((val, name) => { tagStr.push(`${name}="${val}"`) }) if (children.length > 0) { result.push(indent + tagStr.join(' ') + '>') el.children.forEach((child) => { _prettyPrint(result, child, level+1) }) result.push(indent + `</${tagName}>`) } else { result.push(indent + tagStr.join(' ') + ' />') } } } else { result.push(indent + el.outerHTML) } } function _isMixed(el) { const childNodes = el.childNodes for (let i = 0; i < childNodes.length; i++) { let child = childNodes[i] if (child.isTextNode() && !_isTextNodeEmpty(child)) { return true } } }
JavaScript
0.997448
@@ -613,23 +613,32 @@ evel*2). +fill(' '). join(' - ')%0A if
d6800a25f7e2a580f11c8446b249fd23ebedc37b
Use monospace font for pre on Android
HTMLView.js
HTMLView.js
import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import htmlToElement from './htmlToElement'; import {Linking, StyleSheet, View} from 'react-native'; const boldStyle = {fontWeight: '500'}; const italicStyle = {fontStyle: 'italic'}; const underlineStyle = {textDecorationLine: 'underline'}; const codeStyle = {fontFamily: 'Menlo'}; const baseStyles = StyleSheet.create({ b: boldStyle, strong: boldStyle, i: italicStyle, em: italicStyle, u: underlineStyle, pre: codeStyle, code: codeStyle, a: { fontWeight: '500', color: '#007AFF', }, h1: {fontWeight: '500', fontSize: 36}, h2: {fontWeight: '500', fontSize: 30}, h3: {fontWeight: '500', fontSize: 24}, h4: {fontWeight: '500', fontSize: 18}, h5: {fontWeight: '500', fontSize: 14}, h6: {fontWeight: '500', fontSize: 12}, }); const htmlToElementOptKeys = [ 'lineBreak', 'paragraphBreak', 'bullet', 'TextComponent', 'textComponentProps', 'NodeComponent', 'nodeComponentProps', ]; class HtmlView extends PureComponent { constructor() { super(); this.state = { element: null, }; } componentDidMount() { this.mounted = true; this.startHtmlRender(this.props.value); } componentWillReceiveProps(nextProps) { if (this.props.value !== nextProps.value || this.props.stylesheet !== nextProps.stylesheet) { this.startHtmlRender(nextProps.value, nextProps.stylesheet); } } componentWillUnmount() { this.mounted = false; } startHtmlRender(value, style) { const { addLineBreaks, onLinkPress, onLinkLongPress, stylesheet, renderNode, onError, } = this.props; if (!value) { this.setState({element: null}); } const opts = { addLineBreaks, linkHandler: onLinkPress, linkLongPressHandler: onLinkLongPress, styles: {...baseStyles, ...stylesheet, ...style}, customRenderer: renderNode, }; htmlToElementOptKeys.forEach(key => { if (typeof this.props[key] !== 'undefined') { opts[key] = this.props[key]; } }); htmlToElement(value, opts, (err, element) => { if (err) { onError(err); } if (this.mounted) { this.setState({element}); } }); } render() { const {RootComponent, style} = this.props; const {element} = this.state; if (element) { return ( <RootComponent {...this.props.rootComponentProps} style={style} > {element} </RootComponent> ); } return ( <RootComponent {...this.props.rootComponentProps} style={style} /> ); } } HtmlView.propTypes = { addLineBreaks: PropTypes.bool, bullet: PropTypes.string, lineBreak: PropTypes.string, NodeComponent: PropTypes.func, nodeComponentProps: PropTypes.object, onError: PropTypes.func, onLinkPress: PropTypes.func, onLinkLongPress: PropTypes.func, paragraphBreak: PropTypes.string, renderNode: PropTypes.func, RootComponent: PropTypes.func, rootComponentProps: PropTypes.object, style: View.propTypes.style, stylesheet: PropTypes.object, TextComponent: PropTypes.func, textComponentProps: PropTypes.object, value: PropTypes.string, }; HtmlView.defaultProps = { addLineBreaks: true, onLinkPress: url => Linking.openURL(url), onLinkLongPress: null, onError: console.error.bind(console), RootComponent: View, }; export default HtmlView;
JavaScript
0
@@ -134,16 +134,26 @@ Linking, + Platform, StyleSh @@ -360,15 +360,54 @@ ly: -'Menlo' +Platform.OS === 'ios' ? 'Menlo' : 'monospace' %7D;%0A%0A
c67e3b17af968ebfbec5f1624750a705f68805cd
fix feature click error in preview mode
src/RowItem/StackedAnnotations/PointedAnnotation.js
src/RowItem/StackedAnnotations/PointedAnnotation.js
import Color from "color"; import classnames from "classnames"; import withHover from "../../helperComponents/withHover"; import getAnnotationNameAndStartStopString from "../../utils/getAnnotationNameAndStartStopString"; import React from "react"; import { doesLabelFitInAnnotation } from "../utils"; import { noop } from "lodash"; import getAnnotationClassnames from "../../utils/getAnnotationClassnames"; class PointedAnnotation extends React.PureComponent { render() { let { className, widthInBps, charWidth, height, rangeType, forward, name = "", type, onMouseLeave, onMouseOver, isProtein, id, hideName, pointiness = 8, color = "orange", fill, stroke, opacity, onClick, onDoubleClick = noop, textColor, onRightClick, gapsInside, gapsBefore, annotation, externalLabels, onlyShowLabelsThatDoNotFit } = this.props; const classNames = getAnnotationClassnames(annotation, { isProtein, type, viewName: "RowView" }); let width = (widthInBps + gapsInside) * charWidth; let charWN = charWidth; //charWN is normalized if (charWidth < 15) { //allow the arrow width to adapt if (width > 15) { charWN = 15; //tnr: replace 15 here with a non-hardcoded number.. } else { charWN = width; } } let widthMinusOne = width - charWN; let path; let hasAPoint = false; const endLine = annotation.doesOverlapSelf ? `L 0,${height / 2} L -10,${height / 2} L 0,${height / 2} ` : ""; const arrowLine = annotation.doesOverlapSelf ? `L ${width + 10},${height / 2} L ${width},${height / 2} ` : ""; // starting from the top left of the annotation if (rangeType === "middle") { //draw a rectangle path = ` M 0,0 L ${width - pointiness / 2},0 Q ${width + pointiness / 2},${height / 2} ${ width - pointiness / 2 },${height} L ${0},${height} Q ${pointiness},${height / 2} ${0},${0} z`; } else if (rangeType === "start") { path = ` M 0,0 L ${width - pointiness / 2},0 Q ${width + pointiness / 2},${height / 2} ${ width - pointiness / 2 },${height} L 0,${height} ${endLine} z`; } else if (rangeType === "beginningAndEnd") { hasAPoint = true; path = ` M 0,0 L ${widthMinusOne},0 L ${width},${height / 2} ${arrowLine} L ${widthMinusOne},${height} L 0,${height} ${endLine} z`; } else { hasAPoint = true; path = ` M 0,0 L ${widthMinusOne},0 L ${width},${height / 2} ${arrowLine} L ${widthMinusOne},${height} L 0,${height} Q ${pointiness},${height / 2} ${0},${0} z`; } let nameToDisplay = name; let textOffset = width / 2 - (name.length * 5) / 2 - (hasAPoint ? (pointiness / 2) * (forward ? 1 : -1) : 0); if ( !doesLabelFitInAnnotation(name, { width }, charWidth) || (externalLabels && !onlyShowLabelsThatDoNotFit && ["parts", "features"].includes(annotation.annotationTypePlural)) ) { textOffset = 0; nameToDisplay = ""; } return ( <g {...{ onMouseLeave, onMouseOver }} className={` clickable ${className} ${classNames}`} data-id={id} onClick={function (event) { onClick({ annotation, event, gapsBefore, gapsInside }); }} onDoubleClick={function (event) { onDoubleClick && onDoubleClick({ annotation, event, gapsBefore, gapsInside }); }} onContextMenu={function (event) { onRightClick({ annotation, event, gapsBefore, gapsInside }); }} > <title> {getAnnotationNameAndStartStopString(annotation, { isProtein })} </title> <path strokeWidth="1" stroke={stroke || "black"} opacity={opacity} fill={fill || color} transform={forward ? null : "translate(" + width + ",0) scale(-1,1) "} d={path} /> {!hideName && nameToDisplay && ( <text className={classnames( "veLabelText ve-monospace-font", annotation.labelClassName )} style={{ fontSize: ".9em", fill: textColor || (Color(color).isDark() ? "white" : "black") }} transform={`translate(${textOffset},${height - 2})`} > {nameToDisplay} </text> )} </g> ); } } export default withHover(PointedAnnotation);
JavaScript
0
@@ -784,24 +784,31 @@ onClick + = noop ,%0A onDo @@ -860,16 +860,23 @@ ghtClick + = noop ,%0A
d1df4f265d540906f69bea97c18db0a7f0a9b88b
work on click video list
public/js/application.js
public/js/application.js
$(document).ready(function() { var prelingerData; $("#welcome").on("submit", function(event) { event.preventDefault(); // because the preventDefault is preventing the submission // of the data, we had to create formData to catch // what the search query is supposed to be. var formData = $(event.target).serialize() console.log("Default prevented") $("#video").empty() var request = $.ajax({ url: "/new_search", type: 'POST', data: formData, dataType: 'json' }); console.log('test') request.done(function(response){ if (response.match === true){ console.log("we're done!") $("#video").append(addVideo(response)) } else { for (i = 0;i < response.film.length; i++){ // $(response).each(function(index, element) { // console.log(response.film[index].title) // // $(response.film[index].title).each(function(index, element){ $("#video").append(listSearchResults(response.film[i].title)) // $("#video").append(listSearchResults(response.film[index].title)) // // $("#video").append(listSearchResults(element)) // // }) // }) // ) } } }); }); }); var addVideo = function(data){ var video = '<video style="width:100%;height:100%;" controls>' + '<source src="https://archive.org/download/'+ data.identifier +'/'+ data.identifier +'_512kb.mp4">' + '<source src="https://archive.org/download/'+ data.identifier +'/'+ data.identifier +'.ogv">' + '</video>' return video } var listSearchResults = function(data){ var searchResults = '<h1>' + data + '</h1>' return searchResults }
JavaScript
0
@@ -1015,22 +1015,16 @@ .film%5Bi%5D -.title ))%0A @@ -1650,17 +1650,17 @@ ts = '%3Ch -1 +3 %3E' + dat @@ -1664,16 +1664,22 @@ data +.title + '%3C/h -1 +3 %3E'%0A @@ -1700,11 +1700,189 @@ Results%0A + playSearchListVideo()%0A%7D%0A%0Avar playSearchListVideo = function(filmData)%7B%0A $(%22#video%22).empty()%0A $(%22h3#video%22).select(function()%7B%0A $(%22#video%22).append(addVideo(filmData))%0A %7D)%0A%0A %7D -%0A %0A
8c2d47929cdd2d5092b5dda39e61212c769e9917
remove garbage
public/js/controllers.js
public/js/controllers.js
angular.module('elke') .controller('AppCtrl', [ '$scope', '$feathers', 'App', 'Elke', function($scope, $feathers, App, Elke) { $scope.user = false; $scope.$watch(function() { return $feathers.get('user'); }, function(user) { $scope.user = user; }); $scope.logout = $feathers.logout; // Store app data in global service for(var key in App.data) { Elke.set(key, App.data[key]); } // Redirect to registration if app not active (no users found in db) if(!Elke.get('active')) { $state.go('main.auth', {register: true}); } } ]) .controller('HomeCtrl', [ '$scope', '$state', '$feathers', 'Elke', 'Streamings', function($scope, $state, $feathers, Elke, Streamings) { var streamingService = $feathers.service('streamings'); $scope.streamings = Streamings.data; streamingService.on('created', function(data) { $scope.$apply(function() { $scope.streamings.push(data); }); }); streamingService.on('removed', function(data) { $scope.$apply(function() { $scope.streamings = _.filter($scope.streamings, function(streaming) { return streaming.id !== data.id; }); }); }); streamingService.on('updated', function(data) { $scope.$apply(function() { $scope.streamings.forEach(function(streaming, i) { if(streaming.id == data.id) { $scope.streamings[i] = data; } }); }); }); streamingService.on('patched', function(data) { $scope.$apply(function() { $scope.streamings.forEach(function(streaming, i) { if(streaming.id == data.id) { $scope.streamings[i] = data; } }); }); }); } ]) .controller('AuthCtrl', [ '$scope', '$feathers', '$state', '$stateParams', 'Elke', function($scope, $feathers, $state, $stateParams, Elke) { var userService = $feathers.service('users'); $scope.active = Elke.get('active'); if($stateParams.register) { $scope.registration = true; } $scope.credentials = {}; var auth = function() { $feathers.authenticate({ type: 'local', email: $scope.credentials.email, password: $scope.credentials.password }).then(function(res) { $state.go('main.home', {}, {reload:true}); }).catch(function(err) { console.error('Error authenticating', err); }); }; $scope.auth = function() { if($scope.registration) { userService.create($scope.credentials) .then(auth) .catch(function(err) { console.error('Error creating user', err); }); } else { auth(); } } } ]) .controller('StreamCtrl', [ '$scope', '$state', '$feathers', 'Streaming', function($scope, $state, $feathers, Streaming) { var service = $feathers.service('streamings'); $scope.streaming = angular.copy(Streaming); $scope.save = function() { if(Streaming.id) { service.patch(Streaming.id, $scope.streaming).then(function(streaming) { $scope.streaming = streaming; }); } else { service.create($scope.streaming).then(function(res) { $state.go('main.home'); }).catch(function(err) { console.error('Error creating streaming', err); }); } } $scope.createStream = function() { }; } ]);
JavaScript
0.000055
@@ -3394,53 +3394,8 @@ %7D%0A - %7D%0A $scope.createStream = function() %7B%0A
e3e78c3de307dabe0696c857bda319b62c4e2405
Make the topic IDs a little more unique.
public/js/controllers.js
public/js/controllers.js
'use strict'; /* Controllers */ function HangDownListCntr($scope) { $scope.apiLive = false; var _apiRequiredFunction = function(innerFunction){ return function(){ if ($scope.apiLive) innerFunction.apply(this, arguments); }; }; $scope.topics = []; var activeTopicId = null; $scope.activeTopicIndex = 0; $scope.currentUser = null; var resetActiveTopicIndex = function(){ var activeIndex = 0; for (var i = $scope.topics.length - 1; i >= 0; i--) { if ($scope.topics[i].id == activeTopicId) { activeIndex = i; break; } }; $scope.activeTopicIndex = activeIndex; }; $scope.topicSortConfig = { stop: function(e, ui){ // First, make sure that the active index is correct. resetActiveTopicIndex(); // Push state. pushSharedState(); } }; $scope.goToTopic = function(topicId){ // TODO: If we keep this function around, make sure to check for non-existent IDs. activeTopicId = topicId; resetActiveTopicIndex(); }; $scope.regressTopic = _apiRequiredFunction(function(){ // Only regress if the topic is not already the first. if ($scope.activeTopicIndex > 0) { activeTopicId = $scope.topics[$scope.activeTopicIndex-1].id; resetActiveTopicIndex(); // Submit changes to Google. pushSharedState(); } }); $scope.advanceTopic = _apiRequiredFunction(function(){ // Only advance if the topic is not already the last. if ($scope.activeTopicIndex < $scope.topics.length - 1) { activeTopicId = $scope.topics[$scope.activeTopicIndex+1].id; resetActiveTopicIndex(); // Submit changes to Google. pushSharedState(); } }); var _topicIndex = 0; var createTopic = function(newLabel){ return { id: new Date().getTime() + '-' + _topicIndex++, // Still don't like this way of doing it. label: newLabel, creator: $scope.currentUser.person.displayName }; }; $scope.newTopicBuffer = ''; $scope.addNewTopic = _apiRequiredFunction(function(){ // If there is no topic set, bail. if (!$scope.newTopicBuffer.length) return; // If there are any ';;', break the topic into multiple topics. var newTopics = $scope.newTopicBuffer.split(';;'); $scope.newTopicBuffer = ''; // Push add all topics. for (var i = 0; i < newTopics.length; i++) { $scope.topics.push(createTopic(newTopics[i].trim())); }; // If there is no active topic yet, set the active topic. if (activeTopicId == null) { activeTopicId = $scope.topics[0].id; $scope.activeTopicIndex = 0; } // Submit changes to Google. pushSharedState(); }); $scope.deleteTopic = _apiRequiredFunction(function(deleteTopicId){ // If we're about to delete the current topic, // determine the next topic to select. if (deleteTopicId == activeTopicId) { // If the next topic exists, use it. if ($scope.topics[$scope.activeTopicIndex+1]) activeTopicId = $scope.topics[$scope.activeTopicIndex+1].id; else if ($scope.topics[$scope.activeTopicIndex-1]) activeTopicId = $scope.topics[$scope.activeTopicIndex-1].id; else activeTopicId = null; } // Filter the array. var initialLength = $scope.topics.length; $scope.topics = $scope.topics.filter(function(topic){ return topic.id != deleteTopicId; }); // If the length hasn't changed, we're done. if (initialLength == $scope.topics.length) return; // Reset the active index. resetActiveTopicIndex(); // Push state. pushSharedState(); }); var initGapiModel = function(){ // Create expected values in the shared model. gapi.hangout.data.submitDelta({ activeTopicId: JSON.stringify(null), topics: JSON.stringify([]) }); }; var pushSharedState = function(stateDelta){ // If there was no state provided, just push the whole system. if (!stateDelta) { stateDelta = { activeTopicId: JSON.stringify(activeTopicId), topics: JSON.stringify($scope.topics) }; } // Next, set the current updater. stateDelta.modifier = $scope.currentUser.id; // Then submit the delta to GAPI. gapi.hangout.data.submitDelta( stateDelta ); }; var processStateUpdate = function(stateChangedEvent){ // If the current shared state update was self-originated, skip. if (stateChangedEvent.state.modifier == $scope.currentUser.id) return; // Otherwise, apply the shared state. applySharedState(stateChangedEvent.state); }; var applySharedState = function(newState){ // Update the internal model. $scope.topics = JSON.parse(newState.topics); activeTopicId = JSON.parse(newState.activeTopicId); // Make sure that the activeTopicIndex is updated. resetActiveTopicIndex(); $scope.$apply(); // Have to do this to force the view to update. }; // Add a callback to initialize gAPI elements. gapi.hangout.onApiReady.add(function(eventObj){ var initialState = gapi.hangout.data.getState(); // If the state has not been initialized, do that now. if (initialState.activeTopicId == undefined) initGapiModel(); // Otherwise, update internal state with shared state. else applySharedState(initialState); // Set up internal model to work with gapi. $scope.apiLive = true; $scope.currentUser = gapi.hangout.getLocalParticipant(); // Install the event handler for a change in model state. gapi.hangout.data.onStateChanged.add(processStateUpdate); }); } //HangDownListCntr.$inject = ['$scope'];
JavaScript
0.000005
@@ -1818,72 +1818,52 @@ ' + -_topicIndex++, // Still don't like this way of doing it. +$scope.currentUser.id + '-' + _topicIndex++, %0A
e2ea74bc1047cdc51a07d93a1671de6f6e56bccf
Test locally in multiple browsers
testem.js
testem.js
module.exports = { test_page: 'tests/index.html?hidepassed', disable_watching: true, launch_in_ci: [ 'Chrome' ], launch_in_dev: [ 'Chrome' ], browser_args: { Chrome: { mode: 'ci', args: [ // --no-sandbox is needed when running Chrome inside a container process.env.TRAVIS ? '--no-sandbox' : null, '--disable-gpu', '--headless', '--remote-debugging-port=0', '--window-size=1440,900' ].filter(Boolean) } } };
JavaScript
0
@@ -141,32 +141,61 @@ : %5B%0A 'Chrome' +,%0A 'Firefox',%0A 'Safari' %0A %5D,%0A browser_
2b17054833d5a57efe634c67ed03a071897dc583
Make ajax xmlhttprequest so we can get rid of jquery
src/App.js
src/App.js
import React, { Component } from 'react'; import { Router, Route, Link, browserHistory } from 'react-router'; import TopNav from './navigation/topNav.react.js'; import ErrorBar from './ErrorBar.react.js'; import getSpreadsheetData from './scripts/getSpreadsheetData.js'; import ResultListWrapper from './results/ResultListWrapper.react.js'; import $ from 'jquery'; import fuzzy from 'fuzzy'; export default class App extends Component { constructor(){ super(); this.state = { initialLoadComplete: false, errors: '', filterOptions: '', sheetName: '', filterValue: '', results:'', filteredResults: '', searchInput: '', } this.updateState = this.updateState.bind(this); this.setFilters = this.setFilters.bind(this); this.setSearchInput = this.setSearchInput.bind(this); this.componentWillMount = this.componentWillMount.bind(this); } updateState(loadState, sheetName, filterOptions, results, error){ this.setState({ initialLoadComplete: loadState, filterOptions: filterOptions, sheetName: sheetName, results: results, filteredResults: results, errors: error }) } setFilters(event){ let selectedValue = event.target.value; let matchedResults = this.state.results.filter(function(result){ return selectedValue.length > 0 ? result['category'].trim() === selectedValue.trim() : result; }) this.setState({ filterValue: event.target.value, searchInput: '', filteredResults: matchedResults }); } setSearchInput(event) { var list = this.state.results, options = { extract: function(obj){return obj['Organization Name'] + ' ' + obj['Address']} }, results = fuzzy.filter(event.target.value, list, options), matches = results.map(function(el){ return el.index; }), arrayLength = matches.length, filteredResults = []; for (var i = 0; i < arrayLength; i++) { filteredResults.push(this.state.results[matches[i]]) } this.setState({ filteredResults: filteredResults, searchInput: event.target.value }); } componentWillMount(){ $.get('/api/books/' + this.props.params.bookId, function(book_reference){ var spreadsheetLink = book_reference.google_spreadsheet_link; getSpreadsheetData(spreadsheetLink, this.updateState); this.setState({ spreadsheetId: spreadsheetLink }); }.bind(this)) } componentDidUpdate(){ if(this.state.sheetName){ localStorage.setItem(this.state.sheetName, this.props.params.bookId); } } render() { let errors; if(this.state.errors){ errors = <h1>There was an error</h1> } return ( <div> <TopNav loaded={this.state.initialLoadComplete} spreadsheetId={this.state.spreadsheetId} results={this.state.filteredResults} setSearchInput={this.setSearchInput}/> <ErrorBar errors={this.state.errors} /> <ResultListWrapper loaded={this.state.initialLoadComplete} errors={this.state.errors} filterOptions={this.state.filterOptions} setFilters={this.setFilters} results={this.state.filteredResults} /> </div> ); } }
JavaScript
0
@@ -338,32 +338,8 @@ s';%0A -import $ from 'jquery';%0A impo @@ -2164,91 +2164,246 @@ -$.get('/api/books/' + this.props.params.bookId, function(book_reference)%7B%0A +let xhr = new XMLHttpRequest();%0A xhr.open('GET', '/api/books/' + this.props.params.bookId);%0A xhr.onload = (function(data)%7B%0A if (xhr.status === 200)%7B%0A let%0A parsed = JSON.parse(data.srcElement.response),%0A -var + spr @@ -2421,22 +2421,14 @@ k = -book_reference +parsed .goo @@ -2449,16 +2449,18 @@ t_link;%0A + ge @@ -2512,16 +2512,18 @@ State);%0A + th @@ -2536,32 +2536,34 @@ State(%7B%0A + spreadsheetId: s @@ -2577,16 +2577,18 @@ eetLink%0A + %7D) @@ -2597,21 +2597,115 @@ -%7D.bind(this)) + %7D else %7B%0A console.error('Could not fetch spreadsheet');%0A %7D%0A %7D).bind(this);%0A xhr.send(); %0A %7D
e8ec147e3ed3e43503a7d287357e72771a888da5
complete first lesson
src/App.js
src/App.js
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
JavaScript
0
@@ -38,59 +38,8 @@ ct'; -%0Aimport logo from './logo.svg';%0Aimport './App.css'; %0A%0Acl @@ -106,303 +106,20 @@ %3Cdiv - className=%22App%22%3E%0A %3Cdiv className=%22App-header%22%3E%0A %3Cimg src=%7Blogo%7D className=%22App-logo%22 alt=%22logo%22 /%3E%0A %3Ch2%3EWelcome to React%3C/h2%3E%0A %3C/div%3E%0A %3Cp className=%22App-intro%22%3E%0A To get started, edit %3Ccode%3Esrc/App.js%3C/code%3E and save to reload.%0A %3C/p%3E%0A +%3EHello world %3C/di @@ -126,17 +126,16 @@ v%3E%0A ) -; %0A %7D%0A%7D%0A%0A
695182fc3f0c4ec33ab959867dd60da59e930531
Update GH repos
src/App.js
src/App.js
import React, { Component } from 'react' import dedent from 'dedent' import Background from './Background' import TopNav from './TopNav' import About from './About' import Project from './Project' import DataCard from './DataCard' import Work from './Work' import GithubRepo from './GithubRepo' import Layout, { Box, PrintGrid, PrintGridColumn } from './Layout' import { Hero, Heading, Break } from './Typo' export default class App extends Component { aboutContent = dedent` Developer currently @ Microsoft Insterested in frontend development, programming languages, and improving developer experience ` frameworkDescription = dedent` An IDE for novels. Gives users an embeddable an markup language with character analysis and formatting options. Also includes collab editing out of the box. Being developed with React, Firebase, and Google APIs. ` reasonablyTypedDescription = dedent` A Flow and TypeScript library definition compiler for Reason and BuckleScript. It takes a module type definition and turns it into something types for Reason. Written in Reason and compiled to a native binary or JavaScript. ` incyncDescription = dedent` Project for Hack MIT Fall 2015. An app for syncing presentations with your group! Finalists at Hack MIT, GE Best UX Prize, and Facebook award winners. ` topLinks = [ { printText: '516-281-6378', printIcon: 'phone' }, { text: 'GitHub', printIcon: 'dev-github-plain', printText: 'rrdelaney', href: 'https://github.com/rrdelaney' }, { text: 'Twitter', printIcon: 'dev-twitter-plain', printText: '_rrdelaney', href: 'https://twitter.com/_rrdelaney' }, { printText: '[email protected]', printIcon: 'email' }, { text: 'Résumé', href: '', right: true, onClick: async e => { e.preventDefault() await this.background.forcePrint(true) window.print() this.background.forcePrint(false) } } ] education = [ 'Rensselaer Polytechic Institute', 'Computer Science', 'Computer Systems Engineering', 'Class of 2016' ] achievements = [ '2nd @ Facebook Global Hackathon Fall 2015', 'HackMIT Finalist Fall 2015', 'Best UI @ HackMIT Fall 2015', 'Rensselaer Medal Award' ] tech = { Interests: ['Frontend', 'Compilers', 'Developer tools'], Languages: ['JavaScript', 'Reason', 'Scala', 'Python', 'PHP'], Frameworks: ['React', 'GraphQL', 'Angular', 'Django'], Databases: ['MongoDB', 'Postgres', 'Firebase'] } microsoft = [ 'Working on CMS for Office documentation', 'Leading frontend migration to React and GraphQL', 'Work across stack, using React and GraphQL API hitting legacy DB', "Contribute to other team's libraries we depend on" ] datto = [ 'Worked on web app managing fleet of backup devices', 'Used an existing codebase to add new features and fix bugs', 'Wrote unit tests and negative tests for all added features', 'Worked with PHP, Linux, and Symfony framework' ] union = [ 'Worked on a new Club Management System for the Student Union', 'Wrote full-stack features, from frontend to database', 'Used Python, Postgres, and Django' ] render() { return ( <Background ref={c => (this.background = c)}> <Hero>Ryan Delaney</Hero> <TopNav links={this.topLinks} /> <PrintGrid> <About> {this.aboutContent} </About> <PrintGridColumn col={2}> <Heading>Work</Heading> <Work company="Microsoft" position="Software Engineer" time="August 2016 - Present" data={this.microsoft} /> <Work company="Datto" position="Software Engineering Intern" time="Summer 2015" data={this.datto} /> <Work company="Rensselaer Union" position="Developer" time="Fall 2013 - Spring 2016" data={this.union} /> <Work hidePrint company="Power Management Concepts" position="Intern" time="Summer 2014" /> <Heading>Projects</Heading> <Layout> <Project name="Framework Press" url="https://framework.press" description={this.frameworkDescription} img="framework.png" /> </Layout> <Heading>Open Source</Heading> <Layout> <GithubRepo hidePrint owner="rrdelaney" name="material-resume" /> <GithubRepo owner="rrdelaney" name="ReasonablyTyped" printDescription={this.reasonablyTypedDescription} /> <GithubRepo hidePrint owner="rrdelaney" name="bs-loader" /> <GithubRepo hidePrint owner="rrdelaney" name="horizon-devtools" /> <GithubRepo hidePrint owner="rrdelaney" name="HzQL" /> <GithubRepo owner="USA-Hacks" name="inCync-Front" printDescription={this.incyncDescription} /> </Layout> </PrintGridColumn> <PrintGridColumn col={1}> <Layout> <Box> <Heading smallPrint>Education</Heading> <DataCard data={this.education} /> </Box> <Box> <Heading smallPrint>Awards</Heading> <DataCard data={this.achievements} /> </Box> </Layout> <Heading smallPrint>Tech</Heading> <DataCard data={this.tech} /> </PrintGridColumn> </PrintGrid> <Break hidePrint /> </Background> ) } }
JavaScript
0
@@ -5007,134 +5007,274 @@ Repo - hidePrint owner=%22rrdelaney%22 name=%22bs-loader%22 /%3E%0A %3CGithubRepo hidePrint owner=%22rrdelaney%22 name=%22horizon-devtools%22 +%0A hidePrint%0A owner=%22reasonml-community%22%0A name=%22reason-scripts%22%0A /%3E%0A %3CGithubRepo%0A hidePrint%0A owner=%22reasonml-community%22%0A name=%22bs-loader%22%0A /%3E%0A @@ -5337,12 +5337,24 @@ me=%22 -HzQL +horizon-devtools %22 /%3E @@ -5383,150 +5383,48 @@ Repo -%0A owner=%22USA-Hacks%22%0A name=%22inCync-Front%22%0A printDescription=%7Bthis.incyncDescription%7D%0A + hidePrint owner=%22rrdelaney%22 name=%22HzQL%22 /%3E%0A
b53659ef5988cd2b29965c81c43cb2f9c34b41e9
remove dead code
src/api.js
src/api.js
var m = require('mithril'); module.exports = function(element, controller, view) { var action = function(computation) { return function() { m.startComputation(); var result = computation.apply(null, arguments); m.endComputation(); // m.render(element, view(controller)); return result; }; }; return { set: action(controller.reconfigure), toggleOrientation: action(controller.toggleOrientation), getOrientation: controller.getOrientation, getPieces: controller.getPieces, getFen: controller.getFen, dump: function() { return controller.data; }, move: action(controller.apiMove), setPieces: action(controller.setPieces), playPremove: action(controller.playPremove) }; };
JavaScript
0.999454
@@ -254,54 +254,8 @@ ();%0A - // m.render(element, view(controller));%0A
afd7974e9b9f9e60737506952d0eb61efc6df6ac
update cookie preference script [#157372017]
src/app.js
src/app.js
import React from 'react'; import Sidebar from './components/sidebar'; import MarkdownViewer from './components/markdown_viewer'; import contentMap, {attachPackagesToWindow} from './helpers/content'; import '../stylesheets/app.scss'; import 'pivotal-ui/js/prismjs'; attachPackagesToWindow(); export default class App extends React.Component { constructor(props) { super(props); const path = window.location.pathname.split('/').pop(); this.state = {content: App.currentContent(path), path: path}; this.updateContent = this.updateContent.bind(this); } componentDidMount() { window.addEventListener('popstate', (event) => { this.updatePath(event.currentTarget.location); }, false); } updateContent(href) { window.history.pushState({}, '', href); this.updatePath(window.location); } updatePath(location) { content.scrollTop = 0; const path = location.pathname.split('/').pop(); this.setState({content: App.currentContent(path), path: path}); } static currentContent(path) { return contentMap[path] || contentMap['404']; } render() { const currentDate = new Date(); const year = currentDate.getFullYear(); const footer = (<div className="footer whitelabel-bg-color grid mrn mtxxxl"> <div className="col type-ellipsis"> <p> © {year} <a href="https://pivotal.io">Pivotal Software</a>, Inc. All Rights Reserved. <a href='https://pivotal.io/privacy-policy'>Privacy Policy</a> • <a href="https://pivotal.io/terms-of-use">Terms of Use</a> <div id="teconsent"></div> <script async="async" src="//consent.trustarc.com/notice?domain=pivotal.com&c=teconsent&js=nj&text=true&pcookie&v=<%= Time.now.to_i %>" crossorigin=""></script> </p> </div> </div> ); return ( <div id="app" className="grid grid-nogutter"> <div className="col col-fixed"> <Sidebar updateContent={this.updateContent.bind(this)} activePath={this.state.path}/> </div> <div id="content" className="col content"> <div id="wrapper"> <MarkdownViewer json={this.state.content.json} file={this.state.content.file} name={this.state.content.name}/> </div> {footer} </div> </div> ); } }
JavaScript
0
@@ -1581,27 +1581,28 @@ %3C -div +span id=%22teconse @@ -1607,19 +1607,20 @@ sent%22%3E%3C/ -div +span %3E%0A @@ -1740,31 +1740,8 @@ okie -&v=%3C%25= Time.now.to_i %25%3E %22 cr
f6be3250522f081a1c8bcf282a8e35339b48e0f1
Change test subreddit
src/app.js
src/app.js
import Snoocore from 'snoocore'; import request from 'request'; import json2md from 'json2md'; const ACCOUNT_NAME = process.env.REDDIT_ACCOUNT_NAME; const ACCOUNT_PASSWORD = process.env.REDDIT_ACCOUNT_PASSWORD; const STATSFC_API_KEY = process.env.STATSFC_API_KEY; const REDDIT_API_KEY = process.env.REDDIT_API_KEY; const REDDIT_API_SECRET = process.env.REDDIT_API_SECRET; const PREMIER_LEAGUE_ID = 426; const reddit = new Snoocore({ userAgent: '/u/devjunk [email protected]', // unique string identifying the app oauth: { type: 'script', key: REDDIT_API_KEY, secret: REDDIT_API_SECRET, username: ACCOUNT_NAME, password: ACCOUNT_PASSWORD, scope: [ 'identity', 'modconfig' ] } }); const findArsenalIndex = dataset => { let arsenal = dataset.reduce((prev,current,index) => { if (current.teamName === 'Arsenal FC') { return index; } return prev; }, {}); return arsenal; }; const buildTableObject = (dataset,arsenalIndex) => { const range = 3; let count = 0; return dataset.reduce((prev,current,index) => { let inRange = false; for(let i = 1; i <= range; i++) { if (count === range && index !== arsenalIndex) { break; }; if (index === arsenalIndex-i || index === arsenalIndex+i || index === arsenalIndex) { if (index !== arsenalIndex) { count++; } inRange = true; } } return inRange ? prev.concat(current) : prev; },[]); }; const buildMarkdownTable = tableData => { return json2md({ table: { headers: ['\\#','Team','GD','Points'], rows: tableData.map(team => { return [ team.position, team.teamName, team.goalDifference, team.points ] }) } }); }; request(`http://api.football-data.org/v1/competitions/${PREMIER_LEAGUE_ID}/leagueTable `, (err,res,body) => { if (err) { throw new Error(err); } const data = JSON.parse(body); const arsenalIndex = findArsenalIndex(data.standing); const tableObject = buildTableObject(data.standing,arsenalIndex); const markdownTable = buildMarkdownTable(tableObject); reddit('/r/willithappen/about/edit.json') .get() .then(result => { let data = result.data; data.api_type = 'json'; data.sr = data.subreddit_id; data.link_type = data.content_options; data.type = data.subreddit_type; data.description = markdownTable; return reddit('/api/site_admin').post(data); }) .done(result => { console.log(JSON.stringify(result,null,4)); }); });
JavaScript
0.000001
@@ -2160,20 +2160,20 @@ '/r/ -willithappen +sidebartests /abo
9a27af44d847e40af60c51d4bdade8d73a0c1657
Add block-seen initialisation.
src/app.js
src/app.js
var gui = require('nw.gui'); var win = gui.Window.get(); var platform = require('./components/platform'); var updater = require('./components/updater'); var menus = require('./components/menus'); var themer = require('./components/themer'); var settings = require('./components/settings'); var windowBehaviour = require('./components/window-behaviour'); var notification = require('./components/notification'); var dispatcher = require('./components/dispatcher'); var utils = require('./components/utils'); // Add dispatcher events dispatcher.addEventListener('win.alert', function(data) { data.win.window.alert(data.message); }); dispatcher.addEventListener('win.confirm', function(data) { data.callback(data.win.window.confirm(data.message)); }); // Window state windowBehaviour.restoreWindowState(win); windowBehaviour.bindWindowStateEvents(win); // Check for update if (settings.checkUpdateOnLaunch) { updater.checkAndPrompt(gui.App.manifest, win); } // Run as menu bar app if (settings.asMenuBarAppOSX) { win.setShowInTaskbar(false); menus.loadTrayIcon(win); } // Load the app menus menus.loadMenuBar(win) if (platform.isWindows || platform.isLinux) { menus.loadTrayIcon(win); } // Adjust the default behaviour of the main window windowBehaviour.set(win); windowBehaviour.setNewWinPolicy(win); // Watch the system clock for computer coming out of sleep utils.watchComputerWake(win, windowBehaviour, document); // Inject logic into the app when it's loaded var iframe = document.querySelector('iframe'); iframe.onload = function() { // Load the theming module themer.apply(iframe.contentDocument); // Inject a callback in the notification API notification.inject(iframe.contentWindow, win); // Add a context menu menus.injectContextMenu(win, document); //menus.injectContextMenu(win, iframe.contentDocument); // Bind native events to the content window windowBehaviour.bindEvents(win, iframe.contentWindow); // Watch the iframe periodically to sync the badge and the title windowBehaviour.syncBadgeAndTitle(win, document, iframe.contentDocument); // Listen for ESC key press windowBehaviour.closeWithEscKey(win, iframe.contentDocument); // Listen for offline event and remove the iframe. dispatcher.addEventListener('offline', function() { iframe = document.querySelector('iframe'); if(iframe) { iframe.remove(); } }); dispatcher.addEventListener('online', function() { iframe = document.querySelector('iframe'); if(iframe) { iframe.style.display = 'initial'; } }); dispatcher.trigger('online'); }; // Reload the app periodically until it's in online state. utils.checkForOnline(win);
JavaScript
0
@@ -454,24 +454,76 @@ spatcher');%0A +var blockSeen = require('./components/block-seen');%0A var utils = @@ -2595,16 +2595,113 @@ %0A %7D);%0A%0A + // Block 'seen' and typing indicator%0A if (settings.blockSeen) %7B%0A blockSeen.set(true);%0A %7D%0A%0A dispat
3c37801e9b4fef50ed059b7f7a04f64b13088162
use injectTapEventPlugin
src/app.js
src/app.js
import React from 'react' import ReactDOM from 'react-dom' import Route from 'react-route' import Search from './search' import SearchResults from './search_results' import DocView from './doc_view' class Main extends React.Component { constructor(props) { super(props) this.state = {searchQuery: ""} } search(query) { this.setState({ searchQuery: query }) } render() { return ( <div> <Route path="/"> <header> <Search style={{float: "right"}}/> <h1>Ratsinfo Annotieren</h1> </header> <SearchResults/> </Route> <Route path="/file/:id"> <DocView/> </Route> </div> ) } } ReactDOM.render(<Main />, document.getElementById('app-container'))
JavaScript
0.000003
@@ -83,16 +83,97 @@ t-route' +%0Aimport injectTapEventPlugin from 'react-tap-event-plugin'%0AinjectTapEventPlugin() %0A%0Aimport
5ac5c6975bb217dfd3a042cb3b91ed198d058c7a
change to log result
src/app.js
src/app.js
'use strict'; const apiai = require('apiai'); const express = require('express'); const bodyParser = require('body-parser'); const uuid = require('node-uuid'); const request = require('request'); const JSONbig = require('json-bigint'); const async = require('async'); const REST_PORT = (process.env.PORT || 5000); const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG || 'en'; const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN; const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"}); const sessionIds = new Map(); function processEvent(event) { var sender = event.sender.id.toString(); if ((event.message && event.message.text) || (event.postback && event.postback.payload)) { var text = event.message ? event.message.text : event.postback.payload; // Handle a text message from this sender if (!sessionIds.has(sender)) { sessionIds.set(sender, uuid.v1()); } console.log("Text", text); let apiaiRequest = apiAiService.textRequest(text, { sessionId: sessionIds.get(sender) }); apiaiRequest.on('response', (response) => { if (isDefined(response.result)) { let responseText = response.result.fulfillment.speech; let responseData = response.result.fulfillment.data; let action = response.result.action; let facebookAction = response.result.parameters.facebookaction; console.log(response.result.parameters) if (isDefined(responseData) && isDefined(responseData.facebook)) { if (!Array.isArray(responseData.facebook)) { try { console.log('Response as formatted message'); sendFBMessage(sender, responseData.facebook); } catch (err) { sendFBMessage(sender, {text: err.message}); } } else { responseData.facebook.forEach((facebookMessage) => { try { if (facebookMessage.sender_action) { console.log('Response as sender action'); sendFBSenderAction(sender, facebookMessage.sender_action); } else { console.log('Response as formatted message'); sendFBMessage(sender, facebookMessage); } } catch (err) { sendFBMessage(sender, {text: err.message}); } }); } } else if (isDefined(responseText)) { console.log('Response as text message'); // facebook API limit for text length is 320, // so we must split message if needed var splittedText = splitResponse(responseText); async.eachSeries(splittedText, (textPart, callback) => { sendFBMessage(sender, {text: textPart}, callback); }); if (isDefined(facebookAction)) { console.log('send action') sendFBMessage(sender, {attachment: { type: 'template', payload: { template_type: "generic", elements: [ { title: 'Welcome to creative talk page', buttons: [ { type: 'web_url', url: "https://www.facebook.com/creativetalklive", title: "View Website" }, { type: 'postback', title: 'more', payload: 'show me more' } ] } ] } }}) } } } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } } function splitResponse(str) { if (str.length <= 320) { return [str]; } return chunkString(str, 300); } function chunkString(s, len) { var curr = len, prev = 0; var output = []; while (s[curr]) { if (s[curr++] == ' ') { output.push(s.substring(prev, curr)); prev = curr; curr += len; } else { var currReverse = curr; do { if (s.substring(currReverse - 1, currReverse) == ' ') { output.push(s.substring(prev, currReverse)); prev = currReverse; curr = currReverse + len; break; } currReverse--; } while (currReverse > prev) } } output.push(s.substr(prev)); return output; } function sendFBMessage(sender, messageData, callback) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, message: messageData } }, (error, response, body) => { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } if (callback) { callback(); } }); } function sendFBSenderAction(sender, action, callback) { setTimeout(() => { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, sender_action: action } }, (error, response, body) => { if (error) { console.log('Error sending action: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } if (callback) { callback(); } }); }, 1000); } function doSubscribeRequest() { request({ method: 'POST', uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN }, (error, response, body) => { if (error) { console.error('Error while subscription: ', error); } else { console.log('Subscription result: ', response.body); } }); } function isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } const app = express(); app.use(bodyParser.text({type: 'application/json'})); app.get('/webhook/', (req, res) => { if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); setTimeout(() => { doSubscribeRequest(); }, 3000); } else { res.send('Error, wrong validation token'); } }); app.post('/webhook/', (req, res) => { try { var data = JSONbig.parse(req.body); if (data.entry) { let entries = data.entry; entries.forEach((entry) => { let messaging_events = entry.messaging; if (messaging_events) { messaging_events.forEach((event) => { if (event.message && !event.message.is_echo || event.postback && event.postback.payload) { processEvent(event); } }); } }); } return res.status(200).json({ status: "ok" }); } catch (err) { return res.status(400).json({ status: "error", error: err }); } }); app.listen(REST_PORT, () => { console.log('Rest service ready on port ' + REST_PORT); }); doSubscribeRequest();
JavaScript
0
@@ -1650,27 +1650,16 @@ e.result -.parameters )%0A%0A
91d00f68f18ea3a0602f626d9bb1d8fe8991b154
Format GraphQL errors
src/app.js
src/app.js
import http from 'http'; import express from 'express'; import bodyParser from 'body-parser'; import { makeExecutableSchema } from 'graphql-tools'; import { graphqlExpress, graphiqlExpress } from 'apollo-server-express'; import { graphqlSchema, graphqlResolvers } from './graphql'; import config from './constants/config'; const app = express(); app.server = http.createServer(app); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const executableSchema = makeExecutableSchema({ typeDefs: [graphqlSchema], resolvers: graphqlResolvers, }); app.use( '/graphql', bodyParser.json(), graphqlExpress({ schema: executableSchema, }), ); app.use( '/graphiql', graphiqlExpress({ endpointURL: '/graphql', }), ); app.server.listen(process.env.PORT || config.server.port); console.log(`🚀 Server listening on port ${app.server.address().port}...`);
JavaScript
0
@@ -665,16 +665,107 @@ Schema,%0A + formatError: error =%3E (%7B%0A message: error.message,%0A path: error.path,%0A %7D),%0A %7D),%0A);
7ee1088c819015b6d943224dd5c9c13e05ee2030
Fix force download button
src/app.js
src/app.js
import {inject} from 'aurelia-framework'; import {I18N} from 'aurelia-i18n'; import {EventAggregator} from 'aurelia-event-aggregator'; import {parseJSON} from './resources/jsonparser'; import {Field} from './resources/elements/abstract/field'; import {schema, fieldsToShow} from './schemas/index'; import {Validation} from './validation'; import YAML from 'yamljs'; import $ from 'jquery'; @inject(I18N, EventAggregator) export class App { constructor(i18n, ea) { this.split(window.localStorage.split || 'both'); Field.internationalizer = i18n; Field.eventAggregator = ea; Field.validationFunctions = new Validation(i18n); // Allow access from browser console window.$oai = this; try { const pointerlessSchema = $.extend(true, {}, schema); this.forms = parseJSON('form', pointerlessSchema); if (window.localStorage['openapi-v2-design']) { const savedData = JSON.parse(window.localStorage['openapi-v2-design']); this.forms.setValue(savedData); } } catch (exception) { console.log(exception); this.exception = exception; return; } this.activeForm = 'about'; window.onhashchange = () => { const formID = window.location.hash.substr(2) || 'about'; if (typeof this.activeForm === 'object') { this.activeForm.show = false; } if (formID === 'about') { this.activeForm = 'about'; } else if (this.forms.hasChild(formID)) { this.activeForm = this.forms.getChild(formID); this.activeForm.show = true; } else { return; } $('.nav > .nav-link.open').removeClass('open'); $(`#nav-${formID}`).addClass('open'); }; this.forms.addChangeListener(() => this.saveFormLocal()); } split(type) { this.showEditor = type !== 'preview'; this.showPreview = type !== 'editor'; this.showBoth = type === 'both'; window.localStorage.split = type; } attached() { if (window.onhashchange) { window.onhashchange(); } } setLanguage(lang) { window.localStorage.language = lang; location.reload(); } importFile() { const fileInput = $('<input/>', { type: 'file' }); fileInput.css({display: 'none'}); fileInput.appendTo('body'); fileInput.trigger('click'); fileInput.change(() => { const file = fileInput[0].files[0]; const reader = new FileReader(); reader.addEventListener('load', () => { let data; try { if (file.name.endsWith('.yaml') || file.name.endsWith('.yml')) { data = YAML.parse(reader.result); } else { data = JSON.parse(reader.result); } } catch (ex) { console.error(ex); return; // Oh noes! } this.forms.setValue(data); }, false); reader.readAsText(file); }); } importPasted() { const rawData = $(this.pasteImportData).val(); let data; try { data = YAML.parse(rawData); } catch (_) { try { data = JSON.parse(rawData); } catch (ex) { console.error(ex); return; // Oh noes! } } this.forms.setValue(data); this.closePasteImport(); } download(type, force) { if (!force) { let errors = {}; this.forms.revalidate(errors); this.downloadErrors = Object.entries(errors); if (this.downloadErrors.length > 0) { $(this.downloadErrorBox).attr('data-dl-type', type); this.downloadErrorModal.open(); return; } } else { downloadError.close(); } this.downloadErrors = []; if (!type) { type = $(this.downloadErrorBox).attr('data-dl-type'); } let data; if (type === 'json') { data = this.json; } else if (type === 'yaml') { data = this.yaml; } else { return; } // Add an anchor element that has the data as the href attribute, then click // the element to download the data. const blob = new Blob([data], {type: 'text/json'}); if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, `swagger.${type}`); } else { const downloadLink = document.createElement('a'); downloadLink.href = window.URL.createObjectURL(blob); downloadLink.download = `swagger.${type}`; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } delete() { let userInput = confirm('Do you want to delete locally cached form data? \nThis action can not be undone.'); if (userInput === true) { delete localStorage['openapi-v2-design']; location.reload(); } } getFormData() { const data = this.forms.getValue(); data.swagger = '2.0'; return data; } get yaml() { return YAML.stringify(this.getFormData(), 10, 2); } get json() { const data = JSON.stringify(this.getFormData(), '', ' '); return data; } saveFormLocal() { window.localStorage['openapi-v2-design'] = JSON.stringify(this.getFormData()); } get currentFormJSON() { if (fieldsToShow.hasOwnProperty(this.activeForm.id)) { const rawData = this.getFormData(); let output = ''; for (const field of fieldsToShow[this.activeForm.id]) { if (rawData[field]) { output += `"${field}": ${JSON.stringify(rawData[field], '', ' ')}\n`; } } return output; } const data = this.activeForm.getValue(); if (!data || (typeof data === 'object' && Object.entries(data).length === 0)) { return ''; } const stringData = JSON.stringify(data, '', ' '); return `"${this.activeForm.id}": ${stringData}`; } }
JavaScript
0.000001
@@ -3578,24 +3578,29 @@ lse %7B%0A +this. downloadErro @@ -3600,16 +3600,21 @@ oadError +Modal .close()
aa836cd2bd606aa69730e365a855731812bbaf04
repair tooltip
src/06-components/atoms/tooltip-2/tooltip-2.js
src/06-components/atoms/tooltip-2/tooltip-2.js
const registerElement = (name = 'as24-tooltip') => { const AS24TooltipPrototype = Object.create(HTMLElement.prototype, { attachedCallback: { value: function () { this.shown = false; this.content = this.querySelector('.sc-tooltip-content'); this.arrow = document.createElement('span'); this.arrow.classList.add('tooltip-arrow'); this.content.appendChild(this.arrow); this.addEventListener('mouseover', this.show, false) this.addEventListener('mousedown', this.show, false) this.addEventListener('touchstart', this.show, false) this.addEventListener('click', this.show, false) this.addEventListener('mouseleave', this.hide, false) document.addEventListener('touchstart', () => this.hide(), false) } }, show: { value: function () { clearTimeout(this.timeoutID); if (this.shown === true) return; this.content.classList.add('tooltip-shown'); this.setPosition(); } }, hide: { value: function () { this.timeoutID = window.setTimeout(() => { this.shown = false; this.content.classList.remove('tooltip-shown'); this.content.style.top = 0 + 'px'; this.content.style.left = 0 + 'px'; }, 300); } }, setPosition: { value: function () { this.shown = true; const distance = { vertical: 6, horizontal: 8 }; const contentDim = { width: this.content.offsetWidth, height: this.content.offsetHeight, } const wrapperDim = { top: this.offsetTop, left: this.offsetLeft, width: this.offsetWidth, height: this.offsetHeight, } let top = wrapperDim.top - contentDim.height - distance.vertical; let left = wrapperDim.left - (contentDim.width / 2) + (wrapperDim.width / 2); const scrollPosition = document.body.scrollTop || document.documentElement.scrollTop; if (top - scrollPosition <= 0) { top = wrapperDim.top + wrapperDim.height + distance.vertical; this.content.classList.remove('tooltip-top'); this.content.classList.add('tooltip-bottom'); } else { this.content.classList.remove('tooltip-bottom'); this.content.classList.add('tooltip-top'); } this.content.classList.remove('tooltip-right', 'tooltip-left'); if (left + contentDim.width > window.innerWidth) { left = wrapperDim.left - contentDim.width + wrapperDim.width + distance.horizontal; this.content.classList.remove('tooltip-right'); this.content.classList.add('tooltip-left'); } else if (left <= 0) { left = wrapperDim.left - distance.horizontal; this.content.classList.remove('tooltip-left'); this.content.classList.add('tooltip-right'); } this.content.style.top = top + 'px'; this.content.style.left = left + 'px'; } } }); document.registerElement(name, { prototype: AS24TooltipPrototype }); }; module.exports = () => registerElement();
JavaScript
0.000001
@@ -7,23 +7,23 @@ register -Element +Tooltip = (name @@ -3611,16 +3611,30 @@ %7D);%0A + try %7B%0A docu @@ -3698,16 +3698,178 @@ ype %7D);%0A + %7D catch (e) %7B%0A if (window && window.console) %7B%0A window.console.warn('Failed to register CustomElement %22' + name + '%22.', e);%0A %7D%0A %7D%0A %7D;%0A%0Amodu @@ -3899,14 +3899,15 @@ ster -Element +Tooltip (); +%0A
8981a80c721fd7d450c485c2445ff0cff5462619
Remove jQuery usage from authorized-keys.js
pkg/users/authorized-keys.js
pkg/users/authorized-keys.js
(function() { var $ = require("jquery"); var cockpit = require("cockpit"); var lister = require("raw!./ssh-list-public-keys.sh"); var adder = require("raw!./ssh-add-public-key.sh"); var _ = cockpit.gettext; function AuthorizedKeys (user_name, home_dir) { var self = this; var dir = home_dir + "/.ssh"; var filename = dir + "/authorized_keys"; var file = null; var watch = null; var last_tag = null; self.keys = []; self.state = "loading"; function process_failure (ex) { self.keys = []; if (ex.problem == "access-denied") { self.state = ex.problem; } else if (ex.problem == "not-found") { self.state = "ready"; } else { self.state = "failed"; console.warn("Error proccessing authentication keys: "+ ex); } $(self).triggerHandler("changed"); } function update_keys(keys, tag) { if (tag !== last_tag) return; self.keys = keys; self.state = "ready"; $(self).triggerHandler("changed"); } /* * Splits up a strings like: * * 2048 SHA256:AAAAB3NzaC1yc2EAAAADAQ Comment Here (RSA) * 2048 SHA256:AAAAB3NzaC1yc2EAAAADAQ (RSA) */ var PUBKEY_RE = /^(\S+)\s+(\S+)\s+(.*)\((\S+)\)$/; function parse_pubkeys(input) { var df = cockpit.defer(); var keys = []; cockpit.script(lister) .input(input + "\n") .done(function(output) { var match, obj, i, line, lines = output.split("\n"); for (i = 0; i + 1 < lines.length; i += 2) { line = lines[i]; obj = { raw: lines[i + 1] }; keys.push(obj); match = lines[i].trim().match(PUBKEY_RE); obj.valid = !!match && !!obj.raw; if (match) { obj.size = match[1]; obj.fp = match[2]; obj.comment = match[3].trim(); if (obj.comment == "authorized_keys" || obj.comment == "no comment") obj.comment = null; obj.algorithm = match[4]; /* Old ssh-keygen versions need us to find the comment ourselves */ if (!obj.comment && obj.raw) obj.comment = obj.raw.split(" ").splice(0, 2).join(" ") || null; } } }) .always(function() { df.resolve(keys); }); return df.promise(); } function parse_keys(content, tag, ex) { last_tag = tag; if (ex) return process_failure(ex); if (!content) return update_keys([ ], tag); parse_pubkeys(content) .done(function(keys) { update_keys(keys, tag); }); } self.add_key = function(key) { var df = cockpit.defer(); df.notify(_("Validating key")); parse_pubkeys(key) .done(function(keys) { var obj = keys[0]; if (obj && obj.valid) { df.notify(_("Adding key")); cockpit.script(adder, [ user_name, home_dir ], { superuser: "try", err: "message" }) .input(obj.raw + "\n") .done(function() { df.resolve(); }) .fail(function(ex) { df.reject(_("Error saving authorized keys: ") + ex); }); } else { df.reject(_("The key you provided was not valid.")); } }); return df.promise(); }; self.remove_key = function(key) { return file.modify(function(content) { var i; var lines = null; var new_lines = []; if (!content) return ""; new_lines = []; lines = content.trim().split('\n'); for (i = 0; i < lines.length; i++) { if (lines[i] === key) key = undefined; else new_lines.push(lines[i]); } return new_lines.join("\n"); }); }; self.close = function() { if (watch) watch.remove(); if (file) file.close(); }; file = cockpit.file(filename, {'superuser': 'try'}); watch = file.watch(parse_keys); } module.exports = { instance: function instance(user_name, home_dir) { return new AuthorizedKeys(user_name, home_dir); } }; }());
JavaScript
0
@@ -11,39 +11,8 @@ ) %7B%0A - var $ = require(%22jquery%22);%0A @@ -41,24 +41,24 @@ %22cockpit%22);%0A + %0A var lis @@ -437,16 +437,53 @@ null;%0A%0A + cockpit.event_target(self);%0A%0A @@ -942,38 +942,34 @@ -$( self -).triggerHandler +.dispatchEvent (%22change @@ -1165,30 +1165,26 @@ -$( self -).triggerHandler +.dispatchEvent (%22ch
666ee19590e747aaf2362f786588043341314400
Increase debounce delay to 100ms
src/app.js
src/app.js
import { select, event as currentEvent, } from 'd3-selection'; import { drag } from 'd3-drag'; import 'd3-transition'; // defines selection.transition() import Codeck from './Codeck'; // import installServiceWorker from './worker'; const { floor } = Math; const codeck = new Codeck(); const svg = select('#cards svg') .attr('width', '600px') .attr('height', '400px'); const messageInput = select('#message'); const cleanedMessageSpan = select('.cleanednotification'); messageInput.node().maxLength = codeck.maxLength; messageInput.node().size = codeck.maxLength; const cards = {}; codeck.deck.forEach((key, idx) => { cards[key] = { key, idx, dragging: false, dx: 0, dy: 0 }; }); const cardOrder = codeck.deck.slice(); // copy of deck. let debounceInputId = -1; messageInput.on('keyup', () => { clearTimeout(debounceInputId); debounceInputId = setTimeout(updateMessage, 25); }); function cleanMessage(text) { return text.toUpperCase().trim() .replace(/['"]/g, ',') .replace(/[!?]/g, '.') .replace(/[^A-Z0-9,. ]/g, ''); } function updateMessage() { const typedMessage = messageInput.node().value; const cleanedMessage = cleanMessage(messageInput.node().value); const newOrder = codeck.encode(cleanedMessage.toLowerCase()); newOrder.forEach((cardKey, i) => { cardOrder[i] = cardKey; cards[cardKey].idx = i; }); if (typedMessage === cleanedMessage) { cleanedMessageSpan.classed('hide', true); } else { cleanedMessageSpan .classed('hide', false) .select('span') .text(cleanedMessage); } renderCards(); } function moveCard(card, di) { if (card + di > cardOrder.length || card + di < 0) return; if (di > 0) { for (let i = card.idx; i < card.idx + di; i++) { cardOrder[i] = cardOrder[i + 1]; cards[cardOrder[i]].idx = i; } } else if (di < 0) { for (let i = card.idx; i > card.idx + di; i--) { cardOrder[i] = cardOrder[i - 1]; cards[cardOrder[i]].idx = i; } } cardOrder[card.idx + di] = card.key; card.idx += di; renderCards(); } function renderCards() { svg.selectAll('.card').transition() .delay(d => d.idx * 5) .filter(d => !d.dragging) .attr('transform', d => `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`); } function dragstarted(d) { d.dragging = true; currentEvent.sourceEvent.preventDefault(); select(this).style('filter', 'url(#shadow)'); } function dragged(d) { d.dx += currentEvent.dx; d.dy += currentEvent.dy; if (d.dx > 28) { d.dx -= 48; moveCard(d, 1); } else if (d.dx < -28) { d.dx += 48; moveCard(d, -1); } if (d.dy > 34) { d.dy -= 60; moveCard(d, 9); } else if (d.dy < -34) { d.dy += 60; moveCard(d, -9); } select(this).attr('transform', d => `translate(${d.idx % 9 * 48 + d.dx}, ${floor(d.idx / 9) * 60 + d.dy})`); } function dragended(d) { d.dx = 0; d.dy = 0; d.dragging = false; select(this).style('filter', null); renderCards(); const message = codeck.decode(cardOrder); messageInput.node().value = message.trim().toUpperCase(); cleanedMessageSpan.classed('hide', true); } function showCardsInit() { svg.selectAll('.card') .data(Object.values(cards), card => card.key) .enter().append('text') .attr('class', 'card') .attr('transform', 'translate(0, 0)') .text(card => card.key) .attr('y', 60) .attr('fill', d => (floor(d.idx / 13) % 2 !== 0) ? 'red' : 'black') .call(drag() .on('start', dragstarted) .on('drag', dragged) .on('end', dragended)); renderCards(); } setTimeout(showCardsInit, 25); // installServiceWorker();
JavaScript
0.000001
@@ -884,18 +884,19 @@ essage, -25 +100 );%0A%7D);%0A%0A @@ -3645,10 +3645,11 @@ it, -25 +100 );%0A%0A
984089e0e3e683e6be6911af2c79fd58c789d1d6
allow an alternate form of key
src/app.js
src/app.js
var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var errorhandler = require('errorhandler'); //var cookieParser = require('cookie-parser'); var session = require('cookie-session'); var apiBuilder = require('./lib/api'); var unparse = function (config) { var app = express(); //app.use(express.logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'text/plain' // Parse JS SDK is not setting request Content-Type to "application/json" })); //app.use(cookieParser()); //app.use(session(config.session)); //app.use(express.compress()); app.use(methodOverride(function (req, res) { if (req.body && typeof req.body === 'object' && '_method' in req.body) { var method = req.body._method; delete req.body._method; return method; } })); app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.use(function (req, res, next) { // App authentication // Authentication with headers var appAuth = { appId: req.get('X-Parse-Application-Id') || '', javascriptKey: req.get('X-Parse-Javascript-API-Key') || '', restKey: req.get('X-Parse-REST-API-Key') || '' }; // Authentication with basic HTTP authentication // @see https://gist.github.com/charlesdaniel/1686663 if (req.headers['authorization']) { // auth is in base64(username:password) so we need to decode the base64 // Split on a space, the original auth looks like "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part var base64 = auth.split(' ')[1]; var buf = new Buffer(base64, 'base64'); var credentials = buf.toString().split(':'); var username = credentials[0], password = credentials[1]; appAuth.appId = username; var passwdFields = password.split('&'); for (var i = 0; i < passwdFields.length; i++) { var field = passwdFields[i], fieldParts = field.split('=', 2), fieldName = fieldParts[0], fieldVal = fieldParts[1]; switch (fieldName) { case 'javascript-key': appAuth.javascriptKey = fieldVal; break; case 'rest-key': appAuth.restKey = fieldVal; break; } } } if (req.body && typeof req.body === 'object') { // Authentication with request body fields if (req.body._ApplicationId) { appAuth.appId = req.body._ApplicationId; delete req.body._ApplicationId; if (req.body._JavaScriptKey) { appAuth.javascriptKey = req.body._JavaScriptKey; delete req.body._JavaScriptKey; } } } // Check API credentials var authenticated = false; if (config.appId == appAuth.appId) { if (config.javascriptKey == appAuth.javascriptKey) { authenticated = true; } else if (config.restKey == appAuth.restKey) { authenticated = true; } } if (authenticated) { // No problem next(); } else { // Access denied res.status(401).send({ error: 'unauthorized' }); } }); apiBuilder(config).then(function (api) { app.use(api); }, function (err) { console.error('Cannot connect to database:', err); if (err.stack) { console.error(err.stack); } process.exit(1); }); // Error handling if ('development' === app.get('env')) { app.use(errorhandler()); } app.use(function (err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); }); return app; }; module.exports = unparse;
JavaScript
0.000098
@@ -1250,16 +1250,49 @@ Key') %7C%7C + req.get('X-Parse-Client-Key') %7C%7C ''%0A%09%09%7D; @@ -3484,8 +3484,9 @@ unparse; +%0A
d002cc61057e40744944733acea7eee5aa169577
Replace fs.statSync with fs.stat.
src/app.js
src/app.js
var fs = require('fs'); var tmp = require('tmp'); var express = require('express'); var util = require('util'); var app = express(); app.use(express.bodyParser()); app.set('view engine', 'jade'); app.set('views','./views'); app.get('/vocalization/:voix', function (request, response) { var spawn = require('child_process').spawn; tmp.tmpName(function _tempNameGenerated(err, espeakTmpfile) { if (err) throw err; var decodedText = decodeURIComponent(request.query.texte); var espeak = spawn('espeak', ['-vmb-' + request.params.voix , '-w' + espeakTmpfile , '-s130', decodedText]); espeak.on('exit', function(exitCode){ tmp.tmpName(function _tempNameGenerated(err, lameTmpfile) { if(err) throw err; if(exitCode === 0){ // volume normalization with fast replaygain is used by default. var options = ['-r', '-mm', '--little-endian', '--silent', '-b128', '-s16', espeakTmpfile, lameTmpfile]; var lame = spawn('lame', options); lame.on('exit', function(exitCode){ if(err) throw err; var stat = fs.statSync(lameTmpfile); response.header('Content-Type', 'audio/mpeg'); response.header('Content-Length', stat.size - 1); // There is a click that appears at the beginning of the audio. // we start reading 1 byte in to avoid it: var readstream = fs.createReadStream(lameTmpfile, {start: 1}); readstream.pipe(response); }); lame.stderr.on('data', function(data){ console.log("Lame error: " + data); }); }; }); }); espeak.stderr.on('data', function(data){ response.status(404); response.render('404', {error: data}); }); }); }); module.exports = app;
JavaScript
0
@@ -1073,57 +1073,8 @@ rr;%0A - var stat = fs.statSync(lameTmpfile);%0A @@ -1128,16 +1128,75 @@ mpeg');%0A + fs.stat(lameTmpfile, function (err, stats) %7B%0A @@ -1237,16 +1237,17 @@ h', stat +s .size - @@ -1262,16 +1262,18 @@ + // There @@ -1328,16 +1328,18 @@ audio.%0A + @@ -1393,24 +1393,26 @@ + var readstre @@ -1458,24 +1458,26 @@ start: 1%7D);%0A + @@ -1499,24 +1499,40 @@ (response);%0A + %7D);%0A %7D)
72192d194f763fec483dc30e05f9a68c823000ff
use images rather than data-uri for emoticons, closes #26
src/app.js
src/app.js
// css import './assets/css/normalize.css' import './assets/css/main.css' import './assets/css/iconmoon.css' import '../node_modules/emojify.js/dist/css/basic/emojify.min.css' // import '../node_modules/emojify.js/dist/css/sprites/emojify.css' // import '../node_modules/emojify.js/dist/css/sprites/emojify-emoticons.css' import '../node_modules/emojify.js/dist/css/data-uri/emojify.min.css' import '../node_modules/emojify.js/dist/css/data-uri/emojify-emoticons.min.css' import 'babel-polyfill' import Vue from 'vue' import emojify from 'emojify.js' import App from './components/App.vue' import './utils/filters' import './utils/sizer' // app configs Vue.config.debug = true emojify.setConfig({ mode: 'data-uri'}) // emojify.setConfig({ mode: 'sprite'}) emojify.run() // create global socket objects window.user_socket = {} window.server_socket = {} new Vue({ el: 'body', components: { App } })
JavaScript
0
@@ -180,312 +180,8 @@ %0D%0A%0D%0A -// import '../node_modules/emojify.js/dist/css/sprites/emojify.css'%0D%0A// import '../node_modules/emojify.js/dist/css/sprites/emojify-emoticons.css'%0D%0A%0D%0Aimport '../node_modules/emojify.js/dist/css/data-uri/emojify.min.css'%0D%0Aimport '../node_modules/emojify.js/dist/css/data-uri/emojify-emoticons.min.css'%0D%0A%0D%0A impo @@ -414,66 +414,83 @@ ig(%7B - +%0D%0A%09 mode: ' -data-uri'%7D)%0D%0A// emojify.setConfig(%7B mode: 'sprite' +img',%0D%0A%09img_dir: '../node_modules/emojify.js/dist/images/basic'%0D%0A %7D)%0D%0A @@ -636,18 +636,13 @@ s: %7B -%0D%0A%09%09App%0D%0A%09 + App %7D%0D%0A%7D
969f7a7f8b62dc728532ac6c0c412fe6ef832dad
check for postback
src/app.js
src/app.js
'use strict'; const apiai = require('apiai'); const express = require('express'); const bodyParser = require('body-parser'); const uuid = require('node-uuid'); const request = require('request'); const JSONbig = require('json-bigint'); const async = require('async'); const REST_PORT = (process.env.PORT || 5000); const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG || 'en'; const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN; const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"}); const sessionIds = new Map(); function processEvent(event) { var sender = event.sender.id.toString(); if (event.message && event.message.text) { var text = event.message.text; // Handle a text message from this sender if (!sessionIds.has(sender)) { sessionIds.set(sender, uuid.v1()); } console.log("Text", text); let apiaiRequest = apiAiService.textRequest(text, { sessionId: sessionIds.get(sender) }); apiaiRequest.on('response', (response) => { if (isDefined(response.result)) { let responseText = response.result.fulfillment.speech; let responseData = response.result.fulfillment.data; let action = response.result.action; if (isDefined(responseData) && isDefined(responseData.facebook)) { try { console.log('Response as formatted message'); sendFBMessage(sender, responseData.facebook); } catch (err) { sendFBMessage(sender, {text: err.message }); } } else if (isDefined(responseText)) { console.log('Response as text message'); // facebook API limit for text length is 320, // so we split message if needed var splittedText = splitResponse(responseText); async.eachSeries(splittedText, (textPart, callback) => { sendFBMessage(sender, {text: textPart}, callback); }); } } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } } function splitResponse(str) { if (str.length <= 320) { return [str]; } var result = chunkString(str, 300); return result; } function chunkString(s, len) { var curr = len, prev = 0; var output = []; while(s[curr]) { if(s[curr++] == ' ') { output.push(s.substring(prev,curr)); prev = curr; curr += len; } else { var currReverse = curr; do { if(s.substring(currReverse - 1, currReverse) == ' ') { output.push(s.substring(prev,currReverse)); prev = currReverse; curr = currReverse + len; break; } currReverse--; } while(currReverse > prev) } } output.push(s.substr(prev)); return output; } function sendFBMessage(sender, messageData, callback) { request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token: FB_PAGE_ACCESS_TOKEN}, method: 'POST', json: { recipient: {id: sender}, message: messageData } }, function (error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } if (callback) { callback(); } }); } function doSubscribeRequest() { request({ method: 'POST', uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN }, function (error, response, body) { if (error) { console.error('Error while subscription: ', error); } else { console.log('Subscription result: ', response.body); } }); } function isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } const app = express(); app.use(bodyParser.text({ type: 'application/json' })); app.get('/webhook/', function (req, res) { if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); setTimeout(function () { doSubscribeRequest(); }, 3000); } else { res.send('Error, wrong validation token'); } }); app.post('/webhook/', function (req, res) { try { var data = JSONbig.parse(req.body); var messaging_events = data.entry[0].messaging; for (var i = 0; i < messaging_events.length; i++) { var event = data.entry[0].messaging[i]; processEvent(event); } return res.status(200).json({ status: "ok" }); } catch (err) { return res.status(400).json({ status: "error", error: err }); } }); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); }); doSubscribeRequest();
JavaScript
0
@@ -744,16 +744,17 @@ %0A if +( (event.m @@ -787,47 +787,135 @@ xt) -%7B%0A var text = event.message.text +%7C%7C (event.postback && event.postback.payload)) %7B%0A var text = event.message ? event.message.text : event.postback.payload ;%0A
13bf810797b8e0c857a69c350df761754a193c95
remove invalid third argument to ServiceProviderSetup
src/app.js
src/app.js
'use strict'; /** * @file * Configure and start our server */ // Config import {version} from '../package.json'; // path for the API-endpoint, ie /v0/, /v1/, or .. const apiPath = '/v' + parseInt(version, 10) + '/'; // Libraries import fs from 'fs'; import express from 'express'; import path from 'path'; import Logger from 'dbc-node-logger'; import RedisStore from 'connect-redis'; import ServiceProviderSetup from './ServiceProviderSetup.js'; // Middleware import bodyParser from 'body-parser'; import compression from 'compression'; import expressSession from 'express-session'; import helmet from 'helmet'; // Generation of swagger specification import swaggerFromSpec from './swaggerFromSpec.js'; module.exports.run = function (worker) { // Setup const app = express(); const server = worker.httpServer; const ENV = app.get('env'); const PRODUCTION = ENV === 'production'; const APP_NAME = process.env.APP_NAME || 'app_name'; // eslint-disable-line no-process-env const logger = new Logger({app_name: APP_NAME}); const expressLoggers = logger.getExpressLoggers(); // Old config, currently stored in config.json, should be delivered from auth-server, etc. later on const config = JSON.parse( fs.readFileSync( process.env.CONFIG_FILE || // eslint-disable-line no-process-env __dirname + '/../config.json', 'utf8')); config.cache.store = require('cache-manager-redis'); // Direct requests to app server.on('request', app); // Setting bodyparser app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // Helmet configuration // TODO: Setup rest of Helmet, in a way that works with the server setup. app.use(helmet.frameguard()); app.use(helmet.hidePoweredBy({setTo: 'Funkys Venner!'})); app.use(helmet.ieNoOpen()); app.use(helmet.noSniff()); // Port config app.set('port', process.env.PORT || 8080); // eslint-disable-line no-process-env // Configure app variables let serviceProvider = ServiceProviderSetup(config, logger, worker); app.set('serviceProvider', serviceProvider); app.set('logger', logger); // Setup environments let redisConfig; // Redis switch (ENV) { case 'development': redisConfig = config.sessionStores.redis.development; // eslint-disable-line no-process-env break; case 'production': redisConfig = config.sessionStores.redis.production; // eslint-disable-line no-process-env break; default: redisConfig = config.sessionStores.redis.local; // eslint-disable-line no-process-env break; } let redisStore = RedisStore(expressSession); let sessionMiddleware = expressSession({ store: new redisStore({ host: redisConfig.host, port: redisConfig.port, prefix: APP_NAME + '_session_' }), secret: redisConfig.secret + APP_NAME, name: APP_NAME, rolling: true, resave: false, saveUninitialized: false, cookie: { path: '/', httpOnly: true, secure: PRODUCTION } }); // Adding gzip'ing app.use(compression()); // Setting paths app.all('/', (req, res) => res.redirect(apiPath)); app.use(apiPath, express.static(path.join(__dirname, '../static'))); // Setting logger app.use(expressLoggers.logger); // Setting sessions app.use(sessionMiddleware); // DUMMY context, - TODO: get this from the auth server through token, and preserve through sessions let dummyContext = { request: {session: {}}, libdata: { kommune: 'aarhus', config: config, libraryId: (config || {}).agency } // request: {session: req.session}, // libdata: res.locals.libdata }; // Execute transform function callApi(event, query, context, callback) { let prom; // Currently it is needed to run the old-school version of getRecommendations, // since the apitests uses the property isFrontPage=true, which calls the meta-recommender. // But only the regular recommender is implemented in the current neoGetRecommendations. prom = serviceProvider.trigger(event, query, context); // When the above mentioned is fixed, the below will make use of neoGetRecommendations! // if (event === 'getRecommendations') { // console.log('Neo Event called: ' + event); // eslint-disable-line no-console // // The below expects an array. We will give it what it asks for! // prom = [serviceProvider.execute(event, query, context)]; // } else { // eslint-disable-line brace-style // console.log('Old-School Event called: ' + event); // eslint-disable-line no-console // prom = serviceProvider.trigger(event, query, context); // } // TODO: result from serviceProvider should just be a single promise. // fix this in provider if (Array.isArray(prom)) { console.log('warning', 'result is array, instead of single promise', event); // eslint-disable-line no-console if (prom.length !== 1) { console.error('error', 'result length is ', prom.length); // eslint-disable-line no-console } prom = Array.isArray(prom) ? prom : [prom]; } prom[0].then((response) => { callback(response); }, (error) => { callback(error); }); } // WebSocket/SocketCluster transport worker.on('connection', (connection) => { for (let key of serviceProvider.availableTransforms()) { connection.on(key, (data, callback) => { // eslint-disable-line no-loop-func callApi(key, data, dummyContext, callback); }); } }); // HTTP Transport for (let event of serviceProvider.availableTransforms()) { app.all(apiPath + event, (req, res) => { // eslint-disable-line no-loop-func // TODO: should just be req.body, when all endpoints accept object-only as parameter, until then, this hack supports legacy transforms let query = Array.isArray(req.body) ? req.body[0] : req.body; query = query || {}; for (let key in req.query) { // eslint-disable-line guard-for-in try { query[key] = JSON.parse(req.query[key]); } catch (_) { query[key] = req.query.key; } } callApi(event, query, dummyContext, response => { app.set('json spaces', query.pretty ? 2 : null); res.jsonp(response); }); }); } app.all(apiPath + 'swagger.json', (req, res) => { return swaggerFromSpec().then((response) => { res.jsonp(response); }, (error) => { res.jsonp(error); }); }); // Graceful handling of errors app.use((err, req, res, next) => { logger.log('error', 'An error occurred! Got following: ' + err); console.error('error', 'An error occurred! Got following: ', err); // eslint-disable-line no-console console.error(err.stack); // eslint-disable-line no-console if (res.headersSent) { return next(err); } res.status(500); res.jsonp({error: String(err)}); res.end(); }); // Handle 404's app.use((req, res) => { res.status(404); res.jsonp({error: '404 Not Found'}); res.end(); }); // Setting logger -- should be placed after routes app.use(expressLoggers.errorLogger); logger.log('debug', '>> Worker PID: ' + process.pid); logger.log('debug', 'Server listening on port ' + app.get('port')); logger.log('debug', 'APP_NAME: ' + APP_NAME); logger.log('info', 'Versions: ', process.versions); logger.log('info', version + ' is up and running'); };
JavaScript
0
@@ -2041,16 +2041,8 @@ gger -, worker );%0A
dd1f46d6ed12d536f0ac8ddd74c6c7dc491c9f0a
add ;
Client/Client.js
Client/Client.js
"use strict"; var HEARTBEAT_SECONDS = 10; var zmq = require("zmq"); var axon = require("axon"); var MonitoredSocket = require("./MonitoredSocket"); var RPCClient = require("./RPCClient"); var SourceClient = require("./SourceClient"); var SharedObjectClient = require("./SharedObjectClient"); var PullClient = require("./PullClient"); var SinkClient = require("./SinkClient"); class Client { constructor(descriptor, workers){ if (!workers){ workers = {} } this.workers = workers; this.descriptor = descriptor; this.transports = {}; this._setupTransports(); this._setupEndpoints(); } _setupTransports(){ for(let transport in this.descriptor.transports){ switch (transport){ case 'source': this._setupSource(this.descriptor.transports.source.client); break; case 'sink': this._setupSink(this.descriptor.transports.sink.client); break; case 'rpc': this._setupRpc(this.descriptor.transports.rpc.client); break; case 'pushpull': this._setupPull(); break; default: break; } } } _setupSource(hostname){ var msock = new MonitoredSocket('sub'); this.transports.source = msock.sock; this.transports.source.connect(hostname); this._sourceHostname = hostname; this._setupHeartbeat(); this.transports.source.on('message', this._sourceCallback.bind(this)); msock.on('disconnected', this._sourceClosed.bind(this)); msock.on('connected', this._sourceConnected.bind(this)); } _setupHeartbeat(){ this['_heartbeat'] = { _processMessage: this._resetHeartbeatTimeout.bind(this) } this.transports.source.subscribe('_heartbeat'); } _setupSink(hostname){ var sock = new zmq.socket('push'); this.transports.sink = sock; sock.connect(hostname); } _sourceCallback(endpoint, message){ var data = JSON.parse(message); this[endpoint]._processMessage(data); } _sourceConnected(){ this._heartbeatTimeout = setTimeout(this._heartbeatFailed.bind(this), HEARTBEAT_SECONDS * 1000); // Loop endpoints for(let endpoint of this.descriptor.endpoints) { if (endpoint.type == 'Source' || endpoint.type == 'SharedObject') { console.log(endpoint.name, 'connected'); this[endpoint.name].emit('connected') if (endpoint.type == 'SharedObject') { if(this[endpoint.name].ready == false && this[endpoint.name].subscribed) this[endpoint.name]._init(); } } } } _sourceClosed(){ clearTimeout(this._heartbeatTimeout); // Loop endpoints for(let endpoint of this.descriptor.endpoints) { if (endpoint.type == 'Source' || endpoint.type == 'SharedObject') { console.log(endpoint.name, 'disconnected'); this[endpoint.name].emit('disconnected') if (endpoint.type == 'SharedObject') { this[endpoint.name]._flushData(); } } } } _resetHeartbeatTimeout(){ clearTimeout(this._heartbeatTimeout); this._heartbeatTimeout = setTimeout(this._heartbeatFailed.bind(this), HEARTBEAT_SECONDS * 1000); } _heartbeatFailed(){ console.error('Heartbeat failed source transport -> Closing connection'); this.transports.source.disconnect(this._sourceHostname) this._sourceClosed(); this.transports.source.connect(this._sourceHostname) } _setupRpc(hostname){ var sock = new axon.socket('req'); sock.connect(hostname); this.transports.rpc = sock; } _setupPull(hostname){ var sock = new zmq.socket("pull"); // DON'T CONNECT! Client must explicitly ask! sock.on('message', this._pullCallback.bind(this)); this.transports.pushpull = sock; } _pullCallback(message){ if (!this.PullEndpoint){ throw new Error("Got a pull message, but ot Pull enpoint is connected!"); } this.PullEndpoint._processMessage(JSON.parse(message)); } _setupEndpoints(){ for(let endpoint of this.descriptor.endpoints){ switch(endpoint.type){ case 'RPC': this[endpoint.name] = new RPCClient(endpoint, this.transports); break; case 'Source': this[endpoint.name] = new SourceClient(endpoint, this.transports); break; case 'SharedObject': this[endpoint.name] = new SharedObjectClient(endpoint, this.transports); this['_SO_'+endpoint.name] = this[endpoint.name]; break; case 'PushPull': if (this.PullEndpoint){ throw new Error("Only a singly Pushpull endpoint can be constructed per service!"); } this[endpoint.name] = new PullClient(endpoint, this.transports, this.descriptor.transports.pushpull.client); this.PullEndpoint = this[endpoint.name]; break; case 'Sink': this[endpoint.name] = new SinkClient(endpoint, this.transports, this.descriptor.transports.sink.client); this.SinkEndpoint = this[endpoint.name]; break; default: throw "Unknown endpoint type."; } } } } module.exports = Client;
JavaScript
0
@@ -3255,32 +3255,33 @@ ('disconnected') +; %0A
87fe8ae14c1bd8cccd879627fc74ecd5aacb9e02
Access "canmakepayment" event members.
pr/apps/src2/card1/app.js
pr/apps/src2/card1/app.js
self.resolver = null; const response = { methodName: 'https://rsolomakhin.github.io/pr/apps/src2', details: { billingAddress: { addressLine: [ '1875 Explorer St #1000', ], city: 'Reston', country: 'US', dependentLocality: '', languageCode: '', organization: 'Google', phone: '+15555555555', postalCode: '20190', recipient: 'Jon Doe', region: 'VA', sortingCode: '' }, cardNumber: '4111111111111111', cardSecurityCode: '123', cardholderName: 'Jon Doe', expiryMonth: '01', expiryYear: '2020', }, }; self.addEventListener('message', (evt) => { if (evt.data === 'confirm' && self.resolver !== null) { self.resolver(response); self.resolver = null; } else { console.log('Unrecognized message: ' + evt.data); } }); self.addEventListener('paymentrequest', (evt) => { evt.respondWith(new Promise((resolve) => { self.resolver = resolve; evt.openWindow('confirm.html'); })); });
JavaScript
0
@@ -904,16 +904,594 @@ %7D%0A%7D);%0A%0A +self.addEventListener('canmakepayment', (evt) =%3E %7B%0A if (evt.topOrigin !== 'https://rsolomakhin.github.io') %7B%0A console.log('Hi ' + evt.topOrigin + '!');%0A %7D%0A if (evt.paymentRequestOrigin !== 'https://rsolomakhin.github.io' && evt.paymentRequestOrigin !== evt.topOrigin) %7B%0A console.log('Hi ' + evt.paymentRequestOrigin + '!');%0A %7D%0A if (evt.modifiers && evt.modifiers.length %3E 0) %7B%0A console.log('Modifiers are present.');%0A %7D%0A if (evt.methodData && evt.methodData.length !== 1) %7B%0A console.log('Did not expect ' + str(evt.methodData.length) + ' methods.');%0A %7D%0A%7D);%0A%0A self.add
0d4d23e8e0c4f446da5781265dd25622500ef54e
Rearrange requires to make eslint happy
src/app.js
src/app.js
const log = require('./logger'); const icon = require('./icon'); const pjson = require('../package.json'); const store = require('./store'); const electron = require('electron'); const AutoLaunch = require('auto-launch'); const contribution = require('contribution'); const { app, BrowserWindow, Tray, Menu, shell, ipcMain } = electron; app.on('ready', () => { const streakerAutoLauncher = new AutoLaunch({ name: pjson.name, path: `/Applications/${pjson.name}.app` }); const tray = new Tray(icon.done); let usernameWindow = null; function createUsernameWindow() { if (usernameWindow) { usernameWindow.focus(); return; } usernameWindow = new BrowserWindow({ title: `${pjson.name} - Set GitHub Username`, frame: false, width: 270, height: 60, resizable: false, maximizable: false, show: false }); usernameWindow.loadURL(`file://${__dirname}/username.html`); usernameWindow.once('ready-to-show', () => { const screen = electron.screen.getDisplayNearestPoint( electron.screen.getCursorScreenPoint() ); usernameWindow.setPosition( Math.floor( screen.bounds.x + screen.size.width / 2 - usernameWindow.getSize()[0] / 2 ), Math.floor( screen.bounds.y + screen.size.height / 2 - usernameWindow.getSize()[1] / 2 ) ); usernameWindow.show(); }); usernameWindow.on('closed', () => { usernameWindow = null; }); usernameWindow.on('blur', () => { usernameWindow.close(); }); } function createTrayMenu(contributionCount, currentStreak) { const username = store.get('username') || 'username not set'; const githubProfileUrl = `https://github.com/${username}`; const menuTemplate = [ { label: username, enabled: false }, { type: 'separator' }, { label: `Current Streak:\t${currentStreak}`, enabled: false }, { label: `Best Streak:\t\t${currentStreak}`, enabled: false }, { label: `Contributions:\t${contributionCount}`, enabled: false }, { type: 'separator' }, { label: 'Reload', accelerator: 'Cmd+R', click: requestContributionData }, { label: 'Open GitHub Profile...', accelerator: 'Cmd+O', click: () => shell.openExternal(githubProfileUrl) }, { type: 'separator' }, { label: 'Set GitHub Username...', accelerator: 'Cmd+S', click: createUsernameWindow }, { label: 'Preferences', submenu: [ { label: `Launch ${pjson.name} at login`, type: 'checkbox', checked: store.get('autoLaunch'), click: checkbox => { store.set('autoLaunch', checkbox.checked); if (checkbox.checked) { streakerAutoLauncher.enable(); } else { streakerAutoLauncher.disable(); } log.info(`Store updated - autoLaunch=${checkbox.checked}`); } } ] }, { type: 'separator' }, { label: `About ${pjson.name}...`, click: () => shell.openExternal(pjson.homepage) }, { label: 'Feedback && Support...', click: () => shell.openExternal(pjson.bugs.url) }, { type: 'separator' }, { label: `Quit ${pjson.name}`, accelerator: 'Cmd+Q', click: () => app.quit() } ]; return Menu.buildFromTemplate(menuTemplate); } function requestContributionData() { tray.setImage(icon.load); tray.setContextMenu(createTrayMenu('Loading...', 'Loading...')); const username = store.get('username'); contribution(username) .then(data => { tray.setContextMenu(createTrayMenu(data.contributions, data.streak)); tray.setImage(data.streak > 0 ? icon.done : icon.todo); log.info( `Request successful - username=${username} streak=${ data.streak } today=${data.contribution > 0}` ); }) .catch(error => { tray.setContextMenu(createTrayMenu('Error', 'Error')); tray.setImage(icon.fail); log.error( `Request failed - username=${username}) statusCode=${ error.statusCode }` ); }); } function setUsername(event, username) { usernameWindow.close(); if (username && username !== store.get('username')) { store.set('username', username); requestContributionData(); log.info(`Store updated - username=${username}`); } } app.dock.hide(); app.on('window-all-closed', () => {}); tray.on('right-click', requestContributionData); ipcMain.on('setUsername', setUsername); requestContributionData(); setInterval(requestContributionData, 1000 * 60 * 15); // 15 Minutes });
JavaScript
0.000014
@@ -1,12 +1,140 @@ +const electron = require('electron');%0Aconst AutoLaunch = require('auto-launch');%0Aconst contribution = require('contribution');%0A%0A const log = @@ -265,135 +265,8 @@ e'); -%0Aconst electron = require('electron');%0Aconst AutoLaunch = require('auto-launch');%0Aconst contribution = require('contribution'); %0A%0Aco
d8de59f9cc549ed5b9dd102c97cd141d86f871d5
Update login callback
pre-diary/routes/users.js
pre-diary/routes/users.js
var express = require('express'); var router = express.Router(); var mysql = require('../util/sql').mysql; var pool = require('../util/sql').pool; /** * @api {get} /users/:id Get User Info * @apiName GetUser * @apiGroup User * * @apiSuccess {Object} user user 데이터 * @apiSuccess {String} user.id 유저 id * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "id": "123456abcdef" * } */ router.get('/:id', function(req, res, next) { pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); res.send('respond with a resource'); }); }); /** * @api {post} /users Add New User * @apiName PostUser * @apiGroup User * * @apiParam {String} type 가입 타입 * * @apiSuccess {Object} user user 데이터 * @apiSuccess {String} user.id 유저 id(쿠키에 저장할 값) * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "id": "123456abcdef" * } */ router.post('/', function(req, res, next) { }); module.exports = router;
JavaScript
0.000001
@@ -669,16 +669,101 @@ );%0A%7D);%0A%0A +router.get('/login/callback', function(req, res, next) %7B%0A res.send(req.query);%0A%7D);%0A%0A /**%0A * @
7d6a24ac4379e47a41d55b1455ea255b45b5e262
Fix keys
src/modules/modals/JSONmodal/JSONmodal.js
src/modules/modals/JSONmodal/JSONmodal.js
import React, { PureComponent } from 'react' import { bool, object } from 'prop-types' import R from 'ramda' import Modal from '../../../components/Modal/Modal' import Button from '../../../components/Button/Button' import JSONeditor from '../../../components/JSONeditor/JSONeditor' import adjustToJSONeditor from '../../../helpers/adjustToJSONeditor' const propTypes = { message: object.isRequired, show: bool.isRequired } const defaultProps = { message: {}, show: false } class JSONmodal extends PureComponent { constructor (props) { super(props) this.state = { show: false } } componentWillReceiveProps (nextProps) { console.warn('compoennt did mount', nextProps) this.setState({ show: nextProps.show }) } componentWillUnmount () { console.error('componentWillUnmount()') } handleClose = () => this.setState({ show: false }) handleCopyToClipBoard = () => { const textarea = R.compose( setValue(this.props.message), createElement )('textarea') executeCopy(textarea) } render () { return ( <Modal show={this.state.show} message={ <JSONeditor value={adjustToJSONeditor(this.props.message)} readOnly /> } closeModal={this.handleClose} title={'Preview'} buttons={[ <Button key='cancel' mod='default' onClick={this.handleClose} > Close </Button>, <Button key='ok' mod='primary' onClick={() => { this.handleCopyToClipBoard() this.handleClose() }} > Copy to clipboard </Button>, <Button key='ok' mod='github' onClick={this.handleClose} > Download </Button> ]} /> ) } } JSONmodal.propTypes = propTypes JSONmodal.defaultProps = defaultProps export default JSONmodal function executeCopy (textarea) { document.body.appendChild(textarea) textarea.select() document.execCommand('Copy') document.body.removeChild(textarea) } function setValue (value) { return (element) => { element.value = JSON.stringify(value) return element } } function createElement (name) { return document.createElement(name) }
JavaScript
0.000006
@@ -1554,34 +1554,36 @@ key=' -ok +copy '%0A mo @@ -1816,10 +1816,16 @@ ey=' -ok +download '%0A
90fced2df23641c7077850de910b72273aea8931
Fix bug with sameness checked
src/box.js
src/box.js
(function(){ "use strict"; xtag.register('sam-box', { lifecycle: { created: function() {}, inserted: function() {}, removed: function() {}, attributeChanged: function() {} }, events: { }, accessors: { //TODO: DRY height: { get: function () { return this.xtag.height; }, set: function (newValue) { if(newValue === this.xtag.height || typeof(+newValue)!== "number") return; this.xtag.height = +newValue; this.style.height = this.xtag.base * +newValue + "px"; xtag.fireEvent(this, "resize"); } }, width: { get: function () { return this.xtag.width; }, set: function (newValue) { if (newValue === this.xtag.width || typeof(+newValue)!== "number") return; this.xtag.width = +newValue; this.style.width = this.xtag.base * +newValue + "px"; xtag.fireEvent(this, "resize"); } }, base: { get: function () { return this.xtag.base; }, set: function (newValue) { var s = this.style, x = this.xtag; if (typeof(+newValue) !== "number") return; x.base = +newValue; s.height = x.height * x.base + "px"; s.width = x.width * x.base + "px"; xtag.fireEvent(this, "resize"); } } }, methods: { } }); })();
JavaScript
0
@@ -409,16 +409,17 @@ if( ++ newValue @@ -792,16 +792,17 @@ if ( ++ newValue
bd4b7a890df641f53c73f1b6412b7fcbbe444584
Fix DragZoom interaction duration, allow `0` value
src/ol/interaction/dragzoominteraction.js
src/ol/interaction/dragzoominteraction.js
goog.provide('ol.interaction.DragZoom'); goog.require('goog.asserts'); goog.require('ol.animation'); goog.require('ol.easing'); goog.require('ol.events.condition'); goog.require('ol.extent'); goog.require('ol.interaction.DragBox'); goog.require('ol.style.Stroke'); goog.require('ol.style.Style'); /** * @classdesc * Allows the user to zoom the map by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits * it to when a key, shift by default, is held down. * * @constructor * @extends {ol.interaction.DragBox} * @param {olx.interaction.DragZoomOptions=} opt_options Options. * @api stable */ ol.interaction.DragZoom = function(opt_options) { var options = opt_options ? opt_options : {}; var condition = options.condition ? options.condition : ol.events.condition.shiftKeyOnly; /** * @private * @type {number} */ this.duration_ = options.duration ? options.duration : 200; /** * @private * @type {ol.style.Style} */ var style = options.style ? options.style : new ol.style.Style({ stroke: new ol.style.Stroke({ color: [0, 0, 255, 1] }) }); goog.base(this, { condition: condition, style: style }); }; goog.inherits(ol.interaction.DragZoom, ol.interaction.DragBox); /** * @inheritDoc */ ol.interaction.DragZoom.prototype.onBoxEnd = function() { var map = this.getMap(); var view = map.getView(); goog.asserts.assert(view, 'map must have view'); var size = map.getSize(); goog.asserts.assert(size !== undefined, 'size should be defined'); var extent = this.getGeometry().getExtent(); var resolution = view.constrainResolution( view.getResolutionForExtent(extent, size)); var currentResolution = view.getResolution(); goog.asserts.assert(currentResolution !== undefined, 'res should be defined'); var currentCenter = view.getCenter(); goog.asserts.assert(currentCenter !== undefined, 'center should be defined'); map.beforeRender(ol.animation.zoom({ resolution: currentResolution, duration: this.duration_, easing: ol.easing.easeOut })); map.beforeRender(ol.animation.pan({ source: currentCenter, duration: this.duration_, easing: ol.easing.easeOut })); view.setCenter(ol.extent.getCenter(extent)); view.setResolution(resolution); };
JavaScript
0
@@ -927,16 +927,30 @@ uration +!== undefined ? option
e8baf596cabd3c16d0266b786b7de55417c536b3
Copy changes to settings
src/options/settings/components/Ribbon.js
src/options/settings/components/Ribbon.js
import React from 'react' import { Checkbox } from 'src/common-ui/components' import * as utils from '../../../sidebar-overlay/utils' import styles from './settings.css' class Ribbon extends React.Component { state = { ribbon: true, } async componentDidMount() { const ribbon = await utils.getSidebarState() this.setState({ ribbon, }) } toggleRibbon = async () => { const ribbon = !this.state.ribbon await utils.setSidebarState(ribbon) this.setState({ ribbon }) } render() { return ( <div className={styles.container}> <h1 className={styles.header}>Sidebar Ribbon</h1> <p className={styles.subHeader}>Umm.. insert some text here?</p> <Checkbox id="show-memex-ribbon" isChecked={this.state.ribbon} handleChange={this.toggleRibbon} > Show ribbon on every page </Checkbox> </div> ) } } export default Ribbon
JavaScript
0
@@ -752,36 +752,232 @@ er%7D%3E -Umm.. insert some text here? +%0A Memex injects a small ribbon on the right side of every%0A page. %3Cbr /%3E If disabled, you can still reach it via the%0A little 'brain' icon in the popup.%0A %3C/p%3E
99e3a49543617cd711ff9588ae9e25391e81216f
fix format issue
src/cli.js
src/cli.js
#!/usr/bin/env node /** * Created by idok on 11/10/14. */ 'use strict'; //var fs = require('fs'); var _ = require('lodash'); var path = require('path'); var api = require('./api'); var context = require('./context'); var shell = require('./shell'); var pkg = require('../package.json'); //var defaultOptions = {commonJS: false, force: false, json: false}; var options = require('./options'); function executeOptions(currentOptions) { var ret = 0; var files = currentOptions._; if (currentOptions.version) { console.log('v' + pkg.version); } else if (currentOptions.help) { if (files.length) { console.log(options.generateHelpForOption(files[0])); } else { console.log(options.generateHelp()); } } else if (!files.length) { console.log(options.generateHelp()); } else { context.options.format = currentOptions.format; _.forEach(files, handleSingleFile.bind(this, currentOptions)); ret = shell.printResults(context); } return ret; } /** * @param {*} currentOptions * @param {string} filename file name to process */ function handleSingleFile(currentOptions, filename) { if (path.extname(filename) !== '.rt') { context.error('invalid file, only handle rt files', filename); return;// only handle html files } // var html = fs.readFileSync(filename).toString(); // if (!html.match(/\<\!doctype jsx/)) { // console.log('invalid file, missing header'); // return; // } // var js = reactTemplates.convertTemplateToReact(html); // fs.writeFileSync(filename + '.js', js); try { api.convertFile(filename, filename + '.js', currentOptions, context); } catch (e) { context.error(e.message, filename, e.line || -1, -1, e.index || -1); // if (defaultOptions.json) { // context.error(e.message, filename, e.line || -1, -1, e.index || -1); // console.log(JSON.stringify(context.getMessages(), undefined, 2)); // } else { // console.log('Error processing file: ' + filename + ', ' + e.message + ' line: ' + e.line || -1); // } // if (defaultOptions.stack) // console.log(e.stack); } } /** * Executes the CLI based on an array of arguments that is passed in. * @param {string|Array|Object} args The arguments to process. * @returns {int} The exit code for the operation. */ function execute(args) { var currentOptions; try { currentOptions = options.parse(args); } catch (error) { console.error(error.message); return 1; } console.log(currentOptions); return executeOptions(currentOptions); } module.exports = {execute: execute, executeOptions: executeOptions};
JavaScript
0.000001
@@ -481,16 +481,82 @@ ions._;%0A + context.options.format = currentOptions.format %7C%7C 'stylish';%0A%0A if ( @@ -924,64 +924,8 @@ e %7B%0A - context.options.format = currentOptions.format;%0A
f9d54b701641f82807d38d29acb01e972da291ad
fix typo
generators/_node/index.js
generators/_node/index.js
'use strict'; const _ = require('lodash'); const askName = require('inquirer-npm-name'); const parseAuthor = require('parse-author'); const Base = require('yeoman-generator').Base; const patchPackageJSON = require('../../utils').patchPackageJSON; const originUrl = require('git-remote-origin-url'); // based on https://github.com/yeoman/generator-node/blob/master/generators/app/index.js class PackageJSONGenerator extends Base { constructor(args, options) { super(args, options); // readme content this.option('readme'); this.option('longDescription'); } initializing() { const pkg = this.fs.readJSON(this.destinationPath('package.json'), {}); this.props = { description: pkg.description, homepage: pkg.homepage }; var authorName = 'Caleydo Team'; if (_.isObject(pkg.author)) { authorName = pkg.author.name; this.props.authorEmail = pkg.author.email; this.props.authorUrl = pkg.author.url; } else if (_.isString(pkg.author)) { let info = parseAuthor(pkg.author); authorName = info.name; this.props.authorEmail = info.email; this.props.authorUrl = info.url; } this.config.defaults({ name: pkg.name || this.determineAppname(), author: authorName, today: (new Date()).toUTCString(), githubAccount: this.github ? this.github.username() : 'phovea' }); return originUrl(this.destinationPath()).then((url) => { this.originUrl = url; }, () => { this.originUrl = ''; }); } _promptForName() { return askName({ name: 'name', message: 'Plugin Name', default: this.config.get('name'), filter: _.snakeCase }, this).then((props) => { this.config.set('name', props.name); }); } _promptDescription() { return this.prompt([{ name: 'description', message: 'Description', default: this.props.description }, { name: 'homepage', message: 'Project homepage url', default: 'https://phovea.caleydo.org' }, { name: 'authorName', message: 'Author\'s Name', default: this.user.git.name(), store: true }, { name: 'authorEmail', message: 'Author\'s Email', default: this.user.git.email(), store: true }, { name: 'authorUrl', message: 'Author\'s Homepage', store: true }, { name: 'githubAccount', message: 'GitHub username or organization', default: this.config.get('githubAccount'), store: true }]).then((props) => { this.props.description = props.description; this.props.homepage = props.homepage; this.config.set('author', props.authorName); this.props.authorEmail = props.authorEmail; this.props.authorUrl = props.authorUrl; this.config.set('githubAccount', props.githubAccount); }); } prompting() { return this._promptForName().then(() => this._promptDescription()); } writing() { const config = _.extend({}, this.props, this.config.getAll()); if (this.originUrl) { config.repository = this.originUrl; } else { config.repository = `https://github.com/${config.githubAccount}/${config.name}.git`; } patchPackageJSON.call(this, config); config.content = this.options.readme || ''; config.longDescription = tihs.options.longDescription || this.props.description || ''; this.fs.copyTpl(this.templatePath('README.tmpl.md'), this.destinationPath('README.md'), config); const includeDot = { globOptions: { dot: true } }; this.fs.copy(this.templatePath('plain/**/*'), this.destinationPath(), includeDot); } end() { this.spawnCommandSync('git', ['init'], { cwd: this.destinationPath() }); } } module.exports = PackageJSONGenerator;
JavaScript
0.999991
@@ -3348,10 +3348,10 @@ = t -i h +i s.op
9521935f46b96b3c6477250d7ef4ef76070734aa
Add a basic initial git setup on the new project
generators/setup/index.js
generators/setup/index.js
'use strict'; var yeoman = require('yeoman-generator'); var prompts = require('./prompts'); var _ = require('lodash'); module.exports = yeoman.Base.extend({ initializing: function() { this.appName = this.fs.readJSON(this.destinationPath('package.json')).name; }, prompting: prompts, writing: function () { if (this.envFile) { this.fs.write(this.destinationPath('.env'), this.envFile); } else { this.fs.copyTpl( this.templatePath('.env'), this.destinationPath('.env'), { appName: _.snakeCase(this.appName) } ); } }, install: function () { this.npmInstall(); this.spawnCommand('gem', [ 'install', 'bundler', '--conservative' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'bundle'), 'install' ]) .on('exit', (code) => { if (!code) { this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'db:setup' ]); this.spawnCommand('ruby', [ this.destinationPath('bin', 'rails'), 'log:clear', 'tmp:clear' ]); } }); } }); } });
JavaScript
0
@@ -601,24 +601,271 @@ nction () %7B%0A + this.spawnCommand('git', %5B 'init' %5D)%0A .on('exit', () =%3E %7B%0A this.spawnCommand('git', %5B 'add', '.' %5D)%0A .on('exit', () =%3E %7B%0A this.spawnCommand('git', %5B 'commit', '-m', 'Initial commit' %5D);%0A %7D);%0A %7D);%0A%0A this.npm
09d12820c70194641bcf52f35fbc0d65ef74875e
clear input field which causes re-choose bug
src/Uploader/Uploader.js
src/Uploader/Uploader.js
/** * @file Upload * @author nemo <[email protected]> */ import san from 'san'; const _method = { repeatSet: function(obj, fn) { for (let i in obj) { fn(i, obj[i]) } }, initXHR: function(file) { let self = this let xhr = new XMLHttpRequest() let formData = new FormData() let fileIndex = self.fileList.push(file) - 1 self.data.set('fileList', self.fileList) let opt = self.data.get('opt') opt.data[opt.name] = file opt['on-change'](file, self.fileList) _method.repeatSet(opt.data, formData.append.bind(formData)) xhr.upload.onprogress = function(e) { let percentage = 0; if ( e.lengthComputable ) { percentage = e.loaded / e.total } opt['on-progress'](e, file, self.fileList) file.progressCss = {width: 100 * percentage + '%'} self.data.set('fileList', self.fileList) }; xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (/20/.test(xhr.status)) { self.fileList[fileIndex]['response'] = JSON.parse(xhr.response) opt['on-success'](JSON.parse(xhr.response), file, self.fileList) file.progressCss = {width: '100%'} self.data.set('fileList', self.fileList) } else { opt['on-error']('error', file, self.fileList) } opt['on-change'](file, self.fileList) } } xhr.withCredentials = opt['with-credentials'] self.xhrList.push({ fn: function() { if (opt['before-upload'](file)) { xhr.open('POST', opt.action) _method.repeatSet(Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, opt.headers), xhr.setRequestHeader.bind(xhr)) xhr.send(formData) } }, xhr: xhr }) } } let initOpts = { action: '', headers: {}, multiple: false, data: {}, name: 'file', 'with-credentials': false, 'show-file-list': true, drag: false, accept: '', 'on-preview': function() {}, 'on-remove': function() {}, 'on-success': function() {}, 'on-error': function() {}, 'on-progress': function() {}, 'on-change': function() {}, 'before-upload': function() { return true }, 'auto-upload': true, disabled: false } export default san.defineComponent({ template: ` <div> <div san-if="!drag" class="upload sm-button variant-info variant-raised"> <span san-if="autoUpload">上传</span> <span san-if="!autoUpload">选取文件</span> <input san-if="!multiple && !disabled" type="file" on-change="reciveFile($event)" accept="{{accept}}"/> <input san-if="multiple && !disabled" type="file" on-change="reciveFile($event)" accept="{{accept}}" multiple/> </div> <div san-if="!autoUpload && !drag" class="upload sm-button variant-info variant-raised" on-click="excuteUpload()">开始上传</div> <div san-if="drag" class="upload-drag" on-drop="dropFile($event)" on-dragenter="dragEnter($event)" on-dragover="dragOver($event)"></div> <div san-if="showFileList"> <span class="file-list" san-for="file, index in fileList" on-click="fileListClick(index)"> {{ file.name }} <span class="close" on-click="removeFile(index)">+</span> <span class="progress" style="{{ file.progressCss }}"></span> </span> </div> </div> `, components: { }, initData() { return { fileList: [] } }, computed: { multiple() { return this.data.get('opt')['multiple'] }, showFileList() { return this.data.get('opt')['show-file-list'] }, autoUpload() { return this.data.get('opt')['auto-upload'] }, accept() { return this.data.get('opt')['accept'] }, drag() { return this.data.get('opt')['drag'] }, disabled() { return this.data.get('opt')['disabled'] }, fileList() { return this.fileList } }, inited() { this.fileList = [] this.xhrList = [] this.data.set('opt', Object.assign({}, initOpts, this.data.get('opt'))) }, fileListClick(index) { this.data.get('opt')['on-preview'](this.fileList[index]) }, excuteUpload() { this.xhrList.forEach(one => one.fn()) }, removeFile(index) { this.xhrList[index].xhr.abort() let file = this.fileList.splice(index, 1) this.data.get('opt')['on-remove'](file, this.fileList) this.data.set('fileList', this.fileList) }, dragEnter(event) { event.preventDefault(); event.stopPropagation(); }, dragOver(event) { event.preventDefault(); event.stopPropagation(); }, dropFile(event) { event.preventDefault(); event.stopPropagation(); !this.data.get('opt').disabled && Array.prototype.slice.call(event.dataTransfer.files).forEach(file => { _method.initXHR.call(this, file) }) this.xhrList.forEach(one => one.fn()) }, reciveFile(event) { Array.prototype.slice.call(event.target.files).forEach(file => { _method.initXHR.call(this, file) }) console.log(this.data.get('opt')) this.data.get('opt')['auto-upload'] && this.xhrList.forEach(one => one.fn()) } });
JavaScript
0
@@ -1271,16 +1271,41 @@ )%0A%09%09%09%09%7D%0A +%09%09%09%09file.uploaded = true%0A %09%09%09%09opt%5B @@ -1481,16 +1481,34 @@ '%5D(file) + && !file.uploaded ) %7B%0A%09%09%09%09 @@ -5057,41 +5057,31 @@ %09 -console.log(this.data.get('opt')) +event.target.value = '' %0A
63348c8973a58b86516ffce1b65fdcb676a49a56
clean up some code from #97
plugins/kalabox_app/index.js
plugins/kalabox_app/index.js
'use strict'; var exec = require('child_process').exec; var fs = require('fs'); var path = require('path'); var _ = require('lodash'); var rimraf = require('rimraf'); var plugin = require('../../lib/plugin.js'); module.exports = function(manager, app, docker) { manager.registerTask('init', function(done) { manager.init(app, done); }); manager.registerTask('start', function(done) { manager.start(app, done); }); manager.registerTask('stop', function(done) { manager.stop(app, done); }); manager.registerTask('restart', function(done) { manager.stop(app, function(err) { if (err) { done(err); } else { manager.start(app, done); } }); }); manager.registerTask('kill', function(done) { manager.kill(app, done); }); manager.registerTask('remove', function(done) { manager.remove(app, done); }); manager.registerTask('pull', function(done) { manager.pull(app, done); }); manager.registerTask('build', function(done) { manager.build(app, done); }); app.on('post-init', function() { var a = _.cloneDeep(app); delete a.components; fs.writeFileSync(path.resolve(app.dataPath, 'app.json'), JSON.stringify(a)); }); app.on('post-remove', function() { rimraf(app.dataPath, function (er) { if (er) throw er }); }); };
JavaScript
0.000102
@@ -1299,17 +1299,16 @@ function - (er) %7B%0A @@ -1324,16 +1324,17 @@ er) +%7B throw er %0A @@ -1329,16 +1329,19 @@ throw er +; %7D %0A %7D);
f89cd7a0f071f22798a1683645b9e409f2dedabb
Add verbose mode
plugins/no-undefined-vars.js
plugins/no-undefined-vars.js
const fs = require('fs') const stylelint = require('stylelint') const matchAll = require('string.prototype.matchall') const globby = require('globby') const ruleName = 'primer/no-undefined-vars' const messages = stylelint.utils.ruleMessages(ruleName, { rejected: varName => `${varName} is not defined` }) // Match CSS variable definitions (e.g. --color-text-primary:) const variableDefinitionRegex = /(--[\w|-]*):/g // Match CSS variable references (e.g var(--color-text-primary)) // eslint-disable-next-line no-useless-escape const variableReferenceRegex = /var\(([^\)]*)\)/g module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}) => { if (!enabled) { return noop } const {files = ['**/*.scss', '!node_modules']} = options const definedVariables = getDefinedVariables(files) return (root, result) => { root.walkRules(rule => { rule.walkDecls(decl => { for (const [, variableName] of matchAll(decl.value, variableReferenceRegex)) { if (!definedVariables.has(variableName)) { stylelint.utils.report({ message: messages.rejected(variableName), node: decl, result, ruleName }) } } }) }) } }) function getDefinedVariables(files) { const definedVariables = new Set() for (const file of globby.sync(files)) { const css = fs.readFileSync(file, 'utf-8') for (const [, variableName] of matchAll(css, variableDefinitionRegex)) { definedVariables.add(variableName) } } return definedVariables } function noop() {} module.exports.ruleName = ruleName module.exports.messages = messages
JavaScript
0.000138
@@ -745,20 +745,143 @@ es'%5D -%7D = options%0A +, verbose = false%7D = options%0A // eslint-disable-next-line no-console%0A const log = verbose ? (...args) =%3E console.warn(...args) : noop %0A c @@ -929,16 +929,21 @@ es(files +, log )%0A%0A ret @@ -1425,16 +1425,21 @@ es(files +, log ) %7B%0A co @@ -1635,24 +1635,72 @@ onRegex)) %7B%0A + log(%60$%7BvariableName%7D defined in $%7Bfile%7D%60)%0A define
de79a0ae52b86a81d0e45d123da6478ba75e34e3
Linux is not an OS
packages/components/containers/sessions/SessionsSection.js
packages/components/containers/sessions/SessionsSection.js
import React, { useState, useEffect } from 'react'; import { c } from 'ttag'; import { Button, Table, TableHeader, TableBody, TableRow, Time, Pagination, Alert, Block, SubTitle, ConfirmModal, useApi, useAuthentication, useModals, useLoading, usePagination, useNotifications } from 'react-components'; import { querySessions, revokeOtherSessions, revokeSession } from 'proton-shared/lib/api/auth'; import { ELEMENTS_PER_PAGE } from 'proton-shared/lib/constants'; import SessionAction from './SessionAction'; const getClientsI18N = () => ({ Web: c('Badge').t`ProtonMail for web`, VPN: c('Badge').t`ProtonVPN for Windows`, WebVPN: c('Badge').t`ProtonVPN for web`, Admin: c('Badge').t`Admin`, ImportExport: c('Badge').t`ProtonMail import-export`, Bridge: c('Badge').t`ProtonMail Bridge`, iOS: c('Badge').t`ProtonMail for iOS`, Android: c('Badge').t`ProtonMail for Android`, WebMail: c('Badge').t`ProtonMail for web`, WebMailSettings: c('Badge').t`ProtonMail settings for web`, WebContacts: c('Badge').t`ProtonContacts for web`, WebVPNSettings: c('Badge').t`ProtonVPN settings for web`, WebCalendar: c('Badge').t`ProtonCalendar for web`, WebDrive: c('Badge').t`ProtonDrive for web`, // WebWallet: c('Badge').t`ProtonWallet for web`, WebAdmin: c('Badge').t`Admin`, iOSMail: c('Badge').t`ProtonMail for iOS`, iOSVPN: c('Badge').t`ProtonVPN for iOS`, iOSCalendar: c('Badge').t`ProtonCalendar for iOS`, AndroidMail: c('Badge').t`ProtonMail for Android`, AndroidVPN: c('Badge').t`ProtonVPN for Android`, AndroidCalendar: c('Badge').t`ProtonCalendar for Android`, WindowsVPN: c('Badge').t`ProtonVPN for Windows`, WindowsImportExport: c('Badge').t`ProtonMail import-export for Windows`, WindowsBridge: c('Badge').t`ProtonMail Bridge for Windows`, macOSVPN: c('Badge').t`ProtonVPN for macOS`, macOSImportExport: c('Badge').t`ProtonMail import-export for macOS`, macOSBridge: c('Badge').t`ProtonMail Bridge for macOS`, LinuxImportExport: c('Badge').t`ProtonMail import-export for Linux`, LinuxBridge: c('Badge').t`ProtonMail Bridge for Linux` }); const SessionsSection = () => { const { createNotification } = useNotifications(); const api = useApi(); const authentication = useAuthentication(); const [loading, withLoading] = useLoading(); const [table, setTable] = useState({ sessions: [], total: 0 }); const { page, list, onNext, onPrevious, onSelect } = usePagination(table.sessions); const { createModal } = useModals(); const fetchSessions = async () => { const { Sessions } = await api(querySessions()); setTable({ sessions: Sessions.reverse(), total: Sessions.length }); // Most recent, first }; const handleRevoke = async (UID) => { await api(UID ? revokeSession(UID) : revokeOtherSessions()); await fetchSessions(); createNotification({ text: UID ? c('Success').t`Session revoked` : c('Success').t`Sessions revoked` }); }; const handleOpenModal = () => { createModal( <ConfirmModal onConfirm={() => withLoading(handleRevoke())}> <Alert>{c('Info').t`Do you want to revoke all other sessions than the current one?`}</Alert> </ConfirmModal> ); }; useEffect(() => { withLoading(fetchSessions()); }, []); const i18n = getClientsI18N(); const currentUID = authentication.getUID(); return ( <> <SubTitle>{c('Title').t`Sessions`}</SubTitle> <Alert learnMore="https://protonmail.com/support/knowledge-base/log-out-all-other-sessions/">{c('Info') .t`Unless you explicitly logout or change your password, sessions can last for up to 6 months. Sessions expire after 2 weeks of inactivity.`}</Alert> <Block className="flex flex-spacebetween"> <div> <Button onClick={handleOpenModal}>{c('Action').t`Revoke all other sessions`}</Button> </div> <Pagination page={page} total={table.total} limit={ELEMENTS_PER_PAGE} onNext={onNext} onPrevious={onPrevious} onSelect={onSelect} /> </Block> <Table> <TableHeader cells={[c('Title').t`App`, c('Title').t`Date`, c('Title').t`Action`]} /> <TableBody loading={loading} colSpan={3}> {list.map((session) => { const key = session.UID; return ( <TableRow key={key} cells={[ i18n[session.ClientID], <Time format="PPp" key={1}> {session.CreateTime} </Time>, <SessionAction key={2} session={session} currentUID={currentUID} onRevoke={() => withLoading(handleRevoke(session.UID))} /> ]} /> ); })} </TableBody> </Table> </> ); }; export default SessionsSection;
JavaScript
0.99977
@@ -2141,24 +2141,28 @@ -export for +GNU/ Linux%60,%0A @@ -2209,16 +2209,20 @@ dge for +GNU/ Linux%60%0A%7D
8261826ba67567d221849e9adfeac45bc0f7671a
fix merge bug
packages/entity-browser/src/routes/entity-browser/index.js
packages/entity-browser/src/routes/entity-browser/index.js
import React from 'react' import {storeFactory} from 'tocco-util' import asyncRoute from '../../util/asyncRoute' export default store => props => { const Component = asyncRoute(() => new Promise(resolve => { require.ensure([], require => { const EntityBrowserContainer = require('./containers/EntityBrowserContainer').default const reducer = require('./modules').default const toastrReducer = require('react-redux-toastr').reducer const sagas = require('./modules/sagas').default storeFactory.injectReducers(store, { entityBrowser: reducer, toastr: toastrReducer }) storeFactory.injectSaga(store, sagas) resolve(EntityBrowser) }) }) ) return <EntityBrowserContainer {...props}/> }
JavaScript
0.000024
@@ -720,16 +720,25 @@ yBrowser +Container )%0A @@ -761,38 +761,25 @@ return %3C -EntityBrowserContainer +Component %7B...pro
2f977bf2a48226d0c7230bd7c82e2994d7663e0d
Remove unused variables and fix some formatting
src/env.js
src/env.js
var eventHandling = require('./eventhandling'); var mode = typeof(window) !== 'undefined' ? 'browser' : 'node', env = {}, isBackground = false; var Env = function () { return env; }; Env.isBrowser = function () { return mode === "browser"; }; Env.isNode = function () { return mode === "node"; }; Env.goBackground = function () { isBackground = true; Env._emit("background"); }; Env.goForeground = function () { isBackground = false; Env._emit("foreground"); }; Env._rs_init = function (remoteStorage) { eventHandling(Env, "background", "foreground"); function visibility() { if (document[env.hiddenProperty]) { Env.goBackground(); } else { Env.goForeground(); } } if ( mode === 'browser') { if ( typeof(document.hidden) !== "undefined" ) { env.hiddenProperty = "hidden"; env.visibilityChangeEvent = "visibilitychange"; } else if ( typeof(document.mozHidden) !== "undefined" ) { env.hiddenProperty = "mozHidden"; env.visibilityChangeEvent = "mozvisibilitychange"; } else if ( typeof(document.msHidden) !== "undefined" ) { env.hiddenProperty = "msHidden"; env.visibilityChangeEvent = "msvisibilitychange"; } else if ( typeof(document.webkitHidden) !== "undefined" ) { env.hiddenProperty = "webkitHidden"; env.visibilityChangeEvent = "webkitvisibilitychange"; } document.addEventListener(env.visibilityChangeEvent, visibility, false); visibility(); } }; Env._rs_cleanup = function (remoteStorage) { }; module.exports = Env;
JavaScript
0.000003
@@ -1,11 +1,13 @@ -var +const eventHa @@ -44,19 +44,21 @@ ing');%0A%0A -var +const mode = @@ -126,41 +126,16 @@ = %7B%7D -,%0A isBackground = false;%0A%0A%0Avar +;%0A%0Aconst Env @@ -326,31 +326,8 @@ ) %7B%0A - isBackground = true;%0A En @@ -390,32 +390,8 @@ ) %7B%0A - isBackground = false;%0A En @@ -434,32 +434,35 @@ nit = function ( +/* remoteStorage) %7B @@ -454,24 +454,27 @@ emoteStorage + */ ) %7B%0A eventH @@ -537,16 +537,17 @@ sibility + () %7B%0A @@ -665,17 +665,16 @@ %0A%0A if ( - mode === @@ -691,25 +691,24 @@ ) %7B%0A if ( - typeof(docum @@ -726,33 +726,32 @@ !== %22undefined%22 - ) %7B%0A env.hi @@ -836,33 +836,32 @@ %0A %7D else if ( - typeof(document. @@ -878,33 +878,32 @@ !== %22undefined%22 - ) %7B%0A env.hi @@ -994,33 +994,32 @@ %0A %7D else if ( - typeof(document. @@ -1035,33 +1035,32 @@ !== %22undefined%22 - ) %7B%0A env.hi @@ -1157,17 +1157,16 @@ lse if ( - typeof(d @@ -1202,17 +1202,16 @@ defined%22 - ) %7B%0A @@ -1446,16 +1446,19 @@ nction ( +/* remoteSt @@ -1462,16 +1462,19 @@ eStorage + */ ) %7B%0A%7D;%0A%0A
f87bab67b3e855bf5b787e35a9975dd0997e7764
Add some sidebar link tests
installer/frontend/ui-tests/utils/wizard.js
installer/frontend/ui-tests/utils/wizard.js
const nextStep = '.wiz-form__actions__next button.btn-primary'; const prevStep = 'button.wiz-form__actions__prev'; const testPage = (page, platform, json, nextInitiallyDisabled = true) => { page.expect.element(prevStep).to.be.visible; page.expect.element(prevStep).to.have.attribute('class').which.not.contains('disabled'); page.expect.element(nextStep).to.be.visible; if (nextInitiallyDisabled) { page.expect.element(nextStep).to.have.attribute('class').which.contains('disabled'); } // Sidebar link for the current page should be highlighted and enabled page.expect.element('.wiz-wizard__nav__step--active button').to.not.have.attribute('disabled'); // The next sidebar links should be disabled if the next button is disabled const nextNavLink = page.expect.element('.wiz-wizard__nav__step--active + .wiz-wizard__nav__step button'); if (nextInitiallyDisabled) { nextNavLink.to.have.attribute('disabled'); } else { nextNavLink.to.not.have.attribute('disabled'); } // Save progress link exists page.expect.element('.wiz-form__header a').text.which.contains('Save progress'); if (page.test) { page.test(json, platform); } page.expect.element(nextStep).to.have.attribute('class').which.not.contains('disabled'); return page.click(nextStep); }; module.exports = { nextStep, prevStep, testPage, };
JavaScript
0
@@ -936,34 +936,462 @@ ');%0A - %7D else %7B%0A nextNavLink +%0A // If the next button is disabled, all sidebar links for later screens should be disabled%0A page.expect.element('.wiz-wizard__nav__step--active ~ .wiz-wizard__nav__step button:not(%5Bdisabled%5D)').to.not.be.present;%0A %7D else %7B%0A nextNavLink.to.not.have.attribute('disabled');%0A%0A // If the next button is enabled, the next sidebar link should be enabled too%0A page.expect.element('.wiz-wizard__nav__step--active + .wiz-wizard__nav__step button') .to.
551e92c4769797fda67bdfc2ee85abcad0e2962a
Update angulartics-piwik.js
src/angulartics-piwik.js
src/angulartics-piwik.js
/** * @license Angulartics * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics * Piwik 2.1.x update contributed by http://github.com/highskillz * License: MIT */ /* global _paq */ (function(angular) { 'use strict'; /** * @ngdoc overview * @name angulartics.piwik * Enables analytics support for Piwik (http://piwik.org/docs/tracking-api/) */ angular.module('angulartics.piwik', ['angulartics']) .config(['$analyticsProvider', '$windowProvider', function($analyticsProvider, $windowProvider) { var $window = $windowProvider.$get(); $analyticsProvider.settings.pageTracking.trackRelativePath = true; // Add piwik specific trackers to angulartics API // Requires the CustomDimensions plugin for Piwik. $analyticsProvider.api.setCustomDimension = function(dimensionId, value) { if ($window._paq) { $window._paq.push(['setCustomDimension', dimensionId, value]); } }; // Requires the CustomDimensions plugin for Piwik. $analyticsProvider.api.deleteCustomDimension = function(dimensionId) { if ($window._paq) { $window._paq.push(['deleteCustomDimension', dimensionId]); } }; // scope: visit or page. Defaults to 'page' $analyticsProvider.api.setCustomVariable = function(varIndex, varName, value, scope) { if ($window._paq) { scope = scope || 'page'; $window._paq.push(['setCustomVariable', varIndex, varName, value, scope]); } }; // scope: visit or page. Defaults to 'page' $analyticsProvider.api.deleteCustomVariable = function(varIndex, scope) { if ($window._paq) { scope = scope || 'page'; $window._paq.push(['deleteCustomVariable', varIndex, scope]); } }; // trackSiteSearch(keyword, category, [searchCount]) $analyticsProvider.api.trackSiteSearch = function(keyword, category, searchCount) { // keyword is required if ($window._paq && keyword) { var params = ['trackSiteSearch', keyword, category || false]; // searchCount is optional if (angular.isDefined(searchCount)) { params.push(searchCount); } $window._paq.push(params); } }; // logs a conversion for goal 1. revenue is optional // trackGoal(goalID, [revenue]); $analyticsProvider.api.trackGoal = function(goalID, revenue) { if ($window._paq) { _paq.push(['trackGoal', goalID, revenue || 0]); } }; // track outlink or download // linkType is 'link' or 'download', 'link' by default // trackLink(url, [linkType]); $analyticsProvider.api.trackLink = function(url, linkType) { var type = linkType || 'link'; if ($window._paq) { $window._paq.push(['trackLink', url, type]); } }; // Set default angulartics page and event tracking // $analytics.setUsername(username) $analyticsProvider.registerSetUsername(function(username) { if ($window._paq) { $window._paq.push(['setUserId', username]); } }); // $analytics.setAlias(alias) // $analyticsProvider.registerSetAlias(function(param) { // // TODO: No piwik corresponding function found. Use setCustomVariable instead // }); // $analytics.setUserProperties(properties) // $analyticsProvider.registerSetUserProperties(function(param) { // // TODO: No piwik corresponding function found. Use setCustomVariable instead // }); // locationObj is the angular $location object $analyticsProvider.registerPageTrack(function(path, locationObj) { if ($window._paq) { $window._paq.push(['setDocumentTitle', $window.document.title]); $window._paq.push(['setCustomUrl', path]); $window._paq.push(['trackPageView']); } }); // trackEvent(category, event, [name], [value]) $analyticsProvider.registerEventTrack(function(action, properties) { if ($window._paq) { // PAQ requires that eventValue be an integer, see: http://piwik.org/docs/event-tracking/ if (properties.value) { var parsed = parseInt(properties.value, 10); properties.value = isNaN(parsed) ? 0 : parsed; } $window._paq.push(['trackEvent', properties.category, action, properties.label, properties.value]); } }); } ]); })(angular);
JavaScript
0
@@ -5608,16 +5608,879 @@ %7D);%0A + %0A /**%0A * Exception Track Event in GA%0A * @name exceptionTrack%0A * Sugar on top of the eventTrack method for easily handling errors%0A *%0A * @param %7Bobject%7D error An Error object to track: error.toString() used for event 'action', error.stack used for event 'label'.%0A * @param %7Bobject%7D cause The cause of the error given from $exceptionHandler, not used.%0A *%0A * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/events%0A */%0A $analyticsProvider.registerExceptionTrack(function (error, cause) %7B%0A if ($window._paq) %7B%0A $window._paq.push(%5B'trackEvent', 'Exceptions', error.toString(), error.stack, 0%5D);%0A %7D%0A %7D);%0A
46f6de21abfa2a2ab3ff6eae58375179e951cf2e
drop '--windows-compatibility' option
internal/fontello/font_build/_lib/worker.js
internal/fontello/font_build/_lib/worker.js
// Working procedure for the font builder queue. // 'use strict'; const promisify = require('util').promisify; const _ = require('lodash'); const path = require('path'); const fs = require('fs'); const ttf2eot = require('ttf2eot'); const ttf2woff = require('ttf2woff'); const wawoff2 = require('wawoff2'); const svg2ttf = require('svg2ttf'); const pug = require('pug'); const b64 = require('base64-js'); const rimraf = promisify(require('rimraf')); const mkdirp = require('mkdirp'); const glob = promisify(require('glob')); const JSZip = require('jszip'); const read = promisify(fs.readFile); const write = promisify(fs.writeFile); const rename = promisify(fs.rename); const unlink = promisify(fs.unlink); const execFile = promisify(require('child_process').execFile); const TEMPLATES_DIR = path.join(__dirname, '../../../../support/font-templates'); const TEMPLATES = {}; const SVG_FONT_TEMPLATE = _.template(fs.readFileSync(path.join(TEMPLATES_DIR, 'font/svg.tpl'), 'utf8')); _.forEach({ 'demo.pug': 'demo.html', 'css/css.pug': 'css/${FONTNAME}.css', 'css/css-ie7.pug': 'css/${FONTNAME}-ie7.css', 'css/css-codes.pug': 'css/${FONTNAME}-codes.css', 'css/css-ie7-codes.pug': 'css/${FONTNAME}-ie7-codes.css', 'css/css-embedded.pug': 'css/${FONTNAME}-embedded.css', 'LICENSE.pug': 'LICENSE.txt', 'css/animation.css': 'css/animation.css', 'README.txt': 'README.txt' }, (outputName, inputName) => { let inputFile = path.join(TEMPLATES_DIR, inputName); let inputData = fs.readFileSync(inputFile, 'utf8'); let outputData; switch (path.extname(inputName)) { case '.pug': // Pug template. outputData = pug.compile(inputData, { pretty: true, filename: inputFile, filters: [ require('jstransformer-stylus') ] }); break; case '.tpl': // Lodash template. outputData = _.template(inputData); break; default: // Static file - just do a copy. outputData = () => inputData; break; } TEMPLATES[outputName] = outputData; }); module.exports = async function fontWorker(taskInfo) { let logPrefix = '[font::' + taskInfo.fontId + ']'; let timeStart = Date.now(); let fontname = taskInfo.builderConfig.font.fontname; let files; taskInfo.logger.info(`${logPrefix} Start generation: ${JSON.stringify(taskInfo.clientConfig)}`); // Collect file paths. // files = { config: path.join(taskInfo.tmpDir, 'config.json'), svg: path.join(taskInfo.tmpDir, 'font', `${fontname}.svg`), ttf: path.join(taskInfo.tmpDir, 'font', `${fontname}.ttf`), ttfUnhinted: path.join(taskInfo.tmpDir, 'font', `${fontname}-unhinted.ttf`), eot: path.join(taskInfo.tmpDir, 'font', `${fontname}.eot`), woff: path.join(taskInfo.tmpDir, 'font', `${fontname}.woff`), woff2: path.join(taskInfo.tmpDir, 'font', `${fontname}.woff2`) }; // Generate initial SVG font. // /*eslint-disable new-cap*/ let svgOutput = SVG_FONT_TEMPLATE(taskInfo.builderConfig); // Prepare temporary working directory. // await rimraf(taskInfo.tmpDir); await mkdirp(taskInfo.tmpDir); await mkdirp(path.join(taskInfo.tmpDir, 'font')); await mkdirp(path.join(taskInfo.tmpDir, 'css')); // Write clinet config and initial SVG font. // let configOutput = JSON.stringify(taskInfo.clientConfig, null, ' '); await write(files.config, configOutput, 'utf8'); await write(files.svg, svgOutput, 'utf8'); // Convert SVG to TTF // let ttf = svg2ttf(svgOutput, { copyright: taskInfo.builderConfig.font.copyright }); await write(files.ttf, ttf.buffer); // Autohint the resulting TTF. // let max_segments = _.maxBy(taskInfo.builderConfig.glyphs, glyph => glyph.segments).segments; // KLUDGE :) // Don't allow hinting if font has "strange" glyphs. // That's useless anyway, and can hang ttfautohint < 1.0 if (max_segments <= 500 && taskInfo.builderConfig.hinting) { await rename(files.ttf, files.ttfUnhinted); await execFile('ttfautohint', [ '--no-info', '--windows-compatibility', '--symbol', // temporary workaround for #464 // https://github.com/fontello/fontello/issues/464#issuecomment-202244651 '--fallback-script=latn', files.ttfUnhinted, files.ttf ], { cwd: taskInfo.cwdDir }); await unlink(files.ttfUnhinted); } // Read the resulting TTF to produce EOT and WOFF. // let ttfOutput = new Uint8Array(await read(files.ttf)); // Convert TTF to EOT. // let eotOutput = ttf2eot(ttfOutput).buffer; await write(files.eot, eotOutput); // Convert TTF to WOFF. // let woffOutput = ttf2woff(ttfOutput).buffer; await write(files.woff, woffOutput); // Convert TTF to WOFF2. // let woff2Output = await wawoff2.compress(ttfOutput); await write(files.woff2, woff2Output); // Write template files. (generate dynamic and copy static) // let templatesNames = Object.keys(TEMPLATES); for (let i = 0; i < templatesNames.length; i++) { let templateName = templatesNames[i]; let templateData = TEMPLATES[templateName]; // don't create license file when no copyright data exists if ((templateName === 'LICENSE.txt') && (!taskInfo.builderConfig.fonts_list.length)) { continue; } let outputName = templateName.replace('${FONTNAME}', fontname); let outputFile = path.join(taskInfo.tmpDir, outputName); let outputData = templateData(taskInfo.builderConfig); outputData = outputData .replace('%WOFF64%', b64.fromByteArray(woffOutput)) .replace('%TTF64%', b64.fromByteArray(ttfOutput)); await write(outputFile, outputData, 'utf8'); } // // Create zipball. // let archiveFiles = await glob(path.join(taskInfo.tmpDir, '**'), { nodir: true }); let zip = new JSZip(); for (var i = 0; i < archiveFiles.length; i++) { let fileData = await read(archiveFiles[i]); zip.folder(path.basename(taskInfo.tmpDir)).file(path.relative(taskInfo.tmpDir, archiveFiles[i]), fileData); } let zipData = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }); // TODO: force tmp dir cleanup on fail // Remove temporary files and directories. // await rimraf(taskInfo.tmpDir); // Done. // let timeEnd = Date.now(); taskInfo.logger.info(`${logPrefix} Generated in ${(timeEnd - timeStart) / 1000} ` + `(real: ${(timeEnd - taskInfo.timestamp) / 1000})`); return zipData; };
JavaScript
0.000001
@@ -4167,41 +4167,8 @@ o',%0A - '--windows-compatibility',%0A
d3ba5ec8b670995f4d1e0e4a5f357ac119d31f56
add a printf
models/mongoose.js
models/mongoose.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'); var bluebird = require('bluebird'); mongoose.Promise = bluebird; mongoose.connect(config.databaseUrl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); var UserModel = require('./UserModel.js'); var ChannelModel = require('./ChannelModel.js'); module.exports.UserModel = UserModel; module.exports.ChannelModel = ChannelModel;
JavaScript
0.001188
@@ -143,16 +143,60 @@ bird;%0A%0A%0A +console.log('******' + config.databaseUrl);%0A mongoose
2707b080cf245ca51beb7c2b4e35433ac605bc72
Remove example code
dev/FormWithArrays.js
dev/FormWithArrays.js
/* ------------- Imports -------------- */ import React, { Component } from 'react'; /* ------------- Form Library Imports -------------- */ import { Form, Text } from '../src/index'; /* ---------------- Other Imports ------------------ */ import Data from './Data'; import Code from './Code'; /* ------------------ Form Stuff --------------------*/ const FormWithArraysCode = () => { const code = ` import { Form, Text } from 'react-form'; class FormWithArrays extends Component { constructor( props ) { super( props ); this.state = {}; } render() { return ( <div> <Form onSubmit={submittedValues => this.setState( { submittedValues } )}> { formApi => ( <form onSubmit={formApi.submitForm} id="form3"> <label htmlFor="firstName2">First name</label> <Text field="firstName" id="firstName2" /> <label htmlFor="friend1">Friend1</label> <Text field={['friends', 0]} id="friend1" /> <label htmlFor="friend2">Friend2</label> <Text field={['friends', 1]} id="friend2" /> <label htmlFor="friend3">Friend3</label> <Text field={['friends', 2]} id="friend3" /> <button type="submit" className="mb-4 btn btn-primary">Submit</button> </form> )} </Form> </div> ); } } `; return ( <div> <h5>Source Code:</h5> <Code type="html"> {code} </Code> </div> ); }; class FormWithArrays extends Component { constructor( props ) { super( props ); this.state = {}; } render() { return ( <div> <h2 className="mb-4">Form With Array</h2> <p> Fields can also be assotiated with an array. Here is an example where you can input three friends. </p> <Form defaultValues={{ numberField: 0 }} onSubmit={submittedValues => this.setState( { submittedValues } )}> { formApi => ( <div> <form onSubmit={formApi.submitForm} id="form3"> <label htmlFor="firstName2">First name</label> <Text field="firstName" id="firstName2" /> <label htmlFor="friend1">Friend1</label> <Text field={['friends', 0]} id="friend1" /> <label htmlFor="friend2">Friend2</label> <Text field={['friends', 1]} id="friend2" /> <label htmlFor="friend3">Friend3</label> <Text field={['friends', 2]} id="friend3" /> <label htmlFor="numberField">Number field</label> <Text field="numberField" id="numberField" type="number" /> <button type="submit" className="mb-4 btn btn-primary">Submit</button> </form> <br /> <Data title="Values" reference="formApi.values" data={formApi.values} /> <Data title="Touched" reference="formApi.touched" data={formApi.touched} /> <Data title="Submission attempts" reference="formApi.submits" data={formApi.submits} /> <Data title="Submitted" reference="formApi.submitted" data={formApi.submitted} /> <Data title="Submitted values" reference="onSubmit={submittedValues => this.setState( { submittedValues } )}" data={this.state.submittedValues} /> </div> )} </Form> <br /> <FormWithArraysCode /> </div> ); } } export default FormWithArrays;
JavaScript
0.000018
@@ -1945,53 +1945,8 @@ orm%0A - defaultValues=%7B%7B numberField: 0 %7D%7D%0A @@ -2604,150 +2604,8 @@ /%3E%0A - %3Clabel htmlFor=%22numberField%22%3ENumber field%3C/label%3E%0A %3CText field=%22numberField%22 id=%22numberField%22 type=%22number%22 /%3E%0A
1df0657305bd9f06d4c4f594a8a58ea131445d19
Make typing messages pretty
src/gui.js
src/gui.js
const EventEmitter = require('events'), blessed = require('blessed'), timestamp = require('./util/timestamp'); class GUI extends EventEmitter { constructor(screen) { super(); this.screen = screen; this.chatbox = blessed.box({ label: 'Retrocord Light', width: '100%', height: '100%-1', border: { type: 'line' }, }); this.consolebox = blessed.log({ parent: this.chatbox, tags: true, scrollable: true, label: '', alwaysScroll: true, scrollbar: { ch: '', inverse: true, }, mouse: true, }); this.inputbox = blessed.textbox({ bottom: 0, width: '100%', height: 1, inputOnFocus: true, }); this.awaitingResponse = false; } init() { this.inputbox.key('enter', () => { if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue()); else this.emit('input', this.inputbox.getValue()); this.inputbox.clearValue(); this.inputbox.focus(); this.screen.render(); }); this.screen.append(this.chatbox); this.screen.append(this.inputbox); this.screen.render(); this.inputbox.focus(); } put(text) { this.consolebox.log(text); } putMessages(messages) { const me = this; messages.forEach(m => { const ts = timestamp(m.createdAt), arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}↩{/bold}{/green-fg}` : `{green-fg}{bold}↪{/bold}{/green-fg}`, txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} : ${m.content}`; me.put(txt); }); } putMessage(message, opt) { return this.putMessages([message], opt); } putTypingStart(channel, user) { this.put(`{yellow-fg}{bold}↪{/bold}{/yellow-fg} {white-fg}{bold}${user.username}{/bold} has {green-fg}started{/green-fg} typing.`); } putTypingStop(channel, user) { this.put(`{yellow-fg}{bold}↪{/bold}{/yellow-fg} {white-fg}{bold}${user.username}{/bold} has {red-fg}stopped{/red-fg} typing.`); } awaitResponse(text) { this.awaitingResponse = true; return new Promise((resolve) => { this.put(text); this.once('internalInput', (input) => { this.awaitingResponse = false; resolve(input); }); }); } } const screen = blessed.screen({ smartCSR: true, title: 'retrocord', fullUnicode: true, }); const gui = new GUI(screen); module.exports = gui;
JavaScript
0.000226
@@ -1784,38 +1784,36 @@ %0A this.put(%60%7B -yellow +blue -fg%7D%7Bbold%7D%E2%86%AA%7B/bol @@ -1798,33 +1798,33 @@ %60%7Bblue-fg%7D%7Bbold%7D -%E2%86%AA +%E2%86%B7 %7B/bold%7D%7B/yellow- @@ -1808,38 +1808,36 @@ %7Bbold%7D%E2%86%B7%7B/bold%7D%7B/ -yellow +blue -fg%7D %7Bwhite-fg%7D%7B @@ -1860,24 +1860,35 @@ name%7D%7B/bold%7D +%7B/white-fg%7D has %7Bgreen- @@ -1972,22 +1972,20 @@ s.put(%60%7B -yellow +blue -fg%7D%7Bbol @@ -1978,33 +1978,33 @@ %60%7Bblue-fg%7D%7Bbold%7D -%E2%86%AA +%E2%86%B6 %7B/bold%7D%7B/yellow- @@ -1988,38 +1988,36 @@ %7Bbold%7D%E2%86%B6%7B/bold%7D%7B/ -yellow +blue -fg%7D %7Bwhite-fg%7D%7B @@ -2044,16 +2044,27 @@ %7D%7B/bold%7D +%7B/white-fg%7D has %7Bre
9b399f5d53b3b1f2d5de0b0957cd6cdd5161771c
hide 'danger' concern
modules/concern.js
modules/concern.js
/** * concern.js * * !concern * Toggles whether the bot should interrupt charged conversations * with an unhelpful message. */ var bot = require( '..' ); var isEmotional = require( 'emotional_alert' ); var nox = false; bot.addListener( 'message', function ( nick, to, text ) { if ( !nox ) { var x = isEmotional( text ); if ( x.emotional) { if ( x.winner ) { var adj = { 0: '', 1: 'slightly ', 2: 'rather ', 3: 'quite ', 4: 'very ', 5: 'extremely ', 6: 'copiously ', 7: 'agonizingly ' }; x.adj = adj[x.emotional] === undefined ? 'a tad ' : adj[x.emotional]; switch (x.winner) { case 'anger': x.hwinner = 'angry'; break; case 'stress': x.hwinner = 'stressed'; break; case 'sad': /* falls through */ default: x.hwinner = x.winner; } bot.say( to, nick + ': you seem ' + x.adj + x.hwinner + ' (score: ' + x.emotional + ')'); } else { // danger phrase bot.say( to, nick + ': that is a worrying thing to say' ); } } } if ( text === '!concern' ) { if ( !nox ) { nox = true; bot.say( to, nick + ': adopting air of unconcern' ); } else { nox = false; bot.say( to, nick + ': concerning myself with matters' ); } } } );
JavaScript
0.999079
@@ -217,16 +217,51 @@ = false; +%0Avar verbose = false; // TODO: cvar %0A%0Abot.ad @@ -1017,16 +1017,38 @@ phrase%0A +%09%09%09%09if ( verbose ) %7B%0A%09 %09%09%09%09bot. @@ -1102,16 +1102,22 @@ say' );%0A +%09%09%09%09%7D%0A %09%09%09%7D%0A%09%09%7D
927f7f1985756865d6e15b7d833d2a55722c4afe
Fix typo
modules/setting.js
modules/setting.js
(function(root) { var fs = null var path = null var app = null if (typeof require != 'undefined') { fs = require('fs') path = require('path') app = require('electron').app } var context = typeof module != 'undefined' ? module.exports : (window.setting = {}) var settingspath = '' if (path && app) settingspath = path.join(app.getPath('userData'), 'settings.json') var settings = {} var engines = [] var defaults = { 'app.startup_check_updates': true, 'app.startup_check_updates_delay': 100, 'app.loadgame_delay': 100, 'app.hide_busy_delay': 200, 'autoscroll.max_interval': 200, 'autoscroll.min_interval': 50, 'autoscroll.diff': 10, 'console.blocked_commands': [ 'boardsize', 'clear_board', 'play', 'genmove', 'undo', 'fixed_handicap', 'place_free_handicap', 'set_free_handicap', 'loadsgf' ], 'console.max_history_count': 30, 'edit.click_currentvertex_to_remove': true, 'edit.show_removenode_warning': true, 'edit.undo_delay': 100, 'engines.list': engines, 'find.delay': 100, 'game.default_board_size': 19, 'game.default_komi': 6.5, 'game.goto_end_after_loading': false, 'game.show_ko_warning': true, 'game.show_suicide_warning': true, 'graph.collapse_min_depth': 1, 'graph.collapse_tokens_count': 100000, 'graph.delay': 300, 'graph.grid_size': 25, 'graph.node_active_color': '#f76047', 'graph.node_bookmark_color': '#c678dd', 'graph.node_collapsed_color': '#333', 'graph.node_inactive_color': '#777', 'graph.node_color': '#eee', 'graph.node_comment_color': '#6bb1ff', 'graph.node_size': 4, 'gtp.attach_delay': 300, 'gtp.move_delay': 300, 'scoring.method': 'territory', 'sound.capture_delay_max': 500, 'sound.capture_delay_min': 300, 'sound.enable': true, 'view.properties_height': 50, 'view.properties_minheight': 20, 'view.fuzzy_stone_placement': true, 'view.show_leftsidebar': false, 'view.show_comments': false, 'view.show_coordinates': false, 'view.show_graph': false, 'view.show_show_next_moves': true, 'view.leftsidebar_width': 250, 'view.leftsidebar_minwidth': 100, 'view.sidebar_width': 200, 'view.sidebar_minwidth': 100, 'window.height': 622, 'window.minheight': 590, 'window.minwidth': 550, 'window.width': 577 } context.load = function() { if (!fs) return settings = defaults settings = JSON.parse(fs.readFileSync(settingspath, { encoding: 'utf8' })) // Load default settings for (var key in defaults) { if (key in settings) continue settings[key] = defaults[key] } engines = settings['engines.list'] engines.sort(function(x, y) { return x.name >= y.name }) return context } context.save = function() { if (!fs) return context fs.writeFileSync(settingspath, JSON.stringify(settings, null, ' ')) return context } context.get = function(key) { if (key in settings) return settings[key] if (key in defaults) return defaults[key] return null } context.set = function(key, value) { settings[key] = value return context.save() } context.addEngine = function(name, path, args) { engines.push({ name: name, path: path, args: args }) engines.sort(function(x, y) { return x.name >= y.name }) return context } context.getEngines = function() { return engines.slice(0) } context.clearEngines = function() { engines.length = 0 return context } try { fs.accessSync(settingspath, fs.F_OK) } catch(err) { context.save() } context.load() }).call(null, typeof module != 'undefined' ? module : window)
JavaScript
0.999999
@@ -2112,21 +2112,16 @@ ew.show_ -show_ next_mov
b6cb079ff3130637d4a546e5b8b9e1227d89bfc1
Make menu updates fire even when no flush happens, debounce flushes
update.js
update.js
export class MenuUpdate { constructor(pm, events, prepare) { this.pm = pm this.prepare = prepare this.mustUpdate = false this.updateInfo = null this.events = events.split(" ") this.onEvent = () => this.mustUpdate = true this.events.forEach(event => pm.on(event, this.onEvent)) pm.on("flush", this.onFlush = this.onFlush.bind(this)) pm.on("flushed", this.onFlushed = this.onFlushed.bind(this)) } detach() { this.events.forEach(event => this.pm.off(event, this.onEvent)) this.pm.off("flush", this.onFlush) this.pm.off("flushed", this.onFlushed) } onFlush() { if (this.mustUpdate) { this.mustUpdate = false this.update = this.prepare() } } onFlushed() { if (this.update) { this.update() this.update = null } } force() { this.mustUpdate = false this.updateInfo = null let update = this.prepare() if (update) update() } }
JavaScript
0
@@ -1,8 +1,64 @@ +const MIN_FLUSH_DELAY = 200%0Aconst UPDATE_TIMEOUT = 200%0A%0A export c @@ -211,16 +211,63 @@ o = null +%0A this.timeout = null%0A this.lastFlush = 0 %0A%0A th @@ -319,36 +319,70 @@ t = -() =%3E this.mustUpdate = true +this.onEvent.bind(this)%0A this.force = this.force.bind(this) %0A @@ -577,24 +577,55 @@ detach() %7B%0A + clearTimeout(this.timeout)%0A this.eve @@ -788,30 +788,160 @@ -if (this.mustUpdate) %7B +let now = Date.now()%0A if (this.mustUpdate && (now - this.lastFlush) %3E= MIN_FLUSH_DELAY) %7B%0A this.lastFlush = now%0A clearTimeout(this.timeout) %0A @@ -1108,16 +1108,151 @@ %7D%0A %7D%0A%0A + onEvent() %7B%0A this.mustUpdate = true%0A clearTimeout(this.timeout)%0A this.timeout = setTimeout(this.force, UPDATE_TIMEOUT)%0A %7D%0A%0A force( @@ -1306,24 +1306,87 @@ Info = null%0A + this.lastFlush = Date.now()%0A clearTimeout(this.timeout)%0A let upda
811ae14efc513873866d3e4e4a9c1688d33f9b87
Set text on the profile image button
private/library/components/views/dialogs/UserSelfDialog.js
private/library/components/views/dialogs/UserSelfDialog.js
/* Copyright 2019 Carmilla Mina Jankovic 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. */ const BaseDialog = require('./BaseDialog'); const elementCreator = require('../../../ElementCreator'); const labelHandler = require('../../../labels/LabelHandler'); const userComposer = require('../../../data/composers/UserComposer'); const positionComposer = require('../../../data/composers/PositionComposer'); const eventCentral = require('../../../EventCentral'); const viewSwitcher = require('../../../ViewSwitcher'); const ids = { PICTURE: 'picture', }; class UserSelfDialog extends BaseDialog { constructor({ classes = [], elementId = `uDialog-${Date.now()}`, }) { const user = userComposer.getCurrentUser(); const { image, partOfTeams, fullName, username, objectId: userId, } = user; const userPosition = positionComposer.getPosition({ positionId: user.objectId }); const inputs = [ elementCreator.createImageInput({ elementId: ids.PICTURE, inputName: 'picture', appendPreview: true, previewId: 'imagePreview-userSelf', }), ]; const lowerButtons = [ elementCreator.createButton({ text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }), clickFuncs: { leftFunc: () => { this.removeFromView(); }, }, }), // elementCreator.createButton({ // text: labelHandler.getLabel({ baseObject: 'UserSelfDialog', label: 'rename' }), // clickFuncs: { // leftFunc: () => { // const renameDialog = new BaseDialog({ // inputs: [ // elementCreator.createInput({ // elementId: 'username', // inputName: 'username', // type: 'text', // isRequired: true, // maxLength: 10, // placeholder: labelHandler.getLabel({ baseObject: 'LoginDialog', label: 'username' }), // }), // ], // lowerButtons: [ // elementCreator.createButton({ // text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'cancel' }), // clickFuncs: { // leftFunc: () => { renameDialog.removeFromView(); }, // }, // }), // elementCreator.createButton({ // text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }), // clickFuncs: { // leftFunc: () => { // if (this.hasEmptyRequiredInputs()) { // return; // } // // userComposer.updateUsername({ // userId, // username: renameDialog.getInputValue('username'), // callback: ({ error: updateError }) => { // if (updateError) { // console.log('Failed to update username'); // // return; // } // // const parentElement = renameDialog.getParentElement(); // // renameDialog.removeFromView(); // this.addToView({ element: parentElement }); // }, // }); // }, // }, // }), // ], // }); // // renameDialog.addToView({ element: this.getParentElement() }); // this.removeFromView(); // }, // }, // }), elementCreator.createButton({ text: labelHandler.getLabel({ baseObject: 'BaseDialog', label: 'update' }), clickFuncs: { leftFunc: () => { if (this.hasEmptyRequiredInputs()) { return; } const params = { userId, callback: ({ error }) => { if (error) { console.log(error); return; } this.removeFromView(); }, }; const imagePreview = document.getElementById('imagePreview-userSelf'); if (imagePreview.getAttribute('src')) { params.image = { source: imagePreview.getAttribute('src'), imageName: imagePreview.getAttribute('name'), width: imagePreview.naturalWidth, height: imagePreview.naturalHeight, }; } console.log('update user ', params); userComposer.updateUser(params); }, }, }), ]; if (userPosition) { lowerButtons.push(elementCreator.createButton({ text: labelHandler.getLabel({ baseObject: 'UserDialog', label: 'trackPosition' }), clickFuncs: { leftFunc: () => { viewSwitcher.switchViewByType({ type: viewSwitcher.ViewTypes.WORLDMAP }); eventCentral.emitEvent({ event: eventCentral.Events.FOCUS_MAPPOSITION, params: { position: userPosition }, }); this.removeFromView(); }, }, })); } const upperText = [ `${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'userInfo' })}`, '', ]; if (fullName) { upperText.push(fullName); } upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'username' })}: ${username}`); if (partOfTeams && partOfTeams.length > 0) { upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'partOfTeam' })}: ${partOfTeams}`); } if (userPosition && userPosition.coordinatesHistory && userPosition.coordinatesHistory[0]) { const positionLabel = `(${userPosition.lastUpdated}): Lat ${userPosition.coordinatesHistory[0].latitude} Long ${userPosition.coordinatesHistory[0].longitude}`; upperText.push(`${labelHandler.getLabel({ baseObject: 'UserDialog', label: 'position' })}: ${positionLabel}`); } const images = []; if (image) { images.push(elementCreator.createPicture({ picture: image, })); } super({ elementId, lowerButtons, upperText, images, inputs, classes: classes.concat(['userSelfDialog']), }); } } module.exports = UserSelfDialog;
JavaScript
0.000002
@@ -1465,24 +1465,117 @@ mageInput(%7B%0A + buttonText: labelHandler.getLabel(%7B baseObject: 'RegisterDialog', label: 'image' %7D),%0A elem
19c0b33aabb43d4388f58904cabc0335f488c7bf
fix default languages
source/nunjucks/filter/TranslationsFilter.js
source/nunjucks/filter/TranslationsFilter.js
'use strict'; /** * Requirements * @ignore */ const Filter = require('./Filter.js').Filter; const TranslationsRepository = require('../../model/translation/TranslationsRepository.js').TranslationsRepository; const SystemModuleConfiguration = require('../../configuration/SystemModuleConfiguration.js').SystemModuleConfiguration; const assertParameter = require('../../utils/assert.js').assertParameter; const waitForPromise = require('../../utils/synchronize.js').waitForPromise; const isPlainObject = require('lodash.isplainobject'); /** * @memberOf nunjucks.filter */ class TranslationsFilter extends Filter { /** * @inheritDocs */ constructor(translationsRepository, moduleConfiguration) { super(); // Check params assertParameter(this, 'translationsRepository', translationsRepository, true, TranslationsRepository); assertParameter(this, 'moduleConfiguration', moduleConfiguration, true, SystemModuleConfiguration); // Assign options this._name = 'translations'; this._translationsRepository = translationsRepository; this._moduleConfiguration = moduleConfiguration; } /** * @inheritDoc */ static get injections() { return { 'parameters': [TranslationsRepository, SystemModuleConfiguration] }; } /** * @inheritDoc */ static get className() { return 'nunjucks.filter/TranslationsFilter'; } /** * @type {model.translation.TranslationsRepository} */ get translationsRepository() { return this._translationsRepository; } /** * @type {configuration.SystemModuleConfiguration} */ get moduleConfiguration() { return this._moduleConfiguration; } /** * @inheritDoc * value - Queries * languages - Language(s) to return (array, locale, all, current) * excludeQuery - if true will omit the query portion of the key */ filter() { const scope = this; return function (value, languages, excludeQuery) { // Only handle strings if (isPlainObject(value)) { return scope.applyCallbacks(value, arguments); } if (!value) { return scope.applyCallbacks({}, arguments); } // Site const globals = scope.getGlobals(this); const site = globals.location.site || false; // Languages let langs = scope.moduleConfiguration.languages; if (languages == 'current') { langs = (globals.configuration && typeof globals.configuration.getByPath == 'function') ? [globals.configuration.getByPath('language', scope.moduleConfiguration.language)] : [scope.moduleConfiguration.language]; } else { langs = Array.isArray(languages) ? languages : [languages]; } // Get translations const queries = Array.isArray(value) ? value : [value]; const result = {}; for (const language of langs) { for (const query of queries) { const translations = waitForPromise(scope.translationsRepository.getByQuerySiteAndLanguage(query, site, language)) || {}; result[language] = result[language] || {}; if (excludeQuery) { for (const key in translations) { result[language][key.replace(query, '')] = translations[key]; } } else { Object.assign(result[language], translations); } } } return scope.applyCallbacks(result, arguments); }; } } /** * Exports * @ignore */ module.exports.TranslationsFilter = TranslationsFilter;
JavaScript
0.000003
@@ -2261,120 +2261,8 @@ %7D -%0A if (!value)%0A %7B%0A return scope.applyCallbacks(%7B%7D, arguments);%0A %7D %0A%0A @@ -2819,32 +2819,47 @@ else + if (languages) %0A %7B%0A
fe2826234931f14d185770bf94f4c3597b6d7b91
changing to stateless
src/js/components/common/header/Header.component.js
src/js/components/common/header/Header.component.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Header extends Component { super(props) {} render() { const { guest } = this.props; // const id = guest.id ? guest.id : ''; return ( <div className="header" id="header"> <div className="gutters"> <div className="grid-flex"> <div className="header__logo-group"> <p className="header__logo header__menu-item"> <a href="https://daleandkatie.co.nz/">K / D</a> </p> </div> </div> </div> </div> ); } } Header.propTypes = { guest: PropTypes.object, }; Header.defaultProps = { guest: {}, }; export default Header; // <div className="width-4/5@medium u-hidden@small"> // <ul className="list-inline header__menu-large"> // <li className="header__menu-item"> // <a // href={`https://daleandkatie.co.nz/#/${id}#the-details`} // > // The details // </a> // </li> // {!guest.rsvp && ( // <li className="header__menu-item"> // <a // href={`https://daleandkatie.co.nz/#/${id}#rsvp`} // > // RSVP // </a> // </li> // )} // <li className="header__menu-item"> // <a // href={`https://daleandkatie.co.nz/#/${id}#travel`} // > // Travel // </a> // </li> // <li className="header__menu-item"> // <a // href={`https://daleandkatie.co.nz/#/${id}#accommodation`} // > // Accommodation // </a> // </li> // <li className="header__menu-item"> // <a // href={`https://daleandkatie.co.nz/#/${id}#the-extras`} // > // The extras // </a> // </li> // </ul> // </div>
JavaScript
0.99984
@@ -9,23 +9,8 @@ eact -, %7B Component %7D fro @@ -20,16 +20,19 @@ react';%0A +// import P @@ -65,20 +65,20 @@ ;%0A%0Ac -lass +onst Header exte @@ -77,105 +77,18 @@ der -extends Component %7B%0A super(props) %7B%7D%0A render() %7B%0A const %7B guest %7D = this.props;%0A += () =%3E %7B%0A @@ -127,20 +127,16 @@ d : '';%0A - retu @@ -140,36 +140,32 @@ eturn (%0A - - %3Cdiv className=%22 @@ -189,36 +189,32 @@ r%22%3E%0A - - %3Cdiv className=%22 @@ -223,20 +223,16 @@ tters%22%3E%0A - @@ -279,36 +279,32 @@ - - %3Cdiv className=%22 @@ -324,20 +324,16 @@ group%22%3E%0A - @@ -423,20 +423,16 @@ - %3Ca href= @@ -499,46 +499,11 @@ - - %3C/p%3E%0A %3C/div +%3C/p %3E%0A @@ -581,20 +581,29 @@ -);%0A %7D%0A%7D%0A%0A +%3C/div%3E%0A );%0A%7D;%0A%0A// Head @@ -615,24 +615,27 @@ opTypes = %7B%0A +// guest: P @@ -651,20 +651,26 @@ object,%0A +// %7D;%0A%0A +// Header.d @@ -685,16 +685,19 @@ ops = %7B%0A +// gues @@ -703,16 +703,19 @@ st: %7B%7D,%0A +// %7D;%0A%0Aexpo
f043eeaa6475abc78ee02a8ef04e4ab5dc41ec28
Revert "Prevent ghost users"
rdiodj/static/js/chat.js
rdiodj/static/js/chat.js
var chat = chat || {}; chat.User = Backbone.Model.extend({ }); chat.firebasePeopleRef = new Firebase(firebaseRootUrl + '/people'); chat.firebaseMessagesRef = new Firebase(firebaseRootUrl + '/messages'); chat.UserList = Backbone.Firebase.Collection.extend({ model: chat.User, firebase: chat.firebasePeopleRef, // pass the ref here instead of string so we can listen for disconnect. getOnlineUsers: function() { return this.filter(function(user) { return user.get('isOnline'); }); } }); chat.activeUsers = new chat.UserList(); chat.UserView = Backbone.View.extend({ tagName: 'li', template: _.template($('#user-presence-template').html()), initialize: function() { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'remove', this.remove); }, render: function() { var self = this; R.request({ method: 'get', content: { keys: this.model.get('id'), extras: 'shortUrl' }, success: function(response) { var data = _.extend({ 'user': response.result[self.model.get('id')] }); self.$el.html(self.template(data)); self.$el.show(); }, error: function(response) { console.log('Unable to get user information for', self.model.get('id')); } }); return this; } }); chat.UserListView = Backbone.View.extend({ el: '#user-list', initialize: function() { this.presenceStats = $('#presence-stats'); // listen to when new users are added this.listenTo(chat.activeUsers, 'add', this.onListChanged); // and to when users change from online to offline this.listenTo(chat.activeUsers, 'change', this.onListChanged); //probably should render the activeUsers on init so we have a starting point too. this.redraw(chat.activeUsers , {}); }, drawUser: function(model, collection, options) { if (model.get('isOnline')) { console.log("rendering user: ", model); var view = new chat.UserView({ model: model }); this.$el.append(view.render().el); } }, redraw: function(collection, options) { this.$el.empty(); collection.each(this.drawUser, this); }, onListChanged: function(model, options) { console.log("list changed with model: ", model); // this is inefficient, but we don't have another hook to the dom element. this.redraw(chat.activeUsers , {}); } }); /* chat messages! */ chat.Message = Backbone.Model.extend({ }); chat.MessageHistoryList = Backbone.Firebase.Collection.extend({ model: chat.Message, firebase: chat.firebaseMessagesRef }); chat.UserMessageView = Backbone.View.extend({ tagName: 'li', template: _.template($('#chat-user-message-template').html()), render: function() { var user = chat.activeUsers.get(this.model.get('userKey')) if (user) { icon = user.attributes.icon } else { icon = '' } var data = { fullName: this.model.get('fullName'), icon: icon }; this.$el.html(this.template(data)); this.$el.find('.chat-message').text(this.model.get('message')); this.$el.show(); return this; } }); chat.NewTrackMessageView = Backbone.View.extend({ tagName: 'li', template: _.template($('#chat-new-track-template').html()), render: function() { var data = { title: this.model.get('title'), artist: this.model.get('artist'), iconUrl: this.model.get('iconUrl'), trackUrl: this.model.get('trackUrl'), trackKey: this.model.get('trackKey') }; this.$el.html(this.template(data)); this.$el.show(); return this; } }); chat.MessagesView = Backbone.View.extend({ el: '.chat-messages', initialize: function() { // there's probably a better way to do this with inheritance... this.listenTo(chat.messageHistory, 'add', this.onMessageAdded); console.log('chat view initialized'); }, onMessageAdded: function(model, options) { var messageType = model.get('type'); if (messageType == 'User') { var messageView = new chat.UserMessageView({ model: model }); this.$el.append(messageView.render().el); this.el.parentElement.scrollTop = this.el.parentElement.scrollHeight; } else if (messageType == 'NewTrack') { var trackView = new chat.NewTrackMessageView({ model: model }); this.$el.append(trackView.render().el); this.el.parentElement.scrollTop = this.el.parentElement.scrollHeight; } } }); R.ready(function() { chat.currentUser = R.currentUser; var userKey = R.currentUser.get('key'); // add current user to activeUsers list, if they're not already var user = chat.activeUsers.get(userKey); if (user === undefined) { chat.activeUsers.add({ id: userKey, isOnline: true, icon: R.currentUser.get('icon'), fullName: R.currentUser.get('firstName') + ' ' + R.currentUser.get('lastName') }); console.log("added user ", chat.activeUsers.get(userKey), " to chat"); } var isOnlineRef = chat.activeUsers.firebase.child(userKey).child('isOnline'); console.log('online presence:', isOnlineRef.toString()); // Mark yourself as offline on disconnect isOnlineRef.onDisconnect().set(false); //Mark myself as online on reconnect var connectedRef = new Firebase("https://rdiodj.firebaseio.com/.info/connected"); connectedRef.on("value", function(snap) { if (snap.val() === true) { isOnlineRef.set(true); } }); // Mark yourself as online isOnlineRef.set(true); // draw user list view (after marking yourself as online) var userListView = new chat.UserListView(); // Set up chat // user chat entry var chatEntryText = $('.chat-entry-text'); chatEntryText.keypress(function(e) { if (e.keyCode == 13) { // listen for enter key var message = chatEntryText.val(); chat.sendMessage(message); chatEntryText.val(''); } }); // we set up track change messages in rdiodj.js chat.messageHistory = new chat.MessageHistoryList(); var chatView = new chat.MessagesView(); }); chat.sendMessage = function(message) { var fullName = chat.currentUser.get('firstName') + ' ' + chat.currentUser.get('lastName'); var messageData = { type: 'User', fullName: fullName, userKey: chat.currentUser.get('key'), message: message, timestamp: (new Date()).toISOString() }; chat.messageHistory.add(messageData); }
JavaScript
0
@@ -5235,247 +5235,8 @@ );%0A%0A - //Mark myself as online on reconnect%0A var connectedRef = new Firebase(%22https://rdiodj.firebaseio.com/.info/connected%22);%0A connectedRef.on(%22value%22, function(snap) %7B%0A if (snap.val() === true) %7B%0A isOnlineRef.set(true);%0A %7D%0A %7D);%0A //
06564f9e049417087fa53cf8ec15c22ec65724d5
Update gl_field_error tests for better input filtering.
spec/javascripts/gl_field_errors_spec.js.es6
spec/javascripts/gl_field_errors_spec.js.es6
//= require jquery //= require gl_field_errors ((global) => { fixture.preload('gl_field_errors.html'); describe('GL Style Field Errors', function() { beforeEach(function() { fixture.load('gl_field_errors.html'); const $form = this.$form = $('form.show-gl-field-errors'); this.fieldErrors = new global.GlFieldErrors($form); }); it('should properly initialize the form', function() { expect(this.$form).toBeDefined(); expect(this.$form.length).toBe(1); expect(this.fieldErrors).toBeDefined(); const inputs = this.fieldErrors.state.inputs; expect(inputs.length).toBe(5); }); it('should ignore elements with custom error handling', function() { const customErrorFlag = 'no-gl-field-errors'; const customErrorElem = $(`.${customErrorFlag}`); expect(customErrorElem.length).toBe(1); const customErrors = this.fieldErrors.state.inputs.filter((input) => { return input.inputElement.hasClass(customErrorFlag); }); expect(customErrors.length).toBe(0); }); it('should not show any errors before submit attempt', function() { this.$form.find('.email').val('not-a-valid-email').keyup(); this.$form.find('.text-required').val('').keyup(); this.$form.find('.alphanumberic').val('?---*').keyup(); const errorsShown = this.$form.find('.gl-field-error-outline'); expect(errorsShown.length).toBe(0); }); it('should show errors when input valid is submitted', function() { this.$form.find('.email').val('not-a-valid-email').keyup(); this.$form.find('.text-required').val('').keyup(); this.$form.find('.alphanumberic').val('?---*').keyup(); this.$form.submit(); const errorsShown = this.$form.find('.gl-field-error-outline'); expect(errorsShown.length).toBe(4); }); it('should properly track validity state on input after invalid submission attempt', function() { this.$form.submit(); const emailInputModel = this.fieldErrors.state.inputs[1]; const fieldState = emailInputModel.state; const emailInputElement = emailInputModel.inputElement; // No input expect(emailInputElement).toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(true); expect(fieldState.valid).toBe(false); // Then invalid input emailInputElement.val('not-a-valid-email').keyup(); expect(emailInputElement).toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(false); expect(fieldState.valid).toBe(false); // Then valid input emailInputElement.val('[email protected]').keyup(); expect(emailInputElement).not.toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(false); expect(fieldState.valid).toBe(true); // Then invalid input emailInputElement.val('not-a-valid-email').keyup(); expect(emailInputElement).toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(false); expect(fieldState.valid).toBe(false); // Then empty input emailInputElement.val('').keyup(); expect(emailInputElement).toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(true); expect(fieldState.valid).toBe(false); // Then valid input emailInputElement.val('[email protected]').keyup(); expect(emailInputElement).not.toHaveClass('gl-field-error-outline'); expect(fieldState.empty).toBe(false); expect(fieldState.valid).toBe(true); }); it('should properly infer error messages', function() { this.$form.submit(); const trackedInputs = this.fieldErrors.state.inputs; const inputHasTitle = trackedInputs[1]; const hasTitleErrorElem = inputHasTitle.inputElement.siblings('.gl-field-error'); const inputNoTitle = trackedInputs[2]; const noTitleErrorElem = inputNoTitle.inputElement.siblings('.gl-field-error'); expect(noTitleErrorElem.text()).toBe('This field is required.'); expect(hasTitleErrorElem.text()).toBe('Please provide a valid email address.'); }); }); })(window.gl || (window.gl = {}));
JavaScript
0
@@ -372,36 +372,41 @@ uld -properly initialize +select the -form +correct input elements ', f @@ -633,9 +633,9 @@ oBe( -5 +4 );%0A
6725267da9799f285d6c33b90254f6dc57f1f2da
remove comment, since it no longer applies
src/pov.js
src/pov.js
import closestHead from './utils/closestHead'; import intersectOrb from './utils/intersectcenter'; import viewer from './viewer'; import InstancedItem from './instanced-item'; import Room from './room'; import layout from './room/layout'; import settings from './settings'; import controllers from './controllers'; export default function create({ rooms, orb }) { const { holeHeight } = settings; let pointerX; let pointerY; let hoverPerformance; let hoverOrb; const onMouseMove = ({ clientX, clientY }) => { if (viewer.vrEffect.isPresenting) return; pointerX = clientX; pointerY = clientY; }; const onMouseDown = ({ clientX, clientY, touches }) => { if (viewer.vrEffect.isPresenting) return; let x = clientX; let y = clientY; if (touches && touches.length > 0) { x = touches[0].pageX; y = touches[0].pageY; } hoverOrb = intersectOrb(x, y); hoverPerformance = closestHead(x, y, rooms); if (hoverPerformance || hoverOrb) { viewer.switchCamera('default'); InstancedItem.group.add(viewer.camera); } }; const onMouseUp = () => { if (viewer.vrEffect.isPresenting) return; hoverPerformance = null; hoverOrb = false; viewer.switchCamera('orthographic'); }; const clearHighlights = () => { hoverPerformance = null; hoverOrb = false; orb.unhighlight(); Room.setHighlight(); }; window.addEventListener('vrdisplaypresentchange', clearHighlights, false); const POV = { update: (progress = 0, fixedControllers = false) => { if (!viewer.vrEffect.isPresenting) { if (intersectOrb(pointerX, pointerY)) { orb.highlight(); Room.setHighlight(); } else { orb.unhighlight(); if (!hoverPerformance && !hoverOrb) { Room.setHighlight( closestHead( pointerX, pointerY, rooms ) ); } } } // for some reason position has to be done here as well as in playback // otherwise the positional values begin spiraling into infinity const position = layout.getPosition(progress + 0.5); position.y += holeHeight; position.z *= -1; if (fixedControllers) { controllers.fixToPosition(position); } viewer.camera.position.copy(position); if (hoverOrb) { // Move camera into orb: viewer.camera.position.z *= -1; viewer.camera.rotation.set(0, Math.PI, 0); } else if (hoverPerformance) { // Move camera into head of performance: const [index, headIndex] = hoverPerformance; rooms[index].transformToHead(viewer.camera, headIndex); } }, setupInput: () => { window.addEventListener('mousemove', onMouseMove); window.addEventListener('mousedown', onMouseDown); window.addEventListener('mouseup', onMouseUp); window.addEventListener('touchstart', onMouseDown, false); window.addEventListener('touchend', onMouseUp, false); }, removeInput: () => { window.removeEventListener('mousemove', onMouseMove); window.removeEventListener('mousedown', onMouseDown); window.removeEventListener('mouseup', onMouseUp); window.removeEventListener('vrdisplaypresentchange', clearHighlights); }, clearHighlights, }; return POV; }
JavaScript
0
@@ -1992,158 +1992,8 @@ %7D%0A%0A - // for some reason position has to be done here as well as in playback%0A // otherwise the positional values begin spiraling into infinity%0A
12c781309524a0e90d6a9c6b20e321def700d4e7
test commit
src/smx.js
src/smx.js
/** * SMX Synchronized Multimedia XML * * @module smx * */ (function(window){ var smx = {}; /* software version: major.minor.path */ smx.version = '0.8.1'; //expose window.smx = smx; })(window);
JavaScript
0.000001
@@ -62,18 +62,16 @@ */%0D%0A%0D%0A%0D%0A -%0D%0A (functio
4e14f674326bc57a559a0033759934922e678219
remove exit
yibite.js
yibite.js
var Crawler = require("crawler").Crawler; var urls = []; var fs= require('fs'); var times = 0; var c = new Crawler({ "maxConnections": 1, }); function writeFs(urls){ var data = {"news": urls }; fs.writeFile("yibite.json", JSON.stringify(data), function (err) { if (err) throw err; console.log('It\'s saved!'); }); } /* * mongodb */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/bitcoin'); var newsSchema = Schema({ title : String, url : String, time : Date, origin : String, intro : String, no : String }); var News = mongoose.model('News', newsSchema); News.remove({}, function(err) { console.log('News collection removed'); }); function saveMongoDB(urls){ urls.forEach(function(item){ var oneNew = new News( item ); oneNew.save(function (err) { if (err) // ... console.log('insert error'); }); }); } // Queue just one URL, with default callback var tasks = []; var max = 40; for (var i = 1; i <= max; i++) { tasks.push({ "maxConnections": 1, "uri": "http://yibite.com/news/index.php?page="+i, "callback": function(error,result,$) { urls = []; $('.li-holder').each( function(index, div){ var timeDiv = $(div).find('.tags > span.time')[0]; var linkDiv = $(div).find('.right-intro > a.art-myTitle')[0]; var originDiv = $(div).find('.tags > a.author')[0]; var introDiv = $(div).find('.right-intro > span.intro')[0]; urls.push({ url: linkDiv.href, title: linkDiv.innerHTML, time: timeDiv.innerHTML, origin: originDiv.innerHTML, intro: introDiv.innerHTML, no: "page"+times+"-"+index }); console.log("page"+times+"-"+index); }); times += 1; console.log('queue call '+times+' times'); // writeFs(urls); saveMongoDB(urls); if (i == 41) { process.exit(0); }; } }); }; console.dir(tasks); c.queue(tasks); // TODO crawler pagination url // TODO insert the data // TODO check the repeat // TODO 定时任务
JavaScript
0.002894
@@ -1888,62 +1888,8 @@ s);%0A -%09 %09if (i == 41) %7B%0A%09 %09%09process.exit(0);%0A%09 %09%7D;%0A %09%09%7D%0A
83381653f1dfcb8af449a691c75e1cf483f5058a
Update the HTML to give user more direction
googleplusrss.js
googleplusrss.js
var http = require('sys'); var http = require('http'); var https = require('https'); var RSS = require('rss'); var cache = require('./cache'); var reId = new RegExp(/\/(\d+)$/); http.createServer(function(req, serverResponse) { try { //Get the ID off the url var m = reId.exec(req.url); if (m != null) { //Url has the id so send back rss feed serverResponse.writeHead(200, { 'content-type': 'application/rss+xml' }); var googleId = m[1]; var cacheFeed = cache.get(googleId); if (cacheFeed != null) { console.log("Read from cache: " + googleId); serverResponse.end(cacheFeed); } else { var options = { host: 'plus.google.com', port: 443, path: '/_/stream/getactivities/?&sp=[1,2,"'+googleId+'",null,null,40,null,"social.google.com",[]]', method: 'GET', headers: { 'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110613 Firefox/6.0a2', 'Connection':'keep-alive' } }; var googleReq = https.request(options, function(googleResponse) { var data = []; googleResponse.on('data', function(d) { data.push(d); }); googleResponse.on('end', function() { var results = data.join(''); results = results.replace(")]}'",""); results = results.replace(/\[,/g, '["",'); results = results.replace(/,,/g, ',"",'); results = results.replace(/,,/g, ',"",'); var p = JSON.parse(results); var post = p[1][0]; var authorName = post[0][3].toString(); var feed = new RSS({ title: authorName + "'s Google+ Public Feed", feed_url: 'http://plus.google.com/' + googleId + '/posts', site_url: 'http://plus.google.com', author: authorName }); for (i=0;i<post.length;i++) { feed.item({ title: post[i][4].toString(), url: 'https://plus.google.com/' + post[i][21].toString(), // link to the item date: new Date(post[i][5]) // any format that js Date can parse. }); } var feed = feed.xml(); cache.put(googleId, feed, 300000) //Cache for 5 minutes console.log("Pulled from google: " + googleId); serverResponse.end(feed); }); }); googleReq.end(); } } else { //Else output directions serverResponse.writeHead(200, { 'content-type': 'text/html' }); serverResponse.write("<html><head><title>Google+ to RSS Feed</title></head><body>"); serverResponse.write("<h1>Google+ to RSS Feed</h1>"); serverResponse.write("<p>Just add your google user id to this url like this http://googleplus2rss.nodester.com/12345678901234567890 and it will give you your feed.</p>"); serverResponse.end("</body></html>"); } } catch (ex) { serverResponse.writeHead(200, { 'content-type': 'text/html' }); serverResponse.write("<html><head><title>Google+ to RSS Feed</title></head><body>"); serverResponse.write("<h1>Google+ to RSS Feed Error</h1>"); serverResponse.write("<p>We got the following error getting the feed: " + ex.toString() + "</p>"); serverResponse.end("</body></html>"); } }).listen(11908);
JavaScript
0
@@ -2922,27 +2922,28 @@ om/1 -2345678901234567890 +18004117219257714873 and @@ -2965,21 +2965,1038 @@ ou your -feed. +raw rss feed. You can get your user id by logging into your Google+ account and clicking on your name. The url in the browse will have a long number which is your user id.%3C/p%3E%22);%0A serverResponse.write(%22%3Cp%3EThis still is a beta site so it might go down from time to time. If you have any issues please submit a issue to %3Ca href='https://github.com/jtwebman/GooglePlusToRSSFeed/issues'%3EGithub Issues%3C/a%3E%3C/p%3E%22);%0A serverResponse.write(%22%3Cp%3E%3Cb%3ECurrent Working On:%3C/b%3E%3C/p%3E%22);%0A serverResponse.write(%22%3Cul%3E%22);%0A serverResponse.write(%22%3Cli%3EFixing links and videos with no text with them.%3C/li%3E%22);%0A serverResponse.write(%22%3Cli%3EAdding a full express site with more detailed help.%3C/li%3E%22);%0A serverResponse.write(%22%3Cli%3ELimits so we don't get kicked from nodester.com, it's free thanks guys!%3C/li%3E%22);%0A serverResponse.write(%22%3Cli%3EA job doing Node.js so I can stop wasting my time with M$ programming. :)%3C/li%3E%22);%0A serverResponse.write(%22%3C/ul%3E%22);%0A serverResponse.write(%22%3Cp%3EThanks for taking a look! JTWebMan %3C/p%3E%22);%0A @@ -4384,32 +4384,266 @@ ng() + %22%3C/p%3E%22);%0A + serverResponse.write(%22%3Cp%3EThis still is a beta site so it might go down from time to time. If you have any issues please submit a issue to %3Ca href='https://github.com/jtwebman/GooglePlusToRSSFeed/issues'%3EGithub Issues%3C/a%3E%3C/p%3E%22);%0A serverResp
5af66557eba4ee6720a62ac16bc08666b1098796
Support template for message.
src/devilry_extjsextras/devilry_extjsextras/static/devilry_extjsextras/AlertMessage.js
src/devilry_extjsextras/devilry_extjsextras/static/devilry_extjsextras/AlertMessage.js
/** Message for highlighting the failure, possible failure, or success of an action. Particularly useful for forms. */ Ext.define('devilry_extjsextras.AlertMessage', { extend: 'Ext.Component', alias: 'widget.alertmessage', requires: [ 'Ext.fx.Animator', 'Ext.util.DelayedTask' ], tpl: [ '<div class="alert alert-{type} {extracls}" style="{style}">', '<tpl if="closable">', '<button type="button" class="close" data-dismiss="alert">×</button>', '</tpl>', '<tpl if="title">', '<strong>{title}</strong>: ', '</tpl>', '{message}', '</div>' ], /** * @cfg {String} [boxMargin] * Override the margin style of the alert DIV. */ boxMargin: undefined, /** * @cfg * Type of message. Valid values: 'error', 'warning', 'info' or 'success'. * Defaults to 'warning'. */ type: 'warning', /** * @cfg * The one line of message to display. This is not required, as it may be * useful to initialize an hidden alert message and use update() to change * the message when there is a message to show. */ message: '', /** * @cfg {bool} [closable=false] * Show close button. The ``closed`` event is fired when the button is * clicked. */ closable: false, /** * @cfg {int} [autoclose] * Fire the ``close`` event ``autoclose`` seconds after creating the message. * If ``true``, we calculate the autoclose time automatically based on the * number of words. */ /** * @cfg * An optional title for the message. */ title: null, initComponent: function() { var cls = 'bootstrap devilry_extjsextras_alertmessage'; if(this.cls) { cls += Ext.String.format('{0} {1}', cls, this.cls); } this.cls = cls; this.callParent(arguments); this.update(this.message, this.type); this.addListener({ scope: this, element: 'el', delegate: '.close', click: function(e) { e.preventDefault(); this.fireEvent('closed', this); } }); if(!Ext.isEmpty(this.autoclose)) { if(this.autoclose === true) { this.autoclose = this._calculateAutocloseTime(); } this.cancelTask = new Ext.util.DelayedTask(function(){ this.fadeOutAndClose(); }, this); this.addListener({ scope: this, element: 'el', delegate: 'div.alert', //mouseover: this._onMouseOver, mouseleave: this._onMouseLeave, mouseenter: this._onMouseEnter }); this._deferAutoclose(); } }, _deferAutoclose: function() { this.cancelTask.delay(1000*this.autoclose); }, _onMouseEnter: function() { this.cancelTask.cancel(); // We do not close the message while mouse is over it. }, _onMouseLeave: function() { this._deferAutoclose(); }, _calculateAutocloseTime: function() { var alltext = this.message; if(!Ext.isEmpty(this.title)) { alltext += this.title; } var words = Ext.String.splitWords(alltext); var sec = words.length * 0.4; // One second per work sec = sec > 3? sec: 3; // ... but never less than 3 sec return Math.round(2 + sec); // 2 seconds to focus on the message + time to read it }, fadeOutAndClose: function() { Ext.create('Ext.fx.Animator', { target: this.getEl(), duration: 3000, keyframes: { 0: { opacity: 1 }, 100: { opacity: 0.1 } }, listeners: { scope: this, afteranimate: function() { this.fireEvent('closed', this); } } }); }, /** * Update the message and optionally the type. If the type is not * specified, the type will not be changed. * */ update: function(message, type) { if(type) { this.type = type; } this.message = message; var style = ''; if(!Ext.isEmpty(this.boxMargin)) { style = Ext.String.format('margin: {0};', this.boxMargin); } this.callParent([{ type: this.type, message: this.message, title: this.title, style: style, closable: this.closable, extracls: this.closable? 'closable': '' }]); } });
JavaScript
0
@@ -1229,16 +1229,324 @@ e: '',%0A%0A + /**%0A * @cfg %7Bstring%7Carray%7D %5Bmessagetpl%5D%0A * An XTemplate string or array to use instead of %60%60message%60%60.%0A * Requires that you specify %60%60messagedata%60%60.%0A */%0A messagetpl: null,%0A%0A /**%0A * @cfg %7BObject%7D %5Bmessagedata%5D%0A * Data for %60%60messagetpl%60%60.%0A */%0A messagedata: undefined,%0A%0A %0A /** @@ -2312,19 +2312,56 @@ sage -, this.type +tpl %7C%7C this.message, this.type, this.messagedata );%0A%0A @@ -4628,24 +4628,379 @@ be changed.%0A + *%0A * @param messageOrTpl Message string, or XTemplate array/string if %60%60data%60%60 is specified.%0A * @param type The message type. Defaults to %60%60this.type%60%60 if %60%60undefined%60%60.%0A * @param data If this is specified, %60%60message%60%60 is an XTemplate config%0A * (see the %60%60messagetpl%60%60 config), and %60%60data%60%60 is the data for the%0A * template.%0A * */%0A @@ -5029,14 +5029,25 @@ sage +OrTpl , type +, data ) %7B%0A @@ -5117,31 +5117,168 @@ -this.message = message; +if(data) %7B%0A this.message = Ext.create('Ext.XTemplate', messageOrTpl).apply(data);%0A %7D else %7B%0A this.message = messageOrTpl;%0A %7D %0A
0461bd84b23ce9fe32a903e0aeb5f4f019e9b581
set url hash to contain p if on presenter view
src/remark/controllers/inputs/location.js
src/remark/controllers/inputs/location.js
exports.register = function (events, dom, slideshowView) { addLocationEventListeners(events, dom, slideshowView); }; function addLocationEventListeners (events, dom, slideshowView) { // If slideshow is embedded into custom DOM element, we don't // hook up to location hash changes, so just go to first slide. if (slideshowView.isEmbedded()) { events.emit('gotoSlide', 1); } // When slideshow is not embedded into custom DOM element, but // rather hosted directly inside document.body, we hook up to // location hash changes, and trigger initial navigation. else { events.on('hashchange', navigateByHash); events.on('slideChanged', updateHash); navigateByHash(); } function navigateByHash () { var slideNoOrName = (dom.getLocationHash() || '').substr(1); events.emit('gotoSlide', slideNoOrName); } function updateHash (slideNoOrName) { dom.setLocationHash('#' + slideNoOrName); } }
JavaScript
0.000002
@@ -1,8 +1,50 @@ +var utils = require('../../utils.js');%0D%0A%0D%0A exports. @@ -946,24 +946,176 @@ oOrName) %7B%0D%0A + if(utils.hasClass(slideshowView.containerElement, 'remark-presenter-mode'))%7B%0D%0A dom.setLocationHash('#p' + slideNoOrName);%0D%0A %7D%0D%0A else%7B%0D%0A dom.setL @@ -1145,20 +1145,27 @@ NoOrName);%0D%0A + %7D%0D%0A %7D%0D%0A%7D%0D%0A
62bdba683db73e00898033bd160809b7b87d2532
bump version
realtime-client-utils.js
realtime-client-utils.js
/** * @license * Realtime Utils 1.0.0 * https://developers.google.com/google-apps/realtime/overview * Copyright 2015 Seth Howard, Google Inc. All Rights Reserved. * Realtime Utils may be freely distributed under the Apache 2.0 license. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Common utility functionality for the Google Realtime API, * including authorization and file loading. */ /** * Create the utils namespace */ window.utils = {}; /** * @constructor * @param {!Object} options for the realtime utility. One key is mandatory: * * 1) "clientId" the client id from the APIs console. * */ utils.RealtimeUtils = function(options) { this.init(options); }; utils.RealtimeUtils.prototype = { /** * clientId for this realtime application. * @type {!string} */ clientId: null, /** * MimeType for this realtime application. * @type {!string} */ mimeType: 'application/vnd.google-apps.drive-sdk', /** * The interval at which the oauth token will attempt to be refreshed. * @type {!string} */ refreshInterval: 1800000, // 30 minutes /** * Required scopes. * @type {!Array<string>} */ scopes: [ 'https://www.googleapis.com/auth/drive.install', 'https://www.googleapis.com/auth/drive.file' ], /** * Initializes RealtimeUtils * @param {Object} options containing required utility keys. * @private */ init: function(options) { this.mergeOptions(options); this.authorizer = new utils.RealtimeAuthorizer(this); this.createRealtimeFile = this.createRealtimeFile.bind(this); }, /** * Kicks off the authorization process * @param {!Function} onAuthComplete callback invoked after authorizing. * @param {!boolean} usePopup true if authenticating via a popup window. * @export */ authorize: function(onAuthComplete, usePopup) { this.authorizer.start(onAuthComplete, usePopup); }, /** * Merges passed-in options with default options. * @param {Object} options that will be merged with existing options. * @private */ mergeOptions: function(options) { for (var option in options) { this[option] = options[option]; } }, /** * Examines url query parameters for a specific parameter. * @param {!string} urlParam to search for in url parameters. * @return {?(string)} returns match as a string or null if no match. * @export */ getParam: function(urlParam) { var regExp = new RegExp(urlParam + '=(.*?)($|&)', 'g'); var match = window.location.search.match(regExp); if (match && match.length) { match = match[0]; match = match.replace(urlParam + '=', '').replace('&', ''); } else { match = null; } return match; }, /** * Creates a new realtime file. * @param {!string} title for the new realtime document. * @param {Function} callback to be executed once the file has been created. * @export */ createRealtimeFile: function(title, callback) { var that = this; window.gapi.client.load('drive', 'v2', function() { var insertHash = { 'resource': { mimeType: that.mimeType, title: title } }; window.gapi.client.drive.files.insert(insertHash).execute(callback); }); }, /** * Loads an existing realtime file. * @param {!string} documentId for the document to load. * @param {!function(gapi.drive.realtime.Document): undefined} onFileLoaded * to be executed once the file has been loaded. * @param {!function(gapi.drive.realtime.Model): undefined} initializeModel * will be executed if this is the first time this file has been loaded. * @export */ load: function(documentId, onFileLoaded, initializeModel) { var that = this; window.gapi.drive.realtime.load(documentId, function(doc) { window.doc = doc; // Debugging purposes onFileLoaded(doc); }, initializeModel, this.onError.bind(this)); }, /** * Handles errors that occurred during document load. * @param {gapi.drive.realtime.Error} error containing specific realtime * details. * @private */ onError: function(error) { if (error.type == window.gapi.drive.realtime.ErrorType .TOKEN_REFRESH_REQUIRED) { this.authorize(function() { console.log('Error, auth refreshed'); }, false); } else if (error.type == window.gapi.drive.realtime.ErrorType .CLIENT_ERROR) { alert('An Error happened: ' + error.message); window.location.href = '/'; } else if (error.type == window.gapi.drive.realtime.ErrorType.NOT_FOUND) { alert('The file was not found. It does not exist or you do not have ' + 'read access to the file.'); window.location.href = '/'; } else if (error.type == window.gapi.drive.realtime.ErrorType.FORBIDDEN) { alert('You do not have access to this file. Try having the owner share' + 'it with you from Google Drive.'); window.location.href = '/'; } } }; /** * @constructor * @param {utils.RealtimeUtils} realtimeUtil that owns this * RealtimeAuthorizer instance. * */ utils.RealtimeAuthorizer = function(realtimeUtil) { this.util = realtimeUtil; this.handleAuthResult = this.handleAuthResult.bind(this); this.token = null; }; utils.RealtimeAuthorizer.prototype = { /** * Starts the authorizer * @param {!Function} onAuthComplete callback invoked after authorizing. * @param {boolean} usePopup true if authenticating via a popup window. * @export */ start: function(onAuthComplete, usePopup) { var that = this; window.gapi.load('auth:client,drive-realtime,drive-share', { callback: function() { that.authorize(onAuthComplete, usePopup); } }); if (this.authTimer) { window.clearTimeout(this.authTimer); } this.refreshAuth(); }, /** * Attempts to authorize. * @param {!Function} onAuthComplete callback invoked after authorizing. * @param {boolean} usePopup true if authenticating via a popup window. * @private */ authorize: function(onAuthComplete, usePopup) { this.onAuthComplete = onAuthComplete; // Try with no popups first. window.gapi.auth.authorize({ client_id: this.util.clientId, scope: this.util.scopes, immediate: !usePopup }, this.handleAuthResult); }, /** * Handles the auth result before invoking the user supplied callback. * @param {Object} authResult from the drive service containing details about * this authorization attempt. * @private */ handleAuthResult: function(authResult) { if (authResult && !authResult.error) { this.token = authResult.access_token; } this.onAuthComplete(authResult); }, /** * Sets a timer that will refresh the oauth token after an interval. * @private */ refreshAuth: function() { var that = this; this.authTimer = setInterval(function() { that.authorize(function() { console.log('Refreshed Auth Token'); }, false); }, this.util.refreshInterval); } };
JavaScript
0
@@ -31,17 +31,17 @@ ils 1.0. -0 +1 %0A * http
6f0f13016ad02400d35ffaa78f93f057e2163389
remove reference to redos as error was too damn long
no-unsafe-regex.js
no-unsafe-regex.js
var safe = require('safe-regex'); /** * Check if the regex is evil or not using the safe-regex module * @author Adam Baldwin */ //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { "use strict"; return { "Literal": function(node) { var token = context.getTokens(node)[0], nodeType = token.type, nodeValue = token.value; if (nodeType === "RegularExpression") { if (!safe(nodeValue)) { context.report(node, "Unsafe Regular Expression (https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS)"); } } } }; };
JavaScript
0
@@ -710,87 +710,8 @@ sion - (https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS) %22);%0A
0ff25fe3abf0a7b5d7f9b51eb5ae336cabbc58c4
Revert "Added listener to be able to set countdown value"
dist/angular-timer.js
dist/angular-timer.js
/** * angular-timer - v1.0.12 - 2014-02-03 9:30 PM * https://github.com/siddii/angular-timer * * Copyright (c) 2014 Siddique Hameed * Licensed MIT <https://github.com/siddii/angular-timer/blob/master/LICENSE.txt> */ angular.module('timer', []) .directive('timer', ['$compile', function ($compile) { return { restrict: 'E', replace: false, scope: { interval: '=interval', startTimeAttr: '=startTime', endTimeAttr: '=endTime', countdownattr: '=countdown', autoStart: '&autoStart' }, controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) { //angular 1.2 doesn't support attributes ending in "-start", so we're //supporting both "autostart" and "auto-start" as a solution for //backward and forward compatibility. $scope.autoStart = $attrs.autoStart || $attrs.autostart; if ($element.html().trim().length === 0) { $element.append($compile('<span>{{millis}}</span>')($scope)); } else { $element.append($compile($element.contents())($scope)); } $scope.startTime = null; $scope.endTime = null; $scope.timeoutId = null; $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) >= 0 ? parseInt($scope.countdownattr, 10) : undefined; $scope.isRunning = false; $scope.$on('timer-start', function () { $scope.start(); }); $scope.$on('timer-resume', function () { $scope.resume(); }); $scope.$on('timer-stop', function () { $scope.stop(); }); $scope.$on('timer-clear', function () { $scope.clear(); }); $scope.$on('countdown-set', function (e, countdown) { $scope.countdown = countdown; }); function resetTimeout() { if ($scope.timeoutId) { clearTimeout($scope.timeoutId); } } $scope.start = $element[0].start = function () { $scope.startTime = $scope.startTimeAttr ? new Date($scope.startTimeAttr) : new Date(); $scope.endTime = $scope.endTimeAttr ? new Date($scope.endTimeAttr) : null; $scope.countdown = $scope.countdownattr && parseInt($scope.countdownattr, 10) > 0 ? parseInt($scope.countdownattr, 10) : undefined; resetTimeout(); tick(); $scope.isRunning = true; }; $scope.resume = $element[0].resume = function () { resetTimeout(); if ($scope.countdownattr) { $scope.countdown += 1; } $scope.startTime = new Date() - ($scope.stoppedTime - $scope.startTime); tick(); $scope.isRunning = true; }; $scope.stop = $scope.pause = $element[0].stop = $element[0].pause = function () { $scope.clear(); $scope.$emit('timer-stopped', {millis: $scope.millis, seconds: $scope.seconds, minutes: $scope.minutes, hours: $scope.hours, days: $scope.days}); }; $scope.clear = $element[0].clear = function () { // same as stop but without the event being triggered $scope.stoppedTime = new Date(); resetTimeout(); $scope.timeoutId = null; $scope.isRunning = false; }; $element.bind('$destroy', function () { resetTimeout(); $scope.isRunning = false; }); function calculateTimeUnits() { $scope.seconds = Math.floor(($scope.millis / 1000) % 60); $scope.minutes = Math.floor((($scope.millis / (60000)) % 60)); $scope.hours = Math.floor((($scope.millis / (3600000)) % 24)); $scope.days = Math.floor((($scope.millis / (3600000)) / 24)); } //determine initial values of time units and add AddSeconds functionality if ($scope.countdownattr) { $scope.millis = $scope.countdownattr * 1000; $scope.addCDSeconds = $element[0].addCDSeconds = function(extraSeconds){ $scope.countdown += extraSeconds; $scope.$digest(); }; $scope.$on('timer-add-cd-seconds', function (e, extraSeconds) { $timeout(function (){ $scope.addCDSeconds(extraSeconds); }); }); } else { $scope.millis = 0; } calculateTimeUnits(); var tick = function () { $scope.millis = new Date() - $scope.startTime; var adjustment = $scope.millis % 1000; if ($scope.endTimeAttr) { $scope.millis = $scope.endTime - new Date(); adjustment = $scope.interval - $scope.millis % 1000; } if ($scope.countdownattr) { $scope.millis = $scope.countdown * 1000; } if ($scope.millis < 0) { $scope.stop(); $scope.millis = 0; calculateTimeUnits(); return; } calculateTimeUnits(); if ($scope.countdown > 0) { $scope.countdown--; } else if ($scope.countdown <= 0) { $scope.stop(); return; } //We are not using $timeout for a reason. Please read here - https://github.com/siddii/angular-timer/pull/5 $scope.timeoutId = setTimeout(function () { tick(); $scope.$digest(); }, $scope.interval - adjustment); $scope.$emit('timer-tick', {timeoutId: $scope.timeoutId, millis: $scope.millis}); }; if ($scope.autoStart === undefined || $scope.autoStart === true) { $scope.start(); } }] }; }]);
JavaScript
0
@@ -1768,131 +1768,8 @@ );%0A%0A - $scope.$on('countdown-set', function (e, countdown) %7B%0A $scope.countdown = countdown;%0A %7D);%0A %0A
97cd5dd0b8392d5b0e142c22cbda42c597da794e
add ie 11 support
profiles/build.profile.js
profiles/build.profile.js
/* eslint-disable no-unused-vars */ var profile = { basePath: '../src', action: 'release', cssOptimize: 'comments', mini: true, optimize: false, layerOptimize: false, selectorEngine: 'acme', layers: { 'dojo/dojo': { include: [ 'dojo/i18n', 'dojo/domReady', 'app/packages', 'app/run', 'app/App', 'esri/layers/VectorTileLayerImpl', 'dojox/gfx/filters', 'dojox/gfx/path', 'dojox/gfx/svg', 'dojox/gfx/svgext', 'dojox/gfx/shape' ], includeLocales: ['en-us'], customBase: true, boot: true }, 'ijit/widgets/authentication/UserAdmin': { exclude: ['dojo/dojo'] } }, packages: [{ name: 'proj4', trees: [ // don't bother with .hidden, tests, min, src, and templates ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|html)/] ], resourceTags: { amd: function amd() { return true; }, copyOnly: function copyOnly() { return false; } } }, { name: 'moment', location: 'moment', main: 'moment', trees: [ // don't bother with .hidden, tests, min, src, and templates ['.', '.', /(\/\.)|(~$)|(test|txt|src|min|templates)/] ], resourceTags: { amd: function amd(filename, mid) { return /\.js$/.test(filename); } } }], staticHasFeatures: { // The trace & log APIs are used for debugging the loader, so we don’t need them in the build 'dojo-trace-api': 0, 'dojo-log-api': 0, // This causes normally private loader data to be exposed for debugging, so we don’t need that either 'dojo-publish-privates': 0, // We’re fully async, so get rid of the legacy loader 'dojo-sync-loader': 0, // dojo-xhr-factory relies on dojo-sync-loader 'dojo-xhr-factory': 0, // We aren’t loading tests in production 'dojo-test-sniff': 0 }, userConfig: { packages: ['app', 'dijit', 'dojox', 'agrc', 'ijit', 'esri', 'layer-selector', 'sherlock'] } };
JavaScript
0
@@ -2251,16 +2251,111 @@ -sniff': + 0,%0A%0A // ie 11 support%0A 'dojo-guarantee-console': 1,%0A 'console-as-object': 0%0A %7D
bd7ead7f5965b2e295b79596bbf1af7d38ae5cb7
Update player-interaction.js
src/player-interaction.js
src/player-interaction.js
const rx = require('rx'); const _ = require('underscore-plus'); class PlayerInteraction { // Public: Poll players that want to join the game during a specified period // of time. // // messages - An {Observable} representing new messages sent to the channel // channel - The {Channel} object, used for posting messages // scheduler - (Optional) The scheduler to use for timing events // timeout - (Optional) The amount of time to conduct polling, in seconds // maxPlayers - (Optional) The maximum number of players to allow // // Returns an {Observable} that will `onNext` for each player that joins and // `onCompleted` when time expires or the max number of players join. static pollPotentialPlayers(messages, channel, scheduler=rx.Scheduler.timeout, timeout=10, maxPlayers=10) { let formatMessage = t => `Who wants to play? Respond with 'yes' in this channel in the next ${t} seconds.`; let timeExpired = PlayerInteraction.postMessageWithTimeout(channel, formatMessage, scheduler, timeout); // Look for messages containing the word 'yes' and map them to a unique // user ID, constrained to `maxPlayers` number of players. let newPlayers = messages.where(e => e.text && e.text.toLowerCase().match(/\byes\b/)) .map(e => e.user) .distinct() .take(maxPlayers) .publish(); newPlayers.connect(); timeExpired.connect(); // Once our timer has expired, we're done accepting new players. return newPlayers.takeUntil(timeExpired); } // Public: Poll a specific player to take a poker action, within a timeout. // // messages - An {Observable} representing new messages sent to the channel // channel - The {Channel} object, used for posting messages // player - The player being polled // previousActions - A map of players to their most recent action // scheduler - (Optional) The scheduler to use for timing events // timeout - (Optional) The amount of time to conduct polling, in seconds // // Returns an {Observable} indicating the action the player took. If time // expires, a 'timeout' action is returned. static getActionForPlayer(messages, channel, player, previousActions, scheduler=rx.Scheduler.timeout, timeout=30) { let availableActions = PlayerInteraction.getAvailableActions(player, previousActions); let formatMessage = t => PlayerInteraction.buildActionMessage(player, availableActions, t); let timeExpired = null; let expiredDisp = null; if (timeout > 0) { timeExpired = PlayerInteraction.postMessageWithTimeout(channel, formatMessage, scheduler, timeout); expiredDisp = timeExpired.connect(); } else { channel.send(formatMessage(0)); timeExpired = rx.Observable.never(); expiredDisp = rx.Disposable.empty; } // Look for text that conforms to a player action. let playerAction = messages.where(e => e.user === player.id) .map(e => PlayerInteraction.actionFromMessage(e.text, availableActions)) .where(action => action !== null) .publish(); playerAction.connect(); // If the user times out, they will be auto-folded unless they can check. let actionForTimeout = timeExpired.map(() => availableActions.indexOf('check') > -1 ? { name: 'check' } : { name: 'fold' }); let botAction = player.isBot ? player.getAction(availableActions, previousActions) : rx.Observable.never(); // NB: Take the first result from the player action, the timeout, and a bot // action (only applicable to bots). return rx.Observable.merge(playerAction, actionForTimeout, botAction) .take(1) .do(() => expiredDisp.dispose()); } // Private: Posts a message to the channel with some timeout, that edits // itself each second to provide a countdown. // // channel - The channel to post in // formatMessage - A function that will be invoked once per second with the // remaining time, and returns the formatted message content // scheduler - The scheduler to use for timing events // timeout - The duration of the message, in seconds // // Returns an {Observable} sequence that signals expiration of the message static postMessageWithTimeout(channel, formatMessage, scheduler, timeout) { let timeoutMessage = channel.send(formatMessage(timeout)); let timeExpired = rx.Observable.timer(0, 1000, scheduler) .take(timeout + 1) .do((x) => timeoutMessage.updateMessage(formatMessage(`${timeout - x}`))) .publishLast(); return timeExpired; } // Private: Builds up a formatted countdown message containing the available // actions. // // player - The player who is acting // availableActions - An array of the actions available to this player // timeRemaining - Number of seconds remaining for the player to act // // Returns the formatted string static buildActionMessage(player, availableActions, timeRemaining) { let message = `${player.name}, it's your turn. Respond with:\n`; for (let action of availableActions) { message += `*(${action.charAt(0).toUpperCase()})${action.slice(1)}*\t`; } if (timeRemaining > 0) { message += `\nin the next ${timeRemaining} seconds.`; } return message; } // Private: Given an array of actions taken previously in the hand, returns // an array of available actions. // // player - The player who is acting // previousActions - A map of players to their most recent action // // Returns an array of strings static getAvailableActions(player, previousActions) { let actions = _.values(previousActions); let betActions = _.filter(actions, a => a.name === 'bet' || a.name === 'raise'); let hasBet = betActions.length > 0; let availableActions = []; if (player.hasOption) { availableActions.push('check'); availableActions.push('raise'); } else if (hasBet) { availableActions.push('call'); availableActions.push('raise'); } else { availableActions.push('check'); availableActions.push('bet'); } // Prevent players from raising when they don't have enough chips. let raiseIndex = availableActions.indexOf('raise'); if (raiseIndex > -1) { let previousWager = player.lastAction ? player.lastAction.amount : 0; let availableChips = player.chips + previousWager; if (_.max(betActions, a => a.amount).amount >= availableChips) { availableActions.splice(raiseIndex, 1); } } availableActions.push('fold'); return availableActions; } // Private: Parse player input into a valid action. // // text - The text that the player entered // availableActions - An array of the actions available to this player // // Returns an object representing the action, with keys for the name and // bet amount, or null if the input was invalid. static actionFromMessage(text, availableActions) { if (!text) return null; let input = text.trim().toLowerCase().split(/\s+/); if (!input[0]) return null; let name = ''; let amount = 0; switch (input[0]) { case 'c': name = availableActions[0]; break; case 'call': name = 'call'; break; case 'check': name = 'check'; break; case 'f': case 'fold': name = 'fold'; break; case 'b': case 'bet': name = 'bet'; amount = input[1] ? parseInt(input[1]) : NaN; break; case 'r': case 'raise': name = 'raise'; amount = input[1] ? parseInt(input[1]) : NaN; break; default: return null; } // NB: Unavailable actions are always invalid. return availableActions.indexOf(name) > -1 ? { name: name, amount: amount } : null; } } module.exports = PlayerInteraction;
JavaScript
0.000001
@@ -779,17 +779,17 @@ timeout= -1 +2 0, maxPl
feae9ad0a82b3e4f5755a8dc5607005c4cb0441b
Add regression test for scry order
src/test/__tests__/ReactTestUtils-test.js
src/test/__tests__/ReactTestUtils-test.js
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var React; var ReactTestUtils; var mocks; var warn; describe('ReactTestUtils', function() { beforeEach(function() { mocks = require('mocks'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); warn = console.warn; console.warn = mocks.getMockFunction(); }); afterEach(function() { console.warn = warn; }); it('should have shallow rendering', function() { var SomeComponent = React.createClass({ render: function() { return ( <div> <span className="child1" /> <span className="child2" /> </div> ); } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />, {}); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ <span className="child1" />, <span className="child2" /> ]); }); it('should have shallow unmounting', function() { var componentWillUnmount = mocks.getMockFunction(); var SomeComponent = React.createClass({ render: function() { return <div />; }, componentWillUnmount }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />, {}); shallowRenderer.unmount(); expect(componentWillUnmount).toBeCalled(); }); it('can shallow render to null', function() { var SomeComponent = React.createClass({ render: function() { return null; } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />, {}); var result = shallowRenderer.getRenderOutput(); expect(result).toBe(null); }); it('lets you update shallowly rendered components', function() { var SomeComponent = React.createClass({ getInitialState: function() { return {clicked: false}; }, onClick: function() { this.setState({clicked: true}); }, render: function() { var className = this.state.clicked ? 'was-clicked' : ''; if (this.props.aNew === 'prop') { return ( <a href="#" onClick={this.onClick} className={className}> Test link </a> ); } else { return ( <div> <span className="child1" /> <span className="child2" /> </div> ); } } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />, {}); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ <span className="child1" />, <span className="child2" /> ]); shallowRenderer.render(<SomeComponent aNew="prop" />, {}); var updatedResult = shallowRenderer.getRenderOutput(); expect(updatedResult.type).toBe('a'); var mockEvent = {}; updatedResult.props.onClick(mockEvent); var updatedResultCausedByClick = shallowRenderer.getRenderOutput(); expect(updatedResultCausedByClick.type).toBe('a'); expect(updatedResultCausedByClick.props.className).toBe('was-clicked'); }); it('Test scryRenderedDOMComponentsWithClass with TextComponent', function() { var renderedComponent = ReactTestUtils.renderIntoDocument(<div>Hello <span>Jim</span></div>); var scryResults = ReactTestUtils.scryRenderedDOMComponentsWithClass( renderedComponent, 'NonExistantClass' ); expect(scryResults.length).toBe(0); }); });
JavaScript
0
@@ -4017,13 +4017,656 @@ ;%0A%0A %7D); +%0A%0A it('traverses children in the correct order', function() %7B%0A var container = document.createElement('div');%0A%0A React.render(%0A %3Cdiv%3E%0A %7Bnull%7D%0A %3Cdiv%3Epurple%3C/div%3E%0A %3C/div%3E,%0A container%0A );%0A var tree = React.render(%0A %3Cdiv%3E%0A %3Cdiv%3Eorange%3C/div%3E%0A %3Cdiv%3Epurple%3C/div%3E%0A %3C/div%3E,%0A container%0A );%0A%0A var log = %5B%5D;%0A ReactTestUtils.findAllInRenderedTree(tree, function(child) %7B%0A log.push(child.getDOMNode().textContent);%0A %7D);%0A%0A // Should be document order, not mount order (which would be purple, orange)%0A expect(log).toEqual(%5B'orangepurple', 'orange', 'purple'%5D);%0A %7D); %0A%7D);%0A
a965e2d7021b8a742ab870bab2eafabb127e7373
Add cache, remove board/thread history
src/redux/initialState.js
src/redux/initialState.js
import { details as settingDetails } from './settings' export default { status: { alertMessage: null, // reveal status to user provider: '4chan', boardID: null, threadID: null, }, display: { isAppReady: false, isScrolling: false, // app scroll isHeaderVisible: true, isNavbarOpen: false, isDrawerOpen: true, isThreadOpen: false, activeHeaderPanel: null, // responses to header buttons }, boardList: { didInvalidate: false, favourites: [] // [{id:'4chan', board: 'g'}, ...] }, board: { receivedAt: 0, // unix timestamp isFetching: false, didInvalidate: false, searchWord: null, filterWords: [], posts: [], limit: 30 // infinite scroll }, boardHistory: { }, thread: { receivedAt: 0, // unix timestamp isActive: false, isFetching: false, didInvalidate: false, isBeingWatched: false, posts: [], }, threadHistory: { }, threadMonitor: { newPosts: 0, threads: [ // e.g. {threadID, boardID, posts} ] }, post: { isAuthenticated: false, type: null, // thread/comment references: [], message: null, // user input upload: null // canReply }, settings: { internal: { requestThrottle: 3, maxBoardAge: 900, // 15 mins maxThreadAge: 900, // 15 mins }, external: { theme: 'dark', homeBoard: 'g', nsfw: false, downloadLocation: '~/Downloads/Lurka', boardUpdateInterval: 15, threadUpdateInterval: 5, autoMute: false }, details: settingDetails } }
JavaScript
0.000003
@@ -601,24 +601,84 @@ ..%5D%0A %7D,%0A%0A + cache: %7B%0A board: %7B %7D,%0A thread: %7B %7D%0A %7D,%0A %0A board: @@ -898,32 +898,8 @@ %7D,%0A%0A - boardHistory: %7B %7D,%0A%0A @@ -1094,33 +1094,8 @@ %7D,%0A%0A - threadHistory: %7B %7D,%0A%0A @@ -1208,24 +1208,24 @@ %5D%0A + %7D,%0A%0A %0A pos @@ -1216,17 +1216,16 @@ %7D,%0A%0A -%0A post
781ba7615988cd1950f26b1cc4b339375d85daf3
update login form
src/routes/login/index.js
src/routes/login/index.js
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Button, Row, Form, Input } from 'antd' import { config } from 'utils' import styles from './index.less' const FormItem = Form.Item const Login = ({ loading, dispatch, form: { getFieldDecorator, validateFieldsAndScroll, }, }) => { function handleOk () { validateFieldsAndScroll((errors, values) => { if (errors) { return } dispatch({ type: 'login/login', payload: values }) }) } return ( <div className={styles.form}> <div className={styles.logo}> <img alt={'logo'} src={config.logo} /> <span>{config.name}</span> </div> <form> <FormItem hasFeedback> {getFieldDecorator('account', { rules: [ { required: true, message: '请输入账号', }, ], })(<Input size="large" onPressEnter={handleOk} placeholder="账号" />)} </FormItem> <FormItem hasFeedback> {getFieldDecorator('password', { rules: [ { required: true, message: '请输入密码', }, ], })(<Input size="large" type="password" onPressEnter={handleOk} placeholder="密码" />)} </FormItem> <Row> <Button type="primary" size="large" onClick={handleOk} loading={loading.effects.login}> 登陆 </Button> </Row> </form> </div> ) } Login.propTypes = { form: PropTypes.object, dispatch: PropTypes.func, loading: PropTypes.object, } export default connect(({ loading }) => ({ loading }))(Form.create()(Login))
JavaScript
0
@@ -778,17 +778,17 @@ orator(' -a +A ccount', @@ -1085,17 +1085,17 @@ orator(' -p +P assword'
e1686fd7edc0000099cdfd60f5a268f0cd0b368e
Make package-get route asynchronous
src/routes/package-get.js
src/routes/package-get.js
export default class { constructor(storage, validator) { this.storage = storage; this.packageValidator = validator; } /* * Reads package data from fileystem and sends it to npm-client */ process(httpRequest, httpResponse) { let packageName = httpRequest['params']['package']; let fileName = httpRequest['params']['filename']; let fileData = this.storage.getPackage(packageName, fileName); httpResponse.send(fileData); } }
JavaScript
0.000008
@@ -235,24 +235,64 @@ Response) %7B%0A + return new Promise((resolve) =%3E %7B%0A let pack @@ -331,24 +331,26 @@ 'package'%5D;%0A + let file @@ -399,22 +399,9 @@ -let fileData = + thi @@ -447,15 +447,34 @@ ame) -;%0A%0A +.then((data) =%3E %7B%0A + http @@ -491,16 +491,49 @@ end( -fileData +data);%0A resolve();%0A %7D);%0A %7D );%0A
05bf70fc033ffa60cc9eb4391ac5d6c3e557c482
Update AgarMacros.js
src/scripts/AgarMacros.js
src/scripts/AgarMacros.js
// ==UserScript== // @name 13 macro's for Agar.io :) // @version 0.5 // @description 13 macro's. For feeding, linesplits, tricksplits, etc :) // @author Megabyte918 // @match *.agar.io/* // ==/UserScript== window.addEventListener('keydown', keydown); window.addEventListener('keyup', keyup); document.getElementById("nick").maxLength = "9e9"; // List instructions var i = document.getElementById("instructions"); i.innerHTML += "<center class='text-muted'>Hold <b>W</b> for macro feed</center>"; i.innerHTML += "<center class='text-muted'>Press <b>Shift</b> or <b>4</b> to split 4x</center>"; i.innerHTML += "<center class='text-muted'>Press <b>A</b> or <b>3</b> to split 3x</center>"; i.innerHTML += "<center class='text-muted'>Press <b>D</b> or <b>2</b> to split 2x</center>"; i.innerHTML += "<center class='text-muted'>Press <b>S</b> or <b>1</b> to split 1x</center>"; i.innerHTML += "<center class='text-muted'>Press <b>H</b> for horizontal linesplit</center>"; i.innerHTML += "<center class='text-muted'>Press <b>V</b> for vertical linesplit</center>"; i.innerHTML += "<center class='text-muted'>Press <b>C</b> for popsplit macro</center>"; i.innerHTML += "<center class='text-muted'>Press <b>F</b> for solo-tricksplit</center>"; // Load macros var time = 35; var canFeed = false; function keydown(event) { if (event.keyCode == 87) { // Feeding Macro (w) canFeed = true; feed(); } if (event.keyCode == 70) { // Solo-tricksplit (f) for (var f2 = 0; f2 < 4; f2++) { setTimeout(function() { split(); $("body").trigger($.Event("keydown", { keyCode: 87})); $("body").trigger($.Event("keyup", { keyCode: 87})); }, time); time *= 2; } } if (event.keyCode == 67) { // Popsplit macro (C) split(); setTimeout(split, Math.random() * (350 - 200) + 200); } if (event.keyCode == 49 || event.keyCode == 83) { // Space macro (s or 1) split(); } if (event.keyCode == 16 || event.keyCode == 52) { // Tricksplit Macro (shift or 4) for (var e2 = 0; e2 < 4; e2++) { setTimeout(split, time); time *= 2; } } if (event.keyCode == 65 || event.keyCode == 51) { // Triplesplit Macro (a or 3) for (var a2 = 0; a2 < 3; a2++) { setTimeout(split, time); time *= 2; } } if (event.keyCode == 68 || event.keyCode == 50) { // Doublesplit Macro (d or 2) split(); setTimeout(split, 50); } if (event.keyCode == 72) { // Horizontal linesplit (h) X = window.innerWidth / 2; Y = window.innerHeight / 2; $("canvas").trigger($.Event("mousemove", {clientX: X, clientY: Y})); } if (event.keyCode == 86) { // Vertical linesplit (v) X = window.innerWidth / 2; Y = window.innerHeight / 2.006; $("canvas").trigger($.Event("mousemove", {clientX: X, clientY: Y})); } } // When a player lets go of W stop feeding function keyup(event) { if (event.keyCode == 87) canFeed = false; } // Alias for W key function feed() { if (!canFeed) return; window.onkeydown({keyCode: 87}); window.onkeyup({keyCode: 87}); setTimeout(feed, 0); } // Alias for space function split() { $("body").trigger($.Event("keydown", { keyCode: 32})); $("body").trigger($.Event("keyup", { keyCode: 32})); }
JavaScript
0
@@ -1277,23 +1277,8 @@ ros%0A -var time = 35;%0A var @@ -1509,26 +1509,23 @@ var -f2 +a = 0; -f2 +a %3C 4; -f2 +a ++) @@ -1746,36 +1746,15 @@ %7D, -time);%0A time *= 2 +a * 50) ;%0A @@ -2138,43 +2138,26 @@ var -e2 +b = 0; -e2 +b %3C 4; -e2 +b ++) - %7B%0A set @@ -2175,47 +2175,16 @@ it, -time);%0A time *= 2;%0A %7D +b * 50); %0A @@ -2299,43 +2299,26 @@ var -a2 +c = 0; -a2 +c %3C 3; -a2 +c ++) - %7B%0A set @@ -2336,47 +2336,16 @@ it, -time);%0A time *= 2;%0A %7D +c * 50); %0A
81e725f4709e540ab4445d8c6011dd61c8c5e8f0
Fix type
renderer/types/manage.js
renderer/types/manage.js
// @flow export type ModalType = | 'DEFAULT' | 'ADD_COLUMN' | 'FILTER_TAG' | 'SEARCH'; export type ManageFilter = { r18: bool, tags: Array<string> }; export type Manage = { isLogin: bool, isModal: bool, isImageView: bool, isImgLoaded: bool, isMangaView: bool, isDropdown: bool, currentWorkId: ?number, currentColumn: number, filter: ManageFilter, modalType: ModalType }; export type ManageAction = | {type: 'OPEN_IMAGE_VIEW'} | {type: 'CLOSE_IMAGE_VIEW'} | {type: 'OPEN_MANGA_PREVIEW'} | {type: 'CLOSE_MANGA_PREVIEW'} | {type: 'OPEN_MODAL', modal?: ModalType} | {type: 'CLOSE_MODAL'} | {type: 'OPEN_DROPDOWN'} | {type: 'CLOSE_DROPDOWN'} | {type: 'TOGGLE_DROPDOWN'} | {type: 'SELECT_WORK', id: number} | {type: 'LOGIN', name: string, password: string} | {type: 'LOGOUT'} | {type: 'CLOSE_ALL'} | {type: 'REMOVE_TAG_FILTER', tag: string} | {type: 'ADD_TAG_FILTER', tag: string} | {type: 'SET_R18', show: bool} | {type: 'START_IMG_LOADING'} | {type: 'SET_IMG_LOADED'} ;
JavaScript
0.000001
@@ -310,32 +310,8 @@ er,%0A -%09currentColumn: number,%0A %09fil
6304bd2e82506fcc07f486b140af96f01321b703
Check status of page opening
src/scripts/screenshot.js
src/scripts/screenshot.js
(function () { "use strict"; /* Modules & Constants */ var DEF_ZOOM = 1, DEF_QUALITY = 1, DEF_DELAY = 100, DEF_WIDTH = 1024, DEF_HEIGHT = 768, DEF_JS_ENABLED = true, DEF_IMAGES_ENABLED = true, DEF_FORMAT = 'png', DEF_HEADERS = {}, DEF_STYLES = 'body { background: #fff; }'; /* Common functions */ function isPhantomJs() { return console && console.log; } function argument(index) { var delta = isPhantomJs() ? 1 : 0; return system.args[index + delta]; } function log(message) { if (isPhantomJs()) { console.log(message); } else { system.stdout.write(message); } } function exit(page, e) { if (e) { log('Error: ' + e); } if (page) { page.close(); } phantom.exit(); } function def(o, d) { return ((o === null) || (typeof (o) === "undefined")) ? d : o; } function parseOptions(base64) { var optionsJSON = window.atob(base64); log('Script options: ' + optionsJSON); return JSON.parse(optionsJSON); } /* Web page creation */ function pageViewPortSize(options) { return { width: def(options.width, DEF_WIDTH), height: def(options.height, DEF_HEIGHT) }; } function pageSettings(options) { return { javascriptEnabled: def(options.js, DEF_JS_ENABLED), loadImages: def(options.images, DEF_IMAGES_ENABLED), userName: options.user, password: options.password, userAgent: options.agent }; } function pageClipRect(options) { var cr = options.clipRect; return (cr && cr.top && cr.left && cr.width && cr.height) ? cr : null; } function pageQuality(options, format) { // XXX: Quality parameter doesn't work for PNG files. if (format !== 'png') { var quality = def(options.quality, DEF_QUALITY); return isPhantomJs() ? String(quality * 100) : quality; } return null; } function createPage(options) { var page = webpage.create(), clipRect = pageClipRect(options); page.zoomFactor = def(options.zoom, DEF_ZOOM); page.customHeaders = def(options.headers, DEF_HEADERS); page.viewportSize = pageViewPortSize(options); page.settings = pageSettings(options); if (clipRect) { page.clipRect = clipRect; } return page; } /* Screenshot rendering */ function renderScreenshotFile(page, options, outputFile, onFinish) { var delay = def(options.delay, DEF_DELAY), format = def(options.format, DEF_FORMAT), quality = pageQuality(options, format); setTimeout(function () { try { var renderOptions = { onlyViewport: !!options.height, quality: quality, format: format }; page.render(outputFile, renderOptions); log('Rendered screenshot: ' + outputFile); onFinish(page); } catch (e) { onFinish(page, e); } }, delay); } function captureScreenshot(base64, outputFile, onFinish) { try { var options = parseOptions(base64), page = createPage(options); page.open(options.url, function () { try { addStyles(page, DEF_STYLES); renderScreenshotFile(page, options, outputFile, onFinish); } catch (e) { onFinish(page, e); } }); } catch (e) { onFinish(null, e); } } function addStyles(page, styles) { page.evaluate(function(styles) { var style = document.createElement('style'), content = document.createTextNode(styles), head = document.head; style.setAttribute('type', 'text/css'); style.appendChild(content); head.insertBefore(style, head.firstChild); }, styles); } /* Fire starter */ var system = require('system'), webpage = require('webpage'), base64 = argument(0), outputFile = argument(1); captureScreenshot(base64, outputFile, exit); })();
JavaScript
0
@@ -3582,36 +3582,143 @@ .url, function ( +status ) %7B%0A + if (status !== 'success') %7B%0A exit();%0A %7D else %7B%0A @@ -3743,16 +3743,20 @@ + + addStyle @@ -3772,24 +3772,28 @@ EF_STYLES);%0A + @@ -3867,32 +3867,36 @@ + + %7D catch (e) %7B%0A @@ -3885,32 +3885,36 @@ %7D catch (e) %7B%0A + @@ -3928,32 +3928,54 @@ inish(page, e);%0A + %7D%0A
72a5ce61edba72c0a2e404792bb70590c08e938f
Update fix-s22pdf.js example script to accept pages with no fonts.
docs/examples/fix-s22pdf.js
docs/examples/fix-s22pdf.js
// A simple script to fix the broken fonts in PDF files generated by S22PDF. if (scriptArgs.length != 2) { print("usage: mutool run fix-s22pdf.js input.pdf output.pdf"); quit(); } var doc = new PDFDocument(scriptArgs[0]); var font = new Font("zh-Hans"); var song = doc.addCJKFont(font, "zh-Hans", "H", "serif"); var heiti = doc.addCJKFont(font, "zh-Hans", "H", "sans-serif"); song.Encoding = 'GBK-EUC-H'; heiti.Encoding = 'GBK-EUC-H'; var MAP = { "/#CB#CE#CC#E5": song, // SimSun "/#BA#DA#CC#E5": heiti, // SimHei "/#BF#AC#CC#E5_GB2312": song, // SimKai "/#B7#C2#CB#CE_GB2312": heiti, // SimFang "/#C1#A5#CA#E9": song, // SimLi } var i, n = doc.countPages(); for (i = 0; i < n; ++i) { var fonts = doc.findPage(i).Resources.Font; fonts.forEach(function (name, font) { if (font.BaseFont in MAP && font.Encoding == 'WinAnsiEncoding') fonts[name] = MAP[font.BaseFont]; }); } doc.save(scriptArgs[1]);
JavaScript
0
@@ -735,16 +735,31 @@ s.Font;%0A +%09if (fonts) %7B%0A%09 %09fonts.f @@ -789,16 +789,17 @@ font) %7B%0A +%09 %09%09if (fo @@ -859,16 +859,17 @@ ng')%0A%09%09%09 +%09 fonts%5Bna @@ -898,13 +898,17 @@ t%5D;%0A +%09 %09%7D);%0A +%09%7D%0A %7D%0A%0Ad
938f9aeb264bbaf98b7cbf1e840bb75793b6de19
update inline example. fix #584
docs/examples/inline-bot.js
docs/examples/inline-bot.js
const Telegraf = require('telegraf') const fetch = require('node-fetch') // async/await example. async function spotifySearch (query = '', offset, limit) { const apiUrl = `https://api.spotify.com/v1/search?type=track&limit=${limit}&offset=${offset}&q=${encodeURIComponent(query)}` const response = await fetch(apiUrl) const { tracks } = await response.json() return tracks.items } const bot = new Telegraf(process.env.BOT_TOKEN) bot.on('inline_query', async ({ inlineQuery, answerInlineQuery }) => { const offset = parseInt(inlineQuery.offset) || 0 const tracks = await spotifySearch(inlineQuery.query, offset, 30) const results = tracks.map((track) => ({ type: 'audio', id: track.id, title: track.name, audio_url: track.preview_url })) return answerInlineQuery(results, { next_offset: offset + 30 }) }) bot.launch()
JavaScript
0.000002
@@ -107,23 +107,20 @@ unction -spotify +omdb Search ( @@ -133,23 +133,8 @@ = '' -, offset, limit ) %7B%0A @@ -159,111 +159,53 @@ http -s :// -api.spotify.com/v1/search?type=track&limit=$%7Blimit%7D&offset=$%7Boffset%7D&q=$%7BencodeURIComponent(query)%7D +www.omdbapi.com/?s=$%7Bquery%7D&apikey=9699cca %60%0A @@ -253,18 +253,12 @@ nst -%7B tracks %7D +json = a @@ -284,27 +284,145 @@ )%0A -return tracks.items +const posters = (json.Search && json.Search) %7C%7C %5B%5D%0A return posters.filter((%7B Poster %7D) =%3E Poster && Poster.startsWith('https://')) %7C%7C %5B%5D %0A%7D%0A%0A @@ -600,21 +600,22 @@ const -track +poster s = awai @@ -620,15 +620,12 @@ ait -spotify +omdb Sear @@ -680,25 +680,27 @@ s = -track +poster s.map(( -track +poster ) =%3E @@ -714,20 +714,20 @@ type: ' -audi +phot o',%0A @@ -734,73 +734,139 @@ id: -track.id,%0A title: track.nam +poster.imdbID,%0A caption: poster.Title,%0A description: poster.Titl e,%0A -audio +thumb _url: -track.preview_url +poster.Poster,%0A photo_url: poster.Poster %0A %7D
4b620e0f3ccf0b2ee1cc0ac52d8bda0449d52079
fix bug
repo/ensure-directory.js
repo/ensure-directory.js
var fs = require("fs") var path = require("path") var env = require("process").env var async = require("gens") var both = require("gens/both") // ensureDirectory := () => Continuable<String> // ensureDirectory returns the directory where profiles are stored module.exports = async(ensureDirectory) function* ensureDirectory() { var configDir = path.join(home(), ".config") var configDirStat = yield both(fs.stat.bind(null, configDir)) if (configDirStat[0]) { yield fs.mkdir.bind(null, configDir) } var processDashDir = path.join(configDir, processDashDirectory()) var processDashDirStat = yield both(fs.stat.bind(null, processDashDir)) if (processDashDirStat[0]) { yield fs.mkdir.bind(null, processDashDir) } return processDashDir } function processDashDirectory() { return env.processDash_DIRECTORY || "process-dash" } function home() { return env.HOME || env.HOMEPATH || env.USERPROFILE }
JavaScript
0.000001
@@ -834,27 +834,21 @@ urn env. -processDash +PDASH _DIRECTO
45dec81ed25c11ad39d0793d654575b631fb808c
Remove superfluous duplicate prop. Part of STRIPES-266.
ViewUser.js
ViewUser.js
import _ from 'lodash'; // We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { Component, PropTypes } from 'react'; import Route from 'react-router-dom/Route'; import Pane from '@folio/stripes-components/lib/Pane'; import PaneMenu from '@folio/stripes-components/lib/PaneMenu'; import Button from '@folio/stripes-components/lib/Button'; import KeyValue from '@folio/stripes-components/lib/KeyValue'; import { Row, Col } from 'react-bootstrap'; import TextField from '@folio/stripes-components/lib/TextField'; import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList'; import Icon from '@folio/stripes-components/lib/Icon'; import Layer from '@folio/stripes-components/lib/Layer'; import IfPermission from '@folio/stripes-components/lib/IfPermission'; import UserForm from './UserForm'; import UserPermissions from './UserPermissions'; import UserLoans from './UserLoans'; import LoansHistory from './LoansHistory'; class ViewUser extends Component { static propTypes = { stripes: PropTypes.shape({ hasPerm: PropTypes.func.isRequired, connect: PropTypes.func.isRequired, }).isRequired, data: PropTypes.shape({ user: PropTypes.arrayOf(PropTypes.object), availablePermissions: PropTypes.arrayOf(PropTypes.object), }), mutator: React.PropTypes.shape({ users: React.PropTypes.shape({ PUT: React.PropTypes.func.isRequired, }), }), match: PropTypes.shape({ path: PropTypes.string.isRequired, }).isRequired, }; static manifest = Object.freeze({ users: { type: 'okapi', path: 'users/:{userid}', clear: false, }, availablePermissions: { type: 'okapi', records: 'permissions', path: 'perms/permissions?length=100', }, usersPermissions: { type: 'okapi', records: 'permissionNames', DELETE: { pk: 'permissionName', path: 'perms/users/:{username}/permissions', }, GET: { path: 'perms/users/:{username}/permissions?full=true', }, path: 'perms/users/:{username}/permissions', }, patronGroups: { type: 'okapi', path: 'groups', records: 'usergroups', pk: '_id', }, }); constructor(props) { super(props); this.state = { editUserMode: false, viewLoansHistoryMode: false, }; this.onClickEditUser = this.onClickEditUser.bind(this); this.onClickCloseEditUser = this.onClickCloseEditUser.bind(this); this.connectedUserLoans = props.stripes.connect(UserLoans); this.connectedLoansHistory = props.stripes.connect(LoansHistory); this.onClickViewLoansHistory = this.onClickViewLoansHistory.bind(this); this.onClickCloseLoansHistory = this.onClickCloseLoansHistory.bind(this); } // EditUser Handlers onClickEditUser(e) { if (e) e.preventDefault(); this.setState({ editUserMode: true, }); } onClickCloseEditUser(e) { if (e) e.preventDefault(); this.setState({ editUserMode: false, }); } onClickViewLoansHistory(e) { if (e) e.preventDefault(); this.setState({ viewLoansHistoryMode: true, }); } onClickCloseLoansHistory(e) { if (e) e.preventDefault(); this.setState({ viewLoansHistoryMode: false, }); } update(data) { // eslint-disable-next-line no-param-reassign if (data.creds) delete data.creds; // not handled on edit (yet at least) this.props.mutator.users.PUT(data).then(() => { this.onClickCloseEditUser(); }); } render() { const fineHistory = [{ 'Due Date': '11/12/2014', Amount: '34.23', Status: 'Unpaid' }]; const { data: { users, availablePermissions, usersPermissions, patronGroups }, match: { params: { userid } } } = this.props; const detailMenu = (<PaneMenu> <IfPermission {...this.props} perm="users.edit"> <button onClick={this.onClickEditUser} title="Edit User"><Icon icon="edit" />Edit</button> </IfPermission> </PaneMenu>); if (!users || users.length === 0 || !userid) return <div />; if (!this.props.stripes.hasPerm('users.read.basic')) { return (<div> <h2>Permission Error</h2> <p>Sorry - your user permissions do not allow access to this page.</p> </div>); } const user = users.find(u => u.id === userid); if (!user) return <div />; const userStatus = (_.get(user, ['active'], '') ? 'active' : 'inactive'); const patronGroupId = _.get(user, ['patron_group'], ''); const patronGroup = patronGroups.find(g => g._id === patronGroupId) || { group: '' }; return ( <Pane defaultWidth="fill" paneTitle="User Details" lastMenu={detailMenu}> <Row> <Col xs={8} > <Row> <Col xs={12}> <h2>{_.get(user, ['personal', 'last_name'], '')}, {_.get(user, ['personal', 'first_name'], '')}</h2> </Col> </Row> <Row> <Col xs={12}> <KeyValue label="Username" value={_.get(user, ['username'], '')} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Status" value={userStatus} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Email" value={_.get(user, ['personal', 'email'], '')} /> </Col> </Row> <br /> <Row> <Col xs={12}> <KeyValue label="Patron group" value={patronGroup.group} /> </Col> </Row> </Col> <Col xs={4} > <img className="floatEnd" src="http://placehold.it/175x175" role="presentation" /> </Col> </Row> <br /> <hr /> <br /> <Row> <Col xs={3}> <h3 className="marginTopHalf">Fines</h3> </Col> <Col xs={4} sm={3}> <TextField rounded endControl={<Button buttonStyle="fieldControl"><Icon icon="clearX" /></Button>} startControl={<Icon icon="search" />} placeholder="Search" fullWidth /> </Col> <Col xs={5} sm={6}> <Button align="end" bottomMargin0 >View Full History</Button> </Col> </Row> <MultiColumnList fullWidth contentData={fineHistory} /> <hr /> <Route path={`${this.props.match.path}`} render={props => <this.connectedUserLoans stripes={this.props.stripes} onClickViewLoansHistory={this.onClickViewLoansHistory} {...props} />} /> {!this.props.stripes.hasPerm('perms.users.read') ? null : <UserPermissions availablePermissions={availablePermissions} usersPermissions={usersPermissions} viewUserProps={this.props} stripes={this.props.stripes} /> } <Layer isOpen={this.state.editUserMode} label="Edit User Dialog"> <UserForm initialValues={_.merge(user, { available_patron_groups: this.props.data.patronGroups })} onSubmit={(record) => { this.update(record); }} onCancel={this.onClickCloseEditUser} /> </Layer> <Layer isOpen={this.state.viewLoansHistoryMode} label="Loans History"> <this.connectedLoansHistory userid={userid} onCancel={this.onClickCloseLoansHistory} /> </Layer> </Pane> ); } } export default ViewUser;
JavaScript
0
@@ -6662,37 +6662,8 @@ oans - stripes=%7Bthis.props.stripes%7D onC
e94aa55b9c68bffa7dc48dc582e42f38972a1d73
remove the queryselector load
browser.js
browser.js
var domify = require('domify'); var query = require('queryselector'); module.exports = hyperglue; function hyperglue (src, updates) { if (!updates) updates = {}; var dom = typeof src === 'object' ? [ src ] : domify(src) ; forEach(objectKeys(updates), function (selector) { var value = updates[selector]; forEach(dom, function (d) { var nodes = d.querySelectorAll(selector); if (nodes.length === 0) return; for (var i = 0; i < nodes.length; i++) { bind(nodes[i], value); } }); }); return dom.length === 1 ? dom[0] : dom ; } function bind (node, value) { if (isElement(value)) { node.innerHTML = ''; node.appendChild(value); } else if (isArray(value)) { for (var i = 0; i < value.length; i++) { var e = hyperglue(node.cloneNode(true), value[i]); node.parentNode.insertBefore(e, node); } node.parentNode.removeChild(node); } else if (value && typeof value === 'object') { forEach(objectKeys(value), function (key) { if (key === '_text') { setText(node, value[key]); } else if (key === '_html' && isElement(value[key])) { node.innerHTML = ''; node.appendChild(value[key]); } else if (key === '_html') { node.innerHTML = value[key]; } else node.setAttribute(key, value[key]); }); } else setText(node, value); } function forEach(xs, f) { if (xs.forEach) return xs.forEach(f); for (var i = 0; i < xs.length; i++) f(xs[i], i) } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) res.push(key); return res; }; function isElement (e) { return e && typeof e === 'object' && e.childNodes && (typeof e.appendChild === 'function' || typeof e.appendChild === 'object') ; } var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function setText (e, s) { e.innerHTML = ''; var txt = document.createTextNode(String(s)); e.appendChild(txt); }
JavaScript
0.000001
@@ -28,46 +28,8 @@ y'); -%0Avar query = require('queryselector'); %0A%0Amo
0d0b1e5f70c476a6cbfcf5398d1d441665b2ab46
use call to avoid ie shenanigans
browser.js
browser.js
// shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function () { throw new Error('setTimeout is not defined'); } } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function () { throw new Error('clearTimeout is not defined'); } } } ()) var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; cachedClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { cachedSetTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; };
JavaScript
0
@@ -1218,17 +1218,28 @@ tTimeout -( +.call(null, cleanUpN @@ -1634,17 +1634,28 @@ rTimeout -( +.call(null, timeout) @@ -1988,17 +1988,28 @@ tTimeout -( +.call(null, drainQue
aa9452f1560c9c9c799f3132f3d751c26903a0be
Update edit for to handle new schema. Fixes last part of STRIPES-138.
UserForm.js
UserForm.js
import React, { Component, PropTypes } from 'react'; // eslint-disable-line import Paneset from '@folio/stripes-components/lib/Paneset'; // eslint-disable-line import Pane from '@folio/stripes-components/lib/Pane'; // eslint-disable-line import PaneMenu from '@folio/stripes-components/lib/PaneMenu'; // eslint-disable-line import {Row, Col} from 'react-bootstrap'; // eslint-disable-line import Button from '@folio/stripes-components/lib/Button'; // eslint-disable-line import TextField from '@folio/stripes-components/lib/TextField'; // eslint-disable-line import Select from '@folio/stripes-components/lib/Select'; // eslint-disable-line import RadioButtonGroup from '@folio/stripes-components/lib/RadioButtonGroup'; // eslint-disable-line import RadioButton from '@folio/stripes-components/lib/RadioButton'; // eslint-disable-line import {Field, reducer as formReducer, reduxForm} from 'redux-form'; // eslint-disable-line const propTypes = { onClose: PropTypes.func, // eslint-disable-line react/no-unused-prop-types newUser: PropTypes.bool, // eslint-disable-line react/no-unused-prop-types handleSubmit: PropTypes.func.isRequired, reset: PropTypes.func, pristine: PropTypes.bool, submitting: PropTypes.bool, onCancel: PropTypes.func, initialValues: PropTypes.object, }; function UserForm(props) { const { handleSubmit, reset, // eslint-disable-line no-unused-vars pristine, submitting, onCancel, initialValues, } = props; /* Menues for Add User workflow */ const addUserFirstMenu = <PaneMenu><button onClick={onCancel} title="close" aria-label="Close New User Dialog"><span style={{ fontSize: '30px', color: '#999', lineHeight: '18px' }} >&times;</span></button></PaneMenu>; const addUserLastMenu = <PaneMenu><Button type="submit" title="Create New User" disabled={pristine || submitting} onClick={handleSubmit}>Create User</Button></PaneMenu>; const editUserLastMenu = <PaneMenu><Button type="submit" title="Update User" disabled={pristine || submitting} onClick={handleSubmit}>Update User</Button></PaneMenu>; return ( <form> <Paneset> <Pane defaultWidth="100%" firstMenu={addUserFirstMenu} lastMenu={initialValues ? editUserLastMenu : addUserLastMenu} paneTitle={initialValues ? 'Edit User' : 'New User'}> <Row> <Col sm={5} smOffset={1}> <h2>User Record</h2> <Field label="UserName" name="username" id="adduser_username" component={TextField} required fullWidth /> <Field label="Active" name="active" component={RadioButtonGroup}> <RadioButton label="Yes" id="useractiveYesRB" value="true" inline /> <RadioButton label="No" id="useractiveNoRB" value="false" inline /> </Field> <fieldset> <legend>Personal Info</legend> <Field label="Full Name" name="personal.full_name" id="adduser_fullname" component={TextField} required fullWidth /> <Field label="Primary Email" name="personal.email_primary" id="adduser_primaryemail" component={TextField} required fullWidth /> <Field label="Secondary Email" name="personal.email_secondary" id="adduser_secondemail" component={TextField} fullWidth /> </fieldset> <Field label="Type" name="type" id="adduser_type" component={Select} fullWidth dataOptions={[{ label: 'Select user type', value: '' }, { label: 'Patron', value: 'Patron', selected: 'selected' }]} /> <Field label="Group" name="patron_group" id="adduser_group" component={Select} fullWidth dataOptions={[{ label: 'Select patron group', value: '' }, { label: 'On-campus', value: 'on_campus', selected: 'selected' }]} /> </Col> </Row> </Pane> </Paneset> </form> ); } UserForm.propTypes = propTypes; export default reduxForm({ form: 'userForm', })(UserForm);
JavaScript
0
@@ -2871,19 +2871,20 @@ label=%22F -ull +irst Name%22 n @@ -2898,19 +2898,20 @@ rsonal.f -ull +irst _name%22 i @@ -2922,19 +2922,20 @@ dduser_f -ull +irst name%22 co @@ -3010,21 +3010,17 @@ el=%22 -Primary Email +Last Name %22 na @@ -3036,21 +3036,17 @@ nal. -email_primary +last_name %22 id @@ -3059,20 +3059,16 @@ ser_ -primaryemail +lastname %22 co @@ -3082,33 +3082,24 @@ =%7BTextField%7D - required fullWidth / @@ -3134,18 +3134,8 @@ el=%22 -Secondary Emai @@ -3161,18 +3161,8 @@ mail -_secondary %22 id @@ -3175,14 +3175,8 @@ ser_ -second emai @@ -3191,32 +3191,41 @@ nent=%7BTextField%7D + required fullWidth /%3E%0A
0ba05afc6d401f1f995c4bb6fc1c75219bdd669e
update NavMenuList
examples/containers/app/navMenu/NavMenuList.js
examples/containers/app/navMenu/NavMenuList.js
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actions from 'reduxes/actions'; import NavMenuItem from './NavMenuItem'; import Event from 'vendors/Event'; class NavMenuList extends Component { constructor(props) { super(props); } render() { const {navMenu, expandMenuName, activatedMenu, expandMenu, updateActivatedMenu} = this.props; return ( <div className="nav-menu-list" onWheel={Event.preventContainerScroll}> <div className="nav-menu-scroller"> { navMenu.map((menu, index) => <NavMenuItem key={(menu && menu.text) || index} expandMenuName={expandMenuName} activatedMenu={activatedMenu} options={menu} expandMenu={expandMenu} updateActivatedMenu={updateActivatedMenu}/> ) } </div> </div> ); } } NavMenuList.propTypes = { navMenu: PropTypes.array, expandMenuName: PropTypes.string, activatedMenu: PropTypes.object, expandMenu: PropTypes.func, updateActivatedMenu: PropTypes.func }; export default connect(state => ({ navMenu: state.navMenu.menu, expandMenuName: state.navMenu.expandMenuName, activatedMenu: state.navMenu.activatedMenu }), dispatch => bindActionCreators({ expandMenu: actions.expandMenu, updateActivatedMenu: actions.updateActivatedMenu }, dispatch))(NavMenuList);
JavaScript
0
@@ -698,16 +698,27 @@ + navMenu && navMenu
fa3afdd5b3d859c9239751944eba9a76c7fd2be5
use avatarURL
bot/lib/message2embed.js
bot/lib/message2embed.js
const Discord = require('discord.js'); module.exports = async function (message, hotline){ let me = message.embeds.shift(); const embed = new Discord.RichEmbed(); if(me && me!=null) { if(me.author && me.author.name) embed.author = { name: me.author.name, icon_url: me.author.icon_url } if(me.description) embed.description = me.description if(me.fields && me.fields.length >0) { me.fields.map(function(f){ embed.fields.push({ name: f.name, value: f.value, inline: f.inline }); }); } if(me.thumbnail) embed.thumbnail = me.thumbnail; if(me.image) embed.thumbnail = me.image; if(me.url) embed.url = me.url; if(me.title) embed.title = me.title; if(me.color) embed.color = me.color; if(me.timestamp) embed.timestamp = me.timestamp; if(me.footer) embed.footer = { icon_url: me.footer.icon_url, text: me.footer.text }; return embed; //return message.reply("Embeds not supported yet") } embed.setAuthor(message.author.username, message.author.displayAvatarURL()) if (!hotline) embed.setTitle((message.guild)?(message.channel.name + " in " + message.guild.name):(" in a DM with " + message.channel.recipient.tag)); if (!message.content.trim() == "") embed.setDescription(message.cleanContent); else embed.setDescription("**" + (( me.author && me.author!=null)?(me.author.name+ " : "):"") + ((me.title && me.title!=null)?me.title:"") + "**\n " + (me.description || "") + ((me.footer) ? ("\n*At " + me.footer.text + "*") : "")); if (!hotline) embed.setTimestamp(message.createdAt) let color = message.member; if (color) { color = color.roles.filter((r) => { if (r.color !== 0) return r; }).array().sort((r1, r2) => { if (r1.position < r2.position) return 1; }).shift(); if (color) color = color.color; } else color = 0; embed.setColor(color); //embed.setTitle("Quote"); return embed; }
JavaScript
0.000001
@@ -1410,16 +1410,9 @@ hor. -displayA +a vata
04d9f3c330194553a60eb9c273a64674ed1835b2
Update promo.client.controller.js
public/modules/core/controllers/promo.client.controller.js
public/modules/core/controllers/promo.client.controller.js
'use strict'; angular.module('core').controller('promoController', ['$scope', 'Authentication', 'promoService', function($scope, Authentication, promoService) { // This provides Authentication context. $scope.authentication = Authentication; // Some example string - remove in prod $scope.helloText = 'Promo form Test'; $scope.testuser = $scope.authentication.user.displayName; $scope.promos = promoService.query(); $scope.newPromo = {}; $scope.post = function() { promoService.save({ created_by: $scope.authentication.user._id , created_by_name: $scope.authentication.user.displayName , Deal_Type: $scope.newPromo.Deal_Type , Account: $scope.newPromo.Account , Product_Group: $scope.newPromo.Product_Group , Feature: $scope.newPromo.Feature , Display_Level: $scope.newPromo.Display_Level , Normal_Retail: $scope.newPromo.Normal_Retail , Promo_Price: $scope.newPromo.Promo_Price , Allowance_Type: $scope.newPromo.Allowance_Type , Allowance_Amount: $scope.newPromo.Allowance_Amount , Retailer_Margin: $scope.newPromo.Retailer_Margin , Start_Date: $scope.newPromo.Start_Date , End_Date: $scope.newPromo.End_Date , Allocation: $scope.newPromo.Allocation , Allocation_Quantity: $scope.newPromo.Allocation_Quantity , Allocation_UOM: $scope.newPromo.Allocation_UOM , Forecast_Units: $scope.newPromo.Forecast_Units , ROI: $scope.newPromo.ROI , Notes: $scope.newPromo.Notes }, function(){ $scope.promos = promoService.query(); $scope.newPromo = {}; $window.location.href = '/promos'; }); }; $scope.delete = function(promo) { promoService.delete({id: promo._id}); $scope.promo = promoService.query(); }; } ]);
JavaScript
0
@@ -1545,15 +1545,8 @@ $ -window. loca @@ -1554,15 +1554,13 @@ ion. -href = +path( '/pr @@ -1564,16 +1564,17 @@ /promos' +) ;%0A%09 %7D);
28447b3dbdfea19a1a2c55ccf2ce51314c499016
Fix for coinurl
src/sites/link/coinurl.js
src/sites/link/coinurl.js
(function () { 'use strict'; function deep (d) { d.addEventListener('DOMContentLoaded', function () { var a = $.$('#skip-ad', d.document); if (a) { $.openLink(a.href); } }); } $.register({ rule: { host: /^coinurl\.com|cur\.lv$/, }, ready: function () { var d = unsafeWindow.frames[0]; if (d) { deep(d); return; } var o = new MutationObserver(function (mutations) { o.disconnect(); var d = unsafeWindow.frames[0]; d.addEventListener('DOMContentLoaded', function () { d = d.frames[0]; deep(d); }); }); o.observe(document.body, { childList: true, }); }, }); })(); // ex: ts=2 sts=2 sw=2 et // sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true; // kate: space-indent on; indent-width 2;
JavaScript
0
@@ -26,16 +26,136 @@ ict';%0A%0A + $.register(%7B%0A rule: %7B%0A host: /%5E(?:(%5Cw+)%5C.)?(coinurl%5C.com%7Ccur%5C.lv)$/,%0A path: /%5E%5C/%5B-%5Cw%5D+$/%0A %7D,%0A ready: functio @@ -160,23 +160,18 @@ ion -deep (d +(m ) %7B%0A d.ad @@ -170,57 +170,62 @@ -d.addEventListener('DOMContentLoaded', function ( + $.removeNodes('iframe');%0A if (m.host%5B1%5D == null ) %7B%0A @@ -234,42 +234,115 @@ + var -a = $.$('#skip-ad', d.document +mainFrame = 'http://cur.lv/redirect_curlv.php?code=' + escape(document.location.pathname.substring(1) );%0A @@ -350,14 +350,14 @@ -if (a) +%7D else %7B%0A @@ -367,190 +367,365 @@ -$.openLink(a.href);%0A %7D%0A %7D);%0A %7D%0A%0A $.register(%7B%0A rule: %7B%0A host: /%5Ecoinurl%5C.com%7Ccur%5C.lv$/,%0A +var mainFrame = 'http://cur.lv/redirect_curlv.php?zone=' + m.host%5B1%5D + '&name=' + escape(document.location.pathname.substring(1));%0A %7D%0A // Retrieve the main frame%0A $.get(mainFrame, %7B%7D, %0A function(mainFrameContent) %7B%0A -%7D,%0A -ready: function () %7B%0A var d = unsafeWindow.frames%5B0%5D +try %7B%0A // Convert it to HTML nodes%0A var docMainFrame = $.toDOM(mainFrameContent) ;%0A if ( @@ -724,13 +724,22 @@ -if (d + %7D catch (e ) %7B%0A @@ -738,38 +738,82 @@ h (e) %7B%0A -deep(d + throw new _.NoPicAdsError('main frame changed' );%0A retur @@ -811,24 +811,81 @@ -return;%0A + %7D%0A%0A // Regex allowing to extract the link from a subframe%0A -%7D%0A @@ -894,128 +894,344 @@ var -o = new MutationObserver(function (mutations) %7B%0A o.disconnect();%0A var d = unsafeWindow.frames%5B0%5D +rExtractLink = /onclick=%22open_url%5C('(%5B%5E'%5D+)',%5Cs*'go'%5C)/;%0A%0A // Iterate each frame%0A var innerFrames = $.$$('frameset %3E frame', docMainFrame).each(%0A function(currFrame) %7B%0A%0A // Fix the host of the frame%0A var currFrameAddr = currFrame.src.replace(location.hostname,m.host%5B2%5D) ;%0A +%0A d.ad @@ -1230,61 +1230,139 @@ -d.addEventListener('DOMContentLoaded', function ( + // Get the content of the current frame%0A $.get(currFrameAddr, %7B%7D,%0A function(currFrameContent ) %7B%0A +%0A @@ -1371,52 +1371,141 @@ -d = d.frames%5B0%5D;%0A deep(d + // Try to find the link in the current frame%0A var aRealLink = rExtractLink.exec(currFrameContent );%0A +%0A %7D);%0A @@ -1504,87 +1504,353 @@ -%7D);%0A -%7D);%0A o.observe(document.body, %7B%0A childList: true,%0A %7D + // Could not find it? Try to find it in the next frame%0A if (aRealLink == null %7C%7C aRealLink%5B1%5D == null) %7Breturn;%7D%0A%0A // Otherwise redirect to the link%0A var realLink = aRealLink%5B1%5D;%0A $.openLink(realLink);%0A %7D%0A );%0A %7D);%0A %7D%0A );%0A @@ -2037,9 +2037,8 @@ width 2; -%0A
7eb7b8d1fd5ce850b01c7c9dbceda579eb16828d
remove semicolons
lib/components/user/stacked-pane-display.js
lib/components/user/stacked-pane-display.js
import PropTypes from 'prop-types' import React, {useState} from 'react' import FormNavigationButtons from './form-navigation-buttons' import { PageHeading, StackedPaneContainer } from './styled' /** * This component handles the flow between screens for new OTP user accounts. */ const StackedPaneDisplay = ({ onCancel, paneSequence, title }) => { // Create indicator of if cancel button was clicked so that child components can know const [isBeingCanceled, updateBeingCanceled] = useState(false) return ( <> {title && <PageHeading>{title}</PageHeading>} { paneSequence.map(({ pane: Pane, props, title }, index) => ( <StackedPaneContainer key={index}> <h3>{title}</h3> <div><Pane canceled={isBeingCanceled} {...props} /></div> </StackedPaneContainer> )) } <FormNavigationButtons backButton={{ onClick: () => { updateBeingCanceled(true); onCancel() }, text: 'Cancel' }} okayButton={{ text: 'Save Preferences', type: 'submit' }} /> </>) } StackedPaneDisplay.propTypes = { onCancel: PropTypes.func.isRequired, paneSequence: PropTypes.array.isRequired } export default StackedPaneDisplay
JavaScript
0.001735
@@ -576,25 +576,16 @@ %0A %7B -%0A paneSequ @@ -636,18 +636,16 @@ x) =%3E (%0A - @@ -689,18 +689,16 @@ - %3Ch3%3E%7Btit @@ -720,15 +720,26 @@ - %3Cdiv%3E +%0A %3CPan @@ -784,17 +784,26 @@ %7D /%3E +%0A %3C/div%3E%0A - @@ -834,18 +834,16 @@ er%3E%0A - )) %0A @@ -838,23 +838,16 @@ )) -%0A %7D%0A%0A @@ -918,16 +918,28 @@ () =%3E %7B +%0A updateB @@ -960,9 +960,20 @@ rue) -; +%0A onC @@ -979,16 +979,26 @@ Cancel() +%0A %7D,%0A @@ -1139,16 +1139,19 @@ %0A %3C/%3E +%0A )%0A%7D%0A%0ASta
575357557fd3276fb625a6438537bbc0c1018cb7
allow closing of modal dialog on success
cea/interfaces/dashboard/tools/static/tools.js
cea/interfaces/dashboard/tools/static/tools.js
/** * Functions to run a tool from the tools page. */ function cea_run(script) { if(!$('#cea-tool-parameters').parsley().isValid()) return false; $('.cea-modal-close').attr('disabled', 'disabled').removeClass('btn-danger').removeClass('btn-success'); $('#cea-console-output-body').text(''); $('#cea-console-output').modal({'show': true, 'backdrop': 'static'}); let new_job_info = {"script": script, "parameters": get_parameter_values()}; console.log("new_job_info", new_job_info); $.post('/server/jobs/new', new_job_info, function(job_info) { console.log("About to run job_info", job_info); $.post(`start/${job_info.id}`, function() { let socket = io.connect(`http://${document.domain}:${location.port}`); let $cea_modal_close = $(".cea-modal-close"); let message_appender = function(data){ $('#cea-console-output-body').append(data.message); }; socket.on("cea-worker-message", message_appender); socket.on('cea-worker-success', function() { $cea_modal_close.addClass("btn-success"); socket.removeListener("cea-worker-message", message_appender); }); socket.on('cea-worker-error', function() { $cea_modal_close.removeAttr("disabled"); $(".cea-modal-close").addClass("btn-danger"); socket.removeListener("cea-worker-message", message_appender); }); }); }, "json"); } function cea_save_config(script) { if(!$('#cea-tool-parameters').parsley().isValid()) return false; $('#cea-save-config-modal').modal({'show': true, 'backdrop': 'static'}); $.post('save-config/' + script, get_parameter_values(), null, 'json'); $('#cea-save-config-modal').modal('hide'); } /** * Read the values of all the parameters. */ function get_parameter_values() { var result = {}; $('.cea-parameter').not('bootstrap-select').each((index, element) => { console.log('Reading parameter: ' + element.id); result[element.id] = read_value(element); }); console.log(result); return result; } /** * Update the div#cea-console-output-body with the output of the script until it is done. * @param script */ function update_output(script) { $.getJSON('read/' + script, {}, function(msg) { if (msg === null) { $.getJSON('is-alive/' + script, {}, function(msg) { if (msg) { setTimeout(update_output, 1000, script); } else { $('.cea-modal-close').removeAttr('disabled'); $.getJSON('exitcode/' + script, {}, function(msg){ if (msg === 0) { $('.cea-modal-close').addClass('btn-success'); } else { $('.cea-modal-close').addClass('btn-danger'); } }); } }); } else { $('#cea-console-output-body').append(msg.message); setTimeout(update_output, 1000, script); } }); } /** * Read out the value of the parameter as defined by the form input - this depends on the parameter_type. * * @param script * @param parameter_name * @param parameter_type */ function read_value(element) { let value = null; switch (element.dataset.ceaParameterTypename) { case "ChoiceParameter": case "ScenarioNameParameter": value = $(element)[0].value; break; case "WeatherPathParameter": value = $(element)[0].value; break; case "BooleanParameter": value = $(element)[0].checked; break; case "PathParameter": value = $(element)[0].value; break; case "MultiChoiceParameter": case "BuildingsParameter": value = $(element).val(); if (value) { value = value.join(); } else { value = []; } break; case "SubfoldersParameter": value = $(element).val(); break; case "JsonParameter": value = JSON.parse($(element).val()); break; default: // handle the default case value = $(element)[0].value; } return value; } /** * Show an open file dialog for a cea FileParameter and update the contents of the * input field. * * @param parameter_name */ function show_open_file_dialog(parameter_fqname,) { $.get('open-file-dialog/' + parameter_fqname, {}, function(html) { $('#cea-file-dialog .modal-content').html(html); $('#cea-file-dialog').modal({'show': true, 'backdrop': 'static'}); }); } /** * Navigate the open file dialog to a new folder. * @param parameter_fqname */ function file_dialog_navigate_to(parameter_fqname, current_folder, folder) { $.get('open-file-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) { $('#cea-file-dialog .modal-content').html(html); }); } /** * User selected a file, highlight it. * @param link * @param file */ function select_file(link) { $('.cea-file-listing a').removeClass('bg-primary'); $(link).addClass('bg-primary'); $('#cea-file-dialog-select-button').prop('disabled', false); } /** * Save the selected file name (full path) to the input[type=text] with the id <target_id>. * @param target_id */ function save_file_name(target_id) { // figure out file path var file_path = $('.cea-file-listing a.bg-primary').data('save-file-path'); $('#' + target_id).val(file_path); } /** * Show an open folder dialog for a cea PathParameter and update the contents of the * input field. * * @param parameter_name */ function show_open_folder_dialog(parameter_fqname,) { $.get('open-folder-dialog/' + parameter_fqname, {}, function(html) { $('#cea-folder-dialog .modal-content').html(html); $('#cea-folder-dialog').modal({'show': true, 'backdrop': 'static'}); }); } /** * Navigate the open file dialog to a new folder. * @param parameter_fqname * @param current_folder * @param folder */ function folder_dialog_navigate_to(parameter_fqname, current_folder, folder) { $.get('open-folder-dialog/' + parameter_fqname, {current_folder: current_folder, folder: folder}, function(html) { $('#cea-folder-dialog .modal-content').html(html); }); } /** * Save the selected folder name (full path) to the input[type=text] with the id <target_id>. * @param target_id * @param folder_path */ function save_folder_name(target_id, folder_path) { // figure out folder path $('#' + target_id).val(folder_path).trigger("input").trigger("change"); console.log(target_id) }
JavaScript
0
@@ -1063,32 +1063,89 @@ ', function() %7B%0A + $cea_modal_close.removeAttr(%22disabled%22);%0A
19159f684bc22175cbf072b039ac09a82b7ef47d
Return 'Bad Request' on plain HTTP/RPC when encryption is required.
lib/hooks/requests/switch_http_and_https.js
lib/hooks/requests/switch_http_and_https.js
// Redirect between plain HTTP and encrypted HTTPS by following rules: // - If user is logged in - force HTTPS. // - If user is visiting "users.auth.*" page - force HTTPS. // - Otherwise force HTTP. 'use strict'; var isEncryptionAllowed = require('nodeca.core/lib/system/utils/is_encryption_allowed'); module.exports = function (N) { N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env) { var shouldBeEncrypted = Boolean(env.session.user_id) || 'users.auth' === env.method.slice(0, 'users.auth'.length); if (env.request.isEncrypted === shouldBeEncrypted) { return; // Redirection is not needed. Continue. } if (!isEncryptionAllowed(N, env.method)) { return; // It is not possible to encrypt current connection. } var redirectUrl = env.url_to(env.method, env.params, { protocol: shouldBeEncrypted ? 'https' : 'http' }); return { code: N.io.REDIRECT, head: { Location: redirectUrl } }; }); };
JavaScript
0.000003
@@ -928,24 +928,193 @@ p'%0A %7D);%0A%0A + if (!redirectUrl) %7B%0A // Can't build URL - usually RPC-only method.%0A return %7B code: N.io.BAD_REQUEST, message: 'Encrypted connection is required' %7D;%0A %7D%0A%0A return %7B
86d5fcc9b09cf49c58533778125de1c2a00efab5
Optimize integration test on CI
integration_test/test/injection.test.js
integration_test/test/injection.test.js
import { ALL, EACH } from '../util' describe('The Extension page should', () => { beforeAll(ALL) afterAll(ALL) beforeEach(EACH) afterEach(EACH) it('execute the injected script after page loaded', async () => { await page.evaluate(() => { const editor = window.ace.edit('ace-editor') editor.session.setValue(` console.log('abc') document.querySelector('body').style.background = 'red'`) }) await page.evaluate(() => { document.querySelectorAll('button')[6].click() }) await page.waitForTimeout(100) const input = await page.$$('textarea') await input[1].evaluate((node) => (node.value = '')) await input[1].type( 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.11.0/underscore-min.js', { delay: 2 } ) await page.waitForTimeout(100) const allButtons = await page.$$('button') await allButtons[allButtons.length - 1].click() await page.waitForTimeout(100) await page.$eval('button', (x) => x.click()) const newPage = await browser.newPage() await newPage.goto('https://google.com') await newPage.bringToFront() const background = await newPage.$eval( 'body', (node) => node.style.background ) expect(background).toBe('red') expect(await newPage.$eval('body', (node) => window._.VERSION)).toBe( '1.11.0' ) page.bringToFront() const buttons = await page.$$('button') await buttons[1].click() await page.waitForTimeout(100) const dialogButtons = await page.$$('.MuiDialogActions-root > button') expect(dialogButtons).toHaveLength(3) await dialogButtons[1].click() await page.waitForTimeout(500) }) })
JavaScript
0.000001
@@ -1472,33 +1472,33 @@ .waitForTimeout( -1 +5 00)%0A const di
4762aeaee506ae37412ff40b15496b6c11b5b880
Add context to Cell on Search results
src/v2/components/SearchContents/index.js
src/v2/components/SearchContents/index.js
import React, { PureComponent } from 'react' import PropTypes from 'prop-types' import { Query } from '@apollo/client/react/components' import searchContentsQuery from 'v2/components/SearchContents/queries/searchContents' import SearchEmptyMessage from 'v2/components/SearchEmptyMessage' import ErrorAlert from 'v2/components/UI/ErrorAlert' import BlocksLoadingIndicator from 'v2/components/UI/BlocksLoadingIndicator' import Grid from 'v2/components/UI/Grid' import Cell from 'v2/components/Cell' export default class SearchContents extends PureComponent { static propTypes = { type: PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string), ]), q: PropTypes.string.isRequired, fetchPolicy: PropTypes.oneOf(['cache-first', 'network-only']).isRequired, block_filter: PropTypes.oneOf([ 'IMAGE', 'EMBED', 'TEXT', 'ATTACHMENT', 'LINK', ]), } static defaultProps = { type: null, block_filter: null, } state = { page: 1, per: 12, hasMore: true, } loadMore = fetchMore => () => { const { page, per } = this.state fetchMore({ variables: { page: page + 1, per }, updateQuery: (prevResult, { fetchMoreResult }) => ({ contents: [...prevResult.contents, ...fetchMoreResult.contents], }), }).then(({ errors, data }) => { const { contents: { length }, } = data const hasMore = !errors && length > 0 && length >= per this.setState({ page: page + 1, hasMore, }) }) } render() { const { per, hasMore } = this.state const { type, fetchPolicy, q, block_filter } = this.props return ( <Query query={searchContentsQuery} variables={{ type, per, q, block_filter, }} fetchPolicy={fetchPolicy} ssr={false} > {({ loading, error, data, fetchMore }) => { if (error) { return <ErrorAlert>{error.message}</ErrorAlert> } if (loading) { return <BlocksLoadingIndicator /> } const { contents } = data return ( <div> {loading && <BlocksLoadingIndicator />} {!loading && contents.length === 0 && ( <SearchEmptyMessage term={q} type={type} /> )} {!loading && contents.length > 0 && ( <Grid pageStart={1} threshold={800} initialLoad={false} loader={<BlocksLoadingIndicator key="loading" />} hasMore={contents.length >= per && hasMore} loadMore={this.loadMore(fetchMore)} > {contents.map(cell => ({ Image: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), Attachment: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), Text: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), Link: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), Embed: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), Channel: () => ( <Cell.Konnectable key={`${cell.__typename}_${cell.id}`} konnectable={cell} /> ), User: () => ( <Cell.Identifiable key={`${cell.__typename}_${cell.id}`} identifiable={cell} /> ), Group: () => ( <Cell.Identifiable key={`${cell.__typename}_${cell.id}`} identifiable={cell} /> ), }[cell.__typename]()) )} </Grid> )} </div> ) }} </Query> ) } }
JavaScript
0.000453
@@ -3026,32 +3026,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -3098,32 +3098,32 @@ /%3E%0A - @@ -3316,32 +3316,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -3600,32 +3600,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -3884,32 +3884,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -4169,32 +4169,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -4456,32 +4456,77 @@ nectable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -4742,32 +4742,77 @@ tifiable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A @@ -4983,32 +4983,32 @@ e%7D_$%7Bcell.id%7D%60%7D%0A - @@ -5029,32 +5029,77 @@ tifiable=%7Bcell%7D%0A + context=%7Bcontents%7D%0A
1a107eca0848b821fe0ef150713c1a828b28b075
Add hosted target support
lib/package/plugins/checkBundleStructure.js
lib/package/plugins/checkBundleStructure.js
//bundleStructure.js //for every policy check fileName per Apigee recommendations //for every policy check if fileName matches policyName //plugin methods and variables var bundle, root, plugin = { ruleId: "BN001", name: "Bundle Structure", message: "Bundle Structure: Check bundle structure, bundles have a specific structure, extra folder or files may be problematic.", fatal: false, severity: 2, //error nodeType: "Bundle", enabled: true }, fs = require("fs"), hadWarnErr = false; function eq(lh, rh) { return lh === rh; } function contains(a, obj, f) { if (!a || !a.length) { return false; } f = f || eq; for (var i = 0; i < a.length; i++) { if (f(a[i], obj)) { if (!a[i]) { return true; } return a[i]; } } return false; } function mark(source) { var result = { ruleId: plugin.ruleId, severity: plugin.severity, nodeType: plugin.nodeType, message: source }; bundle.addMessage(result); hadWarnErr = true; } function checkNode(node, curRoot) { //node has two arrays files and folders //check if files is correct var files, compareNodeToFolder = function(n, f) { return n.name === f; }; if (!curRoot) { curRoot = root; } try { files = fs.readdirSync(curRoot); } catch (e) { mark({ curRoot, error: e }); return; } if (node.folders && node.folders.length) { node.folders.forEach(function(folder) { if (folder.required && !contains(files, folder.name)) { mark('Required folder "' + folder.name + '" not found.'); } }); } //walk the folders in files files.forEach(function(file) { if (fs.statSync(curRoot + "/" + file).isDirectory()) { //is there a child node that matches? if not error if so recurse var foundNode; if (!foundNode && node.folders && node.folders.any === true) { //create a node that corresponds to the current node with the correct name foundNode = JSON.parse(JSON.stringify(node)); foundNode.name = file; } else { foundNode = contains(node.folders, file, compareNodeToFolder); } if (foundNode) { checkNode(foundNode, curRoot + "/" + foundNode.name); } else { //we may have an unknown folder var allowedFolders = []; if (node.folders) { allowedFolders = JSON.parse(JSON.stringify(node.folders)); allowedFolders.forEach(function(f) { delete f.files; delete f.folders; }); } mark( 'Unexpected folder found "' + file + '". Current root:"' + curRoot.substring(curRoot.indexOf("/apiproxy")) + "/" + file + '". Valid folders: ' + JSON.stringify(allowedFolders) + "." ); } } else if (file !== ".DS_Store") { //does the file extension match those valid for this node var extension = file.split("."); if (extension.length > 1) { extension = extension[extension.length - 1]; } else { extension = ""; } if ( node.files && node.files.extensions && !contains(node.files.extensions, extension) ) { mark( 'Unexpected extension found with file "' + curRoot + "/" + file + '". Valid extensions: ' + JSON.stringify(node.files.extensions) ); } } }); } var bundleStructure = { name: "apiproxy", files: { extensions: ["xml", "md"], maxCount: 1 }, folders: [ { name: "manifests", required: false, files: { extensions: ["xml"] } }, { name: "policies", required: false, files: { extensions: ["xml"] } }, { name: "stepdefinitions", required: false, files: { extensions: ["xml"] } }, { name: "proxies", required: true, files: { extensions: ["xml", "flowfrag"] } }, { name: "targets", required: false, files: { extensions: ["xml"] } }, { name: "resources", required: false, folders: [ { name: "jsc", required: false, files: { extensions: ["js", "jsc", "json"] }, folders: { any: true } }, { name: "java", required: false, files: { extensions: ["jar", "zip", "properties", "inf"] }, folders: { any: true } }, { name: "py", required: false, files: { extensions: ["py", ""] } }, { name: "xsl", required: false, files: { extensions: ["xslt", "xsl"] } }, { name: "openapi", required: false, files: { extensions: ["json"] } }, { name: "node", required: false, files: { extensions: [ "js", "jsc", "json", "zip", "png", "jpg", "jpeg", "css", "ejs", "eot", "svg", "ttf", "woff", "html", "htm" ] }, folders: { any: true } } ] } ] }, onBundle = function(b, cb) { bundle = b; root = bundle.proxyRoot; checkNode(bundleStructure); if (typeof cb == "function") { cb(null, hadWarnErr); } }; module.exports = { plugin, onBundle };
JavaScript
0
@@ -5556,32 +5556,241 @@ : %7B any: true %7D%0A + %7D,%0A %7B%0A name: %22hosted%22,%0A required: false,%0A files: %7B%0A extensions: %5B%22js%22, %22json%22, %22yaml%22, %22ejs%22%5D%0A %7D,%0A folders: %7B any: true %7D%0A %7D%0A
63a560342a40234b4114c5b5d8da0162370d74c0
Add further update to StocktakeBatchModal pagebutton
src/widgets/modals/StocktakeBatchModal.js
src/widgets/modals/StocktakeBatchModal.js
/* eslint-disable react/forbid-prop-types */ /* eslint-disable import/prefer-default-export */ /** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2019 */ import React, { useCallback, useMemo } from 'react'; import PropTypes from 'prop-types'; import { View } from 'react-native'; import { MODAL_KEYS } from '../../utilities'; import { usePageReducer } from '../../hooks'; import { getItemLayout } from '../../pages/dataTableUtilities'; import { GenericChoiceList } from '../GenericChoiceList'; import { PageInfo, DataTablePageView, PageButton } from '..'; import { DataTable, DataTableHeaderRow, DataTableRow } from '../DataTable'; import globalStyles from '../../globalStyles'; import { UIDatabase } from '../../database'; import ModalContainer from './ModalContainer'; import { buttonStrings } from '../../localization/index'; /** * Renders a stateful modal with a stocktake item and it's batches loaded * for editing. * * State: * Uses a reducer to manage state with `backingData` being a realm results * of items to display. `data` is a plain JS array of realm objects. data is * hydrated from the `backingData` for displaying in the interface. * i.e: When filtering, data is populated from filtered items of `backingData`. * * dataState is a simple map of objects corresponding to a row being displayed, * holding the state of a given row. Each object has the shape : * { isSelected, isFocused, isDisabled }, * * @prop {Object} stocktakeItem The realm transaction object for this invoice. * */ export const StocktakeBatchModal = ({ stocktakeItem }) => { const usingReasons = useMemo(() => UIDatabase.objects('StocktakeReasons').length > 0, []); const initialState = { page: usingReasons ? 'stocktakeBatchEditModalWithReasons' : 'stocktakeBatchEditModal', pageObject: stocktakeItem, }; const [state, dispatch, instantDebouncedDispatch] = usePageReducer(initialState); const { pageObject, data, dataState, sortBy, isAscending, modalKey, modalValue, keyExtractor, PageActions, columns, getPageInfoColumns, } = state; const onEditReason = rowKey => PageActions.openModal(MODAL_KEYS.STOCKTAKE_REASON, rowKey); const onCloseModal = () => dispatch(PageActions.closeModal()); const onApplyReason = ({ item }) => dispatch(PageActions.applyReason(item)); const onAddBatch = () => dispatch(PageActions.addStocktakeBatch()); const toggles = useCallback(getPageInfoColumns(pageObject, dispatch, PageActions), []); const getAction = colKey => { switch (colKey) { case 'batch': return PageActions.editStocktakeBatchName; case 'countedTotalQuantity': return PageActions.editStocktakeBatchCountedQuantity; case 'expiryDate': return PageActions.editStocktakeBatchExpiryDate; case 'reasonTitle': return onEditReason; default: return null; } }; const renderRow = useCallback( listItem => { const { item, index } = listItem; const rowKey = keyExtractor(item); return ( <DataTableRow rowData={data[index]} rowState={dataState.get(rowKey)} rowKey={rowKey} columns={columns} dispatch={dispatch} getAction={getAction} rowIndex={index} /> ); }, [data, dataState] ); const renderHeader = useCallback( () => ( <DataTableHeaderRow columns={columns} dispatch={instantDebouncedDispatch} sortAction={PageActions.sortData} isAscending={isAscending} sortBy={sortBy} /> ), [sortBy, isAscending] ); const PageButtons = () => { const { stocktake = {} } = stocktakeItem; const { isFinalised = false } = stocktake; return ( <PageButton text={buttonStrings.add_batch} onPress={onAddBatch} isDisabled={isFinalised} /> ); }; const { pageTopSectionContainer, pageTopLeftSectionContainer, pageTopRightSectionContainer, } = globalStyles; return ( <DataTablePageView> <View style={pageTopSectionContainer}> <View style={pageTopLeftSectionContainer}> <PageInfo columns={toggles} /> </View> <View style={pageTopRightSectionContainer}> <PageButtons /> </View> </View> <DataTable data={data} extraData={dataState} renderRow={renderRow} renderHeader={renderHeader} keyExtractor={keyExtractor} getItemLayout={getItemLayout} columns={columns} windowSize={1} initialNumToRender={0} /> <ModalContainer fullScreen={modalKey === MODAL_KEYS.ENFORCE_STOCKTAKE_REASON} isVisible={!!modalKey} onClose={onCloseModal} > <GenericChoiceList data={UIDatabase.objects('StocktakeReasons')} highlightValue={(modalValue && modalValue.reasonTitle) || ''} keyToDisplay="title" onPress={onApplyReason} /> </ModalContainer> </DataTablePageView> ); }; StocktakeBatchModal.propTypes = { stocktakeItem: PropTypes.object.isRequired, }; export default StocktakeBatchModal;
JavaScript
0
@@ -2109,16 +2109,106 @@ state;%0A%0A + const %7B stocktake = %7B%7D %7D = stocktakeItem;%0A const %7B isFinalised = false %7D = stocktake;%0A%0A const @@ -3743,255 +3743,8 @@ );%0A%0A - const PageButtons = () =%3E %7B%0A const %7B stocktake = %7B%7D %7D = stocktakeItem;%0A const %7B isFinalised = false %7D = stocktake;%0A return (%0A %3CPageButton text=%7BbuttonStrings.add_batch%7D onPress=%7BonAddBatch%7D isDisabled=%7BisFinalised%7D /%3E%0A );%0A %7D;%0A%0A co @@ -4126,17 +4126,139 @@ geButton -s +%0A text=%7BbuttonStrings.add_batch%7D%0A onPress=%7BonAddBatch%7D%0A isDisabled=%7BisFinalised%7D%0A /%3E%0A
654a299a7b8b98bccf3837e0da4260a851780541
Update dKimConfigCtrl.js
src/wwwroot/controllers/dKimConfigCtrl.js
src/wwwroot/controllers/dKimConfigCtrl.js
(function() { 'use strict'; angular .module('dopplerRelay') .controller('dKimConfigCtrl', dKimConfigCtrl); dKimConfigCtrl.$inject = [ '$scope', '$location', 'settings' ]; function dKimConfigCtrl($scope, $location, settings) { var vm = this; var queryParams = $location.search(); vm.domain = queryParams['d']; vm.loading = true; vm.dKimStatus = null; vm.spfStatus = null; vm.dKimPublicKey = null; vm.dKimSelector = null; vm.activationPromise = activate(); function activate() { return loadDataDomain(); } function loadDataDomain() { return settings.getDomain(vm.domain) .then(function(response) { vm.loading = false; vm.dKimStatus = response.data.dkim_ready; vm.spfStatus = response.data.spf_ready; vm.dKimPublicKey = 'k=rsa; p=' + response.data.dkim_public_key; vm.dKimSelector = response.data.dkim_selector + '._domainkey.' + vm.domain; }); } } })();
JavaScript
0.000001
@@ -483,9 +483,10 @@ ll;%0A -%09 + vm