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
334f87439c4ecdc6625d18a40e20c860cb0e6fc8
Add a test for animation callbacks.
frameworks/animation/tests/core.js
frameworks/animation/tests/core.js
// ========================================================================== // Project: SproutCore Animation // ========================================================================== /*globals module test ok isObj equals expects */ var view, base, inherited; module("Animatable", { setup: function() { view = SC.View.create(SC.Animatable, { layout: { left: 100, top: 100, height: 100, width: 100 }, style: { opacity: .5 }, transitions: { left: 0.25, top: { duration: 0.35 }, width: { duration: 0.2, timing: SC.Animatable.TRANSITION_EASE_IN_OUT }, style: { opacity: 1 } } }); // identical to normal view above base = SC.View.extend(SC.Animatable, { layout: { left: 100, top: 100, height: 100, width: 100 }, transitions: { left: 0.25, top: { duration: 0.35 }, width: { duration: 0.2, timing: SC.Animatable.TRANSITION_EASE_IN_OUT } } }); // concatenate this inherited = base.create({ transitions: { left: 0.99 } }); } }); test("animatable should have init-ed correctly", function(){ var left = view.transitions["left"]; var top = view.transitions["top"]; var width = view.transitions["width"]; equals(left["duration"], 0.25, "left duration is .25"); equals(top["duration"], 0.35, "top duration is .35"); equals(width["duration"], 0.2, "width duration is .2"); equals(left["timing"], undefined, "No timing for left."); equals(top["timing"], undefined, "No timing for top."); equals(width["timing"], SC.Animatable.TRANSITION_EASE_IN_OUT, "SC.Animatable.TRANSITION_EASE_IN_OUT for width."); }); test("animatable should handle concatenated transitions properly", function(){ // should be identical to view, but with one difference. var left = inherited.transitions["left"]; var top = inherited.transitions["top"]; var width = inherited.transitions["width"]; equals(left["duration"], 0.99, "left duration is .99 (the overridden value)"); equals(top["duration"], 0.35, "top duration is .35"); equals(width["duration"], 0.2, "width duration is .2"); equals(left["timing"], undefined, "No timing for left."); equals(top["timing"], undefined, "No timing for top."); equals(width["timing"], SC.Animatable.TRANSITION_EASE_IN_OUT, "SC.Animatable.TRANSITION_EASE_IN_OUT for width."); }); test("animatable handler for layer update should ensure both layout and styles are set in the 'current style'.", function() { var original_transition_enabled = SC.Animatable.enableCSSTransitions; SC.Animatable.enableCSSTransitions = NO; // check current style (should be none yet) var current = view.getCurrentJavaScriptStyles(); equals(current, null, "There should be no current style yet."); // create the layer view.createLayer(); view.updateLayer(); // check again. Now, we should have a style current = view.getCurrentJavaScriptStyles(); ok(!SC.none(current), "There now SHOULD be a current JS style."); // and now, make sure we have both style AND layout set properly. equals(current["opacity"], .5, "opacity should be .5"); equals(current["left"], 100, "left should be 100"); // go back to the beginning SC.Animatable.enableCSSTransitions = original_transition_enabled; });
JavaScript
0
@@ -259,18 +259,24 @@ nherited +, pane ;%0A - module(%22 @@ -312,16 +312,161 @@ ion() %7B%0A + SC.RunLoop.begin();%0A pane = SC.Pane.create(%7B%0A layout: %7B top: 0, right: 0, width: 200, height: 200 %7D,%0A %7D);%0A pane.append();%0A %0A view @@ -787,32 +787,60 @@ %7D%0A %7D);%0A + pane.appendChild(view);%0A %0A // iden @@ -1260,17 +1260,48 @@ %7D);%0A -%7D + %0A SC.RunLoop.end();%0A %7D,%0A %0A%7D);%0A%0Ate @@ -2856,283 +2856,52 @@ // -check current styl +w e -( should -be none yet)%0A var current = view.getCurrentJavaScriptStyles();%0A equals(current, null, %22There should be no current style yet.%22);%0A %0A // create the layer%0A view.createLayer();%0A view.updateLayer();%0A %0A // check again. Now, we should have a style +have a style (it is inside a pane) %0A c @@ -3296,11 +3296,472 @@ nabled;%0A - %7D); +%0A%0Atest(%22animatable callbacks work in general%22, function()%7B%0A SC.RunLoop.begin();%0A view.transitions%5B%22left%22%5D = %7B%0A duration: .25,%0A action: function() %7B%0A console.error(%22Callback%22);%0A ok(true, %22Callback was called.%22);%0A start();%0A %7D%0A %7D;%0A view.updateLayout();%0A view.adjust(%22left%22, 0).updateLayout();%0A SC.RunLoop.end();%0A stop();%0A %0A setTimeout(function()%7B%0A ok(false, %22Timeout! Callback was not called.%22);%0A start();%0A %7D, 1000);%0A %0A%7D);%0A
f0d10dd561e33222b91404b272708e5a27c69073
fix tests
projects/qgrid-core/model/model.bind.spec.js
projects/qgrid-core/model/model.bind.spec.js
import { ModelBinder } from './model.bind'; import { Event } from '../event/event'; describe('ModelBinder', () => { let state = { prop: 'originValue' }; let model = { state: value => { if (value) { Object.assign(state, value); return; } return state; }, stateChanged: new Event() }; let modelNames = ['state']; let host = { stateProp: 'hostValue' }; let modelBinder = new ModelBinder(host, { add: x => x }); describe('bind', () => { it('commit should setup model property', () => { const commit = modelBinder.bound(model, modelNames, false); commit(); expect(model.state().prop).to.equal('hostValue'); }); it('model property change should lead to host changes', () => { model.stateChanged.emit({ changes: { prop: { newValue: 'valueAfterEvent', oldValue: model.state().prop } } }); expect(host.stateProp).to.equal('valueAfterEvent'); }); }); });
JavaScript
0.000003
@@ -566,16 +566,23 @@ elNames, + false, false); @@ -795,31 +795,25 @@ Value: ' -valueAfterEvent +hostValue ',%0A%09%09%09%09%09 @@ -903,23 +903,17 @@ al(' -valueAfterEvent +hostValue ');%0A
17ebf087752d0b46c72dc696d7e0da5811f841df
Fix gulpfile to copy Bootstrap less files before mixing
gulpfile.js
gulpfile.js
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | 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. | */ elixir(function(mix) { mix.less('app.less'); // Base Scripts and Styles mix.scripts([ './bower_components/jquery/dist/jquery.min.js', './bower_components/bootstrap/dist/js/bootstrap.min.js', './bower_components/tooltipster/js/jquery.tooltipster.min.js' ], 'public/js/app.js'); mix.styles([ './bower_components/tooltipster/css/themes/tooltipster-light.css', './bower_components/tooltipster/css/tooltipster.css', './bower_components/animate.css/animate.min.css', ], 'public/css/styles.css'); // News Helpers mix.scripts([ './bower_components/jquery-bootstrap-newsbox/dist/jquery.bootstrap.newsbox.min.js', ], 'public/js/newsbox.js'); // Form Helpers mix.scripts([ './bower_components/bootstrap-select/dist/js/bootstrap-select.min.js', './bower_components/bootstrap-validator/dist/validator.min.js', './bower_components/speakingurl/speakingurl.min.js', './bower_components/jquery-slugify/dist/slugify.min.js', './bower_components/bootstrap-list-filter/bootstrap-list-filter.min.js', './bower_components/mjolnic-bootstrap-colorpicker/bootstrap-colorpicker-2.3.0/dist/js/bootstrap-colorpicker.min.js' ], 'public/js/forms.js'); mix.copy([ './bower_components/bootstrap-select/dist/js/i18n/*.min.js', ], 'public/js/bootstrap-select/i18n'); mix.copy([ './bower_components/mjolnic-bootstrap-colorpicker/bootstrap-colorpicker-2.3.0/dist/img/', ], 'public/img/'); mix.styles([ './bower_components/bootstrap-select/dist/css/bootstrap-select.min.css', './bower_components/mjolnic-bootstrap-colorpicker/bootstrap-colorpicker-2.3.0/dist/css/bootstrap-colorpicker.min.css', ], 'public/css/forms.css'); // Highlight mix.scripts([ './bower_components/jquery-highlighttextarea/jquery.highlighttextarea.min.js', ], 'public/js/highlight.js'); mix.styles([ './bower_components/jquery-highlighttextarea/jquery.highlighttextarea.min.css', ], 'public/css/highlight.css'); // Date & Time Helpers mix.scripts([ './bower_components/moment/min/moment-with-locales.min.js', './bower_components/moment-timezone/builds/moment-timezone.min.js', './bower_components/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js', ], 'public/js/datetime.js'); mix.styles([ './bower_components/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css', ], 'public/css/datetime.css'); // Tour Helpers mix.scripts([ './bower_components/bootstrap-tour/build/js/bootstrap-tour.min.js', ], 'public/js/tour.js'); mix.styles([ './bower_components/bootstrap-tour/build/css/bootstrap-tour.min.css', ], 'public/css/tour.css'); });
JavaScript
0
@@ -474,61 +474,166 @@ -mix.less('app.less');%0A%0A // Base Scripts and Styles +// Base Scripts and Styles%0A mix.copy(%5B%0A './bower_components/bootstrap/less/',%0A %5D, 'resources/assets/less/bootstrap/');%0A%0A mix.less('app.less'); %0A%0A @@ -877,32 +877,102 @@ mix.styles(%5B%0A + // './bower_components/bootstrap/dist/css/bootstrap.min.css',%0A './bower
8a3f1acc2abfc72d25149ebc0a5caab53552efc6
Disable lint for test assets
gulpfile.js
gulpfile.js
'use strict'; const path = require('path'); const gulp = require('gulp'); const eslint = require('gulp-eslint'); const excludeGitignore = require('gulp-exclude-gitignore'); const mocha = require('gulp-mocha'); const istanbul = require('gulp-istanbul'); const nsp = require('gulp-nsp'); const plumber = require('gulp-plumber'); gulp.task('nsp', nodeSecurityProtocol); gulp.task('watch', watch); gulp.task('static', eslintCheck); gulp.task('pre-test', istanbulCover); gulp.task('test', gulp.series('pre-test', mochaTest)); gulp.task('prepublish', gulp.series('nsp')); gulp.task('default', gulp.series('static', 'test')); function nodeSecurityProtocol(cb) { nsp({package: path.resolve('package.json')}, cb); } function eslintCheck() { return gulp.src(['**/*.js', '!**/templates/**']) .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); } function istanbulCover() { return gulp.src(['**/*.js', '!**/templates/**']) .pipe(excludeGitignore()) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); } function mochaTest() { return gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .once('error', () => { process.exit(1); }) .pipe(istanbul.writeReports()); } function watch() { gulp.watch('**/*.js', ['test']); }
JavaScript
0.000001
@@ -772,32 +772,51 @@ **/templates/**' +, '!test/assets/**' %5D)%0A .pipe(exc
7ef4340f1861689982e9d5db229d60fae70bd322
upgrade bower to latest version
lib/package_managers/bower.js
lib/package_managers/bower.js
var bower = require('bower'), shell = require('shelljs'), prettyjson = require('prettyjson'), path = require('path'), roots = require('../index'); // this should be configurable bower.config.directory = roots.project.path('components'); module.exports = function(command){ // if installing, make the components directory first if (command.toString().match('install')) { shell.mkdir('-p', roots.project.path('components')); } bower.commands[command[0] || 'help'].line(['node', __dirname].concat(command)) .on('end', function (data) { roots.print.log(prettyjson.render(data)); }) .on('error', function (err) { throw err; }); };
JavaScript
0
@@ -154,16 +154,56 @@ /index') +,%0A prettyjson = require('prettyjson') ;%0A%0A// th
0f34b59eb00cc6a310e6451824b2f04bc7c023d0
correct warn call
lib/logs.js
lib/logs.js
/** * @author Gilles Coomans <gilles.coomans@gmail.com> * */ if (typeof define !== 'function') { var define = require('amdefine')(module); } define(["require", "./utils", "./promise"], function(require, utils, Prom) { var logs = { slog: function(args, s, e) { if (args.length === 0) args.push("dp:success : "); var v = s; if (s && s._deep_query_node_) v = s.value; else if (v && v._deep_array_) { args.push("(" + v.length + " node(s)) : \n\n"); var res = [], count = 0; v.forEach(function(e) { res.push(count++, ": ", e.value); if (count < v.length) res.push(",\n\n"); }); if (res.length) args = args.concat(res); } if (!v || !v._deep_array_) args.push(v); if (Prom.Promise.context.logger) { var logger = Prom.Promise.context.logger; if (logger._deep_ocm_) logger = logger(); logger.log.apply(logger, args); } else if (console.log.apply) console.log.apply(console, args); else console.log(utils.argToArr(args)); return s; }, elog: function(args, s, e) { if (args.length === 0) args.unshift("dp:error"); if (Prom.Promise.context.debug) { utils.dumpError(e, args); return e; } else if (e.report) args.push("(" + e.status + "): ", e.message, e.report); else args.push("(" + e.status + "): ", e.message); if (Prom.Promise.context.logger) { var logger = Prom.Promise.context.logger; if (logger._deep_ocm_) logger = logger(); logger.error.apply(logger, arguments); } else if (console.error.apply) console.error.apply(console, arguments); else console.error(utils.argToArr(arguments)); return e; }, log: function() { if (Prom.Promise.context.logger) { var logger = Prom.Promise.context.logger; if (logger._deep_ocm_) logger = logger(); logger.log.apply(logger, arguments); } else if (console.log.apply) console.log.apply(console, arguments); else console.log(utils.argToArr(arguments)); return logs; }, warn: function() { if (Prom.Promise.context.logger) { var logger = Prom.Promise.context.logger; if (logger._deep_ocm_) logger = logger(); logger.warn.apply(logger, arguments); } else if (console.warn.apply) console.warn.apply(console, arguments); else console.warn(utils.argToArr(arguments)); return logs; }, error: function() { if (Prom.Promise.context.logger) { var logger = Prom.Promise.context.logger; if (logger._deep_ocm_) logger = logger(); logger.error.apply(logger, arguments); } else if (console.error.apply) console.error.apply(console, arguments); else console.error(utils.argToArr(arguments)); return logs; } }; var Promise = Prom.Promise; // __________________________________________________ LOG /** * * log any provided arguments. * If no arguments provided : will log current success or error state. * * transparent true * * @method log * @return {deep.Promise} this * @chainable */ Promise.prototype.log = function() { var self = this; var args = Array.prototype.slice.call(arguments); var func = function(s, e) { if (e) return logs.elog(args, s, e); return logs.slog(args, s, e); }; return self._enqueue(func); }, // __________________________________________________ LOG /** * * log any chain errors * * @method log * @return {deep.Promise} this * @chainable */ Promise.prototype.elog = function() { var self = this; var args = Array.prototype.slice.call(arguments); var func = function(s, e) { return logs.elog(args, s, e); }; func._isFail_ = true; return self._enqueue(func); }; /** * * log any chain errors * * @method log * @return {deep.Promise} this * @chainable */ Promise.prototype.slog = function() { var self = this; var args = Array.prototype.slice.call(arguments); var func = function(s, e) { return logs.slog(args, s, e); }; func._isDone_ = true; return self._enqueue(func); }; //_____________________________________________________ ERROR RELATED utils.dumpError = function(err, args) { if (typeof err === 'object' && err !== null) { if(err.dumped) return; deep.warn("\n**** Error Dump ****"); if (args) { if (args[0] === "dp:error") args.shift(); if(args.length && args.forEach) logs.log((args.join) ? args.join(" - ") : args); } if (err.status) logs.log('\nStatus: ' + err.status); logs.error(err); if (err.requireModules) logs.log("Error from : ", err.requireModules); if (err.stack) { logs.log('\nStacktrace:'); logs.log('===================='); logs.log(err.stack); } if (err.report) { logs.log('\nReport:'); logs.log('===================='); logs.log(JSON.stringify(err.report, null, ' ')); logs.log('============================================================'); } logs.log("\n") err.dumped = true; } else logs.warn('dumpError :: argument is not an object : ', err); }; utils.logItemsProperty = function(array, prop) { var r = []; array.forEach(function(a) { logs.log("deep.logItemsProperty : ", prop, a[prop]); r.push(a[prop]); }); return r; }; return logs; });
JavaScript
0.00001
@@ -4232,20 +4232,20 @@ urn;%0A%09%09%09 -deep +logs .warn(%22%5C
bb0123a853ae297d3419211eb370f63409876acc
Add missing import.
app/models/exec.js
app/models/exec.js
import DS from "ember-data"; export default DS.Model.extend( { code: DS.attr("string"), module: DS.belongsTo("module", { async: true }), report: DS.attr("string"), result: DS.attr("string"), time: DS.attr("date"), user: DS.belongsTo("user", { async: true }), ok: Ember.computed("result", function() { return this.get("result") === "ok"; }), nok: Ember.computed("result", function() { return this.get("result") === "nok"; }), error: Ember.computed("result", function() { return this.get("result") === "error"; }), });
JavaScript
0.000001
@@ -22,16 +22,44 @@ -data%22;%0D +%0Aimport Ember from %22ember%22;%0D %0A%0D%0Aexpor
544c5fd20d08220bf4b43c2fb94595314a304b64
Fix semver
jquery-svg-to-inline.js
jquery-svg-to-inline.js
/*! jQuery SVG to Inline v0.0.1beta * https://github.com/tiagoporto/jquery-svg-to-inline * Copyright (c) 2015-2016 Tiago Porto (tiagoporto.com) * Released under the MIT license */ $.fn.svgToInline = function() { var usedClass = this.selector; this.each(function() { var path = $(this).attr('data') || $(this).attr('src'); var current = $(this); var getClass = []; var newElementClass = ''; $($(this).attr('class').split(' ')).each(function() { if (this.toString() !== usedClass.replace('.', '')) { getClass.push( this.toString() ); }; }); if(getClass.length > 0){ var elementClass = ''; for (var i = 0; i < getClass.length; ++i) { var space = ''; if (i !== getClass.length - 1) { space = ' '; } elementClass += getClass[i] + space; } } if(elementClass !== ''){ newElementClass = `class="${elementClass}"`; }; $.ajax({ url : path, dataType: "text", success : function (data) { var element = data.replace(/<[?!][\s\w\"-\/:=?]+>/g, ''); var getSvgTag = element.match(/<svg[\w\s\t\n:="\\'\/.#-]+>/g); var addedClass = getSvgTag[0].replace('>', `${newElementClass}>`); var newElement = element.replace(/<svg[\w\s\t\n:="\\'\/.#-]+>/g, addedClass); current.replaceWith( newElement ); } }); }); };
JavaScript
0.000003
@@ -25,11 +25,11 @@ v0. -0.1 +1.0 beta
b3eb9f8404e30835f59f6a7c9885d9c672ee6db9
Remove unused variable
app/components/common/form-inputs/blob/index.js
app/components/common/form-inputs/blob/index.js
import React, { Component } from 'react'; import { Text, View, Image, StatusBar, TouchableHighlight, PermissionsAndroid } from 'react-native'; import Camera from 'react-native-camera'; import ImageCache from 'components/common/image-cache'; import { storeImage } from 'helpers/fileManagement'; import i18n from 'locales'; import Theme from 'config/theme'; import styles from './styles'; const cameraIcon = require('assets/camera.png'); const cameraAddIcon = require('assets/camera_add.png'); class ImageBlobInput extends Component { constructor(props) { super(props); this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this)); this.takePicture = this.takePicture.bind(this); this.removePicture = this.removePicture.bind(this); this.timerLoadPicture = null; this.state = { viewPrepared: false, cameraVisible: false, cameraType: Camera.constants.Type.back, saving: false }; } componentDidMount() { this.getPermissions(); if (this.camera !== undefined) { this.selectCameraType(); } } componentWillUnmount() { StatusBar.setBarStyle('default'); } onNavigatorEvent(event) { if (event.type === 'ScreenChangedEvent' && event.id === 'didAppear') { this.setState({ viewPrepared: true }); } } async getPermissions() { try { let isCameraPermitted = false; try { isCameraPermitted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA); } catch (err) { console.warn(err); } if (!isCameraPermitted) { const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA, { title: 'Camera Permission', message: '' } ); if (granted === false) { // TODO: Continue form without picture? console.warn('Please allow Camera'); } } this.setState({ cameraVisible: !this.props.input.value || this.props.input.value.length === 0 }); } catch (err) { console.warn(err); } } selectCameraType() { this.camera.hasFlash() .then((flash) => { if (!flash) { this.setState({ cameraType: Camera.constants.Type.front }); } }) .catch((error) => { console.warn(error); }); } removePicture() { this.props.input.onChange(''); this.setState({ cameraVisible: true }); } async takePicture() { const image = await this.camera.capture(); this.savePicture(image); } async savePicture(image) { if (!this.state.saving) { this.setState({ saving: true }, async () => { try { const storedUrl = await storeImage(image.path, true); this.setState({ cameraVisible: false, saving: false }, () => { this.props.input.onChange(storedUrl); }); } catch (err) { console.warn('TODO: handle error', err); } }); } } renderConfirmView() { let image = <Text>{i18n.t('commonText.loading')}</Text>; if (this.props.input.value && this.props.input.value.length > 0) { image = (<ImageCache resizeMode="contain" style={{ height: 416, width: Theme.screen.width - (56 * 2) }} localSource source={{ uri: this.props.input.value }} />); } return ( <View style={styles.container}> <View style={styles.preview}>{image}</View> <TouchableHighlight style={styles.leftBtn} onPress={this.removePicture} activeOpacity={0.8} underlayColor={Theme.background.white} > <Image style={[Theme.icon, styles.leftBtnIcon]} source={cameraAddIcon} /> </TouchableHighlight> </View> ); } renderCameraView() { return ( <View style={styles.container}> <Text style={styles.captureLabel} >{i18n.t('report.takePicture')}</Text> <View pointerEvents="none" style={styles.cameraContainer}> <Camera ref={(cam) => { this.camera = cam; }} type={this.state.cameraType} style={styles.camera} aspect={Camera.constants.Aspect.fit} captureTarget={Camera.constants.CaptureTarget.disk} captureQuality={Camera.constants.CaptureQuality.medium} onFocusChanged={() => {}} onZoomChanged={() => {}} defaultTouchToFocus mirrorImage={false} /> </View> <TouchableHighlight style={[styles.captureBtn, this.state.saving ? styles.captureBtnDisabled : '']} onPress={this.takePicture} activeOpacity={0.8} underlayColor={Theme.background.secondary} > <Image style={Theme.icon} source={cameraIcon} /> </TouchableHighlight> </View> ); } render() { if (this.state.viewPrepared) { const cameraVisible = this.state.cameraVisible; StatusBar.setBarStyle(cameraVisible ? 'light-content' : 'default'); return cameraVisible ? this.renderCameraView() : this.renderConfirmView(); } return this.renderConfirmView(); } } ImageBlobInput.propTypes = { input: React.PropTypes.shape({ onBlur: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onFocus: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired }).isRequired, navigator: React.PropTypes.object }; export default ImageBlobInput;
JavaScript
0.000015
@@ -774,42 +774,8 @@ s);%0A - this.timerLoadPicture = null;%0A
940fb9a56511b80d55fd4c8284968232abdf1989
Add descriptions for new proposed props
src/ReactBubbleChart.js
src/ReactBubbleChart.js
//------------------------------------------------------------------------------ // Copyright Jonathan Kaufman Corp. 2015 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //------------------------------------------------------------------------------ import ReactBubbleChartD3 from './ReactBubbleChartD3'; import React from 'react'; import ReactDOM from 'react-dom'; // Description of props! // data format: // An array of data objects (defined below) used to populate the bubble chart. // { // _id: string, // unique id (required) // value: number, // used to determine relative size of bubbles (required) // displayText: string,// will use _id if undefined // colorValue: number, // used to determine color // selected: boolean, // if true will use selectedColor/selectedTextColor for circle/text // } // // Can also be a nested JSON object if you want a nested bubble chart. That would look like: // { // _id: string, // children: [ // {data object}, // {data object}, // { // _id: string, // children: [...] // } // ] // legend (optional) // boolean. if true, create and show a legend based on the passed on colors // colorLegend (optional) // an array of: // string || { // color: string, // text: string used in legend, // textColor: string (optional) - if specified will use this for the text color when // over bubbles with that color // } // If this is left undefined everything will render black. But fear not! we add // the css class `bubble` to all... bubbles and `bubble leaf` if it has no // children. This way if you want all bubbles to be styled the same way you can do // so with just css instead of defining a color legend array. // fixedDomain (optional) // Used in tandum with the color legend. If defined, the minimum number corresponds // to the minimum value in the color legend array, and the maximum corresponds to // the max. The rest of the `colorValue` values will use a quantized domain to find // their spot. // If this is undefined we will use the min and max of the `colorValue`s of the // dataset. // { // min: number, // max: number // } // tooltip (optional) // If `true`, will create a `<div>` as a sibling of the main `<svg>` chart, whose // content will be populated by highlighting over one of the bubbles. The class of // this element is `tooltip`. For now all of the styling is handled by this module, // not by CSS. // tooltipProps (optional) // This is where you configure what is populated (and from where) in the tooltip. // This is an array of objects or strings. The objects take three properties - // `css`, `prop`, and `display` (optional). If you use a string instead of an // object, that strings values will be used for all three. // For each object in this array, we create a `<div>` whose class is specified by // `css`. `prop` specifies what property of the data object to display in the // tooltip. `display` (if specified) will prepend the string with `Value: `, if // unspecified, nothing is prepended. // tooltipFunc (optional) // A function that is passed the domNode, the d3 data object, and the color of the // tooltip on hover. Can be used if you want to do fancier dom stuff than just set // some text values. // selectedColor // String hex value. // If defined, will use this to color the circle corresponding to the data object // whose `selected` property is true. // selectedTextColor // String hex value. // If defined, will use this to color the text corresponding to the data object // whose `selected` property is true. // onClick // Can pass a function that will be called with the data object when that bubble is // clicked on. // smallDiameter // Can pass a number below which the label div will have the `small` class added. // defaults to 40 // mediumDiameter // Can pass a number below which the label div will have the `medium` class added, // and above which the `large` class will be added. Defaults to 115. // legendSpacing // The number of pixels between blocks in the legend // for more info, see the README class ReactBubbleChart extends React.Component { constructor(props) { super(props); // define the method this way so that we have a clear reference to it // this is necessary so that window.removeEventListener will work properly this.handleResize = (e => this._handleResize(e)); } /** Render town */ render() { return <div className={"bubble-chart-container " + this.props.className}></div>; } /** When we mount, intialize resize handler and create the bubbleChart */ componentDidMount() { window.addEventListener('resize', this.handleResize); this.bubbleChart = new ReactBubbleChartD3(this.getDOMNode(), this.getChartState()); } /** When we update, update our friend, the bubble chart */ componentDidUpdate() { this.bubbleChart.update(this.getDOMNode(), this.getChartState()); } /** Define what props get passed down to the d3 chart */ getChartState() { return { data: this.props.data, colorLegend: this.props.colorLegend, fixedDomain: this.props.fixedDomain, selectedColor: this.props.selectedColor, selectedTextColor: this.props.selectedTextColor, onClick: this.props.onClick || () => {}, smallDiameter: this.props.smallDiameter, mediumDiameter: this.props.mediumDiameter, legendSpacing: this.props.legendSpacing, legend: this.props.legend, tooltip: this.props.tooltip, tooltipProps: this.props.tooltipProps, tooltipFunc: this.props.tooltipFunc, fontSizeFactor: this.props.fontSizeFactor, duration: this.props.duration, delay: this.props.delay } } /** When we're piecing out, remove the handler and destroy the chart */ componentWillUnmount() { window.removeEventListener('resize', this.handleResize); this.bubbleChart.destroy(this.getDOMNode()); } /** Helper method to reference this dom node */ getDOMNode() { return ReactDOM.findDOMNode(this); } /** On a debounce, adjust the size of our graph area and then update the chart */ _handleResize(e) { this.__resizeTimeout && clearTimeout(this.__resizeTimeout); this.__resizeTimeout = setTimeout(() => { this.bubbleChart.adjustSize(this.getDOMNode()); this.bubbleChart.update(this.getDOMNode(), this.getChartState()); delete this.__resizeTimeout; }, 200); } } export default ReactBubbleChart;
JavaScript
0
@@ -4586,16 +4586,483 @@ legend%0A%0A +// fontSizeFactor%0A// A multiplier used to determine a bubble's font-size as a function of its radius.%0A// If not specified, the font-sizes depend on CSS styles for large, medium, and small classes, or 1em by default.%0A%0A// duration%0A// Determines the length of time (in milliseconds) it takes for each bubble's transition animation to complete.%0A// defaults to 500 ms; can set to zero%0A%0A// delay%0A// Staggers the transition between each bubble element.%0A// defaults to 7 ms%0A%0A // for m
55791e8ffd3a670854fd23581315ad0f30c4da51
Embed Hypothesis (#68)
src/components/Header.js
src/components/Header.js
import { Component } from 'react'; import PropTypes from 'prop-types'; import Menu from './Menu'; import Link from 'next/link'; import api from '../api'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ProgressIndicator from './ProgressIndicator'; const styles = theme => ({ root: { zIndex: theme.zIndex.drawer + 1, }, flex: { flexGrow: 1, }, menuButton: { marginLeft: -12, marginRight: 20, }, noLink: { textDecoration: 'none', color: 'inherit', }, }); class Header extends Component { static propTypes = { classes: PropTypes.object.isRequired, }; state = { whoami: { username: '', admin: false, urls: {}, title: '', }, }; async componentDidMount() { const whoami = await api.whoami(); if (whoami) { this.setState({ whoami }); } } render() { const { classes } = this.props; const { whoami } = this.state; return ( <div className={classes.root}> <AppBar position="absolute"> <Toolbar> <Typography variant="h6" color="inherit" className={classes.flex}> <a href="/" className={classes.noLink + ' the-title'} dangerouslySetInnerHTML={{__html: whoami.title}} /> </Typography> <Menu whoami={whoami} /> </Toolbar> </AppBar> </div> ); } } export default withStyles(styles)(Header); { /*<nav className="navbar navbar-expand-md navbar-dark bg-dark"> <div className="container"> <Link href="/"> <a> <span className="navbar-brand">hoover</span> </a> </Link> <Menu /> </div> </nav> */ }
JavaScript
0
@@ -846,16 +846,318 @@ %7D,%0A%7D);%0A%0A +function embedHypothesis(scriptUrl) %7B%0A window.hypothesisConfig = function() %7B%0A return %7B%0A showHighlights:true,%0A appType:'bookmarklet',%0A %7D;%0A %7D;%0A var scriptNode = document.createElement('script');%0A scriptNode.setAttribute('src', scriptUrl);%0A document.body.appendChild(scriptNode);%0A%7D%0A%0A class He @@ -1545,16 +1545,139 @@ ami %7D);%0A + if (whoami.urls.hypothesis_embed) %7B%0A embedHypothesis(whoami.urls.hypothesis_embed);%0A %7D%0A
4fc788bbca1be963dcdcd857dde2be2e0c268a07
Update jquery.dialogOptions.js
jquery.dialogOptions.js
jquery.dialogOptions.js
/* * jQuery UI dialogOptions v1.0 * @desc extending jQuery Ui Dialog - Responsive, click outside, class handling * @author Jason Day * * Dependencies: * jQuery: http://jquery.com/ * jQuery UI: http://jqueryui.com/ * Modernizr: http://modernizr.com/ * * MIT license: * http://www.opensource.org/licenses/mit-license.php * * (c) Jason Day 2014 * * New Options: * clickOut: true // closes dialog when clicked outside * responsive: true // fluid width & height based on viewport * // true: always responsive * // false: never responsive * // "touch": only responsive on touch device * scaleH: 0.8 // responsive scale height percentage, 0.8 = 80% of viewport * scaleW: 0.8 // responsive scale width percentage, 0.8 = 80% of viewport * showTitleBar: true // false: hide titlebar * showCloseButton: true // false: hide close button * * Added functionality: * add & remove dialogClass to .ui-widget-overlay for scoping styles * patch for: http://bugs.jqueryui.com/ticket/4671 * recenter dialog - ajax loaded content */ // add new options with default values $.ui.dialog.prototype.options.clickOut = true; $.ui.dialog.prototype.options.responsive = true; $.ui.dialog.prototype.options.scaleH = 0.8; $.ui.dialog.prototype.options.scaleW = 0.8; $.ui.dialog.prototype.options.showTitleBar = true; $.ui.dialog.prototype.options.showCloseButton = true; // extend _init var _init = $.ui.dialog.prototype._init; $.ui.dialog.prototype._init = function () { var self = this; // apply original arguments _init.apply(this, arguments); //patch if ($.ui && $.ui.dialog && $.ui.dialog.overlay) { $.ui.dialog.overlay.events = $.map('focus,keydown,keypress'.split(','), function (event) { return event + '.dialog-overlay'; }).join(' '); } }; // end _init // extend open function var _open = $.ui.dialog.prototype.open; $.ui.dialog.prototype.open = function () { var self = this; // apply original arguments _open.apply(this, arguments); // get dialog original size on open var oHeight = self.element.parent().outerHeight(), oWidth = self.element.parent().outerWidth(), isTouch = $("html").hasClass("touch"); // responsive width & height var resize = function () { // check if responsive // dependent on modernizr for device detection / html.touch if (self.options.responsive === true || (self.options.responsive === "touch" && isTouch)) { var elem = self.element, wHeight = $(window).height(), wWidth = $(window).width(), dHeight = elem.parent().outerHeight(), dWidth = elem.parent().outerWidth(), setHeight = Math.min(wHeight * self.options.scaleH, oHeight), setWidth = Math.min(wWidth * self.options.scaleW, oWidth); // check & set height if ((oHeight + 100) > wHeight || elem.hasClass("resizedH")) { elem.dialog("option", "height", setHeight).parent().css("max-height", setHeight); elem.addClass("resizedH"); } // check & set width if ((oWidth + 100) > wWidth || elem.hasClass("resizedW")) { elem.dialog("option", "width", setWidth).parent().css("max-width", setWidth); elem.addClass("resizedW"); } // only recenter & add overflow if dialog has been resized if (elem.hasClass("resizedH") || elem.hasClass("resizedW")) { elem.dialog("option", "position", "center"); elem.css("overflow", "auto"); } } // add webkit scrolling to all dialogs for touch devices if (isTouch) { elem.css("-webkit-overflow-scrolling", "touch"); } }; // call resize() resize(); // resize on window resize $(window).on("resize", function () { resize(); }); // resize on orientation change if (window.addEventListener) { // Add extra condition because IE8 doesn't support addEventListener (or orientationchange) window.addEventListener("orientationchange", function () { resize(); }); } // hide titlebar if (!self.options.showTitleBar) { self.uiDialogTitlebar.css({ "height": 0, "padding": 0, "background": "none", "border": 0 }); self.uiDialogTitlebar.find(".ui-dialog-title").css("display", "none"); } //hide close button if (!self.options.showCloseButton) { self.uiDialogTitlebar.find(".ui-dialog-titlebar-close").css("display", "none"); } // close on clickOut if (self.options.clickOut && !self.options.modal) { // use transparent div - simplest approach (rework) $('<div id="dialog-overlay"></div>').insertBefore(self.element.parent()); $('#dialog-overlay').css({ "position": "fixed", "top": 0, "right": 0, "bottom": 0, "left": 0, "background-color": "transparent" }); $('#dialog-overlay').click(function (e) { e.preventDefault(); e.stopPropagation(); self.close(); }); // else close on modal click } else if (self.options.clickOut && self.options.modal) { $('.ui-widget-overlay').click(function (e) { self.close(); }); } // add dialogClass to overlay if (self.options.dialogClass) { $('.ui-widget-overlay').addClass(self.options.dialogClass); } }; //end open // extend close function var _close = $.ui.dialog.prototype.close; $.ui.dialog.prototype.close = function () { var self = this; // apply original arguments _close.apply(this, arguments); // remove dialogClass to overlay if (self.options.dialogClass) { $('.ui-widget-overlay').removeClass(self.options.dialogClass); } //remove clickOut overlay if ($("#dialog-overlay").length) { $("#dialog-overlay").remove(); } }; //end close
JavaScript
0
@@ -252,16 +252,114 @@ izr.com/ + Modernizr adds feature detection. dialogOptions optionally checks for html.touch for scrolling %0A *%0A * M
6270def62b44079883fcaeec1c7436df120b0a99
Fix comments.
js/tweets.js
js/tweets.js
/* * Retrieve the last 100 tweets of the specified user. * To run, execute node express.js */ var url = require('url'); var request = require('request'); var express = require('express'); var app = express(); app.get('/tweets/:username',function(userRequest, userResponse){ var username = userRequest.params.username; var options = { protocol:'http:', host:'api.twitter.com', pathname:'/1/statuses/user_timeline.json', query:{screen_name:username, count:100} }; var twitterURL = url.format(options); request(twitterURL, function(err, res, body){ var tweets = JSON.parse(body); userResponse.render('../views/tweets.ejs', {tweets:tweets, name:username}); }); }); app.listen(7000);
JavaScript
0
@@ -75,22 +75,21 @@ te node -expres +tweet s.js%0A */
fe4c1c833406215cf7138adc017c76e6d5dd6d33
fix code warnings
src/components/MyPoll.js
src/components/MyPoll.js
import React, { Component } from 'react'; class MyPoll extends Component { constructor(props){ super(props); this.mydata = props.data } componentDidMount(){ let svg = d3.select("svg") let g = svg.append("g") .attr("transform", `translation("10", "10")`) .attr("class", "bar") g.selectAll(".bar") .data(this.mydata) .enter().append("rect") .attr("width", 10) .attr("height", (d) => d.value * 10) .attr("x", (d, i) => i * 15) .attr("y", d => 70 - d.value * 10) } render(){ return( <svg/> ) } } export default MyPoll;
JavaScript
0.000014
@@ -18,16 +18,27 @@ omponent +, PropTypes %7D from @@ -148,16 +148,17 @@ ops.data +; %0A %7D%0A%0A @@ -208,16 +208,17 @@ t(%22svg%22) +; %0A let @@ -313,16 +313,17 @@ , %22bar%22) +; %0A%0A g. @@ -538,16 +538,17 @@ ue * 10) +; %0A %7D%0A%0A @@ -591,15 +591,66 @@ ) +; %0A %7D%0A%7D%0A +MyPoll.propTypes = %7B%0A data: PropTypes.object%0A%7D;%0A%0A expo
ad54797c8a942880f28022c9b470acde702bdebf
kill line
components/Footer.js
components/Footer.js
import React from 'react' const Footer = ({clearCompleted, completedIds, selectedFilter, active, setFilter}) => { const filters = ['all', 'active', 'completed'] return ( <footer> <span> {active.length === 0 ? 'no items ' : null} {active.length === 1 ? '1 item ' : null} {active.length > 1 ? active.length + ' items ' : null} left </span> <ul className='filters'> {filters.map(filter => <li className={selectedFilter === filter && 'selected'} key={filter} onClick={() => setFilter(filter)}>{filter}</li> )} </ul> <a href='#' onClick={() => clearCompleted(completedIds)}>Clear completed</a> </footer> ) } export default Footer
JavaScript
0.000001
@@ -112,57 +112,8 @@ %3E %7B%0A - const filters = %5B'all', 'active', 'completed'%5D%0A re @@ -375,23 +375,46 @@ %7B -filters +%5B'all', 'active', 'completed'%5D .map(fil
09fa6b060340e2b41176f8fce9ec5ffc4e811351
update try/catch in _getKeysAndValuesFromEnvFilePath
lib/main.js
lib/main.js
"use strict"; var package_json = require('./../package.json'); var fs = require('fs'); function dotenv() { dotenv = { version: package_json.version, environment: process.env.NODE_ENV || "development", keys_and_values: {}, _loadEnv: function() { return dotenv._getKeysAndValuesFromEnvFilePath(".env"); }, _loadEnvDotEnvironment: function() { return dotenv._getKeysAndValuesFromEnvFilePath(".env."+dotenv.environment); }, _getKeyAndValueFromLine: function(line) { var key_value_array = line.match(/^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/); var key = key_value_array[1].trim(); var value = key_value_array[2].trim(); if (value.charAt(0) === '"' && value.charAt(value.length-1) == '"') { value = value.replace(/\\n/gm, "\n"); } value = value.replace(/['"]/gm, ''); return [key, value]; }, _getKeysAndValuesFromEnvFilePath: function(filepath) { try { var data = fs.readFileSync(filepath); var content = data.toString().trim(); var lines = content.split('\n'); var lines = lines.filter(function(line) { return line.trim().length; }); // remove any empty lines for (var i=0; i<lines.length; i++) { var array = dotenv._getKeyAndValueFromLine(lines[i]); var key = array[0]; var value = array[1]; dotenv.keys_and_values[key] = value; } } catch (e) { } return true; }, _setEnvs: function() { Object.keys(dotenv.keys_and_values).forEach(function(key) { var value = dotenv.keys_and_values[key]; process.env[key] = process.env[key] || value; }); }, load: function() { dotenv._loadEnv(); dotenv._loadEnvDotEnvironment(); dotenv._setEnvs(); return true; }, }; return dotenv; } module.exports = dotenv();
JavaScript
0.000001
@@ -1008,24 +1008,56 @@ filepath) %7B%0A + var data, content, lines;%0A try %7B%0A @@ -1060,28 +1060,24 @@ y %7B%0A -var data @@ -1113,20 +1113,16 @@ -var content @@ -1151,36 +1151,32 @@ trim();%0A -var lines = co @@ -1202,20 +1202,16 @@ -var lines @@ -1303,19 +1303,45 @@ y lines%0A -%0A + %7D catch (e) %7B%0A %7D%0A%0A fo @@ -1371,24 +1371,38 @@ gth; i++) %7B%0A + try %7B%0A va @@ -1574,24 +1574,16 @@ %7D -%0A %7D catch ( @@ -1579,32 +1579,43 @@ %7D catch (e) %7B%0A + %7D%0A%0A %7D%0A%0A r
1b3a2861e0b1ce31e2e44d99ee06f9b2d99f0742
Remove test from header
components/Header.js
components/Header.js
import React from 'react' module.exports = () => <div className='header'> <h1>top of the flops</h1> <p>useless talents, local leaders</p> <a href="/signup">Home</a> </div>
JavaScript
0
@@ -146,39 +146,8 @@ /p%3E%0A - %3Ca href=%22/signup%22%3EHome%3C/a%3E%0A %3C/
6746c0ed435bacbc875f49e771bff31ce450c3d7
remove comment
test/js/mocha_setup.js
test/js/mocha_setup.js
// This will be overridden by mocha-helper if you run with grunt mocha.setup('tdd'); mocha.reporter('html');
JavaScript
0
@@ -1,69 +1,4 @@ -// This will be overridden by mocha-helper if you run with grunt%0A moch
70d80b7ecf029aa8a892a150f9d4f985c3567dfe
Fix typo.
src/SlotContentMixin.js
src/SlotContentMixin.js
import * as symbols from './symbols.js'; /** @type {any} */ const slotchangeFiredKey = Symbol('slotchangeFired'); /** * Defines a component's content as the flattened set of nodes assigned to a * slot. * * This mixin defines a component's `symbols.content` property as the flattened * set of nodes assigned to a slot, typically the default slot. * * This also provides notification of changes to a component's content. It * will invoke a `symbols.contentChanged` method when the component is first * instantiated, and whenever its distributed children change. This is intended * to satisfy the Gold Standard checklist item for monitoring * [Content Changes](https://github.com/webcomponents/gold-standard/wiki/Content-Changes). * * Example: * * ``` * class CountingElement extends SlotContentMixin(HTMLElement) { * * constructor() { * super(); * let root = this.attachShadow({ mode: 'open' }); * root.innerHTML = `<slot></slot>`; * this[symbols.shadowCreated](); * } * * [symbols.contentChanged]() { * if (super[symbols.contentChanged]) { super[symbols.contentChanged](); } * // Count the component's children, both initially and when changed. * this.count = this.distributedChildren.length; * } * * } * ``` * * By default, the mixin looks in the component's shadow subtree for a default * (unnamed) `slot` element. You can specify that a different slot should be * used by overriding the `contentSlot` property. * * To receive `contentChanged` notification, this mixin expects a component to * invoke a method called `symbols.shadowCreated` after the component's shadow * root has been created and populated. * * Most Elix [elements](elements) use `SlotContentMixin`, including * [ListBox](ListBox), [Modes](Modes), and [Tabs](Tabs). * * @module SlotContentMixin */ export default function SlotContentMixin(Base) { // The class prototype added by the mixin. class SlotContent extends Base { componentDidMount() { if (super.componentDidMount) { super.componentDidMount(); } // Listen to changes on the default slot. const slot = this[symbols.contentSlot]; if (slot) { slot.addEventListener('slotchange', async () => { // Although slotchange isn't generally a user-driven event, it's // impossible for us to know whether a change in slot content is going // to result in effects that the host of this element can predict. // To be on the safe side, we raise any change events that come up // during the processing of this event. this[symbols.raiseChangeEvents] = true; // Note that the event has fired. We use this flag in the // normalization promise below. this[slotchangeFiredKey] = true; // The polyfill seems to be able to trigger slotchange during // rendering, which shouldn't happen in native Shadow DOM. We try to // defend against this by deferring updating state. This feels hacky. if (!this[symbols.rendering]) { assignedNodesChanged(this); } else { Promise.resolve().then(() => { assignedNodesChanged(this); }); } await Promise.resolve(); this[symbols.raiseChangeEvents] = false; }); // Chrome and the polyfill will fire slotchange with the initial content, // but Safari won't. We wait to see whether the event fires. (We'd prefer // to synchronously call assignedNodesChanged, but then if a subsequent // slotchange fires, we won't know whether it's an initial one or not.) // We do our best to normalize the behavior so the component always gets // a chance to process its initial content. // // TODO: We filed WebKit bug // https://bugs.webkit.org/show_bug.cgi?id=169718 to resolve this, which // Apple fixed. We've verified in Safari Tech Preview that, with that // fix, unit tests with the code below removed. When the fix lands in // production (best guess: June 2019), this code can be removed. Promise.resolve().then(() => { if (!this[slotchangeFiredKey]) { // The event didn't fire, so we're most likely in Safari. // Update our notion of the component content. this[symbols.raiseChangeEvents] = true; this[slotchangeFiredKey] = true; assignedNodesChanged(this); this[symbols.raiseChangeEvents] = false; } }); } } /** * See [symbols.contentSlot](symbols#contentSlot). */ get [symbols.contentSlot]() { const slot = this.shadowRoot && this.shadowRoot.querySelector('slot:not([name])'); if (!this.shadowRoot || !slot) { /* eslint-disable no-console */ console.warn(`SlotContentMixin expects ${this.constructor.name} to define a shadow tree that includes a default (unnamed) slot.\nSee https://elix.org/documentation/SlotContentMixin.`); } return slot; } get defaultState() { return Object.assign(super.defaultState, { content: null }); } } return SlotContent; } // The nodes assigned to the given component have changed. // Update the component's state to reflect the new content. function assignedNodesChanged(component) { const slot = component[symbols.contentSlot]; const content = slot ? slot.assignedNodes({ flatten: true }) : null; // Make immutable. Object.freeze(content); component.setState({ content }); }
JavaScript
0.001604
@@ -4061,16 +4061,21 @@ t tests +pass with the @@ -4113,19 +4113,16 @@ ix lands - in %0A @@ -4124,16 +4124,19 @@ // + in product
ddc0a7d62321d56bd9e5cb39e6c79edb07bb8259
Fix jasmine example terminating too early against jasmine 1.1.0.
examples/run-jasmine.js
examples/run-jasmine.js
/** * Wait until the test condition is true or a timeout occurs. Useful for waiting * on a server response or for a ui change (fadeIn, etc.) to occur. * * @param testFx javascript condition that evaluates to a boolean, * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or * as a callback function. * @param onReady what to do when testFx condition is fulfilled, * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or * as a callback function. * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. */ function waitFor(testFx, onReady, timeOutMillis) { var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s start = new Date().getTime(), condition = false, interval = setInterval(function() { if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { // If not time-out yet and condition not yet fulfilled condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code } else { if(!condition) { // If condition still not fulfilled (timeout but condition is 'false') console.log("'waitFor()' timeout"); phantom.exit(1); } else { // Condition fulfilled (timeout and/or condition is 'true') console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled clearInterval(interval); //< Stop this interval } } }, 100); //< repeat check every 100ms }; if (phantom.args.length === 0 || phantom.args.length > 2) { console.log('Usage: run-jasmine.js URL'); phantom.exit(); } var page = require('webpage').create(); // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") page.onConsoleMessage = function(msg) { console.log(msg); }; page.open(phantom.args[0], function(status){ if (status !== "success") { console.log("Unable to access network"); phantom.exit(); } else { waitFor(function(){ return page.evaluate(function(){ if (document.body.querySelector('.finished-at')) { return true; } return false; }); }, function(){ page.evaluate(function(){ console.log(document.body.querySelector('.description').innerText); list = document.body.querySelectorAll('div.jasmine_reporter > div.suite.failed'); for (i = 0; i < list.length; ++i) { el = list[i]; desc = el.querySelectorAll('.description'); console.log(''); for (j = 0; j < desc.length; ++j) { console.log(desc[j].innerText); } } }); phantom.exit(); }); } });
JavaScript
0.007565
@@ -2485,19 +2485,27 @@ r('. -finished-at +runner .description '))
a62609ececbdf0d162c68ec3e924647222016a36
Revert some renames and make lint happy
modules/open-url/open-url.js
modules/open-url/open-url.js
// @flow import {Platform, Linking, Alert} from 'react-native' import {appName} from '@frogpond/constants' import SafariView from 'react-native-safari-view' import {CustomTabs} from 'react-native-custom-tabs' function genericOpen(url: string) { return Linking.canOpenURL(url) .then(isSupported => { if (!isSupported) { console.warn('cannot handle', url) } return Linking.openURL(url) }) .catch(err => { console.error(err) }) } function iosOpen(url: string) { // SafariView.isAvailable throws if it's not available return SafariView.isAvailable() .then(() => SafariView.show({url})) .catch(() => genericOpen(url)) } function androidOpen(url: string) { return CustomTabs.openURL(url, { showPageTitle: true, enableUrlBarHiding: true, enableDefaultShare: true, }).catch(() => genericOpen(url)) // fall back to opening in Chrome / Browser / platform default } export function openUrl(url: string) { const protocol = /^(.*?):/u.exec(url) if (protocol && protocol.length) { switch (protocol[1]) { case 'tel': return genericOpen(url) case 'mailto': return genericOpen(url) default: break } } switch (Platform.OS) { case 'android': return androidOpen(url) case 'ios': return iosOpen(url) default: return genericOpen(url) } } export function trackedOpenUrl({url, _id}: {url: string, _id?: string}) { return openUrl(url) } export function canOpenUrl(url: string) { // iOS navigates to about:blank when you provide raw HTML to a webview. // Android navigates to data:text/html;$stuff (that is, the document you passed) instead. if (/^(?:about|data):/u.test(url)) { return false } return true } export function openUrlInBrowser({url, _id}: {url: string, _id?: string}) { return promptConfirm(url) } function promptConfirm(url: string) { const app = appName() const title = `Leaving ${app}` const detail = `A web page will be opened in a browser outside of ${app}.` Alert.alert(title, detail, [ {text: 'Cancel', onPress: () => {}}, {text: 'Open', onPress: () => genericOpen(url)}, ]) }
JavaScript
0
@@ -1333,29 +1333,24 @@ OpenUrl(%7Burl -, _id %7D: %7Burl: str @@ -1346,33 +1346,32 @@ : %7Burl: string, -_ id?: string%7D) %7B%0A @@ -1709,21 +1709,16 @@ ser(%7Burl -, _id %7D: %7Burl: @@ -1730,9 +1730,8 @@ ng, -_ id?:
48020e3f63304499873a975070c37785dd35f1ee
Fix indentation issues
src/components/footer.js
src/components/footer.js
import { h, Component } from 'preact'; import axios from 'axios'; export default class Footer extends Component { constructor(props) { super(props); this.state = { contributors: [] }; } fetchContributers() { axios.get('https://api.github.com/repos/ivanseed/gitstats/contributors') .then(response => { this.setState({ contributors: response.data }) }) .catch(err => { console.log('gota error :(') }) } componentWillMount() { this.fetchContributers(); } render(props, state) { console.log(this.state.contributors) return ( <div className="footer"> <ul> <li id="footer-title"><a href="https://github.com/ivanseed/gitstats"><span>Git<b>Stats</b></span></a></li> <li> <span>Special thanks to all contributors that made this project possible!</span> <span> { state.contributors.map((contributor, i) => ( <b className="contributor"> <a href={`https://github.com/${contributor.login}`}>{contributor.login}</a> { i + 1 === state.contributors.length ? '' : ', ' /* don't render comma on final name */ } </b> )) } </span> </li> </ul> </div> ); } }
JavaScript
0.000038
@@ -315,16 +315,18 @@ s')%0A + .then(re @@ -333,24 +333,26 @@ sponse =%3E %7B%0A + this.s @@ -388,24 +388,26 @@ nse.data %7D)%0A + %7D)%0A . @@ -405,16 +405,18 @@ %7D)%0A + .catch(e @@ -419,24 +419,26 @@ ch(err =%3E %7B%0A + consol @@ -460,16 +460,18 @@ or :(')%0A + %7D)%0A @@ -913,18 +913,22 @@ -%7B%0A + %7B%0A @@ -994,16 +994,18 @@ + %3Cb class @@ -1020,24 +1020,26 @@ ntributor%22%3E%0A + @@ -1138,16 +1138,18 @@ + %7B i + 1 @@ -1247,16 +1247,18 @@ + %3C/b%3E%0A @@ -1272,11 +1272,15 @@ + ))%0A + @@ -1335,24 +1335,26 @@ %3C/ul%3E%0A + %3C/div%3E%0A
f0e5ac5b1f0207867c3382fde220a6f15b5a327d
update toolbar option for medium editor
public/js/blogelweb.js
public/js/blogelweb.js
/** * Main Application JS */ (function() { 'use strict'; var elements = document.querySelectorAll('.editable'), editor = new MediumEditor(elements, { anchorInputPlaceholder: 'Type a link', buttons: ['bold', 'italic', 'underline', 'anchor', 'header1', 'header2', 'quote', 'pre'], firstHeader: 'h1', secondHeader: 'h2', delay: 0, targetBlank: true }); /** * Event Handlers */ function onNewDocument(event) { console.log('New Document clicked!'); } function onPublish(event) { console.log('publish-btn clicked!'); } function onSave(event) { var content = editor.serialize(), post_content = { post: { title: content['element-0'], content: content['element-1'], status: "draft" } }; $.ajax({ url: '/api/posts', type: 'post', data: post_content, dataType: 'json', success: function(data) { console.log(data); }, error: function(err) { console.log(err); } }); } function onSetting(event) { console.log('setting-btn clicked!'); } function onDeleteDoc(event) { console.log('trash-btn clicked!'); } /** * Register Event Handlers */ $('#new-btn').on('click', onNewDocument); $('#publish-btn').on('click', onPublish); $('#save-btn').on('click', onSave); $('#setting-btn').on('click', onSetting); $('#trash-btn').on('click', onDeleteDoc); })();
JavaScript
0
@@ -1,36 +1,4 @@ -/**%0A * Main Application JS%0A */%0A%0A (fun @@ -7,17 +7,16 @@ ion() %7B%0A -%0A 'use @@ -25,17 +25,16 @@ trict';%0A -%0A var @@ -38,18 +38,33 @@ ar e -lements = +ditor = new MediumEditor( docu @@ -98,16 +98,18 @@ table'), + %7B %0A @@ -113,95 +113,65 @@ -editor = new MediumEditor(elements, %7B%0A anchorInputPlaceholder: 'Type a link' +toolbar: %7B%0A allowMultiParagraphSelection: true ,%0A @@ -237,25 +237,15 @@ , 'h -eader1', 'header2 +2', 'h3 ', ' @@ -276,79 +276,209 @@ -firstHeader: 'h1',%0A secondHeader: 'h2',%0A delay: 0 +diffLeft: 0,%0A diffTop: -10,%0A firstButtonClass: 'medium-editor-button-first',%0A lastButtonClass: 'medium-editor-button-last',%0A standardizeSelectionStart: false ,%0A @@ -491,76 +491,138 @@ +s ta -rgetBlank: true%0A %7D);%0A%0A /**%0A * Event Handlers%0A */ +tic: false,%0A align: 'center',%0A sticky: false,%0A updateOnEmptySelection: false%0A %7D%0A %7D); %0A%0A @@ -1584,55 +1584,8 @@ %7D%0A%0A - /**%0A * Register Event Handlers%0A */%0A @@ -1804,15 +1804,14 @@ teDoc);%0A -%0A %7D)();%0A
74e07883d07814490f8bf3aa92fad36dfcde32da
change the way dates are checked
js/useful.js
js/useful.js
function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' '); } function getLocale(usr) { database.ref('users/' + usr).once('value', function(snap) { var _locale = snap.val().state + '/' + snap.val().city + '/' + snap.val().school; return _locale; }); } function getClubs() { var username = sessionStorage.getItem('user'); var _clubs = []; database.ref('users/' + username + '/clubs').once('value', function(snap) { snap.forEach(function(item) { console.log(item.key); _clubs.push(item.key); }); }); return _clubs; } function getSchoolClubs() { var state = sessionStorage.getItem('state'); var city = sessionStorage.getItem('city'); var school = sessionStorage.getItem('school'); var locale = state + '/' + city + '/' + school; var _clubs = []; database.ref('schools/' + locale).once('value', function(snap) { snap.forEach(function(item) { console.log(item.key); _clubs.push(item.key); }); }); } function getDate(str) { // Looks like MM/DD/YYYY hh:mm TT try { var sects = str.split(' '); var days = sects[0].split('/'); var times = sects[1].split(':'); var tt = sects[2]; var mm = parseInt(days[0]) - 1; var dd = parseInt(days[1]); var yyyy = parseInt(days[2]); var hours = parseInt(times[0]); var minutes = parseInt(times[1]); if (tt == "PM") { hours += 12; } return new Date(yyyy, mm, dd, hours, minutes); } catch (e) { console.log(e); var r = new Date(); r.setSeconds(r.getSeconds() + 60); return r; } }
JavaScript
0.00001
@@ -1224,11 +1224,244 @@ TT%0A%09 -try +let datex = /%5Cd%5Cd%5C/%5Cd%5Cd%5C/%5Cd%5Cd%5Cd%5Cd%5Cs%5Cd%5Cd:%5Cd%5Cd%5Cs%5BA:P%5DM/%0A%0A%09if (!(str.match(datex))) %7B%0A%09%09console.log(%22Date of unknown format. Assuming it hasn't happened yet%22);%0A%09%09var r = new Date();%0A%09%09r.setSeconds(r.getSeconds() + 60);%0A%09%09return r;%0A%09%7D else %7B%0A%09 @@ -1757,108 +1757,446 @@ if ( -tt == %22PM%22) %7B%0A%09%09%09hours += 12;%0A%09%09%7D%0A%0A%09%09return new Date(yyyy, mm, dd, hours, minutes);%0A%09%7D%0A%09catch (e +(((mm + 1 == 1) %7C%7C (mm + 1 == 3) %7C%7C (mm + 1 == 5) %7C%7C (mm + 1 == 7) %7C%7C (mm + 1 == 8) %7C%7C (mm + 1 == 10) %7C%7C (mm + 1 == 12)) && (dd %3E 31))%0A%09%09%09%7C%7C (((mm + 1 == 4) %7C%7C (mm + 1 == 6) %7C%7C (mm + 1 == 9) %7C%7C (mm + 1 == 11)) && (dd %3E 30))%0A%09%09%09%7C%7C ((mm + 1 == 2) && (yyyy %25 4 != 0) && (dd %3E 28))%0A%09%09%09%7C%7C ((mm + 1 == 2) && (yyyy %25 4 == 0) && (dd %3E 29))%0A%09%09%09%7C%7C (hours %3E 12) %7C%7C (hours %3C 1) %7C%7C (minutes %3E 60) %7C%7C (minutes %3C 0) %7C%7C (mm + 1 %3E 12) %7C%7C (mm + 1 %3C 1) ) %7B%0A +%09 %09%09co @@ -2209,14 +2209,28 @@ log( -e +%22Date Invalid%22 );%0A%09%09 +%09 var @@ -2237,32 +2237,33 @@ r = new Date();%0A +%09 %09%09r.setSeconds(r @@ -2268,36 +2268,175 @@ (r.getSeconds() -+ 60 +- 1);%0A%09%09%09return r;%0A%09%09%7D%0A%0A%09%09if (tt == %22PM%22) %7B%0A%09%09%09hours += 12;%0A%09%09%7D%0A%0A%09%09var ret = new Date(yyyy, mm, dd, hours, minutes);%0A%09%09console.log(%22Date Valid%22 );%0A%09%09return r;%0A%09 @@ -2428,18 +2428,20 @@ ;%0A%09%09return r +et ;%0A%09%7D%0A%7D
7b9e5802bd7b12c01cc489542c77e3ba30644f66
Fix tests for 10 language limit
test/langPickerTest.js
test/langPickerTest.js
/* global describe it */ const assert = require('assert'); const LanguagePicker = require('../lib/LanguagePicker'); describe('LanguagePicker: Pick the correct language', () => { const cases = [ { msg: 'No values given', langCode: 'en', values: undefined, expected: undefined, }, { msg: 'Pick first (only) value', langCode: 'en', values: [ { en: 'en value' }, ], expected: 'en value', }, { msg: 'Pick exact match language value', langCode: 'he', values: [ { en: 'en value' }, { he: 'he value' }, ], expected: 'he value', }, { msg: 'Fallback yi -> he', langCode: 'yi', config: { languageMap: { yi: 'he', foo: 'bar', other: 'languages', that: 'dont', matter: 'at all', }, }, values: [ { en: 'en value' }, { he: 'he value' }, { es: 'es value' }, ], expected: 'he value', }, { msg: 'Fallback gan -> zh-hans (third fallback)', langCode: 'gan', config: { languageMap: { gan: [ 'gan-hant', 'zh-hant', 'zh-hans', ], }, }, values: [ { en: 'en value' }, { he: 'he value' }, { 'zh-hans': 'zh-hans value' }, ], expected: 'zh-hans value', }, { msg: 'Object language map, fallback foo -> bar', langCode: 'foo', config: { languageMap: { foo: 'bar' }, }, values: [ { baz: 'baz value' }, { bar: 'bar value' }, { quuz: 'quuz value' }, ], expected: 'bar value', }, { msg: 'Object language map given, but no fallback exists, fall back to en', langCode: 'foo', config: { languageMap: { foo: 'bar' }, }, values: [ { baz: 'baz value' }, { en: 'en value' }, { quuz: 'quuz value' }, ], expected: 'en value', }, { msg: 'No fallback value exists; fallback to en', langCode: 'yi', values: [ { es: 'es value' }, { en: 'en value' }, ], expected: 'en value', }, { msg: 'No fallback value exists, no en value exists, fallback to nameTag', langCode: 'yi', config: { nameTag: 'name', }, values: [ { ru: 'ru value' }, { name: 'base name tag' }, { fr: 'fr value' }, ], expected: 'base name tag', }, { msg: 'No fallback value exists, no en value exists, no nameTag given, fallback to first option given', langCode: 'yi', values: [ { ru: 'ru value' }, { es: 'es value' }, { fr: 'fr value' }, ], expected: 'ru value', }, { msg: 'Use prefixed codes', langCode: 'en', config: { multiTag: 'pref_', }, values: [ { pref_ru: 'ru value' }, { pref_en: 'en value' }, { pref_fr: 'fr value' }, ], expected: 'en value', }, { msg: 'Language code unrecognized, fallback to en', langCode: 'quuz', values: [ { ru: 'ru value' }, { fr: 'fr value' }, { en: 'en value' }, ], expected: 'en value', }, ]; cases.forEach((data) => { const lp = new LanguagePicker(data.langCode, data.config); const lpp = lp.newProcessor(); // Add test values (data.values || []).forEach((valueData) => { const lang = Object.keys(valueData)[0]; lpp.addValue(lang, valueData[lang]); }); // Check the result it(data.msg, () => { assert.equal( lpp.getResult(), data.expected ); }); }); }); describe('LanguagePicker: Build a correct fallback list', () => { const cases = [ { msg: 'Spanish falls back to a Latn language', langCode: 'es', expected: ['es', 'aa', 'abr', 'ace', 'ach', 'ada', 'en'], }, { msg: 'Language with a fallback and script fallbacks', langCode: 'yi', config: { languageMap: { yi: 'he', // From fallbacks.json other: 'languages', that: 'dont', matter: 'at all', }, }, // Languages with 'Hebr' script come after the // official fallback expected: ['yi', 'he', 'jpr', 'jrb', 'lad', 'en'], }, ]; cases.forEach((data) => { const lp = new LanguagePicker(data.langCode, data.config); const lpp = lp.newProcessor(); // Check the result it(data.msg, () => { assert.deepStrictEqual( lpp.getFallbacks(), data.expected ); }); }); });
JavaScript
0.000002
@@ -4028,16 +4028,49 @@ , 'ada', + 'af', 'agq', 'ak', 'akz', 'ale', 'en'%5D,%0A @@ -4427,16 +4427,80 @@ fallback + (and there are only 5 languages%0A // using the Hebr script) %0A e
968dbdc05793a4711b0a64785b2e4a420071ee21
mark field as invalid using df
frappe/public/js/frappe/form/controls/data.js
frappe/public/js/frappe/form/controls/data.js
frappe.ui.form.ControlData = frappe.ui.form.ControlInput.extend({ html_element: "input", input_type: "text", make_input: function() { if(this.$input) return; this.$input = $("<"+ this.html_element +">") .attr("type", this.input_type) .attr("autocomplete", "off") .addClass("input-with-feedback form-control") .prependTo(this.input_area); if (in_list(['Data', 'Link', 'Dynamic Link', 'Password', 'Select', 'Read Only', 'Attach', 'Attach Image'], this.df.fieldtype)) { this.$input.attr("maxlength", this.df.length || 140); } this.set_input_attributes(); this.input = this.$input.get(0); this.has_input = true; this.bind_change_event(); this.bind_focusout(); this.setup_autoname_check(); // somehow this event does not bubble up to document // after v7, if you can debug, remove this }, setup_autoname_check: function() { if (!this.df.parent) return; this.meta = frappe.get_meta(this.df.parent); if (this.meta && ((this.meta.autoname && this.meta.autoname.substr(0, 6)==='field:' && this.meta.autoname.substr(6) === this.df.fieldname) || this.df.fieldname==='__newname') ) { this.$input.on('keyup', () => { this.set_description(''); if (this.doc && this.doc.__islocal) { // check after 1 sec let timeout = setTimeout(() => { // clear any pending calls if (this.last_check) clearTimeout(this.last_check); // check if name exists frappe.db.get_value(this.doctype, this.$input.val(), 'name', (val) => { if (val) { this.set_description(__('{0} already exists. Select another name', [val.name])); } }, this.doc.parenttype ); this.last_check = null; }, 1000); this.last_check = timeout; } }); } }, set_input_attributes: function() { this.$input .attr("data-fieldtype", this.df.fieldtype) .attr("data-fieldname", this.df.fieldname) .attr("placeholder", this.df.placeholder || ""); if(this.doctype) { this.$input.attr("data-doctype", this.doctype); } if(this.df.input_css) { this.$input.css(this.df.input_css); } if(this.df.input_class) { this.$input.addClass(this.df.input_class); } }, set_input: function(value) { this.last_value = this.value; this.value = value; this.set_formatted_input(value); this.set_disp_area(value); this.set_mandatory && this.set_mandatory(value); }, set_formatted_input: function(value) { this.$input && this.$input.val(this.format_for_input(value)); }, get_input_value: function() { return this.$input ? this.$input.val() : undefined; }, format_for_input: function(val) { return val==null ? "" : val; }, validate: function(v) { if(this.df.is_filter) { return v; } if(this.df.options == 'Phone') { if(v+''=='') { return ''; } var v1 = ''; // phone may start with + and must only have numbers later, '-' and ' ' are stripped v = v.replace(/ /g, '').replace(/-/g, '').replace(/\(/g, '').replace(/\)/g, ''); // allow initial +,0,00 if(v && v.substr(0,1)=='+') { v1 = '+'; v = v.substr(1); } if(v && v.substr(0,2)=='00') { v1 += '00'; v = v.substr(2); } if(v && v.substr(0,1)=='0') { v1 += '0'; v = v.substr(1); } v1 += cint(v) + ''; return v1; } else if(this.df.options == 'Email') { if(v+''=='') { return ''; } var email_list = frappe.utils.split_emails(v); if (!email_list) { // invalid email return ''; } else { var invalid_email = false; email_list.forEach(function(email) { if (!validate_email(email)) { frappe.msgprint(__("Invalid Email: {0}", [email])); invalid_email = true; } }); if (invalid_email) { // at least 1 invalid email return ''; } else { // all good return v; } } } else { return v; } } });
JavaScript
0.001573
@@ -3474,25 +3474,25 @@ %09%09%09%09 -var +let email_ invalid -_email = f @@ -3583,79 +3583,21 @@ %09%09%09%09 -frappe.msgprint(__(%22Invalid Email: %7B0%7D%22, %5Bemail%5D));%0A%09%09%09%09%09%09 +email_ invalid -_email = t @@ -3620,114 +3620,45 @@ %7D);%0A -%0A %09%09%09%09 -if ( +this.df. invalid -_ + = email -) %7B%0A%09%09%09%09%09// at least 1 invalid email%0A%09%09%09%09%09return '';%0A%09%09%09%09%7D else %7B%0A%09%09%09%09%09// all good%0A%09 +_invalid;%0A %09%09%09%09 @@ -3667,22 +3667,16 @@ turn v;%0A -%09%09%09%09%7D%0A %09%09%09%7D%0A%0A%09%09
cb1849ffe8ff6fbcdb8311203a841c1dce8d63d1
fix tests
frontend/app/models/answer-type.js
frontend/app/models/answer-type.js
import { computed } from '@ember/object'; import Model from 'ember-data/model'; import attr from 'ember-data/attr'; import { hasMany } from 'ember-data/relationships'; export default Model.extend({ // Attributes name: attr('string'), status: attr('string'), postName: attr('string'), postType: attr('string'), elementType: attr('string'), groupType: attr('string'), descriptiveName: attr('string'), description: attr('string'), hasAnAnswer: attr('boolean', { defaultValue: false }), types: [ 'checkboxlist', 'hiddencheckboxlist', 'chosenmultiselect', 'hiddenchosenmultiselect', 'chosenmultiselectgrouped', 'hiddenchosenmultiselectgrouped', 'radio', 'hiddenradio', 'select', 'hiddenselect', 'chosenselect' ], // Associations questions: hasMany('question'), // Computed Properties hasAnswerChoices: computed('name', function() { return this.get('types').includes(this.get('name')); }), isNotLookupRule: computed('name', function() { return ['chosenselect', 'chosenmultiselect', 'document', 'helperabove', 'photo', 'video', 'line', 'repeater', 'section', 'latlong', 'signature', 'static'].includes(this.get('name')); }), // isNotLookupCondition: computed('name', function() { // return ['time'].includes(this.get('name')); // }), displayName: computed('name', 'descriptiveName', function() { return this.get('descriptiveName') || this.get('name'); }) });
JavaScript
0.000001
@@ -1025,16 +1025,23 @@ return %5B +%0A 'chosens @@ -1047,16 +1047,22 @@ select', +%0A 'chosen @@ -1074,16 +1074,22 @@ select', +%0A 'docume @@ -1092,16 +1092,22 @@ cument', +%0A 'helper @@ -1113,16 +1113,22 @@ rabove', +%0A 'photo' @@ -1128,16 +1128,22 @@ 'photo', +%0A 'video' @@ -1147,16 +1147,22 @@ eo', +%0A 'line', 're @@ -1157,16 +1157,22 @@ 'line', +%0A 'repeat @@ -1175,16 +1175,22 @@ peater', +%0A 'sectio @@ -1192,16 +1192,22 @@ ection', +%0A 'latlon @@ -1209,16 +1209,22 @@ atlong', +%0A 'signat @@ -1232,132 +1232,28 @@ re', - 'static'%5D.includes(this.get('name'));%0A %7D),%0A%0A // isNotLookupCondition: computed('name', function() %7B%0A // return %5B'time' +%0A 'static'%0A %5D.in @@ -1279,19 +1279,16 @@ me'));%0A - // %7D),%0A%0A @@ -1414,13 +1414,12 @@ );%0A %7D)%0A -%0A %7D);%0A
3296558731e51074eafc16b242c3ff60b4027568
Add another test
dev/_/components/js/sourceModel.js
dev/_/components/js/sourceModel.js
// Source Model AV.source = Backbone.Model.extend({ url: 'php/redirect.php#source', defaults: { name: '', type: 'raw', contentType: 'txt', data: '' }, }); // Source Model Tests test_source = new AV.source({ name: 'Potato Chips', type: 'raw', contentType: 'txt', data: "No matter where it is, you'll always find a bag around. At a bar, or"+ " a picnic. Even a baseball ground!" }); test_source.save( { success: function () { alert('success'); }, error: function(d){ alert('everything is terrible'); } }); // Source Model End
JavaScript
0.000035
@@ -72,9 +72,9 @@ .php -# +/ sour @@ -155,20 +155,16 @@ ''%0A%09%7D,%0A - %0A %7D);%0A// S @@ -182,16 +182,19 @@ Tests%0A%0A +// test_sou @@ -215,16 +215,19 @@ ource(%7B%0A +// name @@ -233,27 +233,39 @@ e: ' -Potato Chips +The Wind and the Rain ',%0A +// + type @@ -273,16 +273,19 @@ 'raw',%0A +// cont @@ -300,16 +300,19 @@ 'txt',%0A +// data @@ -318,130 +318,182 @@ a: %22 -No matter where it is, you'll always find a bag around. At a bar +When that I was and a little tiny boy, with a hey-ho, the wind and the rain, a foolish thing was but a toy , +f or -%22+%0A %22 a picnic. Even a baseball ground!%22%0A%7D);%0A%0A + the rain it raineth every day.%22%0A// %7D);%0A// alert('potato');%0A// test @@ -508,16 +508,19 @@ save( %7B%0A +// @@ -542,16 +542,19 @@ on () %7B%0A +// @@ -571,24 +571,27 @@ 'success');%0A +// %7D,%0A @@ -589,16 +589,19 @@ %7D,%0A +// @@ -620,16 +620,18 @@ ion(d)%7B%0A +// @@ -630,24 +630,25 @@ + alert('every @@ -668,16 +668,19 @@ ible');%0A +// @@ -692,17 +692,119 @@ %0A +// + %7D);%0A%0A +other_test = new AV.source();%0Aother_test.url = 'php/redirect.php/source/15';%0Aother_test.fetch();%0A%0A%0A // S
0fdbdaf300211a1f1919870509c64c7787cc4383
clear next frame action before scheduling another
src/TextareaAutosize.js
src/TextareaAutosize.js
/** * <TextareaAutosize /> */ import React from 'react'; import emptyFunction from 'react/lib/emptyFunction'; import calculateNodeHeight from './calculateNodeHeight'; export default class TextareaAutosize extends React.Component { static propTypes = { /** * Current textarea value. */ value: React.PropTypes.string, /** * Callback on value change. */ onChange: React.PropTypes.func, /** * Callback on height changes. */ onHeightChange: React.PropTypes.func, /** * Try to cache DOM measurements performed by component so that we don't * touch DOM when it's not needed. * * This optimization doesn't work if we dynamically style <textarea /> * component. */ useCacheForDOMMeasurements: React.PropTypes.bool, /** * Minimal numbder of rows to show. */ rows: React.PropTypes.number, /** * Alias for `rows`. */ minRows: React.PropTypes.number, /** * Maximum number of rows to show. */ maxRows: React.PropTypes.number } static defaultProps = { onChange: emptyFunction, onHeightChange: emptyFunction, useCacheForDOMMeasurements: false } constructor(props) { super(props); this.state = { height: null, minHeight: -Infinity, maxHeight: Infinity }; this._onChange = this._onChange.bind(this); this._resizeComponent = this._resizeComponent.bind(this); } render() { let {valueLink, onChange, ...props} = this.props; props = {...props}; if (typeof valueLink === 'object') { props.value = this.props.valueLink.value; } props.style = { ...props.style, height: this.state.height }; let maxHeight = Math.max( props.style.maxHeight ? props.style.maxHeight : Infinity, this.state.maxHeight); if (maxHeight < this.state.height) { props.style.overflow = 'hidden'; } return <textarea {...props} onChange={this._onChange} />; } componentDidMount() { this._resizeComponent(); } componentWillReceiveProps() { // Re-render with the new content then recalculate the height as required. this.onNextFrameActionId = onNextFrame(this._resizeComponent); } componentDidUpdate(prevProps, prevState) { // Invoke callback when old height does not equal to new one. if (this.state.height !== prevState.height) { this.props.onHeightChange(this.state.height); } } componentWillUnmount() { //remove any scheduled events to prevent manipulating the node after it's //been unmounted if (this.onNextFrameActionId) { clearNextFrameAction(this.onNextFrameActionId); } } _onChange(e) { this._resizeComponent(); let {valueLink, onChange} = this.props; if (valueLink) { valueLink.requestChange(e.target.value); } else { onChange(e); } } _resizeComponent() { let {useCacheForDOMMeasurements} = this.props; this.setState(calculateNodeHeight( React.findDOMNode(this), useCacheForDOMMeasurements, this.props.rows || this.props.minRows, this.props.maxRows)); } /** * Read the current value of <textarea /> from DOM. */ get value(): string { return React.findDOMNode(this).value; } /** * Put focus on a <textarea /> DOM element. */ focus() { React.findDOMNode(this).focus(); } } function onNextFrame(cb) { if (window.requestAnimationFrame) { return window.requestAnimationFrame(cb); } return window.setTimeout(cb, 1); } function clearNextFrameAction(nextFrameId) { if (window.cancelAnimationFrame) { window.cancelAnimationFrame(nextFrameId); } else { window.clearTimeout(nextFrameId); } }
JavaScript
0
@@ -2165,24 +2165,51 @@ s required.%0A + this.clearNextFrame();%0A this.onN @@ -2618,16 +2618,69 @@ mounted%0A + this.clearNextFrame();%0A %7D%0A%0A clearNextFrame() %7B%0A if (
cff429b2f9bcdfbe32c766832f659d3718579a2f
Fix PR review
packages/core/admin/admin/src/content-manager/pages/EditSettingsView/components/GenericInput.js
packages/core/admin/admin/src/content-manager/pages/EditSettingsView/components/GenericInput.js
import React from 'react'; import PropTypes from 'prop-types'; import { TextInput } from '@strapi/design-system/TextInput'; import { ToggleInput } from '@strapi/design-system/ToggleInput'; import { Select, Option } from '@strapi/design-system/Select'; const GenericInput = ({ type, options, onChange, value, name, ...inputProps }) => { switch (type) { case 'text': { return <TextInput onChange={onChange} value={value} name={name} {...inputProps} />; } case 'bool': { return ( <ToggleInput onChange={e => { onChange({ target: { name, value: e.target.checked } }); }} checked={value === null ? null : value || false} name={name} onLabel="true" offLabel="false" {...inputProps} /> ); } case 'select': { return ( <Select value={value} name={name} onChange={value => onChange({ target: { name, value } })} {...inputProps} > {options.map(option => ( <Option key={option} value={option}> {option} </Option> ))} </Select> ); } default: return null; } }; GenericInput.defaultProps = { options: undefined, }; GenericInput.propTypes = { type: PropTypes.string.isRequired, options: PropTypes.arrayOf(PropTypes.string), onChange: PropTypes.func.isRequired, value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]).isRequired, name: PropTypes.string.isRequired, }; export default GenericInput;
JavaScript
0.000001
@@ -244,16 +244,54 @@ Select'; +%0Aimport %7B useIntl %7D from 'react-intl'; %0A%0Aconst @@ -368,16 +368,56 @@ %7D) =%3E %7B%0A + const %7B formatMessage %7D = useIntl();%0A%0A switch @@ -733,63 +733,171 @@ alue - === null ? null : value %7C%7C false%7D%0A name=%7Bname +%7D%0A name=%7Bname%7D%0A onLabel=%7BformatMessage(%7B%0A id: 'app.components.ToggleCheckbox.on-label',%0A defaultMessage: 'On',%0A %7D) %7D%0A @@ -909,48 +909,140 @@ o -n +ff Label= -%22true%22%0A offL +%7BformatMessage(%7B%0A id: 'app.components.ToggleCheckbox.off-l abel -=%22false%22 +',%0A defaultMessage: 'Off',%0A %7D)%7D %0A
627f1825d624bcd578e501291f170edfb36a8781
add missing semicolon
lib/api-client/resources/authorization.js
lib/api-client/resources/authorization.js
'use strict'; var AbstractClientResource = require("./../abstract-client-resource"); /** * Authorization Resource * @class * @memberof CamSDK.client.resource * @augments CamSDK.client.AbstractClientResource */ var Authorization = AbstractClientResource.extend(); /** * API path for the process definition resource * @type {String} */ Authorization.path = 'authorization'; /** * Fetch a list of authorizations * * @param {Object} params * @param {Object} [params.id] Authorization by the id of the authorization. * @param {Object} [params.type] Authorization by the type of the authorization. * @param {Object} [params.userIdIn] Authorization by a comma-separated list of userIds * @param {Object} [params.groupIdIn] Authorization by a comma-separated list of groupIds * @param {Object} [params.resourceType] Authorization by resource type * @param {Object} [params.resourceId] Authorization by resource id. * @param {Object} [params.sortBy] Sort the results lexicographically by a given criterion. * Valid values are resourceType and resourceId. * Must be used with the sortOrder parameter. * @param {Object} [params.sortOrder] Sort the results in a given order. * Values may be "asc" or "desc". * Must be used in conjunction with the sortBy parameter. * @param {Object} [params.firstResult] Pagination of results. * Specifies the index of the first result to return. * @param {Object} [params.maxResults] Pagination of results. * Specifies the maximum number of results to return. * @param {Function} done */ Authorization.list = function(params, done) { return this.http.get(this.path, { data: params, done: done }); }; /** * Retrieve a single authorization * * @param {uuid} authorizationId of the authorization to be requested * @param {Function} done */ Authorization.get = function(authorizationId, done) { return this.http.get(this.path +'/'+ authorizationId, { done: done }); }; /** * Creates an authorization * * @param {Object} authorization is an object representation of an authorization * @param {Function} done */ Authorization.create = function(authorization, done) { return this.http.post(this.path +'/create', { data: authorization, done: done }); }; /** * Update an authorization * * @param {Object} authorization is an object representation of an authorization * @param {Function} done */ Authorization.update = function(authorization, done) { return this.http.put(this.path +'/'+ authorization.id, { data: authorization, done: done }); }; /** * Save an authorization * * @see Authorization.create * @see Authorization.update * * @param {Object} authorization is an object representation of an authorization, * if it has an id property, the authorization will be updated, * otherwise created * @param {Function} done */ Authorization.save = function(authorization, done) { return Authorization[authorization.id ? 'update' : 'create'](authorization, done); }; /** * Delete an authorization * * @param {uuid} id of the authorization to delete * @param {Function} done */ Authorization.delete = function(id, done) { return this.http.del(this.path +'/'+ id, { done: done }); }; Authorization.check = function(authorization, done) { return this.http.get(this.path + '/check', { data: authorization, done: done }); } module.exports = Authorization;
JavaScript
0.000365
@@ -3767,16 +3767,17 @@ %0A %7D);%0A%7D +; %0A%0A%0A%0Amodu
341e9bb6150140b1ac112d76f455d29c89878e09
remove stale instagram link
src/components/footer.js
src/components/footer.js
import React from "react"; import {Link} from "react-router"; export default class Footer extends React.Component { constructor(props) { super(props); this.state = { views: null, authenticated: false, adminView: null } } componentDidMount = () => { if (typeof(window) !== undefined) { this.setState({ adminView: sessionStorage.getItem("loggedIn") ? <a onClick={this.handleLogout} href="/logout">Logout</a> : <Link id="admin" to="/login">Admin</Link> }) } /*fetch("/views", { method: "get" }).then((res) => { return res.json(); }).then((json) => { if(!json.data) { this.setState({ views: 1 }, () => { return; }); } else { this.setState({ views: json.data }); } })*/ if (!localStorage.getItem("viewed")) { fetch("/views", { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({data: true}) }).then((res) => { return res.json(); }).then((json) => { this.setState({ views: json.data }); localStorage.setItem("viewed", "true"); }); } else if (localStorage.getItem("viewed")) { fetch("/views", { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify({data: false}) }).then((res) => { return res.json(); }).then((json) => { this.setState({ views: json.data }); }); this.setState({ views: Number(localStorage.getItem("views")) }) return; } }; handleLogout = () => { sessionStorage.removeItem("loggedIn"); } render() { let views = this.state.views ? this.state.views : null; return ( <div className="footer"> <h3 id="page-views">Page Views: <span className="views">{this.state.views}</span></h3> <div className="contact"> <h4 id="social">Social Media</h4> <a href="https://www.instagram.com/officialdoublerr7/" target="_blank"><img className="icon" src="/static/images/instagram.png"/></a> <img className="icon" src="/static/images/twitter.png"/> <img className="icon" src="/static/images/facebook.png"/> <img className="icon" src="/static/images/youtube.png"/> </div> <div className="misc"> {this.state.adminView} <h6 id="credits">Designed by Chival Trotman</h6> </div> </div> ) } }
JavaScript
0.000002
@@ -2596,79 +2596,8 @@ -%3Ca href=%22https://www.instagram.com/officialdoublerr7/%22 target=%22_blank%22%3E %3Cimg @@ -2650,20 +2650,16 @@ m.png%22/%3E -%3C/a%3E %0A
4f4ebe9657a34896dc4f181983fb23450ca3351e
Replace insert with a replace frontend
menuitem.js
menuitem.js
import {style, inline, Node} from "../model" import {splitAt, joinPoint, liftableRange, wrappableRange, describeTarget, insertInline} from "../transform" import {elt} from "../edit/dom" export class Item { constructor(icon, title) { this.icon = icon this.title = title } active() { return false } select() { return true } } export class LiftItem extends Item { constructor(icon, title) { super(icon, title || "Move out of block") } select(pm) { let sel = pm.selection return liftableRange(pm.doc, sel.from, sel.to) } apply(pm) { let sel = pm.selection let range = liftableRange(pm.doc, sel.from, sel.to) pm.apply(range) } } export class JoinItem extends Item { constructor(icon, title) { super(icon, title || "Join with above block") } select(pm) { return joinPoint(pm.doc, pm.selection.head) } apply(pm) { let point = joinPoint(pm.doc, pm.selection.head) if (point) pm.apply(point) } } export class SubmenuItem extends Item { constructor(icon, title, submenu) { super(icon, title) this.submenu = submenu } select(pm) { return this.submenu.some(i => i.select(pm)) } apply(pm) { return this.submenu.filter(i => i.select(pm)) } } export class BlockTypeItem extends Item { constructor(icon, title, type, attrs) { super(icon, title) this.type = type this.attrs = attrs } apply(pm) { let sel = pm.selection pm.apply({name: "setType", pos: sel.from, end: sel.to, type: this.type, attrs: this.attrs}) } } export class InsertBlockItem extends Item { constructor(icon, title, type, attrs) { super(icon, title) this.type = type this.attrs = attrs } select(pm) { let sel = pm.selection return sel.empty && pm.doc.path(sel.head.path).type.type == Node.types[this.type].type } apply(pm) { let sel = pm.selection if (sel.head.offset) { pm.apply(splitAt(pm.doc, sel.head)) sel = pm.selection } let desc = describeTarget(pm.doc, sel.head.shorten(), "right") pm.apply({name: "insert", pos: desc.pos, info: desc.info, type: this.type, attrs: this.attrs}) } } export class WrapItem extends Item { constructor(icon, title, type) { super(icon, title) this.type = type } apply(pm) { let sel = pm.selection pm.apply(wrappableRange(pm.doc, sel.from, sel.to, this.type)) } } export class InlineStyleItem extends Item { constructor(icon, title, style, dialog) { super(icon, title) this.style = typeof style == "string" ? {type: style} : style this.dialog = dialog } active(pm) { let sel = pm.selection return inline.rangeHasInlineStyle(pm.doc, sel.from, sel.to, this.style.type) } apply(pm) { let sel = pm.selection if (this.active(pm)) pm.apply({name: "removeStyle", pos: sel.from, end: sel.to, style: this.style.type}) else if (this.dialog) return this.dialog else pm.apply({name: "addStyle", pos: sel.from, end: sel.to, style: this.style}) } } export class ImageItem extends Item { constructor(icon, title) { super(icon, title || "Insert image") } apply(pm) { return new ImageDialog } } export class Dialog { constructor() { this.id = Math.floor(Math.random() * 0xffffff).toString(16) } focus(form) { let input = form.querySelector("input") if (input) input.focus() } buildForm(pm) { let form = this.form(pm) form.appendChild(elt("button", {type: "submit", style: "display: none"})) return form } } export class LinkDialog extends Dialog { form() { return elt("form", null, elt("div", null, elt("input", {name: "href", type: "text", placeholder: "Target URL", size: 40, autocomplete: "off"})), elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title", size: 40, autocomplete: "off"}))) } apply(form, pm) { let elts = form.elements if (!elts.href.value) return let sel = pm.selection pm.apply({name: "addStyle", pos: sel.from, end: sel.to, style: style.link(elts.href.value, elts.title.value)}) } } export class ImageDialog extends Dialog { form(pm) { let alt = pm.selectedText return elt("form", null, elt("div", null, elt("input", {name: "src", type: "text", placeholder: "Image URL", size: 40, autocomplete: "off"})), elt("div", null, elt("input", {name: "alt", type: "text", value: alt, autocomplete: "off", placeholder: "Description / alternative text", size: 40})), elt("div", null, elt("input", {name: "title", type: "text", placeholder: "Title", size: 40, autcomplete: "off"}))) } apply(form, pm) { let elts = form.elements if (!elts.src.value) return let sel = pm.selection pm.apply({name: "replace", pos: sel.from, end: sel.to}) let attrs = {src: elts.src.value, alt: elts.alt.value, title: elts.title.value} pm.apply(insertInline(sel.from, {type: "image", attrs: attrs})) } }
JavaScript
0.000001
@@ -100,36 +100,18 @@ nge, - describeTarget, insert -Inlin +Nod e%7D f @@ -1946,33 +1946,27 @@ -let desc = describeTarget +pm.apply(insertNode (pm. @@ -1994,79 +1994,9 @@ (), -%22right%22)%0A pm.apply(%7Bname: %22insert%22, pos: desc.pos, info: desc.info, +%7B type @@ -2019,32 +2019,33 @@ rs: this.attrs%7D) +) %0A %7D%0A%7D%0A%0Aexport c @@ -5063,15 +5063,21 @@ sert -Inline( +Node(pm.doc, sel.
fc1f316d212315b8e4feeff8bc7bbe79354b0939
Fix gr-reply-dialog-it_test
polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-change-reply-js-api.js
polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-change-reply-js-api.js
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function(window) { 'use strict'; /** * @deprecated */ function GrChangeReplyInterfaceOld(el) { this._el = el; } GrChangeReplyInterfaceOld.prototype.getLabelValue = function(label) { return this._el.getLabelValue(label); }; GrChangeReplyInterfaceOld.prototype.setLabelValue = function(label, value) { this._el.setLabelValue(label, value); }; GrChangeReplyInterfaceOld.prototype.send = function(opt_includeComments) { return this._el.send(opt_includeComments); }; function GrChangeReplyInterface(plugin, el) { GrChangeReplyInterfaceOld.call(this, el); this.plugin = plugin; this._hookName = plugin.getPluginName() + '-autogenerated-' + String(Math.random()).split('.')[1]; } GrChangeReplyInterface.prototype._hookName = ''; GrChangeReplyInterface.prototype._hookClass = null; GrChangeReplyInterface.prototype._hookPromise = null; GrChangeReplyInterface.prototype = Object.create(GrChangeReplyInterfaceOld.prototype); GrChangeReplyInterface.prototype.constructor = GrChangeReplyInterface; GrChangeReplyInterface.prototype.getDomHook = function() { if (!this._hookPromise) { this._hookPromise = new Promise((resolve, reject) => { this._hookClass = Polymer({ is: this._hookName, properties: { plugin: Object, content: Object, }, attached() { resolve(this); }, }); this.plugin.registerCustomComponent('reply-text', this._hookName); }); } return this._hookPromise; }; GrChangeReplyInterface.prototype.addReplyTextChangedCallback = function(handler) { this.getDomHook().then(el => { if (!el.content) { return; } el.content.addEventListener('value-changed', e => { handler(e.detail.value); }); }); }; window.GrChangeReplyInterface = GrChangeReplyInterface; })(window);
JavaScript
0.000055
@@ -1252,16 +1252,17 @@ kName = +( plugin.g @@ -1275,16 +1275,27 @@ inName() + %7C%7C 'test') + '-aut
2d459001fd52181578ca2591751f84838b7aaa0b
Update TumblrShareCount.js
src/TumblrShareCount.js
src/TumblrShareCount.js
import jsonp from 'jsonp'; import objectToGetParams from './utils/objectToGetParams'; import shareCountFactory from './utils/shareCountFactory'; function getTumblrShareCount(shareUrl, callback) { const endpoint = 'http://api.tumblr.com/v2/share/stats'; return jsonp(endpoint + objectToGetParams({ url: shareUrl, }), (err, data) => { callback(data ? data.note_count : undefined); }); } export default shareCountFactory(getTumblrShareCount);
JavaScript
0.000001
@@ -215,16 +215,17 @@ = 'http +s ://api.t
eb8c7196b9e3975291ec15a6d3ba85f6c69795e7
convert jshint comment to eslint
lib/relations/HtmlRelation.js
lib/relations/HtmlRelation.js
var util = require('util'), extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'), Relation = require('./Relation'), query = require('../query'); function HtmlRelation(config) { Relation.call(this, config); } util.inherits(HtmlRelation, Relation); extendWithGettersAndSetters(HtmlRelation.prototype, { // This is very hacky because relations in Html fragments (and Htc assets) // need to be interpreted as relative to the "main" Html asset. // Also, relations found inside Html in Rss and Atom assets need to be interpreted as relative to the Rss/Atom asset. baseAssetQuery: query.or({type: 'Rss', isInline: false}, {type: 'Atom', isInline: false}, {type: 'Html', isInline: false, isFragment: false}), // Override in subclass for relations that don't support inlining, are attached to attributes, etc. inline: function () { Relation.prototype.inline.call(this); if (this.to.type === 'JavaScript') { /*jshint scripturl:true*/ this.href = 'javascript:' + this.to.text; /*jshint scripturl:false*/ } else { this.href = this.to.dataUrl; } this.from.markDirty(); return this; }, attachNodeBeforeOrAfter: function (position, adjacentRelation) { if (position !== 'before' && position !== 'after') { throw new Error('HtmlRelation._attachNode: The "position" parameter must be either "before" or "after"'); } var adjacentNode = (position === 'after' && adjacentRelation.endNode) || adjacentRelation.node, parentNode = adjacentNode.parentNode; if (!parentNode) { throw new Error('HtmlRelation.attachNodeBeforeOrAfter: Adjacent node has no parentNode.'); } if (position === 'after') { parentNode.insertBefore(this.node, adjacentNode.nextSibling); } else { parentNode.insertBefore(this.node, adjacentNode); } }, // Override in subclass for relations that aren't detached by removing this.node from the DOM. detach: function () { this.node.parentNode.removeChild(this.node); this.node = undefined; return Relation.prototype.detach.call(this); } }); module.exports = HtmlRelation;
JavaScript
0.999971
@@ -992,32 +992,48 @@ / -*jshint +/ eslint-disable-next-line no- script +- url -:true*/ %0A @@ -1087,47 +1087,8 @@ xt;%0A - /*jshint scripturl:false*/%0A
de4556aa74bc8b55cdb569bdc5c6e4bbf3502fe1
Add anchor to checks on popover checkFocus
lib/assets/javascripts/uniform/popover.js
lib/assets/javascripts/uniform/popover.js
import Component from './component'; import * as Helpers from './dom-helpers'; /* Requirements --- content: html|node anchor: node Options --- align: [left|right|center|#%|#px] [top|center|bottom|#%|#px] | default: 'center bottom' zIndex: # | default: unset offset: {left: 0, top: 0} */ export default class Popover extends Component { initialize (options) { options = options || {}; this.options = { zIndex: 2, container: document.body, align: 'center bottom', anchor: document.body, content: 'needs content', offset: {left: 0, top: 0} }; Object.assign(this.options, this.pick(options, Object.keys(this.options))); document.addEventListener('click', this.checkFocus.bind(this)); document.addEventListener('focusin', this.checkFocus.bind(this)); document.addEventListener('keyup', this.checkEscape.bind(this)); window.addEventListener('resize', this.resize.bind(this)); } remove () { if(this.el.parentNode) this.el.parentNode.removeChild(this.el); window.removeEventListener('resize', this.resize.bind(this)); document.addEventListener('click', this.checkFocus.bind(this)); document.removeEventListener('focusin', this.checkFocus.bind(this)); document.removeEventListener('keyup', this.checkEscape.bind(this)); } render () { this.el.style.position = 'absolute'; this.el.style.zIndex = this.options.zIndex; if(this.options.content instanceof Node) this.el.appendChild(this.options.content); else this.el.innerHTML = this.options.content; this.options.container.appendChild(this.el); this.resize(); this.trigger('shown'); return this; } resize () { this.setPosition(); var align = this.options.align.split(" "); var reposition = false; if (Helpers.offset(this.el).top + Helpers.outerHeight(this.el) > document.body.offsetHeight) { align[1] = "top"; reposition = true; } if (Helpers.offset(this.el).top < 0) { align[1] = "bottom"; reposition = true; } if (Helpers.offset(this.el).left < 0) { align[0] = "right"; reposition = true; } if (Helpers.offset(this.el).left + Helpers.outerWidth(this.el) > document.body.offsetWidth) { align[0] = "left"; reposition = true; } if(reposition) this.setPosition(align.join(" ")) } setPosition(align){ align = align || this.options.align; var [leftAlign, topAlign] = align.split(" "); leftAlign = leftAlign || "bottom"; var offset = Helpers.offset(this.options.anchor); var container = this.options.container; if(getComputedStyle(container)['position'] == "static") container = container.offsetParent; if(!container) container = document.body; var containerOffset = Helpers.offset(container); offset = { top: offset.top - containerOffset.top, left: offset.left - containerOffset.left } var position = {}; if(leftAlign == 'left'){ position.right = Helpers.outerWidth(container) - offset.left; } else if(leftAlign == 'center'){ position.left = offset.left + Helpers.outerWidth(this.options.anchor) / 2 - Helpers.outerWidth(this.el) / 2; } else if (leftAlign == 'right'){ position.left = offset.left + Helpers.outerWidth(this.options.anchor); } else if (leftAlign.includes("%")){ position.left = offset.left + Helpers.outerWidth(this.options.anchor) * parseInt(leftAlign) / 100; } else if (leftAlign.includes("px")){ position.left = offset.left + Helpers.outerWidth(this.options.anchor) + parseInt(leftAlign); } if(topAlign == 'top'){ position.top = offset.top - Helpers.outerHeight(this.el); } else if(topAlign == 'center'){ position.top = offset.top + Helpers.outerHeight(this.options.anchor) / 2 - Helpers.outerHeight(this.el) / 2; } else if (topAlign == 'bottom'){ position.top = offset.top + Helpers.outerHeight(this.options.anchor); } else if (topAlign.includes("%")){ position.top = offset.top + Helpers.outerHeight(this.options.anchor) * parseInt(topAlign) / 100; } else if (topAlign.includes("px")){ position.top = offset.top + Helpers.outerHeight(this.options.anchor) + parseInt(topAlign); } if(this.options.offset.left) position.left += parseInt(this.options.offset.left); if(this.options.offset.top) position.top += parseInt(this.options.offset.top); if(this.options.offset.left) position.right -= parseInt(this.options.offset.left); this.el.style.left = 'auto'; this.el.style.right = 'auto'; Object.keys(position).forEach(function(key){ this.el.style[key] = position[key] + "px"; }, this); } checkFocus (e) { if(e.defaultPrevented) return; if(this.isHidden()) return; if (e.target === this.el) return; if (this.el.contains(e.target)) return; this.hide(); } checkEscape (e) { if(e.which != 27) return; this.hide(); } isHidden(){ return getComputedStyle(this.el)['display'] == "none"; } hide () { if(this.isHidden()) return; this.el.style.display = 'none'; this.trigger('hidden'); } show () { if(!this.isHidden()) return; this.el.style.display = 'block'; this.trigger('shown'); } toggle(flag) { flag = flag || this.isHidden(); if(flag) this.show(); else this.hide(); } }
JavaScript
0
@@ -5349,16 +5349,17 @@ if + (e.defau @@ -5370,16 +5370,28 @@ evented) + return; @@ -5393,32 +5393,33 @@ turn;%0A if + (this.isHidden() @@ -5411,32 +5411,47 @@ this.isHidden()) + return;%0A @@ -5481,35 +5481,169 @@ el) -return;%0A if (this.el + return;%0A if (e.target == this.options.anchor) return;%0A if (this.el.contains(e.target)) return;%0A if (this.options.anchor .con
25223a3920603d5141bad84ca4d4cbc75109a30f
Fix infinite recursion in geocoder (fixes #1580)
js/id/ui/geocoder.js
js/id/ui/geocoder.js
iD.ui.Geocoder = function(context) { var key = 'f'; function resultExtent(bounds) { return new iD.geo.Extent( [parseFloat(bounds[3]), parseFloat(bounds[0])], [parseFloat(bounds[2]), parseFloat(bounds[1])]); } function truncate(d) { if (d.display_name.length > 80) { return d.display_name.substr(0, 80) + '…'; } else { return d.display_name; } } function geocoder(selection) { var shown = false; function keydown() { if (d3.event.keyCode !== 13) return; d3.event.preventDefault(); var searchVal = this.value; inputNode.classed('loading', true); d3.json('http://nominatim.openstreetmap.org/search/' + encodeURIComponent(searchVal) + '?limit=10&format=json', function(err, resp) { inputNode.classed('loading', false); if (err) return hide(); if (!resp.length) { resultsList.html('') .call(iD.ui.Toggle(true)) .append('span') .attr('class', 'not-found') .text(t('geocoder.no_results', { name: searchVal })); } else if (resp.length > 1) { var spans = resultsList.html('').selectAll('span') .data(resp, function(d) { return d.place_id; }); spans.enter() .append('span') .text(function(d) { return d.type.charAt(0).toUpperCase() + d.type.slice(1) + ': '; }) .append('a') .attr('tabindex', 1) .text(truncate) .on('click', clickResult) .on('keydown', function(d) { // support tabbing to and accepting this // entry if (d3.event.keyCode == 13) clickResult(d); }); spans.exit().remove(); resultsList.call(iD.ui.Toggle(true)); } else { hide(); applyBounds(resultExtent(resp[0].boundingbox)); selectId(resp[0].osm_type, resp[0].osm_id); } }); } function clickResult(d) { selectId(d.osm_type, d.osm_id); applyBounds(resultExtent(d.boundingbox)); } function applyBounds(extent) { var map = context.map(); map.extent(extent); if (map.zoom() > 19) map.zoom(19); } function selectId(type, id) { id = type[0] + id; if (context.hasEntity(id)) { context.enter(iD.modes.Select(context, [id])); } else { context.map().on('drawn.geocoder', function() { if (!context.hasEntity(id)) return; context.enter(iD.modes.Select(context, [id])); }); context.on('enter.geocoder', function() { if (context.mode().id !== 'browse') { context.on('enter.geocoder', null) .map().on('drawn.geocoder', null); } }); } } var tooltip = bootstrap.tooltip() .placement('right') .html(true) .title(iD.ui.tooltipHtml(t('geocoder.title'), key)); var gcForm = selection.append('form'); var inputNode = gcForm.attr('class', 'fillL map-overlay content hide') .append('input') .attr({ type: 'text', placeholder: t('geocoder.placeholder') }) .attr('tabindex', 1) .on('keydown', keydown); var resultsList = selection.append('div') .attr('class', 'fillL map-overlay hide'); var keybinding = d3.keybinding('geocoder'); function hide() { setVisible(false); } function toggle() { if (d3.event) d3.event.preventDefault(); tooltip.hide(button); setVisible(!button.classed('active')); } function setVisible(show) { if (show !== shown) { button.classed('active', show); shown = show; if (!show && !resultsList.classed('hide')) { resultsList.call(iD.ui.Toggle(show)); // remove results so that they lose focus. if the user has // tabbed into the list, then they will have focus still, // even if they're hidden. resultsList.selectAll('span').remove(); } if (show) { selection.on('mousedown.geocoder-inside', function() { return d3.event.stopPropagation(); }); gcForm.style('display', 'block') .style('left', '-500px') .transition() .duration(200) .style('left', '30px'); inputNode.node().focus(); } else { selection.on('mousedown.geocoder-inside', null); gcForm.style('display', 'block') .style('left', '30px') .transition() .duration(200) .style('left', '-500px') .each('end', function() { d3.select(this).style('display', 'none'); }); inputNode.node().blur(); } } } var button = selection.append('button') .attr('tabindex', -1) .on('click', toggle) .call(tooltip); button.append('span') .attr('class', 'icon geocode light'); keybinding.on(key, toggle); d3.select(document) .call(keybinding); context.surface().on('mousedown.geocoder-outside', hide); context.container().on('mousedown.b.geocoder-outside', hide); } return geocoder; };
JavaScript
0
@@ -3249,125 +3249,41 @@ ext. -enter(iD.modes.Select(context, %5Bid%5D));%0A %7D);%0A%0A context.on('enter.geocoder', function() %7B +map().on('drawn.geocoder', null); %0A @@ -3299,28 +3299,24 @@ -if ( context. mode().i @@ -3311,177 +3311,46 @@ ext. -mode().id !== 'browse') %7B%0A context.on('enter.geocoder', null)%0A .map().on('drawn.geocoder', null);%0A %7D +enter(iD.modes.Select(context, %5Bid%5D)); %0A
40fd6bdeaa5014930373c28c7a2c50c00281f126
Fix av moderation n.filter is not a function.
modules/xmpp/AVModeration.js
modules/xmpp/AVModeration.js
import { getLogger } from 'jitsi-meet-logger'; import { $msg } from 'strophe.js'; import * as MediaType from '../../service/RTC/MediaType'; import XMPPEvents from '../../service/xmpp/XMPPEvents'; const logger = getLogger(__filename); /** * The AVModeration logic. */ export default class AVModeration { /** * Constructs AV moderation room. * * @param {ChatRoom} room the main room. */ constructor(room) { this._xmpp = room.xmpp; this._mainRoom = room; this._momderationEnabledByType = { [MediaType.AUDIO]: false, [MediaType.VIDEO]: false }; this._whitelistAudio = []; this._whitelistVideo = []; this._xmpp.addListener(XMPPEvents.AV_MODERATION_RECEIVED, this._onMessage.bind(this)); } /** * Whether AV moderation is supported on backend. * * @returns {boolean} whether AV moderation is supported on backend. */ isSupported() { return Boolean(this._xmpp.avModerationComponentAddress); } /** * Enables or disables AV Moderation by sending a msg with command to the component. */ enable(state, mediaType) { if (!this.isSupported() || !this._mainRoom.isModerator()) { logger.error(`Cannot enable:${state} AV moderation supported:${this.isSupported()}, moderator:${this._mainRoom.isModerator()}`); return; } if (state === this._momderationEnabledByType[mediaType]) { logger.warn(`Moderation already in state:${state} for mediaType:${mediaType}`); return; } // send the enable/disable message const msg = $msg({ to: this._xmpp.avModerationComponentAddress }); msg.c('av_moderation', { enable: state, mediaType }).up(); this._xmpp.connection.send(msg); } /** * Approves that a participant can unmute by sending a msg with its jid to the component. */ approve(mediaType, jid) { if (!this.isSupported() || !this._mainRoom.isModerator()) { logger.error(`Cannot approve in AV moderation supported:${this.isSupported()}, moderator:${this._mainRoom.isModerator()}`); return; } // send a message to whitelist the jid and approve it to unmute const msg = $msg({ to: this._xmpp.avModerationComponentAddress }); msg.c('av_moderation', { mediaType, jidToWhitelist: jid }).up(); this._xmpp.connection.send(msg); } /** * Receives av_moderation parsed messages as json. * @param obj the parsed json content of the message to process. * @private */ _onMessage(obj) { const newWhitelists = obj.whitelists; if (newWhitelists) { const fireEventApprovedJids = (mediaType, oldList, newList) => { newList.filter(x => !oldList.includes(x)) .forEach(jid => this._xmpp.eventEmitter .emit(XMPPEvents.AV_MODERATION_PARTICIPANT_APPROVED, mediaType, jid)); }; if (newWhitelists[MediaType.AUDIO]) { fireEventApprovedJids(MediaType.AUDIO, this._whitelistAudio, newWhitelists[MediaType.AUDIO]); } if (newWhitelists[MediaType.VIDEO]) { fireEventApprovedJids(MediaType.VIDEO, this._whitelistVideo, newWhitelists[MediaType.VIDEO]); } } else if (obj.enabled !== undefined && this._momderationEnabledByType[obj.mediaType] !== obj.enabled) { this._momderationEnabledByType[obj.mediaType] = obj.enabled; this._xmpp.eventEmitter.emit(XMPPEvents.AV_MODERATION_CHANGED, obj.enabled, obj.mediaType, obj.actor); } else if (obj.approved) { this._xmpp.eventEmitter.emit(XMPPEvents.AV_MODERATION_APPROVED, obj.mediaType); } } }
JavaScript
0.000002
@@ -3148,32 +3148,46 @@ %0A if +(Array.isArray (newWhitelists%5BM @@ -3202,16 +3202,17 @@ .AUDIO%5D) +) %7B%0A @@ -3338,32 +3338,46 @@ %0A if +(Array.isArray (newWhitelists%5BM @@ -3392,16 +3392,17 @@ .VIDEO%5D) +) %7B%0A
81b94a1958f462a0dc320f79f3208956668a9c1e
improve error msg
test/streamsource.js
test/streamsource.js
/** For testing asynchronous json downloading, here we have a tiny http server. * * For every request (regardless f path) it responds with the json [0,1,2,3,4,5,6,7,8,9] * but writing out each number one at a time. * * You can start this server up and visit it in a browser to see the numbers stream in. */ require('color'); function startServer( port, grunt ) { "use strict"; var JSON_MIME_TYPE = "application/octet-stream"; var verboseLog = grunt? grunt.verbose.ok : console.log, errorLog = grunt? grunt.log.error : console.error; function echoBackBody(req, res) { req.pipe(res); } function echoBackHeadersAsBodyJson(req, res) { res.end(JSON.stringify(req.headers)); } function echoBackHeadersAsHeaders(req, res) { for( var name in req.headers ) { res.set(name, req.headers[name]); } res.end('{"see":"headers", "for":"content"}'); } function replyWithTenSlowNumbers(_req, res) { sendJsonHeaders(res); var NUMBER_INTERVAL = 250; var MAX_NUMBER = 9; verboseLog( 'slow number server: will write numbers 0 ..' + String(MAX_NUMBER).blue + ' out as a json array at a rate of one per', String(NUMBER_INTERVAL).blue + 'ms' ); res.write('[\n'); var curNumber = 0; var inervalId = setInterval(function () { res.write(String(curNumber)); if (curNumber == MAX_NUMBER) { res.end(']'); clearInterval(inervalId); verboseLog('slow number server: finished writing out'); } else { res.write(',\n'); curNumber++; } }, NUMBER_INTERVAL); } function replyWithInvalidJson(req, res) { res.end('{{'); } function serve404Json(req, res) { // our little REST endpoint with errors: res.status(404).send(JSON.stringify( { "found":"false", "errorMessage":"was not found" } )); } function replyWithStaticJson(req, res) { sendJsonHeaders(res); if( !req.url ) { throw new Error('no url given'); } var filename = 'test/json/' + req.params.name + '.json'; verboseLog('will respond with contents of file ' + filename); require('fs').createReadStream(filename) .on('error', function(err){ errorLog('could not read static file ' + filename + ' ' + err); }).pipe(res); } function sendJsonHeaders(res) { res.setHeader("Content-Type", JSON_MIME_TYPE); res.writeHead(200); } function twoHundredItems(_req, res) { var TIME_BETWEEN_RECORDS = 40; // 80 records but only every other one has a URL: var NUMBER_OF_RECORDS = 200; res.write('{"data": ['); var i = 0; var inervalId = setInterval(function () { res.write(JSON.stringify({ "id": i, "url": "http://localhost:4444/item/" + i, // let's get some entropy in here for gzip: "number1": Math.random(), "number2": Math.random(), "number3": Math.random(), "number4": Math.random() })); if (i == NUMBER_OF_RECORDS) { res.end(']}'); clearInterval(inervalId); console.log('db server: finished writing to stream'); } else { res.write(','); } i++; }, TIME_BETWEEN_RECORDS); } function replyWithTenSlowNumbersGzipped(req, serverResponse){ // request out non-gzipped stream and re-serve gzipped require('http').get({ host: 'localhost', path: '/twoHundredItems', port: port }) .on('response', function(clientResponse){ var zlib = require('zlib'); //res.writeHead(200, { 'content-encoding': 'gzip' }); serverResponse.setHeader("content-type", JSON_MIME_TYPE); serverResponse.setHeader("content-encoding", 'gzip'); serverResponse.writeHead(200); clientResponse.pipe(zlib.createGzip({ flush: zlib.Z_SYNC_FLUSH })).pipe(serverResponse); }); } function makeApp() { var express = require('express'), app = express(); app.get( '/echoBackBody', function(req, res){ res.end("POST here, don't GET")}); app.post( '/echoBackBody', echoBackBody); app.put( '/echoBackBody', echoBackBody); app.patch( '/echoBackBody', echoBackBody); app.get( '/echoBackHeadersAsBodyJson', echoBackHeadersAsBodyJson); app.get( '/echoBackHeadersAsHeaders', echoBackHeadersAsHeaders); app.get( '/static/json/:name.json', replyWithStaticJson); app.get( '/tenSlowNumbers', replyWithTenSlowNumbers); app.get( '/twoHundredItems', twoHundredItems); app.get( '/gzippedTwoHundredItems', replyWithTenSlowNumbersGzipped); app.get( '/invalidJson', replyWithInvalidJson); app.get( '/404json', serve404Json); return app; } makeApp().listen(port); verboseLog('streaming source server started on port'.green, String(port).blue); } function exportApi(){ var server; module.exports.start = function(port, grunt){ server = startServer(port, grunt); }; module.exports.stop = function(){ server.close(); }; } exportApi();
JavaScript
0.000019
@@ -4587,28 +4587,26 @@ %7D);%0A %7D - %0A + %0A funct @@ -4770,16 +4770,26 @@ nd(%22POST +/PUT/PATCH here, d
bc2bcf0c9e5aca1eb9ef7eac092b65a9ef813483
save point
src/comps/Application.js
src/comps/Application.js
import React, { Component } from 'react' import LandingPage from './LandingPage' import NavigationBar from './NavigationBar' export default class Application extends Component { render() { return( <main id="UI"> <NavigationBar /> <LandingPage /> </main> ) } }
JavaScript
0.000001
@@ -18,16 +18,32 @@ omponent +, lazy, Suspense %7D from @@ -61,86 +61,102 @@ ort -LandingPage from './LandingPage'%0Aimport NavigationBar from './NavigationBar' +NavigationBar from './NavigationBar'%0A%0Aconst LandingPage = lazy(() =%3E import('./LandingPage')); %0A%0Aex @@ -291,21 +291,106 @@ %3C -LandingPage / +Suspense fallback=%7B %3Cdiv%3E%3Ch3%3ELoading...%3C/h3%3E%3C/div%3E %7D%3E%0A %3CLandingPage /%3E%0A %3C/Suspense %3E%0A
20285dc7689ad87c1b9e48bae45e15fac04c78e8
move curser out of intrument nav before ending section selection
test/lib/instrument.js
test/lib/instrument.js
"use strict"; // test deps var should = require('should'); var _ = require('lodash'); var getStrict = function(obj, key) { if (obj[key] === undefined) { throw new Error('Expected option `' + key + '` to be set'); } return obj[key]; }; var getFormField = function(key) { var exceptions = { saLabel: 'salabel' }; var actions = { hideSaPrevious: 'selectByValue', saHideSkippedQuestions: 'selectByValue', lock: 'selectByValue', _default: 'setValue' } return { name: exceptions[key] || _.snakeCase(key), action: actions[key] || actions._default }; }; // exports module.exports = function(client, config) { var me = {instrumentId:undefined}; me.filterList = function(query, done) { var selector = '#instrument_grid_filter input[type=search]'; return client.setValue(selector, query, done); }; me.setInstrumentIdFromPage = function(done) { var selector = '[name=instrument_id]'; return client.getValue(selector, function(err, val) { if (err) { throw err; } me.instrumentId = val; done(); }); }; me.toggleLockFromList = function(instrumentId, done) { var selector = '[data-instrument_id="' + instrumentId + '"] input.locked-unlocked'; var lockState, expectedState; var expectedStateMap = { 'lock': 'unlock', 'unlock': 'lock' }; var setLockState = function(err, val) { if (!err) { lockState = val; expectedState = expectedStateMap[val]; } else { throw err; } }; return client.getValue(selector, setLockState) .click(selector) .waitForPaginationComplete() .getValue(selector, function(err, val) { if(err) { throw err; } val.should.be.eql(expectedState); done(); }); }; me.gotoEditFromList = function(instrumentId, done) { var selector = '[data-instrument_id="' + instrumentId + '"] a.pvedit'; return client.click(selector) .waitForPaginationComplete(done); }; me.gotoSection = function(sectionLabel, done) { var navSelector = '#asmtPageNav'; var xPathNavSelector = '//*[@id="asmtPageNav"]'; var xPathSelector = xPathNavSelector + '//li[normalize-space(.) = "' + sectionLabel + '"]'; return client.moveToObject(xPathNavSelector, 80, 10) .click(xPathSelector, done); }; me.create = function(options, done) { return client .setValue('input[name=label]', getStrict(options, 'label')) .setValue('input[name=salabel]', getStrict(options, 'saLabel')) .setValue('input[name=description]', getStrict(options, 'description')) .setValue('input[name=cr_notice]', getStrict(options, 'crNotice')) .setValue('input[name=version]', getStrict(options, 'version')) .setValue('input[name=max_per_segment]', getStrict(options, 'maxPerSegment')) .setValue('input[name=skip_question_text]', getStrict(options, 'skipQuestionText')) .click('button[id=add_instrument]') .waitForPaginationComplete(done); }; me.edit = function(options, done) { _.forEach(options, function(option, key) { var field = getFormField(key); client[field.action]('[name=' + field.name + ']', option); }); return client .click('button[id=update_instrument]') .waitForPaginationComplete(done); }; me.fromHtml = function(callback) { var options = {}; var callbackWrapper = function() { callback(null, options); }; client .getValue('input[name=label]', function(err, val) { options.label = val; }) .getValue('input[name=salabel]', function(err, val) { options.saLabel = val; }) .getValue('input[name=description]', function(err, val) { options.description = val; }) .getValue('input[name=cr_notice]', function(err, val) { options.crNotice = val; }) .getValue('input[name=version]', function(err, val) { options.version = val; }) .getValue('input[name=max_per_segment]', function(err, val) { options.maxPerSegment = val; }) .getValue('input[name=skip_question_text]', function(err, val) { options.skipQuestionText = val; }) .getValue('select[name=hide_sa_previous]', function(err, val) { options.hideSaPrevious = val; }) .getValue('select[name=sa_hide_skipped_questions]', function(err, val) { options.saHideSkippedQuestions = val; }) .getValue('select[name=lock]', function(err, val) { if (err) { // the lock select element is not printed if the instrument is locked options.lock = '1'; } else { options.lock = val; } }) .call(callbackWrapper); }; return me; };
JavaScript
0
@@ -2660,16 +2660,67 @@ Selector +)%0A .moveToObject('#page-container', 0, 0 , done);
8184d21b38ab85c229b02d0bd39699a4095a5128
Use Kodi
theater.js
theater.js
(function () { const webServer = require("./webserver.js"); const KodiController = require("./player/kodi.js"); const VLCController = require("./player/vlc.js"); const OMXController = require("./player/omxplayer.js"); const serviceManager = require("./services/service-manager.js"); const discovery = require("./discovery.js"); function main() { discovery.start(); var player = new OMXController(); serviceManager.setPlayer(player); webServer.setPlayer(player); webServer.start(); player.showNotification("Theater", "Theater application started and is ready now. Enjoy your P2P channels!"); } /* const diff = require("diff"); var imdb = "tt0451279"; var movieFile = "Wonder.Woman.2017.3D.HSBS.BluRay.x264-[YTS.AG].mp4"; var subs = []; const subSearch = require("yifysubtitles"); subSearch(imdb, { path: "/tmp", langs: ["en"], format: "srt" }).then(function (subtitles){ if (subtitles && subtitles.length > 0) { const ignoredRE = /[^a-z0-9]+/gi; const extRE = /\.[a-z0-9]+$/gi; var a = movieFile.replace(extRE, "").replace(ignoredRE, " ").toUpperCase(); for (var sub of subtitles) { var b = sub.fileName.replace(extRE, "").replace(ignoredRE, " ").toUpperCase(); var d = diff.diffWords(a, b); var delta = 0; for (var e of d) if (e.added || e.removed) delta += e.count; subs.push({ fileName: sub.fileName, diff: delta }); } subs.sort(function (a, b) { return a.diff - b.diff; }) for (var sub of subs) { console.log("* " + sub.fileName + ": " + sub.diff); } } }).catch(function (e) { console.log("Failed to search for subtitles."); console.error(e); }); */ module.exports = main; })();
JavaScript
0.000001
@@ -422,19 +422,20 @@ r = new -OMX +Kodi Controll @@ -437,16 +437,21 @@ troller( +13000 );%0A%0A
01736c2dea51ec914a6d1b43b8808ca2db4fa91a
make it clear if there was an http error.
lib/cast-client/commands/services/list.js
lib/cast-client/commands/services/list.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick licenses this file to You 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 sys = require('sys'); var sprintf = require('extern/sprintf').sprintf; var http = require('util/http'); var terminal = require('util/terminal'); var config = { 'short_description': 'Print a list of available services', 'long_description': 'Print a list of available services.', 'required_arguments' : [], 'optional_arguments': [], 'switches': [] }; var format_status = function(value) { if (!value) { return 'service is disabled'; } return sprintf('pid: %s, state: %s', value.pid, value.state); }; function handle_command(args) { http.get_response(undefined, '/services/', 'GET', true, function(error, response) { if (error || response.code === 500) { error = error || response; return sys.puts(sprintf('Error: %s', error.message)); } var services = response; sys.puts('Available services: \n'); terminal.print_table([{'title': 'Name', 'value_property': 'name', 'padding_right': 30}, {'title': 'Enabled', 'value_property': 'enabled', 'padding_right': 20}, {'title': 'Status', 'value_property': 'status', 'format_function': format_status}], services, 'No services available'); }); } exports.config = config; exports.handle_command = handle_command;
JavaScript
0
@@ -1453,118 +1453,222 @@ rror - %7C%7C response.code === 500) %7B%0A error = error %7C%7C response;%0A return sys.puts(sprintf('Error: %25s', error +) %7B%0A error = error;%0A return sys.puts(sprintf('Error: %25s', error.message));%0A %7D%0A if (response.code !== 200) %7B%0A return sys.puts(sprintf('HTTP Error, %25d returned, body: %25s', response.code, response .mes
43ba8b0c6c88181041c3f86f05974e32d48daef6
set rdlabs.beeldengeluid.nl in search page url
web/woordnl-linking-page/js/woordnl_search.js
web/woordnl-linking-page/js/woordnl_search.js
function searchIN () { var jsonStr = null; var mapping = woordnlMapping; scores = []; files= []; var str = document.getElementById('q').value; var gg = document.getElementById('results-toggle').checked; console.log("toggle:"+gg); if (gg) { console.log("now true"); } else { console.log('now false'); } $.getJSON("http://rdlabs.beeldengeluid.nl/woordnl-rc/get_search_results?term="+str, function(data) { jsonStr=data; count=jsonStr.ThemData.hits.total; //if (count>100) count=100; //count="<h1>"+count+" resultaaten</h1>" //console.log("count!"); console.log(data); //$("#resultq").html(count); $("#Themresults").html(""); var htmlcount=0; console.log("JSON RESULTS:"+jsonStr.ThemData.hits.hits.length); for (hit in jsonStr.ThemData.hits.hits) //for (i = 0; i < jsonStr.ThemData.hits.hits.length; i++) { //console.log("did it"); file=jsonStr.ThemData.hits.hits[hit]._source.asr_file; console.log(file); var asrs=file.split("\."); console.log(asrs[1]); var date,subtitle,broadcast,duration,title=""; file=asrs[1]; if (mapping[file]) { title=mapping[file].titles[0].value; if (mapping[file].titles[1]) subtitle=mapping[file].titles[1].value; urn = mapping[file].urn; publish=mapping[file].publishStart; if (publish) { date=publish.split("T"); var month=date[0].split("\-"); var monthNames = [ "jan", "feb", "maa", "apr", "mei", "jun", "jul", "aug", "sep", "oct", "nov", "dec" ]; var monthN=monthNames[month[1]-1]; date=month[2]+" "+monthN+" "+month[0]; } if (mapping[file].broadcasters) broadcast=mapping[file].broadcasters; if (mapping[file].duration) duration=mapping[file].duration; //console.log(mapping[file].tags); //<span class="highlight"> Test <em class="hlt1">Highlight</em></span> html=' \ <a href="http://localhost:4000/woordnl-rc/player.html?urn='+urn+'">\ <div class="result program" data-urn="'+urn+'"> \ \ <div class="visualisation">\ </div><span class="title">'+title+'\ <span class="publishDate">'+date+'</span>\ </span><span class="subTitle">'+subtitle+'</span> <div class="highlights">\ </div>\ <div class="meta"><span class="duration">'+duration+'</span><span class="genres">Interview</span>\ <span class="broadcasters"> \ <span class="broadcaster">'+broadcast+'</span></span> </div></div></a> '; if (gg) { //console.log("gg is :"+gg); if ($.inArray(asrs[1], files)==-1) { files.push(asrs[1]); $("#Themresults").append(html); count="<h1>"+files.length+" resultaaten</h1>" $("#resultq").html(count); htmlcount+=1; } } else { //console.log("gg is :"+gg); $("#Themresults").append(html); htmlcount+=1; } } } console.log("Got to END"); console.log("unique results posted: "+htmlcount); htmlcount="<h1>"+htmlcount+" resultaaten</h1>" $("#resultq").html(htmlcount); }); }
JavaScript
0
@@ -1979,22 +1979,31 @@ p:// -localhost:4000 +rdlabs.beeldengeluid.nl /woo
0d2e86308935f30f9cceb508eba3cb8966cda4e2
Support the new templates.js
public/js/lib/utils.js
public/js/lib/utils.js
define(function() { var sb, shoutTpl, textTpl; var Utils = { init: function(callback) { window.templates.preload_template('shoutbox/shout', function() { window.templates.preload_template('shoutbox/shout/text', function() { shoutTpl = window.templates['shoutbox/shout']; textTpl = window.templates['shoutbox/shout/text']; callback(); }); }); }, parseShout: function(shout, onlyText) { shout.user.hasRights = shout.fromuid === app.uid || app.isAdmin === true; if (onlyText) { return textTpl.parse(shout); } else { return shoutTpl.parse(shout); } }, prepareShoutbox: function() { Utils.getSettings(function() { var shoutBox = sb.base.getShoutPanel(); //if (shoutBox.length > 0 && Config.settings.hide !== 1) { // shoutBox.parents('.shoutbox-row').removeClass('hide'); if (shoutBox.length > 0) { Utils.parseSettings(shoutBox); Utils.registerHandlers(shoutBox); sb.base.getShouts(shoutBox); } }); }, getSettings: function(callback) { socket.emit(sb.config.sockets.getSettings, function(err, settings) { sb.config.settings = settings.settings; sb.config.vars.shoutLimit = settings.shoutLimit; if(callback) { callback(); } }); }, parseSettings: function(shoutBox) { var settings = sb.config.settings; if (!settings) { return; } for(var key in settings) { if (settings.hasOwnProperty(key)) { var value = settings[key]; var el = shoutBox.find('#shoutbox-settings-' + key + ' span'); if (value === 1) { el.removeClass('fa-times').addClass('fa-check'); } else { el.removeClass('fa-check').addClass('fa-times'); } } } }, registerHandlers: function(shoutBox) { Utils.addActionHandlers(shoutBox); Utils.addSocketHandlers(); }, addActionHandlers: function(shoutBox) { var actions = sb.actions; for (var a in actions) { if (actions.hasOwnProperty(a)) { actions[a].register(shoutBox); } } }, addSocketHandlers: function() { var sockets = sb.sockets; for (var s in sockets) { if (sockets.hasOwnProperty(s)) { sockets[s].register(); } } }, checkAnon: function(callback) { if (app.uid === 0) { return callback(true); } return callback(false); }, showEmptyMessage: function(shoutBox) { shoutBox.find('#shoutbox-content').html(Config.messages.empty); } }; return function(Shoutbox) { Shoutbox.utils = Utils; sb = Shoutbox; }; });
JavaScript
0
@@ -96,35 +96,29 @@ %09window. -templates.pre +ajaxify. load -_t +T emplate( @@ -136,32 +136,37 @@ hout', function( +shout ) %7B%0A%09%09%09%09window.t @@ -168,27 +168,21 @@ dow. -templates.pre +ajaxify. load -_t +T empl @@ -209,32 +209,36 @@ text', function( +text ) %7B%0A%09%09%09%09%09shoutTp @@ -245,98 +245,34 @@ l = -window.templates%5B'shoutbox/shout'%5D;%0A%09%09%09%09%09textTpl = window.templates%5B'shoutbox/shout/ +shout;%0A%09%09%09%09%09textTpl = text -'%5D ;%0A%09%09 @@ -344,24 +344,68 @@ onlyText) %7B%0A +%09%09%09var tpl = onlyText ? textTpl : shoutTpl;%0A %09%09%09shout.use @@ -476,103 +476,51 @@ %0A%09%09%09 -if (onlyText) %7B%0A%09%09%09%09return textTpl.parse(shout);%0A%09%09%09%7D else %7B%0A%09%09%09%09return shoutTpl +return window.templates .parse( +tpl, shout);%0A %09%09%09%7D @@ -515,21 +515,16 @@ shout);%0A -%09%09%09%7D%0A %09%09%7D,%0A%09%09p
e30f90a1acff6c66722018c7e68d60d27cbcb08f
Remove Reset Account
public/scripts/controllers/profileController.js
public/scripts/controllers/profileController.js
(function() { 'use strict'; angular .module('tweetstockr') .controller('profileController', profileController); function profileController ($rootScope, $scope, userService, Notification) { $rootScope.updateCurrentUser(); $scope.showResetButton = false; $scope.toggleResetButton = function() { $scope.showResetButton = !$scope.showResetButton; }; $scope.resetAccount = function () { userService.resetAccount( function successCallback(response) { if (response.message) { Notification.success(response.message); } }, function errorCallback(response) { if (response.message) { Notification.error(response.message); } } ); }; $scope.joysticketLogin = function() { userService.joysticketLogin( function successCallback(response){ if(response.url){ window.location.href = response.url; } }, function errorCallback(response){ console.log(response); } ); }; $scope.joysticketLogout = function() { userService.joysticketLogout( function successCallback(response){ if(response.url){ window.location.href = response.url; } }, function errorCallback(response){ console.log(response); } ); }; $scope.logout = function () { userService.logout( function successCallback(response) { }, function errorCallback(response) { if (response.message) { Notification.error(response.message); } } ); }; } })();
JavaScript
0.000001
@@ -384,400 +384,8 @@ %7D;%0A%0A - $scope.resetAccount = function () %7B%0A userService.resetAccount(%0A function successCallback(response) %7B%0A if (response.message) %7B%0A Notification.success(response.message);%0A %7D%0A %7D,%0A function errorCallback(response) %7B%0A if (response.message) %7B%0A Notification.error(response.message);%0A %7D%0A %7D%0A );%0A %7D;%0A%0A @@ -1058,25 +1058,24 @@ nction () %7B%0A -%0A userSe @@ -1303,25 +1303,23 @@ );%0A -%0A %7D;%0A -%0A %7D%0A%7D)()
37fac1cf014cc6581197620e1d55c1379e480313
fix accordion items wrongly registering as childs on the (wrong) parent, e.g. on tab component.
addon/components/base/bs-accordion/item.js
addon/components/base/bs-accordion/item.js
import { oneWay, not } from '@ember/object/computed'; import Component from '@ember/component'; import { computed } from '@ember/object'; import TypeClass from 'ember-bootstrap/mixins/type-class'; import ComponentChild from 'ember-bootstrap/mixins/component-child'; import layout from 'ember-bootstrap/templates/components/bs-accordion/item'; /** A collapsible/expandable item within an accordion See [Components.Accordion](Components.Accordion.html) for examples. @class AccordionItem @namespace Components @extends Ember.Component @uses Mixins.ComponentChild @uses Mixins.TypeClass @public */ export default Component.extend(ComponentChild, TypeClass, { layout, /** * The title of the accordion item, displayed as a .panel-title element * * @property title * @type string * @public */ title: null, /** * The value of the accordion item, which is used as the value of the `selected` property of the parent [Components.Accordion](Components.Accordion.html) component * * @property value * @public */ value: oneWay('elementId'), /** * @property selected * @private */ selected: null, /** * @property collapsed * @type boolean * @readonly * @private */ collapsed: computed('value', 'selected', function() { return this.get('value') !== this.get('selected'); }).readOnly(), /** * @property active * @type boolean * @readonly * @private */ active: not('collapsed'), /** * Reference to the parent `Components.Accordion` class. * * @property accordion * @private */ accordion: null, /** * @event onClick * @public */ onClick() {} });
JavaScript
0
@@ -194,77 +194,8 @@ s';%0A -import ComponentChild from 'ember-bootstrap/mixins/component-child';%0A impo @@ -469,37 +469,8 @@ ent%0A - @uses Mixins.ComponentChild%0A @us @@ -538,24 +538,8 @@ end( -ComponentChild, Type
53fc0e27b3da835d05932cc4f49aa99f8ad31301
Reset compose controller on exit
app/new-stack/route.js
app/new-stack/route.js
import Ember from 'ember'; import { ajaxPromise } from 'ember-api-store/utils/ajax-promise'; const DOCKER = 'docker-compose.yml'; const RANCHER = 'rancher-compose.yml'; function encodeRepo(str) { return str.split('/') .map((substr) => { return encodeURIComponent(substr); }) .join('/'); } function githubUrl(repo,branch,file) { return 'https://raw.githubusercontent.com/' + encodeRepo(repo) + '/' + encodeURIComponent(branch||'master') + '/' + encodeURIComponent(file); } export default Ember.Route.extend({ model: function(params/*, transition*/) { var stack = this.get('store').createRecord({ type: 'stack', }); var dockerUrl = null; var rancherUrl = null; if ( params.githubRepo ) { // Load compose files from GitHub dockerUrl = githubUrl(params.githubRepo, params.githubBranch, DOCKER); rancherUrl = githubUrl(params.githubRepo, params.githubBranch, RANCHER); } else if ( params.composeFiles ) { // Load compose files from arbitrary base URL var base = params.composeFiles.replace(/\/+$/,''); dockerUrl = base + '/' + DOCKER; rancherUrl = base + '/' + RANCHER; } if ( dockerUrl && rancherUrl ) { return Ember.RSVP.hashSettled({ docker: ajaxPromise({url: dockerUrl, dataType: 'text'}, true), rancher: ajaxPromise({url: rancherUrl, dataType: 'text'}, true), }).then((hash) => { if ( hash.docker.state === 'fulfilled' ) { stack.set('dockerCompose', hash.docker.value); } if ( hash.rancher.state === 'fulfilled' ) { stack.set('rancherCompose', hash.rancher.value); } return stack; }); } else { return stack; } }, setupController: function(controller, model) { controller.set('originalModel',null); controller.set('model', model); }, resetController: function (controller, isExiting/*, transition*/) { if (isExiting) { controller.setProperties({ githubRepo: null, githubBranch: null, composeFiles: null, system: false, }); } }, actions: { cancel: function() { this.goToPrevious(); }, } });
JavaScript
0.000001
@@ -2109,32 +2109,55 @@ oseFiles: null,%0A + compose: null,%0A system:
da806a42cda62c69f67f6ad766894d380615707a
replace quote style for regexp
lib/main.js
lib/main.js
/*! EmberUI (c) 2014 Jaco Joubert License: https://github.com/emberui/emberui/blob/master/LICENSE */ import EuiButtonComponent from './components/eui-button'; import EuiButtonTemplate from './templates/eui-button'; import EuiCheckboxComponent from './components/eui-checkbox'; import EuiCheckboxTemplate from './templates/eui-checkbox'; import EuiDropbuttonComponent from './components/eui-dropbutton'; import EuiDropbuttonTemplate from './templates/eui-dropbutton'; import EuiInputComponent from './components/eui-input'; import EuiInputTemplate from './templates/eui-input'; import EuiModalComponent from './components/eui-modal'; import EuiModalTemplate from './templates/eui-modal'; import EuiPoplistComponent from './components/eui-poplist'; import EuiPoplistTemplate from './templates/eui-poplist'; import EuiPoplistOptionTemplate from './templates/eui-poplist-option'; import EuiSelectComponent from './components/eui-select'; import EuiSelectTemplate from './templates/eui-select'; import EuiSelectDateComponent from './components/eui-selectdate'; import EuiSelectDateTemplate from './templates/eui-selectdate'; import EuiTextareaComponent from './components/eui-textarea'; import EuiTextareaTemplate from './templates/eui-textarea'; import EuiMonthComponent from './components/eui-month'; import EuiCalendarComponent from './components/eui-calendar'; import EuiCalendarTemplate from './templates/eui-calendar'; import EuiPopcalComponent from './components/eui-popcal'; import EuiPopcalTemplate from './templates/eui-popcal'; import './utilities/tabbable-selector'; import './utilities/position'; import './animations/popcal-close-default'; import './animations/popcal-open-default'; import './animations/modal-close-default'; import './animations/modal-open-default'; import './animations/modal-close-full'; import './animations/modal-open-full'; import './animations/poplist-close-default'; import './animations/poplist-open-default'; import './animations/poplist-close-flyin'; import './animations/poplist-open-flyin'; import EuiInitializer from './initializers/eui-initializer'; Ember.Application.initializer(EuiInitializer); Ember.libraries.register('EmberUI', '0.1.3'); export { EuiInitializer, EuiButtonComponent, EuiCheckboxComponent, EuiDropbuttonComponent, EuiInputComponent, EuiInputTemplate, EuiModalComponent, EuiPoplistComponent, EuiSelectComponent, EuiSelectDateComponent, EuiTextareaComponent, EuiMonthComponent, EuiCalendarComponent, EuiPopcalComponent }
JavaScript
0.000001
@@ -2177,26 +2177,26 @@ ter( -' +%22 EmberUI -', ' +%22, %22 0.1.3 -' +%22 );%0A%0A
97da10d6e64531f4c4d81582e0b78c17403d09af
Update ns.global.js
public/js/ns.global.js
public/js/ns.global.js
/** * global.js * Global footer file * * @project < write project name here > * @date < put date here > * @author < author name > * @site < site name > */ (function($, ns, window, document, undefined){ "use strict"; var _global = function(){ this.init = function(){ initEventListeners(); initEventTriggers(); }; /** * add all event listeners */ var initEventListeners = function(){ }; /** * put all event triggers, plugin initializations */ var initEventTriggers = function(){ }; /** * Initialize this object when document ready event is triggered */ $.subscribe(ns.events.INIT_MODULES, this.init); }; ns.global = new _global(); })((typeof jQuery !== "undefined") ? jQuery : null, NameSpace || {}, window, window.document);
JavaScript
0.000001
@@ -1,15 +1,26 @@ /**%0A - *%09 +* global.j @@ -21,20 +21,20 @@ obal.js%0A - * -%09 + Global f @@ -48,13 +48,12 @@ ile%0A - *%0A - * + @p @@ -90,18 +90,18 @@ here %3E%0A - * + @date @@ -129,12 +129,12 @@ %3E %0A - * + @aut @@ -138,17 +138,19 @@ author -%09 + %3C author @@ -160,14 +160,15 @@ me %3E -%09%0A * %09 + %0A* @sit @@ -193,14 +193,12 @@ e %3E%0A - */%0A%0A - (fun @@ -202,16 +202,17 @@ function + ($, ns, @@ -243,35 +243,84 @@ ned) + %7B%0A -%09%0A%09%22use strict%22;%0A%0A%09 + %0A %22use strict%22;%0A %0A var -_g +G loba @@ -335,136 +335,186 @@ tion + () + %7B%0A -%09%09this.init = function()%7B%0A%09%09%09initEventListeners();%0A%09%09%09initEventTriggers();%0A%09%09%7D;%0A%0A%09%09/**%0A%09%09 *%09add all event listeners%0A%09%09 */%0A%09%09 + /**%0A * add all event listeners%0A */%0A var @@ -546,90 +546,302 @@ tion + () + %7B%0A -%09%09%09%0A%09%09%7D;%0A%09%09%0A%09%09/**%0A%09%09 *%09put all event triggers, plugin initializations%0A%09%09 */%0A%09%09 + %0A %7D;%0A %0A /**%0A * put all event triggers, plugin initializations%0A */%0A var @@ -872,154 +872,801 @@ tion + () + %7B%0A%0A -%09%09%7D;%0A%0A%09%09/**%0A%09%09 * Initialize this object when document ready event is triggered%0A%09%09 */%0A%09%09$.subscribe(ns.events.INIT_MODULES, this.init);%0A%09%7D;%0A%0A%09 + %7D;%0A %0A /**%0A * define what needs to be done after all stuff %0A * has been loaded in to the browser%0A **/%0A this.onLoad = function () %7B%0A %7D;%0A %0A this.init = function () %7B%0A initEventListeners();%0A initEventTriggers();%0A %7D;%0A /**%0A * Initialize this object when document ready event is triggered%0A */%0A $.subscribe(ns.events.INIT_MODULES, this.init);%0A $.subscribe(ns.events.WINDOW_LOAD, this.onLoad);%0A %0A %7D;%0A%0A ns.g @@ -1681,10 +1681,9 @@ new -_g +G loba @@ -1699,16 +1699,23 @@ (typeof +window. jQuery ! @@ -1732,16 +1732,23 @@ ned%22) ? +window. jQuery : @@ -1754,16 +1754,23 @@ : null, +window. NameSpac @@ -1803,8 +1803,9 @@ cument); +%0A
355b0b7c4b13b6ee572593292f89373a0c05ae47
Add more parens
js/jquery.imadaem.js
js/jquery.imadaem.js
/*! Imadaem v0.4.0 http://imadaem.penibelst.de/ */ (function($, window) { 'use strict'; $.fn.imadaem = function(options) { var $elements = this, settings = $.extend({ dataAttribute: 'imadaem', timthumbPath: '/timthumb/timthumb.php', verticalRhythm: null, windowEvents: 'resize orientationchange' }, options), getNativeLength = (function(cssLength) { var density = window.devicePixelRatio || 1; return Math.round(cssLength * density); }()), lineHeight = (function($element) { var lh = parseFloat($element.css('line-height')); return isNaN(lh) ? 0 : lh; }()), adjustVerticalRhythm = (function($element, height) { if (settings.verticalRhythm === 'line-height') { var lh, l; lh = lineHeight($element); if (lh) { l = Math.max(1, Math.round(height / lh)); height = lh * l; } } return height; }()), getData = (function($element) { var data = $element.data(settings.dataAttribute); if ($.isPlainObject(data)) { // ratio must be a number data.ratio = parseFloat(data.ratio) || 0; // ignore maxRatio if ratio is set data.maxRatio = data.ratio ? 0 : parseFloat(data.maxRatio) || 0; // gravity must be a combination of ['l', 'r', 't', 'b'] data.gravity = data.gravity ? data.gravity.replace(/[^lrtb]/g, '').substr(0, 2) : ''; } else { data = {url: data}; } return $.extend({ url: '', gravity: '', ratio: 0, maxRatio: 0, heightGuide: '' }, data); }()), setSrc = (function($element, newSrc) { var oldSrc = $element.attr('src'), errors = 0; $element .on('error', function() { // fall back to the previous src once if (!errors) { errors += 1; $(this).attr('src', oldSrc); } }) .attr('src', newSrc); }()), scale = (function() { var $this, data, timthumbParams, height, minHeight, width; $elements.each(function() { $this = $(this); data = getData($this); if (!data.url) { return; } width = $this.innerWidth(); height = $this.innerHeight(); if (data.ratio) { height = Math.round(width / data.ratio); } else if ($(data.heightGuide).length) { height = $(data.heightGuide).innerHeight(); } if (data.maxRatio) { minHeight = Math.round(width / data.maxRatio); height = Math.max(minHeight, height); } height = adjustVerticalRhythm($this, height); // prevent blinking effects $this.height(height); timthumbParams = { src: data.url || '', a: data.gravity || '', w: getNativeLength(width), h: getNativeLength(height) }; setSrc($this, settings.timthumbPath + '?' + $.param(timthumbParams)); }); }()); $(window) .one('load', scale) .on(settings.windowEvents, scale); return this; }; }(jQuery, window));
JavaScript
0
@@ -102,16 +102,17 @@ adaem = +( function @@ -1899,16 +1899,17 @@ error', +( function @@ -2085,16 +2085,18 @@ %7D +() )%0A @@ -3416,16 +3416,19 @@ his;%0A %7D +()) ;%0A%7D(jQue
70d6c7a8c83302e0433a0e1ad0e4fd15ffd9aad7
Convert inline predicate to predicate generator
lib/main.js
lib/main.js
"use babel"; import _ from "lodash"; export default { activate() { this.commands = atom.commands.add("atom-workspace", { "gluon:build": () => { this.build(); }, }); }, deactivate() { this.commands.dispose(); }, build() { const builder = this.builderForActiveTextEditor(); if (!builder) { return; } builder.buildFunction(); }, provideBuildService() { const self = this; return { register(registration) { if (!registration) { return; } if (!self.builders) { self.builders = {}; } self.builders[registration.name] = registration; }, }; }, builderForActiveTextEditor() { const grammar = this.getActiveGrammar(); if (!grammar) { return null; } const isMappedToGrammer = (b) => { _.includes(b.grammars, grammar); }; const builder = _.find(this.builders, isMappedToGrammer); return builder; }, getActiveGrammar() { const editor = this.getActiveTextEditor(); if (editor) { return editor.getGrammar().scopeName; } return null; }, getActiveTextEditor() { return atom.workspace.getActiveTextEditor(); }, };
JavaScript
0.999999
@@ -32,16 +32,162 @@ dash%22;%0A%0A +function isMappedToGrammer(grammar) %7B%0A return (builder) =%3E %7B%0A console.log(builder);%0A return _.includes(builder.grammars, grammar);%0A %7D;%0A%7D%0A%0A export d @@ -914,83 +914,8 @@ %7D%0A%0A - const isMappedToGrammer = (b) =%3E %7B _.includes(b.grammars, grammar); %7D;%0A @@ -969,16 +969,25 @@ oGrammer +(grammar) );%0A r
1b1914df7a7f4310a8fff639c4bd854b5693e5ed
Set guid to the full path
to_rss.js
to_rss.js
/*jslint node: true, esversion: 6 */ 'use strict'; var Fs = require('fs'); var Rss = require('rss'); var request = require('request'); class Muut { constructor(board, maintainer_email, title, description) { this.board = board; this.maintainer_email = maintainer_email; this.title = title; this.description = description; } get muutURL() { return 'https://muut.com/'; } get muutApiURL() { return 'https://api.muut.com/'; } get boardURL() { return this.muutURL + this.board; } extract(entry) { var entryData; try { var seed = entry.seed; var author = seed.user.displayname; var description = seed.body; var postTitle = seed.title; var guid = seed.key; var date = seed.time; var path = entry.path.replace('/' + this.board, ''); var full_path = this.muutURL + this.board + '#!' + path; console.log (full_path); entryData = this._entryData( author, description, postTitle, full_path, guid, date ); } catch (error) { entryData = this.entryErrorData; } return entryData; } get entryErrorData() { var author = 'ERROR'; var description = 'There was an error extracting data from an entry. ' + 'Please contact ' + this.maintainer_email + ' to report an error.'; var postTitle = 'Error extracting data for an entry'; var date = new Date().getTime(); var guid = date; return this._entryData(author, description, postTitle, this.muutURL, guid, date); } _entryData(author, description, postTitle, url, guid, date) { return { 'title': postTitle, 'description': description, 'url': url, 'guid': guid, 'author': author, 'date': date }; } } function createFeed(muut, entries) { var feed = new Rss({ 'title': muut.title, 'description': muut.description, 'feed_url': muut.boardURL, 'site_url': muut.boardURL, }); for (var idx in entries) { feed.item(entries[idx]); } var xml = feed.xml({indent: true}); return xml; } function make_muut_response_processor(muut, client_response) { return function(error, response, body) { var data = (error || response.statusCode != 200) ? {} : body; var extractedEntries; try { var entries = body.result.moots.entries; extractedEntries = entries.map(muut.extract, muut); } catch (error) { extractedEntries = [muut.entryErrorData]; } var xml = createFeed(muut, extractedEntries); client_response.writeHead(200); client_response.end(xml); }; } function makeRequest(muut, response) { var options = { url: muut.muutApiURL, method: 'POST', headers: {'Accept': 'application/json'}, json: { 'method': 'init', 'params':[ { 'version': '1.14.0', 'path': '/' + muut.board, 'currentForum': muut.board, 'pageLocation': muut.muutURL, 'expand_all': false, 'reload': false } ], 'id':'#1', 'session':{'sessionId': ''}, 'jsonrpc':'2.1.0', 'transport':'upgrade' } }; var muut_response_processor = make_muut_response_processor(muut, response); request(options, muut_response_processor); } module.exports.muutToRss = makeRequest; module.exports.Muut = Muut;
JavaScript
0
@@ -789,41 +789,8 @@ le;%0A - var guid = seed.key;%0A @@ -953,16 +953,50 @@ + path;%0A + var guid = full_path;%0A
f406a61fe9dc517cecf2555fa96b4534114603e5
fix endpoint; prevent recursive redirect
app/routes/file.js
app/routes/file.js
var express = require('express'); var request = require('request'); var router = express.Router(); var baseUrl = 'http://127.0.0.1:2268/f/'; var backendsUrl = 'http://exonum.com/backends/timestamping/content'; // router.post('/pay', function(req, res) { // var db = req.db; // var hash = req.body.label; // var description = req.body.description; // // db.serialize(function() { // db.get('SELECT 1 FROM pairs WHERE hash = "' + hash + '"', function(err, row) { // if (typeof row === 'undefined') { // db.prepare('INSERT INTO pairs (hash, description) VALUES (?, ?)').run(hash, description).finalize(); // } else { // db.run('UPDATE pairs SET description = "' + description + '" WHERE hash = "' + hash + '"'); // } // }); // }); // // res.redirect(307, 'https://money.yandex.ru/quickpay/confirm.xml'); // }); router.post('/upload', function(req, res) { var db = req.db; var hash = req.body.label; var description = req.body.description; request.post({ url: backendsUrl, headers: [{ name: 'content-type', value: 'multipart/form-data' }], formData: { hash: hash, description: description } }, function() { db.serialize(function() { db.get('SELECT 1 FROM pairs WHERE hash = "' + hash + '"', function(err, row) { if (typeof row === 'undefined') { db.prepare('INSERT INTO pairs (hash, description) VALUES (?, ?)').run(hash, description).finalize(function() { res.redirect(baseUrl + hash + '/redirect'); }); } else { db.run('UPDATE pairs SET description = "' + description + '" WHERE hash = "' + hash + '"', function(error) { if (!error) { res.redirect(baseUrl + hash + '/redirect'); } else { res.render('error', {error: error}); } }); } }); }); }); }); // router.post('/proceed', function(req, res) { // var db = req.db; // var hash = req.body.label; // // db.serialize(function() { // db.each('SELECT 1 rowid, * FROM pairs WHERE hash = "' + hash + '" LIMIT 1', function(err, row) { // if (typeof row !== 'undefined') { // request.post({ // url: backendsUrl, // headers: [{ // name: 'content-type', // value: 'multipart/form-data' // }], // formData: { // hash: hash, // description: row.description // } // }); // } // }); // }); // // res.status(200).send(); // }); router.get('/:hash/exists', function(req, res, next) { var hash = req.params.hash; request.get(backendsUrl + '/' + hash, function(error, response, body) { if (!error) { if (response.statusCode === 200) { res.json({exists: true, redirect: '/f/' + hash}); } else if (response.statusCode === 409) { res.json({exists: false}); } else { res.render('error', {error: error}); } } else { res.render('error', {error: error}); } }); }); router.get('/:hash/redirect', function(req, res) { var hash = req.params.hash; // start pooling until it will be able to get files info with GET request which means file is in a block (function pooling() { request.get({ url: req.protocol + '://' + req.headers.host + '/f/' + hash + '/exists', json: true }, function(error, response, body) { if (!error) { if (body.exists) { res.redirect(body.redirect); } else { setTimeout(function() { pooling(res, hash); }, 512); } } else { res.status(response.statusCode).send(error); } }) })(); }); router.get('/:hash', function(req, res, next) { var hash = req.params.hash; request.get(backendsUrl + '/' + hash, function(error, response, body) { if (!error) { try { var data = JSON.parse(body); if (response.statusCode === 200) { data['title'] = 'Certificate of proof ' + hash; data['url'] = encodeURIComponent(baseUrl + hash); res.render('file', data); } else if (response.statusCode === 409) { res.render('file-not-found', {title: 'File not found', hash: hash}); } else { res.render('error', {error: error}); } } catch(e) { res.render('error'); } } else { res.render('error', {error: error}); } }); }); module.exports = router;
JavaScript
0
@@ -165,27 +165,23 @@ p:// -exonum.com/backends +127.0.0.1:16000 /tim @@ -3636,24 +3636,44 @@ params.hash; +%0A var limit = 10; %0A%0A // sta @@ -4099,32 +4099,166 @@ %7D else %7B%0A + limit++;%0A if (limit %3E 10) %7B%0A res.render('error');%0A %7D%0A
61f9e084ed809001cf977f2273bf2358ad1a90d8
Update hook tests since f4f52fb02 requires their target to be EventEmitters
test/model/HookTest.js
test/model/HookTest.js
var Watai = require('../helpers/subject'), my = require('../helpers/driver').getDriverHolder(), should = require('should'); /* Exported to be also used in WidgetTest. */ exports.checkHook = checkHook = function checkHook(subject, hookName, expectedContent) { it('should add a hook to the target object', function() { subject.should.have.property(hookName); }); it('should return an object when accessed', function() { should(typeof subject[hookName] == 'object'); // prototype of WebDriver internal objects is not augmented }); it('should have the correct text in the retrieved element', function(done) { subject[hookName].getText().then(function(content) { content.should.equal(expectedContent); done(); }); }); } /** This test suite is redacted with [Mocha](http://visionmedia.github.com/mocha/) and [Should](https://github.com/visionmedia/should.js). */ describe('Hook', function() { var hooksTarget = {}; describe('selector', function() { describe('with ID', function() { var hookName = 'id'; before(function() { Watai.Hook.addHook(hooksTarget, hookName, { id: 'toto' }, my.driver); }); checkHook(hooksTarget, hookName, 'This paragraph has id toto'); }); describe('with CSS', function() { var hookName = 'css'; before(function() { Watai.Hook.addHook(hooksTarget, hookName, { css: '.tutu' }, my.driver); }); checkHook(hooksTarget, hookName, 'This paragraph has class tutu'); }); describe('with Xpath', function() { var hookName = 'xpath'; before(function() { Watai.Hook.addHook(hooksTarget, hookName, { xpath: '//div[@id="selectors"]/p[3]' }, my.driver); }); checkHook(hooksTarget, hookName, 'This paragraph is the third of the selectors div'); }); describe('with link text', function() { var hookName = 'linkText'; before(function() { Watai.Hook.addHook(hooksTarget, hookName, { linkText: 'This paragraph is embedded in a link' }, my.driver); }); checkHook(hooksTarget, hookName, 'This paragraph is embedded in a link'); }); it('should work on a field too', function(done) { var target = 'field'; Watai.Hook.addHook(hooksTarget, target, { css: 'input[name="field"]' }, my.driver); hooksTarget[target].getAttribute('value').then(function(content) { content.should.equal('Default'); done(); }); }); }); describe('setter', function() { it('should set the value upon attribution', function(done) { var target = 'field', newContent = 'new content'; Watai.Hook.addHook(hooksTarget, target, { css: 'input[name="field"]' }, my.driver); hooksTarget[target] = newContent; hooksTarget[target].getAttribute('value').then(function(content) { content.should.equal(newContent); done(); }); }); }); });
JavaScript
0
@@ -930,11 +930,48 @@ t = -%7B%7D; +new (require('events').EventEmitter)();%0A %0A%0A%09d
9598c2e88b00a2ef925f838fd8bb4cab9dfa7710
add extra XMP encoding test
packages/exif/test/decoder/jpeg-decoder.test.js
packages/exif/test/decoder/jpeg-decoder.test.js
const {expect, fixture} = require('../utils') const JPEGDecoder = require('../../dist/decoder/jpeg-decoder').JPEGDecoder const xmpJpeg = fixture('xmp.jpg') const nikonJpeg = fixture('nikon.jpg') describe('lib/jpeg-decoder.js', () => { describe('#injectEXIFMetadata', () => { it('should reconstruct same image', () => { const metadataBuffer = new JPEGDecoder(nikonJpeg).extractEXIFBuffer() const result = JPEGDecoder.injectEXIFMetadata(nikonJpeg, metadataBuffer) expect(result).to.eql(nikonJpeg) }) }) describe('#injectXMPMetadata', () => { it('should reconstruct same image', () => { const metadataBuffer = new JPEGDecoder(xmpJpeg).extractXMPBuffer() const result = JPEGDecoder.injectXMPMetadata(xmpJpeg, metadataBuffer) expect(result).to.eql(xmpJpeg) }) }) describe('.extractMetadata', () => { it('should extract EXIF data', () => { const metadata = new JPEGDecoder(nikonJpeg).extractMetadata() expect(metadata).to.include({ISO: 2500}) }) it('should extract XMP data', () => { const metadata = new JPEGDecoder(xmpJpeg).extractMetadata() expect(metadata).to.include({Rating: 4, Label: 'Blue'}) }) }) })
JavaScript
0.000001
@@ -113,16 +113,88 @@ GDecoder +%0Aconst XMPEncoder = require('../../dist/encoder/xmp-encoder').XMPEncoder %0A%0Aconst @@ -276,16 +276,24 @@ be('lib/ +decoder/ jpeg-dec @@ -880,32 +880,363 @@ (xmpJpeg)%0A %7D) +%0A%0A it('should inject from scratch', () =%3E %7B%0A const metadataBuffer = XMPEncoder.encode(%7BRating: 1, Label: 'Red'%7D)%0A const result = JPEGDecoder.injectXMPMetadata(nikonJpeg, metadataBuffer)%0A const metadata = new JPEGDecoder(result).extractMetadata()%0A expect(metadata).to.include(%7BRating: 1, Label: 'Red'%7D)%0A %7D) %0A %7D)%0A%0A describ
965636328d57cec4c0579144b023e22e5fb14e9c
Update BurstingFlare.js
src/parser/warlock/destruction/modules/azerite/BurstingFlare.js
src/parser/warlock/destruction/modules/azerite/BurstingFlare.js
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import { calculateAzeriteEffects } from 'common/stats'; import { formatPercentage } from 'common/format'; import TraitStatisticBox from 'interface/others/TraitStatisticBox'; const burstingFlareStats = traits => traits.reduce((total, rank) => { const [ mastery ] = calculateAzeriteEffects(SPELLS.BURSTING_FLARE.id, rank); return total + mastery; }, 0); export const STAT_TRACKER = { mastery: combatant => burstingFlareStats(combatant.traitsBySpellId[SPELLS.BURSTING_FLARE.id]), }; const debug = false; /* Bursting Flare: Casting Conflagrate on a target affected by your Immolate increases your Mastery by X for 20 sec, stacking up to 5 times. */ class BurstingFlare extends Analyzer { _lastChangeTimestamp = null; _currentStacks = 0; totalMastery = 0; mastery = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.BURSTING_FLARE.id); if (!this.active) { return; } this.mastery = burstingFlareStats(this.selectedCombatant.traitsBySpellId[SPELLS.BURSTING_FLARE.id]); debug && this.log(`Total bonus from BF: ${this.mastery}`); } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BURSTING_FLARE_BUFF.id) / this.owner.fightDuration; } get averageMastery() { const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.BURSTING_FLARE_BUFF.id) / this.owner.fightDuration; return (averageStacks * this.mastery).toFixed(0); } statistic() { return ( <TraitStatisticBox trait={SPELLS.BURSTING_FLARE.id} value={`${this.averageMastery} average Mastery`} tooltip={`Bursting Flare grants ${this.mastery} Mastery per stack (${5 * this.mastery} Mastery at 5 stacks) while active. You had ${formatPercentage(this.uptime)} % uptime on the buff.`} /> ); } } export default BurstingFlare;
JavaScript
0
@@ -807,61 +807,8 @@ r %7B%0A - _lastChangeTimestamp = null;%0A _currentStacks = 0;%0A to
866067e3dd126ed3b77a8fbdfd82453ef5dd065e
change file naming
config/documents.js
config/documents.js
const { URL } = require('url'); const baseFiles = { privacy: 'Onlineeinwilligung/Datenschutzerklaerung-Muster-Schulen-Onlineeinwilligung.pdf', termsOfUse: 'Onlineeinwilligung/Nutzungsordnung-HPI-Schule-Schueler-Onlineeinwilligung.pdf', }; module.exports = { defaultDocuments: () => ({ documentBaseDir: process.env.DOCUMENT_BASE_DIR || 'https://schul-cloud-hpi.s3.hidrive.strato.com/', baseFiles: baseDir => Object.entries(baseFiles).reduce((obj, [key, value]) => { obj[key] = String(new URL(value, baseDir)); return obj; }, {}), otherFiles: {}, }), };
JavaScript
0.000001
@@ -54,16 +54,25 @@ %09privacy +Exemplary : 'Onlin @@ -147,16 +147,93 @@ g.pdf',%0A +%09privacy: 'Onlineeinwilligung/Datenschutzerklaerung-Onlineeinwilligung.pdf',%0A %09termsOf @@ -235,16 +235,25 @@ rmsOfUse +Exemplary : 'Onlin @@ -327,16 +327,90 @@ g.pdf',%0A +%09termsOfUse: 'Onlineeinwilligung/Nutzungsordnung-Onlineeinwilligung.pdf',%0A %7D;%0A%0Amodu
aa4e99088a2a448d16ae7fd3ae1e269f34f14616
Add ignore to text inputs
public/js/netsensia/formwidget_multitable.js
public/js/netsensia/formwidget_multitable.js
$(document).ready(function() { $.fn.editable.defaults.mode = 'popup'; $('table.widget_multitable').each(function() { var numColumns = $(this).find('tr th').length; var editableMode = numColumns < 2 ? 'inline' : 'popup'; if (numColumns == 3) { $(this).find('th').each(function() { $(this).width('33%'); }); } $(this).find('input').each(function() { $(this).width('60%'); }); $(this).find('select').each(function() { $(this).attr('name', 'widgetignore[]'); $(this).prepend($('<option>', { value: -1, text: 'Please select...' })); $(this).val(-1); }); setEditableElements($(this), editableMode); }); function setEditableElements(tableEl, editableMode) { tableEl.find('.widget_multitable_edit').each(function() { $(this).editable({ pk: 1, url: '', mode: editableMode, success: function(response, newValue) { $(this).attr('data-value', newValue); } }); }); } $(document).delegate('.widget_multitable_addrow', 'click', function() { var widgetId = $(this).attr('data-widgetid'); var tableEl = $('table[data-widgetid="' + widgetId + '"]'); var numRows = tableEl.find('tr:visible').length - 1; var lastRow = $(tableEl).find('tr:last'); if (numRows == 0) { $(lastRow).css('display', 'table-row'); } else { var newRow = $(lastRow).clone().insertAfter(lastRow); } setEditableElements(tableEl, 'popup'); }); $(document).delegate('.widget_multitable_deleterow', 'click', function() { var widgetId = $(this).attr('data-widgetid'); var tableEl = $('table[data-widgetid="' + widgetId + '"]'); var numRows = tableEl.find('tr:visible').length - 1; if (numRows == 1) { $(this).parent().parent().css('display', 'none'); } else { $(this).parent().parent().remove(); } return false; }); $(document).delegate('.widget_multitable_edit', 'click', function() { }); $(document).delegate('input[name="form-submit"]', 'click', function() { $('.widget_multitable').each(function() { var widgetId = $(this).attr('data-widgetid'); var widgetData = jQuery.parseJSON( $('#' + widgetId).val() ); var rowCount = 0; widgetData.rowValues = []; $('table[data-widgetid="' + widgetId + '"] > tbody > tr').each(function() { rowCount ++; if (rowCount > 1) { var rowValueArray = []; $(this).children('td').each(function () { rowValueArray.push($(this).val()); }); widgetData.rowValues.push(rowValueArray); } }); var newJson = JSON.stringify(widgetData); $('input[id="' + widgetId + '"]').val(newJson); }); }); });
JavaScript
0.00002
@@ -402,16 +402,59 @@ '60%25');%0A +%09%09%09$(this).attr('name', 'widgetignore%5B%5D');%0A %09%09%7D);%0A%09%09
382b302436acbf5cdbd7c5b54282cf523983e6c3
Remove error
js/jquery.imadaem.js
js/jquery.imadaem.js
/*! Imadaem v0.4.0 http://imadaem.penibelst.de/ */ /*jslint closure: true, indent: 4, regexp: true */ /*global jQuery: false, window: false */ (function ($, window) { "use strict"; $.fn.imadaem = function (options) { var $elements = this, settings = $.extend({ dataAttribute: "imadaem", timthumbPath: "/timthumb/timthumb.php", verticalRhythm: null, windowEvents: "resize orientationchange" }, options), getNativeLength = function (cssLength) { var density = window.devicePixelRatio || 1; return Math.round(cssLength * density); }, lineHeight = function ($element) { var lh = parseFloat($element.css("line-height")); return isNaN(lh) ? 0 : lh; }, adjustVerticalRhythm = function ($element, height) { if (settings.verticalRhythm === "line-height") { var lh, l; lh = lineHeight($element); if (lh) { l = Math.max(1, Math.round(height / lh)); height = lh * l; } } return height; }, getData = function ($element) { var data = $element.data(settings.dataAttribute); if ($.isPlainObject(data)) { // ratio must be a number data.ratio = parseFloat(data.ratio) || 0; // ignore maxRatio if ratio is set data.maxRatio = data.ratio ? 0 : parseFloat(data.maxRatio) || 0; // gravity must be a combination of ["l", "r", "t", "b"] data.gravity = data.gravity ? data.gravity.replace(/[^lrtb]/g, "").substr(0, 2) : ""; } else { data = {url: data}; } return $.extend({ url: "", gravity: "", ratio: 0, maxRatio: 0, heightGuide: "" }, data); }, setSrc = function ($element, newSrc) { var oldSrc = $element.attr("src"), errors = 0; $element .on("error", function () { // fall back to the previous src once if (!errors) { errors += 1; $(this).attr("src", oldSrc); } }) .attr("src", newSrc); }, scale = function () { var $this, data, timthumbParams, height, minHeight, width; $elements.each(function () { $this = $(this); data = getData($this); if (!data.url) { return; } width = $this.innerWidth(); height = $this.innerHeight(); if (data.ratio) { height = Math.round(width / data.ratio); } else if ($(data.heightGuide).length) { height = $(data.heightGuide).innerHeight(); } if (data.maxRatio) { minHeight = Math.round(width / data.maxRatio); height = Math.max(minHeight, height); } height = adjustVerticalRhythm($this, height); // prevent blinking effects $this.height(height); timthumbParams = { src: data.url || "", a: data.gravity || "", w: getNativeLength(width), h: getNativeLength(height) }; setSrc($this, settings.timthumbPath + "?" + $.param(timthumbParams)); }); }; $(window) .one("load", scale) .on(settings.windowEvents, scale); return this; }; }(jQuery, window)
JavaScript
0.000002
@@ -4422,16 +4422,19 @@ (jQuery, window) +);%0A
29be3bb7bf229e674e162a51e675a2c8d63c296f
make getBackgroundStack work properly at mobile widths
lib/commons/color/get-background-color.js
lib/commons/color/get-background-color.js
/* global color, dom */ const graphicNodes = [ 'IMG', 'CANVAS', 'OBJECT', 'IFRAME', 'VIDEO', 'SVG' ]; function elmHasImage(elm, style) { var nodeName = elm.nodeName.toUpperCase(); if (graphicNodes.includes(nodeName)) { return true; } style = style || window.getComputedStyle(elm); return style.getPropertyValue('background-image') !== 'none'; } /** * Returns the non-alpha-blended background color of an element * @param {Element} elm * @return {Color} */ function getBgColor(elm, elmStyle) { elmStyle = elmStyle || window.getComputedStyle(elm); let bgColor = new color.Color(); bgColor.parseRgbString( elmStyle.getPropertyValue('background-color')); if (bgColor.alpha !== 0) { let opacity = elmStyle.getPropertyValue('opacity'); bgColor.alpha = bgColor.alpha * opacity; } return bgColor; } function calculateObscuringAlpha(elmIndex, elmStack) { var totalAlpha = 0; if (elmIndex > 0) { // there are elements above our element, check if they are contribute to the background for (var i = elmIndex - 1; i >= 0; i--) { let bgElm = elmStack[i]; let bgElmStyle = window.getComputedStyle(bgElm); let bgColor = getBgColor(bgElm, bgElmStyle); if (bgColor.alpha) { totalAlpha += bgColor.alpha; } else { // remove elements not contributing to the background elmStack.splice(i, 1); } } } return totalAlpha; } /** * Get all elements rendered underneath the current element, * in the order in which it is rendered */ color.getBackgroundStack = function(elm) { let rect = elm.getBoundingClientRect(); let x, y; if (rect.left > window.innerWidth) { return; } if (rect.top > window.innerWidth) { return; } x = Math.min( Math.ceil(rect.left + (rect.width / 2)), window.innerWidth - 1); y = Math.min( Math.ceil(rect.top + (rect.height / 2)), window.innerHeight - 1); let elmStack = document.elementsFromPoint(x, y); elmStack = dom.reduceToElementsBelowFloating(elmStack, elm); let bodyIndex = elmStack.indexOf(document.body); if (// Check that the body background is the page's background bodyIndex > 1 && // only if there are negative z-index elements !elmHasImage(document.documentElement) && getBgColor(document.documentElement).alpha === 0 ) { // Remove body and html from it's current place elmStack.splice(bodyIndex, 1); elmStack.splice( elmStack.indexOf(document.documentElement), 1); // Put the body background as the lowest element elmStack.push(document.body); } // Return all elements BELOW the current element, null if the element is undefined let elmIndex = elmStack.indexOf(elm); if (calculateObscuringAlpha(elmIndex, elmStack) >= 0.99) { // if the total of the elements above our element results in total obscuring, return null return null; } return elmIndex !== -1 ? elmStack : null; }; color.getBackgroundColor = function(elm, bgElms = [], noScroll = false) { if(noScroll !== true) { elm.scrollIntoView(); } let bgColors = []; let elmStack = color.getBackgroundStack(elm); // Search the stack until we have an alpha === 1 background (elmStack || []).some((bgElm) => { let bgElmStyle = window.getComputedStyle(bgElm); // Get the background color let bgColor = getBgColor(bgElm, bgElmStyle); if (// abort if a node is outside it's parent and its parent has a background (elm !== bgElm && !dom.visuallyContains(elm, bgElm) && bgColor.alpha !== 0) || // OR if the background elm is a graphic elmHasImage(bgElm, bgElmStyle) ) { bgColors = null; bgElms.push(bgElm); return true; } if (bgColor.alpha !== 0) { // store elements contributing to the br color. bgElms.push(bgElm); bgColors.push(bgColor); // Exit if the background is opaque return (bgColor.alpha === 1); } else { return false; } }); if (bgColors !== null && elmStack !== null) { // Mix the colors together, on top of a default white bgColors.push( new color.Color(255, 255, 255, 1)); return bgColors.reduce( color.flattenColors); } return null; }; /** * Determines whether an element has a fully opaque background, whether solid color or an image * @param {Element} node * @return {Boolean} false if the background is transparent, true otherwise */ dom.isOpaque = function(node) { let style = window.getComputedStyle(node); return elmHasImage(node, style) || getBgColor(node, style).alpha === 1; };
JavaScript
0.000001
@@ -1635,37 +1635,38 @@ p %3E window.inner -Width +Height ) %7B%0A%09%09return;%0A%09%7D
85d7c06d7c933d50e7a3219edba5ed8bf95b08e8
remove modal if email ok
app/pages/frontPage.js
app/pages/frontPage.js
import React from 'react' import Bacon from 'baconjs' import BigCalendar from 'react-big-calendar' import moment from 'moment' import Promise from 'bluebird' import R from 'ramda' import Header from '../partials/header' import searchResults from '../partials/searchResults' import searchList from '../partials/searchList' import CourseParser from '../util/courseParser' const request = Promise.promisify(require('superagent')) require('moment/locale/fi') BigCalendar.momentLocalizer(moment) export const pagePath = '/' export const pageTitle = 'Lukkarimaatti' const inputBus = new Bacon.Bus() const selectedCoursesBus = new Bacon.Bus() const emailBus = new Bacon.Bus() const indexBus = new Bacon.Bus() export const initialState = (urlCourses = []) => { return { selectedCourses: urlCourses, currentDate: moment(), courses: [], isSearchListVisible: false, urlParams: [], isModalOpen: false, selectedIndex: -1 } } const searchResultsS = inputBus.flatMap((courseName) => { if (courseName.length > 2) { const responseP = request.get('course/course').query({name: courseName}) return Bacon.fromPromise(responseP) } else { return {text: "[]"} } }) const urlParamS = selectedCoursesBus.flatMapLatest((event) => { const course = R.head(event.courses) CourseParser.addUrlParameter(course.course_code, course.group_name) return [course.group_name ? course.course_code + '&' + course.group_name : course.course_code] }) const selectedCourseS = selectedCoursesBus.flatMapLatest((event) => { if (event.type === 'add') { return R.flatten(R.reduce((a, b) => [a].concat([b]), event.applicationState.selectedCourses, event.courses)) } else if (event.type === 'remove') { return R.filter((c) => c.course_code !== event.courses[0].course_code, event.applicationState.selectedCourses) } else { throw new Error('Unknown action') } }) const modalS = emailBus.flatMapLatest((event) => { if (event.isModalOpen && event.address) { let responseP = request.post('api/save').send({ email: event.address.toString(), link: window.location.href.toString() }) return Bacon.fromPromise(responseP) .map({isModalOpen: false}) .mapError({isModalOpen: true}) } return event.isModalOpen }) export const applicationStateProperty = (initialState) => Bacon.update( initialState, inputBus, (applicationState, input) => ({ ...applicationState, input }), indexBus, (applicationState, selectedIndex) => ({ ...applicationState, selectedIndex }), searchResultsS, (applicationState, courseNames) => ({ ...applicationState, courses: JSON.parse(courseNames.text), isSearchListVisible: true }), selectedCourseS, (applicationState, selectedCourses) => ({ ...applicationState, selectedCourses }), urlParamS, (applicationState, param) => ({ ...applicationState, urlParams: R.append(param, applicationState.urlParams) }), modalS, (applicationState, isModalOpen) => ({ ...applicationState, isModalOpen }) ) const stringToColour = (colorSeed) => { var hash = 0, colour = '#', value colorSeed.split("").forEach(function(e) { hash = colorSeed.charCodeAt(e) + ((hash << 5) - hash) }) for (var j = 0; j < 3; j++) { value = (hash >> (j * 8)) & 0xFF colour += ('00' + value.toString(16)).substr(-2) } return colour } const Event = ({ event }) => ( <div style={{backgroundColor: stringToColour(event.title)}} className="calendar-event"> {event.title}{event.description} </div> ) export const renderPage = (applicationState) => <body> {Header(applicationState, emailBus)} <div className="container"> <a href="https://github.com/Laastine/lukkarimaatti"> <img style={{position: 'absolute', top: '0', right: '0', border: '0'}} src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"></img> </a> {searchList(applicationState, inputBus, selectedCoursesBus, indexBus)} <div className="selected-courses-list"> <div className="selected-courses-list-topic">Selected courses:</div> {searchResults(applicationState, selectedCoursesBus, CourseParser)} </div> <div> <BigCalendar events={CourseParser.addDataToCalendar(applicationState)} defaultView="week" views={['month', 'week', 'day']} formats={{ dayHeaderFormat: "ddd D.M", dayFormat: "ddd D.M" }} components={{ event: Event }} min={new Date(moment(applicationState.currentDate).hours(8).minutes(0).format())} max={new Date(moment(applicationState.currentDate).hours(20).minutes(0).format())} defaultDate={new Date(moment(applicationState.currentDate).format())} /> </div> <div className="footer"> <div id="disclaimer">Use with your own risk!</div> <div id="versionInfo">v1.2.0</div> </div> </div> </body>
JavaScript
0.99893
@@ -2289,28 +2289,22 @@ map( -%7BisModalOpen: +(res) =%3E false -%7D )%0A @@ -2327,27 +2327,12 @@ ror( -%7BisModalOpen: true -%7D )%0A
e77095fd68a2d7b83a46192a577b415e4c3f8788
add setting for default new file line endings
lib/main.js
lib/main.js
'use babel' import _ from 'underscore-plus' import {CompositeDisposable, Disposable} from 'atom' import LineEndingListView from './line-ending-list-view' import StatusBarItem from './status-bar-item' import helpers from './helpers' const LineEndingRegExp = /\r\n|\n/g let disposables = null export function activate () { disposables = new CompositeDisposable() let listView = new LineEndingListView((lineEnding) => { if (lineEnding) { setLineEnding(atom.workspace.getActivePaneItem(), lineEnding) } panel.hide() }) let panel = atom.workspace.addModalPanel({ item: listView, visible: false }) disposables.add(atom.commands.add('atom-text-editor', { 'line-ending-selector:show': (event) => { panel.show() listView.reset() }, 'line-ending-selector:convert-to-LF': (event) => { setLineEnding(event.target.getModel(), '\n') }, 'line-ending-selector:convert-to-CRLF': (event) => { setLineEnding(event.target.getModel(), '\r\n') } })) disposables.add(new Disposable(() => panel.destroy())) } export function deactivate () { disposables.dispose() } export function consumeStatusBar (statusBar) { let statusBarItem = new StatusBarItem() let currentBufferDisposable = null function updateTile (buffer) { let lineEndings = getLineEndings(buffer) if (lineEndings.size === 0) { let platformLineEnding = getPlatformLineEnding() buffer.setPreferredLineEnding(platformLineEnding) lineEndings = new Set().add(platformLineEnding) } statusBarItem.setLineEndings(lineEndings) } let debouncedUpdateTile = _.debounce(updateTile, 0) disposables.add(atom.workspace.observeActivePaneItem((item) => { if (currentBufferDisposable) currentBufferDisposable.dispose() if (item && item.getBuffer) { let buffer = item.getBuffer() updateTile(buffer) currentBufferDisposable = buffer.onDidChange(({oldText, newText}) => { if (!statusBarItem.hasLineEnding('\n')) { if (newText.indexOf('\n') >= 0) { debouncedUpdateTile(buffer) } } else if (!statusBarItem.hasLineEnding('\r\n')) { if (newText.indexOf('\r\n') >= 0) { debouncedUpdateTile(buffer) } } else if (LineEndingRegExp.test(oldText)) { debouncedUpdateTile(buffer) } }) } else { statusBarItem.setLineEndings(new Set()) currentBufferDisposable = null } })) disposables.add(new Disposable(() => { if (currentBufferDisposable) currentBufferDisposable.dispose() })) statusBarItem.onClick(() => { atom.commands.dispatch( atom.views.getView(atom.workspace.getActivePaneItem()), 'line-ending-selector:show' ) }) let tile = statusBar.addRightTile({item: statusBarItem.element, priority: 200}) disposables.add(new Disposable(() => tile.destroy())) } function getPlatformLineEnding () { if (helpers.getProcessPlatform() === 'win32') { return '\r\n' } else { return '\n' } } function getLineEndings (buffer) { let result = new Set() for (let i = 0; i < buffer.getLineCount() - 1; i++) { result.add(buffer.lineEndingForRow(i)) } return result } function setLineEnding (item, lineEnding) { if (item && item.getBuffer) { let buffer = item.getBuffer() buffer.setPreferredLineEnding(lineEnding) buffer.setText(buffer.getText().replace(LineEndingRegExp, lineEnding)) } }
JavaScript
0
@@ -288,16 +288,269 @@ = null%0A%0A +export let config = %7B%0A defaultNewFileLineEnding: %7B%0A title: 'Default line ending for new files',%0A type: 'string',%0A 'default': 'OS Default',%0A enum: %5B'OS Default', 'LF', 'CRLF'%5D,%0A descrition: 'Default line ending for new documents'%0A %7D%0A%7D;%0A%0A export f @@ -563,32 +563,32 @@ n activate () %7B%0A - disposables = @@ -1640,24 +1640,30 @@ let -platform +defaultNewFile LineEndi @@ -1666,32 +1666,38 @@ Ending = get -Platform +DefaultNewFile LineEnding() @@ -1733,24 +1733,30 @@ eEnding( -platform +defaultNewFile LineEndi @@ -1797,16 +1797,22 @@ add( -platform +defaultNewFile Line @@ -3196,24 +3196,30 @@ tion get -Platform +DefaultNewFile LineEndi @@ -3232,100 +3232,325 @@ %7B%0A -if (helpers.getProcessPlatform() === 'win32') %7B%0A return '%5Cr%5Cn'%0A %7D else %7B%0A return +let defaultNewFileLineEnding = atom.config.get('line-ending-selector.defaultNewFileLineEnding');%0A switch (defaultNewFileLineEnding) %7B%0A case 'LF':%0A return '%5Cn';%0A%0A case 'CRLF':%0A return '%5Cr%5Cn';%0A%0A case 'OS Default':%0A default:%0A return (helpers.getProcessPlatform() === 'win32') ? '%5Cr%5Cn' : '%5Cn' +; %0A %7D
445ac15abc3c2bdcc24c56fb51a2f0f8cc7ca87f
Change to adapt to new api
public/js/stargraph.js
public/js/stargraph.js
function callback(response) { var date = new Date(); var chart = new CanvasJS.Chart("chartContainer", { zoomEnabled: true, title:{ text: "Repo with " + response.data.length + " stars at " + date.getHours() + ":" + date.getMinutes() + " on " + date.toDateString() }, data: [ { type: "area", xValueType: "dateTime", dataPoints: response.data } ] }); chart.render(); } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return ""; } $(document).ready(function() { $("#loader").hide(); var token = getCookie("token"); if (token !== "") { $(".token").hide(); } callback([]); $("#form").submit(function(e) { e.preventDefault(); var repo = $("#repo").val(); if (token === "") { token = $("#token").val(); } //console.log(repo, token); $("#loader").show(); $.get("/api?repo=" + repo + "&token=" + token, function(data){ //console.log(data); var obj = JSON.parse(data); //console.log(obj); callback(obj); if (obj.length !== 0) { var lastTimestamp = obj.pop().x; $("#legend").html("Last star on the repository put at: " + new Date(lastTimestamp).toDateString()); } $("#loader").hide(); }); }); });
JavaScript
0
@@ -217,87 +217,43 @@ ars -at %22 + date.getHours() + %22:%22 + date.getMinutes() + %22 on %22 + date.toDateString() +with the last star at %22 + response. %0A
8adb2e2cd71a8ed9981f295b055b5ee32d4a09c5
Add end snapping.
app/scripts/controllers/nowPlayingController.js
app/scripts/controllers/nowPlayingController.js
(function () { angular .module('spotifyApp') .controller('nowPlayingController', function ($scope, $log, nowPlayingService) { $scope.playerOpen = false; $scope.tracks = []; $scope.trackIndex = 0; $scope.trackString = ''; $scope.isplaylist = false; $scope.trackImage = ''; $scope.currentlyPlaying = false; var audio = new Audio(); $scope.$on('tracksUpdated', function () { $scope.tracks = nowPlayingService.getTracks(); $scope.isplaylist = nowPlayingService.getListType(); $scope.trackIndex = nowPlayingService.getTrackIndex(); // Pause audio when track list is updated pauseSong(); resetSongPosition(); if ($scope.isplaylist) { audio.src = $scope.tracks[$scope.trackIndex].track.preview_url; } else { audio.src = $scope.tracks[$scope.trackIndex].preview_url; } updateTrackString(); }); $scope.nextTrack = function () { $scope.trackIndex = ($scope.trackIndex + 1) % $scope.tracks.length; if ($scope.isplaylist) { audio.src = $scope.tracks[$scope.trackIndex].track.preview_url; } else { audio.src = $scope.tracks[$scope.trackIndex].preview_url; } if ($scope.currentlyPlaying) playSong(); updateTrackString(); }; $scope.previousTrack = function () { var temp = $scope.trackIndex - 1; if (temp < 0) { temp = temp + $scope.tracks.length; } $scope.trackIndex = temp % $scope.tracks.length; if ($scope.isplaylist) { audio.src = $scope.tracks[$scope.trackIndex].track.preview_url; } else { audio.src = $scope.tracks[$scope.trackIndex].preview_url; } if ($scope.currentlyPlaying) playSong(); updateTrackString(); }; var updateTrackString = function () { if ($scope.tracks == {}) { $scope.trackString = ''; $scope.trackImage = ''; } if ($scope.isplaylist) { var artistName = $scope.tracks[$scope.trackIndex].track.artists[0].name; var trackName = $scope.tracks[$scope.trackIndex].track.name; $scope.trackImage = $scope.tracks[$scope.trackIndex].track.album.images[0].url; } else { var artistName = $scope.tracks[$scope.trackIndex].artists[0].name; var trackName = $scope.tracks[$scope.trackIndex].name; //$scope.trackImage = $scope.tracks[$scope.trackIndex].album.images[0].url; $scope.trackImage = ''; } $scope.trackString = artistName + ' - ' + trackName; }; $scope.touchMove = function (event) { var element = angular.element(document.querySelector('.now-playing')); element.css({ 'transition': 'none' }); var windowHeight = window.innerHeight; // Multiplier must match app.css height for .now-playing var nowPlayingTotalHeight = 0.6 * windowHeight; var y = event.center.y; var height = 80 - 100 * (windowHeight - y) / nowPlayingTotalHeight; if (height > 80) { height = 80; } else if (height < 0) { height = 0; } element.css({ 'transform': 'translateY(' + height + '%)' }); }; $scope.touchEnd = function (event) { var element = angular.element(document.querySelector('.now-playing')); var y = event.center.y; var windowHeight = window.innerHeight; }; /* $scope.onSwipeUp = function () { $scope.playerOpen = true; }; $scope.onSwipeDown = function () { $scope.playerOpen = false; }; */ $scope.togglePlaying = function () { if ($scope.currentlyPlaying) { pauseSong(); } else { playSong(); } }; $scope.disableBackgroundScrolling = function () { var e = angular.element(document.querySelector('body')); e.addClass('stopscroll'); }; $scope.enableBackgroundScrolling = function () { var e = angular.element(document.querySelector('body')); e.removeClass('stopscroll'); }; var playSong = function () { audio.play(); $scope.currentlyPlaying = true; }; var pauseSong = function () { audio.pause(); $scope.currentlyPlaying = false; }; var resetSongPosition = function () { pauseSong(); if ($scope.isplaylist) { audio.src = $scope.tracks[$scope.trackIndex].track.preview_url; } else { audio.src = $scope.tracks[$scope.trackIndex].preview_url; } }; }); })();
JavaScript
0
@@ -3225,16 +3225,40 @@ %7D);%0A + $log.log(height);%0A %7D;%0A%0A @@ -3379,37 +3379,8 @@ ));%0A - var y = event.center.y; %0A @@ -3417,24 +3417,566 @@ nnerHeight;%0A + // Multiplier must match app.css height for .now-playing%0A var nowPlayingTotalHeight = 0.6 * windowHeight;%0A var y = event.center.y;%0A var height = 80 - 100 * (windowHeight - y) / nowPlayingTotalHeight;%0A%0A if (height %3E 40) %7B%0A element.css(%7B%0A 'transform': 'translateY(' + 80 + '%25)',%0A 'transition': 'ease-in 0.25s all'%0A %7D);%0A %7D else if (height %3C 40) %7B%0A element.css(%7B%0A 'transform': 'translateY(' + 0 + '%25)',%0A 'transition': 'ease-in 0.25s all'%0A %7D);%0A %7D%0A %7D;%0A%0A
9c62b5597caf4e3891fd252fdbd855ced1dc331a
remove action listeners on route change
app/routes/home.js
app/routes/home.js
/*global $:true*/ import Ember from 'ember'; import TimeMachine from 'ember-time-machine'; import ENV from '../config/environment'; let theme = {}; let jsonBlob; function showError(){ let defaultJSON =''; $.ajax({ type: "GET", url: ENV.rootURL + "themes/theme_error.json", async: false, success: function (data) { defaultJSON = data; } }); jsonBlob = JSON.stringify(defaultJSON); } export default Ember.Route.extend({ setupController: function(controller, model) { controller.set('model' , model); document.addEventListener("dragend", ()=>{ controller.set('isDragging', false) }) }, model: async function(params){ jsonBlob = await this.store.findRecord('home', params.guid).then((record)=>{ return record.get('pageData') },function(e) { console.log(e) return false; }); let node = null; try{ node = await this.store.findRecord('node', params.guid); }catch(e){ showError() } if(!jsonBlob){ if( node.get('currentUserPermissions')[1] === 'write'){ $.ajax({ type: "GET", url: ENV.rootURL + "themes/theme_starter.json", async: false, success: (data)=> { //add to firebase let guid = { id: params.guid, guid: params.guid, pageData: JSON.stringify(data), unpublishedPageData: JSON.stringify(data) }; let record = this.store.createRecord('home', guid); record.save() jsonBlob = JSON.stringify(data); }}); }else{ showError() } } const content = Ember.Object.create(JSON.parse(jsonBlob)); const timeMachine = TimeMachine.Object.create({ content }); theme = timeMachine; return { theme, guid: params.guid, node: node }; }, actions: { save(guid){ this.store.findRecord('home', guid).then(function(data) { data.set('pageData', JSON.stringify(theme.content)); data.save(); }); } } });
JavaScript
0
@@ -687,24 +687,116 @@ %7D)%0A %7D,%0A + deactivate: function() %7B%0A document.removeEventListener(%22dragend%22, ()=%3E%7B%7D)%0A %7D,%0A model: a
24db7346efb48ca857a2e44c610f6717e73f7f24
Update version in release notes builder.
build/release-notes.js
build/release-notes.js
#!/usr/bin/env node /* * jQuery Release Note Generator */ var fs = require("fs"), http = require("http"), tmpl = require("mustache"), extract = /<a href="\/ticket\/(\d+)" title="View ticket">(.*?)<[^"]+"component">\s*(\S+)/g; var opts = { version: "1.8.2", short_version: "1.8.2", final_version: "1.8.2", categories: [] }; http.request({ host: "bugs.jquery.com", port: 80, method: "GET", path: "/query?status=closed&resolution=fixed&max=400&component=!web&order=component&milestone=" + opts.final_version }, function (res) { var data = []; res.on( "data", function( chunk ) { data.push( chunk ); }); res.on( "end", function() { var match, file = data.join(""), cur; while ( (match = extract.exec( file )) ) { if ( "#" + match[1] !== match[2] ) { var cat = match[3]; if ( !cur || cur.name !== cat ) { cur = { name: match[3], niceName: match[3].replace(/^./, function(a){ return a.toUpperCase(); }), bugs: [] }; opts.categories.push( cur ); } cur.bugs.push({ ticket: match[1], title: match[2] }); } } buildNotes(); }); }).end(); function buildNotes() { console.log( tmpl.to_html( fs.readFileSync("release-notes.txt", "utf8"), opts ) ); }
JavaScript
0
@@ -248,27 +248,32 @@ version: %221. -8.2 +9 Beta 1 %22,%0A%09short_ve @@ -278,27 +278,27 @@ version: %221. -8.2 +9b1 %22,%0A%09final_ve @@ -311,11 +311,9 @@ %221. -8.2 +9 %22,%0A%09
e0ba2d63e78e616d194fde3a5445068b87fc1fb8
add 2 new ios checkbox tracking fields for new fields in marketo
website-guts/assets/js/utils/oform_globals.js
website-guts/assets/js/utils/oform_globals.js
;(function(){ var w, d; w = window; d = document; w.optly = w.optly || {}; w.optly.mrkt = w.optly.mrkt || {}; w.optly.mrkt.Oform = {}; w.optly.mrkt.Oform.before = function(){ d.getElementsByTagName('body')[0].classList.add('oform-processing'); return true; }; w.optly.mrkt.Oform.validationError = function(element){ w.optly.mrkt.formHadError = true; var elementValue = $(element).val(); var elementHasValue = elementValue ? 'has value' : 'no value'; w.analytics.track($(element).closest('form').attr('id') + ' ' + element.getAttribute('name') + ' error submit', { category: 'form error', label: elementHasValue, value: elementValue.length }, { integrations: { Marketo: false } }); }; w.optly.mrkt.Oform.done = function(){ d.getElementsByTagName('body')[0].classList.remove('processing'); }; w.optly.mrkt.Oform.trackLead = function(data, XMLHttpRequest){ var propertyName, reportingObject, source, response, token; source = w.optly.mrkt.source; response = JSON.parse(XMLHttpRequest.target.responseText); if(response.token){ token = response.token; } else if(response.munchkin_token){ token = response.munchkin_token; } else { token = ''; } reportingObject = { utm_Campaign__c: source.utm.campaign || '', utm_Content__c: source.utm.content || '', utm_Medium__c: source.utm.medium || '', utm_Source__c: source.utm.source || '', utm_Keyword__c: source.utm.keyword || '', otm_Campaign__c: source.otm.campaign || '', otm_Content__c: source.otm.content || '', otm_Medium__c: source.otm.medium || '', otm_Source__c: source.otm.source || '', otm_Keyword__c: source.otm.keyword || '', GCLID__c: source.gclid || '', Signup_Platform__c: source.signupPlatform || '', Email: response.email ? response.email : '', FirstName: response.first_name || '', LastName: response.last_name || '', Phone: response.phone_number || '', Web__c: $('input[type="checkbox"][name="web"]').is(':checked') + '', Mobile_Web__c: $('input[type="checkbox"][name="mobile_web"]').is(':checked') + '', iOS__c: $('input[type="checkbox"][name="ios"]').is(':checked') + '', Android__c: $('input[type="checkbox"][name="android"]').is(':checked') + '' }; $.cookie('sourceCookie', source.utm.campaign + '|||' + source.utm.content + '|||' + source.utm.medium + '|||' + source.utm.source + '|||' + source.utm.keyword + '|||' + source.otm.campaign + '|||' + source.otm.content + '|||' + source.otm.medium + '|||' + source.otm.source + '|||' + source.otm.keyword + '|||' + source.signupPlatform + '|||' ); for(propertyName in data){ reportingObject[propertyName] = data[propertyName]; //jshint ignore:line } w.analytics.identify(response.unique_user_id, reportingObject, { integrations: { Marketo: true } }); /* legacy reporting - to be deprecated */ w.analytics.track('/account/create/success', { category: 'account', label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname) }, { integrations: { Marketo: false } }); w.Munchkin.munchkinFunction('visitWebPage', { url: '/account/create/success' }); w.analytics.track('/account/signin', { category: 'account', label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname) }, { integrations: { 'Marketo': false } }); /* temporarily commented out to decrease marketo queue w.Munchkin.munchkinFunction('visitWebPage', { url: '/event/account/signin' }); w.Munchkin.munchkinFunction('visitWebPage', { url: '/event/customer/signedin' }); */ w.Munchkin.munchkinFunction('visitWebPage', { url: '/event/plan/null' }); /* new reporting */ w.analytics.track('account created', { category: 'account', label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname) }, { integrations: { Marketo: false } }); w.analytics.track('account signin', { category: 'account', label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname) }, { integrations: { Marketo: false } }); }; w.optly.mrkt.Oform.initContactForm = function(arg){ new Oform({ selector: arg.selector }) .on('validationerror', w.optly.mrkt.Oform.validationError) .on('load', function(event){ if(event.target.status === 200){ //identify user $('body').addClass('oform-success'); var response = JSON.parse(event.target.responseText), email = d.querySelector('[name="email"]').value, traffic = d.querySelector('#traffic'); w.analytics.identify(response.unique_user_id, { name: d.querySelector('[name="name"]').value, email: email, Email: email, phone: d.querySelector('[name="phone"]').value || '', company: d.querySelector('[name="company"]').value || '', website: d.querySelector('[name="website"]').value || '', utm_Medium__c: window.optly.mrkt.source.utm.medium, otm_Medium__c: window.optly.mrkt.source.otm.medium, Demo_Request_Monthly_Traffic__c: traffic.options[traffic.selectedIndex].value || '', Inbound_Lead_Form_Type__c: d.querySelector('[name="inboundFormLeadType"]').value, token: response.token }, { integrations: { Marketo: true } }); //track the event w.analytics.track('demo requested', { category: 'contact form', label: window.optly.mrkt.utils.trimTrailingSlash(w.location.pathname) }, { integrations: { Marketo: true } }); } }); }; })();
JavaScript
0
@@ -2354,24 +2354,178 @@ ked') + '',%0A + iOStestc: $('input%5Btype=%22checkbox%22%5D%5Bname=%22ios%22%5D').is(':checked') + '',%0A IOSTest2: $('input%5Btype=%22checkbox%22%5D%5Bname=%22ios%22%5D').is(':checked') + '',%0A Androi
228c79106b9bc51195c571671534bbd97f6ea9f1
Remove unused vars
src/plugin/com.github.tschf.2016ADCentry.germanmap/mapRender.js
src/plugin/com.github.tschf.2016ADCentry.germanmap/mapRender.js
var germanMapRenderer = { width: 960, height: 750, scale: 500, setUpMap: function setUpMap(pluginFilePrefix, ajaxIdentifier, initialYear, red, green, blue){ var projection = d3.geo.mercator() .scale(500); var path = d3.geo.path() .projection(projection); //pull heights of all page components, to assign an appropriate height for the map region var headerHeight = apex.jQuery('.t-Header-navBar').outerHeight(true); var timelineHeaderHeight = apex.jQuery('#mapTimeline h4').outerHeight(true); var timelinePointsHeight = apex.jQuery('#mapTimeline #timelinePoints').outerHeight(true); var legendHeaderHeight = apex.jQuery('#legend h4').outerHeight(true); var legendColourGrid = apex.jQuery('#legend #colourGrid').outerHeight(true); var legendCaption = apex.jQuery('#legend #colourGridCaption').outerHeight(true); //buffer so the legend isn't right on the page border var buffer = 30; //figure out the height to make the map so it fits on the page var computedHeight = apex.jQuery(window).height()-headerHeight-timelineHeaderHeight-timelinePointsHeight-legendHeaderHeight-legendColourGrid-legendCaption-buffer; var svg = d3.select("#germanMap") .attr("height", computedHeight); d3.json(pluginFilePrefix + "de.json", function(error, de) { var states = topojson.feature(de, de.objects.states); svg.selectAll(".state") .data(states.features) .enter().append("path") .attr("class", function(d) { return d.id + " germanState"; }) .attr("d", path) .on("click", germanMapRenderer.onClickState); germanMapRenderer.updateMapPopulationDisplay(ajaxIdentifier, initialYear, red, green, blue); //trim spacing around the svg/map var generatedChart = document.querySelector("svg#germanMap"); var bbox = generatedChart.getBBox(); var viewBox = [bbox.x, bbox.y, bbox.width, bbox.height].join(" "); generatedChart.setAttribute("viewBox", viewBox); }); }, onClickState: function clickedState(d){ apex.event.trigger(document, 'showstateinfo', {adm1_code: d.id}); }, registerChangeTime: function registerChangeTime(ajaxIdentifier, red, green, blue){ apex.jQuery('#timelinePoints li').click(function(){ var $period = apex.jQuery(this); var clickedTimePeriodYear = apex.jQuery(this).text(); $('#timelinePoints li').removeClass('active'); $period.addClass('active'); germanMapRenderer.updateMapPopulationDisplay(ajaxIdentifier, clickedTimePeriodYear, red, green, blue); //Send a DA event should any further logic want to be introduced apex.event.trigger($period, 'gsm_timeclicked', { year: clickedTimePeriodYear }); }); }, updateMapPopulationDisplay: function updateMapPopulationDisplay(ajaxIdentifier, year, red, green, blue){ var throbber = apex.util.showSpinner(); apex.server.plugin( ajaxIdentifier, { "x01" : year }, { dataType: 'json', success: function(statePcts) { for (state in statePcts){ //Format the number with spacing for every 3 digits //Idea grabbed from: http://stackoverflow.com/questions/16637051/adding-space-between-numbers var formattedPopulation = statePcts[state] .totalPopulation .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, " "); apex.jQuery('.'+state) .attr('style', 'fill: rgba(' + red + ','+ green +','+ blue +',' + statePcts[state].pctOfMax + ')') .attr('title', '<span class="bold">' + statePcts[state].stateName + '\nYear:</span> ' + statePcts[state].year + '\n<span class="bold">Population:</span> ' + formattedPopulation + '\nClick for more info...');//Map region switched with charts) throbber.remove(); } } } ); } };
JavaScript
0.000001
@@ -24,58 +24,8 @@ %7B%0A%0A - width: 960,%0A height: 750,%0A scale: 500,%0A%0A
9e3ff39f25883b497161d6287896b37960d851a6
remove extra console.log
test/mylimiter.test.js
test/mylimiter.test.js
"use strict"; var request = require('supertest'); var express = require('express'); var fs = require('fs'); var path = require('path'); var mysql = require('mysql'); var nconf = require('nconf'); var log = require('ssi-logger'); var DbTestUtil = require('dbtestutil'); var mylimiter = require('../'); // uncomment to display debug output // process.on('log', log.consoleTransport()); // load the database configuration. var options = nconf.argv().env().file({ file: path.join(__dirname, 'db.conf') }).get(); var dbTestUtil = new DbTestUtil(options); before(function (done) { this.timeout(30 * 1000); // 30 seconds (max) dbTestUtil.startLocalMySql(path.join(__dirname, 'mylimiter_load.sql'), done); }); describe('mylimiter', function () { this.timeout(10 * 1000); // 10 seconds (max) per test var app; function doRequest(n, done) { if (n === 0) { done(); return; } request(app) .get('/') .expect('Content-Type', /json/) .expect({ message: 'Hello, World!' }) .expect(200) .end(function () { doRequest(n - 1, done); }); } before(function () { app = express(); app.use(mylimiter({ "database": "example", socketPath: options.mysql_socket || '/tmp/mysqltest.sock' }, 'test', 3, 5)); app.get('/', function (req, res) { res.json({ message: 'Hello, World!' }); }); app.use(function (err, req, res, next) { console.log(err, err.toString()); res.sendStatus(err.status || 500); }); }); it('should limit requests', function (done) { doRequest(3, function () { request(app) .get('/') .expect(429, done); }); }); }); after(function (done) { this.timeout(30 * 1000); // 30 seconds (max) dbTestUtil.killLocalMySql(done); });
JavaScript
0.000013
@@ -1520,54 +1520,8 @@ ) %7B%0A - console.log(err, err.toString());%0A
42c81b78de0961bbef8333f5639e6e661c0e374d
Change cron job frequency
lib/main.js
lib/main.js
'use strict'; const config = require('../config'); const CronJob = require('cron').CronJob; const Fetcher = require('./fetcher'); const Promise = require("bluebird"); class Main { constructor(ds) { let self = this; this.banks = {}; this.banksId = {}; this.prices = {}; this.bestPrices = {}; this.needReloadPrice = false; this.ds = ds; this.fetcher = new Fetcher(self); this.initBankNames(); this.initLastPrices(); // Fetch currecy price every 15 minutes new CronJob('0 */15 * * * *', function() { self.fetchAllCurrency(); }, null, true); } initBankNames() { let self = this; self.ds.bank.findAndCountAll() .then((res) => { if (res.count > 0) { self.initBankMap(res.rows); console.log('Loaded', res.rows.length, 'banks.'); } else { return self.insertBankNames(); } }); } insertBankNames() { let self = this; return this.fetcher.fetchBankNames() .then((names) => { if (names.length) { return self.ds.bank.bulkCreate(names); } }) .then((banks) => { if (banks.length) { self.initBankMap(banks); console.log('Inserted', banks.length, 'banks.'); } else { console.warn('Cannot fetch bank names.'); } }); } initBankMap(banks) { let self = this; banks.forEach(bank => { self.banks[bank.id] = bank.name; self.banksId[bank.name] = bank.id; }); } initLastPrices() { let self = this; self.bestPrices = {}; config.availCurrencies.forEach(c => { self.prices[c] = []; self.bestPrices[c] = {stt: -999, snt: -999, btt: 999, bnt: 999}; }) let sql = 'SELECT DISTINCT ON (code, bank) ' + 'code, bank, stt, snt, btt, bnt ' + 'FROM histories ORDER BY code, bank, ts DESC'; return self.ds.sequelize.query(sql, { type: self.ds.sequelize.QueryTypes.SELECT, raw: true }) .then((prices) => { let count = 0; prices.forEach(price => { self.prices[price.code][price.bank] = price; self.initBestPrices(price); delete price.code; delete price.bank; count++; }); console.log('Loaded', count, 'records.'); }); } initBestPrices(price) { let self = this; let code = this.bestPrices[price.code]; ['stt', 'snt'].forEach((f) => { if (price[f] && price[f] > code[f]) { code[f] = price[f]; code[f + 'b'] = +price.bank; } }); ['btt', 'bnt'].forEach(f => { if (price[f] && price[f] < code[f]) { code[f] = price[f]; code[f + 'b'] = +price.bank; } }); } fetchAllCurrency() { let self = this; self.needReloadPrice = false; return Promise.map(config.availCurrencies, (code) => { return self.insertCurrency(code).delay(1000); }, {concurrency: 1}) .then(function() { console.log('Finished fetch all currencies'); if (self.needReloadPrice) { self.initLastPrices(); } }); } insertCurrency(code) { let self = this; return self.fetcher.fetchCurrency(code) .then((prices) => { if (!prices.length) { return false; } let count = 0; prices.forEach(price => { let bank = self.prices[price.code][price.bank]; if (!bank || (bank.stt !== price.stt || bank.btt !== price.btt || bank.snt !== price.snt || bank.bnt !== price.bnt)) { self.ds.history.create(price); count++; } }); if (count > 0) { self.needReloadPrice = true; console.log('Inserted', count, code, 'records.'); } }); } listCurrency(code) { let self = this; code = code.toUpperCase(); if (config.availCurrencies.indexOf(code) > 0) { return self._listCurrency_sub(code); } else if (code === 'ALL') { let res = ''; config.availCurrencies.forEach(code => { res += self._listCurrency_sub(code); }); return res; } } _listCurrency_sub(code) { let self = this; let fields = ['stt', 'snt', 'btt', 'bnt']; let names = ['電匯銀行買入', '現鈔銀行買入', '電匯銀行賣出', '現鈔銀行賣出']; let price = self.bestPrices[code]; let res = code + '\n'; let i = 0; fields.forEach(f => { let bank = price[f + 'b']; if (bank) { res += names[i] + ': ' + price[f] + ' ' + self.banks[bank] + '\n'; } i++; }); return res; } } module.exports = Main;
JavaScript
0.000001
@@ -495,18 +495,18 @@ e every -15 +60 minutes @@ -529,12 +529,9 @@ ('0 -*/15 +0 * *
65e9b7a91fb0874f703b34989b9a62d9f874eb48
modify login function
app/routes/user.js
app/routes/user.js
var express = require('express'); var mongoose = require('mongoose'); var User = mongoose.model('User'); / * CRUD API */ // POST exports.createUser = function (req, res) { // Create a new user document var user = new User({ name: req.body.name, email: req.body.email, password: req.body.password }); user.save(function (err, user) { if (err) { console.log("error creating new user: " + err); res.send("Error creating new user"); } else { console.log("POST creating new user: " + user.name); res.json(user); } }); }; // GET exports.getUser = function (req, res) { User.findOne ({ 'username': req.params.username }, function (err, user) { if (err) { console.log("Error retrieving user: " + err); res.send("Error retrieving user"); } else { console.log("GET user with ID: " + user._id); res.json(user); } }); }; // PUT exports.updateUser = function(req, res) { var newUsername = req.body.username; var newPassword = req.body.password; var newEmail = req.body.email; User.findById(req.params.id, function (err, user) { if (err) { console.log("error retrieving user: " + err); res.send("Error retrieving user"); } else { if (user.name != newUsername) user.name = newUsername; if (user.password != newPassword) user.password = newPassword; user.save(user, function(err, userId) { if (err) { console.log("error updating the user: " + err); res.send("error updating the user"); } else { console.log("UPDATE user with id: " + userId); req.session.regenerate(function() { req.session.user = user; req.session.success = "Update successful"; res.redirect("/"); }); } }); } }); }; // DELETE exports.deleteUser = function (req, res) { User.findById(req.params.id, function(err, user) { if (err) { console.log("Error finding user to delete: " + err); res.send("Error finding user to delete"); } else { User.remove({ _id: user._id }, function (err) { if (err) { console.log("Error deleting user: " + err); res.send("Error deleting user"); } else { console.log("Succesfully deleted user with id: " + user._id); res.send("Successfully deleted user"); } }); } }); };
JavaScript
0.000001
@@ -938,33 +938,32 @@ th ID: %22 + user. -_ id);%0A
13b45c241a4ec4c5158d52055dd1ac63ef7ea7e9
Update VideoIntro.js (#2010)
website/src/components/homepage/VideoIntro.js
website/src/components/homepage/VideoIntro.js
/** @jsx jsx */ import { jsx } from '@emotion/core'; import { useState } from 'react'; import { mq } from '../../utils/media'; import videoThumbnailPNG from '../../assets/video-thumbnail.png'; const VideoIntro = () => { const [showVideo, setShowVideo] = useState(false); return ( <MainWrapper> <VideoWrapper> <VideoEmbed showVideo={showVideo} onMouseEnter={() => setShowVideo(true)} onClick={() => setShowVideo(true)} /> {!showVideo && <VideoStartButton onClick={() => setShowVideo(true)} />} </VideoWrapper> <VideoCta /> </MainWrapper> ); }; // Implementation components const MainWrapper = ({ children }) => ( <div css={mq({ marginLeft: [0, 0, 0, 50], flex: [1, '0 1 600px'], })} > {children} </div> ); const VideoWrapper = ({ children, ...rest }) => ( <div css={{ backgroundColor: '#f2f2f2', backgroundImage: `url(${videoThumbnailPNG})`, backgroundPosition: 'center 0%', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', position: 'relative', borderRadius: 24, boxShadow: '0 8px 32px rgba(0,0,0,0.2)', '&:before': { content: '""', display: 'block', width: '100%', paddingTop: '56.25%', }, }} {...rest} > <div css={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, display: 'flex', justifyContent: 'center', alignItems: 'center', }} > {children} </div> </div> ); const VideoEmbed = ({ showVideo, ...props }) => ( <div css={{ position: 'absolute', height: '100%', width: '100%', transition: 'opacity 0.3s', opacity: showVideo ? 1 : 0, iframe: { width: '100%', height: '100%', outline: 'none', border: 0, }, }} {...props} > <iframe css={{ display: 'block' }} src="https://egghead.io/lessons/graphql-create-a-hello-world-todo-app-with-keystone-5/embed" frameBorder="0" allowFullScreen /> </div> ); const VideoStartButton = props => ( <button css={{ position: 'relative', height: '64px', width: '64px', display: 'block', content: '" "', boxShadow: '0 24px 48px 0 rgba(0,0,0,0.32)', borderRadius: 32, border: 'none', backgroundColor: '#fff', transition: 'all 0.2s', ':hover': { backgroundColor: '#e7e7e7', }, cursor: 'pointer', }} {...props} > <svg width="26" height="32" xmlns="http://www.w3.org/2000/svg" css={{ marginLeft: 10, marginTop: 6 }} > <path css={{}} d="M1.524.938l23.092 14.21a1 1 0 0 1 0 1.704L1.524 31.062A1 1 0 0 1 0 30.21V1.79A1 1 0 0 1 1.524.938z" fill="#3c90ff" fillRule="evenodd" /> </svg> </button> ); const VideoCta = () => ( <div css={mq({ position: 'relative', marginLeft: [40] })}> <svg css={{ position: 'absolute', top: 0, left: 0 }} width="35" height="36" xmlns="http://www.w3.org/2000/svg" > <g fill="#000" fillRule="nonzero"> <path d="M34.376 36a.657.657 0 0 1-.19-.029c-.281-.088-28.038-9.063-30.184-35.31a.615.615 0 0 1 .574-.658.618.618 0 0 1 .671.562c2.079 25.42 29.046 34.157 29.318 34.244a.61.61 0 0 1 .405.77.625.625 0 0 1-.593.421z" /> <path d="M.623 9a.65.65 0 0 1-.31-.079.57.57 0 0 1-.229-.805L5.01 0l7.695 4.505c.292.17.383.535.202.812a.643.643 0 0 1-.859.192L5.452 1.65 1.168 8.707A.646.646 0 0 1 .623 9z" /> </g> </svg> <p css={{ paddingLeft: 54, paddingTop: 24 }}> Click to see how to get a "Hello World" app up and running in under 3 minutes with the Keystone 5 CLI. </p> </div> ); export { VideoIntro };
JavaScript
0
@@ -3758,19 +3758,13 @@ a %22 -Hello World +To Do %22 ap @@ -3789,17 +3789,17 @@ n under -3 +4 minutes @@ -3807,22 +3807,16 @@ with the -%0A Keyston @@ -3818,16 +3818,22 @@ ystone 5 +%0A CLI.%0A
ccd9b5228c2de94d666d63cc8de79bed5aafee2c
Change discover page query param from pushstate to replaceState
app/routes/discover.js
app/routes/discover.js
import Ember from 'ember'; import ResetScrollMixin from '../mixins/reset-scroll'; export default Ember.Route.extend(ResetScrollMixin, { });
JavaScript
0
@@ -134,10 +134,92 @@ , %7B%0A + queryParams: %7B%0A queryString: %7B%0A replace: true%0A %7D%0A %7D %0A%7D);%0A -%0A
780735f4669d60a3adcc17780e82dbec18f28a6a
test a recursive use of the tool
app/scripts/app.js
app/scripts/app.js
/*global define */ define(['queue', 'splitiscope'], function (queue, split_vis) { 'use strict'; function errorMsg(msg) { console.error(msg); } var x_range = { min : 0, max : 8}, y_range = { min :-4, max : 4}, splits_range = { min : 20, max : 200}, label_list = ['high', 'low'], test_data = {}; test_data.x = _.map(_.range(100),function(value) { return Math.round(Math.random()*(x_range.max - x_range.min) + x_range.min); }); test_data.y = _.map(_.range(100),function(value) { return (Math.random()*(y_range.max - y_range.min) + y_range.min); }); test_data.label = _.map(_.range(100),function(value) { return label_list[Math.round(Math.random() * (label_list.length-1))]; }); test_data.splits_on_x = _.map(_.range(100),function(value) { return Math.round(Math.random()*(splits_range.max - splits_range.min) + splits_range.min); }); var test_split_x = { bins: _.map(_.range(1,9), function(value) { return Math.pow(value+1,-1*Math.abs((value-5)/10))* 100; }), low: x_range.min + 1, binsize: ((x_range.max -1) - (x_range.min +1)) / 10 }; var test_split_y = { bins: _.map(_.range(1,9), function(value) { return Math.pow(value+1,-1*Math.abs((value-5)/10))* 100; }), low: y_range.min + 1, binsize: ((y_range.max -1) - (y_range.min +1)) / 10 }; var Application = { initialize: function(){ // queue() // //.defer(d3.json,'http://glados1.systemsbiology.net:3335/svc/data/analysis/rf-leaves/layouts/2013_02_21_ms_ITMI_DF3b_no_NPF_M_FM_3_hilevel.fm_NB_TermCategory_pred_17_12800_10000_1000_4/fiedler/2013_02_21_ms_ITMI_DF3b_no_NPF_M_FM_3_hilevel.fm_NB_TermCategory_pred_17_12800_10000_1000_4.cutoff.0.0.json') // .defer(function() { return true;}) // .await(function(error, data1){ // if (error) { errorMsg(error);} var splitiscope = split_vis({ radius: 12, margin : { top: 10, left: 10, bottom: 30, right: 30 } }); splitiscope('#plot').data(test_data).splits({x:test_split_x, y: test_split_y}).render(); // }); } }; return Application; });
JavaScript
0.000006
@@ -343,16 +343,35 @@ ata = %7B%7D +,%0A num = 500 ;%0A%0A t @@ -389,35 +389,35 @@ = _.map(_.range( -100 +num ),function(value @@ -439,34 +439,24 @@ return -Math.round (Math.random @@ -535,35 +535,35 @@ = _.map(_.range( -100 +num ),function(value @@ -684,35 +684,35 @@ = _.map(_.range( -100 +num ),function(value @@ -851,19 +851,19 @@ _.range( -100 +num ),functi @@ -986,24 +986,208 @@ );%0A %7D);%0A%0A + test_data.id = _.map(_.range(num),function(value) %7B%0A return String.fromCharCode.apply(this, _.map(_.range(5),function() %7B return Math.random()*26 + 65;%7D));%0A %7D);%0A%0A var test @@ -1323,35 +1323,35 @@ (value-5)/10))* -100 +num ;%0A @@ -1627,19 +1627,19 @@ )/10))* -100 +num ;%0A @@ -1885,16 +1885,17 @@ son, + 'http:// glad @@ -1894,283 +1894,8 @@ p:// -glados1.systemsbiology.net:3335/svc/data/analysis/rf-leaves/layouts/2013_02_21_ms_ITMI_DF3b_no_NPF_M_FM_3_hilevel.fm_NB_TermCategory_pred_17_12800_10000_1000_4/fiedler/2013_02_21_ms_ITMI_DF3b_no_NPF_M_FM_3_hilevel.fm_NB_TermCategory_pred_17_12800_10000_1000_4.cutoff.0.0.json ')%0A @@ -2070,16 +2070,19 @@ + // var spl @@ -2119,24 +2119,27 @@ + // radius: @@ -2158,24 +2158,27 @@ + // margin @@ -2192,32 +2192,35 @@ + // @@ -2281,20 +2281,23 @@ +// + %7D%0A%0A @@ -2310,16 +2310,19 @@ + // %7D);%0A @@ -2342,94 +2342,788 @@ -splitiscope('#plot').data(test_data).splits(%7Bx:test_split_x, y: test_split_y%7D).render( +var plot = function(data) %7B%0A var splitiscope = split_vis(%7B%0A radius: 12,%0A margin : %7B%0A top: 10, left: 10, bottom: 30, right: 30%0A %7D%0A %7D);%0A $('#plot').empty();%0A splitiscope('#plot')%0A .data(data)%0A .splits(%7Bx:test_split_x, y: test_split_y%7D)%0A .on('partition',function(data) %7B%0A plot(data);%0A %7D)%0A .render();%0A %7D;%0A plot(test_data );%0A
7484a14f36e1a1fe91e483e2968eb5d9dbce6e95
Update LTS / release try scenario versions.
config/ember-try.js
config/ember-try.js
'use strict'; // eslint-disable-next-line node/no-unpublished-require const getChannelURL = require('ember-source-channel-url'); module.exports = function () { return Promise.all([ getChannelURL('release'), getChannelURL('beta'), getChannelURL('canary'), ]).then((urls) => { return { useYarn: true, scenarios: [ { name: 'default', bower: {}, npm: { devDependencies: { 'ember-data': 'latest', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'ember-lts-n-1', npm: { devDependencies: { 'ember-source': '~3.12.0', 'ember-data': '~3.16.0', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'ember-lts', npm: { devDependencies: { 'ember-source': '~3.16.0', 'ember-data': '~3.16.0', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'ember-data-packages-latest', npm: { devDependencies: { // TODO: change this back to `latest` once Ember 4 compatibility has landed 'ember-source': '^3.28.0', 'ember-data': null, '@ember-data/store': 'latest', '@ember-data/debug': null, // available in 3.15 '@ember-data/model': 'latest', // not yet droppable (Errors) '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': '^3.0.1', }, }, }, { name: 'ember-data-packages-beta', npm: { devDependencies: { // TODO: change this back to `latest` once Ember 4 compatibility has landed 'ember-source': '^3.28.0', 'ember-data': null, '@ember-data/store': 'beta', '@ember-data/debug': 'beta', '@ember-data/model': 'beta', // not yet droppable (Errors) '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': '^3.0.1', }, }, }, { name: 'ember-data-packages-canary', npm: { devDependencies: { // TODO: change this back to `latest` once Ember 4 compatibility has landed 'ember-source': '^3.28.0', 'ember-data': null, '@ember-data/store': 'canary', '@ember-data/debug': 'canary', '@ember-data/model': 'canary', // not yet droppable (Errors) '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': '^3.0.1', }, }, }, { name: 'release-n-1', npm: { devDependencies: { 'ember-source': '~3.17.0', 'ember-data': '~3.17.0', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'release-channel', npm: { devDependencies: { 'ember-source': urls[0], 'ember-data': 'latest', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'beta-channel', npm: { devDependencies: { 'ember-source': urls[1], 'ember-data': 'beta', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, { name: 'canary-channel', npm: { devDependencies: { 'ember-source': urls[2], 'ember-data': 'canary', '@ember-data/store': null, '@ember-data/debug': null, '@ember-data/model': null, '@ember-data/serializer': null, '@ember-data/adapter': null, '@ember-data/record-data': null, 'ember-inflector': null, }, }, }, ], }; }); };
JavaScript
0
@@ -949,10 +949,10 @@ '~3. -1 2 +4 .0', @@ -976,34 +976,34 @@ mber-data': '~3. -16 +24 .0',%0A @@ -1445,26 +1445,26 @@ ource': '~3. -16 +28 .0',%0A @@ -1492,10 +1492,10 @@ '~3. -16 +28 .0', @@ -3916,26 +3916,26 @@ ource': '~3. -17 +28 .0',%0A @@ -3963,10 +3963,10 @@ '~3. -17 +28 .0',
ce75178f44042f5a230e123808ea4fe59b952200
Upgrade to D3 v3
public/scripts/main.js
public/scripts/main.js
require.config({ paths: { underscore: 'http://documentcloud.github.com/underscore/underscore-min', backbone: 'http://backbonejs.org/backbone-min', jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min', d3: 'http://d3js.org/d3.v2.min', audiolet: 'https://raw.github.com/oampo/Audiolet/master/src/audiolet/Audiolet.min' }, shim: { 'backbone': ['underscore'] } }) requirejs.onError = function(error) { if (error.requireType == 'timeout') { alert("Timeout reached loading the dependencies. Please, try reloading the page.") } else { alert("Unknown error found loading the dependencies. See console for details.") } throw error } require(['chart', 'page-title', 'page-icon', 'pings', 'title', 'user', 'audio', 'controls'], function(Chart, PageTitle, PageIcon, Pings, Title, User, Audio, Controls) { var user = new User var pings = new Pings new Chart(user, pings) new PageTitle(user, pings) new PageIcon(user, pings) new Title(user, pings) var audio = new Audio(user, pings) new Controls(audio) })
JavaScript
0.000004
@@ -273,17 +273,17 @@ org/d3.v -2 +3 .min',%0A
34797887be3d2d9bf734d6df043442375077bbd7
Update test copy
src/desktop/apps/article/components/__tests__/InfiniteScrollNewsArticle.test.js
src/desktop/apps/article/components/__tests__/InfiniteScrollNewsArticle.test.js
import 'jsdom-global/register' import _ from 'underscore' import benv from 'benv' import fixtures from 'desktop/test/helpers/fixtures.coffee' import sinon from 'sinon' import React from 'react' import { shallow } from 'enzyme' import { data as sd } from 'sharify' import { UnitCanvasImage } from 'reaction/Components/Publishing/Fixtures/Components' describe('<InfiniteScrollNewsArticle />', () => { before((done) => { benv.setup(() => { benv.expose({ $: benv.require('jquery'), jQuery: benv.require('jquery') }) sd.APP_URL = 'http://artsy.net' sd.CURRENT_PATH = '/news/artsy-editorial-surprising-reason-men-women-selfies-differently' sd.CURRENT_USER = { id: '123' } done() }) }) after(() => { benv.teardown() }) window.matchMedia = () => { return { matches: false, addListener: () => {}, removeListener: () => {}, } } let rewire = require('rewire')('../InfiniteScrollNewsArticle.tsx') let { InfiniteScrollNewsArticle } = rewire const { Article } = require('reaction/Components/Publishing') const { DisplayCanvas, } = require('reaction/Components/Publishing/Display/Canvas') beforeEach(() => { window.history.replaceState = sinon.stub() }) afterEach(() => { window.history.replaceState.reset() }) it('renders the initial article', () => { const article = _.extend({}, fixtures.article, { layout: 'news', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow( <InfiniteScrollNewsArticle article={article} marginTop={'50px'} /> ) rendered.find(Article).length.should.equal(1) rendered.html().should.containEql('NewsLayout') }) it('fetches more articles at the end of the page', async () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const data = { articles: [ _.extend({}, fixtures.article, { slug: 'foobar', channel_id: '123', id: '678', }), ], } rewire.__set__('positronql', sinon.stub().returns(Promise.resolve(data))) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) await rendered.instance().fetchNextArticles() rendered.update() rendered.find(Article).length.should.equal(2) }) it('#onEnter does not push url to browser if it is not scrolling upwards into an article', () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) rendered.instance().onEnter({}, 0, {}) window.history.replaceState.args.length.should.equal(0) }) it('#onEnter pushes url to browser if it is scrolling upwards into an article', () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) rendered.instance().onEnter( { slug: '123' }, { previousPosition: 'above', currentPosition: 'inside', } ) window.history.replaceState.args[0][2].should.containEql('/news/123') }) it('#onEnter does not push url to browser if it is not scrolling upwards into an article', () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) rendered.instance().onEnter({}, {}) window.history.replaceState.args.length.should.equal(0) }) it('#onLeave does not push url to browser if it is not scrolling downwards into the next article', () => { const rendered = shallow( <InfiniteScrollNewsArticle article={fixtures.article} /> ) rendered.instance().onLeave(0, {}) window.history.replaceState.args.length.should.equal(0) }) it('#onLeave pushes next article url to browser if it is scrolling downwards into the next article', () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const article1 = _.extend({}, fixtures.article, { layout: 'news', slug: '456', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) rendered.setState({ articles: rendered.state('articles').concat(article1) }) rendered.instance().onLeave(0, { previousPosition: 'inside', currentPosition: 'above', }) window.history.replaceState.args[0][2].should.containEql('/news/456') }) it('sets up follow buttons', () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) rendered.state().following.length.should.exist }) it('injects a canvas ad after the sixth article', async () => { const article = _.extend({}, fixtures.article, { layout: 'news', published_at: '2017-05-19T13:09:18.567Z', contributing_authors: [{ name: 'Kana' }], }) const data = { articles: _.times(6, () => { return _.extend({}, fixtures.article, { slug: 'foobar', channel_id: '123', id: '678', }) }), display: { name: 'BMW', canvas: UnitCanvasImage, }, } rewire.__set__('positronql', sinon.stub().returns(Promise.resolve(data))) const rendered = shallow(<InfiniteScrollNewsArticle article={article} />) await rendered.instance().fetchNextArticles() rendered.update() rendered.find(DisplayCanvas).length.should.equal(1) rendered.html().should.containEql('Advertisement by BMW') }) })
JavaScript
0
@@ -6275,21 +6275,17 @@ ql(' -Advertisement +Sponsored by
2c4aeb9f7d085fb5865ca0d292b3d706380f717c
Add default route navigating to timetable instead of only at history start
app/scripts/app.js
app/scripts/app.js
'use strict'; var Backbone = require('backbone'); Backbone.$ = require('jquery'); var Marionette = require('backbone.marionette'); var NUSMods = require('./nusmods'); var NavigationCollection = require('./common/collections/NavigationCollection'); var NavigationView = require('./common/views/NavigationView'); var SelectedModulesController = require('./common/controllers/SelectedModulesController'); var _ = require('underscore'); var config = require('./common/config'); var localforage = require('localforage'); require('backbone.analytics'); require('qTip2'); // Set Backbone.History.initialRoute to allow route handlers to find out if they // were called from the initial route. var loadUrl = Backbone.History.prototype.loadUrl; Backbone.History.prototype.loadUrl = function() { if (!Backbone.History.initialRoute) { Backbone.History.initialRoute = true; } else { Backbone.History.initialRoute = false; // No longer initial route, restore original loadUrl. Backbone.History.prototype.loadUrl = loadUrl; } return loadUrl.apply(this, arguments); }; var App = new Marionette.Application(); App.addRegions({ mainRegion: '.content', navigationRegion: 'nav', selectRegion: '.navbar-form', bookmarksRegion: '.nm-bookmarks' }); var navigationCollection = new NavigationCollection(); var navigationView = new NavigationView({collection: navigationCollection}); App.navigationRegion.show(navigationView); App.reqres.setHandler('addNavigationItem', function (navigationItem) { return navigationCollection.add(navigationItem); }); NUSMods.setConfig(config); NUSMods.generateModuleCodes(); var selectedModulesControllers = []; for (var i = 0; i < 5; i++) { selectedModulesControllers[i] = new SelectedModulesController({ semester: i + 1 }); } App.reqres.setHandler('selectedModules', function (sem) { return selectedModulesControllers[sem - 1].selectedModules; }); App.reqres.setHandler('addModule', function (sem, id, options) { return NUSMods.getMod(id).then(function (mod) { return selectedModulesControllers[sem - 1].selectedModules.add(mod, options); }); }); App.reqres.setHandler('removeModule', function (sem, id) { var selectedModules = selectedModulesControllers[sem - 1].selectedModules; return selectedModules.remove(selectedModules.get(id)); }); App.reqres.setHandler('isModuleSelected', function (sem, id) { return !!selectedModulesControllers[sem - 1].selectedModules.get(id); }); App.reqres.setHandler('displayLessons', function (sem, id, display) { _.each(selectedModulesControllers[sem - 1].timetable.where({ ModuleCode: id }), function (lesson) { lesson.set('display', display); }); }); App.reqres.setHandler('getBookmarks', function (callback) { if (!callback) { return; } localforage.getItem('bookmarks:bookmarkedModules', function (modules) { callback(modules); }); }); App.reqres.setHandler('addBookmark', function (id) { localforage.getItem('bookmarks:bookmarkedModules', function (modules) { if (!_.contains(modules, id)) { modules.push(id); } localforage.setItem('bookmarks:bookmarkedModules', modules); }); }); App.reqres.setHandler('deleteBookmark', function (id) { localforage.getItem('bookmarks:bookmarkedModules', function (modules) { var index = modules.indexOf(id); if (index > -1) { modules.splice(index, 1); localforage.setItem('bookmarks:bookmarkedModules', modules); } }); }); App.on('start', function () { var AppView = require('./common/views/AppView'); var TimetableModuleCollection = require('./common/collections/TimetableModuleCollection'); // header modules require('./modules'); require('./timetable'); // require('ivle'); require('./preferences'); // footer modules require('./about'); require('./help'); require('./support'); new AppView(); // Backbone.history.start returns false if no defined route matches // the current URL, so navigate to timetable by default. if (!Backbone.history.start({pushState: true})) { Backbone.history.navigate('timetable', {trigger: true, replace: true}); } localforage.getItem('bookmarks:bookmarkedModules', function (modules) { if (!modules) { localforage.setItem('bookmarks:bookmarkedModules', []); } }); }); module.exports = App;
JavaScript
0
@@ -3536,98 +3536,181 @@ ');%0A +%0A -var TimetableModuleCollection = require('./common/collections/TimetableModuleCollection' +new Marionette.AppRouter(%7B%0A routes: %7B%0A '*default': function () %7B%0A Backbone.history.navigate('timetable', %7Btrigger: true, replace: true%7D);%0A %7D%0A %7D%0A %7D );%0A%0A @@ -3942,266 +3942,50 @@ %0A%0A -// Backbone.history.start returns false if no defined route matches%0A // the current URL, so navigate to timetable by default.%0A if (!Backbone.history.start(%7BpushState: true%7D)) %7B%0A Backbone.history.navigate('timetable', %7Btrigger: true, replace: true%7D);%0A %7D +Backbone.history.start(%7BpushState: true%7D); %0A%0A
932a454398643da6ef5487b15b8d9aa16a45b9fb
Correct folder referenses
gulpfile.js
gulpfile.js
var gulp = require ('gulp'), uglify = require('gulp-uglify'), rename = require('gulp-rename'); gulp.task('default', function() { console.log('Hello, world!'); }); gulp.task('compressJS', function() { return gulp.src('/app/js/*.js') .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('/app/js/')); });
JavaScript
0.000008
@@ -218,17 +218,16 @@ lp.src(' -/ app/js/* @@ -320,17 +320,16 @@ p.dest(' -/ app/js/'
f0714384988f809e95652f0ce029100ab820c309
Update compound-interest.js
js/compound-interest.js
js/compound-interest.js
$(document).ready(function() { var start; var rate; var period; var invest; var years; if(hasKey('start') && hasKey('rate') && hasKey('period') && hasKey('invest')) { } else { start = 100; rate = 0.01; period = 12; invest = 10; years = 2; } var balance = ['balance', start]; var interest = ['interest', 0]; var deposits = ['deposit', 0]; var time = ['0']; var previous = start; for(var p = 1; p < period * years; p++) { balance.push(previous); interest.push(previous * rate / period); deposits.push(invest); time.push((p / period).toString()); previous = previous + previous * rate / period + invest; } c3.generate({ bindto: '#interest-chart', data: { columns: [balance, interest, deposits], type: 'bar', groups: [['balance', 'interest', 'deposit']], order: null }, axis: { x: {type: 'category', categories: time, label: {text: 'time', position: 'outer-center'}}, y: {label: {text: 'money', position: 'outer-middle'}} } }); });
JavaScript
0.000001
@@ -390,17 +390,21 @@ ime = %5B' -0 +start '%5D;%0A %0A @@ -449,16 +449,17 @@ = 1; p %3C += period
6e5029e8686a78535b428c7f4bf702bba50016e0
add some comments to the math logic of the column computation behavior
lib/util/columnComputation.js
lib/util/columnComputation.js
/* * This file is part of the Sententiaregum project. * * (c) Maximilian Bosch <maximilian@mbosch.me> * (c) Ben Bieler <ben@benbieler.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ 'use strict'; module.exports = { computeAppropriateColumn(items, source) { var result = items.reduce(function (prev, cur) { var curCol = cur.loc.start.column; if (Math.abs(source.getTokenBefore(cur).loc.end.column - curCol) > 1) { return prev; } return Math.max(prev, curCol); }, false); return result; }, computePreviousColumn(source, item) { return source.getTokenBefore(item).loc.end.column + 1; }, computeActualColumn(items, source) { return items.reduce((prev, cur) => Math.max(prev, source.getTokenBefore(cur).loc.end.column + 1), 0); } };
JavaScript
0
@@ -305,16 +305,123 @@ rts = %7B%0A + /**%0A * Computes the appropriate (longest) column that should exist in a set of var declarations.%0A */%0A comput @@ -464,20 +464,14 @@ -var result = +return ite @@ -509,19 +509,21 @@ %7B%0A -var +const curCol @@ -709,32 +709,98 @@ e);%0A -%0A return result;%0A %7D, + %7D,%0A%0A /**%0A * Computes the previous column to compare it with the current column.%0A */ %0A c @@ -899,16 +899,102 @@ 1;%0A %7D, +%0A%0A /**%0A * Computes the actual (expected) column of a set of var declarations.%0A */ %0A compu
7d2a6022d2719c0dfa78c4997aec2422b350d351
add gulp.watch(['src/sass/*.scss', 'src/sass/**/*.scss'] , ['sass']); in gulpfile.js.
gulpfile.js
gulpfile.js
const argv = require('minimist')(process.argv.slice(2)) const openURL = require('opn'); const once = require('once'); const gulp = require('gulp'); const sass = require('gulp-sass'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename'); const streamify = require('gulp-streamify'); const source = require('vinyl-source-stream'); const budo = require('budo'); const browserify = require('browserify'); const resetCSS = require('node-reset-scss').includePath; const garnish = require('garnish'); const babelify = require('babelify'); const reactify = require('reactify'); const autoprefixer = require('gulp-autoprefixer'); const errorify = require('errorify'); const entry = './src/js/index.js'; const outfile = 'bundle.js'; //our CSS pre-processor gulp.task('sass', function () { gulp.src('./src/sass/main.scss') .pipe(sass({ errLogToConsole: true, outputStyle: argv.production ? 'compressed' : undefined, includePaths: [resetCSS] })) .pipe(autoprefixer({ browsers: ['last 2 versions'], cascade: false })) .pipe(gulp.dest('./app')) }); //the development task gulp.task('watch', ['sass'], function (cb) { //watch SASS gulp.watch('src/sass/*.scss', ['sass']); var ready = function () { }; var pretty = garnish(); pretty.pipe(process.stdout); //dev server budo(entry, { serve: 'bundle.js', //end point for our <script> tag stream: pretty, //pretty-print requests live: true, //live reload & CSS injection verbose: true, //verbose watchify logging dir: 'app', //directory to serve transform: [babelify, reactify], //browserify transforms plugin: errorify //display errors in browser }) .on('exit', cb) .on('connect', function (ev) { ready = once(openURL.bind(null, ev.uri)) }) .once('update', function () { //open the browser if (argv.open) { ready() } }) }); //the distribution bundle task gulp.task('bundle', ['sass'], function () { var bundler = browserify(entry, {transform: [babelify, reactify]}) .bundle(); return bundler .pipe(source('index.js')) .pipe(streamify(uglify())) .pipe(rename(outfile)) .pipe(gulp.dest('./app')) });
JavaScript
0
@@ -1261,16 +1261,17 @@ p.watch( +%5B 'src/sas @@ -1280,16 +1280,40 @@ *.scss', + 'src/sass/**/*.scss'%5D , %5B'sass'
732dee451bb9304e039abdec291457639ad7163e
Support Steal 1.0
lib/main.js
lib/main.js
var assert = require("assert"); var cli = require("./cordovacli")(); var Promise = require("es6-promise").Promise; var extend = require("xtend"); var path = require("path"); var fs = require("fs-extra"); var asap = require("pdenodeify"); var copy = asap(fs.copy); var glob = asap(require("multi-glob").glob); var slice = Array.prototype.slice; // Allow aliasing certain options to make consistent with steal-nw var aliases = { buildDir: "path" }; module.exports = function(cordovaOptions) { setAliases(cordovaOptions); var stealCordova = {}; stealCordova.init = function(opts){ return runCli(opts, { command: ["create", "platform", "plugin"] }); }; // Only initialize if it hasn't already been. stealCordova.initIfNeeded = function(opts){ var buildPath = (opts && opts.path) || cordovaOptions.path; assert(!!buildPath, "Path needs to be provided"); var p = path.resolve(buildPath); return new Promise(function(resolve){ fs.exists(p, function(doesExist){ if(doesExist) { resolve(); } else { stealCordova.init(opts).then(function() { resolve(); }); } }); }); }; stealCordova.copyProductionFiles = function(bundlesPath){ var index = path.resolve(cordovaOptions.index); var dest = path.resolve(cordovaOptions.path, "www/"); var files = cordovaOptions.files || cordovaOptions.glob || []; files.unshift(bundlesPath); return glob(files).then(function(files){ var copies = files.map(function(file){ return copy(file, destPath(file)); }); // copy the index.html file copies.push(copy(index, path.join(dest, "index.html"))); return Promise.all(copies); }); function destPath(p){ return path.join(dest, path.relative(process.cwd(), p)); } }; stealCordova.platform = function(opts){ return runCli(opts, { command: ["platform"] }); }; stealCordova.build = function(buildResult){ return stealCordova.initIfNeeded().then(function(){ var bundlesPath = buildResult.configuration.bundlesPath; return stealCordova.copyProductionFiles(bundlesPath); }).then(function(){ return runCli({}, { command: ["build"], args: ["--release"] }); }); }; stealCordova.android = { emulate: function(opts){ return runCli(opts, { command: "emulate", platforms: ["android"] }); }, run: function(opts){ } }; stealCordova.ios = { emulate: function(opts){ return runCli(opts, { command: "emulate", platforms: ["ios"] }); } }; return stealCordova; function runCli(/* opts */){ var args = slice.call(arguments); args.unshift(cordovaOptions); args.unshift({}); var opts = extend.apply(null, args); var promise = cli(opts); return promise; } }; function setAliases(options){ Object.keys(aliases).forEach(function(alias){ var opt = aliases[alias]; if(options[alias]) { options[opt] = options[alias]; delete options[alias]; } }); }
JavaScript
0
@@ -1939,27 +1939,22 @@ %0A%09%09%09var -bundlesPath +config = build @@ -1973,16 +1973,57 @@ guration +;%0A%09%09%09var destPath = config.dest %7C%7C config .bundles @@ -2071,23 +2071,20 @@ onFiles( -bundl +d es +t Path);%0A%09
cc389060ddeab19cc088906e74dd8c6604727fdc
Update gulpfile.js
gulpfile.js
gulpfile.js
var gulp = require('gulp') , browserify = require('browserify') , transform = require('vinyl-transform') , sass = require('gulp-sass') , deploy = require('gulp-gh-pages') , concat = require('gulp-concat') , uglify = require('gulp-uglify') , minifycss = require('gulp-minify-css') , imagemin = require('gulp-imagemin') , pngquant = require('imagemin-pngquant'); // Browserify Task gulp.task('browserify', function () { var browserified = transform(function (filename) { var b = browserify(filename); return b.bundle(); }); return gulp.src(['src/js/main.js']) .pipe(browserify) .pipe(uglify()) .pipe(gulp.dest('js')); }); // Sass Task gulp.task('sass', function () { gulp.src('src/_sass/main.scss') .pipe(sass({style: 'expanded'})) .pipe(gulp.dest('css')) .pipe(minifycss()) .pipe(gulp.dest('css')); }); // Imagemin gulp.task('imagemin', function () { gulp.src('src/_img/*') .pipe(imagemin({ progressive: true, use: [pngquant()] })) .pipe(gulp.dest('img')); }); // Watch Task gulp.task('watch', function () { gulp.watch('src/**/*.*', ['default']); }); // Default Task gulp.task('default', ['browserify', 'sass']); // Deploy task gulp.task('deploy', function () { gulp.src('_site/**/*') .pipe(deploy()); });
JavaScript
0.000001
@@ -373,16 +373,35 @@ ant');%0A%0A +// TODO: FIX THIS!%0A // Brows @@ -407,24 +407,27 @@ serify Task%0A +// gulp.task('b @@ -452,16 +452,19 @@ on () %7B%0A +// var br @@ -508,16 +508,19 @@ name) %7B%0A +// var @@ -545,16 +545,19 @@ ename);%0A +// retu @@ -575,15 +575,21 @@ ();%0A +// %7D);%0A%0A +// re @@ -622,16 +622,19 @@ n.js'%5D)%0A +// .pip @@ -647,16 +647,19 @@ serify)%0A +// .pip @@ -666,24 +666,27 @@ e(uglify())%0A +// .pipe(gu @@ -697,24 +697,27 @@ est('js'));%0A +// %7D);%0A%0A// Sass
f738b57c36cc3418b1f859178ec5550142d52ccd
add responsive padding to main container, styling tweaks
app/styles/home.js
app/styles/home.js
export default { container: ({ theme }) => { return { display: 'flex', flexDirection: 'column', alignItems: 'center', alignSelf: 'center', height: '100%', paddingTop: theme.space[1], paddingLeft: theme.space[6], paddingRight: theme.space[6], ':before': { [`@media (max-width: ${theme.breakpoints.desktop})`]: { content: '""', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', opacity: .6, zIndex: -1, backgroundColor: theme.colors.canvas, backgroundImage: 'url("/images/cobuy-bg-sml-1080.jpg")', backgroundSize: 'cover' }, [`@media (min-width: ${theme.breakpoints.desktop})`]: { content: '""', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', opacity: .6, zIndex: -1, backgroundColor: theme.colors.canvas, backgroundImage: 'url("/images/cobuy-bg-lrg-1440.jpg")', backgroundSize: 'cover' } } } }, titleContainer: ({ theme }) => { return { marginBottom: theme.space[1] } }, // Note for SR: // Another way of accessing logo and primary1 directly // ({ theme: { fonts: { logo }, colors: { primary1 } } }) // applied e.g. // fontFamily: logo // color: primary1 titleText: ({ theme }) => ({ fontFamily: theme.fonts.logo, fontSize: theme.fontSizes[12], color: theme.colors.text, margin: theme.space[0], textAlign: 'center' }), taglineText: ({ theme }) => ({ fontFamily: theme.fonts.primary, fontSize: theme.fontSizes[5], color: theme.colors.text, fontWeight: theme.fontWeights.bold, textAlign: 'center' }), bodyContainer: ({ theme }) => { return { } }, bodyText: ({ theme }) => ({ fontFamily: theme.fonts.primary, fontSize: theme.fontSizes[3], color: theme.colors.text }), buttonsContainer: ({ theme }) => { return { display: 'flex', justifyContent: 'space-around', paddingLeft: theme.space[4], paddingRight: theme.space[4] } }, buttonText: ({ theme }) => ({ textTransform: 'capitalize', color: theme.colors.alternateText }) }
JavaScript
0
@@ -218,12 +218,310 @@ ace%5B -1 +3 %5D,%0A + paddingBottom: theme.space%5B3%5D,%0A %5B%60@media (max-width: $%7Btheme.breakpoints.tabletWide%7D)%60%5D: %7B%0A paddingLeft: theme.space%5B5%5D,%0A paddingRight: theme.space%5B5%5D%0A %7D,%0A %5B%60@media (min-width: $%7Btheme.breakpoints.tabletWide%7D) and (max-width: $%7Btheme.breakpoints.desktop%7D)%60%5D: %7B%0A @@ -547,24 +547,26 @@ e.space%5B6%5D,%0A + paddin @@ -579,32 +579,386 @@ : theme.space%5B6%5D +%0A %7D,%0A %5B%60@media (min-width: $%7Btheme.breakpoints.desktop%7D) and (max-width: $%7Btheme.breakpoints.desktopWide%7D)%60%5D: %7B%0A paddingLeft: theme.space%5B8%5D,%0A paddingRight: theme.space%5B8%5D%0A %7D,%0A %5B%60@media (min-width: $%7Btheme.breakpoints.desktopWide%7D)%60%5D: %7B%0A paddingLeft: theme.space%5B10%5D,%0A paddingRight: theme.space%5B10%5D%0A %7D ,%0A ':before @@ -2443,19 +2443,22 @@ %7D),%0A b -ody +uttons Containe @@ -2498,114 +2498,209 @@ -%7D%0A %7D,%0A bodyText: (%7B theme %7D) =%3E (%7B%0A fontFamily: theme.fonts.primary,%0A fontSize: theme.fontSizes%5B3%5D + display: 'flex',%0A justifyContent: 'space-around',%0A paddingTop: theme.space%5B1%5D,%0A paddingBottom: theme.space%5B1%5D%0A %7D%0A %7D,%0A buttonText: (%7B theme %7D) =%3E (%7B%0A textTransform: 'capitalize' ,%0A @@ -2721,17 +2721,26 @@ .colors. -t +alternateT ext%0A %7D) @@ -2736,38 +2736,35 @@ teText%0A %7D),%0A b -uttons +ody Container: (%7B th @@ -2821,109 +2821,59 @@ -justifyContent: 'space-around',%0A paddingLeft: theme.space%5B4%5D,%0A paddingRight: theme.space%5B4%5D +flexDirection: 'column',%0A alignItems: 'center' %0A @@ -2875,37 +2875,35 @@ '%0A %7D%0A %7D,%0A b -utton +ody Text: (%7B theme %7D @@ -2918,35 +2918,73 @@ -textTransform: 'capitalize' +fontFamily: theme.fonts.primary,%0A fontSize: theme.fontSizes%5B3%5D ,%0A @@ -3001,33 +3001,24 @@ heme.colors. -alternateT +t ext%0A %7D)%0A%7D%0A
5b70fd9b109f9feee0234ae944af6fcf447f8dcf
Remove console statement
server/ducks/devices.js
server/ducks/devices.js
/* eslint new-cap:0, no-console:0 */ /* globals setTimeout */ import { HueApi, lightState } from 'node-hue-api'; import { config } from 'environment'; import { handleAction, registerAccessories, flashAuthorized, rain, colorGenerators, toggleLights } from 'utils'; import { DESK_LIGHT_STRIP_PRIMARY, DESK_LIGHT_STRIP_PRIMARY_LENGTH } from 'constants'; import { BATCH_UNIFIED_COMMANDS } from './unified'; export const EMIT_REGISTER_DESK_ACCESSORIES = 'EMIT_REGISTER_DESK_ACCESSORIES'; export const EMIT_REGISTER_BRIDGE = 'EMIT_REGISTER_BRIDGE'; export const EMIT_LR_LIGHT_ON = 'EMIT_LR_LIGHT_ON'; export const EMIT_LR_LIGHT_OFF = 'EMIT_LR_LIGHT_OFF'; export const EMIT_LR_LIGHT_TOGGLE = 'EMIT_LR_LIGHT_TOGGLE'; export const EMIT_LR_LIGHT_SOFT = 'EMIT_LR_LIGHT_SOFT'; export const EMIT_DR_LIGHT_ON = 'EMIT_DR_LIGHT_ON'; export const EMIT_DR_LIGHT_OFF = 'EMIT_DR_LIGHT_OFF'; export const EMIT_DR_LIGHT_TOGGLE = 'EMIT_DR_LIGHT_TOGGLE'; export const EMIT_DESK_MIC_VALUE_CHANGE = 'EMIT_MIC_VALUE_CHANGE'; export const EMIT_BUZZ = 'EMIT_BUZZ'; export const EMIT_BUZZ_RESPONSE = 'EMIT_BUZZ_RESPONSE'; export const EMIT_PC_ON = 'EMIT_PC_ON'; export const EMIT_PC_RESPONSE = 'EMIT_PC_RESPONSE'; export const EMIT_SOUND_COM = 'EMIT_SOUND_COM'; export const EMIT_SOUND_COM_RESPONSE = 'EMIT_SOUND_COM_RESPONSE'; export const EMIT_REGISTER_DEADBOLT_ACCESSORIES = 'EMIT_REGISTER_DEADBOLT_ACCESSORIES'; const initialState = { ports: config.ports, lightState, hueUserId: config.users[Object.keys(config.users)[0]], isDeadboltLocked: false, isDoorClosed: false }; const devicesReducer = (state = initialState, action) => { const reducers = { [EMIT_REGISTER_DESK_ACCESSORIES]() { const newState = registerAccessories(state, action.accessories); rain.start(newState[DESK_LIGHT_STRIP_PRIMARY], DESK_LIGHT_STRIP_PRIMARY_LENGTH); return newState; }, [EMIT_REGISTER_DEADBOLT_ACCESSORIES]() { return registerAccessories(state, action.accessories); }, [EMIT_REGISTER_BRIDGE]() { return { ...state, hueBridge: new HueApi(action.bridge.ipaddress, state.hueUserId) }; }, [EMIT_DR_LIGHT_ON]() { state.hueBridge.setLightState(1, state.lightState.create().on()); return state; }, [EMIT_DR_LIGHT_OFF]() { state.hueBridge.setLightState(1, state.lightState.create().off()); return state; }, [EMIT_LR_LIGHT_ON]() { state.hueBridge.setLightState(2, state.lightState.create().on()); state.hueBridge.setLightState(2, state.lightState.create().bri(255)); return state; }, [EMIT_LR_LIGHT_OFF]() { state.hueBridge.setLightState(2, state.lightState.create().off()); return state; }, [EMIT_LR_LIGHT_SOFT]() { state.hueBridge.setLightState(2, state.lightState.create().on()); state.hueBridge.setLightState(2, state.lightState.create().bri(100)); return state; }, [EMIT_DR_LIGHT_TOGGLE]() { toggleLights(state, 1); }, [EMIT_LR_LIGHT_TOGGLE]() { toggleLights(state, 2); }, [EMIT_BUZZ]() { flashAuthorized(state[DESK_LIGHT_STRIP_PRIMARY], colorGenerators.green, () => { rain.start(state[DESK_LIGHT_STRIP_PRIMARY], DESK_LIGHT_STRIP_PRIMARY_LENGTH); }); }, [EMIT_PC_ON]() { flashAuthorized(state[DESK_LIGHT_STRIP_PRIMARY], colorGenerators.green, () => { rain.start(state[DESK_LIGHT_STRIP_PRIMARY], DESK_LIGHT_STRIP_PRIMARY_LENGTH); }); }, [BATCH_UNIFIED_COMMANDS]() { const { id, body } = action.payload; console.log(id) if (id === config.id && body.followup_events) { body.followup_events.forEach((event) => { if (event.color && colorGenerators[event.color]) { flashAuthorized(state[DESK_LIGHT_STRIP_PRIMARY], colorGenerators[event.color], () => { rain.start(state[DESK_LIGHT_STRIP_PRIMARY], DESK_LIGHT_STRIP_PRIMARY_LENGTH); }); } handleAction(state, { type: event.type }, reducers); }); } } }; return handleAction(state, action, reducers); }; export default devicesReducer;
JavaScript
0.000006
@@ -3627,23 +3627,8 @@ ad;%0A -console.log(id) %0A
6d9ca43c1ef7c137d56ded2edee38e5762fe9acf
Fix paths in cases of building separate targets for Windows OS
lib/make.js
lib/make.js
'use strict'; var VM = require('vm'), Q = require('q'), QFS = require('q-io/fs'), INHERIT = require('inherit'), APW = require('apw'), PATH = require('./path'), UTIL = require('util'), BEMUTIL = require('./util'), REGISTRY = require('./nodesregistry'), LOGGER = require('./logger'), reqf = require('reqf'); exports.DEFAULT_WORKERS = 10; exports.APW = INHERIT(APW, { findAndProcess: function(targets) { if (!Array.isArray(targets)) targets = [targets]; // Strip trailing slashes from target names // See https://github.com/bem/bem-tools/issues/252 var re = new RegExp(PATH.dirSep + '$'); targets = targets.map(function(t) { return t.replace(re, ''); }); var _this = this, foundNodes = targets.map(function(t) { return _this.findNode(t); }); return Q.all(foundNodes) .fail(function(err) { if (typeof err === 'string') return; return Q.reject(err); }) .then(function() { return _this.process(targets); }); }, // TODO: move node introspection logic to the node in arch findNode: function(id, head, tail) { head = head || ''; tail = tail || id; if (this.arch.hasNode(id)) return Q.resolve(id); if (head === id) return Q.reject(UTIL.format('Node "%s" not found', id)); var parts = tail.split(PATH.dirSep), p = parts.shift(); head = (head? [head, p] : [p]).join(PATH.dirSep); tail = parts.join(PATH.dirSep); var _this = this, magicHead = head + '*'; if (!this.arch.hasNode(magicHead)) { return this.findNode(id, head, tail); } return this.process(magicHead).then(function() { return _this.findNode(id, head, tail); }); } }, { Workers: INHERIT(APW.Workers, { start: function(plan) { /* jshint -W109 */ LOGGER.finfo("[i] Going to build '%s' [%s]", plan.getTargets().join("', '"), plan.getId()); /* jshint +W109 */ return this.__base(plan); } }) }); exports.createArch = function(opts) { var arch = new APW.Arch(), DefaultArch = require('./default-arch'), rootMakefile = PATH.join(opts.root, '.bem', 'make.js'); return QFS.exists(rootMakefile) .then(function(exists) { /* jshint -W109 */ LOGGER.fsilly("File '%s' %s", rootMakefile, exists? 'exists' : "doesn't exist"); /* jshint +W109 */ if (exists) return include(rootMakefile); }) .then(function() { return new (DefaultArch.Arch)(arch, opts).alterArch(); }); }; function getPathResolver(base) { return function(path) { return path.match(/^\./)? PATH.resolve(PATH.dirname(base), path) : path; }; } function getIncludeFunc(resolvePath) { return function(path) { return include(resolvePath(path)); }; } function include(path) { return evalConfig(require('fs').readFileSync(path, 'utf8'), path); } function evalConfig(content, path) { /* jshint -W109 */ LOGGER.fsilly("File '%s' read, evaling", path); var resolvePath = getPathResolver(path); VM.runInNewContext( content, BEMUTIL.extend({}, global, { MAKE: REGISTRY, module: null, __filename: path, __dirname: PATH.dirname(path), require: reqf(path, module), include: getIncludeFunc(resolvePath) }), path); LOGGER.fsilly("File '%s' evaled", path); /* jshint +W109 */ }
JavaScript
0.000002
@@ -501,16 +501,60 @@ gets%5D;%0A%0A + targets = replaceSlashes(targets);%0A%0A @@ -3792,12 +3792,186 @@ +W109 */%0A%0A%7D%0A +%0Afunction replaceSlashes(targets) %7B%0A return require('path').sep === '%5C/' ? targets : targets.map(function (target) %7B%0A return target.replace(/%5C//g, '%5C%5C');%0A %7D);%0A%7D%0A
7ed752ca4705fa3afc253f4c9e7c9ba9c16dcb60
fix cidr code ... apparently brackets help
generate.js
generate.js
config = require ("./config") security_group_counter = 0 cidr_port = [] config.ports.forEach (function (port) { config.list.forEach (function (cidr) { cidr_port.push ({ "cidr": cidr.indexOf ("/") < 0 === true ? "/32" : "", "port": port }) }) }) cidr_port.forEach (function (value, index, array) { cidr = value.cidr port = value.port if (index % config.max_security_group_size == 0) { this_security_group_name = config.security_group_name + " " + ++security_group_counter console.log (" - name: " + this_security_group_name) console.log (" ec2_group:") console.log (" name: " + this_security_group_name) console.log (" description: " + this_security_group_name) console.log (" vpc_id: " + config.vpc_id) console.log (" region: " + config.vpc_region) console.log (" rules:") } console.log (" - proto: tcp") console.log (" from_port: " + port) console.log (" to_port: " + port) console.log (" cidr_ip: " + cidr) })
JavaScript
0
@@ -188,16 +188,24 @@ r%22: cidr + + (cidr .indexOf @@ -236,16 +236,17 @@ 32%22 : %22%22 +) ,%0A
0e5384729ea1ab5b2852c22807fb6befb7230dd6
Fix port on Heroku which is not supported.
server/lib/seo/index.js
server/lib/seo/index.js
/** * Serve up "plain html" versions of angular app pages for search crawlers AND facebook crawlers. * * This is needed since Angular apps are rendered entirely by Javascript, and crawlers don't * execture jsavascipt, so they see blank pages. * * What we do to get around this is: * - watch for signs of well behaved crawlers, which is having '?_escaped_fragment_=' in req.params * - sping up a "phantom" browser on the server * - visit the page requested, which is indicated by _escaped_fragment_ * - grab the html from the page * - remove the ng-app part, preventing the app from starting up again! (thanks see below) * - send the html back the browser * * This will let a crawler access content normally generated by javascript. * Especially OG:Meta data!!! * * @see https://github.com/stephanebisson/ngseo/blob/master/src/ngseo.js * the above middleware would work great if not for the bug in phantom 1.9.2 which * causes errors due to unsupported * * @see https://github.com/ariya/phantomjs/wiki/API-Reference-WebPage#wiki-webpage-evaluate * * @note This script should be non-blocking... meaning it will not tie up the main server while the * html page is generated. * * */ var express = require('express'); var app = module.exports = express(); var renderer = require('./renderer'); var grunt = require('grunt'); // use this function as middlware app.use(function(req, res, next) { // if we have no escaped fragement, move onto the next process if (!req.query || !req.query._escaped_fragment_) { // var url2 = '#!' + req.path; // grunt.tasks(['snapshot'], {url: url2}, function(e) { // grunt.log("done running grunt task " + e); // }); return next(); } var frag = req.query._escaped_fragment_; // we do have a fragment, so lets assemble a URL that we can access within our app // basically we are reverse engineering the _escaped_fragment_ // to figure out which url the crawler hit in the first place. var url = (req.secure ? 'https' : 'http') + '://'; url += req.host + ':' + app.get('port') + req.path; // remove the first slash, if present // this gives us some flexability in our templates // and makes this function a little less picky. if(frag.charAt(0) === '/') { frag = frag.slice(1,frag.length); } url += '#!/' + frag; console.log(url); /* grunt.tasks(['snapshot'], {url: url}, function(e) { console.log("done running grunt task " + e); res.send(e); }); */ // start our page renderer renderer.render(url, function(html) { //console.log('Callback has been called'); //console.log(html); res.send(html); }); });
JavaScript
0
@@ -2056,16 +2056,48 @@ q.host + + req.path;%0A //url += req.host + ':' + a @@ -2644,26 +2644,24 @@ lled');%0A -// console.log(
3db939bc1d3b57263613551882c00170f9f8fdd3
fix langSuffix
generate.js
generate.js
// Before running: npm install // npm install -g nodemon var YAML = require('yamljs'); var Mustache = require('mustache'); var glob = require('glob'); var path = require('path'); var fs = require('fs'); const defaultLang = "uk"; const languagesPath = "templates/languages/*.yml"; const pagesPath = "templates/pages/*.tpl"; const partialsPath = "templates/partials/*.tpl"; const outputDir = "public"; // Load languages var languages = glob.sync(languagesPath).reduce(function(acc, fileName){ var langName = path.basename(fileName, ".yml"); var langData = fs.readFileSync(fileName).toString("utf-8"); try { var langObject = YAML.parse(langData); acc[langName] = langObject; } catch(e) { console.error("Problem parsing file", fileName) console.error(e) } return acc; }, {}) // Load partials var partials = glob.sync(partialsPath).reduce(function(acc, fileName){ var partialName = path.basename(fileName, ".tpl"); var partialData = fs.readFileSync(fileName).toString("utf-8"); acc[partialName] = partialData; return acc; }, {}) // Render pages glob.sync(pagesPath).forEach(function(fileName){ var pageName = path.basename(fileName, ".tpl"); var pageData = fs.readFileSync(fileName).toString("utf-8"); for (var lang in languages) { var view = { langName: lang, langSuffix: "_" + lang, pageName: pageName, }; view.__proto__ = languages[lang]; view["lang_" + lang] = true; view["page_" + pageName] = true; var output = Mustache.render(pageData, view, partials); var outputPageName = pageName + "_" + lang + ".html"; if (lang == defaultLang) { outputPageName = pageName + ".html"; view.langSuffix = "" } var fileDestination = outputDir + "/" + outputPageName; console.log("writing", fileDestination); fs.writeFileSync(fileDestination, output); } }); // Dev http server if (process.argv[2]) { var port = parseInt(process.argv[2], 10); var express = require('express'); var app = express(); app.use(express.static(outputDir)); app.listen(port, function () { console.log('Dev server listening on http://localhost:%d', port); }); }
JavaScript
0.000003
@@ -1502,68 +1502,8 @@ e;%0A%0A - var output = Mustache.render(pageData, view, partials);%0A @@ -1665,16 +1665,76 @@ %0A %7D%0A%0A + var output = Mustache.render(pageData, view, partials);%0A var
12b08dc3ef9ce0fdb286f913ac71be7496bd0ce4
Remove race condition on gulp task.
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var fs = require('fs'); var _ = require('underscore'); var wrapper = require('gulp-module-wrapper'); var insert = require('gulp-insert'); var del = require('del'); var eol = require('gulp-eol'); var gutil = require('gulp-util'); var jshint = require('gulp-jshint'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var notify = require('gulp-notify'); var concat = require('gulp-concat'); var replace = require('gulp-replace'); var jasmine = require('gulp-jasmine'); var JasmineConsoleReporter = require('jasmine-console-reporter'); gulp.task('default', ['build']); gulp.task('test', ['build'], function () { return gulp.src("test/tests.js").pipe(jasmine({ "stopSpecOnExpectationFailure": false, "random": false, reporter: new JasmineConsoleReporter() })); }); gulp.task('clean', function(cb) { del(['dist']); cb(); }); gulp.task('build', ['clean'], function() { var json = JSON.parse(fs.readFileSync('package.json', 'utf8')); var version = json.version; var code = gulp.src('src/Filter.js').pipe(concat('filter.js')); var amdcode = gulp.src('src/Filter.js').pipe(concat('filter.js')); var cjscode = gulp.src('src/Filter.js').pipe(concat('filter.js')); //JSHint gutil.log('Running JSHint'); gulp.src('src/Filter.js').pipe(jshint()).pipe(jshint.reporter('default')); var pipes = [code, amdcode, cjscode]; _.each(pipes, function(value) { //Update the version number from the source file value = value.pipe(replace('{{VERSION}}', version)); }); var EOL = '\n'; var noamd = code .pipe(insert.prepend("var Filter = {};" + EOL + "(function() {" + EOL + EOL)) .pipe(insert.append(EOL + EOL + "})();")) .pipe(eol()) .pipe(rename('filter-no-amd.js')) .pipe(gulp.dest('dist')) .pipe(rename('filter-no-amd.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')); var amd = amdcode.pipe(insert.prepend("var Filter = {};" + EOL)) .pipe(wrapper({ name: false, deps: ['jquery', 'underscore', 'moment'], args: ['$', '_', 'moment'], exports: 'Filter' })) .pipe(eol()) .pipe(rename('filter-amd.js')) .pipe(gulp.dest('dist')) .pipe(rename('filter-amd.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')) .pipe(notify({ message: 'Scripts task complete' })); var cjs = cjscode.pipe(insert.prepend("var Filter = {};" + EOL)) .pipe(wrapper({ name: false, deps: ['jquery', 'underscore', 'moment'], args: ['$', '_', 'moment'], exports: 'Filter', type: 'commonjs' })) .pipe(eol()) .pipe(rename('filter-commonjs.js')) .pipe(gulp.dest('dist')) .pipe(rename('filter-commonjs.min.js')) .pipe(uglify()) .pipe(gulp.dest('dist')) .pipe(notify({ message: 'Scripts task complete' })); return cjs; });
JavaScript
0
@@ -927,17 +927,46 @@ t'%5D) -;%0A cb( +.then(function() %7B%0A cb();%0A %7D );%0A%7D
094b2d5844f95f21bb4d4d3d93ca7180e538cbae
Fix issue placement.
server/routes/heroku.js
server/routes/heroku.js
var express = require('express'); var router = express.Router(); var request = require('request'); var slackBot = require('slack-bot')(process.env.URL); router.get('/', function(req, res) { if (req.query.secret !== process.env.SECRET) { res.sendStatus(404).end(); } else { request({ url: 'https://status.heroku.com/api/v3/current-status', method: 'GET' }, function(error, response, body) { var result = JSON.parse(body); var color; var issues = []; if (result.status.Production === 'green' && result.status.Development === 'green') { color = 'good'; result.issues.forEach(function(issue) { issues.push(issue.title); }); } else { color = 'danger'; } slackBot.send({ channel: '#hackers', username: 'Heroku', icon_emoji: ':heroku:', attachments: [{ fallback: 'Heroku Status', color: color, title: 'Heroku Status', title_link: 'https://status.heroku.com/', fields: [{ title: 'Production', value: result.status.Production === 'green' ? 'Operational' : 'Experiencing issues', short: 'true' }, { title: 'Issues', value: issues ? issues.join(', ') : 'No issues', short: 'true' }, { title: 'Development', value: result.status.Development === 'green' ? 'Operational' : 'Experiencing issues', short: 'true' }] }] }, function() { res.end(); }); }); } }); module.exports = router;
JavaScript
0
@@ -604,16 +604,57 @@ 'good'; +%0A %7D else %7B%0A color = 'danger'; %0A%0A @@ -754,72 +754,56 @@ %7D - else %7B%0A color = 'danger';%0A %7D%0A%0A slackBot.send(%7B +%0A%0A slackBot.send(%7B%0A text: undefined, %0A
ebb81a4063c18a489041f0d6f834e98a0a32ed85
return jobId on image upload/submit
server/routes/images.js
server/routes/images.js
var debug = require('debug')('server:routes:images'); var config = require('../config.json'); var Promise = require('bluebird'); var router = require('express').Router(); var jsonParser = require('body-parser').json(); //upload related var Busboy = require('busboy'); var fs = require('fs'); var request = require('request'); var HTTPError = require('node-http-error'); //model var submittedFile = require('../models/submittedFile.js'); var image = require('../models/image.js'); //handle image upload router.post('/upload', function (req, res, next) { debug('/upload'); //prepare busboy for upload var busboy = new Busboy({ headers: req.headers, limits: { files: config.upload.maxFiles, fileSize: config.upload.sizeLimit } }); //feed request to busboy req.pipe(busboy); //init image var uploadedImage = new submittedFile(); uploadedImage.uploaderIP = req.ip || req.connection.remoteAddress; //to check if file limit is reached var fileLimitReached = false; //file handler busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { debug('on file', fieldname, filename, encoding, mimetype); uploadedImage.file = file; uploadedImage.originalFileName = filename; //write upload to tmp folder var tmpFile = fs.createWriteStream(uploadedImage.tmpPath); file.pipe(tmpFile); }); //file limit handler busboy.on('filesLimit', function () { debug('on file limit'); uploadedImage.unlink(); fileLimitReached = true; }); //upload is done busboy.on('finish', function () { //make sure to avoid sending resp > once if( res.headersSent ) { return; } debug('on upload finish', res.headersSent); //cry if more than 1 file submitted if( fileLimitReached ) { return next(new HTTPError(400, 'only 1 file allowed')); } //cry if there was an error or file is too big if( ! uploadedImage.file ) { return next(new HTTPError(500, 'error while uploading the file')); } else if( uploadedImage.file.truncated ) { uploadedImage.unlink(); return next(new HTTPError(413, 'file too big')); } debug('upload OK', uploadedImage); //go ahead with image submission uploadedImage.fileChecks(req.app.models.image) .then(function (image) { // image.getMetadata(); return res.json({ image: image, jobId: '' }); }) .catch(function (err) { return next(err); }); }); }); //submit url router.post('/submit', jsonParser, function (req, res, next) { debug('/submit'); var imageUrl = req.body.url; if( ! imageUrl ) { return next(new HTTPError(400, 'url is required')); } // init image var downloadedImage = new submittedFile(); downloadedImage.uploaderIP = req.ip || req.connection.remoteAddress; downloadedImage.url = imageUrl; //get preliminary info on url Promise.fromNode(function (callback) { return request.head(imageUrl, callback); }) .spread(function (response, body) { //too big if( response.headers['content-length'] > config.upload.sizeLimit) { return next(new HTTPError(413, 'file too big')); } //download the image request.get(imageUrl) //pipe to tmp path .pipe(fs.createWriteStream(downloadedImage.tmpPath)) //process submission when it's over .on('close', function () { downloadedImage.fileChecks(req.app.models.image) .then(function (image) { return res.json({ image: image, jobId: '' }); }) .catch(function (err) { return next(err); }); }); }) .catch(function (err) { return next(err); }); }); //get an image by its permalink router.get('/:permalink', function (req, res, next) { debug('/:permalink'); //try to get image by permalink req.app.models.image.findOne({ permalink: req.params.permalink }) .then(function (image) { //404 if( ! image ) { return next(new HTTPError(404, 'no image with this permalink')); } image.queueAnalysis(); //return image return res.json({ image: image }); }) .catch(function (err) { return next(err); }); }); module.exports = router;
JavaScript
0.000059
@@ -2233,31 +2233,111 @@ %0A%09%09%09 -// image.getMetadata(); +return %5Bimage, image.queueAnalysis(config.defaultAnalysisOpts)%5D;%0A%09%09%7D)%0A%09%09.spread(function (image, job) %7B %0A%09%09%09 @@ -2379,26 +2379,36 @@ %0A%09%09%09%09jobId: -'' +job.data._id %0A%09%09%09%7D);%0A%09%09%7D) @@ -3399,24 +3399,134 @@ n (image) %7B%0A +%09%09%09%09return %5Bimage, image.queueAnalysis(config.defaultAnalysisOpts)%5D;%0A%09%09%09%7D)%0A%09%09%09.spread(function (image, job) %7B%0A %09%09%09%09return r @@ -3570,10 +3570,20 @@ Id: -'' +job.data._id %0A%09%09%09 @@ -4055,30 +4055,8 @@ %09%09%7D%0A -image.queueAnalysis(); %0A%09%09/
58c077bc22727d5131b7651a5bdad14c56e4bf54
Fix tsc watch
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var gutil = require('gutil'); var plumber = require('gulp-plumber'); var shell = require("gulp-shell"); var notify = require('gulp-notify'); var uglify = require('gulp-uglify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var browserify = require('browserify'); var watchify = require('watchify'); var sourcemaps = require('gulp-sourcemaps'); var xtend = require('xtend'); var deploy = require('gulp-gh-pages'); var webserver = require('gulp-webserver'); function notifyError () { return plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }); } gulp.task("tsc-watch", shell.task([ "tsc -w" ])); gulp.task("tsc", shell.task([ "tsc" ])); gulp.task('watch-bundle', ["tsc-watch"], function() { var args = xtend(watchify.args, { debug: true }); var bundler = watchify(browserify('./build/index.js', args)) .transform("babelify") .transform('debowerify'); function bundle () { return bundler .bundle() .on('error', notify.onError('Error: <%= error.message %>')) .pipe(source('bundle.js')) .pipe(notify("Build Finished")) .pipe(gulp.dest('./dist')); } bundle(); bundler.on('update', bundle); }); gulp.task('release-bundle', ["tsc"], function() { return browserify('./build/index.js') .transform("babelify") .transform('debowerify') .bundle() .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(notify("Build Finished")) .pipe(gulp.dest('./dist')); }); gulp.task('deploy', ['release-bundle'], function() { return gulp.src('./dist/**/*') .pipe(deploy()); }); gulp.task('webserver', function() { gulp.src('dist') .pipe(webserver({ host: '0.0.0.0', livereload: true, open: true })); }) gulp.task('default', ['watch-bundle', 'webserver']);
JavaScript
0.000001
@@ -777,22 +777,16 @@ ', %5B%22tsc --watch %22%5D, func @@ -1939,16 +1939,29 @@ ault', %5B +%22tsc-watch%22, 'watch-b
4a7f4798fe72cc1519dc40a203c3a862315c2fe9
Remove undefined task for now
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var runSequence = require('run-sequence'); var jasmine = require('gulp-jasmine'); var cover = require('gulp-coverage'); var coveralls = require('gulp-coveralls'); var options = { testPaths : { unit : [ 'tests/unit/*.js', 'tests/unit/**/*.js', ], spec : [ 'tests/spec/*.js', 'tests/spec/**/*.js', ], integration : [ 'tests/integration/*.js', 'tests/integration/**/*.js', ] }, filePaths : { core : [ 'src/core/*.js', 'src/core/**/*.js' ], framework : [ 'src/framework/*.js', 'src/framework/**/*.js' ], }, jasmine : { includeStackTrace : true, verbose: true } } gulp.task('test', function () { return gulp.src( options.testPaths.spec ) .pipe(cover.instrument({ pattern: options.filePaths.core, debugDirectory: 'debug' })) .pipe( jasmine( options.jasmine ) ) .pipe(cover.gather()) .pipe(cover.format({ reporter: 'lcov' })) .pipe(coveralls()) .pipe(gulp.dest('coverage')); }); gulp.task('default', function ( cb ) { runSequence( 'test', 'build', cb ); });
JavaScript
0.00002
@@ -1205,17 +1205,8 @@ st', - 'build', cb
d0695e62b415979e2eaf4740deea68d3822fd16e
copy ABOUT.md to build folder so it can be loaded via ajax
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var path = require('path'); var gutil = require('gulp-util'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var del = require('del'); var webpackConfig = require('./webpack.config.js'); var gulpWebpack = require('gulp-webpack'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); gulp.task('default', ['copy','webpack-dev-server'], function() {}); gulp.task('clean', function(cb) { del(['build/**'], cb); }); gulp.task('build', ['copy', 'webpack:build'], function() {}); gulp.task('copy', function() { gulp.src('index.html') .pipe(gulp.dest('build')); }); gulp.task('webpack:build', function(callback) { // Modify some webpack config options var myConfig = Object.create(webpackConfig); myConfig.plugins = myConfig.plugins.concat( new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ); // Run webpack gulp.src(webpackConfig.entry) .pipe(gulpWebpack(myConfig, webpack, function(err, stats) { if (err) { throw new gutil.PluginError('webpack:build', err); } gutil.log('[webpack:build]', stats.toString({ colors: true })); })) .pipe(gulp.dest(webpackConfig.output.publicPath)); }); gulp.task("webpack-dev-server", function(callback) { // Start a webpack-dev-server var compiler = webpack(webpackConfig); new WebpackDevServer(compiler, { // server and middleware options }).listen(8000, "localhost", function(err) { if(err) { throw new gutil.PluginError("webpack-dev-server", err); } // Server listening gutil.log("[webpack-dev-server]", "http://local.carduner.net:8000/webpack-dev-server/index.html"); // keep the server alive or continue? // callback(); }); });
JavaScript
0
@@ -646,24 +646,78 @@ ('build'));%0A + gulp.src('ABOUT.md')%0A .pipe(gulp.dest('build'));%0A %7D);%0A%0Agulp.ta
c4eecbdf2c3cf75a0390661abf844c81420ac386
Add better handling for a11y attributes without a validation message.
rocketbelt/components/forms/rocketbelt.forms.js
rocketbelt/components/forms/rocketbelt.forms.js
(function rocketbeltForms(rb, document) { var aria = rb.aria; function onClassMutation(mutations) { var mutationsLen = mutations.length; for (var k = 0; k < mutationsLen; k++) { var mutation = mutations[k]; var el = mutation.target; var message = el.parentNode.querySelector('.validation-message'); if (mutation.oldValue !== 'invalid' && mutation.target.classList.contains('invalid')) { // If "invalid" was added, do the decoratin' el.setAttribute(aria.invalid, 'true'); message.setAttribute(aria.role, 'alert'); message.setAttribute(aria.live, 'polite'); } else if (mutation.oldValue === 'invalid' && !el.classList.contains('invalid')) { // If "invalid" was removed el.setAttribute(aria.invalid, 'false'); message.removeAttribute('role'); message.removeAttribute(aria.live); } } } function decorateInputs() { var formEls = document.querySelectorAll('.form-group input, .form-group select, .form-group textarea, .form-group fieldset'); var formElsLen = formEls.length; for (var i = 0; i < formElsLen; i++) { var formEl = formEls[i]; // Set an observer to listen for .invalid. var observer = new MutationObserver(function (mutations) { onClassMutation(mutations); }); observer.observe(formEl, { subtree: false, attributes: true, attributeOldValue: true, attributeFilter: ['class'] }); var messages = formEl.parentNode.querySelectorAll('.validation-message, .helper-text'); var msgLen = messages.length; var describedByIds = ''; for (var j = 0; j < msgLen; j++) { var thisMsg = messages[j]; var id = 'rb-a11y_' + rb.getShortId(); describedByIds += id + ' '; // Don't clobber any existing attributes! if (!thisMsg.id) { thisMsg.id = id; } } if (!formEl.hasAttribute(aria.describedby)) { formEl.setAttribute(aria.describedby, describedByIds.trim()); } } } rb.onDocumentReady(decorateInputs); rb.forms = rb.forms || {}; rb.forms.decorateInputs = decorateInputs; })(window.rb, document);
JavaScript
0
@@ -515,24 +515,50 @@ d, 'true');%0A +%0A if (message) %7B%0A mess @@ -591,24 +591,26 @@ , 'alert');%0A + mess @@ -644,24 +644,34 @@ 'polite');%0A + %7D%0A %7D else @@ -827,24 +827,50 @@ , 'false');%0A +%0A if (message) %7B%0A mess @@ -894,24 +894,26 @@ te('role');%0A + mess @@ -944,16 +944,26 @@ .live);%0A + %7D%0A %7D%0A
9fdd8fbd5d0a783a001dd35ad053ecdb8ea576d7
Update socket.io.js
config/socket.io.js
config/socket.io.js
'use strict'; // Load the module dependencies var config = require('./config'), path = require('path'), http = require('http'), socketio = require('socket.io'); // Define the Socket.io configuration method module.exports = function (app, db) { var server = http.createServer(app); var io = socketio(config.socketPort, { transports: ['websocket', 'polling'] }); var redis = require('socket.io-redis'); io.adapter(redis( process.env.REDIS_URL || { host: process.env.REDIS_DB_PORT_6379_TCP_ADDR || '127.0.0.1' , port: process.env.REDIS_DB_PORT_6379_TCP_PORT || 6379 })); // Add an event listener to the 'connection' event io.on('connection', function (socket) { config.getGlobbedFiles('./app/sockets/**.js').forEach(function (socketConfiguration) { require(path.resolve(socketConfiguration))(io, socket); }); }); return server; };
JavaScript
0.000001
@@ -363,16 +363,69 @@ '%5D %7D);%0A%09 +%0A%09if(process.env.DISABLE_CLUSTER_MODE === %22TRUE%22)%7B%0A%09%09 var redi @@ -456,16 +456,17 @@ edis');%0A +%09 %09io.adap @@ -625,16 +625,18 @@ 79 %7D));%0A +%09%7D %0A%09// Add