<commit_before>class Emergency extends pso2tools_module{
    constructor(app){
        super(app);
    }

    static getEmergencyInfo(handler){
        var sourceURI = "http://pso2.jp/players/boost/";
        var req = new XMLHttpRequest();
        req.open("GET",sourceURI);
        req.addEventListener("readystatechange",function(e){
            if(e.target.readyState === 4){
                if(e.target.status != 200){
                    return;
                }
                var parser = new DOMParser();
                var content = parser.parseFromString(e.target.responseText,"text/html");
                var emerList = [];
                var timeOffset = -((new Date).getTimezoneOffset() + 540);    // + n minutes from Tokyo Time to Local Time
                const weekday = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]
                const day = [
                    "wednesday1",
                    "thursday",
                    "friday",
                    "saturday",
                    "sunday",
                    "monday",
                    "tuesday",
                    "wednesday2"
                ]
                var dayTbl = {}
                var crossMonth = false; // Point the 1st day of the month.
                day.forEach(function(el,i){
                    dayTbl[el] = parseInt(content.querySelector("th.day-"+el).innerText.match(/(\d*)/g)[2]);    // Hope they won't change this LOL
                    if(!crossMonth)
                        crossMonth = (dayTbl[el] < (dayTbl[day[i-1]]|0)?el:false);
                });

                var today = weekday[(new Date).getDay()]

                if(today == "wednesday"){
                    today = today + (((new Date()).getHours()+(timeOffset/60))>16?"2":"1");
                }

                content.querySelectorAll("div.event-emergency").forEach((i)=>{
                    var name = i.querySelector("span").innerText;
                    var eday = i.parentNode.className.split("-")[1];
                    var time = i.parentNode.parentNode.className;
                    time = Number(time.split(/[\D*]/).filter((el)=>el != "").join(""));

                    var datetime = new Date();
                    datetime.setDate(dayTbl[eday]);
                    if(crossMonth && datetime.getDate()>15 && (day.indexOf(today) < day.indexOf(crossMonth))){
                        datetime.setMonth(datetime.getMonth + 1);
                    }
                    datetime.setHours(parseInt(time/100));
                    datetime.setMinutes((time % 100) + timeOffset);
                    datetime.setSeconds(0);
                    datetime.setMilliseconds(0);

                    if(datetime < (new Date()).setMinutes((new Date()).getMinutes()-30)){
                        return;
                    }

                    emerList.push({name:name,time:datetime});
                })

                emerList.sort(function(el1, el2){
                    return el1.time - el2.time;
                });

                //Rendering
                var emerElem = []
                emerList.forEach(function(el,i){
                    emerElem.push(
{el.name}	{el.time.toLocaleString()}
);
                })
                ReactDOM.unmountComponentAtNode(document.getElementById("Emergency_TimeTable"));
                ReactDOM.render(

{emerElem}

,document.getElementById("Emergency_TimeTable"));
            }
        });
        req.addEventListener("error",function(){
            alert("Connection to Internet required!");
        })
        req.send();
    }

    renderTab(){
        var content =

<button onClick={Emergency.getEmergencyInfo}>{"Get Emergency Time Table"}</button>

        return {content:content,label:"Emergency"}
    }
}<commit_msg>unused param removed<commit_after>class Emergency extends pso2tools_module{
    constructor(app){
        super(app);
    }

    static getEmergencyInfo(){
        var sourceURI = "http://pso2.jp/players/boost/";
        var req = new XMLHttpRequest();
        req.open("GET",sourceURI);
        req.addEventListener("readystatechange",function(e){
            if(e.target.readyState === 4){
                if(e.target.status != 200){
                    return;
                }
                var parser = new DOMParser();
                var content = parser.parseFromString(e.target.responseText,"text/html");
                var emerList = [];
                var timeOffset = -((new Date).getTimezoneOffset() + 540);    // + n minutes from Tokyo Time to Local Time
                const weekday = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]
                const day = [
                    "wednesday1",
                    "thursday",
                    "friday",
                    "saturday",
                    "sunday",
                    "monday",
                    "tuesday",
                    "wednesday2"
                ]
                var dayTbl = {}
                var crossMonth = false; // Point the 1st day of the month.
                day.forEach(function(el,i){
                    dayTbl[el] = parseInt(content.querySelector("th.day-"+el).innerText.match(/(\d*)/g)[2]);    // Hope they won't change this LOL
                    if(!crossMonth)
                        crossMonth = (dayTbl[el] < (dayTbl[day[i-1]]|0)?el:false);
                });

                var today = weekday[(new Date).getDay()]

                if(today == "wednesday"){
                    today = today + (((new Date()).getHours()+(timeOffset/60))>16?"2":"1");
                }

                content.querySelectorAll("div.event-emergency").forEach((i)=>{
                    var name = i.querySelector("span").innerText;
                    var eday = i.parentNode.className.split("-")[1];
                    var time = i.parentNode.parentNode.className;
                    time = Number(time.split(/[\D*]/).filter((el)=>el != "").join(""));

                    var datetime = new Date();
                    datetime.setDate(dayTbl[eday]);
                    if(crossMonth && datetime.getDate()>15 && (day.indexOf(today) < day.indexOf(crossMonth))){
                        datetime.setMonth(datetime.getMonth + 1);
                    }
                    datetime.setHours(parseInt(time/100));
                    datetime.setMinutes((time % 100) + timeOffset);
                    datetime.setSeconds(0);
                    datetime.setMilliseconds(0);

                    if(datetime < (new Date()).setMinutes((new Date()).getMinutes()-30)){
                        return;
                    }

                    emerList.push({name:name,time:datetime});
                })

                emerList.sort(function(el1, el2){
                    return el1.time - el2.time;
                });

                //Rendering
                var emerElem = []
                emerList.forEach(function(el,i){
                    emerElem.push(
{el.name}	{el.time.toLocaleString()}
);
                })
                ReactDOM.unmountComponentAtNode(document.getElementById("Emergency_TimeTable"));
                ReactDOM.render(

{emerElem}

,document.getElementById("Emergency_TimeTable"));
            }
        });
        req.addEventListener("error",function(){
            alert("Connection to Internet required!");
        })
        req.send();
    }

    renderTab(){
        var content =

<button onClick={Emergency.getEmergencyInfo}>{"Get Emergency Time Table"}</button>

        return {content:content,label:"Emergency"}
    }
}<|endoftext|>


<commit_before>import * as d3 from 'd3';
import _ from 'lodash';
import { modeBrowse, modeSelect } from '../modes/index';
import { osmEntity } from '../osm/index';

export function behaviorSelect(context) {

    function keydown() {
        if (d3.event && d3.event.shiftKey) {
            context.surface()
                .classed('behavior-multiselect', true);
        }
    }

    function keyup() {
        if (!d3.event || !d3.event.shiftKey) {
            context.surface()
                .classed('behavior-multiselect', false);
        }
    }

    function click() {

        if (d3.event.type === 'contextmenu') {
          d3.event.preventDefault();
        }

        var datum = d3.event.target.__data__,
            lasso = d3.select('#surface .lasso').node(),
            mode = context.mode();

        if (datum.type === 'midpoint') {
            // do nothing
        } else if (!(datum instanceof osmEntity)) {
            if (!d3.event.shiftKey && !lasso && mode.id !== 'browse')
                context.enter(modeBrowse(context));

        } else if (!d3.event.shiftKey && !lasso) {
            // Avoid re-entering Select mode with same entity.
            if (context.selectedIDs().length !== 1 || context.selectedIDs()[0] !== datum.id) {
                context.enter(modeSelect(context, [datum.id]));
            } else {
                mode.suppressMenu(false).reselect();
            }
        } else if (context.selectedIDs().indexOf(datum.id) >= 0) {
            var selectedIDs = _.without(context.selectedIDs(), datum.id);
            context.enter(selectedIDs.length ? modeSelect(context, selectedIDs) : modeBrowse(context));

        } else {
            context.enter(modeSelect(context, context.selectedIDs().concat([datum.id])));
        }
    }

    var behavior = function(selection) {
        d3.select(window)
            .on('keydown.select', keydown)
            .on('keyup.select', keyup);

        selection.on('click.select', click);
        selection.on('contextmenu.select', click);

        keydown();
    };

    behavior.off = function(selection) {
        d3.select(window)
            .on('keydown.select', null)
            .on('keyup.select', null);

        selection.on('click.select', null);

        keyup();
    };

    return behavior;
}
<commit_msg>Fix right clicking edge cases<commit_after>import * as d3 from 'd3';
import _ from 'lodash';
import { modeBrowse, modeSelect } from '../modes/index';
import { osmEntity } from '../osm/index';

export function behaviorSelect(context) {

    function keydown() {
        if (d3.event && d3.event.shiftKey) {
            context.surface()
                .classed('behavior-multiselect', true);
        }
    }

    function keyup() {
        if (!d3.event || !d3.event.shiftKey) {
            context.surface()
                .classed('behavior-multiselect', false);
        }
    }

    function click() {
        var rtClick = d3.event.type === 'contextmenu';

        if (rtClick) {
          d3.event.preventDefault();
        }

        var datum = d3.event.target.__data__,
            lasso = d3.select('#surface .lasso').node(),
            mode = context.mode();

        if (datum.type === 'midpoint') {
            // do nothing
        } else if (!(datum instanceof osmEntity)) {
            if (!d3.event.shiftKey && !lasso && mode.id !== 'browse')
                context.enter(modeBrowse(context));

        } else if (!d3.event.shiftKey && !lasso) {
            // Reselect when 'rtClick on one of the selectedIDs'
            // OR 'leftClick on the same singular selected entity'
            // Explanation: leftClick should discard any multiple
            //  selection of entities and make the selection singlular.
            // Whereas rtClick should preserve multiple selection of
            // entities  if and only if it clicks on one of the selectedIDs.
            if (context.selectedIDs().indexOf(datum.id) >= 0
                && (rtClick || context.selectedIDs().length === 1)) {
                mode.suppressMenu(false).reselect();
            } else {
                context.enter(modeSelect(context, [datum.id]));
            }
        } else if (context.selectedIDs().indexOf(datum.id) >= 0) {
            if (rtClick) { // To prevent datum.id from being removed when rtClick
                mode.suppressMenu(false).reselect();
            } else {
                var selectedIDs = _.without(context.selectedIDs(), datum.id);
                context.enter(selectedIDs.length ? modeSelect(context, selectedIDs) : modeBrowse(context));
            }
        } else {
            context.enter(modeSelect(context, context.selectedIDs().concat([datum.id])));
        }
    }

    var behavior = function(selection) {
        d3.select(window)
            .on('keydown.select', keydown)
            .on('keyup.select', keyup);

        selection.on('click.select', click);
        selection.on('contextmenu.select', click);

        keydown();
    };

    behavior.off = function(selection) {
        d3.select(window)
            .on('keydown.select', null)
            .on('keyup.select', null);

        selection.on('click.select', null);

        keyup();
    };

    return behavior;
}
<|endoftext|>


