<commit_before>Monocle.Flippers.Slider = function (reader, setPageFn) {
  if (Monocle.Flippers == this) {
    return new Monocle.Flippers.Slider(reader, setPageFn);
  }

  var API = { constructor: Monocle.Flippers.Slider }
  var k = API.constants = API.constructor;
  var p = API.properties = {
    pageCount: 2,
    activeIndex: 1,
    divs: {
      pages: []
    },
    // Properties relating to the current page turn interaction.
    turnData: {}
  }

  function initialize() {
    p.reader = reader;
    p.setPageFn = setPageFn;
  }

  function addPage(pageDiv) {
    p.divs.pages.push(pageDiv);
  }

  function visiblePages() {
    return [upperPage()];
  }

  function listenForInteraction(panelClass) {
    if (typeof panelClass != "function") {
      panelClass = k.DEFAULT_PANELS_CLASS;
    }
    p.panels = new panelClass(
      API,
      {
        'start': function (panel, x) { lift(panel.properties.direction, x); },
        'move': function (panel, x) { turning(panel.properties.direction, x); },
        'end': function (panel, x) { drop(panel.properties.direction, x); },
        'cancel': function (panel, x) { drop(panel.properties.direction, x); }
      }
    );
  }

  function getPlace(pageDiv) {
    pageDiv = pageDiv || upperPage();
    return pageDiv.m ? pageDiv.m.place : null;
  }

  function moveTo(locus) {
    setPage(
      upperPage(),
      locus,
      completedTurn,
      function () { console.log("FAILED TO MOVE TO LOCUS"); }
    );
  }

  function setPage(pageDiv, locus, callback, failCallback) {
    var spCallback = function (offset) {
      pageDiv.m.sheafDiv.style.backgroundColor = "transparent";
      pageDiv.m.activeFrame.style.visibility = "visible";
      if (pageDiv.m.completeWhenReady) {
        pageDiv.m.completeWhenReady();
      }

      if (offset === 'disallow') {
        if (typeof failCallback == 'function') { failCallback(); }
        p.turnData = {};
        return;
      }
      var bdy = pageDiv.m.activeFrame.contentDocument.body;
      Monocle.Styles.affix(bdy, "transform", "translateX("+(0-offset)+"px)");
      if (callback) { callback(); }
    }
    pageDiv.m.sheafDiv.style.backgroundColor = "#FCFCFC";
    pageDiv.m.activeFrame.style.visibility = "hidden";
    return p.setPageFn(pageDiv, locus, spCallback);
  }

  function upperPage() {
    return p.divs.pages[p.activeIndex];
  }

  function lowerPage() {
    return p.divs.pages[(p.activeIndex + 1) % 2];
  }

  function flipPages() {
    upperPage().style.zIndex = 1;
    lowerPage().style.zIndex = 2;
    return p.activeIndex = (p.activeIndex + 1) % 2;
  }

  function deferredCall(fn) {
    setTimeout(fn, k.durations.ANTI_FLICKER_DELAY);
  }

  function onFirstPage() {
    var place = getPlace();
    return place.properties.component.properties.index == 0 &&
      place.pageNumber() == 1;
  }

  function onLastPage() {
    var place = getPlace();
    var cmpt = place.properties.component;
    return cmpt.properties.index == cmpt.properties.book.properties.lastCIndex &&
      place.pageNumber() == cmpt.lastPageNumber();
  }

  function lift(dir, boxPointX) {
    // FIXME: LIFT FAILED. UNRESPONSIVE.
    if (p.turnData.animating) {
      return;
    }

    // FIXME: LIFT FAILED. UNRESPONSIVE.
    if (upperPage().m.pageChanging) {
      return;
    }

    p.turnData.points = {
      start: boxPointX,
      min: boxPointX,
      max: boxPointX
    }

    if (dir == k.FORWARDS) {
      if (onLastPage()) {
        console.log("ON LAST PAGE");
        p.turnData = {};
        return;
      }
      // if (Monocle.Browser.has.iframeTouchBug) {
      //   lowerPage().style.display = "block";
      // }
      slideToCursor(boxPointX);
    } else if (dir == k.BACKWARDS) {
      // if (Monocle.Browser.has.iframeTouchBug) {
      //   lowerPage().style.display = "block";
      // }
      var backwardsTurn = function () {
        if (lowerPage().m.pageChanging) {
          lowerPage().m.completeWhenReady = backwardsTurn;
          p.turnData.animating = true;
          return;
        }
        lowerPage().m.completeWhenReady = null;

        if (onFirstPage()) {
          console.log("ON FIRST PAGE");
          p.turnData = {};
          return;
        }

        p.turnData.animating = true;
        jumpOut(function () {
          var place = getPlace();
          var rslt = setPage(
            lowerPage(),
            place.getLocus({ direction: k.BACKWARDS }),
            null,
            // Callback on failure
            function () {
              p.turnData = {};
            }
          );
          flipPages();
          slideToCursor(boxPointX);
        });
      }
      backwardsTurn();
    }
  }

  function turning(dir, boxPointX) {
    if (p.turnData.animating) {
      return;
    }

    if (!p.turnData.points) {
      return;
    }

    p.turnData.points.min = Math.min(p.turnData.points.min, boxPointX);
    p.turnData.points.max = Math.max(p.turnData.points.max, boxPointX);

    slideToCursor(boxPointX, null, "0");
  }

  function drop(dir, boxPointX) {
    if (p.turnData.animating) {
      p.nextAction = function () { drop(dir, boxPointX); }
      return;
    }
    p.nextAction = null;

    if (!p.turnData.points) {
      return;
    }

    slideToCursor(boxPointX, null, "0");

    p.turnData.points.tap = p.turnData.points.max - p.turnData.points.min < 10;

    if (dir == k.FORWARDS) {
      if (
        p.turnData.points.tap ||
        p.turnData.points.start - boxPointX > 60 ||
        p.turnData.points.min >= boxPointX
      ) {
        // Completing forward turn
        slideOut();
      } else {
        // Cancelling forward turn
        slideIn();
      }
    } else if (dir == k.BACKWARDS) {
      if (
        p.turnData.points.tap ||
        boxPointX - p.turnData.points.start > 60 ||
        p.turnData.points.max <= boxPointX
      ) {
        // Completing backward turn
        slideIn();
      } else {
        // Cancelling backward turn
        slideOut();
      }
    }
  }

  function completedTurn() {
    if (upperPage().m.pageChanging) {
      upperPage().m.completeWhenReady = completedTurn;
      p.turnData.animating = true;
      return;
    }
    upperPage().m.completeWhenReady = null;

    jumpIn(function () {
      p.reader.dispatchEvent('monocle:turn');
      p.turnData = {};

      var place = getPlace();

      setPage(lowerPage(), place.getLocus({ direction: k.FORWARDS }));
    });
  }

  function setX(elem, x, options, callback) {
    var duration;

    if (!options.duration) {
      duration = 0;
    } else {
      duration = parseInt(options['duration']);
    }

    if (typeof(x) == "number") { x = x + "px"; }

    // BROWSERHACK: WEBKIT (transitions & transition events)
    if (typeof WebKitTransitionEvent != "undefined") {
      if (duration) {
        transition = '-webkit-transform';
        transition += ' ' + duration + "ms";
        transition += ' ' + (options['timing'] || 'linear');
        transition += ' ' + (options['delay'] || 0) + 'ms';
      } else {
        transition = 'none';
      }
      elem.style.webkitTransition = transition;
      elem.style.webkitTransform = "translate3d("+x+",0,0)";

    // BROWSERHACK: NON-WEBKIT (no transitions)
    } else if (duration > 0) {
      // Exit any existing transition loop.
      clearTimeout(elem.setXTransitionInterval)

      var stamp = (new Date()).getTime();
      var frameRate = 40;
      var finalX = parseInt(x);
      var currX = getX(elem);
      var step = (finalX - currX) * (frameRate / duration);
      var stepFn = function () {
        var destX = currX + step;
        if (
          (new Date()).getTime() - stamp > duration ||
          Math.abs(currX - finalX) <= Math.abs((currX + step) - finalX)
        ) {
          clearTimeout(elem.setXTransitionInterval)
          elem.style.MozTransform = "translateX(" + finalX + "px)";
          if (elem.setXTCB) {
            elem.setXTCB();
          }
        } else {
          elem.style.MozTransform = "translateX(" + destX + "px)";
          currX = destX;
        }
      }

      elem.setXTransitionInterval = setInterval(stepFn, frameRate);
    } else {
      elem.style.MozTransform = "translateX("+x+")";
    }

    if (elem.setXTCB) {
      Monocle.Events.deafen(elem, 'webkitTransitionEnd', elem.setXTCB);
      elem.setXTCB = null;
    }

    var sX = getX(elem);
    if (!duration || sX == parseInt(x)) {
      if (callback) { callback(); }
    } else {
      elem.setXTCB = function () {
        p.turnData.animating = false;
        if (p.nextAction) {
          p.nextAction();
        }
        if (callback) { callback(); }
      }
      Monocle.Events.listen(elem, 'webkitTransitionEnd', elem.setXTCB);
    }
  }

  function getX(elem) {
    if (typeof WebKitCSSMatrix == "object") {
      var matrix = window.getComputedStyle(elem).webkitTransform;
      matrix = new WebKitCSSMatrix(matrix);
      return matrix.m41;
    } else {
      var prop = elem.style.MozTransform;
      if (!prop || prop == "") { return 0; }
      return parseFloat((/translateX\((\-?.*)px\)/).exec(prop)[1]) || 0;
    }
  }

  /* NB: Jumps are always done by the hidden lower page. */

  function jumpIn(callback) {
    // Duration should be 0, but is set to 1 to address a 10.6 Safari bug.
    setX(lowerPage(), 0, { duration: 1 }, callback);
  }

  function jumpOut(callback) {
    setX(
      lowerPage(),
      0 - p.reader.properties.pageWidth,
      { duration: 0 },
      callback
    );
  }

  function jumpToCursor(cursorX, callback) {
    setX(
      lowerPage(),
      Math.min(0, cursorX - p.reader.properties.pageWidth),
      { duration: 0 },
      callback
    );
  }

  /* NB: Slides are always done by the visible upper page. */

  function slideIn() {
    var slideOpts = {
      duration: k.durations.SLIDE,
      timing: 'ease-in'
    };
    p.turnData.animating = true;
    setX(upperPage(), 0, slideOpts, completedTurn);
  }

  function slideOut() {
    var slideOpts = {
      duration: k.durations.SLIDE,
      timing: 'ease-in'
    };
    var callback = function () { flipPages(); completedTurn(); }
    p.turnData.animating = true;
    setX(upperPage(), 0 - p.reader.properties.pageWidth, slideOpts, callback);
  }

  function slideToCursor(cursorX, callback, duration) {
    setX(
      upperPage(),
      Math.min(0, cursorX - p.reader.properties.pageWidth),
      { duration: duration || k.durations.FOLLOW_CURSOR },
      callback
    );
  }

  // THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
  API.pageCount = p.pageCount;
  API.addPage = addPage;
  API.visiblePages = visiblePages;
  API.getPlace = getPlace;
  API.moveTo = moveTo;
  API.listenForInteraction = listenForInteraction;

  initialize();

  return API;
}

