<commit_before>
// Constants
var g = 9.8;
var p = new pendulum(130, .5);
var rp = new rimPendulum(0.2, 100.0, 100.0);
var lastUpdate = 0.0;
var EPSILON = 0.01;

var g = newtonRaphson(
  function(x) { return x*x - 5*x + 4; },
  2);
console.log(g);

function pendulum(length, angle) {
  this.length = length;
  this.angle = angle;
  this.velocity = 0;
}

function rimPendulum(omega, radius, length) {
  this.x = 250;
  this.y = 150;
  this.omega = omega;
  this.rotation = 0.0;
  this.radius = radius;
  this.length = length;
  this.angle = 0.0;
  this.angleV = 0.0;
}

function createScene() {

  window.requestAnimationFrame(draw);

}

// Newton Raphson method of root finding.
function newtonRaphson(f, guess) {

  var fprime = derivative(guess, EPSILON, f);
  var newguess = guess - f(guess) / fprime;
  var diff = Math.abs(newguess - guess);

  if (diff <= EPSILON) {
    return newguess;
  } else {
    newtonRaphson(f, newguess);
  }

}

function derivative(x, h, f) {
  return (f(x+h) - f(x)) / h;
}

function update(dt) {

  // compute acceleration
  var accel = -g/p.length * Math.sin(p.angle);

  // integrate velocity
  p.velocity = p.velocity + accel * dt;

  // integrate position
  p.angle = p.angle + p.velocity * dt;
}

function updateRim(dt) {

  var a = rp.radius;
  var b = rp.length;
  var theta = rp.angle
  var omega = rp.omega;
  var rotation = rp.rotation;

  var accel = a/b * omega*omega * Math.cos(theta - rotation)
      - g/b * Math.sin(theta - rotation);

  rp.rotation = rotation - dt * omega;

  rp.angleV = rp.angleV + dt * accel;

  rp.angle = rp.angle + dt * rp.angleV;

}

function drawRimPendulum(ctx) {

    var bx = rp.x + rp.radius*Math.cos(rp.rotation);
    var by = rp.y + rp.radius*Math.sin(rp.rotation);

    var px = bx + rp.length*Math.sin(rp.angle);
    var py = by + rp.length*Math.cos(rp.angle);

    ctx.lineWidth = 4;
    ctx.strokeStyle = 'rgba(0,153,255,0.4)';
    ctx.beginPath();
    ctx.arc(rp.x, rp.y, rp.radius, 0, 2*Math.PI);
    ctx.closePath();
    ctx.stroke();

    ctx.beginPath()
    ctx.arc(bx, by, 5, 0, 2*Math.PI);
    ctx.fill();

    ctx.moveTo(bx, by);
    ctx.lineTo(px, py);
    ctx.stroke();

}

// draw function
function draw() {

  var time = new Date();

  if (lastUpdate == 0) {
    lastUpdate = time.getTime() - 5;
  }

  var dt = time.getTime() - lastUpdate;
  lastUpdate = time.getTime();

    dt *= 0.01

    update(dt);
    updateRim(dt);

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    ctx.globalCompositeOperation = 'destination-over';
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

    ctx.fillStyle = "#FFFF00";

    drawRimPendulum(ctx);

    var offsetx = p.length*Math.sin(p.angle);
    var offsety = p.length*Math.cos(p.angle);

    var bx = 100;
    var by = 10;

    ctx.beginPath();
    ctx.moveTo(bx,by);
    ctx.lineTo(bx+offsetx,by+offsety);
    ctx.closePath();
    ctx.stroke();

    window.requestAnimationFrame(draw);
    // setTimeout(draw, 5);

}

<commit_msg>used velocity verlet for integration<commit_after>
// Constants
var g = 9.8;
var p = new pendulum(130, 2.14);
var rp = new rimPendulum(0.0, 100.0, 200.0);
var lastUpdate = 0.0;
var EPSILON = 0.01;

var g = newtonRaphson(
  function(x) { return x*x - 5*x - 4; },
  0);

console.log(g);

function pendulum(length, angle) {
  this.length = length;
  this.angle = angle;
  this.velocity = 0;
}

function rimPendulum(omega, radius, length) {
  this.x = 250;
  this.y = 150;
  this.omega = omega;
  this.rotation = 0.0;
  this.radius = radius;
  this.length = length;
  this.angle = 3.14;
  this.angleV = 0.0;
}

function createScene() {

  window.requestAnimationFrame(draw);

}

// Newton Raphson method of root finding.
function newtonRaphson(f, guess) {

  var fprime = derivative(guess, EPSILON, f);
  var newguess = guess - f(guess) / fprime;
  var diff = Math.abs(newguess - guess);

  if (diff <= EPSILON) {
    return newguess;
  } else {
    return newtonRaphson(f, newguess);
  }

}

// Approximation of the derivative at x
function derivative(x, h, f) {
  return (f(x+h) - f(x)) / h;
}

function updatePendulum(dt) {

  // compute acceleration
  var accel = -g/p.length * Math.sin(p.angle);

  // integrate velocity
  // p.velocity = p.velocity + accel * dt;

  var v = p.velocity;

  p.velocity = newtonRaphson(
    function(x) {
      return x - v - dt * accel;
    }, 0);

  // integrate position
  p.angle = p.angle + p.velocity * dt;
}

function updateRim(dt) {

  var a = rp.radius;
  var b = rp.length;
  var theta = rp.angle
  var omega = rp.omega;
  var rotation = rp.rotation;

  var accel = a/b * omega*omega
      * Math.cos(theta - rotation)
      - g/b * Math.sin(theta);

  rp.rotation = rotation - dt * omega;

  // rp.angleV = rp.angleV + dt * accel;
  var p1 = rp.angle + dt * rp.angleV + 0.5*accel*dt*dt;
  var v1 = rp.angleV + 0.5*accel*dt;

  var accel2 = a/b * omega*omega
      * Math.cos(p1 - rotation)
      - g/b * Math.sin(p1)

  rp.angleV = v1 + 0.5*accel2*dt;

  rp.angle = p1;

  // var v = rp.angleV;
  // rp.angleV = newtonRaphson(
  //   function(x) {
  //     return x - v - dt * accel;
  //   }, 0);

}

function drawRimPendulum(ctx) {

    var bx = rp.x + rp.radius*Math.cos(rp.rotation);
    var by = rp.y + rp.radius*Math.sin(rp.rotation);

    var px = bx + rp.length*Math.sin(rp.angle + Math.PI);
    var py = by + rp.length*Math.cos(rp.angle + Math.PI);

    ctx.beginPath();
    ctx.arc(rp.x, rp.y, rp.radius, 0, 2*Math.PI);
    ctx.closePath();
    ctx.stroke();

    ctx.beginPath()
    ctx.arc(bx, by, 5, 0, 2*Math.PI);
    ctx.fill();

    ctx.moveTo(bx, by);
    ctx.lineTo(px, py);
    ctx.stroke();

}

function drawPendulum(ctx) {
  var offsetx = p.length*Math.sin(p.angle + Math.PI);
  var offsety = p.length*Math.cos(p.angle + Math.PI);

  var bx = 500;
  var by = 100;

  ctx.beginPath();
  ctx.moveTo(bx,by);
  ctx.lineTo(bx+offsetx,by+offsety);
  ctx.closePath();
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(bx + offsetx, by + offsety, 5, 0, 2*Math.PI);
  ctx.stroke();
}

// draw function
function draw() {

  var time = new Date();

  if (lastUpdate == 0) {
    lastUpdate = time.getTime() - 5;
  }

  var dt = time.getTime() - lastUpdate;
  lastUpdate = time.getTime();

  dt *= 0.1

  updatePendulum(dt);
  updateRim(dt);

  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  ctx.lineWidth = 4;
  ctx.strokeStyle = 'rgba(0,153,255,1.0)';
  ctx.fillStyle = "#FFFF00";

  drawRimPendulum(ctx);

  drawPendulum(ctx);

  window.requestAnimationFrame(draw);
  // setTimeout(draw, 5);

}

function onVelocityChanged(slider) {

  var vel = slider.value;
  rp.omega = vel;

}
<|endoftext|>


<commit_before>'use strict';

class SortedArrayNumber {
    constructor(size = 64) {
        this._arr = Array(size).fill(Number());
        this.count = 0;

        Object.defineProperty(this, 'array', {
            get: () => this._arr
        });
    }

    insert(x) {
        let i;
        for(i = this.count; i > 0 && x < this._arr[i-1]; i--) {
            this._arr[i] = this._arr[i-1];
        }
        this._arr[i] = x;
        this.count++;
        return i;
    }

    delete(x) {
        const i = this.BinarySearchRecursive(x);
        if(i >= 0) {
            for(let j = i; j < this.count-1; j++) {
                this._arr[j] = this._arr[j+1];
            }
            this.count--;
        }
        return i;
    }

    [Symbol.iterator]() {
        return this._arr.slice(0, this.count)[Symbol.iterator]();
    }

    static InsertionSort(a, n) {
        for(let o = 1; o < n; o++) {
            for(let i = o; i > 0 && a[i] < a[i-1]; i--) {
                [a[i], a[i-1]] = [a[i-1], a[i]];
            }
        }
        // Invariant: a[:o] sorted
    }

    static BubbleSort(a, n) {
        for(let swapped = true, o = n - 1; swapped && o > 0; o--) {
            for(let swapped = false, i = 0; i < o; i++) {
                if(a[i] > a[i+1]) {
                    [a[i], a[i+1]] = [a[i+1], a[i]];
                    swapped = true;
                }
            }
            // Invariant: a[o:] sorted
        }
    }

    static SelectionSort(a, n) {
        for(let o = 0, min = 0; o < n - 1; min = ++o) {
            for(let i = o + 1; i < n; i++) {
                if(a[i] < a[min]) {
                    min = i;
                }
            }
            if(o != min) {
                [a[o], a[min]] = [a[min], a[o]];
            }
        }
    }

    BinarySearchIterative(x) {
        return this.constructor.BinarySearchIterative(
            this._arr, x, 0, this.count-1);
    }

    static BinarySearchIterative(a, x, min, max) {
        while(min <= max) {
            const mid = Math.trunc((min+max)/2);
            if(x < a[mid]) {
                max = mid - 1;
            }
            else if(x > a[mid]) {
                min = mid + 1;
            }
            else {
                return mid;
            }
        }
        return -1;
    }

    BinarySearchRecursive(x) {
        return this.constructor.BinarySearchRecursive(
            this._arr, x, 0, this.count-1);
    }
}

SortedArrayNumber.BinarySearchRecursive = function f(a, x, min, max) {
    if(min > max) {
        return -1;
    }
    const mid = Math.trunc((min + max) / 2);
    if(x < a[mid]) {
        return f(a, x, min, mid-1);
    }
    else if(x > a[mid]) {
        return f(a, x, mid+1, max);
    }
    else {
        return mid;
    }
}

exports.SortedArrayNumber = SortedArrayNumber;
<commit_msg>Selection sort: use strict rather than abstract inequality<commit_after>'use strict';

class SortedArrayNumber {
    constructor(size = 64) {
        this._arr = Array(size).fill(Number());
        this.count = 0;

        Object.defineProperty(this, 'array', {
            get: () => this._arr
        });
    }

