<commit_before>define(["Tone/core/Tone"], function (Tone) {

	/**
	 *  @class  Wrapper around the native Web Audio's
	 *          [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode).
	 *          Extracts FFT or Waveform data from the incoming signal.
	 *  @extends {Tone}
	 *  @param {Number=} size The size of the FFT. Value must be a power of
	 *                       two in the range 32 to 32768.
	 *  @param {String=} type The return type of the analysis, either "byte", or "float".
	 */
	Tone.Analyser = function(){

		var options = this.optionsObject(arguments, ["size", "type"], Tone.Analyser.defaults);

		/**
		 *  The analyser node.
		 *  @private
		 *  @type {AnalyserNode}
		 */
		this._analyser = this.input = this.context.createAnalyser();

		/**
		 *  The analysis type
		 *  @type {String}
		 *  @private
		 */
		this._type = options.type;

		/**
		 *  The return type of the analysis
		 *  @type {String}
		 *  @private
		 */
		this._returnType = options.returnType;

		/**
		 *  The buffer that the FFT data is written to
		 *  @type {TypedArray}
		 *  @private
		 */
		this._buffer = null;

		//set the values initially
		this.size = options.size;
		this.type = options.type;
		this.returnType = options.returnType;
		this.minDecibels = options.minDecibels;
		this.maxDecibels = options.maxDecibels;
	};

	Tone.extend(Tone.Analyser);

	/**
	 *  The default values.
	 *  @type {Object}
	 *  @const
	 */
	Tone.Analyser.defaults = {
		"size" : 2048,
		"returnType" : "byte",
		"type" : "fft",
		"smoothing" : 0.8,
		"maxDecibels" : -30,
		"minDecibels" : -100
	};

	/**
	 *  Possible return types of Tone.Analyser.value
	 *  @enum {String}
	 */
	Tone.Analyser.Type = {
		Waveform : "waveform",
		FFT : "fft"
	};

	/**
	 *  Possible return types of Tone.Analyser.value
	 *  @enum {String}
	 */
	Tone.Analyser.ReturnType = {
		Byte : "byte",
		Float : "float"
	};

	/**
	 *  Run the analysis given the current settings and return the
	 *  result as a TypedArray.
	 *  @returns {TypedArray}
	 */
	Tone.Analyser.prototype.analyse = function(){
		if (this._type === Tone.Analyser.Type.FFT){
			if (this._returnType === Tone.Analyser.ReturnType.Byte){
				this._analyser.getByteFrequencyData(this._buffer);
			} else {
				this._analyser.getFloatFrequencyData(this._buffer);
			}
		} else if (this._type === Tone.Analyser.Type.Waveform){
			if (this._returnType === Tone.Analyser.ReturnType.Byte){
				this._analyser.getByteTimeDomainData(this._buffer);
			} else {
				this._analyser.getFloatTimeDomainData(this._buffer);
			}
		}
		return this._buffer;
	};

	/**
	 *  The size of analysis. This must be a power of two in the range 32 to 32768.
	 *  @memberOf Tone.Analyser#
	 *  @type {Number}
	 *  @name size
	 */
	Object.defineProperty(Tone.Analyser.prototype, "size", {
		get : function(){
			return this._analyser.frequencyBinCount;
		},
		set : function(size){
			this._analyser.fftSize = size * 2;
			this.type = this._type;
		}
	});

	/**
	 *  The return type of Tone.Analyser.value, either "byte" or "float".
	 *  When the type is set to "byte" the range of values returned in the array
	 *  are between 0-255, when set to "float" the values are between 0-1.
	 *  @memberOf Tone.Analyser#
	 *  @type {String}
	 *  @name type
	 */
	Object.defineProperty(Tone.Analyser.prototype, "returnType", {
		get : function(){
			return this._returnType;
		},
		set : function(type){
			if (type === Tone.Analyser.ReturnType.Byte){
				this._buffer = new Uint8Array(this._analyser.frequencyBinCount);
			} else if (type === Tone.Analyser.ReturnType.Float){
				this._buffer = new Float32Array(this._analyser.frequencyBinCount);
			} else {
				throw new Error("Invalid Return Type: "+type);
			}
			this._returnType = type;
		}
	});

	/**
	 *  The analysis function returned by Tone.Analyser.value, either "fft" or "waveform".
	 *  @memberOf Tone.Analyser#
	 *  @type {String}
	 *  @name type
	 */
	Object.defineProperty(Tone.Analyser.prototype, "type", {
		get : function(){
			return this._type;
		},
		set : function(type){
			if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT){
				throw new Error("Invalid Type: "+type);
			}
			this._type = type;
		}
	});

	/**
	 *  0 represents no time averaging with the last analysis frame.
	 *  @memberOf Tone.Analyser#
	 *  @type {NormalRange}
	 *  @name smoothing
	 */
	Object.defineProperty(Tone.Analyser.prototype, "smoothing", {
		get : function(){
			return this._analyser.smoothingTimeConstant;
		},
		set : function(val){
			this._analyser.smoothingTimeConstant = val;
		}
	});

	/**
	 *  The smallest decibel value which is analysed by the FFT.
	 *  @memberOf Tone.Analyser#
	 *  @type {Decibels}
	 *  @name minDecibels
	 */
	Object.defineProperty(Tone.Analyser.prototype, "minDecibels", {
		get : function(){
			return this._analyser.minDecibels;
		},
		set : function(val){
			this._analyser.minDecibels = val;
		}
	});

	/**
	 *  The largest decibel value which is analysed by the FFT.
	 *  @memberOf Tone.Analyser#
	 *  @type {Decibels}
	 *  @name maxDecibels
	 */
	Object.defineProperty(Tone.Analyser.prototype, "maxDecibels", {
		get : function(){
			return this._analyser.maxDecibels;
		},
		set : function(val){
			this._analyser.maxDecibels = val;
		}
	});

	/**
	 *  Clean up.
	 *  @return  {Tone.Analyser}  this
	 */
	Tone.Analyser.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this._analyser.disconnect();
		this._analyser = null;
		this._buffer = null;
	};

	return Tone.Analyser;
});<commit_msg>fixing doc description of analyser<commit_after>define(["Tone/core/Tone"], function (Tone) {

	/**
	 *  @class  Wrapper around the native Web Audio's
	 *          [AnalyserNode](http://webaudio.github.io/web-audio-api/#idl-def-AnalyserNode).
	 *          Extracts FFT or Waveform data from the incoming signal.
	 *  @extends {Tone}
	 *  @param {Number=} size The size of the FFT. Value must be a power of
	 *                       two in the range 32 to 32768.
	 *  @param {String=} type The return type of the analysis, either "fft", or "waveform".
	 */
	Tone.Analyser = function(){

		var options = this.optionsObject(arguments, ["size", "type"], Tone.Analyser.defaults);

		/**
		 *  The analyser node.
		 *  @private
		 *  @type {AnalyserNode}
		 */
		this._analyser = this.input = this.context.createAnalyser();

		/**
		 *  The analysis type
		 *  @type {String}
		 *  @private
		 */
		this._type = options.type;

		/**
		 *  The return type of the analysis
		 *  @type {String}
		 *  @private
		 */
		this._returnType = options.returnType;

		/**
		 *  The buffer that the FFT data is written to
		 *  @type {TypedArray}
		 *  @private
		 */
		this._buffer = null;

		//set the values initially
		this.size = options.size;
		this.type = options.type;
		this.returnType = options.returnType;
		this.minDecibels = options.minDecibels;
		this.maxDecibels = options.maxDecibels;
	};

	Tone.extend(Tone.Analyser);

	/**
	 *  The default values.
	 *  @type {Object}
	 *  @const
	 */
	Tone.Analyser.defaults = {
		"size" : 2048,
		"returnType" : "byte",
		"type" : "fft",
		"smoothing" : 0.8,
		"maxDecibels" : -30,
		"minDecibels" : -100
	};

	/**
	 *  Possible return types of Tone.Analyser.value
	 *  @enum {String}
	 */
	Tone.Analyser.Type = {
		Waveform : "waveform",
		FFT : "fft"
	};

	/**
	 *  Possible return types of Tone.Analyser.value
	 *  @enum {String}
	 */
	Tone.Analyser.ReturnType = {
		Byte : "byte",
		Float : "float"
	};

	/**
	 *  Run the analysis given the current settings and return the
	 *  result as a TypedArray.
	 *  @returns {TypedArray}
	 */
	Tone.Analyser.prototype.analyse = function(){
		if (this._type === Tone.Analyser.Type.FFT){
			if (this._returnType === Tone.Analyser.ReturnType.Byte){
				this._analyser.getByteFrequencyData(this._buffer);
			} else {
				this._analyser.getFloatFrequencyData(this._buffer);
			}
		} else if (this._type === Tone.Analyser.Type.Waveform){
			if (this._returnType === Tone.Analyser.ReturnType.Byte){
				this._analyser.getByteTimeDomainData(this._buffer);
			} else {
				this._analyser.getFloatTimeDomainData(this._buffer);
			}
		}
		return this._buffer;
	};

	/**
	 *  The size of analysis. This must be a power of two in the range 32 to 32768.
	 *  @memberOf Tone.Analyser#
	 *  @type {Number}
	 *  @name size
	 */
	Object.defineProperty(Tone.Analyser.prototype, "size", {
		get : function(){
			return this._analyser.frequencyBinCount;
		},
		set : function(size){
			this._analyser.fftSize = size * 2;
			this.type = this._type;
		}
	});

	/**
	 *  The return type of Tone.Analyser.value, either "byte" or "float".
	 *  When the type is set to "byte" the range of values returned in the array
	 *  are between 0-255, when set to "float" the values are between 0-1.
	 *  @memberOf Tone.Analyser#
	 *  @type {String}
	 *  @name type
	 */
	Object.defineProperty(Tone.Analyser.prototype, "returnType", {
		get : function(){
			return this._returnType;
		},
		set : function(type){
			if (type === Tone.Analyser.ReturnType.Byte){
				this._buffer = new Uint8Array(this._analyser.frequencyBinCount);
			} else if (type === Tone.Analyser.ReturnType.Float){
				this._buffer = new Float32Array(this._analyser.frequencyBinCount);
			} else {
				throw new Error("Invalid Return Type: "+type);
			}
			this._returnType = type;
		}
	});

	/**
	 *  The analysis function returned by Tone.Analyser.value, either "fft" or "waveform".
	 *  @memberOf Tone.Analyser#
	 *  @type {String}
	 *  @name type
	 */
	Object.defineProperty(Tone.Analyser.prototype, "type", {
		get : function(){
			return this._type;
		},
		set : function(type){
			if (type !== Tone.Analyser.Type.Waveform && type !== Tone.Analyser.Type.FFT){
				throw new Error("Invalid Type: "+type);
			}
			this._type = type;
		}
	});

	/**
	 *  0 represents no time averaging with the last analysis frame.
	 *  @memberOf Tone.Analyser#
	 *  @type {NormalRange}
	 *  @name smoothing
	 */
	Object.defineProperty(Tone.Analyser.prototype, "smoothing", {
		get : function(){
			return this._analyser.smoothingTimeConstant;
		},
		set : function(val){
			this._analyser.smoothingTimeConstant = val;
		}
	});

	/**
	 *  The smallest decibel value which is analysed by the FFT.
	 *  @memberOf Tone.Analyser#
	 *  @type {Decibels}
	 *  @name minDecibels
	 */
	Object.defineProperty(Tone.Analyser.prototype, "minDecibels", {
		get : function(){
			return this._analyser.minDecibels;
		},
		set : function(val){
			this._analyser.minDecibels = val;
		}
	});

	/**
	 *  The largest decibel value which is analysed by the FFT.
	 *  @memberOf Tone.Analyser#
	 *  @type {Decibels}
	 *  @name maxDecibels
	 */
	Object.defineProperty(Tone.Analyser.prototype, "maxDecibels", {
		get : function(){
			return this._analyser.maxDecibels;
		},
		set : function(val){
			this._analyser.maxDecibels = val;
		}
	});

	/**
	 *  Clean up.
	 *  @return  {Tone.Analyser}  this
	 */
	Tone.Analyser.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this._analyser.disconnect();
		this._analyser = null;
		this._buffer = null;
	};

	return Tone.Analyser;
});<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

