<commit_before>;(function () {
    var roundNumber = function (number, decimals) {
        return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
    },

    toArray = function (object) {
        return [].slice.call(object);
    },

    convert = function (value, from, to, base, dpi, decimals) {
        var units = from + '-' + to,
            result,
            formulas = {
                'cm-em': value / 0.42175176,
                'cm-in': value * 0.39,
                'cm-mm': value * 10,
                'cm-pc': value / 0.42175176,
                'cm-pt': value * 28.3464566929,
                'cm-%': value / base * 100 / 2.54 * dpi,
                'cm-px': value / 2.54 * dpi,

                'em-cm': value * 0.42175176,
                'em-in': value * 0.166044,
                'em-mm': value / 0.237106301584,
                'em-pc': value,
                'em-pt': value * 11.955168,
                'em-%': value * 100,
                'em-px': value * base,

                'in-cm': value * 2.54,
                'in-em': value / 0.166044,
                'in-mm': value * 2.54 * 10,
                'in-pc': value / 0.166044,
                'in-pt': value / 0.014842519685,
                'in-%': value / base * 100 * dpi,
                'in-px': value * dpi,

                'mm-cm': value / 10,
                'mm-em': value * 0.237106301584,
                'mm-in': value * 0.39 / 10,
                'mm-pc': value / 4.42175176,
                'mm-pt': value / 0.352777777778,
                'mm-%': value / base * 100 / 2.54 * dpi / 10,
                'mm-px': value / 2.54 * dpi / 10,

                'pc-cm': value * 0.42175176,
                'pc-em': value,
                'pc-in': value * 0.166044,
                'pc-mm': value * 4.42175176,
                'pc-pt': value / 0.0836458341698,
                'pc-%': value * 100,
                'pc-px': value * base,

                'pt-cm': value / 28.3464566929,
                'pt-em': value / 11.955168,
                'pt-in': value * 0.014842519685,
                'pt-mm': value * 0.352777777778,
                'pt-pc': value * 0.0836458341698,
                'pt-%': value / (base - 4) * 100,
                'pt-px': value * 96 / 72,

                '%-cm': value * base / 100 * 2.54 / dpi,
                '%-em': value / 100,
                '%-in': value * base / 100 / dpi,
                '%-mm': value * base / 100 * 2.54 / dpi * 10,
                '%-pc': value / 100,
                '%-pt': value * (base - 4) / 100,
                '%-px': value * base / 100,

                'px-cm': value * 2.54 / dpi,
                'px-em': value / base,
                'px-in': value / dpi,
                'px-mm': value * 2.54 / dpi * 10,
                'px-pc': value / base,
                'px-pt': value * 72 / 96,
                'px-%': value / base * 100
            };

        result = formulas[units] || value;

        return (isNaN(result) ? 'N/A' : roundNumber(result, decimals) + to);
    },

    setupForm = function () {
        var from = document.querySelector('.from'),
            selects = document.querySelectorAll('select'),
            settings = document.querySelectorAll('.settings input'),
            fragment = document.createDocumentFragment(),
            options = [],
            units = ['cm', 'em', 'in', 'mm', 'pc', 'pt', '%', 'px'];

        // Set from value
        from.value = localStorage.getItem(from.name) || '';

        // Add the units
        units.forEach(function (unit) {
            var option = document.createElement('option');

            option.value = unit;
            option.textContent = unit;

            fragment.appendChild(option);
        });

        toArray(selects).forEach(function (select) {
            var unit = localStorage.getItem(select.name),
                selected;

            if (unit) {
                selected = fragment.querySelector('[value="' + unit + '"]');
                selected.defaultSelected = true;
            }

            select.appendChild(fragment.cloneNode(true));

            if (selected) {
                selected.defaultSelected = false;
            }
        });

        // Add settings
        toArray(settings).forEach(function (setting) {
            var name = setting.name;

            setting.value = localStorage.getItem(name) || setting.value;
        });
    },

    run = function () {
        document.querySelector('.result').textContent = convert(
            document.querySelector('.from').value,
            document.querySelector('.from-unit').value,
            document.querySelector('.to-unit').value,
            document.querySelector('.base-size').value,
            document.querySelector('.dpi').value,
            document.querySelector('.decimals').value
        );
    };

    window.addEventListener('DOMContentLoaded', function () {
        var elements = toArray(document.querySelectorAll('input, select'));

        setupForm();

        elements.forEach(function (element) {
            element.addEventListener('change', run);
            element.addEventListener('keyup', run);
        });

        // Toogle display of setting forms
        document.querySelector('.toggle').addEventListener('click', function (e) {
            e.preventDefault();

            document.querySelector('.settings').classList.toggle('show');
        });

        // Save all values once every 30 seconds
        setInterval(function () {
            elements.forEach(function (element) {
                localStorage.setItem(element.name, element.value);
            });
        }, 30000);
    });
}());
<commit_msg>Rename roundNumber()<commit_after>;(function () {
    var round = function (number, decimals) {
        return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
    },

    toArray = function (object) {
        return [].slice.call(object);
    },

    convert = function (value, from, to, base, dpi, decimals) {
        var units = from + '-' + to,
            result,
            formulas = {
                'cm-em': value / 0.42175176,
                'cm-in': value * 0.39,
                'cm-mm': value * 10,
                'cm-pc': value / 0.42175176,
                'cm-pt': value * 28.3464566929,
                'cm-%': value / base * 100 / 2.54 * dpi,
                'cm-px': value / 2.54 * dpi,

                'em-cm': value * 0.42175176,
                'em-in': value * 0.166044,
                'em-mm': value / 0.237106301584,
                'em-pc': value,
                'em-pt': value * 11.955168,
                'em-%': value * 100,
                'em-px': value * base,

                'in-cm': value * 2.54,
                'in-em': value / 0.166044,
                'in-mm': value * 2.54 * 10,
                'in-pc': value / 0.166044,
                'in-pt': value / 0.014842519685,
                'in-%': value / base * 100 * dpi,
                'in-px': value * dpi,

                'mm-cm': value / 10,
                'mm-em': value * 0.237106301584,
                'mm-in': value * 0.39 / 10,
                'mm-pc': value / 4.42175176,
                'mm-pt': value / 0.352777777778,
                'mm-%': value / base * 100 / 2.54 * dpi / 10,
                'mm-px': value / 2.54 * dpi / 10,

                'pc-cm': value * 0.42175176,
                'pc-em': value,
                'pc-in': value * 0.166044,
                'pc-mm': value * 4.42175176,
                'pc-pt': value / 0.0836458341698,
                'pc-%': value * 100,
                'pc-px': value * base,

                'pt-cm': value / 28.3464566929,
                'pt-em': value / 11.955168,
                'pt-in': value * 0.014842519685,
                'pt-mm': value * 0.352777777778,
                'pt-pc': value * 0.0836458341698,
                'pt-%': value / (base - 4) * 100,
                'pt-px': value * 96 / 72,

                '%-cm': value * base / 100 * 2.54 / dpi,
                '%-em': value / 100,
                '%-in': value * base / 100 / dpi,
                '%-mm': value * base / 100 * 2.54 / dpi * 10,
                '%-pc': value / 100,
                '%-pt': value * (base - 4) / 100,
                '%-px': value * base / 100,

                'px-cm': value * 2.54 / dpi,
                'px-em': value / base,
                'px-in': value / dpi,
                'px-mm': value * 2.54 / dpi * 10,
                'px-pc': value / base,
                'px-pt': value * 72 / 96,
                'px-%': value / base * 100
            };

        result = formulas[units] || value;

        return (isNaN(result) ? 'N/A' : round(result, decimals) + to);
    },

    setupForm = function () {
        var from = document.querySelector('.from'),
            selects = document.querySelectorAll('select'),
            settings = document.querySelectorAll('.settings input'),
            fragment = document.createDocumentFragment(),
            options = [],
            units = ['cm', 'em', 'in', 'mm', 'pc', 'pt', '%', 'px'];

        // Set from value
        from.value = localStorage.getItem(from.name) || '';

        // Add the units
        units.forEach(function (unit) {
            var option = document.createElement('option');

            option.value = unit;
            option.textContent = unit;

            fragment.appendChild(option);
        });

        toArray(selects).forEach(function (select) {
            var unit = localStorage.getItem(select.name),
                selected;

            if (unit) {
                selected = fragment.querySelector('[value="' + unit + '"]');
                selected.defaultSelected = true;
            }

            select.appendChild(fragment.cloneNode(true));

            if (selected) {
                selected.defaultSelected = false;
            }
        });

        // Add settings
        toArray(settings).forEach(function (setting) {
            var name = setting.name;

            setting.value = localStorage.getItem(name) || setting.value;
        });
    },

    run = function () {
        document.querySelector('.result').textContent = convert(
            document.querySelector('.from').value,
            document.querySelector('.from-unit').value,
            document.querySelector('.to-unit').value,
            document.querySelector('.base-size').value,
            document.querySelector('.dpi').value,
            document.querySelector('.decimals').value
        );
    };

    window.addEventListener('DOMContentLoaded', function () {
        var elements = toArray(document.querySelectorAll('input, select'));

        setupForm();

        elements.forEach(function (element) {
            element.addEventListener('change', run);
            element.addEventListener('keyup', run);
        });

        // Toogle display of setting forms
        document.querySelector('.toggle').addEventListener('click', function (e) {
            e.preventDefault();

            document.querySelector('.settings').classList.toggle('show');
        });

        // Save all values once every 30 seconds
        setInterval(function () {
            elements.forEach(function (element) {
                localStorage.setItem(element.name, element.value);
            });
        }, 30000);
    });
}());
<|endoftext|>


<commit_before>'use strict';

var del = require('del');
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cssnano = require('gulp-cssnano');
var postcss = require('gulp-postcss');
var sorting = require('postcss-sorting');

// Config
var build = {
  css: './assets/css',
	scss: './src/scss/'
};<commit_msg>added autoprefixer array<commit_after>'use strict';

var del = require('del');
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cssnano = require('gulp-cssnano');
var postcss = require('gulp-postcss');
var sorting = require('postcss-sorting');

// Config
var build = {
  css: './assets/css',
	scss: './src/scss/'
};

var AUTOPREFIXER_BROWSERS = [
  'ie >= 11',
  'edge >= 12',
  'ff >= 38',
  'chrome >= 35',
  'safari >= 8',
  'opera >= 35',
  'ios >= 8'
];
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var mediarenderer = window.mediarenderer = {};

mediarenderer.reset = function() {
	mediarenderer.busName = "com.intel.dleyna-renderer";
	mediarenderer.bus = null;
	mediarenderer.uri = null;
	mediarenderer.manager = null;
};