// Constants
Monocle.Flippers.Slider.DEFAULT_PANELS_CLASS = Monocle.Panels.TwoPane;
Monocle.Flippers.Slider.FORWARDS = 1;
Monocle.Flippers.Slider.BACKWARDS = -1;
Monocle.Flippers.Slider.durations = {
  SLIDE: 250,
  FOLLOW_CURSOR: 150,
  ANTI_FLICKER_DELAY: 0
}

Monocle.pieceLoaded('flippers/slider');
<commit_msg>Rejigging turndata expiration in completedTurn.<commit_after>Monocle.Flippers.Slider = function (reader, setPageFn) {
  if (Monocle.Flippers == this) {
    return new Monocle.Flippers.Slider(reader, setPageFn);
  }

  var API = { constructor: Monocle.Flippers.Slider }
  var k = API.constants = API.constructor;
  var p = API.properties = {
    pageCount: 2,
    activeIndex: 1,
    divs: {
      pages: []
    },
    // Properties relating to the current page turn interaction.
    turnData: {}
  }

  function initialize() {
    p.reader = reader;
    p.setPageFn = setPageFn;
  }

  function addPage(pageDiv) {
    p.divs.pages.push(pageDiv);
  }

  function visiblePages() {
    return [upperPage()];
  }

  function listenForInteraction(panelClass) {
    if (typeof panelClass != "function") {
      panelClass = k.DEFAULT_PANELS_CLASS;
    }
    p.panels = new panelClass(
      API,
      {
        'start': function (panel, x) { lift(panel.properties.direction, x); },
        'move': function (panel, x) { turning(panel.properties.direction, x); },
        'end': function (panel, x) { drop(panel.properties.direction, x); },
        'cancel': function (panel, x) { drop(panel.properties.direction, x); }
      }
    );
  }

  function getPlace(pageDiv) {
    pageDiv = pageDiv || upperPage();
    return pageDiv.m ? pageDiv.m.place : null;
  }

  function moveTo(locus) {
    setPage(
      upperPage(),
      locus,
      completedTurn,
      function () { console.log("FAILED TO MOVE TO LOCUS"); }
    );
  }

  function setPage(pageDiv, locus, callback, failCallback) {
    var spCallback = function (offset) {
      pageDiv.m.sheafDiv.style.backgroundColor = "transparent";
      pageDiv.m.activeFrame.style.visibility = "visible";
      if (pageDiv.m.completeWhenReady) {
        pageDiv.m.completeWhenReady();
      }

      if (offset === 'disallow') {
        if (typeof failCallback == 'function') { failCallback(); }
        p.turnData = {};
        return;
      }
      var bdy = pageDiv.m.activeFrame.contentDocument.body;
      Monocle.Styles.affix(bdy, "transform", "translateX("+(0-offset)+"px)");
      if (callback) { callback(); }
    }
    pageDiv.m.sheafDiv.style.backgroundColor = "#FCFCFC";
    pageDiv.m.activeFrame.style.visibility = "hidden";
    return p.setPageFn(pageDiv, locus, spCallback);
  }

  function upperPage() {
    return p.divs.pages[p.activeIndex];
  }

  function lowerPage() {
    return p.divs.pages[(p.activeIndex + 1) % 2];
  }

  function flipPages() {
    upperPage().style.zIndex = 1;
    lowerPage().style.zIndex = 2;
    return p.activeIndex = (p.activeIndex + 1) % 2;
  }

  function deferredCall(fn) {
    setTimeout(fn, k.durations.ANTI_FLICKER_DELAY);
  }

  function onFirstPage() {
    var place = getPlace();
    return place.properties.component.properties.index == 0 &&
      place.pageNumber() == 1;
  }

  function onLastPage() {
    var place = getPlace();
    var cmpt = place.properties.component;
    return cmpt.properties.index == cmpt.properties.book.properties.lastCIndex &&
      place.pageNumber() == cmpt.lastPageNumber();
  }

  function lift(dir, boxPointX) {
    // FIXME: LIFT FAILED. UNRESPONSIVE.
    if (p.turnData.animating) {
      return;
    }

    // FIXME: LIFT FAILED. UNRESPONSIVE.
    if (upperPage().m.pageChanging) {
      return;
    }

    p.turnData.points = {
      start: boxPointX,
      min: boxPointX,
      max: boxPointX
    }

    if (dir == k.FORWARDS) {
      if (onLastPage()) {
        console.log("ON LAST PAGE");
        p.turnData = {};
        return;
      }
      // if (Monocle.Browser.has.iframeTouchBug) {
      //   lowerPage().style.display = "block";
      // }
      slideToCursor(boxPointX);
    } else if (dir == k.BACKWARDS) {
      // if (Monocle.Browser.has.iframeTouchBug) {
      //   lowerPage().style.display = "block";
      // }
      var backwardsTurn = function () {
        if (lowerPage().m.pageChanging) {
          lowerPage().m.completeWhenReady = backwardsTurn;
          p.turnData.animating = true;
          return;
        }
        lowerPage().m.completeWhenReady = null;

        if (onFirstPage()) {
          console.log("ON FIRST PAGE");
          p.turnData = {};
          return;
        }

        p.turnData.animating = true;
        jumpOut(function () {
          var place = getPlace();
          var rslt = setPage(
            lowerPage(),
            place.getLocus({ direction: k.BACKWARDS }),
            null,
            // Callback on failure
            function () {
              p.turnData = {};
            }
          );
          flipPages();
          slideToCursor(boxPointX);
        });
      }
      backwardsTurn();
    }
  }

  function turning(dir, boxPointX) {
    if (p.turnData.animating) {
      return;
    }

    if (!p.turnData.points) {
      return;
    }

    p.turnData.points.min = Math.min(p.turnData.points.min, boxPointX);
    p.turnData.points.max = Math.max(p.turnData.points.max, boxPointX);

    slideToCursor(boxPointX, null, "0");
  }

  function drop(dir, boxPointX) {
    if (p.turnData.animating) {
      p.nextAction = function () { drop(dir, boxPointX); }
      return;
    }
    p.nextAction = null;

    if (!p.turnData.points) {
      return;
    }

    slideToCursor(boxPointX, null, "0");

    p.turnData.points.tap = p.turnData.points.max - p.turnData.points.min < 10;

    if (dir == k.FORWARDS) {
      if (
        p.turnData.points.tap ||
        p.turnData.points.start - boxPointX > 60 ||
        p.turnData.points.min >= boxPointX
      ) {
        // Completing forward turn
        slideOut();
      } else {
        // Cancelling forward turn
        slideIn();
      }
    } else if (dir == k.BACKWARDS) {
      if (
        p.turnData.points.tap ||
        boxPointX - p.turnData.points.start > 60 ||
        p.turnData.points.max <= boxPointX
      ) {
        // Completing backward turn
        slideIn();
      } else {
        // Cancelling backward turn
        slideOut();
      }
    }
  }

  function completedTurn() {
    p.turnData = {}
    if (upperPage().m.pageChanging) {
      upperPage().m.completeWhenReady = completedTurn;
      p.turnData.animating = true;
      return;
    }
    upperPage().m.completeWhenReady = null;

    jumpIn(function () {
      setPage(
        lowerPage(),
        getPlace().getLocus({ direction: k.FORWARDS }),
        function () {
          p.reader.dispatchEvent('monocle:turn');
        }
      );
    });
  }

  function setX(elem, x, options, callback) {
    var duration;

    if (!options.duration) {
      duration = 0;
    } else {
      duration = parseInt(options['duration']);
    }

    if (typeof(x) == "number") { x = x + "px"; }

    // BROWSERHACK: WEBKIT (transitions & transition events)
    if (typeof WebKitTransitionEvent != "undefined") {
      if (duration) {
        transition = '-webkit-transform';
        transition += ' ' + duration + "ms";
        transition += ' ' + (options['timing'] || 'linear');
        transition += ' ' + (options['delay'] || 0) + 'ms';
      } else {
        transition = 'none';
      }
      elem.style.webkitTransition = transition;
      elem.style.webkitTransform = "translate3d("+x+",0,0)";

    // BROWSERHACK: NON-WEBKIT (no transitions)
    } else if (duration > 0) {
      // Exit any existing transition loop.
      clearTimeout(elem.setXTransitionInterval)

      var stamp = (new Date()).getTime();
      var frameRate = 40;
      var finalX = parseInt(x);
      var currX = getX(elem);
      var step = (finalX - currX) * (frameRate / duration);
      var stepFn = function () {
        var destX = currX + step;
        if (
          (new Date()).getTime() - stamp > duration ||
          Math.abs(currX - finalX) <= Math.abs((currX + step) - finalX)
        ) {
          clearTimeout(elem.setXTransitionInterval)
          elem.style.MozTransform = "translateX(" + finalX + "px)";
          if (elem.setXTCB) {
            elem.setXTCB();
          }
        } else {
          elem.style.MozTransform = "translateX(" + destX + "px)";
          currX = destX;
        }
      }

      elem.setXTransitionInterval = setInterval(stepFn, frameRate);
    } else {
      elem.style.MozTransform = "translateX("+x+")";
    }

    if (elem.setXTCB) {
      Monocle.Events.deafen(elem, 'webkitTransitionEnd', elem.setXTCB);
      elem.setXTCB = null;
    }

    var sX = getX(elem);
    if (!duration || sX == parseInt(x)) {
      if (callback) { callback(); }
    } else {
      elem.setXTCB = function () {
        p.turnData.animating = false;
        if (p.nextAction) {
          p.nextAction();
        }
        if (callback) { callback(); }
      }
      Monocle.Events.listen(elem, 'webkitTransitionEnd', elem.setXTCB);
    }
  }

  function getX(elem) {
    if (typeof WebKitCSSMatrix == "object") {
      var matrix = window.getComputedStyle(elem).webkitTransform;
      matrix = new WebKitCSSMatrix(matrix);
      return matrix.m41;
    } else {
      var prop = elem.style.MozTransform;
      if (!prop || prop == "") { return 0; }
      return parseFloat((/translateX\((\-?.*)px\)/).exec(prop)[1]) || 0;
    }
  }

  /* NB: Jumps are always done by the hidden lower page. */

  function jumpIn(callback) {
    // Duration should be 0, but is set to 1 to address a 10.6 Safari bug.
    setX(lowerPage(), 0, { duration: 1 }, callback);
  }

  function jumpOut(callback) {
    setX(
      lowerPage(),
      0 - p.reader.properties.pageWidth,
      { duration: 0 },
      callback
    );
  }

  function jumpToCursor(cursorX, callback) {
    setX(
      lowerPage(),
      Math.min(0, cursorX - p.reader.properties.pageWidth),
      { duration: 0 },
      callback
    );
  }

  /* NB: Slides are always done by the visible upper page. */

  function slideIn() {
    var slideOpts = {
      duration: k.durations.SLIDE,
      timing: 'ease-in'
    };
    p.turnData.animating = true;
    setX(upperPage(), 0, slideOpts, completedTurn);
  }

  function slideOut() {
    var slideOpts = {
      duration: k.durations.SLIDE,
      timing: 'ease-in'
    };
    var callback = function () { flipPages(); completedTurn(); }
    p.turnData.animating = true;
    setX(upperPage(), 0 - p.reader.properties.pageWidth, slideOpts, callback);
  }

  function slideToCursor(cursorX, callback, duration) {
    setX(
      upperPage(),
      Math.min(0, cursorX - p.reader.properties.pageWidth),
      { duration: duration || k.durations.FOLLOW_CURSOR },
      callback
    );
  }

  // THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
  API.pageCount = p.pageCount;
  API.addPage = addPage;
  API.visiblePages = visiblePages;
  API.getPlace = getPlace;
  API.moveTo = moveTo;
  API.listenForInteraction = listenForInteraction;

  initialize();

  return API;
}

