<commit_before>/**
 * Data structure for a list of atoms
 */
function AtomList(molecule, atoms) {
  this.init(molecule, atoms);
}

AtomList.prototype = {
  molecule: undefined,
  atoms: undefined,

  cache: undefined,

  init: function(molecule, atoms) {
    this.molecule = molecule;
    this.atoms = new Array();
    atoms.each(function(atom, list) {
      list.atoms.push(new Atom(list, atom.id, atom.element, atom.element_id,
          atom.x, atom.y));
    }, this);
    this.cache = new Cache();
  },

  /*
   * Get the atom with the given id.
   */
  get: function(id) {
    return this.atoms[this.indexOf(id)];
  },

  /*
   * Get the index of the atom with the given id.
   */
  indexOf: function(id) {
    for( var i = 0; i < this.atoms.length; i++) {
      if(this.atoms[i].id == id) {
        return i;
      }
    }
  },

  /*
   * Get the number of atoms in this list.
   */
  count: function() {
    return this.atoms.length;
  },

  /*
   * Apply a function f to each atom in this list.
   */
  each: function(f, that) {
    return this.atoms.each(f, that);
  },

  /*
   * Mapping function for a list of atoms.
   */
  map: function(f, that) {
    return this.atoms.mapF(f, that);
  },

  /*
   * Get the width of this AtomList.
   */
  width: function() {
    if(this.cache.get('position.width')) {
      return this.cache.get('position.width');
    }
    var lt = this.leftTop();
    var rb = this.rightBottom();
    var width = rb.x - lt.x;
    this.cache.set('position.width', width, this.cache.getCache('appearance'));
    return width;
  },

  /*
   * Get the height of this AtomList.
   */
  height: function() {
    if(this.cache.get('position.height')) {
      return this.cache.get('position.height');
    }
    var lt = this.leftTop();
    var rb = this.rightBottom();
    var height = rb.y - lt.y;
    this.cache
        .set('position.height', height, this.cache.getCache('appearance'));
    return height;
  },

  /*
   * Get the coordinates of the left top of this AtomList.
   */
  leftTop: function() {
    if(this.cache.get('position.left_top')) {
      return this.cache.get('position.left_top');
    }
    var lt = {
      x: this.map(function(atom) {
        return atom.x - atom.getRadius();
      }).min(),
      y: this.map(function(atom) {
        return atom.y - atom.getRadius();
      }).min()
    };
    this.cache.set('position.left_top', lt, this.cache.getCache('appearance'));
    return lt;
  },

  /*
   * Get the coordinates of the right bottom of this AtomList.
   */
  rightBottom: function() {
    if(this.cache.get('position.right_bottom')) {
      return this.cache.get('position.right_bottom');
    }
    var rb = {
      x: this.map(function(atom) {
        return atom.x + atom.getRadius();
      }).max(),
      y: this.map(function(atom) {
        return atom.y + atom.getRadius();
      }).max()
    };
    this.cache.set('position.right_bottom', rb, this.cache
        .getCache('appearance'));
    return rb;
  },

  /*
   * Get the size (width, height) of this AtomList.
   */
  size: function() {
    if(this.cache.get('position.size')) {
      return this.cache.get('position.size');
    }
    var s = {
      w: this.width(),
      h: this.height()
    };
    this.cache.set('position.size', s, this.cache.getCache('appearance'));
    return s;
  },

  /*
   * Get the coordinates of the center of this AtomList.
   */
  centerPoint: function() {
    if(this.cache.get('position.center_point')) {
      return this.cache.get('position.center_point');
    }
    var lt = this.leftTop();
    var s = this.size();
    var cp = {
      x: lt.x + s.w / 2,
      y: lt.y + s.h / 2
    };
    this.cache.set('position.center_point', cp, this.cache
        .getCache('appearance'));
    return cp;
  },

  /*
   * Get the atom at position (x, y), if any.
   */
  atomAt: function(x, y) {
    return this.each(function(atom) {
      if(atom.touches(x, y)) {
        return atom;
      }
    });
  },

  /*
   * Set the atom that is hovered to h. If h is undefined, no atom is hovered.
   *
   * Returns true if the hover was changed and a redraw is needed.
   */
  setHover: function(h) {
    if(h && !h.isVisible()) {
      return;
    }

    var changed = false;

    // Unset hover from the currently hovered atom
    this.each(function(a) {
      if(a.status === ATOM_STATUSES.hover && a !== h) {
        a.status = ATOM_STATUSES.normal;
        changed = true;
        return;
      }
    });

    var s = this.molecule.mv.settings;
    var c = this.molecule.mv.canvas;
    if(h) {
      if(h.status === ATOM_STATUSES.normal) {
        h.status = ATOM_STATUSES.hover;

        // Bring to back of list to be drawn last (on top).
        this.atoms.toBack(this.indexOf(h.id));
        changed = true;
      }
      if(h.status === ATOM_STATUSES.hover) {
        c.style.cursor = s.cursor.click;
      } else {
        c.style.cursor = s.cursor.normal;
      }
    } else {
      c.style.cursor = s.cursor.drag;
    }

    return changed;
  },

  /*
   * Set the selected atom to s. If s is undefined, no atom is selected.
   *
   * Returns true if the selection was changed and a redraw is needed.
   */
  setSelected: function(s) {
    var changed = false;
    this.each(function(a) {
      if(a.status === ATOM_STATUSES.selected && a !== s) {
        a.status = ATOM_STATUSES.normal;
        changed = true;
        return;
      }
    });

    var t = this.molecule.mv.settings;
    var c = this.molecule.mv.canvas;
    if(s && s.isVisible() && s.status !== ATOM_STATUSES.selected) {
      s.status = ATOM_STATUSES.selected;

      // Bring to back of list to be drawn last (on top).
      this.atoms.toBack(this.indexOf(s.id));
      c.style.cursor = t.cursor.normal;
      changed = true;
    }

    return changed;
  },

  /*
   * Move all atoms in this list dx in the x direction and dy on the y axis.
   */
  move: function(dx, dy) {
    this.each(function(a) {
      a.move(dx, dy);
    });
  },

  /*
   * Scale the atoms with a factor f.
   */
  scale: function(f) {
    this.each(function(a) {
      var dx = a.x * f - a.x;
      var dy = a.y * f - a.y;
      a.move(dx, dy);
    });

    window.molecule = this.molecule;
    window.fixcount = 0;
    window.fixmax = 1000 - 4.8 * this.count();
    window.requestAnimationFrame(function drawLoop() {
      if(fixcount < fixmax && molecule.deoverlap()) {
        fixcount++;
        molecule.mv.redraw();
        requestAnimationFrame(drawLoop);
      }
    });
  },

  /*
   * Center the list of atoms.
   */
  center: function() {
    var cc = this.molecule.mv.ctx.centerPoint();
    var mc = this.centerPoint();
    var dx = cc.x - mc.x;
    var dy = cc.y - mc.y;
    this.move(dx, dy);
  },

  /*
   * Zoom on the center of the molecule with a factor f.
   */
  zoom: function(f) {
    var c = this.centerPoint();
    this.zoomOn(c.x, c.y, f);
  },

  /*
   * Zoom on a specific point (x, y) with a factor f.
   */
  zoomOn: function(x, y, f) {
    this.move(-x, -y);
    this.scale(f);
    this.move(x, y);
  },

  /*
   * Fit the molecule in a box of size w * h and center it there.
   */
  bestFit: function(w, h) {
    var s = this.molecule.mv.settings;
    var wf = w / this.width();
    var hf = h / this.height();
    var f = wf < hf ? wf : hf;
    this.scale(f);

    var tx = w / 2 - this.width() / 2;
    var ty = h / 2 - this.height() / 2;
    var lt = this.leftTop();
    var dx = tx - lt.x;
    var dy = ty - lt.y;
    this.move(dx, dy);
  },

  clearCache: function(name) {
    this.cache.clear(name);
    this.molecule.clearCache(name);
  },

  /*
   * Draw all atoms in this list.
   */
  draw: function() {
    this.each(function(a) {
      a.draw();
    });
  }
};
<commit_msg>AtomList now has cleaner cache dependencies.<commit_after>/**
 * Data structure for a list of atoms
 */
function AtomList(molecule, atoms) {
  this.init(molecule, atoms);
}