var App = require('app');

App.ExperimentalController = Em.Controller.extend(App.UserPref, {
  name: 'experimentalController',
  supports: function () {
    return Em.keys(App.get('supports')).map(function (sup) {
      return Ember.Object.create({
        name: sup,
        selected: App.get('supports')[sup]
      });
    });
  }.property('App.supports'),

  loadSupports: function () {
    return this.getUserPref('user-pref-' + App.router.get('loginName') + '-supports');
  },

  getUserPrefSuccessCallback: function (response, request, data) {
    if (response) {
      App.set('supports', $.merge(response, App.get('supports')));
    }
  },

  doSave: function () {
    var supports = this.get('supports');
    supports.forEach(function(s){
      var propName = 'App.supports.' + s.get('name');
      var propValue = s.get('selected');
      Ember.set(propName, propValue);
    });
    this.postUserPref('user-pref-' + App.router.get('loginName') + '-supports', App.get('supports')).complete(function(){
      App.router.transitionTo('root.index');
    });
  },

  doCancel: function () {
    App.router.transitionTo('root.index');
  },

  doResetUIStates: function () {
    var self = this;
    return App.ModalPopup.show({
      header: Em.I18n.t('reset.ui.states'),
      bodyClass: Ember.View.extend({
        template: Ember.Handlebars.compile(Em.I18n.t('reset.ui.states.body'))
      }),
      primary: Em.I18n.t('yes'),
      context: self,
      onPrimary: function () {
        var router = App.router;
        App.db.cleanUp();
        router.clearAllSteps();
        App.cache.clear();
        App.clusterStatus.setClusterStatus({});
        this.context.postUserPref('wizard-data', {});
        this.hide();
        router.transitionTo('root.index');
      }
    });
  }
});
<commit_msg>AMBARI-20158 - Host filter is missing for admin user after upgrading to ambari 2.4.2 or above <fix1> (rzang)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

var App = require('app');

App.ExperimentalController = Em.Controller.extend(App.UserPref, {
  name: 'experimentalController',
  supports: function () {
    return Em.keys(App.get('supports')).map(function (sup) {
      return Ember.Object.create({
        name: sup,
        selected: App.get('supports')[sup]
      });
    });
  }.property('App.supports'),

  loadSupports: function () {
    return this.getUserPref('user-pref-' + App.router.get('loginName') + '-supports');
  },

  getUserPrefSuccessCallback: function (response, request, data) {
    if (response) {
      App.set('supports', $.extend(App.get('supports'), response));
    }
  },

  doSave: function () {
    var supports = this.get('supports');
    supports.forEach(function(s){
      var propName = 'App.supports.' + s.get('name');
      var propValue = s.get('selected');
      Ember.set(propName, propValue);
    });
    this.postUserPref('user-pref-' + App.router.get('loginName') + '-supports', App.get('supports')).complete(function(){
      App.router.transitionTo('root.index');
    });
  },

  doCancel: function () {
    App.router.transitionTo('root.index');
  },

  doResetUIStates: function () {
    var self = this;
    return App.ModalPopup.show({
      header: Em.I18n.t('reset.ui.states'),
      bodyClass: Ember.View.extend({
        template: Ember.Handlebars.compile(Em.I18n.t('reset.ui.states.body'))
      }),
      primary: Em.I18n.t('yes'),
      context: self,
      onPrimary: function () {
        var router = App.router;
        App.db.cleanUp();
        router.clearAllSteps();
        App.cache.clear();
        App.clusterStatus.setClusterStatus({});
        this.context.postUserPref('wizard-data', {});
        this.hide();
        router.transitionTo('root.index');
      }
    });
  }
});
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/type/Time"], function (Tone) {

	/**
	 *  @class Tone.TransportTime is a the time along the Transport's
	 *         timeline. It is similar to Tone.Time, but instead of evaluating
	 *         against the AudioContext's clock, it is evaluated against
	 *         the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).
	 *  @constructor
	 *  @param  {Time}  val    The time value as a number or string
	 *  @param  {String=}  units  Unit values
	 *  @extends {Tone.Time}
	 */
	Tone.TransportTime = function(val, units){
		if (this instanceof Tone.TransportTime){

			Tone.Time.call(this, val, units);

		} else {
			return new Tone.TransportTime(val, units);
		}
	};

	Tone.extend(Tone.TransportTime, Tone.Time);

	//clone the expressions so that
	//we can add more without modifying the original
	Tone.TransportTime.prototype._unaryExpressions = Object.create(Tone.Time.prototype._unaryExpressions);

	/**
	 *  Adds an additional unary expression
	 *  which quantizes values to the next subdivision
	 *  @type {Object}
	 *  @private
	 */
	Tone.TransportTime.prototype._unaryExpressions.quantize = {
		regexp : /^@/,
		method : function(rh){
			var subdivision = this._secondsToTicks(rh());
			var multiple = Math.ceil(Tone.Transport.ticks / subdivision);
			return this._ticksToUnits(multiple * subdivision);
		}
	};

	/**
	 *  Convert seconds into ticks
	 *  @param {Seconds} seconds
	 *  @return  {Ticks}
	 *  @private
	 */
	Tone.TransportTime.prototype._secondsToTicks = function(seconds){
		var quarterTime = this._beatsToUnits(1);
		var quarters = seconds / quarterTime;
		return Math.round(quarters * Tone.Transport.PPQ);
	};

	/**
	 *  Evaluate the time expression. Returns values in ticks
	 *  @return {Ticks}
	 */
	Tone.TransportTime.prototype.eval = function(){
		var val = this._secondsToTicks(this._expr());
		return val + (this._plusNow ? Tone.Transport.ticks : 0);
	};

	/**
	 *  Return the time in ticks.
	 *  @return  {Ticks}
	 */
	Tone.TransportTime.prototype.toTicks = function(){
		return this.eval();
	};

	/**
	 *  Return the time as a frequency value
	 *  @return  {Frequency}
	 */
	Tone.TransportTime.prototype.toFrequency = function(){
		return 1/this.toSeconds();
	};

	return Tone.TransportTime;
});<commit_msg>added toSeconds method<commit_after>define(["Tone/core/Tone", "Tone/type/Time"], function (Tone) {

	/**
	 *  @class Tone.TransportTime is a the time along the Transport's
	 *         timeline. It is similar to Tone.Time, but instead of evaluating
	 *         against the AudioContext's clock, it is evaluated against
	 *         the Transport's position. See [TransportTime wiki](https://github.com/Tonejs/Tone.js/wiki/TransportTime).
	 *  @constructor
	 *  @param  {Time}  val    The time value as a number or string
	 *  @param  {String=}  units  Unit values
	 *  @extends {Tone.Time}
	 */
	Tone.TransportTime = function(val, units){
		if (this instanceof Tone.TransportTime){

			Tone.Time.call(this, val, units);

		} else {
			return new Tone.TransportTime(val, units);
		}
	};

	Tone.extend(Tone.TransportTime, Tone.Time);

	//clone the expressions so that
	//we can add more without modifying the original
	Tone.TransportTime.prototype._unaryExpressions = Object.create(Tone.Time.prototype._unaryExpressions);

	/**
	 *  Adds an additional unary expression
	 *  which quantizes values to the next subdivision
	 *  @type {Object}
	 *  @private
	 */
	Tone.TransportTime.prototype._unaryExpressions.quantize = {
		regexp : /^@/,
		method : function(rh){
			var subdivision = this._secondsToTicks(rh());
			var multiple = Math.ceil(Tone.Transport.ticks / subdivision);
			return this._ticksToUnits(multiple * subdivision);
		}
	};

	/**
	 *  Convert seconds into ticks
	 *  @param {Seconds} seconds
	 *  @return  {Ticks}
	 *  @private
	 */
	Tone.TransportTime.prototype._secondsToTicks = function(seconds){
		var quarterTime = this._beatsToUnits(1);
		var quarters = seconds / quarterTime;
		return Math.round(quarters * Tone.Transport.PPQ);
	};

	/**
	 *  Evaluate the time expression. Returns values in ticks
	 *  @return {Ticks}
	 */
	Tone.TransportTime.prototype.eval = function(){
		var val = this._secondsToTicks(this._expr());
		return val + (this._plusNow ? Tone.Transport.ticks : 0);
	};

	/**
	 *  Return the time in ticks.
	 *  @return  {Ticks}
	 */
	Tone.TransportTime.prototype.toTicks = function(){
		return this.eval();
	};

	/**
	 *  Return the time in seconds.
	 *  @return  {Seconds}
	 */
	Tone.TransportTime.prototype.toSeconds = function(){
		var val = this._expr();
		return val + (this._plusNow ? Tone.Transport.seconds : 0);
	};

	/**
	 *  Return the time as a frequency value
	 *  @return  {Frequency}
	 */
	Tone.TransportTime.prototype.toFrequency = function(){
		return 1/this.toSeconds();
	};

	return Tone.TransportTime;
});<|endoftext|>