    insert(x) {
        let i;
        for(i = this.count; i > 0 && x < this._arr[i-1]; i--) {
            this._arr[i] = this._arr[i-1];
        }
        this._arr[i] = x;
        this.count++;
        return i;
    }

    delete(x) {
        const i = this.BinarySearchRecursive(x);
        if(i >= 0) {
            for(let j = i; j < this.count-1; j++) {
                this._arr[j] = this._arr[j+1];
            }
            this.count--;
        }
        return i;
    }

    [Symbol.iterator]() {
        return this._arr.slice(0, this.count)[Symbol.iterator]();
    }

    static InsertionSort(a, n) {
        for(let o = 1; o < n; o++) {
            for(let i = o; i > 0 && a[i] < a[i-1]; i--) {
                [a[i], a[i-1]] = [a[i-1], a[i]];
            }
        }
        // Invariant: a[:o] sorted
    }

    static BubbleSort(a, n) {
        for(let swapped = true, o = n - 1; swapped && o > 0; o--) {
            for(let swapped = false, i = 0; i < o; i++) {
                if(a[i] > a[i+1]) {
                    [a[i], a[i+1]] = [a[i+1], a[i]];
                    swapped = true;
                }
            }
            // Invariant: a[o:] sorted
        }
    }

    static SelectionSort(a, n) {
        for(let o = 0, min = 0; o < n - 1; min = ++o) {
            for(let i = o + 1; i < n; i++) {
                if(a[i] < a[min]) {
                    min = i;
                }
            }
            if(o !== min) {
                [a[o], a[min]] = [a[min], a[o]];
            }
        }
    }

    BinarySearchIterative(x) {
        return this.constructor.BinarySearchIterative(
            this._arr, x, 0, this.count-1);
    }

    static BinarySearchIterative(a, x, min, max) {
        while(min <= max) {
            const mid = Math.trunc((min+max)/2);
            if(x < a[mid]) {
                max = mid - 1;
            }
            else if(x > a[mid]) {
                min = mid + 1;
            }
            else {
                return mid;
            }
        }
        return -1;
    }

    BinarySearchRecursive(x) {
        return this.constructor.BinarySearchRecursive(
            this._arr, x, 0, this.count-1);
    }
}

SortedArrayNumber.BinarySearchRecursive = function f(a, x, min, max) {
    if(min > max) {
        return -1;
    }
    const mid = Math.trunc((min + max) / 2);
    if(x < a[mid]) {
        return f(a, x, min, mid-1);
    }
    else if(x > a[mid]) {
        return f(a, x, mid+1, max);
    }
    else {
        return mid;
    }
}

exports.SortedArrayNumber = SortedArrayNumber;
<|endoftext|>


<commit_before>dojo.provide("dijit._Calendar");

dojo.require("dojo.cldr.supplemental");
dojo.require("dojo.date");
dojo.require("dojo.date.locale");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare(
	"dijit._Calendar",
	[dijit._Widget, dijit._Templated],
	{
	//
	//	summary:
	//		A simple GUI for choosing a date in the context of a monthly calendar.
	//
	//	description:
	//		A simple GUI for choosing a date in the context of a monthly calendar.
	//		This widget is used internally by other widgets and is not accessible
	//		as a standalone widget.
	//		This widget can't be used in a form because it doesn't serialize the date to an
	//		`<input>` field.  For a form element, use dijit.form.DateTextBox instead.
	//
	//		Note that the parser takes all dates attributes passed in the
	//		[RFC 3339 format](http://www.faqs.org/rfcs/rfc3339.html), e.g. `2005-06-30T08:05:00-07:00`
	//		so that they are serializable and locale-independent.
	//
	//	example:
	//	|	var calendar = new dijit._Calendar({}, dojo.byId("calendarNode"));
	//
	//	example:
	//	|

	//
		templatePath: dojo.moduleUrl("dijit", "templates/Calendar.html"),

		// value: Date
		// 	the currently selected Date
		value: new Date(),

		// dayWidth: String
		// 	How to represent the days of the week in the calendar header. See dojo.date.locale
		dayWidth: "narrow",

		setValue: function(/*Date*/ value){
			dojo.deprecated("dijit.Calendar:setValue() is deprecated.  Use attr('value', ...) instead.", "", "2.0");
			this.attr('value', value);
		},
		_setValueAttr: function(/*Date*/ value){
			// summary:
			//		Hook to make attr("value", ...) work.
			// description:
			// 		Set the current date and update the UI.  If the date is disabled, the selection will
			//		not change, but the display will change to the corresponding month.
			if(!this.value || dojo.date.compare(value, this.value)){
				value = new Date(value);
				this.displayMonth = new Date(value);
				if(!this.isDisabledDate(value, this.lang)){
					this.value = value;
					this.value.setHours(0,0,0,0);
					this.onChange(this.value);
				}
				this._populateGrid();
			}
		},

		_setText: function(node, text){
			// summary:
			//		This just sets the content of node to the specified text.
			//		Can't do "node.innerHTML=text" because of an IE bug w/tables, see #3434.
			while(node.firstChild){
				node.removeChild(node.firstChild);
			}
			node.appendChild(dojo.doc.createTextNode(text));
		},

		_populateGrid: function(){
			var month = this.displayMonth;
			month.setDate(1);
			var firstDay = month.getDay();
			var daysInMonth = dojo.date.getDaysInMonth(month);
			var daysInPreviousMonth = dojo.date.getDaysInMonth(dojo.date.add(month, "month", -1));
			var today = new Date();
			var selected = this.value;

			var dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
			if(dayOffset > firstDay){ dayOffset -= 7; }

			// Iterate through dates in the calendar and fill in date numbers and style info
			dojo.query(".dijitCalendarDateTemplate", this.domNode).forEach(function(template, i){
				i += dayOffset;
				var date = new Date(month);
				var number, clazz = "dijitCalendar", adj = 0;

				if(i < firstDay){
					number = daysInPreviousMonth - firstDay + i + 1;
					adj = -1;
					clazz += "Previous";
				}else if(i >= (firstDay + daysInMonth)){
					number = i - firstDay - daysInMonth + 1;
					adj = 1;
					clazz += "Next";
				}else{
					number = i - firstDay + 1;
					clazz += "Current";
				}

				if(adj){
					date = dojo.date.add(date, "month", adj);
				}
				date.setDate(number);

				if(!dojo.date.compare(date, today, "date")){
					clazz = "dijitCalendarCurrentDate " + clazz;
				}

				if(!dojo.date.compare(date, selected, "date")){
					clazz = "dijitCalendarSelectedDate " + clazz;
				}

				if(this.isDisabledDate(date, this.lang)){
					clazz = "dijitCalendarDisabledDate " + clazz;
				}

				var clazz2 = this.getClassForDate(date, this.lang);
				if(clazz2){
					clazz = clazz2 + " " + clazz;
				}

				template.className =  clazz + "Month dijitCalendarDateTemplate";
				template.dijitDateValue = date.valueOf();
				var label = dojo.query(".dijitCalendarDateLabel", template)[0];
				this._setText(label, date.getDate());
			}, this);

			// Fill in localized month name
			var monthNames = dojo.date.locale.getNames('months', 'wide', 'standAlone', this.lang);
			this._setText(this.monthLabelNode, monthNames[month.getMonth()]);

			// Fill in localized prev/current/next years
			var y = month.getFullYear() - 1;
			var d = new Date();
			dojo.forEach(["previous", "current", "next"], function(name){
				d.setFullYear(y++);
				this._setText(this[name+"YearLabelNode"],
					dojo.date.locale.format(d, {selector:'year', locale:this.lang}));
			}, this);

			// Set up repeating mouse behavior
			var _this = this;
			var typematic = function(nodeProp, dateProp, adj){
				_this._connects.push(
					dijit.typematic.addMouseListener(_this[nodeProp], _this, function(count){
						if(count >= 0){ _this._adjustDisplay(dateProp, adj); }
					}, 0.8, 500)
				);
			};
			typematic("incrementMonth", "month", 1);
			typematic("decrementMonth", "month", -1);
			typematic("nextYearLabelNode", "year", 1);
			typematic("previousYearLabelNode", "year", -1);
		},

		goToToday: function(){
			this.attr('value', new Date());
		},

		postCreate: function(){
			this.inherited(arguments);
			dojo.setSelectable(this.domNode, false);

			var cloneClass = dojo.hitch(this, function(clazz, n){
				var template = dojo.query(clazz, this.domNode)[0];
	 			for(var i=0; i<n; i++){
					template.parentNode.appendChild(template.cloneNode(true));
				}
			});

			// clone the day label and calendar day templates 6 times to make 7 columns
			cloneClass(".dijitCalendarDayLabelTemplate", 6);
			cloneClass(".dijitCalendarDateTemplate", 6);

			// now make 6 week rows
			cloneClass(".dijitCalendarWeekTemplate", 5);

			// insert localized day names in the header
			var dayNames = dojo.date.locale.getNames('days', this.dayWidth, 'standAlone', this.lang);
			var dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
			dojo.query(".dijitCalendarDayLabel", this.domNode).forEach(function(label, i){
				this._setText(label, dayNames[(i + dayOffset) % 7]);
			}, this);

			// Fill in spacer element with all the month names (invisible) so that the maximum width will affect layout
			var monthNames = dojo.date.locale.getNames('months', 'wide', 'standAlone', this.lang);
			dojo.forEach(monthNames, function(name){
				var monthSpacer = dojo.create("div", null, this.monthLabelSpacer);
				this._setText(monthSpacer, name);
			}, this);

			this.value = null;
			this.attr('value', new Date());
		},

		_adjustDisplay: function(/*String*/part, /*int*/amount){
			this.displayMonth = dojo.date.add(this.displayMonth, part, amount);
			this._populateGrid();
		},

		_onDayClick: function(/*Event*/evt){
			dojo.stopEvent(evt);
			for(var node = evt.target; node && !node.dijitDateValue; node = node.parentNode);
			if(node && !dojo.hasClass(node, "dijitCalendarDisabledDate")){
				this.attr('value', node.dijitDateValue);
				this.onValueSelected(this.value);
			}
		},

		_onDayMouseOver: function(/*Event*/evt){
			var node = evt.target;
			if(node && (node.dijitDateValue || node == this.previousYearLabelNode || node == this.nextYearLabelNode) ){
				dojo.addClass(node, "dijitCalendarHoveredDate");
				this._currentNode = node;
			}
		},

		_onDayMouseOut: function(/*Event*/evt){
			if(!this._currentNode){ return; }
			for(var node = evt.relatedTarget; node;){
				if(node == this._currentNode){ return; }
				try{
					node = node.parentNode;
				}catch(x){
					node = null;
				}
			}
			dojo.removeClass(this._currentNode, "dijitCalendarHoveredDate");
			this._currentNode = null;
		},

		onValueSelected: function(/*Date*/date){
			// summary: a date cell was selected.  It may be the same as the previous value.
		},

		onChange: function(/*Date*/date){
			// summary: called only when the selected date has changed
		},

		isDisabledDate: function(/*Date*/dateObject, /*String?*/locale){
			// summary:
			//	May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
/*=====
			return false; // Boolean
=====*/
		},

		getClassForDate: function(/*Date*/dateObject, /*String?*/locale){
			// summary:
			//  May be overridden to return CSS classes to associate with the date entry for the given dateObject,
			//  for example to indicate a holiday in specified locale.

/*=====
			return ""; // String
=====*/
		}
	}
);
<commit_msg>Avoid Brazilian DST problem (DST occurs at 12AM)  Fixes #8521 !strict<commit_after>dojo.provide("dijit._Calendar");