// Constants
Monocle.Flippers.Slider.DEFAULT_PANELS_CLASS = Monocle.Panels.TwoPane;
Monocle.Flippers.Slider.FORWARDS = 1;
Monocle.Flippers.Slider.BACKWARDS = -1;
Monocle.Flippers.Slider.durations = {
  SLIDE: 250,
  FOLLOW_CURSOR: 150,
  ANTI_FLICKER_DELAY: 0
}

Monocle.pieceLoaded('flippers/slider');
<|endoftext|>


<commit_before>// ==UserScript==
// @name              Pixiv自動ブックマークタグ付け
// @description       Pixivのブックマークタグ付けを半自動化してくれる
// @include           http://www.pixiv.net/bookmark_add.php?type=illust&illust_id=*
// @include           http://www.pixiv.net/member_illust.php?mode=medium&illust_id=*
// @run-at            document-end
// @version           0.2.1
// ==/UserScript==

// デフォルトルール
var defaultRuleStr = 'private R-18';

// タグ入力欄
var input = document.querySelector('#input_tag');

// 設定テキストを解析し、連想配列で返す
var parseRules = function(ruleStr) {
	var patternRule    = [];
	var patternAllRule = [];
	var privateRule    = [];
	var errors         = [];

	// 正規表現を表す文字列のリストから、正規表現のリストを作成
	var createRegExpFromStrAry = function(regexpStrAry, lineNumber) {
		var regexps = [];
		regexpStrAry.forEach(function(regexpStr) {
			try { regexps.push(new RegExp(regexpStr)); }
			catch (e) { errors.push({ lineNumber: lineNumber, message: ('RegularExpression Error:' + e.name + ':' + e.massage + ', Str:' + regexpStr) }); }
		});
		return regexps;
	};

	// strに完全一致する正規表現を生成
	var createRegExpPerfectMatch = function(str) {
		return new RegExp('^' + str.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&') + '$');
	};

	ruleStr.split('\n').forEach(function(line, i) {
		var parsed = line.split(/\s+/);
		var matchData;
		var rule;
		if ( parsed.length >= 3 && (matchData = parsed[0].match(/^match(|_all)$/i)) ) {  // 一致
			rule = { tag: parsed[1], regexps: parsed.slice(2).map(createRegExpPerfectMatch) };
		} else if ( parsed.length >= 3 && (matchData = parsed[0].match(/^pattern(|_all)$/i)) ) { // 正規表現
			var regexps = createRegExpFromStrAry(parsed.slice(2), i + 1);
			rule = { tag: parsed[1], regexps: regexps };
		} else if ( parsed.length >= 2 && parsed[0].match(/^private$/i) ) {                     // 非公開タグ
			privateRule.push.apply(privateRule, parsed.slice(1));
			return;
		} else if ( line.match(/^\s*$|^\s*#/) ) {                                               // 空行 or コメント行
			return;
		} else {
			errors.push({ lineNumber: (i+1), message: ('CommandError:Invalid Command or Too Few Arguments, Str:' + line) });
			return;
		}

		Array.prototype.push.call(matchData[1].length === 0 ? patternRule : patternAllRule, rule);
	});
	return { privateRule: privateRule, patternRule: patternRule, patternAllRule: patternAllRule, errors: errors };
};

// matchDataの配列を渡すと文中の~数字をそれで置き換える
var replaceWithMatch = function(input, matchData) {
	return input.split(/(~\d)/).map(function(str) {
		var match = str.match(/^~(\d)/);
		if(match) { return matchData[parseInt(match[1])] || ''; }
		return str;
	}).join('');
};

// 設定画面の生成・消去
var toggleSettingsView = function() {
	// すでに存在していたなら消去
	var settingsView = document.querySelector('#autotag-settings-view');
	if (settingsView) { settingsView.remove(); return; }

	// 保存済みデータの取得
	var ruleStr = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;

	// フォームの作成
	settingsView = document.createElement('form');
	settingsView.id = 'autotag-settings-view';
	settingsView.style.backgroundColor = '#FFFFFF';
	settingsView.style.marginTop    = '5px';
	settingsView.style.padding      = '10px 9px';
	settingsView.style.borderRadius = '5px';

	var templateStr  = '
タグ付けルール
<textarea id="autotag-settings-tagging-rule" cols="80" rows="10" style="height:auto;">{{:rule}}</textarea>
';
	settingsView.innerHTML = templateStr.replace('{{:rule}}', ruleStr);

	var buttonsParagraph = document.createElement('p');

	var saveButton = document.createElement('input');
	saveButton.type = 'submit';
	saveButton.className = '_button';
	saveButton.value = '保存';
	settingsView.onsubmit = function() {
		var ruleStr = document.querySelector('#autotag-settings-tagging-rule').value;
		var rule = parseRules(ruleStr);
		if (rule.errors.length === 0) {
			window.localStorage.pixivAutoTag_taggingRule = ruleStr;
			alert('保存しました');
		} else {
			alert(rule.errors.map(function(err) { return '[Error] line: ' + err.lineNumber + ', message: ' + err.message; }).join('\n'));
		}
		return false;
	};
	buttonsParagraph.appendChild(saveButton);

	var cancelButton = document.createElement('input');
	cancelButton.className = '_button';
	cancelButton.type = 'reset';
	cancelButton.value = 'キャンセル';
	// cancelButton.onclick = function() { document.querySelector('#autotag-settings-view').remove(); };
	buttonsParagraph.appendChild(cancelButton);

	settingsView.appendChild(buttonsParagraph);

	var settingsButton = document.querySelector('#autotag-settings-button');
	settingsButton.parentElement.insertBefore(settingsView, settingsButton.nextSibling);
};

// タグの自動追加関数
var autoTag = function() {
	var ruleText = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;
	var rule = parseRules(ruleText);

	// 作品タグとタグクラウドの取得
	var tagCloud = Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.tag-cloud-container > ul.list-items.tag-cloud > li')).map(function(item) { return item.textContent; });
	var tagsExist = Array.prototype.concat.apply([], Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.work-tags-container > div > ul span.tag')).map(function(item) { return item.textContent.replace(/^\*/, '').split('/'); }));

	// 非公開タグが含まれていた場合、自動で非公開に設定
	var privateButton = document.querySelector('div.submit-container > ul > li:nth-child(2) > label > input[type="radio"]');
	if (tagsExist.some(function(tag){ return rule.privateRule.indexOf(tag) !== -1; })) {
		privateButton.checked = true;
	}

	// ブックマークタグリストの生成
	if (input.value.length === 0) {
		// 作品タグとタグクラウドの共通タグを抽出
		var tagsFound = tagsExist.filter(function(existTag) { return tagCloud.some(function(cloudTag){ return existTag === cloudTag; }); });

		// 付与タグリストの生成
		var tagsAdded = [];
		tagsExist.forEach(function(tag) { // それぞれの作品タグが
			rule.patternRule.forEach(function(patternRule) { // それぞれのルール文に対し
				var matchData = [];
				var foundMatchFlag = patternRule.regexps.some(function(pattern) { // いずれかのパターンに一致するか
					return (matchData = tag.match(pattern));
				});
				if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
			});
		});

		rule.patternAllRule.forEach(function(patternRule) { // それぞれのルール文の
			var matchData = [];
			var foundMatchFlag = patternRule.regexps.every(function(pattern) { // すべてのパターンが
				return tagsExist.some(function(tag) { return (matchData = tag.match(pattern)); }); // いずれかの作品タグに一致するか？
			});
			if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
		});

		// タグを消去する
		tagsFound = tagsFound.filter(function(foundTag) { return tagsAdded.indexOf('-'+foundTag) === -1; });
		tagsAdded = tagsAdded.filter(function(tag) { return !tag.match(/^-/); });

		// 重複の削除
		var uniqueAry = tagsFound.concat(tagsAdded).filter(function(elem, i, ary) { return ary.indexOf(elem) === i; }).join(' ');

		// ブックマークタグを設定する
		input.value = uniqueAry;

		// タグのハイライトを表示させる
		var keyupEvent = document.createEvent('HTMLEvents');
		keyupEvent.initEvent('keyup', true, true);
		input.dispatchEvent(keyupEvent);

		// 自動補完が終わったら、背景を緑色にして補完がされたことを示す
		input.parentNode.style.backgroundColor = '#76B6E0';
	}
};

(function() {
	// 自動タグ付けの実行
	if (window.location.href.match(/member_illust/)) {
		var ul = document.querySelector('section.list-container.tag-container.work-tags-container > div > ul');
		var func = function(fn) { (ul.childNodes.length > 0) ? autoTag() : window.setTimeout(fn, 750, fn); };
		window.setTimeout(func, 1250, func);
	} else {
		window.setTimeout(autoTag, 750);
	}

	// 設定ボタンの生成
	var settingsButton = document.createElement('button');
	settingsButton.className = '_button';
	settingsButton.style.marginLeft = '1em';
	settingsButton.id = 'autotag-settings-button';
	settingsButton.textContent = 'タグ自動化設定';
	settingsButton.addEventListener('click', toggleSettingsView, false);

	var target = document.querySelector('section.list-container.tag-container.work-tags-container > div > h1');
	target.parentElement.insertBefore(settingsButton, target.nextSibling);

	// タグ付けボタンの生成
	var autoTagButton = document.createElement('button');
	autoTagButton.className = '_button';
	autoTagButton.style.marginLeft = '0.25em';
	autoTagButton.id = 'autotag-button';
	autoTagButton.textContent = '上書きタグ付け';
	autoTagButton.addEventListener('click', function() { input.value = ''; autoTag(); }, false);
	target.parentElement.insertBefore(autoTagButton, settingsButton.nextSibling);
})();
<commit_msg>bigfix: モーダルブックマークで、たまにタグ付けが上手く行えない問題を修正<commit_after>// ==UserScript==
// @name              Pixiv自動ブックマークタグ付け
// @description       Pixivのブックマークタグ付けを半自動化してくれる
// @include           http://www.pixiv.net/bookmark_add.php?type=illust&illust_id=*
// @include           http://www.pixiv.net/member_illust.php?mode=medium&illust_id=*
// @run-at            document-end
// @version           0.2.1
// ==/UserScript==

// デフォルトルール
var defaultRuleStr = 'private R-18';

// タグ入力欄
var input = document.querySelector('#input_tag');

// 設定テキストを解析し、連想配列で返す
var parseRules = function(ruleStr) {
	var patternRule    = [];
	var patternAllRule = [];
	var privateRule    = [];
	var errors         = [];

	// 正規表現を表す文字列のリストから、正規表現のリストを作成
	var createRegExpFromStrAry = function(regexpStrAry, lineNumber) {
		var regexps = [];
		regexpStrAry.forEach(function(regexpStr) {
			try { regexps.push(new RegExp(regexpStr)); }
			catch (e) { errors.push({ lineNumber: lineNumber, message: ('RegularExpression Error:' + e.name + ':' + e.massage + ', Str:' + regexpStr) }); }
		});
		return regexps;
	};

	// strに完全一致する正規表現を生成
	var createRegExpPerfectMatch = function(str) {
		return new RegExp('^' + str.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&') + '$');
	};

	ruleStr.split('\n').forEach(function(line, i) {
		var parsed = line.split(/\s+/);
		var matchData;
		var rule;
		if ( parsed.length >= 3 && (matchData = parsed[0].match(/^match(|_all)$/i)) ) {  // 一致
			rule = { tag: parsed[1], regexps: parsed.slice(2).map(createRegExpPerfectMatch) };
		} else if ( parsed.length >= 3 && (matchData = parsed[0].match(/^pattern(|_all)$/i)) ) { // 正規表現
			var regexps = createRegExpFromStrAry(parsed.slice(2), i + 1);
			rule = { tag: parsed[1], regexps: regexps };
		} else if ( parsed.length >= 2 && parsed[0].match(/^private$/i) ) {                     // 非公開タグ
			privateRule.push.apply(privateRule, parsed.slice(1));
			return;
		} else if ( line.match(/^\s*$|^\s*#/) ) {                                               // 空行 or コメント行
			return;
		} else {
			errors.push({ lineNumber: (i+1), message: ('CommandError:Invalid Command or Too Few Arguments, Str:' + line) });
			return;
		}

		Array.prototype.push.call(matchData[1].length === 0 ? patternRule : patternAllRule, rule);
	});
	return { privateRule: privateRule, patternRule: patternRule, patternAllRule: patternAllRule, errors: errors };
};

// matchDataの配列を渡すと文中の~数字をそれで置き換える
var replaceWithMatch = function(input, matchData) {
	return input.split(/(~\d)/).map(function(str) {
		var match = str.match(/^~(\d)/);
		if(match) { return matchData[parseInt(match[1])] || ''; }
		return str;
	}).join('');
};

// 設定画面の生成・消去
var toggleSettingsView = function() {
	// すでに存在していたなら消去
	var settingsView = document.querySelector('#autotag-settings-view');
	if (settingsView) { settingsView.remove(); return; }

	// 保存済みデータの取得
	var ruleStr = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;

	// フォームの作成
	settingsView = document.createElement('form');
	settingsView.id = 'autotag-settings-view';
	settingsView.style.backgroundColor = '#FFFFFF';
	settingsView.style.marginTop    = '5px';
	settingsView.style.padding      = '10px 9px';
	settingsView.style.borderRadius = '5px';

	var templateStr  = '
タグ付けルール
<textarea id="autotag-settings-tagging-rule" cols="80" rows="10" style="height:auto;">{{:rule}}</textarea>
';
	settingsView.innerHTML = templateStr.replace('{{:rule}}', ruleStr);

	var buttonsParagraph = document.createElement('p');

	var saveButton = document.createElement('input');
	saveButton.type = 'submit';
	saveButton.className = '_button';
	saveButton.value = '保存';
	settingsView.onsubmit = function() {
		var ruleStr = document.querySelector('#autotag-settings-tagging-rule').value;
		var rule = parseRules(ruleStr);
		if (rule.errors.length === 0) {
			window.localStorage.pixivAutoTag_taggingRule = ruleStr;
			alert('保存しました');
		} else {
			alert(rule.errors.map(function(err) { return '[Error] line: ' + err.lineNumber + ', message: ' + err.message; }).join('\n'));
		}
		return false;
	};
	buttonsParagraph.appendChild(saveButton);

	var cancelButton = document.createElement('input');
	cancelButton.className = '_button';
	cancelButton.type = 'reset';
	cancelButton.value = 'キャンセル';
	// cancelButton.onclick = function() { document.querySelector('#autotag-settings-view').remove(); };
	buttonsParagraph.appendChild(cancelButton);

	settingsView.appendChild(buttonsParagraph);

	var settingsButton = document.querySelector('#autotag-settings-button');
	settingsButton.parentElement.insertBefore(settingsView, settingsButton.nextSibling);
};

// タグの自動追加関数
var autoTag = function() {
	var ruleText = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;
	var rule = parseRules(ruleText);

	// 作品タグとタグクラウドの取得
	var tagCloud = Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.tag-cloud-container > ul.list-items.tag-cloud > li')).map(function(item) { return item.textContent; });
	var tagsExist = Array.prototype.concat.apply([], Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.work-tags-container > div > ul span.tag')).map(function(item) { return item.textContent.replace(/^\*/, '').split('/'); }));

	// 非公開タグが含まれていた場合、自動で非公開に設定
	var privateButton = document.querySelector('div.submit-container > ul > li:nth-child(2) > label > input[type="radio"]');
	if (tagsExist.some(function(tag){ return rule.privateRule.indexOf(tag) !== -1; })) {
		privateButton.checked = true;
	}

	// ブックマークタグリストの生成
	if (input.value.length === 0) {
		// 作品タグとタグクラウドの共通タグを抽出
		var tagsFound = tagsExist.filter(function(existTag) { return tagCloud.some(function(cloudTag){ return existTag === cloudTag; }); });

		// 付与タグリストの生成
		var tagsAdded = [];
		tagsExist.forEach(function(tag) { // それぞれの作品タグが
			rule.patternRule.forEach(function(patternRule) { // それぞれのルール文に対し
				var matchData = [];
				var foundMatchFlag = patternRule.regexps.some(function(pattern) { // いずれかのパターンに一致するか
					return (matchData = tag.match(pattern));
				});
				if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
			});
		});

		rule.patternAllRule.forEach(function(patternRule) { // それぞれのルール文の
			var matchData = [];
			var foundMatchFlag = patternRule.regexps.every(function(pattern) { // すべてのパターンが
				return tagsExist.some(function(tag) { return (matchData = tag.match(pattern)); }); // いずれかの作品タグに一致するか？
			});
			if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
		});

		// タグを消去する
		tagsFound = tagsFound.filter(function(foundTag) { return tagsAdded.indexOf('-'+foundTag) === -1; });
		tagsAdded = tagsAdded.filter(function(tag) { return !tag.match(/^-/); });

		// 重複の削除
		var uniqueAry = tagsFound.concat(tagsAdded).filter(function(elem, i, ary) { return ary.indexOf(elem) === i; }).join(' ');

		// ブックマークタグを設定する
		input.value = uniqueAry;

		// タグのハイライトを表示させる
		var keyupEvent = document.createEvent('HTMLEvents');
		keyupEvent.initEvent('keyup', true, true);
		input.dispatchEvent(keyupEvent);

		// タグ付けが終わったら、背景を緑色にして補完がされたことを示す
		input.parentNode.style.backgroundColor = '#76B6E0';
		// それと入力欄にフォーカスする
		input.focus();
	}
};

(function() {
	// 自動タグ付けの実行
	if (window.location.href.match(/member_illust/)) {
		var ul = document.querySelector('section.list-container.tag-container.work-tags-container > div > ul');
		var func = function(fn) { (ul.childNodes.length > 0) ? window.setTimeout(autoTag, 750) : window.setTimeout(fn, 750, fn); };
		window.setTimeout(func, 1250, func);
	} else {
		window.setTimeout(autoTag, 750);
	}

	// 設定ボタンの生成
	var settingsButton = document.createElement('button');
	settingsButton.className = '_button';
	settingsButton.style.marginLeft = '1em';
	settingsButton.id = 'autotag-settings-button';
	settingsButton.textContent = 'タグ自動化設定';
	settingsButton.addEventListener('click', toggleSettingsView, false);

	var target = document.querySelector('section.list-container.tag-container.work-tags-container > div > h1');
	target.parentElement.insertBefore(settingsButton, target.nextSibling);

	// タグ付けボタンの生成
	var autoTagButton = document.createElement('button');
	autoTagButton.className = '_button';
	autoTagButton.style.marginLeft = '0.25em';
	autoTagButton.id = 'autotag-button';
	autoTagButton.textContent = '上書きタグ付け';
	autoTagButton.addEventListener('click', function() { input.value = ''; autoTag(); }, false);
	target.parentElement.insertBefore(autoTagButton, settingsButton.nextSibling);
})();
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Stars for Basecamp Classic
// @description Adds "important" stars to Basecamp Classic todos if they contain an asterisk (*)
// @match       https://*.basecamphq.com/*
// @include     https://*.basecamphq.com/*
// @version     0.1
// @author      Mike Robinson
// @homepage    http://twitter.com/akamike
// ==/UserScript==
(function(){
  var doc = document,
      body = doc.getElementsByTagName('body')[0],
      style = doc.createElement('style');

  // Add custom styles
  style.textContent = [
    '.todo_star { color:#fff; display:inline-block; font-size:3em; line-height:8%; margin-right:3px; background-color:orange; font-family:Helvetica,Arial; padding:0.46em 0.1em 0; vertical-align:middle; }',
    '.hot { background-color:darkOrange; }'
  ].join('\n');

  doc.getElementsByTagName('head')[0].appendChild(style);

  // Format markers
  var todos = body.querySelectorAll('.todolist .content, .item .item_content, .items_wrapper .content span, .page_header .content .item, .event .item span');

  for (var i = 0; i < todos.length; i++) {
    var todo = todos[i], t;

    // matches [HOT] and [WARM] for legacy Enhance! tasks
    if (t = todo.textContent.match(/(\[HOT\]|\[WARM\]|\*)/g)) {
      var p = doc.createElement('span');
          p.textContent = "*";
          p.className = 'todo_star';

      // Subtle difference
      if (t[0] == '[HOT]') {
        p.className += ' hot';
      }

      todo.innerHTML = todo.innerHTML.replace(t[0], '');
      todo.insertBefore(p, todo.firstChild);
    }
  }
})();
<commit_msg>added [COLD] blue star<commit_after>// ==UserScript==
// @name        Stars for Basecamp Classic
// @description Adds "important" stars to Basecamp Classic todos if they contain an asterisk (*)
// @match       https://*.basecamphq.com/*
// @include     https://*.basecamphq.com/*
// @version     0.1
// @author      Mike Robinson
// @homepage    http://twitter.com/akamike
// ==/UserScript==
(function(){
  var doc = document,
      body = doc.getElementsByTagName('body')[0],
      style = doc.createElement('style');

  // Add custom styles
  style.textContent = [
    '.todo_star { color:#fff; display:inline-block; font-size:3em; line-height:8%; margin-right:3px; background-color:orange; font-family:Helvetica,Arial; padding:0.46em 0.1em 0; vertical-align:middle; }',
    '.hot { background-color:darkOrange; }',
    '.cold { background-color:#C3EEFF; }'
  ].join('\n');

  doc.getElementsByTagName('head')[0].appendChild(style);

  // Format markers
  var todos = body.querySelectorAll('.todolist .content, .item .item_content, .items_wrapper .content span, .page_header .content .item, .event .item span');

  for (var i = 0; i < todos.length; i++) {
    var todo = todos[i], t;

    // matches [HOT] and [WARM] and [COLD] for legacy Enhance! tasks
    if (t = todo.textContent.match(/(\[HOT\]|\[WARM\]|\[COLD\]|\*)/g)) {
      var p = doc.createElement('span');
          p.textContent = "*";
          p.className = 'todo_star';

      // Subtle difference
      if (t[0] == '[HOT]') {
        p.className += ' hot';
      } else if (t[0] == '[COLD]') {
        p.className += ' cold';
      }

      todo.innerHTML = todo.innerHTML.replace(t[0], '');
      todo.insertBefore(p, todo.firstChild);
    }
  }
})();
<|endoftext|>


<commit_before>'use strict';

function merge(arr1, arr2) {
  var a = [], arr1Index = 0, arr2Index = 0;
  while(arr1Index < arr1.length && arr2Index < arr2.length) {
    if (arr1[arr1Index] < arr2[arr2Index]) {
      a.push(arr1[arr1Index]);
      arr1Index++;
    }
    else {
      a.push(arr2[arr2Index]);
      arr2Index++;
    }
  }
  while (arr1Index < arr1.length) {
    a.push(arr1[arr1Index]);
    arr1Index++;
  }
  while (arr2Index < arr2.length) {
    a.push(arr2[arr2Index]);
    arr2Index++;
  }
  return a;
}

module.exports = {
  mergeSort: function mergeSort(array) {
    if (array.length <= 1) {
      return array;
    }
    var splitIndex = Math.floor(array.length / 2);
    var arr1 = array.slice(0, splitIndex);
    var arr2 = array.slice(splitIndex, array.length);
    return merge(mergeSort(arr1), mergeSort(arr2));
  }
};
<commit_msg>the cleaner mergesort<commit_after>'use strict';

function merge(arr1, arr2) {
  var a = [], i1 = 0, i2 = 0;
  while(i1 < arr1.length && i2 < arr2.length) {
    if (arr1[i1] < arr2[i2]) {
      a.push(arr1[i1]);
      i1++;
    }
    else {
      a.push(arr2[i2]);
      i2++;
    }
  }
  return a.concat(arr1.slice(i1, arr1.length)).concat(arr2.slice(i2, arr2.length));
}

module.exports = {
  mergeSort: function mergeSort(array) {
    if (array.length <= 1) {
      return array;
    }
    var splitIndex = Math.floor(array.length / 2);
    var arr1 = array.slice(0, splitIndex);
    var arr2 = array.slice(splitIndex, array.length);
    return merge(mergeSort(arr1), mergeSort(arr2));
  }
};
<|endoftext|>


<commit_before>exports.voice = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();

	tropo.say("<speak><prosody rate='80%'>Welcome to con-needs.</prosody></speak>");

  	// Demonstrates how to use the base Tropo action classes.
  	var say = new Say("<speak><prosody rate='70%'>to SEARCH press 1.......... to CONNECT press 2.......... to check your BALANCE press 3.........</prosody></speak>", null, null, null, null, null);

  	var choices = new Choices("[1 DIGIT]", "dtmf", "#");

  	// Action classes can be passes as parameters to TropoWebAPI class methods.
  	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/processChoices", true);
	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.processChoices = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var actionValue = req.body.result.actions.value;
	//console.log(actionValue);
	switch(actionValue) {
		case '1' :
			tropo.say("<speak><prosody rate='60%'>You selected to search. please wait...</prosody></speak>");
			tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/askSearch", true);
			res.send(tropowebapi.TropoJSON(tropo));
		break;
		case '2' :
			tropo.say("<speak><prosody rate='60%'>You selected to connect. please wait...</prosody></speak>");
			tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/askConnect", true);
			res.send(tropowebapi.TropoJSON(tropo));
		break;
		case '3' :

		break;
	}
}

exports.askConnect = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var say = new Say("<speak><prosody rate='70%'>Please enter the I..D..</prosody></speak>", null, null, null, null, null);

	var choices = new Choices("[1 DIGIT]", "dtmf", "#");
	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/doConnect", true);
  	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.askSearch = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var say = new Say("<speak><prosody rate='70%'>What is the keyword you are searching?</prosody></speak>", null, null, null, null, null);

	var choices = new Choices("tutor, teacher, lawyer, nurse");
	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/doSearch", true);
  	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.doConnect = function(req, res) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var actionValue = req.body.result.actions.value;
	//var actionValue = 'teacher';

	Q.ninvoke(User, 'get', actionValue)
	.then(function(user) {
		var arrIds = [];
		arrIds.push(user.id);
		doCall(req, res, arrIds);
	});
}

exports.doSearch = function(req, res) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var actionValue = req.body.result.actions.value;
	//var actionValue = 'teacher';

	Q.ninvoke(User, 'searchProfessional', actionValue)
	.then(function(users) {
		var searchIds = [];
		for (var i in users) {
			searchIds.push(users[i].id);
		}

		doSearching(req, res, searchIds);
	});
}

function doSearching(req, res, searchIds) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	Q.ninvoke(User, 'get', searchIds[0])
	.then(function(user) {
		var say = new Say("<speak><prosody rate='70%'>"+ user.short_desc +"</prosody></speak>", null, null, null, null, null);

		var choices = new Choices("call, next, end");
		var arrayString = searchIds.join(',');

		tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
	  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/processSearch?id="+ arrayString, true);
	  	res.send(tropowebapi.TropoJSON(tropo));
	})
	.fail(function() {
		tropo.hangup();
		res.send(tropowebapi.TropoJSON(tropo));
	});

}

function doCall(req, res, searchIds) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	console.log(searchIds[0]);
	Q.ninvoke(User, 'get', parseInt(searchIds[0]))
	.then(function(user) {
		console.log(user);
		tropo.say("Please hold while we transfer your superman call!");
		var on = [
		   { "event":"ring",
		      "say":{
		         "value":"http://www.phono.com/audio/holdmusic.mp3"
		      },
		   }
		];

		var choices = {
		   "terminator": "#"
		}

		tropo.transfer([user.number, "sip:21581127@sip.tropo.com"], null, choices, null, null, null, on, null, null);

	 	res.send(tropowebapi.TropoJSON(tropo));
	})
	.fail(function() {
		tropo.hangup();
		res.send(tropowebapi.TropoJSON(tropo));
	});

}

exports.processSearch = function(req, res) {
	var actionValue = req.body.result.actions.value;

	switch(actionValue) {
		case 'next':
			var ids = req.query.id;
			var arrayIds = ids.split(',');
			arrayIds.splice(0,1);
			doSearching(req, res, arrayIds);
		break;
		case 'call':
			var ids = req.query.id;
			var arrayIds = ids.split(',');
			console.log(arrayIds);
			doCall(req, res, arrayIds);
		break;
		case 'end':
			var tropowebapi = require('tropo-webapi');
			var tropo = new tropowebapi.TropoWebAPI();
			tropo.hangup();
			res.send(tropowebapi.TropoJSON(tropo));
		break;
	}

}

exports.hangup = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}