<commit_before>var express = require('express')
  , app = module.exports = express()
  , fs = require('fs')
  , path = require('path')
  , md = require('./markdown-it.js').md
  , temp = require('temp')
  , phantom = require('phantom')
  ;

  var phantomSession = phantom.create()
  function getPhantomSession() {
    return phantomSession
  }

  function _getFullHtml(name, str, style) {
    return '<!DOCTYPE html><meta charset="utf-8"><title>'
      + name + '</title>\n'
      + md.render(str) + '\n';
  }

  function _getHtml(str) {
    return md.render(str)
  }

  // Move this into _getFormat() to reload the CSS without restarting node.
  var _format = fs.readFileSync( path.resolve(__dirname, '../../public/css/app.css') ).toString('utf-8');
  function _getFormat() {
      return _format;
  }

  var fetchMd = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
      {
        data: ''
      , error: false
      }

    var name = req.body.name.trim()

    if(!name.includes('.md')){
      name = name + '.md'
    }

   res.attachment( name );
   res.end( unmd );
  }

  var fetchHtml = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
      {
        data: ''
      , error: false
      }

    // For formatted HTML or not...
    var format = req.body.formatting ? _getFormat() : "";

    var html = _getFullHtml(req.body.name, unmd, format);

    var name = req.body.name.trim() + '.html'

    var filename = path.resolve(__dirname, '../../downloads/files/html/' + name )

    res.attachment( name );
    res.end( html );
  }

  var fetchPdf = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
    {
      data: ''
    , error: false
    }

    var html = _getFullHtml(req.body.name, unmd, _getFormat())
    var tempPath = temp.path({suffix: '.htm'})
    fs.writeFile( tempPath, html, 'utf8', function fetchPdfWriteFileCb(err, data) {
      if(err) {
        console.error(err);
        res.end("Something wrong with the pdf conversion.");
      } else {
         _createPdf(req, res, tempPath);
      }
    });
  }

  function _createPdf(req, res, tempFilename) {
    getPhantomSession().then(phantom => {
      return phantom.createPage();
    }).then(page => {
      page.open( tempFilename ).then(status => {
        _renderPage(page);
      });
    });

    function _renderPage(page) {
      var name = req.body.name.trim() + '.pdf'
      var filename = temp.path({suffix: '.pdf'})

      page.property('paperSize', { format: 'A4', orientation: 'portrait', margin: '1cm' })
      page.property('viewportSize', { width: 1024, height: 768 })

      page.render(filename).then(function() {
        res.attachment( name )
        res.sendFile( filename, {}, function() {
          // Cleanup.
          fs.unlink(filename)
          fs.unlink(tempFilename)
        });

        page.close()
      });
    }
  }

/* Start Dillinger Routes */

// Download a markdown file directly as response.
app.post('/factory/fetch_markdown', fetchMd)

// Download an html file directly as response.
app.post('/factory/fetch_html', fetchHtml)

// Download a pdf file directly as response.
app.post('/factory/fetch_pdf', fetchPdf)

/* End Dillinger Core */
<commit_msg>Makes core/server.js support the "preview as" menu<commit_after>'use strict';

var express = require('express')
  , app = module.exports = express()
  , fs = require('fs')
  , path = require('path')
  , md = require('./markdown-it.js').md
  , temp = require('temp')
  , phantom = require('phantom')
  ;

  var phantomSession = phantom.create()
  function getPhantomSession() {
    return phantomSession
  }

  function _getFullHtml(name, str, style) {
    return '<!DOCTYPE html><meta charset="utf-8"><title>'
      + name + '</title>\n'
      + md.render(str) + '\n';
  }

  function _getHtml(str) {
    return md.render(str)
  }

  // Move this into _getFormat() to reload the CSS without restarting node.
  var _format = fs.readFileSync( path.resolve(__dirname, '../../public/css/app.css') ).toString('utf-8');
  function _getFormat() {
      return _format;
  }

  var fetchMd = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
      {
        data: ''
      , error: false
      }

    var name = req.body.name.trim()

    if(!name.includes('.md')){
      name = name + '.md'
    }

    if (req.body.preview === 'false') {
      res.attachment( name );
    } else {
      res.type('txt');
    }

    res.end( unmd );
  }

  var fetchHtml = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
      {
        data: ''
      , error: false
      }

    // For formatted HTML or not...
    var format = req.body.formatting ? _getFormat() : "";

    var html = _getFullHtml(req.body.name, unmd, format);

    var name = req.body.name.trim() + '.html'

    var filename = path.resolve(__dirname, '../../downloads/files/html/' + name )

    if (req.body.preview === 'false') {
      res.attachment( name );
    } else {
      res.type('html');
    }

    res.end( html );
  }

  var fetchPdf = function(req, res) {
    var unmd = req.body.unmd
      , json_response =
    {
      data: ''
    , error: false
    }

    var html = _getFullHtml(req.body.name, unmd, _getFormat())
    var tempPath = temp.path({suffix: '.htm'})
    fs.writeFile( tempPath, html, 'utf8', function fetchPdfWriteFileCb(err, data) {
      if(err) {
        console.error(err);
        res.end("Something wrong with the pdf conversion.");
      } else {
         _createPdf(req, res, tempPath);
      }
    });
  }

  function _createPdf(req, res, tempFilename) {
    getPhantomSession().then(phantom => {
      return phantom.createPage();
    }).then(page => {
      page.open( tempFilename ).then(status => {
        _renderPage(page);
      });
    });

    function _renderPage(page) {
      var name = req.body.name.trim() + '.pdf'
      var filename = temp.path({suffix: '.pdf'})

      page.property('paperSize', { format: 'A4', orientation: 'portrait', margin: '1cm' })
      page.property('viewportSize', { width: 1024, height: 768 })

      page.render(filename).then(function() {
        if (req.body.preview === 'false') {
          res.attachment( name )
        } else {
          res.type('pdf')
        }

        res.sendFile( filename, {}, function() {
          // Cleanup.
          fs.unlink(filename)
          fs.unlink(tempFilename)
        });

        page.close()
      });
    }
  }

/* Start Dillinger Routes */

// Download a markdown file directly as response.
app.post('/factory/fetch_markdown', fetchMd)

// Download an html file directly as response.
app.post('/factory/fetch_html', fetchHtml)

// Download a pdf file directly as response.
app.post('/factory/fetch_pdf', fetchPdf)

/* End Dillinger Core */
<|endoftext|>