dojo.require("dojo.cldr.supplemental");
dojo.require("dojo.date");
dojo.require("dojo.date.locale");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");

dojo.declare(
	"dijit._Calendar",
	[dijit._Widget, dijit._Templated],
	{
	//
	//	summary:
	//		A simple GUI for choosing a date in the context of a monthly calendar.
	//
	//	description:
	//		A simple GUI for choosing a date in the context of a monthly calendar.
	//		This widget is used internally by other widgets and is not accessible
	//		as a standalone widget.
	//		This widget can't be used in a form because it doesn't serialize the date to an
	//		`<input>` field.  For a form element, use dijit.form.DateTextBox instead.
	//
	//		Note that the parser takes all dates attributes passed in the
	//		[RFC 3339 format](http://www.faqs.org/rfcs/rfc3339.html), e.g. `2005-06-30T08:05:00-07:00`
	//		so that they are serializable and locale-independent.
	//
	//	example:
	//	|	var calendar = new dijit._Calendar({}, dojo.byId("calendarNode"));
	//
	//	example:
	//	|

	//
		templatePath: dojo.moduleUrl("dijit", "templates/Calendar.html"),

		// value: Date
		// 	the currently selected Date
		value: new Date(),

		// dayWidth: String
		// 	How to represent the days of the week in the calendar header. See dojo.date.locale
		dayWidth: "narrow",

		setValue: function(/*Date*/ value){
			dojo.deprecated("dijit.Calendar:setValue() is deprecated.  Use attr('value', ...) instead.", "", "2.0");
			this.attr('value', value);
		},
		_setValueAttr: function(/*Date*/ value){
			// summary:
			//		Hook to make attr("value", ...) work.
			// description:
			// 		Set the current date and update the UI.  If the date is disabled, the selection will
			//		not change, but the display will change to the corresponding month.
			if(!this.value || dojo.date.compare(value, this.value)){
				value = new Date(value);
				value.setHours(1); // to avoid DST issues in Brazil see #8521
				this.displayMonth = new Date(value);
				if(!this.isDisabledDate(value, this.lang)){
					this.onChange(this.value = value);
				}
				this._populateGrid();
			}
		},

		_setText: function(node, text){
			// summary:
			//		This just sets the content of node to the specified text.
			//		Can't do "node.innerHTML=text" because of an IE bug w/tables, see #3434.
			while(node.firstChild){
				node.removeChild(node.firstChild);
			}
			node.appendChild(dojo.doc.createTextNode(text));
		},

		_populateGrid: function(){
			var month = this.displayMonth;
			month.setDate(1);
			var firstDay = month.getDay();
			var daysInMonth = dojo.date.getDaysInMonth(month);
			var daysInPreviousMonth = dojo.date.getDaysInMonth(dojo.date.add(month, "month", -1));
			var today = new Date();
			var selected = this.value;

			var dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
			if(dayOffset > firstDay){ dayOffset -= 7; }

			// Iterate through dates in the calendar and fill in date numbers and style info
			dojo.query(".dijitCalendarDateTemplate", this.domNode).forEach(function(template, i){
				i += dayOffset;
				var date = new Date(month);
				var number, clazz = "dijitCalendar", adj = 0;

				if(i < firstDay){
					number = daysInPreviousMonth - firstDay + i + 1;
					adj = -1;
					clazz += "Previous";
				}else if(i >= (firstDay + daysInMonth)){
					number = i - firstDay - daysInMonth + 1;
					adj = 1;
					clazz += "Next";
				}else{
					number = i - firstDay + 1;
					clazz += "Current";
				}

				if(adj){
					date = dojo.date.add(date, "month", adj);
				}
				date.setDate(number);

				if(!dojo.date.compare(date, today, "date")){
					clazz = "dijitCalendarCurrentDate " + clazz;
				}

				if(!dojo.date.compare(date, selected, "date")){
					clazz = "dijitCalendarSelectedDate " + clazz;
				}

				if(this.isDisabledDate(date, this.lang)){
					clazz = "dijitCalendarDisabledDate " + clazz;
				}

				var clazz2 = this.getClassForDate(date, this.lang);
				if(clazz2){
					clazz = clazz2 + " " + clazz;
				}

				template.className =  clazz + "Month dijitCalendarDateTemplate";
				template.dijitDateValue = date.valueOf();
				var label = dojo.query(".dijitCalendarDateLabel", template)[0];
				this._setText(label, date.getDate());
			}, this);

			// Fill in localized month name
			var monthNames = dojo.date.locale.getNames('months', 'wide', 'standAlone', this.lang);
			this._setText(this.monthLabelNode, monthNames[month.getMonth()]);

			// Fill in localized prev/current/next years
			var y = month.getFullYear() - 1;
			var d = new Date();
			dojo.forEach(["previous", "current", "next"], function(name){
				d.setFullYear(y++);
				this._setText(this[name+"YearLabelNode"],
					dojo.date.locale.format(d, {selector:'year', locale:this.lang}));
			}, this);

			// Set up repeating mouse behavior
			var _this = this;
			var typematic = function(nodeProp, dateProp, adj){
				_this._connects.push(
					dijit.typematic.addMouseListener(_this[nodeProp], _this, function(count){
						if(count >= 0){ _this._adjustDisplay(dateProp, adj); }
					}, 0.8, 500)
				);
			};
			typematic("incrementMonth", "month", 1);
			typematic("decrementMonth", "month", -1);
			typematic("nextYearLabelNode", "year", 1);
			typematic("previousYearLabelNode", "year", -1);
		},

		goToToday: function(){
			this.attr('value', new Date());
		},

		postCreate: function(){
			this.inherited(arguments);
			dojo.setSelectable(this.domNode, false);

			var cloneClass = dojo.hitch(this, function(clazz, n){
				var template = dojo.query(clazz, this.domNode)[0];
	 			for(var i=0; i<n; i++){
					template.parentNode.appendChild(template.cloneNode(true));
				}
			});

			// clone the day label and calendar day templates 6 times to make 7 columns
			cloneClass(".dijitCalendarDayLabelTemplate", 6);
			cloneClass(".dijitCalendarDateTemplate", 6);

			// now make 6 week rows
			cloneClass(".dijitCalendarWeekTemplate", 5);

			// insert localized day names in the header
			var dayNames = dojo.date.locale.getNames('days', this.dayWidth, 'standAlone', this.lang);
			var dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
			dojo.query(".dijitCalendarDayLabel", this.domNode).forEach(function(label, i){
				this._setText(label, dayNames[(i + dayOffset) % 7]);
			}, this);

			// Fill in spacer element with all the month names (invisible) so that the maximum width will affect layout
			var monthNames = dojo.date.locale.getNames('months', 'wide', 'standAlone', this.lang);
			dojo.forEach(monthNames, function(name){
				var monthSpacer = dojo.create("div", null, this.monthLabelSpacer);
				this._setText(monthSpacer, name);
			}, this);

			this.value = null;
			this.attr('value', new Date());
		},

		_adjustDisplay: function(/*String*/part, /*int*/amount){
			this.displayMonth = dojo.date.add(this.displayMonth, part, amount);
			this._populateGrid();
		},

		_onDayClick: function(/*Event*/evt){
			dojo.stopEvent(evt);
			for(var node = evt.target; node && !node.dijitDateValue; node = node.parentNode);
			if(node && !dojo.hasClass(node, "dijitCalendarDisabledDate")){
				this.attr('value', node.dijitDateValue);
				this.onValueSelected(this.value);
			}
		},

		_onDayMouseOver: function(/*Event*/evt){
			var node = evt.target;
			if(node && (node.dijitDateValue || node == this.previousYearLabelNode || node == this.nextYearLabelNode) ){
				dojo.addClass(node, "dijitCalendarHoveredDate");
				this._currentNode = node;
			}
		},

		_onDayMouseOut: function(/*Event*/evt){
			if(!this._currentNode){ return; }
			for(var node = evt.relatedTarget; node;){
				if(node == this._currentNode){ return; }
				try{
					node = node.parentNode;
				}catch(x){
					node = null;
				}
			}
			dojo.removeClass(this._currentNode, "dijitCalendarHoveredDate");
			this._currentNode = null;
		},

		onValueSelected: function(/*Date*/date){
			// summary: a date cell was selected.  It may be the same as the previous value.
		},

		onChange: function(/*Date*/date){
			// summary: called only when the selected date has changed
		},

		isDisabledDate: function(/*Date*/dateObject, /*String?*/locale){
			// summary:
			//	May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
/*=====
			return false; // Boolean
=====*/
		},

		getClassForDate: function(/*Date*/dateObject, /*String?*/locale){
			// summary:
			//  May be overridden to return CSS classes to associate with the date entry for the given dateObject,
			//  for example to indicate a holiday in specified locale.

/*=====
			return ""; // String
=====*/
		}
	}
);
<|endoftext|>


<commit_before>'use strict';

define(['ol',
        'toolbar',
        'layermanager',
        'WfsSource', 'query',
        'search',
        'print',
        'permalink',
        'measure',
        'geolocation',
        'api',
        'glutils', 'WGL', 'wglinit', 'manager', 'mapcontroller', 'dataloader', 'd3', 'dimension',
        'heatmapdimension', 'chart_panel', 'stackedbarchart', 'histogramdimension', 'mapdimension', 'floatreaderhistogram',
        'floatrasterreader', 'linearfilter', 'filter', 'multibrush'
    ],

    function(ol, toolbar, layermanager, WfsSource) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.geolocation', 'hs.widgets.chart_panel'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', 'webgl_viz', function(OlMap, Core, $compile, webgl_viz) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    Core.fullscreenMap(element);
                    $("#right-pane", element).append($compile('

')(scope));
                    $("#right-pane", element).attr('class', 'col-md-5');
                    //webgl_viz.webgl_el = $compile('<canvas id="webglayer"></canvas>')(scope);
                    //element.append(webgl_viz.webgl_el);
                    webgl_viz.init();
                }
            };
        }]);

        module.service('webgl_viz', ['hs.map.service',  function(OlMap) {
            OlMap.map.removeInteraction(OlMap.interactions.DragPan);
            OlMap.interactions.DragPan = new ol.interaction.DragPan({
                kinetic: false
            });
            OlMap.map.addInteraction(OlMap.interactions.DragPan);

            var me = {
                map: OlMap.map,
                ol: ol,
                init: function() {
                    wglinit(this);
                }
            };

            return me;
        }])

        module.value('box_layers', []);

        module.value('default_layers', [
            new ol.layer.Tile({
                source: new ol.source.OSM(),
                title: "Base layer",
                box_id: 'osm',
                base: true
            })
        ]);

        module.value('default_view', new ol.View({
            center: ol.proj.transform([17.474129, 52.574000], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
            zoom: 4,
            units: "m"
        }));

        module.controller('Main', ['$scope', 'Core', 'hs.map.service',  'default_layers', 'webgl_viz',
            function($scope, Core, OlMap, default_layers, webgl_viz) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                var map = OlMap.map;
                $scope.$on('infopanel.updated', function(event) {});

            }
        ]);

        return module;
    });