AtomList.prototype = {
  molecule: undefined,
  atoms: undefined,

  cache: undefined,

  init: function(molecule, atoms) {
    this.molecule = molecule;
    this.atoms = new Array();
    atoms.each(function(atom, list) {
      list.atoms.push(new Atom(list, atom.id, atom.element, atom.element_id,
          atom.x, atom.y));
    }, this);
    this.cache = new Cache();
  },

  /*
   * Get the atom with the given id.
   */
  get: function(id) {
    return this.atoms[this.indexOf(id)];
  },

  /*
   * Get the index of the atom with the given id.
   */
  indexOf: function(id) {
    for( var i = 0; i < this.atoms.length; i++) {
      if(this.atoms[i].id == id) {
        return i;
      }
    }
  },

  /*
   * Get the number of atoms in this list.
   */
  count: function() {
    return this.atoms.length;
  },

  /*
   * Apply a function f to each atom in this list.
   */
  each: function(f, that) {
    return this.atoms.each(f, that);
  },

  /*
   * Mapping function for a list of atoms.
   */
  map: function(f, that) {
    return this.atoms.mapF(f, that);
  },

  /*
   * Get the width of this AtomList.
   */
  width: function() {
    if(this.cache.get('position.width')) {
      return this.cache.get('position.width');
    }
    var lt = this.leftTop();
    var rb = this.rightBottom();
    var width = rb.x - lt.x;
    this.cache.set('position.width', width, [
        this.cache.getCache('position.left_top'),
        this.cache.getCache('position.right_bottom')]);
    return width;
  },

  /*
   * Get the height of this AtomList.
   */
  height: function() {
    if(this.cache.get('position.height')) {
      return this.cache.get('position.height');
    }
    var lt = this.leftTop();
    var rb = this.rightBottom();
    var height = rb.y - lt.y;
    this.cache.set('position.height', height, [
        this.cache.getCache('position.left_top'),
        this.cache.getCache('position.right_bottom')]);
    return height;
  },

  /*
   * Get the coordinates of the left top of this AtomList.
   */
  leftTop: function() {
    if(this.cache.get('position.left_top')) {
      return this.cache.get('position.left_top');
    }
    var lt = {
      x: this.map(function(atom) {
        return atom.x - atom.getRadius();
      }).min(),
      y: this.map(function(atom) {
        return atom.y - atom.getRadius();
      }).min()
    };
    this.cache.set('position.left_top', lt, this.cache
        .getCache('appearance.radius'));
    return lt;
  },

  /*
   * Get the coordinates of the right bottom of this AtomList.
   */
  rightBottom: function() {
    if(this.cache.get('position.right_bottom')) {
      return this.cache.get('position.right_bottom');
    }
    var rb = {
      x: this.map(function(atom) {
        return atom.x + atom.getRadius();
      }).max(),
      y: this.map(function(atom) {
        return atom.y + atom.getRadius();
      }).max()
    };
    this.cache.set('position.right_bottom', rb, this.cache
        .getCache('appearance.radius'));
    return rb;
  },

  /*
   * Get the size (width, height) of this AtomList.
   */
  size: function() {
    if(this.cache.get('position.size')) {
      return this.cache.get('position.size');
    }
    var s = {
      w: this.width(),
      h: this.height()
    };
    this.cache.set('position.size', s, [this.cache.getCache('position.width'),
        this.cache.getCache('position.height')]);
    return s;
  },

  /*
   * Get the coordinates of the center of this AtomList.
   */
  centerPoint: function() {
    if(this.cache.get('position.center_point')) {
      return this.cache.get('position.center_point');
    }
    var lt = this.leftTop();
    var s = this.size();
    var cp = {
      x: lt.x + s.w / 2,
      y: lt.y + s.h / 2
    };
    this.cache.set('position.center_point', cp, [
        this.cache.getCache('position.left_top'),
        this.cache.getCache('position.size')]);
    return cp;
  },

  /*
   * Get the atom at position (x, y), if any.
   */
  atomAt: function(x, y) {
    return this.each(function(atom) {
      if(atom.touches(x, y)) {
        return atom;
      }
    });
  },

  /*
   * Set the atom that is hovered to h. If h is undefined, no atom is hovered.
   *
   * Returns true if the hover was changed and a redraw is needed.
   */
  setHover: function(h) {
    if(h && !h.isVisible()) {
      return;
    }

    var changed = false;

    // Unset hover from the currently hovered atom
    this.each(function(a) {
      if(a.status === ATOM_STATUSES.hover && a !== h) {
        a.status = ATOM_STATUSES.normal;
        changed = true;
        return;
      }
    });

    var s = this.molecule.mv.settings;
    var c = this.molecule.mv.canvas;
    if(h) {
      if(h.status === ATOM_STATUSES.normal) {
        h.status = ATOM_STATUSES.hover;

        // Bring to back of list to be drawn last (on top).
        this.atoms.toBack(this.indexOf(h.id));
        changed = true;
      }
      if(h.status === ATOM_STATUSES.hover) {
        c.style.cursor = s.cursor.click;
      } else {
        c.style.cursor = s.cursor.normal;
      }
    } else {
      c.style.cursor = s.cursor.drag;
    }

    return changed;
  },

  /*
   * Set the selected atom to s. If s is undefined, no atom is selected.
   *
   * Returns true if the selection was changed and a redraw is needed.
   */
  setSelected: function(s) {
    var changed = false;
    this.each(function(a) {
      if(a.status === ATOM_STATUSES.selected && a !== s) {
        a.status = ATOM_STATUSES.normal;
        changed = true;
        return;
      }
    });

    var t = this.molecule.mv.settings;
    var c = this.molecule.mv.canvas;
    if(s && s.isVisible() && s.status !== ATOM_STATUSES.selected) {
      s.status = ATOM_STATUSES.selected;

      // Bring to back of list to be drawn last (on top).
      this.atoms.toBack(this.indexOf(s.id));
      c.style.cursor = t.cursor.normal;
      changed = true;
    }

    return changed;
  },

  /*
   * Move all atoms in this list dx in the x direction and dy on the y axis.
   */
  move: function(dx, dy) {
    this.each(function(a) {
      a.move(dx, dy);
    });
  },

  /*
   * Scale the atoms with a factor f.
   */
  scale: function(f) {
    this.each(function(a) {
      var dx = a.x * f - a.x;
      var dy = a.y * f - a.y;
      a.move(dx, dy);
    });

    window.molecule = this.molecule;
    window.fixcount = 0;
    window.fixmax = 1000 - 4.8 * this.count();
    window.requestAnimationFrame(function drawLoop() {
      if(fixcount < fixmax && molecule.deoverlap()) {
        fixcount++;
        molecule.mv.redraw();
        requestAnimationFrame(drawLoop);
      }
    });
  },

  /*
   * Center the list of atoms.
   */
  center: function() {
    var cc = this.molecule.mv.ctx.centerPoint();
    var mc = this.centerPoint();
    var dx = cc.x - mc.x;
    var dy = cc.y - mc.y;
    this.move(dx, dy);
  },

  /*
   * Zoom on the center of the molecule with a factor f.
   */
  zoom: function(f) {
    var c = this.centerPoint();
    this.zoomOn(c.x, c.y, f);
  },

  /*
   * Zoom on a specific point (x, y) with a factor f.
   */
  zoomOn: function(x, y, f) {
    this.move(-x, -y);
    this.scale(f);
    this.move(x, y);
  },

  /*
   * Fit the molecule in a box of size w * h and center it there.
   */
  bestFit: function(w, h) {
    var s = this.molecule.mv.settings;
    var wf = w / this.width();
    var hf = h / this.height();
    var f = wf < hf ? wf : hf;
    this.scale(f);

    var tx = w / 2 - this.width() / 2;
    var ty = h / 2 - this.height() / 2;
    var lt = this.leftTop();
    var dx = tx - lt.x;
    var dy = ty - lt.y;
    this.move(dx, dy);
  },

  clearCache: function(name) {
    this.cache.clear(name);
    this.molecule.clearCache(name);
  },

  /*
   * Draw all atoms in this list.
   */
  draw: function() {
    this.each(function(a) {
      a.draw();
    });
    var cp = this.centerPoint();
    this.molecule.mv.ctx.fillRect(cp.x - 10, cp.y - 10, 20, 20);
  }
};
<|endoftext|>


<commit_before>import zpad from 'zpad';
/**
 * This function pad a fraction with leading zero
 * For example, it converts 1.2 to 1.002 when length argument is 3
 */
export default function padPageNumWithZeros(numStr, length) {

  const [, wholeNumStr, fractionStr] = /^(\d+)\.(\d+)$/.exec(numStr) || [];

  if (undefined === fractionStr) {
    return numStr;
  }

  const fraction = zpad(parseInt(fractionStr, 10), length);

  return `${wholeNumStr}.${fraction}`;
}
<commit_msg>update function padPageNumWithZeros<commit_after>import zpad from 'zpad';
/**
 * This function pad a fraction with leading zero
 * For example, it converts 1.2 to 1.02 when the argument length is 2
 */
export default function padPageNumWithZeros(num, length) {

  const numStr = String(num);
  const [, wholeNumStr, fractionStr] = /^(\d+)\.(\d+)$/.exec(numStr) || [];

  if (undefined === fractionStr) {
    return numStr;
  }
  const fraction = zpad(parseInt(fractionStr, 10), length);
  return parseFloat(`${wholeNumStr}.${fraction}`);
}
<|endoftext|>


<commit_before>/**
 * @fileOverview Configuration dialog module for restartless addons
 * @author       SHIMODA "Piro" Hiroshi
 * @version      5
 *
 * @license
 *   The MIT License, Copyright (c) 2011 SHIMODA "Piro" Hiroshi.
 *   http://www.cozmixng.org/repos/piro/restartless-addon/trunk/license.txt
 * @url http://www.cozmixng.org/repos/piro/restartless-addon/trunk/
 */

const EXPORTED_SYMBOLS = ['config'];

'open,register,unregister,setDefault'.split(',').forEach(function(aSymbol) {
	exports[aSymbol] = function() {
		if (!config)
			throw new Error('config module was already unloaded!');
		return config[aSymbol].apply(config, arguments);
	};
});

/**
 * @class
 *   Provides features to manage custom configuration dialog.
 */