<commit_before>(function($) {
"use strict";

var card = Echo.App.manifest("Echo.Conversations.NestedCard");

if (Echo.App.isDefined(card)) return;

card.templates.photo =
			'
' +
				'
' +
					'
' +
						'{data:author_name}' +
					'
' +
					'' +
						'' +
					'' +
					'
' +
						'
' +
							'
{data:title}
' +
							'
{data:description}
' +
						'
' +
					'
' +
				'
' +
				'

' +
			'
';

card.templates.video =
			'
' +
				'
' +
					'
' +
						'{data:author_name}' +
					'
' +
					'
' +
						'

' +
						'' +
					'
' +
					'
{data:title}
' +
					'
{data:description}
' +
					'

' +
				'
' +
			'
';

card.templates.link =
			'
' +
				'
' +
					'
' +
						'' +
					'
' +
					'
' +
						'
' +
							'{data:title}' +
						'
' +
						'
' +
							'
{data:description}
' +
						'
' +
					'
' +
					'

' +
					'

' +
				'
' +
			'
';

card.templates.main = function() {
	return this.templates[this.get("data.type")];
};

card.config = {
	"width": 340
};

card.init = function() {
	// TODO handle situation when thumbnail_url is not defined
	this.render();
	this.ready();
};

card.renderers.item = function(element) {
	var width = this.config.get("width");
	return element.find("> div").css("max-width", width);
};

card.renderers.sourceIcon = function(element) {
	var proviredURL = element.data("url");
	var icon = proviredURL +
		(proviredURL.substr(-1) === "/" ? "" : "/") +	"favicon.ico";

	Echo.Utils.loadImage({
		"image": icon,
		"onerror": $.noop,
		"onload": function() {
			$(this).attr("title", element.data("name")).appendTo(element);
		}
	});
};

card.renderers.avatar = function(element) {
	return this.get("data.author_name") ? element : element.hide();
};

card.renderers.title = function(element) {
	return this.get("data.title") ? element : element.hide();
};

card.renderers.description = function(element) {
	return this.get("data.description") ? element : element.hide();
};

/**
 * Video
 */
card.renderers.playButton = function(element) {
	var self = this;
	var oembed = this.get("data");
	element.on("click", function() {
		self.view.get("videoPlaceholder").empty().append($(oembed.html));
	});
	return element;
};

card.renderers.videoPlaceholder = function(element) {
	var oembed = this.get("data");
	var maxWidth = this.config.get("width");

	if (!oembed.thumbnail_url) {
		element.empty().append($(oembed.html));
	}
	console.log(oembed);
	//TODO: calc height/width
	var ratio, dimensions;
	if (oembed.thumbnail_width) {
		ratio = maxWidth / oembed.thumbnail_width;
		dimensions = {
			"width": maxWidth,
			"height": oembed.thumbnail_height * ratio
		};
	} else if (maxWidth < oembed.width) {
		ratio = maxWidth / oembed.width;
		dimensions = {
			"width": maxWidth,
			"height": oembed.height * ratio
		};
	} else {
		dimensions = {
			"width": oembed.width,
			"height": oembed.height
		};
	}
	return element.css(dimensions);
};

/**
 *  Photo
 */
card.renderers.photoThumbnail = function(element) {
	var width = this.config.get("width");
	var oembed = this.get("data");
	var thumbnail = oembed.thumbnail_url && oembed.thumbnail_width >= width
		? oembed.thumbnail_url
		: oembed.url;

	return element.attr("src", thumbnail);
};

card.renderers.photoLabelContainer = function(element) {
	return this.get("data.description") || this.get("data.title")
		? element
		: element.hide();
};

card.css =
	'.{class} { background-color: #FFFFFF; border: 1px solid #D2D2D2; border-bottom-width: 2px; margin: 0px; font-family: "Helvetica Neue", arial, sans-serif; color: #42474A; font-size: 13px; line-height: 16px; }' +
	'.{class:title} { font-weight: bold; margin: 5px 0; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:item} .{class:sourceIcon} > img { max-width: 20px; }' +
	'.echo-sdk-ui .{class:avatar} > img { width: 28px; height: 28px; border-radius: 50%; margin-right: 6px; }' +

	// photo
	'.{class:photoAvatar} { position: absolute; padding: 12px; color: #FFF; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:photo} { position: relative; }' +
	'.{class:photo} + .{class:sourceIcon} > img { padding: 10px; }' +
	'.{class:photoLabel} { position: absolute; bottom: 0; color: #FFF; width: 100%; background: rgba(0, 0, 0, 0.5); }' +
	'.{class:photoLabelContainer} { padding: 10px; }' +
	'.{class:photoTitle} { margin: 0 0 5px 0; }' +

	// play button
	'.{class:playButton} { cursor: pointer; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 10; }' +
	'.{class:playButton}:after { content: ""; position: absolute; top: 10px; left: 20px; border-left: 30px solid #FFF; border-top: 20px solid transparent; border-bottom: 20px solid transparent; }' +
	'.{class:playButton} { box-shadow: 0px 0px 40px #000; margin: auto; width: 60px; height: 60px; background-color: rgba(0, 0, 0, 0.7); border-radius: 50%; }' +
	'.{class:playButton}:hover { background-color: #3498DB; }' +

	// video
	'.{class:video} { padding: 10px; }' +
	'.{class:video} .{class:sourceIcon} > img { padding: 10px 0 0 0; }' +
	'.{class:videoAvatar} { margin-bottom: 8px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:videoTitle} { margin: 10px 0 0 0; }' +
	'.{class:videoDescription} { margin: 5px 0 0 0; }' +
	'.{class:videoPlaceholder} { position: relative; background: #000000; }' +
	'.{class:videoPlaceholder} img { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }' +

	// TODO: fix video resizing
	//'.{class:videoPlaceholder} { position: relative; padding-bottom: 75%; height: 0; float: none; margin: 0px; }' +
	'.{class:videoPlaceholder} > iframe { width: 100%; height: 100%; }' +
	'.{class:videoPlaceholder} > video { width: 100%; height: 100%; }' +
	'.{class:videoPlaceholder} > object { width: 100%; height: 100%; }' +

	// article
	'.{class:article} { padding: 10px; min-width: 200px; }' +
	'.{class:article} .{class:sourceIcon} > img { padding: 10px 0 0 0; }' +
	'.{class:article} .{class:articleTitle} > a { color: #42474A; font-weight: bold; }' +
	'.{class:article} .{class:articleTitle} > a:hover { color: #42474A; }' +
	'.{class:articleTitle} { padding: 0 0 5px 0; margin-left: 10px; margin-right: 15px; }' +
	'.{class:articleDescription} { margin-left: 10px; font-size: 13px; line-height: 16px; }' +
	'.{class:articleThumbnail} { width: 30%; float: left; max-width: 120px; max-height: 120px; text-align:center; overflow:hidden; }' +
	'.{class:articleThumbnail} img { width: auto; height: auto; max-height:120px; max-width:120px; }' +
	'.{class:articleTemplate} { width: 70%; float: left; }';

Echo.App.create(card);

})(Echo.jQuery);
<commit_msg>Removed console.log<commit_after>(function($) {
"use strict";

var card = Echo.App.manifest("Echo.Conversations.NestedCard");

if (Echo.App.isDefined(card)) return;

card.templates.photo =
			'
' +
				'
' +
					'
' +
						'{data:author_name}' +
					'
' +
					'' +
						'' +
					'' +
					'
' +
						'
' +
							'
{data:title}
' +
							'
{data:description}
' +
						'
' +
					'
' +
				'
' +
				'

' +
			'
';

card.templates.video =
			'
' +
				'
' +
					'
' +
						'{data:author_name}' +
					'
' +
					'
' +
						'

' +
						'' +
					'
' +
					'
{data:title}
' +
					'
{data:description}
' +
					'

' +
				'
' +
			'
';

card.templates.link =
			'
' +
				'
' +
					'
' +
						'' +
					'
' +
					'
' +
						'
' +
							'{data:title}' +
						'
' +
						'
' +
							'
{data:description}
' +
						'
' +
					'
' +
					'

' +
					'

' +
				'
' +
			'
';

card.templates.main = function() {
	return this.templates[this.get("data.type")];
};

card.config = {
	"width": 340
};

card.init = function() {
	// TODO handle situation when thumbnail_url is not defined
	this.render();
	this.ready();
};

card.renderers.item = function(element) {
	var width = this.config.get("width");
	return element.find("> div").css("max-width", width);
};

card.renderers.sourceIcon = function(element) {
	var proviredURL = element.data("url");
	var icon = proviredURL +
		(proviredURL.substr(-1) === "/" ? "" : "/") +	"favicon.ico";

	Echo.Utils.loadImage({
		"image": icon,
		"onerror": $.noop,
		"onload": function() {
			$(this).attr("title", element.data("name")).appendTo(element);
		}
	});
};

card.renderers.avatar = function(element) {
	return this.get("data.author_name") ? element : element.hide();
};

card.renderers.title = function(element) {
	return this.get("data.title") ? element : element.hide();
};

card.renderers.description = function(element) {
	return this.get("data.description") ? element : element.hide();
};

/**
 * Video
 */
card.renderers.playButton = function(element) {
	var self = this;
	var oembed = this.get("data");
	element.on("click", function() {
		self.view.get("videoPlaceholder").empty().append($(oembed.html));
	});
	return element;
};

card.renderers.videoPlaceholder = function(element) {
	var oembed = this.get("data");
	var maxWidth = this.config.get("width");

	if (!oembed.thumbnail_url) {
		element.empty().append($(oembed.html));
	}
	//TODO: calc height/width
	var ratio, dimensions;
	if (oembed.thumbnail_width) {
		ratio = maxWidth / oembed.thumbnail_width;
		dimensions = {
			"width": maxWidth,
			"height": oembed.thumbnail_height * ratio
		};
	} else if (maxWidth < oembed.width) {
		ratio = maxWidth / oembed.width;
		dimensions = {
			"width": maxWidth,
			"height": oembed.height * ratio
		};
	} else {
		dimensions = {
			"width": oembed.width,
			"height": oembed.height
		};
	}
	return element.css(dimensions);
};

/**
 *  Photo
 */
card.renderers.photoThumbnail = function(element) {
	var width = this.config.get("width");
	var oembed = this.get("data");
	var thumbnail = oembed.thumbnail_url && oembed.thumbnail_width >= width
		? oembed.thumbnail_url
		: oembed.url;

	return element.attr("src", thumbnail);
};

card.renderers.photoLabelContainer = function(element) {
	return this.get("data.description") || this.get("data.title")
		? element
		: element.hide();
};

card.css =
	'.{class} { background-color: #FFFFFF; border: 1px solid #D2D2D2; border-bottom-width: 2px; margin: 0px; font-family: "Helvetica Neue", arial, sans-serif; color: #42474A; font-size: 13px; line-height: 16px; }' +
	'.{class:title} { font-weight: bold; margin: 5px 0; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:item} .{class:sourceIcon} > img { max-width: 20px; }' +
	'.echo-sdk-ui .{class:avatar} > img { width: 28px; height: 28px; border-radius: 50%; margin-right: 6px; }' +

	// photo
	'.{class:photoAvatar} { position: absolute; padding: 12px; color: #FFF; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:photo} { position: relative; }' +
	'.{class:photo} + .{class:sourceIcon} > img { padding: 10px; }' +
	'.{class:photoLabel} { position: absolute; bottom: 0; color: #FFF; width: 100%; background: rgba(0, 0, 0, 0.5); }' +
	'.{class:photoLabelContainer} { padding: 10px; }' +
	'.{class:photoTitle} { margin: 0 0 5px 0; }' +

	// play button
	'.{class:playButton} { cursor: pointer; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 10; }' +
	'.{class:playButton}:after { content: ""; position: absolute; top: 10px; left: 20px; border-left: 30px solid #FFF; border-top: 20px solid transparent; border-bottom: 20px solid transparent; }' +
	'.{class:playButton} { box-shadow: 0px 0px 40px #000; margin: auto; width: 60px; height: 60px; background-color: rgba(0, 0, 0, 0.7); border-radius: 50%; }' +
	'.{class:playButton}:hover { background-color: #3498DB; }' +

	// video
	'.{class:video} { padding: 10px; }' +
	'.{class:video} .{class:sourceIcon} > img { padding: 10px 0 0 0; }' +
	'.{class:videoAvatar} { margin-bottom: 8px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }' +
	'.{class:videoTitle} { margin: 10px 0 0 0; }' +
	'.{class:videoDescription} { margin: 5px 0 0 0; }' +
	'.{class:videoPlaceholder} { position: relative; background: #000000; }' +
	'.{class:videoPlaceholder} img { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }' +

	// TODO: fix video resizing
	//'.{class:videoPlaceholder} { position: relative; padding-bottom: 75%; height: 0; float: none; margin: 0px; }' +
	'.{class:videoPlaceholder} > iframe { width: 100%; height: 100%; }' +
	'.{class:videoPlaceholder} > video { width: 100%; height: 100%; }' +
	'.{class:videoPlaceholder} > object { width: 100%; height: 100%; }' +

	// article
	'.{class:article} { padding: 10px; min-width: 200px; }' +
	'.{class:article} .{class:sourceIcon} > img { padding: 10px 0 0 0; }' +
	'.{class:article} .{class:articleTitle} > a { color: #42474A; font-weight: bold; }' +
	'.{class:article} .{class:articleTitle} > a:hover { color: #42474A; }' +
	'.{class:articleTitle} { padding: 0 0 5px 0; margin-left: 10px; margin-right: 15px; }' +
	'.{class:articleDescription} { margin-left: 10px; font-size: 13px; line-height: 16px; }' +
	'.{class:articleThumbnail} { width: 30%; float: left; max-width: 120px; max-height: 120px; text-align:center; overflow:hidden; }' +
	'.{class:articleThumbnail} img { width: auto; height: auto; max-height:120px; max-width:120px; }' +
	'.{class:articleTemplate} { width: 70%; float: left; }';

Echo.App.create(card);

})(Echo.jQuery);
<|endoftext|>