exports.incomplete = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}

exports.error = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}<commit_msg>update connect voice<commit_after>exports.voice = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();

	tropo.say("<speak><prosody rate='80%'>Welcome to con-needs.</prosody></speak>");

  	// Demonstrates how to use the base Tropo action classes.
  	var say = new Say("<speak><prosody rate='70%'>to SEARCH press 1.......... to CONNECT press 2.......... to check your BALANCE press 3.........</prosody></speak>", null, null, null, null, null);

  	var choices = new Choices("[1 DIGIT]", "dtmf", "#");

  	// Action classes can be passes as parameters to TropoWebAPI class methods.
  	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/processChoices", true);
	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.processChoices = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var actionValue = req.body.result.actions.value;
	//console.log(actionValue);
	switch(actionValue) {
		case '1' :
			tropo.say("<speak><prosody rate='60%'>You selected to search... please wait...</prosody></speak>");
			tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/askSearch", true);
			res.send(tropowebapi.TropoJSON(tropo));
		break;
		case '2' :
			tropo.say("<speak><prosody rate='60%'>You selected to connect... please wait...</prosody></speak>");
			tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/askConnect", true);
			res.send(tropowebapi.TropoJSON(tropo));
		break;
		case '3' :

		break;
	}
}

exports.askConnect = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var say = new Say("<speak><prosody rate='70%'>Please enter the I..D..</prosody></speak>", null, null, null, null, null);

	//@TODO this only the limit update this in future
	var choices = new Choices("[1 DIGIT]", "dtmf", "#");
	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/doConnect", true);
  	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.askSearch = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	var say = new Say("<speak><prosody rate='70%'>What is the keyword you are searching?</prosody></speak>", null, null, null, null, null);

	var choices = new Choices("tutor, teacher, lawyer, nurse");
	tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/doSearch", true);
  	tropo.on("hangup", null, "http://coneeds.98labs.com:8080/globe/voice/hangup", true);
  	res.send(tropowebapi.TropoJSON(tropo));
}