var config = {
	_configs : {},

	/**
	 * Opens a registered dialog bound to the given URI as a "non-modal"
	 * window. If there is existing window, then focus to it.
	 *
	 * @param {String} aURI
	 *   A URI which is bould to any configuration dialog.
	 * @param {nsIDOMWindow} aOwner
	 *   An owner window of the dialog.
	 *
	 * @returns {nsIDOMWindow}
	 *   The window object of the configuration dialog.
	 */
	open : function(aURI, aOwner)
	{
		aURI = this._resolveResURI(aURI);
		if (!(aURI in this._configs))
			return null;

		var current = this._configs[aURI];

		if (current.openedWindow && !current.openedWindow.closed) {
			current.openedWindow.focus();
			return current.openedWindow;
		}

		var source = Cc['@mozilla.org/variant;1']
						.createInstance(Ci.nsIWritableVariant);
		source.setFromVariant(current.source);

		if (aOwner) {
			let parent = aOwner.top
							.QueryInterface(Ci.nsIInterfaceRequestor)
							.getInterface(Ci.nsIWebNavigation)
							.QueryInterface(Ci.nsIDocShell)
							.QueryInterface(Ci.nsIDocShellTreeNode)
							.QueryInterface(Ci.nsIDocShellTreeItem)
							.parent;
			if (parent)
				aOwner = parent.QueryInterface(Ci.nsIWebNavigation)
							.document
							.defaultView;
			else
				aOwner = null;
		}

		current.openedWindow = Cc['@mozilla.org/embedcomp/window-watcher;1']
							.getService(Ci.nsIWindowWatcher)
							.openWindow(
								aOwner || null,
								'data:application/vnd.mozilla.xul+xml,'+encodeURIComponent(
									current.container
								),
								'_blank',
								'chrome,titlebar,toolbar,centerscreen' +
								(Prefs.getBoolPref('browser.preferences.instantApply') ?
									',dialog=no' :
								aOwner ?
									',modal' :
									''
								),
								source
							);
		current.openedWindow.addEventListener('load', function() {
			current.openedWindow.removeEventListener('load', arguments.callee, false);
			current.openedWindow._sourceURI = aURI;
			current.openedWindow.addEventListener('unload', function() {
				current.openedWindow.removeEventListener('unload', arguments.callee, false);
				current.openedWindow = null;
			}, false);
		}, false);
		return current.openedWindow;
	},

	/**
	 * Registers a source code of a XUL document for a configuration dialog
	 * to the given URI. It is used by open().
	 *
	 * @param {String} aURI
	 *   A URI which is the target URI. When the URI is loaded in a browser
	 *   window, then this system automatically opens a generated XUL window
	 *   from the source.
	 * @param {XML} aXML
	 *   A source of a XUL document for a configuration dialog defined as an
	 *   E4X object (XML object). Typical headers (<?xml version="1.0"?> and
	 *   an <?xml-stylesheet?> for the default theme) are automatically added.
	 */
	register : function(aURI, aXML)
	{
		var root = aXML.copy();
		delete root.*;
		var attributes = root.attributes();
		for each (var attribute in attributes)
		{
			delete root['@'+attribute.name()];
		}
		root.script = <script type="application/javascript">{ this._loader }</script>;

		var header = '<?xml version="1.0"?>\n'+
					'<!-- ' + aURI + ' -->\n'+
					'<?xml-stylesheet href="chrome://global/skin/"?>\n';

		var originalSettings = XML.settings();
		XML.ignoreWhitespace = true;
		XML.prettyPrinting = false;

		this._configs[this._resolveResURI(aURI)] = {
			container    : header+((new XMLList(root.toXMLString())).toXMLString()),
			source       : (new XMLList(aXML.toXMLString())).toXMLString(),
			openedWindow : null
		};

		XML.setSettings(originalSettings);
	},
	_loader : <![CDATA[
		var d = document;
		var e = d.documentElement;
		var r = d.createRange();
		r.selectNode(e);
		d.replaceChild(r.createContextualFragment(arguments[0]), e);
		r.detach();
	]]>.toString()
		.replace(/\/\/.*$/gm, '')
		.replace(/\s\s+/g, ' '),

	/**
	 * Unregisters a registeed dialog for the given URI.
	 *
	 * @param {String} aURI
	 *   A URI which have a registered dialog.
	 */
	unregister : function(aURI)
	{
		delete this._configs[this._resolveResURI(aURI)];
	},

	/**
	 * Unregisters a default value for the preference.
	 *
	 * @param {String} aKey
	 *   A key of preference.
	 * @param {nsIVariant} aValue
	 *   The default value. This must be a string, integer, or boolean.
	 */
	setDefault : function(aKey, aValue)
	{
		switch (typeof aValue)
		{
			case 'string':
				return DefaultPrefs.setCharPref(aKey, unescape(encodeURIComponent(aValue)));

			case 'number':
				return DefaultPrefs.setIntPref(aKey, parseInt(aValue));

			default:
				return DefaultPrefs.setBoolPref(aKey, !!aValue);
		}
	},

	observe : function(aSubject, aTopic, aData)
	{
		var uri = aSubject.location.href;
		if (
			uri == 'about:addons' ||
			uri == 'chrome://mozapps/content/extensions/extensions.xul' // Firefox 3.6
			) {
			this._onLoadManager(aSubject);
			return;
		}

		uri = this._resolveResURI(uri);
		if (uri in this._configs) {
			aSubject.setTimeout('window.close();', 0);
			this.open(uri);
		}
	},

	_resolveResURI : function(aURI)
	{
		if (aURI.indexOf('resource:') == 0)
			return ResProtocolHandler.resolveURI(IOService.newURI(aURI, null, null));
		return aURI;
	},

	handleEvent : function(aEvent)
	{
		switch (aEvent.type)
		{
			case 'unload':
				this._onUnloadManager(aEvent.currentTarget);
				return;

			case 'command':
				let target = aEvent.originalTarget;
				let uri;
				if (target.getAttribute('anonid') == 'preferences-btn' ||
					target.id == 'cmd_showItemPreferences')
					uri = target.ownerDocument.defaultView
							.gViewController
							.currentViewObj
							.getSelectedAddon()
							.optionsURL;
				else if (target.id == 'cmd_options') // Firefox 3.6
					uri = target.ownerDocument.defaultView
							.gExtensionsView
							.currentItem
							.getAttribute('optionsURL');
				if (uri &&
					(uri = this._resolveResURI(uri)) &&
					uri in this._configs) {
					this.open(uri, target.ownerDocument.defaultView);
					aEvent.stopPropagation();
					aEvent.preventDefault();
				}
				return;
		}
	},
	_onLoadManager : function(aWindow)
	{
		aWindow.addEventListener('command', this, true);
		aWindow.addEventListener('unload', this, true);
		this._managers.push(aWindow);
	},
	_onUnloadManager : function(aWindow)
	{
		aWindow.removeEventListener('command', this, true);
		aWindow.removeEventListener('unload', this, true);
		this._managers.splice(this._managers.indexOf(aWindow), 1);
	},
	_managers : []
};

var Prefs = Cc['@mozilla.org/preferences;1']
						.getService(Ci.nsIPrefBranch);
var DefaultPrefs = Cc['@mozilla.org/preferences-service;1']
						.getService(Ci.nsIPrefService)
						.getDefaultBranch(null);

var IOService = Cc['@mozilla.org/network/io-service;1']
						.getService(Ci.nsIIOService);
var ResProtocolHandler = IOService
						.getProtocolHandler('resource')
						.QueryInterface(Ci.nsIResProtocolHandler);

var ObserverService = Cc['@mozilla.org/observer-service;1']
						.getService(Ci.nsIObserverService);
ObserverService.addObserver(config, 'chrome-document-global-created', false);
ObserverService.addObserver(config, 'content-document-global-created', false);

var WindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
						.getService(Ci.nsIWindowMediator)
let (managers = WindowMediator.getEnumerator('Addons:Manager')) {
	while (managers.hasMoreElements())
	{
		config._onLoadManager(managers.getNext().QueryInterface(Ci.nsIDOMWindow));
	}
}
let (browsers = WindowMediator.getEnumerator('navigator:browser')) {
	while (browsers.hasMoreElements())
	{
		let browser = browsers.getNext().QueryInterface(Ci.nsIDOMWindow);
		Array.slice(browser.gBrowser.mTabContainer.childNodes)
			.forEach(function(aTab) {
			if (aTab.linkedBrowser.currentURI.spec == 'about:addons')
				config._onLoadManager(aTab.linkedBrowser.contentWindow);
		});
	}
}
let (managers = WindowMediator.getEnumerator('Extension:Manager')) { // Firefox 3.6
	while (managers.hasMoreElements())
	{
		config._onLoadManager(managers.getNext().QueryInterface(Ci.nsIDOMWindow));
	}
}

function shutdown()
{
	var windows = WindowMediator.getEnumerator(null);
	while (windows.hasMoreElements())
	{
		let window = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
		if (window._sourceURI && window._sourceURI in config._configs)
			window.close();
	}

	config._managers.forEach(config._onUnloadManager, config);

	ObserverService.removeObserver(config, 'chrome-document-global-created');
	ObserverService.removeObserver(config, 'content-document-global-created');

	Prefs = void(0);
	DefaultPrefs = void(0);
	IOService = void(0);
	ResProtocolHandler = void(0);
	ObserverService = void(0);
	WindowMediator = void(0);

	config._configs = void(0);
	config._managers = void(0);
	config = void(0);
}
<commit_msg>can work with Thunderbird and Fennec (there are no gBrowser)<commit_after>/**
 * @fileOverview Configuration dialog module for restartless addons
 * @author       SHIMODA "Piro" Hiroshi
 * @version      6
 *
 * @license
 *   The MIT License, Copyright (c) 2011 SHIMODA "Piro" Hiroshi.
 *   http://www.cozmixng.org/repos/piro/restartless-addon/trunk/license.txt
 * @url http://www.cozmixng.org/repos/piro/restartless-addon/trunk/
 */