<commit_before>(function() {
  'use strict';

  /*jshint eqnull:true */
  // https://tc39.github.io/ecma262/#sec-array.prototype.find
  if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
      value: function(predicate) {
      // 1. Let O be ? ToObject(this value).
        if (this == null) {
          throw new TypeError('"this" is null or not defined');
        }

        var o = Object(this);

        // 2. Let len be ? ToLength(? Get(O, "length")).
        var len = o.length >>> 0;

        // 3. If IsCallable(predicate) is false, throw a TypeError exception.
        if (typeof predicate !== 'function') {
          throw new TypeError('predicate must be a function');
        }

        // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
        var thisArg = arguments[1];

        // 5. Let k be 0.
        var k = 0;

        // 6. Repeat, while k < len
        while (k < len) {
          // a. Let Pk be ! ToString(k).
          // b. Let kValue be ? Get(O, Pk).
          // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
          // d. If testResult is true, return kValue.
          var kValue = o[k];
          if (predicate.call(thisArg, kValue, k, o)) {
            return kValue;
          }
          // e. Increase k by 1.
          k++;
        }

        // 7. Return undefined.
        return undefined;
      }
    });
  }

  if (!Array.prototype.filter)
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function') && this) )
        throw new TypeError();

    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        c = 0, i = -1;
    if (thisArg === undefined)
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func(t[i], i, t))
            res[c++] = t[i];
    else
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func.call(thisArg, t[i], i, t))
            res[c++] = t[i];

    res.length = c; // shrink down array to proper size
    return res;
  };
  /*jshint eqnull:false */

  function flameGraph() {

    var w = 960, // graph width
      h = null, // graph height
      c = 18, // cell height
      selection = null, // selection
      tooltip = true, // enable tooltip
      title = "", // graph title
      transitionDuration = 750,
      transitionEase = d3.easeCubic, // tooltip offset
      sort = false,
      reversed = false, // reverse the graph direction
      clickHandler = null,
      minFrameSize = 0;

    var tip = d3.tip()
      .direction("s")
      .offset([8, 0])
      .attr('class', 'd3-flame-graph-tip')
      .html(function(d) { return label(d); });

    var svg;

    var label = function(d) {
      return d.data.name + " (" + d3.format(".3f")(100 * (d.x1 - d.x0), 3) + "%, " + d.data.value + " samples)";
    };

    function setDetails(t) {
      var details = document.getElementById("details");
      if (details)
        details.innerHTML = t;
    }

    function name(d) {
      return d.data.name;
    }

    var colorMapper = function(d) {
      return d.highlight ? "#E600E6" : colorHash(d.data.name);
    };

    function generateHash(name) {
      // Return a vector (0.0->1.0) that is a hash of the input string.
      // The hash is computed to favor early characters over later ones, so
      // that strings with similar starts have similar vectors. Only the first
      // 6 characters are considered.
      var hash = 0, weight = 1, max_hash = 0, mod = 10, max_char = 6;
      if (name) {
        for (var i = 0; i < name.length; i++) {
          if (i > max_char) { break; }
          hash += weight * (name.charCodeAt(i) % mod);
          max_hash += weight * (mod - 1);
          weight *= 0.70;
        }
        if (max_hash > 0) { hash = hash / max_hash; }
      }
      return hash;
    }

    function colorHash(name) {
      // Return an rgb() color string that is a hash of the provided name,
      // and with a warm palette.
      var vector = 0;
      if (name) {
        var nameArr = name.split('`');
        if (nameArr.length > 1) {
          name = nameArr[nameArr.length -1]; // drop module name if present
        }
        name = name.split('(')[0]; // drop extra info
        vector = generateHash(name);
      }
      var r = 200 + Math.round(55 * vector);
      var g = 0 + Math.round(230 * (1 - vector));
      var b = 0 + Math.round(55 * (1 - vector));
      return "rgb(" + r + "," + g + "," + b + ")";
    }

    function hide(d) {
      if(!d.data.original) {
        d.data.original = d.data.value;
      }
      d.data.value = 0;
      if(d.children) {
        d.children.forEach(hide);
      }
    }

    function show(d) {
      d.data.fade = false;
      if(d.data.original) {
        d.data.value = d.data.original;
      }
      if(d.children) {
        d.children.forEach(show);
      }
    }

    function getSiblings(d) {
      var siblings = [];
      if (d.parent) {
        var me = d.parent.children.indexOf(d);
        siblings = d.parent.children.slice(0);
        siblings.splice(me, 1);
      }
      return siblings;
    }

    function hideSiblings(d) {
      var siblings = getSiblings(d);
      siblings.forEach(function(s) {
        hide(s);
      });
      if(d.parent) {
        hideSiblings(d.parent);
      }
    }

    function fadeAncestors(d) {
      if(d.parent) {
        d.parent.data.fade = true;
        fadeAncestors(d.parent);
      }
    }

    function getRoot(d) {
      if(d.parent) {
        return getRoot(d.parent);
      }
      return d;
    }

    function zoom(d) {
      tip.hide(d);
      hideSiblings(d);
      show(d);
      fadeAncestors(d);
      update();
      if (typeof clickHandler === 'function') {
        clickHandler(d);
      }
    }

    function searchTree(d, term) {
      var re = new RegExp(term),
          searchResults = [];

      function searchInner(d) {
        var label = d.data.name;

        if (d.children) {
          d.children.forEach(function (child) {
            searchInner(child);
          });
        }

        if (label.match(re)) {
          d.highlight = true;
          searchResults.push(d);
        } else {
          d.highlight = false;
        }
      }

      searchInner(d);
      return searchResults;
    }

    function clear(d) {
      d.highlight = false;
      if(d.children) {
        d.children.forEach(function(child) {
          clear(child);
        });
      }
    }

    function doSort(a, b) {
      if (typeof sort === 'function') {
        return sort(a, b);
      } else if (sort) {
        return d3.ascending(a.data.name, b.data.name);
      }
    }

    var partition = d3.partition();

    function filterNodes(root) {
      var nodeList = root.descendants();
      if (minFrameSize > 0) {
        var kx = w / (root.x1 - root.x0);
        nodeList = nodeList.filter(function(el) {
          return ((el.x1 - el.x0) * kx) > minFrameSize;
        });
      }
      return nodeList
    }

    function update() {

      selection.each(function(root) {
        var x = d3.scaleLinear().range([0, w]),
            y = d3.scaleLinear().range([0, c]);

        if (sort) root.sort(doSort);
        root.sum(function(d) {
          if (d.fade) {
            return 0;
          }
          // The node's self value is its total value minus all children.
          var v = d.v || d.value || 0;
          if (d.c || d.children) {
            var c = d.c || d.children;
            for (var i = 0; i < c.length; i++) {
              v -= c[i].value;
            }
          }
          return v;
        });
        partition(root);

        var kx = w / (root.x1 - root.x0);
        function width(d) { return (d.x1 - d.x0) * kx; }

        var descendants = filterNodes(root);
        var g = d3.select(this).select("svg").selectAll("g").data(descendants, d => d.id);

        g.transition()
          .duration(transitionDuration)
          .ease(transitionEase)
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });

        g.select("rect").transition()
          .duration(transitionDuration)
          .ease(transitionEase)
          .attr("width", width);

        var node = g.enter()
          .append("svg:g")
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });

        node.append("svg:rect").attr("width", width);

        if (!tooltip)
          node.append("svg:title");

        node.append("foreignObject")
          .append("xhtml:div");

        // Now we have to re-select to see the new elements (why?).
        g = d3.select(this).select("svg").selectAll("g").data(descendants, d => d.id);

        g.attr("width", width)
          .attr("height", function(d) { return c; })
          .attr("name", function(d) { return d.data.name; })
          .attr("class", function(d) { return d.data.fade ? "frame fade" : "frame"; });

        g.select("rect")
          .attr("height", function(d) { return c; })
          .attr("fill", function(d) { return colorMapper(d); });

        if (!tooltip)
          g.select("title")
            .text(label);

        g.select("foreignObject")
          .attr("width", width)
          .attr("height", function(d) { return c; })
          .select("div")
          .attr("class", "label")
          .style("display", function(d) { return (width(d) < 35) ? "none" : "block";})
          .text(name);

        g.on('click', zoom);

        g.exit()
          .remove();

        g.on('mouseover', function(d) {
          if (tooltip) tip.show(d);
          setDetails(label(d));
        }).on('mouseout', function(d) {
          if (tooltip) tip.hide(d);
          setDetails("");
        });
      });
    }

    function merge(data, samples) {
      samples.forEach(function (sample) {
        var node = data.find(function (element) {
          return element.name === sample.name;
        });

        if (node) {
          if (node.original) {
            node.original += sample.value;
          } else {
            node.value += sample.value;
          }
          if (sample.children) {
            if (!node.children) {
              node.children = [];
            }
            merge(node.children, sample.children);
          }
        } else {
          data.push(sample);
        }
      });
    }

    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }

    function injectIds(node) {
      node.id = s4();
      var children = node.c || node.children || [];
      for (var i = 0; i < children.length; i++) {
        injectIds(children[i])
      }
    }

    function chart(s) {
      var root = d3.hierarchy(s.datum(), function(d) { return d.c || d.children; });
      injectIds(root);
      selection = s.datum(root);

      if (!arguments.length) return chart;

      if (!h) {
        h = (root.height + 2) * c;
      }

      selection.each(function(data) {

	      if (!svg) {
          svg = d3.select(this)
            .append("svg:svg")
            .attr("width", w)
            .attr("height", h)
            .attr("class", "partition d3-flame-graph")
            .call(tip);

          svg.append("svg:text")
            .attr("class", "title")
            .attr("text-anchor", "middle")
            .attr("y", "25")
            .attr("x", w/2)
            .attr("fill", "#808080")
            .text(title);
        }
      });

      // first draw
      update();
    }

    chart.height = function (_) {
      if (!arguments.length) { return h; }
      h = _;
      return chart;
    };

    chart.width = function (_) {
      if (!arguments.length) { return w; }
      w = _;
      return chart;
    };

    chart.cellHeight = function (_) {
      if (!arguments.length) { return c; }
      c = _;
      return chart;
    };

    chart.tooltip = function (_) {
      if (!arguments.length) { return tooltip; }
      if (typeof _ === "function") {
        tip = _;
      }
      tooltip = !!_;
      return chart;
    };

    chart.title = function (_) {
      if (!arguments.length) { return title; }
      title = _;
      return chart;
    };

    chart.transitionDuration = function (_) {
      if (!arguments.length) { return transitionDuration; }
      transitionDuration = _;
      return chart;
    };

    chart.transitionEase = function (_) {
      if (!arguments.length) { return transitionEase; }
      transitionEase = _;
      return chart;
    };

    chart.sort = function (_) {
      if (!arguments.length) { return sort; }
      sort = _;
      return chart;
    };

    chart.reversed = function (_) {
      if (!arguments.length) { return reversed; }
      reversed = _;
      return chart;
    };

    chart.label = function(_) {
      if (!arguments.length) { return label; }
      label = _;
      return chart;
    };

    chart.search = function(term) {
      var searchResults = [];
      selection.each(function(data) {
        searchResults = searchTree(data, term);
        update();
      });
      return searchResults;
    };

    chart.clear = function() {
      selection.each(function(data) {
        clear(data);
        update();
      });
    };

    chart.zoomTo = function(d) {
      zoom(d);
    };

    chart.resetZoom = function() {
      selection.each(function (data) {
        zoom(data); // zoom to root
      });
    };

    chart.onClick = function(_) {
      if (!arguments.length) {
        return clickHandler;
      }
      clickHandler = _;
      return chart;
    };

    chart.merge = function(samples) {
      var newRoot; // Need to re-create hierarchy after data changes.
      selection.each(function (root) {
        merge([root.data], [samples]);
        newRoot = d3.hierarchy(root.data, function(d) { return d.c || d.children; });
      });
      selection = selection.datum(newRoot);
      update();
    };

    chart.color = function(_) {
      if (!arguments.length) { return colorMapper; }
      colorMapper = _;
      return chart;
    };

    chart.minFrameSize = function (_) {
      if (!arguments.length) { return minFrameSize; }
      minFrameSize = _;
      return chart;
    };

    return chart;
  }

  if (typeof module !== 'undefined' && module.exports){
		module.exports = flameGraph;
	}
	else {
		d3.flameGraph = flameGraph;
	}
})();
<commit_msg>fix: removing unecessary transition. Closes #26<commit_after>(function() {
  'use strict';

  /*jshint eqnull:true */
  // https://tc39.github.io/ecma262/#sec-array.prototype.find
  if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
      value: function(predicate) {
      // 1. Let O be ? ToObject(this value).
        if (this == null) {
          throw new TypeError('"this" is null or not defined');
        }

        var o = Object(this);

        // 2. Let len be ? ToLength(? Get(O, "length")).
        var len = o.length >>> 0;

        // 3. If IsCallable(predicate) is false, throw a TypeError exception.
        if (typeof predicate !== 'function') {
          throw new TypeError('predicate must be a function');
        }

        // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
        var thisArg = arguments[1];

        // 5. Let k be 0.
        var k = 0;

        // 6. Repeat, while k < len
        while (k < len) {
          // a. Let Pk be ! ToString(k).
          // b. Let kValue be ? Get(O, Pk).
          // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
          // d. If testResult is true, return kValue.
          var kValue = o[k];
          if (predicate.call(thisArg, kValue, k, o)) {
            return kValue;
          }
          // e. Increase k by 1.
          k++;
        }

        // 7. Return undefined.
        return undefined;
      }
    });
  }

  if (!Array.prototype.filter)
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function') && this) )
        throw new TypeError();

    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        c = 0, i = -1;
    if (thisArg === undefined)
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func(t[i], i, t))
            res[c++] = t[i];
    else
      while (++i !== len)
        // checks to see if the key was set
        if (i in this)
          if (func.call(thisArg, t[i], i, t))
            res[c++] = t[i];

    res.length = c; // shrink down array to proper size
    return res;
  };
  /*jshint eqnull:false */

  function flameGraph() {

    var w = 960, // graph width
      h = null, // graph height
      c = 18, // cell height
      selection = null, // selection
      tooltip = true, // enable tooltip
      title = "", // graph title
      transitionDuration = 750,
      transitionEase = d3.easeCubic, // tooltip offset
      sort = false,
      reversed = false, // reverse the graph direction
      clickHandler = null,
      minFrameSize = 0;

    var tip = d3.tip()
      .direction("s")
      .offset([8, 0])
      .attr('class', 'd3-flame-graph-tip')
      .html(function(d) { return label(d); });

    var svg;

    var label = function(d) {
      return d.data.name + " (" + d3.format(".3f")(100 * (d.x1 - d.x0), 3) + "%, " + d.data.value + " samples)";
    };

    function setDetails(t) {
      var details = document.getElementById("details");
      if (details)
        details.innerHTML = t;
    }

    function name(d) {
      return d.data.name;
    }

    var colorMapper = function(d) {
      return d.highlight ? "#E600E6" : colorHash(d.data.name);
    };

    function generateHash(name) {
      // Return a vector (0.0->1.0) that is a hash of the input string.
      // The hash is computed to favor early characters over later ones, so
      // that strings with similar starts have similar vectors. Only the first
      // 6 characters are considered.
      var hash = 0, weight = 1, max_hash = 0, mod = 10, max_char = 6;
      if (name) {
        for (var i = 0; i < name.length; i++) {
          if (i > max_char) { break; }
          hash += weight * (name.charCodeAt(i) % mod);
          max_hash += weight * (mod - 1);
          weight *= 0.70;
        }
        if (max_hash > 0) { hash = hash / max_hash; }
      }
      return hash;
    }

    function colorHash(name) {
      // Return an rgb() color string that is a hash of the provided name,
      // and with a warm palette.
      var vector = 0;
      if (name) {
        var nameArr = name.split('`');
        if (nameArr.length > 1) {
          name = nameArr[nameArr.length -1]; // drop module name if present
        }
        name = name.split('(')[0]; // drop extra info
        vector = generateHash(name);
      }
      var r = 200 + Math.round(55 * vector);
      var g = 0 + Math.round(230 * (1 - vector));
      var b = 0 + Math.round(55 * (1 - vector));
      return "rgb(" + r + "," + g + "," + b + ")";
    }

    function hide(d) {
      if(!d.data.original) {
        d.data.original = d.data.value;
      }
      d.data.value = 0;
      if(d.children) {
        d.children.forEach(hide);
      }
    }

    function show(d) {
      d.data.fade = false;
      if(d.data.original) {
        d.data.value = d.data.original;
      }
      if(d.children) {
        d.children.forEach(show);
      }
    }

    function getSiblings(d) {
      var siblings = [];
      if (d.parent) {
        var me = d.parent.children.indexOf(d);
        siblings = d.parent.children.slice(0);
        siblings.splice(me, 1);
      }
      return siblings;
    }

    function hideSiblings(d) {
      var siblings = getSiblings(d);
      siblings.forEach(function(s) {
        hide(s);
      });
      if(d.parent) {
        hideSiblings(d.parent);
      }
    }

    function fadeAncestors(d) {
      if(d.parent) {
        d.parent.data.fade = true;
        fadeAncestors(d.parent);
      }
    }

    function getRoot(d) {
      if(d.parent) {
        return getRoot(d.parent);
      }
      return d;
    }

    function zoom(d) {
      tip.hide(d);
      hideSiblings(d);
      show(d);
      fadeAncestors(d);
      update();
      if (typeof clickHandler === 'function') {
        clickHandler(d);
      }
    }

    function searchTree(d, term) {
      var re = new RegExp(term),
          searchResults = [];

      function searchInner(d) {
        var label = d.data.name;

        if (d.children) {
          d.children.forEach(function (child) {
            searchInner(child);
          });
        }

        if (label.match(re)) {
          d.highlight = true;
          searchResults.push(d);
        } else {
          d.highlight = false;
        }
      }

      searchInner(d);
      return searchResults;
    }

    function clear(d) {
      d.highlight = false;
      if(d.children) {
        d.children.forEach(function(child) {
          clear(child);
        });
      }
    }

    function doSort(a, b) {
      if (typeof sort === 'function') {
        return sort(a, b);
      } else if (sort) {
        return d3.ascending(a.data.name, b.data.name);
      }
    }

    var partition = d3.partition();

    function filterNodes(root) {
      var nodeList = root.descendants();
      if (minFrameSize > 0) {
        var kx = w / (root.x1 - root.x0);
        nodeList = nodeList.filter(function(el) {
          return ((el.x1 - el.x0) * kx) > minFrameSize;
        });
      }
      return nodeList
    }

    function update() {

      selection.each(function(root) {
        var x = d3.scaleLinear().range([0, w]),
            y = d3.scaleLinear().range([0, c]);

        if (sort) root.sort(doSort);
        root.sum(function(d) {
          if (d.fade) {
            return 0;
          }
          // The node's self value is its total value minus all children.
          var v = d.v || d.value || 0;
          if (d.c || d.children) {
            var c = d.c || d.children;
            for (var i = 0; i < c.length; i++) {
              v -= c[i].value;
            }
          }
          return v;
        });
        partition(root);

        var kx = w / (root.x1 - root.x0);
        function width(d) { return (d.x1 - d.x0) * kx; }

        var descendants = filterNodes(root);
        var g = d3.select(this).select("svg").selectAll("g").data(descendants, d => d.id);

        g.transition()
          .duration(transitionDuration)
          .ease(transitionEase)
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });

        g.select("rect")
          .attr("width", width);

        var node = g.enter()
          .append("svg:g")
          .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + (reversed ? y(d.depth) : (h - y(d.depth) - c)) + ")"; });

        node.append("svg:rect").attr("width", width);

        if (!tooltip)
          node.append("svg:title");

        node.append("foreignObject")
          .append("xhtml:div");

        // Now we have to re-select to see the new elements (why?).
        g = d3.select(this).select("svg").selectAll("g").data(descendants, d => d.id);

        g.attr("width", width)
          .attr("height", function(d) { return c; })
          .attr("name", function(d) { return d.data.name; })
          .attr("class", function(d) { return d.data.fade ? "frame fade" : "frame"; });

        g.select("rect")
          .attr("height", function(d) { return c; })
          .attr("fill", function(d) { return colorMapper(d); });

        if (!tooltip)
          g.select("title")
            .text(label);

        g.select("foreignObject")
          .attr("width", width)
          .attr("height", function(d) { return c; })
          .select("div")
          .attr("class", "label")
          .style("display", function(d) { return (width(d) < 35) ? "none" : "block";})
          .text(name);

        g.on('click', zoom);

        g.exit()
          .remove();

        g.on('mouseover', function(d) {
          if (tooltip) tip.show(d);
          setDetails(label(d));
        }).on('mouseout', function(d) {
          if (tooltip) tip.hide(d);
          setDetails("");
        });
      });
    }

    function merge(data, samples) {
      samples.forEach(function (sample) {
        var node = data.find(function (element) {
          return element.name === sample.name;
        });

        if (node) {
          if (node.original) {
            node.original += sample.value;
          } else {
            node.value += sample.value;
          }
          if (sample.children) {
            if (!node.children) {
              node.children = [];
            }
            merge(node.children, sample.children);
          }
        } else {
          data.push(sample);
        }
      });
    }

    function s4() {
      return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
    }

    function injectIds(node) {
      node.id = s4();
      var children = node.c || node.children || [];
      for (var i = 0; i < children.length; i++) {
        injectIds(children[i])
      }
    }

    function chart(s) {
      var root = d3.hierarchy(s.datum(), function(d) { return d.c || d.children; });
      injectIds(root);
      selection = s.datum(root);

      if (!arguments.length) return chart;

      if (!h) {
        h = (root.height + 2) * c;
      }

      selection.each(function(data) {

	      if (!svg) {
          svg = d3.select(this)
            .append("svg:svg")
            .attr("width", w)
            .attr("height", h)
            .attr("class", "partition d3-flame-graph")
            .call(tip);

          svg.append("svg:text")
            .attr("class", "title")
            .attr("text-anchor", "middle")
            .attr("y", "25")
            .attr("x", w/2)
            .attr("fill", "#808080")
            .text(title);
        }
      });

      // first draw
      update();
    }

    chart.height = function (_) {
      if (!arguments.length) { return h; }
      h = _;
      return chart;
    };

    chart.width = function (_) {
      if (!arguments.length) { return w; }
      w = _;
      return chart;
    };

    chart.cellHeight = function (_) {
      if (!arguments.length) { return c; }
      c = _;
      return chart;
    };

    chart.tooltip = function (_) {
      if (!arguments.length) { return tooltip; }
      if (typeof _ === "function") {
        tip = _;
      }
      tooltip = !!_;
      return chart;
    };

    chart.title = function (_) {
      if (!arguments.length) { return title; }
      title = _;
      return chart;
    };

    chart.transitionDuration = function (_) {
      if (!arguments.length) { return transitionDuration; }
      transitionDuration = _;
      return chart;
    };

    chart.transitionEase = function (_) {
      if (!arguments.length) { return transitionEase; }
      transitionEase = _;
      return chart;
    };

    chart.sort = function (_) {
      if (!arguments.length) { return sort; }
      sort = _;
      return chart;
    };

    chart.reversed = function (_) {
      if (!arguments.length) { return reversed; }
      reversed = _;
      return chart;
    };

    chart.label = function(_) {
      if (!arguments.length) { return label; }
      label = _;
      return chart;
    };

    chart.search = function(term) {
      var searchResults = [];
      selection.each(function(data) {
        searchResults = searchTree(data, term);
        update();
      });
      return searchResults;
    };

    chart.clear = function() {
      selection.each(function(data) {
        clear(data);
        update();
      });
    };

    chart.zoomTo = function(d) {
      zoom(d);
    };

    chart.resetZoom = function() {
      selection.each(function (data) {
        zoom(data); // zoom to root
      });
    };

    chart.onClick = function(_) {
      if (!arguments.length) {
        return clickHandler;
      }
      clickHandler = _;
      return chart;
    };

    chart.merge = function(samples) {
      var newRoot; // Need to re-create hierarchy after data changes.
      selection.each(function (root) {
        merge([root.data], [samples]);
        newRoot = d3.hierarchy(root.data, function(d) { return d.c || d.children; });
      });
      selection = selection.datum(newRoot);
      update();
    };

    chart.color = function(_) {
      if (!arguments.length) { return colorMapper; }
      colorMapper = _;
      return chart;
    };

    chart.minFrameSize = function (_) {
      if (!arguments.length) { return minFrameSize; }
      minFrameSize = _;
      return chart;
    };

    return chart;
  }

  if (typeof module !== 'undefined' && module.exports){
		module.exports = flameGraph;
	}
	else {
		d3.flameGraph = flameGraph;
	}
})();
<|endoftext|>


