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
41a4c31bbad6982bd6737376af5d9e499529c6f4
Fix child_process undefined error by including lib
gulpfile.js
gulpfile.js
// http://blog.ponyfoo.com/2014/01/27/my-first-gulp-adventure var gulp = require('gulp'); var gutil = require('gulp-util'); var bump = require('gulp-bump'); var git = require('gulp-git'); var jshint = require('gulp-jshint'); var clean = require('gulp-clean'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var size = require('gulp-size'); var connect = require('connect'); var mocha = require('gulp-mocha'); var mochaPhantomJS = require('gulp-mocha-phantomjs'); var BUMP_TYPES = ['major', 'minor', 'patch', 'prerelease']; gulp.task('lint', function () { gulp.src('./src/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('mocha', function () { return gulp.src('test/index.html') .pipe(mochaPhantomJS({reporter: 'list'})); }); gulp.task('build', ['lint'], function () { gulp.src('./src/jquery.textarea_autosize.js') .pipe(gulp.dest('./dist')) .pipe(rename('jquery.textarea_autosize.min.js')) .pipe(uglify()) .pipe(size({showFiles: true})) .pipe(gulp.dest('./dist')); }); gulp.task('watch', ['build'], function() { return gulp.watch('src/*.js', ['build']); }); gulp.task('validation', function () { if (BUMP_TYPES.indexOf(gutil.env.type) == -1) throw new Error('\ntype argument is required for gulp bump\nSupported values: major, minor, patch, prerelease\n\nExample:\n\tgulp bump --type major'); }); gulp.task('bump', ['validation', 'build'], function () { return gulp.src(['./package.json', './bower.json']) .pipe(bump({type: gutil.env.type})) .pipe(gulp.dest('./')); }); gulp.task('tag', ['build'], function () { var pkg = require('./package.json'); var v = 'v' + pkg.version; var message = 'Release ' + v; var exec = require('child_process').exec; exec('git commit -a -m "' + message + '"', function (error, stdout, stderr) {}); exec('git tag -a "' + v + '" -m "' + message + '"', function (error, stdout, stderr) {}); exec('git push origin --tags', function (error, stdout, stderr) {}); }); gulp.task('npm', ['tag'], function (done) { require('child_process') .spawn('npm', ['publish'], { stdio: 'inherit' }) .on('close', done); }); gulp.task('server', function() { connect.createServer(connect.static(__dirname)).listen(3000); }); gulp.task('browser', ['server'], function() { child_process.spawn('open', ['http://localhost:3000/index.html']); }); gulp.task('test', ['lint', 'mocha']); gulp.task('ci', ['build']); gulp.task('release', ['npm']); gulp.task('default', ['watch', 'browser']);
JavaScript
0.000005
@@ -482,16 +482,60 @@ tomjs'); +%0Avar childProcess = require('child_process') %0A%0Avar BU @@ -2117,32 +2117,20 @@ %7B%0A -require(' child -_p +P rocess -') %0A @@ -2359,26 +2359,25 @@ () %7B%0A child -_p +P rocess.spawn
49158f91b7bb42f5550a3d1317e307811b61b8a1
fix window resize issue on Windows
gulpfile.js
gulpfile.js
var path = require('path'); var gulp = require('gulp'); var sass = require('gulp-sass'); var process = require('process'); var gutil = require('gulp-util'); var webpack = require('webpack'); var clean = require('gulp-clean'); var packager = require('electron-packager'); var childProcess = require('child_process'); var packageInfo = require('./package.json'); var webpackConfig = require('./webpack.config.js'); var APP_NAME = packageInfo.name; gulp.task('clean', function (callback) { gulp.src(['./app', './build'], {read: false}) .pipe(clean()); callback(); }); gulp.task('copy', function () { gulp.src(['./src/browser.js', './src/app.config.js', './src/*.html']) .pipe(gulp.dest('./app')); gulp.src(['./src/assets/**']) .pipe(gulp.dest('./app/assets')); gulp.src(['./package.json']).pipe(gulp.dest('./app')); gulp.src(['./node_modules/electron-sudo/**']) .pipe(gulp.dest('./app/node_modules/electron-sudo')); }); gulp.task('webpack', function (callback) { webpack(webpackConfig, function (err, stats) { if (err) { throw new gutil.PluginError('webpack', err); } gutil.log('[webpack]', stats.toString({ modules: false, colors: true })); callback(); }); }); gulp.task('sass', function () { gulp.src('./src/sass/main.scss') .pipe( sass({ includePaths: [path.join(__dirname, './src/sass')], outputStyle: 'compressed' }) .on('error', sass.logError)) .pipe(gulp.dest('./app')); }); gulp.task('build', ['copy', 'sass', 'webpack']); var deleteUselessFiles = function (platform, distPath) { var filesToBeRemoved = []; switch (platform) { case 'win32': filesToBeRemoved = [ '*.html', 'LICENSE', 'version', 'pdf.dll', 'libEGL.dll', 'locales/*.*', 'libGLESv2.dll', 'xinput1_3.dll', 'd3dcompiler.dll', 'vccorlib120.dll', 'snapshot_blob.bin', 'd3dcompiler_47.dll', './resources/default_app', 'ui_resources_200_percent.pak', 'content_resources_200_percent.pak', ]; break; case 'darwin': filesToBeRemoved = [ '*.html', 'LICENSE', 'version', '/' + APP_NAME + '.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Resources/snapshot_blob.bin', ]; break; case 'linux': filesToBeRemoved = [ '*.html', 'LICENSE', 'version', 'locales/*.*', 'snapshot_blob.bin', './resources/default_app', ]; break; } filesToBeRemoved = filesToBeRemoved.map((file) => { return path.join(distPath, file); }); console.log('Removed unnecessary files.'); return gulp.src(filesToBeRemoved).pipe(clean()); } var compressFiles = function (platform, distPath, callback) { var upx = ''; var filesToBeCompressed = []; switch (platform) { case 'win32': upx = path.join(__dirname, 'tools/upx.exe') filesToBeCompressed = [ 'node.dll', 'msvcr120.dll', 'msvcp120.dll', APP_NAME + '.exe', ]; break; case 'darwin': upx = path.join(__dirname, 'tools/upx'); break; case 'linux': upx = path.join(__dirname, 'tools/upx-' + process.arch); filesToBeCompressed = [ APP_NAME, 'libnode.so', ]; break; } console.log('Compressing executables...'); filesToBeCompressed.forEach((file) => { var fullPath = path.join(distPath, file); childProcess.exec(upx + ' -9 ' + fullPath, function (error, stdout, stderr) { if (error) { gutil.log(error); } gutil.log(stdout, stderr); }); }); } var buildPackage = function (platform, arch, callback) { var icon; switch (platform) { case 'win32': icon = './app/assets/images/icon.ico'; break; case 'darwin': icon = './app/assets/images/icon.icns'; break; default: icon = './app/assets/images/icon.png'; break; } packager({ arch: arch, icon: icon, dir: './app', out: './build', name: APP_NAME, version: '0.36.2', platform: platform, }, function (err, appPath) { if (appPath) { var distPath = appPath[0]; callback(platform, arch, distPath); } }); } var afterPackage = function (platform, arch, distPath) { deleteUselessFiles(platform, distPath); compressFiles(platform, distPath); } gulp.task('package', ['build'], function (callback) { gulp.src('./app/*.map').pipe(clean()); buildPackage(process.platform, process.arch, afterPackage); }); gulp.task('package-x32', ['build'], function (callback) { gulp.src('./app/*.map').pipe(clean()); buildPackage(process.platform, 'ia32', afterPackage); }); gulp.task('watch', ['build'], function () { gulp.watch('./src/sass/**/*.scss', ['sass']); gulp.watch(['./src/js/**/*.*', './src/app.config.js'], ['webpack']); gulp.watch(['./src/*.html', './package.json', './src/browser.js', './src/assets/**/*.*', './src/app.config.js', './node_modules/electron-sudo/**'], ['copy']); }); gulp.task('default', ['build']);
JavaScript
0
@@ -1921,81 +1921,18 @@ 'l -ibEGL.dll',%0A 'locales/*.*',%0A 'libGLESv2.dll +ocales/*.* ',%0A @@ -3356,24 +3356,54 @@ 'node.dll',%0A + 'libEGL.dll',%0A @@ -3446,32 +3446,65 @@ 'msvcp120.dll',%0A + 'libGLESv2.dll',%0A
4666c63b369dfbfdd0a51cb5e0549d1d1cb96597
Update gulp task
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const tsc = require('gulp-typescript'); const sourcemaps = require('gulp-sourcemaps'); const merge = require('merge2'); const clean = require('gulp-clean'); const tsProject = tsc.createProject('tsconfig.json'); gulp.task('clean', () => { const tsResult = gulp.src(['./src/**/*.d.ts', './src/**/*.js', './src/**/*.js', './src/**/*.js.map']); return tsResult.pipe(clean()); }); gulp.task('release', ['clean'], () => { const tsResult = gulp.src(['./src/**/*.ts', '!./src/**/*.spec.ts']) .pipe(sourcemaps.init()) .pipe(tsProject()); return merge([ tsResult.js .pipe(sourcemaps.write('.')) .pipe(gulp.dest('./src')), tsResult.dts .pipe(gulp.dest('./src')) ]); });
JavaScript
0.000003
@@ -264,32 +264,22 @@ =%3E %7B%0A -const tsResult = +return gulp.sr @@ -359,27 +359,13 @@ p'%5D) -; %0A -return tsResult + .pip
af3e7e5b4db6100dd92889a8224ce18a984611e9
clean up gulpfile
gulpfile.js
gulpfile.js
var gulp = require('gulp'), child = require('child_process'); // Top Level Commands ---------------------------------------------------------- gulp.task('default', ['info']); gulp.task('lint', ['dolint']); gulp.task('example', ['serve']); gulp.task('build', ['dobuild']); // Helper Tasks ---------------------------------------------------------------- gulp.task('info', function() { console.log('\nUsage:\t gulp [ lint | example | build ]\n'); }); gulp.task('dolint', function() { return child.spawn('./node_modules/.bin/jscs', ['./'], { stdio: 'inherit' }); }); gulp.task('serve', function() { console.log('Go to http://127.0.0.1:8080/example/'); return child.spawn('./node_modules/.bin/http-server', ['./'], { stdio: 'inherit' }); }); gulp.task('dobuild', function() { var min = ['-o', 'build/config.js', 'out=dist/validator.min.js', 'optimize=uglify'], max = ['-o', 'build/config.js', 'out=dist/validator.js', 'optimize=none']; child.spawn('./node_modules/.bin/r.js', min, { stdio: 'inherit' }); return child.spawn('./node_modules/.bin/r.js', max, { stdio: 'inherit' }); });
JavaScript
0.000002
@@ -259,23 +259,38 @@ ild', %5B' -do +build-min', ' build +-max '%5D);%0A%0A// @@ -822,15 +822,17 @@ sk(' -do build +-min ', f @@ -941,23 +941,141 @@ uglify'%5D -,%0A +;%0A return child.spawn('./node_modules/.bin/r.js', min, %7B stdio: 'inherit' %7D);%0A%7D);%0A%0Agulp.task('build-max', function() %7B%0A var max = %5B @@ -1145,79 +1145,8 @@ e'%5D; -%0A%0A child.spawn('./node_modules/.bin/r.js', min, %7B stdio: 'inherit' %7D); %0A r
54318e30f78b358ab0a00e8827da11d2d85f0cd7
add admin style
public/vendor/admindata.js
public/vendor/admindata.js
$(document).ready(function(){ $.ajax({ url: "http://localhost:3000/api/pan", success: function(result){ var adminHtml = ''; $.each(result, function(k,v) { adminHtml += ` <tr class="single-list"> <td class="text-center baseimage" style="background-image: url('data:image/png;base64,`+v.rawImage+`');"> </td> <td class="text-center"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <table class="table-fill table-mini"> <thead> <tr class="table-mini-head"> <th class="text-center server_details">Details</th> <th class="text-center status">Correct</th> <th class="text-center status">Wrong</th> <th class="text-center status">Modify</th> </tr> </thead> <tbody class="table-hover"> <tr> <td class="text-center" class="name"> `+v.name+` </td> <td> <input type="radio" name="name-data" value="correct"> </td> <td> <input type="radio" name="name-data" value="wrong"> </td> <td> <input type="radio" name="name-data" value="modified" data-name="modified-data"> </td> </tr> <tr> <td class="text-center" class="pan"> `+v.panNumber+` </td> <td> <input type="radio" name="pan-data" value="correct"> </td> <td> <input type="radio" name="pan-data" value="wrong"> </td> <td> <input type="radio" name="pan-data" value="modified" data-pan="modified-data"> </td> </tr> <tr> <td class="text-center" class="Date"> `+v.dob+` </td> <td> <input type="radio" name="dob-data" value="correct"> </td> <td> <input type="radio" name="dob-data" value="wrong"> </td> <td> <input type="radio" name="dob-data" value="modified" data-dob="modified-data"> </td> </tr> </tbody> </table> </div> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 feedback-btns"> <button type="submit" class="btn btn-primary">Submit</button> </div> </td> </tr> `; $('#adminData').html(adminHtml); }); }, complete: function (jqXHR, status) { window.sr = ScrollReveal(); var block = { reset: true, duration : 1000 } setTimeout(function() { sr.reveal(".single-list", block); },100); function editable() { $("input[type='radio']").on('click', function() { if($(this).data('name') || $(this).data('pan') || $(this).data('dob')) { $(this).closest("tr").find("td:first").attr('contenteditable', 'true'); } }); } editable(); } }); });
JavaScript
0
@@ -4134,16 +4134,43 @@ 'true') +.css('font-weight', 'bold') ;%0A%09%09%09%09%09%7D
120f388879456cb4e07237af8d97ff873102e2dc
Add missing test files to 'gulp test' default.
gulpfile.js
gulpfile.js
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var util = require('./lib/util'); var mocha = require('gulp-mocha'); var gutil = require('gulp-util'); var peg = require('gulp-peg'); var JS_SOURCES = ['gulpfile.js', 'lib/*.js', 'bin/firebase-bolt', 'test/*.js']; var TEST_FILES = ['test/generator-test.js', 'test/parser-test.js']; gulp.task('lint', function() { return gulp.src(JS_SOURCES.concat(['!lib/rules-parser.js'])) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('build', ['build-peg', 'browserify-bolt']); gulp.task('build-peg', function() { return gulp.src('src/rules-parser.pegjs') .pipe(peg()) .pipe(gulp.dest('lib')); }); gulp.task('browserify-bolt', ['build-peg'], function() { return browserifyToDist('lib/bolt.js', { standalone: 'bolt' }); }); // TODO: Use source to pipe glob of test files through browserify. gulp.task('browserify-parser-test', function() { return browserifyToDist('test/parser-test.js', { exclude: 'bolt' }); }); gulp.task('browserify-generator-test', function() { return browserifyToDist('test/generator-test.js', { exclude: 'bolt' }); }); gulp.task('browserify-mail-test', function() { return browserifyToDist('test/mail-test', { exclude: 'bolt' }); }); gulp.task('browserify', ['browserify-bolt', 'browserify-parser-test', 'browserify-generator-test', 'browserify-mail-test']); // Runs the Mocha test suite gulp.task('test', ['lint', 'build'], function() { return gulp.src(TEST_FILES) .pipe(mocha({ui: 'tdd'})); }); gulp.task('default', ['test']); function browserifyToDist(entry, opts) { // Browserify options include: // standalone: name of exported module // exclude: Don't include namespace. // debug: Include sourcemap in output. opts = util.extend({}, opts, { entries: [entry], debug: true }); var exclude = opts.exclude; delete opts.exclude; var b = browserify(opts); if (exclude) { b.exclude(exclude); } return b .bundle() .pipe(source(path.basename(entry))) .on('error', gutil.log) .pipe(gulp.dest('dist')); }
JavaScript
0
@@ -1135,24 +1135,83 @@ ser-test.js' +,%0A 'test/ast-test.js', 'test/util-test.js' %5D;%0A%0Agulp.tas
ed29356d2e5c8a19d97ef7f4b90cdcb4e9f58768
add test
test/static/itemSpec.js
test/static/itemSpec.js
describe("Awesomplete.ITEM", function () { subject(function () { return Awesomplete.ITEM }); def("element", function () { return this.subject("JavaScript", this.input || "") }); it("creates DOM element", function () { expect(this.element instanceof HTMLElement).toBe(true); }); it("creates LI element", function () { expect(this.element.tagName).toBe("LI"); }); it("sets aria-selected to false", function () { expect(this.element.getAttribute("aria-selected")).toBe("false"); }); describe("with matched input", function () { def("input", "jav"); it("marks the match", function () { expect(this.element.innerHTML).toBe("<mark>Jav</mark>aScript"); }); }); describe("with multiple matches", function () { def("input", "a"); it("marks all matches", function () { expect(this.element.innerHTML).toBe("J<mark>a</mark>v<mark>a</mark>Script"); }); }); describe("with no match", function () { def("input", "foo"); it("does not mark anything", function () { expect(this.element.innerHTML).toBe("JavaScript"); }); }); describe("with empty input", function () { def("input", ""); it("does not mark anything", function () { expect(this.element.innerHTML).toBe("JavaScript"); }); }); });
JavaScript
0.000002
@@ -1120,24 +1120,201 @@ put%22, %22%22);%0A%0A +%09%09it(%22does not mark anything%22, function () %7B%0A%09%09%09expect(this.element.innerHTML).toBe(%22JavaScript%22);%0A%09%09%7D);%0A%09%7D);%0A%0A%09describe(%22with space input%22, function () %7B%0A%09%09def(%22input%22, %22 %22);%0A%0A %09%09it(%22does n
016f6585cb5dd57df49a22008dd917b0c87b4694
add .listeners
src/EventEmitter.js
src/EventEmitter.js
'use strict'; /** * Create an EventEmitter * @constructor */ function EventEmitter() { /** * A hash to hold all registered events and their listeners * properties are event names, their values are arrays of * listeners for that event */ this._events = {}; } /** * Register an event that will trigger listener * @param {Mixed} evt - The event to listen for * @param {function} listener - The function to call when evt happens * @returns {Object} - Return the emitter */ EventEmitter.prototype.on = function(evt, listener) { if(typeof listener !== 'function') { throw new TypeError('listener should be a function'); } this._events[evt] = this._events[evt] || []; this._events[evt].push(listener); return this; }; /** * Trigger an event * @param {Mixed} evt - The event to trigger * @param {Mixed} [..var_args] - Optional arguments to pass to listener * @returns {Boolean} - true if evt trigged a listener */ EventEmitter.prototype.emit = function(evt /*, var_args */) { var listeners = this._events[evt], args = Array.prototype.slice.call(arguments, 1), self = this; if(listeners && listeners.length) { listeners.forEach(function(item) { if(typeof item === 'function') { item.apply(self, args); } else if(typeof item === 'object' && item.outer) { item.outer.apply(self, args); } }); return true; } return false; }; /** * Remove all listeners to an event. If no event is specified, * remove all listeners * @param {Mixed} [evt] - The event whose listeners to remove * @returns {Object} - Returns the emitter */ EventEmitter.prototype.removeAllListeners = function(evt) { if(evt) { delete this._events[evt]; } else { this._events = {}; } return this; }; /** Remove a listener from an event * @param {Mixed} evt - The event to remove from * @param {Function} listener - The listener to remove * @returns {Object} - Returns the emitter */ EventEmitter.prototype.removeListener = function(evt, listener) { var listeners = this._events[evt]; if(typeof listener !== 'function') { throw new TypeError('listener must be a function'); } if(listeners) { listeners.forEach(function(item, index, arr) { if(item === listener) { arr.splice(index, 1); } else if(typeof item === 'object' && item.inner === listener) { arr.splice(index,1); } }); } return this; }; /** * Register an event listener to be fired once * Once the event has triggered, the listener is removed * @param {Mixed} evt - The event to listen for * @param {Function} listener - The function to trigger * @returns {Object} - Return the emitter */ EventEmitter.prototype.once = function(evt, listener) { var self = this, wrapper; if(typeof listener !== 'function') { throw new TypeError('listener must be a function'); } wrapper = function wrap() { listener(); self.removeListener(evt, listener); }; /* Need to save a reference to listener so we can still delete it * .emit executes the outer function, * .removeListener removes based on inner function */ this._events[evt] = this._events[evt] || []; this._events[evt].push({ 'outer': wrapper, 'inner': listener }); return this; }; EventEmitter.prototype.listeners = function(evt) { }; module.exports = EventEmitter;
JavaScript
0
@@ -3547,59 +3547,354 @@ %7D;%0A%0A -EventEmitter.prototype.listeners = function(evt) %7B%0A +/**%0A * Return an array of listeners for an event%0A * @param %7BMixed%7D evt - The event whose listeners to get%0A * @returns %7BArray%7D - An array of listeners for the event%0A * Empty array if event isnt registered%0A */%0AEventEmitter.prototype.listeners = function(evt) %7B%0A%0A var listeners = this._events%5Bevt%5D;%0A%0A return listeners %7C%7C %5B%5D; %0A%7D;%0A
1f8ccf7eca00247e2037fbf67ef9c5b734b7c702
Add Gulp serve
gulpfile.js
gulpfile.js
/** * @author Ulrik Moe * @license GPLv3 * * Indentation: 4 spaces * Conventions: https://github.com/airbnb/javascript * * Use 'gulp --min' **/ 'use strict'; const gulp = require('gulp'); const del = require('del'); const gutil = require('gulp-util'); const connect = require('gulp-connect'); const uglify = require('gulp-uglify'); const nunjucks = require('gulp-nunjucks-html'); const htmlmin = require('gulp-htmlmin'); const less = require('gulp-less'); const nano = require('gulp-cssnano'); const babel = require('gulp-babel'); const concat = require('gulp-concat'); // Last changed const months = ['januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december']; const date = new Date(); const updated = date.getDate() + '. ' + months[date.getMonth()] + ' ' + date.getFullYear(); // Global variables const config = { htmlmin: { removeComments: true, collapseWhitespace: true }, uglify: { mangle: { sort: true, toplevel: true }, compress: { drop_console: true, loops: false, unused: false } }, babel: { plugins: ['transform-es2015-block-scoping', 'transform-es2015-shorthand-properties', 'transform-es2015-for-of'] }, nunjucks: { searchPaths: ['www/'], locals: { lastUpdate: updated } } }; function server() { connect.server({ root: 'www', livereload: !gutil.env.min }); } function assets() { return gulp.src(['src/assets/**/*'], { base: 'src/assets', since: gulp.lastRun(assets) }) .pipe(gulp.dest('www')) .pipe(connect.reload()); } function scripts() { return gulp.src(['src/js/data.js', 'src/js/kortgebyr.js']) .pipe(gutil.env.min ? babel(config.babel) : gutil.noop()) .pipe(concat('all.js')) .pipe(gutil.env.min ? uglify(config.uglify) : gutil.noop()) .pipe(gulp.dest('www')); } function less2css() { return gulp.src(['src/css/**/*'], { since: gulp.lastRun(less2css) }) .pipe(less()) .pipe(gutil.env.min ? nano({ safe: true }) : gutil.noop()) .pipe(gulp.dest('www')) .pipe(connect.reload()); } function html() { return gulp.src(['src/**/*.html']) .pipe(nunjucks(config.nunjucks)) .pipe(gutil.env.min ? htmlmin(config.htmlmin) : gutil.noop()) .pipe(gulp.dest('www')) .pipe(connect.reload()); } function stalker() { gulp.watch(['src/assets/**/*'], assets); gulp.watch(['src/**/*.html'], html); gulp.watch(['src/css/*.less'], gulp.series(less2css, html)); gulp.watch(['src/js/data.js', 'src/js/kortgebyr.js'], gulp.series(scripts, html)); gulp.watch(['i18n/*.json'], gulp.series('build')); } gulp.task('clean', function () { return del(['www/**', '!www']); }); gulp.task('build', gulp.series('clean', assets, scripts, less2css, html)); gulp.task('default', gulp.series( 'clean', assets, scripts, less2css, html, gulp.parallel(stalker, server) ));
JavaScript
0
@@ -2739,16 +2739,68 @@ %5D); %7D);%0A +gulp.task('serve', gulp.parallel(stalker, server));%0A gulp.tas @@ -2899,21 +2899,16 @@ .series( -%0A 'clean', @@ -2944,44 +2944,16 @@ tml, -%0A gulp.parallel(stalker, +' serve -r)%0A +' ));%0A
f3c21a411e8bd3c30856ee7aba24e8e25e40aad1
Fix typo
gulpfile.js
gulpfile.js
/*jshint node: true, globalstrict: true, esnext: false */ "use strict"; // Imports // ------- var spawnSync = require("child_process").spawnSync; var gulp = require("gulp-help")(require("gulp")); var to5 = require("gulp-6to5"); var uglify = require("gulp-uglify"); var rename = require("gulp-rename"); // `gulp build` // ------------ gulp.task("build" , "Built the lot." , ["scripts"] ); // `gulp scripts` // -------------- var scripts = { source: "source/n.js" }; gulp.task("scripts" , "Build ES5 and ES6 dist scripts." , ["scripts:es6", "scripts:es5"] ); gulp.task("scripts:es6", false, function () { return gulp .src(scripts.source) .pipe(gulp.dest("dist")) ; }); gulp.task("scripts:es5", false, function () { return gulp .src(scripts.source) .pipe(to5({modules: "6-to-library"})) .pipe(gulp.dest("dist.es5")) .pipe(uglify()) .pipe(rename({extname: ".min.js"})) .pipe(gulp.dest("dist.es5")) ; }); // `gulp gh-pages` // ---------=----- gulp.task("gh-pages" , "Build gh-pages in their branch." , function (done) { var dirty; try { dirty = !!spawnSync("git", ["status", "--porcelain"]).output[1].toString(); if (dirty) spawnSync("git", ["stash", "save", "--include-untracked"]); spawnSync("git" ["checkout", "gh-pages"]); spawnSync("git" ["checkout", "master", scripts.source]); spawnSync("git" ["reset"]); spawnSync("./node_modules/.bin/docco", ["source/**.js"]); spawnSync("rm", ["-rf", "source"]); spawnSync("mv", ["docs/*", "."]); spawnSync("mv", ["*.html", "index.html"]); spawnSync("git", ["add", "--all", "."]); spawnSync("git", ["commit", "--message", "Automatic docs update"]); spawnSync("git", ["checkout", "master"]); if (dirty) spawnSync("git", ["stash", "pop"]); } catch (error) {done(error);} done(); } );
JavaScript
0.999999
@@ -361,17 +361,17 @@ , %22Buil -t +d the lot
1ce0247de014fb1e97b742351166b50355ca2c9c
fix watchify.
gulpfile.js
gulpfile.js
/** * Copied from * https://github.com/gulpjs/gulp/blob/8701b9dda6303429adacea4661311287e172cda3/docs/recipes/fast-browserify-builds-with-watchify.md * * Created by kdbanman on 2/29/16. */ 'use strict'; // REQUIREMENTS var fs = require('fs'); var gulp = require('gulp'); var gutil = require('gulp-util'); var mocha = require('gulp-mocha'); var jshint = require('gulp-jshint'); var sourcemaps = require('gulp-sourcemaps'); var browserify = require('browserify'); var watchify = require('watchify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var assign = require('lodash.assign'); var insideTravis = fs.existsSync('/home/travis'); // CONFIGURATION var browserifyConfig = { entries: ['./polyball/Client.js'], debug: true }; var testFile = './polyball/tests/**/*.js'; var testReporter = process.env.NO_NYAN === 'true' ? 'spec' : 'nyan'; var lintReporter = 'jshint-stylish'; var lintConfig = { verbose: true }; // TASKS gulp.task('build-js', browserifyBundle); gulp.task('run-tests', tests); gulp.task('lint', lint); gulp.task('default', ['lint', 'build-js', 'run-tests']); gulp.task('watch-js', watchifyBundle); function bundle(bundler) { return bundler.bundle() // log errors if they happen .on('error', gutil.log.bind(gutil, 'Browserify Error')) .on('error', function(){ process.exit(1);}) .pipe(source('client-bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) // Add transformation tasks to the pipeline here. .pipe(sourcemaps.write('./')) // writes .map file .pipe(gulp.dest('./public/bin')); } function browserifyBundle() { var bify = browserify(browserifyConfig); return bundle(bify); } function tests(){ return gulp.src(testFile, {read: false}) .pipe(mocha({reporter: testReporter})); } function lint(){ return gulp.src('./polyball/**/*.js') .pipe(jshint()) .pipe(jshint.reporter(lintReporter, lintConfig)) .pipe(jshint.reporter('fail')); } function watchifyBundle() { var opts = assign({}, watchify.args, browserifyConfig); var wify = watchify(browserify(opts)); wify.on('update', bundle); // on any dep update, run the bundler wify.on('update', lint); // on any dep update, run the linter wify.on('log', gutil.log); // output build logs to terminal return bundle(wify); }
JavaScript
0
@@ -631,59 +631,8 @@ ;%0A%0A%0A -var insideTravis = fs.existsSync('/home/travis');%0A%0A // C @@ -1309,18 +1309,20 @@ function + () + %7B%0A @@ -1343,17 +1343,465 @@ exit(1); -%7D +%0A %7D)%0A .pipe(source('client-bundle.js'))%0A .pipe(buffer())%0A .pipe(sourcemaps.init(%7BloadMaps: true%7D))%0A // Add transformation tasks to the pipeline here.%0A .pipe(sourcemaps.write('./')) // writes .map file%0A .pipe(gulp.dest('./public/bin'));%0A%7D%0A%0Afunction bundle_nokill(bundler) %7B%0A return bundler.bundle()%0A // log errors if they happen%0A .on('error', gutil.log.bind(gutil, 'Browserify Error') )%0A @@ -2141,24 +2141,25 @@ ifyConfig);%0A +%0A return b @@ -2168,16 +2168,22 @@ dle(bify +, true );%0A%7D%0A%0Afu @@ -2469,32 +2469,185 @@ er('fail'));%0A%7D%0A%0A +function lint_nokill() %7B%0A return gulp.src('./polyball/**/*.js')%0A .pipe(jshint())%0A .pipe(jshint.reporter(lintReporter, lintConfig));%0A%0A%7D%0A%0A function watchif @@ -2783,22 +2783,71 @@ pdate', -bundle +function () %7B%0A return bundle_nokill(wify);%0A %7D ); // on @@ -2905,16 +2905,23 @@ e', lint +_nokill ); // @@ -3018,16 +3018,17 @@ erminal%0A +%0A retu @@ -3036,16 +3036,23 @@ n bundle +_nokill (wify);%0A
b77da28d952c88c7bd61e062b22d4d3c7eefc869
Test createSocket as best we can.
test/subjection_spec.js
test/subjection_spec.js
const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const expect = chai.expect; chai.use(sinonChai); const util = require('util'); import { EventEmitter } from 'events'; import * as jmp from 'jmp'; import { deepFreeze, createObserver, createObservable, createSubject, } from '../src/subjection'; describe('deepFreeze', () => { it('should Object.freeze nested objects', () => { const obj = { a: 1, b: { bb: { c: 3, }, }, }; deepFreeze(obj); expect((() => {obj.a = 2;})).to.throw('Cannot assign to read only property'); expect((() => {obj.b.bb.c = 42;})).to.throw('Cannot assign to read only property'); expect((() => {obj.d = 12;})).to.throw('Can\'t add property d, object is not extensible'); }); }); describe('createObserver', () => { it('creates an observer from a socket', () => { const hokeySocket = { send: sinon.spy(), removeAllListeners: sinon.spy(), close: sinon.spy(), }; const ob = createObserver(hokeySocket); const message = { content: { x: 2 } }; ob.onNext(message); expect(hokeySocket.send).to.have.been.calledWith(new jmp.Message(message)); }); it('removes all listeners and closes the socket onCompleted', () => { const hokeySocket = { send: sinon.spy(), removeAllListeners: sinon.spy(), close: sinon.spy(), }; const ob = createObserver(hokeySocket); ob.onCompleted(); expect(hokeySocket.removeAllListeners).to.have.been.calledWith(); expect(hokeySocket.close).to.have.been.calledWith(); }); it('should only close once', () => { const hokeySocket = { send: sinon.spy(), removeAllListeners: sinon.spy(), close: sinon.spy(), }; const ob = createObserver(hokeySocket); ob.onCompleted(); expect(hokeySocket.removeAllListeners).to.have.been.calledWith(); expect(hokeySocket.close).to.have.been.calledWith(); hokeySocket.removeAllListeners = sinon.spy(); hokeySocket.close = sinon.spy(); ob.onCompleted(); expect(hokeySocket.removeAllListeners).to.not.have.been.calledWith(); expect(hokeySocket.close).to.not.have.been.calledWith(); }); }); describe('createObservable', () => { it('publishes clean enchannel messages', (done) => { const emitter = new EventEmitter(); const obs = createObservable(emitter); obs.subscribe(msg => { expect(msg).to.deep.equal({ content: { success: true, }, }); done(); }); const msg = { idents: [], signatureOK: true, blobs: [], content: { success: true, }, }; emitter.emit('message', msg); }); it('publishes deeply frozen objects', (done) => { const emitter = new EventEmitter(); const obs = createObservable(emitter); obs.subscribe(msg => { expect(Object.isFrozen(msg)).to.be.true; expect(Object.isFrozen(msg.content)).to.be.true; done(); }); const msg = { idents: [], signatureOK: true, blobs: [], content: { success: true, }, }; emitter.emit('message', msg); }); }); describe('createSubject', () => { it('creates a subject that can send and receive', (done) => { // This is largely captured above, we make sure that the subject gets // created properly const hokeySocket = new EventEmitter(); hokeySocket.removeAllListeners = sinon.spy(); hokeySocket.send = sinon.spy(); hokeySocket.close = sinon.spy(); const s = createSubject(hokeySocket); s.subscribe(msg => { expect(msg).to.deep.equal({ content: { success: true, }, }); s.close(); expect(hokeySocket.removeAllListeners).to.have.been.calledWith(); expect(hokeySocket.close).to.have.been.calledWith(); done(); }); const msg = { idents: [], signatureOK: true, blobs: [], content: { success: true, }, }; const message = { content: { x: 2 } }; s.send(message); expect(hokeySocket.send).to.have.been.calledWith(new jmp.Message(message)); hokeySocket.emit('message', msg); }); });
JavaScript
0
@@ -1,12 +1,71 @@ +/* eslint camelcase: 0 */ // %3C-- Per Jupyter message spec%0A%0A const chai = @@ -212,19 +212,19 @@ %0Aconst u -til +uid = requi @@ -232,11 +232,11 @@ e('u -til +uid ');%0A @@ -272,24 +272,72 @@ 'events';%0A%0A +import * as constants from '../src/constants';%0A%0A import * as @@ -414,16 +414,16 @@ rvable,%0A - create @@ -431,16 +431,32 @@ ubject,%0A + createSocket,%0A %7D from ' @@ -4343,28 +4343,571 @@ ('message', msg);%0A %7D);%0A%7D);%0A +%0Adescribe('createSocket', () =%3E %7B%0A it('creates a JMP socket on the channel with identity', () =%3E %7B%0A const config = %7B%0A signature_scheme: 'hmac-sha256',%0A key: '5ca1ab1e-c0da-aced-cafe-c0ffeefacade',%0A ip: '127.0.0.1',%0A transport: 'tcp',%0A iopub_port: 9009,%0A %7D;%0A const identity = uuid.v4();%0A%0A const socket = createSocket('iopub', identity, config);%0A expect(socket).to.not.be.null;%0A expect(socket.identity).to.equal(identity);%0A expect(socket.type).to.equal(constants.ZMQType.frontend.iopub);%0A %7D);%0A%7D);%0A
1b7f2a019c48ccb4f5591dac47030fa16119ab2b
rename load guard to camel case name
test/swift-simulator.js
test/swift-simulator.js
exports.loadAngularMocks = function () { browser.addMockModule('swiftBrowserE2E', function () { if (!window.e2e_angular_mocks_loaded) { var script = document.createElement('script'); script.src = 'bower_components/angular-mocks/angular-mocks.js'; document.body.appendChild(script); window.e2e_angular_mocks_loaded = true; } angular.module('swiftBrowserE2E', ['ngMockE2E']); }); }; exports.commit = function () { browser.addMockModule('swiftBrowserE2E', function () { angular.module('swiftBrowserE2E').run(function($httpBackend) { $httpBackend.whenGET(/.*/).passThrough(); }); }); } exports.setContainers = function(containers) { /* Testing with Firefox revealed that the array passed in arguments[0] loses its "own properties" when passed into the browser. That is, running Object.getOwnPropertyNames(arguments[0]) Object.getOwnPropertyNames(arguments[0][0]) both return empty arrays in the function below. We can convert arguments[0] to an array, but the objects in the array (the data about individual containers) will be empty since their properties are no longer defined. Converting to and from JSON is a work-around for this. */ browser.addMockModule('swiftBrowserE2E', function () { var containers = JSON.parse(arguments[0]); angular.module('swiftBrowserE2E').run(function($httpBackend) { $httpBackend.whenGET('/app/index.html?format=json') .respond(containers); }); }, JSON.stringify(containers)); } exports.setObjects = function(container, objects) { browser.addMockModule('swiftBrowserE2E', function () { var container = arguments[0]; var objects = JSON.parse(arguments[1]); function escape(string) { return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"); } function parseQueryString(qs) { var params = {}; var parts = qs.split('&'); for (var i = 0; i < parts.length; i++) { var keyvalue = parts[i].split('='); var key = decodeURIComponent(keyvalue[0]); var value = decodeURIComponent(keyvalue[1]); params[key] = value; } return params; } var fixed = '/app/index.html/' + container + '?'; var regex = new RegExp(escape(fixed) + '(.*)'); function listObjects(method, url, data) { var match = url.match(regex); var params = parseQueryString(match[1]); var results = []; for (var i = 0; i < objects.length; i++) { var object = objects[i]; if (object.name.indexOf(params.prefix) == 0) { var rest = object.name.slice(params.prefix.length); var idx = rest.indexOf(params.delimiter); if (idx > -1) { results.push({subdir: rest.slice(0, idx + 1)}) } else { results.push(object); } } } return [200, results]; } angular.module('swiftBrowserE2E').run(function($httpBackend) { $httpBackend.whenGET(regex).respond(listObjects); }); }, container, JSON.stringify(objects)); }
JavaScript
0.000002
@@ -117,32 +117,29 @@ ndow.e2e -_a +A ngular -_m +M ocks -_l +L oaded) %7B @@ -347,24 +347,21 @@ .e2e -_a +A ngular -_m +M ocks -_l +L oade
c1e564a56c05fd121ccacafe93c69072702bdaa8
moved helper out of spec
test/task/TaskShared.js
test/task/TaskShared.js
'use strict'; /** * Requirements */ const baseSpec = require(ES_TEST + '/BaseShared.js').spec; const sinon = require('sinon'); const co = require('co'); const gulp = require('gulp'); /** * Shared Task spec */ function spec(type, className, prepareParameters, options) { const opts = options || {}; /** * Base Test */ baseSpec(type, className, prepareParameters); /** * Task Test */ const createTestee = function() { let parameters = Array.from(arguments); if (prepareParameters) { parameters = prepareParameters(parameters); } return new type(...parameters); }; /** * Reads the given stream and resolves to an array of all chunks */ function readStream(stream) { const promise = new Promise((resolve) => { const data = []; stream.on('data', (item) => { process.nextTick(() => { data.push(item); }); }) .on('finish', () => { process.nextTick(() => { resolve(data); }); }); }); return promise; } spec.readStream = readStream; /** * Creates a stream of files */ function filesStream(glob) { return gulp.src(glob); } spec.filesStream = filesStream; /** * Creates a stream of files and waits until they ran through the task */ function feedFiles(task, glob) { return readStream(task.stream(filesStream(glob))); } spec.feedFiles = feedFiles; describe('#pipe()', function() { it('should return the piped Task', function() { const testee = createTestee(); const pipedTestee = createTestee(); const result = testee.pipe(pipedTestee); expect(result).to.be.equal(pipedTestee); return result; }); it('should set previousTask on the piped task', function() { const testee = createTestee(); const pipedTestee = createTestee(); const result = testee.pipe(pipedTestee); expect(pipedTestee.previousTask).to.be.equal(testee); return result; }); it('should set nextTask on the task', function() { const testee = createTestee(); const pipedTestee = createTestee(); const result = testee.pipe(pipedTestee); expect(testee.nextTask).to.be.equal(pipedTestee); return result; }); }); describe('#stream()', function() { it('should return a stream', function() { const promise = co(function *() { const testee = createTestee(); const result = testee.stream(); expect(result.pipe).to.be.instanceof(Function); // We want to support through2 here.... yield readStream(result); }); return promise; }); }); describe('#run()', function() { it('should return a promise', function() { const testee = createTestee(); const result = testee.run(); expect(result).to.be.instanceof(Promise); return result; }); if (!opts.skipDelegateTest) { it('should delegate to the root task', function() { const promise = co(function *() { const testee = createTestee(); const pipedTestee = createTestee(); sinon.spy(testee, 'run'); sinon.spy(pipedTestee, 'run'); testee.pipe(pipedTestee); yield pipedTestee.run(); expect(testee.run.calledOnce).to.be.ok; expect(pipedTestee.run.calledOnce).to.be.ok; }); return promise; }); } }); } /** * Exports */ module.exports.spec = spec;
JavaScript
0.998551
@@ -671,1046 +671,8 @@ ;%0A%0A%0A - /**%0A * Reads the given stream and resolves to an array of all chunks%0A */%0A function readStream(stream)%0A %7B%0A const promise = new Promise((resolve) =%3E%0A %7B%0A const data = %5B%5D;%0A stream.on('data', (item) =%3E%0A %7B%0A process.nextTick(() =%3E%0A %7B%0A data.push(item);%0A %7D);%0A %7D)%0A .on('finish', () =%3E%0A %7B%0A process.nextTick(() =%3E%0A %7B%0A resolve(data);%0A %7D);%0A %7D);%0A %7D);%0A return promise;%0A %7D%0A spec.readStream = readStream;%0A%0A%0A /**%0A * Creates a stream of files%0A */%0A function filesStream(glob)%0A %7B%0A return gulp.src(glob);%0A %7D%0A spec.filesStream = filesStream;%0A%0A%0A /**%0A * Creates a stream of files and waits until they ran through the task%0A */%0A function feedFiles(task, glob)%0A %7B%0A return readStream(task.stream(filesStream(glob)));%0A %7D%0A spec.feedFiles = feedFiles;%0A%0A%0A @@ -2038,16 +2038,21 @@ yield +spec. readStre @@ -3104,10 +3104,824 @@ %7D);%0A -%0A %7D +%0A%0A%0A/**%0A * Reads the given stream and resolves to an array of all chunks%0A */%0Aspec.readStream = function(stream)%0A%7B%0A const promise = new Promise((resolve) =%3E%0A %7B%0A const data = %5B%5D;%0A stream.on('data', (item) =%3E%0A %7B%0A process.nextTick(() =%3E%0A %7B%0A data.push(item);%0A %7D);%0A %7D)%0A .on('finish', () =%3E%0A %7B%0A process.nextTick(() =%3E%0A %7B%0A resolve(data);%0A %7D);%0A %7D);%0A %7D);%0A return promise;%0A%7D;%0A%0A%0A/**%0A * Creates a stream of files%0A */%0Aspec.filesStream = function(glob)%0A%7B%0A return gulp.src(glob);%0A%7D;%0A%0A%0A/**%0A * Creates a stream of files and waits until they ran through the task%0A */%0Aspec.feedFiles = function(task, glob)%0A%7B%0A return spec.readStream(task.stream(spec.filesStream(glob)));%0A%7D;%0A %0A%0A/*
66b1dcc12dbdb80f1e248d31303e8cad9a04fea4
Fix middleware test for node <= 0.12
test/test-middleware.js
test/test-middleware.js
'use strict'; var Transformer = require('../index.js'); var Middleware = require('../index.js').middleware; var transformer; var Promise = require('bluebird'); var logger; var assert = require('assert'); var AssertionError = assert.AssertionError; var objectPath = require('object-path'); describe('Executing \'jy-transform\' project middleware test suite.', function () { var middleware = function (json) { function key1(json) { objectPath.set(json, 'key1', 'value1'); logger.info('key1 json: ' + JSON.stringify(json)); return Promise.resolve(json); } function key2(json) { objectPath.set(json, 'key2', 'value2'); logger.info('key2 json: ' + JSON.stringify(json)); return Promise.resolve(json); } function key3(json) { objectPath.set(json, 'key3', 'value3'); logger.info('key3 json: ' + JSON.stringify(json)); return Promise.resolve(json); } return Promise.all([key1(json), key2(json), key3(json)]) .then(function(result) { assert.equal(result.length, 3); logger.info('all the elements were created'); logger.info('result: ' + JSON.stringify(result[result.length - 1])); return Promise.resolve(result[result.length - 1]); }); }; var options = { src: {}, //origin: 'js', //target: 'js', dest: {} }; /** * Init the test logger. */ before(function () { logger = require('./logger.js'); transformer = new Transformer(logger); }); describe('Testing Transformer middleware', function () { it('should alter json', function (done) { transformer.transform(options, middleware) .then(function (msg){ logger.info(msg); logger.info('options.dest: ' + JSON.stringify(options.dest, null, 4)); assert.equal(options.dest['key1'], 'value1', 'options.dest.key1 should have value: value1, but was ' + options.dest['key1']); assert.equal(options.dest['key2'], 'value2', 'options.dest.key1 should have value: value2, but was ' + options.dest['key2']); assert.equal(options.dest['key3'], 'value3', 'options.dest.key1 should have value: value3, but was ' + options.dest['key3']); done(); }) .catch(function (err) { logger.error(err.stack); done(err); }); }); }); describe('Testing middleware.ensureMiddleware()', function () { var myMiddleware = function (json) { return Promise.resolve(json); }; it('should provide passed function', function (done) { var func = Middleware.ensureMiddleware(myMiddleware); assert(typeof func === 'function'); assert.deepStrictEqual(func, myMiddleware, 'should return same function'); done(); }); it('should reject Promise if middleware passed is not a function type', function (done) { Middleware.ensureMiddleware({}) .then(function (middleware){ done(new AssertionError({ message: 'rejecting with TypeError', actual: middleware, expected: TypeError, operator: 'instanceof' })); }) .catch(function (err) { assert.notEqual(err, null, 'Promise rejection err should not be null'); assert(err instanceof TypeError); done(); }); }); it('should provide identity Promise if middleware passed is null', function (done) { var func = Middleware.ensureMiddleware(); assert(typeof func === 'function'); done(); }); it('should provide identity Promise if middleware passed is undefined', function (done) { var func = Middleware.ensureMiddleware(undefined); assert(typeof func === 'function'); done(); }); }); });
JavaScript
0.000158
@@ -3012,30 +3012,17 @@ sert -.deepStrictEqual (func -, + === myM @@ -3187,32 +3187,32 @@ nction (done) %7B%0A + Midd @@ -3243,340 +3243,8 @@ %7B%7D)%0A - .then(function (middleware)%7B%0A done(new AssertionError(%7B%0A message: 'rejecting with TypeError',%0A actual: middleware,%0A expected: TypeError,%0A operator: 'instanceof'%0A %7D));%0A %7D)%0A
70d15cf8d9ddaa17c998e0000b83e647f67f6101
don't use double negatives
test/test-validators.js
test/test-validators.js
import assert from 'assert'; import { validateRange, validateWidths, validateWidthTolerance, validateVariableQuality } from '../src/validators'; describe('Validators:', function () { describe('Testing validateWidths', function () { it('throws an error if any width is negative', () => { assert.throws(() => { validateWidths([100, 200, 300, -400]) }) }); it('throws an error if given an empty list', () => { assert.throws(() => { validateWidths([]) }) }); it('throws an error if given a list of non-numeric input', () => { assert.throws(() => { validateWidths([100, 200, 300, '400', '500']) }) }); it('throws an error if given a list of non-integer input', () => { assert.throws(() => { validateWidths([399.99, 499.50]) }) }); it('succeeds silently', () => { let result = validateWidths([100, 200, 300, 400, 500]); assert.strictEqual(result, undefined); }); }); describe('Testing validateRange', function () { it('throws an error if minWidth is not an integer', () => { assert.throws(() => { validateRange(500.9123, 1000) }) }); it('throws an error if maxWidth is not an integer', () => { assert.throws(() => { validateRange(100, 500.9123) }) }); it('throws an error if minWidth is not <= 0', () => { assert.throws(() => { validateRange(-1, 100) }) }); it('throws an error if maxWidth is not <= 0', () => { assert.throws(() => { validateRange(100, -1) }) }); it('throws an error if maxWidth is not >= minWidth', () => { assert.throws(() => { validateRange(500, 100) }) }); it('succeeds silently', () => { let result = validateRange(100, 8192); assert.strictEqual(result, undefined); }); }); describe('Testing validateWidthTolerance', function () { it('throws if typeof widthTolerance is not a number', () => { assert.throws(() => { validateWidthTolerance('0.08') }) }); it('throws if widthTolerance is <= 0', () => { assert.throws(() => { validateWidthTolerance(0) }) }); it('succeeds silently', () => { let result = validateWidthTolerance(0.08); assert.strictEqual(result, undefined); }); // TODO: should fail. it('succeeds silently when widthTolerance === 0.001', () => { let result = validateWidthTolerance(0.001); assert.strictEqual(result, undefined); }); }); describe('Testing validateVariableQuality', function () { it('throws an error if variable quality flag is not a boolean', () => { assert.throws(() => { validateVariableQuality('false') }) assert.throws(() => { validateVariableQuality('true') }) assert.throws(() => { validateVariableQuality(0) }) assert.throws(() => { validateVariableQuality(1) }) }); }); });
JavaScript
0.999861
@@ -1381,38 +1381,41 @@ if minWidth is -not %3C= +less than 0', () =%3E %7B%0A @@ -1531,14 +1531,17 @@ is -not %3C= +less than 0', @@ -1669,14 +1669,17 @@ is -not %3E= +less than min
85c6135ec0ba789611fe91616561a571576b4ed8
Update sync task
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const babel = require('gulp-babel'); const rename = require("gulp-rename"); const eslint = require('gulp-eslint'); const karma = require('karma').Server; const uglify = require('gulp-uglifyjs'); const minify = require("gulp-babel-minify"); const browserSync = require('browser-sync'); // Browser sync task gulp.task('sync', function () { browserSync.init({ server: "./example/" }); // Watch for file changes gulp.watch(['./src/*.js'], ['reload', 'build']); gulp.watch(['./example/*.html', './example/js/*.js', './example/css/*.css'], browserSync.reload); }); // Reload task gulp.task('reload', function () { gulp.src(['./src/turtle.js']) .pipe(babel({ presets: ['env'], plugins: ['add-module-exports', 'transform-es2015-modules-umd'] })) .pipe(uglify()) .pipe(rename('turtle.min.js')) .pipe(gulp.dest('./example/js')) }); // Test task gulp.task('test', function (done) { new karma({ configFile: __dirname + '/karma.conf.js', singleRun: true }, function (exitCode) { done(); process.exit(exitCode); }).start(); }); // Lint task gulp.task('lint', function () { return gulp.src(['./src/turtle.js']) .pipe(eslint({ "parser": "babel-eslint", rules: { "camelcase": 2, "curly": 1, "eqeqeq": 0, "no-empty": 2, "no-const-assign": 2, "no-var": 2, "prefer-const": 1 }, env: { "es6": true }, "parserOptions": { "ecmaVersion": 7 } })) .pipe(eslint.format()) }); // Build task gulp.task('build', function () { gulp.src(['./src/turtle.js']) .pipe(rename('turtle.es7.js')) .pipe(gulp.dest('./dist')) .pipe(minify({ mangle: { keepClassName: true } })) .pipe(rename('turtle.es7.min.js')) .pipe(gulp.dest('./dist')) gulp.src(['./src/turtle.js']) .pipe(babel({ presets: ['env'], plugins: ['add-module-exports', 'transform-es2015-modules-umd'] })) .pipe(gulp.dest('./dist')) .pipe(uglify()) .pipe(rename('turtle.min.js')) .pipe(gulp.dest('./dist')) }); // Set the defaukt task as 'sync' gulp.task('default', ['sync']);
JavaScript
0.000001
@@ -457,16 +457,27 @@ changes + and reload %0D%0A gulp @@ -512,17 +512,8 @@ oad' -, 'build' %5D);%0D
0adfa19c923dd66c338deea67a9bb97f61ec4104
Fix bug in traversal to node
index.es6.js
index.es6.js
const E_ITER = 'Argument 1 of seek must be a NodeIterator.'; const E_SHOW = 'Argument 1 of seek must use filter NodeFilter.SHOW_TEXT.'; const E_WHERE = 'Argument 2 of seek must be a number or a Text Node.'; export default function seek(iter, where) { if (!(iter instanceof NodeIterator)) { throw new Error(E_ITER); } if (iter.whatToShow !== NodeFilter.SHOW_TEXT) { throw new Error(E_SHOW); } let count = 0; let node = iter.referenceNode; let predicates = null; if (isNumber(where)) { predicates = { forward: () => count < where, backward: () => count > where }; } else if (isText(where)) { predicates = { forward: () => before(node, where), backward: () => after(node, where) }; } else { throw new Error(E_WHERE); } while (predicates.forward() && (node = iter.nextNode()) !== null) { count += node.textContent.length; } while (predicates.backward() && (node = iter.previousNode()) !== null) { count -= node.textContent.length; } return count; } function isNumber(n) { return !isNaN(parseInt(n)) && isFinite(n); } function isText(node) { return node.nodeType === Node.TEXT_NODE; } function before(referenceNode, node) { return referenceNode.compareDocumentPosition(node) & (Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_CONTAINED_BY); } function after(referenceNode, node) { return referenceNode.compareDocumentPosition(node) & (Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_CONTAINS); }
JavaScript
0.000002
@@ -716,16 +716,52 @@ d: () =%3E + !iter.pointerBeforeReferenceNode %7C%7C after(n
29221569142361efe47364422d2de2f040c05c53
Add comments
index.esm.js
index.esm.js
/* *************************************************************************************** ES6 version of milsymbol *************************************************************************************** */ export { ms } from "./src/milsymbol.js"; export { app6b, std2525b, std2525c } from "./src/lettersidc.js"; export { app6d, std2525d } from "./src/numbersidc.js"; export { default as path2d } from "./src/ms/path2d.js"; /* *************************************************************************************** ES6 version of milsymbol ****************************************************************************************** To import all and have the same functionality as ordinary milsymbol, do the following: (Or just import the things that you need) import { ms, app6b, std2525b, std2525c, app6d, std2525d, path2d } from "./index.esm.js"; ms.addIcons(app6b); ms.addIcons(std2525b); ms.addIcons(std2525c); ms.addIcons(app6d); ms.addIcons(std2525d); ms.Path2D = path2d; */
JavaScript
0
@@ -773,17 +773,58 @@ ms, -%0A app6b, + // Base for milsymbol%0A app6b, // APP6-B %0A s @@ -831,16 +831,25 @@ td2525b, + // 2525B %0A std25 @@ -856,38 +856,117 @@ 25c, -%0A app6d,%0A std2525d,%0A path2d + // 2525C%0A app6d, // APP6-D%0A std2525d, // 2525D%0A path2d // Pollyfill for Path2D in IE or node-canvas %0A%7D f @@ -1097,16 +1097,16 @@ 2525d);%0A + ms.Path2 @@ -1118,12 +1118,11 @@ ath2d;%0A%0A -%0A */%0A
94fbde75146e0952e6b6bd2807486fba2ce0dbf6
update of gulpfile.js - commit.
gulpfile.js
gulpfile.js
/*! * rose-normalize-sass [v0.0.1] * ___________________________________________________ * Gulp: The streaming build system. * https://github.com/gulpjs/gulp | http://gulpjs.com/ * @author : Prabhat Kumar, http://prabhatkumar.org/ * @date : 11-July-2015 * ___________________________________________________ */ 'use strict'; // main module. var gulp = require('gulp'); // required modules. var sass = require('gulp-sass'); var concat = require('gulp-concat'); var scsslint = require('gulp-scss-lint'); var uglify = require('gulp-uglify'); var beautify = require('gulp-beautify'); var sourcemaps = require('gulp-sourcemaps'); // utility modules. var path = require('path'); var gutil = require('gulp-util'); var gulpif = require('gulp-if'); var size = require('gulp-size'); var del = require('del'); var notify = require("gulp-notify"); var rename = require("gulp-rename"); var replace = require('gulp-replace'); var bytediff = require('gulp-bytediff'); var chmod = require('gulp-chmod');
JavaScript
0
@@ -1167,12 +1167,218 @@ lp-chmod');%0A +%0A// ***** SETTINGS ***** //%0Avar AUTOPREFIXER_BROWSERS = %5B%0A 'ie %3E= 10',%0A 'ie_mob %3E= 10',%0A 'ff %3E= 30',%0A 'chrome %3E= 34',%0A 'safari %3E= 7',%0A 'opera %3E= 22',%0A 'ios %3E= 7',%0A 'android %3E= 4.4',%0A 'bb %3E= 10'%0A%5D;%0A
a65113944eadc90972d753a21b6e1bae95a4ba36
disable in-app warnings
index.ios.js
index.ios.js
import { AppRegistry } from 'react-native'; import App from './app/App'; AppRegistry.registerComponent('FragDenStaat', () => App);
JavaScript
0.000002
@@ -67,16 +67,51 @@ /App';%0A%0A +console.disableYellowBox = true;%0A%0A%0A AppRegis
4c05977b1a882ba746f94ba7ae562b049a4ebf07
Use gulp start to first run everything and then watch
gulpfile.js
gulpfile.js
'use strict'; var gulp = require( 'gulp' ); var plugins = require( 'gulp-load-plugins' )(); gulp.task( 'watch', function() { // Watch .less files gulp.watch( 'design/**/*.less', [ 'styles' ] ); // Watch .js files gulp.watch( 'scripts/**/*.js', [ 'scripts' ] ); gulp.watch( 'web/*', [ 'markup' ] ); // Watch image files gulp.watch( 'design/images/**/*', [ 'images' ] ); }); gulp.task( 'styles', function() { var condition = function( file ) { return !file.lesshint.success; }; return gulp.src( './design/style.less' ) .pipe( plugins.lesshint() ) .pipe( plugins.lesshint.reporter() ) .pipe( plugins.notify( function ( file ) { if ( file.lesshint.success ) { // Don't show something if success return false; } return file.relative + ' errored with ' + file.lesshint.resultCount + ' errors'; }) ) .pipe( plugins.ignore.exclude( condition ) ) .pipe( plugins.less() ) .pipe( plugins.autoprefixer( 'last 2 version' ) ) .pipe( plugins.rename( { suffix: '.min' } ) ) .pipe( plugins.cssnano() ) .pipe( gulp.dest( './dist/' ) ) }); gulp.task( 'scripts', function() { return gulp.src( './scripts/**/*.js' ) .pipe( gulp.dest( './dist/' ) ); }); gulp.task( 'images', function() { return gulp.src( 'design/images/**/*' ) .pipe( plugins.cache( plugins.imagemin( { optimizationLevel: 3, progressive: true, interlaced: true } ) ) ) .pipe( gulp.dest( 'dist/images' )); }); gulp.task( 'markup', function() { return gulp.src( './web/*' ) .pipe( gulp.dest( './dist/' ) ); }); gulp.task( 'default', [ 'styles', 'scripts', 'images', 'markup' ] );
JavaScript
0
@@ -1759,61 +1759,39 @@ k( ' -defaul +star t', %5B ' -styles', 'scripts', 'images', 'markup +default', 'watch ' %5D );%0A +%0A
5d687913baf15d2a0cfb7c7adb1b3eda6d2c645e
Copy android index over to ios
index.ios.js
index.ios.js
/** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; const store = require('./app/store'); const React = require('react-native'); const { AppRegistry, StyleSheet, Text, View, } = React; const { Provider } = require('react-redux'); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); const LedManager = React.createClass({ render() { return ( <Provider store={store}> <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> </Provider> ); }, }); AppRegistry.registerComponent('LedManager', () => LedManager);
JavaScript
0.000001
@@ -76,45 +76,26 @@ */%0A -'use strict';%0A%0Aconst store = require( +import store from './a @@ -107,23 +107,23 @@ ore' -) ;%0A -cons +impor t React = re @@ -118,26 +118,21 @@ t React -= require( +from 'react-n @@ -137,17 +137,16 @@ -native' -) ;%0Aconst @@ -182,22 +182,58 @@ ,%0A -Text,%0A View,%0A +Navigator,%0A Text,%0A TouchableOpacity,%0A Image,%0A %7D = @@ -239,20 +239,21 @@ React;%0A -cons +impor t %7B Prov @@ -263,18 +263,13 @@ r %7D -= require( +from 'rea @@ -281,223 +281,199 @@ dux' -);%0A%0Aconst styles = StyleSheet.create(%7B%0A container: %7B%0A flex: 1,%0A justifyContent: 'center',%0A alignItems: 'center',%0A backgroundColor: '#F5FCFF',%0A %7D,%0A welcome: %7B%0A fontSize: 20,%0A textAlign: 'center', +;%0Aimport routes from './app/constants/routes';%0A%0Aimport backImage from './app/img/back.png';%0A%0Aconst styles = StyleSheet.create(%7B%0A container: %7B%0A backgroundColor: '#F5FCFF',%0A %7D,%0A navBar: %7B %0A @@ -483,12 +483,14 @@ rgin -: 10 +Top: 5 ,%0A @@ -498,276 +498,387 @@ ,%0A -instructions: %7B%0A textAlign: 'center',%0A color: '#333333',%0A marginBottom: 5,%0A %7D,%0A%7D);%0A%0Aconst LedManager = React.createClass(%7B%0A render() %7B%0A return (%0A %3CProvider store=%7Bstore%7D%3E%0A %3CView style=%7Bstyles.container%7D%3E%0A %3CText style=%7Bstyles.welcome%7D +navText: %7B%0A marginTop: 2,%0A fontSize: 30,%0A %7D,%0A%7D);%0A%0Aconst LedManager = React.createClass(%7B%0A render() %7B%0A const routeMapper = %7B%0A LeftButton: (route, navigator, index) =%3E %7B%0A if (index === 0) return;%0A return (%0A %3CTouchableOpacity onPress=%7Bnavigator.pop%7D%3E%0A %3CImage source=%7BbackImage%7D width=%7B48%7D height=%7B42%7D /%3E%0A %3C/TouchableOpacity %3E%0A @@ -887,54 +887,180 @@ +);%0A -Welcome to React Native!%0A %3C/Text%3E + %7D,%0A RightButton: (route, navigator, index, navState) =%3E route.rightElement && route.rightElement(route, navigator, index, navState),%0A Title: (route) =%3E %7B %0A @@ -1056,33 +1056,38 @@ e) =%3E %7B%0A - +return %3CText style=%7Bst @@ -1095,230 +1095,612 @@ les. -instructions%7D%3E +navText%7D%3E%7Broute.name%7D%3C/Text%3E; %0A +%7D,%0A - To get started, edit index.ios.js%0A %3C/Text%3E%0A %3CText s +%7D;%0A%0A // modify top position for navigator container so it doesn't overlap the navbar%0A const navStyles = %7B%0A top: Navigator.NavigationBar.Styles.General.TotalNavHeight,%0A %7D;%0A%0A return (%0A %3CProvider store=%7Bstore%7D%3E%0A %3CNavigator sceneS tyle=%7B +%5B styles. -instructions%7D%3E%0A Press Cmd+R to reload,%7B'%5Cn'%7D%0A Cmd+D or shake for dev menu%0A %3C/Text%3E +container, navStyles%5D%7D%0A initialRoute=%7Broutes.root()%7D%0A renderScene=%7B(route, navigator) =%3E %3Croute.component route=%7Broute%7D navigator=%7Bnavigator%7D /%3E%7D%0A navigationBar=%7B%3CNavigator.NavigationBar style=%7Bstyles.navBar%7D routeMapper=%7BrouteMapper%7D /%3E%7D %0A @@ -1708,14 +1708,9 @@ -%3C/View +/ %3E%0A
cc1ae26169a99ec0b89a04874ef6b169364009a5
Add corrected default vaccinator
src/actions/Entities/VaccinePrescriptionActions.js
src/actions/Entities/VaccinePrescriptionActions.js
import { generateUUID } from 'react-native-database'; import { batch } from 'react-redux'; import { UIDatabase, createRecord } from '../../database'; import { selectHasRefused, selectSelectedBatches, selectSelectedVaccinator, } from '../../selectors/Entities/vaccinePrescription'; import { selectEditingNameId } from '../../selectors/Entities/name'; import { NameActions } from './NameActions'; import { NameNoteActions } from './NameNoteActions'; import { goBack, gotoVaccineDispensingPage } from '../../navigation/actions'; export const VACCINE_PRESCRIPTION_ACTIONS = { CREATE: 'VACCINE_PRESCRIPTION/create', SET_REFUSAL: 'VACCINE_PRESCRIPTION/setRefusal', RESET: 'VACCINE_PRESCRIPTION/reset', SELECT_VACCINE: 'VACCINE_PRESCRIPTION/selectVaccine', SELECT_BATCH: 'VACCINE_PRESCRIPTION/selectBatch', SELECT_VACCINATOR: 'VACCINE_PRESCRIPTION/selectVaccinator', }; const createDefaultVaccinePrescription = () => ({ id: generateUUID(), name: '', code: '', type: 'patient', isCustomer: false, isSupplier: false, isManufacturer: false, isVisible: true, }); const getDefaultVaccinator = () => { const [batches] = UIDatabase.objects('TransactionBatch') .filtered('medicineAdministrator != null && itemBatch.item.isVaccine == true') .sorted('transaction.confirmDate', true); if (batches) { return batches.medicineAdministrator; } return null; }; const getDefaultVaccine = () => { const [mostRecentTrans] = UIDatabase.objects('Transaction') .filtered("type == 'customer_invoice' && (status == 'finalised' || status == 'confirmed')") .sorted('confirmDate', true); const anyVaccine = UIDatabase.objects('Vaccine')[0]; const mostRecentlyUsedVaccine = mostRecentTrans?.items?.filtered('item.isVaccine == true')[0] ?.item; const item = mostRecentlyUsedVaccine ?? anyVaccine; return item ?? null; }; const getRecommendedBatch = vaccine => { const { batchesWithStock = [] } = vaccine ?? getDefaultVaccine() ?? {}; if (batchesWithStock?.length) { const batchesByExpiry = batchesWithStock.sorted('expiryDate'); const openVials = batchesByExpiry.filter(b => !Number.isInteger(b.numberOfPacks)); return openVials.length ? openVials[0] : batchesByExpiry[0]; } return null; }; const create = () => ({ type: VACCINE_PRESCRIPTION_ACTIONS.CREATE, payload: { prescription: createDefaultVaccinePrescription(), vaccinator: getDefaultVaccinator(), selectedVaccines: [getDefaultVaccine()], selectedBatches: [getRecommendedBatch()], }, }); const reset = () => ({ type: VACCINE_PRESCRIPTION_ACTIONS.RESET, }); const selectVaccine = vaccine => ({ type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINE, payload: { vaccine, batch: getRecommendedBatch(vaccine) }, }); const selectBatch = itemBatch => ({ type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_BATCH, payload: { itemBatch }, }); const setRefusal = hasRefused => ({ type: VACCINE_PRESCRIPTION_ACTIONS.SET_REFUSAL, payload: { hasRefused, selectedVaccines: [getDefaultVaccine()], selectedBatches: [getRecommendedBatch()], }, }); const createPrescription = (patient, currentUser, selectedBatches, vaccinator) => { UIDatabase.write(() => { const prescription = createRecord( UIDatabase, 'CustomerInvoice', patient, currentUser, 'dispensary' ); selectedBatches.forEach(itemBatch => { const { item } = itemBatch; const transactionItem = createRecord(UIDatabase, 'TransactionItem', prescription, item); createRecord(UIDatabase, 'TransactionBatch', transactionItem, itemBatch); transactionItem.setDoses(UIDatabase, 1); transactionItem.setVaccinator(UIDatabase, vaccinator); }); prescription.finalise(UIDatabase); }); }; const createRefusalNameNote = name => { const [patientEvent] = UIDatabase.objects('PatientEvent').filtered('code == "RV"'); if (!patientEvent) return; const id = generateUUID(); const newNameNote = { id, name, patientEvent, entryDate: new Date() }; UIDatabase.write(() => UIDatabase.create('NameNote', newNameNote)); }; const confirm = () => (dispatch, getState) => { const { user } = getState(); const { currentUser } = user; const hasRefused = selectHasRefused(getState()); const patientID = selectEditingNameId(getState()); const selectedBatches = selectSelectedBatches(getState()); const vaccinator = selectSelectedVaccinator(getState()); batch(() => { dispatch(NameActions.saveEditing()); dispatch(NameNoteActions.saveEditing()); dispatch(reset()); }); const patient = UIDatabase.get('Name', patientID); if (hasRefused) { createRefusalNameNote(patient); } else { createPrescription(patient, currentUser, selectedBatches, vaccinator); } }; const selectVaccinator = vaccinator => ({ type: VACCINE_PRESCRIPTION_ACTIONS.SELECT_VACCINATOR, payload: { vaccinator }, }); const cancel = () => goBack(); const confirmAndRepeat = () => dispatch => batch(() => { dispatch(confirm()); dispatch(goBack()); dispatch(gotoVaccineDispensingPage()); }); export const VaccinePrescriptionActions = { cancel, confirm, create, reset, selectBatch, selectVaccine, setRefusal, selectVaccinator, confirmAndRepeat, };
JavaScript
0.000001
@@ -1373,32 +1373,101 @@ r;%0A %7D%0A%0A return + UIDatabase.objects('MedicineAdministrator').sorted('lastName')%5B0%5D ?? null;%0A%7D;%0A%0Aconst
5695947e3e34dd15c37484bac8858809b81d03ab
use xjs.Document#importLinksAsync()
gulpfile.js
gulpfile.js
const fs = require('fs') const path = require('path') const util = require('util') const gulp = require('gulp') const autoprefixer = require('gulp-autoprefixer') const clean_css = require('gulp-clean-css') const inject = require('gulp-inject-string') const less = require('gulp-less') const rename = require('gulp-rename') const sourcemaps = require('gulp-sourcemaps') const jsdom = require('jsdom') const kss = require('kss') const xjs = require('extrajs-dom') const {xDirectory,xPermalink} = require('aria-patterns') const PACKAGE = require('./package.json') const META = JSON.stringify({ package: `https://www.npmjs.com/package/${PACKAGE.name}`, version: PACKAGE.version, license: PACKAGE.license, built : new Date().toISOString(), }, null, 2) // HOW-TO: https://github.com/kss-node/kss-node/issues/161#issuecomment-222292620 gulp.task('docs-kss-markup', async function () { return kss(require('./config/kss.json')) }) gulp.task('docs-kss-style', async function () { return gulp.src('./docs/css/kss-custom.less') .pipe(less()) .pipe(autoprefixer({ grid: true, })) .pipe(gulp.dest('./docs/styleguide/')) }) gulp.task('docs-kss', ['docs-kss-markup', 'docs-kss-style']) gulp.task('docs-my-markup', async function () { const dom = new jsdom.JSDOM(await util.promisify(fs.readFile)(path.join(__dirname, './docs/tpl/index.tpl.html'), 'utf8')) const {document} = dom.window await (async function importLinks(relativepath) { if (!('import' in jsdom.JSDOM.fragment('<link rel="import" href="https://example.com/"/>').querySelector('link'))) { console.warn('`HTMLLinkElement#import` is not yet supported. Replacing `<link>`s with their imported contents.') return Promise.all(Array.from(document.querySelectorAll('link[rel~="import"][data-import]')).map(async function (link) { const import_switch = { 'document': async () => jsdom.JSDOM.fragment(await util.promisify(fs.readFile)(path.resolve(relativepath, link.href), 'utf8')), 'template': async () => (await xjs.HTMLTemplateElement.fromFile(path.resolve(relativepath, link.href))).content(), async default() { return null }, } let imported = await (import_switch[link.getAttribute('data-import')] || import_switch.default).call(null) if (imported) { link.after(imported) link.remove() // link.href = path.resolve('https://example.com/index.html', link.href) // TODO set the href relative to the current window.location.href } })) } else return; })(path.resolve(__dirname, './docs/tpl/')) await Promise.all([ (async function () { document.querySelector('#contents').append(xDirectory.render(require('./docs/index-toc.json'))) })(), (async function () { const classname = { figure: 'docs-figure', pre : 'docs-pre', code : 'docs-code', form : 'docs-form', } let fragment = (await xjs.HTMLTemplateElement.fromFile(path.resolve(__dirname, './docs/tpl/base.tpl.html'))).content().cloneNode(true) fragment.querySelectorAll([ 'section[id] > h2:first-of-type', 'section[id] > h3:first-of-type', 'section[id] > h4:first-of-type', 'section[id] > h5:first-of-type', 'section[id] > h6:first-of-type', ].join()).forEach(function (hn) { hn.append(xPermalink.render({ id: hn.parentNode.id })) }) fragment.querySelectorAll(Object.keys(classname).join()).forEach(function (el) { let xel = new xjs.HTMLElement(el) if (classname[xel.tagName]) xel.addClass(classname[xel.tagName]) }) document.querySelector('main').append(fragment) })(), ]) await util.promisify(fs.writeFile)(path.resolve(__dirname, './docs/index.html'), dom.serialize(), 'utf8') }) gulp.task('docs-my-style', async function () { return gulp.src('docs/css/docs.less') .pipe(less()) .pipe(autoprefixer({ grid: true, })) .pipe(gulp.dest('./docs/css/')) }) gulp.task('docs-my', ['docs-my-markup', 'docs-my-style']) gulp.task('docs', ['docs-kss', 'docs-my']) gulp.task('dist', async function () { return gulp.src(['./css/src/*.less', '!./css/src/__*.less']) .pipe(sourcemaps.init()) .pipe(less()) .pipe(autoprefixer({ grid: true, })) .pipe(clean_css({ level: { 2: { overrideProperties: false, // need fallbacks for `initial` and `unset` restructureRules: true, // combines selectors having the same rule (akin to `&:extend()`) // REVIEW be careful here }, }, })) .pipe(rename(function (p) { if (p.basename[0] === '_') { p.basename = p.basename.slice(1) } })) .pipe(inject.prepend(`/* ${META} */`)) .pipe(sourcemaps.write('./')) // writes to an external .map file .pipe(gulp.dest('./css/dist/')) }) gulp.task('build', ['docs', 'dist'])
JavaScript
0
@@ -1481,1143 +1481,51 @@ ait -(async function importLinks(relativepath) %7B%0A if (!('import' in jsdom.JSDOM.fragment('%3Clink rel=%22import%22 href=%22https://example.com/%22/%3E').querySelector('link'))) %7B%0A console.warn('%60HTMLLinkElement#import%60 is not yet supported. Replacing %60%3Clink%3E%60s with their imported contents.')%0A return Promise.all(Array.from(document.querySelectorAll('link%5Brel~=%22import%22%5D%5Bdata-import%5D')).map(async function (link) %7B%0A const import_switch = %7B%0A 'document': async () =%3E jsdom.JSDOM.fragment(await util.promisify(fs.readFile)(path.resolve(relativepath, link.href), 'utf8')),%0A 'template': async () =%3E (await xjs.HTMLTemplateElement.fromFile(path.resolve(relativepath, link.href))).content(),%0A async default() %7B return null %7D,%0A %7D%0A let imported = await (import_switch%5Blink.getAttribute('data-import')%5D %7C%7C import_switch.default).call(null)%0A if (imported) %7B%0A link.after(imported)%0A link.remove() // link.href = path.resolve('https://example.com/index.html', link.href) // TODO set the href relative to the current window.location.href%0A %7D%0A %7D))%0A %7D else return;%0A %7D) +new xjs.Document(document).importLinksAsync (pat
1fdee77ecc7ae1fe3e5be0fd7350d56ab3704755
add initial critical POC task
gulpfile.js
gulpfile.js
var gulp = require('gulp'), less = require('gulp-less'), sass = require('gulp-sass'), browserSync = require('browser-sync').create(), header = require('gulp-header'), cleanCSS = require('gulp-clean-css'), rename = require("gulp-rename"), replace = require('gulp-replace'), uglify = require('gulp-uglify'), concat = require('gulp-concat'), maps = require('gulp-sourcemaps'), pkg = require('./package.json'); // Set the banner content var banner = ['/*!\n', ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n', ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n', ' * Licensed under <%= pkg.license %>\n', ' */\n', '' ].join(''); // Compile LESS files from /less into /css gulp.task('less', function() { return gulp.src('less/agency.less') .pipe(less()) .pipe(header(banner, { pkg: pkg })) .pipe(gulp.dest('css')) .pipe(browserSync.reload({ stream: true })); }); // Concatenate CSS gulp.task('concat-css', ['less'], function(){ return gulp.src(['vendor/bootstrap/css/bootstrap.min.css', 'vendor/font-awesome/css/font-awesome.min.css', 'https://fonts.googleapis.com/css?family=Montserrat:400,700', 'https://fonts.googleapis.com/css?family=Kaushan+Script', 'https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic', 'https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700', 'css/agency.css', 'css/sean.css']) .pipe(maps.init()) .pipe(concat('main.css')) .pipe(maps.write('./')) .pipe(gulp.dest("css")) .pipe(browserSync.reload({ stream: true })); }); // Minify compiled CSS gulp.task('minify-css', ['concat-css'], function() { return gulp.src('css/main.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('css')) .pipe(browserSync.reload({ stream: true })); }); // Concatenate JS gulp.task('concat-js', function(){ return gulp.src(['vendor/jquery/jquery.min.js', 'vendor/bootstrap/js/bootstrap.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js', 'js/jqBootstrapValidation.js', 'js/contact_me.js', 'js/agency.js', 'js/sean.js']) .pipe(maps.init()) .pipe(concat('main.js')) .pipe(maps.write('./')) .pipe(gulp.dest("js")) .pipe(browserSync.reload({ stream: true })); }); // Minify JS gulp.task('minify-js', ['concat-js'], function() { return gulp.src('js/main.js') .pipe(uglify()) .pipe(header(banner, { pkg: pkg })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('js')) .pipe(browserSync.reload({ stream: true })); }); // Create html gulp.task('dev-html', function(){ return gulp.src('index.template') .pipe(replace('{{STYLE}}', 'css/main.css')) .pipe(replace('{{SCRIPT}}', 'js/main.js')) .pipe(rename('index.html')) .pipe(gulp.dest('./')) .pipe(browserSync.reload({ stream: true })); }); // Copy vendor libraries from /node_modules into /vendor gulp.task('copy', function() { gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map']) .pipe(gulp.dest('vendor/bootstrap')) gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js']) .pipe(gulp.dest('vendor/jquery')) gulp.src([ 'node_modules/font-awesome/**', '!node_modules/font-awesome/**/*.map', '!node_modules/font-awesome/.npmignore', '!node_modules/font-awesome/*.txt', '!node_modules/font-awesome/*.md', '!node_modules/font-awesome/*.json' ]) .pipe(gulp.dest('vendor/font-awesome')); gulp.src(['node_modules/font-awesome/fonts/*']) .pipe(gulp.dest('fonts')); }) // Run everything gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']); // Configure the browserSync task gulp.task('browserSync', function() { browserSync.init({ server: { baseDir: '' }, }); }) // Dev task with browserSync gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js', 'dev-html', 'copy'], function() { gulp.watch('less/*.less', ['less']); gulp.watch('css/*.css', ['minify-css']); gulp.watch('js/*.js', ['minify-js']); gulp.watch('index.template', ['dev-html']); // Reloads the browser whenever HTML or JS files change gulp.watch('*.html', browserSync.reload); gulp.watch('js/**/*.js', browserSync.reload); });
JavaScript
0.998628
@@ -442,16 +442,93 @@ e.json') +,%0A gutil = require('gulp-util'),%0A critical = require('critical').stream ;%0A%0A// Se @@ -2251,91 +2251,8 @@ s',%0A -%09%09'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js',%0A %09%09'j @@ -3135,24 +3135,312 @@ %7D));%0A%7D);%0A%0A +//critical css%0Agulp.task('critical', function () %7B%0A return gulp.src('index.html')%0A .pipe(critical(%7Bbase: 'dist/', inline: true, css: %5B'css/main.min.css'%5D%7D))%0A .on('error', function(err) %7B gutil.log(gutil.colors.red(err.message)); %7D)%0A .pipe(gulp.dest('dist'));%0A%7D);%0A%0A // Copy vend
5e34d5db04203ef3f7782de5abeb5212d35659bb
Remove extra calledOnce assertions from (ir)relevant tests
test/test_whoshiring.js
test/test_whoshiring.js
'use strict' /* eslint-env node, mocha */ const expect = require('chai').expect const sinon = require('sinon') const WhosHiring = require('../lib/whoshiring') const HNSearch = require('hacker-news-api') describe('WhosHiring', function () { // ------------------------------------------------------------- // Fixtures // ------------------------------------------------------------- const mockObjectID = 123 const mockTitle = 'title text' const searchTerms = 'search terms' // Fake story result // const mockStorySearch = Promise.resolve({ hits: [{ objectID: mockObjectID, title: mockTitle }] }) // Fake matches result // const mockMatches = [ { comment_text: 'first comment' }, { comment_text: 'second comment' }, { comment_text: 'third comment' } ] const mockMatchesSearch = Promise.resolve({ hits: mockMatches }) // ------------------------------------------------------------- // Sinon sandbox setup/teardown // ------------------------------------------------------------- const sinonbox = sinon.sandbox.create({ useFakeTimers: false, useFakeServer: false }) let spyURL let spyTitle let stubSearch beforeEach(function () { spyURL = sinonbox.spy(WhosHiring, 'url') spyTitle = sinonbox.spy(WhosHiring, 'title') stubSearch = sinonbox.stub(HNSearch, 'searchAsync') stubSearch.returns(mockStorySearch) stubSearch.withArgs(searchTerms).returns(mockMatchesSearch) }) afterEach(function () { sinonbox.restore() WhosHiring.resetStoryCache() }) // ------------------------------------------------------------- // Tests // ------------------------------------------------------------- describe('WhosHiring.url()', function () { it('should only call searchAsync once', function () { return Promise .resolve() .then(WhosHiring.url) .then(WhosHiring.url) .then(WhosHiring.url) .then((url) => { sinon.assert.calledThrice(spyURL) sinon.assert.calledOnce(stubSearch) }) }) it('should return a url with the mockObjectID', function () { return WhosHiring .url() .then((url) => { expect(url).to.match(new RegExp(`${mockObjectID}`)) sinon.assert.calledOnce(stubSearch) }) }) }) describe('WhosHiring.title()', function () { it('should only call searchAsync once', function () { return Promise .resolve() .then(WhosHiring.title) .then(WhosHiring.title) .then(WhosHiring.title) .then((url) => { sinon.assert.calledThrice(spyTitle) sinon.assert.calledOnce(stubSearch) }) }) it('should return a title with the mockTitle', function () { return WhosHiring .title() .then((title) => { expect(title).to.equal(mockTitle) sinon.assert.calledOnce(stubSearch) }) }) }) describe('WhosHiring.matches(terms)', function () { it('should return all matches ', function () { return WhosHiring .matches(searchTerms) .then((results) => { expect(results.length).to.equal(mockMatches.length) }) }) it('should return matches as strings', function () { return WhosHiring .matches(searchTerms) .then((results) => { results.forEach((result) => { expect(result).to.be.a('string') }) }) }) it('should return matches from fixture', function () { const expected = mockMatches.map((m) => m.comment_text) return WhosHiring .matches(searchTerms) .then((results) => { expect(results).to.deep.equal(expected) }) }) }) })
JavaScript
0.000001
@@ -2282,54 +2282,8 @@ %60))%0A - sinon.assert.calledOnce(stubSearch)%0A @@ -2860,54 +2860,8 @@ le)%0A - sinon.assert.calledOnce(stubSearch)%0A
f892796fd34c2987a9f55793e0cb818ececf24d1
Remove unused envify require
gulpfile.js
gulpfile.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. */ 'use strict'; var babel = require('gulp-babel'); var babelPluginDEV = require('fbjs-scripts/babel/dev-expression'); var babelPluginModules = require('fbjs-scripts/babel/rewrite-modules'); var del = require('del'); var derequire = require('gulp-derequire'); var envify = require('envify/custom'); var flatten = require('gulp-flatten'); var gulp = require('gulp'); var gulpUtil = require('gulp-util'); var header = require('gulp-header'); var objectAssign = require('object-assign'); var runSequence = require('run-sequence'); var webpackStream = require('webpack-stream'); var DEVELOPMENT_HEADER = [ '/**', ' * Relay v<%= version %>', ' */' ].join('\n') + '\n'; var PRODUCTION_HEADER = [ '/**', ' * Relay v<%= version %>', ' *', ' * 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.', ' *', ' */' ].join('\n') + '\n'; var babelOpts = { nonStandard: true, loose: [ 'es6.classes' ], stage: 1, optional: ['runtime'], plugins: [babelPluginDEV, babelPluginModules], _moduleMap: objectAssign({}, require('fbjs/module-map'), { 'React': 'react', 'ReactDOM': 'react-dom', 'StaticContainer.react': 'react-static-container' }) }; var buildDist = function(opts) { var webpackOpts = { debug: opts.debug, externals: { 'react': 'React', 'react-dom': 'ReactDOM' }, module: { loaders: [ {test: /\.js$/, loader: 'babel'} ], }, output: { filename: opts.output, libraryTarget: 'umd', library: 'Relay' }, plugins: [ new webpackStream.webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( opts.debug ? 'development' : 'production' ), }), new webpackStream.webpack.optimize.OccurenceOrderPlugin(), new webpackStream.webpack.optimize.DedupePlugin() ] }; if (!opts.debug) { webpackOpts.plugins.push( new webpackStream.webpack.optimize.UglifyJsPlugin({ compress: { hoist_vars: true, screw_ie8: true, warnings: false } }) ); } return webpackStream(webpackOpts, null, function(err, stats) { if (err) { throw new gulpUtil.PluginError('webpack', err); } if (stats.compilation.errors.length) { throw new gulpUtil.PluginError('webpack', stats.toString()); } }); }; var paths = { dist: 'dist', entry: 'lib/Relay.js', lib: 'lib', src: [ '*src/**/*.js', '!src/**/__tests__/**/*.js', '!src/**/__mocks__/**/*.js' ], }; gulp.task('clean', function(cb) { del([paths.dist, paths.lib], cb); }); gulp.task('modules', function() { return gulp .src(paths.src) .pipe(babel(babelOpts)) .pipe(flatten()) .pipe(gulp.dest(paths.lib)); }); gulp.task('dist', ['modules'], function () { var distOpts = { debug: true, output: 'relay.js' }; return gulp.src(paths.entry) .pipe(buildDist(distOpts)) .pipe(derequire()) .pipe(header(DEVELOPMENT_HEADER, { version: process.env.npm_package_version })) .pipe(gulp.dest(paths.dist)); }); gulp.task('dist:min', ['modules'], function () { var distOpts = { debug: false, output: 'relay.min.js' }; return gulp.src(paths.entry) .pipe(buildDist(distOpts)) .pipe(header(PRODUCTION_HEADER, { version: process.env.npm_package_version })) .pipe(gulp.dest(paths.dist)); }); gulp.task('website:check-version', function(cb) { var version = require('./package').version; var websiteVersion = require('./website/core/SiteData').version; if (websiteVersion !== version) { return cb( new Error('Website version does not match package.json. Saw ' + websiteVersion + ' but expected ' + version) ); } cb(); }); gulp.task('watch', function() { gulp.watch(paths.src, ['modules']); }); gulp.task('default', function(cb) { runSequence('clean', 'website:check-version', 'modules', ['dist', 'dist:min'], cb); });
JavaScript
0.000002
@@ -558,47 +558,8 @@ ');%0A -var envify = require('envify/custom');%0A var
440a8e5e612a7d47adb106580d137305c4f6f0a1
Change check to verify in function signature.
test/unit/buttonSpec.js
test/unit/buttonSpec.js
( function() { 'use strict'; var checkElementDimensions = function( elemConstructor ) { var styles; var elem; beforeEach( function () { jasmine.addMatchers(d2l.jasmine.matchers); elem = elemConstructor(); document.body.appendChild(elem); }); it( 'has correct outer height', function() { expect( elem.offsetHeight ).toBe( 28 ); } ); it( 'has correct inner height', function() { expect( elem.clientHeight ).toBe( 26 ); } ); it( 'has correct margins' , function() { expect( elem ).toHaveTopMargin( '0px' ); expect( elem ).toHaveBottomMargin( '0px' ); expect( elem ).toHaveLeftMargin( '0px' ); expect( elem ).toHaveRightMargin( '0px' ); } ); it( 'responds to font change Arial 11', function() { document.body.style.fontFamily="Arial"; document.body.style.fontSize="11px"; expect( elem.offsetHeight ).toBe( 28 ); } ); it( 'responds to font change Arial 13', function() { document.body.style.fontFamily="Arial"; document.body.style.fontSize="13px"; expect( elem.offsetHeight ).toBe( 28 ); } ); it( 'responds to font change Arial 15', function() { document.body.style.fontFamily="Arial"; document.body.style.fontSize="15px"; expect( elem.offsetHeight ).toBeOnBrowser( { 'default' : 29, 'Firefox' : 31 } ); } ); it( 'responds to font change Arial 17', function() { document.body.style.fontFamily="Arial"; document.body.style.fontSize="17px"; expect( elem.offsetHeight ).toBeOnBrowser( { 'default' : 32, 'Firefox' : 33 } ); } ); it( 'responds to font change Verdana 11', function() { document.body.style.fontFamily="Verdana"; document.body.style.fontSize="11px"; expect( elem.offsetHeight ).toBe( 28 ); } ); it( 'responds to font change Verdana 13', function() { document.body.style.fontFamily="Verdana"; document.body.style.fontSize="13px"; expect( elem.offsetHeight ).toBeOnBrowser( { 'default' : 28, 'Firefox' : 29 } ); } ); it( 'responds to font change Verdana 15', function() { document.body.style.fontFamily="Verdana"; document.body.style.fontSize="15px"; expect( elem.offsetHeight ).toBeOnBrowser( { 'default' : 30, 'Firefox' : 32 } ); } ); it( 'responds to font change Verdana 17', function() { document.body.style.fontFamily="Verdana"; document.body.style.fontSize="17px"; expect( elem.offsetHeight ).toBeOnBrowser( { 'default' : 32, 'Firefox' : 34, 'Chrome' : 33 } ); } ); afterEach( function() { document.body.removeChild(elem); } ); }; describe( 'vui-button', function() { beforeEach( function() { document.body.style.fontFamily="Arial"; document.body.style.fontSize="13px"; } ); var createVUIButton = function( tag ) { var vuib = document.createElement( tag ); vuib.className = 'vui-button'; return vuib; } describe ( 'anchor', function() { checkElementDimensions( function() { var anc = createVUIButton( 'a' ); anc.innerHTML = "test"; return anc; } ); describe( 'vui-disabled', function() { checkElementDimensions( function() { var dis = createVUIButton( 'a' ); dis.classList.add( 'vui-disabled' ); dis.innerHTML = "test"; return dis; } ); } ); } ); describe ( 'button', function() { checkElementDimensions( function() { var btn = createVUIButton( 'button' ); btn.innerHTML = "test"; return btn; } ); describe( 'vui-disabled', function() { checkElementDimensions( function() { var dis = createVUIButton( 'button' ); dis.classList.add( 'vui-disabled' ); dis.innerHTML = "test"; return dis; } ); } ); } ); describe ( 'input', function() { checkElementDimensions( function() { var inp = createVUIButton( 'input' ); inp.setAttribute("type", "button"); inp.setAttribute("value", "test"); return inp; } ); describe( 'vui-disabled', function() { checkElementDimensions( function() { var dis = createVUIButton( 'input' ); dis.setAttribute("type", "button"); dis.classList.add( 'vui-disabled' ); dis.setAttribute("value", "test"); return dis; } ); } ); } ); } ); } )();
JavaScript
0
@@ -32,21 +32,22 @@ %0A%0D%0A%09var -check +verify ElementD @@ -2934,37 +2934,38 @@ unction() %7B%0D%0A%09%09%09 -check +verify ElementDimension @@ -2958,33 +2958,32 @@ ementDimensions( - %0D%0A%09%09%09%09function() @@ -3129,37 +3129,38 @@ nction() %7B%0D%0A%09%09%09%09 -check +verify ElementDimension @@ -3153,33 +3153,32 @@ ementDimensions( - %0D%0A%09%09%09%09%09function( @@ -3386,37 +3386,38 @@ unction() %7B%0D%0A%09%09%09 -check +verify ElementDimension @@ -3410,33 +3410,32 @@ ementDimensions( - %0D%0A%09%09%09%09function() @@ -3586,37 +3586,38 @@ nction() %7B%0D%0A%09%09%09%09 -check +verify ElementDimension @@ -3610,33 +3610,32 @@ ementDimensions( - %0D%0A%09%09%09%09%09function( @@ -3855,21 +3855,22 @@ ) %7B%0D%0A%09%09%09 -check +verify ElementD @@ -3875,25 +3875,24 @@ tDimensions( - %0D%0A%09%09%09%09functi @@ -4111,13 +4111,14 @@ %09%09%09%09 -check +verify Elem @@ -4131,17 +4131,16 @@ ensions( - %0D%0A%09%09%09%09%09f
4f6a36871d43a91cdafdbc56510da0b9991f2894
Fix tabwidth for gulpfile
gulpfile.js
gulpfile.js
require('events').EventEmitter.defaultMaxListeners = 30; var cssnext = require('postcss-cssnext'); var elixir = require('laravel-elixir'); var gutils = require('gulp-util'); elixir.config.js.browserify.transformers.push({ name: 'vueify', options: { postcss: [cssnext()] } }); if (gutils.env._.indexOf('watch') > -1) { elixir.config.js.browserify.plugins.push({ name: "browserify-hmr", options : {} }); } elixir(function (mix) { mix.browserify('main.js'); mix.sass('app.scss'); mix.copy('resources/assets/img', 'public/img') .copy('node_modules/font-awesome/fonts', 'public/build/fonts') .copy('resources/assets/fonts', 'public/build/fonts'); mix.scripts([ 'node_modules/babel-polyfill/dist/polyfill.min.js', 'node_modules/plyr/dist/plyr.js', 'node_modules/rangetouch/dist/rangetouch.js', 'resources/assets/js/libs/modernizr-custom.js' ], 'public/js/vendors.js', './') .styles([ 'resources/assets/css/**/*.css', 'node_modules/font-awesome/css/font-awesome.min.css', 'node_modules/rangeslider.js/dist/rangeslider.css' ], 'public/css/vendors.css', './'); mix.version(['css/vendors.css', 'css/app.css', 'js/vendors.js', 'js/main.js']); if (process.env.NODE_ENV !== 'production') { mix.browserSync({ proxy: 'koel.dev', files: [ elixir.config.get('public.css.outputFolder') + '/**/*.css', elixir.config.get('public.versioning.buildFolder') + '/rev-manifest.json', ] }); } });
JavaScript
0.000002
@@ -217,18 +217,16 @@ .push(%7B%0A - name: @@ -236,18 +236,16 @@ eify',%0A%0A - option @@ -253,20 +253,16 @@ : %7B%0A - - postcss: @@ -276,18 +276,16 @@ xt()%5D%0A - - %7D%0A%7D);%0A%0Ai @@ -325,18 +325,16 @@ %3E -1) %7B%0A - elixir @@ -374,20 +374,16 @@ h(%7B%0A - - name: %22b @@ -402,20 +402,16 @@ r%22,%0A - - options @@ -415,18 +415,16 @@ ns : %7B%7D%0A - %7D);%0A%7D%0A @@ -450,18 +450,16 @@ ix) %7B%0A - - mix.brow @@ -477,18 +477,16 @@ n.js');%0A - mix.sa @@ -500,26 +500,24 @@ .scss');%0A%0A - - mix.copy('re @@ -551,20 +551,16 @@ c/img')%0A - .cop @@ -622,20 +622,16 @@ s')%0A - - .copy('r @@ -674,26 +674,24 @@ d/fonts');%0A%0A - mix.script @@ -690,30 +690,24 @@ x.scripts(%5B%0A - 'node_ @@ -748,30 +748,24 @@ ll.min.js',%0A - 'node_ @@ -790,38 +790,32 @@ plyr.js',%0A - - 'node_modules/ra @@ -840,30 +840,24 @@ etouch.js',%0A - 'resou @@ -897,20 +897,16 @@ tom.js'%0A - %5D, ' @@ -934,20 +934,16 @@ , './')%0A - .sty @@ -948,22 +948,16 @@ tyles(%5B%0A - 'r @@ -983,30 +983,24 @@ /**/*.css',%0A - 'node_ @@ -1043,30 +1043,24 @@ e.min.css',%0A - 'node_ @@ -1104,20 +1104,16 @@ er.css'%0A - %5D, ' @@ -1147,18 +1147,16 @@ /');%0A%0A - - mix.vers @@ -1228,18 +1228,16 @@ js'%5D);%0A%0A - if (pr @@ -1279,20 +1279,16 @@ ) %7B%0A - - mix.brow @@ -1303,22 +1303,16 @@ %7B%0A - - proxy: ' @@ -1322,22 +1322,16 @@ l.dev',%0A - fi @@ -1337,24 +1337,16 @@ iles: %5B%0A - @@ -1413,24 +1413,16 @@ - - elixir.c @@ -1492,22 +1492,16 @@ n',%0A - %5D%0A @@ -1500,20 +1500,16 @@ %5D%0A - %7D);%0A @@ -1504,18 +1504,16 @@ %7D);%0A - %7D%0A%7D);%0A
72c81f56da6a272fccc8d13a38279230fdda25cb
Improve test coverage
test/unit/index.test.js
test/unit/index.test.js
import { assert } from 'chai'; import CipherService from '../../src/index'; import JwtCipher from '../../src/JwtCipher'; describe('CipherService', () => { it('Should properly export', () => { assert.isFunction(CipherService); }); it('Should properly create JWT cipher', () => { let cipher = CipherService('jwt'); assert.instanceOf(cipher, JwtCipher); }); it('Should properly encode/decode data', () => { let cipher = CipherService('jwt'); assert.typeOf(cipher.encodeSync('test'), 'string'); }); it('Should properly throw error if type is unrecognized', () => { assert.throw(() => CipherService.create('NOT_EXISTS'), Error); }); });
JavaScript
0.000002
@@ -632,15 +632,8 @@ vice -.create ('NO
f21d75b3cefdfcb3ae67bcafb44c41abcdb51b05
Fix karma conf
test/unit/karma.conf.js
test/unit/karma.conf.js
/*jslint white: true*/ /*global module */ // process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { 'use strict'; config.set({ basePath: '../../', frameworks: ['jasmine', 'requirejs', 'es6-shim'], client: { jasmine: { failFast: false, DEFAULT_TIMEOUT_INTERVAL: 20000 }, requireJsShowNoTimestampsError: '^(?!.*(^/narrative/static/))', clearContext: false }, plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-requirejs', 'karma-coverage', 'karma-mocha-reporter', 'karma-es6-shim' ], preprocessors: { 'kbase-extension/static/kbase/js/**/!(api)/*.js': ['coverage'], 'kbase-extension/static/kbase/js/api/!(*[Cc]lient*|Catalog|KBaseFeatureValues|NarrativeJobServiceWrapper|NewWorkspace)*.js': ['coverage'], 'kbase-extension/static/kbase/js/api/RestAPIClient.js': ['coverage'], 'nbextensions/appcell2/widgets/tabs/*.js': ['coverage'], }, files: [ 'kbase-extension/static/narrative_paths.js', //{pattern: 'test/unit/spec/**/*.js', included: false}, {pattern: 'test/unit/spec/narrative_core/kbaseNarrativeDataList-spec.js', included: false}, {pattern: 'node_modules/jasmine-ajax/lib/mock-ajax.js', included: true}, {pattern: 'kbase-extension/static/ext_components/kbase-ui-plugin-catalog/src/plugin/modules/data/categories.yml', included: false, served: true}, {pattern: 'kbase-extension/static/**/*.css', included: false, served: true}, {pattern: 'kbase-extension/static/kbase/templates/**/*.html', included: false, served: true}, {pattern: 'kbase-extension/static/kbase/config/**/*.json', included: false, served: true}, {pattern: 'kbase-extension/static/kbase/config/**/*.yaml', included: false, served: true}, {pattern: 'kbase-extension/static/**/*.js', included: false, served: true}, {pattern: 'kbase-extension/static/**/*.gif', included: false, served: true}, {pattern: 'nbextensions/appcell2/widgets/tabs/*.js', included: false}, {pattern: 'test/unit/testConfig.json', included: false, served: true, nocache: true}, {pattern: 'test/*.tok', included: false, served: true, nocache: true}, {pattern: 'test/data/**/*', included: false, served: true}, 'test/unit/testUtil.js', 'test/unit/test-main.js' ], exclude: [ 'kbase-extension/static/buildTools/*.js', 'kbase-extension/static/ext_components/**/test/**/*.js', 'kbase-extension/static/kbase/js/patched-components/**/*' ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha', 'coverage'], coverageReporter: { type: 'html', dir: 'js-coverage/', reporters: [{ type: 'html', subdir: 'html' }, { type: 'lcov', subdir: 'lcov' }], includeAllSources: true }, mochaReporter: { ignoreSkipped: true, }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['ChromeHeadless'], browserNoActivityTimeout: 30000, singleRun: true, proxies: { '/narrative/nbextensions': 'http://localhost:32323/narrative/nbextensions', '/narrative/static/': '/base/kbase-extension/static/', '/narrative/static/base': 'http://localhost:32323/narrative/static/base', '/narrative/static/notebook': 'http://localhost:32323/narrative/static/notebook', '/narrative/static/components': 'http://localhost:32323/narrative/static/components', '/narrative/static/services': 'http://localhost:32323/narrative/static/services', '/narrative/static/bidi': 'http://localhost:32323/narrative/static/bidi', '/static/kbase/config': '/base/kbase-extension/static/kbase/config', '/test/': '/base/test/' }, concurrency: Infinity }); };
JavaScript
0.000033
@@ -1316,18 +1316,16 @@ -// %7Bpattern @@ -1374,112 +1374,8 @@ e%7D,%0A - %7Bpattern: 'test/unit/spec/narrative_core/kbaseNarrativeDataList-spec.js', included: false%7D,%0A
aede9f543c3ba158d97176485c2d509365f4b0fb
remove off option of toggle
instant-search/instantsearch.js/search.js
instant-search/instantsearch.js/search.js
/* global instantsearch */ app({ appId: 'latency', apiKey: '6be0576ff61c053d5f9a3225e2a90f76', indexName: 'instant_search' }); function app(opts) { // --------------------- // // Init // // --------------------- const search = instantsearch({ appId: opts.appId, apiKey: opts.apiKey, indexName: opts.indexName, urlSync: true, }); // --------------------- // // Default widgets // // --------------------- search.addWidget( instantsearch.widgets.searchBox({ container: '#search-input', placeholder: 'Search for products by name, type, brand, ...', }) ); search.addWidget( instantsearch.widgets.hits({ container: '#hits', hitsPerPage: 10, templates: { item: getTemplate('hit'), empty: getTemplate('no-results'), }, transformData: { item: function (item) { item.starsLayout = getStarsHTML(item.rating); item.categories = getCategoryBreadcrumb(item); return item; }, }, }) ); search.addWidget( instantsearch.widgets.stats({ container: '#stats', }) ); search.addWidget( instantsearch.widgets.sortBySelector({ container: '#sort-by', autoHideContainer: true, indices: [{ name: opts.indexName, label: 'Most relevant', }, { name: `${opts.indexName}_price_asc`, label: 'Lowest price', }, { name: `${opts.indexName}_price_desc`, label: 'Highest price', }], }) ); search.addWidget( instantsearch.widgets.pagination({ container: '#pagination', scrollTo: '#search-input', }) ); // --------------------- // // Filtering widgets // // --------------------- search.addWidget( instantsearch.widgets.hierarchicalMenu({ container: '#hierarchical-categories', attributes: [ 'hierarchicalCategories.lvl0', 'hierarchicalCategories.lvl1', 'hierarchicalCategories.lvl2'], sortBy: ['isRefined', 'count:desc', 'name:asc'], showParentLevel: true, limit: 10, templates: { header: getHeader('Category'), item: '<a href="javascript:void(0);" class="facet-item {{#isRefined}}active{{/isRefined}}"><span class="facet-name"><i class="fa fa-angle-right"></i> {{name}}</span class="facet-name"><span class="ais-hierarchical-menu--count">{{count}}</span></a>' // eslint-disable-line }, }) ); search.addWidget( instantsearch.widgets.refinementList({ container: '#brand', attributeName: 'brand', sortBy: ['isRefined', 'count:desc', 'name:asc'], limit: 5, operator: 'or', showMore: { limit: 10, }, searchForFacetValues: { placeholder: 'Search for brands', templates: { noResults: '<div class="sffv_no-results">No matching brands.</div>', }, }, templates: { header: getHeader('Brand'), }, collapsible: { collapsed: false, }, }) ); search.addWidget( instantsearch.widgets.rangeSlider({ container: '#price', attributeName: 'price', tooltips: { format: function (rawValue) { return `$${Math.round(rawValue).toLocaleString()}`; }, }, templates: { header: getHeader('Price'), }, collapsible: { collapsed: false, }, }) ); search.addWidget( instantsearch.widgets.priceRanges({ container: '#price-range', attributeName: 'price', labels: { currency: '$', separator: 'to', button: 'Apply', }, templates: { header: getHeader('Price range'), }, collapsible: { collapsed: true, }, }) ); search.addWidget( instantsearch.widgets.starRating({ container: '#stars', attributeName: 'rating', max: 5, labels: { andUp: '& Up', }, templates: { header: getHeader('Rating'), }, collapsible: { collapsed: false, }, }) ); search.addWidget( instantsearch.widgets.toggle({ container: '#free-shipping', attributeName: 'free_shipping', label: 'Free Shipping', values: { on: true, off: false, }, templates: { header: getHeader('Shipping'), }, collapsible: { collapsed: true, }, }) ); search.addWidget( instantsearch.widgets.menu({ container: '#type', attributeName: 'type', sortBy: ['isRefined', 'count:desc', 'name:asc'], limit: 10, showMore: true, templates: { header: getHeader('Type'), }, collapsible: { collapsed: true, }, }) ); search.start(); } // --------------------- // // Helper functions // // --------------------- function getTemplate(templateName) { return document.querySelector(`#${templateName}-template`).innerHTML; } function getHeader(title) { return `<h5>${title}</h5>`; } function getCategoryBreadcrumb(item) { const highlightValues = item._highlightResult.categories || []; return highlightValues.map(category => category.value).join(' > '); } function getStarsHTML(rating, maxRating) { let html = ''; maxRating = maxRating || 5; for (let i = 0; i < maxRating; ++i) { html += `<span class="ais-star-rating--star${i < rating ? '' : '__empty'}"></span>`; } return html; }
JavaScript
0.000002
@@ -4298,28 +4298,8 @@ ue,%0A - off: false,%0A
8b238df39fd553770651d711e4f5e2928903a182
Update character
output.js
output.js
var fs = require('fs'); var child
JavaScript
0
@@ -26,8 +26,9 @@ ar child +_
e779b11d2cf034f89968dd976252e2493f8839fd
Handle config file properly in build
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gutil = require('gulp-util'); var xeditor = require("gulp-xml-editor"); var jeditor = require("gulp-json-editor"); var fmt = require('util').format; var path = require('path'); require('shelljs/global'); gulp.task('default', ['install']); // TODO: move this to a cordova hook gulp.task('install', ['git-check'], function () { exec('git submodule init && git submodule update'); [ 'com.ionic.keyboard', 'org.apache.cordova.splashscreen', 'org.apache.cordova.console', 'org.apache.cordova.dialogs', 'https://github.com/Paldom/SpinnerDialog.git', 'https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git', { name: 'AndroidInAppBilling/v3', options: ['--variable BILLING_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlWtqn9TWvawMDRrykB0OipCwYnArAkinOPq7kb7B7qxokqTmS1maKlxzeAPxwvzYP49u9GNeNJfsqup2E4dR0hiigHQuqmJROUNEOtTxJaIhNLKQaOlC7Bdbvi1n00a5xbb7+kNlIPlo0rtuE2vrj6L3mGV7zKGmsCMU2mPRcE96jMc/kkWsUQnx373MJsgoXq0plUdrkMLhByS4ufKMS1lAebvRPsdkO1dCE3v6ktDyfcdjijMcgTVCqIHtUh6fbidmUClxkNOTsJms+muZyClFGQwvYfZ1+rb00FCcdN6IohJw5crzC3VXL6zlJQhB5SUsv+DuRi9msp0nLFGANwIDAQAB"'] }, 'https://github.com/EddyVerbruggen/cordova-plugin-actionsheet.git', 'org.apache.cordova.inappbrowser', 'org.apache.cordova.statusbar' ] .forEach(function (plugin) { if (typeof plugin == 'object') { exec('cordova plugin add ' + plugin.name + ' ' + plugin.options.join(' ')); } else { exec('cordova plugin add ' + plugin); } }); exec('cordova platform add android'); }); gulp.task('bump', ['bump-package.json', 'bump-config.xml', 'bump-config.json'], function () { return gulp.src('package.json') .pipe(jeditor(function (json) { console.log(gutil.colors.green('New version: ' + json.version)); exec(fmt('git add package.json www/config.xml && git commit -m "Bump version to %s"', json.version)); return json; })); }); function increaseRevision(version) { return version.replace(/\d+$/, parseInt(/\d+$/.exec(version), 10) + 1); } gulp.task('bump-package.json', function () { return gulp.src('package.json') .pipe(jeditor(function (json) { json.version = increaseRevision(json.version); return json; })) .pipe(gulp.dest('.')); }); gulp.task('bump-config.json', function () { return gulp.src('www/config.json') .pipe(jeditor(function (json) { json.version = increaseRevision(json.version); return json; })) .pipe(gulp.dest('www')); }); gulp.task('bump-config.xml', ['bump-package.json'], function () { return gulp.src('www/config.xml') .pipe(xeditor(function (xml) { var version = xml.root().attr('version').value(); var versionCode = xml.root().attr('android-versionCode').value(); xml.root().attr({ version: increaseRevision(version) }); xml.root().attr({ 'android-versionCode': increaseRevision(versionCode) }); return xml; })) .pipe(gulp.dest('www')); }); gulp.task('git-check', function (done) { if (!which('git')) { console.log( ' ' + gutil.colors.red('Git is not installed.'), '\n Git, the version control system, is required to download Ionic.', '\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.', '\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.' ); process.exit(1); } done(); }); function markConfigJsonRelease(release) { return gulp.src('www/config.json') .pipe(jeditor(function (json) { json.debug = !release; return json; })) .pipe(gulp.dest('www')); } gulp.task('mark-release', function () { return markConfigJsonRelease(true); }); gulp.task('mark-debug', function () { return markConfigJsonRelease(false); }); gulp.task('do-release', function () { var jarSigner = path.join(process.env.JAVA_HOME, 'bin', 'jarsigner.exe'), zipAlign = process.env['PROGRAMFILES(x86)'] + '/Android/android-sdk/build-tools/20.0.0/zipalign.exe', keystore = path.join(process.env.userprofile, 'android-release-key.keystore'); if (!test('-f', keystore)) { throw new Error('keystore not found'); } pushd('platforms/android/ant-build'); rm('corvus-release.apk'); exec('cordova build --release android'); exec(fmt('"%s" -verbose -sigalg SHA1withRSA -digestalg SHA1', jarSigner) + fmt(' -keystore %s', keystore) + ' -storepass QyezKqpSLQkm corvus-release-unsigned.apk android-key'); exec(fmt('"%s" -v 4 corvus-release-unsigned.apk corvus-release.apk', zipAlign)); popd(); }); gulp.task('release', ['mark-release', 'do-release', 'mark-debug'], function () { });
JavaScript
0.000001
@@ -3828,16 +3828,32 @@ -debug', + %5B'do-release'%5D, functio @@ -3918,32 +3918,50 @@ sk('do-release', + %5B'mark-release'%5D, function () %7B%0A
78ff26f63dadf6cf3a88febea8fca5d451d89490
fix bad test
spec/javascripts/associationsSpec.js
spec/javascripts/associationsSpec.js
describe('associations', function() { var Address = SC.Resource.define({ schema: { street: String, zip: Number, city: String }, parse: function(json) { json.city = json.city_name; delete json.city_name; return json; } }); var Addresses = SC.Resource.define({ schema: { home: {type: Address, nested: true} } }); describe('has one embedded', function() { it('should use embedded data', function() { var Person = SC.Resource.define({ schema: { name: String, address: {type: Address, nested: true} } }); var data = { name: 'Joe Doe', address: { street: '1 My Street', zip: 12345 } }; var instance = Person.create(data); var address = instance.get('address'); expect(address instanceof Address).toBe(true); expect(address.getPath('data.street')).toBe(data.address.street); instance.set('address', Address.create({street: '2 Your Street'})); expect(instance.getPath('data.address.street')).toBe('2 Your Street'); expect(instance.getPath('data.address.zip')).toBeUndefined(); }); it('should support path overriding', function() { var Person = SC.Resource.define({ schema: { name: String, address: {type: Address, nested: true, path: 'addresses.home'}, addresses: {type: Addresses, nested: true} } }); var data = { name: 'Joe Doe', addresses: { home: { street: '1 My Street', zip: 12345 } } }; var instance = Person.create(data); var address = instance.get('address'); expect(address instanceof Address).toBe(true); expect(address.getPath('data.street')).toBe(instance.getPath('data.addresses.home.street')); instance.set('address', Address.create({street: '2 Your Street'})); expect(instance.getPath('data.addresses.home.street')).toBe('2 Your Street'); expect(instance.getPath('data.addresses.home.zip')).toBeUndefined(); }); }); describe('has many', function() { var Person; describe('with url', function() { beforeEach(function() { Person = SC.Resource.define({ schema: { id: Number, name: String, home_addresses: { type: SC.ResourceCollection, itemType: Address, url: '/people/%@/addresses' }, work_addresses: { type: SC.ResourceCollection, itemType: Address, url: function(instance) { return '/people/' + instance.get('id') + '/addresses'; } } } }); }); it('should support url strings', function() { var person = Person.create({id: 1, name: 'Mick Staugaard'}); var homeAddresses = person.get('home_addresses'); expect(homeAddresses).toBeDefined(); expect(homeAddresses instanceof SC.ResourceCollection).toBe(true); expect(homeAddresses.type).toBe(Address); expect(homeAddresses.url).toBe('/people/1/addresses'); }) it('should support url functions', function() { var person = Person.create({id: 1, name: 'Mick Staugaard'}); var workAddresses = person.get('work_addresses'); expect(workAddresses).toBeDefined(); expect(workAddresses instanceof SC.ResourceCollection).toBe(true); expect(workAddresses.type).toBe(Address); expect(workAddresses.url).toBe('/people/1/addresses'); }) }); describe('nested', function() { beforeEach(function() { Person = SC.Resource.define({ schema: { name: String, home_addresses: { type: SC.ResourceCollection, itemType: Address, nested: true }, work_addresses: { type: SC.ResourceCollection, itemType: Address, nested: true, path: 'office_addresses' } } }); }); it('should use the nested data', function() { var data = { name: 'Joe Doe', home_addresses: [ { street: '1 My Street', zip: 12345 }, { street: '2 Your Street', zip: 23456 } ] }; var person = Person.create(data); var homeAddresses = person.get('home_addresses'); expect(homeAddresses).toBeDefined(); expect(homeAddresses instanceof SC.ResourceCollection).toBe(true); expect(homeAddresses.type).toBe(Address); expect(homeAddresses.get('length')).toBe(2); var address; for (var i=0; i < data.home_addresses.length; i++) { address = homeAddresses.objectAt(i); expect(address).toBeDefined(); expect(address instanceof Address).toBe(true); expect(address.get('street')).toBe(data.home_addresses[i].street); expect(address.get('zip')).toBe(data.home_addresses[i].zip); }; address = homeAddresses.objectAt(0); address.set('street', '3 Other Street'); expect(address.get('street')).toBe('3 Other Street'); expect(person.getPath('home_addresses.firstObject.street')).toBe('3 Other Street'); }); it("should use the class's parse method", function() { var data = { name: 'Joe Doe', home_addresses: [ { street: '1 My Street', zip: 12345, city_name: 'Anytown' } ] }; var person = Person.create(data), address = person.get('home_addresses').objectAt(0); expect(address).toBeTruthy(); expect(address.get('city')).toEqual('Anytown'); }); }); describe('in array', function() { beforeEach(function() { Person = SC.Resource.define({ schema: { name: String, home_addresses: { type: SC.ResourceCollection, itemType: Address, path: 'home_address_ids' } } }); }); }); }); });
JavaScript
0.003293
@@ -200,16 +200,29 @@ n.city = + json.city %7C%7C json.ci @@ -5939,16 +5939,17 @@ tAt(0);%0A +%0A
94e546a69d7ed2d324a33d12d208ab2bf7503437
test server
test/util/api-server.js
test/util/api-server.js
'use strict'; const portfinder = require('portfinder'); const express = require('express'); const bodyParser = require('body-parser'); const _ = require('lodash'); const Promise = require('bluebird'); const fs = Promise.promisifyAll(require('fs')); const formidable = require('formidable'); const form = new formidable.IncomingForm(); const formParse = Promise.promisify(form.parse, {context: form, multiArgs: true}); //const log = require('hw-logger').log; const apiServer = { baseUrl: null, init(appKey) { this.appKey = appKey || 'mysecretkey'; this.app = express(); this.app.use((req, res, next) => { if (req.headers['x-okapi-key'] !== this.appKey) { res.status(401); res.json({code: 'UNAUTHORIZED', message: 'BAD_APP_KEY'}); return; } next(); }); this.app.get('/myapi/v1/myresource', (req, res) => { res.json({foo: 'bar'}); }); this.contacts = []; this.app.post('/myapi/v1/contacts', bodyParser.json(), (req, res) => { const data = Object.assign(_.pick(req.body, ['firstName', 'lastName']), {id: this.contacts.length + 1}); this.contacts.push(data); res.status(201); res.json(data); }); this.app.patch('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => { const data = this.contacts[parseInt(req.params.id) - 1]; if (!data) { res.status(404); res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'}); return; } this.contacts[req.params.id] = Object.assign(data, _.pick(req.body, ['firstName', 'lastName'])); this.contacts.push(this.contacts[req.params.id]); res.status(200); res.json(data); }); this.app.get('/myapi/v1/contacts/:id', (req, res) => { const data = this.contacts[parseInt(req.params.id) - 1]; if (!data) { res.status(404); res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'}); return; } res.json(data); }); this.app.delete('/myapi/v1/contacts/:id', bodyParser.json(), (req, res) => { const index = parseInt(req.params.id) - 1; const data = this.contacts[index]; if (!data) { res.status(404); res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'}); return; } this.contacts.splice(index, 1); res.status(204); res.end(); }); this.app.post('/myapi/v1/upload', (req, res) => { /** * $ curl -i -X POST http://localhost:8000/myapi/v1/upload \ * -H "Content-Type: multipart/form-data" \ * -F "[email protected]" */ formParse(req) .spread((fields, files) => files[_.first(Object.keys(files))]) .then(file => fs.readFileAsync(file.path) .then(content => { res.status(201); res.type(file.type); res.end(content); }) .finally(() => fs.unlinkAsync(file.path)) ); }); this.app.use((req, res, next) => { res.status(404); res.json({code: 'NOT_FOUND', message: 'RESOURCE_NOT_FOUND'}); }); return this; }, start() { return Promise .fromCallback(cb => { portfinder.getPort(cb); }) .then(freePort => { this.port = freePort; this.baseUrl = `http://localhost:${apiServer.port}`; }) .then(() => Promise .fromCallback(cb => { this.server = this.app.listen(this.port, cb); }) ); }, stop() { if (this.server) { return Promise .fromCallback(cb => { this.server.close(cb); }); } } }; if (!module.parent) { apiServer.init() .start() .then(() => { console.log(`Test api server listening to ${apiServer.baseUrl} with app key "${apiServer.appKey}"`); }); } module.exports = apiServer;
JavaScript
0.000001
@@ -885,16 +885,33 @@ on(%7Bfoo: + req.query.foo %7C%7C 'bar'%7D) @@ -944,16 +944,298 @@ s = %5B%5D;%0A + this.app.post('/myapi/v1/contact-forms', bodyParser.urlencoded(), (req, res) =%3E %7B%0A const data = Object.assign(_.pick(req.body, %5B'firstName', 'lastName'%5D), %7Bid: this.contacts.length + 1%7D);%0A this.contacts.push(data);%0A res.status(201);%0A res.json(data);%0A %7D);%0A this
cd8612dc251f04db1bfc1b59d58d9ecea6bff4d9
fix partial style not updated on save
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var stylus = require('gulp-stylus'); var plumber = require('gulp-plumber'); var jade = require('gulp-jade'); var uglify = require('gulp-uglify'); var imagemin = require('gulp-imagemin'); var browserSync = require('browser-sync').create(); //HTML gulp.task('templates', function() { return gulp.src(['./src/jade/*.jade','!./src/jade/_*.jade']) .pipe(plumber()) .pipe(jade({ pretty: true })) .pipe(gulp.dest('./dist/')) }); gulp.task('template-watch',['templates'], function(){ browserSync.reload(); return; }); //STYLE-MINIFY gulp.task('styleCompress', function () { return gulp.src(['./src/styl/*.styl','!./src/styl/_*.styl']) .pipe(plumber()) .pipe(stylus({ compress: true })) .pipe(gulp.dest('./dist/css/')) .pipe(browserSync.stream()); }); //SCRIPTS-MINIFY gulp.task('scriptMinify', function () { return gulp.src('src/js/*.js') .pipe(plumber()) .pipe(uglify()) .pipe(gulp.dest('./dist/js/')) }); gulp.task('script-watch',['scriptMinify'], browserSync.reload); //COMPRESS IMAGE gulp.task('compressImage',function(){ return gulp.src('./src/images/*') .pipe(plumber()) .pipe(imagemin()) .pipe(gulp.dest('./dist/images')) }); //COPY ANIMATE.CSS gulp.task('copyAnimateCSS', function() { gulp.src('./vendor/animate.css/*.min.css') .pipe(gulp.dest('./dist/vendor/css/')); }); //COPY BOOTSTRAP gulp.task('copyBootstrapCSS', function() { gulp.src('./vendor/bootstrap/dist/css/*.min.css') .pipe(gulp.dest('./dist/vendor/css/')); }); gulp.task('copyBootstrapJS', function() { gulp.src('./vendor/bootstrap/dist/js/*.min.js') .pipe(gulp.dest('./dist/vendor/js/')); }); gulp.task('copyBootstrapFont', function() { gulp.src('./vendor/bootstrap/dist/fonts/*.{eot,svg,ttf,woff,woff2}') .pipe(gulp.dest('./dist/vendor/fonts/')); }); //COPY FONTAWESOME gulp.task('copyFontawesomeCSS', function() { gulp.src('./vendor/font-awesome/css/*.min.css') .pipe(gulp.dest('./dist/vendor/css/')); }); gulp.task('copyFontawesomeFont', function() { gulp.src('./vendor/font-awesome/fonts/*.{eot,svg,ttf,otf,woff,woff2}') .pipe(gulp.dest('./dist/vendor/fonts/')); }); gulp.task('copyJqueryJS', function() { gulp.src('./vendor/jquery/dist/jquery.min.js') .pipe(gulp.dest('./dist/vendor/js/')); }); gulp.task('copyLibs',['copyAnimateCSS','copyBootstrapCSS','copyBootstrapJS','copyBootstrapFont','copyFontawesomeCSS','copyFontawesomeFont','copyJqueryJS']); gulp.task('browser-sync', function() { browserSync.init({ server: { baseDir: "./dist/" } }); }); gulp.task('watch', function() { gulp.watch([ 'src/jade/**/*.jade', 'src/jade/*.jade' ], ['template-watch']); gulp.watch(['src/styl/*.styl', './src/styl/**/*.styl'], ['styleCompress']); gulp.watch('src/js/*.js', ['script-watch']); gulp.watch('src/images/**', ['compressImage']); }); gulp.task('default',['copyLibs','templates','styleCompress','scriptMinify','compressImage','browser-sync','watch']);
JavaScript
0
@@ -2776,18 +2776,16 @@ styl', ' -./ src/styl
ee3d487b17ddd54ab8a52543040e43b085a6ef46
Use -1 as absence of data
src/modules/choropleth.js
src/modules/choropleth.js
import 'topojson' import Datamap from 'datamaps/dist/datamaps.usa' import * as util from './utils/choropleth' import colormap from 'colormap' import * as marker from './markers/choropleth' // Map interaction functions // Draw map on given element // Takes d3 instance export default class Choropleth { constructor(d3, elementId, regionHook) { let footBB = d3.select('.footer').node().getBoundingClientRect(), chartBB = d3.select('#' + elementId).node().getBoundingClientRect() let divWidth = chartBB.width, divHeight = window.innerHeight - chartBB.top - footBB.height // Padding offsets divHeight -= 50 // Limits divHeight = Math.min(Math.max(350, divHeight), 600) // Initialized datamap let datamap = new Datamap({ element: document.getElementById(elementId), scope: 'usa', setProjection: (element, options) => { let projection = d3.geoAlbersUsa() .scale(divWidth) .translate([divWidth / 2, divHeight / 2]) return { path: d3.geoPath().projection(projection), projection: projection } }, fills: { defaultFill: '#ccc' }, geographyConfig: { highlightOnHover: false, popupOnHover: false } }) // Add hover info div this.tooltip = d3.select('body').append('div') .attr('id', 'choropleth-tooltip') .style('display', 'none') let svg = d3.select('#' + elementId + ' svg') .attr('height', divHeight) .attr('width', divWidth) this.width = svg.node().getBoundingClientRect().width this.height = svg.node().getBoundingClientRect().height this.svg = svg this.d3 = d3 this.regionHook = regionHook } /** * Plot data on map * Triggered on: * - Choropleth selector change * - Season selector change */ plot(data) { let d3 = this.d3, svg = this.svg, regionHook = this.regionHook, tooltip = this.tooltip let minData = data.range[0], maxData = data.range[1] let colormapName, limits = [], barLimits = [] if (data.type === 'sequential') { // Set a 0 to max ranged colorscheme this.cmap = colormap({ colormap: 'YIOrRd', nshades: 50, format: 'rgbaString' }) limits = [maxData, 0] barLimits = [0, maxData] } else if (data.type === 'diverging') { this.cmap = colormap({ colormap: 'RdBu', nshades: 50, format: 'rgbaString' }).reverse() let extreme = Math.max(Math.abs(maxData), Math.abs(minData)) limits = [extreme, -extreme] barLimits = [-extreme, extreme] } this.colorScale = d3.scaleLinear() .domain(limits) .range([0, this.cmap.length - 0.01]) // Setup color bar this.colorBar = new marker.ColorBar(d3, svg, this.cmap) this.colorBar.update(barLimits) let bb = svg.node().getBoundingClientRect() // Set on hover items d3.selectAll('.datamaps-subunit') .on('mouseover', function() { d3.selectAll('.datamaps-subunit') .filter(d => util.getCousins(this, data.data) .indexOf(d.id) > -1) .style('opacity', '0.4') tooltip.style('display', null) }) .on('mouseout', function() { d3.selectAll('.datamaps-subunit') .filter(d => util.getCousins(this, data.data) .indexOf(d.id) > -1) .style('opacity', '1.0') tooltip.style('display', 'none') }) .on('mousemove', function() { tooltip .style('top', (d3.event.pageY + 20) + 'px') .style('left', (d3.event.pageX + 20) + 'px') .html(util.tooltipText(this, data.data)) }) .on('click', function() { // Change the region selector regionHook(util.getRegionId(util.getSiblings(this, data.data).region)) }) // Save data this.data = data.data } /** * Transition on week change and region highlight * Triggered on: * - Week change * - Region selector change */ update(ids) { let d3 = this.d3, data = this.data, colorScale = this.colorScale, cmap = this.cmap let highlightedStates = [], color = null if (ids.regionIdx >= 0) { highlightedStates = data[ids.regionIdx].states } // Update colors for given week data.map(d => { let value = d.value[ids.weekIdx].data let color = '#ccc' if (value) color = cmap[Math.floor(colorScale(value))] d.states.map(s => { let d3State = d3.select('.' + s) if (highlightedStates.indexOf(s) > -1) { d3State.style('stroke', '#333') .style('stroke-opacity', 1) } else { d3State.style('stroke', 'white') .style('stroke-opacity', 0) } d3State.style('fill', color) d3State.attr('data-value', value) }) }) } }
JavaScript
0.000008
@@ -4527,16 +4527,23 @@ f (value + !== -1 ) color
fef33c9de77a49b3288ad3ed946c403755317c5d
Use plan instead of manual count
test/write-then-read.js
test/write-then-read.js
var fs = require('../'); var rimraf = require('rimraf'); var mkdirp = require('mkdirp'); var test = require('tap').test; var p = require('path').resolve(__dirname, 'files'); process.chdir(__dirname) // Make sure to reserve the stderr fd process.stderr.write(''); var num = 4097; var paths = new Array(num); test('make files', function (t) { rimraf.sync(p); mkdirp.sync(p); for (var i = 0; i < num; ++i) { paths[i] = 'files/file-' + i; fs.writeFileSync(paths[i], 'content'); } t.end(); }) test('read files', function (t) { // now read them var done = 0; for (var i = 0; i < num; ++i) { fs.readFile(paths[i], function(err, data) { if (err) throw err; ++done; if (done === num) { t.pass('success'); t.end() } }); } }); test('cleanup', function (t) { rimraf.sync(p); t.end(); });
JavaScript
0.000001
@@ -565,21 +565,19 @@ m%0A -var done = 0; +t.plan(num) %0A f @@ -632,16 +632,25 @@ aths%5Bi%5D, + 'ascii', functio @@ -709,92 +709,32 @@ -++done;%0A if (done === num) %7B%0A t.pass('success');%0A t.end()%0A %7D +t.equal(data, 'content') %0A
10e37cde7f983ae9496bf642cb8d6cd4b054d39a
Fix missing command name while doing !help if command was not found
modules/general/CommandHelp.js
modules/general/CommandHelp.js
'use strict'; const config = require('config'), Command = require('../Command'), CommandParam = require('../CommandParam'), CommandError = require('../../errors/CommandError'), CacheMiddleware = require('../../middleware/CacheMiddleware'), ReplyMethodMiddleware = require('../../middleware/ReplyMethodMiddleware'), RestrictPermissionMiddleware = require('../../middleware/internal/RestrictPermissionsMiddleware'); class CommandHelp extends Command { constructor(module) { super(module); this.helpText = 'Shows information about how to use commands, with optionally a command as argument to get more detailed information.'; this.shortHelpText = 'Shows information about how to use commands'; this.params = new CommandParam('command', 'The command', true); this.middleware = [ new ReplyMethodMiddleware({ method: 'dm' }), new CacheMiddleware() ]; } onCommand(response) { const modules = this.module.bot.getModules(); const commandPrefix = config.get('discord.command_prefix'); if (response.params.length > 0) { // Reply with help for a specific command const commandTrigger = response.params[0].replace(new RegExp(`^${commandPrefix}?(.*)$`), '$1'); let command; for (module of modules) { const foundCommand = module.commands.find(command => command.trigger == commandTrigger); if (foundCommand) { command = foundCommand; break; } } if (!command) { throw new CommandError(`The command \`${command}\` is not recognized. ` + `Type \`${this}\` to see the list of commands.`); } return `\n${this.formatCommandHelp(response.message, command)}`; } else { // Reply with general help const help = []; modules.forEach(module => { const moduleHelp = this.formatModuleHelp(response.message, module); if (moduleHelp) { help.push(moduleHelp); } }); return `\n${help.join('\n\n')}\n\nCommands marked with an asterisk might be restricted.`; } } formatCommandChannelFilter(command) { let text = []; let middleware = command.allMiddleware.find(m => m.name === 'RestrictChannelsMiddleware'); if (middleware) { // Restricted channels is applied if (middleware.options.types.length === 1) { switch (middleware.options.types[0]) { case 'dm': text.push('DM only'); break; case 'text': if (middleware.options.channels.length > 0) { text.push('specific server channels only'); } else { text.push('server channels only'); } break; } } } middleware = command.allMiddleware.find(m => m.name === 'MentionsMiddleware'); if (middleware) { // Mentions are allowed if (middleware.options.types.includes('mention')) { if (middleware.options.types.length === 1) { text.push('strictly mentionable'); } else { text.push('mentionable'); } } } return text.join(', '); } formatModuleHelp(message, module) { const commands = []; module.commands.forEach(command => { const commandText = `\`${command}\``; const helpText = command.shortHelpText; if (!helpText) { return; } let extraText = this.formatCommandChannelFilter(command); // TODO: Find a better way to detect server role assignments in a DM if (!RestrictPermissionMiddleware.isCommandAllowed(message, command)) { extraText += '*'; } const text = extraText ? `${commandText} - ${helpText} *(${extraText})*` : `${commandText} - ${helpText}`; commands.push(text); }); if (commands.length === 0) { return; } return `__**${module.name}**__\n${commands.join('\n')}`; } formatCommandHelp(message, command) { let invocation = `${command} `; const helpText = command.helpText; const params = []; command.params.forEach(param => { const paramText = `\`${param.name}\``; const helpText = param.helpText; const text = param.isOptional ? `${paramText} - ${helpText} *(optional)*` : `${paramText} - ${helpText}`; params.push(text); invocation += (param.isOptional ? '[' : '') + param.name + (param.isOptional ? ']' : '') + ' '; }); let extraText = this.formatCommandChannelFilter(command); // TODO: Find a better way to detect server role assignments in a DM if (!RestrictPermissionMiddleware.isCommandAllowed(message, command)) { extraText += (extraText ? ', ' : '') + 'might be restricted'; } if (extraText) { return `\`\`\`${invocation}\`\`\`\n**(${extraText})**\n${helpText}\n\n${params.join('\n')}`; } return `\`\`\`${invocation}\`\`\`\n${helpText}\n\n${params.join('\n')}`; } } module.exports = CommandHelp;
JavaScript
0.000374
@@ -1706,16 +1706,23 @@ %7Bcommand +Trigger %7D%5C%60 is n
78d46c89f5117f8355906f6a007d05016234fd2c
Remove vestigal `test/*.coffee` gulpfile pattern
gulpfile.js
gulpfile.js
/* jshint node: true */ var gulp = require('gulp'); var yargs = require('yargs'); var mocha = require('gulp-mocha'); var jshint = require('gulp-jshint'); function buildArgs(args) { var argName, skipArgs = { _: true, '$0': true }; for (argName in yargs.argv) { if (yargs.argv.hasOwnProperty(argName) && !skipArgs[argName]) { args[argName] = yargs.argv[argName]; } } return args; } gulp.task('test', function() { return gulp.src(['./test/*.js', './test/*.coffee'], {read: false}) // Reporters: // https://github.com/mochajs/mocha/blob/master/lib/reporters/index.js .pipe(mocha(buildArgs({ reporter: 'spec' }))); }); gulp.task('lint', function() { return gulp.src(['*.js', 'lib/**/*.js', 'src/**/*.js', 'test/**/*.js']) .pipe(jshint()) .pipe(jshint.reporter('default')); });
JavaScript
0.000001
@@ -466,27 +466,8 @@ .js' -, './test/*.coffee' %5D, %7B
11c5478e3fd14a952d63717b2147e6f8785606e6
Make default gulp task the js task
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const jshint = require('gulp-jshint'); const browserify = require('browserify'); const watchify = require('watchify'); const source = require('vinyl-source-stream'); const gutil = require('gulp-util'); const assign = require('lodash.assign'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); const src = [ 'index.js', './lib/**/*.js' ]; const bundleTarget = 'benzene.js'; const opts = assign({}, watchify.args, { entries: [ 'index.js' ] }); const b = watchify(browserify(opts)); gulp.task('js', bundle); b.on('update', bundle); b.on('log', gutil.log); function bundle() { return b.bundle() .on('error', gutil.log.bind(gutil, 'Browserify error')) .pipe(source(bundleTarget)) .pipe(gulp.dest('./sample/')); } gulp.task('jshint', () => { return gulp.src(src) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')) }); gulp.task('pre-test', () => { return gulp.src(src) .pipe(istanbul()) .pipe(istanbul.hookRequire()); }) gulp.task('test', ['pre-test'], () => { return gulp.src(['test/**/*.js']) .pipe(mocha()) .pipe(istanbul.writeReports()); });
JavaScript
0.000368
@@ -549,18 +549,23 @@ p.task(' -js +default ', bundl
f2dce824ec64cbae671ea756d410db08642b0e46
Add missing // in the local URL in beforeEach
spec/e2e.js
spec/e2e.js
var webdriver = require('selenium-webdriver'), By = require('selenium-webdriver').By, until = require('selenium-webdriver').until; var test = require('selenium-webdriver/testing'); var assert = require('selenium-webdriver/testing/assert'); var driver = new webdriver.Builder() .forBrowser('firefox') .build(); var $ = function (selector, context) { if (context) { return context.findElement(By.css(selector)); } return driver.findElement(By.css(selector)); }; var helper = { setTab: function (selector) { this.tab_selector = selector; this.tab = $(selector); }, assertScreenValue: function (element, expected) { driver.wait(until.elementTextIs(element, expected)); }, assertResult: function (url) { var urlScreen = $('.here-text-screen textarea', this.tab); var markupScreen = $('.markup-screen textarea', this.tab); // Url in the textarea is correct this.assertScreenValue(urlScreen, url); // Markup is correct this.assertScreenValue(markupScreen, '<a href="' + url + '">Your text here</a>'); // Link is there with correct href $('a', this.tab).getAttribute('href').then(function (value) { return assert(value).equals(url); }); // Copy button is there driver.wait(until.elementLocated(By.css(this.tab_selector + ' .url-screen button'))); // Copy button is there driver.wait(until.elementLocated(By.css(this.tab_selector + ' .markup-screen button'))); }, selectOption: function (text) { var listitem = driver.wait(until.elementLocated(By.xpath('//li[normalize-space(.)="' + text + '"]'))); driver.wait(until.elementIsVisible(listitem)); // Although element is visible, because of the transition it is not yet fully there, so we sleep a bit. driver.sleep(300); listitem.click(); }, sendKeysSelectOption: function (selector, keys, text) { $(selector + ' input[type="text"]', this.tab).sendKeys(keys); this.selectOption(text); }, selectMyLocation: function (selector) { $(selector + ' input[type="text"]', this.tab).click(); this.selectOption('Use user\'s location'); } }; test.describe('Link Builder', function () { // Default 2000 ms is not enough for most tests. this.timeout(10000); test.before(function () { }); test.after(function () { driver.quit(); }); test.beforeEach(function () { driver.get('http:127.0.0.1:5000'); driver.executeScript('window.scroll(0, 400)'); }); test.describe('Route panel', function () { test.beforeEach(function () { helper.setTab('.here-tabs-body>div:nth-child(1)'); }); test.it('should generate route from a to b', function () { helper.sendKeysSelectOption('.row-route-from', 'Bremen', 'Bremen, Germany'); helper.sendKeysSelectOption('.row-route-to', 'Berlin', 'Berlin, Germany'); helper.assertResult('https://share.here.com/r/53.0751,8.80469,Bremen%2C%20Germany/52.51607,13.37699,Berlin%2C%20Germany?m=d&t=normal'); }); test.it('should generate route from mylocation to b', function () { helper.selectMyLocation('.row-route-from'); helper.sendKeysSelectOption('.row-route-to', 'Berlin', 'Berlin, Germany'); helper.assertResult('https://share.here.com/r/mylocation/52.51607,13.37699,Berlin%2C%20Germany?m=d&t=normal'); }); test.it('should generate route from a to mylocation', function () { helper.sendKeysSelectOption('.row-route-from', 'Berlin', 'Berlin, Germany'); helper.selectMyLocation('.row-route-to'); helper.assertResult('https://share.here.com/r/52.51607,13.37699,Berlin%2C%20Germany/mylocation?m=d&t=normal'); }); test.describe('Options', function () { test.beforeEach(function () { helper.selectMyLocation('.row-route-from'); helper.sendKeysSelectOption('.row-route-to', 'Berlin', 'Berlin, Germany'); }); test.it('should set route mode', function () { $('select option:nth-child(2)', helper.tab).click(); helper.assertResult('https://share.here.com/r/mylocation/52.51607,13.37699,Berlin%2C%20Germany?m=pt&t=normal'); $('select option:nth-child(3)', helper.tab).click(); helper.assertResult('https://share.here.com/r/mylocation/52.51607,13.37699,Berlin%2C%20Germany?m=w&t=normal'); }); test.it('should set map type', function () { $('.builder-row:nth-of-type(2) select option:nth-child(2)', helper.tab).click(); helper.assertResult('https://share.here.com/r/mylocation/52.51607,13.37699,Berlin%2C%20Germany?m=d&t=terrain'); }); }); }); test.describe('Location panel', function () { test.beforeEach(function () { $('.here-tabs-controls li:nth-child(2)').click(); helper.setTab('.here-tabs-body>div:nth-child(2)'); helper.sendKeysSelectOption('.location-box', 'Berlin', 'Berlin, Germany'); }); test.it('should generate location link', function () { helper.assertResult('https://share.here.com/l/52.51607,13.37699,Berlin%2C%20Germany?t=normal'); }); test.it('should set map type', function () { $('select option:nth-child(2)', helper.tab).click(); helper.assertResult('https://share.here.com/l/52.51607,13.37699,Berlin%2C%20Germany?t=terrain'); }); }); test.describe('Place panel', function () { test.it('should generate place link', function () { $('.here-tabs-controls li:nth-child(3)').click(); helper.setTab('.here-tabs-body>div:nth-child(3)'); helper.sendKeysSelectOption('.location-box', 'Berlin', 'Berlin, Germany'); helper.assertResult('https://share.here.com/p/s-YmI9MTMuMTE5MzclMkM1Mi4zNzYxNSUyQzEzLjY1ODAxJTJDNTIuNjYwNTg7Yz1jaXR5LXRvd24tdmlsbGFnZTtpZD0yNzZ1MzNkYi1mYmNmZmQyZTUyZjk0ZjU2YjZmNTU0YzBiYWEzM2YwNjtsYXQ9NTIuNTE2MDc7bG9uPTEzLjM3Njk4O249QmVybGluO25sYXQ9NTIuNTE2MDc7bmxvbj0xMy4zNzY5ODtoPTYwMTQzNw'); }); }); });
JavaScript
0.000001
@@ -2559,16 +2559,18 @@ t('http: +// 127.0.0.
d5d2aa5ed54cf1216ca94d928bc76432f6d8352b
Use del instead of gulp-rimraf
gulpfile.js
gulpfile.js
var babel = require('gulp-babel'); var clean = require('gulp-rimraf'); var gulp = require('gulp'); var mocha = require('gulp-mocha'); var plumber = require('gulp-plumber'); gulp.task('clean', function() { return gulp.src([ 'dist/*', 'lib/*', 'spec/**/*.js' ]).pipe(clean()); }); gulp.task('build', function() { return gulp.src('src/**/*.js') .pipe(plumber()) .pipe(babel()) .pipe(gulp.dest('.')); }); gulp.task('spec', function() { return gulp.src('spec/**/*.js', {read: false}) .pipe(plumber()) .pipe(mocha({bail: true})); }); gulp.task('rebuild', gulp.series( 'clean', 'build' )); gulp.task('watch', function() { return gulp.watch('src/**/*.js', gulp.series( 'build', 'spec' )); }); gulp.task('default', gulp.series( 'rebuild', 'spec', 'watch' ));
JavaScript
0.000001
@@ -34,21 +34,21 @@ ');%0Avar -clean +del = req @@ -57,19 +57,11 @@ re(' -gulp-rimraf +del ');%0A @@ -188,32 +188,34 @@ lean', function( +cb ) %7B%0A return gul @@ -211,24 +211,19 @@ return -gulp.src +del (%5B%0A ' @@ -270,24 +270,13 @@ %0A %5D -).pipe(clean()); +, cb) %0A%7D);
3ca8b1ad00377b5639f526bbdff8b2b7e24b6e02
add jsx transform to gulpfile
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var clean = require('gulp-clean'); gulp.task('clean', function() { return gulp.src(['build/*'], {read: false}).pipe(clean()); }); var react = require('gulp-react'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var jshint = require('gulp-jshint'); // Parse and compress JS and JSX files gulp.task('javascript', function() { // Listen to every JS file in ./frontend/javascript return gulp.src('lib/**/*.js') // Turn React JSX syntax into regular javascript .pipe(react()) // Output each file into the ./build/javascript/ directory .pipe(gulp.dest('build/javascript/')) // Optimize each JavaScript file //.pipe(uglify()) // Add .min.js to the end of each optimized file //.pipe(rename({suffix: '.min'})) // Output each optimized .min.js file into the ./build/javascript/ dir //.pipe(gulp.dest('build/javascript/')); }); var browserify = require('gulp-browserify'); gulp.task('browserify', ['javascript', 'lint'], function() { return gulp.src('build/javascript/index.js') .pipe(browserify({transform: ['envify']})) .pipe(rename('compiled.js')) .pipe(gulp.dest('build/javascript/')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('build/javascript/')); }); gulp.task('lint', function() { return gulp.src('./build/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); var less = require('gulp-less'); var minifycss = require('gulp-minify-css'); // gulp.task('styles', function() { // return gulp.src('themes/**/*.less') // .pipe(less()) // .pipe(gulp.dest('build/')) // .pipe(minifycss()) // .pipe(rename({suffix: '.min'})) // .pipe(gulp.dest('build/')); // }); var nodemon = require('gulp-nodemon'); gulp.task('watch', ['clean'], function() { var watching = false; gulp.start('browserify', 'styles', function() { // Protect against this function being called twice. (Bug?) if (!watching) { watching = true; // Watch for changes in frontend js and run the 'javascript' task gulp.watch('lib/**/*.js', ['javascript','browserify_nodep']); // // Run the 'browserify_nodep' task when client.js changes // gulp.watch('build/javascript/compiled.js', ['browserify_nodep']); // Watch for .less file changes and re-run the 'styles' task //gulp.watch('frontend/**/*.less', ['styles']); // Start up the server and have it reload when anything in the // ./build/ directory changes //nodemon({script: 'server.js', watch: 'build'}); } }); }); gulp.task('default', ['clean'], function() { return gulp.start('browserify' //, 'styles' ); });
JavaScript
0.000001
@@ -914,24 +914,166 @@ t/'));%0A%7D);%0A%0A +gulp.task('jsxExamples', function() %7B%0A return gulp.src('examples/jsx/*.jsx')%0A .pipe(react())%0A .pipe(gulp.dest('examples/build/'))%0A%7D);%0A%0A var browseri
b29419aa9acc4f666db93e952aacee400e618e4c
Update to use new gulp api
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var audiosprite = require('./vendor/audiosprite'); var glob = require('glob'); var shell = require('gulp-shell'); var fs = require('fs'); gulp.task('audio', function() { var files = glob.sync('./src/assets/sounds/*.mp3'); var outputPath = './dist/audio'; var opts = { output: outputPath, path: './', format: 'howler2', 'export': 'ogg,mp3', loop: ['quacking', 'sniff'] }; return audiosprite(files, opts, function(err, obj) { if (err) { console.error(err); } return fs.writeFile('./dist/audio' + '.json', JSON.stringify(obj, null, 2)); }); }); gulp.task('images', function(){ // There is a texturepacker template for spritesmith but it doesn't work // well with complex directory structures, so instead we use the shell // checking TexturePacker --version first ensures it bails if TexturePacker // isn't installed return gulp.src('', {read:false}) .pipe(shell([ 'TexturePacker --version || echo ERROR: TexturePacker not found, install TexturePacker', 'TexturePacker --disable-rotation --data dist/sprites.json --format json --sheet dist/sprites.png src/assets/images' ])) .pipe(connect.reload()); }); gulp.task('deploy', function() { return gulp.src('', {read:false}) .pipe(shell([ 'AWS_PROFILE=duckhunt terraform plan', 'AWS_PROFILE=duckhunt terraform apply', 'aws --profile duckhunt s3 sync dist/ s3://duckhuntjs.com --include \'*\' --acl \'public-read\'' ])); }); gulp.task('default', ['images', 'audio']);
JavaScript
0
@@ -179,16 +179,30 @@ audio', +gulp.parallel( function @@ -624,24 +624,25 @@ ));%0A %7D);%0A%7D) +) ;%0A%0Agulp.task @@ -652,16 +652,30 @@ mages', +gulp.parallel( function @@ -936,32 +936,33 @@ eturn gulp.src(' +* ', %7Bread:false%7D) @@ -1233,24 +1233,25 @@ eload());%0A%7D) +) ;%0A%0Agulp.task @@ -1261,16 +1261,30 @@ eploy', +gulp.parallel( function @@ -1307,16 +1307,17 @@ lp.src(' +* ', %7Bread @@ -1540,16 +1540,17 @@ %5D));%0A%7D) +) ;%0A%0Agulp. @@ -1565,17 +1565,30 @@ fault', -%5B +gulp.parallel( 'images' @@ -1596,12 +1596,12 @@ 'audio' -%5D +) );%0A
3f0599c0a30be160ccf64e66d06a660cc42a162e
Update gulpfile.js
gulpfile.js
gulpfile.js
/* * Copyright © 2016 I.B.M. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { var gulp = require('gulp'); var $ = require('gulp-load-plugins')({ pattern: ['gulp-*', 'gulp.*'], replaceString: /\bgulp[\-.]/ }); var appDev = './ui/'; var appProd = './dist/'; gulp.task('build-ibm', function() { return gulp.src(appDev + 'ibm/*.js') .pipe(gulp.dest(appProd + 'ibm')); }); gulp.task('build-css', ['build-fonts'], function() { return gulp.src(appDev + 'css/*.css') .pipe($.cleanCss()) .pipe(gulp.dest(appProd + 'css/')) .pipe($.size({ 'title': 'css' })); }); gulp.task('build-fonts', function() { return gulp.src([appDev + 'fonts/**']) // .pipe($.fontmin()) .pipe(gulp.dest(appProd + 'fonts')); }); gulp.task('build-html', ['build-img', 'build-css', 'build-ibm'], function() { var assets = $.useref({ 'searchPath': ['ui/**/*.*', 'node_modules'] }); return gulp.src(appDev + 'index.html') .pipe(assets) //node_modules dir is in the current dir, search there for dependencies! .pipe($.sourcemaps.init({ 'identityMap': true, 'debug': true })) .pipe($.useref()) // TODO re-add with caching //.pipe(sourcemaps.write('./maps')) .pipe($.if('*.js', $.if('**/dashboard.min.js', $.uglify({mangle: false, preserveComments: 'license'}), $.uglify()))) .pipe($.if('*.css', $.cleanCss())) .pipe(gulp.dest(appProd)) .pipe($.size({ 'title': 'html' })); }); gulp.task('build-img', function() { return gulp.src(appDev + 'images/**/*') // TODO re-add with caching // .pipe($.if('*.png', $.imagemin())) .pipe(gulp.dest(appProd + 'images/')); }); gulp.task('clean', function() { return gulp.src(appProd, { read: false }) .pipe($.clean()); }); gulp.task('watch', ['build-html'], function() { gulp.watch(appDev + '**/*.js', ['build-html']); gulp.watch(appDev + 'css/*.css', ['build-html']); gulp.watch(appDev + '**/*.html', ['build-html']); gulp.watch(appDev + 'images/**/*', ['build-html']); }); gulp.task('server:start', function() { $.developServer.listen({ path: './server.js' }); }); gulp.task('server:watch', ['build-html', 'server:start', 'watch']); gulp.task('default', ['build-html']); }());
JavaScript
0
@@ -1845,17 +1845,18 @@ caching + %0A - @@ -1898,32 +1898,115 @@ s'))%0A + // Commenting out lines that don't work with latest version of Node%0A // .pipe($.if('*.j @@ -2110,32 +2110,35 @@ ))))%0A + // .pipe($.if('*.c
a217c9980e03196cee69a96b8add9583c4929c6d
Implement add control behavior for variables
app/scripts/variable.js
app/scripts/variable.js
'use strict'; var m = require('mithril'); var _ = require('underscore'); function Variable(args) { this.name = args.name; } Variable.validNamePattern = /^[A-Za-z]$/; Variable.Component = {}; Variable.Component.controller = function () { return { getVariableIndex: function (variableElem) { var currentElem = variableElem.parentNode.parentNode; var variableIndex = -1; do { currentElem = currentElem.previousElementSibling; variableIndex += 1; } while (currentElem !== null && currentElem.className === 'variable'); return variableIndex; }, updateVariableName: function (ctrl, app, event) { var variableIndex = ctrl.getVariableIndex(event.target); if (Variable.validNamePattern.test(event.target.value)) { app.variables[variableIndex].name = event.target.value; } }, focusVariableInput: function (event) { if (event.target.nodeName === 'INPUT') { event.target.select(); } } }; }; Variable.Component.view = function (ctrl, app) { return m('div#variables', { onclick: ctrl.focusVariableInput, oninput: _.partial(ctrl.updateVariableName, ctrl, app) }, _.map(app.variables, function (variable) { return m('div.variable', m('div.has-controls', [ m('div.control.add'), m('div.control.remove'), m('input', { type: 'text', value: variable.name, maxlength: 1, autocapitalize: 'off', autocomplete: 'off', autocorrect: 'off', spellcheck: false }) ])); })); }; module.exports = Variable;
JavaScript
0.000002
@@ -863,122 +863,1558 @@ -focusVariableInput: function (event) %7B%0A if (event.target.nodeName === 'INPUT') %7B%0A event.target.select( +// Get the next available variable name for a new variable (to insert next%0A // to the given variable)%0A getNextVariableName: function (variables, variable) %7B%0A // Create a list of variable names already in use%0A var variableCharCodes = _.map(variables, function (variable) %7B%0A return variable.name.charCodeAt(0);%0A %7D);%0A // Look for the next letter that isn't already in use%0A var nextVarCharCode = variable.name.charCodeAt(0);%0A do %7B%0A nextVarCharCode += 1;%0A %7D while (variableCharCodes.indexOf(nextVarCharCode) !== -1);%0A // Wrap variable name around alphabet if necessary (e.g. 'z' wraps around%0A // to 'z')%0A if (nextVarCharCode === 91 %7C%7C nextVarCharCode === 123) %7B%0A nextVarCharCode = nextVarCharCode - 26;%0A %7D%0A return String.fromCharCode(nextVarCharCode);%0A %7D,%0A // Add variable next to variable whose add control was pressed%0A addVariable: function (ctrl, app, event) %7B%0A var variableIndex = ctrl.getVariableIndex(event.target);%0A var variable = app.variables%5BvariableIndex%5D;%0A app.variables.splice(variableIndex + 1, 0, new Variable(%7B%0A name: ctrl.getNextVariableName(app.variables, variable)%0A %7D));%0A %7D,%0A handleClick: function (ctrl, app, event) %7B%0A if (event.target.nodeName === 'INPUT') %7B%0A // Focus variable input if input is clicked%0A event.target.select();%0A %7D else if (event.target.className.indexOf('add') !== -1) %7B%0A // Add variable if 'add' control is clicked%0A ctrl.addVariable(ctrl, app, event );%0A @@ -2531,31 +2531,46 @@ ck: -ctrl.focusVariableInput +_.partial(ctrl.handleClick, ctrl, app) ,%0A
49884eda90642e766f0da1731abf5d9b8252573b
Update PACT_BROKER_URL
tests/pact/setup/config.js
tests/pact/setup/config.js
'use strict' const constants = { CONSUMER: 'frontend_client_portal-analytics', PACT_BROKER_URL: process.env.NODE_ENV === 'production' || process.env.TEST_ENV === 'ci' ? 'http://pact-broker/' : 'http://localhost:7228/', } const config = (service) => { if (!service) { console.warn('A service name must be provided.') return } const serviceConfig = require('./' + service + '/config.js') let constantKeys = Object.keys(serviceConfig) constantKeys.forEach((key) => (constants[key] = serviceConfig[key])) return constants } module.exports = config
JavaScript
0
@@ -176,16 +176,17 @@ ? 'http +s ://pact- @@ -191,16 +191,32 @@ t-broker +.reevoocloud.com /'%0A :
cf28497e5be47f21f6d17c4da125d5fce764bf1f
Update the pointsTotal when resetting also.
app/scripts/controllers/task.js
app/scripts/controllers/task.js
'use strict'; angular.module('kanbanBoardApp') .controller('TaskCtrl', ['$scope', 'Task', function ($scope, Task) { var taskPointsLoaded = false; $scope.taskPointsLoaded = function () { return taskPointsLoaded; }; $scope.loadTaskPoints = function () { Task.tags({taskId: $scope.task.id}, function (response) { $scope.points = $scope.taskPoints(response.data); $scope.pointsTotal[$scope.task.id] = $scope.points; $scope.pointTags = $scope.getPointTags(response.data); taskPointsLoaded = true; }); }; $scope.taskPoints = function (tags) { var pointTags = $scope.getPointTags(tags); var pointValue = 0; if (pointTags.length > 0) { pointValue = $scope.tagPointValue(pointTags[0]); } return pointValue; }; $scope.getPointTags = function (tags) { return tags.filter( function (tag) { if (tag.name.match(/points/)) { return tag; } }); }; $scope.tagPointValue = function (tag) { return parseInt(tag.name.replace(/[^\d+]/g, '')); } $scope.setPointTag = function () { $scope.resetPointTags(); Task.addTag({taskId: $scope.task.id}, {data: {tag: $scope.pointTag.id}}, function (response) { $scope.points = $scope.taskPoints([$scope.pointTag]); $scope.pointsTotal[$scope.task.id] = $scope.points; }); }; $scope.resetPointTags = function () { $scope.pointTags.forEach(function (pointTag) { $scope.removePointTag(pointTag.id); }); $scope.points = 0; }; $scope.removePointTag = function (pointTagId) { Task.removeTag({taskId: $scope.task.id}, {data: {tag: pointTagId}}, function (response, status) { }); }; }]);
JavaScript
0
@@ -1586,24 +1586,82 @@ points = 0;%0A + $scope.pointsTotal%5B$scope.task.id%5D = $scope.points;%0A %7D;%0A%0A
834e4d6c203058bd5f87f6ca2d82b0637f9a0af3
fix parser to complete the tests...^^
parser.js
parser.js
"use strict"; var request = require("request"); var cheerio = require("cheerio"); var moment = require("moment"); var mongoose = require("mongoose"); var async = require("async"); var crypto = require("crypto"); // just a static test url, later the client will send a week and a year var url = "https://lsf.hft-stuttgart.de/qisserver/rds?state=wplan&k_abstgv.abstgvnr=262&week=12_2015&act=stg&pool=stg&show=plan&P.vx=lang&P.Print="; var startParser = function() { request(url, function(error, response, html) { if(!error) { var lectures = parse(html); insertInDatabase(lectures); } }); }; var parse = function(html) { var table = null; var days = []; var timeTableGrid = []; var lectures = []; var $ = cheerio.load(html); // load days before we cut of td.plan_rahmen stuff days = getDaysInThisWeek($); // remove td.plan rahmen from the table, this removes a lot of trouble table = $("th.plan_rahmen").closest("table"); table.find(".plan_rahmen").remove(); // lets parse // get all the rows of the timetable (except the header (days) row) var rows = table.children("tr:not(:first-child)"); // create and prefill the grid, which holds our whole timetable for (var i = 0; i < rows.length; i++) { // rows timeTableGrid[i] = new Array(days.length); for (var j = 0; j < days.length; j++) { // columns timeTableGrid[i][j] = "."; } } // iterate over each row and each cell rows.each(function(i) { var cells = $(this).children("td:not(:first-child)"); // it seems like cheerio doesnt support collection.get(), so we just // bottle that cheerio collection into a native array. var cellsArray = []; cells.each(function(j) { cellsArray.push($(this)); }); for (var j = 0; j < days.length; j++) { if (timeTableGrid[i][j] === ".") { // here must be a td-(lecture)-element var currCell = cellsArray[0]; cellsArray.shift(); // removes the first element, its a pseudo queue if (currCell.attr("class").indexOf("plan1") > -1) { // no lecture here } else if (currCell.attr("class").indexOf("plan2") > -1) { // here we have a lecture // now mark the whole rowspan down as the same lecture var rowspan = currCell.attr("rowspan"); for (var k = 0; k < rowspan; k++) { timeTableGrid[i+k][j] = j; } // parse the lectures td element var moreLectures = parseGroupsInLecture(currCell, days, j); lectures = lectures.concat(moreLectures); } } } }); return lectures; }; var insertInDatabase = function(lectures) { // connect to mongodb if not already if(mongoose.connection.readyState === 0) { mongoose.connect("mongodb://localhost:27017/wuw"); } // create models from our schemas var Lecture = require("./model_lecture"); var Deadline = require("./model_deadline"); // drop current lecture collection to get a fresh result mongoose.connection.collections.lectures.drop(function(err) { if(err) console.log(err); // push every lecture to our db async.each(lectures, function(lecture, cb) { // create Lecture from our Model var Lec = new Lecture(); // set attributes Lec.date = lecture.start; Lec.fullLectureName = lecture.lsfName; Lec.shortLectureName = lecture.shortName; Lec.room = lecture.lsfRoom; Lec.startTime = lecture.start; Lec.endTime = lecture.end; Lec.group = lecture.group; Lec.hashCode = lecture.hashCode; // save lecture to db Lec.save(cb); }, function(err) { if (err) console.log(err); mongoose.disconnect(); console.log("Success! The parser inserted " + lectures.length + " lectures in the database"); }); }); }; var parseGroupsInLecture = function(html, days, dayPos) { var lectures = []; var $ = cheerio.load(html); // there could be more then one groups in this lecture, // we create a lecture for every group html.find("table").each(function(i) { var time = trimProperty($(this).find("td.notiz").first().text()); var date = days[dayPos]; var lecture = {}; lecture.lsfName = $(this).find("a").first().attr("title"); lecture.start = parseStartEnd(date, time).start; lecture.end = parseStartEnd(date, time).end; lecture.lsfDate = date; lecture.lsfTime = time; lecture.lsfRoom = $(this).find("td.notiz a").first().text(); lecture.group = parseGroup(lecture.lsfName); lecture.shortName = parseShortName(lecture.lsfName); lecture.hashCode = hashCode(lecture.lsfName+lecture.lsfDate+lecture.lsfTime+lecture.lsfRoom); lectures.push(lecture); }); return lectures; }; var parseGroup = function(s) { return s.split(" ")[0]; }; var parseShortName = function(s) { var parts = s.split(" "); parts.shift(); var shortName = parts.join(" "); return shortName; }; var parseStartEnd = function(date, time) { var start = null; var end = null; var timeString = time.split(" ")[0]; var starTimeString = timeString.split("-")[0]; var endTimeString = timeString.split("-")[1]; var dateString = date.split(" ")[1]; var startString = dateString + " " + starTimeString; var endString = dateString + " " + endTimeString; start = moment(startString, "DD-MM-YYYY HH:mm"); end = moment(endString, "DD-MM-YYYY HH:mm"); return { start: start, end: end }; } var trimProperty = function(s) { s = s.replace(/ /g, ""); // remove that whitespace s = s.replace(/\n/g, ""); s = s.replace(/\r/g, ""); s = s.trim(); return s; }; var outputAsTable = function(timeTableGrid, iteration) { for (var i = 0; i < timeTableGrid.length; i++) { var row = timeTableGrid[i]; process.stdout.write(iteration + ". ROW: " + i + ":\t"); for (var j = 0; j < row.length; j++) { process.stdout.write(row[j] + " "); } process.stdout.write("\n"); } }; var getDaysInThisWeek = function($) { var days = []; var headerRow = $("th.plan_rahmen").closest("table").children("tr").first(); headerRow.find("th").each(function(index) { var day = $(this).text(); day = day.replace(/ /g, ""); day = day.replace(/\n/g, " "); day = day.trim(); days.push(day); }); return days; }; var hashCode = function(s){ var hash = crypto.createHash('md5').update(s).digest('hex'); return hash; }; startParser(); module.exports = { startParser: startParser };
JavaScript
0
@@ -6502,16 +6502,30 @@ orts = %7B + parse: parse, startPa
d03dcfb148fb0139e09516245f125fc8053a9c26
Add GitHub Project button (#1245)
src/scripts/content/github.js
src/scripts/content/github.js
'use strict'; togglbutton.render('#partial-discussion-sidebar', { observe: true }, function( elem ) { var div, link, description, numElem = $('.gh-header-number'), titleElem = $('.js-issue-title'), projectElem = $('h1.public strong a, h1.private strong a'), existingTag = $('.discussion-sidebar-item.toggl'); // Check for existing tag, create a new one if one doesn't exist or is not the first one // We want button to be the first one because it looks different from the other sidebar items // and looks very weird between them. if (existingTag) { if (existingTag.parentNode.firstChild.classList.contains('toggl')) { return; } existingTag.parentNode.removeChild(existingTag); } description = titleElem.textContent; if (numElem !== null) { description = numElem.textContent + ' ' + description.trim(); } div = document.createElement('div'); div.classList.add('discussion-sidebar-item', 'toggl'); link = togglbutton.createTimerLink({ className: 'github', description: description, projectName: projectElem && projectElem.textContent }); div.appendChild(link); elem.prepend(div); });
JavaScript
0
@@ -8,16 +8,47 @@ rict';%0A%0A +// Issue and Pull Request Page%0A togglbut @@ -1199,12 +1199,839 @@ d(div);%0A%7D);%0A +%0A%0A// Project Page%0Atogglbutton.render('.js-project-card-details .js-comment:not(.toggl)', %7B observe: true %7D, function(%0A elem%0A) %7B%0A var link,%0A description,%0A target,%0A wrapper,%0A titleElem = $('.js-issue-title'),%0A numElem = $('.js-issue-number'),%0A projectElem = $('h1.public strong a, h1.private strong a');%0A%0A description = titleElem.textContent;%0A if (numElem !== null) %7B%0A description = numElem.textContent + ' ' + description.trim();%0A %7D%0A%0A link = togglbutton.createTimerLink(%7B%0A className: 'github',%0A description: description,%0A projectName: projectElem && projectElem.textContent%0A %7D);%0A%0A wrapper = createTag('div', 'discussion-sidebar-item js-discussion-sidebar-item');%0A wrapper.appendChild(link);%0A%0A target = $('.discussion-sidebar-item');%0A target.parentNode.insertBefore(wrapper, target);%0A%7D);%0A
c1a59732da5ab542a857646851c165368987a71d
Fix animal link
app/scripts/views/PlacesShow.js
app/scripts/views/PlacesShow.js
import PropTypes from 'prop-types' import React, { Component } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router-dom' import { cachedResource } from '../services/resources' import { fetchResource } from '../actions/resources' import { LocationMap } from '../components' import { numberToSlotSizeStr } from '../utils/slots' import { translate } from '../services/i18n' class PlacesShow extends Component { static propTypes = { fetchResource: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, resourceSlug: PropTypes.string.isRequired, resourceData: PropTypes.object.isRequired, } componentWillMount() { this.props.fetchResource('places', this.props.resourceSlug) } renderPrivacy() { if (this.props.resourceData.isPublic) { return null } return ( <div className="bullet bullet--centered ellipsis"> { translate('components.placeListItem.isPrivatePlace') } </div> ) } renderSlotSize() { return ( <div> <strong>Slot-size (hh:mm)</strong> <p>{ numberToSlotSizeStr(this.props.resourceData.slotSize) }</p> </div> ) } renderAddress() { const { city, cityCode, country, latitude, longitude, mode, street, } = this.props.resourceData if (mode === 'gps') { return ( <div> <strong>Location</strong> <p>@ { latitude }, { longitude }</p> <LocationMap latitude={latitude} longitude={longitude} /> </div> ) } else if (mode === 'address') { return ( <div> <strong>Location</strong> <p> { street }<br /> { `${cityCode} ${city}` }<br /> { country }<br /> </p> </div> ) } return ( <div> <strong>Location</strong> <p>{ translate('components.placeListItem.virtualLocation') }</p> </div> ) } renderDescription() { return ( <div> <strong>Description</strong> <div dangerouslySetInnerHTML={ { __html: this.props.resourceData.descriptionHtml, } } /> </div> ) } renderOwner() { const { name, slug } = this.props.resourceData.animal return ( <p> { translate('views.places.owner') } &nbsp; <Link to={`animals/${slug}`}> { name } </Link> </p> ) } renderContent() { if (this.props.isLoading) { return <p>{ translate('components.common.loading') }</p> } return ( <div> { this.renderOwner() } { this.renderPrivacy() } <hr /> { this.renderAddress() } <hr /> { this.renderSlotSize() } { this.renderDescription() } <hr /> </div> ) } renderTitle() { if (this.props.isLoading || !this.props.resourceData) { return <h1>{ translate('views.places.titlePlaceholder') }</h1> } return <h1>{ this.props.resourceData.title }</h1> } render() { return ( <section> { this.renderTitle() } <Link className="button" to="/places"> { translate('views.places.backToOverview') } </Link> <hr /> { this.renderContent() } </section> ) } constructor(props) { super(props) } } function mapStateToProps(state, ownProps) { const resourceSlug = ownProps.match.params.slug const resource = cachedResource('places', resourceSlug) const { isLoading, object } = resource return { isLoading, resourceData: object, resourceSlug, } } export default connect( mapStateToProps, { fetchResource, } )(PlacesShow)
JavaScript
0.000001
@@ -2413,16 +2413,17 @@ nk to=%7B%60 +/ animals/
cc0d25ef35744d713e1836d5b4acb11c93a2a25c
remove empty space
gulpfile.js
gulpfile.js
/*global require*/ var gulp = require('gulp'); var args = require('yargs').argv; var config = require('./gulp.config')(); var del = require('del'); var $ = require('gulp-load-plugins')({lazy: true}); //var jshint = require('gulp-jshint'); //var jscs = require('gulp-jscs'); //var util = require('gulp-util'); //var gulpprint = require('gulp-print'); //var gulpif = require('gulp-if'); function log(msg) { 'use strict'; var item; if (typeof (msg) === 'object') { for (item in msg) { if (msg.hasOwnProperty(item)) { $.util.log($.util.colors.blue(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } } //gulp vet --verbose gulp.task('vet', function () { 'use strict'; log('Analyzing source with JSHint and JSCS'); return gulp .src(config.alljs) .pipe($.if(args.verbose, $.print())) .pipe($.jscs()) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish', {verbose: true})) .pipe($.jshint.reporter('fail')); }); gulp.task('styles', ['clean-styles'], function () { 'use strict'; log('Compile Less --->CSS'); return gulp .src(config.less) //TODO .pipe($.plumber()) .pipe($.less()) .pipe($.autoprefixer({browsers: ['last 2 version', '> 5%']})) .pipe(gulp.dest(config.temp)); }); function clean(path, done) { 'use strict'; log('Cleaning: ' + $.util.colors.blue(path)); del(path).then(done()); } gulp.task('clean-styles', function (done) { 'use strict'; log('Clean files'); var files = config.temp + '**/*.css'; clean(files, done); }); gulp.task('less-watcher', function () { 'use strict'; gulp.watch([config.less], ['styles']); });
JavaScript
0.999872
@@ -807,29 +807,24 @@ and JSCS');%0A - %0A return g @@ -1171,13 +1171,8 @@ ');%0A - %0A
420f4b2909cf7ccc8d718ecfcc592d5f5052a679
Add service patch method
app/services/contact.service.js
app/services/contact.service.js
angular. module('myApp.core', ['ngResource']). factory('Contact', ['$resource', function($resource) { return $resource('http://localhost/api/contacts/:id', {id: ''}, { query: { method: 'GET', isArray: true }, get: { method: 'GET' }, insert: { method: 'POST' }, update: { method: 'PUT' }, delete: { method: 'DELETE' }, favorite: { url: 'http://localhost/api/contacts/:id/favorite', method: 'PUT' } }); } ]);
JavaScript
0
@@ -494,16 +494,18 @@ +// url: 'h @@ -560,34 +560,36 @@ method: 'P -UT +ATCH '%0A %7D%0A
f8db8beda94027b3862348ec69a8a6ec091184cc
change order of scripts
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), autoprefixer = require('gulp-autoprefixer'), babel = require("gulp-babel"), browserify = require('gulp-browserify'), cssnano = require('gulp-cssnano'), imagemin = require('gulp-imagemin'), jade = require('gulp-jade'), jshint = require('gulp-jshint'), sass = require('gulp-sass'), stylish = require('jshint-stylish'), uglify = require('gulp-uglify'), browserSync = require('browser-sync').create(); const SRC = './src'; const DIST = './dist'; gulp.task('scripts',() => { return gulp.src([SRC+'/js/*.js', '!./node_modules/**', '!./dist/**']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(stylish)) .pipe(babel()) .pipe(browserify({ insertGlobals : true })) .pipe(uglify()) .pipe(gulp.dest(DIST+'/src/js')); }); gulp.task('templates', function() { var LOCALS = {}; gulp.src(['**/*.jade', '!./node_modules/**', '!./dist/**', '!./includes/**']) .pipe(jade({ locals: LOCALS })) .pipe(gulp.dest(DIST)); }); gulp.task('images', () => { return gulp.src([SRC+'/img/**/*', '!./node_modules/**', '!./dist/**']) .pipe(imagemin({ optimizationLevel: 2, progressive: true, svgoPlugins: [ {removeViewBox: false}, {cleanupIDs: false} ]})) .pipe(gulp.dest(DIST+'/src/img')); }); gulp.task('sass', () => { return gulp.src([SRC+'/scss/**/*.scss', '!./node_modules/**', '!./dist/**']) .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['>1%'], cascade: false })) .pipe(cssnano()) .pipe(gulp.dest(DIST+'/src/css')); }); gulp.task('copy',() => { return gulp.src(['CNAME']) .pipe(gulp.dest(DIST)); }); gulp.task('browser-sync', () => { browserSync.init({ server: { baseDir: DIST } }); }); gulp.task('watch',['browser-sync'], () => { gulp.watch('CNAME',['copy']); gulp.watch('**/*.jade', ['templates']); gulp.watch(SRC+'/scss/**/*.scss', ['sass']); gulp.watch(SRC+'/js/**/*.js', ['scripts']); gulp.watch(SRC+'/img/**/*', ['images']); }); gulp.task('default', ['sass','scripts','images','templates']);
JavaScript
0.000002
@@ -1959,16 +1959,26 @@ atch',%5B' +default',' browser- @@ -2227,24 +2227,43 @@ default', %5B' +copy','templates',' sass','scrip @@ -2274,24 +2274,12 @@ 'images' -,'templates' %5D);%0A
b32ff88c8bcea357447297f2bd9d76516b43cdd0
add more ff remove android
gruntTasks/browsers.js
gruntTasks/browsers.js
var Luc = require('../lib/luc'), ie = 'internet explorer', ff = 'firefox', latestFF = 25, s = 'safari', ch = 'chrome', ip= 'IPHONE', an = 'ANDROID', op = 'opera', browsers; module.exports = []; browsers = { XP: [{ name: ie, version: 6 }, { name: ie, version: 7 }, { name: ie, version: 8 },{ name: ff, version: 4 },{ name: ff, version: 3.6 },{ name: ff, version: 3.5 }], WIN8: [{ name: ie, version: 10 }, { name: ch }], 'WIN8.1': [{ name: ie, version: 11 }, { name: ch }], 'OSX 10.8': [{ name: s, version: 6 },{ name: ip, version: 6 },{ name: ip, version: 5 }], 'OSX 10.6': [{ name: s, version: 5 },{ name: ch },{ name: ip, version: 4 }], 'linux': [{ name: an, version: 4 },{ name: ch }], 'Windows 2008': [{ version: 12, name: op }] }; Luc.Object.each(browsers, function(key, values) { Luc.Array.each(values, function(value) { var obj = { platform: key, version: value.version, browserName: value.name }; if(obj.version) { obj.version += ''; } else { delete obj.version; } module.exports.push(obj); }); });
JavaScript
0
@@ -382,16 +382,110 @@ sion: 8%0A + %7D, %7B%0A name: ff,%0A version: 25%0A %7D, %7B%0A name: ff,%0A version: 24%0A %7D,%7B%0A @@ -1097,24 +1097,26 @@ 'linux': %5B +/* %7B%0A na @@ -1140,32 +1140,34 @@ ersion: 4%0A %7D, +*/ %7B%0A name:
0cfe9963e93799214891fc35ea95f8296b8af1d0
Update variables names
gulpfile.js
gulpfile.js
// ************************************* // Gulpfile // ************************************* 'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync'); // ------------------------------------- // Options // ------------------------------------- var options = { html: { files : '*.html' }, sass: { files : 'src/scss/**/*.scss', destination : 'dist/css' } }; // ------------------------------------- // Task: Serve // ------------------------------------- gulp.task('serve', ['styles'], function() { browserSync.init({ server: './' }); gulp.watch(options.sass.files, ['styles']); gulp.watch(options.html.files).on('change', browserSync.reload); }); // ------------------------------------- // Task: Sass // ------------------------------------- gulp.task('styles', function() { return gulp.src(options.sass.files) .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) .pipe(autoprefixer('last 3 versions')) .pipe(gulp.dest(options.sass.destination)) .pipe(browserSync.stream()); }); // ------------------------------------- // Task: Default // ------------------------------------- gulp.task('default', ['serve']);
JavaScript
0.000001
@@ -374,22 +374,20 @@ --%0A%0Avar -option +path s = %7B%0A%0A%09 @@ -400,18 +400,11 @@ %7B%0A%09%09 -files +src : @@ -423,26 +423,23 @@ %0A%0A%09s -as +tyle s: %7B%0A%09%09 -files%09 +src%09 : ' @@ -465,23 +465,16 @@ ,%0A%09%09dest -ination : 'dist @@ -682,34 +682,32 @@ p.watch( -options.sass.files +paths.styles.src , %5B'styl @@ -729,26 +729,22 @@ tch( -option +path s.html. -files +src ).on @@ -932,26 +932,24 @@ src( -options.sass.files +paths.styles.src )%0A%09%09 @@ -1079,32 +1079,25 @@ est( -options.sass.destination +paths.styles.dest ))%0A%09
95befb9d0bfc4906bf3044416ae7b13066b16231
Add images task
gulpfile.js
gulpfile.js
var gulp = require('gulp'), concat = require('gulp-concat'), tsc = require('gulp-typescript'), mocha = require('gulp-mocha'), jsMinify = require('gulp-uglify'), scssLint = require('gulp-scss-lint'), sass = require('gulp-sass'), cssPrefixer = require('gulp-autoprefixer'), cssMinify = require('gulp-cssnano'), del = require('del'), merge = require('merge-stream'), SystemBuilder = require('systemjs-builder'); gulp.task('clean', () => { return del('dist'); }); gulp.task('shims', () => { return gulp.src([ 'node_modules/zone.js/dist/zone.js', 'node_modules/reflect-metadata/Reflect.js' ]) .pipe(concat('shims.js')) .pipe(gulp.dest('dist/js/')); }); gulp.task('system-build', [ 'tsc' ], () => { var builder = new SystemBuilder(); return builder.loadConfig('system.config.js') .then(() => builder.buildStatic('app', 'dist/js/bundle.js')) .then(() => del('build')); }); gulp.task('tsc', () => { var tsProject = tsc.createProject('tsconfig.json'), tsResult = tsProject.src() .pipe(tsc(tsProject)); return tsResult.js .pipe(gulp.dest('build/')); }); gulp.task('html', () => { return gulp.src('src/**/**.html') .pipe(gulp.dest('dist/')); }); gulp.task('lintScss', function() { return gulp.src('src/scss/**/*.scss') .pipe(scssLint({ config: 'lint.yml' })); }); gulp.task('scss', () => { return gulp.src('src/scss/main.scss') .pipe(sass({ precision: 10, includePaths: 'node_modules/node-normalize-scss' })) .pipe(concat('styles.css')) .pipe(cssPrefixer()) .pipe(gulp.dest('dist/css/')); }); gulp.task('test-tsc', () => { var tsProject = tsc.createProject('tsconfig.json'); return tsProject.src() .pipe(tsc(tsProject)) .pipe(gulp.dest('test/js/')); }); gulp.task('test-run', [ 'test-tsc' ], () => { return gulp.src('test/**/*.spec.js') .pipe(mocha()); }); gulp.task('test', [ 'test-run' ], () => { return del('test/js'); }); gulp.task('minify', () => { var js = gulp.src('dist/js/bundle.js') .pipe(jsMinify()) .pipe(gulp.dest('dist/js/')); var css = gulp.src('dist/css/styles.css') .pipe(cssMinify()) .pipe(gulp.dest('dist/css/')); return merge(js, css); }); gulp.task('watch', () => { var watchTs = gulp.watch('src/app/**/**.ts', [ 'system-build' ]), watchScss = gulp.watch('src/scss/**/*.scss', [ 'lintScss', 'styles' ]), watchHtml = gulp.watch('src/**/*.html', [ 'html' ]), watchImages = gulp.watch('src/images/**/*.*', [ 'images' ]), onChanged = function(event) { console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...'); }; watchTs.on('change', onChanged); watchScss.on('change', onChanged); watchHtml.on('change', onChanged); watchImages.on('change', onChanged); }); gulp.task('watchtests', () => { var watchTs = gulp.watch('src/app/**/**.ts', [ 'test-run' ]), watchTests = gulp.watch('test/**/*.spec.js', [ 'test-run' ]), onChanged = function(event) { console.log('File ' + event.path + ' was ' + event.type + '. Running tasks...'); }; watchTs.on('change', onChanged); watchTests.on('change', onChanged); }); gulp.task('default', [ 'shims', 'system-build', 'html', 'lintScss', 'scss' ]);
JavaScript
0.999891
@@ -170,16 +170,57 @@ glify'), +%0A imagemin = require('gulp-imagemin'), %0A%0A sc @@ -1344,32 +1344,174 @@ 'dist/'));%0A%7D);%0A%0A +gulp.task('images', () =%3E %7B%0A return gulp.src('src/images/**/*.*')%0A .pipe(imagemin())%0A .pipe(gulp.dest('dist/images/'));%0A%7D);%0A%0A gulp.task('lintS @@ -3617,16 +3617,20 @@ ault', %5B +%0A 'shims' @@ -3630,16 +3630,20 @@ 'shims', +%0A 'system @@ -3654,16 +3654,20 @@ ld', +%0A 'html', 'li @@ -3662,16 +3662,34 @@ 'html', +%0A 'images',%0A 'lintSc @@ -3696,16 +3696,20 @@ ss', +%0A 'scss' - +%0A %5D);%0A
f594600916ad985231b839d9917d7bace1f5b01e
make complete MVI example
app/templates/module.js
app/templates/module.js
/** @jsx hJSX */ import {Rx} from '@cycle/core'; import {hJSX} from '@cycle/dom'; // eslint-disable-line const DIALOGUE_NAME = `<%= moduleName %>`; let n = 0; function randomNamespace() { return `${n++}`; } function <%= moduleNameCamelized %>({DOM, props$}, optNamespace = randomNamespace()) { const namespace = optNamespace.trim(); return { DOM: props$.map( (props) => ( // eslint-disable-line <div className={`${namespace} ${DIALOGUE_NAME}`}> {props.text} </div> ) ), }; } export default <%= moduleNameCamelized %>;
JavaScript
0.000006
@@ -15,40 +15,8 @@ */%0A%0A -import %7BRx%7D from '@cycle/core';%0A impo @@ -95,34 +95,35 @@ = %60 -%3C%25= moduleName %25%3E%60;%0A%0Alet n +yeoman-test%60;%0A%0Alet idSuffix = 0 @@ -134,31 +134,27 @@ unction -randomNamespace +makeCycleId () %7B%0A r @@ -166,181 +166,500 @@ %60$%7B -n++%7D%60;%0A%7D%0A%0Afunction %3C%25= moduleNameCamelized %25%3E(%7BDOM, props$%7D, optNamespace = randomNamespace()) %7B%0A const namespace = optNamespace.trim();%0A%0A return %7B%0A DOM: props$.map(%0A +DIALOGUE_NAME%7D-$%7BidSuffix++%7D%60;%0A%7D%0A%0Afunction intent(DOM, cycleId) %7B%0A return %7B%0A isClicked$: DOM.select(%60.$%7BcycleId%7D%60).events(%60click%60)%0A .map(() =%3E true)%0A .startWith(false),%0A %7D;%0A%7D%0A%0Afunction model(actions) %7B%0A return actions.isClicked$.map(isClicked =%3E %7B%0A return %7B%0A data: isClicked ?%0A %3Cspan style=%7B%7BwhiteSpace: %60nowrap%60%7D%7D%3EI was clicked%3C/span%3E :%0A %60Click me!%60,%0A %7D;%0A %7D);%0A%7D%0A%0Afunction view(%7Bprops$, state$%7D, cycleId) %7B%0A return props$.combineLatest(%0A state$,%0A @@ -664,16 +664,23 @@ (props +, state ) =%3E ( / @@ -707,18 +707,16 @@ e%0A - %3Cdiv cla @@ -730,17 +730,15 @@ %7B%60$%7B -namespace +cycleId %7D $%7B @@ -763,18 +763,16 @@ - %7Bprops.t @@ -775,19 +775,30 @@ ps.text%7D -%0A + %7Bstate.data%7D%0A %3C/ @@ -810,16 +810,260 @@ +)%0A ) -%0A +;%0A%7D%0A%0Afunction %3C%25= moduleNameCamelized %25%3E(%7BDOM, props$%7D, optCycleId = makeCycleId()) %7B%0A const cycleId = optCycleId.trim();%0A const actions = intent(DOM, cycleId);%0A const state$ = model(actions);%0A%0A return %7B%0A DOM: view(%7Bprops$, state$%7D, cycleId ),%0A
8bf90d44454823305a7c3d8f17a9761d87b357a1
fix FF losing context menu after restart
js/events.js
js/events.js
var activeDoc; brapi.runtime.onInstalled.addListener(function() { if (brapi.contextMenus) brapi.contextMenus.create({ id: "read-selection", title: brapi.i18n.getMessage("context_read_selection"), contexts: ["selection"] }); }) if (brapi.contextMenus) brapi.contextMenus.onClicked.addListener(function(info, tab) { if (info.menuItemId == "read-selection") stop() .then(function() { return playText(info.selectionText, function(err) { if (err) console.error(err); }) }) .catch(console.error) }) if (brapi.commands) brapi.commands.onCommand.addListener(function(command) { if (command == "play") { getPlaybackState() .then(function(state) { if (state == "PLAYING") return pause(); else if (state == "STOPPED" || state == "PAUSED") { return play(function(err) { if (err) console.error(err); }) } }) .catch(console.error) } else if (command == "stop") stop(); else if (command == "forward") forward(); else if (command == "rewind") rewind(); }) if (brapi.ttsEngine) (function() { brapi.ttsEngine.onSpeak.addListener(function(utterance, options, onEvent) { options = Object.assign({}, options, {voice: {voiceName: options.voiceName}}); remoteTtsEngine.speak(utterance, options, onEvent); }); brapi.ttsEngine.onStop.addListener(remoteTtsEngine.stop); brapi.ttsEngine.onPause.addListener(remoteTtsEngine.pause); brapi.ttsEngine.onResume.addListener(remoteTtsEngine.resume); })() function playText(text, onEnd) { if (!activeDoc) { activeDoc = new Doc(new SimpleSource(text.split(/(?:\r?\n){2,}/)), function(err) { handleError(err); closeDoc(); if (typeof onEnd == "function") onEnd(err); }) } return activeDoc.play() .catch(function(err) { handleError(err); closeDoc(); throw err; }) } function play(onEnd) { if (!activeDoc) { activeDoc = new Doc(new TabSource(), function(err) { handleError(err); closeDoc(); if (typeof onEnd == "function") onEnd(err); }) } return activeDoc.play() .catch(function(err) { handleError(err); closeDoc(); throw err; }) } function stop() { if (activeDoc) { activeDoc.stop(); closeDoc(); return Promise.resolve(); } else return Promise.resolve(); } function pause() { if (activeDoc) return activeDoc.pause(); else return Promise.resolve(); } function getPlaybackState() { if (activeDoc) return activeDoc.getState(); else return Promise.resolve("STOPPED"); } function getActiveSpeech() { if (activeDoc) return activeDoc.getActiveSpeech(); else return Promise.resolve(null); } function closeDoc() { if (activeDoc) { activeDoc.close(); activeDoc = null; } } function forward() { if (activeDoc) return activeDoc.forward(); else return Promise.reject(new Error("Can't forward, not active")); } function rewind() { if (activeDoc) return activeDoc.rewind(); else return Promise.reject(new Error("Can't rewind, not active")); } function seek(n) { if (activeDoc) return activeDoc.seek(n); else return Promise.reject(new Error("Can't seek, not active")); } function handleError(err) { if (err) { var code = /^{/.test(err.message) ? JSON.parse(err.message).code : err.message; if (code == "error_payment_required") clearSettings(["voiceName"]); reportError(err); } } function reportError(err) { if (err && err.stack) { var details = err.stack; if (!details.startsWith(err.name)) details = err.name + ": " + err.message + "\n" + details; getState("lastUrl") .then(function(url) {return reportIssue(url, details)}) .catch(console.error) } } function reportIssue(url, comment) { var manifest = brapi.runtime.getManifest(); return getSettings() .then(function(settings) { if (url) settings.url = url; settings.version = manifest.version; settings.userAgent = navigator.userAgent; return ajaxPost(config.serviceUrl + "/read-aloud/report-issue", { url: JSON.stringify(settings), comment: comment }) }) }
JavaScript
0
@@ -48,24 +48,156 @@ istener( -function +installContextMenus);%0Aif (getBrowser() == %22firefox%22) brapi.runtime.onStartup.addListener(installContextMenus);%0A%0Afunction installContextMenus () %7B%0A i @@ -366,25 +366,24 @@ on%22%5D%0A %7D);%0A%7D -) %0A%0Aif (brapi.
9ea6a6af9392d5e6647d301439547406613c09af
test against url regex, not email. fixes #54
app/utils/validators.js
app/utils/validators.js
export default function validateControls (controls) { controls.setEach('widgetIsValid', true); var regex = { email: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, url: /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/ }; var invalidate = function (control, message) { control.set('widgetIsValid', false); control.get('widgetErrors').pushObject(message); }; controls.forEach(function (control) { var value = control.get('value'), options = control.get('meta.data') || {}; control.set('widgetErrors', Ember.A([])); if (!value) { if (control.get('required')) { invalidate(control, 'This field is required'); } return; } switch (control.get('controlType.widget')) { case 'textfield': case 'textarea': if (options.min && value.length < options.min) { invalidate(control, 'This field has a minimum length of ' + options.min + '.'); } if (options.max && value.length > options.max) { invalidate(control, 'This field has a maximum length of ' + options.max + '.'); } break; case 'number': if (!Ember.$.isNumeric(value)) { invalidate(control, 'This field must be a number.'); } if (options.min && parseInt(value, 10) < options.min) { invalidate(control, 'This field has a minimum value of ' + options.min + '.'); } if (options.max && parseInt(value, 10) > options.max) { invalidate(control, 'This field has a maximum value of ' + options.max + '.'); } break; case 'email': if (!regex.email.test(value)) { invalidate(control, 'This field must be an email address.'); } break; case 'url': if (!regex.email.test(value)) { invalidate(control, 'This field must be a URL.'); } break; case 'datetime': if (!moment(value).isValid()) { invalidate(control, 'This field must be a valid date and time.'); } break; } }); }
JavaScript
0.322192
@@ -1876,36 +1876,34 @@ if (!regex. -emai +ur l.test(value)) %7B
db91d738d6d1a03c84eca6b7d5eeaf92380a0d35
Add default task that just runs watch task.
gulpfile.js
gulpfile.js
// http://blog.ponyfoo.com/2014/01/27/my-first-gulp-adventure var gulp = require('gulp'); var gutil = require('gulp-util'); var bump = require('gulp-bump'); var git = require('gulp-git'); var jshint = require('gulp-jshint'); var clean = require('gulp-clean'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var size = require('gulp-size'); var prompt = require('gulp-prompt'); var BUMP_TYPES = ['major', 'minor', 'patch', 'prerelease']; gulp.task('lint', function () { return gulp.src('./src/*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('clean', function () { return gulp.src('./dist', { read: false }) .pipe(clean()); }); gulp.task('build', ['clean'], function () { return gulp.src('./src/jquery.textarea_auto_expand.js') .pipe(gulp.dest('./dist')) .pipe(rename('jquery.textarea_auto_expand.min.js')) .pipe(uglify()) .pipe(size({showFiles: true})) .pipe(gulp.dest('./dist')); }); gulp.task('watch', function() { gulp.watch('src/*.js', ['lint', 'build']); }); gulp.task('validation', function () { if (BUMP_TYPES.indexOf(gutil.env.bump) == -1) throw new Error('\nbump argument is required for gulp release\nSupported values: major, minor, patch, prerelease\n\nExample:\n\tgulp release --bump major'); }); gulp.task('bump', ['validation', 'build'], function () { return gulp.src(['./package.json']) .pipe(bump({type: gutil.env.bump})) .pipe(gulp.dest('./')); }); gulp.task('tag', ['bump'], function () { var pkg = require('./package.json'); var v = 'v' + pkg.version; var message = 'Release ' + v; return gulp.src('./') .pipe(git.commit(message)) .pipe(git.tag(v, message)) .pipe(git.push('origin', 'master', '--tags')) .pipe(gulp.dest('./')); }); gulp.task('npm', ['tag'], function (done) { require('child_process').spawn('npm', ['publish'], { stdio: 'inherit' }) .on('close', done); }); gulp.task('test', ['lint', 'mocha']); gulp.task('ci', ['build']); //gulp.task('release', ['validation', 'npm']); gulp.task('release', ['validation', 'bump']);
JavaScript
0
@@ -2086,12 +2086,46 @@ ', 'bump'%5D); +%0A%0Agulp.task('default', %5B'watch'%5D);
cde378378e8bb10a6c5067dab62bfb0be467b90b
Refactor hasData to use its corresponding getter
dom/attr.js
dom/attr.js
import {splitStringValue} from "./utils"; const SPECIAL_ATTRIBUTE_SETTERS = /^(html|text|css)$/; const customDataStorage = new window.WeakMap(); /** * Sets all attributes on the given element * * @param {Element} element * @param {mojave.types.OptionalKeyMap} attributes */ export function setAttrs (element, attributes) { for (const key in attributes) { if (!attributes.hasOwnProperty(key)) { continue; } const value = attributes[key]; if (SPECIAL_ATTRIBUTE_SETTERS.test(key)) { return; } if (value === null || value === false) { element.removeAttribute(key); } else { element.setAttribute( key, (value === true) ? key : ("" + value) ); } } } /** * Returns the attribute value for the given html node * * @param {Element} element * @param {string} attribute * @returns {string | null} */ export function getAttr (element, attribute) { return element.getAttribute(attribute); } /** * Updates the classes on the given element * * @private * @param {Element | Element[]} element * @param {string | string[]} classes * @param {string} method */ function updateClasses (element, classes, method) { /** @type {Element[]} list */ const list = Array.isArray(element) ? element : [element]; const classList = splitStringValue(classes); for (let i = 0; i < list.length; i++) { for (let j = 0; j < classList.length; j++) { list[i].classList[method](classList[j]); } } } /** * Adds all given classes to the element * * @param {Element | Element[]} element * @param {string | string[]} classes */ export function addClass (element, classes) { updateClasses(element, classes, "add"); } /** * Remove all given classes from the element * * @param {Element | Element[]} element * @param {string | string[]} classes */ export function removeClass (element, classes) { updateClasses(element, classes, "remove"); } /** * Normalizes the key for *Data functions * * @private * @param {string} key * @returns {string} */ function normalizeDataKey (key) { return key.replace( /-([a-z])/g, (matches) => matches[1].toUpperCase() ); } /** * Sets the data on the given element * * @param {Element} element * @param {string} key * @param {*} value */ export function setData (element, key, value) { key = normalizeDataKey(key); let storage = customDataStorage.get(element); if (storage === undefined) { storage = {}; customDataStorage.set(element, storage); } storage[key] = value; } /** * Loads the data from the element * * @param {HTMLElement} element * @param {string} key * @returns {*} */ export function getData (element, key) { const normalizedKey = normalizeDataKey(key); const storage = customDataStorage.get(element); if (typeof storage === "object" && storage[normalizedKey] !== undefined) { return storage[normalizedKey]; } // @legacy IE <= 10 doesn't support dataset if (element.dataset === undefined) { return getAttr(element, `data-${key}`); } const value = element.dataset[normalizedKey]; return value === undefined ? null : value; } /** * Determines whether the given attribute is set on the element * * @param {Element} element * @param {string} key * @returns {boolean} */ export function hasData (element, key) { const normalizedKey = normalizeDataKey(key); const storage = customDataStorage.get(element); if (typeof storage === "object") { return storage[normalizedKey] !== undefined; } // @legacy IE <= 10 doesn't support dataset if (element.dataset === undefined) { return hasAttr(element, `data-${key}`); } return undefined !== element.dataset[normalizedKey]; } /** * Returns all data in custom storage * * @param {HTMLElement} element * @returns {Object} */ export function getAllCustomData (element) { return customDataStorage.get(element) || {}; }
JavaScript
0.000001
@@ -3446,16 +3446,21 @@ e given +data attribut @@ -3489,32 +3489,36 @@ t%0A *%0A * @param %7B +HTML Element%7D element @@ -3622,96 +3622,31 @@ nst -normalizedKey = normalizeDataKey(key);%0A const storage = customDataStorage.get +value = getData (element );%0A%0A @@ -3637,32 +3637,37 @@ Data(element +, key );%0A%0A if (typeof s @@ -3658,310 +3658,150 @@ -if (typeof storage === %22object%22)%0A %7B%0A return storage%5BnormalizedKey%5D !== undefined;%0A %7D%0A%0A // @legacy IE %3C= 10 doesn't support dataset%0A if (element.dataset === undefined)%0A %7B%0A return hasAttr(element, %60data-$%7Bkey%7D%60);%0A %7D%0A%0A return undefined !== element.dataset%5BnormalizedKey%5D +// Empty data attributes' value is an empty string%0A if (%22%22 === value)%0A %7B%0A return true;%0A %7D%0A%0A return null !== (value %7C%7C null) ;%0A%7D%0A
e40a2205d406d22e95ecb7caf68e7e7d93872ea9
Remove errornous svn:executable property from source code file.
javascript/i18n/phonenumbers/regioncodefortesting.js
javascript/i18n/phonenumbers/regioncodefortesting.js
/** * @license * Copyright (C) 2011 The Libphonenumber Authors * * 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 String constants of region codes for testing. * @author Nikolaos Trogkanis */ goog.provide('i18n.phonenumbers.RegionCode'); /** * Enum containing string constants of region codes for easier testing. * * @enum {string} */ i18n.phonenumbers.RegionCode = { // Region code for global networks (e.g. +800 numbers). UN001: '001', AD: 'AD', AO: 'AO', AQ: 'AQ', AR: 'AR', AU: 'AU', BR: 'BR', BS: 'BS', BY: 'BY', CA: 'CA', CN: 'CN', CS: 'CS', DE: 'DE', GB: 'GB', IT: 'IT', JP: 'JP', KR: 'KR', MX: 'MX', NZ: 'NZ', PL: 'PL', RE: 'RE', SG: 'SG', US: 'US', YT: 'YT', ZW: 'ZW', // Official code for the unknown region. ZZ: 'ZZ' };
JavaScript
0
b263be2c7b26280d95caa6d9c06d00a9546df418
fix test
tests/services/dataSpec.js
tests/services/dataSpec.js
var should = require('should'); var sinon = require('sinon'); var assert = require('assert'); var setup = require('./../mocks/setup'); setup.makeSuite('add data service', function() { var dataService = require('./../../src/services/data'); var projectService = require('./../../src/services/project'); var elasticData = require('./../../src/elastic/data'); beforeEach(function(done) { projectService.ensureCollection({ projectName: 'test', collectionName: 'city' }, function(err, res) { assert.equal(err, null); done(); }); }); it('should add documents (batch) successfully', function(done) { var doc = { rating: 6, name: 'Berlin' }; var spy = sinon.spy(elasticData, 'addDocuments'); dataService.addDocumentsAsync({ projectName: 'test', collectionName: 'city', body: [doc, doc, doc, doc], }) .then(function(res) { //assert.equal(err, null); assert.equal(res.items.length, 4); assert(spy.calledOnce); assert(spy.calledWithMatch({index: 'test'})); assert(spy.calledWithMatch({type: 'city'})); done(); }); }); it('should add all documents with configuration successfully', function(done) { var doc = { rating: 6, name: 'Berlin' }; var spy = sinon.spy(dataService, 'addDocuments'); dataService.addAllDocuments({ projectName: 'test', collectionName: 'city', body: [doc, doc], }, function(err, res) { assert.equal(err, null); assert(spy.calledOnce); assert(spy.firstCall.calledWithMatch({projectName: 'test'})); assert(spy.firstCall.calledWithMatch({collectionName: 'city'})); dataService.addDocuments.restore(); done(); }); }); it('should add more documents successfully', function(done) { var doc = { rating: 6, name: 'France' }; var data = { projectName: 'test', collectionName: 'city', batchSize: 4, body: [doc, doc, doc, doc, doc, doc, doc, doc, doc, doc], } var spy = sinon.spy(dataService, 'addDocuments'); dataService.addAllDocuments(data, function(err, res) { assert.equal(err, null); assert.equal(spy.callCount, 3); assert(spy.firstCall.calledWithMatch({projectName: 'test'})); assert(spy.firstCall.calledWithMatch({collectionName: 'city'})); assert(spy.firstCall.calledWith(sinon.match({collectionName: 'city'}))); dataService.addDocuments.restore(); done(); }) }); it('should add document successfully', function(done) { var spy = sinon.spy(elasticData, 'addDocument'); dataService.addDocumentAsync({ projectName: 'test', collectionName: 'city', body: {rating: 5, name: 'Berlin', id: 5}, }).then(function(res) { //assert.equal(err, null); assert.equal(spy.callCount, 1); assert(spy.firstCall.calledWithMatch({index: 'test'})); assert(spy.firstCall.calledWithMatch({type: 'city'})); assert(spy.firstCall.calledWithMatch({id: 5})); assert(spy.firstCall.calledWith(sinon.match({type: 'city'}))); elasticData.addDocument.restore(); done(); }); }); it('should get document successfully', function(done) { var spy = sinon.spy(elasticData, 'getDocument'); dataService.getDocument({ projectName: 'test', collectionName: 'city', id: 5 }, function(err, res) { assert.equal(err, null); assert.equal(spy.callCount, 1); assert(spy.firstCall.calledWithMatch({index: 'test'})); assert(spy.firstCall.calledWithMatch({type: 'city'})); assert(spy.firstCall.calledWithMatch({id: 5})); elasticData.getDocument.restore(); done(); }); }); });
JavaScript
0.000002
@@ -945,32 +945,34 @@ r, null);%0A +// assert.equal(res @@ -990,16 +990,55 @@ th, 4);%0A + assert.equal(res.ids.length, 4);%0A as
987db1937aed730ca9011d294bcdc1599b8fb893
Update app.js
demo/app.js
demo/app.js
var https = require('https'); var express = require('express'); var app = express(); var expressWs = require('express-ws')(app); var pty = require('node-pty'); var cors = require('cors'); app.use(cors()); app.options('*', cors()); var cwds = {}; var cmd = require('node-cmd'); /* ########################################################## ###################FOR TERMINAL DEMO ONLY ################ ########################################################## */ app.use('/build', express.static(__dirname + '/../build')); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); app.get('/style.css', function(req, res){ res.sendFile(__dirname + '/style.css'); }); app.get('/main.js', function(req, res){ res.sendFile(__dirname + '/main.js'); }); /* ########################################################## ###################FOR TERMINAL DEMO ONLY ################ ########################################################## */ /* ##########get user info and .pem file path############### */ function getTerm(token) { return new Promise((resolve, reject) => { try { return https.get({ host: 'api.commit.live', path: '/v1/users/' + token, headers: {'access-token': token} }, function(response) { // Continuously update stream with data var body = ''; response.on('data', function(d) { body += d; }); response.on('end', function() { //console.log(body); try { return resolve(JSON.parse(body)); } catch (err) { console.log('Parse failed'); console.log(err); } }); }); } catch (err) { console.log('Api failed'); console.log(err); reject; } }) } /* ##########xterm over WebSocket############### ##########Do not edit code below if you are not sure & know what you are doing ############### */ app.ws('/terminals/:pid', function (ws, req) { try { getTerm(req.params.pid) .then(user_info => { console.log(user_info); var pcwd = process.env.PWD; if(cwds[req.params.pid]){ pcwd = cwds[req.params.pid]; } // var term = pty.spawn('ssh', ["-i", user_info.pem_file, user_info.user_host], { var term = pty.spawn('sudo', ['su','-',user_info.data.username], { name: 'xterm-color', cwd: pcwd, env: process.env }); term.on('data', function(data) { ws.send(data); }); ws.on('message', function(msg) { term.write(msg); }); ws.on('close', function () { var command = "lsof -a -p "+term.pid+" -d cwd -n | tail -1 | awk '{print $NF}'" cmd.get( command, function(err, data, stderr){ cwds[req.params.pid] = data.trim(); process.kill(term.pid); } ); }); }) .catch(err => { // console.log(err); }) } catch (err) { console.log('Terminal webSocket failed'); console.log(err); } }); /* ##########listen server at port 30000################ */ console.log('App listening to *:3000'); app.listen(3000);
JavaScript
0.000002
@@ -2235,16 +2235,77 @@ nv.PWD;%0A + console.log('i am here');%0A console.log(pcwd);%0A @@ -2330,16 +2330,16 @@ .pid%5D)%7B%0A - @@ -2673,24 +2673,42 @@ ion(data) %7B%0A + try %7B%0A ws @@ -2720,16 +2720,370 @@ (data);%0A + var command = %22lsof -a -p %22+term.pid+%22 -d cwd -n %7C tail -1 %7C awk '%7Bprint $NF%7D'%22%0A cmd.get(%0A command,%0A function(err, data, stderr)%7B%0A cwds%5Breq.params.pid%5D = data.trim();%0A process.kill(term.pid);%0A %7D%0A );%0A %7D catch (err) %7B%0A %7D%0A @@ -3160,32 +3160,32 @@ );%0A %7D);%0A%0A - ws.on('c @@ -3201,24 +3201,71 @@ nction () %7B%0A + console.log('socket disconnecting');%0A va
493b9221c8c0f94c19db1b972cf7d236c5c0401a
Output of binary parser is an object, not a string.
src/AuroraCmdTransformBinary.js
src/AuroraCmdTransformBinary.js
import Stream from "stream"; import _ from 'lodash'; import {Parser} from "binary-parser"; import AuroraConstants from './AuroraConstants'; export default class AuroraCmdTransformBinary extends Stream.Transform { static defaultOptions = { dataType: AuroraConstants.DataTypes.UINT8, parseType: undefined, parseTypeLength: undefined }; constructor(options) { super(); this.options = _.defaultsDeep(options, AuroraCmdTransformBinary.defaultOptions); if (typeof this.options.parseType == 'undefined') { this.options.parseType = this._getParseTypeFromDataType(this.options.dataType); } if (typeof this.options.parseTypeLength == 'undefined') { this.options.parseTypeLength = this._getParseTypeLengthFromDataType(this.options.dataType); } this.parser = new Parser(); this.leftoverBuffer = null; this.hasData = false; this.parser.array('values', { type: this.options.parseType, readUntil: 'eof', formatter: function(values) { console.log('parse', values).join(','); return values.join(','); } }); } _transform(respChunk, encoding, done) { console.log('chunk', respChunk); if (Buffer.isBuffer(this.leftoverBuffer)){ respChunk = Buffer.concat([this.leftoverBuffer, respChunk], this.leftoverBuffer.length + respChunk.length); this.leftoverBuffer = null; } if (respChunk.length < this.options.parseTypeLength) { this.leftoverBuffer = respChunk; done(); return; } this.hasData = true; const numBytesLeftover = respChunk.length % this.options.parseTypeLength; console.log('bytes leftover', numBytesLeftover); if (numBytesLeftover) { this.push((this.hasData ? ',' : '') + this.parser.parse(respChunk.slice(0, -numBytesLeftover))); this.leftoverBuffer = respChunk.slice(-numBytesLeftover); } else { this.push((this.hasData ? ',' : '') + this.parser.parse(respChunk)); } done(); } _flush(done) { if (this.leftoverBuffer) { console.log("Unparsed binary buffer: ", this.leftoverBuffer); } this.hasData = false; done(); } _getParseTypeFromDataType(dataType) { switch(dataType){ case AuroraConstants.DataTypes.INT8 : return 'int8'; case AuroraConstants.DataTypes.UINT16 : return 'uint16le'; case AuroraConstants.DataTypes.INT16 : return 'int16le'; case AuroraConstants.DataTypes.FLOAT : return 'floatle'; case AuroraConstants.DataTypes.UINT32 : case AuroraConstants.DataTypes.STR : case AuroraConstants.DataTypes.PTR : return 'uint32le'; case AuroraConstants.DataTypes.INT32 : return 'int32le'; case AuroraConstants.DataTypes.UINT8 : case AuroraConstants.DataTypes.CHAR : default: return 'uint8'; } } _getParseTypeLengthFromDataType(dataType) { switch(dataType){ case AuroraConstants.DataTypes.UINT16 : case AuroraConstants.DataTypes.INT16 : return 2; case AuroraConstants.DataTypes.UINT32 : case AuroraConstants.DataTypes.FLOAT : case AuroraConstants.DataTypes.STR : case AuroraConstants.DataTypes.PTR : case AuroraConstants.DataTypes.INT32 : return 4; case AuroraConstants.DataTypes.UINT8 : case AuroraConstants.DataTypes.CHAR : case AuroraConstants.DataTypes.INT8 : default: return 1; } } }
JavaScript
0.999999
@@ -1713,28 +1713,8 @@ -this.hasData = true; %0A%0A @@ -1848,24 +1848,50 @@ Leftover);%0A%0A + let parsedChunk;%0A%0A if ( @@ -1927,45 +1927,21 @@ -this.push((this.hasData ? ',' : '') + +parsedChunk = thi @@ -1993,18 +1993,18 @@ ftover)) -) ; +%0A %0A @@ -2062,24 +2062,25 @@ sLeftover);%0A +%0A %7D%0A @@ -2068,32 +2068,40 @@ ver);%0A%0A %7D + else %7B%0A %0A else %7B%0A @@ -2097,19 +2097,67 @@ -else %7B%0A + parsedChunk = this.parser.parse(respChunk);%0A %7D%0A%0A @@ -2202,47 +2202,38 @@ ) + -this.parser.parse(respChunk) +parsedChunk.values );%0A +%0A %7D%0A%0A @@ -2220,33 +2220,52 @@ lues);%0A%0A -%7D +this.hasData = true; %0A%0A done()
2581ecd9086795c5f5348e3fc0cb1f6981028eab
corrected some date code
app/view1/view1_test.js
app/view1/view1_test.js
'use strict'; describe('myApp.view1 module', function() { beforeEach(module('myApp.view1')); describe('view1 controller', function(){ it('should ....', inject(function($controller) { //spec body var $scope = {}; var view1Ctrl = $controller('View1Ctrl', { $scope: $scope }); expect(view1Ctrl).toBeDefined(); })); }); describe('view1 timeSlotService', function(){ var timeSlotService, mockCurrentTimeService beforeEach(function() { mockCurrentTimeService = new Date(2014, 8, 4, 6, 0, 0); module(function ($provide) { $provide.value('currentTimeService', mockCurrentTimeService); }); // inject(function($injector) { // timeSlotService = $injector.get('timeSlotService'); // }); }); it('should populate 34 half hour slots for a full day', inject(function(timeSlotService) { //spec body expect(timeSlotService.slots.length).toEqual(12); })); }); });
JavaScript
0.998203
@@ -527,18 +527,19 @@ (201 -4, 8, 4, 6 +5, 1, 16, 0 , 0, @@ -956,10 +956,10 @@ ual( -12 +34 );%0A
3625ea1123b08ac6beb1dee9921a3b2eeab11729
Fix autosizer on infinite adding
js/global.js
js/global.js
$(document).ready(function() { // Autoresize textareas autosize($('textarea')) // Confirm deleting $('button.delete').on('click', function() { var result = confirm('Do you really want to delete this item?') if (!result) return false }) // Prepare studying if ($('#study').length != 0) { var currentIndex = 0 var correctOnce = Object.keys(new Int8Array($('#study li').length)).map(function() { return false }) var showCard = function(index) { $('#study').removeClass('reveal').removeClass('revealnotes') $('#study li').css('display', 'none').eq(index).css('display', 'block') currentIndex = index var percent = Math.round(correctOnce.filter(function(x) { return x }).length * 100 / correctOnce.length) $('#progress span').css('width', percent + '%') } var nextCard = function() { if (correctOnce.every(function(x) { return x })) { $('form').get(0).submit() return } var i = (currentIndex + 1) % correctOnce.length while (correctOnce[i]) { if (i + 1 == correctOnce.length) i = -1 i++ } showCard(i) } $('#study input[type="checkbox"]').attr('checked', '') $('#study label, button[type="submit"]').css('display', 'none') $('header').after($('<div/>', { id: 'progress' }).append($('<span/>'))) $('#study + p').append($('<button/>', { text: 'Reveal', class: 'reveal', type: 'button' }).on('click', function() { $('#study').addClass('reveal') return false })).append($('<button/>', { text: 'Show Notes', class: 'shownotes', type: 'button' }).on('click', function() { $('#study').addClass('revealnotes') return false })).append($('<button/>', { text: 'Show Again', class: 'showagain', type: 'button' }).on('click', function() { $('#study input[type="checkbox"]').eq(currentIndex).attr('checked', false) nextCard() return false })).append($('<button/>', { text: 'Next Card', class: 'nextcard', type: 'button' }).on('click', function() { correctOnce[currentIndex] = true nextCard() return false })) showCard(0) } // Infinite adding if ($('#addlist').length != 0) { var $template = $('#addlist li:last-child').css('display', 'none') $('#addlist + p').prepend($('<button/>', { text: 'Add Items', type: 'button' }).on('click', function() { for (var i = 0; i < 5; i++) { $template.before($template.clone().css('display', 'block')) } return false })) } // Add edit links to vocabulary page if ($('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').length != 0) { $('section.back').parents('form').find('button[type="submit"]') .css('display', 'none') $('section.back, section.notes').each(function() { if ($(this).find('.tasks').length != 0) return $(this).prepend($('<p/>', { class: 'tasks' }).append($('<a/>', { href: '#', text: 'Edit' }).on('click', function() { $(this).parents('section').css('display', 'none') .next('textarea').css('display', 'block').get(0).focus() $(this).parents('form').find('button[type="submit"]') .css('display', 'inline-block') return false }))) }) $('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').css('display', 'none') } })
JavaScript
0.000002
@@ -3016,25 +3016,55 @@ -$template.before( +var $clone = $template.clone()%0A $tem @@ -3069,23 +3069,29 @@ emplate. +before($ clone -() .css('di @@ -3108,16 +3108,66 @@ lock'))%0A + autosize($clone.find('textarea'))%0A
f8d7ca0799d63e0a51036f18049ab736bf36bf5e
check if blob actually exists in store, and set correct status code
blobs-http.js
blobs-http.js
var pull = require('pull-stream') var toPull = require('stream-to-pull-stream') var qs = require('querystring') var URL = require('url') //host blobs module.exports = function (blobs, url) { return function (req, res, next) { next = next || function (err) { res.writeHead(404, {'Content-Type': 'application/json'}) res.end(JSON.stringify({error: true, status: 404})) } if(req.url === url+'/add') pull( toPull(req), blobs.add(function (err, hash) { res.end(hash) }) ) else if(req.url.indexOf(url+'/get/') == 0) { var u = URL.parse('http://makeurlparseright.com'+req.url) var hash = u.pathname.substring((url+'/get/').length) var q = qs.parse(u.query) //Response.AddHeader("content-disposition", "inline; filename=File.doc") if(q.filename) res.setHeader('Content-Discosition', 'inline; filename='+q.filename) pull( blobs.get(hash), //since this is an http stream, handle error the http way. pull.through(null, function (err) { if(err) next(err) }), toPull(res)) } else next() } }
JavaScript
0.000001
@@ -752,87 +752,9 @@ ry)%0A - //Response.AddHeader(%22content-disposition%22, %22inline; filename=File.doc%22) %0A + @@ -848,16 +848,123 @@ ename)%0A%0A + blobs.has(hash, function (err, has) %7B%0A if(err) return next(err)%0A%0A res.writeHead(200)%0A pu @@ -959,32 +959,34 @@ )%0A pull(%0A + blobs.ge @@ -1002,16 +1002,18 @@ + + //since @@ -1067,24 +1067,26 @@ ay.%0A + pull.through @@ -1105,24 +1105,64 @@ ion (err) %7B%0A + if(err) throw err //DEBUG%0A if @@ -1189,12 +1189,16 @@ + + %7D),%0A + @@ -1212,16 +1212,34 @@ ull(res) +%0A )%0A %7D )%0A %7D%0A @@ -1262,12 +1262,7 @@ %7D%0A + %7D%0A%0A -%0A%0A%0A%0A%0A
63efaae53b7ec2cd6aa53627a45d534dfec64a4d
clear fields and reset dialog when closing
blockchain.js
blockchain.js
var usersBlocked = 0, usersFound = 0, usersAlreadyBlocked = 0, usersSkipped = 0, totalCount = 0, errors = 0; var batchBlockCount = 5; var scrollerInterval = false, finderInterval = false, blockerInterval = false; var userQueue = new Queue(); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.blockChainStart) { if ($(".GridTimeline .ProfileCard").length > 0) { sendResponse({ack: true}); startBlockChain(); } else { sendResponse({error: true, error_description: 'Navigate to a twitter following or followers page.'}); } } }); $("#blockAllUsers").click(startBlockChain); function startBlockChain() { var result = confirm("Are you sure you want to block all users on this page that you aren't following?"); if (!result) return; showDialog(); scrollerInterval = setInterval(function() { window.scroll(0, $(document).height()); if ($(".GridTimeline-end.has-more-items").length==0) { clearInterval(scrollerInterval); scrollerInterval = false; doBlocking(); totalCount = $(".ProfileCard").length; $("#blockchain-dialog .totalCount").text(totalCount); } },500); finderInterval = setInterval(function() { doBlocking(); if (usersFound==totalCount && totalCount > 0) { clearInterval(finderInterval); finderInterval = false; } },1000); blockerInterval = setInterval(function() { for (var i=0;i<batchBlockCount;i++) { var user = userQueue.dequeue(); if (typeof user !== "undefined") { $.ajax({ url: "https://twitter.com/i/user/block", method: "POST", dataType: 'json', data: { authenticity_token: $("#signout-form input.authenticity_token").val(), block_user: true, impression_id: "", report_type: "", screen_name: user.name, user_id: user.id } }).done(function(response) { //console.log(response); }).fail(function(xhr, text, err) { errors++; $("#blockchain-dialog .errorCount").text(errors); //console.log(xhr); }).always(function() { usersBlocked++; $("#blockchain-dialog .usersBlocked").text(usersBlocked); if ((usersBlocked == totalCount || usersBlocked == usersFound) && totalCount > 0) { clearInterval(blockerInterval); blockerInterval = false; } }); } } },40); } function doBlocking() { $(".ProfileCard:not(.blockchain-added)").each(function(i,e) { $(e).addClass("blockchain-added"); if ($(e).find('.user-actions.following').length > 0) { usersSkipped++; $("#blockchain-dialog .usersSkipped").text(usersSkipped); return true; } if ($(e).find('.user-actions.blocked').length > 0) { usersAlreadyBlocked++; $("#blockchain-dialog .usersAlreadyBlocked").text(usersAlreadyBlocked); return true; } usersFound++; $("#blockchain-dialog .usersFound").text(usersFound); userQueue.enqueue({ name: $(e).data('screen-name'), id: $(e).data('user-id') }); }); } function showDialog() { $("body").append( '<div id="blockchain-dialog" class="modal-container block-or-report-dialog block-selected report-user">'+ '<div class="close-modal-background-target"></div>'+ '<div class="modal modal-medium draggable" id="block-or-report-dialog-dialog" role="dialog" aria-labelledby="block-or-report-dialog-header" style="top: 240px; left: 470px;"><div class="js-first-tabstop" tabindex="0"></div>'+ '<div class="modal-content" role="document">'+ '<div class="modal-header">'+ '<h3 class="modal-title report-title" id="blockchain-dialog-header">Twitter Block Chain</h3>'+ '</div>'+ '<div class="report-form">'+ '<p>Found: <span class="usersFound"></span></p>'+ '<p>Skipped: <span class="usersSkipped"></span></p>'+ '<p>Already Blocked: <span class="usersAlreadyBlocked"></span></p>'+ '<p>Blocked: <span class="usersBlocked"></span></p>'+ '<p>Total: <span class="totalCount"></span></p>'+ '<p>Errors: <span class="errorCount"></span></p>'+ '</div>'+ '<div id="report-control" class="modal-body submit-section">'+ '<div class="clearfix">'+ '<button id="done" class="btn primary-btn report-tweet-next-button" type="button">Done</button>'+ '</div>'+ '</div>'+ '</div>'+ '<button type="button" class="modal-btn modal-close js-close" aria-controls="block-or-report-dialog-dialog">'+ '<span class="Icon Icon--close Icon--medium">'+ '<span class="visuallyhidden">Close</span>'+ '</span>'+ '</button>'+ '<div class="js-last-tabstop" tabindex="0"></div>'+ '</div>' ); $("#blockchain-dialog").show().find("button").click(function() { clearInterval(blockerInterval); clearInterval(scrollerInterval); clearInterval(finderInterval); $("#blockchain-dialog").hide(); }); }
JavaScript
0
@@ -5504,32 +5504,579 @@ inderInterval);%0A + usersBlocked = 0;%0A usersFound = 0;%0A usersAlreadyBlocked = 0;%0A usersSkipped = 0;%0A totalCount = 0;%0A errors = 0;%0A $(%22#blockchain-dialog .usersFound%22).text(usersFound);%0A $(%22#blockchain-dialog .usersSkipped%22).text(usersSkipped);%0A $(%22#blockchain-dialog .usersAlreadyBlocked%22).text(usersAlreadyBlocked);%0A $(%22#blockchain-dialog .usersBlocked%22).text(usersBlocked);%0A $(%22#blockchain-dialog .totalCount%22).text(totalCount);%0A $(%22#blockchain-dialog .errorCount%22).text(errors);%0A $(%22#bloc
2144ce9ccf492f2f6a3961088636afcef58a0972
increase likelyhood that a GOTerm is cached
app/assets/javascripts/components/goterms.js
app/assets/javascripts/components/goterms.js
import {postJSON} from "../utils.js"; /** * @typedef {Object} FACounts * @property {number} value count * @property {string} name The name of the GO/EC number * @property {string} code The code of the GO/EC number */ const BATCH_SIZE = 1000; const NAMESPACES = ["biological process", "cellular component", "molecular function"]; /** * Class that helps organizing GO terms */ export default class GOTerms { /** * Static cache of GO term information * @access private */ static goData = new Map(); /** * Creates a new GOTerms * TODO * @param {[FACounts]} [go=[]] list of GO terms with their counts * @param {bool} [ensureData=true] fetch names for this resultset in the background,ss * if false, you must call `ensureData()` on this object. * @param {bool} [clone=false] *for internal use* */ constructor({numAnnotatedProteins = null, data = []}, ensureData = true, clone = false) { if (clone) return; this.numTotalSet = numAnnotatedProteins; this.go = new Map(); Object.values(data).forEach(v => v.forEach(goTerm => this.go.set(goTerm.code, goTerm))); GOTerms.addData(Array.from(this.go.values())); // Sort values to store and have every namespace this.data = {}; for (const namespace of NAMESPACES) { if (namespace in data) { this.data[namespace] = Array.from(data[namespace]).sort((a, b) => (b.value - a.value)); } else { this.data[namespace] = []; } } if (ensureData) { this.ensureData(); } } /** * Make a new GOTerms form a clone * @param {GOTerms} other * @param {GOTerms} [base=null] optional GoTerms instance to reuse * @return {GOTerms} filled GOTerms instance */ static clone(other, base = null) { let go = base; if (base === null) { go = new GOTerms({}, true, true); } go.numTotalSet = other.numTotalSet; go.data = other.data; go.go = other.go; return go; } /** /** * Fetch the names of the GO terms and await them */ async ensureData() { await GOTerms.addMissingNames(Array.from(this.go.keys())); } /** * @return {int} number of annotated peptides */ getTotalSetSize() { return this.numTotalSet; } /** * Returns the originally supplied set of GO Terms * sorted by value for a specific namespace * @param {String} namespace The namespace (one of GOTerms.NAMESPACES) * @return {[FACounts]} Sorted GO Terms */ sortedTerms(namespace) { return this.data[namespace]; } /** * Get the count of the GO term in the data set * @param {string} goTerm the GO term (form "GO:0005886") * @return {number} count of the GO term */ getValueOf(goTerm) { if (this.go.has(goTerm)) { return this.go.get(goTerm).value; } return 0; } /** * Get the count of the GO term in the data set as fraction of the total size * of the set * @param {string} goTerm the GO term (form "GO:0005886") * @return {number} fraction of the GO term */ getFractionOf(goTerm) { return this.getValueOf(goTerm) / this.numTotalSet; } /** * Gets the name of associated with an GO Term * * @param {string} goTerm The code of the GO Term (like "GO:0006423") * @return {string} The name of the GO Term */ static nameOf(goTerm) { if (this.goData.has(goTerm)) { return this.goData.get(goTerm).name; } return "Unknown"; } /** * Give the namespace of a GO term * * @param {string} goTerm The code of the GO Term * @return {[string]} Ancestors of the GO Term (from specific to generic) */ static namespaceOf(goTerm) { if (this.goData.has(goTerm)) { return this.goData.get(goTerm).namespace; } return "Unknown"; } /** * Add GO terms to the global map * @param {[FACounts]} newTerms list of new GO Terms */ static addData(newTerms) { newTerms.forEach(go => { if (!this.goData.has(go.code) && go.namespace && go.name) { this.goData.set(go.code, go); } }); } /** * Fetch the names and data of the GO terms that are not yet in the static map of * names * @param {[string]} codes array of GO terms that should be in the cache */ static async addMissingNames(codes) { const todo = codes.filter(c => !this.goData.has(c)); if (todo.length > 0) { for (let i = 0; i < todo.length; i += BATCH_SIZE) { const res = await postJSON("/private_api/goterms", JSON.stringify({ goterms: todo.slice(i, i + BATCH_SIZE), })); GOTerms.addData(res); } } } /** * Cone the GO Term information into the current GOTerm static value * * Needed to work properly with WebWorkers that do not share these statics * * @param {iteratable<FAInfo>} data inforamtion about GO Terms */ static ingestData(data) { GOTerms.goData = data; } /** * @param {[string]} terms the terms to show in the chart (at least one) * @return {string} The QuickGo chart URL of the given GO terms */ static quickGOChartURL(terms) { return `https://www.ebi.ac.uk/QuickGO/services/ontology/go/terms/${terms.join(",")}/chart`; } /** * Get a list of the 3 root namespaces of the Gene Ontology */ static get NAMESPACES() { return NAMESPACES; } }
JavaScript
0.000002
@@ -1106,20 +1106,21 @@ Object. -valu +entri es(data) @@ -1128,17 +1128,25 @@ forEach( -v +(%5Bns, v%5D) =%3E v.fo @@ -1160,16 +1160,30 @@ oTerm =%3E + %7B%0A this.go @@ -1200,23 +1200,66 @@ m.code, -goTerm) +Object.assign(%7Bnamespace: ns%7D, goTerm));%0A %7D ));%0A @@ -4315,32 +4315,55 @@ of new GO Terms%0A + * @access private%0A */%0A stat
d4edd3e77adf380d67f7d89d267dff75872ca823
Add missing dispatch calls
app/actions/QuoteActions.js
app/actions/QuoteActions.js
import { Quote } from './ActionTypes'; import { callAPI } from '../utils/http'; import { pushState } from 'redux-react-router'; import { startSubmit, stopSubmit } from 'redux-form'; export function fetchAllApproved() { return callAPI({ types: [ Quote.FETCH_ALL_APPROVED_BEGIN, Quote.FETCH_ALL_APPROVED_SUCCESS, Quote.FETCH_ALL_APPROVED_FAILURE ], endpoint: '/quotes/' }); } export function fetchAllUnapproved() { return callAPI({ types: [ Quote.FETCH_ALL_UNAPPROVED_BEGIN, Quote.FETCH_ALL_UNAPPROVED_SUCCESS, Quote.FETCH_ALL_UNAPPROVED_FAILURE ], endpoint: '/quotes/?approved=false' }); } export function fetchQuote(quoteId) { return callAPI({ types: [ Quote.FETCH_BEGIN, Quote.FETCH_SUCCESS, Quote.FETCH_FAILURE ], endpoint: `/quotes/${quoteId}/`, method: 'get', meta: { quoteId } }); } export function like(quoteId) { return callAPI({ types: [ Quote.LIKE_BEGIN, Quote.LIKE_SUCCESS, Quote.LIKE_FAILURE ], endpoint: `/quotes/${quoteId}/like/`, method: 'post' }); } export function unlike(quoteId) { return callAPI({ types: [ Quote.UNLIKE_BEGIN, Quote.UNLIKE_SUCCESS, Quote.UNLIKE_FAILURE ], endpoint: `/quotes/${quoteId}/unlike/`, method: 'post' }); } export function approve(quoteId) { return callAPI({ types: [ Quote.APPROVE_BEGIN, Quote.APPROVE_SUCCESS, Quote.APPROVE_FAILURE ], endpoint: `/quotes/${quoteId}/approve/`, method: 'put' }); } export function unapprove(quoteId) { return callAPI({ types: [ Quote.UNAPPROVE_BEGIN, Quote.UNAPPROVE_SUCCESS, Quote.UNAPPROVE_FAILURE ], endpoint: `/quotes/${quoteId}/unapprove/`, method: 'put' }); } export function addQuotes({ text, source }) { return (dispatch, getState) => { dispatch(startSubmit('addQuote')); dispatch(callAPI({ types: [Quote.ADD_BEGIN, Quote.ADD_SUCCESS, Quote.ADD_FAILURE], endpoint: '/quotes/', method: 'post', body: { title: 'Tittel', text, source, approved: false } })).then( () => { stopSubmit('addQuote'); pushState(null, '/quotes'); }, (error) => { const errors = { ...error.response.body }; if (errors.text) { errors.text = errors.text[0]; } if (errors.source) { errors.source = errors.source[0]; } dispatch(stopSubmit('addQuote', errors)); } ); }; } export function deleter(quoteId) { return callAPI({ types: [Quote.DELETE_BEGIN, Quote.DELETE_SUCCESS, Quote.DELETE_FAILURE], endpoint: `/quotes/${quoteId}/`, method: 'del', meta: { quoteId } }); }
JavaScript
0.000004
@@ -2218,16 +2218,25 @@ +dispatch( stopSubm @@ -2249,16 +2249,17 @@ dQuote') +) ;%0A @@ -2260,16 +2260,25 @@ +dispatch( pushStat @@ -2295,16 +2295,17 @@ quotes') +) ;%0A
32b35520a54d11d88f02bdd61efc979c338ad65e
Add some more tests
kolibri/plugins/management/assets/test/management.js
kolibri/plugins/management/assets/test/management.js
/* eslint-env mocha */ // The following two rules are disabled so that we can use anonymous functions with mocha // This allows the test instance to be properly referenced with `this` /* eslint prefer-arrow-callback: "off", func-names: "off" */ const Vue = require('vue'); const Vuex = require('vuex'); const assert = require('assert'); const _ = require('lodash'); const { store, mutations, constants } = require('../src/vuex/store.js'); const Management = require('../src/main.vue'); const fixture1 = require('./fixtures/fixture1.js'); describe('The management module', () => { it('defines a Management vue', () => { // A sanity check assert(Management !== undefined); }); describe('has the following components:', function () { before(function () { const container = new Vue({ template: '<div class="foo"><management v-ref:main></management></div>', components: { Management }, store, }).$mount(); this.vm = container.$refs.main; }); after(function () { this.vm.$destroy(); }); it('a classroom selector', function (done) { Vue.nextTick(() => { const child = this.vm.$refs.classroomSelector; assert.notStrictEqual(child, undefined); done(); }); }); it('a learner group selector', function (done) { Vue.nextTick(() => { const child = this.vm.$refs.learnerGroupSelector; assert.notStrictEqual(child, undefined); done(); }); }); it('a learner roster', function (done) { Vue.nextTick(() => { const child = this.vm.$refs.learnerRoster; assert.notStrictEqual(child, undefined); done(); }); }); }); describe('changes the list of students in the roster when you select a classroom.', function () { beforeEach(function () { const testStore = new Vuex.Store({ state: fixture1, mutations, }); const container = new Vue({ template: '<div><management v-ref:main></management></div>', components: { Management }, store: testStore, }).$mount(); this.vm = container.$refs.main; this.store = testStore; }); afterEach(function () { this.vm.$destroy(); }); it('The roster shows only John Duck when you select "Classroom C".', function (done) { // Look at the fixture file for the magic numbers here. this.store.dispatch('SET_SELECTED_CLASSROOM_ID', 3); Vue.nextTick(() => { assert(_.isEqual(this.vm.$refs.learnerRoster.learners, [{ id: 2, first_name: 'John', last_name: 'Duck', username: 'jduck', }])); done(); }); }); it('The roster shows all learners when you select "All classrooms".', function (done) { this.store.dispatch('SET_SELECTED_CLASSROOM_ID', constants.ALL_CLASSROOMS_ID); Vue.nextTick(() => { assert(_.isEqual(this.vm.$refs.learnerRoster.learners, fixture1.learners)); done(); }); }); }); });
JavaScript
0
@@ -2925,32 +2925,859 @@ %7B%0A assert +.deepStrictEqual(this.vm.$refs.learnerRoster.learners, fixture1.learners);%0A done();%0A %7D);%0A %7D);%0A%0A it('The roster shows two students when you select %22Classroom A%22 and %22Group 1%22.', function (done) %7B // eslint-disable-line max-len%0A this.store.dispatch('SET_SELECTED_CLASSROOM_ID', 1);%0A Vue.nextTick(() =%3E %7B%0A this.store.dispatch('SET_SELECTED_GROUP_ID', 1);%0A Vue.nextTick(() =%3E %7B%0A const expectedIds = %5B1, 2%5D;%0A assert.deepStrictEqual(this.vm.$refs.learnerRoster.learners.map(learner =%3E%0A learner.id%0A ), expectedIds);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A it('The roster shows no students when you select %22Classroom B%22.', function (done) %7B%0A this.store.dispatch('SET_SELECTED_CLASSROOM_ID', 2);%0A Vue.nextTick(() =%3E %7B%0A assert (_.isEqual(this. @@ -3798,35 +3798,16 @@ erRoster -.learners, fixture1 .learner @@ -3807,16 +3807,20 @@ learners +, %5B%5D ));%0A
9be11fb0a648f797b514ae345d16169a15b7e93b
Allow the fixture adapter to be queried.
app/adapters/application.js
app/adapters/application.js
import DS from 'ember-data'; export default DS.FixtureAdapter.extend({ });
JavaScript
0
@@ -65,12 +65,355 @@ xtend(%7B%0A + // allow fixtures to be queried%0A queryFixtures: function(records, query /*, type */) %7B%0A return records.filter(function(record) %7B%0A for(var key in query) %7B%0A if (!query.hasOwnProperty(key)) %7B continue; %7D%0A var value = query%5Bkey%5D;%0A if (record%5Bkey%5D !== value) %7B return false; %7D%0A %7D%0A return true;%0A %7D);%0A %7D%0A %7D);%0A
5f6994d332a29ac374317172feb902aa23f77490
Add watch tasks to automatically recompile js
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var babel = require("gulp-babel"); gulp.task('build', () => { return gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')); }) gulp.task('default', ['build']);
JavaScript
0.000001
@@ -180,16 +180,96 @@ ));%0A%7D)%0A%0A +gulp.task('watch', () =%3E %7B%0A return gulp.watch('src/**/*.js', %5B'build'%5D);%0A%7D)%0A%0A gulp.tas @@ -281,20 +281,29 @@ fault', %5B'build' +, 'watch' %5D);%0A
7177709f0fca2462db8695712391483e907bd37e
Fix more import references
server/api/routes/account.js
server/api/routes/account.js
const jwt = require('koa-jwt') const bcrypt = require('../utilities/bcrypt-promise') const KoaRouter = require('koa-router') const router = KoaRouter() // list available rooms router.get('/api/account/rooms', async (ctx, next) => { let rooms = await ctx.db.all('SELECT * FROM rooms WHERE status = ?', 'open') return ctx.body = rooms }) // login router.post('/api/account/login', async (ctx, next) => { let {email, password, roomId} = ctx.request.body // check presence of all fields if (!email || !password || !roomId) { ctx.status = 422 return ctx.body = 'Email, password, and room are required' } email = email.trim().toLowerCase() // get user let user = await ctx.db.get('SELECT * FROM users WHERE email = ?', email) // validate password if (!user || !await bcrypt.compare(password, user.password)) { ctx.status = 401 return } // validate roomId let room = await ctx.db.get('SELECT * FROM rooms WHERE roomId = ?', roomId) if (!room || room.status !== 'open') { ctx.status = 401 return ctx.body = 'Invalid Room' } delete user.password user.roomId = room.roomId let token = jwt.sign(user, 'shared-secret') // client also persists this to localStorage ctx.body = { user, token } }) // logout router.get('/api/account/logout', async (ctx, next) => { // doesn't do much... ctx.status = 200 }) // create router.post('/api/account/create', async (ctx, next) => { let {name, email, newPassword, newPasswordConfirm} = ctx.request.body name = name.trim() email = email.trim().toLowerCase() // check presence of all fields if (!name || !email || !newPassword || !newPasswordConfirm) { ctx.status = 422 return ctx.body = 'All fields are required' } // validate email if (!validateEmail(email)) { ctx.status = 422 return ctx.body = 'Invalid email address' } // check for duplicate email if (await ctx.db.get('SELECT * FROM users WHERE email = ?', email)) { ctx.status = 401 return ctx.body = 'Email address is already registered' } // check that passwords match if (newPassword !== newPasswordConfirm) { ctx.status = 422 return ctx.body = 'Passwords do not match' } let hashedPwd = await hash(newPassword, 10) let res = await ctx.db.run('INSERT INTO users (email, password, name) VALUES (?, ?, ?)', email, hashedPwd, name) ctx.status = 200 }) // update router.post('/api/account/update', async (ctx, next) => { // check jwt validity if (!ctx.state.user) { ctx.status = 401 return ctx.body = 'Invalid token' } let user = await ctx.db.get('SELECT * FROM users WHERE userId = ?', ctx.state.user.userId) if (!user) { ctx.status = 401 return ctx.body = 'Invalid user id' } let {name, email, password, newPassword, newPasswordConfirm} = ctx.request.body name = name.trim() email = email.trim().toLowerCase() // check presence of required fields if (!name || !email || !password) { ctx.status = 422 return ctx.body = 'Name, email and current password are required' } // validate current password if (!await compare(password, user.password)) { ctx.status = 401 return ctx.body = 'Current password is incorrect' } // changing password? if (newPassword && newPasswordConfirm) { if (newPassword !== newPasswordConfirm) { ctx.status = 422 return ctx.body = 'New passwords do not match' } password = await hash(newPassword, 10) } else { password = user.password } // validate email if (!validateEmail(email)) { ctx.status = 422 return ctx.body = 'Invalid email address' } // check for duplicate email if (await ctx.db.get('SELECT * FROM users WHERE userId != ? AND email = ? COLLATE NOCASE ', ctx.state.user.userId, email)) { ctx.status = 401 return ctx.body = 'Email address is already registered' } // do update let res = await ctx.db.run('UPDATE users SET name = ?, email = ?, password = ? WHERE userId = ?', name, email, password, ctx.state.user.userId) // return user (shape should match /login) user = await ctx.db.get('SELECT * FROM users WHERE email = ?', email) delete user.password user.roomId = ctx.state.user.roomId // generate new JWT let token = jwt.sign(user, 'shared-secret') // store JWT in httpOnly cookie // ctx.cookies.set('id_token', token, {httpOnly: true}) // client also persists this to localStorage ctx.body = user }) module.exports = router // email validation helper from // http://www.moreofless.co.uk/validate-email-address-without-regex/ function validateEmail(email) { var at = email.indexOf( "@" ) var dot = email.lastIndexOf( "\." ) return email.length > 0 && at > 0 && dot > at + 1 && dot < email.length && email[at + 1] !== "." && email.indexOf( " " ) === -1 && email.indexOf( ".." ) === -1 }
JavaScript
0
@@ -2216,32 +2216,39 @@ shedPwd = await +bcrypt. hash(newPassword @@ -3106,16 +3106,23 @@ (!await +bcrypt. compare( @@ -3446,16 +3446,23 @@ = await +bcrypt. hash(new
bf3a5486245d10e3b256cd8f34b58220a5bcb5ff
Save stocks when prices change
src/public/StockFactory.js
src/public/StockFactory.js
(function(exports) { const randInt = (min, max) => { const range = max - min; return Math.round( min + Math.random() * range ); }; function generateStocks({minPrice, maxPrice}) { const symbols = [ 'Amazon', 'Google', 'Facebook', 'Microsoft', 'Facebook', 'McDonald\'s', 'ExxonMobil' ].sort(); const stocks = symbols.map(symbol => new Stock({ symbol, price: randInt(minPrice, maxPrice) }) ); return stocks; } function StockFactory() { let stocks = Db.get('stocks'); if (typeof stocks !== 'object' || stocks === null) { stocks = generateStocks({ minPrice: 100, maxPrice: 1000 }); } stocks.forEach(stock => { if (stock.shouldUpdatePrice()) { stock.updatePrice(); } }); return stocks; } exports.StockFactory = StockFactory; })(window);
JavaScript
0
@@ -735,16 +735,47 @@ %0A %7D%0A%0A + let pricesChanged = false;%0A stoc @@ -874,17 +874,112 @@ -%7D%0A %7D); + pricesChanged = true;%0A %7D%0A %7D);%0A%0A if (pricesChanged) %7B%0A Db.save('stocks', stocks);%0A %7D %0A%0A
fce0ca83cd0948081401b611b6b18dbfb334071e
Add metrics eventcount support
src/DotNetCore.CAP.Dashboard/wwwroot/vue.config.js
src/DotNetCore.CAP.Dashboard/wwwroot/vue.config.js
module.exports = { publicPath: './', productionSourceMap: false, chainWebpack: config => { config.plugins.delete('prefetch') } }
JavaScript
0
@@ -138,15 +138,190 @@ fetch')%0A + %7D,%0A devServer: %7B%0A proxy: %7B%0A '/cap/api': %7B%0A target: 'http://localhost:5000',%0A changeOrigin: true%0A %7D%0A %7D%0A %7D%0A%7D
f678feaacdf9a6cc26998699304ce251dbcb6baf
remove unused code
src/Enum.js
src/Enum.js
'use strict'; const R = require('ramda'); const EnumFromObject = Object.freeze; const EnumFromArray = R.reduce((acc, value) => EnumValue(value)(acc), {}); const EnumFromPairs = R.reduce((acc, pair) => EnumPairValue(pair)(acc), {}); const EnumKeyValue = (key, value) => R.assoc( R.ifElse( R.is(String), R.identity, String )(key), value ); const EnumValue = value => EnumKeyValue(value, value); const EnumPairValue = pair => EnumKeyValue(pair[0], pair[1]); const excludeEmpty = R.filter(R.pipe(R.length, R.gte(R.__, 1))); const debug = R.tap(console.log); const isSingleArg = R.pipe(R.length, R.equals(1)); const isPair = R.both( R.is(Array), R.pipe(R.length, R.equals(2)) ); const arePairs = R.both(R.is(Array), R.pipe(R.head, isPair)); const extend = [[R.T, R.identity]]; const EnumSingle = R.pipe(R.cond(extend), R.cond([ [arePairs, EnumFromPairs], [R.is(Array), EnumFromArray], [R.is(Map), R.pipe(Array.from, EnumFromPairs)], [R.is(Set), R.pipe(Array.from, EnumFromArray)], [R.is(String), R.pipe(R.split(/[\s]+/ig), excludeEmpty, EnumFromArray)], [R.is(Number), R.pipe(EnumValue, R.apply(R.__, [{}]))], [R.is(Boolean), R.pipe(EnumValue, R.apply(R.__, [{}]))], [R.T, R.identity], ])); const EnumMultiple = R.cond([ [R.pipe(R.head, R.is(String)), EnumFromArray], [R.T, R.identity], ]); /** * @param {Object|Array|Map|Set|...String} values Input arguments. * @return {Object} Frozen object corresponding to given arguments. */ const Enum = R.unapply(R.ifElse( isSingleArg, R.pipe(R.head, EnumSingle, EnumFromObject), R.pipe(R.reduce((acc, value) => R.merge(acc, EnumSingle(value)), {}), EnumFromObject) )); const isValidCondition = R.both(R.is(Function), R.pipe(R.prop('length'), R.equals(1))); const isValidOperator = R.both(R.is(Function), R.pipe(R.prop('length'), R.gte(R.__, 0))); const addExtend = R.invoker(3, 'splice')(0, 0, R.__, extend); Enum.extend = R.unapply(R.ifElse( R.both( R.pipe(R.length, R.equals(2)), R.both( R.pipe(R.head, isValidCondition), R.pipe(R.last, isValidOperator) ) ), addExtend, R.F )); exports = module.exports = Enum;
JavaScript
0.000017
@@ -1260,117 +1260,8 @@ );%0A%0A -const EnumMultiple = R.cond(%5B%0A %5BR.pipe(R.head, R.is(String)), EnumFromArray%5D,%0A %5BR.T, R.identity%5D,%0A%5D);%0A%0A /**%0A
0dde661d6f8e5d916b77cde311b023c5a4d9ee25
add field for new tab configuration of tools
src/services/ltiTool/model.js
src/services/ltiTool/model.js
// model.js - A mongoose model // https://www.edu-apps.org/code.html - LTI Parameters // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const { enableAuditLog } = require('../../utils/database'); const { Schema } = mongoose; const ltiToolSchema = new Schema({ name: { type: String }, url: { type: String, required: true }, key: { type: String }, secret: { type: String, required: true }, logo_url: { type: String }, lti_message_type: { type: String }, lti_version: { type: String }, resource_link_id: { type: String }, roles: { type: [{ type: String, enum: ['Learner', 'Instructor', 'ContentDeveloper', 'Administrator', 'Mentor', 'TeachingAssistant'], }], }, privacy_permission: { type: String, enum: ['anonymous', 'e-mail', 'name', 'public', 'pseudonymous'], default: 'anonymous', }, customs: { type: [{ key: { type: String }, value: { type: String } }] }, isTemplate: { type: Boolean }, isLocal: { type: Boolean }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now }, originTool: { type: Schema.Types.ObjectId, ref: 'ltiTool' }, oAuthClientId: { type: String }, friendlyUrl: { type: String, unique: true, sparse: true }, skipConsent: { type: Boolean }, }); function validateKey(value) { if (this.lti_version === 'LTI-1p0') return !!value; return true; } ltiToolSchema.path('key').validate(validateKey); enableAuditLog(ltiToolSchema); const ltiToolModel = mongoose.model('ltiTool', ltiToolSchema); module.exports = ltiToolModel;
JavaScript
0
@@ -1298,16 +1298,64 @@ lean %7D,%0A +%09openNewTab: %7B type: Boolean, default: false %7D,%0A %7D);%0A%0Afun
7333caae91fdf50eeebba91b0dca8f8f0a253fcc
Use string utility
lib/node_modules/@stdlib/string/replace/benchmark/benchmark.js
lib/node_modules/@stdlib/string/replace/benchmark/benchmark.js
'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var pkg = require( './../package.json' ).name; var replace = require( './../lib' ); // MAIN // bench( pkg+'::string', function benchmark( b ) { var out; var str; var i; str = 'To be, or not to be, that is the question.'; b.tic(); for ( i = 0; i < b.iterations; i++ ) { out = replace( str, 'be', String.fromCharCode( i%126 ) ); if ( !isString( out ) ) { b.fail( 'should return a string' ); } } b.toc(); if ( !isString( out ) ) { b.fail( 'should return a string' ); } b.pass( 'benchmark finished' ); b.end(); }); bench( pkg+'::regexp', function benchmark( b ) { var out; var str; var re; var i; str = 'To be, or not to be, that is the question.'; re = /be/g; b.tic(); for ( i = 0; i < b.iterations; i++ ) { out = replace( str, re, String.fromCharCode( i%126 ) ); if ( !isString( out ) ) { b.fail( 'should return a string' ); } } b.toc(); if ( isString( out ) ) { b.pass( 'benchmark finished' ); } else { b.fail( 'should return a string' ); } b.end(); }); bench( pkg+'::replacer', function benchmark( b ) { var out; var str; var i; str = 'To be, or not to be, that is the question.'; b.tic(); for ( i = 0; i < b.iterations; i++ ) { out = replace( str, 'be', replacer ); if ( !isString( out ) ) { b.fail( 'should return a string' ); } } b.toc(); if ( !isString( out ) ) { b.fail( 'should return a string' ); } b.pass( 'benchmark finished' ); b.end(); function replacer( match, p1 ) { return '/' + p1 + '/'; } });
JavaScript
0.000028
@@ -129,16 +129,81 @@ mitive;%0A +var fromCodePoint = require( '@stdlib/string/from-code-point' );%0A var pkg @@ -241,16 +241,16 @@ ).name;%0A - var repl @@ -502,35 +502,29 @@ , 'be', -String.fromCharCode +fromCodePoint ( i%25126 @@ -962,27 +962,21 @@ re, -String.fromCharCode +fromCodePoint ( i%25 @@ -1074,16 +1074,17 @@ ;%0A%09if ( +! isString @@ -1099,52 +1099,8 @@ ) %7B%0A -%09%09b.pass( 'benchmark finished' );%0A%09%7D else %7B%0A %09%09b. @@ -1133,19 +1133,52 @@ ing' );%0A - %09%7D%0A +%09b.pass( 'benchmark finished' );%0A %09b.end()
1d27758ea8a848a58ee7da2e8649f132c72ce11e
Add potential defaults to user model -these aren't meant to sync up with db, but be representative of a user's relation to the current page
app/assets/javascripts/global/models/user.js
app/assets/javascripts/global/models/user.js
app = ap || {}; app.User = Backbone.Model.extend({ })
JavaScript
0
@@ -45,10 +45,129 @@ xtend(%7B%0A +%0A defaults: %7B%0A user_id: null,%0A voteData = null,%0A questionOwner = null%0A %7D,%0A%0A initialize: function()%7B%0A%0A %7D,%0A%0A %7D)
7b7045a3be34d374370437466b8da95e185f134e
add Flow MouseMoveActionLayer.js
src/components/actionLayer/MouseMoveActionLayer.js
src/components/actionLayer/MouseMoveActionLayer.js
import React from 'react'; export default class MouseMoveActionLayer extends React.Component { constructor(props) { super(props); this.state = { isAction: false, startPoint: {x: 0, y: 0}, }; this.canvas = null; this.ctx = null; this.canvasStartPosition = null; } componentDidMount() { this.ctx = this.canvas.getContext('2d'); const {x, y} = this.canvas.getBoundingClientRect(); this.canvasStartPosition = {x, y}; this.props.callbackDidMount({ canvas: this.canvas, ctx: this.ctx, }); } setStartPoint(mouseEventPageX, mouseEventPageY) { this.setState({ startPoint: { x: mouseEventPageX - this.canvasStartPosition.x, y: mouseEventPageY - this.canvasStartPosition.y, }, }); } getCurrentPoint(mouseEventPageX, mouseEventPageY) { const {canvasStartPosition} = this; return { x: mouseEventPageX - canvasStartPosition.x, y: mouseEventPageY - canvasStartPosition.y, }; } startAction() { this.setState({isAction: true}); } stopAction() { this.setState({isAction: false}); } switchCurrentPointToStartPoint(currentPoint) { this.setState({ startPoint: currentPoint, }); } render() { const {width, height} = this.props.imageData; return ( <canvas className="action-layer" width={width} height={height} ref={ref => { this.canvas = ref; }} onMouseDown={e => { this.startAction(); this.setStartPoint(e.pageX, e.pageY); }} onMouseMove={e => { if (!this.state.isAction) return; const currentPoint = this.getCurrentPoint(e.pageX, e.pageY); this.props.executeAction({ canvas: this.canvas, ctx: this.ctx, startPoint: this.state.startPoint, currentPoint, }); this.switchCurrentPointToStartPoint(currentPoint); }} onMouseUp={() => { this.stopAction(); }} onMouseLeave={() => { this.stopAction(); }} /> ); } }
JavaScript
0
@@ -1,8 +1,17 @@ +// @flow%0A import R @@ -30,16 +30,369 @@ eact';%0A%0A +type Point = %7Bx: number, y: number%7D;%0A%0Atype Props = %7B%0A callbackDidMount: (%7Bctx: CanvasRenderingContext2D%7D) =%3E void,%0A executeAction: (%7B%0A canvas: HTMLCanvasElement,%0A ctx: CanvasRenderingContext2D,%0A startPoint: Point,%0A currentPoint: Point,%0A %7D) =%3E void,%0A imageData: ImageData,%0A%7D;%0A%0Atype State = %7B%0A isAction: boolean,%0A startPoint: Point,%0A%7D;%0A%0A export d @@ -448,16 +448,36 @@ omponent +%3C%0A Props,%0A State%0A%3E %7B%0A con @@ -490,16 +490,23 @@ or(props +: Props ) %7B%0A @@ -718,24 +718,99 @@ -this.ctx = +const %7Bcanvas%7D = this;%0A if (!canvas) throw new Error('canvas is null.');%0A this. +ctx = canv @@ -849,21 +849,18 @@ x, y%7D = -this. +(( canvas.g @@ -881,16 +881,32 @@ ntRect() +: any): DOMRect) ;%0A th @@ -938,16 +938,73 @@ %7Bx, y%7D;%0A + if (!this.ctx) throw new Error('this.ctx is null.');%0A this @@ -1031,37 +1031,24 @@ unt(%7B%0A -canvas: this. canvas,%0A @@ -1099,32 +1099,40 @@ (mouseEventPageX +: number , mouseEventPage @@ -1128,27 +1128,154 @@ seEventPageY -) %7B +: number) %7B%0A const %7BcanvasStartPosition%7D = this;%0A if (!canvasStartPosition) throw new Error('canvasStartPosition is null.'); %0A this.se @@ -1332,21 +1332,16 @@ PageX - -this. canvasSt @@ -1384,21 +1384,16 @@ PageY - -this. canvasSt @@ -1461,16 +1461,24 @@ entPageX +: number , mouseE @@ -1486,17 +1486,32 @@ entPageY -) +: number): Point %7B%0A c @@ -1541,24 +1541,103 @@ on%7D = this;%0A + if (!canvasStartPosition) throw new Error('canvasStartPosition is null.');%0A return %7B @@ -1744,24 +1744,139 @@ %0A %7D;%0A %7D%0A +%0A canvas: HTMLCanvasElement %7C null;%0A ctx: CanvasRenderingContext2D %7C null;%0A canvasStartPosition: Point %7C null;%0A%0A startActio @@ -2026,16 +2026,23 @@ entPoint +: Point ) %7B%0A @@ -2584,32 +2584,164 @@ ageX, e.pageY);%0A + if (!this.canvas) throw new Error('this.canvas is null.');%0A if (!this.ctx) throw new Error('this.ctx is null.');%0A this.p
0cc47c7cbd023c671e7101339211f0465aa96355
Make npm dependencies filter optional to flow
packages/npm/src/index.js
packages/npm/src/index.js
'use strict' /* @flow */ import Path from 'path' import FS from 'fs' import invariant from 'assert' import promisify from 'sb-promisify' import { exec } from 'sb-exec' import semver from 'semver' import { versionFromRange, getManifestPath } from './helpers' import { readJSON } from 'motion-fs' type Installer$Options = { rootDirectory: string, filter: Function } class Installer { options: Installer$Options; constructor({rootDirectory, filter}: Installer$Options) { invariant(typeof rootDirectory === 'string', 'rootDirectory must be a string') invariant(!filter || typeof filter === 'function', 'filter must be a function') this.options = { rootDirectory, filter } } async install(name: string): Promise<void> { await exec('npm', ['install', '--save', name], { cwd: this.options.rootDirectory }) } async uninstall(name: string): Promise<void> { await exec('npm', ['uninstall', '--save', name], { cwd: this.options.rootDirectory }) } async installPeerDependencies( name: string, onStarted?: ((packages: Array<Array<string>>) => void), onProgress?: ((packageName: string, error: ?Error) => void), onComplete?: (() => void) ): Promise<void> { const rootDirectory = this.options.rootDirectory const manifestPath = await getManifestPath(rootDirectory, name) const manifestContents = readJSON(manifestPath) const peerDependencies = manifestContents && manifestContents.peerDependencies || {} if (peerDependencies && typeof peerDependencies === 'object') { let dependencies = Object.keys(peerDependencies) if (this.options.filter) { dependencies = this.options.filter(dependencies) } const versions = dependencies.map(function(name) { const range = peerDependencies[name] const version = semver.maxSatisfying(versionFromRange(range), range) return [name, version] }) if (onStarted) { onStarted(versions) } await Promise.all(versions.map(async function([name, version]) { try { await exec('npm', ['install', `${name}@${version}`], { cwd: rootDirectory }) if (onProgress) { onProgress(name, null) } } catch (_) { if (onProgress) { onProgress(name, _) } else throw _ } })) if (onComplete) { onComplete() } } } } module.exports = Installer
JavaScript
0
@@ -353,16 +353,17 @@ filter: +? Function
04a391faf3dc8c22fc81d3b9df4d9ad46d58aac2
Fix optionalness of plugins param
packages/postcss/index.js
packages/postcss/index.js
/** * PostCSS webpack block. * * @see https://github.com/postcss/postcss-loader */ module.exports = postcss /** * @param {PostCSSPlugin[]} [plugins] Will read `postcss.config.js` file if not supplied. * @param {object} [options] * @param {RegExp|Function|string} [options.exclude] Directories to exclude. * @param {string} [options.parser] Package name of custom PostCSS parser to use. * @param {string} [options.stringifier] Package name of custom PostCSS stringifier to use. * @param {string} [options.syntax] Package name of custom PostCSS parser/stringifier to use. * @return {Function} */ function postcss (plugins, options) { options = options || {} // https://github.com/postcss/postcss-loader#options const postcssOptions = Object.assign( {}, options.parser && { parser: options.parser }, options.stringifier && { stringifier: options.stringifier }, options.syntax && { syntax: options.syntax } ) return (context) => Object.assign( { module: { loaders: [ Object.assign({ test: context.fileType('text/css'), loaders: [ 'style-loader', 'css-loader', 'postcss-loader?' + JSON.stringify(postcssOptions) ] }, options.exclude ? { exclude: Array.isArray(options.exclude) ? options.exclude : [ options.exclude ] } : {}) ] } }, plugins ? createPostcssPluginsConfig(context.webpack, plugins) : {} ) } function createPostcssPluginsConfig (webpack, plugins) { const isWebpack2 = typeof webpack.validateSchema !== 'undefined' if (isWebpack2) { return { plugins: [ new webpack.LoaderOptionsPlugin({ options: { postcss: plugins } }) ] } } else { return { postcss: plugins } } }
JavaScript
0.000001
@@ -732,16 +732,42 @@ ions) %7B%0A + plugins = plugins %7C%7C %5B%5D%0A option
5fb4b6b1f6078c04daa9e94addbf9c32501c4002
change tag task
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var lint = require('./lib'); var mocha = require('gulp-mocha'); var git = require('gulp-git'); var bump = require('gulp-bump'); // Lint task - Meta AF gulp.task('lint', lint({ src: './lib/*.js' })); // Tests gulp.task('test', ['lint'], function() { return gulp.src('./test/index.js', { read: false }) .pipe(mocha({ reporter: 'dot' })); }); // Bump patch version gulp.task('bump', ['test'], function() { return gulp.src(['./package.json']) .pipe(bump()) .pipe(gulp.dest('./')); }); // Bump minor version gulp.task('bump:minor', ['test'], function() { return gulp.src(['./package.json']) .pipe(bump({ type: 'minor' })) .pipe(gulp.dest('./')); }); // Bump major version gulp.task('bump:major', ['test'], function() { return gulp.src(['./package.json']) .pipe(bump({ type: 'major' })) .pipe(gulp.dest('./')); }); // Tag release in git gulp.task('tag', function() { var pkg = require('./package.json'); var v = 'v' + pkg.version; var message = 'Release ' + v; return gulp.src('./') .pipe(git.commit(message)) .pipe(git.tag(v, message)) .pipe(git.push('origin', 'master', '--tags')) .pipe(gulp.dest('./')); }); // Release to git gulp.task('release', ['bump', 'tag']); gulp.task('release:minor', ['bump:minor', 'tag']); gulp.task('release:major', ['bump:major', 'tag']);
JavaScript
0.001134
@@ -1049,12 +1049,11 @@ c('. -/ ')%0A + @@ -1106,32 +1106,66 @@ , message))%0A +.on('end', function() %7B%0A this .pipe(git.push(' @@ -1198,37 +1198,33 @@ '))%0A -.pipe(gulp.dest('./') + .end();%0A %7D );%0A%7D);%0A%0A
72c71a4fb48556c3bc3d4ad0f63ac2accd4b4942
update $ function
public/assets/zdr/common/error_404.js
public/assets/zdr/common/error_404.js
$(document).ready(function () { $("#history-back").click(function () { history.back(); }); });
JavaScript
0.000034
@@ -1,23 +1,7 @@ %EF%BB%BF$( -document).ready( func
b535331450477c36604f8a78ad869147a8750e57
Fix navbar due to js processing
src/site/resources/js/site.js
src/site/resources/js/site.js
$(window).load(function() { $('div.source pre, pre code').each(function(i, e) { e.innerHTML = e.innerHTML.replace(/\n/g, "<br />").replace(/\t/g, "&nbsp;&nbsp;"); }); })
JavaScript
0
@@ -164,12 +164,38 @@ );%0A%09%7D);%0A +%09$(%22#toc-bar%22).affix(%7B%7D);%0A %7D)%0A%0A
0c59a1ba8d216702c756a5a76f0f8e5afc2c1cbc
Remove flexibility
gulpfile.js
gulpfile.js
'use strict'; const gulp = require('gulp'); const babel = require('gulp-babel'); const plumber = require('gulp-plumber'); const stylus = require('gulp-stylus'); const poststylus = require('poststylus'); const rucksack = require('rucksack-css'); const flexibility = require('postcss-flexibility'); const prefixer = require('autoprefixer'); const fontMagician = require('postcss-font-magician'); const gcmq = require('gulp-group-css-media-queries'); const cssnano = require('gulp-cssnano'); const sourcemaps = require('gulp-sourcemaps'); const lost = require('lost'); const rupture = require('rupture'); const postcss = require('gulp-postcss'); const concat = require('gulp-concat'); const uglify = require('gulp-uglify'); const pug = require('gulp-pug'); const data = require('gulp-data'); const imagemin = require('gulp-imagemin'); const browserSync = require('browser-sync'); const svgmin = require('gulp-svgmin'); const svgstore = require('gulp-svgstore'); const cheerio = require('gulp-cheerio'); const mdcss = require('mdcss'); const fs = require('fs'); const del = require('del'); const srcApp = { js: [ 'src/js/**/*.js' ], css: 'src/styl/**/*.styl', styl: 'src/styl/style.styl', html: 'src/pug/*.pug', icons: 'src/svg/icons/*', svg: 'src/svg/', img: 'src/img/**/*', data: 'src/data/', helpers: 'src/helpers/' }; const buildApp = { build: 'build/**/*', js: 'build/js/', css: 'build/css/', html: 'build/', img: 'build/img', svg: 'build/svg' }; let dataJson = {}; let files = []; gulp.task('clean', () => { return del(buildApp.build); }); gulp.task('css', () => { return gulp.src(srcApp.styl) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(stylus({ use: [ rupture(), poststylus([ lost(), fontMagician(), rucksack(), flexibility(), prefixer() ]) ], compress: false })) .pipe(gcmq()) .pipe(cssnano()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(buildApp.css)); }); gulp.task('styleguide', () => { return gulp.src(srcApp.styl) .pipe(plumber()) .pipe(stylus({ use: [ rupture(), poststylus([ lost(), fontMagician(), rucksack({ autoprefixer: true }) ]) ], compress: false })) .pipe(postcss([ mdcss({ //logo: '', destination: 'build/styleguide', title: 'Styleguide', examples: { css: ['../css/style.css'] }, }) ])); }); gulp.task('js', () => { return gulp.src(srcApp.js) .pipe(plumber()) .pipe(sourcemaps.init()) .pipe(babel()) .pipe(concat('main.js')) .pipe(uglify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(buildApp.js)); }); gulp.task('read:data', () => { const dataAdapter = require('./' + srcApp.helpers + 'dataAdapter'); fs.readdir(srcApp.data, (err, items) => { files = items.map(item => item.split('.')[0]); items.forEach((file, index) => dataJson[files[index]] = dataAdapter(srcApp.data + file)); }); }); gulp.task('html', () => { return gulp.src(srcApp.html) .pipe(plumber()) .pipe(data(dataJson)) .pipe(pug()) .pipe(gulp.dest(buildApp.html)); }); gulp.task('images', () => { return gulp.src(srcApp.img) .pipe(plumber()) .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })) .pipe(gulp.dest(buildApp.img)); }); gulp.task('svg', () => { gulp.src(srcApp.svg) .pipe(svgmin()) .pipe(gulp.dest(srcApp.svg)); gulp.src(srcApp.svg) .pipe(svgmin()) .pipe(gulp.dest(buildApp.svg)); }); gulp.task('icons', () => { return gulp.src(srcApp.icons) .pipe(svgmin()) .pipe(svgstore({ fileName: 'icons.svg', inlineSvg: true })) .pipe(cheerio({ run: function ($, file) { $('svg').addClass('hide'); $('[fill]').removeAttr('fill'); }, parserOptions: { xmlMode: true } })) .pipe(gulp.dest(buildApp.svg)); }); gulp.task('watch', () => { gulp.watch(srcApp.html, { debounceDelay: 300 }, ['html']); gulp.watch(srcApp.data + '**/*', { debounceDelay: 300 }, ['read:data', 'html']); gulp.watch(srcApp.css, ['css']); gulp.watch(srcApp.js, ['js']); gulp.watch(srcApp.img, ['images']); gulp.watch(srcApp.icons, ['icons']); }); gulp.task('browser-sync', () => { var files = [ buildApp.build ]; browserSync.init(files, { server: { baseDir: './build/' }, }); }); gulp.task('build', ['clean'], () => { gulp.start( 'styleguide', 'css', 'read:data', 'html', 'js', 'images', 'svg', 'icons' ); }); gulp.task('default', [ 'build', 'watch', 'browser-sync' ]);
JavaScript
0.000002
@@ -242,60 +242,9 @@ s'); -%0Aconst flexibility = require('postcss-flexibility'); + %0Acon @@ -1775,33 +1775,9 @@ k(), -%0A flexibility(), + %0A
5f347bff6785fe49444c4b8534312c12a5c4093d
remove console.logs whoops
app/assets/javascripts/src/Metamaps.Views.js
app/assets/javascripts/src/Metamaps.Views.js
(function () { Metamaps.Views = {}; var initialized = false; Metamaps.Views.init = function () { Metamaps.Views.MapperCard = Backbone.View.extend({ template: Hogan.compile( $('#mapperCardTemplate').html() ), tagName: "div", className: "mapper", render: function () { this.$el.html( this.template.render(this.model) ); return this; } }); Metamaps.Views.MapCard = Backbone.View.extend({ template: Hogan.compile( $('#mapCardTemplate').html() ), tagName: "div", className: "map", id: function() { return this.model.id; }, initialize: function () { this.listenTo(this.model, "change", this.render); }, render: function () { this.$el.html( this.template.render(this.model.attrForCards()) ); return this; } }); var mapsWrapper = Backbone.View.extend({ initialize: function (opts) { }, setCollection: function (collection) { if (this.collection) this.stopListening(this.collection); this.collection = collection; this.listenTo(this.collection, 'add', this.render); this.listenTo(this.collection, 'successOnFetch', this.handleSuccess); this.listenTo(this.collection, 'errorOnFetch', this.handleError); }, render: function (mapperObj) { var that = this; this.el.innerHTML = ""; // in case it is a page where we have to display the mapper card if (mapperObj) { var view = new Metamaps.Views.MapperCard({ model: mapperObj }); that.el.appendChild( view.render().el ); } this.collection.each(function (map) { var view = new Metamaps.Views.MapCard({ model: map }); that.el.appendChild( view.render().el ); }); this.$el.append('<div class="clearfloat"></div>'); var m = Metamaps.Famous.maps.surf; m.setContent(this.el); setTimeout(function(){ var height = $(that.el).height() + 32 + 56; m.setSize([undefined, height]); }, 100); if (!initialized) { m.deploy(m._currTarget); initialized = true; setTimeout(function(){ var height = $(that.el).height() + 32 + 56; m.setSize([undefined, height]); }, 100); } Metamaps.Loading.hide(); console.log("OK current page is " + Metamaps.currentPage); console.log(Metamaps); setTimeout((function(localCurrentPage){ return function(){ console.log("YEAH current page is " + Metamaps.currentPage); console.log("YEAH current page passed is " + localCurrentPage); console.log(Metamaps); var path = (Metamaps.currentSection == "") ? "" : "/explore/" + localCurrentPage; // alter url if for mapper profile page if (that.collection && that.collection.mapperId) { path += "/" + that.collection.mapperId; } Metamaps.Router.navigate(path); }})(Metamaps.currentPage), 500); }, handleSuccess: function () { var that = this; if (this.collection && this.collection.id === "mapper") { this.fetchUserThenRender(); } else { this.render(); } }, handleError: function () { console.log('error loading maps!'); //TODO }, fetchUserThenRender: function () { var that = this; // first load the mapper object and then call the render function $.ajax({ url: "/users/" + this.collection.mapperId + "/details.json", success: function (response) { that.render(response); }, error: function () { } }); } }); Metamaps.Views.exploreMaps = new mapsWrapper(); }; })();
JavaScript
0.000002
@@ -2764,373 +2764,66 @@ -console.log(%22OK current page is %22 + Metamaps.currentPage);%0D%0A console.log(Metamaps);%0D%0A setTimeout((function(localCurrentPage)%7B return function()%7B%0D%0A console.log(%22YEAH current page is %22 + Metamaps.currentPage);%0D%0A console.log(%22YEAH current page passed is %22 + localCurrentPage);%0D%0A console.log(Metamaps); +setTimeout((function(localCurrentPage)%7B return function()%7B %0D%0A
c997e79d265d9985f6302782736fe650e87ed9fd
add focus to input felds
js/layout.js
js/layout.js
function initLayout() { $(":input").val(""); $(".js-name").text(""); $(".js-city").text(""); $(".spinner").css("display", "none"); $(".input-section-visible").hide(0).removeClass("input-section-visible").addClass("input-section-hidden"); $(".input-section-hidden").hide(0) $(".details-hidden").hide(0); $(".js-from:last").show(0); $(".js-to:last").show(0); toggleInputHideClass("init"); } function toggleInput(el) { if ($(el).next(".js-from").length > 0 || $(el).next(".js-to").length > 0 || $(el).next(".js-time-date").length > 0){ $(el).next(":first").slideToggle(300, function () { $(":input").val(""); }); } else $(el).slideToggle(300, function () { showSuggests(".js-section", -1); toggleInputHideClass(el); $(":input").val(""); }); } function showSuggests(section, number, busstop) { $(section).find(".js-suggest").each( function (index, el) { if ($(el).parents(section) && index == number) { $(el).show(); //$(el).slideToggle(400); $(el).find(".js-name").text( (busstop.name != "") ? busstop.name + ", " : ""); $(el).find(".js-city").text(busstop.city); } else { if (index > number) { $(el).hide(); // $(el).slideToggle(400); $(el).find(".js-name").text(); $(el).find(".js-city").text(); } } }); } function showSelectedBusstop(section, busstop) { $(section + ":first").find(".js-name").text(busstop.name + ", "); $(section + ":first").find(".js-city").text(busstop.city); } function showSelectetTime(time) { $(".js-time-date:first").find(".js-name").text(time[1] + ", "); $(".js-time-date:first").find(".js-city").text(time[0]); } // Moves the next input section into visible and // and proves if the next feld is already fulled function toggleInputHideClass(el) { //To validate the next input feld if (el == "init") proveNextSection("init"); else if ($(el).hasClass("js-from")) proveNextSection("js-from"); else if ($(el).hasClass("js-to")) proveNextSection("js-to"); else if ($(el).hasClass("js-time-date")) proveNextSection("js-time-date"); $(".input-section-hidden:first").show(0).removeClass("input-section-hidden").addClass("input-section-visible"); } function showStartRequestStuff() { $(".spinner").css("display", "block"); $("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible"); $(".js-overview").hide().children().hide(); $(".js-overview").find(".js-time").text(""); $(".js-overview").find(".js-duration").text(""); } function showOverview() { var routeData = getRouteData(); if (routeData != undefined) { for (var i = 1; i < routeData.length; i++) { if (routeData[i] != null) genOverviewElement(routeData[i].overview, i); } } else { console.log("Noconnection"); } } function genOverviewElement(data, index) { index--; console.log(index); $(".js-overview").show().children()[index].style.display = "block"; $(".js-overview").find(".js-time")[index].innerHTML = (data.depTime + " - " + data.arrTime); $(".js-overview").find(".js-duration")[index].innerHTML = (data.duration); } function changeToDetails(index) { console.log("go to Detail"); $(".js-transit").hide(); $(".js-intermediate").hide(); $(".search-visible:first").show(0).removeClass("search-visible").addClass("search-hidden"); $(".details-hidden:first").show(0).removeClass("details-hidden").addClass("details-visible"); $("#cancel").removeClass("icon-visible").addClass("icon-hidden-left"); $("#back").show(0).removeClass("icon-hidden-right").addClass("icon-visible"); genDetails(index); } function genDetails(index) { var data = getRouteData()[index].connections; console.log(index); var tBlock = $(".js-transit:first"); var iBlock = $(".js-intermediate:first"); var i = 0; while (i < data.length) { if (data[i].depTime != undefined) { tBlock.show(); tBlock.find(".js-time:first").text(data[i].depTime); tBlock.find(".js-time:last").text(data[i].arrTime); tBlock.find(".js-name:first").text(data[i].depBusstop[1] + ", "); tBlock.find(".js-name:last").text(data[i].arrBusstop[1] + ", "); tBlock.find(".js-city:first").text(data[i].depBusstop[0]); tBlock.find(".js-city:last").text(data[i].arrBusstop[0]); tBlock.find(".js-lineNo").text("Line " + data[i].lineNo); } if (data[i].waitTime != "") iBlock.show().find("p").text(data[i].waitTime); i++; tBlock = tBlock.nextAll(".js-transit:first"); iBlock = iBlock.nextAll(".js-intermediate:first"); } } function changeToSearch() { console.log("go Back"); $(".details-visible:first").removeClass("details-visible").addClass("details-hidden"); $(".search-hidden:first").show(0).removeClass("search-hidden").addClass("search-visible"); $("#back").removeClass("icon-visible").addClass("icon-hidden-right"); $("#cancel").show(0).removeClass("icon-hidden-left").addClass("icon-visible"); }
JavaScript
0.000002
@@ -629,16 +629,45 @@ );%0A%09%09%09%7D) +.find(%22:input:first%22).focus() ;%0A%09%7D%0A%09el @@ -801,16 +801,45 @@ %22);%0A%09%09%7D) +.find(%22:input:first%22).focus() ;%0A%7D%0A%0Afun @@ -2217,24 +2217,53 @@ on-visible%22) +.find(%22:input:first%22).focus() ;%0A%7D%0A%0Afunctio
843476fa3b054fc651c93caea8da82c5c9107d92
Add comments
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); var jade = require('gulp-jade'); var plato = require('gulp-plato'); var espower = require('gulp-espower'); var karma = require('karma').server; gulp.task('jade', function () { return gulp.src('./src/views/*.jade') .pipe(jade()) .pipe(gulp.dest('./dist/')); }); gulp.task('typescript', function () { return gulp.src('./src/scripts/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')) .pipe(ts({ declarationFiles: true, target: 'es5' }) .pipe(gulp.dest('./dist/scripts/'))); }); // Generate complexity analysis reports gulp.task('analyze', function () { return gulp.src('./dist/scripts/*.js') .pipe(plato('./report', { jshint: { options: { strict: true } }, complexity: { trycatch: true } })); }); gulp.task('test', function (done) { gulp.src('./test/scripts/*.js') .pipe(espower()) .pipe(gulp.dest('./test/scripts/espower')); return karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); // Copy all files in "src" directory gulp.task('copy', function () { gulp.src([ 'src/**/*', '!src/**/*.html', '!src/**/*.css', ]) .pipe(gulp.dest('dist/')); }); // Copy all files in "bower_components" directory gulp.task('components', function () { gulp.src([ 'bower_components/**/*' ]) .pipe(gulp.dest('dist/bower_components/')); }); gulp.task('default', function () { });
JavaScript
0
@@ -1,12 +1,27 @@ +'use strict';%0A%0A var gulp = r @@ -255,16 +255,32 @@ erver;%0A%0A +// Compile jade%0A gulp.tas @@ -401,32 +401,63 @@ /dist/'));%0A%7D);%0A%0A +// Compile and Lint TypeScript%0A gulp.task('types @@ -1078,32 +1078,48 @@ %7D));%0A%7D);%0A%0A +// Test scripts%0A gulp.task('test' @@ -1256,23 +1256,16 @@ );%0A%0A -return karma.st
2250ce852d8b76e1ab5e5cf62eef7d8f78bf933c
移除返回 false
src/packages/line/main.js
src/packages/line/main.js
import { itemPoint } from '../../echarts-base' import { getFormated, getStackMap } from '../../utils' function getLineXAxis (args) { const { dimension, rows, xAxisName, axisVisible, xAxisType } = args return dimension.map((item, index) => ({ type: xAxisType, nameLocation: 'middle', nameGap: 22, boundaryGap: false, name: xAxisName[index] || '', axisTick: { show: true, lineStyle: { color: '#eee' } }, data: rows.map(row => row[item]), show: axisVisible })) } function getLineSeries (args) { const { rows, axisSite, metrics, area, stack, nullAddZero, labelMap, label, itemStyle, lineStyle, areaStyle, xAxisType, dimension } = args let series = [] const dataTemp = {} const stackMap = stack && getStackMap(stack) metrics.forEach(item => { dataTemp[item] = [] }) rows.forEach(row => { metrics.forEach(item => { let value = null if (row[item] != null) { value = row[item] } else if (nullAddZero) { value = 0 } const dataItem = xAxisType === 'category' ? value : [row[dimension[0]], value] dataTemp[item].push(dataItem) }) }) metrics.forEach(item => { let seriesItem = { name: labelMap[item] != null ? labelMap[item] : item, type: 'line', data: dataTemp[item] } if (area) seriesItem.areaStyle = { normal: {} } if (axisSite.right) { seriesItem.yAxisIndex = ~axisSite.right.indexOf(item) ? 1 : 0 } if (stack && stackMap[item]) seriesItem.stack = stackMap[item] if (label) seriesItem.label = label if (itemStyle) seriesItem.itemStyle = itemStyle if (lineStyle) seriesItem.lineStyle = lineStyle if (areaStyle) seriesItem.areaStyle = areaStyle series.push(seriesItem) }) return series } function getLineYAxis (args) { const { yAxisName, yAxisType, axisVisible, scale, min, max, digit } = args const yAxisBase = { type: 'value', axisTick: { show: false }, show: axisVisible } let yAxis = [] for (let i = 0; i < 2; i++) { if (yAxisType[i]) { yAxis[i] = Object.assign({}, yAxisBase, { axisLabel: { formatter (val) { return getFormated(val, yAxisType[i], digit) } } }) } else { yAxis[i] = Object.assign({}, yAxisBase) } yAxis[i].name = yAxisName[i] || '' yAxis[i].scale = scale[i] || false yAxis[i].min = min[i] || null yAxis[i].max = max[i] || null } return yAxis } function getLineTooltip (args) { const { axisSite, yAxisType, digit, labelMap, xAxisType, tooltipFormatter } = args const rightItems = axisSite.right || [] const rightList = labelMap ? rightItems.map(item => { return labelMap[item] === undefined ? item : labelMap[item] }) : rightItems return { trigger: 'axis', formatter (items) { if (tooltipFormatter) { return tooltipFormatter.apply(null, arguments) } let tpl = [] const { name, axisValueLabel } = items[0] const title = name || axisValueLabel tpl.push(`${title}<br>`) items.forEach(item => { let showData = null const type = ~rightList.indexOf(item.seriesName) ? yAxisType[1] : yAxisType[0] const data = xAxisType === 'category' ? item.data : item.data[1] showData = getFormated(data, type, digit) tpl.push(itemPoint(item.color)) tpl.push(`${item.seriesName}: ${showData}`) tpl.push('<br>') }) return tpl.join('') } } } function getLegend (args) { const { metrics, legendName, labelMap } = args if (!legendName && !labelMap) return { data: metrics } const data = labelMap ? metrics.map(item => (labelMap[item] == null ? item : labelMap[item])) : metrics return { data, formatter (name) { return legendName[name] != null ? legendName[name] : name } } } export const line = (columns, rows, settings, extra) => { const { axisSite = {}, yAxisType = ['normal', 'normal'], xAxisType = 'category', yAxisName = [], dimension = [columns[0]], xAxisName = [], axisVisible = true, area, stack, scale = [false, false], min = [null, null], max = [null, null], nullAddZero = false, digit = 2, legendName = {}, labelMap = {}, label, itemStyle, lineStyle, areaStyle } = settings const { tooltipVisible, legendVisible, tooltipFormatter } = extra let metrics = columns.slice() if (axisSite.left && axisSite.right) { metrics = axisSite.left.concat(axisSite.right) } else if (axisSite.left && !axisSite.right) { metrics = axisSite.left } else if (settings.metrics) { metrics = settings.metrics } else { metrics.splice(columns.indexOf(dimension[0]), 1) } const legend = legendVisible && getLegend({ metrics, legendName, labelMap }) const tooltip = tooltipVisible && getLineTooltip({ axisSite, yAxisType, digit, labelMap, xAxisType, tooltipFormatter }) const xAxis = getLineXAxis({ dimension, rows, xAxisName, axisVisible, xAxisType }) const yAxis = getLineYAxis({ yAxisName, yAxisType, axisVisible, scale, min, max, digit }) const series = getLineSeries({ rows, axisSite, metrics, area, stack, nullAddZero, labelMap, label, itemStyle, lineStyle, areaStyle, xAxisType, dimension }) if (!xAxis || !series) return false let options = { legend, xAxis, series, yAxis, tooltip } return options }
JavaScript
0.999821
@@ -5582,47 +5582,8 @@ %7D)%0A - if (!xAxis %7C%7C !series) return false%0A%0A le
e298a5d350123de70fa1876738f36e1ff1b34218
remove unused check function
lib/6to5/transformation/transformers/spec-setters.js
lib/6to5/transformation/transformers/spec-setters.js
var check = function (node, file) { }; exports.MethodDefinition = exports.Property = function (node, parent, file) { if (node.kind === "set" && node.value.params.length !== 1) { throw file.errorWithNode(node.value, "Setters must have only one parameter"); } };
JavaScript
0.000001
@@ -1,44 +1,4 @@ -var check = function (node, file) %7B%0A%7D;%0A%0A expo
04433a091a0344f6d4475944c6210e4da77efbbd
Fix up config, default and watch tasks
gulpfile.js
gulpfile.js
var gulp = require('gulp'), htmlhint = require('gulp-htmlhint'), access = require('gulp-accessibility'), csslint = require('gulp-csslint'), concatcss = require('gulp-concat-css'), minifycss = require('gulp-minify-css'), sass = require('gulp-sass'), jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), rename = require('gulp-rename'); var config = { html: './*.html', csslint: ['./css/main.css', '!./css/h5bp.css', '!./css/src/normalize.css'], cssconcatandminify: ['./css/*.css'], sass: './sass/*.scss', js: ['./js/*.js', '!./js/*.min.js'] }; // HTML // hint gulp.task('html:hint', function() { return gulp.src(config.html) .pipe(htmlhint()) .pipe(htmlhint.reporter()) }); // accessibility gulp.task('html:accessibility', function() { return gulp.src('config.html') .pipe( access({accessibilityLevel: 'WCAG2AAA'}) ); }); // CSS // lint gulp.task('css:lint', function () { return gulp.src(config.csslint) .pipe(csslint()) .pipe(csslint.reporter()) }); // concat and minify gulp.task('css:concatandminify', function () { return gulp.src(config.cssconcatandminify) .pipe(concatcss('style.min.css')) .pipe(minifycss()) .pipe(gulp.dest('./css')); }); // Sass gulp.task('sass', function () { return gulp.src(config.sass) .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError)) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('./css')); }); // JavaScript // lint gulp.task('js:lint', function() { return gulp.src(config.js) .pipe(jshint()) .pipe(jshint.reporter('default')); }); // jscs gulp.task('js:jscs', function() { return gulp.src(config.js) // .pipe(jscs({fix: true})) .pipe(jscs()) .pipe(jscs.reporter()); // .pipe(gulp.dest('./js')) }); // uglify gulp.task('js:uglify', function() { return gulp.src(config.js) .pipe(concat('main.js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest('./js')); }); // lint all the things gulp.task('default', function() { gulp.watch('./*.html', ['html:hint', 'html:accessibility']); gulp.watch(['./css/*.css'], ['css:lint']); gulp.watch('./js/*.js', ['js:lint', 'js:jscs']); }); // build all the things gulp.task('build', ['css:concatandminify', 'sass', 'js:uglify']);
JavaScript
0
@@ -463,16 +463,54 @@ fig = %7B%0A + cssdest: './css',%0A jsdest: './js',%0A html: @@ -540,18 +540,35 @@ %5B'./css/ +*.css', '!./css/*. m -a in.css', @@ -599,12 +599,8 @@ css/ -src/ norm @@ -644,24 +644,44 @@ ./css/*.css' +, '!./css/*.min.css' %5D,%0A sass: ' @@ -733,16 +733,62 @@ min.js'%5D +,%0A cssdestname: 'style',%0A jsdestname: 'main' %0A%7D;%0A%0A// @@ -1366,22 +1366,31 @@ ncatcss( -'style +cssdestname + ' .min.css @@ -1428,39 +1428,46 @@ .pipe(gulp.dest( -'./css' +config.cssdest ));%0A%7D);%0A%0A// Sass @@ -1676,23 +1676,30 @@ lp.dest( -'./css' +config.cssdest ));%0A%7D);%0A @@ -2127,21 +2127,30 @@ (concat( -'main +jsdestname + ' .js'))%0A @@ -2240,22 +2240,29 @@ lp.dest( -'./js' +config.jsdest ));%0A%7D);%0A @@ -2305,16 +2305,119 @@ efault', +%0A %5B'html:hint',%0A 'html:accessibility',%0A 'css:lint',%0A 'js:lint',%0A 'js:jscs'%0A%5D);%0A%0Agulp.task('watch', functio @@ -2435,26 +2435,27 @@ p.watch( -'./* +config .html -' , %5B'html @@ -2503,23 +2503,22 @@ tch( -%5B'./css/*.css'%5D +config.csslint , %5B' @@ -2543,27 +2543,25 @@ p.watch( -'./js/* +config .js -' , %5B'js:l @@ -2584,16 +2584,17 @@ );%0A%7D);%0A%0A +%0A // build
2df2f677eb37b2326508a1cbe6ff957bd2219eec
manage results as object
tools/aceditor/presentation/javascripts/components/InputFormField.js
tools/aceditor/presentation/javascripts/components/InputFormField.js
// Text/Number/Color/slider export default { props: [ 'value', 'config', 'selectedForm' ], data() { return { fields: [] } }, mounted() { let initalValues = this.value ? this.value.split(',') : [this.config.default] this.fields = this.fieldOptions.filter((field) => initalValues.includes(field.id)) }, computed: { fieldOptions() { if (this.config.only == 'lists') return this.selectedForm.prepared.filter(a => (typeof a.options == 'object' && a.options !== null)) else return this.selectedForm.prepared } }, watch: { fields() { this.$emit('input', this.fields.map(f => f.id).join(',')) }, }, template: ` <div class="form-group" :class="config.type" :title="config.hint" > <label v-if="config.label" class="control-label">{{ config.label }}</label> <v-select v-if="config.multiple" v-model="fields" :options="fieldOptions" label="id" :multiple="true"> <template v-slot:option="option"> <span v-html="option.label"></span> - {{ option.id }} </template> </v-select> <select v-else :value="value" v-on:input="$emit('input', $event.target.value)" class="form-control"> <option value=""></option> <option v-for="field in fieldOptions" v-if="field.label" :value="field.id"> <span v-html="field.label"></span> - {{ field.id }} </option> </select> <input-hint :config="config"></input-hint> </div> ` }
JavaScript
0
@@ -400,16 +400,435 @@ lists')%0A + if (typeof this.selectedForm.prepared == 'object')%7B%0A let fields = %5B%5D;%0A for (let key in this.selectedForm.prepared) %7B%0A if (typeof this.selectedForm.prepared%5Bkey%5D.options == 'object' %0A && this.selectedForm.prepared%5Bkey%5D.options !== null)%7B%0A fields.push(this.selectedForm.prepared%5Bkey%5D)%0A %7D%0A %7D%0A return fields ;%0A %7D else %7B%0A @@ -927,16 +927,26 @@ null))%0A + %7D%0A el
f5d56452057ff49aa9f680e62fd14b728a5636f9
Disable overscrolling in menu.
src/Menu.js
src/Menu.js
import { merge } from './updates.js'; import * as symbols from './symbols.js'; import AriaMenuMixin from './AriaMenuMixin.js'; import ClickSelectionMixin from './ClickSelectionMixin.js'; import DirectionSelectionMixin from './DirectionSelectionMixin.js'; import FocusVisibleMixin from './FocusVisibleMixin.js'; import KeyboardDirectionMixin from './KeyboardDirectionMixin.js'; import KeyboardMixin from './KeyboardMixin.js'; import KeyboardPagedSelectionMixin from './KeyboardPagedSelectionMixin.js'; import KeyboardPrefixSelectionMixin from './KeyboardPrefixSelectionMixin.js'; import LanguageDirectionMixin from './LanguageDirectionMixin.js'; import ReactiveElement from './ReactiveElement.js'; import SelectedItemTextValueMixin from './SelectedItemTextValueMixin.js'; import SelectionInViewMixin from './SelectionInViewMixin.js'; import SingleSelectionMixin from './SingleSelectionMixin.js'; import SlotItemsMixin from './SlotItemsMixin.js'; const Base = AriaMenuMixin( ClickSelectionMixin( DirectionSelectionMixin( FocusVisibleMixin( KeyboardDirectionMixin( KeyboardMixin( KeyboardPagedSelectionMixin( KeyboardPrefixSelectionMixin( LanguageDirectionMixin( SelectedItemTextValueMixin( SelectionInViewMixin( SingleSelectionMixin( SlotItemsMixin( ReactiveElement ))))))))))))); /** * A menu of choices or commands. * * This holds the contents of the menu, not the top-level UI element that invokes * a menu. For that, see [MenuButton](MenuButton) or [PopupSource](PopupSource). * * @inherits ReactiveElement * @mixes AriaMenuMixin * @mixes ClickSelectionMixin * @mixes DirectionSelectionMixin * @mixes KeyboardDirectionMixin * @mixes KeyboardMixin * @mixes KeyboardPagedSelectionMixin * @mixes KeyboardPrefixSelectionMixin * @mixes LanguageDirectionMixin * @mixes SelectedItemTextValueMixin * @mixes SelectionInViewMixin * @mixes SingleSelectionMixin * @mixes SlotItemsMixin */ class Menu extends Base { componentDidMount() { if (super.componentDidMount) { super.componentDidMount(); } // Treat a pointerdown event as a click. if ('PointerEvent' in window) { // Prefer listening to standard pointer events. this.addEventListener('pointerdown', event => this[symbols.click](event)); } else { this.addEventListener('touchstart', event => this[symbols.click](event)); } } // Filter the set of items to ignore disabled items. itemsForState(state) { const base = super.itemsForState(state); return base ? base.filter((/** @type {any} */ item) => !item.disabled) : []; } itemUpdates(item, calcs, original) { const base = super.itemUpdates ? super.itemUpdates(item, calcs, original) : {}; const selected = calcs.selected; const color = selected ? 'highlighttext' : original.style.color; const backgroundColor = selected ? 'highlight' : original.style['background-color']; return merge(base, { classes: { selected }, style: { 'background-color': backgroundColor, color } }); } get [symbols.scrollTarget]() { return this.$.content; } get [symbols.template]() { return ` <style> :host { border: 1px solid gray; box-sizing: border-box; cursor: default; display: flex; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } #content { display: flex; flex: 1; flex-direction: column; overflow-x: hidden; overflow-y: auto; -webkit-overflow-scrolling: touch; /* for momentum scrolling */ } #content > ::slotted(*) { padding: 0.25em; } @media (pointer: coarse) { #content > ::slotted(*) { padding: 1em; } } #content > ::slotted(option) { font-weight: inherit; min-height: inherit; } </style> <div id="content" role="none"> <slot></slot> </div> `; } get updates() { return merge(super.updates, { style: { 'touch-action': 'manipulation' } }); } } export default Menu; customElements.define('elix-menu', Menu);
JavaScript
0
@@ -3639,16 +3639,56 @@ ling */%0A + overscroll-behavior: contain;%0A