<commit_msg>positioning of elements<commit_after>'use strict';

define(['ol',
        'toolbar',
        'layermanager',
        'WfsSource', 'query',
        'search',
        'print',
        'permalink',
        'measure',
        'geolocation',
        'api',
        'glutils', 'WGL', 'wglinit', 'manager', 'mapcontroller', 'dataloader', 'd3', 'dimension',
        'heatmapdimension', 'chart_panel', 'stackedbarchart', 'histogramdimension', 'mapdimension', 'floatreaderhistogram',
        'floatrasterreader', 'linearfilter', 'filter', 'multibrush'
    ],

    function(ol, toolbar, layermanager, WfsSource) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.geolocation', 'hs.widgets.chart_panel'
        ]);

        module.directive('hs', ['hs.map.service', 'Core', '$compile', 'webgl_viz', function(OlMap, Core, $compile, webgl_viz) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    Core.fullscreenMap(element, 'right');
                    $("#right-pane", element).append($compile('

')(scope));
                    $("#right-pane", element).attr('class', 'col-md-5').css({'padding-top': "40px", 'padding-left': '33px'});
                    $(".search-container").removeClass('col-md-4').addClass('col-md-3');
                    //webgl_viz.webgl_el = $compile('<canvas id="webglayer"></canvas>')(scope);
                    //element.append(webgl_viz.webgl_el);
                    webgl_viz.init();
                }
            };
        }]);

        module.service('webgl_viz', ['hs.map.service',  function(OlMap) {
            OlMap.map.removeInteraction(OlMap.interactions.DragPan);
            OlMap.interactions.DragPan = new ol.interaction.DragPan({
                kinetic: false
            });
            OlMap.map.addInteraction(OlMap.interactions.DragPan);

            var me = {
                map: OlMap.map,
                ol: ol,
                init: function() {
                    wglinit(this);
                }
            };

            return me;
        }])

        module.value('box_layers', []);

        module.value('default_layers', [
            new ol.layer.Tile({
                source: new ol.source.OSM(),
                title: "Base layer",
                box_id: 'osm',
                base: true
            })
        ]);

        module.value('default_view', new ol.View({
            center: ol.proj.transform([17.474129, 52.574000], 'EPSG:4326', 'EPSG:3857'), //Latitude longitude    to Spherical Mercator
            zoom: 4,
            units: "m"
        }));

        module.controller('Main', ['$scope', 'Core', 'hs.map.service',  'default_layers', 'webgl_viz',
            function($scope, Core, OlMap, default_layers, webgl_viz) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                var map = OlMap.map;
                $scope.$on('infopanel.updated', function(event) {});

            }
        ]);

        return module;
    });
<|endoftext|>


<commit_before>/**
 *
 * Install:
 *      npm install browser-sync
 *
 * Run:
 *      node <yourfile.js>
 *
 * This example will redirect all 404 requests to a
 * custom 404.html page
 *
 */

"use strict";

var browserSync = require("browser-sync").create();

browserSync.init({
    files: ["app/css/*.css"],
    server: {
        baseDir: "app"
    }
}, function (err, bs) {
    bs.addMiddleware("*", function (req, res) {
        res.writeHead(302, {
            "location": "404.html"
        });
        res.end('Redirecting!');
    });
});
<commit_msg>ci: remove single quotes from 404 example<commit_after>/**
 *
 * Install:
 *      npm install browser-sync
 *
 * Run:
 *      node <yourfile.js>
 *
 * This example will redirect all 404 requests to a
 * custom 404.html page
 *
 */

"use strict";

var browserSync = require("browser-sync").create();

browserSync.init({
    files: ["app/css/*.css"],
    server: {
        baseDir: "app"
    }
}, function (err, bs) {
    bs.addMiddleware("*", function (req, res) {
        res.writeHead(302, {
            "location": "404.html"
        });
        res.end("Redirecting!");
    });
});
<|endoftext|>


<commit_before>var xmpp = require('../lib/node-xmpp');
var SoftwareVersion = require('../lib/xmpp/c2s_mods/software_version');

/*
 *  TODO
 *  - support for Presence module
 *  - Support for TLS () : https://groups.google.com/group/nodejs/browse_thread/thread/1e8e6501493d63b8#
 *  - Admin tools
 *  - Component interface
 *  - Plugins for 'well-known' services (Roster, PubSub, PEP)
 *  - Logging
 *  - Shapers
 *  - In-band registration
 *  - mods :
 *      - presence
 *      - offline
 *      - announce
 *      - caps
 *      - muc
 *      - roster
 *      - PEP
 */

// Sets up the server.
var c2s = new xmpp.C2S({
    port: 5222,
    domain: 'zipline.local',
    // tls: {
    //     keyPath: './examples/zipline.local.pem',
    //     certPath: './examples/zipline.local.certificate.pem',
    // }
});

// Allows the developer to authenticate users against anything they want.
c2s.on("authenticate", function(jid, password, client) {
    if(jid.user == "julien" || password == "hello") {
        client.emit("auth-success", jid);
    }
    else {
        client.emit("auth-fail", jid);
    }
});

// That's the way you add mods to a given server.
c2s.supports(SoftwareVersion);
SoftwareVersion.name = "Node XMPP server example";
SoftwareVersion.version = "0.0.0.1";
SoftwareVersion.os = "Mac OS X 10.7 Lion";