const EXPORTED_SYMBOLS = ['config'];

'open,register,unregister,setDefault'.split(',').forEach(function(aSymbol) {
	exports[aSymbol] = function() {
		if (!config)
			throw new Error('config module was already unloaded!');
		return config[aSymbol].apply(config, arguments);
	};
});

/**
 * @class
 *   Provides features to manage custom configuration dialog.
 */
var config = {
	_configs : {},

	/**
	 * Opens a registered dialog bound to the given URI as a "non-modal"
	 * window. If there is existing window, then focus to it.
	 *
	 * @param {String} aURI
	 *   A URI which is bould to any configuration dialog.
	 * @param {nsIDOMWindow} aOwner
	 *   An owner window of the dialog.
	 *
	 * @returns {nsIDOMWindow}
	 *   The window object of the configuration dialog.
	 */
	open : function(aURI, aOwner)
	{
		aURI = this._resolveResURI(aURI);
		if (!(aURI in this._configs))
			return null;

		var current = this._configs[aURI];

		if (current.openedWindow && !current.openedWindow.closed) {
			current.openedWindow.focus();
			return current.openedWindow;
		}

		var source = Cc['@mozilla.org/variant;1']
						.createInstance(Ci.nsIWritableVariant);
		source.setFromVariant(current.source);

		if (aOwner) {
			let parent = aOwner.top
							.QueryInterface(Ci.nsIInterfaceRequestor)
							.getInterface(Ci.nsIWebNavigation)
							.QueryInterface(Ci.nsIDocShell)
							.QueryInterface(Ci.nsIDocShellTreeNode)
							.QueryInterface(Ci.nsIDocShellTreeItem)
							.parent;
			if (parent)
				aOwner = parent.QueryInterface(Ci.nsIWebNavigation)
							.document
							.defaultView;
			else
				aOwner = null;
		}

		current.openedWindow = Cc['@mozilla.org/embedcomp/window-watcher;1']
							.getService(Ci.nsIWindowWatcher)
							.openWindow(
								aOwner || null,
								'data:application/vnd.mozilla.xul+xml,'+encodeURIComponent(
									current.container
								),
								'_blank',
								'chrome,titlebar,toolbar,centerscreen' +
								(Prefs.getBoolPref('browser.preferences.instantApply') ?
									',dialog=no' :
								aOwner ?
									',modal' :
									''
								),
								source
							);
		current.openedWindow.addEventListener('load', function() {
			current.openedWindow.removeEventListener('load', arguments.callee, false);
			current.openedWindow._sourceURI = aURI;
			current.openedWindow.addEventListener('unload', function() {
				current.openedWindow.removeEventListener('unload', arguments.callee, false);
				current.openedWindow = null;
			}, false);
		}, false);
		return current.openedWindow;
	},

	/**
	 * Registers a source code of a XUL document for a configuration dialog
	 * to the given URI. It is used by open().
	 *
	 * @param {String} aURI
	 *   A URI which is the target URI. When the URI is loaded in a browser
	 *   window, then this system automatically opens a generated XUL window
	 *   from the source.
	 * @param {XML} aXML
	 *   A source of a XUL document for a configuration dialog defined as an
	 *   E4X object (XML object). Typical headers (<?xml version="1.0"?> and
	 *   an <?xml-stylesheet?> for the default theme) are automatically added.
	 */
	register : function(aURI, aXML)
	{
		var root = aXML.copy();
		delete root.*;
		var attributes = root.attributes();
		for each (var attribute in attributes)
		{
			delete root['@'+attribute.name()];
		}
		root.script = <script type="application/javascript">{ this._loader }</script>;

		var header = '<?xml version="1.0"?>\n'+
					'<!-- ' + aURI + ' -->\n'+
					'<?xml-stylesheet href="chrome://global/skin/"?>\n';

		var originalSettings = XML.settings();
		XML.ignoreWhitespace = true;
		XML.prettyPrinting = false;

		this._configs[this._resolveResURI(aURI)] = {
			container    : header+((new XMLList(root.toXMLString())).toXMLString()),
			source       : (new XMLList(aXML.toXMLString())).toXMLString(),
			openedWindow : null
		};

		XML.setSettings(originalSettings);
	},
	_loader : <![CDATA[
		var d = document;
		var e = d.documentElement;
		var r = d.createRange();
		r.selectNode(e);
		d.replaceChild(r.createContextualFragment(arguments[0]), e);
		r.detach();
	]]>.toString()
		.replace(/\/\/.*$/gm, '')
		.replace(/\s\s+/g, ' '),

	/**
	 * Unregisters a registeed dialog for the given URI.
	 *
	 * @param {String} aURI
	 *   A URI which have a registered dialog.
	 */
	unregister : function(aURI)
	{
		delete this._configs[this._resolveResURI(aURI)];
	},

	/**
	 * Unregisters a default value for the preference.
	 *
	 * @param {String} aKey
	 *   A key of preference.
	 * @param {nsIVariant} aValue
	 *   The default value. This must be a string, integer, or boolean.
	 */
	setDefault : function(aKey, aValue)
	{
		switch (typeof aValue)
		{
			case 'string':
				return DefaultPrefs.setCharPref(aKey, unescape(encodeURIComponent(aValue)));

			case 'number':
				return DefaultPrefs.setIntPref(aKey, parseInt(aValue));

			default:
				return DefaultPrefs.setBoolPref(aKey, !!aValue);
		}
	},

	observe : function(aSubject, aTopic, aData)
	{
		var uri = aSubject.location.href;
		if (
			uri == 'about:addons' ||
			uri == 'chrome://mozapps/content/extensions/extensions.xul' // Firefox 3.6
			) {
			this._onLoadManager(aSubject);
			return;
		}

		uri = this._resolveResURI(uri);
		if (uri in this._configs) {
			aSubject.setTimeout('window.close();', 0);
			this.open(uri);
		}
	},

	_resolveResURI : function(aURI)
	{
		if (aURI.indexOf('resource:') == 0)
			return ResProtocolHandler.resolveURI(IOService.newURI(aURI, null, null));
		return aURI;
	},

	handleEvent : function(aEvent)
	{
		switch (aEvent.type)
		{
			case 'unload':
				this._onUnloadManager(aEvent.currentTarget);
				return;

			case 'command':
				let target = aEvent.originalTarget;
				let uri;
				if (target.getAttribute('anonid') == 'preferences-btn' ||
					target.id == 'cmd_showItemPreferences')
					uri = target.ownerDocument.defaultView
							.gViewController
							.currentViewObj
							.getSelectedAddon()
							.optionsURL;
				else if (target.id == 'cmd_options') // Firefox 3.6
					uri = target.ownerDocument.defaultView
							.gExtensionsView
							.currentItem
							.getAttribute('optionsURL');
				if (uri &&
					(uri = this._resolveResURI(uri)) &&
					uri in this._configs) {
					this.open(uri, target.ownerDocument.defaultView);
					aEvent.stopPropagation();
					aEvent.preventDefault();
				}
				return;
		}
	},
	_onLoadManager : function(aWindow)
	{
		aWindow.addEventListener('command', this, true);
		aWindow.addEventListener('unload', this, true);
		this._managers.push(aWindow);
	},
	_onUnloadManager : function(aWindow)
	{
		aWindow.removeEventListener('command', this, true);
		aWindow.removeEventListener('unload', this, true);
		this._managers.splice(this._managers.indexOf(aWindow), 1);
	},
	_managers : []
};

var Prefs = Cc['@mozilla.org/preferences;1']
						.getService(Ci.nsIPrefBranch);
var DefaultPrefs = Cc['@mozilla.org/preferences-service;1']
						.getService(Ci.nsIPrefService)
						.getDefaultBranch(null);

var IOService = Cc['@mozilla.org/network/io-service;1']
						.getService(Ci.nsIIOService);
var ResProtocolHandler = IOService
						.getProtocolHandler('resource')
						.QueryInterface(Ci.nsIResProtocolHandler);

var ObserverService = Cc['@mozilla.org/observer-service;1']
						.getService(Ci.nsIObserverService);
ObserverService.addObserver(config, 'chrome-document-global-created', false);
ObserverService.addObserver(config, 'content-document-global-created', false);

var WindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
						.getService(Ci.nsIWindowMediator)
let (managers = WindowMediator.getEnumerator('Addons:Manager')) {
	while (managers.hasMoreElements())
	{
		config._onLoadManager(managers.getNext().QueryInterface(Ci.nsIDOMWindow));
	}
}
let (browsers = WindowMediator.getEnumerator('navigator:browser')) {
	while (browsers.hasMoreElements())
	{
		let browser = browsers.getNext().QueryInterface(Ci.nsIDOMWindow);
		if (browser.gBrowser)
			Array.slice(browser.gBrowser.mTabContainer.childNodes)
				.forEach(function(aTab) {
				if (aTab.linkedBrowser.currentURI.spec == 'about:addons')
					config._onLoadManager(aTab.linkedBrowser.contentWindow);
			});
	}
}
let (managers = WindowMediator.getEnumerator('Extension:Manager')) { // Firefox 3.6
	while (managers.hasMoreElements())
	{
		config._onLoadManager(managers.getNext().QueryInterface(Ci.nsIDOMWindow));
	}
}