<commit_before>async function hologram_app(args) {
/*
visibility("PUBLIC")
base_component_id("hologram")
created_timestamp(-1)
display_name("3d hologram app")
is_app(true)
description('Game app, this will return the game app')
uses_javascript_librararies(["advanced_bundle"])
logo_url("/driver_icons/hologram.png")

*/

    Vue.component('hologram',{
      template: `

({{x}},{{y}}) . ({{width}},{{height}}) ,  {{view_x}}, {{view_y}}, {{videoWidth}}

                  <video
                      style="position: absolute;width:50%;height;50%;"
                      v-on:play="onPlay"
                      id="inputVideo"
                      autoplay
                      muted>
                 </video>

                  <canvas  id="overlay"
                            style="position: absolute;;width:50%;height;50%;"
                  />

      `,
      data: function() {
          return {
              msg: "Test Hologram!",
              car: 1,
              x: -1,
              y: -1,
              width: -1,
              height: -1
              ,
              view_x: 0,
              view_y: 0,
              videoWidth: 0
          }
      }
      ,

      mounted: async function() {
        console.log(faceapi.nets)
        await faceapi.nets.ssdMobilenetv1.loadFromUri('/weights')
        await faceapi.loadMtcnnModel('/weights')
        await faceapi.loadFaceRecognitionModel('/weights')
        await faceapi.nets.faceLandmark68Net.loadFromUri('/weights')
        await faceapi.nets.tinyFaceDetector.loadFromUri('/weights' );

            // Grab elements, create settings, etc.
            var video = document.getElementById('inputVideo');

            // Get access to the camera!
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // Not adding `{ audio: true }` since we only want video now
                navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
                    //video.src = window.URL.createObjectURL(stream);
                    video.srcObject = stream;
                    //video.play();
                });
            }

      },
      methods:
      {
        onPlay: async function ()
        {
            let mm = this

            try {
                const mtcnnForwardParams = {
                     minFaceSize: 200
                }

                const detections = await faceapi.detectSingleFace(
                                        document.getElementById('inputVideo')
                                        ,
                                        new faceapi.TinyFaceDetectorOptions({scoreThreshold: .1,inputSize: 128})
                                        ,
                                        mtcnnForwardParams
                                        )

                //const mtcnnResults = await faceapi.mtcnn(document.getElementById('inputVideo'), mtcnnForwardParams)

                //faceapi.draw.drawDetections(document.getElementById('overlay'), detections);
                if (detections) {

                    mm.x = Math.floor(detections._box._x)
                    mm.y = Math.floor(detections._box._y)
                    mm.width = Math.floor(detections._box._width)
                    mm.height = Math.floor(detections._box._height)

                    mm.videoWidth = mm.getInnerWidth(document.getElementById("inputVideo"))

                    mm.view_x = -30 + ((1 / mm.videoWidth) * mm.x * 120)
                    //mm.view_y = -35 + ((1 / mm.height) * mm.y * 30)
                    //console.log(JSON.stringify(mm.view_y,null,2))

                }
                //console.log(mm.car++)

            } catch (err) {

            }

            setTimeout(() => mm.onPlay())
        }
        ,

        getInnerWidth: function(elem) {
            return elem.getBoundingClientRect().width
        }

      }

    })
}
<commit_msg>make the hologram a bit smoother<commit_after>async function hologram_app(args) {
/*
parent_hash("8638cb9c331c8f30ff92eb870eef990ee9bd2d602e2e6462adf8bb5098ca4be1")
visibility("PUBLIC")
base_component_id("hologram")
created_timestamp(-1)
display_name("3d hologram app")
is_app(true)
description('Game app, this will return the game app')
uses_javascript_librararies(["advanced_bundle"])
logo_url("/driver_icons/hologram.png")

*/

    Vue.component('hologram',{
      template: `

({{x}},{{y}}) . ({{width}},{{height}}) ,  {{view_x}}, {{view_y}}, {{videoWidth}}

                  <video
                      style="position: absolute;width:50%;height;50%;"
                      v-on:play="onPlay"
                      id="inputVideo"
                      autoplay
                      muted>
                 </video>

                  <canvas  id="overlay"
                            style="position: absolute;;width:50%;height;50%;"
                  />

      `,
      data: function() {
          return {
              msg: "Test Hologram!",
              car: 1,
              x: -1,
              y: -1,
              width: -1,
              height: -1
              ,
              view_x: 0,
              view_y: 0,
              videoWidth: 0
          }
      }
      ,

      mounted: async function() {
        console.log(faceapi.nets)
        await faceapi.nets.ssdMobilenetv1.loadFromUri('/weights')
        await faceapi.loadMtcnnModel('/weights')
        await faceapi.loadFaceRecognitionModel('/weights')
        await faceapi.nets.faceLandmark68Net.loadFromUri('/weights')
        await faceapi.nets.tinyFaceDetector.loadFromUri('/weights' );

            // Grab elements, create settings, etc.
            var video = document.getElementById('inputVideo');

            // Get access to the camera!
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                // Not adding `{ audio: true }` since we only want video now
                navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
                    //video.src = window.URL.createObjectURL(stream);
                    video.srcObject = stream;
                    //video.play();
                });
            }

      },
      methods:
      {
        onPlay: async function ()
        {
            let mm = this

            try {
                const mtcnnForwardParams = {
                     minFaceSize: 200
                }

                const detections = await faceapi.detectSingleFace(
                                        document.getElementById('inputVideo')
                                        ,
                                        new faceapi.TinyFaceDetectorOptions({scoreThreshold: .1,inputSize: 128})
                                        ,
                                        mtcnnForwardParams
                                        )

                //const mtcnnResults = await faceapi.mtcnn(document.getElementById('inputVideo'), mtcnnForwardParams)

                //faceapi.draw.drawDetections(document.getElementById('overlay'), detections);
                if (detections) {

                    mm.x = Math.floor(detections._box._x)
                    mm.y = Math.floor(detections._box._y)
                    mm.width = Math.floor(detections._box._width)
                    mm.height = Math.floor(detections._box._height)

                    mm.videoWidth = mm.getInnerWidth(document.getElementById("inputVideo"))

                    mm.view_x =  1 + (parseFloat((1 / mm.videoWidth).toFixed(3)) * mm.x * -3)
                    //mm.view_y = -35 + ((1 / mm.height) * mm.y * 30)
                    //console.log(JSON.stringify(mm.view_y,null,2))

                }
                //console.log(mm.car++)

            } catch (err) {

            }

            setTimeout(() => mm.onPlay())
        }
        ,

        getInnerWidth: function(elem) {
            return elem.getBoundingClientRect().width
        }

      }

    })
}
<|endoftext|>


<commit_before>/**
 * Created by weixing on 2015/11/6.
 */

angular.module('chat',[
    'btford.socket-io',
    'angularSocket'
]).factory('btford-socket', function (socketFactory) {
        return socketFactory();
})
    .service('pagination',function(){
    var pagination = function(pager,pagesize){
        this.fromid = pager.startid;
        this.totalMessage = pager.total;
        this.total = 0;
        this.preview = 0;
        this.next = 1;
        this.current = 0;
        this.loaded = 0;
        if(!pagesize) pagesize=10;
        this.pagesize = pagesize;
        if(pager.total) this.total = Math.ceil(pager.total/pagesize);
        if(this.total>1) this.next=1;
    }
    pagination.prototype.hasNext = function(){
        if(this.current< this.total) return true;
        return false;
    }
    pagination.prototype.nextPage = function(){
        if(this.current< this.total){
            if( this.current>0) this.preview = this.current-1;
            this.current = this.next;
            if(this.total> this.next) this.next++;
        }
        return this.current;
    }

    this.getPagination = function(pager,pagesize){
        if(!pagesize) pagesize=10;
        return new pagination(pager,pagesize);
    }
})
    .controller('chatCtrl',['grSocket','pagination',function(socket,pagination){
        var vm = this;
        vm.formModel = {};
        vm.formModel.needLogin = true;

        vm.login = login;
        vm.userMesage = {};//chat record
        vm.cFriend = {};// 当前聊天的朋友
        vm.messagePager={};//record pagination
        vm.friends = {};//all chat friend id=>obj

        vm.addFriend = function(friend){
            if(typeof vm.userMesage[friend.room] === "undefined"){
                vm.friends[friend.id] = friend;
                vm.userMesage[friend.chatRoom] = [];
            }
            return false;
        }

        function login(){
            if(!vm.formModel.uid) return;
            socket.emit('client:get:friends',{ uid : vm.formModel.uid});
            vm.formModel.needLogin = false;
        };
        socket.on('server:send:friends',function(data){
            if(data){
                angular.forEach(data,function(ele){
                    vm.userMesage[ele.room] = [];
                    vm.friends[ele.id] = ele;
                })
            };
            socket.emit('client:get:rooms',{uid: vm.formModel.uid});
        });

        //获取聊天的room数据
        socket.on("server:send:rooms",function(data){
            if(data){
                angular.forEach(data,function(ele){
                    if(typeof vm.friends[ele.fr] === "undefined"){
                        vm.friends[ele.fr] = ele;
                        vm.userMesage[ele.room] = [];
                    }
                });
            };
        });

        vm.chatWithFriend = function(friend){
            if(vm.cFriend.room !== friend.room){
                socket.emit('client:chat:friend',friend);
                vm.cFriend = friend;
            }
            friend.newMsgArrv = false;
        }
        vm.send = function(user){
            if(vm.formModel.gotosend){
                socket.emit('client:friend:msg',{friend:user,message:vm.formModel.gotosend});
                if(typeof vm.userMesage[user.room] === "undefined") vm.userMesage[user.room]=[];
                vm.userMesage[user.room].push(
                    {
                        fr:vm.formModel.uid,
                        msg: vm.formModel.gotosend,
                        created_at: (new Date()).getTime()
                    }
                );
            }
        }

        socket.on('server:friend:msg',function(data){

            if(vm.userMesage[data.room]){
                vm.userMesage[data.room].push(data);
                angular.forEach(vm.friends,function(ele){
                    if(ele.room == data.room){
                        ele.newMsgArrv = true; //set new message arrive
                    }
                });
            }else{
                vm.userMesage[data.room] = [data];
                socket.emit("client:get:new:friend",{uid:data.fr}); //获取新聊天
                socket.on("server:send:new:friend",function(friend){
                    vm.friends[friend.id] = friend;
                    friend.newMsgArrv = true;
                    console.log(vm.friends);
                });
            }
        });

        vm.recordNextPage = function(room){
            var pagination = vm.messagePager[room];
            var data = {
                room: room,
                page: pagination.nextPage(),
                pagesize : pagination.pagesize,
                total: pagination.totalMessage,
                startid: pagination.fromid
            };
            socket.emit('client:get:friend:record',data);
        };
         socket.on('server:send:friend:record',function(data){
                if(data.length>0){
                    var room = data[0].room;
                    angular.forEach(data,function(ele){
                        vm.userMesage[room].unshift(ele);
                    });
                }
            });

        socket.on("server:first:5:message",function(data){
                if(data.length > 0 ) {
                    var room = data[0].room;
                    vm.userMesage[room] = data.reverse();
                    var maxrecordid = data[0].id;
                    socket.emit("client:get:pagination",{room:room,id:maxrecordid});
                };
        });

        socket.on('server:send:pagination',function(pager){
            if(typeof vm.messagePager[pager.room] === "undefined") vm.messagePager[pager.room] = pagination.getPagination(pager,10);
        });
        socket.on('reconnect',function(info){
            socket.emit('client:get:friends',{ uid : vm.formModel.uid});
        });

}])
    .controller("chatFindUserCtrl",['grSocket',function(socket){
        var vm = this;
        vm.formModel = {};
        vm.formModel.username = '';
        vm.findUser = function(){
            if(vm.formModel.username){
                socket.emit("client:find:username",{username: vm.formModel.username});
            }
        };
        socket.on("server:find:username:result",function(data){
            if(data.length > 0){
                vm.filterUser = data;
            }else{
                alert("no matched user!");
            }
        })
    }]);
<commit_msg>fix bug<commit_after>/**
 * Created by weixing on 2015/11/6.
 */

