<commit_before>// Except as noted, this content is licensed under Creative Commons
// Attribution 3.0

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Generate a table of contents (godocs_generateTOC)
 *  + Add links up to the top of the doc from each section (godocs_addTopLinks)
 */

/* We want to do some stuff on page load (after the HTML is rendered).
   So listen for that:
 */
function bindEvent(el, e, fn) {
  if (el.addEventListener){
    el.addEventListener(e, fn, false);
  } else if (el.attachEvent){
    el.attachEvent('on'+e, fn);
  }
}
bindEvent(window, 'load', godocs_onload);

function godocs_onload() {
  godocs_bindSearchEvents();
  godocs_generateTOC();
  godocs_addTopLinks();
}

function godocs_bindSearchEvents() {
  var search = document.getElementById('search');
  function clearInactive() {
    if (search.className == "inactive") {
      search.value = "";
      search.className = "";
    }
  }
  function restoreInactive() {
    if (search.value != "") {
      return;
    }
    if (search.type != "search") {
      search.value = search.getAttribute("placeholder");
    }
    search.className = "inactive";
  }
  restoreInactive();
  bindEvent(search, 'focus', clearInactive);
  bindEvent(search, 'blur', restoreInactive);
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links.  "Decorates" the element with id=="nav" with this table of contents.
 */
function godocs_generateTOC() {
  var navbar = document.getElementById('nav');
  if (!navbar) { return; }

  var toc_items = [];

  var i;
  for (i = 0; i < navbar.parentNode.childNodes.length; i++) {
    var node = navbar.parentNode.childNodes[i];
    if ((node.tagName == 'h2') || (node.tagName == 'H2')) {
      if (!node.id) {
        node.id = 'tmp_' + i;
      }
      var text = godocs_nodeToText(node);
      if (!text) { continue; }

      var textNode = document.createTextNode(text);

      var link = document.createElement('a');
      link.href = '#' + node.id;
      link.appendChild(textNode);

      // Then create the item itself
      var item = document.createElement('dt');

      item.appendChild(link);
      toc_items.push(item);
    }
    if ((node.tagName == 'h3') || (node.tagName == 'H3')) {
      if (!node.id) {
        node.id = 'tmp_' + i;
      }
      var text = godocs_nodeToText(node);
      if (!text) { continue; }

      var textNode = document.createTextNode(text);

      var link = document.createElement('a');
      link.href = '#' + node.id;
      link.appendChild(textNode);

      // Then create the item itself
      var item = document.createElement('dd');

      item.appendChild(link);
      toc_items.push(item);
    }
  }

  if (!toc_items.length) { return; }

  var dl1 = document.createElement('dl');
  var dl2 = document.createElement('dl');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }

  for (i = 0; i < split_index; i++) {
    dl1.appendChild(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.appendChild(toc_items[i]);
  }

  var tocTable = document.createElement('table');
  navbar.appendChild(tocTable);
  tocTable.className = 'unruled';
  var tocBody = document.createElement('tbody');
  tocTable.appendChild(tocBody);

  var tocRow = document.createElement('tr');
  tocBody.appendChild(tocRow);

  // 1st column
  var tocCell = document.createElement('td');
  tocCell.className = 'first';
  tocRow.appendChild(tocCell);
  tocCell.appendChild(dl1);

  // 2nd column
  tocCell = document.createElement('td');
  tocRow.appendChild(tocCell);
  tocCell.appendChild(dl2);
}

/* Returns the "This sweet header" from
This sweet header
.
 * Takes a node, returns a string.
 */
function godocs_nodeToText(node) {
  var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :(

  var text = '';
  for (var j = 0; j != node.childNodes.length; j++) {
    var child = node.childNodes[j];
    if (child.nodeType == TEXT_NODE) {
      if (child.nodeValue != '[Top]') { //ok, that's a hack, but it works.
        text = text + child.nodeValue;
      }
    } else {
      text = text + godocs_nodeToText(child);
    }
  }
  return text;
}

/* For each H2 heading, add a link up to the #top of the document.
 * (As part of this: ensure existence of 'top' named anchor link
 * (theoretically at doc's top).)
 */
function godocs_addTopLinks() {
  /* Make sure there's a "top" to link to. */
  var top = document.getElementById('top');
  if (!top) {
    document.body.id = 'top';
  }

  if (!document.getElementsByTagName) return; // no browser support

  var headers = document.getElementsByTagName('h2');

  for (var i = 0; i < headers.length; i++) {
    var span = document.createElement('span');
    span.className = 'navtop';
    var link = document.createElement('a');
    span.appendChild(link);
    link.href = '#top';
    var textNode = document.createTextNode('[Top]');
    link.appendChild(textNode);
    headers[i].appendChild(span);
  }
}
<commit_msg>godoc: if there is no search box, don't run the respective JS code<commit_after>// Except as noted, this content is licensed under Creative Commons
// Attribution 3.0

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Generate a table of contents (godocs_generateTOC)
 *  + Add links up to the top of the doc from each section (godocs_addTopLinks)
 */

/* We want to do some stuff on page load (after the HTML is rendered).
   So listen for that:
 */
function bindEvent(el, e, fn) {
  if (el.addEventListener){
    el.addEventListener(e, fn, false);
  } else if (el.attachEvent){
    el.attachEvent('on'+e, fn);
  }
}
bindEvent(window, 'load', godocs_onload);

function godocs_onload() {
  godocs_bindSearchEvents();
  godocs_generateTOC();
  godocs_addTopLinks();
}

function godocs_bindSearchEvents() {
  var search = document.getElementById('search');
  if (!search) {
    // no search box (index disabled)
    return;
  }
  function clearInactive() {
    if (search.className == "inactive") {
      search.value = "";
      search.className = "";
    }
  }
  function restoreInactive() {
    if (search.value != "") {
      return;
    }
    if (search.type != "search") {
      search.value = search.getAttribute("placeholder");
    }
    search.className = "inactive";
  }
  restoreInactive();
  bindEvent(search, 'focus', clearInactive);
  bindEvent(search, 'blur', restoreInactive);
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links.  "Decorates" the element with id=="nav" with this table of contents.
 */
function godocs_generateTOC() {
  var navbar = document.getElementById('nav');
  if (!navbar) { return; }

  var toc_items = [];

  var i;
  for (i = 0; i < navbar.parentNode.childNodes.length; i++) {
    var node = navbar.parentNode.childNodes[i];
    if ((node.tagName == 'h2') || (node.tagName == 'H2')) {
      if (!node.id) {
        node.id = 'tmp_' + i;
      }
      var text = godocs_nodeToText(node);
      if (!text) { continue; }

      var textNode = document.createTextNode(text);

      var link = document.createElement('a');
      link.href = '#' + node.id;
      link.appendChild(textNode);

      // Then create the item itself
      var item = document.createElement('dt');

      item.appendChild(link);
      toc_items.push(item);
    }
    if ((node.tagName == 'h3') || (node.tagName == 'H3')) {
      if (!node.id) {
        node.id = 'tmp_' + i;
      }
      var text = godocs_nodeToText(node);
      if (!text) { continue; }

      var textNode = document.createTextNode(text);

      var link = document.createElement('a');
      link.href = '#' + node.id;
      link.appendChild(textNode);

      // Then create the item itself
      var item = document.createElement('dd');

      item.appendChild(link);
      toc_items.push(item);
    }
  }

  if (!toc_items.length) { return; }

  var dl1 = document.createElement('dl');
  var dl2 = document.createElement('dl');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }

  for (i = 0; i < split_index; i++) {
    dl1.appendChild(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.appendChild(toc_items[i]);
  }

  var tocTable = document.createElement('table');
  navbar.appendChild(tocTable);
  tocTable.className = 'unruled';
  var tocBody = document.createElement('tbody');
  tocTable.appendChild(tocBody);

  var tocRow = document.createElement('tr');
  tocBody.appendChild(tocRow);

  // 1st column
  var tocCell = document.createElement('td');
  tocCell.className = 'first';
  tocRow.appendChild(tocCell);
  tocCell.appendChild(dl1);

  // 2nd column
  tocCell = document.createElement('td');
  tocRow.appendChild(tocCell);
  tocCell.appendChild(dl2);
}

/* Returns the "This sweet header" from
This sweet header
.
 * Takes a node, returns a string.
 */
function godocs_nodeToText(node) {
  var TEXT_NODE = 3; // Defined in Mozilla but not MSIE :(

  var text = '';
  for (var j = 0; j != node.childNodes.length; j++) {
    var child = node.childNodes[j];
    if (child.nodeType == TEXT_NODE) {
      if (child.nodeValue != '[Top]') { //ok, that's a hack, but it works.
        text = text + child.nodeValue;
      }
    } else {
      text = text + godocs_nodeToText(child);
    }
  }
  return text;
}

/* For each H2 heading, add a link up to the #top of the document.
 * (As part of this: ensure existence of 'top' named anchor link
 * (theoretically at doc's top).)
 */
function godocs_addTopLinks() {
  /* Make sure there's a "top" to link to. */
  var top = document.getElementById('top');
  if (!top) {
    document.body.id = 'top';
  }

  if (!document.getElementsByTagName) return; // no browser support

  var headers = document.getElementsByTagName('h2');

  for (var i = 0; i < headers.length; i++) {
    var span = document.createElement('span');
    span.className = 'navtop';
    var link = document.createElement('a');
    span.appendChild(link);
    link.href = '#top';
    var textNode = document.createTextNode('[Top]');
    link.appendChild(textNode);
    headers[i].appendChild(span);
  }
}
<|endoftext|>


<commit_before>const extend = require('./helper/extend')
const removeByIndex = require('./helper/remove-by-index')

function BehaviorContainer (entity, system) {
  this.entity = entity

  // store options of the instances
  this._optionsList = []

  // use the 'key' to store informations of the instance
  this._infoList = {}

  // store paused instances
  this._pausedList = {}

  this.system = system
}

BehaviorContainer.prototype = {

  constructor: BehaviorContainer,

  index: 0,

  set (key, behavior, options) {
    if (this.has(key)) return false

    // inherit and override
    const defaults = extend({}, behavior.options)
    options = extend(defaults, options)
    options.$key = key

    // store necessary informations and also the instance
    this._infoList[key] = {
      behavior: behavior,
      index: this._optionsList.push(options) - 1
    }

    // process "create" action of newly instance
    this.process(key, 'create')

    // returns the key of newly instance
    return key
  },

  remove (key) {
    if (!this.has(key)) return false

    const index = this._infoList[key].index
    const list = this._optionsList
    const len = list.length
    const last = list[len - 1]

    // call method 'destroy' before really remove
    this.process(key, 'destroy')

    // remove from instance list
    if (len !== 1 && (index + 1) !== len) {
      this._infoList[last.$key].index = index;
    }
    removeByIndex(list, index)

    // remove from other lists
    this._pausedList[key] = false
    this._infoList[key] = false

    return true
  },

  removeAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    // reverse loop because it's necessary
    for (i = len - 1; i !== -1; --i) {
      this.remove(list[i].$key)
    }
  },

  has (key) {
    return typeof this._infoList[key] === 'object'
  },

  pause (key) {
    if (this.has(key) && !this.isPaused(key)) {
      // process `paused` before pause the instance
      this.process(key, 'paused')
      this._pausedList[key] = true
      return true
    }
    return false
  },

  resume (key) {
    if (this.has(key) && this.isPaused(key)) {
      this._pausedList[key] = false
      // process `resumed` after resume the instance
      this.process(key, 'resumed')
      return true
    }
    return false
  },

  pauseAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.pause(list[i].$key)
    }
  },

  resumeAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.resume(list[i].$key)
    }
  },

  isPaused (key) {
    return this._pausedList[key]
  },

  process (key, methodName, ...args) {
    if (!this.has(key) || this.isPaused(key)) return

    const info = this._infoList[key]
    const method = info.behavior[methodName]
    const entity = this.entity
    const options = this._optionsList[info.index]
    let result = false

    if (typeof method !== 'undefined') {
      switch(args.length) {
        case 0:
          result = method(entity, options)
          break
        case 1:
          result = method(entity, options, args[0])
          break
        case 2:
          result = method(entity, options, args[0], args[1])
          break
        case 3:
          result = method(entity, options, args[0], args[1], args[2])
          break
        default:
          result = method.apply(false, [entity, options, ...args])
          break
      }
    }

    return result
  },

  processAll (methodName, ...args) {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.process(list[i].$key, methodName, ...args)
    }
  }

}