function shutdown()
{
	var windows = WindowMediator.getEnumerator(null);
	while (windows.hasMoreElements())
	{
		let window = windows.getNext().QueryInterface(Ci.nsIDOMWindow);
		if (window._sourceURI && window._sourceURI in config._configs)
			window.close();
	}

	config._managers.forEach(config._onUnloadManager, config);

	ObserverService.removeObserver(config, 'chrome-document-global-created');
	ObserverService.removeObserver(config, 'content-document-global-created');

	Prefs = void(0);
	DefaultPrefs = void(0);
	IOService = void(0);
	ResProtocolHandler = void(0);
	ObserverService = void(0);
	WindowMediator = void(0);

	config._configs = void(0);
	config._managers = void(0);
	config = void(0);
}
<|endoftext|>


<commit_before>/*
 * Run in: http://adventofcode.com/day/3/input
 */

;(function () {
  let input = document.querySelector('pre').textContent

  console.log('Day03/first:', first(input))
  console.log('Day03/second:', second(input))

  function moveSanta (coords, houses, command) {
    switch (command) {
      case '^':
        coords.y++
        break
      case 'v':
        coords.y--
        break
      case '>':
        coords.x++
        break
      case '<':
        coords.x--
        break
    }

    houses[coords.x + ',' + coords.y] = houses[coords.x + ',' + coords.y] + 1 || 1
  }

  function first (input) {
    let result = input.split('').reduce((data, command) => {
      moveSanta(data.coords, data.houses, command)
      return data
    }, {
      coords: { x: 0, y: 0 }, houses: { '0,0': 1 }
    })

    return Object.keys(result.houses).length
  }

  function second (input) {
    let result = input.split('').reduce((data, command, i) => {
      moveSanta(i % 2 ? data.robot : data.santa, data.houses, command)
      return data
    }, {
      santa: { x: 0, y: 0 }, robot: { x: 0, y: 0 }, houses: { '0,0': 2 }
    })

    return Object.keys(result.houses).length
  }
}())
<commit_msg>More use of ES2015 to day03<commit_after>/*
 * Run in: http://adventofcode.com/day/3/input
 */

;(function () {
  let input = document.querySelector('pre').textContent

  console.log('Day03/first:', first(input))
  console.log('Day03/second:', second(input))

  function moveSanta (coords, houses, command) {
    switch (command) {
      case '^':
        coords.y++
        break
      case 'v':
        coords.y--
        break
      case '>':
        coords.x++
        break
      case '<':
        coords.x--
        break
    }

    houses[`${coords.x},${coords.y}`] = houses[`${coords.x},${coords.y}`] + 1 || 1
  }

  function first (input) {
    let result = input.split('').reduce((data, command) => {
      moveSanta(data.coords, data.houses, command)
      return data
    }, {
      coords: { x: 0, y: 0 }, houses: { '0,0': 1 }
    })

    return Object.keys(result.houses).length
  }

  function second (input) {
    let result = input.split('').reduce((data, command, i) => {
      moveSanta(data[i % 2 ? 'robot' : 'santa'], data.houses, command)
      return data
    }, {
      santa: { x: 0, y: 0 }, robot: { x: 0, y: 0 }, houses: { '0,0': 2 }
    })

    return Object.keys(result.houses).length
  }
}())
<|endoftext|>


<commit_before>const chalk = require( 'chalk' );

module.exports = {
    'answer': function ( { petition = 'cybrus, please answer.' } ) {
        console.log( chalk.yellow( petition ) );
        return petition;
    }
};
<commit_msg>refactored the fn expression to arrow fn<commit_after>const chalk = require( 'chalk' );

module.exports = {
    'answer': ( { petition = 'cybrus, please answer.' } ) => {
        console.log( chalk.yellow( petition ) );
        return petition;
    }
};
<|endoftext|>


<commit_before>// Get driving direction using Google Directions API.

var page = new WebPage(),
    origin, dest, steps;

if (phantom.args.length < 2) {
    console.log('Usage: direction.js origin destination');
    console.log('Example: direction.js "San Diego" "Palo Alto"');
    phantom.exit(1);
} else {
    origin = phantom.args[0];
    dest = phantom.args[1];
    page.open(encodeURI('http://maps.googleapis.com/maps/api/directions/xml?origin=' + origin +
                '&destination=' + dest + '&units=imperial&mode=driving&sensor=false'), function (status) {
        if (status !== 'success') {
            console.log('Unable to access network');
        } else {
            steps = page.content.match(/<html_instructions>(.*)<\/html_instructions>/ig);
            if (steps == null) {
                console.log('No data available for ' + phantom.state);
            } else {
                steps.forEach(function (ins) {
                    ins = ins.replace(/\</ig, '<').replace(/\>/ig, '>');
                    ins = ins.replace(/\<div/ig, '\n<div');
                    ins = ins.replace(/<.*?>/g, '');
                    console.log(ins);
                });
                console.log('');
                console.log(page.content.match(/<copyrights>.*<\/copyrights>/ig).join('').replace(/<.*?>/g, ''));
            }
        }
        phantom.exit();
    });
}
<commit_msg>Fix error message.<commit_after>// Get driving direction using Google Directions API.

var page = new WebPage(),
    origin, dest, steps;