<commit_before>
var React = require('react');

var Owl = React.createClass({
  render: function() {
    return
    	(

    		<OwlImage name={this.props.name} />
    		<OwlMessage name={this.props.name} message={this.props.message} />

);
  }
});

var OwlImage = React.createClass({
  render: function() {
    return
    	(

    	 );
  }
});

var OwlMessage = React.createClass({
  render: function() {
    return
    	(

    		Hello {this.props.name}, {this.props.message}

);
  }
});

module.exports = Owl;

//USAGE:
//ReactDOM.render(
//  <Owl name="User" message = "you should go to sleep."/>,
//  document.getElementById('owl-container')
//);

<commit_msg>parentheses are important<commit_after>
var React = require('react');

var Owl = React.createClass({
  render: function() {
    return (

    		<OwlImage name={this.props.name} />
    		<OwlMessage name={this.props.name} message={this.props.message} />

		);
  }
});

var OwlImage = React.createClass({
  render: function() {
    return (

    	 );
  }
});

var OwlMessage = React.createClass({
  render: function() {
    return (

    		Hello {this.props.name}, {this.props.message}

		);
  }
});

module.exports = Owl;

//USAGE:
//ReactDOM.render(
//  <Owl name="User" message = "you should go to sleep."/>,
//  document.getElementById('owl-container')
//);