angular.module('chat',[
    'btford.socket-io',
    'angularSocket'
]).factory('btford-socket', function (socketFactory) {
        return socketFactory();
})
    .service('pagination',function(){
    var pagination = function(pager,pagesize){
        this.fromid = pager.startid;
        this.totalMessage = pager.total;
        this.total = 0;
        this.preview = 0;
        this.next = 1;
        this.current = 0;
        this.loaded = 0;
        if(!pagesize) pagesize=10;
        this.pagesize = pagesize;
        if(pager.total) this.total = Math.ceil(pager.total/pagesize);
        if(this.total>1) this.next=1;
    }
    pagination.prototype.hasNext = function(){
        if(this.current< this.total) return true;
        return false;
    }
    pagination.prototype.nextPage = function(){
        if(this.current< this.total){
            if( this.current>0) this.preview = this.current-1;
            this.current = this.next;
            if(this.total> this.next) this.next++;
        }
        return this.current;
    }

    this.getPagination = function(pager,pagesize){
        if(!pagesize) pagesize=10;
        return new pagination(pager,pagesize);
    }
})
    .controller('chatCtrl',['grSocket','pagination',function(socket,pagination){
        var vm = this;
        vm.formModel = {};
        vm.formModel.needLogin = true;

        vm.login = login;
        vm.userMesage = {};//chat record
        vm.cFriend = {};// 当前聊天的朋友
        vm.messagePager={};//record pagination
        vm.friends = {};//all chat friend id=>obj

        vm.addFriend = function(friend){
            if(typeof vm.userMesage[friend.room] === "undefined"){
                vm.friends[friend.id] = friend;
                vm.userMesage[friend.chatRoom] = [];
            }
            return false;
        }

        function login(){
            if(!vm.formModel.uid) return;
            socket.emit('client:get:friends',{ uid : vm.formModel.uid});
            vm.formModel.needLogin = false;
        };
        socket.on('server:send:friends',function(data){
            if(data){
                angular.forEach(data,function(ele){
                    vm.userMesage[ele.room] = [];
                    vm.friends[ele.id] = ele;
                })
            };
            socket.emit('client:get:rooms',{uid: vm.formModel.uid});
        });

        //获取聊天的room数据
        socket.on("server:send:rooms",function(data){
            if(data){
                angular.forEach(data,function(ele){
                    if(typeof vm.friends[ele.fr] === "undefined"){
                        vm.friends[ele.fr] = ele;
                        vm.userMesage[ele.room] = [];
                    }
                });
            };
        });

        vm.chatWithFriend = function(friend){
            if(vm.cFriend.room !== friend.room){
                if(angular.isArray(vm.userMesage[friend.room]) && vm.userMesage[friend.room].length == 0 ){
                    socket.emit('client:chat:friend',friend);
                }
                console.log(vm.userMesage[friend.room]);
                vm.cFriend = friend;
            }
            friend.newMsgArrv = false;
        }
        vm.send = function(user){
            if(vm.formModel.gotosend){
                socket.emit('client:friend:msg',{friend:user,message:vm.formModel.gotosend});
                if(typeof vm.userMesage[user.room] === "undefined") vm.userMesage[user.room]=[];
                vm.userMesage[user.room].push(
                    {
                        fr:vm.formModel.uid,
                        msg: vm.formModel.gotosend,
                        created_at: (new Date()).getTime()
                    }
                );
            }
        }

        socket.on('server:friend:msg',function(data){

            if(vm.userMesage[data.room]){
                vm.userMesage[data.room].push(data);
                angular.forEach(vm.friends,function(ele){
                    if(ele.room == data.room){
                        ele.newMsgArrv = true; //set new message arrive
                    }
                });
            }else{
                vm.userMesage[data.room] = [data];
                socket.emit("client:get:new:friend",{uid:data.fr}); //获取新聊天
                socket.on("server:send:new:friend",function(friend){
                    vm.friends[friend.id] = friend;
                    friend.newMsgArrv = true;
                    console.log(vm.friends);
                });
            }
        });

        vm.recordNextPage = function(room){
            var pagination = vm.messagePager[room];
            var data = {
                room: room,
                page: pagination.nextPage(),
                pagesize : pagination.pagesize,
                total: pagination.totalMessage,
                startid: pagination.fromid
            };
            socket.emit('client:get:friend:record',data);
        };
         socket.on('server:send:friend:record',function(data){
                if(data.length>0){
                    var room = data[0].room;
                    angular.forEach(data,function(ele){
                        vm.userMesage[room].unshift(ele);
                    });
                }
            });

        socket.on("server:first:5:message",function(data){
                if(data.length > 0 ) {
                    var room = data[0].room;
                    vm.userMesage[room] = data.reverse();
                    var maxrecordid = data[0].id;
                    socket.emit("client:get:pagination",{room:room,id:maxrecordid});
                };
        });

        socket.on('server:send:pagination',function(pager){
            if(typeof vm.messagePager[pager.room] === "undefined") vm.messagePager[pager.room] = pagination.getPagination(pager,10);
        });
        socket.on('reconnect',function(info){
            socket.emit('client:get:friends',{ uid : vm.formModel.uid});
        });

}])
    .controller("chatFindUserCtrl",['grSocket',function(socket){
        var vm = this;
        vm.formModel = {};
        vm.formModel.username = '';
        vm.findUser = function(){
            if(vm.formModel.username){
                socket.emit("client:find:username",{username: vm.formModel.username});
            }
        };
        socket.on("server:find:username:result",function(data){
            if(data.length > 0){
                vm.filterUser = data;
            }else{
                alert("no matched user!");
            }
        })
    }]);
<|endoftext|>


<commit_before>angular.module("jobbiesApp").controller('FeedController', ['$scope', function($scope){

}]);<commit_msg>replaced feed controller that was accidentally removed by previous merge<commit_after>angular.module("jobbiesApp").controller('FeedController', ['$scope', function($scope){
  $scope.jobbies = [{title:"Mow my lawn", pay: 75, category: "Yardwork", city: "New Brunswick", "desc": "Need someone to mow my lawn, property is medium size, shouldn't take more than hour.  Bring your own mower."},

  {title:"Clean up my place", pay: 50, category: "Housework", city: "New Brunswick", "desc": "Had a huge party last night and now I'm hungover and my place is a mess, I just need soemone to come over and tidy up a bit. Thnaks!"},

  {title:"Cook Me Dinner", pay: 30, category: "Housework", city: "New Brunswick", "desc": "Too busy and worn out from work to cook for myself, come over and make me dinner."},

  {title:"Fix My Pumbling", pay: 120, category: "Handywork", city: "New Brunswick", "desc": "My pumbling is broken, sink does not work and water pressure is very low in shower, need someone to fix it ASAP"},

  {title:"Misc Test", pay: 75, category: "Miscellaneous", city: "New Brunswick", "desc": "TESTING"}]

  $scope.filter = {};
  $scope.price = 0;
  $scope.priceModel = {};
  $scope.category = {};
  $scope.priceModel.twenty = false;
  $scope.priceModel.fifty = false;
  $scope.priceModel.hundred = false;
  $scope.category.yardwork = true;
  $scope.category.housework = true;
  $scope.category.handywork = true;
  $scope.category.misc = true;

  $scope.togglePrice = function(price){
    $scope.price = price;
  }

  $scope.categorySelected = function(category){
    if (category === "Yardwork" && $scope.category.yardwork){
      return true;
    }else if (category === "Housework" && $scope.category.housework){
      return true;
    }else if (category === "Handywork" && $scope.category.handywork){
      return true;
    }else if (category === "Miscellaneous" && $scope.category.misc){
      return true;
    }else{
      return false;
    }
  }

  $scope.minPay = function(pay){
    // console.log(pay);
    if ($scope.filter.minTwenty && pay < 20){
      return true;
    }else if ($scope.filter.minFifty && pay < 50){
      return true;
    }else if ($scope.filter.minHundred && pay < 100){
      return true;
    }else{
      return false;
    }
  }

  $scope.resetFilter= function(){
    $scope.filter = {};
    $scope.price = 0;
    $scope.category = {};
    $scope.priceModel.twenty = false;
    $scope.priceModel.fifty = false;
    $scope.priceModel.hundred = false;
    $scope.category.yardwork = true;
    $scope.category.housework = true;
    $scope.category.handywork = true;
    $scope.category.misc = true;
  }

}]);<|endoftext|>


<commit_before>function cookingTime(eggs) {

}

// cook time for 0 eggs
console.log(cookingTime(0) === 0)
// cook time for 2 eggs
console.log(cookingTime(2) === 5)
// cook time for 5 eggs
console.log(cookingTime(5) === 5)
// cook time for 8 eggs
console.log(cookingTime(8) === 5)
// cook time for 15 eggs
console.log(cookingTime(15) === 10)
// cook time for 16 eggs
console.log(cookingTime(16) === 10)
// cook time for 20 eggs
console.log(cookingTime(20) === 15)<commit_msg>commit initial solution for cookingTime<commit_after>function cookingTime(eggs) {
	switch(eggs) {
    case eggs === 0:
        return 0;
        break;
    case eggs > 0 && eggs <= 8:
        return 5;
        break;
    default:
        if (eggs % 8 === 0) {
        	return eggs / 8 * 5
        } else {
        	return Math.floor(eggs / 8 + 1) * 5
        }
}
}

// cook time for 0 eggs
console.log(cookingTime(0) === 0)
// cook time for 2 eggs
console.log(cookingTime(2) === 5)
// cook time for 5 eggs
console.log(cookingTime(5) === 5)
// cook time for 8 eggs
console.log(cookingTime(8) === 5)
// cook time for 15 eggs
console.log(cookingTime(15) === 10)
// cook time for 16 eggs
console.log(cookingTime(16) === 10)
// cook time for 20 eggs
console.log(cookingTime(20) === 15)<|endoftext|>


<commit_before>
/*
 * application JS library, UI independent code
 *
 */

var busyImage = '';
var menuArrowImage = 'ui/lite/images/menuarrow.png';
var menuArrowActiveImagesrc = 'ui/lite/images/menuarrow_active.png';

function urlParameter( name, link) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( link );
  if( results == null )
    return "";
  else
    return results[1];
}

function messageStatusUpdate(msgid) {
   $('#messagestatus'+msgid).load('./?page=pageaction&ajaxed=true&action=msgstatus&id='+msgid,"",function() {
   });
   setTimeout("messageStatusUpdate("+msgid+")",5000);
}

function getServerTime() {
   $('#servertime').load('./?page=pageaction&ajaxed=true&action=getservertime',"",function() {
   });
   setTimeout("getServerTime()",60100); // just over a minute
}

function refreshCriteriaList() {
  var id = urlParameter('id',document.location);
  $("#existingCriteria").html(busyImage);
  $("#existingCriteria").load('./?page=pageaction&ajaxed=true&action=listcriteria&id='+id);
}

function refreshExport() {
 // alert('Refresh '+document.location);
  document.location = document.location;
}

function openDialog(url) {
  $("#dialog").dialog({
    minHeight: 400,
    width: 600,
    modal: true,
    show: 'blind',
    hide: 'explode'
  });
  var destpage = urlParameter('page',url);
  url = url.replace(/page=/,'origpage=');
  $("#dialog").load(url+'&ajaxed=true&page=pageaction&action='+destpage);
}

function totalSentUpdate(msgid) {
   $('#totalsent'+msgid).load('./?page=pageaction&ajaxed=true&action=msgsent&id='+msgid,"",function() {
   });
   setTimeout("totalSentUpdate("+msgid+")",5000);
}