exports.doConnect = function(req, res) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var actionValue = req.body.result.actions.value;

	Q.ninvoke(User, 'get', actionValue)
	.then(function(user) {
		var arrIds = [];
		arrIds.push(user.id);
		doCall(req, res, arrIds);
	});
}

exports.doSearch = function(req, res) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var actionValue = req.body.result.actions.value;
	//var actionValue = 'teacher';

	Q.ninvoke(User, 'searchProfessional', actionValue)
	.then(function(users) {
		var searchIds = [];
		for (var i in users) {
			searchIds.push(users[i].id);
		}

		doSearching(req, res, searchIds);
	});
}

function doSearching(req, res, searchIds) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	Q.ninvoke(User, 'get', searchIds[0])
	.then(function(user) {
		var say = new Say("<speak><prosody rate='70%'>"+ user.short_desc +"</prosody></speak>", null, null, null, null, null);

		var choices = new Choices("call, next, end");
		var arrayString = searchIds.join(',');

		tropo.ask(choices, 5, false, null, "foo", null, true, say, 5, null);
	  	tropo.on("continue", null, "http://coneeds.98labs.com:8080/globe/voice/processSearch?id="+ arrayString, true);
	  	res.send(tropowebapi.TropoJSON(tropo));
	})
	.fail(function() {
		tropo.hangup();
		res.send(tropowebapi.TropoJSON(tropo));
	});

}