module.exports = BehaviorContainer
<commit_msg>remove `extend` helper<commit_after>const removeByIndex = require('./helper/remove-by-index')

function BehaviorContainer (entity, system) {
  this.entity = entity

  // store options of the instances
  this._optionsList = []

  // use the 'key' to store informations of the instance
  this._infoList = {}

  // store paused instances
  this._pausedList = {}

  this.system = system
}

BehaviorContainer.prototype = {

  constructor: BehaviorContainer,

  index: 0,

  set (key, behavior, options) {
    if (this.has(key)) return false

    // inherit and override
    const options = Object.assign(Object.create(null), behavior.options, options)
    options.$key = key

    // store necessary informations and also the instance
    this._infoList[key] = {
      behavior: behavior,
      index: this._optionsList.push(options) - 1
    }

    // process "create" action of newly instance
    this.process(key, 'create')

    // returns the key of newly instance
    return key
  },

  remove (key) {
    if (!this.has(key)) return false

    const index = this._infoList[key].index
    const list = this._optionsList
    const len = list.length
    const last = list[len - 1]

    // call method 'destroy' before really remove
    this.process(key, 'destroy')

    // remove from instance list
    if (len !== 1 && (index + 1) !== len) {
      this._infoList[last.$key].index = index;
    }
    removeByIndex(list, index)

    // remove from other lists
    this._pausedList[key] = false
    this._infoList[key] = false

    return true
  },

  removeAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    // reverse loop because it's necessary
    for (i = len - 1; i !== -1; --i) {
      this.remove(list[i].$key)
    }
  },

  has (key) {
    return typeof this._infoList[key] === 'object'
  },

  pause (key) {
    if (this.has(key) && !this.isPaused(key)) {
      // process `paused` before pause the instance
      this.process(key, 'paused')
      this._pausedList[key] = true
      return true
    }
    return false
  },

  resume (key) {
    if (this.has(key) && this.isPaused(key)) {
      this._pausedList[key] = false
      // process `resumed` after resume the instance
      this.process(key, 'resumed')
      return true
    }
    return false
  },

  pauseAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.pause(list[i].$key)
    }
  },

  resumeAll () {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.resume(list[i].$key)
    }
  },

  isPaused (key) {
    return this._pausedList[key]
  },

  process (key, methodName, ...args) {
    if (!this.has(key) || this.isPaused(key)) return

    const info = this._infoList[key]
    const method = info.behavior[methodName]
    const entity = this.entity
    const options = this._optionsList[info.index]
    let result = false

    if (typeof method !== 'undefined') {
      switch(args.length) {
        case 0:
          result = method(entity, options)
          break
        case 1:
          result = method(entity, options, args[0])
          break
        case 2:
          result = method(entity, options, args[0], args[1])
          break
        case 3:
          result = method(entity, options, args[0], args[1], args[2])
          break
        default:
          result = method.apply(false, [entity, options, ...args])
          break
      }
    }

    return result
  },

  processAll (methodName, ...args) {
    const list = this._optionsList
    const len = list.length

    if (len === 0) return

    for (let i = 0; i < len; ++i) {
      this.process(list[i].$key, methodName, ...args)
    }
  }

}

module.exports = BehaviorContainer
<|endoftext|>


<commit_before>var config = {
  dev :  true,
  poguesURL : 'http://s90datalift.ad.intra.intra:9000/exist/pogues';
};

module.exports = config;
<commit_msg>Fix syntax in config.js<commit_after>var config = {
  dev :  true,
  poguesURL : 'http://s90datalift.ad.intra.intra:9000/exist/pogues'
};

module.exports = config;
<|endoftext|>


<commit_before>require('es6-promise').polyfill()
require('./blog.js')
require('./case-study-carousel.js')
require('./docs.js')
require('./events-carousel.js')
require('./fetch.js')
require('./get-started.js')
require('./install.js')
require('./modal.js')
require('./overlay.js')
require('./quotes-carousel.js')
require('./smooth-scroll.js')
require('./stackdiagram.js')
require('./typer.js')
require('./typer2.js')
require('./html-include.js')
require('swagger-ui-browserify')
require('./ngindox.js')

import Wallop from 'wallop';
import Hammer from 'hammerjs';

// globals
const compareVersions = require('compare-versions');
window.compareVersions = compareVersions;

const docPathName = window.location.pathname

// Mobile menu
$('#nav-icon').on('click', function (event) {
  event.preventDefault();
  if($('#nav-icon').hasClass('open')) {
    $('.navigation').removeClass('mobile-menu--open');
    $('.menu-mobile').removeClass('open');
    $('#nav-icon').removeClass('open');
    $('body').removeAttr('style');
    $('html').removeAttr('style');
  } else {
    $('.navigation').addClass('mobile-menu--open');
    $('.menu-mobile').addClass('open');
    $('#nav-icon').addClass('open');
    $('body').attr('style', 'overflow: hidden;');
    $('html').attr('style', 'overflow: hidden;');
  }
})

// Array.find polyfill
if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

/***********************
  Dropdown
***********************/
$('.dropdown').click(function(event){
  $('html').on('click',function() {
    $('.dropdown').removeClass('is-active')
  });

  $(this).toggleClass('is-active')

  event.stopPropagation()
})

/***********************
  Set timeout function
***********************/
function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
  };

  this.cancel = function() {
    window.clearTimeout(timerId);
  };

  this.resume();
}

/****************
  Slider
****************/
var wallopEl = document.querySelector('.Wallop');
if(wallopEl){
  var slider = new Wallop(wallopEl);

  // Add auto-play functionality
  var autoPlayMs = 6000;
  var nextTimeout;
  var loadNext = function() {
    var nextIndex = (slider.currentItemIndex + 1) % slider.allItemsArray.length;
    slider.goTo(nextIndex);
  }
  nextTimeout = new Timer(function() { loadNext(); }, autoPlayMs);
  slider.on('change', function() {
    nextTimeout.resume();
  });

  slider.on('mouseenter', function(){
    nextTimeout.cancel();
  })

  slider.on('mouseleave', function(){
    nextTimeout.resume();
  })

  // Enable touch for Wallop
  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swipeleft', function() {
    slider.next();
  });

  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swiperight', function() {
    slider.previous();
  });
}

/****************
  Clickable headers
****************/
$('#docs-content h1, #docs-content h2, #docs-content h3, #docs-content h4, #docs-content h5, #docs-content h6').each(function( index ) {
  var hashURL = $(this).attr('id')
  $(this).wrapInner('')
});

/****************
  SwaggerUI
****************/
$(document).ready(function() {
  var yamlFile = $('[data-api]').data('api');

  var swaggerUi = new SwaggerUi({
    url: yamlFile,
    dom_id: 'swagger-ui-container',
    docExpansion: 'none'
  });

  swaggerUi.load();
})

/****************
  Add proper submit feedback link to docs
****************/
const docPageTitle = ($('h1.docs-heading').text()).replace(' ', '+')
const jPid = 10001 // pid
const jIssueType = 10100 // issuetype
const jSummary = `Feedback+for+${docPageTitle}` // summary
const jDescription = `Source: ${window.location.href}` // description
const jLabels = 'documentation'

$('#submit-feedback').attr('href', `https://jira.dcos.io/secure/CreateIssueDetails!init.jspa?pid=${jPid}&issuetype=${jIssueType}&summary=${jSummary}&description=${jDescription}&labels=${jLabels}`)

/****************
  Docs version switch 404 prevention
****************/

const currentUrlPath = window.location.pathname
var pathArray = currentUrlPath.split('/')

$('button.dropdown a.option').click(function(event){
  event.preventDefault()
  pathArray[2] = $(this).attr('data-version')
  var newUrlPath = window.location.origin + pathArray.join('/')

  $.ajax({
      type: "HEAD",
      async: true,
      url: newUrlPath,
      success: function(message){
        location.assign(newUrlPath)
      },
      error: function(message){
        location.assign(`${window.location.origin}/docs/${pathArray[2]}`)
      }
  })

})

/****************
  Open docs images in lightboxes
****************/
$('#docs-content img').each(function(index) {
  var imgUrl = $(this).attr('src')
  $(this).addClass('cursor-pointer')

  $(this).click(function(){
    window.open(imgUrl, '_blank');
  })
})

/****************
  truncate excerpt
****************/
function cut(n) {
  return function textCutter(i, text) {
    var short = text.substr(0, n);
    if (/^\S/.test(text.substr(n)))
      return short.replace(/\s+\S*$/, '…');
    return short;
  };
}

$('.related-pages > div > p').each(function(index) {
  var excerpt = $(this).text();
  if(excerpt.length > 200) {
    $(this).text(cut(200));
  }
})
<commit_msg>Docs version redirect fix<commit_after>require('es6-promise').polyfill()
require('./blog.js')
require('./case-study-carousel.js')
require('./docs.js')
require('./events-carousel.js')
require('./fetch.js')
require('./get-started.js')
require('./install.js')
require('./modal.js')
require('./overlay.js')
require('./quotes-carousel.js')
require('./smooth-scroll.js')
require('./stackdiagram.js')
require('./typer.js')
require('./typer2.js')
require('./html-include.js')
require('swagger-ui-browserify')
require('./ngindox.js')

import Wallop from 'wallop';
import Hammer from 'hammerjs';

// globals
const compareVersions = require('compare-versions');
window.compareVersions = compareVersions;

const docPathName = window.location.pathname

// Mobile menu
$('#nav-icon').on('click', function (event) {
  event.preventDefault();
  if($('#nav-icon').hasClass('open')) {
    $('.navigation').removeClass('mobile-menu--open');
    $('.menu-mobile').removeClass('open');
    $('#nav-icon').removeClass('open');
    $('body').removeAttr('style');
    $('html').removeAttr('style');
  } else {
    $('.navigation').addClass('mobile-menu--open');
    $('.menu-mobile').addClass('open');
    $('#nav-icon').addClass('open');
    $('body').attr('style', 'overflow: hidden;');
    $('html').attr('style', 'overflow: hidden;');
  }
})