if (phantom.args.length < 2) {
    console.log('Usage: direction.js origin destination');
    console.log('Example: direction.js "San Diego" "Palo Alto"');
    phantom.exit(1);
} else {
    origin = phantom.args[0];
    dest = phantom.args[1];
    page.open(encodeURI('http://maps.googleapis.com/maps/api/directions/xml?origin=' + origin +
                '&destination=' + dest + '&units=imperial&mode=driving&sensor=false'), function (status) {
        if (status !== 'success') {
            console.log('Unable to access network');
        } else {
            steps = page.content.match(/<html_instructions>(.*)<\/html_instructions>/ig);
            if (steps == null) {
                console.log('No data available for ' + origin + ' to ' + dest);
            } else {
                steps.forEach(function (ins) {
                    ins = ins.replace(/\</ig, '<').replace(/\>/ig, '>');
                    ins = ins.replace(/\<div/ig, '\n<div');
                    ins = ins.replace(/<.*?>/g, '');
                    console.log(ins);
                });
                console.log('');
                console.log(page.content.match(/<copyrights>.*<\/copyrights>/ig).join('').replace(/<.*?>/g, ''));
            }
        }
        phantom.exit();
    });
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    httpProxy = require('http-proxy')

environment = process.env.NODE_ENV || 'production'
config      = require('./config.' + environment)

var options = {
    https: {
        key: fs.readFileSync(config.ssl.key, 'utf8'),
        cert: fs.readFileSync(config.ssl.cert, 'utf8'),
        ca: config.ssl.ca ? fs.readFileSync(config.ssl.ca, 'utf8') : null,
        ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:'
            + '!MD5:!aNULL:!EDH:!AESGCM',
        honorCipherOrder: true
    },
    enable: {
        xforward: true // enables X-Forwarded-For
    }
}

var proxy = new httpProxy.HttpProxy({
    target: {
        host: 'localhost',
        port: config.app.port
    },
    enable: { xforward: true }
})

var listenOn = config.listen || [ 80, 443 ]

listenOn.forEach(function(port) {

    httpProxy.createServer(options, function (req, res) {
        proxy.proxyRequest(req, res)
    }).listen(port).on('upgrade', function (req, socket, head) {
        proxy.proxyWebSocketRequest(req, socket, head);
    })
})

console.log("Ready to proxy requests on port(s) " + listenOn.join(', ') + "...")
<commit_msg>Update the cipher list to pass ssllabs BEAST tests<commit_after>var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    httpProxy = require('http-proxy')

environment = process.env.NODE_ENV || 'production'
config      = require('./config.' + environment)

var options = {
    https: {
        key: fs.readFileSync(config.ssl.key, 'utf8'),
        cert: fs.readFileSync(config.ssl.cert, 'utf8'),
        ca: config.ssl.ca ? fs.readFileSync(config.ssl.ca, 'utf8') : null,
        ciphers: 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:'
            + 'HIGH:!MD5:!aNULL:!EDH',
        honorCipherOrder: true
    },
    enable: {
        xforward: true // enables X-Forwarded-For
    }
}

var proxy = new httpProxy.HttpProxy({
    target: {
        host: 'localhost',
        port: config.app.port
    },
    enable: { xforward: true }
})

var listenOn = config.listen || [ 80, 443 ]

listenOn.forEach(function(port) {

    httpProxy.createServer(options, function (req, res) {
        proxy.proxyRequest(req, res)
    }).listen(port).on('upgrade', function (req, socket, head) {
        proxy.proxyWebSocketRequest(req, socket, head);
    })
})

console.log("Ready to proxy requests on port(s) " + listenOn.join(', ') + "...")
<|endoftext|>


<commit_before>/**
 * @fileOverview This module provides a flexible templating system.
 */

var strings = require('ringo/utils/strings');
var objects = require('ringo/utils/objects');
var engine = require('ringo/engine');
var webenv = require('ringo/webapp/env');

export('render', 'createSkin', 'Skin');

var log = require('ringo/logging').getLogger(module.id);
var skincache = false; // {}

engine.addHostObject(org.ringojs.template.MacroTag);

/**
 * Parse a skin from a resource and render it using the given context.
 * @param skinOrResource a skin object, ringojs resource, or file name
 * @param context the skin render context
 */
function render(skinOrResource, context) {
    var skin;
    if (typeof(skinOrResource.render) == "function") {
        skin = skinOrResource;
    } else if (skinOrResource instanceof org.ringojs.repository.Resource) {
        skin = createSkin(skinOrResource);
    } else if (typeof(skinOrResource) == "string") {
        var subskin;
        if (skinOrResource.indexOf('#') > -1) {
            [skinOrResource, subskin] = skinOrResource.split('#');
        }
        var resource = this.getResource(skinOrResource);
        skin = createSkin(resource);
        if (subskin) {
            skin = skin.getSubskin(subskin);
        }
    } else {
        throw Error("Unknown skin object: " + skinOrResource);
    }
    return skin.render(context);
}

/**
 * Resolve a skin path (given as string) against a base (which can be either a
 * resource or a name as string).
 */
function resolveSkin(base, skinPath) {
    var skinResource;
    var parentRepo = base.parentRepository;
    if (parentRepo && strings.startsWith(skinPath, ".")) {
        skinResource = parentRepo.getResource(skinPath);
    }
    if (!skinResource || !skinResource.exists()) {
        skinResource = getResource(skinPath);
    }
    return skinResource;
}

/**
 * Parse a skin from a resource.
 * @param resourceOrString the skin resource or string
 */
function createSkin(resourceOrString) {
    if (this.skincache && resourceOrString in skincache) {
        return skincache[resourceOrString];
    }
    if (log.isDebugEnabled())
        log.debug("creating skin: ", resourceOrString);
    var mainSkin = [];
    var subSkins = {};
    var currentSkin = mainSkin;
    var parentSkin = null;
    var eng = engine.getRhinoEngine();

    var parser = new org.ringojs.template.SkinParser({
        renderText: function(text) {
            currentSkin[currentSkin.length] = text;
        },
        renderMacro: function(macro) {
            eng.wrapArgument(macro, global);
            if (macro.name === 'extends') {
                var skinPath = macro.getParameter(0);
                var skinResource = resolveSkin(resourceOrString, skinPath);
                parentSkin = createSkin(skinResource);
            } else if (macro.name === 'subskin')  {
                var skinName = macro.getParameter('name', 0);
                currentSkin = [];
                currentSkin.subskinFilter = macro.filter;
                subSkins[skinName] = currentSkin;
            } else {
                currentSkin[currentSkin.length] = macro;
            }
        }
    });
    if (resourceOrString instanceof org.ringojs.repository.Resource) {
        var config = webenv.getConfig(),
            charset = config && config.charset || 'utf8';
        parser.parse(resourceOrString, charset);
    } else {
        parser.parse(resourceOrString);
    }
    // normalization: cut trailing whitespace so it's
    // easier to tell if main skin should be inherited
    var lastPart = mainSkin[mainSkin.length - 1];
    if (typeof(lastPart) === 'string' && lastPart.trim() === '') {
        mainSkin.pop();
    }
    var skin = new Skin(mainSkin, subSkins, parentSkin, resourceOrString);
    if (skincache)
        skincache[resourceOrString] = skin;
    return skin;
}

/**
 * The Skin object. This takes an array of skin parts (literal strings and MacroTags)
 * and a dictionary of subskins.
 * @param mainSkin an array of skin parts: string literals and macro tags
 * @param subSkins a dictionary of named skin components
 */
function Skin(mainSkin, subSkins, parentSkin, resourceOrString) {

    var self = this;

    this.render = function render(context) {
        // extend context by globally provided macros and filters.
        // user-provided context overrides globally defined stuff
        context = webenv.loadMacros(context);
        if (mainSkin.length === 0 && parentSkin) {
            return renderInternal(parentSkin.getSkinParts(), context);
        }
        return renderInternal(mainSkin, context);
    };

    this.renderSubskin = function renderSubskin(skinName, context) {
        var subSkin = subSkins[skinName];
        if (!subSkin) {
            // First, try to find subskin in parent skins.
            var parts = parentSkin && parentSkin.getSkinParts(skinName);
            if (parts) {
                return renderInternal(parts, context);
            }
            // If that fails, try to load the subskin as external skin.
            var skinResource = resolveSkin(resourceOrString, skinName);
            if (skinResource && skinResource.exists()) {
                subSkin = subSkins[skinName] = createSkin(skinResource);
            }
            // We still might have no subskin here. That's fine, as
            // renderInternal can cope.
        }
        if (subSkin instanceof Skin) {
            return subSkin.render(context);
        }
        return renderInternal(subSkin, context);
    };

    this.getSubskin = function getSubskin(skinName) {
        if (subSkins[skinName]) {
            return new Skin(subSkins[skinName], subSkins, parentSkin);
        }
        return null;
    };

    this.getSkinParts = function getSkinParts(skinName) {
        var parts = skinName ? subSkins[skinName] : mainSkin;
        if (!parts || (!skinName && parts.length === 0)) {
            return parentSkin ? parentSkin.getSkinParts(skinName) : null;
        }
        return parts;
    };

    function renderInternal(parts, context) {
        var value = parts ?
                parts.map(function(part) renderPart(part, context)).join('') : '';
        if (parts && parts.subskinFilter) {
            return evaluateFilter(value, parts.subskinFilter, context);
        }
        return value;
    }

    function renderPart(part, context) {
        return part instanceof MacroTag && part.name
                ? evaluateMacro(part, context)
                : part;
    }

    function evaluateMacro(macro, context) {
        // evaluate the macro itself
        var value = evaluateExpression(macro, context, '_macro');
        return evaluateFilter(value, macro.filter, context);
    }

    function evaluateFilter(value, filter, context) {
        // traverse the linked list of filters
        while (filter) {
            // make sure value is not undefined, otherwise evaluateExpression()
            // might become confused
            if (!isVisible(value)) {
                value = "";
            }
            value = evaluateExpression(filter, context, '_filter', value);
            filter = filter.filter;
        }
        if (value instanceof Array) {
            value = value.join('');
        }
        return value;
    }

    function evaluateNestedMacros(macro, context) {
        // We need to keep the original nested "MacroTag" objects obtained from
        // parsing around, in order to be able to safely re-evaluate the same
        // skin in differing contexts.
        macro.nested = macro.nested || {};
        for (var i in macro.parameters) {
            var param = macro.nested[i] || macro.parameters[i];
            if (param instanceof MacroTag) {
                macro.nested[i] = param;
                macro.parameters[i] = evaluateExpression(param, context, '_macro');
            }
        }
        for (var k in macro.namedParameters) {
            var param = macro.nested[k] || macro.namedParameters[k];
            if (param instanceof MacroTag) {
                macro.nested[k] = param;
                macro.namedParameters[k] = evaluateExpression(param, context, '_macro');
            }
        }
    }

    function evaluateExpression(macro, context, suffix, value) {
        if (log.isDebugEnabled()) {
            log.debug('evaluating expression: ', macro);
        }
        evaluateNestedMacros(macro, context);
        if (builtin[macro.name]) {
            return builtin[macro.name](macro, context);
        }
        var path = macro.name.split('.');
        var elem = context;
        var length = path.length;
        var last = path[length-1];
        for (var i = 0; i < length - 1; i++) {
            elem = elem[path[i]];
            if (!isDefined(elem)) {
                break;
            }
        }
        if (isDefined(elem)) {
            if (elem[last + suffix] instanceof Function) {
                return value === undefined ?
                       elem[last + suffix].call(elem, macro, context, self) :
                       elem[last + suffix].call(elem, value, macro, context, self);
            } else if (value === undefined && isDefined(elem[last])) {
                if (elem[last] instanceof Function) {
                    return elem[last].call(elem, macro, context, self);
                }
                return elem[last];
            }
        }
        // TODO: if filter is not found just return value as is
        return value;
    }

    function isDefined(elem) {
        return elem !== undefined && elem !== null;
    }

    function isVisible(elem) {
        return elem !== undefined && elem !== null && elem !== '';
    }

    // builtin macro handlers
    var builtin = {
        "render": function(macro, context) {
            var skin = macro.getParameter(0);
            return skin == null ? "" : self.renderSubskin(skin, context);
        },

        "echo": function(macro, context) {
            var result = macro.parameters;
            var wrapper = macro.getParameter("wrap") || macro.getParameter("echo-wrap");
            if (wrapper != null) {
                result = result.map(function(part) {return wrapper[0] + part + wrapper[1]});
            }
            var separator = macro.getParameter("separator");
            if (separator != null) {
                return result.join(separator);
            }
            return result.join(' ');
        },

        "for": function(macro, context) {
            if (macro.parameters.length < 4)
                return "[Error in for-in macro: not enough parameters]";
            if (macro.parameters[1] != "in")
                return "[Error in for-in macro: expected in]";
            var name = macro.parameters[0];
            var list = macro.parameters[2];
            var subContext = objects.clone(context || {});
            var subMacro = macro.getSubMacro(3);
            if (subMacro.name == "and") {
                subMacro.name = "for";
            }
            var result = [];
            for (var [index, value] in list) {
                subContext['index'] = index
                subContext[name] = value;
                result.push(evaluateMacro(subMacro, subContext));
            }
            var wrapper = macro.getParameter("wrap") || macro.getParameter(name + "-wrap");
            if (wrapper != null) {
                result = result.map(function(part) {return wrapper[0] + part + wrapper[1]});
            }
            var separator = macro.getParameter("separator");
            if (separator != null) {
                return result.join(separator);
            }
            return result.join('');
        },

        "if": function(macro, context, bypass) {
            if (macro.parameters.length < 2)
                return "[Error in if macro: not enough parameters]";
            var negated = (macro.parameters[0] == "not");
            if (negated && macro.parameters.length < 3)
                return "[Error in if macro: not enough parameters]";
            var index = negated ? 1 : 0;
            var result = true;
            if (bypass) {
                index++;
            } else {
                var condition = macro.parameters[index++];
                result = negated ? !condition : !!condition;
            }
            var subName = macro.parameters[index];
            if (!result && macro.parameters[index] != "or") {
                return "";
            }
            var subMacro = macro.getSubMacro(index);
            if (subName == "or" && result)
                return builtin["if"](subMacro, context, true);
            else if (subName == "and" || subName == "or")
                return builtin["if"](subMacro, context);
            return evaluateMacro(subMacro, context);
        },

        "set": function(macro, context) {
            if (macro.parameters.length < 2)
                return "[Error in set macro: not enough parameters]";
            var map = macro.parameters[0];
            var subContext = objects.clone(context || {});
            var subMacro = macro.getSubMacro(1);
            for (var [key, value] in map) {
                subContext[key] = value;
            }
            return evaluateMacro(subMacro, subContext);
        }

    };

    this.toString = function toString() {
        return "[Skin Object]";
    };

}
<commit_msg>Check if this.getResource() is defined in skin.render(), use global getResource() otherwise<commit_after>/**
 * @fileOverview This module provides a flexible templating system.
 */

var strings = require('ringo/utils/strings');
var objects = require('ringo/utils/objects');
var engine = require('ringo/engine');
var webenv = require('ringo/webapp/env');

export('render', 'createSkin', 'Skin');

var log = require('ringo/logging').getLogger(module.id);
var skincache = false; // {}

engine.addHostObject(org.ringojs.template.MacroTag);

/**
 * Parse a skin from a resource and render it using the given context.
 * @param skinOrResource a skin object, ringojs resource, or file name
 * @param context the skin render context
 */
function render(skinOrResource, context) {
    var skin;
    if (typeof(skinOrResource.render) == "function") {
        skin = skinOrResource;
    } else if (skinOrResource instanceof org.ringojs.repository.Resource) {
        skin = createSkin(skinOrResource);
    } else if (typeof(skinOrResource) == "string") {
        var subskin;
        if (skinOrResource.indexOf('#') > -1) {
            [skinOrResource, subskin] = skinOrResource.split('#');
        }
        // using this.getResource() if available allows as to get relative resources
        var resource = typeof this.getResource === "function" ?
                this.getResource(skinOrResource) : getResource(skinOrResource);
        skin = createSkin(resource);
        if (subskin) {
            skin = skin.getSubskin(subskin);
        }
    } else {
        throw Error("Unknown skin object: " + skinOrResource);
    }
    return skin.render(context);
}

/**
 * Resolve a skin path (given as string) against a base (which can be either a
 * resource or a name as string).
 */
function resolveSkin(base, skinPath) {
    var skinResource;
    var parentRepo = base.parentRepository;
    if (parentRepo && strings.startsWith(skinPath, ".")) {
        skinResource = parentRepo.getResource(skinPath);
    }
    if (!skinResource || !skinResource.exists()) {
        skinResource = getResource(skinPath);
    }
    return skinResource;
}

/**
 * Parse a skin from a resource.
 * @param resourceOrString the skin resource or string
 */
function createSkin(resourceOrString) {
    if (this.skincache && resourceOrString in skincache) {
        return skincache[resourceOrString];
    }
    if (log.isDebugEnabled())
        log.debug("creating skin: ", resourceOrString);
    var mainSkin = [];
    var subSkins = {};
    var currentSkin = mainSkin;
    var parentSkin = null;
    var eng = engine.getRhinoEngine();

    var parser = new org.ringojs.template.SkinParser({
        renderText: function(text) {
            currentSkin[currentSkin.length] = text;
        },
        renderMacro: function(macro) {
            eng.wrapArgument(macro, global);
            if (macro.name === 'extends') {
                var skinPath = macro.getParameter(0);
                var skinResource = resolveSkin(resourceOrString, skinPath);
                parentSkin = createSkin(skinResource);
            } else if (macro.name === 'subskin')  {
                var skinName = macro.getParameter('name', 0);
                currentSkin = [];
                currentSkin.subskinFilter = macro.filter;
                subSkins[skinName] = currentSkin;
            } else {
                currentSkin[currentSkin.length] = macro;
            }
        }
    });
    if (resourceOrString instanceof org.ringojs.repository.Resource) {
        var config = webenv.getConfig(),
            charset = config && config.charset || 'utf8';
        parser.parse(resourceOrString, charset);
    } else {
        parser.parse(resourceOrString);
    }
    // normalization: cut trailing whitespace so it's
    // easier to tell if main skin should be inherited
    var lastPart = mainSkin[mainSkin.length - 1];
    if (typeof(lastPart) === 'string' && lastPart.trim() === '') {
        mainSkin.pop();
    }
    var skin = new Skin(mainSkin, subSkins, parentSkin, resourceOrString);
    if (skincache)
        skincache[resourceOrString] = skin;
    return skin;
}

/**
 * The Skin object. This takes an array of skin parts (literal strings and MacroTags)
 * and a dictionary of subskins.
 * @param mainSkin an array of skin parts: string literals and macro tags
 * @param subSkins a dictionary of named skin components
 */
function Skin(mainSkin, subSkins, parentSkin, resourceOrString) {

    var self = this;

    this.render = function render(context) {
        // extend context by globally provided macros and filters.
        // user-provided context overrides globally defined stuff
        context = webenv.loadMacros(context);
        if (mainSkin.length === 0 && parentSkin) {
            return renderInternal(parentSkin.getSkinParts(), context);
        }
        return renderInternal(mainSkin, context);
    };

    this.renderSubskin = function renderSubskin(skinName, context) {
        var subSkin = subSkins[skinName];
        if (!subSkin) {
            // First, try to find subskin in parent skins.
            var parts = parentSkin && parentSkin.getSkinParts(skinName);
            if (parts) {
                return renderInternal(parts, context);
            }
            // If that fails, try to load the subskin as external skin.
            var skinResource = resolveSkin(resourceOrString, skinName);
            if (skinResource && skinResource.exists()) {
                subSkin = subSkins[skinName] = createSkin(skinResource);
            }
            // We still might have no subskin here. That's fine, as
            // renderInternal can cope.
        }
        if (subSkin instanceof Skin) {
            return subSkin.render(context);
        }
        return renderInternal(subSkin, context);
    };

    this.getSubskin = function getSubskin(skinName) {
        if (subSkins[skinName]) {
            return new Skin(subSkins[skinName], subSkins, parentSkin);
        }
        return null;
    };

    this.getSkinParts = function getSkinParts(skinName) {
        var parts = skinName ? subSkins[skinName] : mainSkin;
        if (!parts || (!skinName && parts.length === 0)) {
            return parentSkin ? parentSkin.getSkinParts(skinName) : null;
        }
        return parts;
    };

    function renderInternal(parts, context) {
        var value = parts ?
                parts.map(function(part) renderPart(part, context)).join('') : '';
        if (parts && parts.subskinFilter) {
            return evaluateFilter(value, parts.subskinFilter, context);
        }
        return value;
    }

    function renderPart(part, context) {
        return part instanceof MacroTag && part.name
                ? evaluateMacro(part, context)
                : part;
    }

    function evaluateMacro(macro, context) {
        // evaluate the macro itself
        var value = evaluateExpression(macro, context, '_macro');
        return evaluateFilter(value, macro.filter, context);
    }

    function evaluateFilter(value, filter, context) {
        // traverse the linked list of filters
        while (filter) {
            // make sure value is not undefined, otherwise evaluateExpression()
            // might become confused
            if (!isVisible(value)) {
                value = "";
            }
            value = evaluateExpression(filter, context, '_filter', value);
            filter = filter.filter;
        }
        if (value instanceof Array) {
            value = value.join('');
        }
        return value;
    }

    function evaluateNestedMacros(macro, context) {
        // We need to keep the original nested "MacroTag" objects obtained from
        // parsing around, in order to be able to safely re-evaluate the same
        // skin in differing contexts.
        macro.nested = macro.nested || {};
        for (var i in macro.parameters) {
            var param = macro.nested[i] || macro.parameters[i];
            if (param instanceof MacroTag) {
                macro.nested[i] = param;
                macro.parameters[i] = evaluateExpression(param, context, '_macro');
            }
        }
        for (var k in macro.namedParameters) {
            var param = macro.nested[k] || macro.namedParameters[k];
            if (param instanceof MacroTag) {
                macro.nested[k] = param;
                macro.namedParameters[k] = evaluateExpression(param, context, '_macro');
            }
        }
    }

    function evaluateExpression(macro, context, suffix, value) {
        if (log.isDebugEnabled()) {
            log.debug('evaluating expression: ', macro);
        }
        evaluateNestedMacros(macro, context);
        if (builtin[macro.name]) {
            return builtin[macro.name](macro, context);
        }
        var path = macro.name.split('.');
        var elem = context;
        var length = path.length;
        var last = path[length-1];
        for (var i = 0; i < length - 1; i++) {
            elem = elem[path[i]];
            if (!isDefined(elem)) {
                break;
            }
        }
        if (isDefined(elem)) {
            if (elem[last + suffix] instanceof Function) {
                return value === undefined ?
                       elem[last + suffix].call(elem, macro, context, self) :
                       elem[last + suffix].call(elem, value, macro, context, self);
            } else if (value === undefined && isDefined(elem[last])) {
                if (elem[last] instanceof Function) {
                    return elem[last].call(elem, macro, context, self);
                }
                return elem[last];
            }
        }
        // TODO: if filter is not found just return value as is
        return value;
    }

    function isDefined(elem) {
        return elem !== undefined && elem !== null;
    }

    function isVisible(elem) {
        return elem !== undefined && elem !== null && elem !== '';
    }

    // builtin macro handlers
    var builtin = {
        "render": function(macro, context) {
            var skin = macro.getParameter(0);
            return skin == null ? "" : self.renderSubskin(skin, context);
        },

        "echo": function(macro, context) {
            var result = macro.parameters;
            var wrapper = macro.getParameter("wrap") || macro.getParameter("echo-wrap");
            if (wrapper != null) {
                result = result.map(function(part) {return wrapper[0] + part + wrapper[1]});
            }
            var separator = macro.getParameter("separator");
            if (separator != null) {
                return result.join(separator);
            }
            return result.join(' ');
        },

        "for": function(macro, context) {
            if (macro.parameters.length < 4)
                return "[Error in for-in macro: not enough parameters]";
            if (macro.parameters[1] != "in")
                return "[Error in for-in macro: expected in]";
            var name = macro.parameters[0];
            var list = macro.parameters[2];
            var subContext = objects.clone(context || {});
            var subMacro = macro.getSubMacro(3);
            if (subMacro.name == "and") {
                subMacro.name = "for";
            }
            var result = [];
            for (var [index, value] in list) {
                subContext['index'] = index
                subContext[name] = value;
                result.push(evaluateMacro(subMacro, subContext));
            }
            var wrapper = macro.getParameter("wrap") || macro.getParameter(name + "-wrap");
            if (wrapper != null) {
                result = result.map(function(part) {return wrapper[0] + part + wrapper[1]});
            }
            var separator = macro.getParameter("separator");
            if (separator != null) {
                return result.join(separator);
            }
            return result.join('');
        },

        "if": function(macro, context, bypass) {
            if (macro.parameters.length < 2)
                return "[Error in if macro: not enough parameters]";
            var negated = (macro.parameters[0] == "not");
            if (negated && macro.parameters.length < 3)
                return "[Error in if macro: not enough parameters]";
            var index = negated ? 1 : 0;
            var result = true;
            if (bypass) {
                index++;
            } else {
                var condition = macro.parameters[index++];
                result = negated ? !condition : !!condition;
            }
            var subName = macro.parameters[index];
            if (!result && macro.parameters[index] != "or") {
                return "";
            }
            var subMacro = macro.getSubMacro(index);
            if (subName == "or" && result)
                return builtin["if"](subMacro, context, true);
            else if (subName == "and" || subName == "or")
                return builtin["if"](subMacro, context);
            return evaluateMacro(subMacro, context);
        },

        "set": function(macro, context) {
            if (macro.parameters.length < 2)
                return "[Error in set macro: not enough parameters]";
            var map = macro.parameters[0];
            var subContext = objects.clone(context || {});
            var subMacro = macro.getSubMacro(1);
            for (var [key, value] in map) {
                subContext[key] = value;
            }
            return evaluateMacro(subMacro, subContext);
        }

    };

    this.toString = function toString() {
        return "[Skin Object]";
    };

}
<|endoftext|>


<commit_before>/**
 * @module Control
 */

import React from 'react'
import PropTypes from 'prop-types'

import ContextTypes from './internal/context-types'
import withControl from './withControl'

class Control extends React.Component {
  render() {
    const { name, children, useStringRefs } = this.props;
    const enhance = withControl(name, { useStringRefs });
    class BaseComponent extends React.Component {
      render() { return this.props.children; }
    }
    const ControlledComponent = enhance(BaseComponent);
    return <ControlledComponent children={ children }/>;
  }
}

Control.contextTypes = ContextTypes;

Control.propTypes = {
  name: PropTypes.string.isRequired,
};

Control.defaultProps = {
  useStringRefs: false,
};

export default Control;
<commit_msg>:art: [Control] Whitespace<commit_after>/**
 * @module Control
 */

import React from 'react'
import PropTypes from 'prop-types'

import ContextTypes from './internal/context-types'
import withControl from './withControl'

class Control extends React.Component {
  render() {
    const { name, children, useStringRefs } = this.props;
    const enhance = withControl(name, { useStringRefs });
    class BaseComponent extends React.Component {
      render() {
        return this.props.children;
      }
    }
    const ControlledComponent = enhance(BaseComponent);
    return <ControlledComponent children={ children }/>;
  }
}

Control.contextTypes = ContextTypes;

Control.propTypes = {
  name: PropTypes.string.isRequired,
};

Control.defaultProps = {
  useStringRefs: false,
};

export default Control;
<|endoftext|>


<commit_before>"use strict";

var speedy = require ("../lib");

var o = {};

speedy.run ({
	"in": function (){
		"a" in o;
	},
	"undefined": function (){
		o.a === undefined;
	}
});

/*
File: in-object.js

Node v0.10.18
V8 v3.14.5.9
Speedy v0.0.8

Benchmarks: 2
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per benchmark: ~3000ms (3s 0ms)
Total time: ~6000ms (6s 0ms)

Higher is better (ops/sec)

in
  16,279,539 ± 0.0%
undefined
  151,203,277 ± 0.0%

Elapsed time: 6053ms (6s 53ms)
*/<commit_msg>updated in-object<commit_after>"use strict";

var speedy = require ("../lib");

var o = {};

speedy.run ({
	"in": function (){
		"a" in o;
	},
	"undefined": function (){
		o.a !== undefined;
	}
});

/*
File: in-object.js

Node v0.10.20
V8 v3.14.5.9
Speedy v0.0.8

Benchmarks: 2
Timeout: 1000ms (1s 0ms)
Samples: 3
Total time per benchmark: ~3000ms (3s 0ms)
Total time: ~6000ms (6s 0ms)

Higher is better (ops/sec)

in
  16,982,098 ± 0.0%
undefined
  152,094,766 ± 0.0%

Elapsed time: 6146ms (6s 146ms)
*/<|endoftext|>


<commit_before>var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , LinkedInStrategy = require('passport-linkedin').Strategy;

var LINKEDIN_API_KEY = "--insert-linkedin-api-key-here--"
var LINKEDIN_SECRET_KEY = "--insert-linkedin-secret-key-here--";

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.  However, since this example does not
//   have a database of user records, the complete LinkedIn profile is
//   serialized and deserialized.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

// Use the LinkedInStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a token, tokenSecret, and LinkedIn profile), and
//   invoke a callback with a user object.
passport.use(new LinkedInStrategy({
    consumerKey: LINKEDIN_API_KEY,
    consumerSecret: LINKEDIN_SECRET_KEY,
    callbackURL: "http://127.0.0.1:3000/auth/linkedin/callback"
  },
  function(token, tokenSecret, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's LinkedIn profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the LinkedIn account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
));

var app = express.createServer();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

// GET /auth/linkedin
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in LinkedIn authentication will involve
//   redirecting the user to linkedin.com.  After authorization, LinkedIn will
//   redirect the user back to this application at /auth/linkedin/callback
app.get('/auth/linkedin',
  passport.authenticate('linkedin'),
  function(req, res){
    // The request will be redirected to LinkedIn for authentication, so this
    // function will not be called.
  });

// GET /auth/linkedin/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/linkedin/callback',
  passport.authenticate('linkedin', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.listen(3000);

// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}
<commit_msg>fixed example to work with express 3.x<commit_after>var express = require('express')
  , http = require('http')
  , passport = require('passport')
  , util = require('util')
  , LinkedInStrategy = require('passport-linkedin').Strategy;

var app = express();

// configure Express
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));

var LINKEDIN_API_KEY = "--insert-linkedin-api-key-here--";
var LINKEDIN_SECRET_KEY = "--insert-linkedin-secret-key-here--";

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.  However, since this example does not
//   have a database of user records, the complete LinkedIn profile is
//   serialized and deserialized.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

// Use the LinkedInStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a token, tokenSecret, and LinkedIn profile), and
//   invoke a callback with a user object.
passport.use(new LinkedInStrategy({
    consumerKey: LINKEDIN_API_KEY,
    consumerSecret: LINKEDIN_SECRET_KEY,
    callbackURL: "http://127.0.0.1:3000/auth/linkedin/callback"
  },
  function(token, tokenSecret, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      // To keep the example simple, the user's LinkedIn profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the LinkedIn account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
));

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

// GET /auth/linkedin
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in LinkedIn authentication will involve
//   redirecting the user to linkedin.com.  After authorization, LinkedIn will
//   redirect the user back to this application at /auth/linkedin/callback
app.get('/auth/linkedin',
  passport.authenticate('linkedin'),
  function(req, res){
    // The request will be redirected to LinkedIn for authentication, so this
    // function will not be called.
  });

// GET /auth/linkedin/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/linkedin/callback',
  passport.authenticate('linkedin', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
}
<|endoftext|>