function doCall(req, res, searchIds) {
	var Q = require('q');
	var path = require('path');
	var modelPath =  path.resolve('./', 'models/orm');
	var User = require(modelPath + '/user')(req.db);

	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	console.log(searchIds[0]);
	Q.ninvoke(User, 'get', parseInt(searchIds[0]))
	.then(function(user) {
		console.log(user);
		tropo.say("Please hold while we transfer your superman call!");
		var on = [
		   { "event":"ring",
		      "say":{
		         "value":"http://www.phono.com/audio/holdmusic.mp3"
		      },
		   }
		];

		var choices = {
		   "terminator": "#"
		}

		tropo.transfer([user.number, "sip:21581127@sip.tropo.com"], null, choices, null, null, null, on, null, null);

	 	res.send(tropowebapi.TropoJSON(tropo));
	})
	.fail(function() {
		tropo.hangup();
		res.send(tropowebapi.TropoJSON(tropo));
	});

}

exports.processSearch = function(req, res) {
	var actionValue = req.body.result.actions.value;

	switch(actionValue) {
		case 'next':
			var ids = req.query.id;
			var arrayIds = ids.split(',');
			arrayIds.splice(0,1);
			doSearching(req, res, arrayIds);
		break;
		case 'call':
			var ids = req.query.id;
			var arrayIds = ids.split(',');
			console.log(arrayIds);
			doCall(req, res, arrayIds);
		break;
		case 'end':
			var tropowebapi = require('tropo-webapi');
			var tropo = new tropowebapi.TropoWebAPI();
			tropo.hangup();
			res.send(tropowebapi.TropoJSON(tropo));
		break;
	}

}

exports.hangup = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}

exports.incomplete = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}

exports.error = function(req, res) {
	var tropowebapi = require('tropo-webapi');
	var tropo = new tropowebapi.TropoWebAPI();
	tropo.say("<speak><prosody rate='70%'>Thank you for calling!</prosody></speak>");
	res.send(tropowebapi.TropoJSON(tropo));
}<|endoftext|>


<commit_before>$(document).ready(function(){
    $("#defaultdemo").click(function() {
        simplePopup({
            'pop-title':'Pop Demo',
            'pop-body':'This is a demonstration of a simple popup. The point is to present information to the user and provide a way to dismiss the popup.',
            'btn-text':'Dismiss',
            'auto-break': 25,
        });
    });
    $("#customdemo").click(function() {
        simplePopup({
            'shrink-in':true,
            'slide-in':true,
            'slide-out':true,
            'btn-style':'success',
            'round-corners':true,
            'head-align':'center',
            'body-align':'center',
            'foot-align':'right',
            'header-bg-shade':true,
            'footer-bg-shade':false,
            'dragable':true,
            'auto-break': 25,
            'pop-title':'Pop Demo',
            'pop-body':'This is a demonstration of a customized popup. Notice the differences in style and presentation.',
            'btn-text':'Dismiss',
            'click-fn':sampleExitTask
        });
    });
});