// Array.find polyfill
if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

/***********************
  Dropdown
***********************/
$('.dropdown').click(function(event){
  $('html').on('click',function() {
    $('.dropdown').removeClass('is-active')
  });

  $(this).toggleClass('is-active')

  event.stopPropagation()
})

/***********************
  Set timeout function
***********************/
function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
  };

  this.resume = function() {
    start = new Date();
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
  };

  this.cancel = function() {
    window.clearTimeout(timerId);
  };

  this.resume();
}

/****************
  Slider
****************/
var wallopEl = document.querySelector('.Wallop');
if(wallopEl){
  var slider = new Wallop(wallopEl);

  // Add auto-play functionality
  var autoPlayMs = 6000;
  var nextTimeout;
  var loadNext = function() {
    var nextIndex = (slider.currentItemIndex + 1) % slider.allItemsArray.length;
    slider.goTo(nextIndex);
  }
  nextTimeout = new Timer(function() { loadNext(); }, autoPlayMs);
  slider.on('change', function() {
    nextTimeout.resume();
  });

  slider.on('mouseenter', function(){
    nextTimeout.cancel();
  })

  slider.on('mouseleave', function(){
    nextTimeout.resume();
  })

  // Enable touch for Wallop
  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swipeleft', function() {
    slider.next();
  });

  Hammer(wallopEl, {
    inputClass: Hammer.TouchInput
  }).on('swiperight', function() {
    slider.previous();
  });
}

/****************
  Clickable headers
****************/
$('#docs-content h1, #docs-content h2, #docs-content h3, #docs-content h4, #docs-content h5, #docs-content h6').each(function( index ) {
  var hashURL = $(this).attr('id')
  $(this).wrapInner('')
});

/****************
  SwaggerUI
****************/
$(document).ready(function() {
  var yamlFile = $('[data-api]').data('api');

  var swaggerUi = new SwaggerUi({
    url: yamlFile,
    dom_id: 'swagger-ui-container',
    docExpansion: 'none'
  });

  swaggerUi.load();
})

/****************
  Add proper submit feedback link to docs
****************/
const docPageTitle = ($('h1.docs-heading').text()).replace(' ', '+')
const jPid = 10001 // pid
const jIssueType = 10100 // issuetype
const jSummary = `Feedback+for+${docPageTitle}` // summary
const jDescription = `Source: ${window.location.href}` // description
const jLabels = 'documentation'

$('#submit-feedback').attr('href', `https://jira.dcos.io/secure/CreateIssueDetails!init.jspa?pid=${jPid}&issuetype=${jIssueType}&summary=${jSummary}&description=${jDescription}&labels=${jLabels}`)

/****************
  Docs version switch 404 prevention
****************/

const currentUrlPath = window.location.pathname
var pathArray = currentUrlPath.split('/')

$('.dropdown a.option').click(function(event){
  event.preventDefault()
  pathArray[2] = $(this).attr('data-version')
  var newUrlPath = window.location.origin + pathArray.join('/')

  $.ajax({
      type: "HEAD",
      async: true,
      url: newUrlPath,
      success: function(message){
        location.assign(newUrlPath)
      },
      error: function(message){
        location.assign(`${window.location.origin}/docs/${pathArray[2]}`)
      }
  })

})

/****************
  Open docs images in lightboxes
****************/
$('#docs-content img').each(function(index) {
  var imgUrl = $(this).attr('src')
  $(this).addClass('cursor-pointer')

  $(this).click(function(){
    window.open(imgUrl, '_blank');
  })
})

/****************
  truncate excerpt
****************/
function cut(n) {
  return function textCutter(i, text) {
    var short = text.substr(0, n);
    if (/^\S/.test(text.substr(n)))
      return short.replace(/\s+\S*$/, '…');
    return short;
  };
}

$('.related-pages > div > p').each(function(index) {
  var excerpt = $(this).text();
  if(excerpt.length > 200) {
    $(this).text(cut(200));
  }
})
<|endoftext|>


<commit_before>// Copyright 2012 Massachusetts Institute of Technology. All rights reserved.

/**
 * @fileoverview Visual blocks editor for App Inventor
 * Set of drawers for holding factory blocks (blocks that create
 * other blocks when dragged onto the workspace). The set of drawers
 * includes the built-in drawers that we get from the blocks language, as
 * well as a drawer per component instance that was added to this workspace.
 *
 * TODO(sharon): add support for advanced drawer that contains generic
 * component blocks
 *
 * @author Sharon Perl (sharon@google.com)
 */

Blockly.Drawer = {};

/**
 * Create the dom for the drawer. Creates a flyout Blockly.Drawer.flyout_,
 * and initializes its dom.
 */
Blockly.Drawer.createDom = function() {
  Blockly.Drawer.flyout_ = new Blockly.Flyout();
  // insert the flyout after the bubble canvas (except, there's no
  // svg.insertAfter method, so we need to insert before the thing following
  // the bubble canvas. Neil Fraser says: this is "less hacky than it looks".
  var flyoutGroup = Blockly.Drawer.flyout_.createDom();
  Blockly.svg.insertBefore(flyoutGroup, Blockly.mainWorkspace.svgGroup_.nextSibling);
};

/**
 * Initializes the drawer by initializing the flyout and creating the
 * language tree. Call after calling createDom.
 */
Blockly.Drawer.init = function() {
  Blockly.Drawer.flyout_.init(Blockly.mainWorkspace,
                              Blockly.getMainWorkspaceMetrics);
  Blockly.Drawer.languageTree = Blockly.Drawer.buildTree_();
};

/**
 * String to prefix on categories of each potential block in the drawer.
 * Used to prevent collisions with built-in properties like 'toString'.
 * @private
 */
Blockly.Drawer.PREFIX_ = 'cat_';

/**
 * Build the hierarchical tree of block types.
 * Note: taken from Blockly's toolbox.js
 * @return {!Object} Tree object.
 * @private
 */
Blockly.Drawer.buildTree_ = function() {
  var tree = {};
  // Populate the tree structure.
  for (var name in Blockly.Language) {
    var block = Blockly.Language[name];
    // Blocks without a category are fragments used by the mutator dialog.
    if (block.category) {
      var cat = Blockly.Drawer.PREFIX_ + window.encodeURI(block.category);
      if (cat in tree) {
        tree[cat].push(name);
      } else {
        tree[cat] = [name];
      }
    }
  }
  return tree;
};

/**
 * Show the contents of the built-in drawer named drawerName. drawerName
 * should be one of Blockly.MSG_VARIABLE_CATEGORY,
 * Blockly.MSG_PROCEDURE_CATEGORY, or one of the built-in block categories.
 * @param drawerName
 */
Blockly.Drawer.showBuiltin = function(drawerName) {
  if (drawerName != Blockly.MSG_VARIABLE_CATEGORY &&
      drawerName != Blockly.MSG_PROCEDURE_CATEGORY) {
      drawerName = Blockly.Drawer.PREFIX_ + drawerName;
  }
  var blockSet = Blockly.Drawer.languageTree[drawerName] || drawerName;
  Blockly.Drawer.flyout_.show(blockSet);
};

/**
 * Show the blocks drawer for the component with give instance name. If no
 * such component is found, currently we just log a message to the console
 * and do nothing.
 */
Blockly.Drawer.showComponent = function(instanceName) {
  if (Blockly.ComponentInstances[instanceName]) {
    Blockly.Drawer.flyout_.hide();
    Blockly.Drawer.flyout_.show(Blockly.ComponentInstances[instanceName].blocks);
  } else {
    //throw 'Error: "' + name + '" is an unknown component name.';
    console.log("Got call to Blockly.Component.show(" +  name +
                ") - unknown component name");
  }
};

/**
 * Hide the Drawer flyout
 */
Blockly.Drawer.hide = function() {
  Blockly.Drawer.flyout_.hide();
};

/**
 * @returns  true if the Drawer flyout is currently open, false otherwise.
 */
Blockly.Drawer.isShowing = function() {
  return Blockly.Drawer.flyout_.isVisible();
};
<commit_msg>fix comments<commit_after>// Copyright 2012 Massachusetts Institute of Technology. All rights reserved.

/**
 * @fileoverview Visual blocks editor for App Inventor
 * Set of drawers for holding factory blocks (blocks that create
 * other blocks when dragged onto the workspace). The set of drawers
 * includes the built-in drawers that we get from the blocks language, as
 * well as a drawer per component instance that was added to this workspace.
 *
 * TODO(sharon): add support for advanced drawer that contains generic
 * component blocks
 *
 * @author Sharon Perl (sharon@google.com)
 */

Blockly.Drawer = {};

/**
 * Create the dom for the drawer. Creates a flyout Blockly.Drawer.flyout_,
 * and initializes its dom.
 */
Blockly.Drawer.createDom = function() {
  Blockly.Drawer.flyout_ = new Blockly.Flyout();
  // insert the flyout after the main workspace (except, there's no
  // svg.insertAfter method, so we need to insert before the thing following
  // the main workspace. Neil Fraser says: this is "less hacky than it looks".
  var flyoutGroup = Blockly.Drawer.flyout_.createDom();
  Blockly.svg.insertBefore(flyoutGroup, Blockly.mainWorkspace.svgGroup_.nextSibling);
};

/**
 * Initializes the drawer by initializing the flyout and creating the
 * language tree. Call after calling createDom.
 */
Blockly.Drawer.init = function() {
  Blockly.Drawer.flyout_.init(Blockly.mainWorkspace,
                              Blockly.getMainWorkspaceMetrics);
  Blockly.Drawer.languageTree = Blockly.Drawer.buildTree_();
};

/**
 * String to prefix on categories of each potential block in the drawer.
 * Used to prevent collisions with built-in properties like 'toString'.
 * @private
 */
Blockly.Drawer.PREFIX_ = 'cat_';

/**
 * Build the hierarchical tree of block types.
 * Note: taken from Blockly's toolbox.js
 * @return {!Object} Tree object.
 * @private
 */
Blockly.Drawer.buildTree_ = function() {
  var tree = {};
  // Populate the tree structure.
  for (var name in Blockly.Language) {
    var block = Blockly.Language[name];
    // Blocks without a category are fragments used by the mutator dialog.
    if (block.category) {
      var cat = Blockly.Drawer.PREFIX_ + window.encodeURI(block.category);
      if (cat in tree) {
        tree[cat].push(name);
      } else {
        tree[cat] = [name];
      }
    }
  }
  return tree;
};

/**
 * Show the contents of the built-in drawer named drawerName. drawerName
 * should be one of Blockly.MSG_VARIABLE_CATEGORY,
 * Blockly.MSG_PROCEDURE_CATEGORY, or one of the built-in block categories.
 * @param drawerName
 */
Blockly.Drawer.showBuiltin = function(drawerName) {
  if (drawerName != Blockly.MSG_VARIABLE_CATEGORY &&
      drawerName != Blockly.MSG_PROCEDURE_CATEGORY) {
      drawerName = Blockly.Drawer.PREFIX_ + drawerName;
  }
  var blockSet = Blockly.Drawer.languageTree[drawerName] || drawerName;
  Blockly.Drawer.flyout_.show(blockSet);
};