// Most imoortant pieces of code : that is where you can configure your XMPP server to support only what you care about/need.
c2s.on("stanza", function(stanza, client) {
    var query, vCard;
    // We should provide a bunch of "plugins" for the functionalities below.

    // No roster support in this server!
    if (stanza.is('iq') && (session = stanza.getChild('query', 'jabber:iq:roster'))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No private support on this server
    else if (stanza.is('iq') && (query = stanza.getChild('query', "jabber:iq:private"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No vCard support on this server.
    else if (stanza.is('iq') && (vCard = stanza.getChild('vCard', "vcard-temp"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No DiscoInfo on this server.
    else if (stanza.is('iq') && (query = stanza.getChild('query', "http://jabber.org/protocol/disco#info"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No Version support on this server.
    else {

    }
})

// You can also decide to rewrite many things, like for example the way you route stanzas.
// This will allow for clustering for your node-xmpp server, using redis's PubSub feature.
// To run this example in its full "power", just run node exmaple c2s.js from 2 different machines, as long as they share the redis server, they should be able to communicate!
// var sys = require("sys");
// var redis = require("redis-node");
// var redispub = redis.createClient();
// var redissub = redis.createClient();
//
// xmpp.C2S.prototype.route = function(stanza) {
//     var self = this;
//     if(stanza.attrs && stanza.attrs.to) {
//         var toJid = new xmpp.JID(stanza.attrs.to);
//         redispub.publish(toJid.bare().toString(), stanza.toString());
//     }
// }
// xmpp.C2S.prototype.registerRoute = function(jid, client) {
//     redissub.subscribeTo(jid.bare().toString(), function(channel, stanza, pattern) {
//         client.send(stanza);
//     });
//     return true;
// }
<commit_msg>example cleanup<commit_after>var xmpp = require('../lib/node-xmpp');
var SoftwareVersion = require('../lib/xmpp/c2s_mods/software_version');

/*
 *  TODO
 *  - support for Presence module
 *  - Support for TLS () : https://groups.google.com/group/nodejs/browse_thread/thread/1e8e6501493d63b8#
 *  - Admin tools
 *  - Component interface
 *  - Plugins for 'well-known' services (Roster, PubSub, PEP)
 *  - Logging
 *  - Shapers
 *  - In-band registration
 *  - mods :
 *      - presence
 *      - offline
 *      - announce
 *      - caps
 *      - muc
 *      - roster
 *      - PEP
 */

// Sets up the server.
var c2s = new xmpp.C2S({
    port: 5222,
    domain: 'localhost',
    // tls: {
    //     keyPath: './examples/localhost.pem',
    //     certPath: './examples/localhost.certificate.pem',
    // }
});

// Allows the developer to authenticate users against anything they want.
c2s.on("authenticate", function(jid, password, client) {
    if(password == "password") {
        client.emit("auth-success", jid);
    }
    else {
        client.emit("auth-fail", jid);
    }
});

// That's the way you add mods to a given server.
c2s.supports(SoftwareVersion);
SoftwareVersion.name = "Node XMPP server example";
SoftwareVersion.version = "0.0.0.1";
SoftwareVersion.os = "Mac OS X 10.7 Lion";

// Most imoortant pieces of code : that is where you can configure your XMPP server to support only what you care about/need.
c2s.on("stanza", function(stanza, client) {
    var query, vCard;
    // We should provide a bunch of "plugins" for the functionalities below.

    // No roster support in this server!
    if (stanza.is('iq') && (session = stanza.getChild('query', 'jabber:iq:roster'))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No private support on this server
    else if (stanza.is('iq') && (query = stanza.getChild('query', "jabber:iq:private"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No vCard support on this server.
    else if (stanza.is('iq') && (vCard = stanza.getChild('vCard', "vcard-temp"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No DiscoInfo on this server.
    else if (stanza.is('iq') && (query = stanza.getChild('query', "http://jabber.org/protocol/disco#info"))) {
        stanza.attrs.type = "error";
        stanza.attrs.to = stanza.attrs.from;
        delete stanza.attrs.from;
        client.send(stanza);
    }
    // No Version support on this server.
    else {

    }
})

// You can also decide to rewrite many things, like for example the way you route stanzas.
// This will allow for clustering for your node-xmpp server, using redis's PubSub feature.
// To run this example in its full "power", just run node exmaple c2s.js from 2 different machines, as long as they share the redis server, they should be able to communicate!
// var sys = require("sys");
// var redis = require("redis-node");
// var redispub = redis.createClient();
// var redissub = redis.createClient();
//
// xmpp.C2S.prototype.route = function(stanza) {
//     var self = this;
//     if(stanza.attrs && stanza.attrs.to) {
//         var toJid = new xmpp.JID(stanza.attrs.to);
//         redispub.publish(toJid.bare().toString(), stanza.toString());
//     }
// }
// xmpp.C2S.prototype.registerRoute = function(jid, client) {
//     redissub.subscribeTo(jid.bare().toString(), function(channel, stanza, pattern) {
//         client.send(stanza);
//     });
//     return true;
// }
<|endoftext|>


<commit_before>var hash = require('../');

var str = 'abcdefg.....';

console.log(hash.md5(str));
console.log(hash.sha1(str));
console.log(hash.sha256(str));
console.log(hash.sha512(str));

console.log(hash.md5(str, 'base64'));
console.log(hash.sha1(str, 'base64'));
console.log(hash.sha256(str, 'base64'));
console.log(hash.sha512(str, 'base64'));
<commit_msg>update example.<commit_after>var hash = require('../');

var str = 'abcdefg.....';

console.log(hash.md5(str));
console.log(hash.sha1(str));
console.log(hash.sha256(str));
console.log(hash.sha512(str));

console.log(hash.md5(str, 'base64'));
console.log(hash.sha1(str, 'base64'));
console.log(hash.sha256(str, 'base64'));
console.log(hash.sha512(str, 'base64'));

var sh = hash.sortable.encode([10, 10, -10]);
console.log(sh); // => skfsmq4xj7d9
console.log(hash.sortable.decode(sh, 3)); // => [ 9.999942779541016, 9.999942779541016, -9.999942779541016 ]

var biggerHash  = hash.sortable.encode([10, 10, -10], 35);
console.log(biggerHash); // => skfsmq4xj7d9v2fsmq4xj7d9v2fsmq4xj3h
console.log(hash.sortable.decode(biggerHash, 3)); // => [ 10, 10, -10 ]

var corrd = { lng: 116.389550, lat: 39.928167 },
    gh = hash.geo.encode(corrd, 8);
console.log(gh); // => wx4g0s8q
console.log(hash.geo.decode(gh)); // => { lng: 116.38967514038086, lat: 39.928178787231445 }

<|endoftext|>


<commit_before>
import Raw from './raw'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import typeOf from 'type-of'
import { Record } from 'immutable'

/**
 * String.
 *
 * @type {String}
 */

const String = new Record({
  kind: 'string',
  text: ''
})

/**
 * A rule to (de)serialize text nodes. This is automatically added to the HTML
 * serializer so that users don't have to worry about text-level serialization.
 *
 * @type {Object}
 */

const TEXT_RULE = {

  deserialize(el) {
    if (el.tagName == 'br') {
      return {
        kind: 'text',
        text: '\n'
      }
    }

    if (el.tagName == 'span' || el.nodeName == '#text') {
      if (el.value && el.value.match(//)) return

      return {
        kind: 'text',
        text: el.value || el.nodeValue
      }
    }
  },

  serialize(obj, children) {
    if (obj.kind == 'string') {
      return children
        .split('\n')
        .reduce((array, text, i) => {
          if (i != 0) array.push(
)
          array.push(text)
          return array
        }, [])
    }
  }

}

/**
 * HTML serializer.
 *
 * @type {Html}
 */

class Html {

  /**
   * Create a new serializer with `rules`.
   *
   * @param {Object} options
   *   @property {Array} rules
   *   @property {String|Object} defaultBlockType
   *   @property {Function} parseHtml
   */

  constructor(options = {}) {
    this.rules = [
      ...(options.rules || []),
      TEXT_RULE
    ]

    this.defaultBlockType = options.defaultBlockType || 'paragraph'

    // Set DOM parser function or fallback to native DOMParser if present.
    if (typeof options.parseHtml === 'function') {
      this.parseHtml = options.parseHtml
    } else if (typeof DOMParser !== 'undefined') {
      this.parseHtml = (html) => {
        const parsed = new DOMParser().parseFromString(html, 'text/html')
        // Unwrap from  and
        return parsed.childNodes[0].childNodes[1]
      }
    } else {
      throw new Error(
        'Native DOMParser is not present in this environment; you must supply a parse function via options.parseHtml'
      )
    }
  }

  /**
   * Deserialize pasted HTML.
   *
   * @param {String} html
   * @param {Object} options
   *   @property {Boolean} toRaw
   * @return {State}
   */

  deserialize = (html, options = {}) => {
    const children = Array.from(this.parseHtml(html).childNodes)
    let nodes = this.deserializeElements(children)

    const { defaultBlockType } = this
    const defaults = typeof defaultBlockType == 'string'
      ? { type: defaultBlockType }
      : defaultBlockType

    // HACK: ensure for now that all top-level inline are wrapped into a block.
    nodes = nodes.reduce((memo, node, i, original) => {
      if (node.kind == 'block') {
        memo.push(node)
        return memo
      }

      if (i > 0 && original[i - 1].kind != 'block') {
        const block = memo[memo.length - 1]
        block.nodes.push(node)
        return memo
      }

      const block = {
        kind: 'block',
        nodes: [node],
        ...defaults
      }

      memo.push(block)
      return memo
    }, [])

    if (nodes.length === 0) {
      nodes = [{
        kind: 'block',
        nodes: [],
        ...defaults
      }]
    }

    const raw = {
      kind: 'state',
      document: {
        kind: 'document',
        nodes,
      }
    }

    if (options.toRaw) {
      return raw
    }

    const state = Raw.deserialize(raw, { terse: true })
    return state
  }

  /**
   * Deserialize an array of DOM elements.
   *
   * @param {Array} elements
   * @return {Array}
   */

  deserializeElements = (elements = []) => {
    let nodes = []

    elements.filter(this.cruftNewline).forEach((element) => {
      const node = this.deserializeElement(element)
      switch (typeOf(node)) {
        case 'array':
          nodes = nodes.concat(node)
          break
        case 'object':
          nodes.push(node)
          break
      }
    })

    return nodes
  }

  /**
   * Deserialize a DOM element.
   *
   * @param {Object} element
   * @return {Any}
   */

  deserializeElement = (element) => {
    let node

    if (!element.tagName) {
      element.tagName = ''
    }

    const next = (elements) => {
      if (typeof NodeList !== 'undefined' && elements instanceof NodeList) {
        elements = Array.from(elements)
      }
      switch (typeOf(elements)) {
        case 'array':
          return this.deserializeElements(elements)
        case 'object':
          return this.deserializeElement(elements)
        case 'null':
        case 'undefined':
          return
        default:
          throw new Error(`The \`next\` argument was called with invalid children: "${elements}".`)
      }
    }

    for (const rule of this.rules) {
      if (!rule.deserialize) continue
      const ret = rule.deserialize(element, next)
      const type = typeOf(ret)

      if (type != 'array' && type != 'object' && type != 'null' && type != 'undefined') {
        throw new Error(`A rule returned an invalid deserialized representation: "${node}".`)
      }

      if (ret === undefined) continue
      if (ret === null) return null

      node = ret.kind == 'mark' ? this.deserializeMark(ret) : ret
      break
    }

    return node || next(element.childNodes)
  }

  /**
   * Deserialize a `mark` object.
   *
   * @param {Object} mark
   * @return {Array}
   */

  deserializeMark = (mark) => {
    const { type, value } = mark

    const applyMark = (node) => {
      if (node.kind == 'mark') {
        return this.deserializeMark(node)
      }

      else if (node.kind == 'text') {
        if (!node.ranges) node.ranges = [{ text: node.text }]
        node.ranges = node.ranges.map((range) => {
          range.marks = range.marks || []
          range.marks.push({ type, value })
          return range
        })
      }

      else {
        node.nodes = node.nodes.map(applyMark)
      }

      return node
    }

    return mark.nodes.reduce((nodes, node) => {
      const ret = applyMark(node)
      if (Array.isArray(ret)) return nodes.concat(ret)
      nodes.push(ret)
      return nodes
    }, [])
  }

  /**
   * Serialize a `state` object into an HTML string.
   *
   * @param {State} state
   * @param {Object} options
   *   @property {Boolean} render
   * @return {String|Array}
   */

  serialize = (state, options = {}) => {
    const { document } = state
    const elements = document.nodes.map(this.serializeNode)
    if (options.render === false) return elements

    const html = ReactDOMServer.renderToStaticMarkup({elements})
    const inner = html.slice(6, -7)
    return inner
  }

  /**
   * Serialize a `node`.
   *
   * @param {Node} node
   * @return {String}
   */

  serializeNode = (node) => {
    if (node.kind == 'text') {
      const ranges = node.getRanges()
      return ranges.map(this.serializeRange)
    }

    const children = node.nodes.map(this.serializeNode)

    for (const rule of this.rules) {
      if (!rule.serialize) continue
      const ret = rule.serialize(node, children)
      if (ret) return addKey(ret)
    }

    throw new Error(`No serializer defined for node of type "${node.type}".`)
  }

  /**
   * Serialize a `range`.
   *
   * @param {Range} range
   * @return {String}
   */

  serializeRange = (range) => {
    const string = new String({ text: range.text })
    const text = this.serializeString(string)

    return range.marks.reduce((children, mark) => {
      for (const rule of this.rules) {
        if (!rule.serialize) continue
        const ret = rule.serialize(mark, children)
        if (ret) return addKey(ret)
      }

      throw new Error(`No serializer defined for mark of type "${mark.type}".`)
    }, text)
  }

  /**
   * Serialize a `string`.
   *
   * @param {String} string
   * @return {String}
   */

  serializeString = (string) => {
    for (const rule of this.rules) {
      if (!rule.serialize) continue
      const ret = rule.serialize(string, string.text)
      if (ret) return ret
    }
  }

  /**
   * Filter out cruft newline nodes inserted by the DOM parser.
   *
   * @param {Object} element
   * @return {Boolean}
   */

  cruftNewline = (element) => {
    return !(element.nodeName == '#text' && element.value == '\n')
  }

}

/**
 * Add a unique key to a React `element`.
 *
 * @param {Element} element
 * @return {Element}
 */

let key = 0

function addKey(element) {
  return React.cloneElement(element, { key: key++ })
}

/**
 * Export.
 *
 * @type {Html}
 */

export default Html
<commit_msg>Remove unneeded check. (#961)<commit_after>
import Raw from './raw'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import typeOf from 'type-of'
import { Record } from 'immutable'

/**
 * String.
 *
 * @type {String}
 */

const String = new Record({
  kind: 'string',
  text: ''
})

/**
 * A rule to (de)serialize text nodes. This is automatically added to the HTML
 * serializer so that users don't have to worry about text-level serialization.
 *
 * @type {Object}
 */

const TEXT_RULE = {

  deserialize(el) {
    if (el.tagName == 'br') {
      return {
        kind: 'text',
        text: '\n'
      }
    }

    if (el.nodeName == '#text') {
      if (el.value && el.value.match(//)) return

      return {
        kind: 'text',
        text: el.value || el.nodeValue
      }
    }
  },

  serialize(obj, children) {
    if (obj.kind == 'string') {
      return children
        .split('\n')
        .reduce((array, text, i) => {
          if (i != 0) array.push(
)
          array.push(text)
          return array
        }, [])
    }
  }

}

/**
 * HTML serializer.
 *
 * @type {Html}
 */

class Html {

  /**
   * Create a new serializer with `rules`.
   *
   * @param {Object} options
   *   @property {Array} rules
   *   @property {String|Object} defaultBlockType
   *   @property {Function} parseHtml
   */

  constructor(options = {}) {
    this.rules = [
      ...(options.rules || []),
      TEXT_RULE
    ]

    this.defaultBlockType = options.defaultBlockType || 'paragraph'

    // Set DOM parser function or fallback to native DOMParser if present.
    if (typeof options.parseHtml === 'function') {
      this.parseHtml = options.parseHtml
    } else if (typeof DOMParser !== 'undefined') {
      this.parseHtml = (html) => {
        const parsed = new DOMParser().parseFromString(html, 'text/html')
        // Unwrap from  and
        return parsed.childNodes[0].childNodes[1]
      }
    } else {
      throw new Error(
        'Native DOMParser is not present in this environment; you must supply a parse function via options.parseHtml'
      )
    }
  }

  /**
   * Deserialize pasted HTML.
   *
   * @param {String} html
   * @param {Object} options
   *   @property {Boolean} toRaw
   * @return {State}
   */

  deserialize = (html, options = {}) => {
    const children = Array.from(this.parseHtml(html).childNodes)
    let nodes = this.deserializeElements(children)

    const { defaultBlockType } = this
    const defaults = typeof defaultBlockType == 'string'
      ? { type: defaultBlockType }
      : defaultBlockType

    // HACK: ensure for now that all top-level inline are wrapped into a block.
    nodes = nodes.reduce((memo, node, i, original) => {
      if (node.kind == 'block') {
        memo.push(node)
        return memo
      }

      if (i > 0 && original[i - 1].kind != 'block') {
        const block = memo[memo.length - 1]
        block.nodes.push(node)
        return memo
      }

      const block = {
        kind: 'block',
        nodes: [node],
        ...defaults
      }

      memo.push(block)
      return memo
    }, [])

    if (nodes.length === 0) {
      nodes = [{
        kind: 'block',
        nodes: [],
        ...defaults
      }]
    }

    const raw = {
      kind: 'state',
      document: {
        kind: 'document',
        nodes,
      }
    }

    if (options.toRaw) {
      return raw
    }

    const state = Raw.deserialize(raw, { terse: true })
    return state
  }

  /**
   * Deserialize an array of DOM elements.
   *
   * @param {Array} elements
   * @return {Array}
   */

  deserializeElements = (elements = []) => {
    let nodes = []

    elements.filter(this.cruftNewline).forEach((element) => {
      const node = this.deserializeElement(element)
      switch (typeOf(node)) {
        case 'array':
          nodes = nodes.concat(node)
          break
        case 'object':
          nodes.push(node)
          break
      }
    })

    return nodes
  }

  /**
   * Deserialize a DOM element.
   *
   * @param {Object} element
   * @return {Any}
   */

  deserializeElement = (element) => {
    let node

    if (!element.tagName) {
      element.tagName = ''
    }

    const next = (elements) => {
      if (typeof NodeList !== 'undefined' && elements instanceof NodeList) {
        elements = Array.from(elements)
      }
      switch (typeOf(elements)) {
        case 'array':
          return this.deserializeElements(elements)
        case 'object':
          return this.deserializeElement(elements)
        case 'null':
        case 'undefined':
          return
        default:
          throw new Error(`The \`next\` argument was called with invalid children: "${elements}".`)
      }
    }

    for (const rule of this.rules) {
      if (!rule.deserialize) continue
      const ret = rule.deserialize(element, next)
      const type = typeOf(ret)

      if (type != 'array' && type != 'object' && type != 'null' && type != 'undefined') {
        throw new Error(`A rule returned an invalid deserialized representation: "${node}".`)
      }

      if (ret === undefined) continue
      if (ret === null) return null

      node = ret.kind == 'mark' ? this.deserializeMark(ret) : ret
      break
    }

    return node || next(element.childNodes)
  }

  /**
   * Deserialize a `mark` object.
   *
   * @param {Object} mark
   * @return {Array}
   */

  deserializeMark = (mark) => {
    const { type, value } = mark

    const applyMark = (node) => {
      if (node.kind == 'mark') {
        return this.deserializeMark(node)
      }

      else if (node.kind == 'text') {
        if (!node.ranges) node.ranges = [{ text: node.text }]
        node.ranges = node.ranges.map((range) => {
          range.marks = range.marks || []
          range.marks.push({ type, value })
          return range
        })
      }

      else {
        node.nodes = node.nodes.map(applyMark)
      }

      return node
    }

    return mark.nodes.reduce((nodes, node) => {
      const ret = applyMark(node)
      if (Array.isArray(ret)) return nodes.concat(ret)
      nodes.push(ret)
      return nodes
    }, [])
  }

  /**
   * Serialize a `state` object into an HTML string.
   *
   * @param {State} state
   * @param {Object} options
   *   @property {Boolean} render
   * @return {String|Array}
   */

  serialize = (state, options = {}) => {
    const { document } = state
    const elements = document.nodes.map(this.serializeNode)
    if (options.render === false) return elements

    const html = ReactDOMServer.renderToStaticMarkup({elements})
    const inner = html.slice(6, -7)
    return inner
  }

  /**
   * Serialize a `node`.
   *
   * @param {Node} node
   * @return {String}
   */

  serializeNode = (node) => {
    if (node.kind == 'text') {
      const ranges = node.getRanges()
      return ranges.map(this.serializeRange)
    }

    const children = node.nodes.map(this.serializeNode)

    for (const rule of this.rules) {
      if (!rule.serialize) continue
      const ret = rule.serialize(node, children)
      if (ret) return addKey(ret)
    }

    throw new Error(`No serializer defined for node of type "${node.type}".`)
  }

  /**
   * Serialize a `range`.
   *
   * @param {Range} range
   * @return {String}
   */

  serializeRange = (range) => {
    const string = new String({ text: range.text })
    const text = this.serializeString(string)

    return range.marks.reduce((children, mark) => {
      for (const rule of this.rules) {
        if (!rule.serialize) continue
        const ret = rule.serialize(mark, children)
        if (ret) return addKey(ret)
      }

      throw new Error(`No serializer defined for mark of type "${mark.type}".`)
    }, text)
  }

  /**
   * Serialize a `string`.
   *
   * @param {String} string
   * @return {String}
   */

  serializeString = (string) => {
    for (const rule of this.rules) {
      if (!rule.serialize) continue
      const ret = rule.serialize(string, string.text)
      if (ret) return ret
    }
  }

  /**
   * Filter out cruft newline nodes inserted by the DOM parser.
   *
   * @param {Object} element
   * @return {Boolean}
   */

  cruftNewline = (element) => {
    return !(element.nodeName == '#text' && element.value == '\n')
  }

}

/**
 * Add a unique key to a React `element`.
 *
 * @param {Element} element
 * @return {Element}
 */

let key = 0

function addKey(element) {
  return React.cloneElement(element, { key: key++ })
}

/**
 * Export.
 *
 * @type {Html}
 */

export default Html
<|endoftext|>


<commit_before>/*
 Copyright 2007-2010 WebDriver committers
 Copyright 2007-2010 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 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.
 */

goog.require('fxdriver.moz');

/**
 * An active FirefoxDriver session.
 * @constructor
 */
function wdSession() {
  /**
   * A wrapped self-reference for XPConnect.
   * @type {wdSession}
   */
  this.wrappedJSObject = this;
}

/**
 * This component's ID.
 * @type {nsIJSID}
 */
wdSession.CLASS_ID = Components.ID('{e193dc71-5b1d-4fea-b4c2-ec71f4557f0f}');

/**
 * This component's class name.
 * @type {string}
 */
wdSession.CLASS_NAME = 'wdSession';

/**
 * This component's contract ID.
 * @type {string}
 */
wdSession.CONTRACT_ID = '@googlecode.com/webdriver/wdsession;1';

/**
 * This session's ID.
 * @type {?string}
 * @private
 */
wdSession.prototype.id_ = null;

/**
 * The main chrome window that this is session is currently focused on. All
 * command's for this session will be directed at the current window, which
 * may be inside a [I]FRAME, within this window.
 * @type {?ChromeWindow}
 * @private
 */
wdSession.prototype.chromeWindow_ = null;

/**
 * The content window this session is currently focused on.
 * @type {?nsIDOMWindow}
 * @private
 */
wdSession.prototype.window_ = null;

/**
 * The current user input speed setting for this session.
 * @type {number}
 * @private
 */
wdSession.prototype.inputSpeed_ = 1;

/**
 * The amount of time, in milliseconds, this session should wait for an element
 * to be located when performing a search.
 * When searching for a single element, the driver will wait up to this amount
 * of time for the element to be located before returning an error.
 * When searching for multiple elements, the driver will wait up to this amount
 * of time for at least one element to be located before returning an empty
 * list.
 * @type {number}
 * @private
 */
wdSession.prototype.implicitWait_ = 0;

/**
 * Current position of the mouse cursor, in X,Y coordinates.
 */
wdSession.prototype.mousePosition_ = {
  x: 0,
  y: 0,
  // When the mouse button is pressed (pressed == true), use these
  // coordinates rather than x,y
  viewPortXOffset: 0,
  viewPortYOffset: 0,
  initialized: false,
  pressed: false
};

/**
 * The amount of time, in milliseconds, this session should wait for
 * asynchronous scripts to finish executing. If set to 0, then the timeout will
 * not fire until the next event loop after the script is executed. This will
 * give scripts that employ a 0-based setTimeout to finish.
 * @type {number}
 * @private
 */
wdSession.prototype.scriptTimeout_ = 0;

/** @see nsISupports.QueryInterface */
wdSession.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsISupports)) {
    return this;
  }
  throw Components.results.NS_ERROR_NO_INTERFACE;
};

/** @return {?string} This session's ID. */
wdSession.prototype.getId = function() {
  return this.id_;
};

/**
 * Sets this session's ID.
 * @param {string} id The session ID.
 */
wdSession.prototype.setId = function(id) {
  this.id_ = id;
};

/**
 * @return {browser|tabbrowser} The browser object for this session's current
 *     window.
 */
wdSession.prototype.getBrowser = function() {
  return this.chromeWindow_.getBrowser();
};

/** @return {?ChromeWindow} The chrome window for this session. */
wdSession.prototype.getChromeWindow = function() {
  return this.chromeWindow_;
};

/** @return {?nsIDOMWindow} This session's current window. */
wdSession.prototype.getWindow = function() {
  var win;
  if (this.window_) {
    win = this.window_.get();
  }

  if (!win || !win.document) {
    // Uh-oh, we lost our DOM! Try to recover by changing focus to the
    // main content window.
    win = this.chromeWindow_.getBrowser().contentWindow;
    this.setWindow(win);
  }

  return win;
};

/** @return {nsIDOMDocument} This session's current document. */
wdSession.prototype.getDocument = function() {
  return this.getWindow().document;
};

/**
 * Set the chrome window for this session; will also set the current window to
 * the main content window inside the chrome window.
 * @param {ChromeWindow} win The new chrome window.
 */
wdSession.prototype.setChromeWindow = function(win) {
  this.chromeWindow_ = win;
  this.setWindow(win.getBrowser().contentWindow);
};

/**
 * Set this session's current window.
 * @param {nsIDOMWindow} win The new window.
 */
wdSession.prototype.setWindow = function(win) {
  var unwrapped = fxdriver.moz.unwrapFor4(win);
  this.window_ = Components.utils.getWeakReference(unwrapped);

  // Our other means of testing for window unloads rely on window.closed, which
  // can sometimes not be set for frames/iframes (because in most javascript
  // contexts, it's not possible to access window after a window has closed
  // except for top-level windows (e.g. popups).
  // Fall back to an unload event if we need to.

  var self = this;
  var handler = function(e) {
    if (win == win.top) {
      self.window_ = null;
    }
  }

  // Listen in capture mode to force us to be called (can't stop event
  // propagation in capture mode)
  // unload can only be called when the window is actually closing;
  // window closing can only be cancelled in the beforeload event phase.
  unwrapped.addEventListener('unload',
                             handler,
                             /*useCapture=*/true);
};

/**
 * @return {number} The user input speed for this session.
 */
wdSession.prototype.getInputSpeed = function() {
  return this.inputSpeed_;
};

/**
 * Sets the user input speed for this session.
 * @param {number} speed The new input speed.
 */
wdSession.prototype.setInputSpeed = function(speed) {
  this.inputSpeed_ = speed;
};

/**
 * @return {number} The amount of time, in milliseconds, this session should
 *     wait for an element to be located on the page.
 */
wdSession.prototype.getImplicitWait = function() {
  return this.implicitWait_;
};

/**
 * Sets the amount of time, in milliseconds, this session should wait for an
 * element to be located on the page.
 * @param {number} wait The amount of time to wait.
 */
wdSession.prototype.setImplicitWait = function(wait) {
  this.implicitWait_ = Math.max(wait, 0);
};

/**
 * @return {number} the amount of time, in milliseconds, that asynchronous
 *     scripts are allowed to run before timing out.
 */
wdSession.prototype.getScriptTimeout = function() {
  return this.scriptTimeout_;
};

/**
 * Sets the amount of time, in milliseconds, that asynchronous scripts are
 *     allowed to run before timing out.
 * @param {number} timeout The new timeout.
 */
wdSession.prototype.setScriptTimeout = function(timeout) {
  this.scriptTimeout_ = Math.max(timeout, 0);
};

/**
 * @return {object} The current position of the mouse cursor.
 */
wdSession.prototype.getMousePosition = function() {
  return this.mousePosition_;
};

/**
 * Sets the current mouse position.
 * @param {number} x coordinates.
 * @param {number} y coordinates.
 */
wdSession.prototype.setMousePosition = function(x, y) {
  this.mousePosition_.x = x;
  this.mousePosition_.y = y;
  this.mousePosition_.initialized = true;
};

wdSession.prototype.isMousePressed = function() {
  return this.mousePosition_.pressed;
};

wdSession.prototype.setMousePressed = function(isPressed) {
  this.mousePosition_.pressed = isPressed;
};

wdSession.prototype.setMouseViewportOffset = function(x, y) {
  this.mousePosition_.viewPortXOffset = x;
  this.mousePosition_.viewPortYOffset = y;
}

///////////////////////////////////////////////////////////////////
//
// nsIFactory functions
//
///////////////////////////////////////////////////////////////////

/** @constructor */
function wdSessionFactory() {
}

/** @see nsIFactory.createInstance */
wdSessionFactory.prototype.createInstance = function(aOuter, aIID) {
  if (aOuter != null) {
    throw Components.results.NS_ERROR_NO_AGGREGATION;
  }
  return new wdSession().QueryInterface(aIID);
};

///////////////////////////////////////////////////////////////////
//
// nsIModule functions
//
///////////////////////////////////////////////////////////////////

/** @constructor */
function wdSessionModule() {
}

/**
 * Whether this module has already been registered.
 * @type {!boolean}
 * @private
 */
wdSessionModule.prototype.hasRegistered_ = false;

/** @see nsIModule.registerSelf */
wdSessionModule.prototype.registerSelf = function(aCompMgr, aFileSpec, aLocation, aType) {
  if (this.hasRegistered_) {
    throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  }
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
      registerFactoryLocation(
          wdSession.CLASS_ID,
          wdSession.CLASS_NAME,
          wdSession.CONTRACT_ID,
          aFileSpec, aLocation, aType);
  this.hasRegistered_ = true;
};

/** @see nsIModule.unregisterSelf */
wdSessionModule.prototype.unregisterSelf = function(aCompMgr, aLocation) {
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
      unregisterFactoryLocation(wdSession.CLASS_ID, aLocation);
};

/** @see nsIModule.getClassObject */
wdSessionModule.prototype.getClassObject = function(aCompMgr, aCID, aIID) {
  if (!aIID.equals(Components.interfaces.nsIFactory)) {
    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  } else if (!aCID.equals(wdSession.CLASS_ID)) {
    throw Components.results.NS_ERROR_NO_INTERFACE;
  }
  return new wdSessionFactory();
};

/** @see nsIModule.canUnload */
wdSessionModule.prototype.canUnload = function() {
  return true;
};

/**
 * Module initialization.
 */
function NSGetModule() {
  return new wdSessionModule();
}

wdSession.prototype.classID = wdSession.CLASS_ID
fxdriver.moz.load("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  /** @const */ var NSGetFactory = XPCOMUtils.generateNSGetFactory([wdSession]);
}

<commit_msg>JariBakken: Remove seemingly redundant unwrapping added in r15226.<commit_after>/*
 Copyright 2007-2010 WebDriver committers
 Copyright 2007-2010 Google Inc.
 Portions copyright 2011 Software Freedom Conservancy

 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.
 */

goog.require('fxdriver.moz');

/**
 * An active FirefoxDriver session.
 * @constructor
 */
function wdSession() {
  /**
   * A wrapped self-reference for XPConnect.
   * @type {wdSession}
   */
  this.wrappedJSObject = this;
}

/**
 * This component's ID.
 * @type {nsIJSID}
 */
wdSession.CLASS_ID = Components.ID('{e193dc71-5b1d-4fea-b4c2-ec71f4557f0f}');

/**
 * This component's class name.
 * @type {string}
 */
wdSession.CLASS_NAME = 'wdSession';

/**
 * This component's contract ID.
 * @type {string}
 */
wdSession.CONTRACT_ID = '@googlecode.com/webdriver/wdsession;1';

/**
 * This session's ID.
 * @type {?string}
 * @private
 */
wdSession.prototype.id_ = null;

/**
 * The main chrome window that this is session is currently focused on. All
 * command's for this session will be directed at the current window, which
 * may be inside a [I]FRAME, within this window.
 * @type {?ChromeWindow}
 * @private
 */
wdSession.prototype.chromeWindow_ = null;

/**
 * The content window this session is currently focused on.
 * @type {?nsIDOMWindow}
 * @private
 */
wdSession.prototype.window_ = null;

/**
 * The current user input speed setting for this session.
 * @type {number}
 * @private
 */
wdSession.prototype.inputSpeed_ = 1;

/**
 * The amount of time, in milliseconds, this session should wait for an element
 * to be located when performing a search.
 * When searching for a single element, the driver will wait up to this amount
 * of time for the element to be located before returning an error.
 * When searching for multiple elements, the driver will wait up to this amount
 * of time for at least one element to be located before returning an empty
 * list.
 * @type {number}
 * @private
 */
wdSession.prototype.implicitWait_ = 0;

/**
 * Current position of the mouse cursor, in X,Y coordinates.
 */
wdSession.prototype.mousePosition_ = {
  x: 0,
  y: 0,
  // When the mouse button is pressed (pressed == true), use these
  // coordinates rather than x,y
  viewPortXOffset: 0,
  viewPortYOffset: 0,
  initialized: false,
  pressed: false
};

/**
 * The amount of time, in milliseconds, this session should wait for
 * asynchronous scripts to finish executing. If set to 0, then the timeout will
 * not fire until the next event loop after the script is executed. This will
 * give scripts that employ a 0-based setTimeout to finish.
 * @type {number}
 * @private
 */
wdSession.prototype.scriptTimeout_ = 0;

/** @see nsISupports.QueryInterface */
wdSession.prototype.QueryInterface = function(aIID) {
  if (aIID.equals(Components.interfaces.nsISupports)) {
    return this;
  }
  throw Components.results.NS_ERROR_NO_INTERFACE;
};

/** @return {?string} This session's ID. */
wdSession.prototype.getId = function() {
  return this.id_;
};

/**
 * Sets this session's ID.
 * @param {string} id The session ID.
 */
wdSession.prototype.setId = function(id) {
  this.id_ = id;
};

/**
 * @return {browser|tabbrowser} The browser object for this session's current
 *     window.
 */
wdSession.prototype.getBrowser = function() {
  return this.chromeWindow_.getBrowser();
};

/** @return {?ChromeWindow} The chrome window for this session. */
wdSession.prototype.getChromeWindow = function() {
  return this.chromeWindow_;
};

/** @return {?nsIDOMWindow} This session's current window. */
wdSession.prototype.getWindow = function() {
  var win;
  if (this.window_) {
    win = this.window_.get();
  }

  if (!win || !win.document) {
    // Uh-oh, we lost our DOM! Try to recover by changing focus to the
    // main content window.
    win = this.chromeWindow_.getBrowser().contentWindow;
    this.setWindow(win);
  }

  return win;
};

/** @return {nsIDOMDocument} This session's current document. */
wdSession.prototype.getDocument = function() {
  return this.getWindow().document;
};

/**
 * Set the chrome window for this session; will also set the current window to
 * the main content window inside the chrome window.
 * @param {ChromeWindow} win The new chrome window.
 */
wdSession.prototype.setChromeWindow = function(win) {
  this.chromeWindow_ = win;
  this.setWindow(win.getBrowser().contentWindow);
};

/**
 * Set this session's current window.
 * @param {nsIDOMWindow} win The new window.
 */
wdSession.prototype.setWindow = function(win) {
  this.window_ = Components.utils.getWeakReference(win);

  // Our other means of testing for window unloads rely on window.closed, which
  // can sometimes not be set for frames/iframes (because in most javascript
  // contexts, it's not possible to access window after a window has closed
  // except for top-level windows (e.g. popups).
  // Fall back to an unload event if we need to.

  var self = this;
  var handler = function(e) {
    if (win == win.top) {
      self.window_ = null;
    }
  }

  // Listen in capture mode to force us to be called (can't stop event
  // propagation in capture mode)
  // unload can only be called when the window is actually closing;
  // window closing can only be cancelled in the beforeload event phase.
  win.addEventListener('unload',
                        handler,
                        /*useCapture=*/true);
};

/**
 * @return {number} The user input speed for this session.
 */
wdSession.prototype.getInputSpeed = function() {
  return this.inputSpeed_;
};

/**
 * Sets the user input speed for this session.
 * @param {number} speed The new input speed.
 */
wdSession.prototype.setInputSpeed = function(speed) {
  this.inputSpeed_ = speed;
};

/**
 * @return {number} The amount of time, in milliseconds, this session should
 *     wait for an element to be located on the page.
 */
wdSession.prototype.getImplicitWait = function() {
  return this.implicitWait_;
};

/**
 * Sets the amount of time, in milliseconds, this session should wait for an
 * element to be located on the page.
 * @param {number} wait The amount of time to wait.
 */
wdSession.prototype.setImplicitWait = function(wait) {
  this.implicitWait_ = Math.max(wait, 0);
};

/**
 * @return {number} the amount of time, in milliseconds, that asynchronous
 *     scripts are allowed to run before timing out.
 */
wdSession.prototype.getScriptTimeout = function() {
  return this.scriptTimeout_;
};

/**
 * Sets the amount of time, in milliseconds, that asynchronous scripts are
 *     allowed to run before timing out.
 * @param {number} timeout The new timeout.
 */
wdSession.prototype.setScriptTimeout = function(timeout) {
  this.scriptTimeout_ = Math.max(timeout, 0);
};

/**
 * @return {object} The current position of the mouse cursor.
 */
wdSession.prototype.getMousePosition = function() {
  return this.mousePosition_;
};

/**
 * Sets the current mouse position.
 * @param {number} x coordinates.
 * @param {number} y coordinates.
 */
wdSession.prototype.setMousePosition = function(x, y) {
  this.mousePosition_.x = x;
  this.mousePosition_.y = y;
  this.mousePosition_.initialized = true;
};

wdSession.prototype.isMousePressed = function() {
  return this.mousePosition_.pressed;
};

wdSession.prototype.setMousePressed = function(isPressed) {
  this.mousePosition_.pressed = isPressed;
};

wdSession.prototype.setMouseViewportOffset = function(x, y) {
  this.mousePosition_.viewPortXOffset = x;
  this.mousePosition_.viewPortYOffset = y;
}

///////////////////////////////////////////////////////////////////
//
// nsIFactory functions
//
///////////////////////////////////////////////////////////////////

/** @constructor */
function wdSessionFactory() {
}

/** @see nsIFactory.createInstance */
wdSessionFactory.prototype.createInstance = function(aOuter, aIID) {
  if (aOuter != null) {
    throw Components.results.NS_ERROR_NO_AGGREGATION;
  }
  return new wdSession().QueryInterface(aIID);
};

///////////////////////////////////////////////////////////////////
//
// nsIModule functions
//
///////////////////////////////////////////////////////////////////

/** @constructor */
function wdSessionModule() {
}

/**
 * Whether this module has already been registered.
 * @type {!boolean}
 * @private
 */
wdSessionModule.prototype.hasRegistered_ = false;

/** @see nsIModule.registerSelf */
wdSessionModule.prototype.registerSelf = function(aCompMgr, aFileSpec, aLocation, aType) {
  if (this.hasRegistered_) {
    throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  }
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
      registerFactoryLocation(
          wdSession.CLASS_ID,
          wdSession.CLASS_NAME,
          wdSession.CONTRACT_ID,
          aFileSpec, aLocation, aType);
  this.hasRegistered_ = true;
};

/** @see nsIModule.unregisterSelf */
wdSessionModule.prototype.unregisterSelf = function(aCompMgr, aLocation) {
  aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
      unregisterFactoryLocation(wdSession.CLASS_ID, aLocation);
};

/** @see nsIModule.getClassObject */
wdSessionModule.prototype.getClassObject = function(aCompMgr, aCID, aIID) {
  if (!aIID.equals(Components.interfaces.nsIFactory)) {
    throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  } else if (!aCID.equals(wdSession.CLASS_ID)) {
    throw Components.results.NS_ERROR_NO_INTERFACE;
  }
  return new wdSessionFactory();
};

/** @see nsIModule.canUnload */
wdSessionModule.prototype.canUnload = function() {
  return true;
};

/**
 * Module initialization.
 */
function NSGetModule() {
  return new wdSessionModule();
}

wdSession.prototype.classID = wdSession.CLASS_ID
fxdriver.moz.load("resource://gre/modules/XPCOMUtils.jsm");
if (XPCOMUtils.generateNSGetFactory) {
  /** @const */ var NSGetFactory = XPCOMUtils.generateNSGetFactory([wdSession]);
}

<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const AutoIncrement = require('mongoose-sequence')(mongoose);
const OrderState = require('../../common/orderState');

const models = {};

models.ProductPicturesCollection = 'productpictures';

const address = {
  streetAddress: String,
  zip: Number,
  city: String,
  country: String,
};

const AddressSchema = mongoose.Schema(address);

const ProductCategoryTranslationsSchema = {
  name: String,
};

models.ProductCategory = mongoose.model('ProductCategory', {
  parentCategory: mongoose.Schema.Types.Object,
  de: ProductCategoryTranslationsSchema,
  en: ProductCategoryTranslationsSchema,
  fr: ProductCategoryTranslationsSchema,
  it: ProductCategoryTranslationsSchema,
});

models.Tag = mongoose.model('Tag', {
  name: {
    type: String,
    index: true,
    unique: true,
  },
});

const DownloadLinkSchema = {
  text: String,
  href: String,
};

const ProductTranslationsSchema = {
  name: {
    type: String,
    required: true,
  },
  shortDescription: {
    type: String,
    default: '',
  },
  description: {
    type: String,
    default: '',
  },
  specifications: [String],
  delivery: [String],
  downloads: [DownloadLinkSchema],
};

const ProductSchema = mongoose.Schema({
  category: {
    type: mongoose.Schema.Types.ObjectId,
    index: true,
  },
  de: ProductTranslationsSchema,
  en: ProductTranslationsSchema,
  fr: ProductTranslationsSchema,
  it: ProductTranslationsSchema,
  price: Number,
  purchasePrice: Number,
  purchasePackageSize: Number,
  stock: Number,
  minStock: Number,
  supplier: mongoose.Schema.Types.ObjectId,
  supplierProductCode: String,
  producer: mongoose.Schema.Types.ObjectId,
  remarks: String,
  files: [String],
  tags: [String],
});

models.Product = mongoose.model('Product', ProductSchema);

models.Producer = mongoose.model('Producer', {
  name: String,
  vatNumber: String,
  address: AddressSchema,
  contactName: String,
  contactEmail: String,
  contactPhone: String,
  remarks: String,
});

models.Supplier = mongoose.model('Supplier', {
  name: String,
  vatNumber: String,
  customerNumber: String,
  address: AddressSchema,
  bank: String,
  iban: String,
  bic: String,
  bankRemarks: String,
  contactName: String,
  contactEmail: String,
  contactPhone: String,
  remarks: String,
});

const UserAddressSchema = mongoose.Schema(Object.assign(
  {},
  {
    user: {
      type: String,
      index: true,
    },
    title: String,
    firstName: String,
    lastName: String,
  },
  address
));

models.UserAddress = mongoose.model('UserAddress', UserAddressSchema);

const OrderItemSchema = mongoose.Schema({
  amount: Number,
  product: ProductSchema,
});

const InvoiceSchema = mongoose.Schema({
  user: {
    type: String,
    index: true,
  },
  esr: String,
  invoiceNumber: {
    type: Number,
    index: true,
  },
  value: Number,
  address: UserAddressSchema,
});
InvoiceSchema.plugin(AutoIncrement, { inc_field: 'invoiceNumber' });

models.Invoice = mongoose.model('Invoice', InvoiceSchema);

models.Order = mongoose.model('Order', {
  _id: {
    type: String,
    index: true,
  },
  state: {
    type: String,
    enum: Object.keys(OrderState),
    default: OrderState.STARTED,
  },
  user: {
    type: String,
    index: true,
  },
  address: UserAddressSchema,
  date: {
    type: Date,
    default: Date.now(),
    index: true,
  },
  items: [OrderItemSchema],
  itemTotal: {
    type: Number,
  },
  total: {
    type: Number,
  },
  invoice: mongoose.Schema.Types.ObjectId,
});

const HomeTileName = mongoose.Schema({
  name: String,
});

models.HomeTile = mongoose.model('HomeTile', {
  de: HomeTileName,
  fr: HomeTileName,
  it: HomeTileName,
  en: HomeTileName,
  category: mongoose.Schema.Types.ObjectId,
  picture: String,
  order: {
    type: Number,
    default: 0,
    index: true,
  },
});

module.exports = models;
<commit_msg>remove translations because we don't have them yet<commit_after>const mongoose = require('mongoose');
const AutoIncrement = require('mongoose-sequence')(mongoose);
const OrderState = require('../../common/orderState');

const models = {};

models.ProductPicturesCollection = 'productpictures';

const address = {
  streetAddress: String,
  zip: Number,
  city: String,
  country: String,
};

const AddressSchema = mongoose.Schema(address);

const ProductCategoryTranslationsSchema = {
  name: String,
};

models.ProductCategory = mongoose.model('ProductCategory', {
  parentCategory: mongoose.Schema.Types.Object,
  de: ProductCategoryTranslationsSchema,
  en: ProductCategoryTranslationsSchema,
  fr: ProductCategoryTranslationsSchema,
  it: ProductCategoryTranslationsSchema,
});

models.Tag = mongoose.model('Tag', {
  name: {
    type: String,
    index: true,
    unique: true,
  },
});

const DownloadLinkSchema = {
  text: String,
  href: String,
};

const ProductTranslationsSchema = {
  name: {
    type: String,
    required: true,
  },
  shortDescription: {
    type: String,
    default: '',
  },
  description: {
    type: String,
    default: '',
  },
  specifications: [String],
  delivery: [String],
  downloads: [DownloadLinkSchema],
};

const ProductSchema = mongoose.Schema({
  category: {
    type: mongoose.Schema.Types.ObjectId,
    index: true,
  },
  de: ProductTranslationsSchema,
  // TODO: translate all our products
  // en: ProductTranslationsSchema,
  // fr: ProductTranslationsSchema,
  // it: ProductTranslationsSchema,
  price: Number,
  purchasePrice: Number,
  purchasePackageSize: Number,
  stock: Number,
  minStock: Number,
  supplier: mongoose.Schema.Types.ObjectId,
  supplierProductCode: String,
  producer: mongoose.Schema.Types.ObjectId,
  remarks: String,
  files: [String],
  tags: [String],
});

models.Product = mongoose.model('Product', ProductSchema);

models.Producer = mongoose.model('Producer', {
  name: String,
  vatNumber: String,
  address: AddressSchema,
  contactName: String,
  contactEmail: String,
  contactPhone: String,
  remarks: String,
});

models.Supplier = mongoose.model('Supplier', {
  name: String,
  vatNumber: String,
  customerNumber: String,
  address: AddressSchema,
  bank: String,
  iban: String,
  bic: String,
  bankRemarks: String,
  contactName: String,
  contactEmail: String,
  contactPhone: String,
  remarks: String,
});

const UserAddressSchema = mongoose.Schema(Object.assign(
  {},
  {
    user: {
      type: String,
      index: true,
    },
    title: String,
    firstName: String,
    lastName: String,
  },
  address
));

models.UserAddress = mongoose.model('UserAddress', UserAddressSchema);

const OrderItemSchema = mongoose.Schema({
  amount: Number,
  product: ProductSchema,
});

const InvoiceSchema = mongoose.Schema({
  user: {
    type: String,
    index: true,
  },
  esr: String,
  invoiceNumber: {
    type: Number,
    index: true,
  },
  value: Number,
  address: UserAddressSchema,
});
InvoiceSchema.plugin(AutoIncrement, { inc_field: 'invoiceNumber' });

models.Invoice = mongoose.model('Invoice', InvoiceSchema);

models.Order = mongoose.model('Order', {
  _id: {
    type: String,
    index: true,
  },
  state: {
    type: String,
    enum: Object.keys(OrderState),
    default: OrderState.STARTED,
  },
  user: {
    type: String,
    index: true,
  },
  address: UserAddressSchema,
  date: {
    type: Date,
    default: Date.now(),
    index: true,
  },
  items: [OrderItemSchema],
  itemTotal: {
    type: Number,
  },
  total: {
    type: Number,
  },
  invoice: mongoose.Schema.Types.ObjectId,
});

const HomeTileName = mongoose.Schema({
  name: String,
});

models.HomeTile = mongoose.model('HomeTile', {
  de: HomeTileName,
  fr: HomeTileName,
  it: HomeTileName,
  en: HomeTileName,
  category: mongoose.Schema.Types.ObjectId,
  picture: String,
  order: {
    type: Number,
    default: 0,
    index: true,
  },
});

module.exports = models;
<|endoftext|>