function sampleExitTask() {
    $("#exitTaskOutput").html("Action on Popup Dismissal.
This event fired at the time the popup was dismissed based on the function assigned to the 'click-fn' option.");
    $("#exitTaskOutput").css({padding: "4px", background: "#ff8080"});
    $("#exitTaskOutput").fadeIn();
    setTimeout(function(){
        $("#exitTaskOutput").fadeOut();
    },6000);
}
<commit_msg>Update project.js<commit_after>$(document).ready(function(){
    $("#defaultdemo").click(function() {
        simplePopup({
            'pop-title':'Pop Demo',
            'pop-body':'This is a demonstration of a simple popup. The point is to present information to the user and provide a way to dismiss the popup.',
            'btn-text':'Dismiss',
            'body-align':'left',
            'auto-break': 35,
        });
    });
    $("#customdemo").click(function() {
        simplePopup({
            'shrink-in':true,
            'slide-in':true,
            'slide-out':true,
            'btn-style':'success',
            'round-corners':true,
            'head-align':'center',
            'body-align':'center',
            'foot-align':'right',
            'header-bg-shade':true,
            'footer-bg-shade':false,
            'dragable':true,
            'auto-break': 35,
            'pop-title':'Pop Demo',
            'pop-body':'This is a demonstration of a customized popup. Notice the differences in style and presentation.',
            'btn-text':'Dismiss',
            'click-fn':sampleExitTask
        });
    });
});

function sampleExitTask() {
    $("#exitTaskOutput").html("Action on Popup Dismissal.
This event fired at the time the popup was dismissed based on the function assigned to the 'click-fn' option.");
    $("#exitTaskOutput").css({padding: "4px", background: "#ff8080"});
    $("#exitTaskOutput").fadeIn();
    setTimeout(function(){
        $("#exitTaskOutput").fadeOut();
    },6000);
}
<|endoftext|>


<commit_before>import * as p from 'path';
import * as fs from 'fs';
import { rollup } from 'rollup';
import buble from 'rollup-plugin-buble';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import uglify from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import pack from '../package.json';
import commonjs from 'rollup-plugin-commonjs';
import typescript from 'rollup-plugin-typescript';

const pkg = JSON.parse(fs.readFileSync('./package.json'));
const external = Object.keys(pkg.peerDependencies || {}).concat(Object.keys(pkg.dependencies || {}));

const plugins = [
	typescript({
		typescript: require('typescript')
	}),
	buble({
		objectAssign: 'Object.assign'
	}),
	nodeResolve({
		jsnext: true,
		main: true,
		skip: external
	}),
	commonjs({
		include: 'node_modules/**',
		exclude: ['node_modules/symbol-observable/**', '**/*.css']
	})
];

if (process.env.NODE_ENV === 'production') {
	plugins.push(
		uglify({
			warnings: false,
			compress: {
				screw_ie8: true,
				dead_code: true,
				unused: true,
				drop_debugger: true, //
				booleans: true // various optimizations for boolean context, for example !!a ? b : c → a ? b : c
			},
			mangle: {
				screw_ie8: true
			}
		})
	);
	plugins.push(
		replace({
			VERSION: pack.version,
			'process.env.NODE_ENV': JSON.stringify('production')
		})
	)
} else {
	plugins.push(
		replace({
			VERSION: pack.version,
			'process.env.NODE_ENV': JSON.stringify('development')
		})
	)
}

// Filesize plugin needs to be last to report correct filesizes when minified
plugins.push(filesize());

const bundles = [
	{
		moduleGlobal: 'Inferno',
		moduleName: 'inferno',
		moduleEntry: 'packages/inferno/src/index.js',
		path: 'packages/inferno/'
	},
	{
		moduleGlobal: 'InfernoDOM',
		moduleName: 'inferno-dom',
		moduleEntry: 'packages/inferno-dom/src/index.js',
		path: 'packages/inferno-dom/'
	},
	{
		moduleGlobal: 'InfernoServer',
		moduleName: 'inferno-server',
		moduleEntry: 'packages/inferno-server/src/index.js',
		path: 'packages/inferno-server/'
	},
	{
		moduleGlobal: 'InfernoComponent',
		moduleName: 'inferno-component',
		moduleEntry: 'packages/inferno-component/src/index.js',
		path: 'packages/inferno-component/'
	},
	{
		moduleGlobal: 'InfernoTestUtils',
		moduleName: 'inferno-test-utils',
		moduleEntry: 'packages/inferno-test-utils/src/index.js',
		path: 'packages/inferno-test-utils/'
	},
	{
		moduleGlobal: 'InfernoCreateElement',
		moduleName: 'inferno-create-element',
		moduleEntry: 'packages/inferno-create-element/src/index.js',
		path: 'packages/inferno-create-element/'
	},
	{
		moduleGlobal: 'InfernoCompat',
		moduleName: 'inferno-compat',
		moduleEntry: 'packages/inferno-compat/src/index.js',
		path: 'packages/inferno-compat/'
	},
	{
		moduleGlobal: 'InfernoRouter',
		moduleName: 'inferno-router',
		moduleEntry: 'packages/inferno-router/src/index.js',
		path: 'packages/inferno-router/'
	},
	{
		moduleGlobal: 'InfernoCreateClass',
		moduleName: 'inferno-create-class',
		moduleEntry: 'packages/inferno-create-class/src/index.js',
		path: 'packages/inferno-create-class/'
	},
	{
		moduleGlobal: 'InfernoRedux',
		moduleName: 'inferno-redux',
		moduleEntry: 'packages/inferno-redux/src/index.js',
		path: 'packages/inferno-redux/'
	},
	{
		moduleGlobal: 'InfernoHyperscript',
		moduleName: 'inferno-hyperscript',
		moduleEntry: 'packages/inferno-hyperscript/src/index.js',
		path: 'packages/inferno-hyperscript/'
	}
];

function createBundle({ moduleGlobal, moduleName, moduleEntry }, path) {
	const copyright =
		'/*!\n' +
		' * ' + moduleName + ' v' + pack.version + '\n' +
		' * (c) ' + new Date().getFullYear() + ' ' + pack.author.name + '\n' +
		' * Released under the ' + pack.license + ' License.\n' +
		' */';
	const entry = p.resolve(moduleEntry);
	const dest  = p.resolve(`${ path }${ moduleName }.${ process.env.NODE_ENV === 'production' ? 'min.js' : 'js' }`);

	const bundleConfig = {
		dest,
		format: 'umd',
		moduleName: moduleGlobal,
		globals: {
			moduleGlobal: moduleGlobal
		},
		banner: copyright,
		sourceMap: false
	};

	return rollup({ entry, plugins }).then(({ write }) => write(bundleConfig)).catch(err => {
		console.log(err);
	});
}

Promise.all(bundles.map(bundle => createBundle(bundle, 'packages/inferno/dist/')));
<commit_msg>Add inferno-mobx + Give proper credit to package creators<commit_after>import * as p from 'path';
import * as fs from 'fs';
import { rollup } from 'rollup';
import buble from 'rollup-plugin-buble';
import nodeResolve from 'rollup-plugin-node-resolve';
import replace from 'rollup-plugin-replace';
import uglify from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import pack from '../package.json';
import commonjs from 'rollup-plugin-commonjs';
import typescript from 'rollup-plugin-typescript';

const pkg = JSON.parse(fs.readFileSync('./package.json'));
const external = Object.keys(pkg.peerDependencies || {}).concat(Object.keys(pkg.dependencies || {}));

const plugins = [
	typescript({
		typescript: require('typescript')
	}),
	buble({
		objectAssign: 'Object.assign'
	}),
	nodeResolve({
		jsnext: true,
		main: true,
		skip: external
	}),
	commonjs({
		include: 'node_modules/**',
		exclude: ['node_modules/symbol-observable/**', '**/*.css']
	})
];

if (process.env.NODE_ENV === 'production') {
	plugins.push(
		uglify({
			warnings: false,
			compress: {
				screw_ie8: true,
				dead_code: true,
				unused: true,
				drop_debugger: true, //
				booleans: true // various optimizations for boolean context, for example !!a ? b : c → a ? b : c
			},
			mangle: {
				screw_ie8: true
			}
		})
	);
	plugins.push(
		replace({
			VERSION: pack.version,
			'process.env.NODE_ENV': JSON.stringify('production')
		})
	)
} else {
	plugins.push(
		replace({
			VERSION: pack.version,
			'process.env.NODE_ENV': JSON.stringify('development')
		})
	)
}

// Filesize plugin needs to be last to report correct filesizes when minified
plugins.push(filesize());

const bundles = [
	{
		moduleGlobal: 'Inferno',
		moduleName: 'inferno',
		moduleEntry: 'packages/inferno/src/index.js',
		path: 'packages/inferno/'
	},
	{
		moduleGlobal: 'InfernoDOM',
		moduleName: 'inferno-dom',
		moduleEntry: 'packages/inferno-dom/src/index.js',
		path: 'packages/inferno-dom/'
	},
	{
		moduleGlobal: 'InfernoServer',
		moduleName: 'inferno-server',
		moduleEntry: 'packages/inferno-server/src/index.js',
		path: 'packages/inferno-server/'
	},
	{
		moduleGlobal: 'InfernoComponent',
		moduleName: 'inferno-component',
		moduleEntry: 'packages/inferno-component/src/index.js',
		path: 'packages/inferno-component/'
	},
	{
		moduleGlobal: 'InfernoTestUtils',
		moduleName: 'inferno-test-utils',
		moduleEntry: 'packages/inferno-test-utils/src/index.js',
		path: 'packages/inferno-test-utils/'
	},
	{
		moduleGlobal: 'InfernoCreateElement',
		moduleName: 'inferno-create-element',
		moduleEntry: 'packages/inferno-create-element/src/index.js',
		path: 'packages/inferno-create-element/'
	},
	{
		moduleGlobal: 'InfernoCompat',
		moduleName: 'inferno-compat',
		moduleEntry: 'packages/inferno-compat/src/index.js',
		path: 'packages/inferno-compat/'
	},
	{
		moduleGlobal: 'InfernoRouter',
		moduleName: 'inferno-router',
		moduleEntry: 'packages/inferno-router/src/index.js',
		path: 'packages/inferno-router/'
	},
	{
		moduleGlobal: 'InfernoCreateClass',
		moduleName: 'inferno-create-class',
		moduleEntry: 'packages/inferno-create-class/src/index.js',
		path: 'packages/inferno-create-class/'
	},
	{
		moduleGlobal: 'InfernoRedux',
		moduleName: 'inferno-redux',
		moduleEntry: 'packages/inferno-redux/src/index.js',
		path: 'packages/inferno-redux/'
	},
	{
		moduleGlobal: 'InfernoMobx',
		moduleName: 'inferno-mobx',
		moduleEntry: 'packages/inferno-mobx/src/index.js',
		path: 'packages/inferno-mobx/'
	},
	{
		moduleGlobal: 'InfernoHyperscript',
		moduleName: 'inferno-hyperscript',
		moduleEntry: 'packages/inferno-hyperscript/src/index.js',
		path: 'packages/inferno-hyperscript/'
	}
];

function createBundle({ moduleGlobal, moduleName, moduleEntry }, path) {
	const pkg = getPackageJSON(moduleName);
	const copyright =
		'/*!\n' +
		' * ' + moduleName + ' v' + pkg.version + '\n' +
		' * (c) ' + new Date().getFullYear() + ' ' + pkg.author.name + '\n' +
		' * Released under the ' + pkg.license + ' License.\n' +
		' */';
	const entry = p.resolve(moduleEntry);
	const dest  = p.resolve(`${ path }${ moduleName }.${ process.env.NODE_ENV === 'production' ? 'min.js' : 'js' }`);

	const bundleConfig = {
		dest,
		format: 'umd',
		moduleName: moduleGlobal,
		globals: {
			moduleGlobal: moduleGlobal
		},
		banner: copyright,
		sourceMap: false
	};

	return rollup({ entry, plugins }).then(({ write }) => write(bundleConfig)).catch(err => {
		console.log(err);
	});
}

function getPackageJSON(moduleName, defaultPackage) {
	try {
		return require('../packages/' + moduleName + '/package.json');
	} catch(e) {
		return defaultPackage
	}
}

Promise.all(bundles.map(bundle => createBundle(bundle, 'packages/inferno/dist/')));
<|endoftext|>


<commit_before>module.exports = {
	output: 'dist/*',
	cssLibs: [],
	sass: [
		'app/**/*.scss'
	],
	html: [
		'app/index.html',
		'app/**/*.html'
	],
	images: [
		'app/images/**/*.{jpg,gif,png,svg,ico}'
	],
	assets: [
		'app/assets/**/*'
	],
	fixtures: [
		'app/fixtures/**/*'
	],
	scripts: [
		'app/app.js',
		'app/services/**/*.js',
		'app/filters/**/*.js',
		'app/components/**/*.js',
		'app/controllers/**/*.js'
	],
	scriptsSkip: [
		'!app/**/*.test.js',
		'!app/**/*.mock.js'
	],
	libs: [
	    'node_modules/fg-loadcss/src/loadCSS.js',
	    'node_modules/fg-loadcss/src/cssrelpreload.js',
		'node_modules/angular/angular.min.js',
		'node_modules/angular-ui-router/release/angular-ui-router.min.js'
	],
	docLibs: [
		'node_modules/angular-animate/angular-animate.js',
		'node_modules/marked/lib/marked.js'
	],
	testLibs: [
		'node_modules/angular-mocks/angular-mocks.js',
		'node_modules/babel-polyfill/dist/polyfill.min.js'
	]
};
<commit_msg>Add factories and constants to the gulp config<commit_after>module.exports = {
	output: 'dist/*',
	cssLibs: [],
	sass: [
		'app/**/*.scss'
	],
	html: [
		'app/index.html',
		'app/**/*.html'
	],
	images: [
		'app/images/**/*.{jpg,gif,png,svg,ico}'
	],
	assets: [
		'app/assets/**/*'
	],
	fixtures: [
		'app/fixtures/**/*'
	],
	scripts: [
		'app/app.js',
		'app/services/**/*.js',
		'app/filters/**/*.js',
		'app/components/**/*.js',
		'app/factories/**/*.js',
		'app/constants/**/*.js',
		'app/controllers/**/*.js'
	],
	scriptsSkip: [
		'!app/**/*.test.js',
		'!app/**/*.mock.js'
	],
	libs: [
	    'node_modules/fg-loadcss/src/loadCSS.js',
	    'node_modules/fg-loadcss/src/cssrelpreload.js',
		'node_modules/angular/angular.min.js',
		'node_modules/angular-ui-router/release/angular-ui-router.min.js'
	],
	docLibs: [
		'node_modules/angular-animate/angular-animate.js',
		'node_modules/marked/lib/marked.js'
	],
	testLibs: [
		'node_modules/angular-mocks/angular-mocks.js',
		'node_modules/babel-polyfill/dist/polyfill.min.js'
	]
};
<|endoftext|>


<commit_before>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['require', 'module'], function (require, module) {

    var EncryptionHandler = function (packageMetadata, publicationFetcher) {
        var self = this;

        var _uid = packageMetadata.id;
        var _encryptionDom;
        var _encryptionHash;
        var _isEncryptionSpecified = false;

        var ENCRYPTION_METHODS = {
            'http://www.idpf.org/2008/embedding': embeddedFontDeobfuscateIdpf,
            'http://ns.adobe.com/pdf/enc#RC': embeddedFontDeobfuscateAdobe
        };

        // INTERNAL FUNCTIONS

        function blob2BinArray(blob, callback) {
            var fileReader = new FileReader();
            fileReader.onload = function () {
                var arrayBuffer = this.result;
                callback(new Uint8Array(arrayBuffer));
            };
            fileReader.readAsArrayBuffer(blob);
        }

        function xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, xorKey, callback) {
            var obfuscatedPrefixBlob = obfuscatedResourceBlob.slice(0, prefixLength);
            blob2BinArray(obfuscatedPrefixBlob, function (bytes) {
                var masklen = xorKey.length;
                for (var i = 0; i < prefixLength; i++) {
                    bytes[i] = bytes[i] ^ (xorKey[i % masklen]);
                }
                var deobfuscatedPrefixBlob = new Blob([bytes], { type: obfuscatedResourceBlob.type });
                var remainderBlob = obfuscatedResourceBlob.slice(prefixLength);
                var deobfuscatedBlob = new Blob([deobfuscatedPrefixBlob, remainderBlob],
                    { type: obfuscatedResourceBlob.type });

                callback(deobfuscatedBlob);
            });
        }

        function embeddedFontDeobfuscateIdpf(obfuscatedResourceBlob, callback) {
            var hashedUid = window.Crypto.SHA1(unescape(encodeURIComponent(_uid.trim())), { asBytes: true });
            var prefixLength = 1040;
            // Shamelessly copied from
            // https://github.com/readium/readium-chrome-extension/blob/26d4b0cafd254cfa93bf7f6225887b83052642e0/scripts/models/path_resolver.js#L102 :
            xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, hashedUid, callback);
        }

        function urnUuidToByteArray(id) {
            var uuidRegexp = /(urn:uuid:)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/i;
            var matchResults = uuidRegexp.exec(id);
            var rawUuid = matchResults[2] + matchResults[3] + matchResults[4] + matchResults[5] + matchResults[6];
            if (!rawUuid || rawUuid.length != 32) {
                console.error('Bad UUID format for ID :' + id);
            }
            var byteArray = [];
            for (var i = 0; i < 16; i++) {
                var byteHex = rawUuid.substr(i * 2, 2);
                var byteNumber = parseInt(byteHex, 16);
                byteArray.push(byteNumber);
            }
            return byteArray;
        }

        function embeddedFontDeobfuscateAdobe(obfuscatedResourceBlob, callback) {

            // extract the UUID and convert to big-endian binary form (16 bytes):
            var uidWordArray = urnUuidToByteArray(_uid);
            var prefixLength = 1024;
            xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, uidWordArray, callback)
        }

        // PUBLIC API

        this.getEncryptionDom = function (callback, onerror) {
            if (_encryptionDom) {
                callback(_encryptionDom);
            } else {
                publicationFetcher.getXmlFileDom('META-INF/encryption.xml', function (encryptionDom) {
                    _encryptionDom = encryptionDom;
                    callback(_encryptionDom);
                }, onerror);
            }
        };

        this.isEncryptionSpecified = function () {
            return _isEncryptionSpecified;
        };

        this.initializeEncryptionHash = function (encryptionInitializedCallback) {
            self.getEncryptionDom(function (encryptionDom) {
                if (!_encryptionHash) {
                    _encryptionHash = {};
                }

                var encryptedData = $('EncryptedData', encryptionDom);
                encryptedData.each(function (index, encryptedData) {
                    var encryptionAlgorithm = $('EncryptionMethod', encryptedData).first().attr('Algorithm');

                    // For some reason, jQuery selector "" against XML DOM sometimes doesn't match properly
                    var cipherReference = $('CipherReference', encryptedData);
                    cipherReference.each(function (index, CipherReference) {
                        var cipherReferenceURI = $(CipherReference).attr('URI');
                        console.log('Encryption/obfuscation algorithm ' + encryptionAlgorithm + ' specified for ' +
                            cipherReferenceURI);
                        _isEncryptionSpecified = true;
                        _encryptionHash[cipherReferenceURI] = encryptionAlgorithm;
                    });
                });

                encryptionInitializedCallback();
            }, function (error) {
                console.log(error.message);
                console.log("Document doesn't make use of encryption.");
                encryptionInitializedCallback();
            });
        };

        this.getEncryptionMethodForRelativePath = function (pathRelativeToRoot) {
            if (_encryptionHash) {
                return _encryptionHash[pathRelativeToRoot];
            } else {
                return undefined;
            }
        };

        this.getDecryptionFunctionForRelativePath = function (pathRelativeToRoot) {
            var encryptionMethod = self.getEncryptionMethodForRelativePath(pathRelativeToRoot);
            if (ENCRYPTION_METHODS[encryptionMethod]) {
                return ENCRYPTION_METHODS[encryptionMethod];
            } else {
                return undefined;
            }
        };

    };
    return EncryptionHandler;
});<commit_msg>Fix a small reference error in error logging<commit_after>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