/**
 * Show the blocks drawer for the component with give instance name. If no
 * such component is found, currently we just log a message to the console
 * and do nothing.
 */
Blockly.Drawer.showComponent = function(instanceName) {
  if (Blockly.ComponentInstances[instanceName]) {
    Blockly.Drawer.flyout_.hide();
    Blockly.Drawer.flyout_.show(Blockly.ComponentInstances[instanceName].blocks);
  } else {
    //throw 'Error: "' + name + '" is an unknown component name.';
    console.log("Got call to Blockly.Component.show(" +  name +
                ") - unknown component name");
  }
};

/**
 * Hide the Drawer flyout
 */
Blockly.Drawer.hide = function() {
  Blockly.Drawer.flyout_.hide();
};

/**
 * @returns  true if the Drawer flyout is currently open, false otherwise.
 */
Blockly.Drawer.isShowing = function() {
  return Blockly.Drawer.flyout_.isVisible();
};
<|endoftext|>


<commit_before><commit_msg>Hide and display on button click the explanations<commit_after><|endoftext|>


<commit_before>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Bind search box hint placeholder show/hide events (bindSearchEvents)
 *  + Generate a table of contents (generateTOC)
 *  + Bind foldable sections (bindToggles)
 *  + Bind links to foldable sections (bindToggleLinks)
 */