<|endoftext|>


<commit_before>"use strict";

var migrations = [];

migrations.push({
  version: 1,
  migrate: function (transaction, next) {
    var itemStore
      , projectStore
      , collectionStore

    itemStore = transaction.db.createObjectStore('items');
    itemStore.createIndex('dateStartInt', 'dateStartInt', { unique: false });
    itemStore.createIndex('dateEndInt', 'dateEndInt', { unique: false });

    projectStore = transaction.db.createObjectStore('projects');
    projectStore.createIndex('name', 'name', { unique: true });

    collectionStore = transaction.db.createObjectStore('collections');
    collectionStore.createIndex('name', 'name', { unique: false });
    collectionStore.createIndex('itemID', 'itemID', { unique: false, multiEntry: true });

    next();
  }
})

module.exports = {
  id: 'timeline-db',
  description: 'Database for the timeline app. Contains projects, collections, and items.',
  migrations: migrations
}
<commit_msg>Update database schema<commit_after>"use strict";

var migrations = [];

migrations.push({
  version: 1,
  migrate: function (transaction, next) {
    var itemStore
      , projectStore
      , collectionStore

    itemStore = transaction.db.createObjectStore('items');
    itemStore.createIndex('dateStartInt', 'dateStartInt', { unique: false });
    itemStore.createIndex('dateEndInt', 'dateEndInt', { unique: false });

    projectStore = transaction.db.createObjectStore('projects');
    projectStore.createIndex('name', 'name', { unique: true });

    collectionStore = transaction.db.createObjectStore('collections');
    collectionStore.createIndex('name', 'name', { unique: false });
    collectionStore.createIndex('itemID', 'itemID', { unique: false, multiEntry: true });

    next();
  }
});

migrations.push({
  version: 2,
  migrate: function (transaction, next) {
    var itemStore = transaction.objectStore('items');
    itemStore.createIndex('added', 'added', { unique: false });
    itemStore.createIndex('itemType', 'itemType', { unique: false });
    itemStore.createIndex('metadataKeys', 'metadataKeys', { unique: false, multiEntry: true });

    var projectStore = transaction.objectStore('projects');
    projectStore.createIndex('added', 'added', { unique: false });

    var collectionStore = transaction.objectStore('collections');
    collectionStore.createIndex('added', 'added', { unique: false });

    next();
  }
});

migrations.push({
  version: 3,
  migrate: function (transaction, next) {
    var collectionStore = transaction.objectStore('collections');
    collectionStore.createIndex('projectID', 'projectID', { unique: false });
    collectionStore.deleteIndex('itemID');

    var itemStore = transaction.objectStore('items');
    itemStore.createIndex('collectionID', 'collectionID', { unique: false, multiEntry: true });
    itemStore.createIndex('title', 'title', { unique: false });

    next();
  }
});

module.exports = {
  id: 'timeline-db',
  description: 'Database for the timeline app. Contains projects, collections, and items.',
  migrations: migrations
}
<|endoftext|>