mediarenderer.init = function(uri, manifest, successCB, errorCB) {
	mediarenderer.reset();

	function onManagerOk() {
		if (successCB)
			successCB();
	}

	function onConnectOk() {
		mediarenderer.bus = cloudeebus.SessionBus();
		mediarenderer.uri = uri;
		mediarenderer.manager = mediarenderer.bus.getObject(mediarenderer.busName, "/com/intel/dLeynaRenderer", onManagerOk);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

mediarenderer.setRendererListener = function(rendererCallback, errorCallback) {

	var rendererFoundCB = rendererCallback.onrendererfound;
	var rendererLostCB = rendererCallback.onrendererlost;

	function onRendererOk(proxy) {
		if (rendererFoundCB)
			rendererFoundCB(new mediarenderer.MediaRenderer(proxy));
	}

	function onObjIdOk(id) {
		var proxy = mediarenderer.bus.getObject(mediarenderer.busName, id);
		proxy.callMethod("org.freedesktop.DBus.Properties", "Get", ["org.mpris.MediaPlayer2", "Identity"],
			function() {
				mediarenderer.bus.getObject(mediarenderer.busName, id, onRendererOk);
			}
		);
	}

	function onObjIdsOk(ids) {
		for (var i=0; i<ids.length; i++)
			onObjIdOk(ids[i]);
	}

	mediarenderer.manager.GetServers(onObjIdsOk, errorCallback);
	mediarenderer.manager.connectToSignal("com.intel.dLeynaRenderer.Manager", "FoundServer",
			onObjIdOk, errorCallback);
	mediarenderer.manager.connectToSignal("com.intel.dLeynaRenderer.Manager", "LostServer",
			rendererLostCB, errorCallback);
};

/*****************************************************************************/

mediarenderer.MediaController = function(renderer) {
	this.renderer = renderer;
	this.paused = true;
	this.muted = renderer.proxy.Mute == undefined ? false : renderer.proxy.Mute;
	this.volume = renderer.proxy.Volume == undefined ? 1 : Number(renderer.proxy.Volume);
	this.track = renderer.proxy.CurrentTrack == undefined ? 1 : Number(renderer.proxy.CurrentTrack);
	this.rate = renderer.proxy.Rate;
	this.playSpeeds = renderer.proxy.TransportPlaySpeeds;
	return this;
};

mediarenderer.MediaController.prototype.mute = function(mute) {
	this.renderer.proxy.Set("org.mpris.MediaPlayer2.Player", "Mute", mute);
};

mediarenderer.MediaController.prototype.play = function() {
	this.renderer.proxy.Play();
};

mediarenderer.MediaController.prototype.pause = function() {
	this.renderer.proxy.Pause();
};

mediarenderer.MediaController.prototype.stop = function() {
	this.renderer.proxy.Stop();
};

mediarenderer.MediaController.prototype.next = function() {
	this.renderer.proxy.Next();
};

mediarenderer.MediaController.prototype.previous = function() {
	this.renderer.proxy.Previous();
};

mediarenderer.MediaController.prototype.setVolume = function(vol) {
	this.renderer.proxy.Set("org.mpris.MediaPlayer2.Player", "Volume", Math.max(0,Math.min(0.99,Number(vol))));
};

mediarenderer.MediaController.prototype.setSpeed = function(speed) {
	this.renderer.proxy.Set("org.mpris.MediaPlayer2.Player", "Rate", Number(speed));
};

mediarenderer.MediaController.prototype.gotoTrack = function(track) {
	this.renderer.proxy.GotoTrack(Number(track));
};

mediarenderer.MediaController.prototype.seek = function(secOffset) {
	this.renderer.proxy.Seek(Number(secOffset) * 1000000);
};

/*****************************************************************************/

mediarenderer.MediaRenderer = function(proxy) {
	this.proxy = proxy;
	this.controller = new mediarenderer.MediaController(this);
	if (proxy) {
		this.id = proxy.objectPath;
		this.friendlyName = proxy.Identity;
		this.protocolInfo = proxy.ProtocolInfo;
		proxy.controller = this.controller;
		proxy.connectToSignal("org.freedesktop.DBus.Properties","PropertiesChanged",
			function(iface, changed, invalidated) {
				if (changed.CurrentTrack != undefined)
					this.controller.track = changed.CurrentTrack;
				if (changed.Volume != undefined)
					this.controller.volume = changed.Volume;
				if (changed.Mute != undefined)
					this.controller.muted = changed.Mute;
				if (changed.PlaybackStatus != undefined)
					this.controller.paused = changed.PlaybackStatus != "Playing";
				if (changed.Rate != undefined)
					this.controller.rate = changed.Rate;
				if (changed.TransportPlaySpeeds != undefined)
					this.controller.playSpeeds = changed.TransportPlaySpeeds;
				if (this.controller.onchange)
					this.controller.onchange.apply(this.controller);
			}, cloudeebus.log);
	}
	return this;
};

mediarenderer.MediaRenderer.prototype.openURI = function(mediaURI, metaData, successCallback, errorCallback) {
	if (metaData)
		this.proxy.OpenUriEx(mediaURI, metaData, successCallback, errorCallback);
	else
		this.proxy.OpenUri(mediaURI, successCallback, errorCallback);
};
<commit_msg>set properties on float workaround<commit_after>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var mediarenderer = window.mediarenderer = {};

mediarenderer.reset = function() {
	mediarenderer.busName = "com.intel.dleyna-renderer";
	mediarenderer.bus = null;
	mediarenderer.uri = null;
	mediarenderer.manager = null;
};

mediarenderer.init = function(uri, manifest, successCB, errorCB) {
	mediarenderer.reset();

	function onManagerOk() {
		if (successCB)
			successCB();
	}

	function onConnectOk() {
		mediarenderer.bus = cloudeebus.SessionBus();
		mediarenderer.uri = uri;
		mediarenderer.manager = mediarenderer.bus.getObject(mediarenderer.busName, "/com/intel/dLeynaRenderer", onManagerOk);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

mediarenderer.setRendererListener = function(rendererCallback, errorCallback) {

	var rendererFoundCB = rendererCallback.onrendererfound;
	var rendererLostCB = rendererCallback.onrendererlost;

	function onRendererOk(proxy) {
		if (rendererFoundCB)
			rendererFoundCB(new mediarenderer.MediaRenderer(proxy));
	}

	function onObjIdOk(id) {
		var proxy = mediarenderer.bus.getObject(mediarenderer.busName, id);
		proxy.callMethod("org.freedesktop.DBus.Properties", "Get", ["org.mpris.MediaPlayer2", "Identity"],
			function() {
				mediarenderer.bus.getObject(mediarenderer.busName, id, onRendererOk);
			}
		);
	}

	function onObjIdsOk(ids) {
		for (var i=0; i<ids.length; i++)
			onObjIdOk(ids[i]);
	}

	mediarenderer.manager.GetServers(onObjIdsOk, errorCallback);
	mediarenderer.manager.connectToSignal("com.intel.dLeynaRenderer.Manager", "FoundServer",
			onObjIdOk, errorCallback);
	mediarenderer.manager.connectToSignal("com.intel.dLeynaRenderer.Manager", "LostServer",
			rendererLostCB, errorCallback);
};

/*****************************************************************************/

mediarenderer.MediaController = function(renderer) {
	this.renderer = renderer;
	this.paused = true;
	this.muted = renderer.proxy.Mute == undefined ? false : renderer.proxy.Mute;
	this.volume = renderer.proxy.Volume == undefined ? 1 : Number(renderer.proxy.Volume);
	this.track = renderer.proxy.CurrentTrack == undefined ? 1 : Number(renderer.proxy.CurrentTrack);
	this.rate = renderer.proxy.Rate;
	this.playSpeeds = renderer.proxy.TransportPlaySpeeds;
	return this;
};

mediarenderer.MediaController.prototype.mute = function(mute) {
	this.renderer.proxy.Set("org.mpris.MediaPlayer2.Player", "Mute", mute);
};

mediarenderer.MediaController.prototype.play = function() {
	this.renderer.proxy.Play();
};

mediarenderer.MediaController.prototype.pause = function() {
	this.renderer.proxy.Pause();
};

mediarenderer.MediaController.prototype.stop = function() {
	this.renderer.proxy.Stop();
};

mediarenderer.MediaController.prototype.next = function() {
	this.renderer.proxy.Next();
};

mediarenderer.MediaController.prototype.previous = function() {
	this.renderer.proxy.Previous();
};

mediarenderer.MediaController.prototype.setVolume = function(vol) {
	var argStr = String(vol);
	if (argStr.indexOf(".") == -1)
		argStr += ".0";
	var proxy = this.renderer.proxy;
	var arglist = [
	       		proxy.busConnection.name,
	       		proxy.busName,
	       		proxy.objectPath,
	       		"org.freedesktop.DBus.Properties",
	       		"Set",
	       		"[\"org.mpris.MediaPlayer2.Player\",\"Volume\"," + argStr + "]"
	       	];
	proxy.wampSession.call("dbusSend", arglist);
};

mediarenderer.MediaController.prototype.setSpeed = function(speed) {
	var argStr = String(speed);
	if (argStr.indexOf(".") == -1)
		argStr += ".0";
	var proxy = this.renderer.proxy;
	var arglist = [
	       		proxy.busConnection.name,
	       		proxy.busName,
	       		proxy.objectPath,
	       		"org.freedesktop.DBus.Properties",
	       		"Set",
	       		"[\"org.mpris.MediaPlayer2.Player\",\"Rate\"," + argStr + "]"
	       	];
	proxy.wampSession.call("dbusSend", arglist);
};

mediarenderer.MediaController.prototype.gotoTrack = function(track) {
	this.renderer.proxy.GotoTrack(Number(track));
};

mediarenderer.MediaController.prototype.seek = function(secOffset) {
	this.renderer.proxy.Seek(Number(secOffset) * 1000000);
};

/*****************************************************************************/

mediarenderer.MediaRenderer = function(proxy) {
	this.proxy = proxy;
	this.controller = new mediarenderer.MediaController(this);
	if (proxy) {
		this.id = proxy.objectPath;
		this.friendlyName = proxy.Identity;
		this.protocolInfo = proxy.ProtocolInfo;
		proxy.controller = this.controller;
		proxy.connectToSignal("org.freedesktop.DBus.Properties","PropertiesChanged",
			function(iface, changed, invalidated) {
				if (changed.CurrentTrack != undefined)
					this.controller.track = changed.CurrentTrack;
				if (changed.Volume != undefined)
					this.controller.volume = changed.Volume;
				if (changed.Mute != undefined)
					this.controller.muted = changed.Mute;
				if (changed.PlaybackStatus != undefined)
					this.controller.paused = changed.PlaybackStatus != "Playing";
				if (changed.Rate != undefined)
					this.controller.rate = changed.Rate;
				if (changed.TransportPlaySpeeds != undefined)
					this.controller.playSpeeds = changed.TransportPlaySpeeds;
				if (this.controller.onchange)
					this.controller.onchange.apply(this.controller);
			}, cloudeebus.log);
	}
	return this;
};

mediarenderer.MediaRenderer.prototype.openURI = function(mediaURI, metaData, successCallback, errorCallback) {
	if (metaData)
		this.proxy.OpenUriEx(mediaURI, metaData, successCallback, errorCallback);
	else
		this.proxy.OpenUri(mediaURI, successCallback, errorCallback);
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    browserify = require('browserify'),
    del = require('del'),
    exec = require('child_process').exec,
    ts = require('gulp-typescript'),
    source = require('vinyl-source-stream'),
    uglify = require('gulp-uglify'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    gutil = require('gulp-util'),
    glob = require('glob'),
    es = require('event-stream'),
    fs = require('fs'),
    nodemon = require('gulp-nodemon');

var ts_project = ts.createProject('./src/tsconfig.json');

gulp.task('default', ['watch', 'nodemon']);

// download the types definitions from definitely typed
gulp.task('tsd', function(cb) {
  exec('tsd reinstall --save --overwrite', function(err, stdout, stderr) {
    console.log(stdout);
    console.error(stderr);
    cb(err);
  });
  return gulp;
});

// compile the typescript source
gulp.task('ts', function() {
  var ts_result = ts_project.src().pipe( ts(ts_project) );
  return ts_result.js.pipe(gulp.dest('./'));
});

// clean up the generated javascript files
gulp.task('clean:ts', function() {
  var files = [
    './src/**/*.js',
    './analysis/**/*.js'
  ]
  del(files);
  return gulp;
});

// watch typescript files for changes and recompile
gulp.task('watch', function() {
  gulp.watch(
    [
      './src/*.ts',
      './src/**/*.ts',
    ],
    ['bundle-js']
  );
});

// start the node server
gulp.task('nodemon', function() {
  nodemon({ script: './src/server.js' });
});

gulp.task('bundle-js', ['ts'], function(done) {
  var files = glob.sync('./src/client/script/**/*.js'),
      tasks = [];
  for (var f in files) {
    var file_path = files[f].split('/'),
        file = file_path[ file_path.length -1 ];
    var b = browserify({
      entries: file_path.slice(0, file_path.length-1).join('/') + '/' + file,
      debug: true
    });
    tasks.push(b.bundle()
      .pipe(source(file))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .on('error', gutil.log)
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./src/public/script/')));
  }
  return es.merge(tasks);
});

gulp.task('bundle-css', function() {
  var files = fs.readFileSync('./src/client/style/dependencies', 'utf8')
                .split('\n');
  return gulp
    .src(files, { base: './node_modules/' })
    .pipe(gulp.dest('./src/public/style/'));
});
<commit_msg>gulpfile patch in ts compile<commit_after>'use strict';

var gulp = require('gulp'),
    browserify = require('browserify'),
    del = require('del'),
    exec = require('child_process').exec,
    ts = require('gulp-typescript'),
    source = require('vinyl-source-stream'),
    uglify = require('gulp-uglify'),
    buffer = require('vinyl-buffer'),
    sourcemaps = require('gulp-sourcemaps'),
    gutil = require('gulp-util'),
    glob = require('glob'),
    es = require('event-stream'),
    fs = require('fs'),
    nodemon = require('gulp-nodemon');

var ts_project = ts.createProject('./src/tsconfig.json');

gulp.task('default', ['watch', 'nodemon']);

// download the types definitions from definitely typed
gulp.task('tsd', function(cb) {
  exec('tsd reinstall --save --overwrite', function(err, stdout, stderr) {
    console.log(stdout);
    console.error(stderr);
    cb(err);
  });
  return gulp;
});

// compile the typescript source
gulp.task('ts', function() {
  var ts_result = ts_project.src().pipe( ts(ts_project) );
  return ts_result.js.pipe(gulp.dest('./src'));
});

// clean up the generated javascript files
gulp.task('clean:ts', function() {
  var files = [
    './src/**/*.js',
    './analysis/**/*.js'
  ]
  del(files);
  return gulp;
});

// watch typescript files for changes and recompile
gulp.task('watch', function() {
  gulp.watch(
    [
      './src/*.ts',
      './src/**/*.ts',
    ],
    ['bundle-js']
  );
});

// start the node server
gulp.task('nodemon', function() {
  nodemon({ script: './src/server.js' });
});

gulp.task('bundle-js', ['ts'], function(done) {
  var files = glob.sync('./src/client/script/**/*.js'),
      tasks = [];
  for (var f in files) {
    var file_path = files[f].split('/'),
        file = file_path[ file_path.length -1 ];
    var b = browserify({
      entries: file_path.slice(0, file_path.length-1).join('/') + '/' + file,
      debug: true
    });
    tasks.push(b.bundle()
      .pipe(source(file))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .on('error', gutil.log)
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('./src/public/script/')));
  }
  return es.merge(tasks);
});

gulp.task('bundle-css', function() {
  var files = fs.readFileSync('./src/client/style/dependencies', 'utf8')
                .split('\n');
  return gulp
    .src(files, { base: './node_modules/' })
    .pipe(gulp.dest('./src/public/style/'));
});
<|endoftext|>


<commit_before>(function ($) {

    var defaults = {
        inputClass: '',
        invalid: [],
        group: false
    }

    $.scroller.presets.select = function (inst) {
        var s = $.extend({}, defaults, inst.settings),
            elm = $(this),
            option = elm.val(),
            group = elm.find('option[value="' + elm.val() + '"]').parent(),
            prev = group.index() + '',
            prevent,
            id = this.id + '_dummy',
            l1 = $('label[for="' + this.id + '"]').attr('for', id),
            l2 = $('label[for="' + id + '"]'),
            label = s.label !== undefined ? s.label : (l2.length ? l2.text() : elm.attr('name')),
            invalid = [],
            main = {},
            wIndex = {}, // wheel index container
            shTime,
            roPre = inst.settings.readonly,
            w;

        // if groups is true and there are no groups fall back to no grouping
        if (s.group && !$('optgroup', elm).length)
            s.group = false;

        if (!s.invalid.length)
            s.invalid = invalid;

        if (s.group) {
            wIndex.groups = 0;
            wIndex.options = 1;

            $('.dwwl0').live('mousedown touchstart', function (e) {
                clearTimeout(shTime);
            });
        }
        else {
            wIndex.groups = -1;
            wIndex.options = 0;
        }

        $('#' + id).remove();

        $('option', elm).each(function () {
            main[$(this).attr('value')] = $(this).text();
        });

        var input = $('<input type="text" id="' + id + '" value="' + main[elm.val()] + '" class="' + s.inputClass + '" readonly />').insertBefore(elm);
        inst.settings.anchor = input; // give the core the input element for the bubble positioning

        if (s.showOnFocus)
            input.focus(function () { inst.show() });

        elm.bind('change', function () {
            if (!prevent && option != elm.val()) {
                inst.setSelectVal([elm.val()], true);
            }
            prevent = false;
        }).hide().closest('.ui-field-contain').trigger('create');

        inst.setSelectVal = function (d, fill, time) {
            option = d[0];

            if (s.group) {
                group = elm.find('option[value="' + option + '"]').parent();
                inst.temp = ['_' + group.index(), '_' + option];
            }
            else
                inst.temp = ['_' + option];

            inst.setValue(true, fill, time);

            // Set input/select values
            if (fill) {
                input.val(main[option]);
                var changed = option !== elm.val();
                elm.val(option);
                // Trigger change on element
                if (changed)
                    elm.trigger('change');
            }
        }

        inst.getSelectVal = function (temp) {
            var val = temp ? inst.temp : inst.values;
            return replace(val[wIndex.options]);
        }

        return {
            width: 200,
            wheels: w,
            headerText: false,
            formatResult: function (d) {
                return main[option];
            },
            parseValue: function () {
                option = elm.val();
                group = elm.find('option[value="' + option + '"]').parent();
                return s.group ? ['_' + group.index(), '_' + option] : ['_' + option];
            },
            validate: function (dw, index, time) {
                if (index === wIndex.groups) {
                    var gr = replace(inst.temp[wIndex.groups]);

                    if (gr !== prev) {
                        inst.settings.readonly = [false, true];
                        group = elm.find('optgroup').eq(gr);
                        option = group.find('option').eq(0).val();
                        option = option ? option : elm.val();

                        clearTimeout(shTime);
                        shTime = setTimeout(function () {
                            inst.settings.wheels = genWheels();
                            if (s.group) {
                                inst.temp = ['_' + group.index(), '_' + option];
                                inst.changeWheel(1);
                                prev = group.index() + '';
                            }
                            inst.settings.readonly = roPre;
                        }, time * 1000);
                    }
                    else
                        inst.settings.readonly = roPre;
                }
                else {
                    option = replace(inst.temp[wIndex.options]);
                }

                $.each(s.invalid, function (i, v) {
                    $('li[data-val="_' + v + '"]', dw).removeClass('dw-v');
                });
            },
            onBeforeShow: function () {
                inst.settings.wheels = genWheels();
                if (s.group)
                    inst.temp = ['_' + group.index(), '_' + option];
            },
            onSelect: function (v, inst) {
                input.val(v);
                prevent = true;
                elm.val(option).trigger('change');
                if (s.group)
                    inst.values = null;
            },
            onCancel: function () {
                if (s.group)
                    inst.values = null;
            },
            onChange: function (v, inst) {
                if (s.display == 'inline') {
                    input.val(v);
                    prevent = true;
                    elm.val(replace(inst.temp[wIndex.options])).trigger('change');
                }
            },
            onClose: function () {
                input.blur();
            },
            methods: {
                setValue: function (d, fill, time) {
                    return this.each(function () {
                        var inst = $(this).scroller('getInst');
                        if (inst) {
                            if (inst.setSelectVal) {
                                inst.setSelectVal(d, fill, time);
                            }
                            else {
                                inst.temp = d;
                                inst.setValue(true, fill, time);
                            }
                        }
                    });
                },
                getValue: function (temp) {
                    var inst = $(this).scroller('getInst');
                    if (inst) {
                        if (inst.getSelectVal) {
                            return inst.getSelectVal(temp);
                        }
                        else {
                            return inst.values;
                        }
                    }
                }
            }
        };

        function replace(str) {
            if (str) {
                return str.replace(/_/, '');
            }
            return '';
        }

        function genWheels() {
            var cont,
                wg = 0,
                w = [{}];

            if (s.group) {
                var wheel = {};
                $('optgroup', elm).each(function (index) {
                    wheel['_' + index] = $(this).attr('label');
                });
                w[wg]['Groups'] = wheel;
                cont = group;
                wg++;
            }
            else {
                cont = elm;
            }
            w[wg] = {};
            w[wg][label] = {};

            $('option', cont).each(function () {
                var v = $(this).attr('value');
                w[wg][label]['_' + v] = $(this).text();
                if ($(this).prop('disabled')) invalid.push(v);
            });

            return w;
        }

    }

})(jQuery);
<commit_msg>groupLabel option for the select preset<commit_after>(function ($) {

    var defaults = {
        inputClass: '',
        invalid: [],
        group: false,
        groupLabel: 'Groups'
    }

    $.scroller.presets.select = function (inst) {
        var s = $.extend({}, defaults, inst.settings),
            elm = $(this),
            option = elm.val(),
            group = elm.find('option[value="' + elm.val() + '"]').parent(),
            prev = group.index() + '',
            prevent,
            id = this.id + '_dummy',
            l1 = $('label[for="' + this.id + '"]').attr('for', id),
            l2 = $('label[for="' + id + '"]'),
            label = s.label !== undefined ? s.label : (l2.length ? l2.text() : elm.attr('name')),
            invalid = [],
            main = {},
            wIndex = {}, // wheel index container
            shTime,
            roPre = inst.settings.readonly,
            w;

        // if groups is true and there are no groups fall back to no grouping
        if (s.group && !$('optgroup', elm).length)
            s.group = false;

        if (!s.invalid.length)
            s.invalid = invalid;

        if (s.group) {
            wIndex.groups = 0;
            wIndex.options = 1;

            $('.dwwl0').live('mousedown touchstart', function (e) {
                clearTimeout(shTime);
            });
        }
        else {
            wIndex.groups = -1;
            wIndex.options = 0;
        }

        $('#' + id).remove();

        $('option', elm).each(function () {
            main[$(this).attr('value')] = $(this).text();
        });

        var input = $('<input type="text" id="' + id + '" value="' + main[elm.val()] + '" class="' + s.inputClass + '" readonly />').insertBefore(elm);
        inst.settings.anchor = input; // give the core the input element for the bubble positioning

        if (s.showOnFocus)
            input.focus(function () { inst.show() });

        elm.bind('change', function () {
            if (!prevent && option != elm.val()) {
                inst.setSelectVal([elm.val()], true);
            }
            prevent = false;
        }).hide().closest('.ui-field-contain').trigger('create');

        inst.setSelectVal = function (d, fill, time) {
            option = d[0];

            if (s.group) {
                group = elm.find('option[value="' + option + '"]').parent();
                inst.temp = ['_' + group.index(), '_' + option];
            }
            else
                inst.temp = ['_' + option];

            inst.setValue(true, fill, time);

            // Set input/select values
            if (fill) {
                input.val(main[option]);
                var changed = option !== elm.val();
                elm.val(option);
                // Trigger change on element
                if (changed)
                    elm.trigger('change');
            }
        }

        inst.getSelectVal = function (temp) {
            var val = temp ? inst.temp : inst.values;
            return replace(val[wIndex.options]);
        }

        return {
            width: 200,
            wheels: w,
            headerText: false,
            formatResult: function (d) {
                return main[option];
            },
            parseValue: function () {
                option = elm.val();
                group = elm.find('option[value="' + option + '"]').parent();
                return s.group ? ['_' + group.index(), '_' + option] : ['_' + option];
            },
            validate: function (dw, index, time) {
                if (index === wIndex.groups) {
                    var gr = replace(inst.temp[wIndex.groups]);

                    if (gr !== prev) {
                        inst.settings.readonly = [false, true];
                        group = elm.find('optgroup').eq(gr);
                        option = group.find('option').eq(0).val();
                        option = option ? option : elm.val();

                        clearTimeout(shTime);
                        shTime = setTimeout(function () {
                            inst.settings.wheels = genWheels();
                            if (s.group) {
                                inst.temp = ['_' + group.index(), '_' + option];
                                inst.changeWheel(1);
                                prev = group.index() + '';
                            }
                            inst.settings.readonly = roPre;
                        }, time * 1000);
                    }
                    else
                        inst.settings.readonly = roPre;
                }
                else {
                    option = replace(inst.temp[wIndex.options]);
                }

                $.each(s.invalid, function (i, v) {
                    $('li[data-val="_' + v + '"]', dw).removeClass('dw-v');
                });
            },
            onBeforeShow: function () {
                inst.settings.wheels = genWheels();
                if (s.group)
                    inst.temp = ['_' + group.index(), '_' + option];
            },
            onSelect: function (v, inst) {
                input.val(v);
                prevent = true;
                elm.val(option).trigger('change');
                if (s.group)
                    inst.values = null;
            },
            onCancel: function () {
                if (s.group)
                    inst.values = null;
            },
            onChange: function (v, inst) {
                if (s.display == 'inline') {
                    input.val(v);
                    prevent = true;
                    elm.val(replace(inst.temp[wIndex.options])).trigger('change');
                }
            },
            onClose: function () {
                input.blur();
            },
            methods: {
                setValue: function (d, fill, time) {
                    return this.each(function () {
                        var inst = $(this).scroller('getInst');
                        if (inst) {
                            if (inst.setSelectVal) {
                                inst.setSelectVal(d, fill, time);
                            }
                            else {
                                inst.temp = d;
                                inst.setValue(true, fill, time);
                            }
                        }
                    });
                },
                getValue: function (temp) {
                    var inst = $(this).scroller('getInst');
                    if (inst) {
                        if (inst.getSelectVal) {
                            return inst.getSelectVal(temp);
                        }
                        else {
                            return inst.values;
                        }
                    }
                }
            }
        };

        function replace(str) {
            if (str) {
                return str.replace(/_/, '');
            }
            return '';
        }

        function genWheels() {
            var cont,
                wg = 0,
                w = [{}];

            if (s.group) {
                var wheel = {};
                $('optgroup', elm).each(function (index) {
                    wheel['_' + index] = $(this).attr('label');
                });
                w[wg][s.groupLabel] = wheel;
                cont = group;
                wg++;
            }
            else {
                cont = elm;
            }
            w[wg] = {};
            w[wg][label] = {};

            $('option', cont).each(function () {
                var v = $(this).attr('value');
                w[wg][label]['_' + v] = $(this).text();
                if ($(this).prop('disabled')) invalid.push(v);
            });

            return w;
        }

    }

})(jQuery);
<|endoftext|>


<commit_before>var del = require('del')
  , metadata = require('./package')
  , path = require('path')

var gulp = require('gulp')
  , concat = require('gulp-concat')
  , cssmin = require('gulp-cssmin')
  , gutil = require('gulp-util')
  , gzip = require('gulp-gzip')
  , less = require('gulp-less')
  , rename = require('gulp-rename')
  , tar = require('gulp-tar')
  , uglify = require('gulp-uglify')
  , watch = require('gulp-watch')

var bowerComponents = './bower_components'
  , dist = './assets'
  , src  = './src'

gulp.task('default', ['less', 'js', 'assets', 'vendor'])

gulp.task('less', function () {
  return compileLess()
})

gulp.task('js', function () {
  return compileJs()
})

gulp.task('assets', function () {
  var blogCover = path.join(src, 'img', 'the-wheat-field.jpg')

  return gulp.src(blogCover)
    .pipe(gulp.dest(path.join(dist, 'img')))
})

gulp.task('vendor', ['vendor-css', 'vendor-js', 'vendor-assets'])

gulp.task('vendor-css', ['vendor-less'], function () {
  var highlight = path.join(bowerComponents, 'highlightjs', 'styles', 'rainbow.css')
  var vendorLess = path.join('tmp', 'vendor-less.css')

  return gulp.src([highlight, vendorLess])
    .pipe(concat('vendor.css'))
    .pipe(cssmin())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-less', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome', 'less')

  return gulp.src(path.join(src, 'vendor-less', 'fontawesome.less'))
    .pipe(less({paths: [fontawesome]}))
    .pipe(rename({basename: 'vendor-less'}))
    .pipe(gulp.dest('tmp'))
})

gulp.task('vendor-js', function () {
  var highlight = path.join(bowerComponents, 'highlightjs', 'highlight.pack.js')
  return gulp.src([highlight])
    .pipe(concat('vendor.js'))
    .pipe(uglify())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-assets', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome')

  return gulp.src(path.join(fontawesome, 'fonts/*.*'), {base: fontawesome})
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('watch', function () {
  watch(path.join(src, 'less/*.less'), compileLess)
  watch(path.join(src, 'js/*.js'), compileJs)
})

gulp.task('clean', function (cb) {
  del([path.join(dist, 'vendor'), path.join(dist, 'css'), path.join(dist, 'js'), 'tmp', release + '.tar.gz'], cb)
})

gulp.task('package', ['default'], function () {
  var packageName = metadata.name + '-' + metadata.version
  return gulp.src([path.join(dist, '**/*.*'), 'partials/*.*', '*.hbs', 'package.json'], {base: '.'})
    .pipe(tar(packageName + '.tar'))
    .pipe(gzip())
    .pipe(gulp.dest('.'))
})

function compileJs() {
  gutil.log('Compiling js files.')
  return gulp.src(path.join(src, 'js/*.js'))
    .pipe(uglify())
    .pipe(rename({basename: 'all', suffix:'.min'}))
    .pipe(gulp.dest(path.join(dist, 'js')))
}

function compileLess() {
  gutil.log('Compiling less files.')
  return gulp.src(path.join(src, 'less/app.less'))
    .pipe(less({
      paths: [path.join(src, 'less')]
    }))
    .pipe(cssmin())
    .pipe(rename({basename: 'style'}))
    .pipe(gulp.dest(path.join(dist, 'css')))
}<commit_msg>change watch method<commit_after>var del = require('del')
  , metadata = require('./package')
  , path = require('path')

var gulp = require('gulp')
  , concat = require('gulp-concat')
  , cssmin = require('gulp-cssmin')
  , gutil = require('gulp-util')
  , gzip = require('gulp-gzip')
  , less = require('gulp-less')
  , rename = require('gulp-rename')
  , tar = require('gulp-tar')
  , uglify = require('gulp-uglify')
  , watch = require('gulp-watch')

var bowerComponents = './bower_components'
  , dist = './assets'
  , src  = './src'

gulp.task('default', ['less', 'js', 'assets', 'vendor'])

gulp.task('less', function () {
  return compileLess()
})

gulp.task('js', function () {
  return compileJs()
})

gulp.task('assets', function () {
  var blogCover = path.join(src, 'img', 'the-wheat-field.jpg')

  return gulp.src(blogCover)
    .pipe(gulp.dest(path.join(dist, 'img')))
})

gulp.task('vendor', ['vendor-css', 'vendor-js', 'vendor-assets'])

gulp.task('vendor-css', ['vendor-less'], function () {
  var highlight = path.join(bowerComponents, 'highlightjs', 'styles', 'rainbow.css')
  var vendorLess = path.join('tmp', 'vendor-less.css')

  return gulp.src([highlight, vendorLess])
    .pipe(concat('vendor.css'))
    .pipe(cssmin())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-less', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome', 'less')

  return gulp.src(path.join(src, 'vendor-less', 'fontawesome.less'))
    .pipe(less({paths: [fontawesome]}))
    .pipe(rename({basename: 'vendor-less'}))
    .pipe(gulp.dest('tmp'))
})

gulp.task('vendor-js', function () {
  var highlight = path.join(bowerComponents, 'highlightjs', 'highlight.pack.js')
  return gulp.src([highlight])
    .pipe(concat('vendor.js'))
    .pipe(uglify())
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('vendor-assets', function () {
  var fontawesome = path.join(bowerComponents, 'fontawesome')

  return gulp.src(path.join(fontawesome, 'fonts/*.*'), {base: fontawesome})
    .pipe(gulp.dest(path.join(dist, 'vendor')))
})

gulp.task('watch', function () {
  gulp.watch(path.join(src, 'less/*.less'), ['less'])
  //watch(path.join(src, 'js/*.js'), compileJs)
})

gulp.task('clean', function (cb) {
  del([path.join(dist, 'vendor'), path.join(dist, 'css'), path.join(dist, 'js'), 'tmp', release + '.tar.gz'], cb)
})

gulp.task('package', ['default'], function () {
  var packageName = metadata.name + '-' + metadata.version
  return gulp.src([path.join(dist, '**/*.*'), 'partials/*.*', '*.hbs', 'package.json'], {base: '.'})
    .pipe(tar(packageName + '.tar'))
    .pipe(gzip())
    .pipe(gulp.dest('.'))
})

function compileJs() {
  gutil.log('Compiling js files.')
  return gulp.src(path.join(src, 'js/*.js'))
    .pipe(uglify())
    .pipe(rename({basename: 'all', suffix:'.min'}))
    .pipe(gulp.dest(path.join(dist, 'js')))
}

function compileLess() {
  gutil.log('Compiling less files.')
  return gulp.src(path.join(src, 'less/app.less'))
    .pipe(less({
      paths: [path.join(src, 'less')]
    }))
    .pipe(cssmin())
    .pipe(rename({basename: 'style'}))
    .pipe(gulp.dest(path.join(dist, 'css')))
}<|endoftext|>


<commit_before>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * AbstractBox is the parent for VBox and HBox, which arrange child nodes.
 * See https://github.com/phetsims/scenery/issues/116
 *
 * @author Sam Reid
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Node = require( 'SCENERY/nodes/Node' );

  /**
   * Main constructor for AbstractBox.
   *
   * @param {object} options Same as Node.constructor.options with the following additions:
   *
   * spacing: can be a number or a function.  If a number, then it will be the spacing between each object.
   *              If a function, then the function will have the signature function(a,b){} which returns the spacing between adjacent pairs of items.
   * align:   How to line up the items, defaults to 'center'.
   *
   * @param {string} type 'vertical' or 'horizontal'
   * @param {function} layoutFunction the function to layout out the nodes (different for HBox and VBox)
   *
   * @constructor
   */
  scenery.AbstractBox = function AbstractBox( type, layoutFunction, options ) {
    assert && assert( type === 'vertical' || type === 'horizontal' );

    this.type = type;
    this.layoutFunction = layoutFunction;
    this.boundsListener = this.updateLayout.bind( this );

    // ensure we have a parameter object
    this.options = _.extend( {
      // defaults
      spacing: function() { return 0; },
      align: 'center',

      //By default, update the layout when children are added/removed/resized, see #116
      resize: true
    }, options );

    if ( typeof this.options.spacing === 'number' ) {
      var spacingConstant = this.options.spacing;
      this.options.spacing = function() { return spacingConstant; };
    }

    Node.call( this );

    //See HBox.js
    this.inited = false;
    this.mutate( this.options );
    this.inited = true;
  };
  var AbstractBox = scenery.AbstractBox;

  inherit( Node, AbstractBox, {
    updateLayout: function() {
      if ( !this.updatingLayout ) {
        //Bounds of children are changed in updateLayout, we don't want to stackoverflow so bail if already updating layout
        this.updatingLayout = true;
        this.layoutFunction.call( this );
        this.updatingLayout = false;
      }
    }
  } );

  //Override the child mutators to updateLayout
  //Have to listen to the child bounds individually because there are a number of possible ways to change the child
  //bounds without changing the overall bounds.
  var overrides = ['insertChild', 'removeChildWithIndex'];
  overrides.forEach( function( override ) {

    //Support up to two args for overrides
    AbstractBox.prototype[override] = function( arg1, arg2 ) {

      //Remove event listeners from any nodes (will be added back later if the node was not removed)
      var abstractBox = this;
      if ( this.options.resize ) {
        this.children.forEach( function( child ) {
          if ( child.containsEventListener( 'bounds', abstractBox.boundsListener ) ) {
            child.removeEventListener( 'bounds', abstractBox.boundsListener );
          }
        } );
      }

      //Super call
      Node.prototype[override].call( this, arg1, arg2 );

      //Update the layout if it should be dynamic
      if ( this.options.resize || !this.inited ) {
        this.updateLayout();
      }

      //Add event listeners for any current children (if it should be dynamic)
      if ( this.options.resize ) {
        this.children.forEach( function( child ) {
          if ( !child.containsEventListener( 'bounds', abstractBox.boundsListener ) ) {
            child.addEventListener( 'bounds', abstractBox.boundsListener );
          }
        } );
      }
    };
  } );

  return AbstractBox;
} );
<commit_msg>Port of https://github.com/phetsims/scenery/commit/211e9c42609f9e9010d383c981683ea24ac8dd84 for phet-core#11<commit_after>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * AbstractBox is the parent for VBox and HBox, which arrange child nodes.
 * See https://github.com/phetsims/scenery/issues/116
 *
 * @author Sam Reid
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Node = require( 'SCENERY/nodes/Node' );

  /**
   * Main constructor for AbstractBox.
   *
   * @param {Object} options Same as Node.constructor.options with the following additions:
   *
   * spacing: can be a number or a function.  If a number, then it will be the spacing between each object.
   *              If a function, then the function will have the signature function(a,b){} which returns the spacing between adjacent pairs of items.
   * align:   How to line up the items, defaults to 'center'.
   *
   * @param {string} type 'vertical' or 'horizontal'
   * @param {function} layoutFunction the function to layout out the nodes (different for HBox and VBox)
   *
   * @constructor
   */
  scenery.AbstractBox = function AbstractBox( type, layoutFunction, options ) {
    assert && assert( type === 'vertical' || type === 'horizontal' );

    this.type = type;
    this.layoutFunction = layoutFunction;
    this.boundsListener = this.updateLayout.bind( this );

    // ensure we have a parameter object
    this.options = _.extend( {
      // defaults
      spacing: function() { return 0; },
      align: 'center',

      //By default, update the layout when children are added/removed/resized, see #116
      resize: true
    }, options );

    if ( typeof this.options.spacing === 'number' ) {
      var spacingConstant = this.options.spacing;
      this.options.spacing = function() { return spacingConstant; };
    }

    Node.call( this );

    //See HBox.js
    this.inited = false;
    this.mutate( this.options );
    this.inited = true;
  };
  var AbstractBox = scenery.AbstractBox;

  inherit( Node, AbstractBox, {
    updateLayout: function() {
      if ( !this.updatingLayout ) {
        //Bounds of children are changed in updateLayout, we don't want to stackoverflow so bail if already updating layout
        this.updatingLayout = true;
        this.layoutFunction.call( this );
        this.updatingLayout = false;
      }
    }
  } );

  //Override the child mutators to updateLayout
  //Have to listen to the child bounds individually because there are a number of possible ways to change the child
  //bounds without changing the overall bounds.
  var overrides = ['insertChild', 'removeChildWithIndex'];
  overrides.forEach( function( override ) {

    //Support up to two args for overrides
    AbstractBox.prototype[override] = function( arg1, arg2 ) {

      //Remove event listeners from any nodes (will be added back later if the node was not removed)
      var abstractBox = this;
      if ( this.options.resize ) {
        this.children.forEach( function( child ) {
          if ( child.containsEventListener( 'bounds', abstractBox.boundsListener ) ) {
            child.removeEventListener( 'bounds', abstractBox.boundsListener );
          }
        } );
      }

      //Super call
      Node.prototype[override].call( this, arg1, arg2 );

      //Update the layout if it should be dynamic
      if ( this.options.resize || !this.inited ) {
        this.updateLayout();
      }

      //Add event listeners for any current children (if it should be dynamic)
      if ( this.options.resize ) {
        this.children.forEach( function( child ) {
          if ( !child.containsEventListener( 'bounds', abstractBox.boundsListener ) ) {
            child.addEventListener( 'bounds', abstractBox.boundsListener );
          }
        } );
      }
    };
  } );

  return AbstractBox;
} );
<|endoftext|>


<commit_before>// Dependencies that makes this all work! Yay packages!
var gulp = require('gulp'),
    cleanCSS = require('gulp-clean-css'),
    del = require('del'),
    dotenv_extended = require('dotenv-extended'),
    fs = require('fs'),
    git_rev = require('git-rev'),
    inlineCSS = require('gulp-inline-css'),
    preprocess = require('gulp-preprocess'),
    rename = require('gulp-rename'),
    strip = require('gulp-strip-comments');

// Load in environment variables from .boilerplate.defaults first and then .boilerplate.custom if it exists
var boilerplateConfig = dotenv_extended.load(
    {
        encoding: 'utf8',
        silent: true,
        path: '.boilerplate.custom',
        defaults: '.boilerplate.defaults',
        errorOnMissing: false,
        errorOnExtra: false,
        assignToProcessEnv: true,
        overrideProcessEnv: true
    }
);

// We need to check if DOCTYPE_VERSION is using an XHTML value for inline-css purposes later
var currentSetDoctype = process.env.DOCTYPE_VERSION;
if (/XHTML/i.test(currentSetDoctype)) {
    xmlMode = true;
}
else {
    xmlMode = false;
}

// Clean out /tmp and /dist directories each time gulp is run
gulp.task('clean', function () {
    return del(
        [
            'tmp/css/**',
            'tmp/html-samples/**',
            'dist/boilerplate/**'
        ]
    ).then(paths => {
        console.log('Cleaning directories :\n', paths.join('\n'));
    });
});

// Get Git revision details for use in boilerplate templates
gulp.task('git-rev-info', function() {
    // Get latest commit (short)
    git_rev.short(
        function(rev) {
            return process.env.GIT_REVISION_SHORT = rev;
        }
    )
    // Get latest commit (long)
    git_rev.long(
        function(rev) {
            return process.env.GIT_REVISION_LONG = rev;
        }
    )
    // Get branch name boilerplate is being generated from
    git_rev.branch(
        function(branch) {
            return process.env.GIT_BRANCH = branch;
        }
    )
});

// Preprocess CSS files with config values
gulp.task('preprocess-css', function() {
    var stream = gulp.src('./app/css/*.css')
    .pipe(preprocess())
    .pipe(gulp.dest('./tmp/css/'))
    return stream;
});

// Minify processed CSS for inclusion in the email boilerplate
gulp.task('minify-css', ['preprocess-css'], function() {
    var stream = gulp.src('./tmp/css/*.css')
    .pipe(cleanCSS(
        {
            advanced: false,
            keepSpecialComments: '*',
            aggressiveMerging: false,
            debug: true, // Needed for the size output on before and after min files
            keepBreaks: true,
            shorthandCompacting: false,
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        },
        // Log original size and minified size in gulp output
        function(details) {
            console.log(details.name + ': ' + details.stats.originalSize);
            console.log(details.name + '.min' + ': ' + details.stats.minifiedSize);
        })
    )
    .pipe(rename({ extname: '.css.min' }))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Remove CSS comments from minified files for production version of the boilerplate
gulp.task('remove-css-comments', ['minify-css'], function() {
    var stream = gulp.src('./tmp/css/*.css.min')
    .pipe(cleanCSS(
        {
            advanced: false,
            aggressiveMerging: false,
            keepBreaks: true,
            keepSpecialComments: 0,
            shorthandCompacting: false,
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        }
    ))
    .pipe(rename(
        function(path) {
            path.extname = "" // Drop extension to avoid double css naming
        }
    ))
    // Specific versions with no CSS comments for the production version
    .pipe(rename({ extname: '-nocomments.css.min'}))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Build all HTML samples, inline CSS and strip comments to be included in boilerplate
gulp.task('build-html-samples', function() {
    var stream = gulp.src('./app/html-samples/*.html')
    .pipe(preprocess())
    .pipe(inlineCSS(
        {
            applyStyleTags: true,
            removeStyleTags: true,
            removeHtmlSelectors: true,
            applyTableAttributes: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./tmp/html-samples/'));
    return stream;
});

// Strip HTML comments from HTML samples for to be included in boilerplate
gulp.task('remove-html-comments', ['build-html-samples'], function() {
    var stream = gulp.src('./tmp/html-samples/*.html')
    .pipe(strip(
        {
            ignore: /<!--\[if(?!\s*(?:\[[^\]]+]|<!|>))(?:(?!-->).)*-->/g, // Mantain MSO conditional comments
            safe: true,
            trim: true
        }
    ))
    .pipe(rename({ extname: '-nocomments.html'}))
    .pipe(gulp.dest('./tmp/html-samples/'));
    return stream;
});

// Build boilerplate and output the HTML versions
gulp.task('preprocess-boilerplate', ['remove-css-comments'], function() {
    var stream = gulp.src('app/email-boilerplate*')
    .pipe(preprocess({ extension: 'html' }))
    .pipe(rename(
        function(path) {
            path.extname = "" // Drop preprocess ext and change to .html
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'))
    return stream;
});

// Inline CSS to main layout elements after boilerplate is generated and update documents
gulp.task('inline-css', ['preprocess-boilerplate'], function() {
    var stream = gulp.src('./dist/boilerplate/*.html')
    .pipe(inlineCSS(
        {
            applyTableAttributes: true,
            applyWidthAttributes: true,
            applyStyleTags: false,
            applyLinkTags: true,
            removeStyleTags: false,
            removeLinkTags: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'));
    return stream;
});

// Detect certain configurations and warn in console when they are not optimal from recommended guidelines
gulp.task('check-config', ['inline-css'], function() {

    var isMsoNamespacesEnabled = process.env.ENABLE_VML_NAMESPACES;
    var isXuaCompatMetaTagEnabled = process.env.ENABLE_XUA_COMPATIBLE_META_TAG;
    var xuaCompatValue = process.env.XUA_COMPATIBLE_VALUE;
    var isViewportMetaTagEnabled = process.env.ENABLE_VIEWPORT_META_TAG;
    var viewportValue = process.env.VIEWPORT_META_VALUE;
    var isFormatDetectionEnabled = process.env.ENABLE_FORMAT_DETECTION_META_TAG;
    var formatDetectionValue = process.env.FORMAT_DETECTION_META_VALUE;
    var isYahooShortcutsCSSEnabled = process.env.ENABLE_YAHOO_SHORTCUTS_CSS;
    var isMsoDpiScalingFixEnabled = process.env.ENABLE_MSO_DPI_SCALING_FIX;
    var isWebkitMediaQueryEnabled = process.env.ENABLE_WEBKIT_DETECTION_QUERY;
    var isGeckoMediaQueryEnabled = process.env.ENABLE_GECKO_MEDIA_QUERY;
    var isIEMediaQueryEnabled = process.env.ENABLE_IE_10_11_MEDIA_QUERY;
    var isGmailAndroidFixEnabled = process.env.ENABLE_GMAIL_ANDROID_RESIZE_FIX;
    var isGmailiOSFontFixEnabled = process.env.ENABLE_GMAIL_IOS_FONT_FIX;
    var isTableContainerFixedWidth = process.env.TABLE_CONTAINER_FIXED_WIDTH;

    // Small function to re-use for warnings, because lazy
    function configWarn(configMessage) {
        var label = 'CONFIG WARNING:'
        console.warn(label, configMessage)
    }

    // While they act as booleans, they aren't actually REAL booleans (quacks like a duck etc..)

    if((isMsoNamespacesEnabled === 'false') && (isMsoDpiScalingFixEnabled === 'true')) {
        configWarn('ENABLE_VML_NAMESPACES should be set to true when ENABLE_MSO_DPI_SCALING_FIX is set to true');
    }

    if(isXuaCompatMetaTagEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_XUA_COMPATIBLE_META_TAG to true for better Windows Phone/IE compatibility');
    }

    if((isXuaCompatMetaTagEnabled === 'true') && (!/IE=edge/i.test(xuaCompatValue))) {
        configWarn('Using any other value than IE=edge for XUA_COMPATIBLE_VALUE is not recommended');
    }

    if(isViewportMetaTagEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_VIEWPORT_META_TAG to true for correct scaling on mobile devices');
    }

    if((isViewportMetaTagEnabled === 'true') && (/user-scalable=no/i.test(viewportValue))) {
        configWarn('You should not disable pinch zooming/resizing gestures, it is bad UX');
    }

    if((isFormatDetectionEnabled === 'true') && (/no/i.test(formatDetectionValue))) {
        configWarn('Disabling auto formatting data also disables any user interaction events i.e. tap to call');
    }

    if(isMsoDpiScalingFixEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_MSO_DPI_SCALING_FIX to true for fixing image scaling with DPI values higher than 96');
    }

    if(isYahooShortcutsCSSEnabled === 'true') {
        configWarn('Yahoo Shortcuts is no longer a feature of the Yahoo! Mail webmail client and does not need additional CSS to override');
    }

    if(isWebkitMediaQueryEnabled === 'true') {
        configWarn('The Webkit vendor prefixes return true on some non-webkit clients, do not rely on it for absolute accuracy');
    }

    if(isGeckoMediaQueryEnabled === 'true') {
        configWarn('The Gecko/Mozilla media query is often mangled in Yahoo! Mail and can cause unexpected CSS issues');
    }

    if(isIEMediaQueryEnabled === 'true') {
        configWarn('The IE 10/11 media query will also return true on IEMobile (Windows Phone 8.0/8.1)');
    }

    if((isGmailAndroidFixEnabled === 'true') && (isTableContainerFixedWidth === 'false')) {
        configWarn('You should set ENABLE_GMAIL_ANDROID_RESIZE_FIX to false when not using a fixed width container table');
    }

    if((isGmailiOSFontFixEnabled === 'true') && (isTableContainerFixedWidth === 'false')) {
        configWarn('You should set ENABLE_GMAIL_IOS_FONT_FIX to false when not using a fixed width container table');
    }

    if((isGmailiOSFontFixEnabled === 'true') || (isGmailAndroidFixEnabled === 'true')) {
        configWarn('Gmail app font/image spacer hacks for iOS and Android should be deprecated due to CSS3 support, see USAGE.md for more info');
    }

    // Check for older .env file
    fs.stat('.env', function(err, stat) {
        if(err == null) {
            configWarn('.env is deprecated, please rename your custom settings file to .boilerplate.custom');
        }
    });

});

// The order is important! The CSS preprocess stuff must happen first otherwise minify will break everything!
gulp.task('default',
    [
        'clean',
        'git-rev-info',
        'preprocess-css',
        'minify-css',
        'remove-css-comments',
        'build-html-samples',
        'remove-html-comments',
        'preprocess-boilerplate',
        'inline-css',
        'check-config'
    ]
);
<commit_msg>Ensure preprocess-boilerplate tasks runs after HTML samples have been generated<commit_after>// Dependencies that makes this all work! Yay packages!
var gulp = require('gulp'),
    cleanCSS = require('gulp-clean-css'),
    del = require('del'),
    dotenv_extended = require('dotenv-extended'),
    fs = require('fs'),
    git_rev = require('git-rev'),
    inlineCSS = require('gulp-inline-css'),
    preprocess = require('gulp-preprocess'),
    rename = require('gulp-rename'),
    strip = require('gulp-strip-comments');

// Load in environment variables from .boilerplate.defaults first and then .boilerplate.custom if it exists
var boilerplateConfig = dotenv_extended.load(
    {
        encoding: 'utf8',
        silent: true,
        path: '.boilerplate.custom',
        defaults: '.boilerplate.defaults',
        errorOnMissing: false,
        errorOnExtra: false,
        assignToProcessEnv: true,
        overrideProcessEnv: true
    }
);

// We need to check if DOCTYPE_VERSION is using an XHTML value for inline-css purposes later
var currentSetDoctype = process.env.DOCTYPE_VERSION;
if (/XHTML/i.test(currentSetDoctype)) {
    xmlMode = true;
}
else {
    xmlMode = false;
}

// Clean out /tmp and /dist directories each time gulp is run
gulp.task('clean', function () {
    return del(
        [
            'tmp/css/**',
            'tmp/html-samples/**',
            'dist/boilerplate/**'
        ]
    ).then(paths => {
        console.log('Cleaning directories :\n', paths.join('\n'));
    });
});

// Get Git revision details for use in boilerplate templates
gulp.task('git-rev-info', function() {
    // Get latest commit (short)
    git_rev.short(
        function(rev) {
            return process.env.GIT_REVISION_SHORT = rev;
        }
    )
    // Get latest commit (long)
    git_rev.long(
        function(rev) {
            return process.env.GIT_REVISION_LONG = rev;
        }
    )
    // Get branch name boilerplate is being generated from
    git_rev.branch(
        function(branch) {
            return process.env.GIT_BRANCH = branch;
        }
    )
});

// Preprocess CSS files with config values
gulp.task('preprocess-css', function() {
    var stream = gulp.src('./app/css/*.css')
    .pipe(preprocess())
    .pipe(gulp.dest('./tmp/css/'))
    return stream;
});

// Minify processed CSS for inclusion in the email boilerplate
gulp.task('minify-css', ['preprocess-css'], function() {
    var stream = gulp.src('./tmp/css/*.css')
    .pipe(cleanCSS(
        {
            advanced: false,
            keepSpecialComments: '*',
            aggressiveMerging: false,
            debug: true, // Needed for the size output on before and after min files
            keepBreaks: true,
            shorthandCompacting: false,
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        },
        // Log original size and minified size in gulp output
        function(details) {
            console.log(details.name + ': ' + details.stats.originalSize);
            console.log(details.name + '.min' + ': ' + details.stats.minifiedSize);
        })
    )
    .pipe(rename({ extname: '.css.min' }))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Remove CSS comments from minified files for production version of the boilerplate
gulp.task('remove-css-comments', ['minify-css'], function() {
    var stream = gulp.src('./tmp/css/*.css.min')
    .pipe(cleanCSS(
        {
            advanced: false,
            aggressiveMerging: false,
            keepBreaks: true,
            keepSpecialComments: 0,
            shorthandCompacting: false,
            compatibility: '*,' +
            '-properties.colors,' +
            '-properties.zeroUnits'
        }
    ))
    .pipe(rename(
        function(path) {
            path.extname = "" // Drop extension to avoid double css naming
        }
    ))
    // Specific versions with no CSS comments for the production version
    .pipe(rename({ extname: '-nocomments.css.min'}))
    .pipe(gulp.dest('./tmp/css/'));
    return stream;
});

// Build all HTML samples, inline CSS and strip comments to be included in boilerplate
gulp.task('build-html-samples', function() {
    var stream = gulp.src('./app/html-samples/*.html')
    .pipe(preprocess())
    .pipe(inlineCSS(
        {
            applyStyleTags: true,
            removeStyleTags: true,
            removeHtmlSelectors: true,
            applyTableAttributes: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./tmp/html-samples/'));
    return stream;
});

// Strip HTML comments from HTML samples for to be included in boilerplate
gulp.task('remove-html-comments', ['build-html-samples'], function() {
    var stream = gulp.src('./tmp/html-samples/*.html')
    .pipe(strip(
        {
            ignore: /<!--\[if(?!\s*(?:\[[^\]]+]|<!|>))(?:(?!-->).)*-->/g, // Mantain MSO conditional comments
            safe: true,
            trim: true
        }
    ))
    .pipe(rename({ extname: '-nocomments.html'}))
    .pipe(gulp.dest('./tmp/html-samples/'));
    return stream;
});

// Build boilerplate and output the HTML versions
gulp.task('preprocess-boilerplate', ['remove-html-comments'], function() {
    var stream = gulp.src('app/email-boilerplate*')
    .pipe(preprocess({ extension: 'html' }))
    .pipe(rename(
        function(path) {
            path.extname = "" // Drop preprocess ext and change to .html
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'))
    return stream;
});

// Inline CSS to main layout elements after boilerplate is generated and update documents
gulp.task('inline-css', ['preprocess-boilerplate'], function() {
    var stream = gulp.src('./dist/boilerplate/*.html')
    .pipe(inlineCSS(
        {
            applyTableAttributes: true,
            applyWidthAttributes: true,
            applyStyleTags: false,
            applyLinkTags: true,
            removeStyleTags: false,
            removeLinkTags: true,
            xmlMode: xmlMode
        }
    ))
    .pipe(gulp.dest('./dist/boilerplate/'));
    return stream;
});

// Detect certain configurations and warn in console when they are not optimal from recommended guidelines
gulp.task('check-config', ['inline-css'], function() {

    var isMsoNamespacesEnabled = process.env.ENABLE_VML_NAMESPACES;
    var isXuaCompatMetaTagEnabled = process.env.ENABLE_XUA_COMPATIBLE_META_TAG;
    var xuaCompatValue = process.env.XUA_COMPATIBLE_VALUE;
    var isViewportMetaTagEnabled = process.env.ENABLE_VIEWPORT_META_TAG;
    var viewportValue = process.env.VIEWPORT_META_VALUE;
    var isFormatDetectionEnabled = process.env.ENABLE_FORMAT_DETECTION_META_TAG;
    var formatDetectionValue = process.env.FORMAT_DETECTION_META_VALUE;
    var isYahooShortcutsCSSEnabled = process.env.ENABLE_YAHOO_SHORTCUTS_CSS;
    var isMsoDpiScalingFixEnabled = process.env.ENABLE_MSO_DPI_SCALING_FIX;
    var isWebkitMediaQueryEnabled = process.env.ENABLE_WEBKIT_DETECTION_QUERY;
    var isGeckoMediaQueryEnabled = process.env.ENABLE_GECKO_MEDIA_QUERY;
    var isIEMediaQueryEnabled = process.env.ENABLE_IE_10_11_MEDIA_QUERY;
    var isGmailAndroidFixEnabled = process.env.ENABLE_GMAIL_ANDROID_RESIZE_FIX;
    var isGmailiOSFontFixEnabled = process.env.ENABLE_GMAIL_IOS_FONT_FIX;
    var isTableContainerFixedWidth = process.env.TABLE_CONTAINER_FIXED_WIDTH;

    // Small function to re-use for warnings, because lazy
    function configWarn(configMessage) {
        var label = 'CONFIG WARNING:'
        console.warn(label, configMessage)
    }

    // While they act as booleans, they aren't actually REAL booleans (quacks like a duck etc..)

    if((isMsoNamespacesEnabled === 'false') && (isMsoDpiScalingFixEnabled === 'true')) {
        configWarn('ENABLE_VML_NAMESPACES should be set to true when ENABLE_MSO_DPI_SCALING_FIX is set to true');
    }

    if(isXuaCompatMetaTagEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_XUA_COMPATIBLE_META_TAG to true for better Windows Phone/IE compatibility');
    }

    if((isXuaCompatMetaTagEnabled === 'true') && (!/IE=edge/i.test(xuaCompatValue))) {
        configWarn('Using any other value than IE=edge for XUA_COMPATIBLE_VALUE is not recommended');
    }

    if(isViewportMetaTagEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_VIEWPORT_META_TAG to true for correct scaling on mobile devices');
    }

    if((isViewportMetaTagEnabled === 'true') && (/user-scalable=no/i.test(viewportValue))) {
        configWarn('You should not disable pinch zooming/resizing gestures, it is bad UX');
    }

    if((isFormatDetectionEnabled === 'true') && (/no/i.test(formatDetectionValue))) {
        configWarn('Disabling auto formatting data also disables any user interaction events i.e. tap to call');
    }

    if(isMsoDpiScalingFixEnabled === 'false') {
        configWarn('You should strongly consider setting ENABLE_MSO_DPI_SCALING_FIX to true for fixing image scaling with DPI values higher than 96');
    }

    if(isYahooShortcutsCSSEnabled === 'true') {
        configWarn('Yahoo Shortcuts is no longer a feature of the Yahoo! Mail webmail client and does not need additional CSS to override');
    }

    if(isWebkitMediaQueryEnabled === 'true') {
        configWarn('The Webkit vendor prefixes return true on some non-webkit clients, do not rely on it for absolute accuracy');
    }

    if(isGeckoMediaQueryEnabled === 'true') {
        configWarn('The Gecko/Mozilla media query is often mangled in Yahoo! Mail and can cause unexpected CSS issues');
    }

    if(isIEMediaQueryEnabled === 'true') {
        configWarn('The IE 10/11 media query will also return true on IEMobile (Windows Phone 8.0/8.1)');
    }

    if((isGmailAndroidFixEnabled === 'true') && (isTableContainerFixedWidth === 'false')) {
        configWarn('You should set ENABLE_GMAIL_ANDROID_RESIZE_FIX to false when not using a fixed width container table');
    }

    if((isGmailiOSFontFixEnabled === 'true') && (isTableContainerFixedWidth === 'false')) {
        configWarn('You should set ENABLE_GMAIL_IOS_FONT_FIX to false when not using a fixed width container table');
    }

    if((isGmailiOSFontFixEnabled === 'true') || (isGmailAndroidFixEnabled === 'true')) {
        configWarn('Gmail app font/image spacer hacks for iOS and Android should be deprecated due to CSS3 support, see USAGE.md for more info');
    }

    // Check for older .env file
    fs.stat('.env', function(err, stat) {
        if(err == null) {
            configWarn('.env is deprecated, please rename your custom settings file to .boilerplate.custom');
        }
    });

});

// The order is important! The CSS preprocess stuff must happen first otherwise minify will break everything!
gulp.task('default',
    [
        'clean',
        'git-rev-info',
        'preprocess-css',
        'minify-css',
        'remove-css-comments',
        'build-html-samples',
        'remove-html-comments',
        'preprocess-boilerplate',
        'inline-css',
        'check-config'
    ]
);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var babelify = require('babelify');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');

gulp.task('jsminify', function () {

    return browserify({entries: ['./src/js/main.jsx'], extensions: ['.jsx'], debug: false, standalone: "SBJS"}).transform(babelify)
        .bundle()
        .pipe(source('sbjs.min.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('build/js/'));

});

gulp.task('sass', function () {
    return gulp.src('./src/sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./build/css'));
});

//gulp.task("watch", ['jsminify'], function () {
//
//});

<commit_msg>change output name<commit_after>var gulp = require('gulp');
var babelify = require('babelify');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');

gulp.task('jsminify', function () {

    return browserify({entries: ['./src/js/main.jsx'], extensions: ['.jsx'], debug: false, standalone: "Kaas"}).transform(babelify)
        .bundle()
        .pipe(source('sbjs.min.js'))
        .pipe(buffer())
        .pipe(uglify())
        .pipe(gulp.dest('build/js/'));

});

gulp.task('sass', function () {
    return gulp.src('./src/sass/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./build/css'));
});

//gulp.task("watch", ['jsminify'], function () {
//
//});

<|endoftext|>


<commit_before>(function () {
// IMPORTS
//##########################################################
'use strict';
/* global require */
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
var browser = require('browser-sync');

// SETTINGS
//##########################################################
var paths = {
    'css': './static/css/',
    'images': './static/img/',
    'js': './static/js/',
    'media': './tmp/media/',
    'sass': './private/sass/',
    'html': './templates/'
};

var patterns = {
    'images': [paths.images+'*', paths.images+'**/*', '!'+paths.images+'/dummy/*/**'],
    'js': [paths.js+'*.js', paths.js+'**/*.js', '!'+paths.js+'*.min.js', '!'+paths.js+'**/*.min.js'],
    'media': [paths.media+'**/*'],
    'sass': [paths.sass+'*', paths.sass+'**/*']
};

// TASKS
//##########################################################
// TASKS/javascript
gulp.task('lint', function() {
    gulp.src(patterns.js.concat([paths.js+'!libs/*.js', './gulpfile.js']))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// TASK/browser reload
gulp.task('browser', function() {
    var files = [
        paths.html+'**/*.html',
        paths.css+'base.css',
        paths.js+'**/*min.js'
    ];

    browser.init(files, {
        proxy: 'localhost:' + process.env.PORT || '8000'
    });
});

// TASK/image preprocessing
gulp.task('static', function () {
    gulp.src(patterns.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.images));
});

gulp.task('media', function () {
    gulp.src(patterns.media)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.media));
});

// RUNNERS
//##########################################################
gulp.task('default', function () {

    // initial load
    // gulp.start('static'); start this manually
    gulp.start('lint');
    gulp.start('browser');

    // add watch tasks
    gulp.watch(patterns.js.concat(['./gulpfile.js']), ['lint']);

});

// end of gulpfile.js
}());<commit_msg>fix an issue with port assignment<commit_after>(function () {
// IMPORTS
//##########################################################
'use strict';
/* global require */
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
var browser = require('browser-sync');

// SETTINGS
//##########################################################
var paths = {
    'css': './static/css/',
    'images': './static/img/',
    'js': './static/js/',
    'media': './tmp/media/',
    'sass': './private/sass/',
    'html': './templates/'
};

var patterns = {
    'images': [paths.images+'*', paths.images+'**/*', '!'+paths.images+'/dummy/*/**'],
    'js': [paths.js+'*.js', paths.js+'**/*.js', '!'+paths.js+'*.min.js', '!'+paths.js+'**/*.min.js'],
    'media': [paths.media+'**/*'],
    'sass': [paths.sass+'*', paths.sass+'**/*']
};

var port = process.env.PORT || '8000';

// TASKS
//##########################################################
// TASKS/javascript
gulp.task('lint', function() {
    gulp.src(patterns.js.concat([paths.js+'!libs/*.js', './gulpfile.js']))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});

// TASK/browser reload
gulp.task('browser', function() {
    var files = [
        paths.html+'**/*.html',
        paths.css+'base.css',
        paths.js+'**/*min.js'
    ];

    browser.init(files, {
        proxy: 'localhost:' + port
    });
});

// TASK/image preprocessing
gulp.task('static', function () {
    gulp.src(patterns.images)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.images));
});

gulp.task('media', function () {
    gulp.src(patterns.media)
        .pipe(imagemin())
        .pipe(gulp.dest(paths.media));
});

// RUNNERS
//##########################################################
gulp.task('default', function () {

    // initial load
    // gulp.start('static'); start this manually
    gulp.start('lint');
    gulp.start('browser');

    // add watch tasks
    gulp.watch(patterns.js.concat(['./gulpfile.js']), ['lint']);

});

// end of gulpfile.js
}());<|endoftext|>


<commit_before>var taskResult = require('./taskresult');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var commonDefines = require('./../../Common/sources/commondefines');
var docsCoServer = require('./DocsCoServer');
var storage = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var statsDClient = require('./../../Common/sources/statsdclient');

//todo
var CONVERT_TIMEOUT = 6 * 60 * 1000;
var CONVERT_ASYNC_DELAY = 1000;

var clientStatsD = statsDClient.getClient();

function* getConvertStatus(cmd, selectRes, req) {
  var status = {url: undefined, err: constants.NO_ERROR};
  if (selectRes.length > 0) {
    var row = selectRes[0];
    switch (row.tr_status) {
      case taskResult.FileStatus.Ok:
        status.url = yield storage.getSignedUrl(utils.getBaseUrlByRequest(req), cmd.getDocId() + '/' + cmd.getOutputPath());
        break;
      case taskResult.FileStatus.Err:
      case taskResult.FileStatus.ErrToReload:
        status.err = row.tr_status_info;
        break;
    }
    var lastOpenDate = row.tr_last_open_date;
    //todo
    if (new Date().getTime() - lastOpenDate.getTime() > CONVERT_TIMEOUT) {
      status.err = constants.UNKNOWN;
    }
  }
  return status;
}

exports.convert = function(req, res) {
  utils.spawn(function* () {
    try {
      var startDate = null;
      if(clientStatsD) {
        startDate = new Date();
      }
      logger.debug('Start convert request');
      var cmd = new commonDefines.InputCommand();
      cmd.setCommand('conv');
      cmd.setVKey(req.query['vkey']);
      cmd.setUrl(req.query['url']);
      cmd.setEmbeddedFonts(false);//req.query['embeddedfonts'];
      cmd.setFormat(req.query['filetype']);
      var outputtype = req.query['outputtype'];
      cmd.setDocId('conv_' + req.query['key'] + '_' + outputtype);
      cmd.setTitle(constants.OUTPUT_NAME + '.' + outputtype);
      cmd.setOutputFormat(formatChecker.getFormatFromString(outputtype));
      cmd.setCodepage(req.query['codePage']);
      cmd.setCodepage(req.query['delimiter']);
      var async = 'true' == req.query['async'];

      var task = new taskResult.TaskResultData();
      task.key = cmd.getDocId();
      task.format = cmd.getFormat();
      task.status = taskResult.FileStatus.WaitQueue;
      task.statusInfo = constants.NO_ERROR;
      task.title = cmd.getTitle();

      var upsertRes = yield taskResult.upsert(task);
      //var bCreate = (upsertRes.affectedRows == 1);
      var bExist = (upsertRes.affectedRows > 1);
      var selectRes;
      var status;
      if (bExist) {
        selectRes = yield taskResult.select(task);
        status = yield* getConvertStatus(cmd, selectRes, req);
      } else {
        var queueData = new commonDefines.TaskQueueData();
        queueData.setCmd(cmd);
        queueData.setToFile(cmd.getTitle());
        yield* docsCoServer.addTask(queueData, constants.QUEUE_PRIORITY_LOW);
        //wait
        if (!async) {
          var waitTime = 0;
          while (true) {
            yield utils.sleep(CONVERT_ASYNC_DELAY);
            selectRes = yield taskResult.select(task);
            status = yield* getConvertStatus(cmd, selectRes, req);
            waitTime += CONVERT_ASYNC_DELAY;
            if (waitTime > CONVERT_TIMEOUT) {
              status.err = constants.CONVERT_TIMEOUT;
            }
            if (status.url || constants.NO_ERROR != status.err) {
              break;
            }
          }
        } else {
          status = {url: undefined, percent: 0, err: constants.NO_ERROR};
        }
      }
      utils.fillXmlResponse(res, status.url, status.err);
      logger.debug('End convert request');
      if(clientStatsD) {
        clientStatsD.timing('coauth.convertservice', new Date() - startDate);
      }
    }
    catch (e) {
      logger.error('error convert:\r\n%s', e.stack);
      utils.fillXmlResponse(res, undefined, constants.UNKNOWN);
    }
  });
};
<commit_msg>после Revision: 64999 отвалился converterservice<commit_after>var taskResult = require('./taskresult');
var logger = require('./../../Common/sources/logger');
var utils = require('./../../Common/sources/utils');
var constants = require('./../../Common/sources/constants');
var commonDefines = require('./../../Common/sources/commondefines');
var docsCoServer = require('./DocsCoServer');
var storage = require('./../../Common/sources/storage-base');
var formatChecker = require('./../../Common/sources/formatchecker');
var statsDClient = require('./../../Common/sources/statsdclient');

//todo
var CONVERT_TIMEOUT = 6 * 60 * 1000;
var CONVERT_ASYNC_DELAY = 1000;

var clientStatsD = statsDClient.getClient();

function* getConvertStatus(cmd, selectRes, req) {
  var status = {url: undefined, err: constants.NO_ERROR};
  if (selectRes.length > 0) {
    var row = selectRes[0];
    switch (row.tr_status) {
      case taskResult.FileStatus.Ok:
        status.url = yield storage.getSignedUrl(utils.getBaseUrlByRequest(req), cmd.getDocId() + '/' + cmd.getTitle());
        break;
      case taskResult.FileStatus.Err:
      case taskResult.FileStatus.ErrToReload:
        status.err = row.tr_status_info;
        break;
    }
    var lastOpenDate = row.tr_last_open_date;
    //todo
    if (new Date().getTime() - lastOpenDate.getTime() > CONVERT_TIMEOUT) {
      status.err = constants.UNKNOWN;
    }
  }
  return status;
}

exports.convert = function(req, res) {
  utils.spawn(function* () {
    try {
      var startDate = null;
      if(clientStatsD) {
        startDate = new Date();
      }
      logger.debug('Start convert request');
      var cmd = new commonDefines.InputCommand();
      cmd.setCommand('conv');
      cmd.setVKey(req.query['vkey']);
      cmd.setUrl(req.query['url']);
      cmd.setEmbeddedFonts(false);//req.query['embeddedfonts'];
      cmd.setFormat(req.query['filetype']);
      var outputtype = req.query['outputtype'];
      cmd.setDocId('conv_' + req.query['key'] + '_' + outputtype);
      cmd.setTitle(constants.OUTPUT_NAME + '.' + outputtype);
      cmd.setOutputFormat(formatChecker.getFormatFromString(outputtype));
      cmd.setCodepage(req.query['codePage']);
      cmd.setCodepage(req.query['delimiter']);
      var async = 'true' == req.query['async'];

      var task = new taskResult.TaskResultData();
      task.key = cmd.getDocId();
      task.format = cmd.getFormat();
      task.status = taskResult.FileStatus.WaitQueue;
      task.statusInfo = constants.NO_ERROR;
      task.title = cmd.getTitle();

      var upsertRes = yield taskResult.upsert(task);
      //var bCreate = (upsertRes.affectedRows == 1);
      var bExist = (upsertRes.affectedRows > 1);
      var selectRes;
      var status;
      if (bExist) {
        selectRes = yield taskResult.select(task);
        status = yield* getConvertStatus(cmd, selectRes, req);
      } else {
        var queueData = new commonDefines.TaskQueueData();
        queueData.setCmd(cmd);
        queueData.setToFile(cmd.getTitle());
        yield* docsCoServer.addTask(queueData, constants.QUEUE_PRIORITY_LOW);
        //wait
        if (!async) {
          var waitTime = 0;
          while (true) {
            yield utils.sleep(CONVERT_ASYNC_DELAY);
            selectRes = yield taskResult.select(task);
            status = yield* getConvertStatus(cmd, selectRes, req);
            waitTime += CONVERT_ASYNC_DELAY;
            if (waitTime > CONVERT_TIMEOUT) {
              status.err = constants.CONVERT_TIMEOUT;
            }
            if (status.url || constants.NO_ERROR != status.err) {
              break;
            }
          }
        } else {
          status = {url: undefined, percent: 0, err: constants.NO_ERROR};
        }
      }
      utils.fillXmlResponse(res, status.url, status.err);
      logger.debug('End convert request');
      if(clientStatsD) {
        clientStatsD.timing('coauth.convertservice', new Date() - startDate);
      }
    }
    catch (e) {
      logger.error('error convert:\r\n%s', e.stack);
      utils.fillXmlResponse(res, undefined, constants.UNKNOWN);
    }
  });
};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
	clean = require('gulp-clean'),
	path = require('path'),
	Server = require('karma').Server,
	concat = require('gulp-concat'),
	templateCache = require('gulp-angular-templatecache'),
	uglify = require('gulp-uglify'),
	rename = require("gulp-rename"),
	ngAnnotate = require('gulp-ng-annotate');

// Use the gulp-angular-templatecache in order to create JS file of HTML templates to
// make it easier to use in AngularJS directive
gulp.task('templates', function () {
	return gulp.src('src/**/*.html')
		.pipe(templateCache('templates.tmp',
			{
				module: 'hm.readmore'
			}
		))
		.pipe(gulp.dest('.'));
});

gulp.task('concat', ['templates'], function () {
	return gulp.src(['./src/readmore.js', 'templates.tmp'])
		.pipe(concat('readmore.js'))
		.pipe(gulp.dest('./dist/'));
});

gulp.task('clean', ['concat'], function () {
	gulp.src('./*.tmp', {read: false})
		.pipe(clean());
});

// Need to do ngAnnotate before uglify in order to keep the angular dependency injections after compress
gulp.task('compress', ['concat'], function () {
	return gulp.src('dist/readmore.js')
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(rename({
			extname: '.min.js'
		}))
		.pipe(gulp.dest('./dist/'));
});

gulp.task('build', ['templates', 'concat', 'compress', 'clean']);

gulp.task('test', ['build'], function (done) {
	new Server({
		configFile: path.join(__dirname, '/karma.conf.js'),
		singleRun: true
	}, done).start();
});
<commit_msg>added gulp watch task<commit_after>'use strict';

var gulp = require('gulp'),
	clean = require('gulp-clean'),
	path = require('path'),
	Server = require('karma').Server,
	concat = require('gulp-concat'),
	templateCache = require('gulp-angular-templatecache'),
	uglify = require('gulp-uglify'),
	rename = require("gulp-rename"),
	ngAnnotate = require('gulp-ng-annotate');

// Use the gulp-angular-templatecache in order to create JS file of HTML templates to
// make it easier to use in AngularJS directive
gulp.task('templates', function () {
	return gulp.src('src/**/*.html')
		.pipe(templateCache('templates.tmp',
			{
				module: 'hm.readmore'
			}
		))
		.pipe(gulp.dest('.'));
});

gulp.task('concat', ['templates'], function () {
	return gulp.src(['./src/readmore.js', 'templates.tmp'])
		.pipe(concat('readmore.js'))
		.pipe(gulp.dest('./dist/'));
});

gulp.task('clean', ['concat'], function () {
	gulp.src('./*.tmp', {read: false})
		.pipe(clean());
});

// Need to do ngAnnotate before uglify in order to keep the angular dependency injections after compress
gulp.task('compress', ['concat'], function () {
	return gulp.src('dist/readmore.js')
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(rename({
			extname: '.min.js'
		}))
		.pipe(gulp.dest('./dist/'));
});

gulp.task('build', ['templates', 'concat', 'compress', 'clean']);

gulp.task('test', ['build'], function (done) {
	new Server({
		configFile: path.join(__dirname, '/karma.conf.js'),
		singleRun: true
	}, done).start();
});

gulp.task('watch', ['build'], function () {
	gulp.watch('src/**/*.*', ['build']);
});
<|endoftext|>