define(['require', 'module'], function (require, module) {

    var EncryptionHandler = function (packageMetadata, publicationFetcher) {
        var self = this;

        var _uid = packageMetadata.id;
        var _encryptionDom;
        var _encryptionHash;
        var _isEncryptionSpecified = false;

        var ENCRYPTION_METHODS = {
            'http://www.idpf.org/2008/embedding': embeddedFontDeobfuscateIdpf,
            'http://ns.adobe.com/pdf/enc#RC': embeddedFontDeobfuscateAdobe
        };

        // INTERNAL FUNCTIONS

        function blob2BinArray(blob, callback) {
            var fileReader = new FileReader();
            fileReader.onload = function () {
                var arrayBuffer = this.result;
                callback(new Uint8Array(arrayBuffer));
            };
            fileReader.readAsArrayBuffer(blob);
        }

        function xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, xorKey, callback) {
            var obfuscatedPrefixBlob = obfuscatedResourceBlob.slice(0, prefixLength);
            blob2BinArray(obfuscatedPrefixBlob, function (bytes) {
                var masklen = xorKey.length;
                for (var i = 0; i < prefixLength; i++) {
                    bytes[i] = bytes[i] ^ (xorKey[i % masklen]);
                }
                var deobfuscatedPrefixBlob = new Blob([bytes], { type: obfuscatedResourceBlob.type });
                var remainderBlob = obfuscatedResourceBlob.slice(prefixLength);
                var deobfuscatedBlob = new Blob([deobfuscatedPrefixBlob, remainderBlob],
                    { type: obfuscatedResourceBlob.type });

                callback(deobfuscatedBlob);
            });
        }

        function embeddedFontDeobfuscateIdpf(obfuscatedResourceBlob, callback) {
            var hashedUid = window.Crypto.SHA1(unescape(encodeURIComponent(_uid.trim())), { asBytes: true });
            var prefixLength = 1040;
            // Shamelessly copied from
            // https://github.com/readium/readium-chrome-extension/blob/26d4b0cafd254cfa93bf7f6225887b83052642e0/scripts/models/path_resolver.js#L102 :
            xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, hashedUid, callback);
        }

        function urnUuidToByteArray(id) {
            var uuidRegexp = /(urn:uuid:)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})/i;
            var matchResults = uuidRegexp.exec(id);
            var rawUuid = matchResults[2] + matchResults[3] + matchResults[4] + matchResults[5] + matchResults[6];
            if (!rawUuid || rawUuid.length != 32) {
                console.error('Bad UUID format for ID :' + id);
            }
            var byteArray = [];
            for (var i = 0; i < 16; i++) {
                var byteHex = rawUuid.substr(i * 2, 2);
                var byteNumber = parseInt(byteHex, 16);
                byteArray.push(byteNumber);
            }
            return byteArray;
        }

        function embeddedFontDeobfuscateAdobe(obfuscatedResourceBlob, callback) {

            // extract the UUID and convert to big-endian binary form (16 bytes):
            var uidWordArray = urnUuidToByteArray(_uid);
            var prefixLength = 1024;
            xorObfuscatedBlob(obfuscatedResourceBlob, prefixLength, uidWordArray, callback)
        }

        // PUBLIC API

        this.getEncryptionDom = function (callback, onerror) {
            if (_encryptionDom) {
                callback(_encryptionDom);
            } else {
                publicationFetcher.getXmlFileDom('META-INF/encryption.xml', function (encryptionDom) {
                    _encryptionDom = encryptionDom;
                    callback(_encryptionDom);
                }, onerror);
            }
        };

        this.isEncryptionSpecified = function () {
            return _isEncryptionSpecified;
        };

        this.initializeEncryptionHash = function (encryptionInitializedCallback) {
            self.getEncryptionDom(function (encryptionDom) {
                if (!_encryptionHash) {
                    _encryptionHash = {};
                }

                var encryptedData = $('EncryptedData', encryptionDom);
                encryptedData.each(function (index, encryptedData) {
                    var encryptionAlgorithm = $('EncryptionMethod', encryptedData).first().attr('Algorithm');

                    // For some reason, jQuery selector "" against XML DOM sometimes doesn't match properly
                    var cipherReference = $('CipherReference', encryptedData);
                    cipherReference.each(function (index, CipherReference) {
                        var cipherReferenceURI = $(CipherReference).attr('URI');
                        console.log('Encryption/obfuscation algorithm ' + encryptionAlgorithm + ' specified for ' +
                            cipherReferenceURI);
                        _isEncryptionSpecified = true;
                        _encryptionHash[cipherReferenceURI] = encryptionAlgorithm;
                    });
                });

                encryptionInitializedCallback();
            }, function (error) {
                console.log(error);
                console.log("Document doesn't make use of encryption.");
                encryptionInitializedCallback();
            });
        };

        this.getEncryptionMethodForRelativePath = function (pathRelativeToRoot) {
            if (_encryptionHash) {
                return _encryptionHash[pathRelativeToRoot];
            } else {
                return undefined;
            }
        };

        this.getDecryptionFunctionForRelativePath = function (pathRelativeToRoot) {
            var encryptionMethod = self.getEncryptionMethodForRelativePath(pathRelativeToRoot);
            if (ENCRYPTION_METHODS[encryptionMethod]) {
                return ENCRYPTION_METHODS[encryptionMethod];
            } else {
                return undefined;
            }
        };

    };
    return EncryptionHandler;
});<|endoftext|>


<commit_before>var path = require("path");

module.exports = {
	// mode: "development" || "production",
	entry: {
		pageA: "./pageA",
		pageB: "./pageB",
		pageC: "./pageC"
	},
	optimization: {
		splitChunks: {
			cacheGroups: {
				commons: {
					chunks: "initial",
					minChunks: 2,
					minSize: 0 // This is example is too small to create commons chunks
				},
				vendor: {
					test: /node_modules/,
					chunks: "initial",
					name: "vendor",
					enforce: true
				}
			}
		}
	},
	output: {
		path: path.join(__dirname, "dist"),
		filename: "[name].js"
	}
};
<commit_msg>fix example<commit_after>var path = require("path");

module.exports = {
	// mode: "development" || "production",
	entry: {
		pageA: "./pageA",
		pageB: "./pageB",
		pageC: "./pageC"
	},
	optimization: {
		splitChunks: {
			cacheGroups: {
				commons: {
					chunks: "initial",
					minChunks: 2,
					maxInitialRequests: 5, // The default limit is too small to showcase the effect
					minSize: 0 // This is example is too small to create commons chunks
				},
				vendor: {
					test: /node_modules/,
					chunks: "initial",
					name: "vendor",
					priority: 10,
					enforce: true
				}
			}
		}
	},
	output: {
		path: path.join(__dirname, "dist"),
		filename: "[name].js"
	}
};
<|endoftext|>