<commit_before>export default {
  games: [
    {
      name: 'Rise of the Tomb Raider',
      description: `Featuring epic, high-octane action moments set in the most beautiful hostile environments on earth, Rise of the Tomb Raider delivers a cinematic survival action adventure where you will join Lara Croft on her first tomb raiding expedition as she seeks to discover the secret of immortality.`,
      youtubeId: 'qiYiddjc6cU',
      tags: [
        'price:$$$',
        'fps',
        'adventure',
        'action',
        'single-player',
        'exploration'
      ]
    },
    {
      name: 'Crashlands',
      description: `Crashlands is a story-driven crafting ARPG set in an outlandish world of hidden magic and high technology. Fight and tame alien beasts, craft resources into menacing weaponry, befriend the locals, and go toe-to-chin with a world-domineering maniac.`,
      youtubeId: 'q5M6qTEtsSQ',
      tags: [
        'action', 'adventure', 'rpg', 'single-player', 'pricing:$$',
      ]
    },
    {
      name: 'Cobalt',
      description: `Forget everything you've learned about combat. Cobalt's slo-mo mechanic lets you perform moves that other games can't comprehend. Discover the secrets of a distant colony in a cosmic campaign, take on challenges and rule the leaderboards, or face off against others in local and online multiplayer.`,
      youtubeId: 'pK_VCmJlscY',
      tags: [
        'multi-player',
        'single-player',
        'adventure',
        'action',
        'pricing:$$',
      ]
    }
  ],

  questions: [
    // question: what would you like to play?
    {
      prompt: 'What would you like to do today?',
      answers: [
        {
          text: 'Save the planet',
          fragment: 'save the planet',
          tags: ['aliens', 'adventure', 'space', 'fps', 'simulation',
                 'heroic', 'sci-fi', 'action', 'exploration']
        },
        {
          text: 'Solve a puzzle',
          fragment: 'solve a puzzle',
          tags: ['puzzles', 'relax', 'simulation']
        },
        {
          text: 'Be someone new',
          fragment: 'be someone else for a while',
          tags: ['fps', 'adventure', 'dating-sim', 'job-oriented', 'heroic',
                 'sci-fi', 'action', 'exploration']
        },
        {
          text: 'Set the world on fire',
          fragment: 'set the world on fire',
          tags: ['fps', 'adventure', 'relax', 'sci-fi', 'action']
        }
      ]
    },

    // question: multi-player or not?
    {
      prompt: 'Do you want to play...',
      answers: [
        {
          text: 'With other people?',
          fragment: 'with other people',
          tags: ['multi-player', 'cooperative']
        },
        {
          text: 'Against other people?',
          fragment: 'by myself',
          tags: ['multi-player']
        },
        {
          text: 'On your own?',
          fragment: 'by my lonesome',
          tags: ['single-player']
        },
        {
          text: 'Don\'t Care',
          fragment: null,
          tags: []
        }
      ]
    },

    // question: pricing?
    {
      prompt: 'How much are you willing to spend on this game?',
      answers: [
        {
          text: '$25 or more',
          fragment: 'for $25 or more',
          tags: ['price:$$$']
        },
        {
          text: 'Up to $25',
          fragment: 'up to $25',
          tags: ['pricing:$', 'pricing:$$']
        },
        {
          text: 'Keep it under $20',
          fragment: 'while keeping it under $20',
          tags: ['pricing:$']
        },
        {
          text: 'Game free or die',
          fragment: 'for free',
          tags: ['pricing:free']
        }
      ]
    },

    // question: difficulty
    {
      prompt: 'What level of difficulty are you looking for?',
      answers: [
        {
          text: 'Easy',
          fragment: 'something easy',
          tags: ['difficulty:easy']
        },
        {
          text: 'Medium',
          fragment: 'something moderately challenging',
          tags: ['difficulty:medium']
        },
        {
          text: 'Hard',
          fragment: 'something very challenging',
          tags: ['difficulty:hard']
        },
        {
          text: 'Whatever',
          fragment: null,
          tags: []
        }
      ]
    },

    // question: content
    {
      prompt: 'What kind of content are you comfortable with?',
      answers: [
        {
          text: 'No violence, drug use, or bad language, please',
          fragment: 'keep it clean',
          tags: ['content:clean']
        },
        {
          text: 'Pretty time, like a PG-13 movie',
          fragment: 'tame',
          tags: ['content:clean', 'content:tame']
        },
        {
          text: 'Contains sex, violence, and even some rock and roll',
          fragment: 'risque',
          tags: ['content:tame', 'content:risque']
        },
        {
          text: 'I am a hedonist and want it all',
          fragment: 'everything',
          tags: ['content:risque', 'content:hedonist']
        }
      ]
    }
  ]
}
<commit_msg>new questions<commit_after>export default {
  games: [
    {
      name: 'Rise of the Tomb Raider',
      description: `Featuring epic, high-octane action moments set in the most beautiful hostile environments on earth, Rise of the Tomb Raider delivers a cinematic survival action adventure where you will join Lara Croft on her first tomb raiding expedition as she seeks to discover the secret of immortality.`,
      youtubeId: 'qiYiddjc6cU',
      tags: [
        'price:$$$',
        'fps',
        'adventure',
        'action',
        'single-player',
        'exploration'
      ]
    },
    {
      name: 'Crashlands',
      description: `Crashlands is a story-driven crafting ARPG set in an outlandish world of hidden magic and high technology. Fight and tame alien beasts, craft resources into menacing weaponry, befriend the locals, and go toe-to-chin with a world-domineering maniac.`,
      youtubeId: 'q5M6qTEtsSQ',
      tags: [
        'action', 'adventure', 'rpg', 'single-player', 'pricing:$$',
      ]
    },
    {
      name: 'Cobalt',
      description: `Forget everything you've learned about combat. Cobalt's slo-mo mechanic lets you perform moves that other games can't comprehend. Discover the secrets of a distant colony in a cosmic campaign, take on challenges and rule the leaderboards, or face off against others in local and online multiplayer.`,
      youtubeId: 'pK_VCmJlscY',
      tags: [
        'multi-player',
        'single-player',
        'adventure',
        'action',
        'pricing:$$',
      ]
    }
  ],

  questions: [
    // question: what would you like to play?
    {
      prompt: 'What would you like to do today?',
      answers: [
        {
          text: 'Save the planet',
          fragment: 'save the planet',
          tags: ['aliens', 'adventure', 'space', 'fps', 'simulation',
                 'heroic', 'sci-fi', 'action', 'exploration']
        },
        {
          text: 'Work on a puzzle',
          fragment: 'solve a puzzle',
          tags: ['puzzles', 'relax', 'simulation']
        },
        {
          text: 'Be someone new',
          fragment: 'be someone else for a while',
          tags: ['fps', 'adventure', 'dating-sim', 'job-oriented', 'heroic',
                 'sci-fi', 'action', 'exploration']
        },
        {
          text: 'Set the world on fire',
          fragment: 'set the world on fire',
          tags: ['fps', 'adventure', 'relax', 'sci-fi', 'action']
        }
      ]
    },

    // question: multi-player or not?
    {
      prompt: 'Do you want to play...',
      answers: [
        {
          text: 'With other people?',
          fragment: 'with other people',
          tags: ['multi-player', 'cooperative']
        },
        {
          text: 'Against other people?',
          fragment: 'by myself',
          tags: ['multi-player']
        },
        {
          text: 'On your own?',
          fragment: 'by my lonesome',
          tags: ['single-player']
        },
        {
          text: 'Don\'t Care',
          fragment: null,
          tags: []
        }
      ]
    },

    // question: pricing?
    {
      prompt: 'How much are you willing to spend on this game?',
      answers: [
        {
          text: '$25 or more',
          fragment: 'for $25 or more',
          tags: ['price:$$$']
        },
        {
          text: 'Up to $25',
          fragment: 'up to $25',
          tags: ['pricing:$', 'pricing:$$']
        },
        {
          text: 'Keep it under $20',
          fragment: 'while keeping it under $20',
          tags: ['pricing:$']
        },
        {
          text: 'Game free or die',
          fragment: 'for free',
          tags: ['pricing:free']
        }
      ]
    },

    // question: difficulty
    {
      prompt: 'What level of difficulty are you looking for?',
      answers: [
        {
          text: 'Easy',
          fragment: 'something easy',
          tags: ['difficulty:easy']
        },
        {
          text: 'Medium',
          fragment: 'something moderately challenging',
          tags: ['difficulty:medium']
        },
        {
          text: 'Hard',
          fragment: 'something very challenging',
          tags: ['difficulty:hard']
        },
        {
          text: 'Whatever',
          fragment: null,
          tags: []
        }
      ]
    },

    // question: content
    {
      prompt: 'What kind of content are you comfortable with?',
      answers: [
        {
          text: 'No violence, drug use, or bad language, please',
          fragment: 'keep it clean',
          tags: ['content:clean']
        },
        {
          text: 'Pretty time, like a PG-13 movie',
          fragment: 'tame',
          tags: ['content:clean', 'content:tame']
        },
        {
          text: 'Contains sex, violence, and even some rock and roll',
          fragment: 'risque',
          tags: ['content:tame', 'content:risque']
        },
        {
          text: 'I am a hedonist and want it all',
          fragment: 'everything',
          tags: ['content:risque', 'content:hedonist']
        }
      ]
    }
  ]
}
<|endoftext|>


<commit_before>/**
 * @file: database.js
 * @date: September 2017
 * @brief: Database object description
 */

var sqlite3 = require('sqlite3').verbose();

var Event   = require('./event.js');

/**
 * Database(path, callback)
 * @pre: nothing
 * @post: a database is created on disk at path
 * @return: a Database object
 * @param: 'path', the path for the database
 */
function Database(path, callback) {
    this.path = path;

    const create_table = "CREATE TABLE IF NOT EXISTS tb_events"
                       + "("
                       + "uid TEXT NOT NULL, "
                       + "key TEXT NOT NULL, "
                       + "value TEXT NOT NULL, "
                       + "payload TEXT "
                       + ");";

    let obj = this; // used to access 'this' in the following closure

    // create/init connection to db
    this.db = new sqlite3.Database(path, function() {

        // create primary table
        obj.db.run(create_table, function() {
            if (callback) callback();
        });
    });
}; // end of function Database

/**
 * Database#delete_event(event_uid)
 * @pre: the db is initialized properly
 * @post: the event with event_uid is deleted
 * @return: nothing
 * @param: 'event_uid', event to delete
 */
Database.prototype.delete_event = function(event_uid) {
    let query = "DELETE FROM tb_events WHERE uid = '" + event_uid + "';";
    this.db.run(query);
} // end of Database#delete_event

/**
 * Database#keyval_parse(event, key, value, payload)
 * @pre: nothing
 * @post: the event parameter is modified
 * @param: 'event' is the event to modify, 'key' and 'value' are the given keyval pair, 'payload' is an optional payload
 * @return: nothing
 */
Database.prototype.keyval_parse = function(event, key, value, payload) {
    if (key == "name") {
        event.name = value;
    }
    if (key == "description") {
        event.description = value;
    }
    if (key == "date") {
        event.date = value;
    }
    if (key == "times") {
        event.times = value;
    }
    if (key == "owner") {
        event.owner = value;
    }
    if (key == "attendee") {
        let attendee = {};
        attendee.name  = value;
        attendee.times = payload?payload.split(',').map(a=>+a):[];
        event.attendees.push(attendee);
    }
}; // end of function Database#keyval_parse

/**
 * Database#read_event(uid, callback)
 * @pre: the db being initialized
 * @post: the db is read
 * @param: 'uid' is the event uid to get, callback' is a function called when the read is complete
 * @return: nothing
 */
Database.prototype.read_event = function(uid, callback) {
    let event = new Event();
    let obj   = this;

    this.db.each("SELECT * FROM tb_events WHERE uid = '" + uid + "';", function(err, row) {
        event.uid = uid;
        obj.keyval_parse(event, row.key, row.value, row.payload);
        if (typeof event.times === 'string') {
          event.times = event.times.split(',').map(time=>+time)
        }
    }, function(err, rows) {
        if (rows != undefined && rows != 0) {
            callback(event);
        } else {
            callback(null);
        }
    });
}; // end of Database#read_event

/**
 * Database#read_events(callback)
 * @pre: the db being initialized
 * @post: the db is read
 * @param: 'callback' is a function called when the read is complete
 * @return: an array of the event objects read. if the db wasn't initialized, an
 *          empty array is returned
 */
Database.prototype.read_events = function(callback) {
    let events = [];

    let obj = this;
    events = new Array();

    // Get all distinct event UIDs
    this.db.all("SELECT DISTINCT uid FROM tb_events", function(uid_err, uid_rows) {
        if (uid_rows.length == 0) {
            callback([]);
        }

        // Iterate through each UID
        uid_rows.forEach(function(uid_row) {
            // Get the event object with this UID from the db
            obj.read_event(uid_row.uid, function(event) {
                events.push(event);
                if (events.length == uid_rows.length) {
                    callback(events);
                }
            });
        });
    });
}; // end of Database#read_events

/**
 * Database#register(attendee)
 * @pre: the db is initialized properly
 * @post: attendee is registered the given event
 * @return: nothing
 * @param: 'attendee', the person to register
 */