$(document).ready(function() {
  $(".note .hide").click(function() {
    $(this).parents('.note').hide();
  });

  //$(".paging").scrollable();

  $(".configurelink").click(function() {
   // alert(this.href);
    $("#configurecontent").load('./?page=ajaxcall&action=test');
    $("#configurecontent").show();
    return false;
  });

  $("a.ajaxable").click(function() {
    var url = this.href;
    var thispage = urlParameter('page',window.location.href);
    var action = urlParameter('action',url);
    if (action == "") {
      url += '&action='+thispage;
    }
    parent = $(this).parent();
    parent.html(busyImage);
    url = url.replace(/page=/,'origpage=');
  //  alert(url+'&ajaxed=true&page=pageaction');
    parent.load(url+'&ajaxed=true&page=pageaction');
    return false;
  });

  $("input:checkbox.checkallcheckboxes").click(function() {
    if (this.checked) {
      $("input[type=checkbox]:not(:checked)").each(function(){
        this.checked = true;
      });
    } else {
      $("input[type=checkbox]:checked").each(function(){
        this.checked = false;
      });
    }
  });

  var stop = false;

  if ($.fn.accordion) {
    $(".accordion").accordion({
        autoHeight: false,
        navigation: true,
        collapsible: true
      });
  }

  $(".opendialog").click(function() {
    openDialog(this.href);
    return false;
  });
  $(".helpdialog").click(function() {
    openDialog(this.href);
    return false;
  });
  $(".closedialog").click(function() {
    $("#dialog").dialog('close');
  });

  //dropbuttons
  $("div.dropButton img.arrow").click(function(){
      submenu = $(this).parent().parent().find("div.submenu");
      if(submenu.css('display')=="block"){
        submenu.hide();
        $(this).attr('src',menuArrowImagesrc);
      } else {
        submenu.fadeIn();
        $(this).attr('src',menuArrowActiveImagesrc);
      }
      return false;
  });

  /* hmm, doesn't work yet, but would be nice at some point
  $("#emailsearch").autocomplete({
    source: "?page=pageaction&ajaxed=true&action=searchemail",
    minLength: 2,
    select: function(event, ui) {
    log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
    }
  });
  */

  if ($.fn.tabs) {
    $(".tabbed").tabs({
      ajaxOptions: {
        error: function(xhr, status, index, anchor) {
          $(anchor.hash).html("Error fetching page");
        }
      }
    });
    $(".tabbed1").tabs();
  }

  $("#remoteurlinput").focus(function() {
    if (this.value == 'e.g. http://www.phplist.com/testcampaign.html') {
      this.value = "";
    }
  })

  $("#remoteurlinput").blur(function() {
    if (this.value == "") {
      this.value = "e.g. http://www.phplist.com/testcampaign.html";
      return;
    }
    $("#remoteurlstatus").html(busyImage);
    $("#remoteurlstatus").load("./?page=pageaction&action=checkurl&ajaxed=true&url="+this.value);
  });

  $("input:radio[name=sendmethod]").change(function() {
    if (this.value == "remoteurl") {
      $("#remoteurl").show();
      $("#messagecontent").hide();
    } else {
      $("#remoteurl").hide();
      $("#messagecontent").show();
    }
  });

  $("a.savechanges").click(function() {
    if (changed) {
      document.sendmessageform.followupto.value = this.href;
      document.sendmessageform.submit();
      return false;
    }
  });

  $("#criteriaSelect").change(function() {
    var val = $("#criteriaSelect").val();
    var operator = '';
    switch (aT[val]) {
      case 'checkbox':
        $("#criteriaAttributeOperator").html('<input type="hidden" name="criteria_operator" value="is" />');
        $("#criteriaAttributeValues").html('CHECKED <input type="radio" name="criteria_values" value="checked" /> UNCHECKED <input type="radio" name="criteria_values" value="unchecked" />');
        break;
      case 'checkboxgroup':
      case 'select':
      case 'radio':
        $("#criteriaAttributeOperator").html('IS <input type="radio" name="criteria_operator" value="is" checked="checked" /> IS NOT <input type="radio" name="criteria_operator" value="isnot" />');
        $("#criteriaAttributeValues").html(busyImage);
        $("#criteriaAttributeValues").load("./?page=pageaction&ajaxed=true&action=attributevalues&name=criteria_values&type=multiselect&attid="+val);
        break;
      case 'date':
        $("#criteriaAttributeOperator").html('IS <input type="radio" name="criteria_operator" value="is" checked="checked" /> IS NOT <input type="radio" name="criteria_operator" value="isnot" /> IS BEFORE <input type="radio" name="criteria_operator" value="isbefore" /> IS AFTER <input type="radio" name="criteria_operator" value="isafter" />');
        $("#criteriaAttributeValues").html('<input type="text" id="datepicker" name="criteria_values" size="30"/>');
        $("#datepicker").datepicker({dateFormat: 'yy-mm-dd' });
        break;
      default:
        $("#criteriaAttributeOperator").html('');
        $("#criteriaAttributeValues").html('');
        break;
    }
  });

  $("#initialadminpassword").keyup(function() {
    if (this.value.length >= 8) {
      $("#initialisecontinue").removeAttr('disabled');
    }
  });

  // export page
  $("input:radio[name=column]").change(function() {
    if (this.value == 'nodate') {
      $("#exportdates").hide();
    } else {
      $("#exportdates").show();
    }
  });

  $("#processexport").click(function() {
    // for export, refresh underlying page, to get a new security token
    setTimeout("refreshExport()",2000);
  })

  //fade out 'actionresult' user feedback
  $('.actionresult').delay(4000).fadeOut(4000);
  //fade out 'result' user feedback
  $('.result').delay(4000).fadeOut(4000);

//  $("#processqueueoutput").html('Processing queue, please wait');
  $("#spinner").html(busyImage);

  $("#stopqueue").click(function() {
    $("#processqueueoutput").html('Processing cancelled');
    $("#spinner").html(' ');
    $("#stopqueue").hide();
    $("#resumequeue").show();
  });

  var docurl = document.location.search;
  document.cookie="browsetrail="+escape(docurl);

/* future dev
  $("#listinvalid").load("./?page=pageaction&action=listinvalid&ajaxed=true",function() {
 //  alert("Loaded")
  });
  $("#refreshCriteria").click(refreshCriteriaList);

  $("#addcriterionbutton").click(function() {
    $("#addcriterionbutton").addClass('disabled');
    var request = document.location.search+'&'+$("#sendmessageform").serialize();
    var attr = urlParameter('criteria_attribute',request);
    if (attr == '') {
      alert('Select an attribute to add');
      return false;
    };
    var vals = urlParameter('criteria_values',request);
    var arrVals = urlParameter('criteria_values[]',request);
    if (vals == '' && arrVals) {
      alert('Select a value to add');
      return false;
    };

    request = request.replace(/\?/,'');
    request = request.replace(/page=/,'origpage=');
    request = './?page=pageaction&action=storemessage&'+request;
    alert(request);
    $("#existingCriteria").html(busyImage);
 //   $("#hiddendiv").load(request);
 //   $("#sendmessageform").submit();
 //   setTimeout("refreshCriteriaList()",5000);

//    refreshCriteriaList();
    return true;
  });
*/

});

function allDone() {
  $("#processqueueoutput").html('All done');
  $("#spinner").html(' ');
  $("#stopqueue").hide();
  $("#resumequeue").show();
  $("#progressmeter").hide();
}

var overallTotal = 0;
var overallSent = 0;
$.fn.updateProgress = function() {
  var args = arguments[0].split(',') || {}; //  arguments
  var total = parseInt(args[1]);
  // fix the total first time
  if (total > overallTotal) {    overallTotal = total;  } else {    total = overallTotal;  }
  var done = parseInt(args[0]);
  if (done > 0) {
    overallSent += done;
  }
  var perc;
  if (overallTotal == 0) {
    perc = 0;
  } else {
    perc = parseInt((overallSent / overallTotal) * 100);
  }
  $("#progress").width(perc * 5);
  $("#progress").html(perc + '%');
  $("#progresscount").html(overallSent + ' / '+ overallTotal);
};

/*
 * old library of stuff that needs to be ported to jQuery style JS
 */

var helpwin = null;
var helploc = null;
function deleteRec(url) {
	if (confirm("Are you sure you want to delete this record?")) {
		document.location = url;
	}
}

function deleteRec2(msg,url) {
	if (confirm(msg)) {
		document.location = url;
  }
}

function help(loc) {
  if (helpwin && !helpwin.closed) {
    helpwin.close();
    helpwin = '';
    helploc = loc;
    setTimeout("openhelp()",500)
  } else {
    helploc = loc;
    openhelp();
  }
}

function openhelp() {
  helpwin=window.open(helploc,"help",'screenX=100,screenY=100,width=350,height=350,scrollbars=yes');
  if (window.focus) {helpwin.focus()}
}
function print_self(){
  window.focus();
  if (typeof(window.print) != "undefined"){
    window.print();
  } else {
    show_print_alert();
  }
}

function show_print_alert() {
  alert("Please use your browser's print button");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

var pic = null;
var t_url;
var t_w;
var t_h;

function viewImage(url,w,h) {
   openpic(url,w,h);
}

function openpic(url,w,h) {
  if (w == null || w == 0) {
    w = 120;
  }
  if (h == null || h == 0){
    h = 120;
  }

  if (pic)  {
    pic.close();
    pic = null;
    t_url = url;
    t_w = w;
    t_h = h;
    setTimeout("openit()",500);
  } else {
    do_openpic(url,w,h);
  }
}

function openit() {
	do_openpic(t_url,t_w,t_h);
	t_url = null;
	t_w = null;
	t_h = null;
}

function do_openpic(url,w,h) {
  w +=30;
  h +=30;
  //var features = "scrollbars=auto,toolbar=yes,location=yes,menubar=yes,screenx=150,screeny=150";
  var	features = "dependent=yes,width=" + w + ",height=" + h + ",noresize,scrollbars=auto,toolbar=no,location=no,menubar=no,screenx=150,screeny=150";
//    alert(features);
  pic = window.open(url,"picwin",features);
  //    setTimeout("createContent()",100);

}
function createContent(){
  if (!pic.document){
    setTimeout("createContent()",100);
  } else {
    var url ="aaa";
    var w=100;
    var h=200;
    pic.document.write('');
    pic.document.write('');
    if (window.focus){pic.focus();}
  }
}

<commit_msg>clear the hash after a send test to avoid scrolling down every time<commit_after>
/*
 * application JS library, UI independent code
 *
 */

var busyImage = '';
var menuArrowImage = 'ui/lite/images/menuarrow.png';
var menuArrowActiveImagesrc = 'ui/lite/images/menuarrow_active.png';

function urlParameter( name, link) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( link );
  if( results == null )
    return "";
  else
    return results[1];
}

function messageStatusUpdate(msgid) {
   $('#messagestatus'+msgid).load('./?page=pageaction&ajaxed=true&action=msgstatus&id='+msgid,"",function() {
   });
   setTimeout("messageStatusUpdate("+msgid+")",5000);
}

function getServerTime() {
   $('#servertime').load('./?page=pageaction&ajaxed=true&action=getservertime',"",function() {
   });
   setTimeout("getServerTime()",60100); // just over a minute
}

function refreshCriteriaList() {
  var id = urlParameter('id',document.location);
  $("#existingCriteria").html(busyImage);
  $("#existingCriteria").load('./?page=pageaction&ajaxed=true&action=listcriteria&id='+id);
}

function refreshExport() {
 // alert('Refresh '+document.location);
  document.location = document.location;
}