(function() {
'use strict';

function bindSearchEvents() {

  var search = $('#search');
  if (search.length === 0) {
    return; // no search box
  }

  function clearInactive() {
    if (search.is('.inactive')) {
      search.val('');
      search.removeClass('inactive');
    }
  }

  function restoreInactive() {
    if (search.val() !== '') {
      return;
    }
    search.val(search.attr('placeholder'));
    search.addClass('inactive');
  }

  search.on('focus', clearInactive);
  search.on('blur', restoreInactive);

  restoreInactive();
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links. "Decorates" the element with id=="nav" with this table of contents.
 */
function generateTOC() {
  if ($('#manual-nav').length > 0) {
    return;
  }

  var nav = $('#nav');
  if (nav.length === 0) {
    return;
  }

  var toc_items = [];
  $(nav).nextAll('h2, h3').each(function() {
    var node = this;
    if (node.id == '')
      node.id = 'tmp_' + toc_items.length;
    var link = $('').attr('href', '#' + node.id).text($(node).text());
    var item;
    if ($(node).is('h2')) {
      item = $('
');
    } else { // h3
      item = $('
');
    }
    item.append(link);
    toc_items.push(item);
  });
  if (toc_items.length <= 1) {
    return;
  }

  var dl1 = $('
');
  var dl2 = $('
');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }
  for (var i = 0; i < split_index; i++) {
    dl1.append(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.append(toc_items[i]);
  }

  var tocTable = $('
').appendTo(nav);
  var tocBody = $('
').appendTo(tocTable);
  var tocRow = $('
').appendTo(tocBody);

  // 1st column
  $('').appendTo(tocRow).append(dl1);
  // 2nd column
  $('').appendTo(tocRow).append(dl2);
}

function bindToggle(el) {
  $('.toggleButton', el).click(function() {
    if ($(el).is('.toggle')) {
      $(el).addClass('toggleVisible').removeClass('toggle');
    } else {
      $(el).addClass('toggle').removeClass('toggleVisible');
    }
  });
}
function bindToggles(selector) {
  $(selector).each(function(i, el) {
    bindToggle(el);
  });
}

function bindToggleLink(el, prefix) {
  $(el).click(function() {
    var href = $(el).attr('href');
    var i = href.indexOf('#'+prefix);
    if (i < 0) {
      return;
    }
    var id = '#' + prefix + href.slice(i+1+prefix.length);
    if ($(id).is('.toggle')) {
      $(id).find('.toggleButton').first().click();
    }
  });
}
function bindToggleLinks(selector, prefix) {
  $(selector).each(function(i, el) {
    bindToggleLink(el, prefix);
  });
}

function setupDropdownPlayground() {
  if (!$('#page').is('.wide')) {
    return; // don't show on front page
  }
  var button = $('#playgroundButton');
  var div = $('#playground');
  var setup = false;
  button.toggle(function() {
    button.addClass('active');
    div.show();
    if (setup) {
      return;
    }
    setup = true;
    playground({
      'codeEl': $('.code', div),
      'outputEl': $('.output', div),
      'runEl': $('.run', div),
      'fmtEl': $('.fmt', div),
      'shareEl': $('.share', div),
      'shareRedirect': 'http://play.golang.org/p/'
    });
  },
  function() {
    button.removeClass('active');
    div.hide();
  });
  button.show();
  $('#menu').css('min-width', '+=60');
}

$(document).ready(function() {
  bindSearchEvents();
  generateTOC();
  bindToggles(".toggle");
  bindToggles(".toggleVisible");
  bindToggleLinks(".exampleLink", "example_");
  bindToggleLinks(".overviewLink", "");
  bindToggleLinks(".examplesLink", "");
  bindToggleLinks(".indexLink", "");
  setupDropdownPlayground();
});

})();
<commit_msg>doc/godoc.js: put focus on div#page when necessary so that keyboard navigation events are sent to div#page.<commit_after>// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/* A little code to ease navigation of these documents.
 *
 * On window load we:
 *  + Bind search box hint placeholder show/hide events (bindSearchEvents)
 *  + Generate a table of contents (generateTOC)
 *  + Bind foldable sections (bindToggles)
 *  + Bind links to foldable sections (bindToggleLinks)
 */

(function() {
'use strict';

function bindSearchEvents() {

  var search = $('#search');
  if (search.length === 0) {
    return; // no search box
  }

  function clearInactive() {
    if (search.is('.inactive')) {
      search.val('');
      search.removeClass('inactive');
    }
  }

  function restoreInactive() {
    if (search.val() !== '') {
      return;
    }
    search.val(search.attr('placeholder'));
    search.addClass('inactive');
  }

  search.on('focus', clearInactive);
  search.on('blur', restoreInactive);

  restoreInactive();
}

/* Generates a table of contents: looks for h2 and h3 elements and generates
 * links. "Decorates" the element with id=="nav" with this table of contents.
 */
function generateTOC() {
  if ($('#manual-nav').length > 0) {
    return;
  }

  var nav = $('#nav');
  if (nav.length === 0) {
    return;
  }

  var toc_items = [];
  $(nav).nextAll('h2, h3').each(function() {
    var node = this;
    if (node.id == '')
      node.id = 'tmp_' + toc_items.length;
    var link = $('').attr('href', '#' + node.id).text($(node).text());
    var item;
    if ($(node).is('h2')) {
      item = $('
');
    } else { // h3
      item = $('
');
    }
    item.append(link);
    toc_items.push(item);
  });
  if (toc_items.length <= 1) {
    return;
  }

  var dl1 = $('
');
  var dl2 = $('
');

  var split_index = (toc_items.length / 2) + 1;
  if (split_index < 8) {
    split_index = toc_items.length;
  }
  for (var i = 0; i < split_index; i++) {
    dl1.append(toc_items[i]);
  }
  for (/* keep using i */; i < toc_items.length; i++) {
    dl2.append(toc_items[i]);
  }

  var tocTable = $('
').appendTo(nav);
  var tocBody = $('
').appendTo(tocTable);
  var tocRow = $('
').appendTo(tocBody);

  // 1st column
  $('').appendTo(tocRow).append(dl1);
  // 2nd column
  $('').appendTo(tocRow).append(dl2);
}

function bindToggle(el) {
  $('.toggleButton', el).click(function() {
    if ($(el).is('.toggle')) {
      $(el).addClass('toggleVisible').removeClass('toggle');
    } else {
      $(el).addClass('toggle').removeClass('toggleVisible');
    }
  });
}
function bindToggles(selector) {
  $(selector).each(function(i, el) {
    bindToggle(el);
  });
}

function bindToggleLink(el, prefix) {
  $(el).click(function() {
    var href = $(el).attr('href');
    var i = href.indexOf('#'+prefix);
    if (i < 0) {
      return;
    }
    var id = '#' + prefix + href.slice(i+1+prefix.length);
    if ($(id).is('.toggle')) {
      $(id).find('.toggleButton').first().click();
    }
  });
}
function bindToggleLinks(selector, prefix) {
  $(selector).each(function(i, el) {
    bindToggleLink(el, prefix);
  });
}

function setupDropdownPlayground() {
  if (!$('#page').is('.wide')) {
    return; // don't show on front page
  }
  var button = $('#playgroundButton');
  var div = $('#playground');
  var setup = false;
  button.toggle(function() {
    button.addClass('active');
    div.show();
    if (setup) {
      return;
    }
    setup = true;
    playground({
      'codeEl': $('.code', div),
      'outputEl': $('.output', div),
      'runEl': $('.run', div),
      'fmtEl': $('.fmt', div),
      'shareEl': $('.share', div),
      'shareRedirect': 'http://play.golang.org/p/'
    });
  },
  function() {
    button.removeClass('active');
    div.hide();
  });
  button.show();
  $('#menu').css('min-width', '+=60');
}

// fixFocus tries to put focus to div#page so that keyboard navigation works.
function fixFocus() {
  var page = $('div#page');
  var topbar = $('div#topbar');
  page.css('outline', 0); // disable outline when focused
  page.attr('tabindex', -1); // and set tabindex so that it is focusable
  $(window).resize(function (evt) {
    // only focus page when the topbar is at fixed position (that is, it's in
    // front of page, and keyboard event will go to the former by default.)
    // by focusing page, keyboard event will go to page so that up/down arrow,
    // space, etc. will work as expected.
    if (topbar.css('position') == "fixed")
      page.focus();
  }).resize();
}

$(document).ready(function() {
  bindSearchEvents();
  generateTOC();
  bindToggles(".toggle");
  bindToggles(".toggleVisible");
  bindToggleLinks(".exampleLink", "example_");
  bindToggleLinks(".overviewLink", "");
  bindToggleLinks(".examplesLink", "");
  bindToggleLinks(".indexLink", "");
  setupDropdownPlayground();
  fixFocus();
});

})();
<|endoftext|>


<commit_before>function benchmarkReporter(suite) {
  var table = document.createElement('table');

  function renderBenchmarkCol(parent, elemName, innerHTML) {
    var elem = document.createElement(elemName);
    elem.innerHTML = innerHTML;
    parent.appendChild(elem);
  }

  function renderBenchmark() {
    while (table.hasChildNodes()) {
      table.removeChild(table.lastChild);
    }

    var tr, txt;

    tr = document.createElement('tr');
    renderBenchmarkCol(tr, "th", "Test");
    renderBenchmarkCol(tr, "th", "Ops/sec");
    table.appendChild(tr);

    for (var i = 0, ilen = suite.length; i < ilen; i++) {
      var bench = suite[i];
      tr = document.createElement('tr');
      renderBenchmarkCol(tr, "td", bench.name);

      if (bench.running) {
        txt = 'running…';
      }
      // status: completed
      else if (bench.hz) {
        // obscure details until the suite has completed
        txt = '' + Benchmark.formatNumber(bench.hz.toFixed(bench.hz < 100 ? 2 : 0)) +
          ' ±' + bench.stats.rme.toFixed(2) + '%' + '';
      }
      else {
        txt = "ready";
      }

      renderBenchmarkCol(tr, "td", txt);
      table.appendChild(tr);
    }
  }

  var button = document.createElement('button');
  button.className = "benchmark";
  window.addEventListener("load", function () {
    button.innerHTML = "Run benchmark";
    button.addEventListener("click", function () {
      button.innerHTML = "Running benchmark...";
      button.disabled = true;
      setTimeout(function () {
        suite.run();
      }, 0);
    });
    document.body.appendChild(button);

    var p = document.createElement('p');
    p.innerHTML = Benchmark.platform.toString();
    document.body.appendChild(p);

    table.id = "test_results";
    document.body.appendChild(table);

    renderBenchmark();
  });

  suite.on('cycle', function (event) {
    //renderBenchmark();
  });
  suite.on('complete', function () {
    renderBenchmark();
    button.innerHTML = "Run benchmark";
    button.disabled = false;
  });
}<commit_msg>increase start timeout<commit_after>function benchmarkReporter(suite) {
  var table = document.createElement('table');

  function renderBenchmarkCol(parent, elemName, innerHTML) {
    var elem = document.createElement(elemName);
    elem.innerHTML = innerHTML;
    parent.appendChild(elem);
  }

  function renderBenchmark() {
    while (table.hasChildNodes()) {
      table.removeChild(table.lastChild);
    }

    var tr, txt;

    tr = document.createElement('tr');
    renderBenchmarkCol(tr, "th", "Test");
    renderBenchmarkCol(tr, "th", "Ops/sec");
    table.appendChild(tr);

    for (var i = 0, ilen = suite.length; i < ilen; i++) {
      var bench = suite[i];
      tr = document.createElement('tr');
      renderBenchmarkCol(tr, "td", bench.name);

      if (bench.running) {
        txt = 'running…';
      }
      // status: completed
      else if (bench.hz) {
        // obscure details until the suite has completed
        txt = '' + Benchmark.formatNumber(bench.hz.toFixed(bench.hz < 100 ? 2 : 0)) +
          ' ±' + bench.stats.rme.toFixed(2) + '%' + '';
      }
      else {
        txt = "ready";
      }

      renderBenchmarkCol(tr, "td", txt);
      table.appendChild(tr);
    }
  }

  var button = document.createElement('button');
  button.className = "benchmark";
  window.addEventListener("load", function () {
    button.innerHTML = "Run benchmark";
    button.addEventListener("click", function () {
      button.innerHTML = "Running benchmark...";
      button.disabled = true;
      setTimeout(function () {
        suite.run();
      }, 30);
    });
    document.body.appendChild(button);

    var p = document.createElement('p');
    p.innerHTML = Benchmark.platform.toString();
    document.body.appendChild(p);

    table.id = "test_results";
    document.body.appendChild(table);

    renderBenchmark();
  });

  suite.on('cycle', function (event) {
    //renderBenchmark();
  });
  suite.on('complete', function () {
    renderBenchmark();
    button.innerHTML = "Run benchmark";
    button.disabled = false;
  });
}<|endoftext|>


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

	app.directive('sigmajs', function() {
		sigma.classes.graph.addMethod('neighbors', function(nodeId) {
			var k,
				neighbors = {},
				index = this.allNeighborsIndex[nodeId] || {};

			for (k in index)
			  neighbors[k] = this.nodesIndex[k];

			return neighbors;
		});
		//over-engineered random id, so that multiple instances can be put on a single page
		var divId = 'sigmjs-dir-container-'+Math.floor((Math.random() * 999999999999))+'-'+Math.floor((Math.random() * 999999999999))+'-'+Math.floor((Math.random() * 999999999999));
		return {
			restrict: 'E',
			template: '

',
			scope: {
				//@ reads the attribute value, = provides two-way binding, & works with functions
				graph: '=',
				width: '@',
				height: '@',
				releativeSizeNode: '='
			},
			link: function (scope, element, attrs) {
				// Let's first initialize sigma:
				var s = new sigma({
					container: divId,
					settings: {
						defaultNodeColor: '#ec5148',
						labelThreshold: 4
					}
				});

				scope.$watch('graph', function(newVal,oldVal) {
					s.graph.clear();
					s.graph.read(scope.graph);
					s.refresh();
					if(scope.releativeSizeNode) {
						//this feature needs the plugin to be added
						sigma.plugins.relativeSize(s, 2);
					}
				});

				scope.$watch('width', function(newVal,oldVal) {
					console.log("graph width: "+scope.width);
					element.children().css("width",scope.width);
					s.refresh();
					window.dispatchEvent(new Event('resize')); //hack so that it will be shown instantly
				});
				scope.$watch('height', function(newVal,oldVal) {
					console.log("graph height: "+scope.height);
					element.children().css("height",scope.height);
					s.refresh();
					window.dispatchEvent(new Event('resize'));//hack so that it will be shown instantly
				});

				element.on('$destroy', function() {
					s.graph.clear();
				});
				sigma.classes.graph.addMethod('neighbors', function(nodeId) {
					var k,
						neighbors = {},
						index = this.allNeighborsIndex[nodeId] || {};

					for (k in index)
					  neighbors[k] = this.nodesIndex[k];

					return neighbors;
				});

				s.bind('clickNode', function(e) {
					var nodeId = e.data.node.id, toKeep = s.graph.neighbors(nodeId);
					toKeep[nodeId] = e.data.node;

					s.graph.nodes().forEach(function(n) {
						if (toKeep[n.id])
							n.color = '#27ae60';
						else
							n.color = '#aaa';
					});

					s.graph.edges().forEach(function(e) {
						if (toKeep[e.source] && toKeep[e.target])
							e.color = '#27ae60';
						else
							e.color = '#aaa';
					});
					s.refresh();
				});

				// When the stage is clicked, we just color each
				// node and edge with its original color.
				s.bind('clickStage', function(e) {
					s.graph.nodes().forEach(function(n) {
						n.color = n.originalColor;
					});
					s.graph.edges().forEach(function(e) {
						e.color = e.originalColor;
					});
					// Same as in the previous event:
					s.refresh();
				  });
			}
		};
	});
})();<commit_msg>Displaying clicked neurons works fine<commit_after>(function() {
	'use strict';

	app.directive('sigmajs', function() {
		sigma.classes.graph.addMethod('neighbors', function(nodeId) {
			var k,
				neighbors = {},
				index = this.allNeighborsIndex[nodeId] || {};

			for (k in index)
			  neighbors[k] = this.nodesIndex[k];

			return neighbors;
		});
		//over-engineered random id, so that multiple instances can be put on a single page
		var divId = 'sigmjs-dir-container-'+Math.floor((Math.random() * 999999999999))+'-'+Math.floor((Math.random() * 999999999999))+'-'+Math.floor((Math.random() * 999999999999));
		return {
			restrict: 'E',
			template: '

',
			scope: {
				//@ reads the attribute value, = provides two-way binding, & works with functions
				graph: '=',
				width: '@',
				height: '@',
				releativeSizeNode: '='
			},
			link: function (scope, element, attrs) {
				// Let's first initialize sigma:
				var s = new sigma({
					container: divId,
					settings: {
						defaultNodeColor: '#ec5148',
						labelThreshold: 4
					}
				});

				scope.$watch('graph', function(newVal,oldVal) {
					s.graph.clear();
					s.graph.read(scope.graph);
					s.refresh();
					if(scope.releativeSizeNode) {
						//this feature needs the plugin to be added
						sigma.plugins.relativeSize(s, 2);
					}
				});

				scope.$watch('width', function(newVal,oldVal) {
					console.log("graph width: "+scope.width);
					element.children().css("width",scope.width);
					s.refresh();
					window.dispatchEvent(new Event('resize')); //hack so that it will be shown instantly
				});
				scope.$watch('height', function(newVal,oldVal) {
					console.log("graph height: "+scope.height);
					element.children().css("height",scope.height);
					s.refresh();
					window.dispatchEvent(new Event('resize'));//hack so that it will be shown instantly
				});

				element.on('$destroy', function() {
					s.graph.clear();
				});

				s.bind('clickNode', function(e) {
					var nodeId = e.data.node.id, toKeep = s.graph.neighbors(nodeId);
					toKeep[nodeId] = e.data.node;

					s.graph.nodes().forEach(function(n) {
						if (toKeep[n.id])
							n.color = '#27ae60';
						else
							n.color = '#aaa';
					});

					s.graph.edges().forEach(function(e) {
						if (toKeep[e.source] && toKeep[e.target])
							e.color = '#27ae60';
						else
							e.color = '#aaa';
					});
					s.refresh();
				});

				// When the stage is clicked, we just color each
				// node and edge with its original color.
				s.bind('clickStage', function(e) {
					s.graph.nodes().forEach(function(n) {
						n.color = n.originalColor;
					});
					s.graph.edges().forEach(function(e) {
						e.color = e.originalColor;
					});
					// Same as in the previous event:
					s.refresh();
				  });
			}
		};
	});
})();
<|endoftext|>


<commit_before>const stopEvent = function(e) {

	if (typeof e.stopPropagation === 'function') e.stopPropagation()
	if (typeof e.preventDefault === 'function')  e.preventDefault()

}

const bindShow = function(elem, opts) {

	elem.onclick = function(e) {

		let id          = this.getAttribute('data-basicLightbox-show')
		let contentElem = document.querySelector(`[data-basicLightbox="${ id }"]`)
		let html        = contentElem.outerHTML

		stopEvent(e)
		show(html, opts)

	}

}

const bindClose = function(elem, opts) {

	elem.onclick = function(e) {

		stopEvent(e)
		close(opts)

	}

}

const validate = function(opts = {}) {

	if (opts.closable!==false) opts.closable = true

	if (typeof opts.className === 'function') opts.className = opts.className()
	if (typeof opts.className !== 'string')   opts.className = ''

	if (typeof opts.beforeShow !== 'function')  opts.beforeShow = () => {}
	if (typeof opts.afterShow !== 'function')   opts.afterShow = () => {}
	if (typeof opts.beforeClose !== 'function') opts.beforeClose = () => {}
	if (typeof opts.afterClose !== 'function')  opts.afterClose = () => {}

	if (typeof opts.beforeHTML === 'function') opts.beforeHTML = opts.beforeHTML()
	if (typeof opts.beforeHTML !== 'string')   opts.beforeHTML = ''

	if (typeof opts.afterHTML === 'function') opts.afterHTML = opts.afterHTML()
	if (typeof opts.afterHTML !== 'string')   opts.afterHTML = ''

	if (typeof opts.beforePlaceholder === 'function') opts.beforePlaceholder = opts.beforePlaceholder()
	if (typeof opts.beforePlaceholder !== 'string')   opts.beforePlaceholder = ''

	if (typeof opts.afterPlaceholder === 'function') opts.afterPlaceholder = opts.afterPlaceholder()
	if (typeof opts.afterPlaceholder !== 'string')   opts.afterPlaceholder = ''

	return opts

}

const render = function(html = '', opts) {

	return (`

			${ opts.beforePlaceholder }

				${ opts.beforeHTML }
				${ html }
				${ opts.afterHTML }

			${ opts.afterPlaceholder }

	`)

}

export const exists = function() {

	let elem = document.querySelector('.basicLightbox')

	return (elem==null ? false : true)

}

export const visible = function() {

	let elem = document.querySelector('.basicLightbox--visible')

	return (elem==null ? false : true)

}

export const show = function(html, opts) {

	// Validate options
	opts = validate(opts)

	// Run beforeShow event
	// Stop execution when function returns false
	if (opts.beforeShow()===false) return false

	// Append lightbox to DOM
	document.body.insertAdjacentHTML('beforeend', render(html, opts))

	// Get the newly created lightbox element
	let elem = document.querySelector('.basicLightbox')

	// Bind close element
	if (opts.closable===true) bindClose(elem.querySelector('.basicLightbox__close'), opts)

	// Wait a while to ensure that the class change triggers the animation
	setTimeout(() => {
		requestAnimationFrame(() => {

			// Show lightbox
			elem.classList.add('basicLightbox--visible')

			// Run afterShow event
			opts.afterShow()

		})
	}, 10)

}

export const close = function(opts) {

	// Validate options
	opts = validate(opts)

	// Run beforeClose event
	// Stop execution when function returns false
	if (opts.beforeClose()===false) return false

	// Get the lightbox element
	let elem = document.querySelector('.basicLightbox')

	// Don't continue to hide lightbox when element not visible
	if (visible()===false) return false

	// Hide lightbox
	elem.classList.remove('basicLightbox--visible')

	setTimeout(() => {
		requestAnimationFrame(() => {

			// Don't continue to remove lightbox when element missing
			if (exists()===false) return false

			// Remove lightbox from DOM
			elem.parentElement.removeChild(elem)

			// Run afterClose event
			opts.afterClose()

		})
	}, 410)

}

export const init = function(elems, opts) {

	if (typeof elems === 'string') elems = [ ...document.querySelectorAll(elems) ]
	if (elems==null)               elems = [ ...document.querySelectorAll('[data-basicLightbox-show]') ]

	elems.forEach((elem) => bindShow(elem, opts))

}<commit_msg>Return true after show/hide<commit_after>const stopEvent = function(e) {

	if (typeof e.stopPropagation === 'function') e.stopPropagation()
	if (typeof e.preventDefault === 'function')  e.preventDefault()

}

const bindShow = function(elem, opts) {

	elem.onclick = function(e) {

		let id          = this.getAttribute('data-basicLightbox-show')
		let contentElem = document.querySelector(`[data-basicLightbox="${ id }"]`)
		let html        = contentElem.outerHTML

		stopEvent(e)
		show(html, opts)

	}

}

const bindClose = function(elem, opts) {

	elem.onclick = function(e) {

		stopEvent(e)
		close(opts)

	}

}

const validate = function(opts = {}) {

	if (opts.closable!==false) opts.closable = true

	if (typeof opts.className === 'function') opts.className = opts.className()
	if (typeof opts.className !== 'string')   opts.className = ''

	if (typeof opts.beforeShow !== 'function')  opts.beforeShow = () => {}
	if (typeof opts.afterShow !== 'function')   opts.afterShow = () => {}
	if (typeof opts.beforeClose !== 'function') opts.beforeClose = () => {}
	if (typeof opts.afterClose !== 'function')  opts.afterClose = () => {}

	if (typeof opts.beforeHTML === 'function') opts.beforeHTML = opts.beforeHTML()
	if (typeof opts.beforeHTML !== 'string')   opts.beforeHTML = ''

	if (typeof opts.afterHTML === 'function') opts.afterHTML = opts.afterHTML()
	if (typeof opts.afterHTML !== 'string')   opts.afterHTML = ''

	if (typeof opts.beforePlaceholder === 'function') opts.beforePlaceholder = opts.beforePlaceholder()
	if (typeof opts.beforePlaceholder !== 'string')   opts.beforePlaceholder = ''

	if (typeof opts.afterPlaceholder === 'function') opts.afterPlaceholder = opts.afterPlaceholder()
	if (typeof opts.afterPlaceholder !== 'string')   opts.afterPlaceholder = ''

	return opts

}

const render = function(html = '', opts) {

	return (`

			${ opts.beforePlaceholder }

				${ opts.beforeHTML }
				${ html }
				${ opts.afterHTML }

			${ opts.afterPlaceholder }

	`)

}

export const exists = function() {

	let elem = document.querySelector('.basicLightbox')

	return (elem==null ? false : true)

}

export const visible = function() {

	let elem = document.querySelector('.basicLightbox--visible')

	return (elem==null ? false : true)

}

export const show = function(html, opts) {

	// Validate options
	opts = validate(opts)

	// Run beforeShow event
	// Stop execution when function returns false
	if (opts.beforeShow()===false) return false

	// Append lightbox to DOM
	document.body.insertAdjacentHTML('beforeend', render(html, opts))

	// Get the newly created lightbox element
	let elem = document.querySelector('.basicLightbox')

	// Bind close element
	if (opts.closable===true) bindClose(elem.querySelector('.basicLightbox__close'), opts)

	// Wait a while to ensure that the class change triggers the animation
	setTimeout(() => {
		requestAnimationFrame(() => {

			// Show lightbox
			elem.classList.add('basicLightbox--visible')

			// Run afterShow event
			opts.afterShow()

		})
	}, 10)

	return true

}

export const close = function(opts) {

	// Validate options
	opts = validate(opts)

	// Run beforeClose event
	// Stop execution when function returns false
	if (opts.beforeClose()===false) return false

	// Get the lightbox element
	let elem = document.querySelector('.basicLightbox')

	// Don't continue to hide lightbox when element not visible
	if (visible()===false) return false

	// Hide lightbox
	elem.classList.remove('basicLightbox--visible')

	setTimeout(() => {
		requestAnimationFrame(() => {

			// Don't continue to remove lightbox when element missing
			if (exists()===false) return false

			// Remove lightbox from DOM
			elem.parentElement.removeChild(elem)

			// Run afterClose event
			opts.afterClose()

		})
	}, 410)

	return true

}

export const init = function(elems, opts) {

	if (typeof elems === 'string') elems = [ ...document.querySelectorAll(elems) ]
	if (elems==null)               elems = [ ...document.querySelectorAll('[data-basicLightbox-show]') ]

	elems.forEach((elem) => bindShow(elem, opts))

}<|endoftext|>


<commit_before>import 'isomorphic-fetch';
import sharify from 'sharify';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';

import mount from 'react/util/mount';

import { Themed } from 'react/styles/theme';

import introspectionQueryResultData from 'react/apollo/fragmentTypes.json';

import clientData from 'react/apollo/localState/clientData';

const isClientSide = typeof window !== 'undefined';

const { data: { APP_URL } } = sharify;

const httpLink = createHttpLink({ uri: `${APP_URL}/graphql` });

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData,
});

export const initApolloClient = ({
  token: X_AUTH_TOKEN,
  currentRoute,
  isLoggedIn,
  cookies,
} = {}) => {
  if (isClientSide && window.__APOLLO_CLIENT__) {
    return window.__APOLLO_CLIENT__;
  }

  const cache = new InMemoryCache({ fragmentMatcher });

  if (isClientSide && window.__APOLLO_STATE__) {
    cache.restore(window.__APOLLO_STATE__);
  }

  const { data: { X_APP_TOKEN } } = sharify;

  const stateLink = withClientState({
    cache,
    defaults: {
      currentRoute: {
        __typename: 'CurrentRoute',
        ...currentRoute,
      },
      loginStatus: {
        __typename: 'LoginStatus',
        isLoggedIn,
      },
      cookies: {
        __typename: 'Cookies',
      },
    },
    resolvers: {
      Cookies: {
        get: (_obj, args) => cookies[args.name] || null,
      },
    },
  });

  const authLink = setContext((_, { headers }) => ({
    headers: {
      ...headers,
      'X-AUTH-TOKEN': X_AUTH_TOKEN,
      'X-APP-TOKEN': X_APP_TOKEN,
    },
  }));

  const link = ApolloLink.from([
    authLink,
    stateLink,
    httpLink,
  ]);

  const client = new ApolloClient({
    ssrMode: !isClientSide,
    link,
    cache,
  });

  if (isClientSide) {
    window.__APOLLO_CLIENT__ = client;
  }

  return client;
};

export const initClientSideApolloClient = () =>
  initApolloClient(clientData());

if (isClientSide) {
  initClientSideApolloClient();
}

export const wrapWithProviders =
  (client = isClientSide && window.__APOLLO_CLIENT__) =>
    (Component, props = {}) => (
      <ApolloProvider client={client}>
        <Themed>
          <Component {...props} />
        </Themed>
      </ApolloProvider>
    );

export const mountWithApolloProvider = (Component, props = {}, mountNode) => {
  if (!mountNode) return null;

  const client = initClientSideApolloClient();
  const WrappedComponent = wrapWithProviders(client)(Component, props);

  return mount(WrappedComponent, mountNode);
};
<commit_msg>Only proxy client-side requests<commit_after>import 'isomorphic-fetch';
import sharify from 'sharify';
import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';

import mount from 'react/util/mount';

import { Themed } from 'react/styles/theme';

import introspectionQueryResultData from 'react/apollo/fragmentTypes.json';

import clientData from 'react/apollo/localState/clientData';

const isClientSide = typeof window !== 'undefined';

const { data: { APP_URL, GRAPHQL_ENDPOINT } } = sharify;

const clientHttpLink = createHttpLink({ uri: `${APP_URL}/graphql` });
const serverHttpLink = createHttpLink({ uri: GRAPHQL_ENDPOINT });

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData,
});

export const initApolloClient = ({
  token: X_AUTH_TOKEN,
  currentRoute,
  isLoggedIn,
  cookies,
} = {}) => {
  if (isClientSide && window.__APOLLO_CLIENT__) {
    return window.__APOLLO_CLIENT__;
  }

  const cache = new InMemoryCache({ fragmentMatcher });

  if (isClientSide && window.__APOLLO_STATE__) {
    cache.restore(window.__APOLLO_STATE__);
  }

  const { data: { X_APP_TOKEN } } = sharify;

  const stateLink = withClientState({
    cache,
    defaults: {
      currentRoute: {
        __typename: 'CurrentRoute',
        ...currentRoute,
      },
      loginStatus: {
        __typename: 'LoginStatus',
        isLoggedIn,
      },
      cookies: {
        __typename: 'Cookies',
      },
    },
    resolvers: {
      Cookies: {
        get: (_obj, args) => cookies[args.name] || null,
      },
    },
  });

  const authLink = setContext((_, { headers }) => ({
    headers: {
      ...headers,
      'X-AUTH-TOKEN': X_AUTH_TOKEN,
      'X-APP-TOKEN': X_APP_TOKEN,
    },
  }));

  const httpLink = isClientSide ? clientHttpLink : serverHttpLink;

  const link = ApolloLink.from([
    authLink,
    stateLink,
    httpLink,
  ]);

  const client = new ApolloClient({
    ssrMode: !isClientSide,
    link,
    cache,
  });

  if (isClientSide) {
    window.__APOLLO_CLIENT__ = client;
  }

  return client;
};

export const initClientSideApolloClient = () =>
  initApolloClient(clientData());

if (isClientSide) {
  initClientSideApolloClient();
}

export const wrapWithProviders =
  (client = isClientSide && window.__APOLLO_CLIENT__) =>
    (Component, props = {}) => (
      <ApolloProvider client={client}>
        <Themed>
          <Component {...props} />
        </Themed>
      </ApolloProvider>
    );

export const mountWithApolloProvider = (Component, props = {}, mountNode) => {
  if (!mountNode) return null;

  const client = initClientSideApolloClient();
  const WrappedComponent = wrapWithProviders(client)(Component, props);

  return mount(WrappedComponent, mountNode);
};
<|endoftext|>


<commit_before>module.exports = function(deployer) {
};
<commit_msg>chore(deploy): deploy and wire contracts together using truffle (#38)<commit_after>var Nutz = artifacts.require("./contracts/satelites/Nutz.sol");
var Power = artifacts.require("./contracts/satelites/Power.sol");
var PullPayment = artifacts.require("./contracts/satelites/PullPayment.sol");
var Storage = artifacts.require("./contracts/satelites/Storage.sol");
var Controller = artifacts.require("./contracts/controller/Controller.sol");

module.exports = function(deployer, network, accounts) {
  let controller;
  deployer.deploy([Nutz, Power, PullPayment, Storage]).then(function() {
    return deployer.deploy(Controller, Power.address, PullPayment.address, Nutz.address, Storage.address);
  }).then(function() {
    return Controller.deployed();
  }).then(function(_controller){
    controller = _controller;
    return Nutz.deployed();
  }).then(function(nutz) {
    nutz.transferOwnership(controller.address);
    return Power.deployed();
  }).then(function(power) {
    power.transferOwnership(controller.address);
    return PullPayment.deployed();
  }).then(function(pull) {
    pull.transferOwnership(controller.address);
    return Storage.deployed();
  }).then(function(storage) {
    storage.transferOwnership(controller.address);
    return controller.unpause();
  });
};
<|endoftext|>


<commit_before>function GuiEvent(renderObject) {
    // render object for this gui event
    this.renderObject = renderObject;

    $.getJSON("data/userlist.php", function(json) {
        var names = [];
        $.each(json.users, function(i, entry) {
            // builds array from JSON
            names.push(entry.username);
        });

        // need access to names after getJSON, so we put autocomplete here
        $("#searchbar").autocomplete({
            source: names,
            minLength: 2,   //minimum number of characters before matching
            max: 5,         //maximum number of matched results
            select: function(event, ui) {
                // throw a new popup up
                resetPopup();
                var depth = 100;
                // erase and empty current render
                renderObject.empty();
                // call to server to obtain new graph info
                d3.json('data/search.php?user='+ui.item.value+'&hops=1', function(data) {
                    // switch the spinning bar for the loading bar
                    switchBars();

                    // reenable the subgraph button
                    $("#dots").show();

                    // data for new graph
                    renderObject.data(data.nodes, data.distances, data.links);
                    renderObject.setCenterNode(data.nodes[0].id);
                    // redraw with new graph and new graph events
                    renderObject.draw();
                });
            }
        });
    });

	var initial;
	$("#slider").mousedown(function () {
		initial = this.value;
	});

	$("#slider").mouseup(function () {
		//alert(this.value - initial);
		var diff = this.value - initial;
        //if diff is 0 do nothing
        if (diff == 0) {
            return;
        }
		if (diff < 0) {
			return new ChromeWheel( 1 , (Math.abs(diff) / 5));
		}
		else {
			return new ChromeWheel( 0 , (diff / 5));
		}
		diff = 0;
	});
}
<commit_msg>set node count on autocomplete search<commit_after>function GuiEvent(renderObject) {
    // render object for this gui event
    this.renderObject = renderObject;

    $.getJSON("data/userlist.php", function(json) {
        var names = [];
        $.each(json.users, function(i, entry) {
            // builds array from JSON
            names.push(entry.username);
        });

        // need access to names after getJSON, so we put autocomplete here
        $("#searchbar").autocomplete({
            source: names,
            minLength: 2,   //minimum number of characters before matching
            max: 5,         //maximum number of matched results
            select: function(event, ui) {
                // throw a new popup up
                resetPopup();
                var depth = 100;
                // erase and empty current render
                renderObject.empty();
                // call to server to obtain new graph info
                d3.json('data/search.php?user='+ui.item.value+'&hops=1', function(data) {
                    // switch the spinning bar for the loading bar
                    switchBars();

                    // reenable the subgraph button
                    $("#dots").show();
                    $("#count").show();

                    // data for new graph
                    renderObject.data(data.nodes, data.distances, data.links);
                    renderObject.setCenterNode(data.nodes[0].id);
                    // redraw with new graph and new graph events
                    renderObject.draw();
                });
            }
        });
    });

	var initial;
	$("#slider").mousedown(function () {
		initial = this.value;
	});

	$("#slider").mouseup(function () {
		//alert(this.value - initial);
		var diff = this.value - initial;
        //if diff is 0 do nothing
        if (diff == 0) {
            return;
        }
		if (diff < 0) {
			return new ChromeWheel( 1 , (Math.abs(diff) / 5));
		}
		else {
			return new ChromeWheel( 0 , (diff / 5));
		}
		diff = 0;
	});
}
<|endoftext|>


<commit_before>import React from 'react'
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';

import TextSmsIcon from 'material-ui/svg-icons/content/send'
import ReplyIcon from 'material-ui/svg-icons/content/reply'
import IconButton from 'material-ui/IconButton'

const messages = [
  {
    "_id": "5a1796db3e0d4f0208d224e7",
    "body": "Do you think you can tell",
    "author": "pink",
    "createdAt": 1511495387263,
    "replies": [
      {
        "body": "Which one is pink by the way",
        "author": "manager",
        "createdAt": 1511495410511
      }
    ]
  }
]

const style={width:650, margin: "0 auto"}

function nestedMessage(m,i){
  return (
    <ListItem primaryText={`By: ${m.author}`}
        secondaryTextLines={2}
        secondaryText={m.body} key={i}/>)
}

export default class FeedbackPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {dialogOpen: false, replyTo: null, messagesSent: 0}
    this.handlePost = this.handlePost.bind(this)
  }

  handlePost(msg){
    consloe.log("SENDING...")
    consloe.log(msg)
    this.setState((oldState)=>({
        messagesSent: oldState.messagesSent + 1,
        dialogOpen: false,
        replyTo: null
    }))
  }

  handleReply(msg){
    console.log(msg)
    this.setState({dialogOpen: true, replyTo: msg._id})
  }

  render() {
    return(

      <List>
        <Subheader style={{textAlign: "center"}}>Latest Messages</Subheader>
        {messages.map((m, i)=> (
          <ListItem primaryText={`By: ${m.author}`} secondaryText={m.body} key={i}
              secondaryTextLines={2} rightIconButton={<IconButton tooltip="Reply" onClick={()=>this.handleReply(m)} >
              <ReplyIcon/></IconButton>}
              open={true} nestedItems={m.replies ? m.replies.map(nestedMessage) : []}/>
        ))}
      </List>
      <MessageDialog open={this.state.dialogOpen} onSubmit={this.handlePost}/>

)
  }
}

class MessageDialog extends React.Component{
  constructor(props){
    super(props)
    this.state = {name: "", body: ""}
  }

  handleNameChange(e){
    this.setState({name: e.target.value})
  }

  handleBodyChange(e){
    this.setState({body : e.target.value})
  }

  render(){
    return (
      <Dialog title="Give Feedback"
          actions={[]}
          modal={false}
          open={this.props.open}>
        <TextField
          floatingLabelText="Name (Optional)"
          style={{bottom:105, position:"absolute"}}
          value={this.state.name}
          onChange={(e) => this.handleNameChange(e)}
        />
        <TextField
          floatingLabelText="Any feedback is apprectiated"
          multiLine={true}
          style={{bottom:11, position:"absolute"}}
          value={this.state.body}
          onChange={(e) => this.handleBodyChange(e)}
          style={{width:650}}
        />
    </Dialog>)
  }
}
<commit_msg>add basic interactive ui for feedback page<commit_after>import React from 'react'
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton'
import TextSmsIcon from 'material-ui/svg-icons/content/send'
import ReplyIcon from 'material-ui/svg-icons/content/reply'
import IconButton from 'material-ui/IconButton'

const evilMessages = [
  {
    "_id": "5a1796db3e0d4f0208d224e7",
    "body": `"Do you think you can tell
    Heaven from hel Blue sky from the groung above"`,
    "author": "pink",
    "createdAt": 1511495387263,
    "replies": [
      {
        "body": `"Which one is pink by the way.Or what is going on anyway"`,
        "author": "manager",
        "createdAt": 1511495410511
      }
    ]
  }
]

const style={width:650, margin: "0 auto"}

function nestedMessage(m,i){
  return (
    <ListItem primaryText={m.body}
        secondaryTextLines={2}
        secondaryText={`Sent By: ${m.author}`} key={i}/>)
}

export default class FeedbackPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {dialogOpen: false, replyTo: null, messagesSent: 0, messages: evilMessages}
    this.handlePost = this.handlePost.bind(this)
  }

  handlePost(msg){
    console.log("SENDING...")
    console.log(msg)
    this.setState((oldState)=>({
        messagesSent: oldState.messagesSent + 1,
        dialogOpen: false,
        replyTo: null,
        messages: [...oldState.messages,msg]
    }))
  }

  handleReply(msg){
    console.log(msg)
    this.setState({dialogOpen: true, replyTo: msg._id})
  }

  render() {
    return(

      <List>
        <Subheader style={{textAlign: "center"}}>Latest Messages</Subheader>
        {this.state.messages.map((m, i)=> (
          <ViewMessage nested={false} message={m}
              onReply={() => this.handleReply(m)} key={i}/>))}
      </List>
      <MessageDialog open={this.state.dialogOpen} onSubmit={this.handlePost}/>

)
  }
}

function ViewMessage(props){
  const m = props.message
  const bodyLines = m.body.split('\n')
  const secondaryText = bodyLines.length > 1
                         ? (
 {bodyLines[1]}
 SentBy: {m.author}
)
                         : `By: ${m.author}`
  const replyButton =  (<IconButton tooltip="Reply" onClick={props.onReply}><ReplyIcon/></IconButton>)
  if(props.nested){
    return (<ListItem primaryText={bodyLines[0]}
        secondaryTextLines={2}
        secondaryText={secondaryText} disabled={true} key={props.key}/>)
  }else{
    return (
      <ListItem primaryText={bodyLines[0]} secondaryText={secondaryText}
                disabled={true}
                secondaryTextLines={2}
                rightIconButton={replyButton}
                open={true}
                nestedItems={m.replies ?
                m.replies.map((m,i) => ViewMessage({nested:true, message:m, key:i})) : []}/>)
  }

}

class MessageDialog extends React.Component{
  constructor(props){
    super(props)
    this.state = {name: "", body: ""}
  }

  handleNameChange(e){
    this.setState({name: e.target.value})
  }

  handleBodyChange(e){
    const newBody = e.target.value
    const newLines = newBody.match(/\n/g)
    if(newLines && newLines.length > 1) return
    if(newBody.length > 140) return
    this.setState({body : newBody})
  }

  handleSubmit(){
    const msg = {
      body: this.state.body,
      author: this.state.name
    }
    this.props.onSubmit(msg)
  }

  render(){
    return (
      <Dialog
          actions={[<FlatButton label="Send" onClick={()=>this.handleSubmit()} icon={<ReplyIcon />} /> ]}
          modal={true}
          open={this.props.open}
          onRequestClose={this.handleClose}>
        <TextField
          floatingLabelText="Name (Optional)"
          value={this.state.name}
          onChange={(e) => this.handleNameChange(e)}
        />
        <TextField
          floatingLabelText={`Any thoughts (${this.state.body.length}/140)`}
          value={this.state.body}
          onChange={(e) => this.handleBodyChange(e)}
          multiLine={true}
          style={{width:650}}
        />
    </Dialog>)
  }
}
<|endoftext|>


<commit_before><commit_msg>update jQuery to v 1.10.2<commit_after><|endoftext|>


<commit_before>var m = require('mithril');
var Raven = require('raven-js');
var $osf = require('js/osfHelpers');
var ShareJSDoc = require('js/pages/ShareJSDocFile.js');
require('ace-noconflict');
require('ace-mode-markdown');
require('ace-ext-language_tools');
require('addons/wiki/static/ace-markdown-snippets.js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

var util = require('./util.js');

var model = {};

var FileEditor = {
    controller: function(contentUrl, shareWSUrl, editorMeta, observables) {
        var self = {};

        self.url = contentUrl;
        self.loaded = false;
        self.initialText = '';
        self.editorMeta = editorMeta;

        self.observables = observables;

        self.unthrottledStatus = self.observables.status;
        $osf.throttle(self.observables.status, 4000, {leading: false});

        self.bindAce = function(element, isInitialized, context) {
            if (isInitialized) {
                return;
            }
            model.editor = ace.edit(element.id);
            model.editor.setValue(self.initialText, -1);
            new ShareJSDoc(shareWSUrl, self.editorMeta, model.editor, self.observables);
        };

        self.handleResponse = function(response) {
            m.startComputation();
            self.loaded = true;
            self.initialText = response;
            if (model.editor) {
                model.editor.setValue(self.initialText);
            }
            m.endComputation();
        };

        self.reloadFile = function() {
            self.loaded = false;
            $.ajax({
                type: 'GET',
                url: self.url,
                dataType: 'text',
                beforeSend: $osf.setXHRAuthorization,
            }).done(function (parsed, status, response) {
                model.loadedResponse = response.responseText;
                self.handleResponse(response.responseText);
            }).fail(function (xhr, textStatus, error) {
                $osf.growl('Error','The file content could not be loaded.');
                Raven.captureMessage('Could not GET file contents.', {
                    extra: {
                        url: self.url,
                        textStatus: textStatus,
                        error: error
                    }
                });
            });
        };

        self.saveFile = $osf.throttle(function() {
            var oldstatus = self.observables.status();
            model.editor.setReadOnly(true);
            self.unthrottledStatus('saving');
            m.redraw();
            var request = $.ajax({
                type: 'PUT',
                url: self.url,
                data: model.editor.getValue(),
                beforeSend: $osf.setXHRAuthorization
            }).done(function () {
                model.editor.setReadOnly(false);
                self.unthrottledStatus(oldstatus);
                $(document).trigger('fileviewpage:reload');
                self.initialText = model.editor.getValue();
                m.redraw();
            }).fail(function(xhr, textStatus, err) {
                var message;
                if (xhr.status === 507) {
                    message = 'Could not update file. Insufficient storage space in your Dropbox.';
                } else {
                    message = 'The file could not be updated.';
                }
                model.editor.setReadOnly(false);
                self.unthrottledStatus(oldstatus);
                $(document).trigger('fileviewpage:reload');
                model.editor.setValue(self.initialText);
                $osf.growl('Error', message);
                Raven.captureMessage('Could not PUT file content.', {
                    extra: {
                        textStatus: textStatus,
                        url: self.url
                    }
                });
                m.redraw();
            });
        }, 500);

        self.changed = function() {
            var file1 = self.initialText;
            var file2 = !model.editor ? '' : model.editor.getValue();

            var clean1 = typeof file1 === 'string' ?
                file1.replace(/(\r\n|\n|\r)/gm, '\n') : '';
            var clean2 = typeof file2 === 'string' ?
                file2.replace(/(\r\n|\n|\r)/gm, '\n') : '';

            return clean1 !== clean2;
        };

        // Hack to prevent double downloads of files from controllers being called twice
        // Double download is caused by treebeard and fileviewpage both being mounted by mithril
        if(model.loadedResponse){
            self.handleResponse(model.loadedResponse);
        }else{
            self.reloadFile();
        }

        return self;
    },
    view: function(ctrl) {
        if (!ctrl.loaded) {
            return util.Spinner;
        }
        return m('.editor-pane.panel-body', [
            m('.wiki-connected-users', m('.row', m('.col-sm-12', [
                m('.ul.list-inline', {style: {'margin-top': '10px'}}, [
                    ctrl.observables.activeUsers().map(function(user) {
                        return m('li', m('a', {href: user.url}, [
                            m('img', {
                                title: user.name,
                                src: user.gravatar,
                                'data-container': 'body',
                                'data-placement': 'top',
                                'data-toggle': 'tooltip',
                                style: {border: '1px solid black'}
                            })
                        ]));
                    })

                ])
            ]))),
            m('', {style: {'padding-top': '10px'}}, [
                m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce})
            ]),
            m('br'),
            m('[style=position:inherit]', [
                m('.row', m('.col-sm-12', [
                    m('.pull-right', [
                        m('button#fileEditorRevert.btn.btn-sm.btn-danger', {onclick: function(){ctrl.reloadFile();}}, 'Revert'),
                        ' ',
                        m('button#fileEditorSave.btn.btn-sm.btn-success', {onclick: function() {ctrl.saveFile();}}, 'Save')
                    ])
                ]))
            ])
        ]);

    }
};

module.exports = FileEditor;
<commit_msg>Replace hack with promise<commit_after>var m = require('mithril');
var Raven = require('raven-js');
var $osf = require('js/osfHelpers');
var ShareJSDoc = require('js/pages/ShareJSDocFile.js');
require('ace-noconflict');
require('ace-mode-markdown');
require('ace-ext-language_tools');
require('addons/wiki/static/ace-markdown-snippets.js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

var util = require('./util.js');

var model = {};

// This stops the FileEditor Ajax from being called twice on load when
// Mithril reloads the controller twice
var FileHandler = {
    fetchUrl: function(url, reload){
        self = this;
        if(typeof self.promise === 'undefined' || reload){
            self.promise = $.ajax({
                type: 'GET',
                url: url,
                dataType: 'text',
                beforeSend: $osf.setXHRAuthorization,
            })
        }
        return self.promise;
    }
}

var FileEditor = {
    controller: function(contentUrl, shareWSUrl, editorMeta, observables) {
        var self = {};

        self.url = contentUrl;
        self.loaded = false;
        self.initialText = '';
        self.editorMeta = editorMeta;

        self.observables = observables;

        self.unthrottledStatus = self.observables.status;
        $osf.throttle(self.observables.status, 4000, {leading: false});

        self.bindAce = function(element, isInitialized, context) {
            if (isInitialized) {
                return;
            }
            model.editor = ace.edit(element.id);
            model.editor.setValue(self.initialText, -1);
            new ShareJSDoc(shareWSUrl, self.editorMeta, model.editor, self.observables);
        };

        self.loadFile = function(reload) {
            self.loaded = false;
            var response = FileHandler.fetchUrl(self.url, reload);

            response.done(function (parsed, status, response) {
                m.startComputation();
                self.loaded = true;
                self.initialText = response.responseText;
                if (model.editor) {
                    model.editor.setValue(self.initialText);
                }
                m.endComputation();
            })

            response.fail(function (xhr, textStatus, error) {
                $osf.growl('Error','The file content could not be loaded.');
                Raven.captureMessage('Could not GET file contents.', {
                    extra: {
                        url: self.url,
                        textStatus: textStatus,
                        error: error
                    }
                });
            });
        }

        self.saveFile = $osf.throttle(function() {
            var oldstatus = self.observables.status();
            model.editor.setReadOnly(true);
            self.unthrottledStatus('saving');
            m.redraw();
            var request = $.ajax({
                type: 'PUT',
                url: self.url,
                data: model.editor.getValue(),
                beforeSend: $osf.setXHRAuthorization
            }).done(function () {
                model.editor.setReadOnly(false);
                self.unthrottledStatus(oldstatus);
                $(document).trigger('fileviewpage:reload');
                self.initialText = model.editor.getValue();
                m.redraw();
            }).fail(function(xhr, textStatus, err) {
                var message;
                if (xhr.status === 507) {
                    message = 'Could not update file. Insufficient storage space in your Dropbox.';
                } else {
                    message = 'The file could not be updated.';
                }
                model.editor.setReadOnly(false);
                self.unthrottledStatus(oldstatus);
                $(document).trigger('fileviewpage:reload');
                model.editor.setValue(self.initialText);
                $osf.growl('Error', message);
                Raven.captureMessage('Could not PUT file content.', {
                    extra: {
                        textStatus: textStatus,
                        url: self.url
                    }
                });
                m.redraw();
            });
        }, 500);

        self.changed = function() {
            var file1 = self.initialText;
            var file2 = !model.editor ? '' : model.editor.getValue();

            var clean1 = typeof file1 === 'string' ?
                file1.replace(/(\r\n|\n|\r)/gm, '\n') : '';
            var clean2 = typeof file2 === 'string' ?
                file2.replace(/(\r\n|\n|\r)/gm, '\n') : '';

            return clean1 !== clean2;
        };

        self.loadFile(false);

        return self;
    },
    view: function(ctrl) {
        if (!ctrl.loaded) {
            return util.Spinner;
        }
        return m('.editor-pane.panel-body', [
            m('.wiki-connected-users', m('.row', m('.col-sm-12', [
                m('.ul.list-inline', {style: {'margin-top': '10px'}}, [
                    ctrl.observables.activeUsers().map(function(user) {
                        return m('li', m('a', {href: user.url}, [
                            m('img', {
                                title: user.name,
                                src: user.gravatar,
                                'data-container': 'body',
                                'data-placement': 'top',
                                'data-toggle': 'tooltip',
                                style: {border: '1px solid black'}
                            })
                        ]));
                    })

                ])
            ]))),
            m('', {style: {'padding-top': '10px'}}, [
                m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce})
            ]),
            m('br'),
            m('[style=position:inherit]', [
                m('.row', m('.col-sm-12', [
                    m('.pull-right', [
                        m('button#fileEditorRevert.btn.btn-sm.btn-danger', {onclick: function(){ctrl.loadFile(true);}}, 'Revert'),
                        ' ',
                        m('button#fileEditorSave.btn.btn-sm.btn-success', {onclick: function() {ctrl.saveFile();}}, 'Save')
                    ])
                ]))
            ])
        ]);

    }
};

module.exports = FileEditor;
<|endoftext|>