Database.prototype.register = function(attendee) {
    let query = "INSERT INTO tb_events (uid, key, value, payload) VALUES "
              + "("
              + "'" + attendee.event + "', "
              + "'attendee', "
              + "'" + attendee.name + "', "
              + "'" + attendee.times + "'"
              + " );";
    this.db.run(query);
} // end of Database#register

/**
 * Database#write_event(event)
 * @pre: the db is initialized properly
 * @post: event is written to the db
 * @return: nothing
 * @param: 'event', the object to be written to the db
 */
Database.prototype.write_event = function(event) {
    let obj = this;
    let write_keyval = function(key, val) {
        let query = "INSERT INTO tb_events (uid, key, value) VALUES "
                  + "("
                  + "'" + event.uid + "', "
                  + "'" + key + "', "
                  + "'" + val + "'"
                  + " );";
        obj.db.run(query);
    };

    [["name",        event.name],
     ["description", event.description],
     ["date",        event.date],
     ["times",       event.times],
     ["owner",       event.owner]]
     .forEach(function(keyval) {
        write_keyval(keyval[0], keyval[1]);
    });
}; // end of function Database#write_event

module.exports = Database;
<commit_msg>Fix SQL injections (failed on ')<commit_after>/**
 * @file: database.js
 * @date: September 2017
 * @brief: Database object description
 */

var sqlite3 = require('sqlite3').verbose();

var Event   = require('./event.js');

/**
 * Database(path, callback)
 * @pre: nothing
 * @post: a database is created on disk at path
 * @return: a Database object
 * @param: 'path', the path for the database
 */
function Database(path, callback) {
    this.path = path;

    const create_table = "CREATE TABLE IF NOT EXISTS tb_events"
                       + "("
                       + "uid TEXT NOT NULL, "
                       + "key TEXT NOT NULL, "
                       + "value TEXT NOT NULL, "
                       + "payload TEXT "
                       + ");";

    let obj = this; // used to access 'this' in the following closure

    // create/init connection to db
    this.db = new sqlite3.Database(path, function() {

        // create primary table
        obj.db.run(create_table, function() {
            if (callback) callback();
        });
    });
}; // end of function Database

/**
 * Database#delete_event(event_uid)
 * @pre: the db is initialized properly
 * @post: the event with event_uid is deleted
 * @return: nothing
 * @param: 'event_uid', event to delete
 */
Database.prototype.delete_event = function(event_uid) {
    let query = "DELETE FROM tb_events WHERE uid = '" + event_uid + "';";
    this.db.run(query);
} // end of Database#delete_event

/**
 * Database#keyval_parse(event, key, value, payload)
 * @pre: nothing
 * @post: the event parameter is modified
 * @param: 'event' is the event to modify, 'key' and 'value' are the given keyval pair, 'payload' is an optional payload
 * @return: nothing
 */
Database.prototype.keyval_parse = function(event, key, value, payload) {
    if (key == "name") {
        event.name = value;
    }
    if (key == "description") {
        event.description = value;
    }
    if (key == "date") {
        event.date = value;
    }
    if (key == "times") {
        event.times = value;
    }
    if (key == "owner") {
        event.owner = value;
    }
    if (key == "attendee") {
        let attendee = {};
        attendee.name  = value;
        attendee.times = payload?payload.split(',').map(a=>+a):[];
        event.attendees.push(attendee);
    }
}; // end of function Database#keyval_parse

/**
 * Database#read_event(uid, callback)
 * @pre: the db being initialized
 * @post: the db is read
 * @param: 'uid' is the event uid to get, callback' is a function called when the read is complete
 * @return: nothing
 */
Database.prototype.read_event = function(uid, callback) {
    let event = new Event();
    let obj   = this;

    this.db.each("SELECT * FROM tb_events WHERE uid = ? ;", [uid], function(err, row) {
        event.uid = uid;
        obj.keyval_parse(event, row.key, row.value, row.payload);
        if (typeof event.times === 'string') {
          event.times = event.times.split(',').map(time=>+time)
        }
    }, function(err, rows) {
        if (rows != undefined && rows != 0) {
            callback(event);
        } else {
            callback(null);
        }
    });
}; // end of Database#read_event

/**
 * Database#read_events(callback)
 * @pre: the db being initialized
 * @post: the db is read
 * @param: 'callback' is a function called when the read is complete
 * @return: an array of the event objects read. if the db wasn't initialized, an
 *          empty array is returned
 */
Database.prototype.read_events = function(callback) {
    let events = [];

    let obj = this;
    events = new Array();

    // Get all distinct event UIDs
    this.db.all("SELECT DISTINCT uid FROM tb_events", function(uid_err, uid_rows) {
        if (uid_rows.length == 0) {
            callback([]);
        }

        // Iterate through each UID
        uid_rows.forEach(function(uid_row) {
            // Get the event object with this UID from the db
            obj.read_event(uid_row.uid, function(event) {
                events.push(event);
                if (events.length == uid_rows.length) {
                    callback(events);
                }
            });
        });
    });
}; // end of Database#read_events

/**
 * Database#register(attendee)
 * @pre: the db is initialized properly
 * @post: attendee is registered the given event
 * @return: nothing
 * @param: 'attendee', the person to register
 */
Database.prototype.register = function(attendee) {
    this.db.run(
      "INSERT INTO tb_events (uid, key, value, payload) VALUES ( ? , 'attendee', ? , ? );",
      [attendee.event, attendee.name, attendee.times]
    );
} // end of Database#register

/**
 * Database#write_event(event)
 * @pre: the db is initialized properly
 * @post: event is written to the db
 * @return: nothing
 * @param: 'event', the object to be written to the db
 */
Database.prototype.write_event = function(event) {
    let obj = this;
    let write_keyval = function(key, val) {
        obj.db.run(
          "INSERT INTO tb_events (uid, key, value) VALUES ( ? , ? , ? );",
          [event.uid, key, val]
        );
    };

    [["name",        event.name],
     ["description", event.description],
     ["date",        event.date],
     ["times",       event.times.join(',')],
     ["owner",       event.owner]]
     .forEach(function(keyval) {
        write_keyval(keyval[0], keyval[1]);
    });
}; // end of function Database#write_event

module.exports = Database;
<|endoftext|>


<commit_before>import { DocHead } from 'meteor/kadira:dochead';

// lib
import Config from './_config/_config.js';

// models
import Editions from '/imports/models/editions';

const Utils = {
	isReady: (sub) => {
		if (sub) {
			return FlowRouter.subsReady(sub);
		}
		return FlowRouter.subsReady();
	},
	prettyDate: (date) => {
		if (Config.dateFormat) {
			return moment(date).format(Config.dateFormat);
		}
		return moment(date).format('D/M/YYYY');
	},
	timeSince: (date) => {
		let interval;
		const seconds = Math.floor((new Date() - date) / 1000);
		interval = Math.floor(seconds / 31536000);
		if (interval > 1) {
			return `${interval} years ago`;
		}
		interval = Math.floor(seconds / 2592000);
		if (interval > 1) {
			return `${interval} months ago`;
		}
		interval = Math.floor(seconds / 86400);
		if (interval > 1) {
			return `${interval} days ago`;
		}
		interval = Math.floor(seconds / 3600);
		if (interval > 1) {
			return `${interval} hours ago`;
		}
		interval = Math.floor(seconds / 60);
		if (interval > 1) {
			return `${interval} minutes ago`;
		}
		return 'just now';
	},
	trunc: (str, length) => {
		const ending = ' ...';
		let trimLen = length;
		str = str.replace(/<(?:.|\n)*?>/gm, '');

		if (trimLen == null) {
			trimLen = 100;
		}

		if (str.length > length) {
			return str.substring(0, length - ending.length) + ending;
		}

		return str;
	},

	isMobile: () => {
		/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
	},
	loginRequired: () => {
		Router.go('/sign-in');
	},
	scrollToTop: () => {
		$('html,body').animate({
			scrollTop: $('body').offset().top,
		}, 500);
	},
	scrollToElem: () => {
		$('html,body').animate({
			scrollTop: $(selector).offset().top,
		}, 500);
	},
	initHeadroom: () => {
		const headroom = new Headroom(document.getElementById('header'));
		if (headroom) {
			return headroom.init();
		}
		return false;
	},
	capitalize: (str) => {
		const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
		return capitalized;
	},
	defaultCmp: function defaultCmp(a, b) {
		if (a === b) return 0;
		return a < b ? -1 : 1;
	},
	getCmpFunc: (primer, reverse) => {
		const dfc = Utils.defaultCmp;
		let cmp = Utils.defaultCmp;
		if (primer) {
			cmp = (a, b) => { // eslint-disable-line
				return dfc(primer(a), primer(b));
			};
		}
		if (reverse) {
			return (a, b) => { // eslint-disable-line
				return -1 * cmp(a, b);
			};
		}
		return cmp;
	},
	sortBy: function sort() {
		const fields = [];
		const nFields = arguments.length;
		let field;
		let name;
		let cmp;

		// preprocess sorting options
		for (let i = 0; i < nFields; i++) {
			field = arguments[i]; // eslint-disable-line

			if (typeof field === 'string') {
				name = field;
				cmp = Utils.defaultCmp;
			} else {
				name = field.name;
				cmp = Utils.getCmpFunc(field.primer, field.reverse);
			}
			fields.push({
				name,
				cmp,
			});
		}

		// final comparison function
		return (A, B) => {
			let result;

			for (let i = 0; i < nFields; i++) {
				result = 0;
				field = fields[i];
				name = field.name;

				result = field.cmp(A[name], B[name]);
				if (result !== 0) break;
			}
			return result;
		};
	},
	setBaseDocMeta() {
		Utils.setMetaTag('name', 'url', 'content', location.href);
		Utils.setMetaTag('name', 'twitter:card', 'content', 'summary');
		Utils.setMetaTag('name', 'twitter:url', 'content', location.href);
		if ('serviceConfigurations' in Meteor.settings && 'facebook' in Meteor.settings.serviceConfigurations) {
			Utils.setMetaTag('property', 'fb:app_id', 'content', Meteor.settings.serviceConfigurations.facebook.appId);
		}
		Utils.setMetaTag('property', 'og:url', 'content', location.href);
		Utils.setMetaTag('property', 'og:type', 'content', 'website');
		Utils.setLinkTag('rel', 'canonical', 'href', location.href);
	},
	setTitle(title) {
		DocHead.setTitle(`${title}`);
		Utils.setMetaTag('property', 'og:title', 'content', title);
		Utils.setMetaTag('property', 'og:site_name', 'content', title);
		Utils.setMetaTag('property', 'og:local', 'content', 'en_US');
		Utils.setMetaTag('property', 'twitter:title', 'content', title);
		Utils.setMetaTag('itemprop', 'title', 'content', title);
	},
	setDescription(description) {
		Utils.setMetaTag('name', 'description', 'content', description);
		Utils.setMetaTag('property', 'og:description', 'content', description);
		Utils.setMetaTag('property', 'twitter:description', 'content', description);
		Utils.setMetaTag('itemprop', 'description', 'content', description);
	},
	setMetaImage(imageSrc = null) {
		if (imageSrc) {
			Utils.setMetaTag('property', 'og:image', 'content', imageSrc);
			Utils.setMetaTag('property', 'twitter:image', 'content', imageSrc);
			Utils.setMetaTag('itemprop', 'image', 'content', imageSrc);
		} else {
			Utils.setMetaTag('property', 'og:image', 'content', `${location.origin}/images/hector.jpg`);
			Utils.setMetaTag('property', 'twitter:image', 'content', `${location.origin}/images/hector.jpg`);
			Utils.setMetaTag('itemprop', 'image', 'content', `${location.origin}/images/hector.jpg`);
		}
	},
	setMetaTag(attr1, key, attr2, val) {
		const metaInfo = {};
		metaInfo[attr1] = key;
		metaInfo[attr2] = val;
		if ($(`meta[${attr1}="${key}"]`).length) {
			$(`meta[${attr1}="${key}"]`).attr(attr2, val);
		} else {
			DocHead.addMeta(metaInfo);
		}
	},
	setLinkTag(attr1, key, attr2, val) {
		const linkInfo = {};
		linkInfo[attr1] = key;
		linkInfo[attr2] = val;
		if ($(`link[${attr1}="${key}"]`).length) {
			$(`link[${attr1}="${key}"]`).attr(attr2, val);
		} else {
			DocHead.addLink(linkInfo);
		}
	},
	replaceLast(str, find, replace) {
		const index = str.lastIndexOf(find);
		if (index >= 0) {
			return str.substring(0, index) + replace + str.substring(index + find.length);
		}
		return str.toString();
	},
	getEntityData(entity, key) {
		const foundItem = entity.data.mention._root.entries.find(item => (item[0] === key));
		return foundItem[1];
	},
	getEnvDomain() {
		let domain;

		if (location.hostname.match(/\w+.chs.harvard.edu/)) {
			domain = 'chs.harvard.edu';
		} else if (location.hostname.match(/\w+.orphe.us/)) {
			domain = 'orphe.us';
		} else if (location.hostname.match(/\w+.localhost.dev/)) {
			domain = 'localhost.dev';
		}

		return domain;
	},
	textFromTextNodesGroupedByEdition(textNodesCursor) {
		const editions = [];
		textNodesCursor.forEach((textNode) => {
			textNode.text.forEach((text) => {
				let myEdition = editions.find(e => text.edition === e._id);

				if (!myEdition) {
					const foundEdition = Editions.findOne({ _id: text.edition });
					myEdition = {
						_id: foundEdition._id,
						title: foundEdition.title,
						slug: foundEdition.slug,
						lines: [],
					};
					editions.push(myEdition);
				}

				myEdition.lines.push({
					_id: textNode._id,
					html: text.html,
					n: text.n,
				});
			});
		});

		// sort lines for each edition by line number
		for (let i = 0; i < editions.length; ++i) {
			editions[i].lines.sort((a, b) => {
				if (a.n < b.n) {
					return -1;
				} else if (b.n < a.n) {
					return 1;
				}
				return 0;
			});
		}

		return editions;
	},
};

export default Utils;
<commit_msg>change local development environment url to prevent ICANN errors in browser console<commit_after>import { DocHead } from 'meteor/kadira:dochead';

// lib
import Config from './_config/_config.js';

// models
import Editions from '/imports/models/editions';

const Utils = {
	isReady: (sub) => {
		if (sub) {
			return FlowRouter.subsReady(sub);
		}
		return FlowRouter.subsReady();
	},
	prettyDate: (date) => {
		if (Config.dateFormat) {
			return moment(date).format(Config.dateFormat);
		}
		return moment(date).format('D/M/YYYY');
	},
	timeSince: (date) => {
		let interval;
		const seconds = Math.floor((new Date() - date) / 1000);
		interval = Math.floor(seconds / 31536000);
		if (interval > 1) {
			return `${interval} years ago`;
		}
		interval = Math.floor(seconds / 2592000);
		if (interval > 1) {
			return `${interval} months ago`;
		}
		interval = Math.floor(seconds / 86400);
		if (interval > 1) {
			return `${interval} days ago`;
		}
		interval = Math.floor(seconds / 3600);
		if (interval > 1) {
			return `${interval} hours ago`;
		}
		interval = Math.floor(seconds / 60);
		if (interval > 1) {
			return `${interval} minutes ago`;
		}
		return 'just now';
	},
	trunc: (str, length) => {
		const ending = ' ...';
		let trimLen = length;
		str = str.replace(/<(?:.|\n)*?>/gm, '');

		if (trimLen == null) {
			trimLen = 100;
		}

		if (str.length > length) {
			return str.substring(0, length - ending.length) + ending;
		}

		return str;
	},

	isMobile: () => {
		/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
	},
	loginRequired: () => {
		Router.go('/sign-in');
	},
	scrollToTop: () => {
		$('html,body').animate({
			scrollTop: $('body').offset().top,
		}, 500);
	},
	scrollToElem: () => {
		$('html,body').animate({
			scrollTop: $(selector).offset().top,
		}, 500);
	},
	initHeadroom: () => {
		const headroom = new Headroom(document.getElementById('header'));
		if (headroom) {
			return headroom.init();
		}
		return false;
	},
	capitalize: (str) => {
		const capitalized = str.charAt(0).toUpperCase() + str.slice(1);
		return capitalized;
	},
	defaultCmp: function defaultCmp(a, b) {
		if (a === b) return 0;
		return a < b ? -1 : 1;
	},
	getCmpFunc: (primer, reverse) => {
		const dfc = Utils.defaultCmp;
		let cmp = Utils.defaultCmp;
		if (primer) {
			cmp = (a, b) => { // eslint-disable-line
				return dfc(primer(a), primer(b));
			};
		}
		if (reverse) {
			return (a, b) => { // eslint-disable-line
				return -1 * cmp(a, b);
			};
		}
		return cmp;
	},
	sortBy: function sort() {
		const fields = [];
		const nFields = arguments.length;
		let field;
		let name;
		let cmp;

		// preprocess sorting options
		for (let i = 0; i < nFields; i++) {
			field = arguments[i]; // eslint-disable-line

			if (typeof field === 'string') {
				name = field;
				cmp = Utils.defaultCmp;
			} else {
				name = field.name;
				cmp = Utils.getCmpFunc(field.primer, field.reverse);
			}
			fields.push({
				name,
				cmp,
			});
		}

		// final comparison function
		return (A, B) => {
			let result;

			for (let i = 0; i < nFields; i++) {
				result = 0;
				field = fields[i];
				name = field.name;

				result = field.cmp(A[name], B[name]);
				if (result !== 0) break;
			}
			return result;
		};
	},
	setBaseDocMeta() {
		Utils.setMetaTag('name', 'url', 'content', location.href);
		Utils.setMetaTag('name', 'twitter:card', 'content', 'summary');
		Utils.setMetaTag('name', 'twitter:url', 'content', location.href);
		if ('serviceConfigurations' in Meteor.settings && 'facebook' in Meteor.settings.serviceConfigurations) {
			Utils.setMetaTag('property', 'fb:app_id', 'content', Meteor.settings.serviceConfigurations.facebook.appId);
		}
		Utils.setMetaTag('property', 'og:url', 'content', location.href);
		Utils.setMetaTag('property', 'og:type', 'content', 'website');
		Utils.setLinkTag('rel', 'canonical', 'href', location.href);
	},
	setTitle(title) {
		DocHead.setTitle(`${title}`);
		Utils.setMetaTag('property', 'og:title', 'content', title);
		Utils.setMetaTag('property', 'og:site_name', 'content', title);
		Utils.setMetaTag('property', 'og:local', 'content', 'en_US');
		Utils.setMetaTag('property', 'twitter:title', 'content', title);
		Utils.setMetaTag('itemprop', 'title', 'content', title);
	},
	setDescription(description) {
		Utils.setMetaTag('name', 'description', 'content', description);
		Utils.setMetaTag('property', 'og:description', 'content', description);
		Utils.setMetaTag('property', 'twitter:description', 'content', description);
		Utils.setMetaTag('itemprop', 'description', 'content', description);
	},
	setMetaImage(imageSrc = null) {
		if (imageSrc) {
			Utils.setMetaTag('property', 'og:image', 'content', imageSrc);
			Utils.setMetaTag('property', 'twitter:image', 'content', imageSrc);
			Utils.setMetaTag('itemprop', 'image', 'content', imageSrc);
		} else {
			Utils.setMetaTag('property', 'og:image', 'content', `${location.origin}/images/hector.jpg`);
			Utils.setMetaTag('property', 'twitter:image', 'content', `${location.origin}/images/hector.jpg`);
			Utils.setMetaTag('itemprop', 'image', 'content', `${location.origin}/images/hector.jpg`);
		}
	},
	setMetaTag(attr1, key, attr2, val) {
		const metaInfo = {};
		metaInfo[attr1] = key;
		metaInfo[attr2] = val;
		if ($(`meta[${attr1}="${key}"]`).length) {
			$(`meta[${attr1}="${key}"]`).attr(attr2, val);
		} else {
			DocHead.addMeta(metaInfo);
		}
	},
	setLinkTag(attr1, key, attr2, val) {
		const linkInfo = {};
		linkInfo[attr1] = key;
		linkInfo[attr2] = val;
		if ($(`link[${attr1}="${key}"]`).length) {
			$(`link[${attr1}="${key}"]`).attr(attr2, val);
		} else {
			DocHead.addLink(linkInfo);
		}
	},
	replaceLast(str, find, replace) {
		const index = str.lastIndexOf(find);
		if (index >= 0) {
			return str.substring(0, index) + replace + str.substring(index + find.length);
		}
		return str.toString();
	},
	getEntityData(entity, key) {
		const foundItem = entity.data.mention._root.entries.find(item => (item[0] === key));
		return foundItem[1];
	},
	getEnvDomain() {
		let domain;

		if (location.hostname.match(/\w+.chs.harvard.edu/)) {
			domain = 'chs.harvard.edu';
		} else if (location.hostname.match(/\w+.orphe.us/)) {
			domain = 'orphe.us';
		} else if (location.hostname.match(/\w+.chs.local/)) {
			domain = 'chs.local';
		}

		return domain;
	},
	textFromTextNodesGroupedByEdition(textNodesCursor) {
		const editions = [];
		textNodesCursor.forEach((textNode) => {
			textNode.text.forEach((text) => {
				let myEdition = editions.find(e => text.edition === e._id);

				if (!myEdition) {
					const foundEdition = Editions.findOne({ _id: text.edition });
					myEdition = {
						_id: foundEdition._id,
						title: foundEdition.title,
						slug: foundEdition.slug,
						lines: [],
					};
					editions.push(myEdition);
				}

				myEdition.lines.push({
					_id: textNode._id,
					html: text.html,
					n: text.n,
				});
			});
		});

		// sort lines for each edition by line number
		for (let i = 0; i < editions.length; ++i) {
			editions[i].lines.sort((a, b) => {
				if (a.n < b.n) {
					return -1;
				} else if (b.n < a.n) {
					return 1;
				}
				return 0;
			});
		}

		return editions;
	},
};

export default Utils;
<|endoftext|>


<commit_before>var global = require('./_global');
var core = require('./_core');
var ctx = require('./_ctx');
var hide = require('./_hide');
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && key in exports) continue;
    // export native or passed
    out = own ? target[key] : source[key];
    // prevent global pollution for namespaces
    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
    // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global)
    // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? (function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0: return new C();
            case 1: return new C(a);
            case 2: return new C(a, b);
          } return new C(a, b, c);
        } return C.apply(this, arguments);
      };
      F[PROTOTYPE] = C[PROTOTYPE];
      return F;
    // make static versions for prototype methods
    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out;
      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
};
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
<commit_msg>fix __(define|lookup)[GS]etter__ import in the `library` version<commit_after>var global = require('./_global');
var core = require('./_core');
var ctx = require('./_ctx');
var hide = require('./_hide');
var has = require('./_has');
var PROTOTYPE = 'prototype';

