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
|
---|---|---|---|---|---|---|---|
d9ec2d1398102ce70ef897b02848b057daf3de0f | add table | public/javascripts/mosura/app.js | public/javascripts/mosura/app.js | angular.module('mosura', ['ngRoute', 'ngResource', 'ngCookies']);
angular.module('mosura').controller('mainController', function ($scope, $resource, $cookieStore) {
var issuesResource = $resource('/jira/issues/:status');
$scope.data = {};
$scope.columns = [];
function loadColumns() {
$resource('/config/columns').query().$promise.then(function (targetColumns) {
targetColumns.forEach(function (column) {
$scope.columns[column.order] = column;
column.data = issuesResource.get({ status: column.status });
});
});
}
$scope.jira = $cookieStore.get('jira') || {};
if ($scope.jira.username && $scope.jira.password && $scope.jira.baseUrl && $scope.jira.component) {
$scope.allGood = true;
loadColumns();
}
$scope.updateCookie = function () {
$cookieStore.put('jira', $scope.jira);
$scope.allGood = true;
loadColumns();
};
}); | JavaScript | 0.000042 | @@ -284,24 +284,272 @@
Columns() %7B%0A
+ $scope.allGood = true;%0A console.table(%5B%0A %5B'username', $scope.jira.username%5D,%0A %5B'password', 'password for ' + $scope.jira.username + ' ;)'%5D,%0A %5B'baseUrl', $scope.jira.baseUrl%5D,%0A %5B'component', $scope.jira.component%5D%0A %5D);%0A
$resourc
@@ -960,35 +960,8 @@
) %7B%0A
- $scope.allGood = true;%0A
@@ -1065,35 +1065,8 @@
a);%0A
- $scope.allGood = true;%0A
|
45d7497765ae04b7b115156d4ecfd4011223f3b1 | add clean task | gulpfile.js | gulpfile.js | /*jshint node:true*/
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var dest = 'extension';
var base = {base: 'src/'};
gulp.task('copy', () => gulp.src([
'src/manifest.json',
'src/icon_128.jpg',
'src/*.css'], base)
.pipe(gulp.dest(dest)));
gulp.task('html', () => gulp.src('src/*.html', base)
.pipe($.htmlReplace({js: 'lib.js'}))
.pipe(gulp.dest(dest)));
gulp.task('js', () => gulp.src('src/*.js', base)
.pipe($.ngAnnotate())
.pipe($.uglify())
.pipe(gulp.dest(dest)));
gulp.task('lib', () => gulp.src('src/templates/*.html', base)
.pipe($.angularTemplatecache())
.pipe(gulp.src('src/common/*.js'))
.pipe($.ngAnnotate())
.pipe($.uglify())
.pipe(gulp.src(['src/bower/angular/angular.min.js',
'src/bower/lodash/lodash.min.js']))
.pipe($.concat('lib.js'))
.pipe(gulp.dest(dest)));
gulp.task('default', ['copy', 'html', 'js', 'lib']);
| JavaScript | 0.999918 | @@ -932,8 +932,57 @@
lib'%5D);%0A
+%0Agulp.task('clean', () =%3E require('del')(dest));%0A
|
c6f06826674d5e46fe41a11d223000efc1009618 | Fix webpack tasks for mattermost.js | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var prettify = require('gulp-jsbeautifier');
var babel = require('gulp-babel');
var webpack = require('webpack-stream');
var named = require('vinyl-named');
var changed = require('gulp-changed');
var esformatter = require('gulp-esformatter');
var del = require('del');
var electron = require('electron-connect').server.create({
path: './dist'
});
var packager = require('electron-packager');
var sources = ['**/*.js', '**/*.css', '**/*.html', '!**/node_modules/**', '!**/build/**', '!release/**'];
gulp.task('prettify', ['prettify:sources', 'prettify:jsx']);
gulp.task('prettify:sources', ['sync-meta'], function() {
return gulp.src(sources)
.pipe(prettify({
html: {
indentSize: 2
},
css: {
indentSize: 2
},
js: {
indentSize: 2,
braceStyle: "end-expand"
}
}))
.pipe(gulp.dest('.'));
});
gulp.task('prettify:jsx', function() {
return gulp.src('src/browser/**/*.jsx')
.pipe(esformatter({
indent: {
value: ' '
},
plugins: ['esformatter-jsx']
}))
.pipe(gulp.dest('src/browser'));
});
gulp.task('build', ['sync-meta', 'webpack', 'copy'], function() {
return gulp.src('src/package.json')
.pipe(gulp.dest('dist'));
});
gulp.task('webpack', ['webpack:main', 'webpack:browser']);
gulp.task('webpack:browser', function() {
return gulp.src('src/browser/**/*.jsx')
.pipe(named())
.pipe(webpack({
module: {
loaders: [{
test: /\.json$/,
loader: 'json'
}, {
test: /\.jsx$/,
loader: 'babel',
query: {
presets: ['react']
}
}]
},
output: {
filename: '[name].js'
},
node: {
__filename: false,
__dirname: false
},
target: 'electron'
}))
.pipe(gulp.dest('dist/browser/'));
});
gulp.task('webpack:main', function() {
return gulp.src('src/main.js')
.pipe(webpack({
module: {
loaders: [{
test: /\.json$/,
loader: 'json'
}]
},
output: {
filename: '[name].js'
},
node: {
__filename: false,
__dirname: false
},
target: 'electron'
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('copy', ['copy:resources', 'copy:html/css', 'copy:webview:js', 'copy:modules']);
gulp.task('copy:resources', function() {
return gulp.src('src/resources/**')
.pipe(gulp.dest('dist/resources'));
});
gulp.task('copy:html/css', function() {
return gulp.src(['src/browser/**/*.html', 'src/browser/**/*.css'])
.pipe(gulp.dest('dist/browser'));
});
gulp.task('copy:webview:js', function() {
return gulp.src(['src/browser/webview/**/*.js'])
.pipe(gulp.dest('dist/browser/webview'))
});
gulp.task('copy:modules', function() {
return gulp.src(['src/node_modules/bootstrap/dist/**'])
.pipe(gulp.dest('dist/browser/modules/bootstrap'))
});
gulp.task('watch', ['build'], function() {
var options = ['--livereload'];
electron.start(options);
gulp.watch(['src/main.js', 'src/main/**/*.js', 'src/common/**/*.js'], ['webpack:main']);
gulp.watch(['src/browser/**/*.js', 'src/browser/**/*.jsx'], ['webpack:browser', 'copy:webview:js']);
gulp.watch(['src/browser/**/*.css', 'src/browser/**/*.html', 'src/resources/**/*.png'], ['copy']);
gulp.watch(['dist/main.js', 'dist/resources/**'], function() {
electron.restart(options);
});
gulp.watch(['dist/browser/*.js'], electron.reload);
});
function makePackage(platform, arch, callback) {
var packageJson = require('./src/package.json');
packager({
dir: './dist',
name: packageJson.name,
platform: platform,
arch: arch,
version: require('./package.json').devDependencies['electron-prebuilt'],
out: './release',
prune: true,
overwrite: true,
"app-version": packageJson.version,
icon: 'resources/electron-mattermost',
"version-string": {
CompanyName: packageJson.author,
LegalCopyright: 'Copyright (c) 2015 ' + packageJson.author,
FileDescription: packageJson.name,
OriginalFilename: packageJson.name + '.exe',
ProductVersion: packageJson.version,
ProductName: packageJson.name,
InternalName: packageJson.name
}
}, function(err, appPath) {
if (err) {
callback(err);
}
else {
callback();
}
});
};
gulp.task('package', ['build'], function(cb) {
makePackage(process.platform, 'all', cb);
});
gulp.task('package:all', ['build'], function(cb) {
makePackage('all', 'all', cb);
});
gulp.task('package:windows', ['build'], function(cb) {
makePackage('win32', 'all', cb);
});
gulp.task('package:osx', ['build'], function(cb) {
makePackage('darwin', 'all', cb);
});
gulp.task('package:linux', ['build'], function(cb) {
makePackage('linux', 'all', cb);
});
gulp.task('sync-meta', function() {
var appPackageJson = require('./src/package.json');
var packageJson = require('./package.json');
appPackageJson.name = packageJson.name;
appPackageJson.version = packageJson.version;
appPackageJson.description = packageJson.description;
appPackageJson.author = packageJson.author;
appPackageJson.license = packageJson.license;
var fs = require('fs');
fs.writeFileSync('./src/package.json', JSON.stringify(appPackageJson, null, ' ') + '\n');
});
| JavaScript | 0 | @@ -1340,20 +1340,39 @@
browser'
+, 'webpack:webview'
%5D);%0A
-
%0Agulp.ta
@@ -2321,32 +2321,306 @@
'dist/'));%0A%7D);%0A%0A
+gulp.task('webpack:webview', function() %7B%0A return gulp.src('src/browser/webview/mattermost.js')%0A .pipe(named())%0A .pipe(webpack(%7B%0A output: %7B%0A filename: '%5Bname%5D.js'%0A %7D,%0A target: 'electron'%0A %7D))%0A .pipe(gulp.dest('dist/browser/webview'))%0A%7D);%0A%0A
gulp.task('copy'
@@ -2660,27 +2660,8 @@
ss',
- 'copy:webview:js',
'co
@@ -2956,151 +2956,8 @@
);%0A%0A
-gulp.task('copy:webview:js', function() %7B%0A return gulp.src(%5B'src/browser/webview/**/*.js'%5D)%0A .pipe(gulp.dest('dist/browser/webview'))%0A%7D);%0A%0A
gulp
@@ -3392,20 +3392,23 @@
', '
-copy
+webpack
:webview
:js'
@@ -3403,19 +3403,16 @@
:webview
-:js
'%5D);%0A g
|
34e17cfad586f44e0b02c540a9aca23ceaec6607 | update initialParams import to match project style | mocha_test/initialParams.js | mocha_test/initialParams.js | var initialParams = require('../lib/internal/initialParams');
var expect = require('chai').expect;
describe('initialParams', function() {
it('should curry any bound context to the wrapped function', function() {
var passContext = function(args, cb) {
cb(this);
};
// call bind after wrapping with initialParams
var contextOne = {context: "one"};
var postBind = initialParams.default(passContext);
postBind = postBind.bind(contextOne);
postBind([], function(ref) {
expect(ref).to.equal(contextOne);
});
// call bind before wrapping with initialParams
var contextTwo = {context: "two"};
var preBind = passContext.bind(contextTwo);
preBind = initialParams.default(preBind);
preBind([], function(ref) {
expect(ref).to.equal(contextTwo);
});
});
});
| JavaScript | 0 | @@ -1,11 +1,14 @@
-var
+import
initial
@@ -14,26 +14,21 @@
lParams
-= require(
+from
'../lib/
@@ -50,17 +50,16 @@
lParams'
-)
;%0D%0Avar e
@@ -405,24 +405,16 @@
alParams
-.default
(passCon
@@ -688,24 +688,24 @@
ntextTwo);%0D%0A
+
preBind
@@ -723,16 +723,8 @@
rams
-.default
(pre
|
420a6747492d2b07f3fbf06b92c1ab603936c149 | build error fix (reverting backend to es5) | gulpfile.js | gulpfile.js | var ts = require('gulp-typescript');
var gulp = require('gulp');
var zip = require('gulp-zip');
var runSequence = require('run-sequence');
var jsonModify = require('gulp-json-modify');
var exec = require('child_process').exec;
var tsBackendProject = ts.createProject('backend/tsconfig.json');
gulp.task('build-backend', function () {
return gulp.src([
"common/**/*.ts",
"backend/**/*.ts"], {base: "."})
.pipe(tsBackendProject())
.js
.pipe(gulp.dest("./release"))
});
gulp.task('build-frontend', function (cb) {
exec("ng build -prod --output-path=./release/dist --no-progress", function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('copy-static', function () {
return gulp.src([
"README.md",
"LICENSE"], {base: "."})
.pipe(gulp.dest('./release'));
});
gulp.task('copy-package', function () {
return gulp.src([
"package.json"], {base: "."})
.pipe(jsonModify({
key: 'devDependencies',
value: {}
}))
.pipe(jsonModify({
key: 'scripts',
value: {"start": "node ./backend/index.js"}
}))
.pipe(gulp.dest('./release'));
});
gulp.task('zip-release', function () {
return gulp.src(['release/**/*'], {base: "./release"})
.pipe(zip('pigallery2.zip'))
.pipe(gulp.dest('.'));
});
gulp.task('build-release', function (done) {
runSequence('build-frontend', 'build-backend', 'copy-static', 'copy-package', 'zip-release', function () {
done();
});
});
| JavaScript | 0 | @@ -262,24 +262,16 @@
roject('
-backend/
tsconfig
|
7f0be18f4dd04923232092bb9ed31c303304d27c | update gulpfile | gulpfile.js | gulpfile.js | var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
// Load all gulp plugins automatically
// and attach them to the `plugins` object
var plugins = require('gulp-load-plugins')();
// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
var uglify = require('gulp-uglify');
var pump = require('pump');
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath).mode
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
]).then(function () {
done();
});
});
gulp.task('copy', [
'copy:.htaccess',
'copy:jquery',
'copy:bootstrap-css',
'copy:bootstrap-js',
'copy:bootstrap-fonts',
'copy:license',
'copy:css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:bootstrap-css', function () {
return gulp.src(['node_modules/bootstrap/dist/css/bootstrap.min.css'])
.pipe(gulp.dest(dirs.dist + '/js/vendor/bootstrap/css'));
});
gulp.task('copy:bootstrap-js', function () {
return gulp.src(['node_modules/bootstrap/dist/js/bootstrap.js'])
.pipe(uglify())
.pipe(plugins.rename('bootstrap.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor/bootstrap/js'));
});
gulp.task('copy:bootstrap-fonts', function () {
return gulp.src(['node_modules/bootstrap/dist/fonts/*'])
.pipe(gulp.dest(dirs.dist + '/js/vendor/bootstrap/fonts'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/**/*.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/**/*.css',
'!' + dirs.src + '/js/**/*.js'
], {
// Include hidden files by default
dot: true
})
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
]).pipe(plugins.jscs())
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
gulp.task('compress', function (cb) {
pump([
gulp.src(dirs.src + '/js/**/*.js'),
uglify(),
gulp.dest(dirs.dist + "/js")
],
cb
);
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js', 'compress'],
'copy',
done);
});
gulp.task('default', ['build']);
| JavaScript | 0.000001 | @@ -5473,17 +5473,26 @@
lint:js'
-,
+%5D,%0A
'compre
@@ -5494,17 +5494,16 @@
ompress'
-%5D
,%0A
|
761a67c25e59eec487b6609f0e515a5eb3e9fbd0 | Remove unused variables | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var browserify = require('gulp-browserify');
var jade = require('gulp-jade');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var browserSync = require('browser-sync').create();
var dist = './dist';
var src = './src';
// default task
gulp.task('default', ['browser-sync', 'jade', 'sass', 'css', 'fonts', 'js'], function () {
gulp.watch('src/jade/*.jade', ['jade', 'reload']);
gulp.watch('src/css/*.scss', ['sass', 'css', 'reload']);
gulp.watch('src/js/*.js', ['js', 'reload']);
});
// sync browser
gulp.task('browser-sync', function() {
browserSync.init({
port: 8080,
server: {
baseDir: 'dist',
index: 'popup.html'
}
});
});
// reload browser
gulp.task('reload', function () {
browserSync.reload();
});
// convert jade to html
gulp.task('jade', function() {
gulp.src('src/jade/*.jade')
.pipe(jade())
.pipe(gulp.dest('dist'));
});
// convert sass to css
gulp.task('sass', function() {
gulp.src('src/css/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('src/css'));
});
// minify and concat css
gulp.task('css', function() {
gulp.src([
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/bootflat/bootflat/css/bootflat.min.css',
'src/css/style.css'
])
.pipe(minifyCss())
.pipe(concat('app.css'))
.pipe(gulp.dest('dist/css'));
});
// copy fonts into dist/fonts
gulp.task('fonts', function() {
gulp.src('node_modules/bootstrap/dist/fonts/**')
.pipe(gulp.dest('dist/fonts'));
});
// minify and concat js
gulp.task('js', function() {
gulp.src([
'node_modules/bootflat/js/jquery-1.10.1.min.js',
'node_modules/bootstrap/js/transition.js',
'node_modules/bootstrap/js/tab.js'
])
.pipe(uglify({
preserveComments: 'license'
}))
.pipe(concat('app.js'))
.pipe(gulp.dest('dist/js'));
});
// convert and minify and distribution into dist
| JavaScript | 0.000007 | @@ -383,50 +383,8 @@
);%0A%0A
-var dist = './dist';%0Avar src = './src';%0A%0A
// d
|
5d0bc22aa1c2c936954503207e6a6b7e1c5bbdc7 | update sass-compilation task to unclude postcss | gulpfile.js | gulpfile.js | /******************************************************
* PATTERN LAB NODE
* EDITION-NODE-GULP
* The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
var gulp = require('gulp'),
path = require('path'),
browserSync = require('browser-sync').create(),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
argv = require('minimist')(process.argv.slice(2));
/******************************************************
* COPY TASKS - stream assets from source to destination
******************************************************/
// JS copy
gulp.task('pl-copy:js', function(){
return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} )
.pipe(gulp.dest(path.resolve(paths().public.js)));
});
// Images copy
gulp.task('pl-copy:img', function(){
return gulp.src('**/*.*',{cwd: path.resolve(paths().source.images)} )
.pipe(gulp.dest(path.resolve(paths().public.images)));
});
// Favicon copy
gulp.task('pl-copy:favicon', function(){
return gulp.src('favicon.ico', {cwd: path.resolve(paths().source.root)} )
.pipe(gulp.dest(path.resolve(paths().public.root)));
});
// Fonts copy
gulp.task('pl-copy:font', function(){
return gulp.src('*', {cwd: path.resolve(paths().source.fonts)})
.pipe(gulp.dest(path.resolve(paths().public.fonts)));
});
// SASS Compilation
gulp.task('pl-sass', function(){
return gulp.src(path.resolve(paths().source.sass, '**/*.scss'))
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(path.resolve(paths().source.css)));
});
// CSS Copy
gulp.task('pl-copy:css', function(){
return gulp.src(path.resolve(paths().source.css, '*.css'))
.pipe(gulp.dest(path.resolve(paths().public.css)))
.pipe(browserSync.stream());
});
// Styleguide Copy everything but css
gulp.task('pl-copy:styleguide', function(){
return gulp.src(path.resolve(paths().source.styleguide, '**/!(*.css)'))
.pipe(gulp.dest(path.resolve(paths().public.root)))
.pipe(browserSync.stream());
});
// Styleguide Copy and flatten css
gulp.task('pl-copy:styleguide-css', function(){
return gulp.src(path.resolve(paths().source.styleguide, '**/*.css'))
.pipe(gulp.dest(function(file){
//flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
file.path = path.join(file.base, path.basename(file.path));
return path.resolve(path.join(paths().public.styleguide, 'css'));
}))
.pipe(browserSync.stream());
});
/******************************************************
* PATTERN LAB CONFIGURATION - API with core library
******************************************************/
//read all paths from our namespaced config file
var config = require('./patternlab-config.json'),
patternlab = require('patternlab-node')(config);
function paths() {
return config.paths;
}
function getConfiguredCleanOption() {
return config.cleanPublic;
}
function build(done) {
patternlab.build(done, getConfiguredCleanOption());
}
gulp.task('pl-assets', gulp.series(
gulp.parallel(
'pl-copy:js',
'pl-copy:img',
'pl-copy:favicon',
'pl-copy:font',
gulp.series('pl-sass', 'pl-copy:css', function(done){done();}),
'pl-copy:styleguide',
'pl-copy:styleguide-css'
),
function(done){
done();
})
);
gulp.task('patternlab:version', function (done) {
patternlab.version();
done();
});
gulp.task('patternlab:help', function (done) {
patternlab.help();
done();
});
gulp.task('patternlab:patternsonly', function (done) {
patternlab.patternsonly(done, getConfiguredCleanOption());
});
gulp.task('patternlab:liststarterkits', function (done) {
patternlab.liststarterkits();
done();
});
gulp.task('patternlab:loadstarterkit', function (done) {
patternlab.loadstarterkit(argv.kit, argv.clean);
done();
});
gulp.task('patternlab:build', gulp.series('pl-assets', build, function(done){
done();
}));
/******************************************************
* SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
return getSupportedTemplateExtensions().map(function (dotExtension) {
return path.resolve(paths().source.patterns, '**/*' + dotExtension);
});
}
function reload() {
browserSync.reload();
}
function watch() {
gulp.watch(path.resolve(paths().source.sass, '**/*.scss')).on('change', gulp.series('pl-sass'));
gulp.watch(path.resolve(paths().source.css, '**/*.css')).on('change', gulp.series('pl-copy:css', reload));
gulp.watch(path.resolve(paths().source.styleguide, '**/*.*')).on('change', gulp.series('pl-copy:styleguide', 'pl-copy:styleguide-css', reload));
var patternWatches = [
path.resolve(paths().source.patterns, '**/*.json'),
path.resolve(paths().source.patterns, '**/*.md'),
path.resolve(paths().source.data, '*.json'),
path.resolve(paths().source.fonts + '/*'),
path.resolve(paths().source.images + '/*'),
path.resolve(paths().source.meta, '*'),
path.resolve(paths().source.annotations + '/*')
].concat(getTemplateWatches());
gulp.watch(patternWatches).on('change', gulp.series(build, reload));
}
gulp.task('patternlab:connect', gulp.series(function(done) {
browserSync.init({
server: {
baseDir: path.resolve(paths().public.root)
},
snippetOptions: {
// Ignore all HTML files within the templates folder
blacklist: ['/index.html', '/', '/?*']
},
notify: {
styles: [
'display: none',
'padding: 15px',
'font-family: sans-serif',
'position: fixed',
'font-size: 1em',
'z-index: 9999',
'bottom: 0px',
'right: 0px',
'border-top-left-radius: 5px',
'background-color: #1B2032',
'opacity: 0.4',
'margin: 0',
'color: white',
'text-align: center'
]
}
}, function(){
console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
});
done();
}));
/******************************************************
* COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));
| JavaScript | 0.000601 | @@ -1582,16 +1582,38 @@
Error))%0A
+ .pipe(postcss()),%0A
.pip
|
7ffd3a9a4f0aa3229dcc1127bdec3ec2d93b3ba6 | Tweak theme banner | gulpfile.js | gulpfile.js | 'use strict';
// Dependencies
var gulp = require('gulp');
var del = require('del');
var gutil = require('gulp-util');
var zip = require('gulp-zip');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
var sourcemaps = require('gulp-sourcemaps');
var runSequence = require('run-sequence');
var banner = {
theme:
'/* \n' +
'Theme Name: KAP Correspondence Child Theme \n' +
'Theme URI: \n' +
'Description: Twenty Fifteen Child Theme \n' +
'Author: Trevor Muñoz \n' +
'Author URI: http://www.trevormunoz.com \n' +
'Template: twentyfifteen \n' +
'Version: 0.1.0 \n' +
'License: MIT \n' +
'License URI: http://opensource.org/licenses/MIT \n' +
'Tags: minimal, backbonejs \n' +
'Text Domain: kap-twenty-fifteen-child \n' +
'*/ \n\n'
};
gulp.task('clean', function(callback) {
return del(['./dist', './kap-twenty-fifteen-child.zip'], callback);
});
gulp.task('build:css', function() {
return gulp.src('src/scss/**/*.scss')
.pipe(sass().on('error', gutil.log))
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(header(banner.theme))
.pipe(gulp.dest('dist/'));
});
gulp.task('typography', function() {
return gulp.src(['src/js/typography.js'])
.pipe(gulp.dest('dist/js'));
});
gulp.task('build:es6', function() {
return browserify({
entries: './src/js/main.js',
debug: true
})
.transform(babelify)
.bundle()
.pipe(source('kap.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(rename('kap.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('zip', function() {
return gulp.src(['dist/**/*', 'src/**/*.php', 'src/**/*.png'])
.pipe(zip('kap-twenty-fifteen-child.zip'))
.pipe(gulp.dest('./'));
});
gulp.task('default', function(callback) {
return runSequence(
'clean',
['build:css', 'typography', 'build:es6'],
'zip',
callback
);
});
| JavaScript | 0 | @@ -1037,53 +1037,8 @@
' +%0A
- 'Tags: minimal, backbonejs %5Cn' +%0A
|
bc42bd9f81d58a9eaba8ad133f220a87da108dbe | add initial gulp-mocha support | gulpfile.js | gulpfile.js | /**
*
* Material Design Styleguide
* 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
*
* https://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';
// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var fs = require('fs');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
// Lint JavaScript
// TODO: Fix linting
gulp.task('jshint', function () {
return gulp.src('src/**/*.js')
.pipe(reload({stream: true, once: true}))
//.pipe($.jshint())
//.pipe($.jshint.reporter('jshint-stylish'))
//.pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});
// Optimize Images
// TODO: Update image paths in final CSS to match root/images
gulp.task('images', function () {
return gulp.src('src/**/*.{svg,png,jpg}')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('./images'))
.pipe($.size({title: 'images'}));
});
// Compile and Automatically Prefix Stylesheets (dev)
gulp.task('styles:dev', function () {
return gulp.src([
'src/**/**/*.scss'
])
.pipe($.changed('.tmp/styles', {extension: '.css'}))
.pipe($.sass({
precision: 10,
onError: console.error.bind(console, 'Sass error:')
}))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('.tmp/styles'))
.pipe($.size({title: 'styles'}));
});
// Compile and Automatically Prefix Stylesheets (production)
gulp.task('styles', function () {
// For best performance, don't add Sass partials to `gulp.src`
return gulp.src([
'src/styleguide.scss'
])
//.pipe($.changed('.tmp/styles', {extension: '.css'}))
.pipe($.sass({
precision: 10,
onError: console.error.bind(console, 'Sass error:')
}))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('.tmp'))
// Concatenate Styles
.pipe($.concat('material.css'))
.pipe($.header(banner, {pkg: pkg}))
.pipe(gulp.dest('./css'))
// Minify Styles
.pipe($.if('*.css', $.csso()))
.pipe($.concat('material.min.css'))
//.pipe($.header(banner, {pkg: pkg}))
.pipe(gulp.dest('./css'))
.pipe($.size({title: 'styles'}));
});
// Concatenate And Minify JavaScript
gulp.task('scripts', function () {
var sources = [
// Component handler
'src/wskComponentHandler.js',
// Polyfills/dependencies
'src/third_party/**/*.js',
// Base components
'src/animation/animation.js',
'src/button/button.js',
'src/checkbox/checkbox.js',
'src/column-layout/column-layout.js',
'src/icon-toggle/icon-toggle.js',
'src/item/item.js',
'src/radio/radio.js',
'src/slider/slider.js',
'src/spinner/spinner.js',
'src/switch/switch.js',
'src/tabs/tabs.js',
'src/textfield/textfield.js',
'src/tooltip/tooltip.js',
// Complex components (which reuse base components)
'src/layout/layout.js',
// And finally, the ripples
'src/ripple/ripple.js'
];
return gulp.src(sources)
.pipe($.sourcemaps.init())
// Concatenate Scripts
.pipe($.concat('material.js'))
.pipe($.header(banner, {pkg: pkg}))
.pipe(gulp.dest('./js'))
// Minify Scripts
.pipe($.uglify({preserveComments: 'some', sourceRoot: '.', sourceMapIncludeSources: true}))
.pipe($.concat('material.min.js'))
// Write Source Maps
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('./js'))
.pipe($.size({title: 'scripts'}));
});
// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'css/*', 'js/*', '!dist/.git'], {dot: true}));
// Watch Files For Changes & Reload
gulp.task('serve', ['styles:dev'], function () {
browserSync({
notify: false,
// Customize the BrowserSync console logging prefix
logPrefix: 'WSK',
server: ['.tmp', 'src', '.tmp/styles']
});
gulp.watch(['src/**/**/**/*.html'], reload);
gulp.watch(['src/**/**/*.{scss,css}'], ['styles:dev', reload]);
gulp.watch(['src/**/*.js'], ['jshint']);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
browserSync({
notify: false,
logPrefix: 'WSK',
server: './',
baseDir: "src"
});
});
// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
runSequence(
'styles',
['jshint', 'scripts', 'images'],
cb);
});
| JavaScript | 0 | @@ -4492,24 +4492,167 @@
s'%7D));%0A%7D);%0A%0A
+// Run Unit Tests%0Agulp.task('mocha', function () %7B%0A return gulp.src('./test/*.js', %7B read: false %7D)%0A .pipe(mocha(%7Breporter: 'list'%7D))%0A%7D);%0A%0A
// Clean Out
|
2bf1daca6f4496d00d8865ee30265bb3398bf20a | add comment | gulpfile.js | gulpfile.js | /*global require */
var pkg = require('./package.json'),
gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
merge = require('event-stream').merge,
del = require('del');
var jshint_options = require('jshint/src/cli').loadConfig('.jshintrc');
delete jshint_options.dirname;
$.banner = function() {
return $.header([
'/**',
' * <%= pkg.title %> v<%= pkg.version %>',
' * <%= pkg.homepage %>',
' *',
' * Copyright 2014 <%= pkg.author.name %>',
' * Released under the MIT license',
' * <%= pkg.homepage %>/blob/master/LICENSE',
' *',
' * Date: <%= $.util.date("isoUtcDateTime") %>',
' */',
''].join('\n'),
{ 'pkg': pkg, '$': $ }
);
};
$.minBanner = function() {
return $.header([
'/*!',
' * <%= pkg.title %> v<%= pkg.version %>',
' * (c) 2014 <%= pkg.author.name %>',
' * MIT license',
' */',
''].join('\n'),
{ 'pkg': pkg, '$': $ }
);
};
$.enableDebug = function() {
return $.replace(
/^\/\*\s*(?:DEBUG|END).*?\*\/\n/gm, ''
);
};
$.disableDebug = function() {
return $.replace(
/^\/\*\s*DEBUG.*?\*\/[\s\S]*?^\/\*\s*END.*?\*\/\n/gm, ''
);
};
gulp.task('default', function() {
gulp.watch('src/forceAsync.js', ['jshint']);
gulp.watch('src/forceAsync.html', ['htmlhint']);
});
gulp.task('clean', function(cb) {
del('dist/*', cb);
});
gulp.task('build', ['clean'], function() {
return merge(
// make debug.js
gulp.src('src/forceAsync.js')
.pipe($.rename({basename: pkg.name, suffix: '.debug'}))
.pipe($.banner())
.pipe($.enableDebug())
.pipe(gulp.dest('dist')),
// make js & min.js & source map
gulp.src('src/forceAsync.js')
.pipe($.rename({basename: pkg.name}))
.pipe($.banner())
.pipe($.disableDebug())
.pipe(gulp.dest('dist'))
.pipe($.rename({suffix: '.min'}))
.pipe($.sourcemaps.init())
.pipe($.minBanner())
.pipe($.uglify({preserveComments: 'some'}))
.pipe($.sourcemaps.write('./', {includeContent: false}))
.pipe(gulp.dest('dist')),
gulp.src('src/forceAsync.html')
.pipe($.htmlmin({
collapseWhitespace: true,
removeAttributeQuotes: true,
removeOptionalTags: true,
minifyJS: true
}))
.pipe(gulp.dest('dist'))
);
});
gulp.task('jshint', function() {
return gulp.src('src/forceAsync.js')
.pipe($.jshint(jshint_options))
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('htmlhint', function() {
return gulp.src('src/forceAsync.html')
.pipe($.htmlhint({jshint: jshint_options}))
.pipe($.htmlhint.reporter());
});
gulp.task('lint', ['jshint', 'htmlhint']);
| JavaScript | 0 | @@ -1,10 +1,11 @@
/*
+
global r
@@ -2276,32 +2276,53 @@
.dest('dist')),%0A
+ // make html%0A
gulp.src
|
908ca0747fefaf1180959355646bb46c3d4c4770 | Create a task to remove the anonymous parallel task in the console | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var connect = require('gulp-connect');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var pug = require('gulp-pug'); // formerly Jade
var del = require('del');
var path = require('path');
var git = require('simple-git');
// Configuration
// =============================================================================
// This is where the source code is stored.
const SOURCE_DIR = 'src'
const BUILD_DIR = 'build'
// Used for retrieving files/folders in the source directory.
function src(f) {
return path.join(SOURCE_DIR, f);
}
var locals = {
site: {
title: 'David Minnerly',
url: 'http://davidminnerly.com'
}
}
// Paths to the files that need to be compiled.
var paths = {
css: src('css'),
img: src('img'),
js: src('js'),
// Static files that don't require pre-processing. They're simply moved when
// building the site.
static: [
src('favicon.ico')
]
}
// Remote repositories for deploying the site. These can only be pushed to with
// proper authorization.
var remotes = {
staging: 'ssh://git@davidminnerly.com/~/beta.davidminnerly.git',
production: 'ssh://git@davidminnerly.com/~/davidminnerly.git'
}
// Compiling
// =============================================================================
function clean(done) {
return del(BUILD_DIR, done);
}
function styles() {
return gulp.src(path.join(paths.css, 'main.scss'), { base: SOURCE_DIR })
.pipe(plumber())
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest(BUILD_DIR));
}
function images() {
return gulp.src(path.join(paths.img, '**'), { base: SOURCE_DIR })
.pipe(gulp.dest(BUILD_DIR));
}
function scripts() {
return gulp.src(path.join(paths.js, '**'), { base: SOURCE_DIR })
.pipe(plumber())
.pipe(gulp.dest(BUILD_DIR));
}
function templates() {
return gulp.src(path.join(SOURCE_DIR, '*.pug'))
.pipe(plumber())
.pipe(pug({
locals: locals
}))
.pipe(gulp.dest(BUILD_DIR));
}
// Moving files that aren't processed by the above tasks.
function move() {
return gulp.src(paths.static)
.pipe(gulp.dest(BUILD_DIR));
}
gulp.task('compile', gulp.parallel(move, templates, styles, images, scripts));
gulp.task('build', gulp.series(clean, 'compile'));
// Development
// =============================================================================
function server() {
connect.server({
root: BUILD_DIR
});
}
function watch(done) {
// All watched tasks should include `.pipe(plumber())` at the beginning of the
// stream. This prevents you from having to rerun tasks if an error occurs.
//
// Very helpful when working with Sass. If you mess up a variable name or
// @import path, everything is still running fine.
gulp.watch(paths.static, move);
// Gets all Sass files, even the ones in bower_components.
gulp.watch(src('**/*.scss'), styles);
gulp.watch(path.join(paths.img, '**'), images);
gulp.watch(path.join(paths.js, '**'), scripts);
gulp.watch(src('**/*.pug'), templates);
done()
}
gulp.task('serve', gulp.series('build', gulp.parallel(server, watch)))
// Deployment
// =============================================================================
var buildRepo = git(BUILD_DIR)
function makeRelease(done) {
buildRepo
.init()
.add('.')
.commit('Release');
done()
}
function setupRemote(remote) {
buildRepo.addRemote('origin', remote)
}
function setupStaging(done) {
setupRemote(remotes.staging)
done()
}
function setupProduction(done) {
setupRemotes(remotes.production)
done()
}
function push(done) {
buildRepo.push(['-f', 'origin', 'master']);
done()
}
gulp.task('deploy:setup', gulp.series('build', makeRelease));
gulp.task('deploy:staging', gulp.series('deploy:setup', setupStaging, push));
gulp.task('deploy:prod', gulp.series('deploy:setup', setupProduction, push));
gulp.task('deploy', gulp.parallel('deploy:staging'));
// Default
// =============================================================================
gulp.task('default', gulp.parallel('serve'));
| JavaScript | 0.000219 | @@ -3070,34 +3070,15 @@
sk('
-serve', gulp.series('build
+connect
', g
@@ -3105,17 +3105,70 @@
watch))
-)
+;%0Agulp.task('serve', gulp.series('build', 'connect'));
%0A%0A%0A// De
|
39c5375c4ea69af6d1719d3c5911ad0f4f7e1f4e | fix hot reload hotOnly set to true | config/webpack/development.js | config/webpack/development.js | // Note: You must restart bin/webpack-dev-server for changes to take effect
const merge = require('webpack-merge');
const sharedConfig = require('./shared.js');
const { settings, output } = require('./configuration.js');
module.exports = merge(sharedConfig, {
devtool: '#eval-source-map',
stats: {
errorDetails: true
},
output: {
pathinfo: true
},
devServer: {
clientLogLevel: 'none',
https: settings.dev_server.https,
host: settings.dev_server.host,
port: settings.dev_server.port,
contentBase: output.path,
publicPath: output.publicPath,
compress: true,
headers: { 'Access-Control-Allow-Origin': '*' },
historyApiFallback: true,
watchOptions: {
ignored: /node_modules/
},
hot: true
}
});
| JavaScript | 0.004338 | @@ -750,16 +750,35 @@
hot:
+ true,%0A hotOnly:
true%0A
|
a991acf59422f4fa9875ef55113058b4ab9d505b | Use PhantomJS as default browser for karma | gulpfile.js | gulpfile.js | "use strict";
var fs = require("fs");
var url = require("url");
var path = require("path");
var gulp = require("gulp");
var less = require("less");
var jspm = require("jspm");
var karma = require("karma");
var rimraf = require("rimraf");
var runSequence = require("run-sequence");
var browserSync = require("browser-sync");
var AutoPrefixPlugin = require("less-plugin-autoprefix");
var historyApiFallback = require("connect-history-api-fallback");
var $ = require("gulp-load-plugins")();
var autoPrefix = new AutoPrefixPlugin({
browsers: ["last 3 versions", "last 3 BlackBerry versions", "last 3 Android versions"]
});
gulp.task("clean", function (done) {
rimraf.sync("dist", { maxBusyTries: 5 });
done();
});
gulp.task("lint", function () {
return gulp.src(["**/*.js", "!dist/**", "!node_modules/**", "!app/jspm_packages/**"])
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.if(shouldExitOnFailure, $.eslint.failAfterError()));
});
gulp.task("build:css", function () {
return gulp.src("app/main.less")
.pipe($.less({ plugins: [autoPrefix] }))
.pipe($.csso())
.pipe(gulp.dest("dist"));
});
gulp.task("build:js", function (done) {
jspm.setPackagePath(".");
jspm.bundleSFX("main", "dist/main.js", { minify: true, mangle: true, sourceMaps: true, lowResSourceMaps: false }).then(done);
});
gulp.task("build:html", function () {
return gulp.src("app/index.html")
.pipe($.htmlReplace({ css: "/main.css", js: "/main.js" }))
.pipe($.minifyHtml({ empty: true, spare: true, quotes: true }))
.pipe(gulp.dest("dist"));
});
gulp.task("build", function (done) {
runSequence("clean", "lint-and-test", ["build:css", "build:js", "build:html"], done);
});
gulp.task("test", function (done) {
runKarma(done, true, ["PhantomJS"]);
});
gulp.task("test:debug", function (done) {
runKarma(done, false, ["Chrome"]);
});
gulp.task("lint-and-test", function (done) {
runSequence("lint", "test", done);
});
gulp.task("reload-styles", function () {
browserSync.reload("main.less");
});
gulp.task("serve", function () {
startBrowserSync("app");
gulp.watch(["app/**/*.js"], ["lint-and-test"]);
gulp.watch(["app/**/*.less"], ["reload-styles"]);
});
gulp.task("serve:dist", function () {
startBrowserSync("dist");
});
gulp.task("default", ["serve"]);
function lessMiddleware (req, res, next) {
var requestedPath = url.parse(req.url).pathname;
if (requestedPath.match(/\.less$/)) {
var fileName = path.resolve("app" + requestedPath);
var content = fs.readFileSync(fileName).toString();
return less.render(content, { filename: fileName, plugins: [autoPrefix] }).then(function (output) {
res.setHeader("Content-Type", "text/css");
res.end(output.css);
});
}
next();
}
function runKarma(done, singleRun, browsers) {
karma.server.start({
configFile: path.resolve("karma.conf.js"),
singleRun: singleRun,
browsers: browsers || ["Chrome"]
}, function (failedTests) {
if (failedTests && shouldExitOnFailure()) {
throw new Error("Terminating process due to failing tests.");
}
done();
});
}
function startBrowserSync(baseDir, browser) {
browserSync({
files: [baseDir + "/**"],
server: { baseDir: baseDir, middleware: [lessMiddleware, historyApiFallback] },
injectFileTypes: ["less"],
startPath: "/",
browser: browser || "default"
});
}
function shouldExitOnFailure() {
return !browserSync.active;
}
| JavaScript | 0 | @@ -3068,22 +3068,25 @@
rs %7C%7C %5B%22
-Chrome
+PhantomJS
%22%5D%0A %7D,
|
392beb7e4bca0d56a9240143bfce55daf99b87d7 | use GET params instead of hash | static/javascripts/search-box.js | static/javascripts/search-box.js | $(document).ready(function () {
$('#search-box input').keydown(function(event) {
if (event.keyCode == 13) {
window.location = '/en-US/core/search/#q=' + $('#search-box input').val();
return false;
}
});
var search_cache = {};
$('#search-box input').autocomplete({
minLength: 1,
appendTo: '#search-box-result',
position: { my: "right top", at: "right bottom"},
source: function(request, response) {
var term = request.term;
if (term in search_cache) {
response(search_cache[term]);
return;
}
$.getJSON('/en-US/core/search/ajax_type_search/',
{'query': term, 'record_type': 'SYSTEM'},
function( data, status, xhr ) {
search_cache[term] = data.SYSTEM;
response(data.SYSTEM);
});
},
select: function( event, ui ) {
window.location = '/en-US/systems/show/' + ui.item.pk + '/';
return false;
},
focus: function( event, ui ) {
return false;
}
});
});
| JavaScript | 0.000001 | @@ -155,10 +155,15 @@
rch/
-#q
+?search
=' +
|
e94febd1577590d85f12887e82e09ff205937ab3 | tweak 'test' task deps | gulpfile.js | gulpfile.js | // Build file.
// Usage:
//
// $ gulp
//
// See: https://github.com/prose/prose/issues/702
// Require dependencies.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var shell = require('gulp-shell');
var browserify = require('browserify');
var rename = require('gulp-rename');
var rimraf = require('gulp-rimraf');
var watch = require('gulp-watch');
var source = require('vinyl-source-stream');
var nodeJS = process.execPath;
// Scripts paths.
var paths = {
vendorScripts: [
'vendor/codemirror/codemirror.js',
'vendor/codemirror/overlay.js',
'vendor/codemirror/htmlmixed.js',
'vendor/codemirror/clike.js',
'vendor/codemirror/yaml.js',
'vendor/codemirror/ruby.js',
'vendor/codemirror/markdown.js',
'vendor/codemirror/xml.js',
'vendor/codemirror/javascript.js',
'vendor/codemirror/css.js',
'vendor/codemirror/gfm.js',
'vendor/liquid.js'
],
app: [
'app/**/**/*.js'
],
test: [
'test/**/*.{js, json}',
'!test/lib/index.js', // built test file
'!test/lib/polyfill.js' // built test file.
],
templates: [
'templates/**/*.html'
]
};
// Removes `dist` folder.
gulp.task('clean', function () {
return gulp.src('dist', {read: false})
.pipe(rimraf());
});
// Translations.
// To run this task we have to have a `transifex.auth`
// file inside `translations` folder.
// Example file contents:
//
// {
// "user": "",
// "pass": ""
// }
//
// An account can be created at https://www.transifex.com/
//
gulp.task('translations', function () {
return gulp.src('')
.pipe(
shell([
'mkdir -p dist',
nodeJS + ' translations/update_locales',
nodeJS + ' build'
])
);
});
// Default tasks.
// ---------------------------
// Build templates.
gulp.task('templates', function () {
return gulp.src('')
.pipe(
shell([
'mkdir -p dist && ' + nodeJS + ' build'
])
);
});
// Creates `dist` directory if not created and
// creates `oauth.json`.
gulp.task('oauth', function () {
return gulp.src('')
.pipe(
shell([
'mkdir -p dist',
'[ -f oauth.json ] && echo "Using existing oauth.json." || curl "https://raw.githubusercontent.com/prose/prose/gh-pages/oauth.json" > oauth.json'
])
);
});
// Build tests.
gulp.task('build-tests', function() {
// Browserify polyfill-require.js
// Pass `debug` option to enable source maps.
browserify({debug:true})
.add('./test/lib/polyfill-require.js')
.bundle()
.pipe(source('polyfill.js'))
.pipe(gulp.dest('./test/lib/'));
// Browserify index.js
// Pass `debug` option to enable source maps.
return browserify({debug: true})
.add('./test/index.js')
.external('chai')
.bundle()
.pipe(source('index.js')) // Output file.
.pipe(gulp.dest('./test/lib/')); // Output folder.
});
// Concatenate vendor scripts, browserify app scripts and
// merge them both into `prose.js`.
gulp.task('build-app', ['templates', 'oauth'], function() {
// Concatenate vendor scripts.
gulp.src(paths.vendorScripts)
.pipe(concat('vendor.js'))
.pipe(gulp.dest('dist/'));
// Browserify app scripts.
return browserify({debug: true})
.add('./app/boot.js')
.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('./dist/'))
// Concatenate scripts once browserify finishes.
.on('end', function() {
// Concatenate `vendor` and `app` scripts into `prose.js`.
return gulp.src(['dist/vendor.js', 'dist/app.js'])
.pipe(concat('prose.js'))
.pipe(gulp.dest('dist/'));
});
});
// Compress `prose.js`.
gulp.task('uglify', ['build-app'], function() {
return gulp.src('dist/prose.js')
.pipe(rename('prose.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
// Watch for changes in `app` scripts.
// Usage:
//
// $ gulp watch
//
gulp.task('watch', ['build-app', 'build-tests'], function() {
// Watch any `.js` file under `app` folder.
gulp.watch(paths.app, ['build-app']);
gulp.watch(paths.test, ['build-tests']);
gulp.watch(paths.templates, ['build-app']);
});
gulp.task('run-tests', ['build-tests'], shell.task([
'./node_modules/.bin/mocha-phantomjs test/index.html'
], {ignoreErrors: true}));
// Like watch, but actually run the tests whenever anything changes.
gulp.task('test', ['run-tests'], function() {
gulp.watch([paths.app, paths.test, paths.templates], ['run-tests'])
});
// Default task which builds the project when we
// run `gulp` from the command line.
gulp.task('default', ['build-tests', 'build-app', 'uglify']);
| JavaScript | 0.000012 | @@ -2320,16 +2320,195 @@
;%0A%7D);%0A%0A%0A
+%0A// Concatenate vendor scripts into dist/vendor.js%0Agulp.task('vendor', function() %7B%0A gulp.src(paths.vendorScripts)%0A .pipe(concat('vendor.js'))%0A .pipe(gulp.dest('dist/'));%0A%7D)%0A%0A%0A
// Build
@@ -2539,16 +2539,50 @@
-tests',
+ %5B'templates', 'oauth', 'vendor'%5D,
functio
@@ -3118,81 +3118,68 @@
%0A//
-Concatenate vendor scripts, browserify app scripts and%0A// merge them both
+Browserify app scripts, then concatenate with vendor scripts
int
@@ -3236,19 +3236,29 @@
'oauth'
-%5D
,
+'vendor'%5D,
function
@@ -3266,135 +3266,8 @@
) %7B%0A
-%0A // Concatenate vendor scripts.%0A gulp.src(paths.vendorScripts)%0A .pipe(concat('vendor.js'))%0A .pipe(gulp.dest('dist/'));
%0A%0A
|
3065bf0c58592adf4b8f60e3ed117b63be19cf20 | Make the enter key go to panels. | static/js/settings_panel_menu.js | static/js/settings_panel_menu.js | var settings_panel_menu = (function () {
var exports = {};
exports.make_menu = function (opts) {
var main_elem = opts.main_elem;
var hash_prefix = opts.hash_prefix;
var load_section = opts.load_section;
var curr_li = main_elem.children('li').eq(0);
var self = {};
self.show = function () {
main_elem.show();
self.activate_section({
li_elem: curr_li,
});
curr_li.focus();
};
self.hide = function () {
main_elem.hide();
};
self.current_tab = function () {
return curr_li.data('section');
};
self.set_key_handlers = function (toggler) {
keydown_util.handle({
elem: main_elem,
handlers: {
left_arrow: toggler.maybe_go_left,
right_arrow: toggler.maybe_go_right,
up_arrow: self.prev,
down_arrow: self.next,
},
});
};
self.prev = function () {
curr_li.prev().focus().click();
return true;
};
self.next = function () {
curr_li.next().focus().click();
return true;
};
self.activate_section = function (opts) {
var li_elem = opts.li_elem;
var section = li_elem.data('section');
curr_li = li_elem;
main_elem.children("li").removeClass("active no-border");
li_elem.addClass("active");
li_elem.prev().addClass("no-border");
window.location.hash = hash_prefix + section;
$(".settings-section, .settings-wrapper").removeClass("show");
ui.update_scrollbar($("#settings_content"));
load_section(section);
var sel = "[data-name='" + section + "']";
$(".settings-section" + sel + ", .settings-wrapper" + sel).addClass("show");
};
main_elem.on("click", "li[data-section]", function (e) {
self.activate_section({
li_elem: $(this),
});
e.stopPropagation();
});
return self;
};
exports.initialize = function () {
exports.normal_settings = exports.make_menu({
main_elem: $('.normal-settings-list'),
hash_prefix: "settings/",
load_section: function (section) {
settings_sections.load_settings_section(section);
},
});
exports.org_settings = exports.make_menu({
main_elem: $('.org-settings-list'),
hash_prefix: "organization/",
load_section: function (section) {
admin_sections.load_admin_section(section);
},
});
};
exports.show_normal_settings = function () {
exports.org_settings.hide();
exports.normal_settings.show();
};
exports.show_org_settings = function () {
exports.normal_settings.hide();
exports.org_settings.show();
};
exports.set_key_handlers = function (toggler) {
exports.normal_settings.set_key_handlers(toggler);
exports.org_settings.set_key_handlers(toggler);
};
return exports;
}());
if (typeof module !== 'undefined') {
module.exports = settings_panel_menu;
}
| JavaScript | 0.000002 | @@ -829,16 +829,61 @@
_right,%0A
+ enter_key: self.enter_panel,%0A
@@ -1175,32 +1175,298 @@
n true;%0A %7D;%0A%0A
+ self.enter_panel = function () %7B%0A var panel = self.get_panel();%0A var sel = 'input:visible:first,button:visible:first,select:visible:first';%0A var panel_elem = panel.find(sel).first();%0A%0A panel_elem.focus();%0A return true;%0A %7D;%0A%0A
self.activat
@@ -1964,24 +1964,157 @@
(section);%0A%0A
+ self.get_panel().addClass('show');%0A %7D;%0A%0A self.get_panel = function () %7B%0A var section = curr_li.data('section');%0A
var
@@ -2151,32 +2151,44 @@
+ %22'%5D%22;%0A
+ var panel =
$(%22.settings-se
@@ -2234,25 +2234,30 @@
sel)
-.addClass(%22show%22)
+;%0A return panel
;%0A
|
15303547345f09bf2bc08e5b13c154a817e2a983 | fix jade path | gulpfile.js | gulpfile.js | 'use strict'
const gulp = require('gulp')
const sass = require('gulp-sass')
const postcss = require('gulp-postcss')
const sugarss = require('sugarss')
const autoprefixer = require('autoprefixer')
const jade = require('gulp-jade')
const rename = require('gulp-rename')
gulp.task('sss', () => {
return gulp.src('src/**/*.sss')
.pipe(postcss([], { parser: sugarss }))
.pipe(rename({ extname: '.scss' }))
.pipe(gulp.dest('scss'))
})
gulp.task('scss', ['sss'], () => {
return gulp.src('scss/**/*.scss')
.pipe(sass({ style: 'expanded' }).on('error', sass.logError))
.pipe(postcss([ autoprefixer ]))
.pipe(gulp.dest('css'))
})
gulp.task('jade', () => {
return gulp.src('src/**/index.jade')
.pipe(jade({ pretty: true }))
.pipe(gulp.dest(''))
})
gulp.task('build', ['scss', 'jade'])
gulp.task('watch', () => {
gulp.watch('src/**/*', ['build'])
})
| JavaScript | 0.000001 | @@ -706,23 +706,16 @@
lp.src('
-src/**/
index.ja
|
da0de2915e32402d65702824a9a8167f05388713 | change gulp script to order files for concat | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('build', function () {
return gulp
.src('./src/**/*.js')
.pipe(concat('mutant-ng-translate.js'))
.pipe(gulp.dest('./build/'));
});
gulp.task('watch', function () {
gulp.watch('./src/**/*.js', ['build']);
}); | JavaScript | 0 | @@ -126,16 +126,39 @@
.src(
+%5B'./src/translate.js',
'./src/*
@@ -164,16 +164,17 @@
**/*.js'
+%5D
)%0D%0A
|
07eed5b6047b8b8fc2fcbb518ca320d6cd64b897 | Add setting about server port | gulpfile.js | gulpfile.js | /**
* Created by dell on 2015/7/20.
* This is gulp init
*/
(function(){
"use strict";
var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var plugins = loadPlugins();
var Browsersync = require('browser-sync').create();
var del = require('del');
var paths = {
src: 'app',
dist: 'dist'
};
// 默认任务
gulp.task('default', ["server","less","watch"]);
// 搭建静态服务器
gulp.task('server', function() {
Browsersync.init({
server: {
baseDir: "./" +paths.src
}
});
});
// 编译Less文件
gulp.task('less',function(){
gulp.src([paths.src + '/less/style.less'])
.pipe(plugins.less())
.pipe(gulp.dest(paths.src + '/css'));
});
// 监控文件
gulp.task('watch',function(){
gulp.watch(paths.src + '/less/**/*.less', ['less']);
gulp.watch([
paths.src +"/**/*.html",
paths.src + "/js/**/*.js",
paths.src + "/lib/**/*.js",
paths.src + "/css/**/*.css",
paths.src + "/lib/**/*.css"
]).on("change", Browsersync.reload);
});
}).call(this); | JavaScript | 0 | @@ -533,16 +533,104 @@
init(%7B%0D%0A
+ port: 3005,%0D%0A ui: %7B%0D%0A port: 3006%0D%0A %7D,%0D%0A
|
771270dacbba1a50a512b9eacb4a3390da5a107f | fix gulp error | 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',
'locales/*.*',
'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',
'libEGL.dll',
'msvcr120.dll',
'msvcp120.dll',
'libGLESv2.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];
console.log(distPath)
callback && 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());
if (process.arch !== 'ia32') {
buildPackage(process.platform, process.arch, afterPackage);
}
if (process.platform !== 'darwin') {
buildPackage(process.platform, 'ia32', afterPackage);
}
});
gulp.task('package-uncompressed', ['build'], function (callback) {
gulp.src('./app/*.map').pipe(clean());
if (process.arch !== 'ia32') {
buildPackage(process.platform, process.arch);
}
if (process.platform !== 'darwin') {
buildPackage(process.platform, 'ia32');
}
});
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 | @@ -748,16 +748,18 @@
assets/*
+/*
*'%5D)%0A
@@ -901,16 +901,18 @@
n-sudo/*
+/*
*'%5D)%0A
|
2c316e56b2fa059e9914d4ffc21644a28262f522 | Remove `build-darwin` task from `build-all` task | gulpfile.js | gulpfile.js | 'use strict';
const cp = require('child_process');
const gulp = require('gulp');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const packager = require('electron-packager');
const path = require('path');
const install = require('gulp-install');
const zip = require('gulp-zip');
const electronInstaller = require('electron-winstaller');
const fs = require('fs');
const del = require('del');
const replace = require('gulp-replace');
const appPkg = require('./app/package.json');
gulp.task('deps', () => {
return gulp.src('./app/package.json')
.pipe(install({ production: true }));
});
gulp.task('clean:renderer', () => {
return del(['./app/renderer']);
});
gulp.task('renderer', ['deps', 'clean:renderer'], () => {
const js = gulp.src('./app/renderer-jsx/**/*.js*')
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015', 'react']
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./app/renderer'));
return js;
});
function build(arch, platform, icon) {
return new Promise((resolve, reject) => {
packager({
arch,
dir: path.join(__dirname, 'app'),
platform: platform || 'win32',
asar: true,
ignore: /(renderer-jsx|__tests__)/gi,
overwrite: true,
out: path.join(__dirname, 'out'),
icon: path.join(__dirname, 'build', icon || 'icon.ico'),
'version-string': {
ProductName: 'Hain',
CompanyName: 'Heejin Lee'
}
}, (err, appPath) => {
if (err) {
console.log(err);
return reject(err);
}
return resolve();
});
});
}
function buildZip(arch) {
const filename = `Hain-${arch}-v${appPkg.version}.zip`;
return gulp.src(`./out/Hain-win32-${arch}/**/*`)
.pipe(zip(filename))
.pipe(gulp.dest('./out/'));
}
// Workaround to build zip file which is including symlinks
function buildZipUsingExec(arch, platform) {
const filename = `hain-${platform}-${arch}-v${appPkg.version}.zip`;
const targetDir = `hain-${platform}-${arch}`;
const workingDir = path.join(__dirname, 'out', targetDir);
return new Promise((resolve, reject) => {
cp.exec(`zip --symlinks -r ../${filename} *`, {
cwd: workingDir
}, (err, stdout, stderr) => {
if (err) {
console.log(stdout);
console.log(stderr);
return reject(err);
}
return resolve();
});
});
}
function buildInstaller(arch) {
const filename = `HainSetup-${arch}-v${appPkg.version}.exe`;
return electronInstaller.createWindowsInstaller({
appDirectory: path.resolve(`./out/hain-win32-${arch}`),
outputDirectory: `./out/${arch}`,
authors: 'Heejin Lee',
title: 'Hain',
iconUrl: 'https://raw.githubusercontent.com/appetizermonster/Hain/master/build/icon.ico',
setupIcon: path.resolve('./build/icon.ico'),
loadingGif: path.resolve('./build/installer.gif'),
skipUpdateIcon: true, // HACK to resolve rcedit error (electron-winstaller)
noMsi: true
}).then(() => {
fs.renameSync(`./out/${arch}/Setup.exe`, `./out/${filename}`);
});
}
function buildDebianPkg() {
const electronDebianPkg = require('electron-installer-debian');
const options = {
src: 'out/hain-linux-x64/',
dest: 'out/installers/',
arch: 'amd64'
};
return new Promise((resolve, reject) => {
electronDebianPkg(options, function (err) {
if (err) {
console.log(err);
return reject(err);
}
return resolve();
});
});
}
gulp.task('build', ['renderer', 'deps'], () => {
return build('ia32')
.then(() => build('x64'));
});
gulp.task('build-zip-ia32', ['build'], () => buildZip('ia32'));
gulp.task('build-zip-x64', ['build'], () => buildZip('x64'));
gulp.task('build-zip', ['build-zip-ia32', 'build-zip-x64']);
gulp.task('build-debian', ['renderer'], () => {
return build('x64', 'linux')
.then(() => buildDebianPkg());
});
gulp.task('build-darwin', ['renderer', 'deps'], () => {
return build('x64', 'darwin', 'icon.icns')
.then(() => buildZipUsingExec('x64', 'darwin'));
});
gulp.task('build-installer', ['build', 'build-zip'], () => {
return buildInstaller('ia32')
.then(() => buildInstaller('x64'));
});
gulp.task('build-chocolatey', () => {
return gulp.src('./chocolatey/**/*')
.pipe(replace('${version}', appPkg.version))
.pipe(gulp.dest('./out/chocolatey/'));
});
gulp.task('build-all', ['build-zip', 'build-installer', 'build-chocolatey', 'build-darwin']);
gulp.task('watch', ['renderer'], () => {
const opts = {
debounceDelay: 2000
};
gulp.watch('./app/renderer-jsx/**/*', opts, ['renderer']);
});
gulp.task('default', ['renderer']);
| JavaScript | 0.000022 | @@ -4460,24 +4460,8 @@
tey'
-, 'build-darwin'
%5D);%0A
|
87358a35ed768711777988ee39b1ab2071a2f4fb | Add comments. | console/server/node-server.js | console/server/node-server.js | const MONGOOSE_CONSOLE_DEFAULT_PORT = 8080;
const PROMETHEUS_DEFAULT_CONFIGURATION_PATH = '/configuration/prometheus.yml';
const CONFIGURATION_DIRECTORY_NAME = "configuration";
const PROMETHEUS_CONFIGURATION_FILENAME = "prometeus";
const PROMETHEUS_CONFIGURATION_EXTENSION = ".yml";
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var cors = require('cors');
// NOTE: ShellJS is being used to create full path directories.
var shell = require('shelljs');
var app = express();
var path = __dirname + '';
// NOTE: Fetching environment variables' values
var port = process.env.CONSOLE_PORT || MONGOOSE_CONSOLE_DEFAULT_PORT;
var prometheusConfigurationPath = process.env.PROMETHEUS_CONFIGURATION_PATH || PROMETHEUS_DEFAULT_CONFIGURATION_PATH;
app.use(express.static(path));
app.use(bodyParser.json()); // NOTE: Supporting JSON-encoded bodies
app.use(express.multipart()); // NOTE: We're saving Prometheus configuration via the server
// NOTE: CORS configuration
app.use(cors())
app.options('*', cors());
// NOTE: Configurating server to serve index.html since during the production ...
// build Angular converts its html's to only one file.
app.get('*', function(req, res) {
res.sendFile(path + '/index.html');
});
app.post('/savefile', function (req, res) {
let fileName = req.body.fileName;
var creatingFilePath = `${CONFIGURATION_DIRECTORY_NAME}/${fileName}`;
console.log(`Processing file with path: ${creatingFilePath}`);
// NOTE: Save Prometheus' configuration to its specified path.
if (fileName == (PROMETHEUS_CONFIGURATION_FILENAME + PROMETHEUS_CONFIGURATION_EXTENSION)) {
creatingFilePath = prometheusConfigurationPath;
}
var fileContent = req.body.fileContent;
let configurationDirectoryPath = `${CONFIGURATION_DIRECTORY_NAME}`;
// NOTE: Creating directory for Prometheus configuration if not exist.
if (!fs.existsSync(configurationDirectoryPath)) {
// NOTE: Using ShellJS in order to create the full path.
shell.mkdir('-p', configurationDirectoryPath);
shell.cd(configurationDirectoryPath);
}
var fileWriteFlag = "";
if (!fs.existsSync(creatingFilePath)) {
fileWriteFlag = { flag: 'wx' };
}
fs.writeFile(creatingFilePath, fileContent, fileWriteFlag, function(error) {
if (error) {
return console.log(error);
}
console.log("File has been sccessfully saved.");
});
});
app.listen(port);
| JavaScript | 0 | @@ -1270,24 +1270,88 @@
tml');%0A%7D);%0A%0A
+// NOTE: Saving file on 'CONFIGURATION_DIRECTORY_NAME' folder. %0A
app.post('/s
@@ -2275,32 +2275,85 @@
ingFilePath)) %7B%0A
+ // NOTE: Creating file if it doesn't exist. %0A
fileWrit
|
175a2de181e04bc04a8923124fd0e148df87ac93 | Add NPM_MOD_DIR to gulpfile.js | gulpfile.js | gulpfile.js | /**
* @license MIT License
*
* Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
* Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
let babel = require('gulp-babel');
let babelify = require('babelify');
let browserify = require('browserify');
let childProcess = require('child_process');
let concat = require('gulp-concat');
let del = require('del');
let gulp = require('gulp');
let path = require('path');
let source = require('vinyl-source-stream');
let uglify = require('gulp-uglifyjs');
const isRelease = process.env.NODE_ENV === 'production';
const CLIENT_SRC = [
'client/js/libs/handlebars.js',
'client/js/libs/handlebars/**/*.js',
'client/js/libs/jquery.js',
'client/js/libs/jquery/**/*.js',
'client/js/libs/moment.js',
'client/js/libs/stringcolor.js',
'client/js/libs/uri.js',
];
const SERVER_SRC = [
'./server/**/*.js'
];
const OBJ_CLIENT = './client/__obj/';
const DIST_SERVER = './dist/';
const DIST_CLIENT = './client/dist/';
const DIST_CLIENT_JS = path.resolve(DIST_CLIENT, './js/');
/**
* # The rules of task name
*
* ## public task
* - This is completed in itself.
* - This is callable as `gulp <taskname>`.
*
* ## private task
* - This has some sideeffect in dependent task trees
* and it cannot recovery by self.
* - This is __callable only from public task__.
* DONT CALL as `gulp <taskname>`.
* - MUST name `__taskname`.
*/
gulp.task('__uglify', ['clean:client'], function () {
return gulp.src(CLIENT_SRC)
.pipe(uglify('libs.min.js', {
compress: false,
}))
.pipe(gulp.dest(DIST_CLIENT_JS));
});
gulp.task('__handlebars', ['clean:client'], function () {
let handlebars = path.relative(__dirname, './node_modules/handlebars/bin/handlebars');
let args = [
String(handlebars),
'client/views/',
'-e', 'tpl',
'-f', path.resolve(DIST_CLIENT_JS, './karen.templates.js'),
];
let option = {
cwd: path.relative(__dirname, ''),
stdio: 'inherit',
};
childProcess.spawn('node', args, option);
});
gulp.task('__cp_client', ['clean:client'], function () {
return gulp.src('./client/script/**/*.js')
.pipe(gulp.dest(OBJ_CLIENT));
});
gulp.task('__typescript', ['clean:client'], function (callback) {
const args = [
path.relative(__dirname, './node_modules/.bin/tsc'),
];
const option = {
cwd: path.relative(__dirname, ''),
stdio: 'inherit',
};
const tsc = childProcess.spawn('iojs', args, option);
tsc.on('exit', callback);
});
gulp.task('__browserify', ['clean:client', '__cp_client', '__typescript'], function () {
const ENTRY_POINT = [
path.resolve(OBJ_CLIENT, './karen.js'),
];
const option = {
insertGlobals: false,
debug: !isRelease,
};
const babel = babelify.configure({
optional: [],
});
browserify(ENTRY_POINT, option)
.transform(babel)
.bundle()
.pipe(source('karen.js'))
.pipe(gulp.dest(DIST_CLIENT_JS));
});
gulp.task('jslint', function (callback) {
const src = [
'./gulpfile.js',
'./client/script/',
'./defaults/',
'./server/',
];
const bin = path.join(__dirname, './node_modules/', './.bin', 'eslint');
const args = [
'--ext', '.js',
].concat(src);
const option = {
cwd: path.relative(__dirname, ''),
stdio: 'inherit',
};
const eslint = childProcess.spawn(bin, args, option);
eslint.on('exit', callback);
});
gulp.task('__babel:server', ['clean:server'], function () {
return gulp.src(SERVER_SRC)
.pipe(babel({
// For io.js, we need not some transforms:
blacklist: [
'es6.blockScoping',
'es6.classes',
'es6.constants',
'es6.forOf',
'es6.properties.shorthand',
'es6.templateLiterals',
],
sourceMaps: false,
}))
.pipe(gulp.dest(DIST_SERVER));
});
gulp.task('clean:client', function () {
const deleter = function (dir) {
return new Promise(function(resolve){
del(path.join(dir, '**', '*.*'), resolve);
});
};
const obj = deleter(OBJ_CLIENT);
const dist = deleter(DIST_CLIENT);
return Promise.all([obj, dist]);
});
gulp.task('clean:server', function (callback) {
return del(path.join(DIST_SERVER, '**', '*.*'), callback);
});
gulp.task('__build:server', ['__babel:server']);
gulp.task('__build:client', ['__handlebars', '__uglify', '__browserify']);
gulp.task('build:server', ['jslint', '__build:server']);
gulp.task('build:client', ['jslint', '__build:client']);
gulp.task('build', ['jslint', '__build:client', '__build:server']);
gulp.task('clean', ['clean:client', 'clean:server']);
gulp.task('default', ['build']);
| JavaScript | 0.000002 | @@ -2144,16 +2144,80 @@
./js/');
+%0Aconst NPM_MOD_DIR = path.resolve(__dirname, './node_modules/');
%0A%0A/**%0A *
@@ -2887,41 +2887,29 @@
h.re
-lative(__dirname, './node_modules
+solve(NPM_MOD_DIR, '.
/han
@@ -3496,49 +3496,37 @@
ath.
-relative(__dirname, './node_modules/.bin/
+join(NPM_MOD_DIR, './.bin', '
tsc'
@@ -4410,36 +4410,19 @@
oin(
-__dirname, './node_modules/'
+NPM_MOD_DIR
, '.
|
f611a5a81452d57c6aa0780d2d5db73f65c2525d | Remove gray background for past events | aspc/static/js/course_calendar.js | aspc/static/js/course_calendar.js | var year = new Date().getFullYear();
var month = new Date().getMonth();
var day = new Date().getDate();
var CURRENT_PAGE = window.location.pathname;
var add_to = '+ add to schedule'
var remove_from = '- remove from schedule';
function init() {
$('#calendar').weekCalendar({
businessHours: {
start: 8,
end: 24,
limitDisplay: true
},
timeslotsPerHour: 2,
daysToShow: 5,
timeSeparator: '–',
readonly: true,
allowCalEventOverlap: true,
overlapEventsSeparate: true,
height: function($calendar) {
return $('table.wc-time-slots').height() + $('#calendar').find(".wc-toolbar").outerHeight() + $('#calendar').find(".wc-header").outerHeight();
},
eventHeader: function(calEvent, calendar) {
return calEvent.title;
},
eventBody: function(calEvent, calendar) {
var options = calendar.weekCalendar('option');
var one_hour = 3600000;
var displayTitleWithTime = calEvent.end.getTime() - calEvent.start.getTime() <= (2 * (one_hour / options.timeslotsPerHour));
if (displayTitleWithTime) {
return '';
}
else {
return calendar.weekCalendar('formatTime', calEvent.start, options.timeFormat) + options.timeSeparator + calendar.weekCalendar('formatTime', calEvent.end, options.timeFormat);
}
},
eventRender: function(calEvent, $event) {
if (calEvent.end.getTime() < new Date().getTime()) {
$event.css("backgroundColor", "#aaa");
$event.find(".time").css({
"backgroundColor": "#999",
"border": "1px solid #888"
});
}
},
eventAfterRender: function(calEvent, $event) {
$event.addClass('campus_' + calEvent.campus);
},
getHeaderDate: function(date, $calendar) {
var options = $calendar.weekCalendar('option');
var dayName = options.useShortDayNames ? options.shortDays[date.getDay()] : options.longDays[date.getDay()];
return dayName;
},
});
gotodate = $('#calendar').weekCalendar('gotoDate', new Date(2012, 8, 3, 0, 0, 0, 0));
}
function addCourseData(course_data, frozen) {
var events = course_data.events;
var info = course_data.info;
for (var evid in events) {
var cevent = events[evid];
var translated_event = {
"start": Date.parse(cevent.start),
"end": Date.parse(cevent.end),
"title": cevent.title,
"id": cevent.id,
"campus": info.campus_code,
};
$('#calendar').weekCalendar('updateEvent', translated_event);
}
var $c_c_list = $('ol#schedule_courses');
if (frozen === true) {
$c_c_list.append('<li class="campus_' + info.campus_code +
'" id="indicator_' + info.course_code_slug + '"><a href="' + info.detail_url + '" class="course_detail">' +
info.course_code + '</li>');
} else {
$c_c_list.append('<li class="campus_' + info.campus_code +
'" id="indicator_' + info.course_code_slug + '"><a href="' + info.detail_url + '" class="course_detail">' +
info.course_code + '<a class="course_delete">x</a></li>');
$('li#indicator_' + info.course_code_slug + ' a.course_delete').click(function(event) {
removeCourse(info.course_code_slug);
});
var $result_entry = $('h3#course_' + info.course_code_slug);
if ($result_entry.length != 0) {
$result_entry.data('added', true);
$result_entry.prev().text(remove_from);
}
}
}
function addCourse(course_slug) {
$.get(CURRENT_PAGE + course_slug + '/add/', addCourseData);
}
function toggleCourse(course_slug) {
var $c = $('h3#course_' + course_slug);
var added = $c.data('added');
if (added == true || added == "True") {
removeCourseData(course_slug);
$c.prev().text(add_to);
$('li#indicator_' + course_slug).remove();
$c.data('added', false);
} else {
$c.prev().text(remove_from);
addCourse(course_slug);
$c.data('added', true);
}
}
function removeCourse(course_slug) {
var $c = $('h3#course_' + course_slug);
if ($c.length != 0) {
toggleCourse(course_slug);
} else {
removeCourseData(course_slug);
$('li#indicator_' + course_slug).remove();
}
}
function removeCourseData(course_slug) {
$.get(CURRENT_PAGE + course_slug + '/remove/',
function(data) {
for (var idid in data) {
var event_id = data[idid];
$('#calendar').weekCalendar('removeEvent', event_id);
}
});
}
function loadSavedCalendar(all_data) {
for (var cid in all_data) {
var course_data = all_data[cid];
addCourseData(course_data, true);
}
}
function loadCalendar() {
$.get(CURRENT_PAGE + 'load/',
function(data) {
for (var cid in data) {
var course_data = data[cid];
addCourseData(course_data, false);
}
$('ol.course_list > li > h3').each(function(idx, elem) {
var course_code_slug = $(elem).data('code');
var already_in_calendar = $(elem).data('added');
if (already_in_calendar) {
var new_link = $('<a class="add_course" id="indicator2_' + course_code_slug + '">' + remove_from + '</a>');
} else {
var new_link = $('<a class="add_course" id="indicator2_' + course_code_slug + '">' + add_to + '</a>');
}
new_link.bind('click', function(event) {
toggleCourse(course_code_slug);
});
$(elem).before(new_link);
});
$('h4#share_clear a#clear_schedule').click(function(e) {
clearCalendar();
});
});
}
function clearCalendar() {
$.get(CURRENT_PAGE + 'clear/',
function(data) {
$('#calendar').weekCalendar('clear');
window.location.replace(CURRENT_PAGE);
});
}
| JavaScript | 0.000001 | @@ -1483,360 +1483,8 @@
%7D,%0A
- eventRender: function(calEvent, $event) %7B%0A if (calEvent.end.getTime() %3C new Date().getTime()) %7B%0A $event.css(%22backgroundColor%22, %22#aaa%22);%0A $event.find(%22.time%22).css(%7B%0A %22backgroundColor%22: %22#999%22,%0A %22border%22: %221px solid #888%22%0A %7D);%0A %7D%0A %7D,%0A
|
86be5a270ecfd2f03568b99ed4a74db983348518 | Fix Cannot read property in credentialcounter | js/app/directives/credentialcounter.js | js/app/directives/credentialcounter.js | /**
* Nextcloud - passman
*
* @copyright Copyright (c) 2016, Sander Brand (brantje@gmail.com)
* @copyright Copyright (c) 2016, Marcos Zuriaga Miguel (wolfi@wolfi.es)
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
(function () {
'use strict';
/**
* @ngdoc directive
* @name passmanApp.directive:passwordGen
* @description
* # passwordGen
*/
angular.module('passmanApp')
.directive('credentialCounter', [function () {
return {
template: '<div ng-show="counter" translate="number.filtered" translate-values="{number_filtered: counter, credential_number: total}"></div>',
replace: false,
restrict: 'A',
scope: {
filteredCredentials: '=credentialCounter',
deleteTime: '=',
vault: '=',
filters: '='
},
link: function (scope) {
function countCredentials() {
var countedCredentials = 0;
var total = 0;
angular.forEach(scope.vault.credentials, function (credential) {
var pos = scope.filteredCredentials.map(function(c) { return c.guid; }).indexOf(credential.guid);
if (scope.deleteTime === 0 && credential.hidden === 0 && credential.delete_time === 0) {
total = total + 1;
countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials;
}
if (scope.deleteTime > 0 && credential.hidden === 0 && credential.delete_time > 0) {
total = total + 1;
countedCredentials = (pos !== -1) ? countedCredentials + 1 : countedCredentials;
}
});
scope.counter = countedCredentials;
scope.total = total;
}
scope.$watch('[filteredCredentials, deleteTime, filters]', function () {
countCredentials();
}, true);
}
};
}]);
}()); | JavaScript | 0 | @@ -1550,24 +1550,108 @@
total = 0;%0A
+%09%09%09%09%09%09if(!scope.vault.hasOwnProperty('credentials'))%7B%0A%09%09%09%09%09%09%09return;%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%0A
%09%09%09%09%09%09angula
|
8f557712ac9db54932e85fac1ebff1a0abd51482 | Add golden tests back to the "gulp watch" set of test tasks. | gulpfile.js | gulpfile.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
require('source-map-support').install();
var clangFormat = require('clang-format');
var formatter = require('gulp-clang-format');
var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var merge = require('merge2');
var mocha = require('gulp-mocha');
var sourcemaps = require('gulp-sourcemaps');
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var typescript = require('typescript');
var tsProject = ts.createProject('tsconfig.json', {
// Specify the TypeScript version we're using.
typescript: typescript,
});
const formatted = ['*.js', 'src/**/*.ts', 'test/**/*.ts'];
gulp.task('format', function() {
return gulp.src(formatted, {base: '.'})
.pipe(formatter.format('file', clangFormat))
.pipe(gulp.dest('.'));
});
gulp.task('test.check-format', function() {
return gulp.src(formatted)
.pipe(formatter.checkFormat('file', clangFormat, {verbose: true}))
.on('warning', onError);
});
gulp.task('test.check-lint', function() {
return gulp.src(['src/**/*.ts', 'test/**/*.ts'])
.pipe(tslint({formatter: 'verbose'}))
.pipe(tslint.report())
.on('warning', onError);
});
var hasError;
var failOnError = true;
var onError = function(err) {
hasError = true;
if (failOnError) {
process.exit(1);
}
};
gulp.task('compile', function() {
hasError = false;
var tsResult =
gulp.src(['src/**/*.ts']).pipe(sourcemaps.init()).pipe(tsProject()).on('error', onError);
return merge([
tsResult.dts.pipe(gulp.dest('built/definitions')),
// Write external sourcemap next to the js file
tsResult.js.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: '../../src'}))
.pipe(gulp.dest('built/src')),
tsResult.js.pipe(gulp.dest('built/src')),
]);
});
gulp.task('test.compile', ['compile'], function(done) {
if (hasError) {
done();
return;
}
return gulp.src(['test/*.ts'], {base: '.'})
.pipe(sourcemaps.init())
.pipe(tsProject())
.on('error', onError)
.js.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: '../..'}))
.pipe(gulp.dest('built/')); // '/test/' comes from base above.
});
gulp.task('test.unit', ['test.compile'], function(done) {
if (hasError) {
done();
return;
}
return gulp.src(['built/test/**/*.js', '!built/test/**/e2e*.js', '!built/test/**/golden*.js'])
.pipe(mocha({timeout: 1000}));
});
gulp.task('test.e2e', ['test.compile'], function(done) {
if (hasError) {
done();
return;
}
return gulp.src(['built/test/**/e2e*.js']).pipe(mocha({timeout: 25000}));
});
gulp.task('test.golden', ['test.compile'], function(done) {
if (hasError) {
done();
return;
}
return gulp.src(['built/test/**/golden*.js']).pipe(mocha({timeout: 1000}));
});
gulp.task('test', ['test.unit', 'test.e2e', 'test.golden', 'test.check-format', 'test.check-lint']);
gulp.task('watch', function() {
failOnError = false;
gulp.start(['test.unit']); // Trigger initial build.
return gulp.watch(['src/**/*.ts', 'test/**/*.ts', 'test_files/**'], ['test.unit']);
});
gulp.task('default', ['compile']);
| JavaScript | 0 | @@ -3184,16 +3184,31 @@
st.unit'
+, 'test.golden'
%5D); //
@@ -3312,16 +3312,31 @@
st.unit'
+, 'test.golden'
%5D);%0A%7D);%0A
|
2c405ea8d43a7bac72fb4f88b14c68f838be5de1 | Update build system | gulpfile.js | gulpfile.js | var fs = require('fs'),
gulp = require('gulp'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
replace = require('gulp-replace'),
merge = require('merge2'),
shell = require('gulp-shell'),
concat = require('gulp-concat');
var version = fs.readFileSync('src/quarky.js', {encoding:'utf8'}).match(/^\/\*\! \w+ ([0-9.]+)/)[1];
// ======================================== gulp version
gulp.task('version', function() {
var streams = merge();
streams.add(
gulp.src( 'package.json' )
.pipe( replace(/"version": "[0-9.]+",/, '"version": "'+version+'",') )
.pipe( gulp.dest('.') )
);
streams.add(
gulp.src( 'README.md' )
.pipe( replace(/^(\w+) [0-9.]+/, '$1 '+version) )
.pipe( gulp.dest('.') )
);
return streams;
});
// ======================================== gulp build
gulp.task('build', ['version'], function() {
var streams = merge();
streams.add(
gulp.src( './src/*.js' )
.pipe( jshint({
loopfunc: true,
boss: true
}) )
.pipe( jshint.reporter('jshint-stylish') )
);
streams.add(
gulp.src( ['./src/quarky.js', './node_modules/pyrsmk-w/src/W.js'] )
.pipe( uglify() )
.pipe( concat('quarky.min.js') )
.pipe( gulp.dest('.') )
);
return streams;
});
// ======================================== gulp publish
gulp.task('publish', shell.task([
"git tag -a "+version+" -m '"+version+"'",
'git push --tags',
'npm publish'
]));
// ======================================== gulp
gulp.task('default', ['build', 'publish']);
| JavaScript | 0.000001 | @@ -1062,27 +1062,8 @@
c( %5B
-'./src/quarky.js',
'./n
@@ -1092,16 +1092,35 @@
rc/W.js'
+, './src/quarky.js'
%5D )%0A%09%09%09.
|
922704e013f64b3f3800020b9bd0ecb67c8e9d0a | update batch test (#345) | automl/test/batch_predict.test.js | automl/test/batch_predict.test.js | // Copyright 2020 Google LLC
//
// 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
//
// https://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';
const {assert} = require('chai');
const {after, before, describe, it} = require('mocha');
const {AutoMlClient} = require('@google-cloud/automl').v1;
const {Storage} = require('@google-cloud/storage');
const cp = require('child_process');
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
const BATCH_PREDICT_REGION_TAG = 'batch_predict';
const LOCATION = 'us-central1';
const MODEL_ID = 'TEN2238627664384491520';
const PREFIX = 'TEST_BATCH_PREDICT';
describe('Automl Batch Predict Test', () => {
const client = new AutoMlClient();
before('should verify the model is deployed', async () => {
const projectId = await client.getProjectId();
const request = {
name: client.modelPath(projectId, LOCATION, MODEL_ID),
};
const [response] = await client.getModel(request);
if (response.deploymentState === 'UNDEPLOYED') {
const request = {
name: client.modelPath(projectId, LOCATION, MODEL_ID),
};
const [operation] = await client.deployModel(request);
// Wait for operation to complete.
await operation.promise();
}
});
it('should batch predict', async () => {
const projectId = await client.getProjectId();
const inputUri = `gs://${projectId}-lcm/entity_extraction/input.jsonl`;
const outputUri = `gs://${projectId}-lcm/${PREFIX}/`;
const batchPredictOutput = execSync(
`node ${BATCH_PREDICT_REGION_TAG}.js ${projectId} ${LOCATION} ${MODEL_ID} ${inputUri} ${outputUri}`
);
assert.match(
batchPredictOutput,
/Batch Prediction results saved to Cloud Storage bucket/
);
});
after('delete created files', async () => {
const projectId = await client.getProjectId();
const storageClient = new Storage();
const options = {
prefix: PREFIX,
};
const [files] = await storageClient
.bucket(`gs://${projectId}-lcm`)
.getFiles(options);
files.forEach(file => {
storageClient
.bucket(`gs://${projectId}-lcm`)
.file(file.name)
.delete();
});
});
});
| JavaScript | 0 | @@ -1009,26 +1009,26 @@
'TEN
-223862766438449152
+000000000000000000
0';%0A
@@ -1151,22 +1151,18 @@
t();%0A%0A
-before
+it
('should
@@ -1166,591 +1166,240 @@
uld
-verify the model is deployed', async () =%3E %7B%0A const projectId = await client.getProjectId();%0A const request = %7B%0A name: client.modelPath(projectId, LOCATION, MODEL_ID),%0A %7D;%0A%0A const %5Bresponse%5D = await client.getModel(request);%0A if (response.deploymentState === 'UNDEPLOYED') %7B%0A const request = %7B%0A name: client.
+batch predict', async () =%3E %7B%0A // As batch prediction can take a long time, instead try to batch predict%0A // on a nonexistent
model
-Path(projectId, LOCATION, MODEL_ID),%0A %7D;%0A%0A const %5Boperation%5D = await client.deployModel(request);%0A%0A // Wait for operation to complete.%0A await operation.promise();%0A %7D%0A %7D);%0A%0A it('should batch predict', async () =%3E %7B
+ and confirm that the model was not found, but%0A // other elements of the request were valid.
%0A
@@ -1571,77 +1571,49 @@
lcm/
-$%7BPREFIX%7D/%60;%0A%0A const batchPredictOutput = execSync(%0A %60node $%7B
+TEST_BATCH_PREDICT/%60;%0A%0A const args = %5B
BATC
@@ -1636,15 +1636,10 @@
_TAG
-%7D.js $%7B
+,
proj
@@ -1647,20 +1647,18 @@
ctId
-%7D $%7B
+,
LOCATION
%7D $%7B
@@ -1657,20 +1657,18 @@
TION
-%7D $%7B
+,
MODEL_ID
%7D $%7B
@@ -1667,20 +1667,18 @@
L_ID
-%7D $%7B
+,
inputUri
%7D $%7B
@@ -1677,12 +1677,10 @@
tUri
-%7D $%7B
+,
outp
@@ -1688,571 +1688,127 @@
tUri
-%7D%60%0A );%0A assert.match(%0A batchPredictOutput,%0A /Batch Prediction results saved to Cloud Storage bucket/%0A );%0A %7D);%0A%0A after('delete created files', async () =%3E %7B%0A const projectId = await client.getProjectId(
+%5D;%0A const output = cp.spawnSync('node', args, %7Bencoding: 'utf8'%7D
);%0A
+%0A
-const storageClient = new Storage();%0A const options = %7B%0A prefix: PREFIX,%0A %7D;%0A const %5Bfiles%5D = await storageClient%0A .bucket(%60gs://$%7BprojectId%7D-lcm%60)%0A .getFiles(options);%0A files.forEach(file =%3E %7B%0A storageClient%0A .bucket(%60gs://$%7BprojectId%7D-lcm%60)%0A .file(file.name)%0A .delete();%0A %7D
+assert.match(output.stderr, /does not exist/
);%0A
|
8332c6f2056758649d95e1f613cef86f3e040bb3 | Add missing done. | katas/es6/language/promise/creation.js | katas/es6/language/promise/creation.js | // 76: Promise - creation
// To do: make all tests pass, leave the assert lines unchanged!
describe('a promise can be created in multiple ways', function() {
describe('creation fails when', function() {
it('using `Promise` as a function', function() {
function callPromiseAsFunction() {
Promise();
}
assert.throws(callPromiseAsFunction);
});
it('no parameter is passed', function() {
assert.throws(() => new Promise());
});
it('passing a non-callable throws too', function() {
const notAFunction = 1;
assert.throws(() => { new Promise(notAFunction); });
});
});
describe('most commonly Promises get created using the constructor', function() {
it('by passing a resolve function to it', function() {
const promise = new Promise(resolve => resolve());
return promise;
});
it('by passing a resolve and a reject function to it', function() {
const promise = new Promise((resolve, reject) => reject());
promise
.then(() => done(new Error('Expected promise to be rejected.')))
.catch(done);
});
});
describe('extending a `Promise`', function() {
it('is possible', function() {
class MyPromise extends Promise {}
const promise = new MyPromise(resolve => resolve());
promise
.then(() => done())
.catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});
it('must call `super()` in the constructor if it wants to inherit/specialize the behavior', function() {
class ResolvingPromise extends Promise {
constructor() {
super(resolve => resolve());
}
}
return new ResolvingPromise();
});
});
describe('`Promise.all()` returns a promise that resolves when all given promises resolve', function() {
it('returns all results', function(done) {
const promise = Promise.all([new Promise(resolve => resolve(1)), new Promise(resolve => resolve(2))]);
promise
.then(value => { assert.deepEqual(value, [1, 2]); done(); })
.catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});
it('is rejected if one rejects', function(done) {
const promise = Promise.all([new Promise(resolve => resolve(1)), new Promise((resolve, reject) => reject())]);
promise
.then(() => done(new Error('Expected promise to be rejected.')))
.catch(() => done());
});
});
describe('`Promise.race()` returns the first settled promise', function() {
it('if it resolves first, the promises resolves', function(done) {
const lateRejectedPromise = new Promise((resolve, reject) => setTimeout(reject, 100));
const earlyResolvingPromise = new Promise(resolve => resolve('1st :)'));
const promise = Promise.race([lateRejectedPromise, earlyResolvingPromise]);
promise
.then(value => { assert.deepEqual(value, '1st :)'); done(); })
.catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});
it('if one of the given promises rejects first, the new promise is rejected', function(done) {
const earlyRejectedPromise = new Promise((resolve, reject) => reject('I am a rejector'));
const lateResolvingPromise = new Promise(resolve => setTimeout(resolve, 10));
const promise = Promise.race([earlyRejectedPromise, lateResolvingPromise]);
promise
.then(() => done(new Error('Expected promise to be rejected.')))
.catch(value => { assert.deepEqual(value, 'I am a rejector'); done(); })
.catch(done);
});
});
describe('`Promise.resolve()` returns a resolving promise', function() {
it('if no value given, it resolves with `undefined`', function(done) {
const promise = Promise.resolve();
promise
.then(value => { assert.deepEqual(value, void 0); done(); })
.catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});
it('resolves with the given value', function(done) {
const promise = Promise.resolve('quick resolve');
promise
.then(value => { assert.deepEqual(value, 'quick resolve'); done(); })
.catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});
});
describe('`Promise.reject()` returns a rejecting promise', function() {
it('if no value given, it rejects with `undefined`', function(done) {
const promise = Promise.reject();
promise
.then(() => done(new Error('Expected promise to be rejected.')))
.catch(value => { assert.deepEqual(value, void 0); done(); })
.catch(done);
});
it('rejects only', function(done) {
const promise = Promise.reject('quick reject');
promise
.then(() => done(new Error('Expected promise to be rejected.')))
.catch(value => { assert.deepEqual(value, 'quick reject'); done(); })
.catch(done);
});
});
});
| JavaScript | 0.000004 | @@ -948,32 +948,36 @@
o it', function(
+done
) %7B%0A const
|
837f0f1a08d41f09c7cff899322f8b85625e49ca | Fix for Index Exchange ad tags to wrap creative in iframe (#8138) | ads/ix.js | ads/ix.js | /**
* Copyright 2016 The AMP HTML Authors. 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.
*/
import {writeScript, loadScript} from '../3p/3p';
import {doubleclick} from '../ads/google/doubleclick';
const DEFAULT_TIMEOUT = 500; // ms
/**
* @param {!Window} global
* @param {!Object} data
*/
export function ix(global, data) {
if (!('slot' in data)) {
global.CasaleArgs = data;
writeScript(global, 'https://js-sec.indexww.com/indexJTag.js');
} else { //DFP ad request call
let calledDoubleclick = false;
data.ixTimeout = isNaN(data.ixTimeout) ? DEFAULT_TIMEOUT : data.ixTimeout;
const timer = setTimeout(() => {
callDoubleclick();
}, data.ixTimeout);
const callDoubleclick = function() {
if (calledDoubleclick) { return; }
calledDoubleclick = true;
clearTimeout(timer);
delete data['ixId'];
delete data['ixSlot'];
delete data['ixTimeout'];
data.targeting['IX_AMP'] = '1';
doubleclick(global, data);
};
data.targeting = data.targeting || {};
if (typeof data.ixId === 'undefined' || isNaN(data.ixId)) {
callDoubleclick();
return;
} else {
data.ixId = parseInt(data.ixId, 10);
}
if (typeof data.ixSlot === 'undefined' || isNaN(data.ixSlot)) {
data.ixSlot = 1;
} else {
data.ixSlot = parseInt(data.ixSlot, 10);
}
if (typeof global._IndexRequestData === 'undefined') {
global._IndexRequestData = {};
global._IndexRequestData.impIDToSlotID = {};
global._IndexRequestData.reqOptions = {};
global._IndexRequestData.targetIDToBid = {};
}
global.IndexArgs = {
siteID: data.ixId,
slots: [{
width: data.width,
height: data.height,
id: data.ixSlot,
}],
callback: (responseID, bids) => {
if (typeof bids !== 'undefined' && bids.length > 0) {
const target = bids[0].target.substring(0,2) === 'O_' ? 'IOM' : 'IPM';
data.targeting[target] = bids[0].target.substring(2);
}
callDoubleclick();
},
};
global.addEventListener('message', event => {
if (typeof event.data !== 'string' ||
event.data.substring(0,11) !== 'ix-message-') {
return;
}
indexAmpRender(document, event.data.substring(11), global);
});
loadScript(global, 'https://js-sec.indexww.com/apl/apl6.js', undefined, () => {
callDoubleclick();
});
}
}
function indexAmpRender(doc, targetID, global) {
try {
const ad = global._IndexRequestData.targetIDToBid[targetID].pop();
if (ad != null) {
const admDiv = document.createElement('div');
admDiv.setAttribute('style', 'position: absolute; top: 0; left: 0;');
admDiv./*OK*/innerHTML = ad;
document.getElementById('c').appendChild(admDiv);
} else {
global.context.noContentAvailable();
}
} catch (e) {
global.context.noContentAvailable();
};
}
| JavaScript | 0 | @@ -3143,19 +3143,21 @@
onst adm
-Div
+Frame
= docum
@@ -3179,11 +3179,14 @@
nt('
-div
+iframe
');%0A
@@ -3195,36 +3195,118 @@
-admDiv.setAttribute('
+const w = global.IndexArgs.slots%5B0%5D.width;%0A const h = global.IndexArgs.slots%5B0%5D.height;%0A let
style
-',
+ =
'po
@@ -3312,17 +3312,16 @@
osition:
-
absolute
@@ -3325,117 +3325,467 @@
ute;
-
top:
-
0;
-
left:
-
0;
-');%0A admDiv./*OK*/innerHTML = ad;%0A document.getElementById('c').appendChild(admDiv
+border:none;';%0A style += 'width:' + w + 'px;height:' + h + 'px;';%0A admFrame.setAttribute('style', style);%0A admFrame.setAttribute('scrolling', 'no');%0A document.getElementById('c').appendChild(admFrame);%0A const ifdoc = admFrame.contentWindow.document;%0A ifdoc.open();%0A ifdoc.write('%3Chtml%3E%3Chead%3E%3Cbase target=%22_top%22%3E%3C/head%3E');%0A ifdoc.write('%3Cbody style=%22margin:0;%22%3E' + ad + '%3C/body%3E%3C/html%3E');%0A ifdoc.close(
);%0A
|
8061b85f63c7494328ce5cc1c8e1708fc16e20fe | add support for update() method | source/api/http.js | source/api/http.js | import { baseUrl } from "config"
import store from "store"
function headers() {
let base = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
const { tokens, currentToken } = store.getState()
if (tokens.get(currentToken)) {
base['Authorization'] = 'Bearer ' + tokens.get(currentToken).access_token
}
return (base)
}
function handleError(response) {
if (response.status >= 200 && response.status < 300) {
return response
}
else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
function handleJSON(response) {
return response.json()
}
export default {
create: (path, record) => {
return fetch(`${baseUrl}${path}`, {
method: "POST",
body: JSON.stringify(record),
mode: 'cors',
headers: {
...headers()
}
})
.then(handleError)
.then(handleJSON)
},
find: (path, query) => {
return fetch(`${baseUrl}${path}`, {
method: "GET",
mode: 'cors',
headers: {
...headers()
}
})
.then(handleError)
.then(handleJSON)
}
}
| JavaScript | 0 | @@ -907,16 +907,266 @@
)%0A %7D,%0A%0A
+ update: (path, record) =%3E %7B%0A return fetch(%60$%7BbaseUrl%7D$%7Bpath%7D%60, %7B%0A method: %22PUT%22,%0A body: JSON.stringify(record),%0A mode: 'cors',%0A headers: %7B%0A ...headers()%0A %7D%0A %7D)%0A .then(handleError)%0A .then(handleJSON)%0A %7D%0A%0A
find:
|
afffed68a24e5768f309f6a99faca5060b7c5c8d | Add allowHighlanderDeactivate prop to Group | source/ui/Group.js | source/ui/Group.js | /**
_enyo.Group_ provides a wrapper around multiple elements. It enables the
creation of radio groups from arbitrary components supporting the
[GroupItem](#enyo.GroupItem) API.
*/
enyo.kind({
name: "enyo.Group",
published: {
/**
If true, only one GroupItem in the component list may be active at
a given time.
*/
highlander: true,
//* The control that was last selected
active: null,
/**
The `groupName` property is used to scope this group to a certain
set of controls. When used, the group only controls activation of controls who
have the same `groupName` property set on them.
*/
groupName: null
},
//* @protected
handlers: {
onActivate: "activate"
},
activate: function(inSender, inEvent) {
if ((this.groupName || inEvent.originator.groupName) && (inEvent.originator.groupName != this.groupName)) {
return;
}
if (this.highlander) {
// deactivation messages are ignored unless it's an attempt
// to deactivate the highlander
if (!inEvent.originator.active) {
// this clause prevents deactivating a grouped item once it's been active.
// the only proper way to deactivate a grouped item is to choose a new
// highlander.
if (inEvent.originator == this.active) {
this.active.setActive(true);
}
} else {
this.setActive(inEvent.originator);
}
}
},
activeChanged: function(inOld) {
if (inOld) {
inOld.setActive(false);
inOld.removeClass("active");
}
if (this.active) {
this.active.addClass("active");
}
}
});
| JavaScript | 0 | @@ -342,16 +342,112 @@
: true,%0A
+%09%09//* If true, an active highlander item may be deactivated%0A%09%09allowHighlanderDeactivate: false,%0A
%09%09//* Th
@@ -1196,16 +1196,76 @@
tive
-.
+,
%0A%09%09%09%09//
+ as long as %60allowHighlanderDeactivate%60 is false. Otherwise,
the
@@ -1269,16 +1269,23 @@
the only
+%0A%09%09%09%09//
proper
@@ -1335,23 +1335,16 @@
se a new
-%0A%09%09%09%09//
highlan
@@ -1385,24 +1385,59 @@
this.active
+ && !this.allowHighlanderDeactivate
) %7B%0A%09%09%09%09%09thi
|
b3c44a194cb437e1e4667ad05067892bbf030efc | Implement the closure-generating click handler generator | public/js/Board.js | public/js/Board.js | function Board(submitBtn, options) {
this.submitBtn = submitBtn;
this.options = options;
}
Board.prototype.prepareBoard = function() {
this.hideButton(this.submitBtn);
var board = this;
this.options.forEach(function(option) {
option.addCallBack(board.makeOnClick(option));
});
};
Board.prototype.makeOnClick = function(option) {
};
Board.prototype.hideButton = function(btn) {
btn.classList.add("hidden");
};
Board.prototype.disableOptions = function() {
this.options.forEach(function(opt) {
opt.disable();
});
};
Board.prototype.enableOptions = function() {
this.options.forEach(function(opt) {
opt.enable();
});
};
| JavaScript | 0.000001 | @@ -327,41 +327,201 @@
ype.
-makeOnClick = function(option) %7B%0A
+sendMove = function(move) %7B%0A%0A%7D;%0A%0ABoard.prototype.makeOnClick = function(option) %7B%0A var move = option.value;%0A var board = this;%0A return function() %7B%0A board.sendMove(move);%0A %7D;
%0A%7D;%0A
|
cbc685a189ddaebe54e5491bbe8d4c022c65e105 | remove dom node after delete | public/js/books.js | public/js/books.js | $(document).ready(function(){
$('#add').click(function(){
$('#thumb').remove();
$('#bookTitle, #authors, #ISBN').val('');
$('.bookInfo').addClass('hide');
})
$('#isbnSearch').click(function(){
$('#thumb').remove();
var isbn = $('#ISBN').val();
var title;
var authors;
var publisher;
var publishedDate;
var description;
var isbn10;
var isbn13;
var smallthumbnail;
var thumbnail;
var price;
var condition;
var bookdata = {};
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn,
dataType: 'json',
success: function(data) {
bookdata.title = data.items[0].volumeInfo.title;
bookdata.authors = data.items[0].volumeInfo.authors;
bookdata.publisher = data.items[0].volumeInfo.publisher;
bookdata.publishedDate = data.items[0].volumeInfo.publishedDate;
bookdata.description = data.items[0].volumeInfo.description;
bookdata.isbn10 = data.items[0].volumeInfo.industryIdentifiers[0].identifier;
bookdata.isbn13 = data.items[0].volumeInfo.industryIdentifiers[1].identifier;
bookdata.smallthumbnail = data.items[0].volumeInfo.imageLinks.smallThumbnail;
bookdata.thumbnail = data.items[0].volumeInfo.imageLinks.thumbnail;
bookdata.owner_description = owner_description;
$('#bookTitle').val(bookdata.title);
$('#authors').val(bookdata.authors);
$('#publisher').val(bookdata.publisher);
$('#publishedDate').val(bookdata.publishedDate);
$('.bookInfo, #showImage').removeClass('hide');
$('#thumbnail').prepend('<img id="thumb" style="width:120px;margin-top:10px "src="'+bookdata.thumbnail+'"/>');
}
})
$('#save').click(function(){
bookdata.price = $('#price').val();
bookdata.condition = $('#condition').val();
bookdata.owner_description = $('#owner_description').val();
// $.post('/newBook', bookdata)
// .done(function(data, textStatus){
// console.log('new book added');
// console.log(textStatus);
// }).fail(function(data, textStatus){
// console.log('error');
// console.log(textStatus);
// })
$.ajax({
url: "/book/new",
type: "POST",
data: bookdata,
success: function(){
// console.log(textStatus + ' saved: '+ data);
},
error: function(){
// console.log(textStatus);
},
statusCode:{
409: function(){
alert('Duplicated Book');
}
}
})
})
})
$('#ISBN').change(function(){
if($(this).val().length >= 10){
$('#isbnSearch').removeClass('disabled');
}
})
$('.remove_item').click(function(){
var _id = $(this).attr('_id');
console.log();
if(confirm("Are you sure you want to delete this Book?")){
$.ajax({
type: "POST",
url: "/book/delete",
data: {"_id":_id},
success: function(data){
console.log(_id + ' deleted ' + data);
// console.log($(this).parent());
$("#"+_id).remove();
}
});
}
})
$(function(){
$('.created').each(function(){
$(this).text(moment(Date.parse($(this).text())).fromNow());
});
});
})
| JavaScript | 0.000001 | @@ -2151,35 +2151,32 @@
unction()%7B%0A%09%09%09%09%09
-//
console.log(text
@@ -2175,37 +2175,12 @@
log(
-textStatus + ' saved: '+ data
+'OK'
);%0A%09
@@ -2213,19 +2213,16 @@
)%7B%0A%09%09%09%09%09
-//
console.
@@ -2221,34 +2221,31 @@
console.log(
-textStatus
+'ERROR'
);%0A%09%09%09%09%7D,%0A%09%09
@@ -2532,16 +2532,47 @@
'_id');%0A
+%09%09var node_to_delte = $(this);%0A
%09%09consol
@@ -2884,68 +2884,38 @@
%09
-// console.log($(this).parent());%0A %09$(%22#%22+_id
+node_to_delte.parent().parent(
).re
@@ -2922,17 +2922,16 @@
move();%0A
-%0A
|
a548e86c0b628b870b80c8eb95eff12a335f5d35 | Update crooz.js | public/js/crooz.js | public/js/crooz.js | "use strict";
var socket;
var mapper;
function main() {
socket = io();
mapper = Mapper.init(document.getElementById('mapCard'));
socket.on('connected', function (users) {
socket.emit('subscribe', users[0]);
console.log(users);
});
socket.on('newPacket', function (packet) {
if(!packet) {return}
console.log(packet);
mapper.addPackets([packet]);
console.log(mapper._packets);
mapper.render();
var car = mapper.car;
document.getElementById('songCard').innerText = car.song;
document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce(
function(a, b) {
return car.mood[a] > car.mood[b] ? a : b
}
);
});
socket.on('newPackets', function (packets) {
if(!packets.length) {return}
console.log(packets);
mapper.addPackets(packets);
console.log(mapper._packets);
mapper.render();
var car = mapper.car;
document.getElementById('songCard').innerText = car.song;
document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce(
function(a, b) {
return car.mood[a] > car.mood[b] ? a : b
}
);
});
}
| JavaScript | 0 | @@ -216,24 +216,27 @@
users%5B0%5D);%0A
+//
cons
@@ -318,501 +318,161 @@
-if(!packet) %7Breturn%7D%0A console.log(packet);%0A mapper.addPackets(%5Bpacket%5D);%0A console.log(mapper._packets);%0A mapper.render();%0A var car = mapper.car;%0A document.getElementById('songCard').innerText = car.song;%0A document.getElementById('moodCard').innerText = Object.keys(car.mood).reduce(%0A function(a, b) %7B%0A return car.mood%5Ba%5D %3E car.mood%5Bb%5D ? a : b%0A %7D%0A );%0A %7D);%0A %0A socket.on('newPackets', function
+handlePackets(%5Bpacket%5D);%0A %7D);%0A %0A socket.on('newPackets', function (packets) %7B%0A handlePackets(packets);%0A %7D);%0A function handlePackets
(pac
@@ -520,38 +520,8 @@
rn%7D%0A
- console.log(packets);%0A
@@ -544,32 +544,35 @@
ckets(packets);%0A
+//
console.
@@ -648,16 +648,98 @@
er.car;%0A
+ document.getElementById('speedCard').innerText = car.speed*3.6 + %22 km/h%22;%0A
@@ -998,13 +998,11 @@
);%0A %7D
-);
%0A%7D%0A
|
cd7d65e48289ba63a083f82f5de34b5a9c35c0ca | Fix formatting | web/google-analytics.js | web/google-analytics.js | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-7409939-1', 'auto'); // Replace with your property ID.
ga('send', 'pageview');
| JavaScript | 0.057169 | @@ -9,21 +9,31 @@
n(i,
+
s,
+
o,
+
g,
+
r,
+
a,
+
m)
-%7B
+ %7B%0A
i%5B'G
@@ -58,22 +58,31 @@
ct'%5D
-=r;
+ = r;%0A
i%5Br%5D
-=
+ =
i%5Br%5D
+
%7C%7C
+
func
@@ -91,26 +91,35 @@
on()
+
%7B%0A
+
(i%5Br%5D.q
-=
+ =
i%5Br%5D.q
+
%7C%7C
+
%5B%5D).
@@ -137,19 +137,27 @@
nts)
+%0A
%7D,
+
i%5Br%5D.l
-=1*
+ = 1 *
new
@@ -167,10 +167,15 @@
e();
-a=
+%0A a =
s.cr
@@ -194,10 +194,16 @@
o),%0A
-m=
+ m =
s.ge
@@ -231,26 +231,39 @@
%5B0%5D;
+%0A
a.async
-=1;a.src=g;
+ = 1;%0A a.src = g;%0A
m.pa
@@ -286,16 +286,17 @@
efore(a,
+
m)%0A%7D)(wi
@@ -300,16 +300,17 @@
(window,
+
document
@@ -310,16 +310,17 @@
ocument,
+
'script'
@@ -320,16 +320,17 @@
script',
+
'//www.g
@@ -363,16 +363,17 @@
ics.js',
+
'ga');%0A%0A
@@ -409,17 +409,16 @@
'auto');
-
// Repl
|
99d9cdaaeb3083da8e3896adc9b1b133e0627aa3 | Remove error bars when 1 iteration is used. | landscapesim/static/js/column_chart.js | landscapesim/static/js/column_chart.js | function createColumnChart(vegtype, chartDivID, xAxisCategories) {
$(function () {
$('#'+chartDivID).highcharts({
chart: {
type: 'column',
width:308,
height:250,
marginBottom: 100,
marginLeft:58,
marginRight:10,
marginTop:10
},
title: {
text: ''
},
subtitle: {
text: ''
},
credits: {
enabled:false
},
tooltip: {
valueSuffix: '%',
shared: true,
hideDelay:100
},
legend: {
},
xAxis: {
categories:xAxisCategories,
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Percent of Landscape'
}
},
plotOptions: {
column: {
pointPadding:0,
borderWidth: 1
},
series: {
groupPadding: 0.05,
borderWidth: 1
}
}
});
});
}
function createColumnCharts(data, run) {
//$("#iteration_tr_" + run).hide();
$("#column_charts").empty();
var cached_config = modelRunCache[run].config;
var iterations = cached_config.run_control.max_iteration;
var timesteps = cached_config.run_control.max_timestep;
//Restructure Dictionary
//Creates a dictionary of all the final timestep values by vegtype/state class.
var columnChartDictionary = {};
for (var iteration = 1; iteration <= iterations; iteration++) {
$.each(data[iteration][timesteps], function (vegtype, stateclassDictionary) {
if (typeof columnChartDictionary[vegtype] == "undefined") columnChartDictionary[vegtype] = {}
$.each(stateclassDictionary, function (stateclass, value) {
if (typeof columnChartDictionary[vegtype][stateclass] == "undefined") columnChartDictionary[vegtype][stateclass] = []
columnChartDictionary[vegtype][stateclass].push(parseFloat(value) * 100)
})
})
}
//Get the min/median/max from the dictionary above. Store in a new dictionary.
var columnChartDictionaryFinal = {};
$.each(columnChartDictionary, function (vegtype, stateclasses) {
columnChartDictionaryFinal[vegtype] = {};
$.each(stateclasses, function (stateclass, values) {
var min = Math.min.apply(Math, values);
var max = Math.max.apply(Math, values);
var sorted = values.sort();
//var length_of_array = sorted.length;
var low = Math.floor((sorted.length - 1) / 2);
var high = Math.ceil((sorted.length - 1) / 2);
var median = (sorted[low] + sorted[high]) / 2;
columnChartDictionaryFinal[vegtype][stateclass] = [];
columnChartDictionaryFinal[vegtype][stateclass].push(min);
columnChartDictionaryFinal[vegtype][stateclass].push(median);
columnChartDictionaryFinal[vegtype][stateclass].push(max);
})
});
// Go through each veg type in the min/median/max dictionary and make a chart out of the state class values
var chartCount = 1;
$.each(columnChartDictionaryFinal, function (vegtype, stateclasses) {
var chartDivID = "column_chart_" + run + "_" + chartCount;
$("#column_charts").append("<div class='stacked_area_chart_title' id='stacked_area_chart_title_" + chartCount + "'>" + vegtype +
"<span class='show_chart_link' id='show_column_chart_link_" + chartCount + "_" + run + "'> <img class='dropdown_arrows' src='/static/img/up_arrow.png'></span></div>")
//add a new chart div
$("#column_charts").append("<div id='" + chartDivID + "' vegtype='" + vegtype + "' class='column-chart'></div>");
var medians = [];
var minMaxValues = [];
var stateClassNames = [];
$.each(stateclasses, function (name, value) {
stateClassNames.push([name]);
var median = parseFloat(value[1].toFixed(1));
var min = parseFloat(value[0].toFixed(1));
var max = parseFloat(value[2].toFixed(1));
medians.push({y: median, color: colorMap["State Classes"][name]});
minMaxValues.push([min, max])
});
// Create the chart
createColumnChart(vegtype, chartDivID, stateClassNames);
var cc = $('#' + chartDivID).highcharts();
// Add a series for each of the median values
cc.addSeries({
name: 'Percent Cover',
data: medians,
showInLegend: false,
})
cc.addSeries({
name: 'Error Bars',
type: 'errorbar',
data: minMaxValues,
})
$("#show_column_chart_link_" + chartCount + "_" + run).click(function () {
var div = $("#" + chartDivID);
if (div.is(":visible")) {
$(this).html(" <img class='dropdown_arrows' src='/static/img/down_arrow.png'>")
div.hide()
}
else {
$(this).html(" <img class='dropdown_arrows' src='/static/img/up_arrow.png'>")
div.show()
}
});
chartCount++;
});
}
| JavaScript | 0 | @@ -4858,32 +4858,181 @@
lse,%0A %7D)%0A
+%0A // If the model is only run for one iteration, error bars don't make sense since there is no uncertainty.%0A if (iterations %3E 1) %7B%0A
cc.addSe
@@ -5030,32 +5030,36 @@
cc.addSeries(%7B%0A
+
name
@@ -5074,16 +5074,20 @@
Bars',%0A
+
@@ -5116,24 +5116,28 @@
+
data: minMax
@@ -5144,34 +5144,52 @@
Values,%0A
+ %7D) %0A
%7D
-)
%0A%0A $(%22#sh
|
153a17af724229e6b2626c28ece8351d8136c7ae | bring in websocket reconnect code from 'release' branch | ui/redux/actions/websocket.js | ui/redux/actions/websocket.js | import * as ACTIONS from 'constants/action_types';
import { getAuthToken } from 'util/saved-passwords';
import { doNotificationList } from 'redux/actions/notifications';
let socket = null;
export const doSocketConnect = () => dispatch => {
const authToken = getAuthToken();
if (!authToken) {
console.error('Unable to connect to web socket because auth token is missing'); // eslint-disable-line
return;
}
if (socket !== null) {
socket.close();
}
socket = new WebSocket(`wss://api.lbry.com/subscribe?auth_token=${authToken}`);
socket.onmessage = e => {
const data = JSON.parse(e.data);
if (data.type === 'pending_notification') {
dispatch(doNotificationList());
}
};
socket.onerror = e => {
console.error('Error connecting to websocket', e); // eslint-disable-line
};
socket.onclose = e => {
// Reconnect?
};
socket.onopen = e => {
console.log('\nConnected to WS \n\n'); // eslint-disable-line
};
};
export const doSocketDisconnect = () => ({
type: ACTIONS.WS_DISCONNECT,
});
| JavaScript | 0 | @@ -183,16 +183,37 @@
= null;%0A
+let retryCount = 0;%0A%0A
export c
@@ -435,16 +435,49 @@
n;%0A %7D%0A%0A
+ function connectToSocket() %7B%0A
if (so
@@ -497,16 +497,18 @@
) %7B%0A
+
socket.c
@@ -517,19 +517,18 @@
se();%0A
-%7D%0A%0A
+
socket
@@ -535,79 +535,335 @@
= n
-ew WebSocket(%60wss://api.lbry.com/subscribe?auth_token=$%7BauthToken%7D%60);%0A%0A
+ull;%0A %7D%0A%0A const timeToWait = retryCount ** 2 * 1000;%0A setTimeout(() =%3E %7B%0A const url = %60wss://api.lbry.com/subscribe?auth_token=$%7BauthToken%7D%60;%0A socket = new WebSocket(url);%0A socket.onopen = e =%3E %7B%0A retryCount = 0;%0A console.log('%5CnConnected to WS %5Cn%5Cn'); // eslint-disable-line%0A %7D;%0A
so
@@ -878,32 +878,36 @@
essage = e =%3E %7B%0A
+
const data =
@@ -928,24 +928,28 @@
data);%0A%0A
+
if (data.typ
@@ -986,16 +986,20 @@
%7B%0A
+
dispatch
@@ -1030,16 +1030,28 @@
+
%7D%0A
-%7D;%0A%0A
+ %7D;%0A%0A
so
@@ -1064,32 +1064,36 @@
nerror = e =%3E %7B%0A
+
console.erro
@@ -1099,73 +1099,119 @@
or('
-Error connecting to websocket', e); // eslint-disable-line%0A
+websocket onerror', e);%0A // onerror and onclose will both fire, so nothing is needed here%0A
%7D;%0A%0A
+
so
@@ -1240,122 +1240,156 @@
-// Reconnect?%0A %7D;%0A%0A
+ console.error('web
socket
-.onopen = e =%3E %7B%0A
+ onclose', e);%0A retryCount += 1;%0A
+
con
-sole.log('%5CnConnected to WS %5Cn%5Cn'); // eslint-disable-line%0A %7D
+nectToSocket();%0A %7D;%0A %7D, timeToWait);%0A %7D%0A%0A connectToSocket()
;%0A%7D;
|
d3fc6f58e3e0196947e3a1f1450520d6ce3f2718 | fix lint on public/js/slide.js | public/js/slide.js | public/js/slide.js | /* eslint-env browser, jquery */
/* global serverurl, Reveal, RevealMarkdown */
import { preventXSS } from './render'
import { md, updateLastChange, removeDOMEvents, finishView } from './extra'
require('../css/extra.css')
require('../css/site.css')
const body = preventXSS($('.slides').text())
window.createtime = window.lastchangeui.time.attr('data-createtime')
window.lastchangetime = window.lastchangeui.time.attr('data-updatetime')
updateLastChange()
const url = window.location.pathname
$('.ui-edit').attr('href', `${url}/edit`)
$('.ui-print').attr('href', `${url}?print-pdf`)
$(document).ready(() => {
// tooltip
$('[data-toggle="tooltip"]').tooltip()
})
function extend () {
const target = {}
for (const source of arguments) {
for (const key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target
}
// Optional libraries used to extend on reveal.js
const deps = [{
src: `${serverurl}/build/reveal.js/lib/js/classList.js`,
condition () {
return !document.body.classList
}
}, {
src: `${serverurl}/build/reveal.js/plugin/notes/notes.js`,
async: true,
condition () {
return !!document.body.classList
}
}]
const slideOptions = {
separator: '^(\r\n?|\n)---(\r\n?|\n)$',
verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
}
const slides = RevealMarkdown.slidify(body, slideOptions)
$('.slides').html(slides)
RevealMarkdown.initialize()
removeDOMEvents($('.slides'))
$('.slides').show()
// default options to init reveal.js
const defaultOptions = {
controls: true,
progress: true,
slideNumber: true,
history: true,
center: true,
transition: 'none',
dependencies: deps
}
// options from yaml meta
const meta = JSON.parse($('#meta').text())
var options = meta.slideOptions || {}
if (options.hasOwnProperty('spotlight')) {
defaultOptions.dependencies.push({
src: `${serverurl}/build/reveal.js/plugin/spotlight/spotlight.js`
})
}
if (options.hasOwnProperty('allottedTime') || options.hasOwnProperty('allottedMinutes')) {
defaultOptions.dependencies.push({
src: `${serverurl}/build/reveal.js/plugin/elapsed-time-bar/elapsed-time-bar.js`
})
if (options.hasOwnProperty('allottedMinutes')) {
options.allottedTime = options.allottedMinutes * 60 * 1000
}
}
const view = $('.reveal')
// text language
if (meta.lang && typeof meta.lang === 'string') {
view.attr('lang', meta.lang)
} else {
view.removeAttr('lang')
}
// text direction
if (meta.dir && typeof meta.dir === 'string' && meta.dir === 'rtl') {
options.rtl = true
} else {
options.rtl = false
}
// breaks
if (typeof meta.breaks === 'boolean' && !meta.breaks) {
md.options.breaks = false
} else {
md.options.breaks = true
}
// options from URL query string
const queryOptions = Reveal.getQueryHash() || {}
options = extend(defaultOptions, options, queryOptions)
Reveal.initialize(options)
window.viewAjaxCallback = () => {
Reveal.layout()
}
function renderSlide (event) {
if (window.location.search.match(/print-pdf/gi)) {
const slides = $('.slides')
let title = document.title
finishView(slides)
document.title = title
Reveal.layout()
} else {
const markdown = $(event.currentSlide)
if (!markdown.attr('data-rendered')) {
let title = document.title
finishView(markdown)
markdown.attr('data-rendered', 'true')
document.title = title
Reveal.layout()
}
}
}
Reveal.addEventListener('ready', event => {
renderSlide(event)
const markdown = $(event.currentSlide)
// force browser redraw
setTimeout(() => {
markdown.hide().show(0)
}, 0)
})
Reveal.addEventListener('slidechanged', renderSlide)
const isWinLike = navigator.platform.indexOf('Win') > -1
if (isWinLike) $('.container').addClass('hidescrollbar')
| JavaScript | 0.000003 | @@ -784,22 +784,22 @@
if (
-source
+Object
.hasOwnP
@@ -805,17 +805,30 @@
Property
-(
+.call(source,
key)) %7B%0A
@@ -1810,31 +1810,30 @@
%7C%7C %7B%7D%0A%0Aif (
-options
+Object
.hasOwnPrope
@@ -1835,17 +1835,31 @@
Property
-(
+.call(options,
'spotlig
@@ -1981,31 +1981,30 @@
%7D)%0A%7D%0A%0Aif (
-options
+Object
.hasOwnPrope
@@ -1998,33 +1998,47 @@
t.hasOwnProperty
-(
+.call(options,
'allottedTime')
@@ -2040,23 +2040,22 @@
me') %7C%7C
-options
+Object
.hasOwnP
@@ -2053,33 +2053,47 @@
t.hasOwnProperty
-(
+.call(options,
'allottedMinutes
@@ -2230,23 +2230,22 @@
)%0A if (
-options
+Object
.hasOwnP
@@ -2251,17 +2251,31 @@
Property
-(
+.call(options,
'allotte
@@ -3133,26 +3133,28 @@
lides')%0A
-le
+cons
t title = do
@@ -3339,18 +3339,20 @@
%7B%0A
-le
+cons
t title
|
21e4d5dd8637c8abbd0f3dc3dcf6ab4febf137a4 | Enable sourcemaps for webpack | webpack.config.babel.js | webpack.config.babel.js | import path from 'path';
import webpack from 'webpack';
import { NODE_ENV, isDevelopment } from './gulp/util/env.js';
const outputFileName = '[name].js';
let options = {
entry: {
vendor: [ 'jquery', './vendor.js' ],
main: './main.js'
},
output: {
filename: outputFileName,
path: __dirname + '/dest/assets/javascripts',
publicPath: '/assets/javascripts/',
library: '[name]'
},
// watch: isDevelopment,
devtool: isDevelopment ? 'eval-source-map' : 'source-map',
context: path.resolve(__dirname, 'source/static/scripts'),
module: {
noParse: /\/node_modules\/(jquery|backbone)/,
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
}
]
}
};
options.plugins = [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
filename: outputFileName
}),
new webpack.DefinePlugin({
NODE_ENV: JSON.stringify(NODE_ENV),
'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
];
if (isDevelopment) {
options.plugins.push(
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
);
}
else {
options.plugins.push(
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true
},
output: {
comments: false
}
})
);
}
export default options;
| JavaScript | 0 | @@ -408,35 +408,8 @@
%7D,%0A
- // watch: isDevelopment,%0A
de
@@ -1486,24 +1486,47 @@
yJsPlugin(%7B%0A
+ sourceMap: true,%0A
compre
|
dcaddf16684e501b8245b4e6e29e8d043c18573d | Fix file-loader mappings in production | webpack.config.babel.js | webpack.config.babel.js | import path from 'path';
import process from 'process';
import webpack from "webpack";
import ManifestPlugin from "webpack-manifest-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
import TerserPlugin from "terser-webpack-plugin";
// Check for production mode
const PROD = process.env.NODE_ENV === "production";
const src = path.resolve(__dirname, 'web', 'resources');
const dep = path.join(src, 'node_modules');
const dst = path.resolve(__dirname, 'web', 'static');
export default {
mode: PROD ? "production" : "development",
// We're creating a web application
target: 'web',
context: src,
entry: {
'advanced-search': './js/advanced-search.js',
'balance-chart': './js/balance-chart.js',
'lazy-load-select': './js/lazy-load-select.js',
'mac-address-input': './js/mac-address-input.js',
'main': './main.js',
'navigation': './js/navigation.js',
'tooltip': './js/tooltip.js',
'table-fixed-header': './js/table-fixed-header.js',
'traffic-graph': './js/traffic-graph.js',
'transaction-chart': './js/transaction-chart.js',
'transaction-form': './js/transaction-form.js',
'unlimited-end-date': './js/unlimited-end-date.js',
'select-multiple-improvement': './js/select-multiple-improvement.js',
'tab-anchor': './js/tab-anchor.js',
},
output: {
path: dst,
filename: `[name].[chunkhash].${PROD ? 'min.js' : 'js'}`,
hashFunction: 'md5',
hashDigest: 'hex',
hashDigestLength: 32,
pathinfo: !PROD,
},
watchOptions: {
aggregateTimeout: 1000,
ignored: [
dep,
],
},
devtool: PROD ? "source-map" : "eval-source-map",
resolve: {
symlinks: false,
},
optimization: {
minimizer: [
// Compress JavaScript
new TerserPlugin({
cache: true,
parallel: true,
sourceMap: true,
}),
],
runtimeChunk: {
name: "main",
},
splitChunks: {
cacheGroups: {
vendor: {
name: "vendor",
chunks: "all",
enforce: true,
test: dep,
},
},
},
},
plugins: [
// Clean the destination
new CleanWebpackPlugin(),
// Create stable module IDs
new webpack.HashedModuleIdsPlugin({
hashFunction: 'md5',
hashDigest: 'hex',
hashDigestLength: 32,
}),
// Put CSS into a separate file
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css',
allChunks: true,
}),
// Generate a manifest file, that maps entries and assets to their
// output file.
new ManifestPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
].concat(PROD ? [
// PROD plugins
] : [
// !PROD plugins
]),
module: {
rules: [
// Use the source-map-loader to reuse existing source maps, that
// are provided by dependencies
{
test: /\.js$/,
use: ["source-map-loader"],
enforce: "pre",
include: dep,
},
// Some dependencies are not proper modules yet, they need to
// be shimmed and their dependencies need to be declared manually.
{
test: /\.js$/,
include: [
'bootstrap',
'bootstrap-datepicker',
'bootstrap-table',
].map(pkg => path.join(dep, pkg)),
},
// Expose our table module as a global variable.
// Functions from this module are referenced through
// data-*-attributes for use by bootstrap-table
{
// test: path.join(src, 'js', 'table.js'),
test: path.join(src, 'js', 'table.js'),
use: {
loader: "expose-loader",
options: {
exposes: "table",
},
},
},
{
test: path.join(dep, 'jquery'),
use: {
loader: "expose-loader",
options: {
exposes: "$",
},
},
},
// Inject bootstrap-table import into its locales
{
test: /\.js$/,
use: {
loader: "imports-loader",
options: {
imports: ['bootstrapTable bootstrap-table'],
},
},
include: path.join(dep, "bootstrap-table", "dist", "locale"),
},
// Transpile modern JavaScript for older browsers.
{
test: /\.js$/,
exclude: dep,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// Use the recommended preset-env
presets: [
['@babel/preset-env', {
targets: {
browsers: [
'IE 11',
'FF 52',
'Chrome 49',
],
},
// Let webpack handle modules
modules: false,
forceAllTransforms: PROD,
}],
],
// Import the babel runtime instead of inlining it in
// every file.
plugins: [
['@babel/plugin-transform-runtime', {
helpers: false,
regenerator: true,
useESModules: true,
}],
],
},
},
},
// Handle CSS
{
test: /\.css$/,
use: [
{
loader: "style-loader",
},
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: "css-loader",
},
],
},
// Handle other assets
{
test: [
/\.(?:gif|ico|jpg|png|svg)$/, // Images
/\.(?:eot|otf|ttf|woff|woff2)$/, // Fonts
/\.(?:xml)$/, // static XML initial for openSearch
],
use: {
loader: 'file-loader',
options: {
name: "[path][name].[hash].[ext]",
publicPath: './',
},
},
},
],
},
};
| JavaScript | 0.999999 | @@ -7480,16 +7480,57 @@
: './',%0A
+ esModule: false,%0A
|
9079a838a2af84c1e71fb3ce1d73010367d5af65 | Fix demo file paths | webpack/config.babel.js | webpack/config.babel.js | import { join } from 'path'
import webpack from 'webpack'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
const PORT = 3000
const PRODUCTION = process.env.NODE_ENV === 'production'
// const LOCAL_IDENT_NAME = PRODUCTION ? '[hash:base64:5]' : '[name]__[local]__[hash:base64:5]'
const PUBLIC_PATH = PRODUCTION ? '/' : `http://localhost:${PORT}/`
const STYLE_LOADER = PRODUCTION ? MiniCssExtractPlugin.loader : 'style-loader'
const PATH_ROOT = join(__dirname, '..')
const PATH_SRC = join(PATH_ROOT, 'src')
const PATH_DEMO = join(PATH_ROOT, 'demo')
const PATH_NODE_MODULES = join(PATH_ROOT, 'node_modules')
const PATH_ASSETS = join(PATH_ROOT, 'assets')
const PATH_INDEX = join(PATH_SRC, 'demo', 'index.html')
export const PATH_DIST = join(PATH_ROOT, 'dist')
export const PATH_REACT_PLAYER = join(PATH_SRC, 'ReactPlayer.js')
export const PATH_STANDALONE = join(PATH_SRC, 'standalone.js')
export const plugins = [
new HtmlWebpackPlugin({
template: PATH_INDEX,
minify: {
collapseWhitespace: true,
quoteCharacter: '\''
}
})
]
export default {
mode: 'development',
devtool: 'cheap-module-eval-source-map',
entry: join(PATH_SRC, 'demo', 'index'),
resolve: {
alias: {
assets: PATH_ASSETS,
'react-dom': '@hot-loader/react-dom'
}
},
module: {
rules: [{
test: /\.js$/,
loader: 'babel-loader',
include: PATH_SRC,
query: {
presets: [['@babel/preset-env', { modules: false }]]
}
}, {
test: /\.css$/,
use: [
STYLE_LOADER,
{
loader: 'css-loader',
options: {
sourceMap: true
// modules: {
// localIdentName: LOCAL_IDENT_NAME
// }
}
},
'postcss-loader'
],
include: PATH_SRC
}, {
test: /\.css$/,
use: [
STYLE_LOADER,
'css-loader?sourceMap'
],
include: PATH_NODE_MODULES
}, {
test: /\.(png|jpg)$/,
loader: 'file-loader?name=assets/[hash].[ext]',
include: PATH_ASSETS
}]
},
output: {
path: PATH_DEMO,
filename: 'app.js',
publicPath: PUBLIC_PATH
},
plugins: [
...plugins,
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
devServer: {
port: PORT,
publicPath: PUBLIC_PATH,
hot: true,
overlay: true,
historyApiFallback: true,
stats: 'minimal'
},
performance: {
hints: false
}
}
| JavaScript | 0.000001 | @@ -368,17 +368,16 @@
TION ? '
-/
' : %60htt
|
890bed0a4567b33feaff491e483b573c9b9f3162 | add json loader | webpack/config/babel.js | webpack/config/babel.js | /**
* Copyright (c) 2015-present, goreutils
* All rights reserved.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const ecmaScriptFileExtensions = require('../../src/pckg/ecmaScriptFileExtensions');
const gorePckg = require('../../package.json');
const isArray = require('lodash/isArray');
const merge = require('lodash/merge');
const os = require('os');
const path = require('path');
const Promise = require('bluebird');
function normalizeAliasPaths(config, pckg) {
const alias = {};
if (!isArray(pckg.directories.lib)) {
alias[pckg.name] = pckg.directories.lib;
}
return merge(alias, pckg.alias);
}
function babel(config, pckg) {
const cacheIdentifier = gorePckg.name + gorePckg.version + pckg.name + pckg.version;
const cacheDirectory = path.resolve(os.tmpdir(), cacheIdentifier);
return Promise.resolve(merge({}, {
bail: true,
externals: pckg.externals,
module: {
loaders: [
{
loader: path.resolve(__dirname, '..', 'babelLoader'),
test: /\.jsx?$/,
query: {
babelrc: false,
cacheDirectory,
cacheIdentifier,
},
},
],
},
plugins: [],
resolve: {
alias: normalizeAliasPaths(config, pckg),
extensions: ecmaScriptFileExtensions(pckg),
root: config.baseDir,
},
}));
}
module.exports = babel;
| JavaScript | 0.000001 | @@ -1248,24 +1248,98 @@
%0A %7D,%0A
+ %7B%0A test: /%5C.json$/,%0A loader: 'json',%0A %7D,%0A
%5D,%0A
|
d616213e0a459f5b9b89e55faf30e0eaacdaee98 | Remove unused Event | scripts/background/main.js | scripts/background/main.js | /**
* Chrome-Extension-Template v1.0
*
* @author Dustin Breuer <dustin.breuer@thedust.in>
* @version 1.0
* @category chrome-extension
* @licence MIT http://opensource.org/licenses/MIT
*/
window.addEventListener("load", function () {
/**
* An Array that contains all connected Ports
* @type {PortList}
* @private
*/
var _oPortList = new PortList(),
/**
* @class
*/
HelloMessage = Message.createMessageType("hello"),
/***
* @class
*/
ConfigMessage = Message.createMessageType("config",
/**
* @lends Message.prototype
*/
{
foo : "bar"
}
);
chrome.runtime.onConnect.addListener(_onRuntimePortConnect);
/**
* Callback for connecting with tab-injected Script
*
* @param {chrome.runtime.Port} oPort The connected Port
*
* @private
*/
function _onRuntimePortConnect(oPort) {
console.info("%O connected", oPort);
_oPortList.add(oPort);
oPort.onDisconnect.addListener(_onRuntimePortDisconnect);
oPort.onMessage.addListener(_onRuntimePortMessage);
oPort.postMessage(new HelloMessage());
}
/**
* Callback for disconnecting with tab-injected Script
*
* @param {chrome.runtime.Port} oPort The disconnected Port
*
* @private
*/
function _onRuntimePortDisconnect(oPort) {
console.info("%O disconnected", oPort);
_oPortList.remove(oPort);
}
/**
* Callback for receiving a message from a tab-injected Script
*
* @param {*} oMessage The message sent by the calling script
* @param {chrome.runtime.Port} oSender
* @param {Function} oSendResponse Function to call (at most once) when you have a response
* {@link http://developer.chrome.com/extensions/runtime.html#property-onMessage-sendResponse}
*
* @returns {?Boolean} returns true, to keep the message channel open and send a response asynchronously
*
* @private
* @link http://developer.chrome.com/extensions/runtime.html#event-onMessage
*/
function _onRuntimePortMessage(oMessage, oSender, oSendResponse) {
console.info("Receive %O by %O", oMessage, oSender);
switch (oMessage.type) {
case HelloMessage.Type:
oSendResponse(new ConfigMessage({
foo : "myBar"
}));
break;
}
// uncomment if you want to keep the message channel open and send a response asynchronously
// {@link http://developer.chrome.com/extensions/runtime.html#property-onMessage-sendResponse}
// return true;
}
chrome.extension.onRequest.addListener(function () {
console.info("chrome.extension.onRequest(%O)", arguments);
});
chrome.webNavigation.onDOMContentLoaded.addListener(function (oDetails) {
console.info("chrome.webNavigation.onDOMContentLoaded(%O)", oDetails);
var iTabId = oDetails.tabId;
chrome.tabs.get(iTabId, function (oTab) {
// chrome.tabs.insertCSS(oTab.id, {
// file : 'background/inject-style.css',
// runAt : 'document_start'
// });
chrome.tabs.executeScript(oTab.id, {
file : 'background/inject.js',
runAt : 'document_start'
});
});
});
});
| JavaScript | 0.000002 | @@ -2764,141 +2764,8 @@
%7D%0A%0A
- chrome.extension.onRequest.addListener(function () %7B%0A console.info(%22chrome.extension.onRequest(%25O)%22, arguments);%0A %7D);%0A%0A
@@ -2903,16 +2903,35 @@
aded(%25O)
+ :: ready to inject
%22, oDeta
@@ -3303,32 +3303,41 @@
file : '
+/scripts/
background/injec
|
b9567457cafba676ebd659e25919e2831a3186f4 | clones the input object | weightedRandomPicker.js | weightedRandomPicker.js | function WeightedRandomPicker (weightedValues) {
this.weightedValues = weightedValues || {};
this.randomPick = function(options){
var options = options || {};
var uniq = options.uniq || false;
var times = options.times || 1;
var picks = [];
if (uniq && times > this.getKeys().length) {
throw new InvalidUniqTimesException();
} else {
for (var i=0; i<times; i++){
picks.push(_randomPick.call(this, uniq));
}
}
return options.times > 1 ? picks : picks[0];
};
this.getKeys = function(){
return Object.keys(this.weightedValues);
};
this.getValues = function(){
var values = this.getKeys().map(function(key) {
return this.weightedValues[key];
}.bind(this));
return values;
};
var InvalidUniqTimesException = function(){
this.toString = function(){
return "While uniq is set to true, times option cannot be more than what the actual number of key/values in object. Please confirm.";
};
};
var _getSumOfWeights = function(){
var sumOfWeights = this.getValues().reduce(function(a,b){
return a + b;
});
return sumOfWeights;
};
var _getRandom = function(max, min){
var min = min || 0;
var max = max || _getSumOfWeights.call(this);
return Math.random() * max;
};
var _randomPick = function(uniq){
var random = _getRandom.call(this);
var pick;
this.getKeys().forEach(function(key, index){
var weight = this.weightedValues[key];
if (weight >= random) {
pick = pick || key; //only store the first pick
if (uniq && this.weightedValues[pick]) {
// delete from pick not from key since
// it is not breaking out from forEach
// also checks if the pick exists in
// the object
delete this.weightedValues[pick];
}
}
random -= weight;
}.bind(this));
return pick;
};
} | JavaScript | 0.999999 | @@ -24,17 +24,24 @@
Picker (
-w
+initialW
eightedV
@@ -52,21 +52,127 @@
s) %7B%0A%0A
-this.
+//clones the initialWeightedValues:%0A //set default to empty object for the JSON lib clone trick to work%0A var
weighted
@@ -180,17 +180,24 @@
alues =
-w
+initialW
eightedV
@@ -208,16 +208,129 @@
s %7C%7C %7B%7D;
+%0A // clones param object to property of this%0A this.weightedValues = JSON.parse(JSON.stringify(weightedValues));
%0A%0A this
|
0eda3f7a23d491ddaf0a96d8802ac7ccfe38b6dd | Use getView instead view | web/app/view/DevicesController.js | web/app/view/DevicesController.js | /*
* Copyright 2015 - 2016 Anton Tananaev (anton.tananaev@gmail.com)
*
* 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.
*/
Ext.define('Traccar.view.DevicesController', {
extend: 'Ext.app.ViewController',
alias: 'controller.devices',
requires: [
'Traccar.view.CommandDialog',
'Traccar.view.DeviceDialog'
],
config: {
listen: {
controller: {
'*': {
selectDevice: 'selectDevice',
selectReport: 'selectReport'
}
},
store: {
'#Devices': {
update: 'onUpdateDevice'
}
}
}
},
init: function () {
var readonly = Traccar.app.getServer().get('readonly') && !Traccar.app.getUser().get('admin');
this.lookupReference('toolbarAddButton').setVisible(!readonly);
this.lookupReference('toolbarEditButton').setVisible(!readonly);
this.lookupReference('toolbarRemoveButton').setVisible(!readonly);
},
onAddClick: function () {
var device, dialog;
device = Ext.create('Traccar.model.Device');
device.store = Ext.getStore('Devices');
dialog = Ext.create('Traccar.view.DeviceDialog');
dialog.down('form').loadRecord(device);
dialog.show();
},
onEditClick: function () {
var device, dialog;
device = this.getView().getSelectionModel().getSelection()[0];
dialog = Ext.create('Traccar.view.DeviceDialog');
dialog.down('form').loadRecord(device);
dialog.show();
},
onRemoveClick: function () {
var device = this.getView().getSelectionModel().getSelection()[0];
Ext.Msg.show({
title: Strings.deviceDialog,
message: Strings.sharedRemoveConfirm,
buttons: Ext.Msg.YESNO,
buttonText: {
yes: Strings.sharedRemove,
no: Strings.sharedCancel
},
fn: function (btn) {
var store;
if (btn === 'yes') {
store = Ext.getStore('Devices');
store.remove(device);
store.sync();
}
}
});
},
onCommandClick: function () {
var device, deviceId, command, dialog, comboStore;
device = this.getView().getSelectionModel().getSelection()[0];
deviceId = device.get('id');
command = Ext.create('Traccar.model.Command');
command.set('deviceId', deviceId);
dialog = Ext.create('Traccar.view.CommandDialog');
comboStore = dialog.down('form').down('combobox').getStore();
comboStore.getProxy().setExtraParam('deviceId', deviceId);
dialog.down('form').loadRecord(command);
dialog.show();
},
onFollowClick: function (button, pressed) {
if (pressed) {
var device = this.getView().getSelectionModel().getSelection()[0];
this.fireEvent('selectDevice', device, true);
}
},
onSelectionChange: function (selected) {
var empty = selected.getCount() === 0;
this.lookupReference('toolbarEditButton').setDisabled(empty);
this.lookupReference('toolbarRemoveButton').setDisabled(empty);
this.lookupReference('deviceCommandButton').setDisabled(empty || (selected.getLastSelected().get('status') !== 'online'));
if (!empty) {
this.fireEvent('selectDevice', selected.getLastSelected(), true);
}
},
selectDevice: function (device, center) {
this.getView().getSelectionModel().select([device], false, true);
},
selectReport: function (position) {
if (position !== undefined) {
this.getView().getSelectionModel().deselectAll();
}
},
onUpdateDevice: function (store, data) {
this.onSelectionChange(this.view.getSelectionModel());
}
});
| JavaScript | 0 | @@ -4432,20 +4432,25 @@
ge(this.
-v
+getV
iew
+()
.getSele
|
9a06ecb45112aaa8ba4b3240ccfba152ebc44231 | Change GA tracking id | popup/lib/ga.js | popup/lib/ga.js | var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-57493072-3']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); | JavaScript | 0 | @@ -55,17 +55,17 @@
7493072-
-3
+4
'%5D);%0A%0A(f
|
764453430cf53ab5b89ba63752e580cd9b4a288e | Fix locale selector in New RB | indico/modules/rb_new/client/js/common/config/reducers.js | indico/modules/rb_new/client/js/common/config/reducers.js | /* This file is part of Indico.
* Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Indico is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/
import {combineReducers} from 'redux';
import camelizeKeys from 'indico/utils/camelize';
import {requestReducer} from 'indico/utils/redux';
import * as configActions from './actions';
export const initialState = {
roomsSpriteToken: '',
languages: {},
tileServerURL: '',
};
export default combineReducers({
request: requestReducer(configActions.FETCH_REQUEST, configActions.FETCH_SUCCESS, configActions.FETCH_ERROR),
data: (state = initialState, action) => {
switch (action.type) {
case configActions.CONFIG_RECEIVED: {
const {roomsSpriteToken, languages, tileserverUrl: tileServerURL} = camelizeKeys(action.data);
return {
roomsSpriteToken,
languages,
tileServerURL,
};
}
default:
return state;
}
}
});
| JavaScript | 0.000043 | @@ -1343,27 +1343,16 @@
teToken,
- languages,
tileser
@@ -1403,16 +1403,65 @@
.data);%0A
+ const %7Blanguages%7D = action.data;%0A
|
49d6af216b040c05da5bb731436913401b8880cc | stop it from getting caught in a loop | easyreply.user.js | easyreply.user.js | // ==UserScript==
// @name easyreply
// @namespace http://reddit.com/u/undergroundmonorail
// @author monorail
// @version 0.1
// @description easily respond to a user's last message in se chat
// @copyright MIT
// @include *://chat.stackoverflow.com/*
// @include *://chat.stackexchange.com/*
// @include *://chat.meta.stackexchange.com/*
// ==/UserScript==
function withJQuery(f) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.textContent = '('+ f + ')(jQuery)';
document.head.appendChild(script);
}
withJQuery(easyreply);
function easyreply($) {
function messageAuthor(message) {
return message.parent().parent().children('.signature').children('.username').text().replace(/ /g, '');
}
function getNewText(old) {
var newText = '';
var firstWord = old.split(' ')[0];
if (firstWord[0] == '@' && firstWord.slice(-1) == '@') {
var message = $('.message:last');
while (message.length && firstWord != '@' + messageAuthor(message) + '@') {
var prev = message.prev('.message');
if (!prev.length) {
prev = message.closest('.monologue').prevAll('.monologue').eq(0).find('.message:last');
}
if (prev.length) {
message = prev;
}
}
if (message.length) {
newText = ':' + message.attr('id').split('-')[1] + ' ' + old.split(' ').slice(1).join(' ');
} else {
newText = old;
}
} else {
newText = old;
}
return newText;
}
var input = $('#input');
input.keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
input[0].value = getNewText(input[0].value);
$('sayit-button').click();
}
});
// i don't know what this means but doorknob's code has it ¯\_(ツ)_/¯
var kdevts = $('#input').data('events').keydown;
kdevts.unshift(kdevts.pop());
}
| JavaScript | 0.000001 | @@ -1165,32 +1165,8 @@
%09%09%7D%0A
-%09%09%09%09if (prev.length) %7B%0A%09
%09%09%09%09
@@ -1181,22 +1181,16 @@
= prev;%0A
-%09%09%09%09%7D%0A
%09%09%09%7D%0A%09%09%09
|
af251a6a8c7d0e71a6f75dbff1e5edc9c37888da | Remove Interval | web/www/js/index.js | web/www/js/index.js | var activeView = "";
$.get("http://127.0.0.1:1338/views", function (views) {
$('.nav-sidebar').html("");
views.forEach(function(view){
$(".nav-sidebar").append(`<li data-view="` + view.view + `"><a href="#" onclick="loadData('` + view.view + `')">` + view.name + `</a></li>`);
});
loadData(views[0].view);
});
function loadData(view) {
if(!view)
view = activeView
else
activeView = view;
$("li[data-view]").removeClass("active");
$("li[data-view=" + view + "]").addClass("active");
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) {
var table = `<div class="table-responsive"><table class="table table-striped"><thead><tr>`;
view.headers.forEach(function (header) {
table += "<th>" + header.text + "</th>";
});
table += `</tr></thead><tbody>`;
view.data.forEach(function (datum) {
table += `<tr>`;
view.headers.forEach(function (header) {
table += "<td>" + getDescendantProp(datum, header.value) + "</td>";
});
table += `</tr>`;
});
table += `</tbody></table></div>`
$(".main").html(table);
$('table').DataTable({
"order": []
});
});
});
}
/* http://stackoverflow.com/a/8052100 */
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
setInterval(function(){
loadData();
}, 1000); | JavaScript | 0 | @@ -1364,52 +1364,4 @@
j;%0A%7D
-%0A%0AsetInterval(function()%7B%0A%09loadData();%0A%7D, 1000);
|
ab1c723c487a4226543d230e2fedb950083857f8 | update about page | elements/about.js | elements/about.js | var BaseElement = require('base-element')
var inherits = require('inherits')
module.exports = About
inherits(About, BaseElement)
function About (options) {
if (!(this instanceof About)) return new About(options)
BaseElement.call(this)
}
About.prototype.render = function (state) {
var h = this.html
var elements = [
h('h1', 'About EditData.org'),
h('h2', 'Hello')
]
var vtree = h('div.about', elements)
return this.afterRender(vtree)
}
| JavaScript | 0 | @@ -373,17 +373,274 @@
, 'Hello
-'
+. Let me tell you about everything.'),%0A h('p', 'EditData.org is a tool for editing CSV & JSON files from your computer & from GitHub.'),%0A h('p', %5B%0A h('a.button', 'Source on GitHub')%0A %5D),%0A h('p', %5B%0A h('a.button', 'Report an issue')%0A %5D
)%0A %5D%0A
|
0765eeec064535ee601c33e5413063486b5cfad9 | Add callback to handle result of promises queued | promisequeue.js | promisequeue.js | 'use strict';
export class PromiseQueue {
constructor() {
this.promises = [];
this.endCallback;
this.exceptionCallback;
this.running;
}
run() {
if(!this.running) {
if(this.promises.isEmpty()) {
if(this.endCallback) {
this.endCallback();
}
}
else {
this.running = this.promises.shift();
this.running.call()
.then(() => {this.running = undefined; this.run();})
.catch(exception => {if(this.exceptionCallback) {this.exceptionCallback(exception);}});
}
}
}
add(promise) {
this.promises.push(promise);
this.run();
return this;
}
addAll(promises) {
this.promises.pushAll(promises);
this.run();
return this;
}
clear() {
this.promises = [];
return this;
}
then(callback) {
this.endCallback = callback;
return this;
}
catch(callback) {
this.exceptionCallback = callback;
return this;
}
}
| JavaScript | 0 | @@ -1,19 +1,4 @@
-'use strict';%0A%0A
expo
@@ -34,16 +34,31 @@
tructor(
+result_callback
) %7B%0A%09%09th
@@ -75,16 +75,57 @@
s = %5B%5D;%0A
+%09%09this.resultCallback = result_callback;%0A
%09%09this.e
@@ -399,15 +399,102 @@
hen(
-() =%3E %7B
+result =%3E %7B%0A%09%09%09%09%09%09if(this.resultCallback) %7B%0A%09%09%09%09%09%09%09this.resultCallback(result);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09
this
@@ -514,17 +514,23 @@
defined;
-
+%0A%09%09%09%09%09%09
this.run
@@ -532,16 +532,22 @@
s.run();
+%0A%09%09%09%09%09
%7D)%0A%09%09%09%09%09
@@ -567,16 +567,23 @@
ion =%3E %7B
+%0A%09%09%09%09%09%09
if(this.
@@ -602,16 +602,24 @@
lback) %7B
+%0A%09%09%09%09%09%09%09
this.exc
@@ -644,17 +644,30 @@
eption);
-%7D
+%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09
%7D);%0A%09%09%09%7D
|
1bba5fb6d73e5a6fdfb9313a6504e54c906ebd9b | Add count keyword. | lib/ace/mode/xquery_highlight_rules.js | lib/ace/mode/xquery_highlight_rules.js | /*
* eXide - web-based XQuery IDE
*
* Copyright (C) 2011 Wolfgang Meier
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define("ace/mode/xquery_highlight_rules", function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var XQueryHighlightRules = function() {
var keywords = lang.arrayToMap(
("return|for|let|where|order|by|declare|function|variable|xquery|version|option|namespace|import|module|" +
"switch|default|try|catch|group|tumbling|sliding|window|start|end|at|only|" +
"if|then|else|as|and|or|typeswitch|case|ascending|descending|empty|in").split("|")
);
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
start : [ {
token : "text",
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml_pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
regex : "<\\!--",
next : "comment"
}, {
token : "comment",
regex : "\\(:",
next : "comment"
}, {
token : "text", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "constant", // number
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "variable", // variable
regex : "\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b"
}, {
token: "string",
regex : '".*?"'
}, {
token: "string",
regex : "'.*?'"
}, {
token : "text",
regex : "\\s+"
}, {
token: "support.function",
regex: "\\w[\\w+_\\-:]+(?=\\()"
}, {
token: "keyword.operator",
regex: "\\*|=|<|>|\\-|\\+|and|or|eq|ne|lt|gt"
}, {
token: "lparen",
regex: "[[({]"
}, {
token: "rparen",
regex: "[\\])}]"
}, {
token : function(value) {
if (keywords[value])
return "keyword";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
} ],
tag : [ {
token : "text",
regex : ">",
next : "start"
}, {
token : "keyword",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "text",
regex : "\\s+"
}, {
token : "string",
regex : '".*?"'
}, {
token : "string",
regex : "'.*?'"
} ],
cdata : [ {
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
regex : "\\s+"
}, {
token : "text",
regex : "(?:[^\\]]|\\](?!\\]>))+"
} ],
comment : [ {
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token: "comment",
regex : ".*:\\)",
next : "start"
}, {
token : "comment",
regex : ".+"
} ]
};
};
oop.inherits(XQueryHighlightRules, TextHighlightRules);
exports.XQueryHighlightRules = XQueryHighlightRules;
});
| JavaScript | 0 | @@ -1314,16 +1314,22 @@
empty%7Cin
+%7Ccount
%22).split
|
feba59eced18e45f21e2044259fc82c044b9607d | Remove lock | lib/api/controllers/adminController.js | lib/api/controllers/adminController.js | /*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2022 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* 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
*
* https://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';
const Bluebird = require('bluebird');
const kerror = require('../../kerror');
const { NativeController } = require('./baseController');
const { Mutex } = require('../../util/mutex');
/**
* @class AdminController
*/
class AdminController extends NativeController {
constructor () {
super([
'dump',
'loadFixtures',
'loadMappings',
'loadSecurities',
'refreshIndexCache',
'resetCache',
'resetDatabase',
'resetSecurity',
'shutdown'
]);
this.shuttingDown = false;
}
async refreshIndexCache () {
await global.kuzzle.ask('core:storage:public:cache:refresh');
}
/**
* Reset Redis cache
*/
async resetCache (request) {
const database = request.getString('database');
// @todo allow only memoryStorage
if (database === 'internalCache') {
await this.ask('core:cache:internal:flushdb');
}
else if (database === 'memoryStorage') {
await this.ask('core:cache:public:flushdb');
}
else {
throw kerror.get('services', 'cache', 'database_not_found', database);
}
return { acknowledge: true };
}
/**
* Reset all roles, profiles and users
*/
async resetSecurity () {
const mutex = new Mutex('resetSecurity', { timeout: 0 });
if (! await mutex.lock()) {
throw kerror.get('api', 'process', 'action_locked', 'Kuzzle is already reseting roles, profiles and users.');
}
const result = {};
try {
const options = { refresh: 'wait_for' };
result.deletedUsers = await this.ask(
'core:security:user:truncate',
options);
result.deletedProfiles = await this.ask(
'core:security:profile:truncate',
options);
result.deletedRoles = await this.ask(
'core:security:role:truncate',
options);
await global.kuzzle.internalIndex.createInitialSecurities();
}
finally {
await mutex.unlock();
}
return result;
}
/**
* Reset all indexes created by users
*/
async resetDatabase () {
const mutex = new Mutex('resetDatabase', { timeout: 0 });
if (! await mutex.lock()) {
throw kerror.get('api', 'process', 'action_locked', 'Kuzzle is already reseting all indexes.');
}
try {
const indexes = await this.ask('core:storage:public:index:list');
await this.ask('core:storage:public:index:mDelete', indexes);
return { acknowledge: true };
}
finally {
await mutex.unlock();
}
}
/**
* Generate a dump
* Kuzzle will throw a PreconditionError if a dump is already running
*/
dump (request) {
const waitForRefresh = request.input.args.refresh === 'wait_for';
const suffix = request.getString('suffix', 'manual-api-action');
const promise = global.kuzzle.dump(suffix);
return this._waitForAction(waitForRefresh, promise);
}
/**
* Shutdown Kuzzle
*/
async shutdown () {
if (this.shuttingDown) {
throw kerror.get('api', 'process', 'action_locked', 'Kuzzle is already shutting down.');
}
global.kuzzle.shutdown();
return { acknowledge: true };
}
loadFixtures (request) {
const fixtures = request.getBody();
const refresh = request.getRefresh('wait_for');
return global.kuzzle.ask('core:storage:public:document:import', fixtures, {
refresh
});
}
loadMappings (request) {
const mappings = request.getBody();
return this._waitForAction(
request.getRefresh('wait_for'),
global.kuzzle.ask(
'core:storage:public:mappings:import',
mappings,
{ rawMappings: true }));
}
async loadSecurities (request) {
const permissions = request.getBody();
const user = request.getUser();
const onExistingUsers = request.input.args.onExistingUsers;
const force = request.getBoolean('force');
const waitForRefresh = request.getRefresh('wait_for');
const promise = this.ask('core:security:load', permissions, {
force,
onExistingUsers,
refresh: waitForRefresh,
user,
});
return this._waitForAction(waitForRefresh, promise);
}
_waitForAction (waitForRefresh, promise) {
const result = { acknowledge: true };
if (waitForRefresh === 'false') {
// Attaching an error handler to the provided promise to prevent
// uncaught rejections
promise.catch(err => global.kuzzle.log.error(err));
return Bluebird.resolve(result);
}
return promise
.then(() => result);
}
}
module.exports = AdminController;
| JavaScript | 0.000004 | @@ -3147,24 +3147,101 @@
indexes);%0A%0A
+ await this.ask('core:cache:internal:del', 'backend:import:mappings');%0A%0A
return
|
3ead96a686b5681e48230837de4cf2c6a9ece83d | support ie onload listeners | lib/assets/javascripts/jasmine-boot.js | lib/assets/javascripts/jasmine-boot.js | var jsApiReporter;
(function() {
var jasmineEnv = jasmine.getEnv();
jsApiReporter = new jasmine.JsApiReporter();
jasmineEnv.addReporter(jsApiReporter);
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
if (jasmine.ConsoleReporter) {
jasmineEnv.addReporter(new jasmine.ConsoleReporter());
}
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
| JavaScript | 0 | @@ -436,229 +436,255 @@
%0A%0A
-var currentWindowOnload = window.onload;%0A window.onload = function() %7B%0A if (currentWindowOnload) %7B%0A currentWindowOnload();%0A %7D%0A execJasmine();%0A %7D;%0A%0A function execJasmine() %7B%0A jasmineEnv.execute(
+function execJasmine() %7B%0A jasmineEnv.execute();%0A %7D%0A%0A if (window.addEventListener) %7B // W3C%0A window.addEventListener('load', execJasmine, false);%0A %7D else if (window.attachEvent) %7B // MSIE%0A window.attachEvent('onload', execJasmine
);%0A %7D%0A
-%0A
%7D)()
|
48a6d7f3b2b14b9db866d417644a4f4f4f87c12d | fix missing request property | lib/container/RemoteOverridesModule.js | lib/container/RemoteOverridesModule.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy
*/
"use strict";
const { OriginalSource } = require("webpack-sources");
const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
const Module = require("../Module");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const createHash = require("../util/createHash");
const makeSerializable = require("../util/makeSerializable");
const RemoteOverrideDependency = require("./RemoteOverrideDependency");
/** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("../RequestShortener")} RequestShortener */
/** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("../WebpackError")} WebpackError */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
/**
* @typedef {Object} OverrideOptions
* @property {string} import request to new module
*/
const TYPES = new Set(["javascript"]);
class RemoteOverridesModule extends Module {
/**
* @param {[string, OverrideOptions][]} overrides list of overrides
*/
constructor(overrides) {
super("remote-overrides-module");
this._overrides = overrides;
if (overrides.length > 0) {
const hash = createHash("md4");
for (const [key, request] of overrides) {
hash.update(key);
hash.update(request.import);
}
this._overridesHash = hash.digest("hex");
} else {
this._overridesHash = "empty";
}
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `remote overrides ${this._overridesHash}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `remote overrides ${this._overrides
.map(([key, request]) => `${key} = ${request}`)
.join(", ")}`;
}
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
libIdent(options) {
return `webpack/container/remote-overrides/${this._overridesHash.slice(
0,
6
)}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
callback(null, !this.buildInfo);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
this.buildMeta = {};
this.buildInfo = {
strict: true
};
this.clearDependenciesAndBlocks();
for (const [, options] of this._overrides) {
const block = new AsyncDependenciesBlock({});
const dep = new RemoteOverrideDependency(options.import);
block.addDependency(dep);
this.addBlock(block);
}
callback();
}
/**
* @param {Chunk} chunk the chunk which condition should be checked
* @param {Compilation} compilation the compilation
* @returns {boolean} true, if the chunk is ok for the module
*/
chunkCondition(chunk, { chunkGraph }) {
return chunkGraph.getNumberOfEntryModules(chunk) > 0;
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
return TYPES;
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
return this.request;
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
const runtimeRequirements = new Set([RuntimeGlobals.module]);
let i = 0;
const source = Template.asString([
`module.exports = ${runtimeTemplate.basicFunction(
"external",
this._overrides.length > 0
? [
"if(external.override) external.override(Object.assign({",
Template.indent(
this._overrides
.map(([key, options]) => {
const block = this.blocks[i++];
const dep = block.dependencies[0];
const module = moduleGraph.getModule(dep);
return `${JSON.stringify(
key
)}: ${runtimeTemplate.basicFunction(
"",
`return ${runtimeTemplate.blockPromise({
block,
message: "",
chunkGraph,
runtimeRequirements
})}.then(${runtimeTemplate.basicFunction(
"",
`return ${runtimeTemplate.returningFunction(
runtimeTemplate.moduleRaw({
module,
chunkGraph,
request: options.import,
runtimeRequirements
})
)}`
)})`
)}`;
})
.join(",\n")
),
`}, ${RuntimeGlobals.overrides}));`,
"return external;"
]
: [
`if(external.override) external.override(${RuntimeGlobals.overrides});`,
"return external;"
]
)};`
]);
const sources = new Map();
sources.set(
"javascript",
new OriginalSource(source, `webpack/remote-overrides ${this.request}`)
);
return { sources, runtimeRequirements };
}
serialize(context) {
const { write } = context;
write(this._overrides);
super.serialize(context);
}
static deserialize(context) {
const { read } = context;
const obj = new RemoteOverridesModule(read());
obj.deserialize(context);
return obj;
}
}
makeSerializable(
RemoteOverridesModule,
"webpack/lib/container/RemoteOverridesModule"
);
module.exports = RemoteOverridesModule;
| JavaScript | 0.000004 | @@ -4402,182 +4402,8 @@
%09%7D%0A%0A
-%09/**%0A%09 * @returns %7Bstring %7C null%7D absolute path which should be used for condition matching (usually the resource path)%0A%09 */%0A%09nameForCondition() %7B%0A%09%09return this.request;%0A%09%7D%0A%0A
%09/**
@@ -6064,16 +6064,25 @@
rce(
+%0A%09%09%09%09
source,
-
+%0A%09%09%09%09
%60web
@@ -6110,25 +6110,36 @@
$%7Bthis.
-request%7D%60
+_overridesHash%7D%60%0A%09%09%09
)%0A%09%09);%0A%09
|
9651e8d2bff9b66e82d0544d35fcb27ad0311aac | fix js once again | public/index.js | public/index.js | function objectIsEmpty(obj) {
for(var x in obj)
return false;
return true;
}
function draw(groups, nodes, edges) {
var renderer = new dagreD3.Renderer();
var oldDrawNodes = renderer.drawNodes();
var oldDrawEdgePaths = renderer.drawEdgePaths();
renderer.drawEdgePaths(function(graph, root) {
var svgEdges = oldDrawEdgePaths(graph, root);
svgEdges.attr("id", function(u) {
return "edge-" + u;
});
graph.eachEdge(function(u) {
var edge = graph.edge(u);
if(edge.status) {
$("#edge-"+u).attr("class", $("#edge-"+u).attr("class") + " " + edge.status);
if (graph.isDirected() && root.select('#arrowhead-'+edge.status).empty()) {
root
.append('svg:defs')
.append('svg:marker')
.attr('id', 'arrowhead-'+edge.status)
.attr('viewBox', '0 0 10 10')
.attr('refX', 8)
.attr('refY', 5)
.attr('markerUnits', 'strokewidth')
.attr('markerWidth', 8)
.attr('markerHeight', 5)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M 0 0 L 10 5 L 0 10 z');
}
$("#edge-"+u+" path").attr("marker-end", "url(#arrowhead-"+edge.status+")");
}
});
return svgEdges;
});
renderer.drawNodes(function(graph, root) {
var svgNodes = oldDrawNodes(graph, root);
svgNodes.attr("id", function(u) {
return "node-" + u;
});
graph.eachNode(function(u) {
var node = graph.node(u);
$("#node-"+u).attr("class", $("#node-"+u).attr("class") + " " + node.type + " " + node.status);
$("#node-"+u+" rect").attr("rx", "0").attr("ry", "0");
});
return svgNodes;
});
var digraph = dagreD3.json.decode(nodes, edges);
var filtered = digraph;
if(!objectIsEmpty(groups) {
// filter all non-matching groups
filtered = filtered.filterNodes(function(u) {
var value = digraph.node(u);
if(!value.groups) {
return true;
}
for(var i in value.groups) {
if(groups[value.groups[i]]) {
return true;
}
}
return false;
});
// filter orphaned nodes
filtered = filtered.filterNodes(function(u) {
var value = digraph.node(u);
for(var i in value.groups) {
if(groups[value.groups[i]]) {
return true;
}
}
if(filtered.incidentEdges(u).length == 0) {
return false;
}
return true;
});
}
var layout = renderer.layout(
dagreD3.layout().rankDir("LR")).run(
filtered,
d3.select("svg g")
);
var svg = d3.select("svg")
svg.attr("viewBox", "-20 -20 " + (layout.graph().width + 40) + " " + (layout.graph().height + 40));
svg.call(d3.behavior.zoom().on("zoom", function() {
var ev = d3.event;
svg.select("g")
.attr("transform", "translate(" + ev.translate + ") scale(" + ev.scale + ")");
}));
}
| JavaScript | 0 | @@ -1876,24 +1876,25 @@
mpty(groups)
+)
%7B%0A // fi
|
7a045846947d365f2934f02421a1992c12f5341d | add call plugin | plugins/core/plugin.js | plugins/core/plugin.js |
module.exports[0] = require("./groups")
module.exports[1] = require("./friends")
module.exports[2] = require("./identities")
module.exports[3] = require("./connect")
module.exports[4] = require("./addrs")
module.exports[5] = require("./dht")
module.exports[6] = require("./ping")
/*
module.exports[7] = require("./lb")
*/ | JavaScript | 0.000001 | @@ -278,11 +278,8 @@
g%22)%0A
-/*%0A
modu
@@ -309,12 +309,11 @@
(%22./
-lb%22)%0A%0A*/
+call%22)%0A
|
db48a9a716f10746008bee0d95bd472f56316f71 | Fix a mistake | Task2_7/task.js | Task2_7/task.js | window.onload = function(){
var input = document.getElementById("input");
var leftIn = document.getElementById("left_in");
var leftOut = document.getElementById("left_out");
var rightIn = document.getElementById("right_in");
var rightOut = document.getElementById("right_out");
var addChild = document.getElementById("add");
var sortbtn = document.getElementById("sort");
//左侧入
function checkInsert(value){
clearInterval(action);
var listArr=document.getElementsByClassName("li");
if(isNaN(value)){
alert("请输入10-100的数");
return false;
}else if(value<10||value>100){
alert("请输入10-100的数");
return false;
}else if(listArr.length>=60){
alert("数据长度超过60");
return false;
}else{
return true;
}
}
leftIn.addEventListener("click",function(){
if(checkInsert(input.value)){
if(input.value == ""){
alert("输入为空");
}else{
var child = document.createElement("li");
child.innerHTML = input.value;
child.className = "li";
var height = parseInt(input.value)*2;
child.style.height = height + "px";
child.style.lineHeight = height + "px";
addChild.insertBefore(child,addChild.firstChild);
}
}
});
//左侧出
leftOut.addEventListener("click",function(){
clearInterval(action);
var listArr = document.getElementsByClassName("li");
for(var i=0;i<listArr.length;i++){
if(listArr[i].innerHTML == input.value){
addChild.removeChild(listArr[i]);
return;
}
}
alert("没有该元素");
});
//右侧入
rightIn.addEventListener("click",function(){
if(checkInsert(input.value)){
if(input.value == ""){
alert("输入为空");
}else{
var child = document.createElement("li");
child.className = "li";
var height = parseInt(input.value)*2;
child.style.height = height + "px";
child.style.lineHeight = height + "px";
child.innerHTML = input.value;
addChild.insertBefore(child,addChild.lastChild);
}
}
});
//右侧出
rightOut.addEventListener("click",function(){
clearInterval(action);
var listArr = document.getElementsByClassName("li");
for(var i=listArr.length;i>0;i--){
if(listArr[i-1].innerHTML == input.value){
addChild.removeChild(listArr[i-1]);
return;
}
}
alert("没有该元素");
});
//点击某个li
window.addEventListener("click",function(){
//clearInterval(action);
var listArr = document.getElementsByClassName("li");
for(var i =0; i< listArr.length;i++){
listArr[i].onclick=function(){
//console.log(this);
alert("被删除的元素的值:"+this.innerHTML);
this.remove();
}
}
});
sortbtn.addEventListener("click",function(){
sort();
action = setInterval("draw()",speed);
});
}
var action;
var valueArr = [];
var speed = 20;
function sort(){
var listArr = document.getElementsByClassName("li");
for(var i=0;i<listArr.length;i++){
valueArr[i] = parseInt(listArr[i].innerHTML);
}
for(var k=0;k<listArr.length;k++){
var value;
for(var j=0;j<listArr.length-1;j++){
if(valueArr[j]>valueArr[j+1]){
value = valueArr[j];
valueArr[j] = valueArr[j+1];
valueArr[j+1] = value;
}
}
}
return valueArr;
}
function draw(){
var listArr = document.getElementsByClassName("li");
for(var i=0;i<listArr.length;i++){
//console.log(listArr[i].offsetHeight);
var height = listArr[i].offsetHeight;
if(listArr[i].offsetHeight<valueArr[i]*2){
height++;
listArr[i].style.height = height + "px";
listArr[i].style.lineHeight = height + "px";
listArr[i].innerHTML = valueArr[i];
}else if(listArr[i].offsetHeight>valueArr[i]*2){
height--;
listArr[i].style.height = height + "px";
listArr[i].style.lineHeight = height + "px";
listArr[i].innerHTML = valueArr[i];
}
}
} | JavaScript | 0.999999 | @@ -2737,22 +2737,24 @@
%E4%B8%AAli%0A
-window
+addChild
.addEven
@@ -2955,45 +2955,8 @@
()%7B%0A
- //console.log(this);%0A
%09
@@ -3026,16 +3026,37 @@
%09%7D%0A%09%09%7D
+%0A getValues();
%09%0A
@@ -3238,20 +3238,25 @@
unction
-sort
+getValues
()%7B%0A
@@ -3402,24 +3402,62 @@
HTML);%0A %7D
+ %0A%7D%0Afunction sort()%7B%0A getValues();
%0A for(var
@@ -3463,20 +3463,21 @@
r k=0;k%3C
-list
+value
Arr.leng
@@ -3526,20 +3526,21 @@
r j=0;j%3C
-list
+value
Arr.leng
|
a674619b8019693702e5dbdccb89edc1250182ba | Rename JSON key | modules/commands/weather.js | modules/commands/weather.js | 'use strict';
module.exports = {
key: 'weather',
description: 'shows weather station readings',
execute: function(ircbot, config, from, to) {
const request = require('request');
request({
url: 'https://spitfire.initlab.org/weather.json',
json: true
}, function(error, response, body) {
if (error !== null) {
ircbot.say(to, error.reason ? ('Request error: ' + error.reason) : error.toString());
return;
}
if (response && response.statusCode !== 200) {
ircbot.say(to, 'Error getting data, status code=' + response.statusCode);
return;
}
ircbot.say(to, 'Temperature: ' + body.temp_in.toFixed(1) + ' °C in / ' + body.temp_out.toFixed(1) + ' °C out');
ircbot.say(to, 'Humidity: ' + body.hum_in.toFixed(0) + ' % in / ' + body.hum_out.toFixed(0) + ' % out');
ircbot.say(to, 'Pressure: ' + body.abs_pressure.toFixed(1) + ' hPa');
});
}
};
| JavaScript | 0.00012 | @@ -848,12 +848,8 @@
ody.
-abs_
pres
|
20547d3eb8c217ca4806b77dcec9c6141c945329 | Add memo. | background.js | background.js | JavaScript | 0 | @@ -0,0 +1,141 @@
+/*%0A Keeping an empty 'background' script for now, as having one%0A seems to improve performance of the initial popup window display.%0A */%0A
|
|
1fc28b9d688741ac6142d9b2f178422d52c9f287 | change flickr url to scout api key | background.js | background.js | (function(){
var config = {
apiKey: "AIzaSyAfWj-rBzdy7vH7GvqL6u8iyL6PTTwamfw",
authDomain: "scout-1d20f.firebaseapp.com",
databaseURL: "https://scout-1d20f.firebaseio.com",
// storageBucket: "",
};
firebase.initializeApp(config);
}());
(function(){
/**
* Function called when clicking the Login/Logout button.
*/
// [START buttoncallback]
function toggleSignIn() {
if (!firebase.auth().currentUser) {
// [START createprovider]
var provider = new firebase.auth.GoogleAuthProvider();
// [END createprovider]
// [START addscopes]
provider.addScope('https://www.googleapis.com/auth/plus.login');
// [END addscopes]
// [START signin]
firebase.auth().signInWithRedirect(provider);
// [END signin]
} else {
// [START signout]
firebase.auth().signOut();
// [END signout]
}
// [START_EXCLUDE]
document.getElementById('quickstart-sign-in').disabled = true;
// [END_EXCLUDE]
}
// [END buttoncallback]
/**
* initApp handles setting up the Firebase context and registering
* callbacks for the auth status.
*
* The core initialization is in firebase.App - this is the glue class
* which stores configuration. We provide an app name here to allow
* distinguishing multiple app instances.
*
* This method also registers a listener with firebase.auth().onAuthStateChanged.
* This listener is called when the user is signed in or out, and that
* is where we update the UI.
*
* When signed in, we also authenticate to the Firebase Realtime Database.
*/
function initApp() {
// Result from Redirect auth flow.
// [START getidptoken]
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// [START_EXCLUDE]
document.getElementById('quickstart-oauthtoken').textContent = token;
} else {
document.getElementById('quickstart-oauthtoken').textContent = 'null';
// [END_EXCLUDE]
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// [START_EXCLUDE]
if (errorCode === 'auth/account-exists-with-different-credential') {
alert('You have already signed up with a different auth provider for that email.');
// If you are using multiple auth providers on your app you should handle linking
// the user's accounts here.
} else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END getidptoken]
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function(user) {
// var usersRef = firebase.database().ref('users').child("jen").toString();
var usersRef = firebase.database().ref('users');
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var refreshToken = user.refreshToken;
var providerData = user.providerData;
// [START_EXCLUDE]
document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';
document.getElementById('quickstart-sign-in').textContent = 'Sign out';
document.getElementById('quickstart-account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
emailVerified: emailVerified,
photoURL: photoURL,
isAnonymous: isAnonymous,
uid: uid,
refreshToken: refreshToken,
providerData: providerData
}, null, ' ');
var info = { email: user.email, destinations: {'boraBora': true} }
usersRef.push(info)
// [END_EXCLUDE]
} else {
// User is signed out.
// [START_EXCLUDE]
document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';
document.getElementById('quickstart-sign-in').textContent = 'Sign in with Google';
document.getElementById('quickstart-account-details').textContent = 'null';
document.getElementById('quickstart-oauthtoken').textContent = 'null';
// [END_EXCLUDE]
}
// [START_EXCLUDE]
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
// [END authstatelistener]
document.getElementById('quickstart-sign-in').addEventListener('click', toggleSignIn, false);
}
window.onload = function() {
initApp();
};
}());
$(document).ready(function(){
$("body").css("background", "darkgray");
$("#fakeLoader").fakeLoader({
timeToHide:1200, //Time in milliseconds for fakeLoader disappear
zIndex:999, // Default zIndex
spinner:"spinner1",//Options: 'spinner1', 'spinner2', 'spinner3', 'spinner4', 'spinner5', 'spinner6', 'spinner7'
bgColor:"#6E6464", //Hex, RGB or RGBA colors
// imagePath:"icon-sm.png" //If you want can you insert your custom image
});
var response = $.ajax({url: "https://api.flickr.com/services/rest/?method=flickr.favorites.getPublicList&api_key=7323d71df9858598dd027bd0b1dadef9&user_id=87845824%40N05&extras=tags&format=json&nojsoncallback=1&auth_token=72157670174326456-2d8f4fffb8956f3f&api_sig=985abda1c6c0d32fb158202b0d96736d", method: "get"});
var allPhotos = response.done(function(photos) {
var pArray = getMatchingTagArray(grabPhotoObjects(photos));
var background = returnSpecificImage(pArray);
var image = "https://farm"+background.farm+".staticflickr.com/"+background.server+"/"+background.id+"_"+background.secret+"_b.jpg"
$.backstretch(image);
});
});
function grabPhotoObjects(response) {
// console.log(response.photos.photo)
return response.photos.photo;
};
function getMatchingTagArray(allObjects) {
var countryPics = [];
allObjects.forEach(function(picture){
if(picture.tags.includes("barcelona")){
countryPics.push(picture);
};
});
return countryPics;
};
function returnSpecificImage(array) {
var image = array[Math.floor(Math.random() * array.length)];
return image
};
| JavaScript | 0 | @@ -5933,14 +5933,8 @@
.get
-Public
List
@@ -5946,40 +5946,40 @@
key=
-7323d71df9858598dd027bd0b1dadef9
+15814abffa9beab837cad31506bd4eca
&use
@@ -6042,95 +6042,8 @@
ck=1
-&auth_token=72157670174326456-2d8f4fffb8956f3f&api_sig=985abda1c6c0d32fb158202b0d96736d
%22, m
|
011b6dbf316d42a9ad99f521d2a89538dbe79752 | Round the values to the matching traffic image up, so that on below 5% no 'no traffic' icon is shown | background.js | background.js | var usedTraffic = null,
quotaPerDay = 3 * 1024 * 1024,
maxQuota = quotaPerDay * 21;
/** Resets all modified values to their defaults. */
function clearState() {
chrome.browserAction.setIcon({path:"icon/inactive.png"});
usedTraffic = null;
}
/** Requests the current traffic usage and updates the icon. */
function updateTraffic(){
$.getJSON("https://agdsn.de/sipa/usertraffic/json", function(data){
if(!data["version"]){
clearState();
return;
}
var quota = parseFloat(data.quota);
var proc = Math.round(quota / maxQuota * 100);
if(proc > 100) proc = 100;
var name = proc - (proc % 5);
chrome.browserAction.setIcon({path: "icon/" + name + ".png"});
usedTraffic = data;
}).fail(function(){
clearState();
});
}
chrome.browserAction.setBadgeBackgroundColor({color: [1, 1, 1, 1]});
updateTraffic();
chrome.alarms.onAlarm.addListener(updateTraffic);
chrome.alarms.create("updateTraffic", {periodInMinutes: 2});
| JavaScript | 0.999815 | @@ -571,16 +571,131 @@
= 100;%0A
+%09%09// Round the value up to the next 5%25 step %0A%09%09// to not display the no more traffic icon when there is still some%0A
%09%09var na
@@ -704,16 +704,20 @@
= proc
++ 5
- (proc
|
b2da60431e1e5a405e019688c11af362d4f37cad | Add file overview | background.js | background.js | // Background job which monitors chrome tabs and closes duplicates.
var tabs = [];
// Called when extension is installed or updated
chrome.runtime.onInstalled.addListener(function(reason){
// Set initial tabs
chrome.tabs.query({}, function(result) {
for (var i = 0; i < result.length; i++) {
tabs.push(result[i])
}
});
// TODO: Close and remove duplicates in initial tabs
});
// Called when new tab is created
chrome.tabs.onCreated.addListener(function(tab) {
if (tab.url !== null && tab.url !== "undefined") {
// Remove old duplicated tab
if (this.isTabKnown(tab) === true) {
var oldTab = findTabByUrl(tab.url);
if (oldTab !== null) {
chrome.tabs.remove(oldTab.id); // close tab
this.removeTab(oldTab)
}
}
// Save new tab
this.addTab(tab)
}
});
// Called when tab is closed
chrome.tabs.onRemoved.addListener(function(tabId, detachInfo) {
var oldTab = findTabById(tabId);
if (oldTab !== null) {
this.removeTab(oldTab)
}
});
// Called when tab is updated or refreshed
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tab.url !== null && tab.url !== "undefined") {
// If tab url is known find and close duplicated (older) tab
if (this.isTabKnown(tab) === true) {
var tabsByUrlResult = findTabsByUrl(tab.url);
for (var i = 0; i < tabsByUrlResult.length; i++) {
if (tabsByUrlResult[i].id !== tab.id) {
chrome.tabs.remove(tabsByUrlResult[i].id); // close tab
this.removeTab(tabsByUrlResult[i])
}
}
}
// Update tabs
var updatedTab = findTabById(tab.id);
if (updatedTab !== null) {
this.removeTab(updatedTab)
}
this.addTab(tab)
}
});
function isTabKnown(tab) {
for (var i = 0; i < tabs.length; i++) {
if (tab.url === tabs[i].url) {
return true
}
}
return false;
}
function findTabByUrl(url) {
for (var i = 0; i < tabs.length; i++) {
if (url === tabs[i].url) {
return tabs[i]
}
}
return null;
}
function findTabsByUrl(url) {
var tabsByUrl = [];
for (var i = 0; i < tabs.length; i++) {
if (url === tabs[i].url) {
tabsByUrl.push(tabs[i])
}
}
return tabsByUrl;
}
function findTabById(id) {
for (var i = 0; i < tabs.length; i++) {
if (id === tabs[i].id) {
return tabs[i]
}
}
return null;
}
function addTab(tab) {
tabs.push(tab)
}
function removeTab(tab) {
var index = tabs.indexOf(tab);
if (index !== -1) {
tabs.splice(index, 1);
}
} | JavaScript | 0 | @@ -1,47 +1,33 @@
/
-/ Background job which monitors chrome tab
+**%0A * @fileOverview Monitor
s an
@@ -44,18 +44,34 @@
uplicate
-s.
+d chrome tabs.%0A */
%0A%0Avar ta
|
bbcb9b7836336f67076cb8ff153de95af9cbac55 | Tweak color: Lucky 7's | background.js | background.js | /*
* Copyright 2013 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.
*/
var History = {};
chrome.browserAction.setBadgeText({ 'text': '?'});
chrome.browserAction.setBadgeBackgroundColor({ 'color': "#666" });
function HandleChange(tabId, changeInfo, tab) {
if ("url" in changeInfo) {
var now = new Date();
if (!(tabId in History)) {
History[tabId] = [];
}
History[tabId].unshift([now, changeInfo.url]);
var history_limit = parseInt(localStorage["history_size"]);
if (! history_limit) {
history_limit = 23;
}
while (History[tabId].length > history_limit) {
History[tabId].pop();
}
chrome.browserAction.setBadgeText({ 'tabId': tabId, 'text': '0m'});
chrome.browserAction.setPopup({ 'tabId': tabId, 'popup': "popup.html#tabId=" + tabId});
}
}
function HandleRemove(tabId, removeInfo) {
delete History[tabId];
}
function HandleReplace(addedTabId, removedTabId) {
delete History[removedTabId];
}
function UpdateBadges() {
var now = new Date();
for (tabId in History) {
var description = FormatDuration(now - History[tabId][0][0]);
chrome.browserAction.setBadgeText({ 'tabId': parseInt(tabId), 'text': description});
}
}
setInterval(UpdateBadges, 3000);
chrome.tabs.onUpdated.addListener(HandleChange);
chrome.tabs.onRemoved.addListener(HandleRemove);
chrome.tabs.onReplaced.addListener(HandleReplace);
| JavaScript | 0.000001 | @@ -742,11 +742,11 @@
: %22#
-666
+777
%22 %7D)
|
f252bd41af333b7d3f82d0ed11b524534b768e7f | Fix for #11 - adding websites via context menu | background.js | background.js | /**
* RapidTabOpener
*
* Action to be executed when toolbar button is clicked. Determines the
* current window mode and the desired window type then with that
* information either opens a new window first or the specified URLs.
*
* @author cedricium - Cedric Amaya
*/
browser.browserAction.onClicked.addListener(getDataFromStorage);
var urls,
windowSettings,
currentWindow;
function getDataFromStorage(window) {
currentWindow = window;
var getting = browser.storage.local.get(["urls", "windowSettings"]);
getting.then(determineWindow);
}
function determineWindow(item) {
if (Object.keys(item).length == 0)
openOptionsPage();
else {
urls = item.urls;
windowSettings = item.windowSettings;
}
var windowType = windowSettings.type;
if (urls.length <= 0)
openOptionsPage();
else {
if (windowType === "incognito" && currentWindow.incognito)
openURLs();
if (windowType === "incognito" && !currentWindow.incognito)
openWindow(windowType);
if (windowType === "normal" && !currentWindow.incognito)
openURLs();
if (windowType === "normal" && currentWindow.incognito)
openWindow(windowType);
}
}
function openOptionsPage() {
browser.runtime.openOptionsPage();
var title = "Oops!",
message = "Add some URLs that you want opened.";
createNotification(title, message);
}
function openWindow(type) {
var newWindow;
if (type === "normal") {
newWindow = browser.windows.create({
incognito: false,
state: "maximized"
});
}
else if (type === "incognito") {
newWindow = browser.windows.create({
incognito: true,
state: "maximized"
});
}
newWindow.then(openURLs);
}
function closeNewTab(tabs) {
var newTab = tabs[tabs.length - 1];
var removingNewTab = browser.tabs.remove(newTab.id);
}
function openURLs() {
var querying = browser.tabs.query({currentWindow: true});
querying.then(closeNewTab);
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
browser.tabs.create({
index: i,
url: url
});
}
}
browser.contextMenus.create({
id: "add_page",
title: "Add Page to RapidTabOpener",
type: "normal",
contexts: [
"page",
"tab"
],
onclick: listener
});
browser.contextMenus.create({
id: "open_options_page",
title: "Open Options Page",
type: "normal",
contexts: [
"page",
"tab"
],
onclick: listener
});
function listener(info, tab) {
if (info.menuItemId == "open_options_page")
browser.runtime.openOptionsPage();
else { // for handling the add_page context
var getting = browser.storage.local.get(["urls"]);
getting.then(function(item) {
addURL(info, item);
});
}
}
function addURL(info, item) {
var urls = item.urls,
urlToAdd = info.pageUrl;
urls.push(urlToAdd);
browser.storage.local.set({ urls });
var title = "Website Added!",
message = 'The following URL was added to your RapidTabs: "' +
urlToAdd + '".';
createNotification(title, message);
}
function createNotification(heading, message) {
browser.notifications.create({
"type": "basic",
"title": heading,
"message": message,
"iconUrl": "icons/icon-128.png"
});
} | JavaScript | 0 | @@ -271,16 +271,182 @@
ya%0A */%0A%0A
+(function setDefaultSettings() %7B%0A var urls = %5B%5D;%0A var windowSettings = %7Btype: 'normal'%7D;%0A %0A browser.storage.local.set(%7B%0A urls,%0A windowSettings%0A %7D);%0A%7D)();%0A%0A
browser.
|
7641cce26930ee17292bf4e3e716d70cd7cfd2a0 | support the thread list of pink2ch | user_script/simple2ch.user.js | user_script/simple2ch.user.js | // ==UserScript==
// @name simple2ch
// @namespace https://github.com/neEverett/simple2ch-2chChromeExtension
// @version 0.2
// @description Making the webpage version of 2ch a little bit easy to use.
// @author neEverett
// @match http://*.2ch.net/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
function isNotTag(tag)
{
try
{
var tname = tag.tagName;
}
catch(e1)
{
return 1;
}
return 0;
}
function board_and_thread_page()
{
//换行功能
var isBoardPage = 1;
var menuNamedTag = document.getElementsByName("menu"); //用来定位
if (menuNamedTag.length !== 0)
{
var tableTag = menuNamedTag[0].nextSibling; //目前发现2ch有两种html。对于其中一种,menuNamedTag后的一个节点就是table标签。对另一种,nextSibling会获得一个换行符
while (isNotTag(tableTag) || tableTag.tagName != "TABLE") //获得到非talbe标签时,继续向后获取直到找到table标签
{
tableTag = tableTag.nextSibling;
}
var titleaTags = tableTag.getElementsByTagName("a");
if (titleaTags[4].previousSibling.nodeValue == " ") //对于其中一种html,所有a标签之间有一个空格。判断为这种后,要在第一个a标签前手动加上空格保持排版的一致性。
{
var space = document.createElement("nobr");
var parentNode = titleaTags[2].parentNode;
space.innerHTML = " ";
parentNode.insertBefore(space,titleaTags[2]);
}
for (var i=0; i < titleaTags.length; i++)
{
if (titleaTags[i].innerHTML.length > 5) //前几个标题,序号和内容分别是两个a标签。如果是序号标签,则不换行。
titleaTags[i].innerHTML += "<br>";
}
}
//取消外部url跳转确认
//2ch不同板块跳转url的格式也略有区别,有的板块http://jump.2ch.net/?后不接http://,有的板块后接。因此需分两种情况处理。
var hasThreadPage = 1;
var dlTags = document.getElementsByClassName("thread"); //在板块主页定位到串的部分
if (dlTags.length !== 0)
{
var urlExp = new RegExp("http:\/\/jump.2ch.net/[?]|https:\/\/jump.2ch.net/[?]"); //这里用\?会出错,匹配不到问号
var httpExp = new RegExp(".*[?]http.*");
for (var k=0; k < dlTags.length; k++)
{
var threadaTags = dlTags[k].getElementsByTagName("a");
for (var j=0; j < threadaTags.length; j++)
{
if (urlExp.test(threadaTags[j].href)) //是一个跳转的url
{
if (!httpExp.test(threadaTags[j].href)) //如果这个url没有包含http://,则加上http://,删去跳转的代码
{
threadaTags[j].href = ("http://" + threadaTags[j].href.replace(urlExp,""));
}
else //如果包含了http://或https://,这部分保持原样,删去跳转的代码
{
threadaTags[j].href = (threadaTags[j].href.replace(urlExp,""));
}
}
}
}
}
}
function thread_list_page()
{
//匹配串列表页面
var smallTag = document.getElementById("trad"); //定位
if (smallTag)
{
var aTags = smallTag.getElementsByTagName("a");
var space = new Array(aTags.length); //在每个标题前加几个空格,视觉效果好一些。
for (var i=0; i < aTags.length; i++)
{
space[i] = document.createElement("nobr");
space[i].innerHTML = " ";
smallTag.insertBefore(space[i],aTags[i]);
//如果在循环中使用insertBefore(tag,aTags[i]),则tag的插入位置会不断地被替换,最终只在最后一个位置插入。因此使用数组。
aTags[i].innerHTML += "<br>";
}
}
}
board_and_thread_page();
thread_list_page();
})();
| JavaScript | 0 | @@ -136,16 +136,18 @@
0.2
+.1
%0D%0A// @de
@@ -283,16 +283,70 @@
.net/*%0D%0A
+// @match http://*.bbspink.com/*/subback.html%0D%0A
// @gran
|
95e2800d8f3763c476158f96b134ca78dbe0dfb1 | Add URI as a dependency. Add a handler for the search-callers on the front page. | scripts/js/dictionaries.js | scripts/js/dictionaries.js | // http://stackoverflow.com/a/17606289
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
!function ($, VirtualKeyboard, params, xcontext, navigator) {
var m = {};
m.ready = false;
m.userLangs = navigator.languages;
m.userLang = m.userLangs[0];
m.autoCompleteDelay = 200;
m.indexes = {};
m.indexNames = [];
m.href = new String;
/* get the relevant indexes for the dictionary and store them in an array */
m.getIndexes = $.getJSON(params.switchURL + "?version=1.2&operation=explain&x-context=" +
xcontext + "&x-format=json");
function gotIndexesDone(data) {
m.indexes = data.indexes;
$.each(m.indexes, function (unused, value) {
$("style").append('.ui-widget-content li.ui-menu-item a.ui-corner-all.' + value.name + '{ color: #F00; }');
if (value.name === "lemma" || value.name === "inflected" || value.name.substring(0, 6) === "sense-") {
m.indexNames.push(value.name);
m.indexesString = +value.name + ",";
}
m.ready = true;
});
}
m.getIndexes.done(gotIndexesDone);
$('document').ready(function () {
resultContainerLoaded();
$('.navbar-collapse ul li a').click(function () {
$('.navbar-toggle:visible').click();
});
$(".nav").on("click", "li", function () {
var index = $(this).index() + 2;
$("#main > div").hide();
$("#main > div:nth-child(" + index + ")").show();
});
$(".jumbotron").click(function () {
$("#main > div").hide();
$("#front").show();
});
$("body").on("submit", "form", onSubmitForm);
});
function getFilteredSuggestions(unused, callWhenDone) {
if (!m.ready) {
return;
}
// so now we have to do several requests and then present the result
// when all of them are done.
// Solution is similiar to this:
// http://stackoverflow.com/a/9865124
// and this
// http://stackoverflow.com/a/16287125
var requestsForAllIndexes = []; // array of promises that will be fullfilled
// one after the other.
$.each(m.indexNames, function (unused, value) {
var filterText = $("#query-text-ui").val();
var url = params.switchURL + "?version=1.2&operation=scan&scanClause=" +
value + "&x-filter=" + filterText + "&x-context=" + xcontext +
"&x-format=json&maximumTerms=10";
requestsForAllIndexes.push($.getJSON(url));
});
// when used like this collects all the promises and then delevers all of
// them to the done function
$.when.apply($, requestsForAllIndexes).then(function () {
var results = [];
$.each(arguments, function (index, responseData) {
for (var i = 0; i < responseData[2].responseJSON.terms.length; i++) {
results.push(responseData[2].responseJSON.terms[i]);
}
});
gotFilteredSuggestions(results, callWhenDone);
}, function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
callWhenDone();
});
}
function gotFilteredSuggestions(results, callWhenDone) {
var sortedResults = [];
var firstTenOfsortedResults = [];
sortedResults = results.sort(function (a, b) {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
return 0;
});
for (var j = 0; j < 9; j++) {
if (sortedResults[j] !== undefined) {
firstTenOfsortedResults.push(sortedResults[j]);
}
}
callWhenDone($.map(firstTenOfsortedResults, function (item) {
return {
label: item.value,
value: item.key,
href: item.nextHref
};
}));
}
function onSubmitForm(event) {
event.preventDefault();
$("#submit-query").hide();
$("#loader").show();
var searchTerm = $("#query-text-ui").val();
if ((searchTerm[0] !== '"') &&
(searchTerm.indexOf(' ') !== -1)) {
searchTerm = '"' + searchTerm + '"';
}
console.log(params.switchURL);
console.log(searchTerm);
if (m.href === '') {
m.href = params.switchURL + "?version=1.2&operation=searchRetrieve&query=" +
encodeURIComponent(searchTerm) + "&x-context=" + xcontext +
"&startRecord=1&maximumRecords=50&x-format=htmlpagetable";
}
var encodedHref = m.href.replaceAll('"', '%22').replaceAll(' ', '%20');
$("#searchcontainer").load(encodedHref + " #result-container", resultContainerLoaded);
}
function resultContainerLoaded() {
/* turn input field into autocomplete field, and fill with data from server for all relevant indexes */
$("#loader").hide();
$("#submit-query").show();
$("#query-text-ui").autocomplete({
source: getFilteredSuggestions,
minLength: 1,
delay: m.autoCompleteDelay,
select: function (event, ui) {
if (ui.item) {
$('#query-text-ui').val(ui.item.value);
// quick fix; bad!
m.href = ui.item.href;
}
$('#searchretrieve').submit();
}
}).data("autocomplete")._renderItem = function (ul, item) {
var listItem = $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
var index = item.href.slice(item.href.search("query=") + 6, item.href.search("%3"));
listItem.addClass(index);
return listItem;
};
VirtualKeyboard.attachKeyboards();
m.href = '';
}
}(jQuery, VirtualKeyboard, params, xcontext, navigator) | JavaScript | 0 | @@ -245,16 +245,21 @@
avigator
+, URI
) %7B%0A
@@ -1815,24 +1815,86 @@
ubmitForm);%0A
+ $(%22#front .search-caller%22).on(%22click%22, onSearchCall);%0A
%7D);%0A%0A
@@ -6294,16 +6294,495 @@
;%0A %7D%0A
+ %0A function onSearchCall(event) %7B%0A event.preventDefault();%0A var searchConfig = (new URI(event.currentTarget.href)).query(true);%0A if (searchConfig.query === 'metaText==Dictionaries') %7B%0A // TODO switch someqhere%0A return;%0A %7D%0A $('#query-text-ui').val(searchConfig.query.replace('serverChoice=', ''));%0A $('#li-search a').click();%0A $('form#searchretrieve').submit();%0A console.log(searchConfig);%0A %7D%0A
%7D(jQuery
@@ -6827,9 +6827,14 @@
avigator
+, URI
)
|
8a12ec62db5329a5499a3de2647f5288ed524c17 | fix argument of precacheAndRoute() | bin/app/sw.js | bin/app/sw.js | /* eslint-disable */
console.log(`${new Date()}: Service Worker is loaded`);
// Set cache name for multiple projects.
// @see https://developers.google.com/web/tools/workbox/modules/workbox-core
workbox.core.setCacheNameDetails({
prefix: "starter-react-flux",
suffix: "v1",
precache: "install-time",
runtime: "run-time",
googleAnalytics: "ga"
});
workbox.core.skipWaiting();
workbox.core.clientsClaim();
// Enable google analytics for offline
// @see https://developers.google.com/web/tools/workbox/modules/workbox-google-analytics
// workbox.googleAnalytics.initialize();
workbox.precaching.precacheAndRoute(self.__precacheManifest);
// Cache Google Fonts
workbox.routing.registerRoute(
"https://fonts.googleapis.com/(.*)",
new workbox.strategies.CacheFirst({
cacheName: "google-fonts",
cacheableResponse: { statuses: [0, 200] }
})
);
// Static content from Google
workbox.routing.registerRoute(
/.*(?:gstatic)\.com.*$/,
new workbox.strategies.CacheFirst({
cacheName: "google-static"
})
);
// Cache any images which are included the extention list
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|svg)$/,
new workbox.strategies.CacheFirst({
cacheName: "image-content",
cacheableResponse: { statuses: [0, 200] }
})
);
// Cache any JavaScript and CSS which are included the extention list
workbox.routing.registerRoute(
/\.(?:js|css)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: "static-resources",
cacheableResponse: { statuses: [0, 200] }
})
);
// Cache any HTTP Content
workbox.routing.registerRoute(
/^http.*/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: "http-content",
cacheableResponse: { statuses: [0, 200] }
}),
"GET"
);
| JavaScript | 0 | @@ -628,24 +628,19 @@
f.__
-precacheManifest
+WB_MANIFEST
);%0A%0A
|
660cd8521263dbdf6cceea6634ccbbb65588336d | Update Colors and names | shared/styles/style-guide.desktop.js | shared/styles/style-guide.desktop.js | /* @flow */
// Styles from our designers
export const globalColors = {
blue: '#00bff0',
green: '#90d05c',
grey1: '#444444',
grey2: '#9e9e9e',
grey3: '#cccccc',
grey4: '#e1e1e1',
grey5: '#f6f6f6',
highRiskWarning: '#d0021b',
lightBlue: '#86e2f9',
lightOrange: '#fc8558',
lowRiskWarning: '#f5a623',
orange: '#ff602e',
white: '#ffffff',
black: '#000000'
}
export const globalColorsDZ2 = {
// Keybase Brand Colors
blue: '#00bff0',
lightBlue1: '#86e2f9',
lightBlue2: '#c7f4ff',
orange1: '#ff602e',
orange2: '#fc8558',
yellow: '#fff75a',
darkBlue: '#385f8c',
// Additional Colors
green1: '#90d05c',
green2: '#5bad34',
red1: '#e66272',
red2: '#dc001b',
// Backgrounds
backgroundGrey: '#f6f6f6',
backgroundWhite: '#ffffff'
}
export const globalResizing = {
login: {width: 700, height: 580}
}
const fontCommon = {
WebkitFontSmoothing: 'antialiased',
textRendering: 'optimizeLegibility'
}
const font = {
fontRegular: {
...fontCommon,
fontFamily: 'Noto Sans'
},
fontBold: {
...fontCommon,
fontFamily: 'Noto Sans Bold'
},
fontItalic: {
...fontCommon,
fontFamily: 'Noto Sans Italic'
},
fontTerminal: {
...fontCommon,
fontFamily: 'Source Code Pro'
}
}
const flexBoxCommon = {
display: 'flex'
}
const util = {
flexBoxColumn: {
...flexBoxCommon,
flexDirection: 'column'
},
flexBoxRow: {
...flexBoxCommon,
flexDirection: 'row'
},
noSelect: {
WebkitUserSelect: 'none'
},
windowDragging: { // allow frameless window dragging
WebkitAppRegion: 'drag'
},
windowDraggingClickable: { // allow things in frameless regions to be clicked and not dragged
WebkitAppRegion: 'no-drag'
},
rounded: {
borderRadius: 3
},
windowBorder: {
border: `solid ${globalColors.grey4}`,
borderWidth: 1
},
clickable: {
cursor: 'pointer'
},
topMost: {
zIndex: 9999
}
}
export const globalStyles = {
...font,
...util
}
| JavaScript | 0 | @@ -450,97 +450,86 @@
: '#
-00b
+33a0
ff
-0
',%0A
-lightBlue1
+blue2
: '#
-86e2f9',%0A lightBlue2
+66b8ff',%0A blue3
: '#
-c7f4
+a8d7
ff',%0A
-orange1: '#ff602e
+blue4: '#e6f3ff
',%0A
+%0A
orange
2: '
@@ -528,22 +528,22 @@
ange
-2
: '#f
-c8558
+f6f21
',%0A
+%0A
ye
@@ -559,16 +559,17 @@
ff75a',%0A
+%0A
darkBl
@@ -578,48 +578,73 @@
: '#
-385f8c',%0A%0A // Additional Colors
+195080',%0A darkBlue2: '#2470b3',%0A darkBlue3: '#001b33',%0A
%0A green
1: '
@@ -643,19 +643,18 @@
reen
-1
: '#
-90d05c
+3dcc8e
',%0A
@@ -668,89 +668,298 @@
: '#
-5bad34
+36b37c
',%0A
+%0A
red
-1
: '#
-e66272
+ff4d61
',%0A
+%0A
-red2: '#dc001b
+yellowGreen: '#b3db39',%0A yellowGreen2: '#89a82c',%0A%0A black75: 'rgba(0, 0, 0, 0.75)',%0A black60: 'rgba(0, 0, 0, 0.60)
',%0A
-%0A
-// Backgrounds
+black40: 'rgba(0, 0, 0, 0.40)',%0A black20: 'rgba(0, 0, 0, 0.20)',
%0A b
+l
ack
-ground
+10: 'rgba(0, 0, 0, 0.10)',%0A%0A lightGrey: '#ebebeb',%0A light
Grey
+2
: '#
@@ -971,21 +971,12 @@
6',%0A
+%0A
-backgroundW
+w
hite
@@ -986,16 +986,36 @@
#ffffff'
+,%0A black: '#000000'
%0A%7D%0A%0Aexpo
|
a6b42c07c7fa2d19c8d8f829ae85ccd5ec6596f4 | remove unused dependency | spec/karma.spec.js | spec/karma.spec.js | var Karma = require('../tasks/wrappers/karma');
var karmaServer = require('karma').server;
var log = require('../tasks/utils/log');
function onError(e){
console.log('** Test Error **')
console.log(e)
expect(false).toBe(true)
}
describe('Karma', function () {
it('reports test coverage to the user', function (done) {
spyOn(log, 'info').and.callFake(function (message) {
return message;
});
var karma = new Karma({
summary: './spec/fixtures/karma/summary.json',
config: './spec/fixtures/karma/karma.conf.js'
});
karma.coverage().then(function(err){
expect(err).toBe('Test Coverage SUCCESS');
}).then(done).catch(onError);
});
it('fails when test coverage is insufficient', function (done) {
spyOn(log, 'warn').and.callFake(function (message) {
return message;
});
spyOn(log, 'info').and.callFake(function (message) {
return message;
});
var karma = new Karma({
summary: './spec/fixtures/karma/summary-failing.json',
config: './spec/fixtures/karma/karma.conf.js'
});
karma.coverage().catch(function(err){
expect(err).toBe('Test Coverage FAILED');
expect(log.warn.calls.count()).toBe(2);
done();
});
});
}); | JavaScript | 0.000002 | @@ -45,51 +45,8 @@
');%0A
-var karmaServer = require('karma').server;%0A
var
|
9504664ae0b5f13f6d7ab789820b4c8601b550ad | Enable all tests | spec/merge.spec.js | spec/merge.spec.js | var fs = require("fs");
var nodePath = require("path");
var g = require("../src/gitlet");
var merge = require("../src/merge");
var testUtil = require("./test-util");
function spToUnd(charr) {
return charr === "_" ? undefined : charr;
};
ddescribe("merge", function() {
beforeEach(testUtil.initTestDataDir);
beforeEach(testUtil.pinDate);
afterEach(testUtil.unpinDate);
it("should throw if not in repo", function() {
expect(function() { g.merge(); })
.toThrow("fatal: Not a gitlet repository (or any of the parent directories): .gitlet");
});
describe('longest common subsequence', function() {
it("should say HMAN for HUMAN and CHIMPANZEE", function() {
var a = "HUMAN".split("");
var b = "CHIMPANZEE".split("");
var exp = "HMAN".split("");
expect(merge.longestCommonSubsequence(a, b)).toEqual(exp);
});
it("should say mfe for mjfe and mfeb", function() {
var a = "mjfe".split("");
var b = "mfeb".split("");
var exp = "mfe".split("");
expect(merge.longestCommonSubsequence(a, b)).toEqual(exp);
});
it("should say mfe for mfeb and mfseb", function() {
var a = "mfeb".split("");
var b = "mfseb".split("");
var exp = "mfeb".split("");
expect(merge.longestCommonSubsequence(a, b)).toEqual(exp);
});
it("should say tsitest for thisisatest and testing123testing", function() {
var a = "thisisatest".split("");
var b = "testing123testing".split("");
var exp = "tsitest".split("");
expect(merge.longestCommonSubsequence(a, b)).toEqual(exp);
});
});
describe('longest common subsequence alignment', function() {
it("should work for sequences that don't start w the same character", function() {
var a = "HUMAN".split("");
var b = "CHIMPANZEE".split("");
var exp = { a: "_HUM_AN___".split("").map(spToUnd),
b: "CHIMPANZEE".split("").map(spToUnd) };
expect(merge.align(a, b)).toEqual(exp);
});
it("should work for first part of milk flour eggs example", function() {
var a = "mjfe".split("");
var b = "mfeb".split("");
var exp = { a: "mjfe_".split("").map(spToUnd),
b: "m_feb".split("").map(spToUnd) };
expect(merge.align(a, b)).toEqual(exp);
});
it("should work for second part of milk flour eggs example", function() {
var a = "mfeb".split("");
var b = "mfseb".split("");
var exp = { a: "mf_eb".split("").map(spToUnd),
b: "mfseb".split("").map(spToUnd) };
expect(merge.align(a, b)).toEqual(exp);
});
it("should work for rosetta code example 1", function() {
var a = "1234".split("");
var b = "1224533324".split("");
var exp = { a: "12___3___4".split("").map(spToUnd),
b: "1224533324".split("").map(spToUnd) };
expect(merge.align(a, b)).toEqual(exp);
});
it("should work for rosetta code example 2", function() {
var a = "thisisatest".split("");
var b = "testing123testing".split("");
var exp = { a: "this_isa___test___".split("").map(spToUnd),
b: "te_sting123testing".split("").map(spToUnd) };
expect(merge.align(a, b)).toEqual(exp);
});
it("should work for example of arrays of actual lines", function() {
var a = ["milk", "flour", "eggs", "butter"];
var b = ["milk", "flour", "sausage", "eggs", "butter"];;
var exp = { a: ["milk", "flour", undefined, "eggs", "butter"],
b: ["milk", "flour", "sausage", "eggs", "butter"] };
expect(merge.align(a, b)).toEqual(exp);
});
});
});
| JavaScript | 0.000009 | @@ -234,17 +234,16 @@
rr;%0A%7D;%0A%0A
-d
describe
|
10156a337040531978122221cd70ba30ddcb89b4 | fix UTF8 BOM charset | bin/jslint.js | bin/jslint.js | #!/usr/bin/env node
var linter = require("../lib/linter");
var reporter = require("../lib/reporter");
var nopt = require("nopt");
var fs = require("fs");
function commandOptions () {
var flags = [
'adsafe', 'bitwise', 'browser', 'cap', 'continue', 'css',
'debug', 'devel', 'es5', 'evil', 'forin', 'fragment',
'newcap', 'node', 'nomen', 'on', 'onevar', 'passfail',
'plusplus', 'regexp', 'rhino', 'undef', 'safe', 'windows',
'strict', 'sub', 'white', 'widget', 'goodparts', 'json',
'boring'
];
var commandOpts = {
'indent' : Number,
'maxerr' : Number,
'maxlen' : Number,
'predef' : [String, null]
};
flags.forEach(function (option) {
commandOpts[option] = Boolean;
});
return commandOpts;
}
var options = commandOptions(),
shorthandOptions = {
"good" : ["--goodparts"],
"gp" : ["--goodparts"]
},
shorthands = Object.keys(shorthandOptions);
var parsed = nopt(options, shorthandOptions);
function die(why) {
console.warn(why);
console.warn("Usage: " + process.argv[1] +
" [--" + Object.keys(options).join("] [--") +
"] [-" + shorthands.join("] [-") +
"] <scriptfile>...");
process.exit(1);
}
if (!parsed.argv.remain.length) {
die("No files specified.");
}
// If there are no more files to be processed, exit with the value 1
// if any of the files contains any lint.
var maybeExit = (function() {
var filesLeft = parsed.argv.remain.length;
var ok = true;
return function (lint) {
filesLeft -= 1;
ok = lint.ok && ok;
if (filesLeft === 0) {
// This was the last file; return appropriate exit value.
process.exit(ok ? 0 : 1);
}
};
}());
function lintFile(file) {
fs.readFile(file, function (err, data) {
if (err) {
throw err;
}
data = data.toString("utf8");
var lint = linter.lint(data, parsed);
if (parsed.json) {
console.log(JSON.stringify([file, lint]));
} else {
reporter.report(file, lint, parsed);
}
maybeExit(lint);
});
}
parsed.argv.remain.forEach(lintFile);
| JavaScript | 0.000136 | @@ -1877,16 +1877,140 @@
%7D%0A
+%09%09%0A%09%09// Fix UTF8 with BOM%0A%09%09if (0xEF === data%5B0%5D && 0xBB === data%5B1%5D && 0xBF === data%5B2%5D) %7B%0A%09%09%09data = data.slice(3);%0A%09%09%7D%0A%09%09%0A
|
65cfadd03d70b0854980d5eb046ffc7ec6e5f8b3 | Add logging to minify.js | bin/minify.js | bin/minify.js | const fs = require('fs');
const path = require('path');
const browserify = require('browserify');
const CleanCSS = require('clean-css');
require('dotenv').config();
// CSS Minification Configs
const cssSources = [
path.join('node_modules', 'normalize.css', 'normalize.css'),
path.join('node_modules', 'bootstrap', 'dist', 'css', 'bootstrap.css'),
path.join('static', 'css', 'global.css'),
path.join('static', 'css', 'syntax.css'),
];
const cssOutputFile = path.join('static', 'gen', 'bundle.min.css');
// JS Minification Configs
const jsInputFile = path.join('static', 'js', 'index.js');
const jsOutputFile = path.join('static', 'gen', 'bundle.min.js');
const jsRawAppends = [
path.join('node_modules', 'bootstrap', 'dist', 'js', 'bootstrap.min.js'),
];
// Minify js
const jsOutputStream = fs.createWriteStream(jsOutputFile);
browserify(jsInputFile, {debug: true})
.transform('envify')
.transform('babelify', {presets: ['@babel/preset-env']})
.transform('uglifyify', {compress: true, 'keep_fnames': true, global: true})
.bundle()
.pipe(jsOutputStream);
// Append additional files at end of bundle
const jsRawAppendPromises = jsRawAppends.map(rawAppend => {
return fs.promises.readFile(rawAppend);
});
jsOutputStream.on('finish', () => {
Promise.all(jsRawAppendPromises).then(rawAppendData => {
const stream = fs.createWriteStream(jsOutputFile, {flags: 'a'});
for(let data of rawAppendData) {
stream.write(data + '\n');
}
});
});
// Minify CSS
new CleanCSS({returnPromise: true})
.minify(cssSources)
.then(output => {
const stream = fs.createWriteStream(cssOutputFile);
stream.write(output.styles);
})
.catch(error => { console.error(error); });
| JavaScript | 0.000001 | @@ -774,16 +774,89 @@
nify js%0A
+console.log('Minifying JS:');%0Aconsole.log(jsInputFile);%0Aconsole.log('');%0A
const js
@@ -1561,16 +1561,83 @@
ify CSS%0A
+console.log('Minifying CSS:');%0Aconsole.log(cssSources.join(', '));%0A
new Clea
|
289fd05afd2e5aaadaed051d32be4efc164d0d71 | Fix temperature display | ui/public/javascripts/main.js | ui/public/javascripts/main.js | $(function() {
withSelectedFilter();
$("#refresh").click(withSelectedFilter);
$("#filter").change(withSelectedFilter);
});
var withSelectedFilter = function() {
var val = $("#filter").find(":selected").val();
if(val == "last24") {
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
loaddata(yesterday.getTime(), null);
} else if(val == "lastWeek") {
var yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000 * 7));
loaddata(yesterday.getTime(), null);
} else {
loaddata(null, null);
}
}
var loaddata = function(starttime, endtime) {
var url = "/api/v1/temperature"
var params = $.param({ starttime: starttime, endtime: endtime })
console.log(params)
url = url + "?" + params
$.getJSON(url, function(data) {
data.forEach(function(d) {
d.time = new Date(d.time);
});
var chart = c3.generate({
bindto: '#tempChart',
data: {
json: data,
keys: {
x: 'time',
value: ['value']
},
type: 'spline',
colors: {
value: '#33339F'
},
names: {
value: "Temperature Livingroom"
}
},
point: {
show: false
},
axis: {
x: {
label: 'Time',
type: 'timeseries',
tick: {
count: 10,
format: '%Y-%m-%d %H:%M:%S'
}
},
y: {
tick: {
format: d3.format('.2f')
},
label: 'Temperature °C'
}
},
regions: [
{ axis: 'y', start: 20, end: 23.5, class: 'regionY' }
]
});
});
$.getJSON("/api/v1/temperature/current", function(data) {
var d = data[0];
d.time = new Date(d.time);
var now = new Date();
var diff = ((now - d.time) / 1000).toFixed(0);
$('#temp').text(d.value.toFixed(2));
$('#time').text(dateFormat(d.time, "yyyy-mm-dd HH:MM:ss"));
$('#ago').text(diff);
if(d.value < 20) {
$('#comfort').removeClass().addClass("label label-primary");
$('#comfort').text("Too cold!");
} else if(d.value >= 20 && d.value <= 23.5) {
$('#comfort').removeClass().addClass("label label-success");
$('#comfort').text("Comfy :)");
} else {
$('#comfort').removeClass().addClass("label label-danger");
$('#comfort').text("Too warm!");
}
});
};
$.urlParams = function() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
| JavaScript | 0.000002 | @@ -1008,16 +1008,21 @@
%5B'value
+_real
'%5D%0A
|
aad59400e2d69727224a3ca9b6aa9f9d7c87e9f7 | Update bootstrap.js | resources/assets/js/bootstrap.js | resources/assets/js/bootstrap.js |
window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass');
} catch (e) {}
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo'
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: 'your-pusher-key',
// cluster: 'eu',
// encrypted: true
// });
| JavaScript | 0.000001 | @@ -1617,10 +1617,11 @@
r: '
-eu
+mt1
',%0A/
|
5338cc7a82f766242892b74d4c716f986bcdbaee | Switch bootstrap module import to foundation | resources/assets/scripts/main.js | resources/assets/scripts/main.js | // import external dependencies
import 'jquery';
// Import everything from autoload
import "./autoload/**/*"
// import local dependencies
import Router from './util/Router';
import common from './routes/common';
import home from './routes/home';
import aboutUs from './routes/about';
/** Populate Router instance with DOM routes */
const routes = new Router({
// All pages
common,
// Home page
home,
// About Us page, note the change from about-us to aboutUs.
aboutUs,
});
// Load Events
jQuery(document).ready(() => routes.loadEvents());
| JavaScript | 0 | @@ -41,16 +41,43 @@
jquery';
+%0Aimport 'foundation-sites';
%0A%0A// Imp
|
4a228e38efb9eae0e5cbaf495f06abd8d0b844b2 | Add configurable timeout to cleanup-utility | specs/testUtils.js | specs/testUtils.js | 'use strict';
// testUtils should be require'd before anything else in each spec file!
// Ensure we are using the 'as promised' libs before any tests are run:
require('mocha-as-promised')();
require('chai').use(require('chai-as-promised'));
var utils = module.exports = {
getUserStripeKey: function() {
var key = process.env.STRIPE_TEST_API_KEY;
if (!key) {
throw new Error('Expected environment variable STRIPE_TEST_API_KEY to be set.');
}
if (!/^sk_test_/.test(key)) {
throw new Error('Expected STRIPE_TEST_API_KEY to be of the form "sk_test_[...]".');
}
return key;
},
getSpyableStripe: function() {
// Provide a testable stripe instance
// That is, with mock-requests built in and hookable
var Stripe = require('../lib/stripe');
var stripeInstance = Stripe('fakeAuthToken');
for (var i in stripeInstance) {
if (stripeInstance[i] instanceof Stripe.StripeResource) {
// Override each _request method so we can make the params
// avaialable to consuming tests:
stripeInstance[i]._request = function(method, url, data, cb) {
stripeInstance.LAST_REQUEST = {
method: method,
url: url,
data: data
};
};
}
}
return stripeInstance;
},
/**
* A utility where cleanup functions can be registered to be called post-spec.
* CleanupUtility will automatically register on the mocha afterEach hook,
* ensuring its called after each descendent-describe block.
*/
CleanupUtility: (function() {
function CleanupUtility() {
var self = this;
this._cleanupFns = [];
this._stripe = require('../lib/stripe')(
utils.getUserStripeKey()
);
afterEach(function(done) {
return self.doCleanup(done);
});
}
CleanupUtility.prototype = {
doCleanup: function(done) {
var cleanups = this._cleanupFns;
var total = cleanups.length;
var completed = 0;
for (var fn; fn = cleanups.shift();) {
fn.call(this).then(function() {
// cleanup successful
++completed;
if (completed === total) {
done();
}
}, function(err) {
// not successful
throw err;
});
}
},
add: function(fn) {
this._cleanupFns.push(fn);
},
deleteCustomer: function(custId) {
this.add(function() {
return this._stripe.customers.del(custId);
});
},
deletePlan: function(custId) {
this.add(function() {
return this._stripe.plans.del(custId);
});
}
};
return CleanupUtility;
}())
};
| JavaScript | 0.000001 | @@ -1572,24 +1572,69 @@
nction() %7B%0A%0A
+ CleanupUtility.DEFAULT_TIMEOUT = 20000;%0A%0A
function
@@ -1649,16 +1649,23 @@
Utility(
+timeout
) %7B%0A
@@ -1826,32 +1826,97 @@
unction(done) %7B%0A
+ this.timeout(timeout %7C%7C CleanupUtility.DEFAULT_TIMEOUT);%0A
return s
|
5a92a99eeb0e5a21ef210dc095448345de58f3d6 | Update AppVersionPlugin.js | www/AppVersionPlugin.js | www/AppVersionPlugin.js | /*jslint indent: 2 */
/*global window, jQuery, angular, cordova */
"use strict";
// Returns a jQuery or AngularJS deferred object, or pass a success and fail callbacks if you don't want to use jQuery or AngularJS
var getPromisedCordovaExec = function (command, success, fail) {
var toReturn, deferred, injector, $q;
if (success === undefined) {
if (window.jQuery) {
deferred = jQuery.Deferred();
success = deferred.resolve;
fail = deferred.reject;
toReturn = deferred;
} else if (window.angular) {
injector = angular.injector(["ng"]);
$q = injector.get("$q");
deferred = $q.defer();
success = deferred.resolve;
fail = deferred.reject;
toReturn = deferred.promise;
} else if (window.Promise) {
toReturn = new Promise(function(c, e) {
success = c;
fail = e;
});
} else if (window.WinJS && window.WinJS.Promise) {
toReturn = new WinJS.Promise(function(c, e) {
success = c;
fail = e;
});
} else {
return console.error('AppVersion either needs a success callback, or jQuery/AngularJS/Promise/WinJS.Promise defined for using promises');
}
}
// 5th param is NOT optional. must be at least empty array
cordova.exec(success, fail, "AppVersion", command, []);
return toReturn;
};
var getAppVersion = function (success, fail) {
return getPromisedCordovaExec('getVersionNumber', success, fail);
};
getAppVersion.checkVersion = function (success, fail) {
return getPromisedCordovaExec('checkVersion', success, fail);
};
getAppVersion.getAppName = function (success, fail) {
return getPromisedCordovaExec('getAppName', success, fail);
};
getAppVersion.getPackageName = function (success, fail) {
return getPromisedCordovaExec('getPackageName', success, fail);
};
getAppVersion.getVersionNumber = function (success, fail) {
return getPromisedCordovaExec('getVersionNumber', success, fail);
};
getAppVersion.getVersionCode = function (success, fail) {
return getPromisedCordovaExec('getVersionCode', success, fail);
};
module.exports = getAppVersion;
| JavaScript | 0.000001 | @@ -1461,23 +1461,22 @@
on.check
-Version
+Update
= funct
@@ -1535,23 +1535,22 @@
c('check
-Version
+Update
', succe
|
8ba8b5982406fc4a203d4c7da12ec192d30edb5d | Move the timer into the animation loop | Web/JS/index.js | Web/JS/index.js |
jQuery(document).ready(function (){
IndexPage.Init();
});
/* Timer */
var d = new Date;
var timeSent = 0;
var timeTaken_s;
var timeTaken_ms;
function onInitFs(fs) {
fs.root.getFile("streaming.txt", { create: true }, function (DataFile) {
DataFile.createWriter(function (DataContent) {
DataContent.seek(DataContent.length);
var blob = new Blob([timeTaken_ms +"\n"], { type: "text/plain" });
DataContent.write(blob);
});
});
}
function getByteLen(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
c < (1 << 21) ? 4 :
c < (1 << 26) ? 5 :
c < (1 << 31) ? 6 : Number.NaN;
}
return byteLen;
}
var IndexPage = {
networkClient: null,
visualisationCanvas: null,
Init: function () {
this.networkClient = Network.initClient(GlobalVar.hostURL,GlobalVar.port),
this.visualisationCanvas = new Visualisation();
localStorage.setItem("globalScene", "");
this.Diagnostic();
var clients = this.networkClient.fetchedConnectedClients();
this.visualisationCanvas.init({ id: "canvas-container", height: "600px", width: "100%" }
, { wireFrameColor: 0x3300FF, backgroundColor: 0xB6B6B4,float:'none'}
, this.ReconstructFn);
this.visualisationCanvas.render("canvas-container");
this.UpdateSensorTable(clients);
this.StartCommunicationWithScene();
},
Diagnostic: function () {
if (this.networkClient
&& this.visualisationCanvas) {
console.log("Libraries Initialisation Successful");
return true;
} else {
if (!this.networkClient) {
this.networkClient = Network.initClient("localhost", GlobalVar.port);
console.log("Network Connection Failed : Default to Localhost");
} else {
console.log("Network Connection Failed : Fail Safe failed");
}
return false;
}
},
StartCommunicationWithScene: function () {
return this.networkClient.startCommWorker({ type: "global"}, this.NetworkHandler);
},
NetworkHandler: function (event) {
var responseType = event.data.type;
var responseData = event.data.msg;
if (responseType == "data") {
if (responseData != "") {
var sceneFromServer = JSON.parse(responseData);
localStorage.setItem("globalScene", JSON.stringify(sceneFromServer));
} else {
localStorage.setItem("globalScene", "");
}
}
},
UpdateSensorTable: function (clients) {
if (clients.length == 0) {
$("#sensor-info-count").text("0");
} else {
var numOfClients = clients.length;
$("#sensor-info-count").text(numOfClients);
for (var client = 0; client < numOfClients; client += 1) {
var newClientRow = document.createElement("tr");
var clientIdCell = document.createElement("td");
clientIdCell.innerHTML = clients[client]["id"];
var clientLocCell = document.createElement("td");
clientLocCell.innerHTML = clients[client]["location"];
var clientAddressCell = document.createElement("td");
clientAddressCell.innerHTML = clients[client]["address"];
newClientRow.appendChild(clientIdCell);
newClientRow.appendChild(clientLocCell);
newClientRow.appendChild(clientAddressCell);
var sensors = clients[client]["sensors"];
var numOfSensors = sensors.length;
var sensorIdList = [];
for (var sensor = 0; sensor < numOfSensors; sensor += 1) {
// Add to the sensor list
sensorIdList.push(sensors[sensor]["id"]);
jQuery.data(document.body, "sensorIdList", sensorIdList);
var sensorId = document.createElement("td");
sensorId.innerHTML = sensors[sensor]["id"];
var sensorOrdering = document.createElement("td");
sensorOrdering.innerHTML = sensors[sensor]["ordering"];
var sensorCalibrated = document.createElement("td");
sensorCalibrated.innerHTML = sensors[sensor]["calibrated"];
if (sensor == 0) {
newClientRow.id = sensors[sensor]["id"];
newClientRow.appendChild(sensorId);
newClientRow.appendChild(sensorCalibrated);
newClientRow.appendChild(sensorOrdering);
$("#sensor-info > tbody").append(newClientRow.outerHTML);
} else {
var additionalClientRow = document.createElement("tr");
additionalClientRow.id = sensors[sensor]["id"];
var blankCell = document.createElement("td");
blankCell.innerHTML = "";
var blankCell1 = document.createElement("td");
blankCell.innerHTML = "";
var blankCell2 = document.createElement("td");
blankCell.innerHTML = "";
additionalClientRow.appendChild(blankCell);
additionalClientRow.appendChild(blankCell1);
additionalClientRow.appendChild(blankCell2);
additionalClientRow.appendChild(sensorId);
additionalClientRow.appendChild(sensorCalibrated);
additionalClientRow.appendChild(sensorOrdering);
$("#sensor-info > tbody").append(additionalClientRow.outerHTML);
}
}
}
}
},
ReconstructFn: function (glScene, canvasId) {
timeSent = d.getTime();
// Remove all skeletons previously inserted into scene
var sceneChildrenNum = glScene.children.length;
for (var child = 7; child < sceneChildrenNum; child++) {
glScene.remove(glScene.children[child]);
}
/* Choose the global scene to draw*/
if(localStorage.getItem("globalScene")!=""){
var globalScene = JSON.parse(globalSceneJSON);
}
if (globalScene != null) {
for (var newSkeleton in globalScene["skeletons"]) {
var skeletonObj = new Skeleton(globalScene["skeletons"][newSkeleton]);
var skeletonGeometry;
if (globalScene["skeletons"][newSkeleton]["shared"] == "true") {
//purple
skeletonGeometry = skeletonObj.getGeometry(0xA30000);
} else {
//orange
skeletonGeometry = skeletonObj.getGeometry(0xFF9933);
}
glScene.add(skeletonGeometry);
}
var d = new Date;
timeTaken_ms = Math.round((d.getTime() - timeSent) / 10);
timeSent += timeTaken_ms;
window.webkitRequestFileSystem(window.TEMPORARY, 1024 * 1024, onInitFs)
}
return null;
}
}; | JavaScript | 0.000001 | @@ -61,92 +61,8 @@
);%0A%0A
-/* Timer */%0Avar d = new Date;%0Avar timeSent = 0;%0Avar timeTaken_s;%0Avar timeTaken_ms;%0A%0A
func
@@ -6279,32 +6279,117 @@
-timeSent = d.getTime();%0A
+/* Timer */%0A var d = new Date;%0A var timeSent = d.getTime();%0A var timeTaken_ms=0;%0A
%0A
@@ -7424,36 +7424,32 @@
%7D%0A%0A
-var
d = new Date;%0A
@@ -7519,46 +7519,8 @@
10);
-%0A timeSent += timeTaken_ms;
%0A%0A
|
cb457850b402047b04582aae97cf2ec52f256fb7 | change api url to demo host | app/core/api-urls.js | app/core/api-urls.js | 'use strict';
this.apiUrls = {};
this.apiUrls.root = 'http://10.131.235.12:3000/api/v1';
this.apiUrls.signUp = apiUrls.root + '/users';
this.apiUrls.signIn = apiUrls.signUp + '/token';
this.apiUrls.logOut = apiUrls.signIn;
this.apiUrls.courses = apiUrls.root + '/courses';
this.apiUrls.courseTags = apiUrls.courses + '/tags';
this.apiUrls.posts = apiUrls.root + '/posts';
this.apiUrls.postTags = apiUrls.posts + '/tags';
this.apiUrls.teachers = apiUrls.root + '/teachers';
//this.apiUrls.courses = 'mock-data/courses.json'
//this.apiUrls.courseTags = 'mock-data/courseTags.json';
//this.apiUrls.posts = 'mock-data/posts.json'
//this.apiUrls.postTags = 'mock-data/postTags.json'; | JavaScript | 0 | @@ -60,26 +60,35 @@
p://
-10.131.235.12:3000
+sedemo.carbon941030.tk:8081
/api
|
9b0bdf3e33c097708cf97628d8e9c37be7061f7c | Simplify paths | douglas-peucker/app.js | douglas-peucker/app.js | // create a map in the "map" div, set the view to a given place and zoom
var map = L.map('map').setView([51.505, -0.09], 13);
var markers = []
var polyline = L.polyline([]).addTo(map)
var startTime = new Date();
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var adder = document.getElementById('add-point')
adder.addEventListener('click', addPoint)
function addPoint() {
var position = {
coords: {
longitude: nextLon(),
latitude: nextLat()
}
}
positionSuccess(position)
}
function generator() {
return function () {
this.value = this.value || 0
this.variation = this.variation || 0
var varvar = Math.random() > 0.9 ? 1 : 4
this.variation += Math.sin((Math.random()-2)/varvar)
this.value += Math.random()*0.001 * this.variation
return this.value
}
}
var nextLon = generator()
var nextLat = generator()
function positionSuccess(position) {
var p = position.coords
var ll = [p.latitude, p.longitude]
var marker = L.marker(ll).addTo(map)
markers.push(marker)
polyline.addLatLng(ll)
map.fitBounds(polyline.getBounds())
}
| JavaScript | 0.002766 | @@ -66,16 +66,70 @@
nd zoom%0A
+var initialLat = 51.508611%0Avar initialLon = -0.163611%0A
var map
@@ -156,21 +156,30 @@
ew(%5B
-51.505, -0.09
+initialLat, initialLon
%5D, 1
@@ -471,20 +471,8 @@
);%0A%0A
-var adder =
docu
@@ -508,13 +508,10 @@
t')%0A
-adder
+
.add
@@ -544,16 +544,92 @@
Point)%0A%0A
+document.getElementById('simplify')%0A .addEventListener('click', simplify)%0A%0A
function
@@ -790,19 +790,48 @@
nerator(
-) %7B
+initialValue) %7B%0A var state = %7B%7D
%0A retur
@@ -846,28 +846,29 @@
on () %7B%0A
-this
+state
.value = thi
@@ -864,20 +864,21 @@
value =
-this
+state
.value %7C
@@ -883,18 +883,30 @@
%7C%7C
-0%0A this
+initialValue%0A state
.var
@@ -914,20 +914,21 @@
ation =
-this
+state
.variati
@@ -985,20 +985,21 @@
: 4%0A
-this
+state
.variati
@@ -1043,20 +1043,21 @@
ar)%0A
-this
+state
.value +
@@ -1078,18 +1078,21 @@
)*0.
+00
001 *
-this
+state
.var
@@ -1114,12 +1114,13 @@
urn
-this
+state
.val
@@ -1153,16 +1153,26 @@
nerator(
+initialLon
)%0Avar ne
@@ -1189,17 +1189,461 @@
nerator(
-)
+initialLat)%0A%0Afunction simplify() %7B%0A var points = polyline.getLatLngs().map(function(ll) %7B return L.point(ll.lng, ll.lat)%7D)%0A var newPoints = L.LineUtil.simplify(points, 0.00001).map(function(p)%7B return L.latLng(p.y, p.x) %7D)%0A polyline.setLatLngs(newPoints)%0A%0A markers.forEach(function(m)%7B map.removeLayer(m) %7D)%0A markers = %5B%5D%0A polyline.getLatLngs().forEach(function(ll)%7B%0A var marker = L.marker(ll).addTo(map)%0A markers.push(marker)%0A %7D)%0A%7D
%0A%0Afuncti
|
6708dbf1da755968e6e5929a26d7bbd58378d781 | Update some params | main.js | main.js | 'use strict';
var strips = require('./strips');
var currentImage; // image element, hidden
var currentPolys; // specifically these are cut-strip polygons in pixel coords relative to currentImage
function loadImageFromFile(file, cb) {
// Prevent any non-image file type from being read.
if (!file.type.match(/image.*/)) {
console.log('The dropped file is not an image: ', file.type);
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var image = new Image();
image.onload = function() {
cb(image);
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
}
function renderPolys(canvas, polys) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
for (var i = 0; i < polys.length; i++) {
var poly = polys[i];
ctx.beginPath();
for (var j = 0; j < poly.length; j++) {
var p = poly[j];
ctx.lineTo(p.x, p.y);
}
ctx.closePath();
ctx.fill();
}
}
function polysToSVG(image, polys, forPreview) {
var framePadFrac = 0.1;
var imageMaxDim = Math.max(image.width, image.height);
var framePadPx = framePadFrac*imageMaxDim;
var withFrameWidthPx = image.width + 2*framePadPx;
var withFrameHeightPx = image.height + 2*framePadPx;
var svgWidth, svgHeight;
var viewBox;
var polyScale;
var polyOffset;
var cutStrokeWidth;
var frameCutX, frameCutY, frameCutWidth, frameCutHeight;
if (forPreview) {
// For web preview
polyScale = 1.0;
polyOffset = 0;
cutStrokeWidth = '1px';
} else {
// For real laser cutting
// We give an extra mm of safe area padding beyond what Ponoko says, so we do 6mm instead of 5mm
// These safeXXX vars are in mm units
var safeAreaWidth = 788;
var safeAreaHeight = 382;
var safeOffset = 6;
polyScale = Math.min(safeAreaWidth/withFrameWidthPx, safeAreaHeight/withFrameHeightPx);
polyOffset = {
x: safeOffset + framePadPx*polyScale,
y: safeOffset + framePadPx*polyScale,
};
var totalWidth = polyScale*withFrameWidthPx + 2*safeOffset;
var totalHeight = polyScale*withFrameHeightPx + 2*safeOffset;
svgWidth = totalWidth + 'mm';
svgHeight = totalHeight + 'mm';
viewBox = '0 0 ' + totalWidth + ' ' + totalHeight;
cutStrokeWidth = '0.01';
frameCutX = safeOffset;
frameCutY = safeOffset;
frameCutWidth = polyScale*withFrameWidthPx;
frameCutHeight = polyScale*withFrameHeightPx;
}
var polysPathData = '';
for (var i = 0; i < currentPolys.length; i++) {
var poly = currentPolys[i];
for (var j = 0; j < poly.length; j++) {
var p = poly[j];
var tp = {
x: p.x*polyScale + polyOffset.x,
y: p.y*polyScale + polyOffset.y,
};
if (j === 0) {
polysPathData += 'M'; // moveto absolute
} else {
polysPathData += 'L'; // lineto absolute
}
polysPathData += tp.x.toFixed(4) + ',' + tp.y.toFixed(4);
}
polysPathData += 'z'; // closepath
}
var cutColor = 'rgb(0,0,255)';
var exportText = '';
exportText += '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n';
exportText += '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="' + svgWidth + '" height="' + svgHeight + '" viewBox="' + viewBox + '">\n';
exportText += ' <path fill="none" stroke="' + cutColor + '" stroke-width="' + cutStrokeWidth + '" d="' + polysPathData + '"/>\n';
exportText += ' <rect x="' + frameCutX + '" y="' + frameCutX + '" width="' + frameCutWidth + '" height="' + frameCutHeight + '" fill="none" stroke="' + cutColor + '" stroke-width="' + cutStrokeWidth + '"/>\n';
exportText += '</svg>';
return exportText;
}
function setCurrentImage(image) {
currentImage = image;
console.log('Loaded image ' + image.width + 'x' + image.height);
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var mainElem = document.getElementById('main');
mainElem.insertBefore(canvas, mainElem.firstChild);
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, image.width, image.height);
var imageData = ctx.getImageData(0, 0, image.width, image.height);
console.log('Extracted ' + imageData.data.length + ' bytes of image data');
console.log('Sampling ...');
var testStrips = new strips.SimpleVerticalStrips(image.width, image.height, 40, 100);
currentPolys = testStrips.sampleToPolys(imageData, 1);
console.log('Finished sampling');
renderPolys(canvas, currentPolys);
}
document.addEventListener('DOMContentLoaded', function() {
var dropTarget = document;
dropTarget.addEventListener('dragover', function(e){ e.preventDefault(); }, true);
dropTarget.addEventListener('drop', function(e) {
e.preventDefault();
loadImageFromFile(e.dataTransfer.files[0], function(image) {
setCurrentImage(image);
});
}, true);
document.getElementById('preview-link').addEventListener('click', function(e) {
if (!currentPolys) {
return;
}
var svgData = polysToSVG(currentImage, currentPolys, true);
this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
}, false);
document.getElementById('download-link').addEventListener('click', function(e) {
if (!currentPolys) {
return;
}
var svgData = polysToSVG(currentImage, currentPolys, false);
this.href = 'data:image/svg+xml,' + encodeURIComponent(svgData);
}, false);
});
| JavaScript | 0.000001 | @@ -1112,17 +1112,18 @@
rac = 0.
-1
+05
;%0A var
@@ -4550,13 +4550,14 @@
ht,
-40, 1
+118, 2
00);
|
c1bed3b9db2cc6be7177e0829c2d0b1431242ba7 | Set operating system determination. | main.js | main.js | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
electron.crashReporter.start({
productName: 'GeometrA',
companyName: 'NTUT',
submitURL: 'https://localhost:5000',
uploadToServer: true
});
var mainWindow = null;
app.on('window-all-closed', function() {
//if (process.platform != 'darwin') {
app.quit();
//}
});
app.on('ready', function() {
// call python?
var subpy = require('child_process').spawn('python3', ['./main.py']);
var rq = require('request-promise');
var mainAddr = 'http://localhost:5000';
var openWindow = function(){
mainWindow = new BrowserWindow({width: 800, height: 600});
// mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.loadURL('http://localhost:5000');
mainWindow.webContents.openDevTools();
mainWindow.on('closed', function() {
mainWindow = null;
subpy.kill('SIGINT');
});
};
app.on('activate', function () {
if (mainWindow === null) {
openWindow()
}
})
var startUp = function(){
rq(mainAddr)
.then(function(htmlString){
console.log('server started!');
openWindow();
})
.catch(function(err){
//console.log('waiting for the server start...');
startUp();
});
};
// fire!
startUp();
});
| JavaScript | 0 | @@ -430,16 +430,130 @@
python?%0A
+ if (process.platform === %22win32%22)%0A var subpy = require('child_process').spawn('py', %5B'./main.py'%5D);%0A else%0A
var su
|
52fb8dc799ae15f577e0204e0447e9749f7a3dd8 | clarify email name | main.js | main.js | //
// required packages
//
var fs = require('fs');
var underscore = require('underscore');
var winston = require('winston');
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var forecasts = require('./forecasts.js');
var observations = require('./observations.js');
runServer();
function runServer() {
configureLogger();
initializeForecastProcessing();
startHTTPServer();
}
function configureLogger() {
var localLogFilePath = '/tmp/aviforecast-log.txt';
// remove the default transport, so that we can reconfigure it
winston.remove(winston.transports.Console);
// NOTE verbose, info, warn, error are the log levels we're using
winston.add(winston.transports.Console,
{
level:'info',
timestamp:!(process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') // the heroku envs already have timestamps
});
if (!(process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging')) {
winston.add(winston.transports.File, {level:'info', timestamp:true, json:false, filename:localLogFilePath});
winston.info('main_configureLogger NOT production or staging mode; local logfile is at: ' + localLogFilePath);
}
}
function initializeForecastProcessing() {
var regions = JSON.parse(fs.readFileSync(forecasts.REGIONS_PATH, 'utf8'));
// generate the forecast content
forecasts.aggregateForecasts(regions);
// configure a timer to regenerate the forecast content on a recurring basis
setInterval(forecasts.aggregateForecasts, forecasts.FORECAST_GEN_INTERVAL_SECONDS * 1000, regions);
}
function startHTTPServer() {
var app = express();
// set up the express middleware, in the order we want it to execute
// enable web server logging; pipe those log messages through winston
var winstonStream = {
write: function(str){
winston.info(str);
}
};
app.use(express.logger({stream:winstonStream}));
// compress responses
app.use(express.compress());
// parse request bodies, including file uploads
app.use(express.bodyParser({keepExtensions: true}));
// support observation uploads
app.post('/v1/observation', function (req, res) {
var observation = underscore.pick(req.body, ['providerId', 'email', 'latitude', 'longitude', 'timestampUtc', 'notes']);
observation.image = (req.files ? req.files.image : null);
winston.info('received observation; contents: ' + JSON.stringify(observation));
if (!observation.providerId || !observation.email) {
// bad request
res.send(400);
} else {
observations.processObservation(observation, function(error) {
if (!error) {
res.send(200);
} else {
res.send(500);
}
});
}
});
//
// BEGIN PROXYING HACK
//
// BUGBUG hack to get around problem caching IPAC web pages on android due to cache-control:no-store header;
// proxy their content to avoid these headers being sent to the client
app.get('/v1/proxy/ipac/:zone', function(req, res) {
var baseUrl = 'http://www.idahopanhandleavalanche.org/';
var url = baseUrl + req.params.zone + '.html';
proxy(url, baseUrl, res);
});
// BUGBUG hack to get around problem caching CAIC web pages on android due to cache-control:no-store header;
// proxy their content to avoid these headers being sent to the client
app.get('/v1/proxy/caic/:zone', function(req, res) {
var baseUrl = 'http://avalanche.state.co.us/';
var url = baseUrl + 'caic/pub_bc_avo.php?zone_id=' + req.params.zone;
proxy(url, baseUrl, res);
});
function proxy(url, baseUrl, res) {
request({url:url, jar:false, timeout: forecasts.DATA_REQUEST_TIMEOUT_SECONDS * 1000},
function(error, response, body) {
if (!error && response.statusCode === 200) {
winston.info('successful proxy response; url: ' + url);
body = fixRelativeLinks(baseUrl, body);
res.send(body);
} else {
winston.warn('failed proxy response; url: ' + url + '; response status code: ' + (response ? response.statusCode : '[no response]') + '; error: ' + error);
res.send(503);
}
}
);
}
function fixRelativeLinks(baseUrl, body) {
// NOTE some sites use relative links, but don't specify the base url, which breaks things when
// going through our explicit proxy; so fix the pages by putting in a <base> tag
var $ = cheerio.load(body, {lowerCaseTags:true, lowerCaseAttributeNames:true});
$('head').prepend('<base href=' + baseUrl + '>');
return $.html();
}
//
// END PROXYING HACK
//
// serve static content
app.use(express.static(forecasts.STATIC_FILES_DIR_PATH, {maxAge: forecasts.CACHE_MAX_AGE_SECONDS * 1000 }));
// handle errors gracefully
app.use(express.errorHandler());
// use the value from the PORT env variable if available, fallback if not
var port = process.env.PORT || 5000;
app.listen(port,
function () {
// NOTE if you don't get this log message, then the http server didn't start correctly;
// check if another instance is already running...
winston.info('HTTP server listening on port: ' + port);
}
);
}
| JavaScript | 0.999994 | @@ -2378,17 +2378,25 @@
erId', '
-e
+observerE
mail', '
|
2284c5f768027a13e22ae5f58d0b2a03eba2a4c9 | set endpoint transfer type bulk, changed timeout to infinite | main.js | main.js | const ROMVID = 0x0451;
const ROMPID = 0x6141;
const BOOTPS = 67;
const BOOTPC = 68;
const IPUDP = 17;
const SPLVID = 0x0525;
const SPLPID = 0xA4A2;
const ETHIPP = 0x0800;
const ETHARPP = 0x0806;
const MAXBUF = 450;
const server_hwaddr = [0x9a, 0x1f, 0x85, 0x1c, 0x3d, 0x0e];
const server_ip = [0xc0, 0xa8, 0x01, 0x09]; // 192.168.1.9
const BB_ip = [0xc0, 0xa8, 0x01, 0x03]; // 192.168.1.3
const servername = [66, 69, 65, 71, 76, 69, 66, 79, 79, 84]; // ASCII ['B','E','A','G','L','E','B','O','O','T']
const file_spl = [42, 83, 80, 76, 43]; // ASCII ['*','S','P','L','*']
const file_uboot = [85, 66, 79, 79, 84]; // ASCII ['U','B','O','O','T']
// Size of all packets
var rndisSize = 44;
var etherSize = 14;
var arp_Size = 28;
var ipSize = 20;
var udpSize = 8;
var bootpSize = 300;
var tftpSize = 4;
var fullSize = 386;
// Include modules
var usb = require('usb');
var protocols = require('./src/protocols');
var deasync = require('deasync');
// Connect to BeagleBone
var device = usb.findByIds(ROMVID, ROMPID);
device.open();
var interface = device.interface(1); // Select interface 1
// Detach Kernel Driver
if(interface.isKernelDriverActive()){
interface.detachKernelDriver();
}
interface.claim();
// Set endpoints for usb transfer
var inEndpoint = interface.endpoint(0x81);
var outEndpoint = interface.endpoint(0x02);
// Receive BOOTP
var bootp_buf = Buffer.alloc(MAXBUF-rndisSize); // Buffer for InEnd transfer
inEndpoint.timeout = 1000;
inEndpoint.transfer(MAXBUF, onFirstIn); // InEnd transfer
var done = false; // Boolean for sync function
function onFirstIn(error, data) { // Callback for InEnd transfer
data.copy(bootp_buf, 0, rndisSize, MAXBUF);
done = true;
}
deasync.loopWhile(function(){return !done;}); // Synchronize InEnd transfer function
var ether = protocols.decode_ether(bootp_buf); // Gets decoded ether packet data
var rndis = protocols.make_rndis(fullSize-rndisSize); // Make RNDIS
var eth2 = protocols.make_ether2(ether.h_source, server_hwaddr); // Make ether2
var ip = protocols.make_ipv4(server_ip, BB_ip, IPUDP, 0, ipSize + udpSize + bootpSize); // Make ipv4
var udp = protocols.make_udp(bootpSize, BOOTPS, BOOTPC); // Make udp
var bootreply = protocols.make_bootp(servername, file_spl, 1, ether.h_source, BB_ip, server_ip); // Make BOOTP for reply
| JavaScript | 0 | @@ -1423,16 +1423,162 @@
0x02);%0A%0A
+// Set endpoint transfer type%0AinEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;%0AoutEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK;%0A%0A
// Recei
@@ -1586,16 +1586,16 @@
e BOOTP%0A
-
var boot
@@ -1667,16 +1667,16 @@
ransfer%0A
+
inEndpoi
@@ -1692,11 +1692,8 @@
t =
-100
0;
|
9fa8012315ac93db07e5a4510c06237e66ae8b44 | Convert haveMsisdnToken to async / await | src/AddThreepid.js | src/AddThreepid.js | /*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
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.
*/
import MatrixClientPeg from './MatrixClientPeg';
import { _t } from './languageHandler';
/**
* Allows a user to add a third party identifier to their homeserver and,
* optionally, the identity servers.
*
* This involves getting an email token from the identity server to "prove" that
* the client owns the given email address, which is then passed to the
* add threepid API on the homeserver.
*/
export default class AddThreepid {
constructor() {
this.clientSecret = MatrixClientPeg.get().generateClientSecret();
}
/**
* Attempt to add an email threepid. This will trigger a side-effect of
* sending an email to the provided email address.
* @param {string} emailAddress The email address to add
* @param {boolean} bind If True, bind this email to this mxid on the Identity Server
* @return {Promise} Resolves when the email has been sent. Then call checkEmailLinkClicked().
*/
addEmailAddress(emailAddress, bind) {
this.bind = bind;
return MatrixClientPeg.get().requestAdd3pidEmailToken(emailAddress, this.clientSecret, 1).then((res) => {
this.sessionId = res.sid;
return res;
}, function(err) {
if (err.errcode === 'M_THREEPID_IN_USE') {
err.message = _t('This email address is already in use');
} else if (err.httpStatus) {
err.message = err.message + ` (Status ${err.httpStatus})`;
}
throw err;
});
}
/**
* Attempt to add a msisdn threepid. This will trigger a side-effect of
* sending a test message to the provided phone number.
* @param {string} phoneCountry The ISO 2 letter code of the country to resolve phoneNumber in
* @param {string} phoneNumber The national or international formatted phone number to add
* @param {boolean} bind If True, bind this phone number to this mxid on the Identity Server
* @return {Promise} Resolves when the text message has been sent. Then call haveMsisdnToken().
*/
addMsisdn(phoneCountry, phoneNumber, bind) {
this.bind = bind;
return MatrixClientPeg.get().requestAdd3pidMsisdnToken(
phoneCountry, phoneNumber, this.clientSecret, 1,
).then((res) => {
this.sessionId = res.sid;
return res;
}, function(err) {
if (err.errcode === 'M_THREEPID_IN_USE') {
err.message = _t('This phone number is already in use');
} else if (err.httpStatus) {
err.message = err.message + ` (Status ${err.httpStatus})`;
}
throw err;
});
}
/**
* Checks if the email link has been clicked by attempting to add the threepid
* @return {Promise} Resolves if the email address was added. Rejects with an object
* with a "message" property which contains a human-readable message detailing why
* the request failed.
*/
checkEmailLinkClicked() {
const identityServerDomain = MatrixClientPeg.get().idBaseUrl.split("://")[1];
return MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind).catch(function(err) {
if (err.httpStatus === 401) {
err.message = _t('Failed to verify email address: make sure you clicked the link in the email');
} else if (err.httpStatus) {
err.message += ` (Status ${err.httpStatus})`;
}
throw err;
});
}
/**
* Takes a phone number verification code as entered by the user and validates
* it with the ID server, then if successful, adds the phone number.
* @param {string} token phone number verification code as entered by the user
* @return {Promise} Resolves if the phone number was added. Rejects with an object
* with a "message" property which contains a human-readable message detailing why
* the request failed.
*/
haveMsisdnToken(token) {
return MatrixClientPeg.get().submitMsisdnToken(
this.sessionId, this.clientSecret, token,
).then((result) => {
if (result.errcode) {
throw result;
}
const identityServerDomain = MatrixClientPeg.get().idBaseUrl.split("://")[1];
return MatrixClientPeg.get().addThreePid({
sid: this.sessionId,
client_secret: this.clientSecret,
id_server: identityServerDomain,
}, this.bind);
});
}
}
| JavaScript | 0.999989 | @@ -4670,16 +4670,22 @@
*/%0A
+async
haveMsis
@@ -4701,38 +4701,52 @@
oken) %7B%0A
-return
+const result = await
MatrixClientPeg
@@ -4838,38 +4838,18 @@
)
-.then((result) =%3E %7B%0A
+;%0A
if
@@ -4840,26 +4840,24 @@
);%0A
-
if (result.e
@@ -4862,28 +4862,24 @@
.errcode) %7B%0A
-
@@ -4896,34 +4896,27 @@
lt;%0A
- %7D%0A
+%7D%0A%0A
cons
@@ -4993,28 +4993,24 @@
1%5D;%0A
-
return Matri
@@ -5044,36 +5044,32 @@
d(%7B%0A
-
sid: this.sessio
@@ -5077,36 +5077,32 @@
Id,%0A
-
-
client_secret: t
@@ -5123,36 +5123,32 @@
et,%0A
-
-
id_server: ident
@@ -5168,28 +5168,24 @@
in,%0A
-
%7D, this.bind
@@ -5187,28 +5187,16 @@
.bind);%0A
- %7D);%0A
%7D%0A%7D%0A
|
b919bbded06371454fe288a8450ef72a67d5d677 | Allow Browserify to handle regenerator errors #20 | main.js | main.js | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var path = require("path");
var fs = require("fs");
var through = require("through");
var transform = require("./lib/visit").transform;
var utils = require("./lib/util");
var recast = require("recast");
var types = recast.types;
var genOrAsyncFunExp = /\bfunction\s*\*|\basync\b/;
var blockBindingExp = /\b(let|const)\s+/;
function exports(file, options) {
var data = [];
return through(write, end);
function write(buf) {
data.push(buf);
}
function end() {
this.queue(compile(data.join(""), options).code);
this.queue(null);
}
}
// To get a writable stream for use as a browserify transform, call
// require("regenerator")().
module.exports = exports;
// To include the runtime globally in the current node process, call
// require("regenerator").runtime().
function runtime() {
require("regenerator-runtime");
}
exports.runtime = runtime;
runtime.path = require("regenerator-runtime/path.js").path;
function compile(source, options) {
options = normalizeOptions(options);
if (!genOrAsyncFunExp.test(source)) {
return {
// Shortcut: no generators or async functions to transform.
code: (options.includeRuntime === true ? fs.readFileSync(
runtime.path, "utf-8"
) + "\n" : "") + source
};
}
var recastOptions = getRecastOptions(options);
var ast = recast.parse(source, recastOptions);
var nodePath = new types.NodePath(ast);
var programPath = nodePath.get("program");
if (shouldVarify(source, options)) {
// Transpile let/const into var declarations.
varifyAst(programPath.node);
}
transform(programPath, options);
return recast.print(nodePath, recastOptions);
}
function normalizeOptions(options) {
options = utils.defaults(options || {}, {
includeRuntime: false,
supportBlockBinding: true
});
if (!options.esprima) {
options.esprima = require("esprima-fb");
}
assert.ok(
/harmony/.test(options.esprima.version),
"Bad esprima version: " + options.esprima.version
);
return options;
}
function getRecastOptions(options) {
var recastOptions = {
range: true
};
function copy(name) {
if (name in options) {
recastOptions[name] = options[name];
}
}
copy("esprima");
copy("sourceFileName");
copy("sourceMapName");
copy("inputSourceMap");
copy("sourceRoot");
return recastOptions;
}
function shouldVarify(source, options) {
var supportBlockBinding = !!options.supportBlockBinding;
if (supportBlockBinding) {
if (!blockBindingExp.test(source)) {
supportBlockBinding = false;
}
}
return supportBlockBinding;
}
function varify(source, options) {
var recastOptions = getRecastOptions(normalizeOptions(options));
var ast = recast.parse(source, recastOptions);
varifyAst(ast.program);
return recast.print(ast, recastOptions).code;
}
function varifyAst(ast) {
types.namedTypes.Program.assert(ast);
var defsResult = require("defs")(ast, {
ast: true,
disallowUnknownReferences: false,
disallowDuplicated: false,
disallowVars: false,
loopClosures: "iife"
});
if (defsResult.errors) {
throw new Error(defsResult.errors.join("\n"))
}
return ast;
}
// Convenience for just translating let/const to var declarations.
exports.varify = varify;
// Allow packages that depend on Regenerator to use the same copy of
// ast-types, in case multiple versions are installed by NPM.
exports.types = types;
// Transforms a string of source code, returning the { code, map? } result
// from recast.print.
exports.compile = compile;
// To modify an AST directly, call require("regenerator").transform(ast).
exports.transform = transform;
| JavaScript | 0 | @@ -809,24 +809,36 @@
ion end() %7B%0A
+ try %7B%0A
this.que
@@ -879,24 +879,26 @@
.code);%0A
+
this.queue(n
@@ -903,16 +903,59 @@
(null);%0A
+ %7D catch (e) %7B this.emit('error', e); %7D%0A
%7D%0A%7D%0A%0A/
|
03ce4f6e47168142a741dd8e5f9334ceba191473 | Check external links on new windows too | main.js | main.js | const url = require('url')
const menuTemplateBuilder = require('./lib/menu')
const { app, BrowserWindow, Menu, shell } = require('electron')
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')()
// prevent window being garbage collected
let mainWindow
function onClosed () {
// dereference the window
// for multiple windows store them in an array
mainWindow = null
}
// Open external links on default browser
function onNewWindow (event, newURL, frameName, disposition, options) {
const urlObject = url.parse(newURL, true)
// Change width and height to something better
options.width = 1280
options.height = 720
// Messenger has some interesting views for some pages
if (urlObject.hostname === 'l.messenger.com' ||
urlObject.hostname === 'l.facebook.com'
) {
const targetURL = url.parse(urlObject.query.u, true)
// Allowed targets
if (targetURL.hostname === 'media.giphy.com' || // Giphy
targetURL.href.match(/google\.\w{1,3}\/maps\//i) || // Google Maps
targetURL.href.match(/goo.gl\/maps\//i) // Google Maps
) {
return true
} else if (targetURL.hostname === 'www.youtube.com') {
event.preventDefault()
return createYouTubeWindow(targetURL, options)
}
// Show YouTube video in an embedded window
} else if (urlObject.hostname === 'www.youtube.com') {
event.preventDefault()
return createYouTubeWindow(urlObject, options)
}
// Any external link will be sent to the default browser
event.preventDefault()
return shell.openExternal(urlObject.href)
}
function createMainWindow () {
const win = new BrowserWindow({
width: 1280,
height: 800,
webPreferences: {
nodeIntegration: false
}
})
win.loadURL('https://messenger.com')
const menu = menuTemplateBuilder(app, shell)
Menu.setApplicationMenu(Menu.buildFromTemplate(menu))
win.on('closed', onClosed)
win.webContents.on('new-window', onNewWindow)
return win
}
function createYouTubeWindow (urlObject, options) {
const win = new BrowserWindow(options)
win.loadURL(`https://www.youtube.com/embed/${urlObject.query.v}`)
win.webContents.on('new-window', onNewWindow)
win.on('closed', onClosed)
return win
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow()
}
})
app.on('ready', () => {
mainWindow = createMainWindow()
})
| JavaScript | 0 | @@ -570,24 +570,49 @@
ewURL, true)
+%0A event.preventDefault()
%0A%0A // Chang
@@ -1177,20 +1177,56 @@
return
-true
+createNewWindow(targetURL.href, options)
%0A %7D e
@@ -1287,73 +1287,83 @@
-event.preventDefault()%0A return createYouTubeWindow(targetURL
+return createNewWindow(%60https://www.youtube.com/embed/$%7BtargetURL.query.v%7D%60
, op
@@ -1486,71 +1486,83 @@
-event.preventDefault()%0A return createYouTubeWindow(urlObject
+return createNewWindow(%60https://www.youtube.com/embed/$%7BurlObject.query.v%7D%60
, op
@@ -1636,33 +1636,8 @@
ser%0A
- event.preventDefault()%0A
re
@@ -1989,37 +1989,8 @@
))%0A%0A
- win.on('closed', onClosed)%0A
wi
@@ -2032,16 +2032,45 @@
wWindow)
+%0A win.on('closed', onClosed)
%0A%0A retu
@@ -2094,23 +2094,19 @@
n create
-YouTube
+New
Window (
@@ -2108,22 +2108,16 @@
dow (url
-Object
, option
@@ -2160,24 +2160,27 @@
(options)%0A%0A
+ //
win.loadURL
@@ -2234,16 +2234,35 @@
ry.v%7D%60)%0A
+ win.loadURL(url)%0A
win.we
|
70b2d2ab5364eded1d77fe4d527fe20ef47607f8 | add a start msg and add score gameover alert | main.js | main.js | var score = 0;
var time = 30;
$(".js-time").text("Time: " + time);
addTile(randomTile(), "blueTile");
window.setInterval(function(){
if (time <= 0) {
$(".js-time").text("Time: " + 0);
alert("Game Over! Looooooser!");
start();
}
else {
time--;
$(".js-time").text("Time: " + time);
}
}, 1000);
window.setInterval(function(){
var rand = Math.floor(Math.random()*50);
if (rand === 13 || rand === 29 || rand === 26) {
addTile(randomTile(), "greenTile");
}
else if (rand < 7){
addTile(randomTile(), "redTile");
}
else
addTile(randomTile(), "blueTile");
}, 1000);
function removeTile(el) {
$(el).removeClass("greenTile");
$(el).removeClass("redTile");
$(el).removeClass("blueTile");
}
function addTile(index, el) {
$($(".grid_tile")[index]).addClass(el);
var test = $(".grid_tile")[index];
setTimeout(function(){
$(test).removeClass("redTile");
}, 3500);
setTimeout(function(){
$(test).removeClass("greenTile");
}, 1500);
}
function start() {
$(".js-score").text("Score: " + score);
$(".js-time").text("Time: " + time);
score = 0;
time = 30;
removeTile(".grid_tile");
}
function select(el) {
if ($(el).hasClass("blueTile")) {
score++;
removeTile(el);
addTile(randomTile(), "blueTile");
}
else if ($(el).hasClass("redTile")) {
removeTile(el);
time -= 10;
}
else if ($(el).hasClass("greenTile")) {
removeTile(el);
score += 5;
time += 5;
}
else {
time -=2;
}
$(".js-score").text("Score: " + score);
$(".js-time").text("Time: " + time);
}
function randomTile() {
var rand = Math.floor(Math.random()*20);
var el = $(".grid_tile")[rand];
if($(el).hasClass("redTile") || $(el).hasClass("blueTile") || $(el).hasClass("greenTile"))
return randomTile();
return rand;
}
| JavaScript | 0 | @@ -23,16 +23,101 @@
e = 30;%0A
+alert(%22This game is under heavy development! Therefore, there are still some bugs.%22);
%0A$(%22.js-
@@ -296,20 +296,29 @@
er!
-Looooooser!%22
+Your score: %22 + score
);%0A
|
6e80490a163675550977cd19894685acbc09eb71 | remove debug code | main.js | main.js | import input from 'inquirer'
import anidb from './api/anidb'
import animeplanet from './api/animeplanet'
import anilist from './api/anilist'
import annict from './api/annict'
import kitsu from './api/kitsu'
import myanimelist from './api/myanimelist'
const log = console.log
input.prompt([
{
type: 'checkbox',
name: 'service',
message: 'Select service to test:',
choices: [
{
name: 'AniDB',
disabled: 'not implemented'
},
{
name: 'AniList',
disabled: 'not implemented'
},
{
name: 'AnimePlanet',
disabled: 'no api'
},
{
name: 'Annict',
disabled: 'not implemented'
},
{
name: 'Kitsu',
disabled: 'not implemented'
},
'MyAnimeList'
],
validate: answer => {
if (answer.length < 1) {
return 'Select at least one service'
}
return true
}
},
{
type: 'list',
name: 'type',
message: 'Library type to use:',
choices: [
'Anime',
'Manga'
]
}
])
.then(answer => {
console.log(answer)
answer.service.forEach(service => {
switch (service) {
case ('AniDB'):
anidb(answer.type)
break
case ('AniList'):
anilist(answer.type)
break
case ('AnimePlanet'):
animeplanet(answer.type)
break
case ('Annict'):
annict(answer.type)
break
case ('Kitsu'):
kitsu(answer.type)
break
case ('MyAnimeList'):
myanimelist(answer.type)
break
}
})
})
| JavaScript | 0.000492 | @@ -1329,32 +1329,8 @@
%3E %7B%0A
- console.log(answer)%0A
|
10c4dfc9c61e9104ec09d6ff33d1b43cea35451b | fix bad cookies | main.js | main.js | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import configureStore from './store/bots';
import config from 'react-global-configuration';
if (!String.prototype.includes) {
String.prototype.includes = function() {
'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
config.set({
API_HOST: "tweebot.co:8080"
});
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('app'))
| JavaScript | 0.000003 | @@ -210,16 +210,73 @@
ation';%0A
+import cookie from 'react-cookie';%0A%0A//for IE/opera/safari
%0Aif (!St
@@ -450,16 +450,340 @@
%7D;%0A%7D%0A%0A
+//if the userId cookie is in bad form, get rid of it%0Aif(cookie.load('userId'))%0Aif(!(typeof cookie.load('userId') == 'string'))%7B%0A Object.keys(cookie.select(/%5Euser.*/i)).forEach(name =%3E cookie.remove(name, %7B path: '/' %7D));%0A Object.keys(cookie.select(/%5Eoauth.*/i)).forEach(name =%3E cookie.remove(name, %7B path: '/' %7D));%0A%7D%0A%0A
config.s
@@ -957,9 +957,10 @@
('app'))
+;
%0A
|
9defb2f58578e3c504b00708bbb249cb154059ce | update main process registry | main.js | main.js | module.exports = {
load: function () {
},
unload: function () {
},
'ui-tree:open': function () {
Editor.Panel.open('ui-tree.preview');
},
};
| JavaScript | 0.000001 | @@ -1,8 +1,23 @@
+'use strict';%0A%0A
module.e
@@ -31,34 +31,22 @@
= %7B%0A
-
load
-: function
() %7B%0A
%7D,
@@ -45,24 +45,20 @@
%7B%0A
-
-
%7D,%0A%0A
-
unload
: fu
@@ -53,34 +53,24 @@
unload
-: function
() %7B%0A
%7D,%0A%0A
@@ -65,50 +65,40 @@
%7B%0A
-
-
%7D,%0A%0A
-
- 'ui-tree:open': functio
+messages: %7B%0A ope
n () %7B%0A
-
@@ -144,11 +144,15 @@
%0A %7D,%0A
+ %7D%0A
%7D;%0A
|
9409acd36ed339fc80f439f0ff0661fe9ae0b56c | Add static file recording | main.js | main.js | /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */
/** Extension that starts/stops Recode and saves when appropriate */
define(function (require, exports, module) {
"use strict";
var CommandManager = brackets.getModule('command/CommandManager'),
Menus = brackets.getModule('command/Menus'),
MainViewManager = brackets.getModule('view/MainViewManager'),
DocumentManager = brackets.getModule('document/DocumentManager'),
FileSystem = brackets.getModule('filesystem/FileSystem'),
ProjectManager = brackets.getModule('project/ProjectManager'),
Dialogs = brackets.getModule('widgets/Dialogs'),
DefaultDialogs = brackets.getModule('widgets/DefaultDialogs'),
ProjectModel = brackets.getModule('project/ProjectModel');
var Recoder = function() {
var self = this;
this.currentDocument = null;
this.recording = false;
this.saveDir = null;
this.startTime = null;
this.onTextChangeProxy = function() {
Recoder.prototype.onTextChange.call(self, arguments);
};
this.onFileChangeProxy = function() {
Recoder.prototype.onFileChange.call(self, arguments);
}
};
Recoder.prototype.onFileChange = function(e, newFile, newPaneId, oldFile, oldPaneId) {
this.removeDocument();
this.addDocument();
};
Recoder.prototype.onTextChange = function(e, document, changelist) {
console.log(changelist);
};
Recoder.prototype.addDocument = function() {
this.currentDocument = DocumentManager.getCurrentDocument();
if (this.currentDocument) {
console.log(this.currentDocument);
this.currentDocument.addRef();
this.currentDocument.on('change', this.onTextChangeProxy);
}
};
Recoder.prototype.removeDocument = function() {
if (this.currentDocument) {
this.currentDocument.off('change', this.onTextChangeProxy);
this.currentDocument.releaseRef();
}
this.currentDocument = null;
};
Recoder.prototype.start = function(callback) {
var self = this;
var now = new Date();
var formatDate = (now.getFullYear()) + '-' + (now.getMonth() + 1) + '-' + (now.getDate()) + '_' + (now.getHours()) + '-' + (now.getMinutes()) + '-' + (now.getSeconds());
var recodeFolder = ProjectManager.getProjectRoot().fullPath + 'recode-sessions/';
var startRecode = function startRecode() {
self.recording = true;
MainViewManager.on('currentFileChange', self.onFileChangeProxy);
self.addDocument();
callback();
};
var makeDirectory = function makeDirectory() {
self.startTime = now.getTime();
self.saveDir = recodeFolder + formatDate + '/';
console.log(self.saveDir);
ProjectManager
.createNewItem(ProjectManager.getProjectRoot(), 'recode-sessions/' + formatDate + '/', true, true)
.done(startRecode);
};
FileSystem.resolve(recodeFolder, function(error, file, stats) {
if ((error) && (error !== 'NotFound')) {
Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, 'Error', 'Something went wrong when trying to find the recode-sessions folder: ' + error);
return;
}
if ((!file) || (file.isDirectory)) {
makeDirectory();
} else {
Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, 'Save Error', 'The entry "recode-sessions" at project root must be a directory, currently it is not.');
}
});
};
Recoder.prototype.stop = function() {
this.recording = false;
// Unbind events
MainViewManager.off('currentFileChange', this.onFileChangeProxy);
this.removeDocument();
};
var recoder = new Recoder();
// Function to run when the menu item is clicked
function handleRecode() {
if (!recoder.recording) {
recoder.start(function() {
command.setName('Stop Recoding');
});
} else {
recoder.stop();
command.setName('Recode');
}
}
// First, register a command - a UI-less object associating an id to a handler
var RECODE_COMMAND_ID = "recode.recode"; // package-style naming to avoid collisions
var command = CommandManager.register("Recode", RECODE_COMMAND_ID, handleRecode);
// Then create a menu item bound to the command
// The label of the menu item is the name we gave the command (see above)
var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
menu.addMenuItem(RECODE_COMMAND_ID);
// We could also add a key binding at the same time:
//menu.addMenuItem(MY_COMMAND_ID, "Ctrl-Alt-H");
// (Note: "Ctrl" is automatically mapped to "Cmd" on Mac)
});
| JavaScript | 0.000001 | @@ -1055,16 +1055,48 @@
= null;
+%0A this.trackedFiles = %5B%5D;
%0A%0A
@@ -1174,28 +1174,29 @@
nTextChange.
-call
+apply
(self, argum
@@ -1303,20 +1303,21 @@
eChange.
-call
+apply
(self, a
@@ -1747,82 +1747,642 @@
-if (this.currentDocument) %7B%0A console.log(this.currentDocument);
+console.log(this.currentDocument);%0A if (this.currentDocument) %7B%0A if (this.trackedFiles.indexOf(this.currentDocument.file.fullPath) === -1) %7B%0A this.trackedFiles.push(this.currentDocument.file.fullPath);%0A var path = this.saveDir + ProjectManager.makeProjectRelativeIfPossible(this.currentDocument.file.fullPath).replace(/%5C//g, '--');%0A var file = FileSystem.getFileForPath(path);%0A file.write(this.currentDocument.getText(), function(error, stats) %7B%0A console.error(%22Error saving new Recode file: %22 + error);%0A %7D);%0A %7D
%0A
@@ -4575,32 +4575,64 @@
leChangeProxy);%0A
+ this.trackedFiles = %5B%5D;%0A
this.rem
|
75e0fd0d6b0789f8843d8c7247944e8b8a0a99f3 | Add pause support | main.js | main.js | var app = require('app'),
browserWindow = require('browser-window'),
globalShortcut = require('global-shortcut'),
mainWindow = null;
app.on('window-all-closed', function () {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function () {
mainWindow = new browserWindow({
width : 1280,
height : 720,
'title' : 'Brain.fm',
webSecurity : false,
'node-integration': false
});
mainWindow.setMenu(null);
mainWindow.loadURL('http://brain.fm');
//mainWindow.webContents.openDevTools();
mainWindow.on('app-command', function (e, cmd) {
if (cmd === 'browser-backward' && mainWindow.webContents.canGoBack()) {
mainWindow.webContents.goBack();
}
else if (cmd === 'browser-forward' && mainWindow.webContents.canGoForward()) {
mainWindow.webContents.goForward();
}
});
// Global shortcuts..
globalShortcut.register('MediaNextTrack', function () {skip();});
globalShortcut.register('MediaStop', function () {playPause();}); // ?
globalShortcut.register('MediaPlayPause', function () {playPause();});
//globalShortcut.register('MediaPreviousTrack', function() {});
mainWindow.on('closed', function () {
mainWindow = null;
});
});
function skip() {
if (mainWindow == null) {
return;
}
// todo
}
function playPause() {
if (mainWindow == null) {
return;
}
mainWindow.webContents.executeJavaScript('' +
'if ($("#play_button").hasClass("tc_pause")) {' +
'$("#jquery_jplayer").jPlayer("play", 0);' +
'$("#play_button").removeClass("tc_pause").addClass("tc_play");' +
'} else {' +
'$("#jquery_jplayer").jPlayer("play", 1);' +
'$("#play_button").removeClass("tc_play").addClass("tc_pause");' +
'}'
);
}
| JavaScript | 0.000001 | @@ -964,80 +964,8 @@
%7D);%0A
-%09globalShortcut.register('MediaStop', function () %7BplayPause();%7D); // ?%0A
%09glo
@@ -1032,16 +1032,16 @@
e();%7D);%0A
+
%09//globa
@@ -1350,19 +1350,8 @@
pt('
-' +%0A%09%09'if (
$(%22#
@@ -1368,293 +1368,17 @@
n%22).
-hasClass(%22tc_pause%22)) %7B' +%0A%09%09'$(%22#jquery_jplayer%22).jPlayer(%22play%22, 0);' +%0A%09%09'$(%22#play_button%22).removeClass(%22tc_pause%22).addClass(%22tc_play%22);' +%0A%09%09'%7D else %7B' +%0A%09%09'$(%22#jquery_jplayer%22).jPlayer(%22play%22, 1);' +%0A%09%09'$(%22#play_button%22).removeClass(%22tc_play%22).addClass(%22tc_pause%22);' +%0A%09%09'%7D'%0A%09);%0A%7D%0A%0A%0A
+click()');%0A%7D
%0A
|
886616e85c5c2d0a63bddf465a185ebbe399c6cf | allow running multiple services in parallel | main.js | main.js | import input from 'inquirer'
import anidb from './api/anidb'
import animeplanet from './api/animeplanet'
import anilist from './api/anilist'
import annict from './api/annict'
import kitsu from './api/kitsu'
import myanimelist from './api/myanimelist'
const log = console.log
input.prompt([
{
type: 'checkbox',
name: 'service',
message: 'Select service to test:',
choices: [
{
name: 'AniDB',
disabled: 'not implemented'
},
{
name: 'AniList',
disabled: 'not implemented'
},
{
name: 'AnimePlanet',
disabled: 'no api'
},
{
name: 'Annict',
disabled: 'not implemented'
},
{
name: 'Kitsu',
disabled: 'not implemented'
},
'MyAnimeList'
],
validate: answer => {
if (answer.length < 1) {
return 'Select at least one service'
}
return true
}
},
{
type: 'list',
name: 'type',
message: 'Library type to use:',
choices: [
'Anime',
'Manga'
]
}
])
.then(answer => {
switch (answer.service) {
case ('AniDB'):
anidb(answer.type)
break
case ('AniList'):
anilist(answer.type)
break
case ('AnimePlanet'):
animeplanet(answer.type)
break
case ('Annict'):
annict(answer.type)
break
case ('Kitsu'):
kitsu(answer.type)
break
case ('MyAnimeList'):
myanimelist(answer.type)
break
}
})
| JavaScript | 0 | @@ -1333,34 +1333,99 @@
-switch (answer.service) %7B%0A
+console.log(answer)%0A answer.service.forEach(service =%3E %7B%0A switch (service) %7B%0A
@@ -1456,16 +1456,20 @@
+
+
anidb(an
@@ -1483,38 +1483,46 @@
pe)%0A
+
break%0A
+
case ('A
@@ -1543,16 +1543,20 @@
+
anilist(
@@ -1572,32 +1572,36 @@
pe)%0A
+
break%0A ca
@@ -1590,32 +1590,36 @@
break%0A
+
+
case ('AnimePlan
@@ -1620,24 +1620,28 @@
mePlanet'):%0A
+
@@ -1657,32 +1657,36 @@
et(answer.type)%0A
+
brea
@@ -1687,32 +1687,36 @@
break%0A
+
case ('Annict'):
@@ -1712,24 +1712,28 @@
('Annict'):%0A
+
@@ -1756,38 +1756,46 @@
pe)%0A
+
+
break%0A
+
case ('K
@@ -1814,16 +1814,20 @@
+
+
kitsu(an
@@ -1841,38 +1841,46 @@
pe)%0A
+
break%0A
+
case ('M
@@ -1905,16 +1905,20 @@
+
myanimel
@@ -1950,19 +1950,34 @@
+
break%0A
+
%7D%0A
+ %7D)%0A
%7D)%0A
|
5a9268ed78ad9a3e4634cd2f03b453d354b8e9ca | Send full URLs back to cURL upload requests. | main.js | main.js | 'use strict';
var fs = require('fs');
var readTextFileSync = require('read-text-file-sync');
var mkdirp = require('mkdirp');
var path = require('path');
var extname = path.extname;
var basename = path.basename;
var realpathSync = fs.realpathSync;
var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer({ dest: './uploads' });
var uploadPage = readTextFileSync(__dirname + '/upload.html');
var key = process.env.TEAMKEY;
if(!key) {
console.error("Missing TEAMKEY.");
process.exit(-1);
}
function keyCheck(req, res, next) {
if(req.params.key !== key) {
res.status(403);
res.send("Bad team key.");
return;
}
next();
}
app.get('/upload/:key', keyCheck, function(req, res) {
res.send(uploadPage);
});
app.post('/upload/:key', keyCheck, upload.single('file'), function(req, res) {
var originalPath = './uploads/' + req.file.filename;
var newPath = originalPath + extname(req.file.originalname);
var newPathBaseName = basename(newPath);
var refDirPath = './refs/' + req.file.originalname;
var refPath = refDirPath + '/' + newPathBaseName;
var relUrl;
fs.renameSync(originalPath, newPath);
fs.symlinkSync(newPathBaseName, originalPath);
mkdirp.sync(refDirPath);
fs.symlinkSync('../../uploads/' + newPathBaseName, refPath);
relUrl = '/' + basename(originalPath) + '/' + req.file.originalname;
if(req.get('User-Agent').startsWith('curl/')) {
res.send(relUrl);
}
else {
res.redirect(relUrl);
}
});
app.use(function(req, res, next) {
var urlPath = req.url;
var reResults;
reResults = /^(\/[^\/]+)/.exec(urlPath);
if(!reResults) {
next();
return;
}
req.url = reResults[1];
next();
});
{
let mime = express.static.mime;
let originalFn = mime.lookup;
mime.lookup = function (path, fallback) {
if(fs.existsSync(path)) {
path = realpathSync(path);
}
return originalFn.call(this, path, fallback);
};
}
app.use(express.static('./uploads'));
app.listen(process.env.PORT || 3000);
| JavaScript | 0 | @@ -791,24 +791,179 @@
Page);%0A%7D);%0A%0A
+function fullUrl(req, rel) %7B%0A if(rel%5B0%5D === '/') %7B%0A rel = rel.slice(1);%0A %7D%0A%0A return req.protocol + '://' + req.get('Host') + '/' + rel;%0A%7D%0A%0A
app.post('/u
@@ -1655,22 +1655,43 @@
es.send(
-relUrl
+fullUrl(req, relUrl) + '%5Cn'
);%0A %7D
|
b59dcf6eef7b9d2b87177aed132abba9e42d55d8 | Increase maximum number of allowed listeners. | make.js | make.js | var b = require('substance-bundler');
var fs = require('fs')
var path = require('path')
var examples = [
'code-editor',
'focused',
'form',
'image',
'inline-node',
'input',
'macros',
'nested',
'table',
'isolated-nodes',
'tangle',
]
b.task('clean', function() {
b.rm('./dist')
})
function _assets(legacy) {
b.copy('node_modules/font-awesome', './dist/lib/font-awesome')
b.copy('node_modules/ace-builds/src', './dist/lib/ace')
b.copy('node_modules/substance/dist', './dist/lib/substance')
b.copy('./index.html', './dist/')
}
b.task('assets', function() {
_assets(true)
})
b.task('dev:assets', function() {
_assets(false)
})
b.task('examples', ['assets'], function() {
examples.forEach(function(name) {
_example(name, true)
})
})
b.task('dev:examples', ['dev:assets'], function() {
examples.forEach(function(name) {
_example(name, false)
})
})
examples.forEach(function(name) {
b.task('dev:'+name, ['dev:assets'], function() {
_example(name, false)
})
b.task(name, ['assets'], function() {
_example(name, true)
})
})
// Used for deployment (transpiled js and css)
b.task('default', ['clean', 'assets', 'examples'])
// Used for development (native js + css)
b.task('dev', ['clean', 'dev:assets', 'dev:examples'])
// starts a server when CLI argument '-s' is set
b.setServerPort(5555)
b.serve({
static: true, route: '/', folder: 'dist'
})
// builds one example
function _example(name, legacy) {
const src = './'+name+'/'
const dist = './dist/'+name+'/'
if (fs.existsSync(src+'assets')) {
b.copy(src+'assets', dist+'assets')
}
b.copy(src+'index.html', dist)
b.css(src+'app.css', dist+'app.css', { variables: legacy })
let opts = {
target: {
useStrict: !legacy,
dest: dist+'app.js',
format: 'umd', moduleName: 'example_'+name
},
ignore: ['./XNode'],
}
if (legacy) {
opts.external = ['substance']
opts.buble = true
} else {
opts.alias = {
'substance': path.join(__dirname, 'node_modules/substance/index.es.js')
}
}
b.js(src+'app.js', opts)
}
| JavaScript | 0 | @@ -82,16 +82,203 @@
path')%0A%0A
+// We need to increase the maximum number of allowed listeners as we want to%0A// watch for changes on a large number of files%0Arequire('events').EventEmitter.prototype._maxListeners = 100%0A%0A
var exam
|
5bf8cfff51f7ecb34db2a21ddec613ccc250994c | Add null check to Trips.js file | Trips.js | Trips.js | var http = require('http'),
fs = require('fs'),
Routes = require('./Routes'),
events = require('events'),
xml2js = require('xml2js'),
util = require('util'),
Progress = require('./Progress'),
blockMap = JSON.parse(fs.readFileSync('conf/block_map.json', 'utf8'));
var Trips = function(routes) {
var self = this,
parser = new xml2js.Parser(),
progress = new Progress('Trips and Stop Times');
self.tripsContent = ['route_id,service_id,trip_id,trip_headsign,direction_id\r\n'],
self.stopTimesContent = ['trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign\r\n'];
self.numberFinished = 0;
self.on('complete', function(self) {
fs.writeFileSync('trips.txt', self.tripsContent.join(''), 'utf8');
fs.writeFileSync('stop_times.txt', self.stopTimesContent.join(''), 'utf8');
self.emit('done');
});
routes.forEach(function(r) {
http.request({
host: 'webservices.nextbus.com',
path: '/service/xmlFeed?command=schedule&a=' + r.agencytag + '&r=' + r.tag
}, function(res) {
var xmlstring = '';
res.on('data', function(chunk) {
xmlstring += chunk;
});
res.on('end', function() {
parser.parseString(xmlstring, function(err, rr) {
if (rr.route) {
tripsBuilder(rr, r, self);
}
self.numberFinished++;
var pc = Math.round((self.numberFinished * 100.0) / routes.length);
progress.tick(pc);
if (self.numberFinished === routes.length) {
self.emit('complete', self);
}
});
});
}).end();
});
};
Trips.prototype = new events.EventEmitter;
module.exports = Trips;
var tripsBuilder = function(nextRoute, ebongoRoute, self) {
var routeId = ebongoRoute.tag,
tripHeadsign = ebongoRoute.name,
services = blockMap[ebongoRoute.agencytag][routeId],
trips = self.tripsContent,
stopTimesContent = self.stopTimesContent;
Object.keys(services).forEach(function(serviceId) {
var blocks = services[serviceId],
prevDirection;
if(serviceId === 'unknown') {
return;
}
nextRoute.route = wrap(nextRoute.route);
nextRoute.route.forEach(function(route) {
var directionId = route['@'].direction,
tripCount = 0,
directionFlag;
if (!prevDirection) {
directionFlag = 0;
} else if (prevDirection != directionId) {
directionFlag = 1;
}
prevDirection = directionId;
route.tr = wrap(route.tr);
route.tr.forEach(function(trip) {
var tripId = routeId + '_' + serviceId + '_' + directionId + '_' + tripCount;
if (!~services[serviceId].indexOf(parseInt(trip['@'].blockID, 10))) {
return;
}
trips.push(routeId + ',', serviceId + ',');
trips.push(tripId + ',');
trips.push('"' + tripHeadsign + '",', directionFlag + '\r\n');
tripCount++;
ebongoRoute.directions = wrap(ebongoRoute.directions);
ebongoRoute.directions.forEach(function(direction) {
var stopCount = 1,
firstTime = '';
if (direction.directiontag === directionId) {
direction.stops = wrap(direction.stops);
direction.stops.forEach(function(stop) {
var stopId = stop.stopnumber,
stopHeadsign = stop.stoptitle,
time = '';
route.header.stop = wrap(route.header.stop);
route.header.stop.forEach(function(metaStop) {
if (metaStop['#'] === stopHeadsign) {
trip.stop = wrap(trip.stop);
trip.stop.forEach(function(timeStop) {
if (metaStop['@'].tag === timeStop['@'].tag && timeStop['#'] != '--') {
time = timeStop['#'];
if (!firstTime) {
firstTime = time;
} else if(parseInt(firstTime.split(':')[0],10) > parseInt(time.split(':')[0],10)) {
var splitTime = time.split(':');
splitTime[0] = (parseInt(splitTime[0],10) + 24) + '';
time = splitTime.join(':');
}
}
});
}
});
stopTimesContent.push(tripId + ',' + time + ',' + time + ',');
stopTimesContent.push(stopId + ',' + stopCount + ',');
stopTimesContent.push('"' + stopHeadsign + '"\r\n');
stopCount++;
});
}
});
});
});
});
};
var wrap = function(obj) {
return util.isArray(obj) ? obj : [obj];
}; | JavaScript | 0 | @@ -1846,16 +1846,40 @@
tent;%0A%09%0A
+%09if (!services) return;%0A
%09Object.
@@ -4276,12 +4276,13 @@
: %5Bobj%5D;%0A%7D;
+%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.