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 |
|---|---|---|---|---|---|---|---|
2dcc2951f721c20944582f35c208908aee859755 | remove callback param | gulpfile.js | gulpfile.js | /**
* Gulp Build Script
* -----------------------------------------------------------------------------
* @category Node.js Build File
* @package Frunt
* @copyright Copyright (c) 2015 Piccirilli Dorsey
* @license https://opensource.org/licenses/MIT The MIT License (MIT)
* @version 1.0
* @link https://github.com/picdorsey/frunt
*/
//
// Modules
//
var gulp = require('gulp');
var argv = require('yargs').argv;
var babelify = require('babelify');
var browserify = require('browserify');
var browserSync = require('browser-sync');
var buffer = require('vinyl-buffer');
var del = require('del');
var reload = browserSync.reload;
var source = require('vinyl-source-stream');
var stringify = require('stringify');
var plugins = require('gulp-load-plugins')();
//
// Assets Paths / Config
//
var dist = './public/';
var guideDist = './public/guide/';
var src = './src/';
var config = {
production: !! plugins.util.env.production,
src: {
scss: src + 'scss/',
js: src + 'js/'
},
dist: {
css: dist + 'assets/css/',
js: dist + 'assets/js/'
},
guideDist: {
css: guideDist + 'assets/css/',
js: guideDist + 'assets/js/'
},
sourcemaps: ! plugins.util.env.production,
autoprefix: true,
babelOptions: {
presets: ['es2015'],
compact: false
},
autoprefixerOptions: {
browsers: ['last 2 versions'],
cascade: false
}
};
//
// Styles
//
function compileScss(src, dist, cb) {
gulp.src(src)
.pipe(plugins.plumber({ errorHandler: function (err) {console.log(err);}}))
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
.pipe(plugins.cssGlobbing({
extensions: ['.scss']
}))
.pipe(plugins.sass({
outputStyle: 'expanded',
errLogToConsole: true,
sourceComments: false
}).on('error', plugins.sass.logError))
.pipe(plugins.autoprefixer(config.autoprefixerOptions))
.pipe(plugins.if(config.production, plugins.minifyCss({processImport: false})))
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
.pipe(gulp.dest(dist))
.pipe(cb());
}
gulp.task('styles', function () {
compileScss([config.src.scss + 'style.scss', '!' + config.src.scss + 'guide.scss'], config.dist.css, function (gulp) {
return plugins.notify({message: 'Site Styles Compiled!', onLast: true});
});
});
//
// Guide Styles
//
gulp.task('guide', function (gulp) {
compileScss(config.src.scss + 'guide.scss', config.guideDist.css, function () {
return plugins.notify({message: 'Guide Styles Compiled!', onLast: true});
});
});
//
// Javascript
//
gulp.task('lint', function () {
gulp.src([config.src.js + '**/*.js', '!' + config.src.js + 'vendor/*.js'])
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('default'));
});
gulp.task('browserify', function () {
return browserify({ entries: [config.src.js + 'app.js']})
.transform(babelify, config.babelOptions)
.transform(stringify(['.html']))
.bundle()
.on('error', function(e){
console.log(e.message);
this.emit('end');
})
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
.pipe(plugins.if(config.production, plugins.uglify()))
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
.pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
.pipe(gulp.dest(config.dist.js))
.pipe(plugins.notify({message: 'Scripts Compiled!', onLast: true}));
});
gulp.task('js', function() {
return gulp.src(config.src.js + 'vendor/*.js')
.pipe(plugins.concat('vendor.js'))
.pipe(plugins.plumber({ errorHandler: function (err) { console.log(err); } }))
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.init()))
.pipe(plugins.if(config.production, plugins.uglify()))
.pipe(plugins.if(config.sourcemaps, plugins.sourcemaps.write('./')))
.pipe(gulp.dest(config.dist.js))
.pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})))
.pipe(plugins.notify({message: 'Vendor Scripts Compiled!', onLast: true}));
});
//
// HTML
//
gulp.task('html', function () {
gulp.src(dist + '/**/*.html')
.pipe(plugins.if(argv.livereload, plugins.livereload(), reload({stream: true})));
});
//
// Clean
//
gulp.task('clean', function() {
del([
// Build Files
'./public/assets/css/*.css',
'./public/assets/css/*.map',
'./public/assets/js/*.js',
'./public/assets/js/*.map',
// Guide
'./public/guide/*', // Needs to be run before the dir can be removed.
'./public/guide',
]);
});
//
// Browser Sync
//
gulp.task('browser-sync', function () {
browserSync({
notify: false,
ghostMode: {
clicks: true,
forms: true,
scroll: true
},
server: {
baseDir: dist
}
});
});
//
// Gulp Tasks
//
gulp.task('watch', function () {
plugins.watch(config.src.js + '**/*', function () {
gulp.start(['lint', 'js', 'browserify']);
});
plugins.watch(config.src.scss + '**/*.scss', function () {
gulp.start('styles', 'guide');
});
plugins.watch(dist + '/**/*.html', function () {
gulp.start('html');
});
});
gulp.task('dev', function () {
gulp.start('watch');
if (argv.livereload) {
plugins.livereload.listen();
} else {
gulp.start('browser-sync');
}
});
gulp.task('default', function () {
gulp.start('styles', 'guide', 'browserify', 'js');
});
| JavaScript | 0.000001 | @@ -2379,36 +2379,32 @@
.css, function (
-gulp
) %7B%0A retu
|
17b8982c7529892fdb2545a12e01bc5324a16543 | move title attributes to the div | src/components/structures/RightPanel.js | src/components/structures/RightPanel.js | /*
Copyright 2015 OpenMarket 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.
*/
'use strict';
var React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixClientPeg = require("matrix-react-sdk/lib/MatrixClientPeg");
module.exports = React.createClass({
displayName: 'RightPanel',
Phase : {
MemberList: 'MemberList',
FileList: 'FileList',
MemberInfo: 'MemberInfo',
},
componentWillMount: function() {
this.dispatcherRef = dis.register(this.onAction);
var cli = MatrixClientPeg.get();
cli.on("RoomState.members", this.onRoomStateMember);
},
componentWillUnmount: function() {
dis.unregister(this.dispatcherRef);
if (MatrixClientPeg.get()) {
MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember);
}
},
getInitialState: function() {
return {
phase : this.Phase.MemberList
}
},
onMemberListButtonClick: function() {
if (this.props.collapsed) {
this.setState({ phase: this.Phase.MemberList });
dis.dispatch({
action: 'show_right_panel',
});
}
else {
dis.dispatch({
action: 'hide_right_panel',
});
}
},
onRoomStateMember: function(ev, state, member) {
// redraw the badge on the membership list
if (this.state.phase == this.Phase.MemberList && member.roomId === this.props.roomId) {
this.forceUpdate();
}
else if (this.state.phase === this.Phase.MemberInfo && member.roomId === this.props.roomId &&
member.userId === this.state.member.userId) {
// refresh the member info (e.g. new power level)
this.forceUpdate();
}
},
onAction: function(payload) {
if (payload.action === "view_user") {
if (payload.member) {
this.setState({
phase: this.Phase.MemberInfo,
member: payload.member,
});
}
else {
this.setState({
phase: this.Phase.MemberList
});
}
}
if (payload.action === "view_room") {
if (this.state.phase === this.Phase.MemberInfo) {
this.setState({
phase: this.Phase.MemberList
});
}
}
},
render: function() {
var MemberList = sdk.getComponent('rooms.MemberList');
var buttonGroup;
var panel;
var filesHighlight;
var membersHighlight;
if (!this.props.collapsed) {
if (this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) {
membersHighlight = <div className="mx_RightPanel_headerButton_highlight"></div>;
}
else if (this.state.phase == this.Phase.FileList) {
filesHighlight = <div className="mx_RightPanel_headerButton_highlight"></div>;
}
}
var membersBadge;
if ((this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) && this.props.roomId) {
var cli = MatrixClientPeg.get();
var room = cli.getRoom(this.props.roomId);
if (room) {
membersBadge = <div className="mx_RightPanel_headerButton_badge">{ room.getJoinedMembers().length }</div>;
}
}
if (this.props.roomId) {
buttonGroup =
<div className="mx_RightPanel_headerButtonGroup">
<div className="mx_RightPanel_headerButton" onClick={ this.onMemberListButtonClick }>
<object type="image/svg+xml" data="img/members.svg" width="17" height="22" title="Members"/>
{ membersBadge }
{ membersHighlight }
</div>
<div className="mx_RightPanel_headerButton mx_RightPanel_filebutton">
<object type="image/svg+xml" data="img/files.svg" width="17" height="22" title="Files"/>
{ filesHighlight }
</div>
</div>;
if (!this.props.collapsed) {
if(this.state.phase == this.Phase.MemberList) {
panel = <MemberList roomId={this.props.roomId} key={this.props.roomId} />
}
else if(this.state.phase == this.Phase.MemberInfo) {
var MemberInfo = sdk.getComponent('rooms.MemberInfo');
panel = <MemberInfo roomId={this.props.roomId} member={this.state.member} key={this.props.roomId} />
}
}
}
var classes = "mx_RightPanel";
if (this.props.collapsed) {
classes += " collapsed";
}
return (
<aside className={classes}>
<div className="mx_RightPanel_header">
{ buttonGroup }
</div>
{ panel }
</aside>
);
}
});
| JavaScript | 0.000001 | @@ -4293,16 +4293,32 @@
rButton%22
+ title=%22Members%22
onClick
@@ -4454,32 +4454,16 @@
ght=%2222%22
- title=%22Members%22
/%3E%0A
@@ -4674,16 +4674,30 @@
ebutton%22
+ title=%22Files%22
%3E%0A
@@ -4790,30 +4790,16 @@
ght=%2222%22
- title=%22Files%22
/%3E%0A
|
666bc602abcbb5227e92fc580b8816fd2a676b59 | Update tasks | gulpfile.js | gulpfile.js | const gulp = require('gulp');
const babel = require('gulp-babel');
const rename = require("gulp-rename");
const eslint = require('gulp-eslint');
const uglify = require('gulp-uglifyjs');
const minify = require("gulp-babel-minify");
const browserSync = require('browser-sync');
// Live reload task
gulp.task('sync', function () {
browserSync.init({
server: "./example/"
});
// Watch for file changes
gulp.watch(['./src/*.js'], ['test', 'uglify', 'minify']);
gulp.watch(["./example/*.html", "./example/js/*.js"], browserSync.reload);
});
// Minify task using babel-minify (for es7)
gulp.task('minify', function () {
gulp.src(['./src/turtle.js'])
.pipe(minify({
mangle: {
keepClassName: true
}
}))
.pipe(rename('turtle.es7.min.js'))
.pipe(gulp.dest('./dist'))
});
// Minify task using uglifyjs (for es5)
gulp.task('uglify', function () {
gulp.src('./src/turtle.js')
.pipe(babel({
presets: ['env']
}))
.pipe(uglify())
.pipe(rename('turtle.min.js'))
.pipe(gulp.dest('./dist'))
.pipe(gulp.dest('./example/js'))
});
// Tests task
gulp.task('test', function () {
return gulp.src(['./src/*.js'])
.pipe(eslint({
"parser": "babel-eslint",
rules: {
"camelcase": 2,
"curly": 1,
"eqeqeq": 0,
"no-empty": 2,
"no-const-assign": 2,
"no-var": 2,
"prefer-const": 1
},
env: {
"es6": true
},
"parserOptions": {
"ecmaVersion": 7
}
}))
.pipe(eslint.format())
});
// Set the defaukt task as 'sync'
gulp.task('default', ['sync']);
| JavaScript | 0.000002 | @@ -449,19 +449,19 @@
js'%5D, %5B'
-tes
+lin
t', 'ugl
@@ -493,17 +493,17 @@
.watch(%5B
-%22
+'
./exampl
@@ -514,12 +514,12 @@
html
-%22, %22
+', '
./ex
@@ -531,17 +531,40 @@
/js/*.js
-%22
+', './example/css/*.css'
%5D, brows
@@ -692,32 +692,100 @@
c/turtle.js'%5D)%0D%0A
+ .pipe(rename('turtle.es7.js'))%0D%0A .pipe(gulp.dest('./dist'))%0D%0A
.pipe(minify
@@ -1081,24 +1081,56 @@
v'%5D%0D%0A%09%09%7D))%0D%0A
+ .pipe(gulp.dest('./dist'))%0D%0A
.pipe(ug
@@ -1258,13 +1258,12 @@
%0A//
-Tests
+Lint
tas
@@ -1280,11 +1280,11 @@
sk('
-tes
+lin
t',
|
501168acce303527f07d568f68aeb6a108f7ee83 | Modify browser selection statement | gulpfile.js | gulpfile.js | var os = require('os');
var gulp = require('gulp')
var open = require('gulp-open');
var Server = require('karma').Server;
/* Check the platform before selecting a browswer */
var browser = os.platform() === 'linux' ? 'google-chrome' : 'firefox'(
os.platform() === 'darwin' ? 'google chrome' : 'safari' (
os.platform() === 'win32' ? 'chrome' : 'iexplore'));
/* Run every unit test once, then quit */
gulp.task('unitTests', function(done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
/* Wait for unitTests to finish, then open the generated report */
gulp.task('openCodeCoverage', ['unitTests'], function(){
gulp.src('./reports/*/index.html')
.pipe(open({app: browser}));
});
/* Can run `gulp test` to just run unit tests */
gulp.task('test', ['unitTests']);
/* Can run `gulp test-coverage` run unit tests and then show the code coverage */
gulp.task('test-coverage', ['unitTests', 'openCodeCoverage']);
| JavaScript | 0.000001 | @@ -208,24 +208,25 @@
= 'linux' ?
+(
'google-chro
@@ -229,18 +229,18 @@
chrome'
-:
+%7C%7C
'firefo
@@ -241,16 +241,20 @@
firefox'
+) :
(%0A os.p
@@ -278,16 +278,17 @@
rwin' ?
+(
'google
@@ -299,18 +299,23 @@
me'
-:
+%7C%7C
'safar
+a
i'
+) :
(%0A
|
11d737977892a892c6913c8d4818d9a410cf9c4c | Refactor buffer constructor (#1912) | gulpfile.js | gulpfile.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var babel = require('gulp-babel');
var del = require('del');
var cleanCSS = require('gulp-clean-css');
var concatCSS = require('gulp-concat-css');
var derequire = require('gulp-derequire');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var gulpUtil = require('gulp-util');
var header = require('gulp-header');
var packageData = require('./package.json');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var StatsPlugin = require('stats-webpack-plugin');
var through = require('through2');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var webpackStream = require('webpack-stream');
var fbjsConfigurePreset = require('babel-preset-fbjs/configure');
var gulpCheckDependencies = require('fbjs-scripts/gulp/check-dependencies');
var moduleMap = require('./scripts/module-map');
var paths = {
dist: 'dist',
lib: 'lib',
src: [
'src/**/*.js',
'!src/**/__tests__/**/*.js',
'!src/**/__mocks__/**/*.js',
],
css: ['src/**/*.css'],
};
var babelOptsJS = {
presets: [
fbjsConfigurePreset({
stripDEV: true,
rewriteModules: {map: moduleMap},
}),
],
};
var babelOptsFlow = {
presets: [
fbjsConfigurePreset({
target: 'flow',
rewriteModules: {map: moduleMap},
}),
],
};
var COPYRIGHT_HEADER = `/**
* Draft v<%= version %>
*
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
`;
var buildDist = function(opts) {
var webpackOpts = {
externals: {
immutable: {
root: 'Immutable',
commonjs2: 'immutable',
commonjs: 'immutable',
amd: 'immutable',
},
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom',
},
},
output: {
filename: opts.output,
libraryTarget: 'umd',
library: 'Draft',
},
plugins: [
new webpackStream.webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(
opts.debug ? 'development' : 'production',
),
}),
new webpackStream.webpack.LoaderOptionsPlugin({
debug: opts.debug,
}),
new StatsPlugin(`../meta/bundle-size-stats/${opts.output}.json`, {
chunkModules: true,
}),
],
};
if (!opts.debug) {
webpackOpts.plugins.push(new UglifyJsPlugin());
}
return webpackStream(webpackOpts, null, function(err, stats) {
if (err) {
throw new gulpUtil.PluginError('webpack', err);
}
if (stats.compilation.errors.length) {
gulpUtil.log('webpack', '\n' + stats.toString({colors: true}));
}
});
};
gulp.task('clean', function() {
return del([paths.dist, paths.lib]);
});
gulp.task('modules', function() {
return gulp
.src(paths.src)
.pipe(babel(babelOptsJS))
.pipe(flatten())
.pipe(gulp.dest(paths.lib));
});
gulp.task('flow', function() {
return gulp
.src(paths.src)
.pipe(babel(babelOptsFlow))
.pipe(flatten())
.pipe(rename({extname: '.js.flow'}))
.pipe(gulp.dest(paths.lib));
});
gulp.task('css', function() {
return (gulp
.src(paths.css)
.pipe(
through.obj(function(file, encoding, callback) {
var contents = file.contents.toString();
var replaced = contents.replace(
// Regex based on MakeHasteCssModuleTransform: ignores comments,
// strings, and URLs
/\/\*.*?\*\/|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|url\([^)]*\)|(\.(?:public\/)?[\w-]*\/{1,2}[\w-]+)/g,
function(match, cls) {
if (cls) {
return cls.replace(/\//g, '-');
} else {
return match;
}
},
);
replaced = replaced.replace(
// MakeHasteCssVariablesTransform
/\bvar\(([\w-]+)\)/g,
function(match, name) {
var vars = {
'fig-secondary-text': '#9197a3',
'fig-light-20': '#bdc1c9',
};
if (vars[name]) {
return vars[name];
} else {
throw new Error('Unknown CSS variable ' + name);
}
},
);
file.contents = new Buffer(replaced);
callback(null, file);
}),
)
.pipe(concatCSS('Draft.css'))
// Avoid rewriting rules *just in case*, just compress
.pipe(cleanCSS({advanced: false}))
.pipe(header(COPYRIGHT_HEADER, {version: packageData.version}))
.pipe(gulp.dest(paths.dist)) );
});
gulp.task('dist', ['modules', 'css'], function() {
var opts = {
debug: true,
output: 'Draft.js',
};
return gulp
.src('./lib/Draft.js')
.pipe(buildDist(opts))
.pipe(derequire())
.pipe(
gulpif('*.js', header(COPYRIGHT_HEADER, {version: packageData.version})),
)
.pipe(gulp.dest(paths.dist));
});
gulp.task('dist:min', ['modules'], function() {
var opts = {
debug: false,
output: 'Draft.min.js',
};
return gulp
.src('./lib/Draft.js')
.pipe(buildDist(opts))
.pipe(
gulpif('*.js', header(COPYRIGHT_HEADER, {version: packageData.version})),
)
.pipe(gulp.dest(paths.dist));
});
gulp.task('check-dependencies', function() {
return gulp.src('package.json').pipe(gulpCheckDependencies());
});
gulp.task('watch', function() {
gulp.watch(paths.src, ['modules']);
});
gulp.task('dev', function() {
gulp.watch(paths.src, ['modules', 'dist']);
});
gulp.task('default', function(cb) {
runSequence(
'check-dependencies',
'clean',
['modules', 'flow'],
['dist', 'dist:min'],
cb,
);
});
| JavaScript | 0.000011 | @@ -4950,19 +4950,20 @@
ts =
- new
Buffer
+.from
(rep
|
4f161aa5f8f2359e11e1edbefdf7aa998537ed7c | Fix source path when running generator via bin script | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
concat = require('gulp-concat'),
livereload = require('gulp-livereload'),
neat = require('node-neat'),
please = require('gulp-pleeease'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
util = require('gulp-util'),
styleguide = require('./lib/styleguide'),
markdownPath = util.env.markdown ? util.env.markdown.replace(/\/$/, '') : 'demo/source/overview.md',
outputPath = util.env.output ? util.env.output.replace(/\/$/, '') : 'demo/output',
sourcePath = util.env.source ? util.env.source.replace(/\/$/, '') : 'demo/source';
/* Tasks for development */
gulp.task('serve', function() {
var app = require('./lib/server').app,
server = require('./lib/server').server;
serverModule = require('./lib/server')(sourcePath, outputPath);
app = serverModule.app;
server = serverModule.server;
app.set('port', util.env.port || 3000);
server = server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
});
gulp.task('styleguide', ['build'], function() {
return gulp.src(['demo/source/**/*.scss'])
.pipe(styleguide({
dest: outputPath,
markdownPath: markdownPath,
sass: {
loadPath: neat.includePaths
}
}));
});
gulp.task('js:app', function() {
return gulp.src(['lib/app/js/**/*.js', '!lib/app/js/vendor/**/*.js'])
.pipe(plumber())
.pipe(concat('app.js'))
.pipe(gulp.dest(outputPath + '/js'));
});
gulp.task('js:vendor', function() {
return gulp.src('lib/app/js/vendor/**/*.js')
.pipe(plumber())
.pipe(concat('vendor.js'))
.pipe(gulp.dest(outputPath + '/js'));
});
gulp.task('sass', function() {
return gulp.src('lib/app/sass/**/*.scss')
.pipe(plumber())
.pipe(sass({
// Include bourbon & neat
includePaths: neat.includePaths
}))
.pipe(sourcemaps.init())
.pipe(please({
minifier: false
}))
.pipe(gulp.dest(outputPath + '/css'));
});
gulp.task('html', function() {
return gulp.src('lib/app/**/*.html')
.pipe(gulp.dest(outputPath + '/'));
});
gulp.task('assets', function() {
return gulp.src('lib/app/assets/**')
.pipe(gulp.dest(outputPath + '/assets'));
});
gulp.task('watch', ['build', 'styleguide', 'serve'], function() {
var app, serverModule, server;
// TODO: configure livereload
// livereload.listen();
gulp.watch('lib/app/sass/**/*.scss', ['sass']);
gulp.watch(['lib/app/js/**/*.js', '!lib/app/js/vendor/**/*.js'], ['js:app']);
gulp.watch('lib/app/js/vendor/**/*.js', ['js:vendor']);
gulp.watch('lib/app/**/*.html', ['html']);
gulp.watch(sourcePath + '/**', ['styleguide']);
});
gulp.task('build', ['sass', 'js:app', 'js:vendor', 'html', 'assets']);
| JavaScript | 0.000001 | @@ -1177,28 +1177,30 @@
lp.src(%5B
-'demo/
source
+Path + '
/**/*.sc
|
44d8aef2f4fd0346f8b5c1b898be1a1968f06350 | Enhance handleError in gulpfile. | gulpfile.js | gulpfile.js | 'use strict';
var browserify = require('browserify'),
gulp = require('gulp'),
gutil = require('gulp-util'),
livereload = require('gulp-livereload'),
notify = require('gulp-notify'),
rename = require('gulp-rename'),
rimraf = require('gulp-rimraf'),
source = require('vinyl-source-stream'),
uglify = require('gulp-uglify'),
watchify = require('watchify');
var staticDir = './openfisca_web_ui/static';
var jsDir = staticDir + '/js';
var indexJsFile = jsDir + '/index.js';
var distDir = staticDir + '/dist';
var vendorJsFiles = [
'./node_modules/jquery/dist/jquery.js',
'./node_modules/lazy.js/lazy.js',
];
var vendorDir = distDir + '/vendor',
vendorBootstrapDir = vendorDir + '/bootstrap';
function buildScripts(entryFile, options) {
var debug = options && options.debug,
watch = options && options.watch;
var bundlerConstructor = options && watch ? watchify : browserify;
var bundler = bundlerConstructor(entryFile);
// bundler.transform(reactify, {es6: true});
function rebundle() {
var stream = bundler.bundle({debug: debug});
if (watch) {
stream = stream.on('error', handleError);
}
stream = stream
.pipe(source('bundle.js'))
.pipe(gulp.dest(distDir));
return stream;
}
bundler.on('update', function() {
gutil.log('Rebundle...');
rebundle()
.on('end', function() { gutil.log('Rebundle done.'); });
});
return rebundle();
}
function handleError() {
/* jshint validthis: true */
var args = Array.prototype.slice.call(arguments);
var filePathRegex = /Error: Parsing file (.+): Line \d+/;
var match = filePathRegex.exec(args[0]);
var filePath = match[1];
notify.onError({
message: '<%= error.message %> <a href="file://<%= options.filePath %>">open</a>',
templateOptions: {filePath: filePath},
title: 'Compile Error',
}).apply(this, args);
this.emit('end'); // Keep gulp from hanging on this task
}
function startLiveReload() {
var port = 35731;
var liveReloadServer = livereload(port);
var reloadPage = function(event) {
gutil.log('Reload browser page.')
liveReloadServer.changed(event.path);
};
return gulp.watch([distDir + '/**/*'], reloadPage);
}
gulp.task('bundle', function() {
return buildScripts(indexJsFile);
});
gulp.task('bundle-dev', function() {
return buildScripts(indexJsFile, {debug: true});
});
gulp.task('clean', function() {
return gulp.src(distDir, {read: false})
.pipe(rimraf());
});
gulp.task('default', ['dev']);
gulp.task('dev', ['bundle-dev', 'vendor']);
gulp.task('prod', ['bundle', 'uglify', 'vendor']);
gulp.task('uglify', ['bundle'], function() {
gulp.src(distDir + '/bundle.js')
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(distDir));
});
gulp.task('vendor', ['vendor-bootstrap', 'vendor-js']);
gulp.task('vendor-bootstrap', function() {
return gulp.src('./node_modules/bootstrap/dist/**')
.pipe(gulp.dest(vendorBootstrapDir));
});
gulp.task('vendor-js', function() {
return gulp.src(vendorJsFiles)
.pipe(gulp.dest(vendorDir));
});
gulp.task('watch', ['vendor'], function() {
startLiveReload();
buildScripts(indexJsFile, {debug: true, watch: true});
});
| JavaScript | 0 | @@ -1509,16 +1509,287 @@
ments);%0A
+ gutil.log(args);%0A var errorData = %7B%0A message: '%3C%25= error.message %25%3E',%0A title: 'Compile Error',%0A %7D;%0A var filePath;%0A if (args%5B0%5D && args%5B0%5D.fileName) %7B%0A // React JSX source files.%0A filePath = args%5B0%5D.fileName;%0A %7D else %7B%0A // Vanilla JS source files.%0A
var fi
@@ -1840,16 +1840,18 @@
e %5Cd+/;%0A
+
var ma
@@ -1883,27 +1883,44 @@
args%5B0%5D);%0A
-var
+ if (match) %7B%0A
filePath =
@@ -1935,48 +1935,75 @@
;%0A
-notify.onError(%7B%0A message: '%3C%25=
+ %7D%0A %7D%0A if (filePath) %7B%0A console.log(errorData);%0A
error
+Data
.mes
@@ -2007,18 +2007,20 @@
message
-%25%3E
++= '
%3Ca href
@@ -2062,22 +2062,60 @@
pen%3C/a%3E'
-,
+;
%0A
+console.log(errorData);%0A errorData.
template
@@ -2121,17 +2121,18 @@
eOptions
-:
+ =
%7BfilePa
@@ -2148,41 +2148,40 @@
ath%7D
-,%0A title: 'Compile Error',%0A %7D
+;%0A %7D%0A notify.onError(errorData
).ap
|
21cd3d0bd7d1df8c74a5fcaa6c82589e542de72b | fix for front and backend app sass files | gulpfile.js | gulpfile.js | var elixir = require('laravel-elixir');
require('laravel-elixir-eslint');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var paths = {
'bower': './vendor/bower_components/',
'jquery': './vendor/bower_components/jquery/',
'bootstrap': './vendor/bower_components/bootstrap-sass-official/assets/',
'fontawesome': './vendor/bower_components/fontawesome/',
'dropzone': './vendor/bower_components/dropzone/dist/',
'jasny': './vendor/bower_components/jasny-bootstrap/dist/',
'swipebox': './vendor/bower_components/swipebox/src/',
'sortable': './vendor/bower_components/Sortable/'
}
elixir(function(mix) {
mix.sass('**/*', 'public/css/', {includePaths: [paths.bootstrap + 'stylesheets', paths.fontawesome + 'scss']})
.copy(paths.bootstrap + 'fonts/bootstrap/**', 'public/fonts/bootstrap')
.copy(paths.fontawesome + 'fonts/**', 'public/fonts/fontawesome')
.copy(paths.swipebox + 'img/**', 'public/images')
.scripts([
paths.jquery + "dist/jquery.js",
paths.bootstrap + "javascripts/bootstrap.js",
paths.bower + "select2/dist/js/select2.js",
paths.bower + "fancybox/source/jquery.fancybox.js",
paths.bower + "moment/moment.js",
paths.bower + "moment-range/lib/moment-range.js",
paths.bower + "jcrop/js/jquery.Jcrop.js",
paths.bower + "slick-carousel/slick/slick.js",
paths.dropzone + "dropzone.js",
paths.jasny + "js/jasny-bootstrap.js",
paths.sortable + "Sortable.js",
paths.sortable + "jquery.binding.js",
paths.swipebox + "js/jquery.swipebox.js",
], 'public/js/vendor.js', './')
.eslint(['resources/assets/js/*.js'])
.browserify('app.js', './public/js/app.js')
.version([
'css/app.css',
'css/admin/app.css',
'js/vendor.js',
'js/app.js',
])
});
| JavaScript | 0 | @@ -977,12 +977,143 @@
ss('
-**/*
+app.scss', 'public/css/app.css', %7BincludePaths: %5Bpaths.bootstrap + 'stylesheets', paths.fontawesome + 'scss'%5D%7D)%0A%09%09.sass('admin/app.scss
', '
@@ -1123,16 +1123,29 @@
lic/css/
+admin/app.css
', %7Bincl
|
09d1e4f31de60ee49057d784d2c55787d671b807 | Add watch task | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer');
var config = {
paths: {
boneless: {
src: './scss/boneless.scss',
dest: './lib'
}
},
plugins: {
sass: {
outputStyle: 'nested',
precision: 10,
noCache: true,
},
autoprefixer: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
cascade: false
}
}
};
gulp.task('build', function () {
return gulp.src(config.paths.boneless.src)
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: config.plugins.sass.outputStyle,
precision: config.plugins.sass.precision,
noCache: config.plugins.sass.noCache
}))
.pipe(autoprefixer({
browsers: config.plugins.autoprefixer.browsers,
cascade: config.plugins.autoprefixer.cascade
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.paths.boneless.dest));
});
| JavaScript | 0.999877 | @@ -239,16 +239,52 @@
'./lib'
+,%0A watch: './scss/**/**/*.scss'
%0A %7D%0A
@@ -1020,8 +1020,101 @@
));%0A%7D);%0A
+%0Agulp.task('watch', function() %7B%0A gulp.watch(config.paths.boneless.watch, %5B'build'%5D);%0A%7D);%0A
|
82cc4711493f302b0be86c5e0fc5280af0a9ef4d | Fix the focus jump in post. | src/layouts/Post/index.js | src/layouts/Post/index.js | import React, { Component, PropTypes } from 'react';
import ReactDisqusComments from 'react-disqus-comments';
import Page from '../Page';
import styles from './index.scss';
const setOverflow = (overflow) => {
const html = document.querySelector('html');
const body = document.body;
html.style.overflow = overflow;
body.style.overflow = overflow;
}
class Post extends Component {
static propTypes = {
head: PropTypes.object.isRequired,
};
componentDidMount() {
this.main.focus();
setOverflow('auto');
}
componentWillUnmount() {
setOverflow('hidden');
}
render() {
const { props } = this;
// it's up to you to choose what to do with this layout ;)
const pageDate = props.head.date ? new Date(props.head.date) : null;
const author = props.head.author;
return (
<main className={styles.main} tabIndex={-1} ref={e => this.main = e}>
<article className={styles.article}>
<Page
{...props}
header={
<header>
<span>{author}, </span>
<time key={pageDate.toISOString()}>
{ pageDate.toDateString() }
</time>
</header>
}
/>
<ReactDisqusComments
shortname='makersden-io'
title={props.head.title}
identifier={props.head.title.replace(/\s/g, '') + pageDate}
/>
</article>
</main>
);
}
}
export default Post;
| JavaScript | 0 | @@ -481,31 +481,8 @@
) %7B%0A
- this.main.focus();%0A
|
67abb0384f3f88cbabc11897c556406ed26399e9 | fix watch images | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var del = require('del');
var path = require('path');
// Load plugins
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var watchify = require('watchify');
var source = require('vinyl-source-stream'),
sourceFile = './app/scripts/app.js',
destFolder = './dist/scripts',
destFileName = 'app.js';
// Styles
gulp.task('styles', function () {
return gulp.src('app/styles/main.scss')
.pipe($.rubySass({
style: 'expanded',
precision: 10,
loadPath: ['app/bower_components']
}))
.pipe($.autoprefixer('last 1 version'))
.pipe(gulp.dest('dist/styles'))
.pipe($.size());
});
// Scripts
gulp.task('scripts', function () {
var bundler =browserify({
entries: [sourceFile],
insertGlobals: true,
cache: {},
packageCache: {},
fullPaths: true
});
return bundler.bundle()
// log errors if they happen
.on('error', $.util.log.bind($.util, 'Browserify Error'))
.pipe(source(destFileName))
.pipe(gulp.dest(destFolder));
});
// Scripts
gulp.task('scripts_debug', function () {
var bundler = watchify(browserify({
entries: [sourceFile],
insertGlobals: true,
cache: {},
packageCache: {},
fullPaths: true,
debug: true
}));
function rebundle() {
return bundler.bundle()
// log errors if they happen
.on('error', $.util.log.bind($.util, 'Browserify Error'))
.pipe(source(destFileName))
.pipe(gulp.dest(destFolder));
}
bundler.on('update', rebundle);
return rebundle();
});
gulp.task('jade', function () {
return gulp.src('app/template/*.jade')
.pipe($.jade({ pretty: true }))
.pipe(gulp.dest('dist'));
});
// HTML
gulp.task('html', function () {
return gulp.src('app/*.html')
.pipe($.useref())
.pipe(gulp.dest('dist'))
.pipe($.size());
});
// Images
gulp.task('images', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
.pipe($.size());
});
gulp.task('jest', function () {
var nodeModules = path.resolve('./node_modules');
return gulp.src('app/scripts/**/__tests__')
.pipe($.jest({
scriptPreprocessor: nodeModules + '/gulp-jest/preprocessor.js',
unmockedModulePathPatterns: [nodeModules + '/react']
}));
});
// Clean
gulp.task('clean', function (cb) {
cb(del.sync(['dist/styles', 'dist/scripts', 'dist/images']));
});
// Bundle
gulp.task('bundle', ['styles', 'scripts', 'bower', 'worker'], function(){
return gulp.src('./app/*.html')
.pipe($.useref.assets())
.pipe($.useref.restore())
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
// Bundle
gulp.task('bundle_debug', ['styles', 'scripts_debug', 'bower', 'worker'], function(){
return gulp.src('./app/*.html')
.pipe($.useref.assets())
.pipe($.useref.restore())
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
// Webserver
gulp.task('serve', function () {
gulp.src('./dist')
.pipe($.webserver({
port: 9000
}));
});
// Bower helper
gulp.task('bower', function() {
gulp.src('app/bower_components/**/*.js', {base: 'app/bower_components'})
.pipe(gulp.dest('dist/bower_components/'));
});
gulp.task('worker', function() {
gulp.src('app/scripts/worker/**/*.js', {base: 'app/scripts/worker'})
.pipe(gulp.dest('dist/worker'));
});
gulp.task('json', function() {
gulp.src('app/scripts/json/**/*.json', {base: 'app/scripts'})
.pipe(gulp.dest('dist/scripts/'));
});
// Robots.txt and favicon.ico
gulp.task('extras', function () {
return gulp.src(['app/*.txt', 'app/*.ico'])
.pipe(gulp.dest('dist/'))
.pipe($.size());
});
// Watch
gulp.task('watch', ['html', 'bundle_debug', 'serve'], function () {
// Watch .json files
gulp.watch('app/scripts/**/*.json', ['json']);
// Watch .html files
gulp.watch('app/*.html', ['html']);
// Watch .scss files
gulp.watch('app/styles/**/*.scss', ['styles']);
// Watch .jade files
gulp.watch('app/template/**/*.jade', ['jade', 'html']);
// Watch image files
gulp.watch('app/images/**/*', ['images']);
});
// Build
gulp.task('build', ['html', 'bundle', 'images', 'extras']);
// Default task
gulp.task('default', ['clean', 'build', 'jest' ]);
| JavaScript | 0 | @@ -4078,16 +4078,26 @@
_debug',
+ 'images',
'serve'
|
376a75a4ea96b32275fe46ee07eb864d286fcfcb | Clean task | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var buffer = require('vinyl-buffer');
var del = require('del');
var merge = require('merge-stream');
var path = require('path');
var runSequence = require('run-sequence');
const SRC = './src';
const DEST = './dist';
const PACKAGES = './modules';
function sass()
{
var sass = gulp.src(SRC + '/assets/scss/totem.scss')
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sassGlob({
ignorePaths: [
'**/__*.scss'
]
}))
.pipe(plugins.sass().on('error', plugins.sass.logError))
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest(DEST + '/assets/css'));
return sass.pipe(plugins.connect.reload());
}
function spritesmith()
{
var spritesmith = gulp.src(SRC + '/assets/img/layout/sprite/**.png')
.pipe(plugins.plumber())
.pipe(plugins.spritesmith({
padding: 4,
imgName: 'sprite.png',
cssName: 'totem.sprite.css',
cssTemplate: SRC + '/assets/img/layout/sprite/config.handlebars',
cssHandlebarsHelpers : {
outputSprite : function(image)
{
return '/assets/img/layout/sprite.png';
},
divideRetina : function(value) {
return parseInt(value) / 2;
}
}
}));
var img = spritesmith.img
.pipe(buffer())
.pipe(gulp.dest(DEST + '/assets/img/layout/'));
var css = spritesmith.css
.pipe(gulp.dest(DEST + '/assets/css/'));
return merge(img, css).pipe(plugins.connect.reload());
}
gulp.task('sass', function() {
return sass();
});
gulp.task('spritesmith', function() {
return spritesmith();
});
gulp.task('stylesheets', function(callback) {
runSequence(
'sass',
'spritesmith',
callback
);
});
gulp.task('default', function(callback) {
return;
}); | JavaScript | 0.999983 | @@ -315,16 +315,61 @@
odules';
+%0Afunction clean()%0A%7B%0A return del(%5BDEST%5D);%0A%7D
%0A%0Afuncti
|
8ead1419f9676c797a91d959b5c1a22deb761cb7 | update makdoc | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var Handlebars = require('handlebars');
var $ = require('gulp-load-plugins')();
var seq = require('run-sequence');
var through = require('through2');
/*************************************************************************
* initialize makdoc
*/
var makdoc = require('gulp-makdoc'); // should init before local task
makdoc.init(gulp, Handlebars);
/*************************************************************************
* tasks
*/
gulp.task('deploy', ['makdoc'], function () {
var deploy = require('gulp-gh-pages');
var path = require('path');
return gulp.src([path.join($.makdoc.vars.DIST(),'**/*'),
'!**/*.map'])
.pipe(deploy({
remoteUrl: 'git@github.com:pismute/pismute.github.io.git',
cacheDir: '.gh-pages',
branch:'master'
}));
});
// Bower helper
gulp.task('bower', function() {
var base = 'app/bower_components/';
var files = [
'requirejs/require.js',
'bootstrap/dist/**/*.min.{js,css}',
'bootstrap-material-design/dist/**/material.min.{js,css}',
'bootstrap-material-design/dist/**/ripples.min.{js,css}',
'{d3,jquery,lodash,dashbars}/**/*.min.js',
'moment/min/{locales,moment}.min.js',
'handlebars/handlebars/handlebars.min.js'
];
files = files.map(function(file){
return 'app/bower_components/' + file;
});
return gulp.src(files, {base:base})
.pipe(gulp.dest('dist/bower_components/'));
});
gulp.task('makdoc:init:after', function(done){
var returns = function(v) {
return function(){
return v;
};
};
$.makdoc.vars.BASE_URL = returns('http://pismute.github.io/'),
done();
});
gulp.task('makdoc:done:after', function(done){
seq(['bower',
'lint'],
done);
});
gulp.task('lint', function(){
return gulp.src(['gulpfiles.js', './gulp/**/*.js'])
.pipe($.cached('lint'))
.pipe($.jshint('.jshintrc'))
.pipe($.jshint.reporter('default'));
});
/*************************************************************************
* template data
*/
makdoc.templateData({
package:require('./package.json')
});
/*************************************************************************
* override:highlight
*/
var _alias = {
'js-run': 'js',
'js-run-d3': 'js'
};
makdoc.util.highlight = function() {
var _highlight = makdoc.util.highlight_pygment();
return function(code, lang, done){
return _highlight(code, _alias[lang] || lang, done);
}
}
/*************************************************************************
* helpers
*/
var _ = require('lodash');
var arrayfy = function(value) {
//value is string or array
return !value? []:
Array.isArray(value)? value:value.split(',');
}
Handlebars.registerHelper('_keyword-links', function(tags) {
return _(arrayfy(tags))
.map(function(it){
it = it.trim();
return '<a href="/site/keyword-map.html#' +
it.toLowerCase() + '" class="keyword">' +
it + '</a>';
})
.value()
.join(' ');
});
Handlebars.registerHelper('_group-doc', function(models){
return models.reduce(function(g, m){
var keywords = m['keywords'];
if( keywords ) {
var keywords = _.isString(keywords)? keywords.split(','): keywords;
keywords.forEach(function(keyword){
if( (g[keyword]) ) {
g[keyword].push(m);
}else{
g[keyword] = [m];
}
});
}
return g;
}, {});
});
Handlebars.registerHelper('_summary', function(html) {
if(html){
var matched = (/<h[123456].*?>.*<\/h[123456].*?>([\s\S*]*?)<h[123456].*?>.*<\/h[123456].*?>/i).exec(html)
if( matched ) {
return matched[1];
}
}
return "empty-summary";
});
| JavaScript | 0.000001 | @@ -322,16 +322,34 @@
makdoc')
+(gulp, Handlebars)
; // sho
@@ -378,39 +378,8 @@
task
-%0Amakdoc.init(gulp, Handlebars);
%0A%0A/*
@@ -618,18 +618,16 @@
th.join(
-$.
makdoc.v
@@ -1666,18 +1666,16 @@
%7D;%0A%0A
-$.
makdoc.v
|
74cedb07c54949c9d2a1dccaae236bcaf86d842f | Update gulpfile to use gulp v4.0 | gulpfile.js | gulpfile.js |
var path = require('path')
var gulp = require('gulp')
var sourcemaps = require('gulp-sourcemaps')
var babel = require('gulp-babel')
var paths = {
es6: ['**/*.js', '!gulpfile.js', '!build/**/*.*', '!node_modules/**/*.*'],
es5: 'build',
// must be absolute or relative to source map
sourceRoot: path.join(__dirname)
}
gulp.task('babel', function () {
return gulp.src(paths.es6)
.pipe(sourcemaps.init())
.pipe(babel({
optional: [
'es7.asyncFunctions',
'es7.exportExtensions'
]
}))
.pipe(sourcemaps.write('.', {sourceRoot: paths.sourceRoot}))
.pipe(gulp.dest(paths.es5))
})
gulp.task('watch', function () {
gulp.watch(paths.es6, ['babel'])
})
gulp.task('default', ['watch'])
| JavaScript | 0 | @@ -321,16 +321,17 @@
ame)%0A%7D%0A%0A
+%0A
gulp.tas
@@ -441,88 +441,65 @@
-optional: %5B%0A 'es7.asyncFunctions',%0A 'es7.exportExtensions'%0A %5D
+presets: %5B'es2015', 'stage-0'%5D,%0A retainLines: 'true'
%0A
@@ -600,24 +600,66 @@
s.es5))%0A%7D)%0A%0A
+gulp.task('build', gulp.series('babel'))%0A%0A
gulp.task('w
@@ -707,17 +707,28 @@
s6,
-%5B
+gulp.series(
'babel'
-%5D
+)
)%0A%7D)
@@ -754,15 +754,35 @@
t',
-%5B
+gulp.series('build',
'watch'
-%5D
+)
)%0A
|
f8dec387de66e162fe04abe2738daffa4bd2f173 | fix handling of empty values with ~= | src/lib/dependshandler.js | src/lib/dependshandler.js | define([
"jquery",
"./depends_parse"
], function($, parser) {
function DependsHandler($el, expression) {
var $context = $el.closest("form");
if (!$context.length)
$context=$(document);
this.$el=$el;
this.$context=$context;
this.ast=parser.parse(expression); // TODO: handle parse exceptions here
}
DependsHandler.prototype = {
_findInputs: function(name) {
var $input = this.$context.find(":input[name='"+name+"']");
if (!$input.length)
$input=$("#"+name);
return $input;
},
_getValue: function(name) {
var $input = this._findInputs(name);
if (!$input.length)
return null;
if ($input.attr("type")==="radio" || $input.attr("type")==="checkbox")
return $input.filter(":checked").val() || null;
else
return $input.val();
},
getAllInputs: function() {
var todo = [this.ast],
$inputs = $(),
node;
while (todo.length) {
node=todo.shift();
if (node.input)
$inputs=$inputs.add(this._findInputs(node.input));
if (node.children && node.children.length)
todo.push.apply(todo, node.children);
}
return $inputs;
},
_evaluate: function(node) {
var value = node.input ? this._getValue(node.input) : null,
i;
switch (node.type) {
case "NOT":
return !this._evaluate(node.children[0]);
case "AND":
for (i=0; i<node.children.length; i++)
if (!this._evaluate(node.children[i]))
return false;
return true;
case "OR":
for (i=0; i<node.children.length; i++)
if (this._evaluate(node.children[i]))
return true;
return false;
case "comparison":
switch (node.operator) {
case "=":
return node.value==value;
case "!=":
return node.value!=value;
case "<=":
return value<=node.value;
case "<":
return value<node.value;
case ">":
return value>node.value;
case ">=":
return value>=node.value;
case "~=":
return value.indexOf(node.value)!=-1;
}
break;
case "truthy":
return !!value;
}
},
evaluate: function() {
return this._evaluate(this.ast);
}
};
return DependsHandler;
});
| JavaScript | 0.000001 | @@ -2785,24 +2785,116 @@
case %22~=%22:%0A
+ if (value===null)%0A return false;%0A
|
94a06b66bd0da2f290276002eec2e61d5bff3b65 | fix watch process | gulpfile.js | gulpfile.js | var browserify = require('browserify');
var del = require('del');
var debug = require('gulp-debug');
var minimist = require('minimist');
var gulp = require('gulp');
var coverage = require('gulp-coverage');
var jshint = require('gulp-jshint');
var jsxhint = require('gulp-jsxhint');
var map = require('map-stream');
var mocha = require('gulp-spawn-mocha');
var nodemon = require('gulp-nodemon');
var stylish = require('jshint-stylish');
var reactify = require('reactify');
var react = require('gulp-react');
var runSequence = require('run-sequence');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var watch = require('gulp-watch');
var watchify = require('watchify');
var options = minimist(process.argv.slice(2));
/**
* Runs Mocha tests for the server
*/
gulp.task('test', function () {
var sources = ['spec/config.js', 'app/**/*.spec.js'];
options.reporter = 'min';
options.istanbul = true;
options.debugBrk = options.debug ? 'debug' : undefined;
return gulp
.src(sources)
.pipe(mocha(options));
});
/**
* Lints the server
*/
gulp.task('lint-server', function () {
var sources = ['app/**/*.js', '!app/public/**/*.js'];
return gulp
.src(sources)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
/**
* Lints the client
*/
gulp.task('lint-client', function (done) {
return gulp
.src(['app/public/**/*.js'])
.pipe(react())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish', { verbose: true }))
.pipe(jshint.reporter('fail'))
.pipe(done);
});
/**
* Cleans the dist directory
*/
gulp.task('clean', function (callback) {
return del(['./dist/**/*'], callback);
});
gulp.task('browserify', function () {
var bundler = browserify({
debug: true,
transform: [ reactify ],
entries: [ './app/public/app.js' ],
cache: {},
packageCache: {}
});
bundler.plugin('minifyify', { map: 'app.js.map', output: __dirname + '/dist/public/app.js.map' });
return bundler
.bundle()
.pipe(source('public/app.js'))
.pipe(gulp.dest('./dist/'));
});
/**
* Compiles the client javascript
*/
gulp.task('watchify', function () {
var bundler = browserify({
debug: true,
transform: [ reactify ],
entries: [ './app/public/app.js' ],
cache: {},
packageCache: {}
});
bundler.plugin('minifyify', { map: 'app.js.map', output: __dirname + '/dist/public/app.js.map' });
var watcher = watchify(bundler);
return watcher
.on('error', function (err) {
console.log(err.message);
})
.on('update', function () {
console.log('updating bundle');
watcher.bundle()
.pipe(source('public/app.js'))
.pipe(gulp.dest('./dist/'));
console.log('updated bundle!');
})
.bundle()
.pipe(source('public/app.js'))
.pipe(gulp.dest('./dist/'));
});
/**
* Copies the server component to the dist directory
*/
gulp.task('copy-server', function () {
return gulp
.src(['./app/**/*', '!./app/public/**/*'])
.pipe(gulp.dest('./dist/'));
});
/**
* Copies the client component to the dist directory
*/
gulp.task('copy-client', function () {
return gulp
.src(['./app/public/index.html'])
.pipe(gulp.dest('./dist/public/'));
});
/**
* Compiles the client SASS
*/
gulp.task('sass', function () {
return gulp
.src(['./app/public/main.scss'])
.pipe(sass({
outputStyle: 'compress',
errLogToConsole: true
}))
.pipe(gulp.dest('./dist/public/'));
});
/**
* Copies client assets
*/
gulp.task('assets', function () {
return gulp
.src(['./app/public/assets/**/*'])
.pipe(gulp.dest('./dist/public/assets/'));
});
/**
* Builds the application
*/
gulp.task('build', function (done) {
return runSequence('clean', 'copy-server', 'browserify', 'copy-client', 'sass', 'assets', done);
});
gulp.task('watch', function (done) {
return runSequence('clean', 'copy-server', 'watchify', 'copy-client', 'sass', 'assets', done);
});
/**
* Automatic server reload
*/
gulp.task('nodemon', ['watch'], function (done) {
var called = false;
return nodemon({
script: './dist/index.js',
ext: 'js',
ignore: ['dist/**/*', 'app/public/**/*', 'coverage/**/*', 'doc/**/*', 'node_modules/**/*', 'spec/**/*']
}).on('change', ['lint-server', 'copy-server'])
.on('start', ['watch']);
});
/**
* Development task
*/
gulp.task('watch', function () {
gulp.watch(['app/public/index.html'], ['copy-client']);
gulp.watch(['app/public/**/*.scss'], ['sass']);
});
/**
* Default
*/
gulp.task('default', ['nodemon']); | JavaScript | 0.000001 | @@ -4550,16 +4550,23 @@
%5B'watch
+-assets
'%5D);%0A%7D);
@@ -4603,32 +4603,39 @@
gulp.task('watch
+-assets
', function () %7B
|
3760b58686f1e30e16691630381f4d4a868c62e2 | fix build scripts | gulpfile.js | gulpfile.js | const gulp = require('gulp');
const shell = cmd => require('child_process').execSync(cmd, {stdio:[0,1,2]});
const del = require('del');
const extend = require('extend');
const seq = require('run-sequence');
const $ = require('gulp-load-plugins')({
//pattern: ['gulp-*', 'gulp.*'],
//replaceString: /\bgulp[\-.]/
});
const Server = require('karma').Server;
const pkg = require('./package.json');
const karmaconfig = require('./karma.conf.js');
const config = {
ts: {
options: extend(require('./tsconfig.json').compilerOptions, {
typescript: require('typescript')
}),
source: {
src: [
'typings/*.d.ts',
'*.ts',
'src/**/*.ts'
],
dest: 'dist/'
},
dist: {
src: [
'typings/*.d.ts',
'*.ts',
'src/**/*.d.ts',
'src/**/+([!.]).ts'
],
dest: 'dist/'
},
test: {
src: [
'typings/*.d.ts',
'test/**/*.ts'
],
dest: 'test/'
}
},
banner: [
`/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2016, ${pkg.author} | ${pkg.license.type} License (${pkg.license.url}) */`,
''
].join('\n'),
exporter:
`define = typeof define === 'function' && define.amd
? define
: (function () {
'use strict';
var name = '${pkg.name}',
workspace = {};
return function define(m, rs, f) {
return !f
? void define(name, m, rs)
: void f.apply(this, rs.map(function (r) {
switch (r) {
case 'require': {
return typeof require === 'function' ? require : void 0;
}
case 'exports': {
return m.indexOf('/') === -1
? workspace[m] = typeof exports === 'undefined' ? self[m] = self[m] || {} : exports
: workspace[m] = workspace.hasOwnProperty(m) ? workspace[m] : {};
}
default: {
return r.slice(-2) === '.d' && {}
|| workspace.hasOwnProperty(r) && workspace[r]
|| typeof require === 'function' && require(r)
|| self[r];
}
}
}));
};
})();
`,
clean: {
src: 'src/**/*.js',
dist: 'dist',
test: 'test/**/*.js',
bench: 'benchmark/**/*.js',
cov: 'coverage'
},
karma: {
watch: extend({}, require('./karma.conf.js'), {
browsers: ['Chrome'],
preprocessors: {
'dist/*.js': ['espower'],
'test/**/*.js': ['espower']
},
singleRun: false
}),
test: extend({}, require('./karma.conf.js'), {
browsers: ['Chrome', 'Firefox', 'IE11', 'IE10', 'IE9'],
reporters: ['dots'],
preprocessors: {
'dist/*.js': ['espower'],
'test/**/*.js': ['espower']
},
singleRun: true
}),
server: extend({}, require('./karma.conf.js'), {
browsers: ['Chromium', 'Firefox'],
reporters: ['dots'],
preprocessors: {
'dist/*.js': ['espower'],
'test/**/*.js': ['espower']
},
singleRun: true
})
}
};
gulp.task('ts:source', function () {
return gulp.src(config.ts.source.src)
.pipe($.typescript(Object.assign({
outFile: `${pkg.name}.js`
}, config.ts.options)))
.pipe($.header(config.exporter))
.pipe(gulp.dest(config.ts.source.dest));
});
gulp.task('ts:dist', function () {
return gulp.src(config.ts.dist.src)
.pipe($.typescript(Object.assign({
outFile: `${pkg.name}.js`
}, config.ts.options)))
.once("error", function () {
this.once("finish", () => process.exit(1));
})
.pipe($.unassert())
.pipe($.header(config.exporter))
.pipe($.header(config.banner))
.pipe(gulp.dest(config.ts.dist.dest))
.pipe($.uglify({ preserveComments: 'license' }))
.pipe($.rename({ extname: '.min.js' }))
.pipe(gulp.dest(config.ts.dist.dest));
});
gulp.task('ts:test', function () {
return gulp.src(config.ts.test.src)
.pipe($.typescript(Object.assign({
}, config.ts.options)))
.pipe(gulp.dest(config.ts.test.dest));
});
gulp.task('ts:watch', function () {
gulp.watch(config.ts.source.src, ['ts:source']);
gulp.watch(config.ts.test.src, ['ts:test']);
});
gulp.task('mocha:watch', function () {
gulp.watch(config.ts.source.dest + '*.js', ['mocha:test']);
});
gulp.task('mocha:test', function () {
return gulp.src(config.ts.source.dest + '*.js', { read: false })
.pipe($.mocha({
require: ['intelli-espower-loader'],
reporter: 'dot'
}));
});
gulp.task('karma:watch', function (done) {
new Server(config.karma.watch, function(exitCode) {
console.log('Karma has exited with ' + exitCode);
done();
}).start();
});
gulp.task('karma:test', function (done) {
new Server(config.karma.test, function(exitCode) {
console.log('Karma has exited with ' + exitCode);
done();
}).start();
});
gulp.task('karma:server', function (done) {
new Server(config.karma.server, function(exitCode) {
console.log('Karma has exited with ' + exitCode);
done();
}).start();
});
gulp.task('clean', function () {
return del([config.clean.src, config.clean.dist, config.clean.test, config.clean.bench]);
});
gulp.task('install', function () {
shell('npm i');
shell('tsd install --save --overwrite');
});
gulp.task('update', function () {
shell('npm-check-updates -u');
shell('npm i');
//shell('tsd update --save --overwrite');
});
gulp.task('build', ['clean'], function (done) {
seq(
['ts:source', 'ts:test'],
done
);
});
gulp.task('watch', ['build'], function () {
seq([
'ts:watch',
'karma:watch'
]);
});
gulp.task('test', ['build'], function (done) {
seq(
'karma:test',
function () {
done();
}
);
});
gulp.task('dist', ['clean'], function (done) {
seq(
'ts:dist',
done
);
});
gulp.task('server', function (done) {
seq(
'build',
'karma:server',
'dist',
function () {
done();
}
);
});
| JavaScript | 0.000006 | @@ -4573,278 +4573,106 @@
ch,
-function(exitCode) %7B%0A console.log('Karma has exited with ' + exitCode);%0A done();%0A %7D).start();%0A%7D);%0A%0Agulp.task('karma:test', function (done) %7B%0A new Server(config.karma.test, function(exitCode) %7B%0A console.log('Karma has exited with ' + exitCode);%0A done();%0A %7D
+done).start();%0A%7D);%0A%0Agulp.task('karma:test', function (done) %7B%0A new Server(config.karma.test, done
).st
@@ -4765,98 +4765,12 @@
er,
-function(exitCode) %7B%0A console.log('Karma has exited with ' + exitCode);%0A done();%0A %7D
+done
).st
|
61acafe4d4588cb76a16f856d62466ec8ac271c8 | Fix path merging | src/lib/php-autoloader.js | src/lib/php-autoloader.js | let fs = require("fs")
export default class PHPAutoloader {
/**
* Build the object
* @param {{[x: string]: string[]}} paths
*/
constructor(paths) {
this.paths = paths
}
/**
* @type {{[x: string]: string[]}} Class name prefixes mapped to arrays of
* paths. Each path should end with a /, and most prefixes will also.
*/
get paths() {
return this._paths
}
set paths(v) {
this._paths = v
}
/**
* Merges another autoloader into this one.
* @param {PHPAutoloader} autoloader
*/
add(autoloader) {
this.paths = Object.assign(
{},
this.paths,
autoloader.paths
)
}
/**
* Finds the filename that holds the class, if possible.
* @param {string} class_name
* @returns {?string}
*/
findClassFile(name) {
let canonical_class_name = name.replace(/^\\+/, "").replace(/_/g, '\\')
let paths = Object.keys(this.paths)
paths.sort((a, b) => b.length - a.length || a.localeCompare(b))
for(let k of paths) {
if(
k.length < canonical_class_name.length &&
k == canonical_class_name.substr(0, k.length)
) {
let path_tail = canonical_class_name.substr(k.length).replace(/\\/g, "/") + ".php"
let full_path = this.paths[k].map(
path => path + path_tail
).find(
path => fs.existsSync(path)
)
if(full_path) {
return full_path
}
}
}
return null
}
} | JavaScript | 0.000014 | @@ -607,88 +607,96 @@
-this.paths = Object.assign(%0A %7B%7D,%0A this.paths,%0A
+for(var k in autoloader.paths) %7B%0A this.paths%5Bk%5D = (this.paths%5Bk%5D%7C%7C%5B%5D).concat(
auto
@@ -703,24 +703,28 @@
loader.paths
+%5Bk%5D)
%0A )%0A
@@ -716,25 +716,25 @@
k%5D)%0A
-)
+%7D
%0A %7D%0A /
|
fd296ed5b24377f0f08307100ec51c3f1d8e476d | update workflow | gulpfile.js | gulpfile.js | var fs = require('fs');
var gulp = require('gulp');
var util = require('gulp-util');
var stylus = require('gulp-stylus');
var uglify = require('gulp-uglify');
var replace = require('gulp-replace');
var webpack = require('webpack-stream');
var sizereport = require('gulp-sizereport');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var getVersion = function() {
return JSON.parse(fs.readFileSync('./package.json').toString()).version;
};
var compile = function(isServeTask, done) {
var options = {
module: {
preLoaders: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'eslint-loader'
}],
loaders: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader?optional[]=runtime&stage=0'
}]
}
};
if (isServeTask) {
options.watch = true;
options.devtool = 'inline-source-map';
options.output = {
filename: 'app.js'
};
} else {
options.output = {
filename: 'smooth-scrollbar.js',
library: 'Scrollbar',
libraryTarget: 'umd'
};
}
return webpack(options, null, function(err, stats) {
if (err) throw new util.PluginError('webpack', err);
util.log('[webpack]', stats.toString({
colors: util.colors.supportsColor,
chunks: false,
hash: false,
version: false
}));
browserSync.reload();
if (isServeTask) {
isServeTask = false;
done();
}
});
};
gulp.task('scripts:build', function(done) {
return gulp.src('test/scripts/index.js')
.pipe(compile(true, done))
.pipe(replace(/<%= version %>/, getVersion()))
.pipe(gulp.dest('build/'));
});
gulp.task('scripts:dist', function() {
return gulp.src('src/index.js')
.pipe(compile(false))
.pipe(replace(/<%= version %>/, getVersion()))
.pipe(uglify())
.pipe(gulp.dest('build/'));
});
gulp.task('styles:build', function() {
return gulp.src('test/styles/index.styl')
.pipe(stylus())
.pipe(autoprefixer('> 1%, last 2 versions, Firefox ESR, Opera 12.1, ie >= 10'))
.pipe(gulp.dest('build/'))
.pipe(browserSync.stream());
});
gulp.task('styles:dist', function() {
return gulp.src('src/**/*.styl')
.pipe(stylus())
.pipe(autoprefixer('> 1%, last 2 versions, Firefox ESR, Opera 12.1, ie >= 10'))
.pipe(gulp.dest('dist/'));
});
gulp.task('serve', ['scripts:build', 'styles:build'], function() {
browserSync.init({
server: ['./test', '.'],
routes: {
'/build': 'build',
'/bower_components': 'bower_components'
}
});
gulp.watch('test/styles/*.styl', ['styles:build']);
gulp.watch('test/**/*.html').on('change', browserSync.reload);
});
gulp.task('dist', ['scripts:dist', 'styles:dist'], function() {
return gulp.src('dist/**/*.*')
.pipe(sizereport());
});
gulp.task('default', ['dist']);
| JavaScript | 0.000588 | @@ -2159,37 +2159,36 @@
pipe(gulp.dest('
-build
+dist
/'));%0A%7D);%0A%0Agulp.
@@ -2519,18 +2519,21 @@
rc('src/
-**
+style
/*.styl'
|
dcb53f90d5f4906f3560efd5a19b4cc66f5cb477 | Update FileManagerModel.js | static/sqleditor/models/FileManagerModel.js | static/sqleditor/models/FileManagerModel.js | define([
'dojo/_base/declare',
'dojo/store/Observable',
'dijit/tree/ObjectStoreModel'
], function (declare, Observable, ObjectStoreModel) {
var FileManagerModel = declare('sqleditor.models.FileManagerStoreModel', null, { });
/**
* Creates an Observable ObjectStoreModel.
* @param {Memory || FileManagerStore} store The tree store.
* @param {Object} rootQuery The root query for the tree store.
* @returns {ObjectStoreModel} The ObjectStoreModel(Observable(store));
*/
FileManagerModel.createModel = function (store, rootQuery) {
FileManagerModel.model = new ObjectStoreModel({
store: new Observable(store),
query: rootQuery,
labelAttr: 'name',
mayHaveChildren: function (node) {
return (node.isDir);
}
});
return FileManagerModel.model;
};
/**
* Gets the file tree model. This model needs to be shared amongst
* the file manager dialog and the file navigator in the main window.
* @returns {ObjectStoreModel} The file manager tree model.
*/
FileManagerModel.getModel = function () {
if (!FileManagerModel.model) {
FileManagerModel.createModel();
}
return FileManagerModel.model;
};
return FileManagerModel;
});
| JavaScript | 0 | @@ -1218,89 +1218,111 @@
-FileManagerModel.createModel();%0A %7D%0A%0A return FileManagerModel.model;
+throw %22Please initialize the model first with FileManagerModel.createModel(store, rootQuery)%22%0A %7D
%0A
|
56857a82dc7dbc58b99bf29dfd0598ea54f017c6 | implement logic | src/guild/index.js | src/guild/index.js | var angular = require('angular'),
moduleName = 'wow.guild',
mod = angular.module(moduleName, [
require('../core/configuration')
]);
mod.provider('wowResource', function() {
this.$get = ['$http', 'wowConfig', function($http, config) {
var options = config.options;
return {
members: members
};
function getUrl(opts) {
opts = opts ? opts : options;
return config.getUrl() + '/guild/' + opts.realm + '/' + opts.guild;
}
function getData(params, options) {
var url = options ? getUrl(options) : getUrl();
params = params ? params : {};
angular.extend(params, {jsonp: 'JSON_CALLBACK'});
return $http.jsonp(url, {
params: params,
cache: true
})
}
function members() {
return getData({fields: 'members'});
}
}]
});
module.exports = moduleName;
| JavaScript | 0 | @@ -146,16 +146,45 @@
%5D);%0A%0A
+module.exports = moduleName;%0A
%0Amod.pro
@@ -197,16 +197,13 @@
'wow
-Resource
+Guild
', f
@@ -363,16 +363,40 @@
members
+,%0A news: news
%0A
@@ -998,41 +998,94 @@
-%7D%5D%0A%7D);%0A%0Amodule.exports = moduleName
+ function news() %7B%0A return getData(%7Bfields: 'news'%7D);%0A %7D%0A%0A %7D%5D%0A%7D)
;%0A
|
2192a53a49764e05d1642846d915692d7f7890f2 | Remove duplicate commented gulp task line | gulpfile.js | gulpfile.js | /*
* require gulp plugins
*/
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
minifycss = require('gulp-minify-css'),
newer = require('gulp-newer'),
imagemin = require('gulp-imagemin'),
livereload = require('gulp-livereload'),
lr = require('tiny-lr'),
server = lr();
/*
* common directories
*/
var src = 'wp-content/themes/theopenpress/src',
images = src + '/images',
stylesheets = src + '/stylesheets',
scripts = src + '/scripts',
build = 'wp-content/themes/theopenpress/assets',
img = build + '/img',
css = build + '/css',
js = build + '/js';
/*
* styles task
*/
gulp.task('styles', function() {
return gulp.src(stylesheets + '/app.scss', {base: stylesheets})
/* return gulp.src(stylesheets + '/app.scss', {base: stylesheets}) */
.pipe(plumber())
.pipe(sass({style: 'expanded'}))
.pipe(gulp.dest(css))
.pipe(autoprefixer('last 2 versions'))
.pipe(minifycss())
.pipe(gulp.dest(css))
.pipe(livereload(server));
});
/*
* images task
*/
gulp.task('images', function() {
return gulp.src(images + '/*', {base: images})
.pipe(newer(img))
.pipe(imagemin({optimizationLevel: 3, progressive: true, interlaced: true}))
.pipe(gulp.dest(img));
});
/*
* watch task
*/
gulp.task('watch', function() {
server.listen(35739, function(error) {
if (error) {
return console.log(error)
};
gulp.watch(stylesheets + '/*.scss', ['styles']);
gulp.watch(stylesheets + '/**/*.scss', ['styles']);
gulp.watch(images + '/**', ['images']);
});
});
/*
* default task
*/
gulp.task('default', ['styles', 'images', 'watch']);
| JavaScript | 0.000001 | @@ -924,80 +924,8 @@
s%7D)%0A
-/* return gulp.src(stylesheets + '/app.scss', %7Bbase: stylesheets%7D) */%0A
|
496c7652eefc607c65a406694b6d6e4c1d7d6613 | Update stylus build destination. | gulpfile.js | gulpfile.js | // Load Gulp and all of our Gulp plugins
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
// Load other npm modules
const del = require('del');
const glob = require('glob');
const path = require('path');
const isparta = require('isparta');
const babelify = require('babelify');
const watchify = require('watchify');
const buffer = require('vinyl-buffer');
const esperanto = require('esperanto');
const browserify = require('browserify');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
// Gather the library data from `package.json`
const manifest = require('./package.json');
const config = manifest.babelBoilerplateOptions;
const mainFile = manifest.main;
const destinationFolder = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
// Remove the built files
gulp.task('clean', function(cb) {
del([destinationFolder], cb);
});
// Remove our temporary files
gulp.task('clean-tmp', function(cb) {
del(['tmp'], cb);
});
// Send a notification when JSCS fails,
// so that you know your changes didn't build
function jscsNotify(file) {
if (!file.jscs) { return; }
return file.jscs.success ? false : 'JSCS failed';
}
function createLintTask(taskName, files) {
gulp.task(taskName, function() {
return gulp.src(files)
.pipe($.plumber())
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failOnError())
.pipe($.jscs())
.pipe($.notify(jscsNotify));
});
}
// Lint our source code
createLintTask('lint-src', ['src/**/*.js']);
// Lint our test code
createLintTask('lint-test', ['test/**/*.js']);
// Build two versions of the library
gulp.task('build', ['lint-src', 'clean', 'stylus'], function(done) {
esperanto.bundle({
base: 'src',
entry: config.entryFileName,
}).then(function(bundle) {
var res = bundle.toUmd({
// Don't worry about the fact that the source map is inlined at this step.
// `gulp-sourcemaps`, which comes next, will externalize them.
sourceMap: 'inline',
name: config.mainVarName
});
$.file(exportFileName + '.js', res.code, { src: true })
.pipe($.plumber())
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.babel())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(destinationFolder))
.pipe($.filter(['*', '!**/*.js.map']))
.pipe($.rename(exportFileName + '.min.js'))
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.uglify())
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(destinationFolder))
.on('end', done);
})
.catch(done);
});
function bundle(bundler) {
return bundler.bundle()
.on('error', function(err) {
console.log(err.message);
this.emit('end');
})
.pipe($.plumber())
.pipe(source('./tmp/__spec-build.js'))
.pipe(buffer())
.pipe(gulp.dest(''))
.pipe($.livereload());
}
function getBundler() {
// Our browserify bundle is made up of our unit tests, which
// should individually load up pieces of our application.
// We also include the browserify setup file.
var testFiles = glob.sync('./test/unit/**/*');
var allFiles = ['./test/setup/browserify.js'].concat(testFiles);
// Create our bundler, passing in the arguments required for watchify
var bundler = browserify(allFiles, watchify.args);
// Watch the bundler, and re-bundle it whenever files change
bundler = watchify(bundler);
bundler.on('update', function() {
bundle(bundler);
});
// Set up Babelify so that ES6 works in the tests
bundler.transform(babelify.configure({
sourceMapRelative: __dirname + '/src'
}));
return bundler;
};
// Build the unit test suite for running tests
// in the browser
gulp.task('browserify', function() {
return bundle(getBundler());
});
function test() {
return gulp.src(['test/setup/node.js', 'test/unit/**/*.js'], {read: false})
.pipe($.mocha({reporter: 'dot', globals: config.mochaGlobals}));
}
gulp.task('coverage', ['lint-src', 'lint-test'], function(done) {
require('babel-core/register');
gulp.src(['src/**/*.js'])
.pipe($.istanbul({ instrumenter: isparta.Instrumenter }))
.pipe($.istanbul.hookRequire())
.on('finish', function() {
return test()
.pipe($.istanbul.writeReports())
.on('end', done);
});
});
// Lint and run our tests
gulp.task('test', ['lint-src', 'lint-test'], function() {
require('babel-core/register');
return test();
});
gulp.task('stylus', function() {
return gulp.src('./src/marionette.overlay-view.styl')
.pipe($.stylus({
compress:true
}))
.pipe(gulp.dest('./dest'));
});
// Ensure that linting occurs before browserify runs. This prevents
// the build from breaking due to poorly formatted code.
gulp.task('build-in-sequence', function(callback) {
runSequence(['lint-src', 'lint-test'], 'browserify', callback);
});
// These are JS files that should be watched by Gulp. When running tests in the browser,
// watchify is used instead, so these aren't included.
const jsWatchFiles = ['src/**/*', 'test/**/*'];
// These are files other than JS files which are to be watched. They are always watched.
const otherWatchFiles = ['package.json', '**/.eslintrc', '.jscsrc'];
// Run the headless unit tests as you make changes.
gulp.task('watch', function() {
const watchFiles = jsWatchFiles.concat(otherWatchFiles);
gulp.watch(watchFiles, ['test']);
});
// Set up a livereload environment for our spec runner
gulp.task('test-browser', ['build-in-sequence'], function() {
$.livereload.listen({port: 35729, host: 'localhost', start: true});
return gulp.watch(otherWatchFiles, ['build-in-sequence']);
});
// An alias of test
gulp.task('default', ['test']);
| JavaScript | 0 | @@ -4666,17 +4666,17 @@
est('./d
-e
+i
st'));%0A%7D
|
47d8add58c03eaccbe7d67189e3d99b525f71de4 | Add default gulp compilation. | gulpfile.js | gulpfile.js | "use strict";
/**
* Gulp usage file for the whole project.
*/
var gulp = require("gulp");
var ts = require("gulp-typescript");
var eventStream = require("event-stream");
var tslint = require("gulp-tslint");
var sequence = require("run-sequence").use(gulp);
var babel = require("gulp-babel");
var path = require("path");
var typeScriptSource = [
"./typedefinitions/backend.d.ts",
"./backend/**/*.ts"
];
var typeScriptDestination = "./release/";
// TYPESCRIPT COMPILATION
gulp.task("typescript", function() {
return gulp
.src( typeScriptSource )
// Pipe source to lint
.pipe(tslint())
.pipe(tslint.report("verbose"))
// Push through to compiler
.pipe(ts({
typescript: require("typescript"),
declarationFiles: false,
noImplicitAny: true,
noExternalResolve: false,
removeComments: true,
target: "es6",
showErrors: true
}))
// Through babel (es6->es5)
.pipe(babel({
comments: false,
presets: [ "es2015" ]
}))
.pipe(gulp.dest(typeScriptDestination));
});
/**
* Run with: 'gulp w'
*/
gulp.task("w", function() {
gulp.watch(typeScriptSource, [ "typescript" ]);
});
| JavaScript | 0 | @@ -1268,12 +1268,136 @@
pt%22 %5D);%0A%7D);%0A
+%0A/**%0A * Run with: 'gulp' or 'gulp default'%0A */%0Agulp.task(%22default%22, function() %7B%0A return sequence(%5B %22typescript%22 %5D);%0A%7D);%0A
|
19b567286c959ced959223a7a9d855baa9c71ac2 | add build script | gulpfile.js | gulpfile.js | 'use strict';
const gulp = require('gulp');
const del = require('del');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const runSequence = require('run-sequence');
const inlineNg2Template = require('gulp-inline-ng2-template');
const rename = require("gulp-rename");
const paths = {
all: "./npm-modules/**/*.*",
tmp: "./tmp",
sass: "./tmp/**/*.scss",
css: "./tmp/**/*.css",
ts: "./tmp/**/*.ts"
};
gulp.task('build-clean', function () {
return del(paths.tmp);
});
gulp.task('build-rename', function () {
return gulp.src(paths.css)
.pipe(rename(function (path) {
path.extname = ".scss"
}))
.pipe(gulp.dest(sameFolder));
});
gulp.task('build-sass', function () {
return gulp.src(paths.sass)
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(cleanCSS())
.pipe(gulp.dest(sameFolder));
});
gulp.task('build-inline', () => {
return gulp.src(paths.ts)
.pipe(inlineNg2Template({ useRelativePaths:true}))
.pipe(gulp.dest(sameFolder));
});
gulp.task('build-copy-npm-modules', () => {
return gulp.src(paths.all)
.pipe(gulp.dest(paths.tmp));
});
gulp.task('build', () => {
runSequence(
'build-clean',
'build-copy-npm-modules',
'build-sass',
'build-rename',
'build-inline'
);
});
function sameFolder(file) {
return file.base;
}
| JavaScript | 0.000001 | @@ -344,18 +344,16 @@
ame%22);%0A%0A
-%0A%0A
const pa
|
33383accd052fa6cfb73faebc81f2a59e2afdc51 | Modify path to node_modules | gulpfile.js | gulpfile.js | require('es6-promise').polyfill();
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var moduleImporter = require('sass-module-importer');
var autoprefixer = require('gulp-autoprefixer');
var gcmq = require('gulp-group-css-media-queries');;
var cleanCSS = require('gulp-clean-css');
var include = require('gulp-include');
var uglify = require('gulp-uglify');
var del = require('del');
var runSequence = require('run-sequence');
var srcThemesPath = './resources/themes/';
var destThemesPath = './public/assets/';
gulp.task('sass-dev', function() {
return gulp.src([srcThemesPath + '**/*.scss'])
.pipe(sourcemaps.init())
.pipe(sass({ importer: moduleImporter() }).on('error', sass.logError))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(destThemesPath));
});
gulp.task('sass-prod', function() {
return gulp.src([srcThemesPath + '**/*.scss'])
.pipe(sass({ importer: moduleImporter() }).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gcmq())
.pipe(cleanCSS({debug: true}, function(details) {
console.log(details.name + ' before: ' + details.stats.originalSize);
console.log(details.name + ' after: ' + details.stats.minifiedSize);
}))
.pipe(gulp.dest(destThemesPath));
});
gulp.task('js', function() {
return gulp.src([srcThemesPath + '**/*.js'])
.pipe(include())
.pipe(include({
includePaths: [__dirname + "/node_modules"]
})).on('error', console.log)
.pipe(uglify())
.pipe(gulp.dest(destThemesPath));
});
gulp.task('clean', function() {
return del.sync('./public/assets');
})
gulp.task('watch', function(){
gulp.watch(srcThemesPath + '**/*.scss', ['sass-dev']);
gulp.watch(srcThemesPath + '**/*.js', ['js']);
})
// Build Sequences
// ---------------
gulp.task('default', function() {
runSequence('clean', ['sass-dev', 'js'], 'watch')
})
gulp.task('build', function() {
runSequence('clean', ['sass-prod', 'js'])
})
| JavaScript | 0.000002 | @@ -1495,21 +1495,10 @@
s: %5B
-__dirname + %22
+'.
/nod
@@ -1510,9 +1510,9 @@
ules
-%22
+'
%5D%0A
|
d7fb37f95acd4de9026cd74c402a50b784d737b0 | change gulp file | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var babelify = require('babelify');
var babel = require('gulp-babel');
var server = require('gulp-webserver');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var eslint = require('gulp-eslint');
var replace = require('gulp-replace');
var minifyCSS = require('gulp-minify-css');
var config = {
componentFileName: 'react-star-rating',
componentSrc: './src/StarRating.jsx',
componentStylesDir: './src/sass',
stylesDest: './dist/css'
};
/**
* Lint
*/
gulp.task('lint', function () {
return gulp.src('./src/**/*.{jsx, js}')
.pipe(eslint({
useEslintrc: true
}))
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
/**
* Styles
*/
gulp.task('styles', ['demo-styles'], function () {
return gulp.src(config.componentStylesDir + '/' + config.componentFileName + '.scss')
.pipe(sass({
includePaths: require('node-bourbon').includePaths
}))
.pipe(gulp.dest(config.stylesDest))
.pipe(minifyCSS())
.pipe(rename(config.componentFileName + '.min.css'))
.pipe(gulp.dest(config.stylesDest));
});
/**
* Build
*/
gulp.task('build', ['lint'], function () {
return gulp.src(config.componentSrc)
.pipe(babel())
.pipe(rename(config.componentFileName + '.js'))
.pipe(gulp.dest('dist'))
.pipe(rename(config.componentFileName + '.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
/**
* Demo Styles
*/
gulp.task('demo-styles', function () {
return gulp.src(config.componentStylesDir + '/demo.scss')
.pipe(sass({
includePaths: require('node-bourbon').includePaths
}))
.pipe(gulp.dest(config.stylesDest));
});
/**
* Demo Bundle
*/
gulp.task('default', ['lint', 'styles'], function () {
return browserify('./src/docs.jsx', {extensions: '.jsx'})
.transform(babelify)
.bundle()
.on('error', function (err) {
console.log(err);
})
.pipe(source('docs.js'))
.pipe(gulp.dest('dist'));
});
/**
* Watch
*/
gulp.task('watch', ['default'], function () {
gulp.watch(['./src/*.js', './src/**/*.jsx', './src/sass/{*/,}*.scss'], ['dist']);
return gulp.src('.').pipe(server());
});
/**
* Dist
*/
gulp.task('dist', ['default', 'styles', 'build']);
| JavaScript | 0.000001 | @@ -2367,16 +2367,36 @@
(server(
+%7B%0A port: 3000%0A %7D
));%0A%7D);%0A
|
1576a53f5711c78bd4fb6dea0702228fca3c0ae2 | fix gulp templateCache | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var clean = require('gulp-clean');
var jshint = require('gulp-jshint');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require("gulp-uglify");
var imagemin = require('gulp-imagemin');
var htmlreplace = require('gulp-html-replace');
var templateCache = require('gulp-angular-templatecache');
var wiredep = require('wiredep');
var usemin = require('gulp-usemin');
var minifyHtml = require('gulp-minify-html');
var rev = require('gulp-rev');
var install = require("gulp-install");
var paths = {
sass: ['./scss/**/*.scss'],
scripts: ['./www/js/**/*.js', '!./www/js/app.bundle.min.js'], // exclude the file we write too
images: ['./www/img/**/*'],
templates: ['./www/templates/**/*.html'],
css: ['./www/css/**/*.min.css'],
html: ['./www/index.html'],
fonts: ['./www/lib/ionic/fonts/*'],
lib: ['./www/lib/parse-1.2.18.min.js', './www/lib/moment.min.js', './www/lib/bindonce.min.js'],
www: ['./www/'],
dist: ['./dist/']
};
// Check the project is up to date.
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
// Install npm packages.
gulp.task('npm', function(done) {
gulp.src(['./package.json'])
.pipe(install());
});
// Install bower dependenices.
gulp.task('bower', function () {
bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
// Set bower dependencies.
gulp.task('wiredep', function(){
gulp.src(paths.html)
.pipe(wiredep.stream())
.pipe(gulp.dest(paths.www + './'));
});
gulp.task('install', ['git-check', 'npm', 'bower', 'wiredep']);
// Build sass file.
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass({
errLogToConsole: true
}))
.pipe(gulp.dest(paths.www + 'css/'))
.on('end', done);
});
// concat all html templates and load into templateCache
gulp.task('templateCache', function() {
gulp.src(paths.templates)
.pipe(templateCache({
'filename': 'templates.js',
'root': 'templates/',
'module': 'app'
}))
.pipe(gulp.dest(paths.www + 'js'))
done();
});
gulp.task('jshint', function() {
gulp.src(paths.scripts)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
gulp.watch(paths.templates, ['templateCache']);
gulp.watch(paths.scripts, ['scripts']);
});
gulp.task('default', ['sass', 'templateCache']);
gulp.task('clean', function(done) {
gulp.src(paths.dist, { read: false })
.pipe(clean());
done();
});
gulp.task('usemin', ['clean', 'sass', 'templateCache'], function (done) {
gulp.src(paths.html)
.pipe(usemin({
html: [minifyHtml({empty: true})],
css: [minifyCss(), 'concat', rev()],
jsVendor: [uglify(), rev()],
jsApp: [
ngAnnotate({remove: true, add: true, single_quotes: true }),
jshint(),
jshint.reporter('default'),
uglify(),
rev()
]
}))
.pipe(gulp.dest(paths.dist + ''));
done();
});
// Imagemin images and ouput them in dist
gulp.task('imagemin', function() {
gulp.src(paths.images)
.pipe(imagemin())
.pipe(gulp.dest(paths.dist + 'img'));
});
gulp.task('copy', function() {
gulp.src(paths.fonts, {base: paths.www + ''})
.pipe(gulp.dest(paths.dist + ''));
});
gulp.task('build', ['clean'], function(){
gulp.start('usemin');
gulp.start('imagemin');
gulp.start('copy');
}); | JavaScript | 0.000001 | @@ -2530,32 +2530,36 @@
ache', function(
+done
) %7B%0A gulp.src(p
@@ -2732,22 +2732,34 @@
'js'))%0A
+ .on('end',
done
-(
);%0A%7D);%0A%0A
|
6b3c92193576957690a484b089851e3c4a45419b | remove clean task from gulp | gulpfile.js | gulpfile.js | var $ = require('gulp-load-plugins')();
var _ = require('lodash');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var es = require('event-stream');
var exec = require('child_process').exec;
var git = require('git-rev');
var glob = require('glob');
var gulp = require('gulp');
var ngAnnotate = require('browserify-ngannotate');
var source = require('vinyl-source-stream');
var copiedFiles = require('./config/copiedFiles.json');
var packageJson = require('./package.json');
var config = {
outputName: 'app',
templateCache: {
file: "templates.js",
options: {
module: 'app',
transformUrl: function(url) {
return url.replace(/\.nghtml$/, ".html");
}
}
},
packedAssetName: 'assets.go',
serveLiveAssets: !$.util.env.production,
appName: packageJson.name,
version: packageJson.version
};
var paths = {
base: "assets",
js: "assets/js/**.js",
angularIncludes: 'assets/js/*/',
scss: ["assets/css/**/*.scss", "assets/css/**/*.css", "!assets/css/colors.scss"],
images: "assets/images/**/*",
html: "assets/*.html",
templates: "assets/**/*.nghtml",
goTemplates: "templates/**.*",
outputBase: "build",
goOutput: "build/templates",
assetOutput: "build/public",
distOutput: "dist"
};
var cachebust;
if (config.serveLiveAssets) {
// create noop version of cachebust
cachebust = {
resources: $.util.noop,
references: $.util.noop,
};
} else {
cachebust = new $.cachebust();
}
gulp.task('clean', function() {
return gulp.src([
paths.goOutput,
paths.assetOutput,
paths.distOutput,
paths.outputBase + "/" + config.packedAssetName,
paths.outputBase + "/" + config.outputName
]).
pipe($.clean());
});
gulp.task("copy-files", function(cb) {
var files = _.map(copiedFiles, function(fileGlobs, dest) {
return gulp.src(fileGlobs).
pipe(gulp.dest(dest)).
pipe($.size({ title: "copied files" }));
});
es.merge(files).on('end', cb);
});
gulp.task("image-assets", function() {
return gulp.src(paths.images).
pipe($.imagemin({
progressive: true,
interlaced: true
})).
pipe(cachebust.resources()).
pipe(gulp.dest(paths.assetOutput + "/images")).
pipe($.size({ title: "images" }));
});
gulp.task("js-assets", function(cb) {
glob(paths.js, function(err, files) {
var bundles = _.map(files, function(filename) {
return browserify({
entries: filename,
debug: true,
paths: paths.angularIncludes,
external: ['angular', 'jquery'],
transform: [ngAnnotate]
}).bundle().
pipe(source(filename.replace(paths.base + '/', ''))).
pipe(buffer()).
pipe($.sourcemaps.init({ loadMaps: true })).
pipe($.uglify()).
pipe(cachebust.resources()).
pipe($.sourcemaps.write('./')).
pipe(gulp.dest(paths.assetOutput)).
pipe($.size({ title: "script bundles" }));
});
es.merge(bundles).on('end', cb);
});
});
gulp.task("style-assets", function() {
return gulp.src(paths.scss).
pipe($.sass().on('error', $.sass.logError)).
pipe(cachebust.resources()).
pipe(gulp.dest(paths.assetOutput + "/css")).
pipe($.size({ title: "stylesheets" }));
});
gulp.task('templatecache', ["compile-assets"], function() {
return gulp.src(paths.templates).
pipe($.angularTemplatecache(config.templateCache.file, config.templateCache.options)).
pipe(cachebust.resources()).
pipe(cachebust.references()).
pipe(gulp.dest(paths.assetOutput + "/js")).
pipe($.size({ title: "templates" }));
});
gulp.task("html-pages", ["compile-assets", "templatecache"], function() {
return gulp.src(paths.html).
pipe(cachebust.references()).
pipe(gulp.dest(paths.assetOutput)).
pipe($.size({ title: "html pages"}));
});
gulp.task("go-templates:html", ["compile-assets", "templatecache"], function() {
return gulp.src(paths.goTemplates).
pipe(cachebust.references()).
pipe(gulp.dest(paths.goOutput)).
pipe($.size({ title: "Go template html pages"}));
});
gulp.task("compile-assets", ["copy-files", "style-assets", "image-assets", "js-assets"]);
gulp.task("build-web", ["compile-assets", "templatecache", "html-pages"]);
gulp.task("all-assets", ["build-web", "go-templates:html"]);
gulp.task("build", ["all-assets"]);
gulp.task("default", ["build"]);
| JavaScript | 0.000354 | @@ -517,29 +517,8 @@
= %7B%0A
- outputName: 'app',%0A
te
@@ -528,24 +528,24 @@
ateCache: %7B%0A
+
file: %22t
@@ -703,40 +703,8 @@
%7D,%0A
- packedAssetName: 'assets.go',%0A
se
@@ -1193,30 +1193,8 @@
lic%22
-,%0A distOutput: %22dist%22
%0A%7D;%0A
@@ -1411,272 +1411,11 @@
();%0A
+
%7D%0A%0A
-gulp.task('clean', function() %7B%0A return gulp.src(%5B%0A paths.goOutput,%0A paths.assetOutput,%0A paths.distOutput,%0A paths.outputBase + %22/%22 + config.packedAssetName,%0A paths.outputBase + %22/%22 + config.outputName%0A %5D).%0A pipe($.clean());%0A%7D);%0A%0A
gulp
|
4e0f67ad6a87dfb99403cb49b5a38b46a3fafc64 | Remove redundancy of test commands. | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var typescript = require('gulp-typescript');
var sourcemaps = require('gulp-sourcemaps');
var electronConnect = require('electron-connect');
var process = require('process');
var packager = require('electron-packager');
var archiver = require('archiver');
var fs = require('fs');
var path = require('path');
var shell = require('gulp-shell');
var pkg = require('./package.json');
var exec = require('child_process').exec;
var argv = require('yargs').argv;
var embedTemplates = require('gulp-angular-embed-templates');
var webserver = require('gulp-webserver');
var paths = {
'build': 'dist/',
'release': 'release/'
};
gulp.task('clean', function() {
return del([paths.build + '/**/*', paths.release + '/**/*']);
});
// compile sass and concatenate to single css file in build dir
gulp.task('convert-sass', function() {
return gulp.src('src/scss/app.scss')
.pipe(sass({includePaths: [
'node_modules/bootstrap-sass/assets/stylesheets/',
'node_modules/mdi/scss/'
], precision: 8}))
.pipe(concat(pkg.name + '.css'))
.pipe(gulp.dest(paths.build + '/css'));
});
gulp.task('provide-resources', function() {
gulp.src([
'node_modules/mdi/fonts/**/*',
'node_modules/bootstrap-sass/assets/fonts/**/*'
])
.pipe(gulp.dest(paths.build + '/fonts'));
return gulp.src('src/img/**/*')
.pipe(gulp.dest(paths.build + '/img'));
});
gulp.task('provide-configs', function() {
return gulp.src('src/config/**/*.json')
.pipe(gulp.dest(paths.build + '/config'));
});
gulp.task('package-node-dependencies', function() {
gulp.src('node_modules/angular2-uuid/*' )
.pipe(gulp.dest('dist/lib/angular2-uuid/'));
});
const tscConfig = require('./tsconfig.json');
/**
* Copies the indext to the dist folder, compiles typescript sources to javascript
* AND renders the html templates into the component javascript files.
*/
gulp.task('provide-sources', function () {
gulp.src('src/index.html')
.pipe(gulp.dest(paths.build));
return gulp
.src('src/app/**/*.ts')
.pipe(embedTemplates({basePath: "src", sourceType:'ts'}))
.pipe(typescript(tscConfig.compilerOptions))
.pipe(gulp.dest(paths.build + 'app'));
});
/**
*
*/
gulp.task('copy-electron-files', function () {
gulp.src(['package.json']).pipe(gulp.dest('dist')); // also needed for an electron app
return gulp.src(['main.js']).pipe(gulp.dest('dist'));
});
/**
* Compiles the typescript written unit tests and copies the
* javascript written end to end test files.
*/
gulp.task('provide-test-sources', function () {
gulp
.src('src/test/**/*.ts')
.pipe(typescript(tscConfig.compilerOptions))
.pipe(gulp.dest(paths.build + 'test'));
return gulp
.src('src/e2e/**/*.js')
.pipe(gulp.dest(paths.build + 'e2e'));
});
gulp.task('concat-deps', function() {
return gulp.src([
'node_modules/node-uuid/uuid.js',
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/http.dev.js',
'node_modules/angular2/bundles/router.dev.js'
])
.pipe(concat(pkg.name + '-deps.js'))
.pipe(uglify())
.pipe(gulp.dest(paths.build + '/lib'));
});
function watch() {
gulp.watch('src/scss/**/*.scss', ['convert-sass']);
gulp.watch('src/app/**/*.ts', ['provide-sources']);
gulp.watch('src/templates/**/*.html', ['provide-sources']);
gulp.watch('src/index.html', ['provide-sources']);
gulp.watch('src/config/**/*.json', ['provide-configs']);
gulp.watch('src/img/**/*', ['provide-resources']);
gulp.watch('src/test/**/*ts', ['provide-test-sources']);
gulp.watch('src/e2e/**/*js', ['provide-test-sources']);
}
gulp.task('webserver-watch',['build'], function() {
gulp.src('dist')
.pipe(webserver({
fallback: 'index.html',
port: 8081
}));
watch();
});
var electronServer = electronConnect.server.create({path: paths.build});
// runs the development server and sets up browser reloading
gulp.task('run', ['build'], function() {
electronServer.start();
gulp.watch('main.js', ['copy-electron-files'], electronServer.restart);
watch();
gulp.watch('dist/**/*', electronServer.reload);
});
// builds an electron app package for different platforms
gulp.task('package', [], function() {
packager({
dir: paths.build,
name: pkg.name,
platform: ['win32', 'darwin'],
arch: 'all',
version: '0.36.10',
appBundleId: pkg.name,
appVersion: pkg.version,
buildVersion: pkg.version,
cache: 'cache/',
helperBundleId: pkg.name,
icon: 'dist/img/logo',
out: paths.release
}, function(err, appPath) {
if (err)
throw err;
var folderPaths = appPath.toString().split(',');
for (var i in folderPaths) {
var fileName = folderPaths[i].substring(folderPaths[i].lastIndexOf(path.sep) + 1);
var output = fs.createWriteStream(paths.release + '/' + fileName + '.zip');
var archive = archiver('zip');
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
archive.directory(folderPaths[i], fileName, { 'name': fileName });
archive.finalize();
}
});
});
gulp.task('build', [
'convert-sass',
'copy-electron-files',
'concat-deps',
'provide-sources',
'provide-test-sources',
'provide-resources',
'provide-configs',
'package-node-dependencies'
]);
gulp.task('default', function() {
runSequence('clean', 'build', 'test' );
}); | JavaScript | 0.000018 | @@ -5702,16 +5702,8 @@
ild'
-, 'test'
);%0A
|
8dc08050be3f6b53b13d0a6c4e421b0806897355 | fix gulpfile, let gulp exit with error when jshint failed. | gulpfile.js | gulpfile.js | var gulp = require('gulp')
, jshint = require('gulp-jshint')
, uglify = require('gulp-uglify')
, rename = require('gulp-rename')
, ghpages = require('gulp-gh-pages')
gulp.task('jshint', function(){
gulp.src(['**/*.js', '!node_modules/**', '!**/*.min.js'])
.pipe(jshint('.jshintrc'))
.pipe(jshint.reporter())
})
gulp.task('compress', function(){
gulp.src(['./fontonload.js'])
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./'))
})
gulp.task('gh-pages', function () {
gulp.src(['**/*', '!node_modules/**'])
.pipe(ghpages());
})
gulp.task('test', ['jshint'])
gulp.task('default', ['jshint', 'compress', 'gh-pages'])
| JavaScript | 0 | @@ -320,16 +320,51 @@
rter())%0A
+ .pipe(jshint.reporter('fail'))%0A
%7D)%0A%0Agulp
|
bd1679edef742622c71b8e44832d721c0d04ec1f | Add layer in getROIIDs | src/image/roi/manager.js | src/image/roi/manager.js | import createROIMap from './createROIMap';
import createROI from './createROI';
import extendObject from 'extend';
export default class ROIManager {
constructor(image, options = {}) {
this._image = image;
this._options = options;
this._layers = {};
this._painted = null;
}
putMask(mask, maskLabel = 'default', options = {}) {
let opt = extendObject({}, this._options, options);
this._layers[maskLabel] = new ROILayer(mask, opt);
}
getROIMap(maskLabel = 'default') {
if (!this._layers[maskLabel]) return;
return this._layers[maskLabel].roiMap;
}
getROIIDs(options) {
let rois = this.getROI(options);
if (!rois) return;
let ids = new Array(rois.length);
for (let i = 0; i < rois.length; i++) {
ids[i] = rois[i].id;
}
return ids;
}
getROI(maskLabel = 'default', {
positive = true,
negative = true,
minSurface = 0,
maxSurface = Number.POSITIVE_INFINITY
} = {}) {
let allROIs = this._layers[maskLabel].roi;
let rois = new Array(allROIs.length);
let ptr = 0;
for (let i = 0; i < allROIs.length; i++) {
let roi = allROIs[i];
if (((roi.id < 0 && negative) || roi.id > 0 && positive)
&& roi.surface > minSurface
&& roi.surface < maxSurface) {
rois[ptr++] = roi;
}
}
rois.length = ptr;
return rois;
}
getROIMasks(maskLabel = 'default', options = {}) {
let rois = this.getROI(maskLabel, options);
let masks = new Array(rois.length);
for (let i = 0; i < rois.length; i++) {
masks[i] = rois[i].mask;
}
return masks;
}
getPixels(maskLabel = 'default', options = {}) {
if (this._layers[maskLabel]) {
return this._layers[maskLabel].roiMap.pixels;
}
}
paint(maskLabel = 'default', options = {}) {
if (!this._painted) this._painted = this._image.clone();
let masks = this.getROIMasks(maskLabel, options);
this._painted.paintMasks(masks, options);
return this._painted;
}
resetPainted() {
this._painted = undefined;
}
}
class ROILayer {
constructor(mask, options) {
this.mask = mask;
this.options = options;
this.roiMap = createROIMap(this.mask, options);
this.roi = createROI(this.roiMap);
}
}
| JavaScript | 0 | @@ -645,16 +645,39 @@
tROIIDs(
+maskLabel = 'default',
options)
@@ -710,16 +710,27 @@
.getROI(
+maskLabel,
options)
|
79f647dc5cdf9552547cb82f245e7fde67a194a2 | Set default values for user and userDomains | hawk/app.js | hawk/app.js | 'use strict';
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('dotenv').config();
/** * Loggers ***/
/* Main logger */
var winston = require('winston');
/* Allow rotate log files by date */
require('winston-daily-rotate-file');
/* Express middleware logger */
var morgan = require('morgan');
/** */
/* File system */
var fs = require('fs');
/** Setup loggers **/
var logsDir = './logs',
accessDir = logsDir + '/access',
errorsDir = logsDir + '/errors';
if (!fs.existsSync(logsDir)) {
fs.mkdirSync(logsDir);
fs.mkdirSync(accessDir);
fs.mkdirSync(errorsDir);
}
if (!fs.existsSync(accessDir)) {
fs.mkdirSync(accessDir);
}
if (!fs.existsSync(errorsDir)) {
fs.mkdirSync(errorsDir);
}
/* HTTP requests logger */
winston.loggers.add('access', {
dailyRotateFile: {
level: 'debug',
filename: 'logs/access/.log',
datePattern: 'yyyy-MM',
prepend: true,
timestamp: true
}
});
/* Global logger */
winston.loggers.add('console', {
console: {
level: 'debug',
colorize: true,
timestamp: true,
handleExceptions: true,
humanReadableUnhandledException: true
},
dailyRotateFile: {
level: 'debug',
filename: 'logs/errors/.log',
datePattern: 'yyyy-MM',
prepend: true,
timestamp: true,
handleExceptions: true,
humanReadableUnhandledException: true
}
});
/**
* @usage logger.log(level, message)
* logger[level](message)
*/
global.logger = winston.loggers.get('console');
let accessLogger = winston.loggers.get('access');
accessLogger.stream = {
write: function (message) {
accessLogger.info(message);
}
};
var app = express();
/**
* User model
* @uses for getting current user data
*/
let user = require('./models/user');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
/** We use morgan as express middleware to link winston and express **/
app.use(morgan('combined', { stream: accessLogger.stream }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/static', express.static(path.join(__dirname, 'public')));
/**
* Sets response scoped variables
*
* res.locals.user — current authored user
* res.locals.userDomains — domains list for current user
*
* @fires user.getInfo
*/
app.use(function (req, res, next) {
user.getInfo(req).then(function (userData) {
res.locals.user = userData.user;
res.locals.userDomains = userData.domains;
next();
});
});
/**
* Garage
*/
var garage = require('./routes/garage/garage');
app.use('/garage', garage);
/**
* Yard
*/
var index = require('./routes/yard/index');
var login = require('./routes/yard/auth/login');
var logout = require('./routes/yard/auth/logout');
var join = require('./routes/yard/auth/join');
var websites = require('./routes/yard/websites');
app.use('/', index);
app.use('/websites', websites);
app.use('/login', login);
app.use('/logout', logout);
app.use('/join', join);
/**
* Catcher
*/
var catcher = require('./routes/catcher/catcher');
app.use('/catcher', catcher);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = process.env.ENVIRONMENT === 'DEVELOPMENT' ? err : {};
logger.error('Error thrown: ', err);
// render the error page
res.status(err.status || 500);
let errorPageData;
if (err.status === 404) {
errorPageData = {
title: '404',
message : 'Page not found'
};
} else {
errorPageData = {
title: ':(',
message : 'Sorry, dude. Looks like some of our services is busy.'
};
}
res.render('yard/errors/error', errorPageData);
});
module.exports = app;
| JavaScript | 0.000001 | @@ -2628,16 +2628,72 @@
ext) %7B%0A%0A
+ res.locals.user = %7B%7D;%0A res.locals.userDomains = %7B%7D;%0A%0A
user.g
@@ -2829,16 +2829,77 @@
ext();%0A%0A
+ %7D).catch(function (e) %7B%0A%0A logger.error(e);%0A next();%0A%0A
%7D);%0A%0A%7D
|
41bdb5005515b673f4dac32e264657705b67e2ff | Fix outputdir resolution | markdown2bootstrap.js | markdown2bootstrap.js | #!/usr/bin/env node
/*jshint node:true, es5:true */
var argv = require('optimist').
usage('Usage: $0 [options] <doc.md ...>').
demand(1).
boolean('n').
describe('n', 'Turn off numbered sections').
boolean('h').
describe('h', 'Turn on bootstrap page header.').
describe('outputdir', 'Directory to put the converted files in.').
default('outputdir', '.').
argv,
pagedown = require('pagedown'),
converter = new pagedown.Converter(),
path = require('path'),
fs = require('fs'),
top_part = fs.readFileSync(__dirname + "/parts/top.html").toString(),
bottom_part = fs.readFileSync(__dirname + "/parts/bottom.html").toString(),
levels, toc, nextId;
function findTag(md, tag, obj) {
var re = new RegExp("^<!-- " + tag + ": (.+) -->", "m"), match = md.match(re);
if (!obj) { return; }
if (match) {
obj[tag] = match[1];
}
}
// Configure section and toc generation
converter.hooks.set("postConversion", function(text) {
return text.replace(/<(h(\d))>/g, function(match, p1, p2, offset, str) {
var i, levelStr = "";
levels[p1] = levels[p1] || 0;
// Figure out section number
if (!argv.n) {
// reset lower levels
for (i = Number(p2) + 1; levels["h"+i]; i++) {
levels["h"+i] = 0;
}
// grab higher levels
for (i = Number(p2) - 1; levels["h"+i]; i--) {
levelStr = levels["h"+i] + "." + levelStr;
}
levels[p1] = levels[p1] + 1;
levelStr = levelStr + levels[p1] + ". ";
}
// Add toc entry
toc.push({
levelStr: levelStr,
id: ++nextId,
title: str.slice(offset+4, str.slice(offset).indexOf("</h")+offset)
});
return "<h" + p2 + ' id="' + nextId + '">' + levelStr;
}).replace(/<pre>/g, '<pre class="prettyprint">');
});
// Create output directory
if (!fs.existsSync('html')) {
fs.mkdirSync('html');
}
argv._.forEach(function(md_path) {
var tags = { title: "TITLE HERE", subtitle: "SUBTITLE HERE" },
md, output, tocHtml = "",
output_path = path.join(argv.outputdir, path.basename(md_path));
// Determine output filename
if (/\.md$/.test(output_path)) {
output_path = output_path.slice(0, -3);
}
output_path += '.html';
// Read markdown in
md = fs.readFileSync(md_path).toString();
// Find title and subtitle tags in document
findTag(md, "title", tags);
findTag(md, "subtitle", tags);
levels = {}; nextId = 0; toc = [];
output = converter.makeHtml(md);
// Add table of contents
tocHtml += '<div class="span3 bs-docs-sidebar"><ul class="nav nav-list bs-docs-sidenav" data-spy="affix">';
toc.forEach(function(entry) {
tocHtml += '<li><a href="#' + entry.id + '">' + entry.levelStr + entry.title + '</a></li>';
});
tocHtml += '</ul></div><div class="span9">';
// Bootstrap-fy
output =
top_part.replace(/\{\{header\}\}/, function() {
if (argv.h) {
return '<header class="jumbotron subhead" id="overview">' +
'<div class="container">' +
'<h1>' + tags.title + '</h1>' +
'<p class="lead">' + tags.subtitle + '</p>' +
'</div></header>';
} else {
return "";
}
}).replace(/\{\{title\}\}/, tags.title === "TITLE HERE" ? "" : tags.title) +
tocHtml +
output +
bottom_part;
fs.writeFileSync(output_path, output);
console.log("Converted " + md_path + " to " + output_path);
});
| JavaScript | 0.000213 | @@ -2006,16 +2006,78 @@
rectory%0A
+argv.outputdir = path.resolve(process.cwd(), argv.outputdir);%0A
if (!fs.
@@ -2087,22 +2087,30 @@
stsSync(
-'html'
+argv.outputdir
)) %7B%0A
@@ -2127,14 +2127,22 @@
ync(
-'html'
+argv.outputdir
);%0A%7D
@@ -3809,16 +3809,45 @@
%22 to %22 +
+ path.relative(process.cwd(),
output_
@@ -3851,14 +3851,15 @@
ut_path)
+)
;%0A%7D);%0A
|
90d7109029d8887b97be6e3f879246fb30f156c8 | Use registerRootComponent directly (#6008) | packages/expo/AppEntry.js | packages/expo/AppEntry.js | import { registerRootComponent } from 'expo';
import { activateKeepAwake } from 'expo-keep-awake';
import App from '../../App';
if (__DEV__) {
activateKeepAwake();
}
registerRootComponent(App);
| JavaScript | 0 | @@ -1,16 +1,14 @@
import
- %7B
registe
@@ -21,18 +21,16 @@
omponent
- %7D
from 'e
@@ -32,16 +32,51 @@
om 'expo
+/build/launch/registerRootComponent
';%0Aimpor
|
5d47fbdd5768461e57f3ee9bb6748decc14bf736 | use wildcards | packages/gi-pkg/src/ls.js | packages/gi-pkg/src/ls.js | import glob from 'glob'
import { exclude } from './config.json'
export default async (dir, ignore = []) => {
return new Promise(resolve => {
glob('**',
{ignore: [...ignore, ...exclude], cwd: dir, follow: false},
(err, files) => {
files = err ? null : files
resolve(files)
}
)
})
}
| JavaScript | 0.000001 | @@ -148,17 +148,16 @@
glob('*
-*
',%0A
|
3a1af2a204cd2ade83d15497f7a86e903f56ffa4 | Add Mongo export | packages/mongo/package.js | packages/mongo/package.js | // XXX We should revisit how we factor MongoDB support into (1) the
// server-side node.js driver [which you might use independently of
// livedata, after all], (2) minimongo [ditto], and (3) Collection,
// which is the class that glues the two of them to Livedata, but also
// is generally the "public interface for newbies" to Mongo in the
// Meteor universe. We want to allow the components to be used
// independently, but we don't want to overwhelm the user with
// minutiae.
Package.describe({
summary: "Adaptor for using MongoDB and Minimongo over DDP",
version: '1.0.3'
});
Npm.depends({
mongodb: "https://github.com/meteor/node-mongodb-native/tarball/cbd6220ee17c3178d20672b4a1df80f82f97d4c1"
});
Package.on_use(function (api) {
api.use(['random', 'ejson', 'json', 'underscore', 'minimongo', 'logging',
'ddp', 'tracker', 'application-configuration'],
['client', 'server']);
api.use('check', ['client', 'server']);
// Binary Heap data structure is used to optimize oplog observe driver
// performance.
api.use('binary-heap', 'server');
// Allow us to detect 'insecure'.
api.use('insecure', {weak: true});
// Allow us to detect 'autopublish', and publish collections if it's loaded.
api.use('autopublish', 'server', {weak: true});
// Allow us to detect 'disable-oplog', which turns off oplog tailing for your
// app even if it's configured in the environment. (This package will be
// probably be removed before 1.0.)
api.use('disable-oplog', 'server', {weak: true});
// defaultRemoteCollectionDriver gets its deployConfig from something that is
// (for questionable reasons) initialized by the webapp package.
api.use('webapp', 'server', {weak: true});
// If the facts package is loaded, publish some statistics.
api.use('facts', 'server', {weak: true});
api.use('callback-hook', 'server');
// Stuff that should be exposed via a real API, but we haven't yet.
api.export('MongoInternals', 'server');
// For tests only.
api.export('MongoTest', 'server', {testOnly: true});
api.add_files(['mongo_driver.js', 'oplog_tailing.js',
'observe_multiplex.js', 'doc_fetcher.js',
'polling_observe_driver.js','oplog_observe_driver.js'],
'server');
api.add_files('local_collection_driver.js', ['client', 'server']);
api.add_files('remote_collection_driver.js', 'server');
api.add_files('collection.js', ['client', 'server']);
});
Package.on_test(function (api) {
api.use('mongo');
api.use('check');
api.use(['tinytest', 'underscore', 'test-helpers', 'ejson', 'random',
'ddp']);
// XXX test order dependency: the allow_tests "partial allow" test
// fails if it is run before mongo_livedata_tests.
api.add_files('mongo_livedata_tests.js', ['client', 'server']);
api.add_files('allow_tests.js', ['client', 'server']);
api.add_files('collection_tests.js', ['client', 'server']);
api.add_files('observe_changes_tests.js', ['client', 'server']);
api.add_files('oplog_tests.js', 'server');
api.add_files('doc_fetcher_tests.js', 'server');
});
| JavaScript | 0 | @@ -2047,32 +2047,55 @@
estOnly: true%7D);
+%0A api.export(%22Mongo%22);
%0A%0A api.add_file
|
064535a6f91460ce89f063497af8f9bbff8854c2 | Fix postcss config | packages/postcss/index.js | packages/postcss/index.js | /**
* PostCSS webpack block.
*
* @see https://github.com/postcss/postcss-loader
*/
module.exports = postcss
/**
* @param {PostCSSPlugin[]} [plugins] Will read `postcss.config.js` file if not supplied.
* @param {object} [options]
* @param {RegExp|Function|string} [options.exclude] Directories to exclude.
* @param {string} [options.parser] Package name of custom PostCSS parser to use.
* @param {string} [options.stringifier] Package name of custom PostCSS stringifier to use.
* @param {string} [options.syntax] Package name of custom PostCSS parser/stringifier to use.
* @return {Function}
*/
function postcss (plugins, options) {
plugins = plugins || []
options = options || {}
// https://github.com/postcss/postcss-loader#options
const postcssOptions = Object.assign(
{},
options.parser && { parser: options.parser },
options.stringifier && { stringifier: options.stringifier },
options.syntax && { syntax: options.syntax }
)
return (context) => Object.assign(
{
module: {
loaders: [
Object.assign({
test: context.fileType('text/css'),
loaders: [ 'style-loader', 'css-loader', 'postcss-loader?' + JSON.stringify(postcssOptions) ]
}, options.exclude ? {
exclude: Array.isArray(options.exclude) ? options.exclude : [ options.exclude ]
} : {})
]
}
},
plugins ? createPostcssPluginsConfig(context.webpack, plugins) : {}
)
}
function createPostcssPluginsConfig (webpack, plugins) {
const isWebpack2 = typeof webpack.validateSchema !== 'undefined'
if (isWebpack2) {
return {
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
postcss: plugins,
// Hacky fix for a strange issue involving the postcss-loader, sass-loader and webpack@2
// (see https://github.com/andywer/webpack-blocks/issues/116)
// Might be removed again once the `sass` block uses a newer `sass-loader`
context: '/'
}
})
]
}
} else {
return {
postcss: plugins
}
}
}
| JavaScript | 0.000001 | @@ -1494,16 +1494,27 @@
plugins
+.length %3E 0
? creat
|
cbd3b68d7247b1de514fdf3bdad5e8a339b6bfc1 | Fix double-sending of runs request. | wandb/board/ui/src/subscriptions.js | wandb/board/ui/src/subscriptions.js | import watch from 'redux-watch';
import {RUNS_QUERY} from './graphql/runs';
import {matchPath} from 'react-router';
import {setFlash} from './actions';
let unsubscribe, runsChannel;
try {
const p = require('Cloud/util/pusher');
unsubscribe = p.unsubscribe;
runsChannel = p.runsChannel;
} catch (e) {
const p = require('./util/pusher');
unsubscribe = p.unsubscribe;
runsChannel = p.dummyChannel;
}
const SUBSCRIPTION_COOLDOWN = 20000;
function matchProject(path) {
return matchPath(path, '/:entity/:project') || {params: {}};
}
function project(path) {
return matchProject(path).params.project;
}
function updateRunsQuery(store, client, queryVars, payloads) {
//console.time('updating runs');
const state = store.getState();
//Ensure we do the initial query
const data = client.readQuery({
query: RUNS_QUERY,
variables: queryVars,
}),
edges = data.model.buckets.edges;
for (var payload of payloads) {
const sameUser = payload.user.username === state.global.user.entity;
if (payload.state !== 'running' && sameUser) {
//TODO: fix the finished hack
//TODO: only dispatch if the run belongs to me
//TODO: figure out why Lukas has his run marked as failed
if (payload.state === 'failed') {
console.log('failed run');
//store.dispatch(setFlash({message: 'Run Failed', color: 'red'}));
} else {
store.dispatch(setFlash({message: 'Run Finished', color: 'green'}));
}
}
let node;
if (edges[0]) {
node = Object.assign({}, edges[0].node, payload);
} else {
//TODO: Because I couldn't figure out how to modify the store, we just reload on the first run
window.location.reload(true);
}
let idx = edges.findIndex(e => e.node.id === node.id);
let del = 0;
if (idx >= 0) del = 1;
else {
idx = 0;
if (sameUser) {
store.dispatch(setFlash({message: 'New run started', color: 'blue'}));
}
}
edges.splice(idx, del, {node, __typename: node.__typename});
}
client.writeQuery({
query: RUNS_QUERY,
variables: queryVars,
data,
});
//console.timeEnd('updating runs');
}
export default (store, client) => {
const projectChange = watch(
store.getState,
'router.location.pathname',
(cur, next) => {
return project(cur) === project(next);
},
),
slug = params => {
return `${params.entity}@${params.project}`;
};
store.subscribe(
projectChange((newPath, oldPath) => {
//TODO: global order state?
const newParams = matchProject(newPath).params,
oldParams = matchProject(oldPath).params,
vars = {
entityName: newParams.entity,
name: newParams.project,
order: 'timeline',
};
if (oldParams.project) {
unsubscribe('runs-' + slug(oldParams));
}
if (
newParams.project &&
['teams', 'admin'].indexOf(newParams.entity) < 0 &&
['new', 'projects'].indexOf(newParams.project) < 0
) {
let queuedPayloads = [];
let nextTimeout = null;
let lastSubmitTime = 0;
//Ensure we do the initial query
client
.query({
query: RUNS_QUERY,
variables: vars,
})
.then(() => {
runsChannel(slug(newParams)).bind('updated', payload => {
// We had a performance problem here where too frequent
// updates caused the page to hang. Now we queue them up if
// we're within a cooldown period, and do a single page update
// for the whole batch.
queuedPayloads.push(payload);
let now = new Date().getTime();
if (now - lastSubmitTime > SUBSCRIPTION_COOLDOWN) {
updateRunsQuery(store, client, vars, queuedPayloads);
if (nextTimeout !== null) {
clearTimeout(nextTimeout);
}
lastSubmitTime = now;
queuedPayloads = [];
nextTimeout = null;
} else {
if (nextTimeout === null) {
nextTimeout = setTimeout(() => {
updateRunsQuery(store, client, vars, queuedPayloads);
lastSubmitTime = new Date().getTime();
queuedPayloads = [];
nextTimeout = null;
}, SUBSCRIPTION_COOLDOWN);
}
}
});
});
}
}),
);
};
| JavaScript | 0.000001 | @@ -2773,24 +2773,58 @@
'timeline',%0A
+ requestSubscribe: true,%0A
%7D;%0A
|
8e96027e7027844604a7ff1f3186aec6a418aba0 | fix wiredep / injectScripts conflict | templates/tasks/dev.js | templates/tasks/dev.js | 'use strict';
/* jshint camelcase: false */
var config = require('./config');
var gulp = require('gulp');
/**
* Dev Task File
*
*/
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var wiredep = require('wiredep').stream;
var inj = require('gulp-inject');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var watch = require('gulp-watch');
var runSequence = require('run-sequence').use(gulp);
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var karma = require('gulp-karma');
var webdriver_standalone = require('gulp-protractor').webdriver_standalone;
var protractor = require('gulp-protractor').protractor;
gulp.task('webdriver_standalone', webdriver_standalone);
function swallowError(error)
{
console.log(error.toString());
this.emit('end');
}
// main task
gulp.task('default', function ()
{
runSequence(
'injectAll',
'buildStyles',
'browserSync',
'test',
'watch'
);
});
gulp.task('serve', ['default']);
gulp.task('server', ['default']);
gulp.task('injectAll', function ()
{
runSequence(
'wiredep',
'injectScripts',
'injectStyles'
);
});
gulp.task('watch', function ()
{
watch(config.stylesF, function ()
{
gulp.start('buildStyles');
});
watch(config.scriptsF, function ()
{
gulp.start('injectScripts');
});
watch(config.scriptsAllF, function ()
{
gulp.start('lint');
});
watch(config.allHtmlF, function ()
{
gulp.start('html');
});
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('buildStyles', function ()
{
runSequence(
'injectStyles',
'sass'
);
});
gulp.task('injectStyles', function ()
{
var sources = gulp.src(config.stylesF, {read: false});
var target = gulp.src(config.mainSassFile);
var outputFolder = gulp.dest(config.styles);
target
.pipe(inj(sources,
{
starttag: '// inject:sass',
endtag: '// endinject',
ignorePath: [config.base.replace('./', ''), 'styles'],
relative: true,
addRootSlash: false,
transform: function (filepath)
{
if (filepath) {
return '@import \'' + filepath + '\';';
}
}
}
))
.pipe(outputFolder);
});
gulp.task('injectScripts', function ()
{
var sources = gulp.src(config.scriptsF, {read: false});
var target = gulp.src(config.mainFile);
target
.pipe(inj(sources,
{
ignorePath: config.base.replace('./', ''),
addRootSlash: false
}
))
.pipe(gulp.dest(config.base))
.pipe(reload({stream: true}));
});
gulp.task('sass', function ()
{
var sources = gulp.src(config.mainSassFile);
var outputFolder = gulp.dest(config.styles);
sources
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(sourcemaps.write())
.pipe(outputFolder)
.pipe(reload({stream: true}))
.on('error', swallowError)
});
gulp.task('browserSync', function ()
{
browserSync({
server: {
baseDir: config.base,
livereload: true
}
});
});
gulp.task('html', function ()
{
gulp.src(config.allHtmlF)
.pipe(reload({stream: true}));
});
gulp.task('wiredep', function ()
{
gulp.src([config.mainFile], {base: './'})
.pipe(wiredep({
exclude: [],
devDependencies: false
}))
.pipe(gulp.dest('./'));
gulp.src([config.karmaConf], {base: './'})
.pipe(wiredep({
exclude: [],
devDependencies: true
}))
.pipe(gulp.dest('./'));
});
gulp.task('test', function ()
{
// Be sure to return the stream
gulp.src('.nonononoNOTHING')
.pipe(karma({
configFile: './karma.conf.js',
action: 'watch'
}))
.on('error', function (err)
{
throw err;
})
.on('error', swallowError);
});
gulp.task('testSingle', function ()
{
// Be sure to return the stream
gulp.src('.nonononoNOTHING')
.pipe(karma({
configFile: './karma.conf.js',
action: 'run'
}))
.on('error', function (err)
{
throw err;
});
});
gulp.task('protractor', function ()
{
// Be sure to return the stream
gulp.src('.nonononoNOTHING')
.pipe(protractor({
configFile: './karma-e2e.conf.js',
args: ['--baseUrl', e2eBaseUrl]
}))
.on('error', function (e)
{
throw e;
});
});
gulp.task('lint', function ()
{
gulp.src([
config.scriptsAllF,
'./karma-e2e.conf.js',
'./karma.conf.js',
'./gulpfile.js'
])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jscs());
});
gulp.task('e2e', [
'browserSync',
'protractor'
]);
| JavaScript | 0 | @@ -387,21 +387,16 @@
reload
-
= browse
@@ -409,16 +409,16 @@
reload;%0A
+
var watc
@@ -607,197 +607,8 @@
');%0A
-var webdriver_standalone = require('gulp-protractor').webdriver_standalone;%0Avar protractor = require('gulp-protractor').protractor;%0Agulp.task('webdriver_standalone', webdriver_standalone);%0A
%0A%0Afu
@@ -797,32 +797,48 @@
'buildStyles',%0A
+ 'test',%0A
'browser
@@ -844,32 +844,16 @@
rSync',%0A
- 'test',%0A
@@ -964,32 +964,40 @@
All', function (
+callback
)%0A%7B%0A runSeque
@@ -1067,16 +1067,34 @@
tStyles'
+,%0A callback
%0A );%0A
@@ -2728,46 +2728,8 @@
se))
-%0A .pipe(reload(%7Bstream: true%7D))
;%0A%7D)
@@ -3530,33 +3530,8 @@
p(%7B%0A
- exclude: %5B%5D,%0A
@@ -3603,16 +3603,54 @@
t('./'))
+%0A .pipe(reload(%7Bstream: true%7D))
;%0A%0A g
@@ -3719,33 +3719,8 @@
p(%7B%0A
- exclude: %5B%5D,%0A
@@ -4426,328 +4426,8 @@
);%0A%0A
-%0Agulp.task('protractor', function ()%0A%7B%0A // Be sure to return the stream%0A gulp.src('.nonononoNOTHING')%0A .pipe(protractor(%7B%0A configFile: './karma-e2e.conf.js',%0A args: %5B'--baseUrl', e2eBaseUrl%5D%0A %7D))%0A .on('error', function (e)%0A %7B%0A throw e;%0A %7D);%0A%7D);%0A%0A
gulp
@@ -4686,69 +4686,8 @@
));%0A
+
%7D);%0A
-%0A%0Agulp.task('e2e', %5B%0A 'browserSync',%0A 'protractor'%0A%5D);%0A
|
9f27374b878b0f611062e0d78d4d03b0349f9860 | Make project dialog stop propagation | templates/js/pages/sidebar.js | templates/js/pages/sidebar.js | $(function() {
$('button.atp').prop('title', 'Add/Remove to/from Project').button({ icons: { primary: 'ui-icon-note' }, text: false }).unbind('click').click(function() {
_load_project_dialog($(this).attr('ty'), $(this).attr('iid'), $(this).attr('name'))
})
var c = $.cookie('ispyb_help')
var help_def = ($(window).width() <= 800) ? 0 : 1
var help = c === undefined ? help_def : c
$('[title]').each(function(i,e) {
$(e).attr('t_old', $(e).attr('title'))
})
$.editable.addInputType('autocomplete', {
element : $.editable.types.text.element,
plugin : function(settings, original) {
$('input', this).autocomplete(settings.autocomplete);
}
})
/*$('.current').editable('/proposal/ajax/set/', {
type: 'autocomplete',
autocomplete: { source: '/proposal/ajax/p/' },
name: 'prop',
width: '60px',
submit: 'Ok',
style: 'display: inline',
placeholder: 'Click to Select',
//onblur: 'ignore',
callback: function() { window.location.href = '/proposal/visits' },
}).addClass('editable');*/
//$('#sidebar a.pull').click(function() {
// $('#sidebar ul').slideToggle()
//})
$('a.pull').addClass('enable').click(function() { $('body').toggleClass('active'); return false })
$('#sidebar ul li.help a').click(function() {
help = help == 1 ? 0 : 1;
$.cookie('ispyb_help', help);
_toggle_help()
return false;
})
function _toggle_help() {
if (help == 1) {
$('#sidebar ul li.help').addClass('active')
$('[title]').tipTip({delay:100, fadeIn: 400, defaultPosition: 'top'})
$('[t_old]').each(function(i,e) { $(e).data('tt_disable', false) })
$('p.help').fadeIn()
} else {
$('#sidebar ul li.help').removeClass('active')
$('[t_old]').each(function(i,e) { $(e).data('tt_disable', true) })
$('p.help').fadeOut()
}
}
_toggle_help()
$(document).ajaxComplete(function() {
$('button.atp').prop('title', 'Add/Remove to/from Project').button({ icons: { primary: 'ui-icon-note' }, text: false }).unbind('click').click(function() {
_load_project_dialog($(this).attr('ty'), $(this).attr('iid'), $(this).attr('name'))
})
$('[title]').each(function(i,e) {
$(e).attr('t_old', $(e).attr('title'))
})
_toggle_help()
})
// Add to project popup
$('.project').dialog({ title: 'Add To Project', autoOpen: false, height: 'auto', width: 'auto' });
$('.project select[name=pid]').change(function() { _check_project_item })
// Check whether item is already in project, show add / remove button as needed
function _check_project_item() {
var pid = $('.project select[name=pid]').val()
var ty = $('.project').attr('ty')
var id = $('.project').attr('pid')
$.ajax({
url: '/projects/ajax/check/ty/'+ty+'/pid/'+pid+'/iid/'+id,
type: 'GET',
dataType: 'json',
timeout: 5000,
success: function(r) {
var btns = {}
btns[(r ? 'Remove' : 'Add')] = function() {
if (pid && ty && id) {
$.ajax({
url: '/projects/ajax/addto/pid/'+pid+'/ty/'+ty+'/iid/'+id+(r ? '/rem/1' : ''),
type: 'GET',
dataType: 'json',
timeout: 5000,
success: function(r){
$('.project').dialog('close')
}
})
}
}
btns['Close'] = function() { $(this).dialog('close') }
$('.project').dialog('option', 'buttons', btns)
$('.project').dialog('option', 'title', r ? 'Remove From Project' : 'Add To Project')
}
})
}
// Show add to project popup
function _load_project_dialog(ty, id, name) {
$('.project').attr('ty', ty)
$('.project').attr('pid', id)
$('.project span.title').html(name)
$.ajax({
url: '/projects/ajax/array/1',
type: 'GET',
dataType: 'json',
timeout: 5000,
success: function(r){
$('.project select[name=pid]').empty()
$.each(r, function(p,t) {
$('<option value="'+p+'">'+t+'</option>').appendTo($('.project select[name=pid]'))
})
_check_project_item()
$('.project').dialog('open')
}
})
}
})
| JavaScript | 0.000001 | @@ -2168,32 +2168,33 @@
.click(function(
+e
) %7B%0A _load_
@@ -2267,24 +2267,51 @@
tr('name'))%0A
+ e.stopPropagation();%0A
%7D)%0A
|
ac0276035a6f3afe9428bf354d90cbdc2dd2c8db | Remove accidental duplication of subscribe method. | terrific-extensions.js | terrific-extensions.js | /**
* https://github.com/MarcDiethelm/terrificjs-extensions
* Adds some sugar and enhancements to @brunschgi's excellent Terrificjs frontend framework.
*/
'use strict';
/**
* Simplify connector channel subscription
*
* Because the second parameter to sandbox.subscribe() (this) often is forgotten.
* Plus, connecting to multiple channels requires you to call subscribe for every channel.
* @author Simon Harte <simon.harte@namics.com>
* @param {...string} channels - Connector channels to subscribe to
*/
Tc.Module.prototype.subscribe = function subscribe(channels) {
var i = 0,
args = arguments,
argLen = args.length,
channelName
;
for (i; i < argLen; i++) {
channelName = channels[i];
this.sandbox.subscribe(channelName, this);
}
return true;
};
/**
* Select elements in the module context. Usage: this.$$(selector)
* @author Marc Diethelm <marc.diethelm@namics.com>
* @param {string} selector
* @returns {object} – jQuery collection
*
*/
Tc.Module.prototype.$$ = function $$(selector) {
return this.$ctx.find(selector);
};
/**
* Bind methods to Terrific module context. Usage: this.bindAll(funcName [,funcName...])
* @author Marc Diethelm <marc.diethelm@namics.com>
* @author Simon Harte <simon.harte@namics.com>
* @param {...string} methods - Names of methods each as a param.
* @return {boolean|undefined} - Returns true if binding succeeds, throws an exception otherwise.
*/
Tc.Module.prototype.bindAll = function bindAll(methods) {
var i = 0,
args = arguments,
argLen = args.length,
methodName
;
for (i; i < argLen; i++) {
methodName = args[i];
if (typeof this[methodName] === 'function') {
this[methodName] = jQuery.proxy(this, methodName);
}
else {
throw new TypeError('Tc.Module.' + this.getName() + '.' + methodName + ' is not a function');
}
}
return true;
};
/**
* Get the name of the Terrific module
* @author Remo Brunschwiler <remo.brunschwiler@namics.com>
* @author Mathias Hayoz <mathias.hayoz@namics.com>
* @returns {string} – Module name
*/
Tc.Module.prototype.getName = function getName() {
var property;
if (!this._modName) {
findMod: for (property in Tc.Module) {
if (Tc.Module.hasOwnProperty(property) && property !== 'constructor' && this instanceof Tc.Module[property]) {
this._modName = property;
break findMod;
}
}
}
return this._modName;
};
/**
* Simplify connector channel subscription
*
* Because the second parameter to sandbox.subscribe() (this) often is forgotten.
* Plus, connecting to multiple channels requires you to call subscribe for every channel.
* @author Simon Harte <simon.harte@namics.com>
* @param {...string} channels - Connector channels to subscribe to
*/
Tc.Module.prototype.subscribe = function subscribe(channels) {
var i = 0,
args = arguments,
argLen = args.length,
channelName
;
for (i; i < argLen; i++) {
channelName = channels[i];
this.sandbox.subscribe(channelName, this);
}
return true;
};
(function () {
var cache = {};
/**
* Micro-templating for modules. Extrapolates {{= foo }} variables in strings from data.
* This function is a remix of
* - Simple JavaScript Templating – John Resig - http://ejohn.org/ - MIT Licensed
* - https://gist.github.com/topliceanu/1537847
* - http://weblog.west-wind.com/posts/2008/Oct/13/Client-Templating-with-jQuery
* This code incorporates a fix for single-quote usage.
* @author Marc Diethelm <marc.diethelm@namics.com>
* @param {string} str - Template
* @param {object} [data] – Optional, renders template immediately if present. Data to use as the template context for variable extrapolation.
* @returns {function|string} - Template function, to render template with data, or if data was supplied already the rendered template.
*/
Tc.Module.prototype.template = function template(str, data) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
template(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
/*jshint -W054, -W014 */
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^%]*\}\}>)/g, "\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/\{\{=(.+?)\}\}/g, "',$1,'")
.split("{{").join("');")
.split("}}").join("p.push('")
+ "');}return p.join('');");
/*jshint +W054, +W014 */
// Provide some basic currying to the user
return data ? fn(data) : fn;
};
})();
| JavaScript | 0.000001 | @@ -171,612 +171,8 @@
';%0A%0A
-/**%0A * Simplify connector channel subscription%0A *%0A * Because the second parameter to sandbox.subscribe() (this) often is forgotten.%0A * Plus, connecting to multiple channels requires you to call subscribe for every channel.%0A * @author Simon Harte %3Csimon.harte@namics.com%3E%0A * @param %7B...string%7D channels - Connector channels to subscribe to%0A */%0ATc.Module.prototype.subscribe = function subscribe(channels) %7B%0A%09var i = 0,%0A%09%09args = arguments,%0A%09%09argLen = args.length,%0A%09%09channelName%0A%09;%0A%0A%09for (i; i %3C argLen; i++) %7B%0A%09%09channelName = channels%5Bi%5D;%0A%0A%09%09this.sandbox.subscribe(channelName, this);%0A%09%7D%0A%09return true;%0A%7D;%0A%0A
/**%0A
|
2763fdd4562eb9fd5b66e8a8ab3242f4faebbc3c | Make plugin work when called on multiple selects | src/jquery.combostars.js | src/jquery.combostars.js | /**
* jquery.combostars.js: Turn select widgets into star rating widgets.
*
* Copyright (c) 2015 John Parsons.
*
* This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details.
*/
$(function () {
/**
* Determines the needed background position for a star with the specified height and fill state.
*
* @param starHeight the height of a star, in px.
* @param isFilled whether or not the star image is filled in.
*/
var getBackgroundPosition = function (starHeight, isFilled) {
return '0 ' + (isFilled ? '0' : '-' + (starHeight) + 'px');
};
$.fn.combostars = function (config) {
'use strict';
var options = {
starUrl: '../src/img/stars.png',
starWidth: 16,
starHeight: 15
};
$.extend(options, config);
var numStars = this.children().length, // Number of stars = number of options in the combo box
wrapper = $('<span />').addClass('combostar-wrapper'), // Wrapper for the stars
i, // Counter variable
newStar, // Newly created star
select = this; // The select that combostars() is called on
/** Handles a click on a star. Updates the value of the combo box and sets view state. */
var starClickHandler = function () {
var clickedStar = $(this).data('star-index'),
newValue = select.find('option:nth-child(' + clickedStar + ')').attr('value');
select.val(newValue);
select.change();
// Update star backgrounds
wrapper.find('.combostar-star').each(function () {
$(this).css('background-position', getBackgroundPosition(options.starHeight, $(this).data('star-index') <= clickedStar));
});
};
wrapper = this.wrap(wrapper).parent(); // Wrap the widget with a star container
this.hide(); // Hide the combobox so we can show the star widget
// Add all the stars to the container
for (i = 1; i <= numStars; i++) {
newStar = $('<div />').css({
display: 'inline',
'padding-left' : options.starWidth + 'px', // Use padding to set the width and height
'padding-top' : options.starHeight + 'px',
'padding-right': 0,
'padding-bottom' : 0,
'background-image' : 'url(' + options.starUrl + ')', // Image to display as the star
'background-position' : getBackgroundPosition(options.starHeight, false),
'font-size' : 0 // Setting font size to 0 allows us to set the height exclusively with padding
}).addClass('combostar-star')
.data('star-index', i)
.on('click', starClickHandler);
wrapper.append(newStar);
}
};
}); | JavaScript | 0 | @@ -665,16 +665,207 @@
rict';%0A%0A
+%09%09// Deal with multiple selects by recursively applying combostars to each one%0A%09%09if (this.length %3E 1) %7B%0A%09%09%09this.each(function () %7B%0A%09%09%09%09$(this).combostars(config);%0A%09%09%09%7D);%0A%09%09%09return this;%0A%09%09%7D%0A%0A
%09%09var op
@@ -2679,16 +2679,32 @@
ar);%0A%09%09%7D
+%0A%0A%09%09return this;
%0A%09%7D;%0A%7D);
|
a44c54fb5e948ac4fa9baf1f88f2da047c401e90 | Make sure I'm not a liar. | test/3-complex.test.js | test/3-complex.test.js | const Proxy = require('..')
const test = require('tap').test
const testServer = require('./server')
const testRequest = require('./request')
const localSocket = require('./localSocket')
test('proxy server: simple routing', function (t) {
const servers = {
food: makeServer('food'),
music: makeServer('music'),
dot: makeServer('dotpath'),
default: makeServer('default'),
}
const proxySocket = localSocket('proxy-test.socket')
const serverDefs = [
['test.localhost', [
['/food/*', servers.food.socket],
['/music/*', servers.music.socket],
['/.*', servers.dot.socket],
['*', servers.default.socket],
]],
]
const proxy = new Proxy({ servers: serverDefs })
const gateway = proxy
.createServer()
.listen(proxySocket)
gateway.unref()
t.plan(4)
testRequest({
socketPath: proxySocket,
path: '/food/sandwiches/blt',
host: 'test.localhost',
method: 'GET',
}, function (proxyRes) {
t.same(proxyRes.socketPath, servers.food.socket, 'should food')
})
testRequest({
socketPath: proxySocket,
path: '/music/himalaya/',
host: 'test.localhost',
method: 'GET',
}, function (proxyRes) {
t.same(proxyRes.socketPath, servers.music.socket, 'should music')
})
testRequest({
socketPath: proxySocket,
path: '/.link',
host: 'test.localhost',
method: 'GET',
}, function (proxyRes) {
t.same(proxyRes.socketPath, servers.dot.socket, 'should dot')
})
testRequest({
socketPath: proxySocket,
path: '/literally/anything/else',
host: 'test.localhost',
method: 'GET',
}, function (proxyRes) {
t.same(proxyRes.socketPath, servers.default.socket, 'should default')
})
})
function makeServer(name) {
return testServer(localSocket(name + '.socket'))
}
| JavaScript | 0.000248 | @@ -256,20 +256,20 @@
= %7B%0A
-food
+json
: makeSe
@@ -278,20 +278,20 @@
er('
-food
+json
'),%0A
musi
@@ -286,21 +286,19 @@
'),%0A
-music
+xml
: makeSe
@@ -303,21 +303,19 @@
Server('
-music
+xml
'),%0A
@@ -500,14 +500,18 @@
%5B'/
-food/*
+api/*.json
', s
@@ -513,28 +513,28 @@
n', servers.
-food
+json
.socket%5D,%0A
@@ -544,15 +544,17 @@
%5B'/
-music/*
+api/*.xml
', s
@@ -556,29 +556,27 @@
l', servers.
-music
+xml
.socket%5D,%0A
@@ -872,27 +872,22 @@
: '/
-food/sandwiches/blt
+api/x/y/z.json
',%0A
@@ -999,20 +999,20 @@
servers.
-food
+json
.socket,
@@ -1024,12 +1024,12 @@
uld
-food
+json
')%0A
@@ -1094,23 +1094,35 @@
: '/
-music/himalaya/
+api/v2/lol/rattleskates.xml
',%0A
@@ -1234,21 +1234,19 @@
servers.
-music
+xml
.socket,
@@ -1258,13 +1258,11 @@
uld
-music
+xml
')%0A
|
91feaa9630295b818352b7520d8a5bdee57a233b | Change JSXTransformer URL to non-fb link | kboard/kboard-html5/js/main.js | kboard/kboard-html5/js/main.js | requirejs.config({
"baseUrl": "./",
"paths": {
"jquery":"bower_components/jquery/jquery.min",
"jquery-ui":"bower_components/jquery-ui/ui/jquery-ui",
"react": "bower_components/react/react.min",
"jsx":"bower_components/require-jsx/jsx",
"JSXTransformer":"http://dragon.ak.fbcdn.net/hphotos-ak-prn1/851547_221914424655081_22271_n",
"kboard.client": '/api/client'
},
"shim": {
JSXTransformer: {
exports: "JSXTransformer"
},
'kboard.client': {
exports: 'KboardRestClient'
}
}
});
define(['jquery', 'react','kboard.client', 'js/data'],
function($, React, KboardRestClient, Data) {
KboardRestClient.authenticate(function (data, err) {
if(data == true && err == undefined) {
// successful login. Render board app
require(['jsx!js/board/app'], function(BoardApplication) {
Data.getData(function (data) {
React.renderComponent(
BoardApplication({'data': data}),
document.getElementById('content'));
});
});
/*
require(['jsx!js/dashboard'], function(Dashboard) {
React.renderComponent(
Dashboard(), document.getElementById('content'));
});
*/
}else{
// failed login. Render login app.
require(['jsx!js/login'], function(Login) {
React.renderComponent(
Login(), document.getElementById('content'));
});
}
});
}
);
| JavaScript | 0 | @@ -275,81 +275,67 @@
r%22:%22
-http://dragon.ak.fbcdn.net/hphotos-ak-prn1/851547_221914424655081_22271_n
+//cdnjs.cloudflare.com/ajax/libs/react/0.8.0/JSXTransformer
%22,%0A
|
c69aa18c25e57df5a451b0a7a99388a5c692634f | Fix link controllers not sending energy to each other | LinkController.js | LinkController.js | module.exports = {
decide: function(link) {
if(!link.memory.type) {
if(link.pos.findInRange(FIND_SOURCES, 2).length) {
link.memory.type = "dispatch";
} else {
link.memory.type = "recieve";
}
}
if(link.energy) {
var closeBuilders = [];
Memory.roleList.Builder.forEach(function(name) {
var builder = Game.creeps[name];
if(link.pos.isNearTo(builder) && builder.energy < builder.energyCapacity) {
closeBuilders.push(builder);
}
});
closeBuilders.sort(function(a, b) {
return a.energy - b.energy;
});
if(closeBuilders.length) {
var energyLeft = closeBuilders[0].energyCapacity - closeBuilders[0].energy;
link.transferEnergy(closeBuilders[0], energyLeft < link.energy ? energyLeft : link.energy);
}
}
if(link.memory.type === "dispatch" && link.energy === link.energyCapacity && !link.cooldown) {
var recieveLinks = [];
Memory.linkList.forEach(function(linkId) {
var targetLink = Game.structures[linkId];
if(targetLink.memory.type === "recieve" && targetLink.energy <= targetLink.energyCapacity/2 && link.pos.room === targetLink.pos.room) {
recieveLinks.push(targetLink);
}
});
recieveLinks.sort(function(a, b) {
return a.energy - b.energy;
});
link.transferEnergy(recieveLinks, link.energyCapacity/2);
}
}
};
| JavaScript | 0 | @@ -1635,16 +1635,19 @@
eveLinks
+%5B0%5D
, link.e
|
97dbea8af0187d5fea8ae2f07c800650fb79ce6f | fix unit test | test/CoachMark.test.js | test/CoachMark.test.js | /*global describe, it, beforeEach, afterEach*/
import expect from 'expect.js';
import CoachMark from './../src/js/CoachMark';
describe('CoachMark', () => {
let element = null;
let footer = null;
let mark = null;
beforeEach(() => {
element = document.createElement('div');
element.innerText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
element.style.top = '200px';
element.style.position = 'absolute';
element.style.width = '60%';
element.style.margin = 'auto';
footer = document.createElement('div');
footer.innerText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
footer.style.top = '600px';
footer.style.width = '60%';
footer.style.position = 'absolute';
document.body.appendChild(element);
document.body.appendChild(footer);
});
afterEach(() => {
document.body.removeChild(element);
document.body.removeChild(footer);
if(document.querySelector('.o-coach-mark__container')) {
document.body.removeChild(
document.querySelector('.o-coach-mark__container'));
}
});
it('should initialize', () => {
mark = new CoachMark(element, {
placement: 'top',
title: 'bar',
text: 'baz'
}, function () {
console.log('test');
});
expect(mark).to.be.an('object');
});
it('should throw an Error if no parent element', () => {
expect(function () {
new CoachMark(null , {
placement: 'top',
title: 'foo',
text: 'bar'
}, function () {
console.log('test');
})}).to.throwError();
});
it('should throw an Error if there is no text', () => {
expect(function () {
new CoachMark(element , {
placement: 'top',
title: 'bar'
}, function () {
console.log('test');
})
}).to.throwError();
});
it('should default to bottom if there is no placement', () => {
mark = new CoachMark(element, {
title: 'foo',
text: 'bar'
}, function () {
});
expect(mark.opts.placement).to.be('bottom');
});
it('should correctly calculate placement if placed above the feature', () => {
mark = new CoachMark(element, {
placement: 'top',
title: 'foo',
text: 'bar'
}, function () {});
const pos = document.querySelector('.o-coach-mark__container')
.getBoundingClientRect();
expect(pos.top).to.be(122);
expect(pos.left).to.be(85);
});
it('should correctly calculate placement if placed below the feature', () => {
mark = new CoachMark(element, {
placement: 'bottom',
title: 'foo',
text: 'bar'
}, function () {});
const pos = document.querySelector('.o-coach-mark__container')
.getBoundingClientRect();
expect(pos.top).to.be(244);
expect(pos.left).to.be(85);
});
it('should correctly calculate placement if placed left of the feature', () => {
mark = new CoachMark(element, {
placement: 'left',
title: 'foo',
text: 'bar'
}, function () {});
const pos = document.querySelector('.o-coach-mark__container')
.getBoundingClientRect();
expect(pos.top).to.be(208);
expect(pos.left).to.be(64);
});
it('should correctly calculate placement if placed right of the feature', () => {
mark = new CoachMark(element, {
placement: 'right',
title: 'foo',
text: 'bar'
}, function () {});
const pos = document.querySelector('.o-coach-mark__container')
.getBoundingClientRect();
expect(pos.top).to.be(208);
expect(pos.left).to.be(315);
});
it('should call the callback when dismissed', () => {
let called = false;
mark = new CoachMark(element, {
placement: 'right',
title: 'foo',
text: 'bar'
}, function() { called = true; });
const link = document.querySelector('.o-coach-mark__container a');
const ev = document.createEvent("MouseEvent");
ev.initMouseEvent("click", true, true, window);
link.dispatchEvent(ev);
expect(called).to.be(true);
});
});
| JavaScript | 0.000698 | @@ -2238,24 +2238,28 @@
(pos.top
+%3C200
).to.be(
122);%0A%09%09
@@ -2254,41 +2254,12 @@
.be(
-122);%0A%09%09expect(pos.left).to.be(85
+true
);%0A%09
@@ -2565,24 +2565,28 @@
(pos.top
+%3E200
).to.be(
244);%0A%09%09
@@ -2581,41 +2581,12 @@
.be(
-244);%0A%09%09expect(pos.left).to.be(85
+true
);%0A%09
@@ -2880,38 +2880,8 @@
();%0A
-%09%09expect(pos.top).to.be(208);%0A
%09%09ex
@@ -2893,24 +2893,28 @@
pos.left
+%3C100
).to.be(
64);%0A%09%7D)
@@ -2909,10 +2909,12 @@
.be(
-64
+true
);%0A%09
@@ -3210,38 +3210,8 @@
();%0A
-%09%09expect(pos.top).to.be(208);%0A
%09%09ex
@@ -3223,24 +3223,28 @@
pos.left
+%3E300
).to.be(
315);%0A%09%7D
@@ -3239,11 +3239,12 @@
.be(
-315
+true
);%0A%09
|
71ea41d6265766cb2bd50a4d15154d260bfcf195 | Update Testing1.js | BiabCalc/Calc/Testing1.js | BiabCalc/Calc/Testing1.js | (function ($) {
function allFieldsValid() {
var fields = [
'BatchVol',
'GBill',
'HBill',
'DHop',
'BoilTime',
'BoilRate',
'TempGrain',
'TempMash',
'VolSparge',
'PotSize',
'KettleID',
'LossTrub',
'LossFermTrub',
'HChilled',
'VolPackaged',
'Gabs',
'Habs',
'EBoil',
];
for (i = 0; i < fields.length; i++) {
if (!$('#' + fields[i]).val().match(/^d*(.\d+)?/)) {
return false;
}
}
return true;
}
function updateCalc() {
if (!allFieldsValid()) {
return;
}
var BatchVol = parseFloat($('#BatchVol').val()),
GBill = parseFloat($('#GBill').val()),
HBill = parseFloat($('#HBill').val()),
DHop = parseFloat($('#DHop').val()),
BoilTime = parseFloat($('#BoilTime').val()),
BoilRate = parseFloat($('#BoilRate').val()),
TempGrain = parseFloat($('#TempGrain').val()),
TempMash = parseFloat($('#TempMash').val()),
VolSparge = parseFloat($('#VolSparge').val()),
PotSize = parseFloat($('#PotSize').val()),
KettleID = parseFloat($('#KettleID').val()),
LossTrub = parseFloat($('#LossTrub').val()),
Gabs = parseFloat($('#Gabs').val()),
Habs = parseFloat($('#Habs').val()),
MashAdj = parseFloat($('#MashAdj').val()),
StrikeAdj = parseFloat($('#StrikeAdj').val()),
LossFermTrub = parseFloat($('#LossFermTrub').val()),
LossBoil = BoilTime * BoilRate / 60,
LossHop = HBill * Habs,
LossGrain = GBill * Gabs,
LossTot = LossGrain + LossHop + LossBoil + LossTrub,
WaterTot = BatchVol + LossTot,
VolStart = (WaterTot - VolSparge),
TempStrike = TempMash + (0.05 * GBill / VolStart) * (TempMash - TempGrain),
MashAdj = 1.022494888,
//( 4.13643 * Math.pow(10,-16) * Math.pow($('#TempMash').val(),6) - 4.05998 * Math.pow(10,-13) * Math.pow($('#TempMash').val(),5) + 1.61536 * Math.pow(10,-10) * Math.pow($('#TempMash').val(),4) - 3.44854 * Math.pow(10,-8) * Math.pow($('#TempMash').val(),3) + 0.00000532769 * Math.pow($('#TempMash').val(),2) - 0.000292675 * $('#TempMash').val() + 1.00493),
StrikeAdj = 1.025641026,
//( 4.13643 * Math.pow(10,-16) * Math.pow($('#TempStrike').val(),6) - 4.05998 * Math.pow(10,-13) * Math.pow($('#TempStrike').val(),5) + 1.61536 * Math.pow(10,-10) * Math.pow($('#TempStrike').val(),4) - 3.44854 * Math.pow(10,-8) * Math.pow($('#TempStrike').val(),3) + 0.00000532769 * Math.pow($('#TempStrike').val(),2) - 0.000292675 * $('#TempStrike').val() + 1.00493),
VolStrike = VolStart * StrikeAdj,
LossHop = HBill * Habs,
LossGrain = GBill * Gabs,
VolMash = (VolStart + GBill * 0.08) * MashAdj,
VolPre = (WaterTot - LossGrain) * 1.043841336,
VolPost = (WaterTot - LossTot + LossTrub) * 1.043841336,
VolChilled = ( VolPost / 1.043841336 ) - LossTrub,
VolPackaged = VolChilled - LossFermTrub - ( DHop * Gabs ),
GalH = 294.118334834 / (KettleID * KettleID),
HTot = GalH * WaterTot,
HStart = GalH * VolStart,
HStrike = GalH * VolStrike,
HMash = GalH * VolMash,
HPre = GalH * VolPre,
HChilled = GalH * VolChilled,
MashThick = VolStart * 4 / GBill,
VolMinSparge = Math.max(0,((WaterTot + GBill * 0.08) * MashAdj) - (PotSize - 0.01 )),
HPost = GalH * VolPost,
EBoil = (0.0058 * KettleID * KettleID) - (0.0009 * KettleID) + 0.0038;
// console.log(VolStrike, WaterTot, MashThick, TempStrike);
$('#WaterTot').text(WaterTot.toFixed(2));
$('#VolStrike').text(VolStrike.toFixed(2));
$('#LossBoil').text(LossBoil.toFixed(2));
$('#LossHop').text(LossHop.toFixed(2));
$('#LossGrain').text(LossGrain.toFixed(2));
$('#LossTot').text(LossTot.toFixed(2));
$('#LossFermTrub').text(LossFermTrub.toFixed(2));
$('#VolStart').text(VolStart.toFixed(2));
$('#VolMash').text(VolMash.toFixed(2));
$('#VolPre').text(VolPre.toFixed(2));
$('#VolPost').text(VolPost.toFixed(2));
$('#TempStrike').text(TempStrike.toFixed(2));
$('#MashAdj').text(MashAdj.toFixed(12));
$('#Strikeadj').text(StrikeAdj.toFixed(12));
$('#GalH').text(GalH.toFixed(3));
$('#HTot').text(HTot.toFixed(2));
$('#HStart').text(HStart.toFixed(2));
$('#HStrike').text(HStrike.toFixed(2));
$('#HMash').text(HMash.toFixed(2));
$('#HPre').text(HPre.toFixed(2));
$('#HPost').text(HPost.toFixed(2));
$('#DHop').text(DHop.toFixed(2));
$('#HChilled').text(HChilled.toFixed(2));
$('#MashThick').text(MashThick.toFixed(2));
$('#VolMinSparge').text(VolMinSparge.toFixed(2));
$('#VolChilled').text(VolChilled.toFixed(2));
$('#VolPackaged').text(VolPackaged.toFixed(2));
$('#EBoil').text(VolPackaged.toFixed(2));
}
function validateField(field) {
$field = $(field);
if ($field.val().match(/^d*(.\d+)?/)) {
$field.parents('div.control-group:first').removeClass('error');
return true;
}
$field.parents('div.control-group:first').addClass('error');
return false;
}
$(document).ready(function () {
$('#calcForm').delegate('input[type=text]', 'change', function () {
if (validateField(this)) {
updateCalc();
}
}).submit(function (e) {
e.defaultPrevented;
updateCalc();
});
updateCalc();
$('#GBill').focus();
});
}) (jQuery);
| JavaScript | 0 | @@ -4676,35 +4676,29 @@
Boil').text(
-VolPackaged
+EBoil
.toFixed(2))
|
9e5ff75cd85a02ca7b587b10d09ff3156588234a | Switch account keys to a single translated message (#1004) | app/components/views/AccountsPage/Accounts/AccountRow/AccountDetails.js | app/components/views/AccountsPage/Accounts/AccountRow/AccountDetails.js | import { FormattedMessage as T } from "react-intl";
import { Balance, Tooltip } from "shared";
const AccountsList = ({
account,
showRenameAccount,
hidden,
hideAccount,
showAccount,
}) => (
<div className="account-row-details-bottom" key={"details" + account.accountNumber}>
<div className="account-row-details-bottom-columns">
<div className="account-row-details-bottom-column-left">
<div className="account-row-details-bottom-title">
<div className="account-row-details-bottom-title-name">
<T id="accounts.balances" m="Balances" />
</div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.total" m="Total" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.total} /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.details.spendable" m="Spendable" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.spendable} /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.immatureRewards" m="Immature Rewards" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.immatureReward} /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.lockedByTickets" m="Locked By Tickets" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.lockedByTickets} /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.votingAuthority" m="Voting Authority" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.votingAuthority} /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name">
<T id="accounts.immatureStake" m="Immature Stake Generation" />
</div>
<div className="account-row-details-bottom-spec-value"><Balance amount={account.immatureStakeGeneration} /></div>
</div>
</div>
<div className="account-row-details-bottom-column-right">
<div className="account-row-details-bottom-title">
<div className="account-row-details-bottom-title-name"><T id="accounts.properties" m="Properties" /></div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name"><T id="accounts.number" m="Account number" /></div>
<div className="account-row-details-bottom-spec-value">{account.accountNumber}</div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name"><T id="accounts.hdPath" m="HD Path" /></div>
<div className="account-row-details-bottom-spec-value">{account.HDPath}</div>
</div>
<div className="account-row-details-bottom-spec">
<div className="account-row-details-bottom-spec-name"><T id="accounts.keys" m="Keys" /></div>
<div className="account-row-details-bottom-spec-value">
<T id="accounts.keys.external" m="{keys} external" values={{ keys: account.externalKeys }} />
<T id="accounts.keys.internal" m="{keys} internal" values={{ keys: account.internalKeys }} />
<T id="accounts.keys.imported" m="{keys} imported" values={{ keys: account.importedKeys }} />
</div>
</div>
</div>
</div>
<div className="account-actions">
{account.accountName !== "imported" ?
<Tooltip text={<T id="accounts.rename.tip" m="Rename Account" />}>
<div className="rename-account-button" onClick={showRenameAccount} />
</Tooltip> :
<div></div>
}
{account.accountName !== "imported" && account.accountName !== "default" && account.total == 0 && !hidden ?
<Tooltip text={<T id="accounts.show.tip" m="Show" />}>
<div className="hide-account-button" onClick={hideAccount} />
</Tooltip> :
account.accountName !== "imported" && account.accountName !== "default" && hidden ?
<Tooltip text={<T id="accounts.hide.tip" m="Hide" />}>
<div className="show-account-button" onClick={showAccount} />
</Tooltip> :
<div></div>
}
</div>
</div>
);
AccountsList.propTypes = {
account: PropTypes.object.isRequired,
showRenameAccount: PropTypes.func.isRequired,
hidden: PropTypes.bool.isRequired,
hideAccount: PropTypes.func.isRequired,
showAccount: PropTypes.func.isRequired,
};
export default AccountsList;
| JavaScript | 0 | @@ -3833,52 +3833,134 @@
eys.
-external%22 m=%22%7Bkeys%7D external%22 values=%7B%7B keys
+counts%22 m=%22%7Bexternal%7D external, %7Binternal%7D internal, %7Bimported%7D imported%22%0A values=%7B%7B%0A external
: ac
@@ -3969,38 +3969,33 @@
unt.externalKeys
- %7D%7D /%3E
+,
%0A %3C
@@ -3997,73 +3997,20 @@
-%3CT id=%22accounts.keys.internal%22 m=%22%7Bkeys%7D internal%22 values=%7B%7B keys
+ internal
: ac
@@ -4023,31 +4023,28 @@
internalKeys
- %7D%7D /%3E%0A
+,%0A
@@ -4049,73 +4049,18 @@
-%3CT id=%22accounts.keys.imported%22 m=%22%7Bkeys%7D imported%22 values=%7B%7B keys
+ imported
: ac
|
73c6cdcb63fb4ccb8a77ad03fe02091594e5a331 | Update to use dynamic ports | src/firefox/lib/firefox_proxy_config.js | src/firefox/lib/firefox_proxy_config.js | /**
* Firefox proxy settings implementation
* TODO(salomegeo): rewrite it in typescript
*/
var prefsvc = require("sdk/preferences/service");
var proxyConfig = function() {
this.running_ = false;
};
proxyConfig.startUsingProxy = function(endpoint) {
if (!this.running_) {
this.running_ = true;
this.socks_server_ = prefsvc.get("network.proxy.socks");
this.socks_port_ = prefsvc.get("network.proxy.socks_port");
this.proxy_type_ = prefsvc.get("network.proxy.type");
prefsvc.set("network.proxy.socks", '127.0.0.1');
prefsvc.set("network.proxy.http_port", 9999);
prefsvc.set("network.proxy.type", 1);
}
};
proxyConfig.stopUsingProxy = function(askUser) {
if (this.running_) {
this.running_ = false;
prefsvc.set("network.proxy.socks", this.socks_server_);
prefsvc.set("network.proxy.http_port", this.socks_port_);
prefsvc.set("network.proxy.type", this.proxy_type);
}
};
exports.proxyConfig = proxyConfig
| JavaScript | 0 | @@ -300,16 +300,50 @@
= true;%0A
+ // Store initial proxy state.%0A
this
@@ -391,24 +391,24 @@
xy.socks%22);%0A
-
this.soc
@@ -561,19 +561,24 @@
s%22,
-'127.0.0.1'
+endpoint.address
);%0A
@@ -623,12 +623,21 @@
t%22,
-9999
+endpoint.port
);%0A
@@ -749,32 +749,32 @@
his.running_) %7B%0A
-
this.running
@@ -784,16 +784,52 @@
false;%0A
+ // Restore initial proxy state.%0A
pref
|
adcc757ee2b34b26e6d37d03b3c4592cbcbd664f | Remove unused import | app/pages/reservation/reservation-information/ReservationInformation.js | app/pages/reservation/reservation-information/ReservationInformation.js | import pick from 'lodash/pick';
import uniq from 'lodash/uniq';
import camelCase from 'lodash/camelCase';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import Well from 'react-bootstrap/lib/Well';
import moment from 'moment';
import injectT from '../../../i18n/injectT';
import { isStaffEvent } from '../../../utils/reservationUtils';
import { getTermsAndConditions } from '../../../utils/resourceUtils';
import ReservationInformationForm from './ReservationInformationForm';
class ReservationInformation extends Component {
static propTypes = {
isAdmin: PropTypes.bool.isRequired,
isEditing: PropTypes.bool.isRequired,
isMakingReservations: PropTypes.bool.isRequired,
isStaff: PropTypes.bool.isRequired,
onBack: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
openResourceTermsModal: PropTypes.func.isRequired,
reservation: PropTypes.object,
resource: PropTypes.object.isRequired,
selectedTime: PropTypes.object.isRequired,
t: PropTypes.func.isRequired,
unit: PropTypes.object.isRequired,
};
onConfirm = (values) => {
const { onConfirm } = this.props;
onConfirm(values);
}
getFormFields = (termsAndConditions) => {
const {
isAdmin,
isStaff,
resource,
} = this.props;
const formFields = [...resource.supportedReservationExtraFields].map(value => camelCase(value));
if (isAdmin) {
formFields.push('comments');
/* waiting for backend implementation */
// formFields.push('reserverName');
// formFields.push('reserverEmailAddress');
// formFields.push('reserverPhoneNumber');
}
if (resource.needManualConfirmation && isStaff) {
formFields.push('staffEvent');
}
if (termsAndConditions) {
formFields.push('termsAndConditions');
}
return uniq(formFields);
}
getFormInitialValues = () => {
const {
isEditing,
reservation,
resource,
} = this.props;
let rv = reservation ? pick(reservation, this.getFormFields()) : {};
if (isEditing) {
rv = { ...rv, staffEvent: isStaffEvent(reservation, resource) };
}
return rv;
}
getRequiredFormFields(resource, termsAndConditions) {
const requiredFormFields = [...resource.requiredReservationExtraFields.map(
field => camelCase(field)
)];
if (termsAndConditions) {
requiredFormFields.push('termsAndConditions');
}
return requiredFormFields;
}
renderInfoTexts = () => {
const { resource, t } = this.props;
if (!resource.needManualConfirmation) return null;
return (
<div className="app-ReservationInformation__info-texts">
<p>{t('ConfirmReservationModal.priceInfo')}</p>
<p>{t('ConfirmReservationModal.formInfo')}</p>
</div>
);
}
render() {
const {
isEditing,
isMakingReservations,
onBack,
onCancel,
openResourceTermsModal,
resource,
selectedTime,
t,
unit,
} = this.props;
const termsAndConditions = getTermsAndConditions(resource);
const beginText = moment(selectedTime.begin).format('D.M.YYYY HH:mm');
const endText = moment(selectedTime.end).format('HH:mm');
const hours = moment(selectedTime.end).diff(selectedTime.begin, 'minutes') / 60;
return (
<div className="app-ReservationInformation">
<Col md={7} sm={12}>
{this.renderInfoTexts()}
<ReservationInformationForm
fields={this.getFormFields(termsAndConditions)}
initialValues={this.getFormInitialValues()}
isEditing={isEditing}
isMakingReservations={isMakingReservations}
onBack={onBack}
onCancel={onCancel}
onConfirm={this.onConfirm}
openResourceTermsModal={openResourceTermsModal}
requiredFields={this.getRequiredFormFields(resource, termsAndConditions)}
resource={resource}
termsAndConditions={termsAndConditions}
/>
</Col>
<Col md={5} sm={12}>
<div className="app-ReservationDetails">
<h2 className="app-ReservationPage__title">{t('ReservationPage.detailsTitle')}</h2>
<Row>
<Col md={4}>
<span className="app-ReservationDetails__name">
{t('common.resourceLabel')}
</span>
</Col>
<Col md={8}>
<span className="app-ReservationDetails__value">
{resource.name}
<br />
{unit.name}
</span>
</Col>
</Row>
<Row>
<Col md={4}>
<span className="app-ReservationDetails__name">
{t('ReservationPage.detailsTime')}
</span>
</Col>
<Col md={8}>
<span className="app-ReservationDetails__value">
{`${beginText}–${endText} (${hours} h)`}
</span>
</Col>
</Row>
</div>
</Col>
</div>
);
}
}
export default injectT(ReservationInformation);
| JavaScript | 0.000001 | @@ -267,53 +267,8 @@
w';%0A
-import Well from 'react-bootstrap/lib/Well';%0A
impo
|
0afd20600d2c901d2b190cd59a920d9987a9eb5b | Correct millisecond SimpleDateFormat specifier. | src/foam/nanos/logger/AbstractLogger.js | src/foam/nanos/logger/AbstractLogger.js | /**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.logger',
name: 'AbstractLogger',
implements: [ 'foam.nanos.logger.Logger' ],
abstract: true,
javaImports: [
'java.io.PrintWriter',
'java.io.StringWriter',
'java.io.Writer',
'java.text.SimpleDateFormat'
],
axioms: [
{
name: 'javaExtras',
buildJavaClass: function(cls) {
cls.extras.push(foam.java.Code.create({
data:
`protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.Z");
}
};
protected ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() {
@Override
protected StringBuilder initialValue() {
return new StringBuilder();
}
@Override
public StringBuilder get() {
StringBuilder b = super.get();
b.setLength(0);
return b;
}
};`
}))
}
}
],
methods: [
{
name: 'formatArg',
args: [
{
name: 'obj',
javaType: 'Object'
}
],
javaReturns: 'String',
javaCode:
`if ( obj instanceof Throwable ) {
Throwable t = (Throwable) obj;
Writer w = new StringWriter();
PrintWriter pw = new PrintWriter(w);
t.printStackTrace(pw);
return w.toString();
}
return String.valueOf(obj);`
},
{
name: 'combine',
args: [
{
name: 'args',
javaType: 'Object[]'
}
],
javaReturns: 'String',
javaCode:
`StringBuilder str = sb.get();
for ( Object n : args ) {
str.append(',');
str.append(formatArg(n));
}
return str.toString();`
}
]
});
| JavaScript | 0 | @@ -746,9 +746,11 @@
.ss.
-Z
+SSS
%22);%0A
|
8d226ca94a61fd2c816638975a1a18f3f9083542 | Fix version | src/js/f7-intro.js | src/js/f7-intro.js | 'use strict';
/*===========================
Framework 7
===========================*/
window.Framework7 = function (params) {
// App
var app = this;
// Version
app.version = '0.9.6';
// Default Parameters
app.params = {
cache: true,
cacheIgnore: [],
cacheIgnoreGetParameters: false,
cacheDuration: 1000 * 60 * 10, // Ten minutes
preloadPreviousPage: true,
uniqueHistory: false,
uniqueHistoryIgnoreGetParameters: false,
dynamicPageUrl: 'content-{{index}}',
router: true,
// Push State
pushState: false,
pushStateRoot: undefined,
pushStateNoAnimation: false,
pushStateSeparator: '#!/',
// Fast clicks
fastClicks: true,
fastClicksDistanceThreshold: 0,
// Active State
activeState: true,
activeStateElements: 'a, button, label, span',
// Animate Nav Back Icon
animateNavBackIcon: false,
// Swipe Back
swipeBackPage: true,
swipeBackPageThreshold: 0,
swipeBackPageActiveArea: 30,
swipeBackPageAnimateShadow: true,
swipeBackPageAnimateOpacity: true,
// Ajax
ajaxLinks: undefined, // or CSS selector
// External Links
externalLinks: ['external'], // array of CSS class selectors and/or rel attributes
// Sortable
sortable: true,
// Scroll toolbars
hideNavbarOnPageScroll: false,
hideToolbarOnPageScroll: false,
showBarsOnPageScrollEnd: true,
// Swipeout
swipeout: true,
swipeoutNoFollow: false,
// Smart Select Back link template
smartSelectBackTemplate: '<div class="left sliding"><a href="#" class="back link"><i class="icon icon-back"></i><span>{{backText}}</span></a></div>',
smartSelectBackText: 'Back',
smartSelectInPopup: false,
smartSelectPopupCloseTemplate: '<div class="left"><a href="#" class="link close-popup"><i class="icon icon-back"></i><span>{{closeText}}</span></a></div>',
smartSelectPopupCloseText: 'Close',
smartSelectSearchbar: false,
smartSelectBackOnSelect: false,
// Searchbar
searchbarHideDividers: true,
searchbarHideGroups: true,
// Panels
swipePanel: false, // or 'left' or 'right'
swipePanelActiveArea: 0,
swipePanelCloseOpposite: true,
swipePanelNoFollow: false,
swipePanelThreshold: 0,
panelsCloseByOutside: true,
// Modals
modalButtonOk: 'OK',
modalButtonCancel: 'Cancel',
modalUsernamePlaceholder: 'Username',
modalPasswordPlaceholder: 'Password',
modalTitle: 'Framework7',
modalCloseByOutside: false,
actionsCloseByOutside: true,
popupCloseByOutside: true,
modalPreloaderTitle: 'Loading... ',
// Name space
viewClass: 'view',
viewMainClass: 'view-main',
viewsClass: 'views',
// Notifications defaults
notificationCloseOnClick: false,
notificationCloseIcon: true,
// Animate Pages
animatePages: true,
// Template7
templates: {},
templatesData: {},
template7Pages: false,
precompileTemplates: false,
// Auto init
init: true,
};
// Extend defaults with parameters
for (var param in params) {
app.params[param] = params[param];
}
// DOM lib
var $ = Dom7;
// Template7 lib
var t7 = Template7;
app._compiledTemplates = {};
// Touch events
app.touchEvents = {
start: app.support.touch ? 'touchstart' : 'mousedown',
move: app.support.touch ? 'touchmove' : 'mousemove',
end: app.support.touch ? 'touchend' : 'mouseup'
};
// Link to local storage
app.ls = localStorage;
// RTL
app.rtl = $('body').css('direction') === 'rtl';
if (app.rtl) $('html').attr('dir', 'rtl');
// Overwrite statusbar overlay
if (typeof app.params.statusbarOverlay !== 'undefined') {
if (app.params.statusbarOverlay) $('html').addClass('with-statusbar-overlay');
else $('html').removeClass('with-statusbar-overlay');
}
| JavaScript | 0.000001 | @@ -190,17 +190,17 @@
= '0.9.
-6
+7
';%0A%0A
|
4bc9492a55d45a8aa20438320020df95760ba8a1 | fix TypeError in content-script.js | src/js/content-script.js | src/js/content-script.js | 'use strict';
chrome.runtime.sendMessage({
type: 'pontoon-page-loaded',
url: document.location.toString(),
value: document.documentElement.innerHTML
});
const unreadNotificationsIcon = document.querySelector('#notifications.unread .button .icon');
function unreadNotificationsIconClick() {
unreadNotificationsIcon.removeEventListener('click', unreadNotificationsIconClick);
chrome.runtime.sendMessage({type: 'mark-all-notifications-as-read-from-page'});
}
if (unreadNotificationsIcon !== undefined) {
unreadNotificationsIcon.addEventListener('click', unreadNotificationsIconClick);
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'mark-all-notifications-as-read-from-extension') {
unreadNotificationsIcon.style.color = '#4D5967';
}
});
}
| JavaScript | 0.000004 | @@ -508,17 +508,12 @@
!==
-undefined
+null
) %7B%0A
|
7a3ec6caa3fb46c38f30039dec806777d70d3a57 | Update collection on saved datasets properly | arborweb/js/views/DatasetManagementView.js | arborweb/js/views/DatasetManagementView.js | /*jslint browser: true, nomen: true */
(function (flow, $, _, Backbone, Blob, d3, FileReader, girderUpload, URL) {
"use strict";
// The view for managing data saving and downloading
flow.DatasetManagementView = Backbone.View.extend({
saveFormats: {
table: ['csv', 'rows.json'],
tree: ['nested.json', 'nexus', 'newick'],
image: ['png'],
r: ['serialized']
},
extensions: {
"table:csv": "csv",
"table:rows.json": "rows-json",
"tree:nested.json": "nested-json",
"tree:nexus": "nex",
"tree:newick": "phy",
"image:png": "png",
"r:serialized": "rds"
},
events: {
'change .datasets': 'updateDataset',
'click .dataset-save': function () {
var name = this.$('.dataset-name').val(),
format = this.$('.dataset-format-select').val(),
dataset = this.datasets.get(this.$('.datasets').val());
flow.retrieveDatasetAsFormat(dataset, dataset.get('type'), format, false, _.bind(function (error, converted) {
var blob = new Blob([converted.get('data')]),
extension = this.extensions[dataset.get('type') + ":" + format],
parts = name.split('.'),
nameWithExtension = parts[parts.length - 1] === extension ? name : name + '.' + extension;
girderUpload(blob, nameWithExtension, flow.saveLocation.get('dataFolder'));
}, this));
},
'click .dataset-download': function () {
var name = this.$('.dataset-name').val(),
format = this.$('.dataset-format-select').val(),
dataset = this.datasets.get(this.$('.datasets').val());
flow.retrieveDatasetAsFormat(dataset, dataset.get('type'), format, false, _.bind(function (error, converted) {
var blob = new Blob([converted.get('data')]),
extension = this.extensions[dataset.get('type') + ":" + format],
parts = name.split('.'),
nameWithExtension = parts[parts.length - 1] === extension ? name : name + '.' + extension,
anchor = $('<a href="' + URL.createObjectURL(blob) + '" download="' + nameWithExtension + '" class="hidden"></a>');
anchor[0].click();
}, this));
},
'change #g-files': function () {
var files = $('#g-files')[0].files;
_.each(files, function (file) {
this.upload(file);
}, this);
},
'click #upload': function () {
$('#g-files').click();
},
'dragenter #upload': function (e) {
e.stopPropagation();
e.preventDefault();
e.originalEvent.dataTransfer.dropEffect = 'copy';
d3.select('#upload')
.classed('btn-success', true)
.classed('btn-primary', false)
.html('<i class="glyphicon glyphicon-upload"></i> Drop files here');
},
'dragleave #upload': function (e) {
e.stopPropagation();
e.preventDefault();
d3.select('#upload')
.classed('btn-success', false)
.classed('btn-primary', true)
.html('<i class="glyphicon glyphicon-file"/></i> Browse or drop files');
},
'dragover #upload': function (e) {
e.preventDefault();
},
'drop #upload': function (e) {
var files = e.originalEvent.dataTransfer.files;
e.stopPropagation();
e.preventDefault();
d3.select('#upload')
.classed('btn-success', false)
.classed('btn-primary', true)
.html('<i class="glyphicon glyphicon-file"></i> Browse or drop files');
_.each(files, function (file) {
this.upload(file);
}, this);
}
},
initialize: function (settings) {
this.datasets = settings.datasets;
this.datasetsView = new flow.ItemsView({el: this.$('.datasets'), itemView: flow.ItemOptionView, collection: this.datasets});
this.datasetsView.render();
flow.events.on('flow:change-save-location', this.saveLocationChange, this);
this.saveLocationChange();
// Once the first dataset is added, make it the active dataset
this.datasets.on('add', _.bind(function () {
if (!this.dataset) {
this.updateDataset();
}
}, this));
},
upload: function (file) {
var reader = new FileReader();
reader.onload = _.bind(function (e) {
var dataset = {
name: file.name,
data: e.target.result
},
extension = file.name.split('.');
extension = extension[extension.length - 1];
_.extend(dataset, flow.extensionToType[extension]);
dataset = new Backbone.Model(dataset);
this.datasets.add(dataset);
}, this);
reader.readAsText(file);
},
updateDataset: function () {
var options, valid;
this.dataset = this.datasets.get(this.$('.datasets').val());
// If we don't know the format, don't let them download it
valid = this.dataset.get('type') !== undefined && this.dataset.get('format') !== undefined;
this.$('.dataset-save-form').toggleClass('hidden', !valid);
if (valid) {
this.$('.dataset-name').val(this.dataset.get('name'));
options = d3.select('.dataset-format-select').selectAll('option')
.data(this.saveFormats[this.dataset.get('type')], function (d) { return d; });
options.enter().append('option')
.text(function (d) { return d; })
.attr('value', function (d) { return d; });
options.exit().remove();
}
},
saveLocationChange: function () {
this.$('.dataset-save').toggleClass('hidden', flow.saveLocation === null);
}
});
}(window.flow, window.$, window._, window.Backbone, window.Blob, window.d3, window.FileReader, window.girderUpload, window.URL));
| JavaScript | 0 | @@ -1577,24 +1577,90 @@
aFolder'));%0A
+ dataset.set(%7Bcollection: flow.saveLocation%7D);%0A
@@ -5582,16 +5582,51 @@
atasets.
+off('add', null, 'set-collection').
add(data
|
3fba2ad48d03ea0182689bd775faf010b2fe7d85 | fix NULL counter and no article title cases | public/client.js | public/client.js | // TODO: switch to requireJS or AMD modules
// TODO: convert to backbone?
$(function(){
mf.init()
mf.load()
})
var mf = {}
mf.init = function() {
// put in constructor
mf.nav.skip = new mf.controllers.button('#skip')
mf.nav.discard = new mf.controllers.button('#discard')
mf.nav.publish = new mf.controllers.button('#publish')
mf.nav.inspect = new mf.controllers.button('#inspect')
mf.nav.undo = new mf.controllers.button('#undo')
mf.nav.skip.bind('right').bind('j').bind('s')
mf.nav.discard.bind('x').bind('d').bind('space')
mf.nav.publish.bind('w').bind('p')
mf.nav.inspect.bind('i')
mf.nav.undo.bind('u').bind('ctrl+z')
mf.nav.undo.disable()
mf.display = new mf.controllers.display('article')
mf.display.wait()
mf.pending = new mf.controllers.counter('#pending')
// queue refill should load article
mf.pending.change(function(from, to){
if (from == 0 && to > 0)
mf.load()
document.title = '('+to+') Megafilter'
console.log('change to',to,'from',from)
})
mf.nav.skip.action(mf.skip)
mf.nav.discard.action(mf.discard)
mf.nav.publish.action(mf.publish)
mf.nav.inspect.action(mf.inspect)
//mf.nav.undo.action(mf.undo)
setInterval(mf.check_pending,5000)
}
// render the next article from cache and begin to use the
mf.next = function() {}
mf.controllers = {}
mf.controllers.display = function(selector) {
var ele = $(selector)
// currently displayed article, if any
this.article = null
// render a given node-feedparser article to the page
this.render = function(article) {
this.article = article
$('#error').hide()
$('#loading').hide()
ele.css('visibility','visible')
$('section.description',ele).html(article.description)
$('> h1 a',ele).html(article.title).attr('href',article.origlink)
$('time',ele).attr('datetime',article.pubdate)
$('.note',ele).html(article.author).prepend(' by ')
return this
}
var discard = this.discard = function() {
this.article = null
ele.css('visibility','hidden')
return this
}
// show loading animation
this.wait = function(){
$('#loading').show()
discard()
$('#error').hide()
return this
}
// show 'error' message
this.error = function(msg) {
$('#loading').hide()
discard()
$('#error').show().text(msg)
return this
}
}
// positive article counter
mf.controllers.counter = function(selector) {
ele = $(selector)
// count
var value = null
// callback for when number changes
var change = function(from,to) {}
this.change = function(fn) {
change = fn
}
this.set = function(number) {
if (number == value) return;
// from, to
change(value,number)
ele.text(number)
value = number
return this
}
// initialise to zero without triggering change()
ele.text(value)
this.get = function() {
return value
}
this.decrement = function() {
if (value > 0) {
ele.text(--value)
change(value+1,value)
}
return this
}
}
// navigation buttons (sort of like a view controller)
mf.controllers.button = function(selector){
var ele = $(selector)
var enabled = true;
// callback for when button is clicked or key is pressed
var action = function() {}
this.action = function(fn) {
action = fn
}
ele.click(function() {
if (enabled)
action()
})
this.enable = function() {
enabled = true
ele.removeClass('disabled')
return this
}
this.disable = function() {
enabled = false
ele.addClass('disabled')
return this
}
// bind a key
this.bind = function(key) {
// press
$(document).bind('keydown',key,function() {
if (!enabled) return false
ele.addClass('depressed')
return false
})
// release
$(document).bind('keyup',key,function() {
if (!enabled) return false
ele.removeClass('depressed')
action()
return false
})
return this
}
}
// -------model?
// download and display the next article (or current on first load)
mf.load = mf.skip = function() {
mf.display.wait()
mf.nav.disable()
$.ajax({
url: mf.display.article?'/next':'/current',
type:'GET',
error:function() {
mf.display.error('No more articles')
},
success:function(article) {
if (!article.pending) {
mf.display.error('None left in queue')
ml.article = null
} else {
mf.display.render(article)
mf.nav.enable()
}
mf.pending.set(article.pending)
}
})
}
mf.publish = function() {
mf.pending.decrement()
$.ajax({
url:'/publish/'+mf.display.article.id,
type:'GET',
error:function() {
mf.display.error("None left!")
},
success:function() {
console.log('Published article')
}
})
mf.load()
}
mf.discard = function() {
mf.pending.decrement()
$.ajax({
url:'/'+mf.display.article.id,
type:'DELETE',
error:function() {
mf.display.error("That's it!")
},
success:function() {
console.log('Deleted article')
}
})
mf.load()
}
mf.inspect = function() {
window.open(mf.display.article.link)
}
mf.nav = {}
mf.nav.enable = function() {
mf.nav.skip.enable()
mf.nav.discard.enable()
mf.nav.publish.enable()
mf.nav.inspect.enable()
}
mf.nav.disable = function() {
mf.nav.skip.disable()
mf.nav.discard.disable()
mf.nav.publish.disable()
mf.nav.inspect.disable()
}
mf.check_pending = function () {
$.ajax({
url: '/pending',
type: 'GET',
success: function(d) {
mf.pending.set(d.pending)
}
})
}
| JavaScript | 0.000012 | @@ -1805,16 +1805,36 @@
date)%0A%09%09
+if (article.author)
$('.note
@@ -1877,16 +1877,58 @@
' by ')%0A
+%09%09// also do link to source site homepage%0A
%09%09return
@@ -2432,28 +2432,27 @@
var value =
-null
+%22 %22
%0A%0A%09// callba
|
ea4082f8d8dddd9332d66352702dee219871712d | Remove console.log | src/js/internal.js | src/js/internal.js | import utils from './utils';
import {
CLASSNAME,
VARS,
eventType as EVENT_TYPE
} from './constants';
/**
* @class Internal
*/
export class Internal {
constructor(base) {
this.Base = base;
this.container = base.container.element;
// ready to close when both are chosen
this.closeWhen = { hour: false, minute: false };
// increment internal ids
this._ids = 0;
// active picker
this.id_active = undefined;
// is this opened
this.opened = false;
// these are targets we're working on
this.targets = [];
// this will cache DOM <a> hours (and minutes) array among others
this.collection = {
hours: [],
minutes: []
};
this.events = utils.events();
this.request_ani_id = undefined;
}
init() {
this.setFocusListener(this.Base.target);
this.setSelectListener();
}
show(id) {
const target = this.targets[id].element;
const target_offset = utils.offset(target);
const container_offset = this.Base.container.size;
const top = target_offset.top + target_offset.height + 5;
const window_ = utils.getWindowSize();
if (target_offset.left + container_offset.width > window_.width) {
this.container.style.left = '';
this.container.style.right = '5px';
} else {
this.container.style.right = '';
this.container.style.left = target_offset.left + 'px';
}
if (target_offset.top + container_offset.height > window_.height) {
this.container.style.bottom = '5px';
} else {
this.container.style.top = top + 'px';
}
this.events.subscribe(EVENT_TYPE.start_fade_in, obj => {
obj.target.style.opacity = 0;
obj.target.style.display = 'block';
});
this.request_ani_id = utils.fade(this.events, this.container, 400);
this.Base.dispatchEvent(EVENT_TYPE.open, { element: target });
this.handleOpen(id);
}
show_() {
this.targets.forEach(each => { this.show(each.element._id); });
}
hide(id) {
this.opened = false;
this.events.subscribe(EVENT_TYPE.start_fade_out, obj => {
obj.target.style.opacity = 1;
obj.target.style.display = 'block';
});
this.events.subscribe(EVENT_TYPE.end_fade_out, obj => {
obj.target.style.display = 'none';
});
this.request_ani_id = utils.fade(this.events, this.container, 800, 'out');
console.warn(this.targets);
console.warn(id);
this.Base.dispatchEvent(EVENT_TYPE.close, {
element: this.targets[id].element
});
}
hide_() {
this.targets.forEach(each => { console.warn(each); this.hide(each.element._id); });
}
handleOpen(id) {
const this_ = this;
const hour = this.targets[id].hour;
const minute = this.targets[id].minute;
let value;
utils.removeClass(this.collection.hours, CLASSNAME.selected);
utils.removeClass(this.collection.minutes, CLASSNAME.selected);
if (hour && minute) {
this.collection.hours.forEach(element => {
value = this.getHour(element);
if (value === hour) {
utils.addClass(element, CLASSNAME.selected);
return;
}
});
this.collection.minutes.forEach(element => {
value = this.getMinute(element);
if (value === minute) {
utils.addClass(element, CLASSNAME.selected);
return;
}
});
}
//one-time fire
document.addEventListener('mousedown', {
handleEvent: function (evt) {
// click inside Picker
if (this_.container.contains(evt.target)) return;
let is_clicking_target = false;
this_.targets.forEach(target => {
if (target.element === evt.target) is_clicking_target = true;
});
if (!is_clicking_target && this_.opened) this_.hide(id);
if (this_.targets[id].element !== evt.target) {
document.removeEventListener(evt.type, this, false);
}
}
}, false);
this.opened = true;
this.id_active = id;
this.closeWhen = {
hour: false,
minute: false
};
}
handleClose(id) {
if (this.closeWhen.hour && this.closeWhen.minute) this.hide(id);
}
getHour(element) {
return element.getAttribute(VARS.attr.hour);
}
getMinute(element) {
return element.getAttribute(VARS.attr.minute);
}
setSelectListener() {
const hour_list = utils.$(VARS.ids.hour_list);
const minute_list = utils.$(VARS.ids.minute_list);
const selectHour = evt => {
evt.preventDefault();
const active = this.targets[this.id_active];
active.hour = this.getHour(evt.target);
this.Base.dispatchEvent(EVENT_TYPE.change, {
element: active.element,
hour: active.hour,
minute: active.minute
});
utils.removeClass(this.collection.hours, CLASSNAME.selected);
utils.addClass(evt.target, CLASSNAME.selected);
this.closeWhen.hour = true;
this.handleClose(this.id_active);
};
const selectMinute = evt => {
evt.preventDefault();
const active = this.targets[this.id_active];
active.minute = this.getMinute(evt.target);
this.Base.dispatchEvent(EVENT_TYPE.change, {
element: active.element,
hour: active.hour,
minute: active.minute
});
utils.removeClass(this.collection.minutes, CLASSNAME.selected);
utils.addClass(evt.target, CLASSNAME.selected);
this.closeWhen.minute = true;
this.handleClose(this.id_active);
};
this.collection.hours = utils.getAllChildren(hour_list, 'a');
this.collection.minutes = utils.getAllChildren(minute_list, 'a');
this.collection.hours.forEach(hour => {
hour.addEventListener('click', selectHour);
});
this.collection.minutes.forEach(minute => {
minute.addEventListener('click', selectMinute);
});
}
setFocusListener(target) {
const triggerShow = evt => {
evt.preventDefault();
window.cancelAnimationFrame(this.request_ani_id);
this.show(evt.target._id);
};
let ar_target = [], element;
// to array if string
target = Array.isArray(target) ? target : [target];
// merge
Array.prototype.push.apply(ar_target, target);
ar_target.forEach(el => {
element = utils.evaluate(el);
if (!element) return;
let id = this._ids++;
element._id = id;
this.targets[id] = { element: element };
if (utils.focusable.test(element.nodeName)) {
element.addEventListener('focus', triggerShow, true);
} else if (utils.clickable.test(element.nodeName)) {
element.addEventListener('click', triggerShow, true);
}
});
}
}
| JavaScript | 0.000004 | @@ -2361,62 +2361,8 @@
');%0A
- console.warn(this.targets);%0A console.warn(id);%0A
@@ -2508,28 +2508,8 @@
=%3E %7B
- console.warn(each);
thi
|
fa20b86696298e4405bf49843d71ef7dbfc84b13 | Add creation validation configuration, e. g. in order to check whether the user is authorized to create the room type | packages/rocketchat-lib/lib/RoomTypeConfig.js | packages/rocketchat-lib/lib/RoomTypeConfig.js | export const RoomSettingsEnum = {
NAME: 'roomName',
TOPIC: 'roomTopic',
ANNOUNCEMENT: 'roomAnnouncement',
DESCRIPTION: 'roomDescription',
READ_ONLY: 'readOnly',
REACT_WHEN_READ_ONLY: 'reactWhenReadOnly',
ARCHIVE_OR_UNARCHIVE: 'archiveOrUnarchive',
JOIN_CODE: 'joinCode'
};
export class RoomTypeRouteConfig {
constructor({ name, path }) {
if (typeof name !== 'undefined' && (typeof name !== 'string' || name.length === 0)) {
throw new Error('The name must be a string.');
}
if (typeof path !== 'undefined' && (typeof path !== 'string' || path.length === 0)) {
throw new Error('The path must be a string.');
}
this._name = name;
this._path = path;
}
get name() {
return this._name;
}
get path() {
return this._path;
}
}
export class RoomTypeConfig {
constructor({
identifier = Random.id(),
order,
icon,
header,
label,
route
}) {
if (typeof identifier !== 'string' || identifier.length === 0) {
throw new Error('The identifier must be a string.');
}
if (typeof order !== 'number') {
throw new Error('The order must be a number.');
}
if (typeof icon !== 'undefined' && (typeof icon !== 'string' || icon.length === 0)) {
throw new Error('The icon must be a string.');
}
if (typeof header !== 'undefined' && (typeof header !== 'string' || header.length === 0)) {
throw new Error('The header must be a string.');
}
if (typeof label !== 'undefined' && (typeof label !== 'string' || label.length === 0)) {
throw new Error('The label must be a string.');
}
if (typeof route !== 'undefined' && !(route instanceof RoomTypeRouteConfig)) {
throw new Error('Room\'s route is not a valid route configuration. Must be an instance of "RoomTypeRouteConfig".');
}
this._identifier = identifier;
this._order = order;
this._icon = icon;
this._header = header;
this._label = label;
this._route = route;
}
/**
* The room type's internal identifier.
*/
get identifier() {
return this._identifier;
}
/**
* The order of this room type for the display.
*/
get order() {
return this._order;
}
/**
* Sets the order of this room type for the display.
*
* @param {number} order the number value for the order
*/
set order(order) {
if (typeof order !== 'number') {
throw new Error('The order must be a number.');
}
this._order = order;
}
/**
* The icon class, css, to use as the visual aid.
*/
get icon() {
return this._icon;
}
/**
* The header name of this type.
*/
get header() {
return this._header;
}
/**
* The i18n label for this room type.
*/
get label() {
return this._label;
}
/**
* The route config for this room type.
*/
get route() {
return this._route;
}
/**
* Gets the room's name to display in the UI.
*
* @param {object} room
*/
getDisplayName(room) {
return room.name;
}
allowRoomSettingChange(/* room, setting */) {
return true;
}
canBeDeleted(room) {
return Meteor.isServer ?
RocketChat.authz.hasAtLeastOnePermission(Meteor.userId(), [`delete-${ room.t }`], room._id) :
RocketChat.authz.hasAtLeastOnePermission([`delete-${ room.t }`], room._id);
}
supportMembersList(/* room */) {
return true;
}
isGroupChat() {
return false;
}
canAddUser(/* userId, room */) {
return false;
}
userDetailShowAll(/* room */) {
return true;
}
userDetailShowAdmin(/* room */) {
return true;
}
preventRenaming(/* room */) {
return false;
}
includeInRoomSearch() {
return false;
}
}
| JavaScript | 0.000001 | @@ -2923,24 +2923,249 @@
n true;%0A%09%7D%0A%0A
+%09canBeCreated() %7B%0A%09%09return Meteor.isServer ?%0A%09%09%09RocketChat.authz.hasAtLeastOnePermission(Meteor.userId(), %5B%60create-$%7B this._identifier %7D%60%5D) :%0A%09%09%09RocketChat.authz.hasAtLeastOnePermission(%5B%60create-$%7B this._identifier %7D%60%5D);%0A%09%7D%0A%0A
%09canBeDelete
|
4444fb0bf4b046f7aab0135ba57657d17edeac8b | Fix formatting. | docs/.vuepress/config.js | docs/.vuepress/config.js | const _ = require("lodash")
const vueSlugify = require("vuepress/lib/markdown/slugify")
const jf = require("jsonfile")
const path = require("path")
const packagePath = path.join(__dirname, "../../package.json")
const version = jf.readFileSync(packagePath).version
const versionWithLowDashs = version.replace(/\./g, "_")
const slugMap = {
"Common Prefix Ambiguities": "COMMON_PREFIX",
"None Unique Grammar Name Found": "UNIQUE_GRAMMAR_NAME",
"Terminal Token Name Not Found": "TERMINAL_NAME_NOT_FOUND",
"No LINE_BREAKS Found": "LINE_BREAKS",
"Unexpected RegExp Anchor Error": "ANCHORS",
"Token can never be matched": "UNREACHABLE",
"Complement Sets cannot be automatically optimized": "COMPLEMENT",
"Failed parsing < /.../ > Using the regexp-to-ast library":
"REGEXP_PARSING",
"The regexp unicode flag is not currently supported by the regexp-to-ast library":
"UNICODE_OPTIMIZE",
"TokenType <...> is using a custom token pattern without providing <char_start_hint> parameter":
"CUSTOM_OPTIMIZE",
"Why should I use a Parsing DSL instead of a Parser Generator?":
"VS_GENERATORS",
"What Differentiates Chevrotain from other JavaScript Parsing Solutions?":
"VS_OTHERS",
"Why are Error Recovery / Fault Tolerant capabilities needed in a Parser?":
"WHY_ERROR_RECOVERY",
"How do I debug my parser?": "DEBUGGING",
"Why are the unique numerical suffixes (CONSUME1/CONSUME2/...) needed for the DSL Rules?":
"NUMERICAL_SUFFIXES",
"Why does Chevrotain not work correctly after I minified my Grammar?":
"MINIFIED",
"Why does Chevrotain not work correctly after I webpacked my Grammar?":
"WEBPACK",
"Why does my parser appear to be stuck during it's initialization?":
"STUCK_AMBIGUITY",
"How do I Maximize my parser's performance?": "PERFORMANCE",
"Unable to identify line terminator usage in pattern":
"IDENTIFY_TERMINATOR",
"A Custom Token Pattern should specify the <line_breaks> option":
"CUSTOM_LINE_BREAK",
"Missing <lineTerminatorCharacters> property on the Lexer config":
"MISSING_LINE_TERM_CHARS"
}
const slugMapUsed = _.mapValues(slugMap, () => false)
module.exports = {
title: "Chevrotain",
base: "/chevrotain/docs/",
description: "Parser Building Toolkit for JavaScript",
markdown: {
slugify: function(str) {
const mappedSlug = slugMap[str]
if (mappedSlug) {
// TODO: can we test all mappings have been used?
slugMapUsed[str] = true
return mappedSlug
}
return vueSlugify(str)
}
},
themeConfig: {
repo: "SAP/chevrotain",
docsDir: "docs",
docsBranch: "master",
editLinks: true,
editLinkText: "Edit this page on GitHub",
nav: [
{ text: "Home", link: "/" },
{ text: "Features", link: "/features/blazing_fast" },
{ text: "Tutorial", link: "/tutorial/step0_introduction" },
{ text: "Guide", link: "/guide/introduction" },
{ text: "FAQ", link: "/FAQ" },
{ text: "Changes", link: "/changes/BREAKING_CHANGES" },
{
text: "APIs",
link: `https://sap.github.io/chevrotain/documentation/${versionWithLowDashs}/globals.html`
},
{
text: "Playground",
link: "https://sap.github.io/chevrotain/playground/"
},
{
text: "Benchmark",
link: "https://sap.github.io/chevrotain/performance/"
},
{
text: "Chat",
link: "https://gitter.im/chevrotain-parser/Lobby"
}
],
sidebar: {
"/tutorial/": [
{
title: "Tutorial",
collapsable: false,
children: [
// "",
["step0_introduction", "Introduction"],
["step1_lexing", "Lexer"],
["step2_parsing", "Parser"],
["step3_adding_actions_root", "Semantics"],
[
"step3a_adding_actions_visitor",
"Semantics - CST Visitor"
],
[
"step3b_adding_actions_embedded",
"Semantics - Embedded"
],
["step4_fault_tolerance", "Fault Tolerance"]
]
}
],
"/guide/": [
{
title: "Guide",
collapsable: false,
children: [
["introduction", "Introduction"],
["concrete_syntax_tree", "CST"],
["generating_syntax_diagrams", "Syntax Diagrams"],
["custom_token_patterns", "Custom Token Patterns"],
[
"syntactic_content_assist",
"Syntactic Content Assist"
],
["custom_apis", "Custom APIs"],
[
"resolving_grammar_errors",
"Resolving Grammar Errors"
],
["resolving_lexer_errors", "Resolving Lexer Errors"]
]
}
],
"/features/": [
{
title: "Features",
collapsable: false,
children: [
["blazing_fast", "Blazing Fast"],
["llk", "LL(K) Grammars"],
["separation", "Separation of Grammar and Semantics"],
["easy_debugging", "Easy Debugging"],
["fault_tolerance", "Fault Tolerance"],
["multiple_start_rules", "Multiple Start Rules"],
["custom_errors", "Customizable Error Messages"],
["parameterized_rules", "Parameterized Rules"],
["gates", "Gates"],
[
"syntactic_content_assist",
"Syntactic Content Assist"
],
["grammar_inheritance", "Grammar Inheritance"],
["backtracking", "Backtracking"],
["syntax_diagrams", "Syntax Diagrams"],
["regexp", "RegExp Based Lexers"],
["position_tracking", "Position Tracking"],
["token_alternative_matches", "Token Alternative Matches"],
["token_skipping", "Token Skipping"],
["token_grouping", "Token Grouping"]
]
}
],
"/changes/": [
{
title: "Changes",
collapsable: false,
children: [
["BREAKING_CHANGES", "Breaking Changes"],
["CHANGELOG", "ChangeLog"]
]
}
]
}
}
}
| JavaScript | 0.000017 | @@ -6899,36 +6899,93 @@
%5B
-%22token_alternative_matches%22,
+%0A %22token_alternative_matches%22,%0A
%22To
@@ -7008,16 +7008,41 @@
Matches%22
+%0A
%5D,%0A
|
d7389c9b0f1ff073f9edc5b53e13579474845304 | delete space line | test/app.model-test.js | test/app.model-test.js | import expect from 'expect';
import React from 'react';
import dva from '../src/index';
import dvaM from '../src/mobile';
describe('app.model', () => {
it('namespace: type error', () => {
const app = dva();
expect(_ => {
app.model({});
}).toThrow(/app.model: namespace should be defined/);
expect(_ => {
app.model({
namespace: 'routing',
});
}).toThrow(/app.model: namespace should not be routing/);
const appM = dvaM();
expect(_ => {
appM.model({
namespace: 'routing',
});
}).toNotThrow();
});
it('namespace: unique error', () => {
const app = dva();
expect(_ => {
app.model({
namespace: 'repeat'
});
app.model({
namespace: 'repeat'
});
}).toThrow(/app.model: namespace should be unique/);
});
it('dynamic model', () => {
let count = 0;
const app = dva();
app.model({
namespace: 'users',
state: [],
reducers: {
'add'(state, { payload }) {
return [...state, payload];
},
},
});
app.router(_ => <div />);
app.start();
// inject model
app.model({
namespace: 'tasks',
state: [],
reducers: {
'add'(state, { payload }) {
return [...state, payload];
},
},
effects: {
*'add'() {
yield 1;
count = count + 1;
},
},
subscriptions: {
setup() {
count = count + 1;
},
},
});
// subscriptions
expect(count).toEqual(1);
// reducers
app._store.dispatch({ type: 'tasks/add', payload: 'foo' });
app._store.dispatch({ type: 'users/add', payload: 'foo' });
const state = app._store.getState();
expect(state.users).toEqual(['foo']);
expect(state.tasks).toEqual(['foo']);
// effects
expect(count).toEqual(2);
});
it('don\'t inject if exists', () => {
const app = dva();
let count = 0;
const model = {
namespace: 'count',
state: 0,
subscriptions: {
setup() {
count += 1;
},
},
};
app.model(model);
app.router(() => 1);
app.start();
app.model(model);
expect(count).toEqual(1);
});
});
| JavaScript | 0.001108 | @@ -825,17 +825,16 @@
ique/);%0A
-%0A
%7D);%0A%0A
|
99dad6906144359eaad06deb2cd00d20e5995ee8 | Add debugger to stop at edge case point. | src/js/messages.js | src/js/messages.js | if (typeof(messages) === "undefined") {
var messages = {};
}
else {
console.error("There is already a global variable called \"messages\".");
}
function aMsg(key, message){
if (arguments.length === 2 && typeof(key) === "string" && iStr(message)) {
messages[key] = message;
}
else
if (arguments.length === 1 && typeof(key) === "object"){
var p;
for (p in key) {
aMsg(p, key[p]);
}
}
}
function gMsg(key, args){
if (!key) {
throw "No message key specified";
}
var msg = messages[key] || key;
var n = arguments.length, msgArgs;
if (n > 2) {
msgArgs = {};
for (i = 1; i < n; i++){
msgArgs[i] = arguments[i];
}
}
else
if (n === 2) {
msgArgs = args;
if (typeof(msgArgs) !== "object") {
msgArgs = {"1": msgArgs}
}
}
var msgArg;
for (msgArg in msgArgs) {
var re = new RegExp("\\$\\{" + msgArg + "\\}", "ig");
msg = msg.replace(re, msgArgs[msgArg]);
}
return msg;
} | JavaScript | 0 | @@ -493,16 +493,30 @@
ified%22;%0A
+ debugger;%0A
%7D%0A va
|
161f380a59cac98ac33e460dfff99b6126e242a5 | enable 'fork' as a valid ganacheOption to use within truffle develop (lib/commands/develop.js) | packages/truffle-core/lib/commands/develop.js | packages/truffle-core/lib/commands/develop.js | const emoji = require("node-emoji");
const mnemonicInfo = require("truffle-core/lib/mnemonics/mnemonic");
const command = {
command: "develop",
description: "Open a console with a local development blockchain",
builder: {
log: {
type: "boolean",
default: false
}
},
help: {
usage: "truffle develop",
options: []
},
runConsole: (config, ganacheOptions, done) => {
const Console = require("../console");
const { Environment } = require("truffle-environment");
const commands = require("./index");
const excluded = ["console", "develop", "unbox", "init"];
const availableCommands = Object.keys(commands).filter(
name => !excluded.includes(name)
);
const consoleCommands = availableCommands.reduce(
(acc, name) => Object.assign({}, acc, { [name]: commands[name] }),
{}
);
Environment.develop(config, ganacheOptions)
.then(() => {
const c = new Console(
consoleCommands,
config.with({ noAliases: true })
);
c.start(done);
c.on("exit", () => process.exit());
})
.catch(err => done(err));
},
run: (options, done) => {
const Config = require("truffle-config");
const { Develop } = require("truffle-environment");
const config = Config.detect(options);
const customConfig = config.networks.develop || {};
const { mnemonic, accounts, privateKeys } = mnemonicInfo.getAccountsInfo(
customConfig.accounts || 10
);
const onMissing = () => "**";
const warning =
":warning: Important :warning: : " +
"This mnemonic was created for you by Truffle. It is not secure.\n" +
"Ensure you do not use it on production blockchains, or else you risk losing funds.";
const ipcOptions = { log: options.log };
const ganacheOptions = {
host: customConfig.host || "127.0.0.1",
port: customConfig.port || 9545,
network_id: customConfig.network_id || 5777,
total_accounts: customConfig.accounts || 10,
default_balance_ether: customConfig.defaultEtherBalance || 100,
blockTime: customConfig.blockTime || 0,
mnemonic,
gasLimit: customConfig.gas || 0x6691b7,
gasPrice: customConfig.gasPrice || 0x77359400,
noVMErrorsOnRPCResponse: true
};
if (customConfig.hardfork !== null && customConfig.hardfork !== undefined) {
ganacheOptions["hardfork"] = customConfig.hardfork;
}
function sanitizeNetworkID(network_id) {
if (network_id !== "*") {
if (!parseInt(network_id, 10)) {
const error =
`The network id specified in the truffle config ` +
`(${network_id}) is not valid. Please properly configure the network id as an integer value.`;
throw new Error(error);
}
return network_id;
} else {
// We have a "*" network. Return the default.
return 5777;
}
}
ganacheOptions.network_id = sanitizeNetworkID(ganacheOptions.network_id);
Develop.connectOrStart(ipcOptions, ganacheOptions, started => {
const url = `http://${ganacheOptions.host}:${ganacheOptions.port}/`;
if (started) {
config.logger.log(`Truffle Develop started at ${url}`);
config.logger.log();
config.logger.log(`Accounts:`);
accounts.forEach((acct, idx) => config.logger.log(`(${idx}) ${acct}`));
config.logger.log();
config.logger.log(`Private Keys:`);
privateKeys.forEach((key, idx) => config.logger.log(`(${idx}) ${key}`));
config.logger.log();
config.logger.log(`Mnemonic: ${mnemonic}`);
config.logger.log();
config.logger.log(emoji.emojify(warning, onMissing));
config.logger.log();
} else {
config.logger.log(
`Connected to existing Truffle Develop session at ${url}`
);
config.logger.log();
}
if (!options.log) {
command.runConsole(config, ganacheOptions, done);
}
});
}
};
module.exports = command;
| JavaScript | 0 | @@ -2149,16 +2149,47 @@
e %7C%7C 0,%0A
+ fork: customConfig.fork,%0A
mn
|
b28caec8eb1c88b130e779ee7cf615f88b54332f | Transform fillRule attribute to fill-rule | src/js/utils/ReactSVG.js | src/js/utils/ReactSVG.js | var DOMProperty = require('react/lib/DOMProperty');
var svgAttrs = ['dominant-baseline', 'shape-rendering', 'mask'];
// hack for getting react to render svg attributes
DOMProperty.injection.injectDOMPropertyConfig({
isCustomAttribute: function (attribute) {
return svgAttrs.includes(attribute);
}
});
| JavaScript | 0.000001 | @@ -210,16 +210,70 @@
onfig(%7B%0A
+ DOMAttributeNames: %7B%0A fillRule: 'fill-rule'%0A %7D,%0A
isCust
@@ -349,16 +349,92 @@
ibute);%0A
+ %7D,%0A Properties: %7B%0A fillRule: DOMProperty.injection.MUST_USE_ATTRIBUTE%0A
%7D%0A%7D);%0A
|
579d4048b17ff3edd40dc6ca8e02e40a526703f4 | improve test context with more describes | test/components/error_spec.js | test/components/error_spec.js | import PlayerError from '../../src/components/error'
import Core from '../../src/components/core'
import Events from '../../src/base/events'
describe('PlayerError', function() {
beforeEach(function() {
this.core = new Core({})
this.errorData = {
code: 'test_01',
description: 'test error',
level: PlayerError.Levels.FATAL,
origin: 'test',
scope: 'it',
raw: {},
}
})
it('trigger ERROR with error data when error method is called', function() {
sinon.spy(this.core, 'trigger')
PlayerError.error(this.errorData)
assert.ok(this.core.trigger.calledWith(Events.ERROR, {
code: 'test_01',
description: 'test error',
level: PlayerError.Levels.FATAL,
origin: 'test',
scope: 'it',
raw: {},
}))
})
it('does not trigger ERROR when core is not setted', function() {
sinon.spy(this.core, 'trigger')
PlayerError.core = undefined
PlayerError.error(this.errorData)
assert.notOk(this.core.trigger.calledWith(Events.ERROR, this.errorData))
})
})
| JavaScript | 0.000424 | @@ -410,24 +410,81 @@
%7D%0A %7D)%0A%0A
+ describe('when error method is called', function() %7B%0A
it('trigge
@@ -491,16 +491,22 @@
r ERROR
+event
with err
@@ -516,36 +516,8 @@
data
- when error method is called
', f
@@ -520,32 +520,34 @@
', function() %7B%0A
+
sinon.spy(th
@@ -562,32 +562,34 @@
'trigger')%0A
+
+
PlayerError.erro
@@ -599,32 +599,34 @@
his.errorData)%0A%0A
+
assert.ok(th
@@ -666,32 +666,34 @@
.ERROR, %7B%0A
+
code: 'test_01',
@@ -685,32 +685,34 @@
ode: 'test_01',%0A
+
descriptio
@@ -726,32 +726,34 @@
t error',%0A
+
level: PlayerErr
@@ -767,32 +767,34 @@
ls.FATAL,%0A
+
+
origin: 'test',%0A
@@ -785,32 +785,34 @@
origin: 'test',%0A
+
scope: 'it
@@ -812,32 +812,34 @@
pe: 'it',%0A
+
raw: %7B%7D,%0A %7D))
@@ -839,20 +839,24 @@
+
+
%7D))%0A
+
%7D)%0A%0A
it('
@@ -855,35 +855,20 @@
%0A%0A
-it('does not trigger ERROR
+ describe('
when
@@ -898,24 +898,76 @@
unction() %7B%0A
+ it('does not trigger ERROR', function() %7B%0A
sinon.sp
@@ -990,24 +990,28 @@
igger')%0A
+
+
PlayerError.
@@ -1027,16 +1027,20 @@
defined%0A
+
Play
@@ -1066,24 +1066,28 @@
errorData)%0A%0A
+
assert.n
@@ -1151,16 +1151,32 @@
rData))%0A
+ %7D)%0A %7D)%0A
%7D)%0A%7D)%0A
|
fea885ef9854e28c330fe47131ce14be87950383 | Dumb merge conflicts are dumb | web/src/reducers/project-reducer.js | web/src/reducers/project-reducer.js | import { handleActions } from 'redux-actions'
import moment from 'moment'
const initialState = {
projectData: {},
weekFrom: moment().startOf('isoWeek'),
weekTo: moment().add(5, 'week').startOf('isoWeek'),
isLoading: true,
availableProjects: [],
dirty: false
}
const projectReducer = handleActions({
ADD_PROJECT : (state, action) => ({
...state,
projectData: {
...state.projectData,
[ action.payload.newProject.uuid ] : {
...action.payload.newProject
}
},
dirty: true
}),
REMOVE_PROJECT : (state, action) => {
const { projectId } = action.payload
const projectData = Object.values(state.projectData).reduce((accumulator, currentValue) => {
const { uuid } = currentValue
if (uuid === projectId) {
currentValue.isHidden = true;
currentValue.values = Object.values(currentValue.values).reduce((accumulator, value) => {
return {
...accumulator,
[ value.Week_Start__c ]: {
...value,
Hours__c: 0
}
};
}, {})
}
return {
...accumulator,
[ uuid ]: currentValue
}
}, {})
return {
...state,
projectData,
dirty: true
}
},
PROJECT_UUID_TO_ID_UPDATE : (state, action) => ({
...state,
projectData: {
...state.projectData,
[ action.payload.uuid ] : {
...state.projectData[action.payload.uuid],
Id: action.payload.projectId
}
}
}),
SET_RESOURCES : (state, action) => ({
...state,
projectData: action.payload.projectData,
dirty: false
}),
SET_PROJECTS : (state, action) => ({
...state,
availableProjects: action.payload.availableProjects,
dirty: false
}),
UPDATE_RESOURCE_VALUE : (state, action) => {
const { hours, week, projectId } = action.payload
const currentValue = state.projectData[projectId].values[week];
const values = {
...state.projectData[projectId].values,
[ week ] : {
...currentValue,
Hours__c: hours,
Week_Start__c: week
}
}
return {
...state,
projectData: {
...state.projectData,
[ projectId ]: {
...state.projectData[projectId],
values
}
},
dirty: true
}
},
UPDATE_WEEKS : (state, action) => ({
...state,
weekFrom: moment(action.payload.weekFrom),
weekTo: moment(action.payload.weekTo),
isLoading: true
}),
SAVE_TO_SERVER : (state, action) => ({
...state,
isLoading: true
}),
SAVE_SUCCESS : (state, action) => ({
...state,
isLoading: false,
dirty: false
}),
SAVE_ERROR : (state, action) => ({ ...state }),
SET_IS_LOADING : (state, action) => ({
...state,
isLoading: action.payload.isLoading
})
}, initialState)
export default projectReducer
| JavaScript | 0.999543 | @@ -1508,24 +1508,41 @@
%7D%0A %7D
+,%0A dirty: true
%0A %7D),%0A%0A SE
@@ -1774,34 +1774,16 @@
Projects
-,%0A dirty: false
%0A %7D),%0A%0A
|
6fae94f63f5820d61e6e17e5d7c2599d02904de2 | Update projects.js | src/js/projects.js | src/js/projects.js | function(){
var xhr = new XMLHttpRequest();
xhr.open("GET","https://scratch.mit.edu/site-api/projects/in/1000000/1/",true);
xhr.responseType = "document";
xhr.onload = function() {
if(this.status=='200'){var in=this.response.querySelectorAll("li"),i,out=document.querySelector("#scratch");for(i=0;i<in.length;i++)out.appendChild(in[i]);}
};
xhr.send();
})();
| JavaScript | 0.000001 | @@ -1,16 +1,17 @@
+(
function()%7B%0A va
|
f73b9ce04948cc674ea893295e237621ec1d7a50 | Use HTTPS endpoint for GFS grib filter service in tests | packages/weacast-alert/test/config/default.js | packages/weacast-alert/test/config/default.js | var path = require('path')
var containerized = require('containerized')()
var API_PREFIX = '/api'
module.exports = {
port: process.env.PORT || 8081,
apiPath: API_PREFIX,
host: 'localhost',
paginate: {
default: 10,
max: 50
},
authentication: {
secret: 'b5KqXTye4fVxhGFpwMVZRO3R56wS5LNoJHifwgGOFkB5GfMWvIdrWyQxEJXswhAC',
strategies: [
'jwt',
'local'
],
path: API_PREFIX + '/authentication',
service: API_PREFIX + '/users'
},
logs: {
Console: {
colorize: true,
level: 'verbose'
}
},
db: {
adapter: 'mongodb',
path: path.join(__dirname, '../db-data'),
url: (containerized ? 'mongodb://mongodb:27017/weacast-test' : 'mongodb://127.0.0.1:27017/weacast-test')
},
forecastPath: path.join(__dirname, '../forecast-data'),
forecasts: [
{
name: 'gfs-world',
label: 'GFS - 0.5°',
description: 'World-wide',
attribution: 'Forecast data from <a href="http://www.emc.ncep.noaa.gov/index.php?branch=GFS">NCEP</a>',
model: 'gfs',
baseUrl: 'http://nomads.ncep.noaa.gov/cgi-bin/filter_gfs_0p50.pl',
bounds: [0, -90, 360, 90],
origin: [0, 90],
size: [720, 361],
resolution: [0.5, 0.5],
tileResolution: [20, 20],
runInterval: 6 * 3600, // Produced every 6h
oldestRunInterval: 24 * 3600, // Don't go back in time older than 1 day
interval: 3 * 3600, // Steps of 3h
lowerLimit: 0, // From T0
upperLimit: 3 * 3600, // Up to T0+3
updateInterval: -1, // We will check for update manually for testing
keepPastForecasts: true, // We will keep past forecast times so that the number of forecasts is predictable for tests
elements: [
{
name: 'u-wind',
variable: 'var_UGRD',
levels: ['lev_10_m_above_ground']
},
{
name: 'v-wind',
variable: 'var_VGRD',
levels: ['lev_10_m_above_ground']
}
]
}
]
}
| JavaScript | 0 | @@ -1061,16 +1061,17 @@
l: 'http
+s
://nomad
|
f22c0410674345addcdca95e9b861791598fe504 | update demo | packages/yhtml5-scripts/demo/spa/src/index.js | packages/yhtml5-scripts/demo/spa/src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import './global.css'
import './index.css'
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { square, cube } from './features/treeShake';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
cube(5)
console.log('\nindex.js\n', {
process: process,
'process.env': process.env,
})
| JavaScript | 0 | @@ -235,16 +235,77 @@
eShake';
+%0A// const %7B square, cube %7D = require('./features/treeShake');
%0A%0AReactD
|
0e0c1f8741dc61bbdf292fdd6daf13075534c8a3 | test update | test/companies.spec.js | test/companies.spec.js | /**
* Avalara © 2017
* file: test/companies.spec.js
*/
import Avatax from '../lib/AvaTaxClient';
import { v4 } from 'node-uuid';
import loadCreds from './helpers/load_creds';
import nock from 'nock';
import companyGetResponse from './fixtures/company_get_response';
import companiesListResponse from './fixtures/companies_list_response';
describe('Company Integration Tests', () => {
describe('Valid company initialize request', () => {
const clientCreds = loadCreds();
const client = new Avatax(clientCreds).withSecurity(clientCreds);
it('should initialize a company', () => {
const request = {
name: "Bob's Artisan Pottery",
companyCode: v4().replace(/-/gi, '').substring(0, 8),
taxpayerIdNumber: '12-3456789',
line1: '123 Main Street',
city: 'Irvine',
region: 'CA',
postalCode: '92615',
country: 'US',
firstName: 'Bob',
lastName: 'Example',
title: 'Owner',
email: 'bob@example.org',
phoneNumber: '714 555-2121',
mobileNumber: '714 555-1212'
};
return client.companyInitialize({ model: request }).then(res => {
expect(res).toBeDefined();
expect(res.contacts.length).toEqual(1);
expect(res.locations.length).toEqual(1);
expect(res.nexus.length).toEqual(3);
});
});
describe('Invalid company initialize request', () => {
it('should return valid exception response');
});
});
});
describe('Company Unit Tests', () => {
const clientCreds = loadCreds();
const baseUrl = 'https://sandbox-rest.avatax.com';
const client = new Avatax(clientCreds).withSecurity(clientCreds);
afterEach(() => {
nock.cleanAll();
});
describe('Get company by id', () => {
const id = 12345;
beforeEach(() => {
nock(baseUrl)
.get(`/api/v2/companies/${id}`)
.reply(200, companyGetResponse);
});
it('should return single company', () => {
return client.getCompany({ id }).then(res => {
expect(res).toEqual(companyGetResponse);
});
});
});
describe('Listing companies for account', () => {
beforeEach(() => {
nock(baseUrl).get(`/api/v2/companies`).reply(200, companiesListResponse);
});
it('should return list of companies', () => {
return client.queryCompanies().then(res => {
expect(res).toEqual(companiesListResponse);
});
});
});
});
| JavaScript | 0.000001 | @@ -1330,17 +1330,17 @@
toEqual(
-3
+2
);%0A
|
83b2889b4a6b8879d42b0deba98de7a4e004c9b6 | add devel aliases for BWS urls | src/js/controllers/preferencesBwsUrl.js | src/js/controllers/preferencesBwsUrl.js | 'use strict';
angular.module('copayApp.controllers').controller('preferencesBwsUrlController',
function($scope, configService, isMobile, isCordova, go, applicationService ) {
this.isSafari = isMobile.Safari();
this.isCordova = isCordova;
this.error = null;
this.success = null;
var config = configService.getSync();
this.bwsurl = config.bws.url;
this.save = function() {
var opts = {
bws: {
url: this.bwsurl,
}
};
configService.set(opts, function(err) {
if (err) console.log(err);
$scope.$emit('Local/BWSUpdated');
applicationService.restart();
});
};
});
| JavaScript | 0 | @@ -107,16 +107,21 @@
($scope,
+$log,
configS
@@ -400,24 +400,521 @@
unction() %7B%0A
+%0A var bws;%0A switch (this.bwsurl) %7B%0A case 'prod':%0A case 'production':%0A bws = 'https://bws.bitpay.com/bws/api'%0A break;%0A case 'sta':%0A case 'staging':%0A bws = 'https://bws-staging.b-pay.net/bws/api'%0A break;%0A case 'loc':%0A case 'local':%0A bws = 'http://localhost:3232/bws/api'%0A break;%0A %7D;%0A if (bws) %7B%0A $log.info('Using BWS URL Alias to ' + bws);%0A this.bwsurl = bws;%0A %7D%0A%0A
var op
|
71371ab9e62e4aa71bbe5bcfff1d4e55411a49ce | Clear selected block after rotation to make result immediately visible | assets/src/components/block-mover/index.js | assets/src/components/block-mover/index.js | /**
* This file is mainly copied from the default BlockMover component, there are some small differences.
* The arrows' labels are changed and are switched. Also, dragging is enabled even if the element is the only block.
**/
/**
* External dependencies
*/
import { first, partial, castArray } from 'lodash';
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { IconButton } from '@wordpress/components';
import { getBlockType } from '@wordpress/blocks';
import { Component } from '@wordpress/element';
import { withSelect, withDispatch } from '@wordpress/data';
import { withInstanceId, compose } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { upArrow, downArrow, dragHandle } from './icons';
import { IconDragHandle } from './drag-handle';
import IgnoreNestedEvents from './ignore-nested-events';
import './edit.css';
export class BlockMover extends Component {
constructor() {
super( ...arguments );
this.state = {
isFocused: false,
};
this.onFocus = this.onFocus.bind( this );
this.onBlur = this.onBlur.bind( this );
}
onFocus() {
this.setState( {
isFocused: true,
} );
}
onBlur() {
this.setState( {
isFocused: false,
} );
}
render() {
const { bringForward, sendBackward, isFirst, isLast, isDraggable, onDragStart, onDragEnd, clientIds, blockElementId, instanceId } = this.props;
const { isFocused } = this.state;
// We emulate a disabled state because forcefully applying the `disabled`
// attribute on the button while it has focus causes the screen to change
// to an unfocused state (body as active element) without firing blur on,
// the rendering parent, leaving it unable to react to focus out.
return (
<IgnoreNestedEvents childHandledEvents={ [ 'onDragStart', 'onMouseDown' ] }>
<div className={ classnames( 'amp-story-editor-block-mover editor-block-mover block-editor-block-mover', { 'is-visible': isFocused } ) }>
<IconButton
className="editor-block-mover__control block-editor-block-mover__control"
onClick={ isFirst ? null : bringForward }
icon={ upArrow }
label={ __( 'Bring Forward', 'amp' ) }
aria-describedby={ `editor-block-mover__up-description-${ instanceId }` }
aria-disabled={ isFirst }
onFocus={ this.onFocus }
onBlur={ this.onBlur }
/>
<IconDragHandle
className="editor-block-mover__control block-editor-block-mover__control"
icon={ dragHandle }
clientId={ clientIds }
blockElementId={ blockElementId }
isVisible={ isDraggable }
onDragStart={ onDragStart }
onDragEnd={ onDragEnd }
/>
<IconButton
className="editor-block-mover__control block-editor-block-mover__control"
onClick={ isLast ? null : sendBackward }
icon={ downArrow }
label={ __( 'Send Backward', 'amp' ) }
aria-describedby={ `editor-block-mover__down-description-${ instanceId }` }
aria-disabled={ isLast }
onFocus={ this.onFocus }
onBlur={ this.onBlur }
/>
</div>
</IgnoreNestedEvents>
);
}
}
export default compose(
withSelect( ( select, { clientIds } ) => {
const { getBlock, getBlockIndex, getTemplateLock, getBlockRootClientId } = select( 'core/block-editor' );
const firstClientId = first( castArray( clientIds ) );
const block = getBlock( firstClientId );
const rootClientId = getBlockRootClientId( first( castArray( clientIds ) ) );
return {
firstIndex: getBlockIndex( firstClientId, rootClientId ),
blockType: block ? getBlockType( block.name ) : null,
isLocked: getTemplateLock( rootClientId ) === 'all',
rootClientId,
};
} ),
withDispatch( ( dispatch, { clientIds, rootClientId } ) => {
const { moveBlocksDown, moveBlocksUp } = dispatch( 'core/block-editor' );
return {
bringForward: partial( moveBlocksDown, clientIds, rootClientId ),
sendBackward: partial( moveBlocksUp, clientIds, rootClientId ),
};
} ),
withInstanceId,
)( BlockMover );
| JavaScript | 0 | @@ -3783,16 +3783,36 @@
BlocksUp
+, clearSelectedBlock
%7D = dis
@@ -3841,16 +3841,17 @@
tor' );%0A
+%0A
%09%09return
@@ -3853,16 +3853,50 @@
eturn %7B%0A
+%09%09%09onDragEnd: clearSelectedBlock,%0A
%09%09%09bring
|
5d640926b721a0a7ac203ac90d761078370a3a9d | Set operator to 'and' for refinementLists | assets/tnd-search/instantsearch/widgets.js | assets/tnd-search/instantsearch/widgets.js | let timerId
export let tndWidgets = {
searchBox: {
queryHook(query, refine) {
clearTimeout(timerId);
timerId = setTimeout(() => refine(query), 500);
},
},
hits: {
transformItems(items) {
return items.map(item => ({
...item,
type: item.type.toUpperCase(),
}));
},
},
refinementBase: {
templates: {
item: `<a href="{{url}}" class="block w-full hover:bg-gray-400 px-3 -ml-3 py-1 text-gray-700{{#isRefined}} font-bold{{/isRefined}}">{{label}} <span class="text-xs text-gray-600 font-normal">({{count}})</span>
</a>`,
sortBy: ["name:asc", "count:desc"],
},
}
} | JavaScript | 0.000004 | @@ -630,16 +630,38 @@
desc%22%5D,%0A
+ operator: 'and'%0A
%7D,%0A
|
c2c051e06f04268686874b574466cb952492a2e3 | Update to the lastmodified-tracking sample. | lastmodified-tracking/index.js | lastmodified-tracking/index.js | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var Firebase = require('firebase');
var env = require('./env');
var ref = new Firebase(env.get('firebase.database.url'));
function touch(context) {
ref.auth(env.get('firebase.database.token'), function(error) {
if (error) {
context.done(error);
} else {
console.log('Authenticated successfully with admin rights');
ref.child('lastmodified').set(Firebase.ServerValue.TIMESTAMP);
context.done();
}
});
}
module.exports = {
touch: touch
} | JavaScript | 0 | @@ -749,40 +749,20 @@
rl')
-);%0A%0Afunction touch(context) %7B%0A
+, 'admin');%0A
ref.
@@ -804,89 +804,48 @@
en')
-, function(error) %7B%0A if (error) %7B%0A context.done(error);%0A %7D else
+);%0A%0Aexports.touch = function(context)
%7B%0A
-
co
@@ -903,20 +903,16 @@
ghts');%0A
-
ref.ch
@@ -969,16 +969,9 @@
TAMP
-);%0A
+,
con
@@ -983,58 +983,9 @@
done
-(
);%0A
- %7D%0A %7D);%0A%7D%0A%0Amodule.exports = %7B%0A touch: touch%0A
%7D
+;
|
5b7928d284e5c4b69d91d3e82e36ae0f7d5d2030 | Fix using `endsWith` method | test/entry/snapshot.js | test/entry/snapshot.js | import * as allIsFunctions from '../../src/utils/is'
import { create } from '../../src/entry/instance'
import { validateTypeOf } from '../../tools/validateBundle'
/**
* Based on an object with factory functions, create the expected
* structures for ES6 export and a mathjs instance.
* @param {Object} factories
* @return {{expectedInstanceStructure: Object, expectedES6Structure: Object}}
*/
export function createSnapshotFromFactories (factories) {
const math = create(factories)
const allFactoryFunctions = {}
const allFunctionsConstantsClasses = {}
const allFunctionsConstants = {}
const allTransformFunctions = {}
const allDependencyCollections = {}
const allClasses = {}
const allNodeClasses = {}
Object.keys(factories).forEach(factoryName => {
const factory = factories[factoryName]
const name = factory.fn
const isTransformFunction = factory.meta && factory.meta.isTransformFunction
const isClass = !isLowerCase(name[0]) && (validateTypeOf(math[name]) === 'Function')
const dependenciesName = factory.fn +
(isTransformFunction ? 'Transform' : '') +
'Dependencies'
allFactoryFunctions[factoryName] = 'Function'
allFunctionsConstantsClasses[name] = validateTypeOf(math[name])
allDependencyCollections[dependenciesName] = 'Object'
if (isTransformFunction) {
allTransformFunctions[name] = 'Function'
}
if (isClass) {
if (name.endsWith('Node')) {
allNodeClasses[name] = 'Function'
} else {
allClasses[name] = 'Function'
}
} else {
allFunctionsConstants[name] = validateTypeOf(math[name])
}
})
let embeddedDocs = {}
Object.keys(factories).forEach(factoryName => {
const factory = factories[factoryName]
const name = factory.fn
if (isLowerCase(factory.fn[0])) { // ignore class names starting with upper case
embeddedDocs[name] = 'Object'
}
})
embeddedDocs = exclude(embeddedDocs, [
'equalScalar',
'apply',
'addScalar',
'multiplyScalar',
'eye',
'print',
'divideScalar',
'parse',
'compile',
'parser',
'chain',
'reviver'
])
const allTypeChecks = {}
Object.keys(allIsFunctions).forEach(name => {
if (name.indexOf('is') === 0) {
allTypeChecks[name] = 'Function'
}
})
const allErrorClasses = {
ArgumentsError: 'Function',
DimensionError: 'Function',
IndexError: 'Function'
}
const expectedInstanceStructure = {
...allFunctionsConstantsClasses,
on: 'Function',
off: 'Function',
once: 'Function',
emit: 'Function',
'import': 'Function',
'var': 'Function',
'eval': 'Function',
'typeof': 'Function',
config: 'Function',
core: 'Function',
create: 'Function',
...allTypeChecks,
...allErrorClasses,
expression: {
transform: {
...allTransformFunctions
},
mathWithTransform: {
// note that we don't have classes here,
// only functions and constants are allowed in the editor
...exclude(allFunctionsConstants, [
'chain'
]),
'config': 'Function'
},
// deprecated stuff:
// docs: embeddedDocs,
node: {
...allNodeClasses
},
parse: 'Function',
Parser: 'Function'
},
// deprecated stuff:
type: {
...allTypeChecks,
...allClasses
},
json: {
reviver: 'Function'
},
error: {
...allErrorClasses
}
}
const expectedES6Structure = {
// functions
...exclude(allFunctionsConstantsClasses, [
'typeof',
'eval',
'var',
'E',
'false',
'Infinity',
'NaN',
'null',
'PI',
'true'
]),
core: 'Function',
create: 'Function',
config: 'Function',
factory: 'Function',
deprecatedEval: 'Function',
deprecatedImport: 'Function',
deprecatedVar: 'Function',
deprecatedTypeof: 'Function',
'_true': 'boolean',
'_false': 'boolean',
'_null': 'null',
'_Infinity': 'number',
'_NaN': 'number',
...allTypeChecks,
...allErrorClasses,
...allDependencyCollections,
...allFactoryFunctions,
docs: embeddedDocs,
// deprecated stuff:
expression: {
node: {
...allNodeClasses
},
parse: 'Function',
Parser: 'Function'
},
type: {
...allTypeChecks,
...allClasses
},
json: {
reviver: 'Function'
},
error: {
...allErrorClasses
}
}
return {
expectedInstanceStructure,
expectedES6Structure
}
}
/**
* Create a copy of the provided `object` and delete
* all properties listed in `excludedProperties`
* @param {Object} object
* @param {string[]} excludedProperties
* @return {Object}
*/
function exclude (object, excludedProperties) {
const strippedObject = Object.assign({}, object)
excludedProperties.forEach(excludedProperty => {
delete strippedObject[excludedProperty]
})
return strippedObject
}
function isLowerCase (text) {
return typeof text === 'string' && text.toLowerCase() === text
}
| JavaScript | 0.000097 | @@ -155,16 +155,66 @@
eBundle'
+%0Aimport %7B endsWith %7D from '../../src/utils/string'
%0A%0A/**%0A *
@@ -1464,21 +1464,16 @@
if (
-name.
endsWith
@@ -1473,16 +1473,22 @@
ndsWith(
+name,
'Node'))
|
5e36a514b4651795d821633e5dde449b0d833c0a | Fix console promise test | test/html/js/console/index.js | test/html/js/console/index.js | import sinon from 'sinon';
import chai from 'chai';
const expect = chai.expect;
import * as fetch from '../../../../src/functions/fetch.js';
import checkConsoleLog from '../../../../src/html/js/console';
describe('html', function() {
describe('test console promise', function() {
let sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should return original URL even if JS contains console logs', () => {
const result = {
body: 'function something(text) { console.log("not minified javascript file"); }',
};
sandbox.stub(fetch, 'fetch').returns(result);
return new Promise((resolve, reject) => {
resolve('https://www.juffalow.com/jsfile.js');
})
.then(checkConsoleLog)
.then((url) => {
expect(url).to.equal('https://www.juffalow.com/jsfile.js');
});
});
});
});
| JavaScript | 0.000003 | @@ -526,220 +526,559 @@
nst
-result = %7B%0A body: 'function something(text) %7B console.log(%22not minified javascript file%22); %7D',%0A %7D;%0A%0A sandbox.stub(fetch, 'fetch').returns(result);%0A%0A return new Promise((resolve, reject) =%3E %7B
+html = %7B%0A body: '%3Chtml%3E%3Chead%3E%3Clink rel=%22stylesheet%22 href=%22https://juffalow.com/cssfile.css%22 /%3E%3C/head%3E%3Cbody%3E%3Cp%3EText%3C/p%3E%3Ca href=%22#%22%3Elink%3C/a%3E%3Cscript src=%22https://juffalow.com/jsfile.js%22%3E%3C/script%3E%3C/body%3E%3C/html%3E',%0A %7D;%0A%0A const result = %7B%0A body: 'function something(text) %7B console.log(%22not minified javascript file%22); %7D',%0A response: %7B%0A statusCode: 200,%0A %7D,%0A %7D;%0A%0A sandbox.stub(fetch, 'fetch').callsFake((url) =%3E %7B%0A switch (url) %7B%0A case 'https://juffalow.com/':%0A return html;
%0A
@@ -1088,16 +1088,13 @@
-resolve(
+case
'htt
@@ -1090,36 +1090,32 @@
case 'https://
-www.
juffalow.com/jsf
@@ -1113,33 +1113,59 @@
w.com/jsfile.js'
-)
+:%0A return result
;%0A %7D)%0A
@@ -1163,39 +1163,72 @@
%7D
-)
%0A
- .then(checkConsoleLog
+%7D);%0A%0A return checkConsoleLog('https://juffalow.com/'
)%0A
@@ -1240,19 +1240,23 @@
.then((
-url
+results
) =%3E %7B%0A
@@ -1275,58 +1275,148 @@
ect(
-url).to.equal('https://www.juffalow.com/jsfile.js'
+results.length).to.equal(1);%0A expect(results%5B0%5D.messages.length).to.equal(0);%0A expect(results%5B0%5D.errors.length).to.equal(1
);%0A
|
907b327dc1fdfac17e2068e4e63467d77660a50d | Add support for loading zipped .nes files. | src/lib/core/readers/abstract-reader.js | src/lib/core/readers/abstract-reader.js | import { loadModule } from "../utils/system"
var JSZip = loadModule({global: "JSZip", commonjs: "jszip"});
const ZIP_SIGNATURE = [0x50, 0x4B, 0x03, 0x04];
//=========================================================
// Base class of readers
//=========================================================
export class AbstractReader {
constructor() {
this.reset();
}
reset() {
this.offset = 0;
}
readByte() {
return this.read(1)[0];
}
read(length) {
var data = this.peek(length);
this.skip(length);
return data;
}
peek(length) {
return this.peekOffset(this.offset, length);
}
skip(length) {
this.offset += length;
if (this.offset > this.getLength()) {
throw new Error("Unexpected end of input.");
}
}
contains(signature) {
var data = this.peek(signature.length);
if (data.length !== signature.length) {
return false;
}
for (var i = 0; i < signature.length; i++) {
if (data[i] !== signature[i]) {
return false;
}
}
return true;
}
check(signature) {
if (!this.contains(signature)) {
throw new Error("Invalid input signature.");
}
this.skip(signature.length);
}
tryUnzip(data, onSuccess) {
if (this.contains(ZIP_SIGNATURE)) {
if (!JSZip) {
throw new Error("Unable to unzip data: JSZip library is not available.");
}
var files = JSZip(data).file(/^.*\.nes$/);
if (files.length > 0) {
onSuccess(files[0]);
}
}
}
}
| JavaScript | 0 | @@ -1610,16 +1610,17 @@
*%5C.nes$/
+i
);%0A
|
ad6dd4f61030228a81269c459978d50d40175075 | reset browserwidth again after last test | test/mobileResponsive.spec.js | test/mobileResponsive.spec.js | 'use strict';
jasmine.getFixtures().fixturesPath = 'base/test/fixtures';
var createWidget = require('./utils/createWidget');
var mockAjax = require('./utils/mockAjax');
var interact = require('./utils/commonInteractions');
/**
* Tests for mobile and responsive
*/
describe('Mobile & responsive', function() {
beforeEach(function(){
loadFixtures('main.html');
jasmine.Ajax.install();
mockAjax.all();
$('body').width(400);
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('should be able change day in mobile mode by clicking arrows', function(done) {
createWidget({
name: 'John Doe'
});
expect($('.fc-basicDay-view')).toBeInDOM()
var currentDay = $('.fc-day-header')[0].textContent;
var displayNameRect = $('.bookingjs-displayname')[0].getBoundingClientRect();
var clickableArrowRect = $('.fc-next-button')[0].getBoundingClientRect();
var overlap = !(displayNameRect.right < clickableArrowRect.left ||
displayNameRect.left > clickableArrowRect.right ||
displayNameRect.bottom < clickableArrowRect.top ||
displayNameRect.top > clickableArrowRect.bottom)
expect(overlap).toBe(false);
setTimeout(function() {
var calEventStart = interact.clickNextArrow();
setTimeout(function() {
var nextDay = $('.fc-day-header')[0].textContent;
expect(currentDay).not.toBe(nextDay);
done();
}, 100);
}, 200);
});
});
| JavaScript | 0 | @@ -219,16 +219,35 @@
ons');%0A%0A
+var browserWidth;%0A%0A
/**%0A * T
@@ -427,24 +427,62 @@
Ajax.all();%0A
+ browserWidth = $('body').width();%0A
$('body'
@@ -557,16 +557,51 @@
tall();%0A
+ $('body').width(browserWidth);%0A
%7D);%0A%0A
|
3cec35be026b57b824529378db691591e0ad5cf3 | Fix description comment | src/lib/storage/GuildStorageRegistry.js | src/lib/storage/GuildStorageRegistry.js | 'use babel';
'use strict';
import { Collection } from 'discord.js';
// Handle loading all GuildStorage objects
export default class GuildStorageRegistry extends Collection
{
constructor()
{
super();
}
// Allow guild lookup by Guild object or id string
get(guild)
{
return super.get(guild.id ? guild.id : guild);
}
// Return a collection of of guilds with a specific setting value
findAllBySetting(key, value)
{
let collection = new Collection();
this.forEach(guild =>
{
if (guild.getSetting(key) === value) collection.set(guild.id, guild);
});
if (collection.size === 0) return null;
return collection;
}
// Reset all guild settings to default
resetAllGuildSettings(defaults)
{
super.forEach(guild => guild.resetSettings(defaults));
}
}
| JavaScript | 0.000008 | @@ -77,15 +77,18 @@
dle
-loading
+storage of
all
|
4d16e61121a31f6cd326545067f7bd2d42a18c69 | Create custom Directive productButton | public/js/app.js | public/js/app.js | "use strict";
(function() {
var app = angular.module("gemStore", []);
app.controller("StoreController", function () {
this.product = gems;
});
app.controller("ReviewController", function () {
this.review = {};
this.addReview = function(product) {
this.review.createdOn = Date.now(); // returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
product.reviews.push(this.review);
this.review = {};
};
});
app.directive("productTitle", function () {
return {
restrict: "A",
templateUrl: "product-title.html"
}
});
app.directive("productPanels", function () {
return {
restrict: "E",
templateUrl: "product-panels.html",
controller: function () {
this.tab = 1;
this.setTab = function (setTab) {
this.tab = setTab;
};
this.isSet = function (setValue) {
return this.tab === setValue;
};
this.setActive = function (activeValue) {
return this.tab === activeValue;
};
},
controllerAs: "navTab"
}
});
app.directive("productGallery", function () {
return {
restrict: "E",
templateUrl: "product-gallery.html",
controller: function () {
this.currentImage = 0;
this.setCurrent = function (currentValue) {
this.currentImage = currentValue || 0;
};
this.toggleCurrent = function (toggleValue) {
if (this.currentImage === toggleValue) {
return false;
}
this.currentImage = toggleValue || 0;
};
this.setActive = function (activeValue) {
return this.currentImage === activeValue;
};
},
controllerAs: "gallery"
}
});
var gems = [
{
name: 'Azurite',
description: "Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems. Some gems have hidden qualities beyond their luster, beyond their shine... Azurite is one of those gems.",
shine: 8,
price: 110.50,
rarity: 7,
color: '#CCC',
faces: 14,
images: [
"images/gem-02.gif",
"images/gem-05.gif",
"images/gem-09.gif"
],
reviews: [{
stars: 5,
body: "I love this gem!",
author: "joe@example.org",
createdOn: 1397490980837
}, {
stars: 1,
body: "This gem sucks.",
author: "tim@example.org",
createdOn: 1397490980837
}],
canPurchase: true
},
{
name: 'Bloodstone',
description: "Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however. Origin of the Bloodstone is unknown, hence its low value. It has a very high shine and 12 sides, however.",
shine: 9,
price: 22.90,
rarity: 6,
color: '#EEE',
faces: 12,
images: [
"images/gem-01.gif",
"images/gem-03.gif",
"images/gem-04.gif"
],
reviews: [{
stars: 3,
body: "I think this gem was just OK, could honestly use more shine, IMO.",
author: "JimmyDean@example.org",
createdOn: 1397490980837
}, {
stars: 4,
body: "Any gem with 12 faces is for me!",
author: "gemsRock@example.org",
createdOn: 1397490980837
}],
canPurchase: true
},
{
name: 'Zircon',
description: "Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem. Zircon is our most coveted and sought after gem. You will pay much to be the proud owner of this gorgeous and high shine gem.",
shine: 70,
price: 1100,
rarity: 2,
color: '#000',
faces: 6,
images: [
"images/gem-06.gif",
"images/gem-07.gif",
"images/gem-10.gif"
],
reviews: [{
stars: 1,
body: "This gem is WAY too expensive for its rarity value.",
author: "turtleguyy@example.org",
createdOn: 1397490980837
}, {
stars: 1,
body: "BBW: High Shine != High Quality.",
author: "LouisW407@example.org",
createdOn: 1397490980837
}, {
stars: 1,
body: "Don't waste your rubles!",
author: "nat@example.org",
createdOn: 1397490980837
}],
canPurchase: true
}];
})();
| JavaScript | 0 | @@ -1781,16 +1781,152 @@
%0A %7D);%0A%0A
+ app.directive(%22productButton%22, function () %7B%0A return %7B%0A restrict: %22E%22,%0A templateUrl: %22product-button.html%22%0A %7D;%0A %7D);%0A%0A
var ge
|
48b502a34720e40ba769ef84481b0b8fe0206e2a | Enable chrome app feature flag | src/lib/feature-flags.js | src/lib/feature-flags.js | const isStaging = () => process.env.SCRATCH_ENV === 'staging';
const flagInUrl = flag => {
const url = (window.location && window.location.search) || '';
return url.indexOf(`${flag}=true`) !== -1;
};
module.exports = {
CHROME_APP_RELEASED: isStaging() && flagInUrl('CHROME_APP_RELEASED')
};
| JavaScript | 0 | @@ -1,12 +1,55 @@
+// eslint-disable-next-line no-unused-vars%0A
const isStag
@@ -100,16 +100,59 @@
ging';%0A%0A
+// eslint-disable-next-line no-unused-vars%0A
const fl
@@ -337,55 +337,12 @@
ED:
-isStaging() && flagInUrl('CHROME_APP_RELEASED')
+true
%0A%7D;%0A
|
916256ed1260e9657f971c2a08a19622279d512d | Add onEnter to react-router | public/js/app.js | public/js/app.js | /**
Coupley entry point for webpack
*/
//es6 imports
import React from 'react';
import ReactDOM from 'react-dom';
//Router components
import { Router, Route, Link, hashHistory } from 'react-router';
import Header from './components/base/Header.react';
import Home from './components/Home.react';
import Profile from './components/profile/profile.react';
import ActivityContainer from './components/profile/ActivityFeed/ActivityFeedContainer.react';
import About from './components/profile/About.react';
import Photos from './components/profile/Photos.react';
import Search from './components/Search.react';
import Admin from './components/admin/dashboard.react';
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/login" component={Home} />
<Route path="/dashboard" component={Admin} />
<Route path="/" component={Header}>
<Route path="/search" component={Search} />
<Route path="profile" component={Profile} >
<Route path="activityfeed" component={ActivityContainer} />
<Route path="about" component={About} />
<Route path="photos" component={Photos} />
</Route>
</Route>
</Router>
),
document.getElementById('content')
);
| JavaScript | 0 | @@ -661,16 +661,215 @@
eact';%0A%0A
+function requireAuth(nextState, replace) %7B%0A if(! localStorage.getItem('apitoken')) %7B%0A replace(%7B%0A pathname: '/login',%0A state: %7B nextPathname: nextState.location.pathname %7D%0A %7D)%0A %7D%0A%7D%0A%0A
ReactDOM
@@ -1044,16 +1044,39 @@
%7BHeader%7D
+ onEnter=%7BrequireAuth%7D
%3E%0A
|
446e1665894761e95a4ff279fceafd193ddc93d5 | fix macOS normalization test (#1916) | test/integration/case_or_encoding_change.js | test/integration/case_or_encoding_change.js | /* @flow */
/* eslint-env mocha */
const should = require('should')
const configHelpers = require('../support/helpers/config')
const cozyHelpers = require('../support/helpers/cozy')
const pouchHelpers = require('../support/helpers/pouch')
const TestHelpers = require('../support/helpers')
describe('Case or encoding change', () => {
// This test passes on a macOS workstation when using the docker container,
// since files are stored on an ext4 FS. But Travis macOS workers lack
// virtualization support, which means the cozy-stack will run directly on
// macOS with HFS+ and the test will fail (see below).
// Maybe we could create an ext4 volume on Travis and put the storage files
// there to better match the production environment?
if (process.env.TRAVIS && process.platform === 'darwin') {
it.skip('is unstable on Travis (macOS)')
return
}
let cozy, helpers
before(configHelpers.createConfig)
before(configHelpers.registerClient)
beforeEach(pouchHelpers.createDatabase)
beforeEach(cozyHelpers.deleteAll)
afterEach(() => helpers.local.clean())
afterEach(pouchHelpers.cleanDatabase)
after(configHelpers.cleanConfig)
beforeEach(async function() {
cozy = cozyHelpers.cozy
helpers = TestHelpers.init(this)
await helpers.local.setupTrash()
await helpers.remote.ignorePreviousChanges()
})
describe('directory', () => {
let dir, dir2
beforeEach(async () => {
// This will fail with a 409 conflict error when cozy-stack runs directly
// on macOS & HFS+ because a file with an equivalent name already exists.
dir = await cozy.files.createDirectory({ name: 'e\u0301' }) // 'é'
dir2 = await cozy.files.createDirectory({ name: 'foo' })
await helpers.remote.pullChanges()
await helpers.syncAll()
helpers.spyPouch()
should(await helpers.local.tree()).deepEqual([
'e\u0301/', // 'é/'
'foo/'
])
})
it('remote', async () => {
await cozy.files.updateAttributesById(dir._id, { name: '\u00e9' }) // 'é'
await cozy.files.updateAttributesById(dir2._id, { name: 'FOO' })
await helpers.remote.pullChanges()
await helpers.syncAll()
await helpers._local.watcher.start()
await helpers._local.watcher.stop()
await helpers.syncAll()
const tree = await helpers.local.tree()
switch (process.platform) {
case 'win32':
should(tree).deepEqual([
'FOO/',
'\u00e9/' // 'é/'
])
break
case 'darwin':
should(tree).deepEqual([
'FOO/',
'\u00e9/' // 'é/'
])
break
case 'linux':
should(tree).deepEqual([
'FOO/',
'\u00e9/' // 'é/'
])
}
})
})
})
| JavaScript | 0 | @@ -2613,38 +2613,40 @@
'
+e
%5Cu0
-0e9
+301
/' // '
-%C3%A9
+e%CC%81
/'%0A
|
7ce2a1a7d068fcb55f1d594d0a9d7d40084f895f | Remove "custom favicon" test | test/integration/middleware.favicon.test.js | test/integration/middleware.favicon.test.js | var _ = require('lodash');
var request = require('request');
var Sails = require('../../lib').Sails;
var assert = require('assert');
var fs = require('fs-extra');
var request = require('request');
var appHelper = require('./helpers/appHelper');
var path = require('path');
describe('middleware :: ', function() {
describe('favicon :: ', function() {
var appName = 'testApp';
before(function(done) {
this.timeout(5000);
appHelper.build(done);
});
after(function() {
process.chdir('../');
// appHelper.teardown();
});
describe('with no favicon file in the assets folder', function() {
before(function(done) {
appHelper.lift(function(err, _sailsServer) {
assert(!err);
sailsServer = _sailsServer;
return done();
});
});
after(function(done) {
sailsServer.lower(done);
});
it('the default sailboat favicon should be provided', function(done) {
var default_favicon = fs.readFileSync(path.resolve(__dirname, '../../lib/hooks/http/public/favicon.ico'));
request(
{
method: 'GET',
uri: 'http://localhost:1342/favicon.ico',
},
function(err, response, body) {
assert.equal(default_favicon.toString('utf-8'), body);
return done();
}
);
});
});
describe('with a favicon file in the assets folder', function() {
var customFaviconPath = path.resolve(__dirname, 'fixtures/favicon.ico');
before(function(done) {
console.log(customFaviconPath);
fs.copySync(customFaviconPath, path.resolve('../', appName, '.tmp/public/favicon.ico'));
appHelper.lift(function(err, _sailsServer) {
assert(!err);
sailsServer = _sailsServer;
return done();
});
});
after(function(done) {
sailsServer.lower(done);
});
it('the default sailboat favicon should be provided', function(done) {
var custom_favicon = fs.readFileSync(customFaviconPath);
request(
{
method: 'GET',
uri: 'http://localhost:1342/favicon.ico',
},
function(err, response, body) {
assert.equal(custom_favicon.toString('utf-8'), body);
return done();
}
);
});
});
});
});
| JavaScript | 0.000002 | @@ -1399,1005 +1399,8 @@
);%0A%0A
- describe('with a favicon file in the assets folder', function() %7B%0A%0A var customFaviconPath = path.resolve(__dirname, 'fixtures/favicon.ico');%0A before(function(done) %7B%0A console.log(customFaviconPath);%0A fs.copySync(customFaviconPath, path.resolve('../', appName, '.tmp/public/favicon.ico'));%0A appHelper.lift(function(err, _sailsServer) %7B%0A assert(!err);%0A sailsServer = _sailsServer;%0A return done();%0A %7D);%0A %7D);%0A%0A after(function(done) %7B%0A sailsServer.lower(done);%0A %7D);%0A%0A it('the default sailboat favicon should be provided', function(done) %7B%0A var custom_favicon = fs.readFileSync(customFaviconPath);%0A request(%0A %7B%0A method: 'GET',%0A uri: 'http://localhost:1342/favicon.ico',%0A %7D,%0A function(err, response, body) %7B%0A assert.equal(custom_favicon.toString('utf-8'), body);%0A return done();%0A %7D%0A );%0A%0A %7D);%0A%0A %7D);%0A%0A
%7D)
|
b84f8e2518b036edfeb43fadd9b08de4c9081d18 | update unit test | test/inventory/inventory-movement/report.js | test/inventory/inventory-movement/report.js | require("should");
var InventoryMovement = require("../../data-util/inventory/inventory-movement-data-util");
var helper = require("../../helper");
var moment = require("moment");
var validate = require("dl-models").validator.inventory.inventoryMovement;
var InventoryMovementManager = require("../../../src/managers/inventory/inventory-movement-manager");
var inventoryMovementManager = null;
//delete unitest data
// var DLModels = require('dl-models');
// var map = DLModels.map;
// var MachineType = DLModels.master.MachineType;
before('#00. connect db', function (done) {
helper.getDb()
.then(db => {
inventoryMovementManager = new InventoryMovementManager(db, {
username: 'dev'
});
done();
})
.catch(e => {
done(e);
});
});
var createdId;
it("#01. should success when create new data", function (done) {
InventoryMovement.getNewData()
.then((data) => inventoryMovementManager.create(data))
.then((id) => {
id.should.be.Object();
createdId = id;
done();
})
.catch((e) => {
done(e);
});
});
var createdData;
it(`#02. should success when get created data with id`, function (done) {
inventoryMovementManager.getSingleById(createdId)
.then((data) => {
data.should.instanceof(Object);
validate(data);
createdData = data;
done();
})
.catch((e) => {
done(e);
});
});
it('#03. should success when create report', function (done) {
var info = {};
info.storageId = createdData.storageId;
info.type = createdData.type;
info.productId = createdData.productId;
info.shiftIm = createdData.shiftIm;
info.dateFrom = moment("1970-01-01").format("YYYY-MM-DD");
info.dateTo = moment().format("YYYY-MM-DD");
inventoryMovementManager.getMovementReport(info)
.then(result => {
var inventoryMovement = result.data;
inventoryMovement.should.instanceof(Array);
inventoryMovement.length.should.not.equal(0);
done();
}).catch(e => {
done(e);
});
});
var resultForExcelTest = {};
it("#04. should success when read data", function (done) {
inventoryMovementManager.read({
filter: {
_id: createdId
}
})
.then((documents) => {
resultForExcelTest = documents;
documents.should.have.property("data");
documents.data.should.be.instanceof(Array);
documents.data.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
var filter = {};
it('#05. should success when get data for Excel Report', function (done) {
inventoryMovementManager.getXls(resultForExcelTest, filter)
.then(xlsData => {
xlsData.should.have.property('data');
xlsData.should.have.property('options');
xlsData.should.have.property('name');
done();
}).catch(e => {
done(e);
});
});
it("#06. should success when destroy all unit test data", function (done) {
inventoryMovementManager.destroy(createdData._id)
.then((result) => {
result.should.be.Boolean();
result.should.equal(true);
done();
})
.catch((e) => {
done(e);
});
});
| JavaScript | 0 | @@ -1558,690 +1558,8 @@
);%0A%0A
-it('#03. should success when create report', function (done) %7B%0A var info = %7B%7D;%0A info.storageId = createdData.storageId;%0A info.type = createdData.type;%0A info.productId = createdData.productId;%0A info.shiftIm = createdData.shiftIm;%0A info.dateFrom = moment(%221970-01-01%22).format(%22YYYY-MM-DD%22);%0A info.dateTo = moment().format(%22YYYY-MM-DD%22);%0A%0A inventoryMovementManager.getMovementReport(info)%0A .then(result =%3E %7B%0A var inventoryMovement = result.data;%0A inventoryMovement.should.instanceof(Array);%0A inventoryMovement.length.should.not.equal(0);%0A done();%0A %7D).catch(e =%3E %7B%0A done(e);%0A %7D);%0A%7D);%0A%0A%0A
var
@@ -1593,9 +1593,9 @@
(%22#0
-4
+3
. sh
@@ -1671,20 +1671,33 @@
Manager.
-read
+getMovementReport
(%7B%0A
@@ -2084,17 +2084,16 @@
);%0A%7D);%0A%0A
-%0A
var filt
@@ -2111,9 +2111,9 @@
('#0
-5
+4
. sh
@@ -2506,16 +2506,15 @@
);%0A%0A
-%0A
it(%22#0
-6
+5
. sh
|
8eaeeb09fe7dd3909d7c3a662ad4ca9ae6e75f49 | purge lint violations | server/09-typescript/temp.js | server/09-typescript/temp.js | var FooBar = (function () {
function FooBar() {
this.name = 'wil';
}
return FooBar;
}());
| JavaScript | 0 | @@ -1,8 +1,10 @@
+//
var FooB
@@ -19,24 +19,26 @@
nction () %7B%0A
+//
function
@@ -49,16 +49,18 @@
Bar() %7B%0A
+//
@@ -82,14 +82,18 @@
l';%0A
+//
%7D%0A
+//
@@ -107,14 +107,16 @@
FooBar;%0A
+//
%7D());%0A
|
342087edcadd7cbbb5393584e02247eb08981121 | Add missing semicolon | website/static/js/mithrilHelpers.js | website/static/js/mithrilHelpers.js | 'use strict';
var $ = require('jquery');
/* Send with ajax calls to work with api2 */
var apiV2Config = function (options) {
var defaults = {
withCredentials: true
}
var opts = $.extend({}, defaults, options);
return function (xhr) {
xhr.withCredentials = opts.withCredentials;
xhr.setRequestHeader('Content-Type', 'application/vnd.api+json;');
xhr.setRequestHeader('Accept', 'application/vnd.api+json; ext=bulk');
};
};
var unwrap = function (value) {
return typeof(value) === 'function' ? value() : value;
};
module.exports = {
apiV2Config: apiV2Config,
unwrap: unwrap
};
| JavaScript | 0.999999 | @@ -175,16 +175,17 @@
ue%0A %7D
+;
%0A var
|
3108048b778c48575cb53e252f6594f2b90dd88d | fix master? | test/protractorWithoutRestartBrowserConf.js | test/protractorWithoutRestartBrowserConf.js | /*
* Copyright 2014 TWO SIGMA OPEN SOURCE, 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
*
* 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 helper = require('./helper.js');
var config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
framework: 'jasmine2',
allScriptsTimeout: 100000,
restartBrowserBetweenTests: false,
jasmineNodeOpts: {
defaultTimeoutInterval: 100000,
print: function() {}
},
capabilities: {
shardTestFiles: true,
maxInstances: 3,
browserName: 'firefox'
},
getMultiCapabilities: helper.getFirefoxProfile,
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({
displayStacktrace: 'specs'
}));
},
specs: [
'tests/tutorials/groovy_plotting/category-plot-tutorial.js',
'tests/tutorials/groovy_plotting/charting-tutorial.js',
'tests/tutorials/groovy_plotting/plot-features-tutorial.js',
'tests/tutorials/groovy_plotting/heatmap-tutorial.js',
'tests/tutorials/groovy_plotting/treemap-tutorial.js',
'tests/tutorials/groovy_plotting/histogram-tutorial.js',
'tests/tutorials/groovy_plotting/levelsOfDetail-tutorial.js',
'tests/tutorials/groovy_plotting/plotActions-tutorial.js',
'tests/tutorials/language_demos/sql-tutorial.js',
'tests/tutorials/language_demos/java-tutorial.js',
'tests/tutorials/language_demos/groovy-tutorial.js',
'tests/tutorials/language_demos/clojure-tutorial.js',
'tests/tutorials/language_demos/python-tutorial.js',
'tests/tutorials/language_demos/jscript-tutorial.js',
'tests/tutorials/language_demos/R-tutorial.js',
'tests/tutorials/language_demos/nodejs-tutorial.js',
'tests/tutorials/standard_visual_api/d3js-tutorial.js',
'tests/tutorials/standard_visual_api/p5js-tutorial.js',
'tests/tutorials/automate/progress-reporting-tutorial.js',
'tests/tutorials/automate/notebookControl-tutorial.js',
'tests/tutorials/automate/notebook-reflection-tutorial.js',
'tests/tutorials/automate/dashboard-tutorial.js',
'tests/tables.js',
'tests/tutorials/native_plotting/jscriptPlot-tutorial.js',
'tests/tutorials/table_display/tableGroovy-tutorial.js',
'tests/tutorials/feature_overview/autotranslation-tutorial.js',
'tests/tutorials/feature_overview/codeReuse-tutorial.js',
'tests/tutorials/feature_overview/beakerObject-tutorial.js',
'tests/tutorials/feature_overview/outputContainer-tutorial.js',
'tests/tutorials/feature_overview/bigIntegerTables-tutorial.js',
'tests/tutorials/feature_overview/text-tutorial.js'
]
};
exports.config = config;
| JavaScript | 0 | @@ -2630,32 +2630,34 @@
torial.js',%0A
+//
'tests/tutorials
|
3f7fbad642da740ee4231ba4b9ebe038f81198e4 | Build Comment component | public/js/app.js | public/js/app.js | /*
CommentBox
*/
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList />
<CommentForm />
</div>
);
}
});
/*
CommentList
*/
var CommentList = React.createClass({
render: function() {
return (
<div className="commentList">
Hello, world! I am a CommentList.
</div>
);
}
});
/*
CommentForm
*/
var CommentForm = React.createClass({
render: function() {
return (
<div className="commentForm">
Hello, world! I am a CommentForm.
</div>
);
}
});
/*
Initialize the app
*/
React.render(
<CommentBox />,
document.getElementById('content')
);
| JavaScript | 0 | @@ -369,41 +369,423 @@
-Hello, world! I am a CommentList.
+%3CComment author=%22Pete Hunt%22%3EThis is one comment%3C/Comment%3E%0A %3CComment author=%22Jordan Walke%22%3EThis is *another* comment%3C/Comment%3E%0A %3C/div%3E%0A );%0A %7D%0A%7D);%0A%0A/*%0A Comment%0A */%0A%0Avar Comment = React.createClass(%7B%0A render: function() %7B%0A return (%0A %3Cdiv className=%22comment%22%3E%0A %3Ch2 className=%22commentAuthor%22%3E%0A %7Bthis.props.author%7D%0A %3C/h2%3E%0A%0A %7Bmarked(this.props.children.toString())%7D%0A
%0A
|
ede8c293fc5f7a1c02c8d20f211b90536beb8515 | Fix for #1643 | public/js/ff/accounts/reconcile.js | public/js/ff/accounts/reconcile.js | /*
* reconcile.js
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III 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.
*
* Firefly III 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 Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
/** global: overviewUri, transactionsUri, indexUri,accounting */
var balanceDifference = 0;
var difference = 0;
var selectedAmount = 0;
var reconcileStarted = false;
var changedBalances = false;
/**
*
*/
$(function () {
"use strict";
/*
Respond to changes in balance statements.
*/
$('input[type="number"]').on('change', function () {
if (reconcileStarted) {
calculateBalanceDifference();
difference = balanceDifference - selectedAmount;
updateDifference();
}
changedBalances = true;
});
/*
Respond to changes in the date range.
*/
$('input[type="date"]').on('change', function () {
if (reconcileStarted) {
// hide original instructions.
$('.select_transactions_instruction').hide();
// show date-change warning
$('.date_change_warning').show();
// show update button
$('.change_date_button').show();
}
});
$('.change_date_button').click(startReconcile);
$('.start_reconcile').click(startReconcile);
$('.store_reconcile').click(storeReconcile);
});
function storeReconcile() {
// get modal HTML:
var ids = [];
$.each($('.reconcile_checkbox:checked'), function (i, v) {
ids.push($(v).data('id'));
});
var cleared = [];
$.each($('input[class="cleared"]'), function (i, v) {
var obj = $(v);
cleared.push(obj.data('id'));
});
var variables = {
startBalance: parseFloat($('input[name="start_balance"]').val()),
endBalance: parseFloat($('input[name="end_balance"]').val()),
startDate: $('input[name="start_date"]').val(),
startEnd: $('input[name="end_date"]').val(),
transactions: ids,
cleared: cleared,
};
var uri = overviewUri.replace('%start%', $('input[name="start_date"]').val()).replace('%end%', $('input[name="end_date"]').val());
$.getJSON(uri, variables).done(function (data) {
$('#defaultModal').empty().html(data.html).modal('show');
});
}
/**
* What happens when you check a checkbox:
* @param e
*/
function checkReconciledBox(e) {
var el = $(e.target);
var amount = parseFloat(el.val());
// if checked, add to selected amount
if (el.prop('checked') === true && el.data('younger') === false) {
selectedAmount = selectedAmount - amount;
}
if (el.prop('checked') === false && el.data('younger') === false) {
selectedAmount = selectedAmount + amount;
}
difference = balanceDifference - selectedAmount;
updateDifference();
}
/**
* Calculate the difference between given start and end balance
* and put it in balanceDifference.
*/
function calculateBalanceDifference() {
var startBalance = parseFloat($('input[name="start_balance"]').val());
var endBalance = parseFloat($('input[name="end_balance"]').val());
balanceDifference = startBalance - endBalance;
}
/**
* Grab all transactions, update the URL and place the set of transactions in the box.
* This more or less resets the reconciliation.
*/
function getTransactionsForRange() {
// clear out the box:
$('#transactions_holder').empty().append($('<p>').addClass('text-center').html('<i class="fa fa-fw fa-spin fa-spinner"></i>'));
var uri = transactionsUri.replace('%start%', $('input[name="start_date"]').val()).replace('%end%', $('input[name="end_date"]').val());
var index = indexUri.replace('%start%', $('input[name="start_date"]').val()).replace('%end%', $('input[name="end_date"]').val());
window.history.pushState('object or string', "Reconcile account", index);
$.getJSON(uri).done(placeTransactions);
}
/**
* Loop over all transactions that have already been cleared (in the range) and add this to the selectedAmount.
*
*/
function includeClearedTransactions() {
$.each($('input[class="cleared"]'), function (i, v) {
var obj = $(v);
if (obj.data('younger') === false) {
selectedAmount = selectedAmount - parseFloat(obj.val());
}
});
}
/**
* Place the HTML for the transactions within the date range and update the balance difference.
* @param data
*/
function placeTransactions(data) {
$('#transactions_holder').empty().html(data.html);
selectedAmount = 0;
// update start + end balance when user has not touched them.
if (!changedBalances) {
$('input[name="start_balance"]').val(data.startBalance);
$('input[name="end_balance"]').val(data.endBalance);
}
// as long as the dates are equal, changing the balance does not matter.
calculateBalanceDifference();
// any already cleared transactions must be added to / removed from selectedAmount.
includeClearedTransactions();
difference = balanceDifference - selectedAmount;
updateDifference();
// enable the check buttons:
$('.reconcile_checkbox').prop('disabled', false).unbind('change').change(checkReconciledBox);
// show the other instruction:
$('.select_transactions_instruction').show();
$('.store_reconcile').prop('disabled', false);
}
/**
*
* @returns {boolean}
*/
function startReconcile() {
reconcileStarted = true;
// hide the start button.
$('.start_reconcile').hide();
// hide the start instructions:
$('.update_balance_instruction').hide();
// hide date-change warning
$('.date_change_warning').hide();
// hide update button
$('.change_date_button').hide();
getTransactionsForRange();
return false;
}
function updateDifference() {
var addClass = 'text-info';
if (difference > 0) {
addClass = 'text-success';
}
if (difference < 0) {
addClass = 'text-danger';
}
$('#difference').addClass(addClass).text(accounting.formatMoney(difference));
} | JavaScript | 0 | @@ -2202,24 +2202,26 @@
v);%0A
+//
cleared.push
@@ -4552,16 +4552,19 @@
e range)
+%0A *
and add
@@ -4770,32 +4770,34 @@
) %7B%0A
+//
selectedAmount =
|
67e8209c380765347f0d1848ede119684530e603 | Use the access token for all github requests | public/js/app.js | public/js/app.js | "use strict";
var GitHubAPI = function(accessToken, org, repo) {
var API_URL = 'https://api.github.com/repos/' + org + '/' + repo;
return {
getBranch: function(branchName) {
return $.get(API_URL + '/branches/' + branchName);
},
getTree: function(sha) {
return $.get(API_URL + '/git/trees/' + sha + '?recursive=1');
},
getFileContents: function(path, ref) {
return $.get(API_URL + '/contents/' + path + '?ref=' + ref);
},
updateFileContents: function(path, message, content, sha, branch) {
return $.ajax({
method: 'PUT',
url: API_URL + '/contents/' + path,
headers: {
'Authorization': 'token ' + accessToken,
'Content-Type': 'application/json'
},
data: JSON.stringify({
message: message,
sha: sha,
content: content,
branch: branch
}),
});
},
};
}
var Vidius = function(github) {
return {
getBranch: function(name) {
return github.getBranch(name);
},
getFileListing: function(branch) {
return github.getTree(branch.commit.sha).then(function(data) {
return data.tree;
});
},
getMarkdownFiles: function(branch) {
return this.getFileListing(branch).then(function(files) {
return files.filter(function(file) {
return file.path.endsWith('.md');
});
});
},
getTextFileContents: function(file) {
// TODO don't hardcode the ref
return github.getFileContents(file.path, 'master').then(function(contents) {
// TODO check type is file and encoding is base64, otherwise fail
// See http://ecmanaut.blogspot.co.uk/2006/07/encoding-decoding-utf8-in-javascript.html
return decodeURIComponent(escape(atob(contents.content.replace(/\s/g, ''))));
});
},
saveTextFileContents: function(file, contents) {
// TODO: branch name like `vidius/paulfurley/2016-01-28T18-34-56`
// 1. get sha of master
// 2. create a branch pointing to the sha of master
// 3. push the file to the new branch
// 4. make a pull request
//
var commitMessage = 'Updated file',
branchName='vidius/tmp',
base64Contents = btoa(unescape(encodeURIComponent(contents)));
return github.updateFileContents(file.path, commitMessage, base64Contents, file.sha, branchName);
}
};
};
| JavaScript | 0 | @@ -132,32 +132,515 @@
po;%0A%0A return %7B%0A
+ callApi: function(method, endpoint, data) %7B%0A return $.ajax(%7B%0A method: method,%0A url: API_URL + endpoint,%0A headers: %7B%0A 'Authorization': 'token ' + accessToken,%0A 'Content-Type': 'application/json'%0A %7D,%0A data: JSON.stringify(data)%0A %7D);%0A%0A %7D,%0A%0A get: function(endpoint) %7B%0A return this.callApi('GET', endpoint);%0A %7D,%0A%0A put: function(endpoint, data) %7B%0A return this.callApi('PUT', endpoint, data);%0A %7D,%0A%0A
getBranch: f
@@ -674,32 +674,25 @@
return
-$
+this
.get(
-API_URL +
'/branch
@@ -761,32 +761,25 @@
return
-$
+this
.get(
-API_URL +
'/git/tr
@@ -877,24 +877,17 @@
urn
-$
+this
.get(
-API_URL +
'/co
@@ -1017,239 +1017,55 @@
urn
-$.ajax(%7B%0A method: 'PUT',%0A url: API_URL + '/contents/' + path,%0A headers: %7B%0A 'Authorization': 'token ' + accessToken,%0A 'Content-Type': 'application/json'%0A %7D,%0A data: JSON.stringify(
+this.put(%0A '/contents/' + path,%0A
%7B%0A
@@ -1176,18 +1176,15 @@
%7D
-),
%0A
-%7D
);%0A
|
ad826588256fb82001c3685f88111433ff371745 | Clarify architecture detection for server-side rendering | SvelteCompiler.js | SvelteCompiler.js | import htmlparser from 'htmlparser2';
import sourcemap from 'source-map';
import svelte from 'svelte';
SvelteCompiler = class SvelteCompiler extends CachingCompiler {
constructor(options = {}) {
super({
compilerName: 'svelte',
defaultCacheSize: 1024 * 1024 * 10
});
this.options = options;
}
getCacheKey(file) {
return [
this.options,
file.getPathInPackage(),
file.getSourceHash(),
file.getArch()
];
}
setDiskCacheDirectory(cacheDirectory) {
this.cacheDirectory = cacheDirectory;
}
// The compile result returned from `compileOneFile` can be an array or an
// object. If the processed HTML file is not a Svelte component, the result is
// an array of HTML sections (head and/or body). Otherwise, it's an object
// with JavaScript from a compiled Svelte component.
compileResultSize(result) {
let size = 0;
if (Array.isArray(result)) {
result.forEach(section => size += section.data.length);
} else {
size = result.data.length + result.sourceMap.toString().length;
}
return size;
}
addCompileResult(file, result) {
if (Array.isArray(result)) {
result.forEach(section => file.addHtml(section));
} else {
file.addJavaScript(result);
}
}
compileOneFile(file) {
const raw = file.getContentsAsString();
const basename = file.getBasename();
const path = file.getPathInPackage();
const extension = path.substring(path.lastIndexOf('.') + 1);
if (extension === 'html') {
let isSvelteComponent = true;
const sections = [];
// Search for top level head and body tags. If at least one of these tags
// exists, the file is not processed with the Svelte compiler. Instead,
// the inner HTML of the tags is added to the respective section in the
// HTML output generated by Meteor.
htmlparser.parseDOM(raw).forEach(el => {
if (el.name === 'head' || el.name === 'body') {
isSvelteComponent = false;
sections.push({
section: el.name,
data: htmlparser.DomUtils.getInnerHTML(el).trim()
});
}
});
if (!isSvelteComponent) {
return sections;
}
}
const svelteOptions = {
dev: process.env.NODE_ENV !== 'production',
filename: path,
name: basename
.slice(0, basename.indexOf('.')) // Remove extension
.replace(/[^a-z0-9_$]/ig, '_') // Ensure valid identifier
};
if (file.getArch().startsWith('os.')) {
svelteOptions.generate = 'ssr';
} else {
const { hydratable, css } = this.options;
if (hydratable === true) {
svelteOptions.hydratable = true;
}
if (css === false) {
svelteOptions.css = false;
}
}
try {
return this.transpileWithBabel(
svelte.compile(raw, svelteOptions).js,
path
);
} catch (e) {
// Throw unknown errors.
if (!e.start) {
throw e;
}
let message;
if (e.frame) {
// Prepend a vertical bar to each line to prevent Meteor from trimming
// whitespace and moving the code frame indicator to the wrong position.
const frame = e.frame.split('\n').map(line => {
return `| ${line}`;
}).join('\n');
message = `${e.message}\n\n${frame}`;
} else {
message = e.message;
}
file.error({
message,
line: e.start.line,
column: e.start.column
});
}
}
transpileWithBabel(source, path) {
const options = Babel.getDefaultOptions();
options.filename = path;
const transpiled = Babel.compile(source.code, options, {
cacheDirectory: this.cacheDirectory
});
return {
sourcePath: path,
path,
data: transpiled.code,
sourceMap: this.combineSourceMaps(transpiled.map, source.map)
};
}
// Generates a new source map that maps a file transpiled by Babel back to the
// original HTML via a source map generated by the Svelte compiler.
combineSourceMaps(babelMap, svelteMap) {
const result = new sourcemap.SourceMapGenerator;
const babelConsumer = new sourcemap.SourceMapConsumer(babelMap);
const svelteConsumer = new sourcemap.SourceMapConsumer(svelteMap);
babelConsumer.eachMapping(mapping => {
// Ignore mappings that don't have a source.
if (!mapping.source) {
return;
}
const position = svelteConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
// Ignore mappings that don't map to the original HTML.
if (!position.source) {
return;
}
result.addMapping({
source: position.source,
original: {
line: position.line,
column: position.column
},
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
});
});
// Copy source content from the source map generated by the Svelte compiler.
// We can just take the first entry because only one file is involved in the
// Svelte compilation and Babel transpilation.
result.setSourceContent(
svelteMap.sources[0],
svelteMap.sourcesContent[0]
);
return result.toJSON();
}
};
| JavaScript | 0.000009 | @@ -2495,16 +2495,89 @@
%7D;%0A%0A
+ // If the component was imported by server code, compile it for SSR.%0A
if (
|
579bbd44b373cb38f385a6c2832bc291c69cce77 | Add عدل special form | public/js/qlb.js | public/js/qlb.js | // TODO fold these into jx.js?
function loadJS(url) {
var scriptElement = document.createElement('script')
scriptElement.setAttribute("type","text/javascript")
scriptElement.setAttribute("src", url)
document.getElementsByTagName("head")[0].appendChild(scriptElement)
return scriptElement;
}
function loadCSS(url) {
var linkElement = document.createElement("link")
linkElement.setAttribute("rel", "stylesheet")
linkElement.setAttribute("type", "text/css")
linkElement.setAttribute("href", url)
document.getElementsByTagName("head")[0].appendChild(linkElement)
return linkElement;
}
var Qlb = {};
Qlb.Environment = function(table, outer) {
this.table = table
this.outer = outer
this.find = function (sym) { return this.table[sym] === undefined ? (this.outer ? this.outer.find(sym) : undefined) : this.table[sym] }
this.merge = function(other) { for(var name in other) { Qlb.symbols[name] = true; this.table[name] = other[name] } }
}
Qlb.globalEnvironment = new Qlb.Environment({});
Qlb.symbols = {
"حرفي": true,
"إفعل": true,
"إذا": true,
"حدد": true,
"لامدا": true
}
Qlb.isSymbol = function(sym) {
return !!Qlb.symbols[sym];
}
Qlb.init = function(onloaded) {
// Load grammar from separate file, because dealing with JavaScripts lack of
// multiline strings AND Arabic input is just too much. Just too much.
jx.load("/peg/qlb.peg", function(grammar) {
// Load grammar
Qlb.parser = PEG.buildParser(grammar);
// Default console is window consle
if(Qlb.console === 'undefined') Qlb.console = window.console;
Qlb.eval = function(exp, env) {
if(typeof exp == "string") { // evaling string/symbol
var sym = env.find(exp);
if(sym === undefined) return exp;
else return sym;
} else if(!(exp instanceof Array)) { // evaling literal
return exp;
} else { // evaling list
var first = exp[0]
var rest = exp.slice(1)
if(first == "حرفي") {
return rest
} else if(first == "إفعل") {
rest = rest.map(function(e) { return Qlb.eval(e, env) });
return rest[rest.length - 1];
} else if(first == "إذا") {
var test = rest[0],
ifex = rest[1],
elex = rest[2]
return Qlb.eval(Qlb.eval(test, env) ? ifex : elex, env)
} else if(first == "حدد") {
var sym = rest[0],
val = rest[1]
return (env.table[sym] = Qlb.eval(val, env))
} else if(first == "لامدا") {
var params = rest[0],
body = rest.slice(1)
return function() {
var table = {}
for (var i = 0; i < params.length; i++)
table[params[i]] = arguments[i]
return Qlb.eval(body, new Qlb.Environment(table, env))
}
} else {
var exps = exp.map(function(p) { return Qlb.eval(p, env) })
if(typeof exps[0] == "function")
// first element evaluates to a function
return exps.shift().apply(this, exps)
else if(Qlb.isSymbol(exps[0])) {
throw new ReferenceError(exps[0]);
} else
// return last element
return exps[exps.length - 1];
}
}
}
Qlb.execute = function(code) {
try {
var ast = Qlb.parser.parse(code);
var val;
for (var i = 0; i < ast.length; i++) {
val = Qlb.eval(ast[i], Qlb.globalEnvironment);
};
return val;
} catch(e) {
Qlb.handleUncaughtException(e);
}
}
Qlb.handleUncaughtException = function(e) {
switch(e.name) {
case "SyntaxError":
Qlb.console.warn("خطأ: حرف '" + e.found + "' غير متوقع");
break;
case "ReferenceError":
Qlb.console.warn("خطأ: رمز '" + e.message + "' غير موجود");
break;
default:
throw e;
}
}
if(onloaded) onloaded();
});
}
| JavaScript | 0 | @@ -838,16 +838,138 @@
%5Bsym%5D %7D%0A
+ this.envForSym = function (sym) %7B return this.table%5Bsym%5D === undefined ? (this.outer ? this.outer : undefined) : this %7D%0A
this.m
@@ -2650,16 +2650,245 @@
env))%0A%0A
+ %7D else if(first == %22%D8%B9%D8%AF%D9%84%22) %7B%0A var sym = rest%5B0%5D,%0A val = rest%5B1%5D%0A%0A if(env.envForSym(sym))%0A return (env.envForSym(sym).table%5Bsym%5D = Qlb.eval(val, env));%0A return undefined;%0A%0A
|
00811d4f6eb61d2bf8bf6e261549715217d9b1d2 | fix typos | demo/app.js | demo/app.js | import Carousel from '../src/index';
import React from 'react';
import ReactDom from 'react-dom';
const colors = ['7732bb', '047cc0', '00884b', 'e3bc13', 'db7c00', 'aa231f'];
class App extends React.Component {
constructor() {
super(...arguments);
this.state = {
slideIndex: 0,
length: 6,
wrapAround: false,
animation: undefined,
underlineHeader: false,
zoomScale: 0.5,
slidesToShow: 1,
cellAlign: 'left',
transitionMode: 'scroll',
heightMode: 'max',
withoutControls: false
};
this.handleImageClick = this.handleImageClick.bind(this);
this.handleZoomChangeChange = this.handleZoomChangeChange.bind(this);
}
handleImageClick() {
this.setState({ underlineHeader: !this.state.underlineHeader });
}
handleZoomChangeChange(event) {
this.setState({
zoomScale: event.target.value
});
}
render() {
return (
<div style={{ width: '50%', margin: 'auto' }}>
<Carousel
withoutControls={this.state.withoutControls}
transitionMode={this.state.transitionMode}
cellAlign={this.state.cellAlign}
animation={this.state.animation}
zoomScale={Number(this.state.zoomScale || 0)}
wrapAround={this.state.wrapAround}
slideIndex={this.state.slideIndex}
heightMode={this.state.heightMode}
renderTopCenterControls={({ currentSlide }) => (
<div
style={{
fontFamily: 'Helvetica',
color: '#fff',
textDecoration: this.state.underlineHeader
? 'underline'
: 'none'
}}
>
Nuka Carousel: Slide {currentSlide + 1}
</div>
)}
renderAnnounceSlideMessage={({ currentSlide, slideCount }) => {
return `Showing slide ${currentSlide + 1} of ${slideCount}`;
}}
>
{colors.slice(0, this.state.length).map((color, index) => (
<img
src={`http://placehold.it/1000x400/${color}/ffffff/&text=slide${index +
1}`}
alt={`Slide ${index + 1}`}
key={color}
onClick={this.handleImageClick}
style={{
height:
this.state.heightMode === 'current' ? 100 * (index + 1) : 400
}}
/>
))}
</Carousel>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<button onClick={() => this.setState({ slideIndex: 0 })}>1</button>
<button onClick={() => this.setState({ slideIndex: 1 })}>2</button>
<button onClick={() => this.setState({ slideIndex: 2 })}>3</button>
<button onClick={() => this.setState({ slideIndex: 3 })}>4</button>
<button onClick={() => this.setState({ slideIndex: 4 })}>5</button>
<button onClick={() => this.setState({ slideIndex: 5 })}>6</button>
</div>
<div>
<button
onClick={() =>
this.setState(prevState => {
const length = prevState.length === 6 ? 3 : 6;
return {
length
};
})
}
>
Toggle Show 3 Slides Only
</button>
<button
onClick={() =>
this.setState({
transitionMode:
this.state.transitionMode === 'fade' ? 'scroll' : 'fade',
animation: undefined
})
}
>
Toggle Fade {this.state.transitionMode === 'fade' ? 'Off' : 'On'}
</button>
<button
onClick={() =>
this.setState(prevState => ({
wrapAround: !prevState.wrapAround
}))
}
>
Toggle Wrap Around
</button>
</div>
</div>
{this.state.transitionMode !== 'fade' && (
<>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
{this.state.slidesToShow > 1.0 && (
<div>
<button onClick={() => this.setState({ cellAlign: 'left' })}>
Left
</button>
<button
onClick={() => this.setState({ cellAlign: 'center' })}
>
Center
</button>
<button onClick={() => this.setState({ cellAlign: 'right' })}>
Right
</button>
</div>
)}
<div style={{ marginLeft: 'auto' }}>
<button
onClick={() =>
this.setState({
slidesToShow: this.state.slidesToShow > 1.0 ? 1.0 : 1.25
})
}
>
Toggle Partially Visible Slides
</button>
<button
onClick={() =>
this.setState({
heightMode:
this.state.heightMode === 'current' ? 'max' : 'current'
})
}
>
Toggle Height Mode Current
</button>
<button
onClick={() =>
this.setState({
withoutControls: !this.state.withoutControls
})
}
>
Toggle Controls
</button>
</div>
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
{this.state.animation === 'zoom' && (
<input
type="number"
value={this.state.zoomScale}
onChange={this.handleZoomChangeChange}
/>
)}
<button
onClick={() =>
this.setState({
animation:
this.state.animation === 'zoom' ? undefined : 'zoom',
cellAlign: 'center'
})
}
>
Toggle Zoom Animation{' '}
{this.state.animation === 'zoom' ? 'Off' : 'On'}
</button>
</div>
</>
)}
</div>
);
}
}
ReactDom.render(<App />, document.getElementById('content'));
| JavaScript | 0.999974 | @@ -630,29 +630,28 @@
s.handleZoom
-Chang
+Scal
eChange = th
@@ -659,29 +659,28 @@
s.handleZoom
-Chang
+Scal
eChange.bind
@@ -797,29 +797,28 @@
handleZoom
-Chang
+Scal
eChange(even
@@ -6055,21 +6055,20 @@
ndleZoom
-Chang
+Scal
eChange%7D
|
11c65ef8aa44a0740b87ee8c7108318dd4ec22e5 | remove path | lib/services/travis-service.js | lib/services/travis-service.js | const bindAll = require("lodash/fp/bindAll")
const TravisRepo = require("../models/travis-repo")
const fs = require("fs-extra")
const path = require("path")
class TravisService {
constructor({ githubToken, travisToken, travisEnabled, travisJsonFile, spinner }) {
bindAll(Object.getOwnPropertyNames(TravisService.prototype), this)
this.githubToken = githubToken
this.travisToken = travisToken
this.travisEnabled = travisEnabled
this.travisJsonFile = travisJsonFile
if (this.travisEnabled && !this.githubToken) throw new Error("Missing githubToken in config")
this.travisEnv = this.parseBeekeeperTravisJson().env
this.spinner = spinner
}
parseBeekeeperTravisJson() {
const filePath = this.travisJsonFile
try {
fs.accessSync(filePath, fs.constants.F_OK | fs.constants.R_OK)
} catch (e) {
return {}
}
return fs.readJsonSync(filePath)
}
async configure({ projectName, projectOwner, isPrivate }) {
if (!this.travisEnabled) return
const { githubToken, spinner, travisToken } = this
const travisRepo = new TravisRepo({ projectName, projectOwner, isPrivate, githubToken, travisToken })
if (spinner) spinner.start("Travis: Enabling repository")
await travisRepo.init()
await travisRepo.enable()
if (spinner) spinner.log("Travis: Repository enabled")
if (spinner) spinner.start("Travis: Updating environment variables")
await travisRepo.updateAllEnv(this.travisEnv)
if (spinner) spinner.log("Travis: Environment variables updated")
}
}
module.exports = TravisService
| JavaScript | 0.000001 | @@ -124,37 +124,8 @@
ra%22)
-%0Aconst path = require(%22path%22)
%0A%0Acl
|
f8d9c0e9c58831a7f41e11863256a662cfdd01c2 | Test for null instead of relying on type coercion in lb.base.log.print() | src/lb.base.log.js | src/lb.base.log.js | /*
* Namespace: lb.base.log
* Logging Adapter Module for Base Library
*
* Author:
* Eric Bréchemier <legalbox@eric.brechemier.name>
*
* Copyright:
* Legal-Box SAS (c) 2010-2011, All Rights Reserved
*
* License:
* BSD License
* http://creativecommons.org/licenses/BSD/
*
* Version:
* 2011-01-05
*/
/*requires lb.base.js */
/*jslint white:false, plusplus:false */
/*global lb, goog */
// preserve the module, if already loaded
lb.base.log = lb.base.log || (function() {
// Builder of
// Closure for lb.base.log module
// Define aliases
/*requires closure/goog.debug.Console.js*/
var Console = goog.debug.Console,
/*requires closure/goog.debug.Logger.js*/
Logger = goog.debug.Logger,
Level = goog.debug.Logger.Level,
// Private fields
// object - the logger instance (goog.debug.Logger)
logger;
function print(message){
// Function: print(message)
// Print a message to the log console.
//
// Parameter:
// message - string, the message to print
//
// Notes:
// The console will be activated if (and only if) Debug=true
// is present in the URL.
//
// The console is initialized on first call.
if (!logger){
Console.autoInstall();
logger = Logger.getLogger('lb');
logger.setLevel(Level.INFO);
}
logger.info(message);
}
return { // public API
print: print
};
}());
| JavaScript | 0 | @@ -301,12 +301,12 @@
11-0
-1-05
+4-12
%0A */
@@ -845,16 +845,23 @@
logger
+ = null
;%0A%0A fun
@@ -1215,15 +1215,21 @@
if (
-!
logger
+===null
)%7B%0A
|
94d647d33efecb2f0020729c52e862d272cbfd1f | add passing test case | tests/lib/rules/jsx-no-comment-textnodes.js | tests/lib/rules/jsx-no-comment-textnodes.js | /**
* @fileoverview Tests for jsx-no-comment-textnodes
* @author Ben Vinegar
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const RuleTester = require('eslint').RuleTester;
const rule = require('../../../lib/rules/jsx-no-comment-textnodes');
const parsers = require('../../helpers/parsers');
const parserOptions = {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
};
// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions });
ruleTester.run('jsx-no-comment-textnodes', rule, {
valid: parsers.all([
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
{/* valid */}
</div>
);
}
}
`,
},
{
code: `
class Comp1 extends Component {
render() {
return (
<>
{/* valid */}
</>
);
}
}
`,
features: ['fragment'],
},
{
code: `
class Comp1 extends Component {
render() {
return (<div>{/* valid */}</div>);
}
}
`,
},
{
code: `
class Comp1 extends Component {
render() {
const bar = (<div>{/* valid */}</div>);
return bar;
}
}
`,
},
{
code: `
var Hello = createReactClass({
foo: (<div>{/* valid */}</div>),
render() {
return this.foo;
},
});
`,
},
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
{/* valid */}
{/* valid 2 */}
{/* valid 3 */}
</div>
);
}
}
`,
},
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
</div>
);
}
}
`,
},
{
code: `
var foo = require('foo');
`,
},
{
code: `
<Foo bar='test'>
{/* valid */}
</Foo>
`,
},
{
code: `
<strong>
https://www.example.com/attachment/download/1
</strong>
`,
},
// inside element declarations
{
code: `
<Foo /* valid */ placeholder={'foo'}/>
`,
},
{
code: `
</* valid */></>
`,
features: ['fragment'],
},
{
code: `
<></* valid *//>
`,
features: ['fragment', 'no-ts'], // TODO: FIXME: figure out why both TS parsers fail on this
},
{
code: `
<Foo title={'foo' /* valid */}/>
`,
},
{
code: '<pre>// TODO: Write perfect code</pre>',
},
{
code: '<pre>/* TODO: Write perfect code */</pre>',
},
]),
invalid: parsers.all([
{
code: `
class Comp1 extends Component {
render() {
return (<div>// invalid</div>);
}
}
`,
features: ['no-ts-old'], // TODO: FIXME: remove this and figure out why the old TS parser hangs here
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
class Comp1 extends Component {
render() {
return (<>// invalid</>);
}
}
`,
features: ['fragment', 'no-ts-old'], // TODO: FIXME: remove this and figure out why the old TS parser hangs here
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
class Comp1 extends Component {
render() {
return (<div>/* invalid */</div>);
}
}
`,
features: ['no-ts-old'], // TODO: FIXME: remove this and figure out why the old TS parser hangs here
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
// invalid
</div>
);
}
}
`,
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
asdjfl
/* invalid */
foo
</div>
);
}
}
`,
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
class Comp1 extends Component {
render() {
return (
<div>
{'asdjfl'}
// invalid
{'foo'}
</div>
);
}
}
`,
errors: [{ messageId: 'putCommentInBraces' }],
},
{
code: `
const Component2 = () => {
return <span>/*</span>;
};
`,
features: ['no-ts-old'], // TODO: FIXME: remove this and figure out why the old TS parser hangs here
errors: [{ messageId: 'putCommentInBraces' }],
},
]),
});
| JavaScript | 0.000001 | @@ -3283,24 +3283,180 @@
e%3E',%0A %7D,%0A
+ %7B%0A code: %60%0A %3Cdiv%3E%0A %3Cspan className=%22pl-c%22%3E%3Cspan className=%22pl-c%22%3E//%3C/span%3E ...%3C/span%3E%3Cbr /%3E%0A %3C/div%3E%0A %60,%0A %7D,%0A
%5D),%0A%0A inv
|
da3cde83a4cdb7daf10531d2cd44fe00c9034486 | Add tests for paranoid cache key (#62) | test/unit/getCacheKey.test.js | test/unit/getCacheKey.test.js | import {getCacheKey} from '../../src';
import expect from 'unexpected';
import {connection} from '../helper';
describe('getCacheKey', function () {
const User = connection.define('user')
, Task = connection.define('task')
, association = User.hasMany(Task);
it('handles circular structures', function () {
let foo = {}
, bar = {}
, options = {
foo,
bar
};
foo.bar = bar;
bar.foo = foo;
expect(getCacheKey({
name: 'user'
}, 'id', options), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
});
it('handles nulls', function () {
expect(getCacheKey(User, 'id', {
order: null
}), 'to equal', 'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:null|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
});
it('does not modify arrays', function () {
let options = {
order: ['foo', 'bar']
};
expect(getCacheKey(User, 'id', options), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:foo,bar|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
expect(options.order, 'to equal', ['foo', 'bar']);
});
it('handles associations', function () {
expect(getCacheKey(User, 'id', {
association,
limit: 42
}), 'to equal', 'user|id|association:HasMany,task,tasks|attributes:undefined|groupedLimit:undefined|limit:42|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
});
it('handles attributes', function () {
expect(getCacheKey(User, 'id', {
attributes: ['foo', 'bar', 'baz']
}), 'to equal', 'user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
});
it('handles schemas', function () {
expect(getCacheKey({
name: 'user',
options: {
schema: 'app'
}
}, 'id', {
attributes: ['foo', 'bar', 'baz']
}), 'to equal', 'app|user|id|association:undefined|attributes:bar,baz,foo|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:undefined');
});
describe('where statements', function () {
it('POJO', function () {
expect(getCacheKey(User, 'id', {
where: {
completed: true
}
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:true');
});
it('symbols', function () {
expect(getCacheKey(User, 'id', {
where: {
[Symbol('or')]: {
name: { [Symbol('iLike')]: '%test%' }
},
[Symbol('or')]: {
name: { [Symbol('iLike')]: '%test%' }
}
}
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:Symbol(or):name:Symbol(iLike):%test%|Symbol(or):name:Symbol(iLike):%test%');
});
it('date', function () {
const from = new Date(Date.UTC(2016, 1, 1));
const to = new Date(Date.UTC(2016, 2, 1));
expect(getCacheKey(User, 'id', {
where: {
completed: {
$between: [
from,
to
]
}
}
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:completed:$between:2016-02-01T00:00:00.000Z,2016-03-01T00:00:00.000Z');
});
it('literal', function () {
expect(getCacheKey(User, 'id', {
where: {
foo: connection.literal('SELECT foo FROM bar')
}
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:val:SELECT foo FROM bar');
});
it('fn + col', function () {
expect(getCacheKey(User, 'id', {
where: {
foo: {
$gt: connection.fn('FOO', connection.col('bar'))
}
}
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:undefined|through:undefined|where:foo:$gt:args:col:bar|fn:FOO');
});
});
it('searchPath', function () {
expect(getCacheKey(User, 'id', {
searchPath: 'test'
}), 'to equal',
'user|id|association:undefined|attributes:undefined|groupedLimit:undefined|limit:undefined|offset:undefined|order:undefined|raw:undefined|searchPath:test|through:undefined|where:undefined');
});
});
| JavaScript | 0 | @@ -642,32 +642,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -978,16 +978,35 @@
er:null%7C
+paranoid:undefined%7C
raw:unde
@@ -1362,16 +1362,35 @@
foo,bar%7C
+paranoid:undefined%7C
raw:unde
@@ -1768,32 +1768,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -2130,32 +2130,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -2563,32 +2563,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -2981,32 +2981,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -3519,32 +3519,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -4143,32 +4143,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -4611,32 +4611,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -5072,32 +5072,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
@@ -5443,32 +5443,51 @@
order:undefined%7C
+paranoid:undefined%7C
raw:undefined%7Cse
|
fee207d5aae965cdc7241dbcc77f06f8c1ef4dd0 | コメントをSJISからUTF-8に変更 | phantomjs-script.js | phantomjs-script.js | var system = require('system');
var args = system.args;
var page = require('webpage').create();
page.open(args[1] + args[2] + '#fight=' + args[3] + '&type=damage-done', function(status) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', function() {
setTimeout(function () {
console.log("Start_Response")
console.log(page.evaluate(eva));
console.log("End_Response");
phantom.exit();
}, 10000);
});
});
var eva = function() {
var msg = "";
// eX̒l擾
for (var i = 0, size = $(".table-icon").length; i < size; i++) {
if($(".main-table-performance")[i]) {
msg += $(".main-table-performance")[i].innerText.replace(/\t|(\r?\n)/g,"");
msg += "% ";
}
if($(".main-table-name")[i]) {
msg += $(".main-table-name")[i].innerText.replace(/\t|(\r?\n)/g,"");
}
if($(".table-icon")[i]) {
msg += " (";
msg += $(".table-icon")[i].src.match(/\/(\w+).png/)[1];
msg += ") ";
}
if($(".main-table-number")[i]) {
msg += $(".main-table-number")[i].innerText.replace(/\t|(\r?\n)/g,"");
}
msg += "\n";
}
// total̒l擾
{
if($(".main-table-performance")[$(".main-table-performance").length-1]) {
msg += $(".main-table-performance")[$(".main-table-performance").length-1].innerText.replace(/\t|(\r?\n)/g,"");
msg += "% "
}
msg += "Total ";
if($(".main-table-number")[$(".main-table-number").length-1]) {
msg += $(".main-table-number")[$(".main-table-number").length-1].innerText;
}
msg += "\n";
}
return msg;
} | JavaScript | 0.000078 | @@ -511,13 +511,15 @@
%09//
-eX%CC%92l%E6%93%BE
+%E5%90%84%E3%80%85%E3%81%AE%E5%80%A4%E3%82%92%E5%8F%96%E5%BE%97
%0A%09fo
@@ -1090,17 +1090,16 @@
%5Cn%22;%0A%09%7D%0A
-%09
%0A%09// tot
@@ -1104,11 +1104,13 @@
otal
-%CC%92l%E6%93%BE
+%E3%81%AE%E5%80%A4%E3%82%92%E5%8F%96%E5%BE%97
%0A%09%7B%0A
|
45e209d8b21ffda5e4f175ff747ec321a18a7dd8 | add actual detection. quelle surprise, my first implementation is bugged on this. | tests/structuredheadings/presetdiscovery.js | tests/structuredheadings/presetdiscovery.js | /* eslint-disable */
/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles,dialog,richcombo,undo */
/* eslint-enable */
// Clean up all instances been created on the page.
(function () {
bender.editor = {
allowedForTests: "h1; h2; h3; h4; h5; p"
};
function getDetectedPreset(editor) {
return editor.plugins.structuredheadings.getCurrentPreset();
};
bender.test({
setUp: function () {
//Anything to be run before each test if needed
},
tearDown: function () {
// reset the plugin between tests
var editor = this.editorBot.editor;
editor.plugins.structuredheadings.currentPreset = null;
},
"default is numbered": function () {
var bot = this.editorBot;
var editor = bot.editor;
bot.setHtmlWithSelection(
"<h1 class=\"autonumber autonumber-0\">^foo</h1>" +
"<h2 class=\"autonumber autonumber-1\">bar</h2>"
);
assert.areEqual(
"1.1.1.1.1.",
getDetectedPreset(editor)
);
},
"invalid combos return numbered": function () {
var bot = this.editorBot;
var editor = bot.editor;
bot.setHtmlWithSelection(
"<h1 class=\"autonumber autonumber-0 autonumber-a\">^foo</h1>" +
"<h2 class=\"autonumber autonumber-1 autonumber-N\">bar</h2>"
);
assert.areEqual(
"1.1.1.1.1.",
getDetectedPreset(editor)
);
}
});
})();
| JavaScript | 0 | @@ -1445,24 +1445,355 @@
r)%0A );%0A
+ %7D,%0A%0A %22can detect based off of one level%22: function () %7B%0A var bot = this.editorBot;%0A var editor = bot.editor;%0A bot.setHtmlWithSelection(%0A %22%3Ch1 class=%5C%22autonumber autonumber-0 autonumber-N%5C%22%3E%5Efoo%3C/h1%3E%22%0A );%0A%0A assert.areEqual(%0A %221. a. i. a. i.%22,%0A getDetectedPreset(editor)%0A );%0A
%7D%0A%0A%0A %7D)
|
b6d1dc9923447f535a80324c68f71fea3f285834 | Change octal literal formatting? | server/src/modules/Logger.js | server/src/modules/Logger.js | var fs = require("fs");
var util = require('util');
var EOL = require('os').EOL;
var log = "";
module.exports.toString = toString;
module.exports.debug = debug;
module.exports.info = info;
module.exports.warn = warn;
module.exports.error = error;
module.exports.err = error;
module.exports.fatal = fatal;
module.exports.print = print;
module.exports.write = write;
module.exports.start = start;
module.exports.prompt = prompt;
module.exports.clear = clear;
module.exports.green = green;
module.exports.white = white;
function toString()
{
return log;
}
function debug(message) {
message = util.format(message);
writeCon(colorWhite, "[DEBUG] " + message);
writeLog("[DEBUG][" + getTimeString() + "] " + message);
};
function info(message) {
message = util.format(message);
writeCon(colorWhite + colorBright, "[INFO ] " + message);
writeLog("[INFO ][" + getTimeString() + "] " + message);
};
function warn(message) {
message = util.format(message);
writeCon(colorYellow + colorBright, "[WARN ] " + message);
writeLog("[WARN ][" + getTimeString() + "] " + message);
};
function error(message) {
message = util.format(message);
writeCon(colorRed + colorBright, "[ERROR] " + message);
writeLog("[ERROR][" + getTimeString() + "] " + message);
};
function fatal(message) {
message = util.format(message);
writeCon(colorRed + colorBright, "[FATAL] " + message);
writeLog("[FATAL][" + getTimeString() + "] " + message);
};
function print(message) {
message = util.format(message);
writeCon(colorWhite, message);
writeLog("[NONE ][" + getTimeString() + "] " + message);
};
function write(message) {
message = util.format(message);
writeLog("[NONE ][" + getTimeString() + "] " + message);
};
function green(message) {
message = util.format(message);
writeCon(colorGreen + colorBright, message);
};
function white(message) {
message = util.format(message);
writeCon(colorWhite + colorBright, message);
};
function getDateTimeString() {
var date = new Date();
var dy = date.getFullYear();
var dm = date.getMonth();
var dd = date.getDay();
var th = date.getHours();
var tm = date.getMinutes();
var ts = date.getSeconds();
var tz = date.getMilliseconds();
dy = ("0000" + dy).slice(-4);
dm = ("00" + dm).slice(-2);
dd = ("00" + dd).slice(-2);
th = ("00" + th).slice(-2);
tm = ("00" + tm).slice(-2);
ts = ("00" + ts).slice(-2);
tz = ("000" + tz).slice(-3);
return dy + "-" + dm + "-" + dd + "T" + th + "-" + tm + "-" + ts + "-" + tz;
};
function getTimeString() {
var date = new Date();
var th = date.getHours();
var tm = date.getMinutes();
var ts = date.getSeconds();
th = ("00" + th).slice(-2);
tm = ("00" + tm).slice(-2);
ts = ("00" + ts).slice(-2);
return th + "-" + tm + "-" + ts;
};
function prompt(callback)
{
rl.setPrompt("# ");
rl.question('# ', callback);
}
function clear()
{
log = "";
process.stdout.write('\033c');
readline.cursorTo(process.stdout, 0);
process.stdout.write("\r\x1b[K");
readline.clearLine(process.stdout, 0);
log = "";
}
function writeCon(color, message) {
log += message + "\u001B[0m" + EOL;
readline.cursorTo(process.stdout, 0);
process.stdout.write(color + message + "\u001B[0m" + EOL);
rl.prompt(true);
};
function writeLog(message) {
//Do nothing!!! lmao xd
};
function start() {
if (consoleLog != null)
return;
var timeString = getDateTimeString();
var fileName = logFolder + "/" + logFileName + ".log";
var fileName2 = logBackupFolder + "/" + logFileName + "-" + timeString + ".log";
console.log = function (message) { print(message); };
}
var logFolder = "./logs";
var logBackupFolder = "./logs/LogBackup";
var logFileName = "xQube";
var consoleLog = null;
var colorBlack = "\u001B[30m";
var colorRed = "\u001B[31m";
var colorGreen = "\u001B[32m";
var colorYellow = "\u001B[33m";
var colorBlue = "\u001B[34m";
var colorMagenta = "\u001B[35m";
var colorCyan = "\u001B[36m";
var colorWhite = "\u001B[37m";
var colorBright = "\u001B[1m";
| JavaScript | 0 | @@ -3025,15 +3025,15 @@
ite(
-'
+%22
%5C033c
-'
+%22
);%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.