var $export = function (type, name, source) {
  var IS_FORCED = type & $export.F;
  var IS_GLOBAL = type & $export.G;
  var IS_STATIC = type & $export.S;
  var IS_PROTO = type & $export.P;
  var IS_BIND = type & $export.B;
  var IS_WRAP = type & $export.W;
  var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  var expProto = exports[PROTOTYPE];
  var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  var key, own, out;
  if (IS_GLOBAL) source = name;
  for (key in source) {
    // contains in native
    own = !IS_FORCED && target && target[key] !== undefined;
    if (own && has(exports, key)) continue;
    // export native or passed
    out = own ? target[key] : source[key];
    // prevent global pollution for namespaces
    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
    // bind timers to global for call from export context
    : IS_BIND && own ? ctx(out, global)
    // wrap global constructors for prevent change them in library
    : IS_WRAP && target[key] == out ? (function (C) {
      var F = function (a, b, c) {
        if (this instanceof C) {
          switch (arguments.length) {
            case 0: return new C();
            case 1: return new C(a);
            case 2: return new C(a, b);
          } return new C(a, b, c);
        } return C.apply(this, arguments);
      };
      F[PROTOTYPE] = C[PROTOTYPE];
      return F;
    // make static versions for prototype methods
    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
    if (IS_PROTO) {
      (exports.virtual || (exports.virtual = {}))[key] = out;
      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
      if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
    }
  }
};
// type bitmap
$export.F = 1;   // forced
$export.G = 2;   // global
$export.S = 4;   // static
$export.P = 8;   // proto
$export.B = 16;  // bind
$export.W = 32;  // wrap
$export.U = 64;  // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
<|endoftext|>


<commit_before>/**
 * @file mute command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

exports.exec = async (Bastion, message, args) => {
  try {
    let user;
    if (message.mentions.users.size) {
      user = message.mentions.users.first();
    }
    else if (args.id) {
      user = await Bastion.fetchUser(args.id);
    }
    if (!user) {
      /**
      * The command was ran with invalid parameters.
      * @fires commandUsage
      */
      return Bastion.emit('commandUsage', message, this.help);
    }

    let member = await message.guild.fetchMember(user.id);
    if (message.author.id !== message.guild.ownerID && message.member.highestRole.comparePositionTo(member.highestRole) <= 0) return Bastion.log.info(Bastion.strings.error(message.guild.language, 'lowerRole', true));

    await member.setMute(true);

    args.reason = args.reason.join(' ');

    message.channel.send({
      embed: {
        color: Bastion.colors.ORANGE,
        description: `${message.author.tag} voice-muted ${user.tag} with reason **${args.reason}**`
      }
    }).catch(e => {
      Bastion.log.error(e);
    });

    /**
    * Logs moderation events if it is enabled
    * @fires moderationLog
    */
    Bastion.emit('moderationLog', message.guild, message.author, this.help.name, user, args.reason);
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [ 'm' ],
  enabled: true,
  argsDefinitions: [
    { name: 'id', type: String, defaultOption: true },
    { name: 'reason', alias: 'r', type: String, multiple: true, defaultValue: [ 'No reason given.' ] }
  ]
};