function openDialog(url) {
  $("#dialog").dialog({
    minHeight: 400,
    width: 600,
    modal: true,
    show: 'blind',
    hide: 'explode'
  });
  var destpage = urlParameter('page',url);
  url = url.replace(/page=/,'origpage=');
  $("#dialog").load(url+'&ajaxed=true&page=pageaction&action='+destpage);
}

function totalSentUpdate(msgid) {
   $('#totalsent'+msgid).load('./?page=pageaction&ajaxed=true&action=msgsent&id='+msgid,"",function() {
   });
   setTimeout("totalSentUpdate("+msgid+")",5000);
}

$(document).ready(function() {
  $(".note .hide").click(function() {
    $(this).parents('.note').hide();
  });

  //$(".paging").scrollable();

  $(".configurelink").click(function() {
   // alert(this.href);
    $("#configurecontent").load('./?page=ajaxcall&action=test');
    $("#configurecontent").show();
    return false;
  });

  $("a.ajaxable").click(function() {
    var url = this.href;
    var thispage = urlParameter('page',window.location.href);
    var action = urlParameter('action',url);
    if (action == "") {
      url += '&action='+thispage;
    }
    parent = $(this).parent();
    parent.html(busyImage);
    url = url.replace(/page=/,'origpage=');
  //  alert(url+'&ajaxed=true&page=pageaction');
    parent.load(url+'&ajaxed=true&page=pageaction');
    return false;
  });

  $("input:checkbox.checkallcheckboxes").click(function() {
    if (this.checked) {
      $("input[type=checkbox]:not(:checked)").each(function(){
        this.checked = true;
      });
    } else {
      $("input[type=checkbox]:checked").each(function(){
        this.checked = false;
      });
    }
  });

  var stop = false;

  if ($.fn.accordion) {
    $(".accordion").accordion({
        autoHeight: false,
        navigation: true,
        collapsible: true
      });
  }

  $(".opendialog").click(function() {
    openDialog(this.href);
    return false;
  });
  $(".helpdialog").click(function() {
    openDialog(this.href);
    return false;
  });
  $(".closedialog").click(function() {
    $("#dialog").dialog('close');
  });

  //dropbuttons
  $("div.dropButton img.arrow").click(function(){
      submenu = $(this).parent().parent().find("div.submenu");
      if(submenu.css('display')=="block"){
        submenu.hide();
        $(this).attr('src',menuArrowImagesrc);
      } else {
        submenu.fadeIn();
        $(this).attr('src',menuArrowActiveImagesrc);
      }
      return false;
  });

  /* hmm, doesn't work yet, but would be nice at some point
  $("#emailsearch").autocomplete({
    source: "?page=pageaction&ajaxed=true&action=searchemail",
    minLength: 2,
    select: function(event, ui) {
    log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
    }
  });
  */

  if ($.fn.tabs) {
    $(".tabbed").tabs({
      ajaxOptions: {
        error: function(xhr, status, index, anchor) {
          $(anchor.hash).html("Error fetching page");
        }
      }
    });
    $(".tabbed1").tabs();
  }

  $("#remoteurlinput").focus(function() {
    if (this.value == 'e.g. http://www.phplist.com/testcampaign.html') {
      this.value = "";
    }
  })

  $("#remoteurlinput").blur(function() {
    if (this.value == "") {
      this.value = "e.g. http://www.phplist.com/testcampaign.html";
      return;
    }
    $("#remoteurlstatus").html(busyImage);
    $("#remoteurlstatus").load("./?page=pageaction&action=checkurl&ajaxed=true&url="+this.value);
  });

  $("input:radio[name=sendmethod]").change(function() {
    if (this.value == "remoteurl") {
      $("#remoteurl").show();
      $("#messagecontent").hide();
    } else {
      $("#remoteurl").hide();
      $("#messagecontent").show();
    }
  });

  $("a.savechanges").click(function() {
    if (changed) {
      document.sendmessageform.followupto.value = this.href;
      document.location.hash=""
      document.sendmessageform.submit();
      return false;
    }
  });

  $("#criteriaSelect").change(function() {
    var val = $("#criteriaSelect").val();
    var operator = '';
    switch (aT[val]) {
      case 'checkbox':
        $("#criteriaAttributeOperator").html('<input type="hidden" name="criteria_operator" value="is" />');
        $("#criteriaAttributeValues").html('CHECKED <input type="radio" name="criteria_values" value="checked" /> UNCHECKED <input type="radio" name="criteria_values" value="unchecked" />');
        break;
      case 'checkboxgroup':
      case 'select':
      case 'radio':
        $("#criteriaAttributeOperator").html('IS <input type="radio" name="criteria_operator" value="is" checked="checked" /> IS NOT <input type="radio" name="criteria_operator" value="isnot" />');
        $("#criteriaAttributeValues").html(busyImage);
        $("#criteriaAttributeValues").load("./?page=pageaction&ajaxed=true&action=attributevalues&name=criteria_values&type=multiselect&attid="+val);
        break;
      case 'date':
        $("#criteriaAttributeOperator").html('IS <input type="radio" name="criteria_operator" value="is" checked="checked" /> IS NOT <input type="radio" name="criteria_operator" value="isnot" /> IS BEFORE <input type="radio" name="criteria_operator" value="isbefore" /> IS AFTER <input type="radio" name="criteria_operator" value="isafter" />');
        $("#criteriaAttributeValues").html('<input type="text" id="datepicker" name="criteria_values" size="30"/>');
        $("#datepicker").datepicker({dateFormat: 'yy-mm-dd' });
        break;
      default:
        $("#criteriaAttributeOperator").html('');
        $("#criteriaAttributeValues").html('');
        break;
    }
  });

  $("#initialadminpassword").keyup(function() {
    if (this.value.length >= 8) {
      $("#initialisecontinue").removeAttr('disabled');
    }
  });

  // export page
  $("input:radio[name=column]").change(function() {
    if (this.value == 'nodate') {
      $("#exportdates").hide();
    } else {
      $("#exportdates").show();
    }
  });

  $("#processexport").click(function() {
    // for export, refresh underlying page, to get a new security token
    setTimeout("refreshExport()",2000);
  })

  //fade out 'actionresult' user feedback
  $('.actionresult').delay(4000).fadeOut(4000);
  //fade out 'result' user feedback
  $('.result').delay(4000).fadeOut(4000);

//  $("#processqueueoutput").html('Processing queue, please wait');
  $("#spinner").html(busyImage);

  $("#stopqueue").click(function() {
    $("#processqueueoutput").html('Processing cancelled');
    $("#spinner").html(' ');
    $("#stopqueue").hide();
    $("#resumequeue").show();
  });

  var docurl = document.location.search;
  document.cookie="browsetrail="+escape(docurl);

/* future dev
  $("#listinvalid").load("./?page=pageaction&action=listinvalid&ajaxed=true",function() {
 //  alert("Loaded")
  });
  $("#refreshCriteria").click(refreshCriteriaList);

  $("#addcriterionbutton").click(function() {
    $("#addcriterionbutton").addClass('disabled');
    var request = document.location.search+'&'+$("#sendmessageform").serialize();
    var attr = urlParameter('criteria_attribute',request);
    if (attr == '') {
      alert('Select an attribute to add');
      return false;
    };
    var vals = urlParameter('criteria_values',request);
    var arrVals = urlParameter('criteria_values[]',request);
    if (vals == '' && arrVals) {
      alert('Select a value to add');
      return false;
    };

    request = request.replace(/\?/,'');
    request = request.replace(/page=/,'origpage=');
    request = './?page=pageaction&action=storemessage&'+request;
    alert(request);
    $("#existingCriteria").html(busyImage);
 //   $("#hiddendiv").load(request);
 //   $("#sendmessageform").submit();
 //   setTimeout("refreshCriteriaList()",5000);

//    refreshCriteriaList();
    return true;
  });
*/

});

function allDone() {
  $("#processqueueoutput").html('All done');
  $("#spinner").html(' ');
  $("#stopqueue").hide();
  $("#resumequeue").show();
  $("#progressmeter").hide();
}

var overallTotal = 0;
var overallSent = 0;
$.fn.updateProgress = function() {
  var args = arguments[0].split(',') || {}; //  arguments
  var total = parseInt(args[1]);
  // fix the total first time
  if (total > overallTotal) {    overallTotal = total;  } else {    total = overallTotal;  }
  var done = parseInt(args[0]);
  if (done > 0) {
    overallSent += done;
  }
  var perc;
  if (overallTotal == 0) {
    perc = 0;
  } else {
    perc = parseInt((overallSent / overallTotal) * 100);
  }
  $("#progress").width(perc * 5);
  $("#progress").html(perc + '%');
  $("#progresscount").html(overallSent + ' / '+ overallTotal);
};

/*
 * old library of stuff that needs to be ported to jQuery style JS
 */

var helpwin = null;
var helploc = null;
function deleteRec(url) {
	if (confirm("Are you sure you want to delete this record?")) {
		document.location = url;
	}
}

function deleteRec2(msg,url) {
	if (confirm(msg)) {
		document.location = url;
  }
}

function help(loc) {
  if (helpwin && !helpwin.closed) {
    helpwin.close();
    helpwin = '';
    helploc = loc;
    setTimeout("openhelp()",500)
  } else {
    helploc = loc;
    openhelp();
  }
}

function openhelp() {
  helpwin=window.open(helploc,"help",'screenX=100,screenY=100,width=350,height=350,scrollbars=yes');
  if (window.focus) {helpwin.focus()}
}
function print_self(){
  window.focus();
  if (typeof(window.print) != "undefined"){
    window.print();
  } else {
    show_print_alert();
  }
}

function show_print_alert() {
  alert("Please use your browser's print button");
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

var pic = null;
var t_url;
var t_w;
var t_h;

function viewImage(url,w,h) {
   openpic(url,w,h);
}

function openpic(url,w,h) {
  if (w == null || w == 0) {
    w = 120;
  }
  if (h == null || h == 0){
    h = 120;
  }

  if (pic)  {
    pic.close();
    pic = null;
    t_url = url;
    t_w = w;
    t_h = h;
    setTimeout("openit()",500);
  } else {
    do_openpic(url,w,h);
  }
}

function openit() {
	do_openpic(t_url,t_w,t_h);
	t_url = null;
	t_w = null;
	t_h = null;
}

function do_openpic(url,w,h) {
  w +=30;
  h +=30;
  //var features = "scrollbars=auto,toolbar=yes,location=yes,menubar=yes,screenx=150,screeny=150";
  var	features = "dependent=yes,width=" + w + ",height=" + h + ",noresize,scrollbars=auto,toolbar=no,location=no,menubar=no,screenx=150,screeny=150";
//    alert(features);
  pic = window.open(url,"picwin",features);
  //    setTimeout("createContent()",100);

}
function createContent(){
  if (!pic.document){
    setTimeout("createContent()",100);
  } else {
    var url ="aaa";
    var w=100;
    var h=200;
    pic.document.write('');
    pic.document.write('');
    if (window.focus){pic.focus();}
  }
}

<|endoftext|>