exports.help = {
  name: 'mute',
  botPermission: 'MUTE_MEMBERS',
  userTextPermission: 'MUTE_MEMBERS',
  userVoicePermission: '',
  usage: 'mute @user-mention [Reason]',
  example: [ 'mute @user#0001 Reason for the mute.' ]
};
<commit_msg>Updated usage & example - mute command<commit_after>/**
 * @file mute command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

exports.exec = async (Bastion, message, args) => {
  try {
    let user;
    if (message.mentions.users.size) {
      user = message.mentions.users.first();
    }
    else if (args.id) {
      user = await Bastion.fetchUser(args.id);
    }
    if (!user) {
      /**
      * The command was ran with invalid parameters.
      * @fires commandUsage
      */
      return Bastion.emit('commandUsage', message, this.help);
    }

    let member = await message.guild.fetchMember(user.id);
    if (message.author.id !== message.guild.ownerID && message.member.highestRole.comparePositionTo(member.highestRole) <= 0) return Bastion.log.info(Bastion.strings.error(message.guild.language, 'lowerRole', true));

    await member.setMute(true);

    args.reason = args.reason.join(' ');

    message.channel.send({
      embed: {
        color: Bastion.colors.ORANGE,
        description: `${message.author.tag} voice-muted ${user.tag} with reason **${args.reason}**`
      }
    }).catch(e => {
      Bastion.log.error(e);
    });

    /**
    * Logs moderation events if it is enabled
    * @fires moderationLog
    */
    Bastion.emit('moderationLog', message.guild, message.author, this.help.name, user, args.reason);
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [ 'm' ],
  enabled: true,
  argsDefinitions: [
    { name: 'id', type: String, defaultOption: true },
    { name: 'reason', alias: 'r', type: String, multiple: true, defaultValue: [ 'No reason given.' ] }
  ]
};

exports.help = {
  name: 'mute',
  botPermission: 'MUTE_MEMBERS',
  userTextPermission: 'MUTE_MEMBERS',
  userVoicePermission: '',
  usage: 'mute <@USER_MENTION | USER_ID> -r [Reason]',
  example: [ 'mute @user#001 -r Shouting like crazy', 'mute 167147569575323761 -r Singing like a broken radio' ]
};
<|endoftext|>


<commit_before>function Elevator() {
  // body...
  this.currentFloor = Math.floor((Math.random() * 100) + 1);
  this.startingFloor = Math.floor((this.currentFloor / 5));
  this.child = new Plucky;
  this.player = new Player;
  this.rollCount = 0;
  this.numOfTries = 4;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.elevatorInfo = function () {
  // body...
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.currentFloor, 'floor'].join(" ");

  document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollCount += 1;
  this.floorDifference = Math.abs(this.currentFloor - this.player.desiredFloor);

  if(this.rollCount == this.numOfTries){
    var plucky = '
My turn! not your turn! my turn! I push the button!';
    var plucky2 = 'My elalator! not your elalator, my elalator.
'
    var result = ('Sorry. You died of starvation.');
    var currentStatus = ['Your current floor was:', this.currentFloor].join(" ");
  document.getElementById('results').innerHTML = [plucky, plucky2, result, currentStatus].join("
");
    document.getElementById('roll').disabled = true;
  }
  else
    if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor += 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if (this.currentFloor != this.player.desiredFloor &&  this.player.desiredFloor < this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor -= 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      document.getElementById('roll').disabled = true;
      document.getElementById('winner').innerHTML = [results];
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child.reroll();
  if (this.child.chanceOfPushingButton < 60) {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = Math.floor(Math.random() * 100 + 1);
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
document.getElementById('results').innerHTML = ' ';
document.getElementById('floor').innerHTML = " ";
document.getElementById('winner').innerHTML = " ";
game = new Elevator();
game.elevatorInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};
<commit_msg>refactor code<commit_after>function Elevator() {
  // body...
  this.currentFloor = Math.floor((Math.random() * 100) + 1);
  this.startingFloor = Math.floor((this.currentFloor / 5));
  this.child = new Plucky;
  this.player = new Player;
  this.rollCount = 0;
  this.numOfTries = 4;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.elevatorInfo = function () {
  // body...
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.currentFloor, 'floor'].join(" ");

  document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollCount += 1;
  this.floorDifference = Math.abs(this.currentFloor - this.player.desiredFloor);

  if(this.rollCount == this.numOfTries){
    var plucky = '
My turn! not your turn! my turn! I push the button!';
    var plucky2 = 'My elalator! not your elalator, my elalator.
'
    var result = ('Sorry. You died of starvation.');
    var currentStatus = ['Your current floor was:', this.currentFloor].join(" ");
  document.getElementById('results').innerHTML = [plucky, plucky2, result, currentStatus].join("
");
    document.getElementById('roll').disabled = true;
  }
  else
    if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor += 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if (this.currentFloor != this.player.desiredFloor &&  this.player.desiredFloor < this.currentFloor) {
      this.child.reroll();
      for (var i = 0; i < this.floorDifference / 2; i++) {
        this.calculateCurrentFloor();
      }
      for (var i = 0; i < this.player.wins; i++) {
        this.currentFloor -= 1;
        var floor = this.currentFloor;
        var str = 'Floor:';
        document.getElementById('floor').innerHTML = [str, floor].join(" ");
        if (this.currentFloor == this.player.desiredFloor){
          var result = 'The player has won!';
          document.getElementById('roll').disabled = true;
          document.getElementById('winner').innerHTML = [result];
          break;
        }
        this.elevatorInfo();
      }

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      document.getElementById('roll').disabled = true;
      document.getElementById('winner').innerHTML = [results];
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child.reroll();
  if (this.child.chanceOfPushingButton < 60) {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = Math.floor(Math.random() * 100 + 1);
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = 0;
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
document.getElementById('results').innerHTML = ' ';
document.getElementById('floor').innerHTML = " ";
document.getElementById('winner').innerHTML = " ";
game = new Elevator();
game.elevatorInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};
<|endoftext|>