<commit_before>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  $(currentSlide).find(".content").trigger("showoff:show");

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{

  var event = jQuery.Event("showoff:prev");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  var event = jQuery.Event("showoff:next");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33 || key == 38) // Left arrow, page up, or up arrow
    {
      prevStep()
    }
    else if (key == 39 || key == 34 || key == 40) // Right arrow, page down, or down arrow
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
	else if (key == 80) // 'p' for preshow
	{
		runPreShow();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);

/********************
 PreShow Code
 ********************/

var preshow_seconds = 0;
var preshow_secondsLeft = 0;
var preshow_secondsPer = 8;
var preshow_running = false;
var preshow_timerRunning = false;
var preshow_current = 0;
var preshow_images;
var preshow_imagesTotal = 0;
var preshow_des;

function runPreShow() {
	if(preshow_running) {
		stopPreShow()
	} else {
		var minutes = prompt("Minutes from now to start")
		preshow_secondsLeft = parseFloat(minutes) * 60
		toggleFooter()
		$.getJSON("preshow_files", false, function(data) {
			$('#preso').after("

")
			$.each(data, function(i, n) {
				if(n == "preshow.json") {
					// has a descriptions file
					$.getJSON("/file/_preshow/preshow.json", false, function(data) {
						preshow_des = data
					})
				} else {
					$('#preshow').append('')
				}
			})
			startPreShow()
		})
	}
}

function startPreShow() {
  if (!preshow_running) {
    preshow_running = true
    preshow_seconds = 0
    preshow_images = $('#preshow > img')
    preshow_imagesTotal = preshow_images.size()
    nextPreShowImage()

    if(!preshow_timerRunning) {
      setInterval(function() {
        preshow_timerRunning = true
        if (!preshow_running) { return }
        preshow_seconds++
        preshow_secondsLeft--
		if (preshow_secondsLeft < 0) {
			stopPreShow()
		}
        if (preshow_seconds == preshow_secondsPer) {
          preshow_seconds = 0
          nextPreShowImage()
        }
		addPreShowTips()
      }, 1000)
    }
  }
}

function addPreShowTips() {
	time = secondsToTime(preshow_secondsLeft)
	$('#preshow_timer').text(time + ' to go-time')
	var des = preshow_des[tmpImg.attr("ref")]
	if(des) {
		$('#tips').show()
		$('#tips').text(des)
	} else {
		$('#tips').hide()
	}
}

function secondsToTime(sec) {
	min = Math.floor(sec / 60)
	sec = sec - (min * 60)
	if(sec < 10) {
		sec = "0" + sec
	}
	return min + ":" + sec
}

function stopPreShow() {
	preshow_running = false

	$('#preshow').remove()
	$('#tips').remove()
	$('#preshow_timer').remove()

	toggleFooter()
	loadSlides(loadSlidesBool, loadSlidesPrefix);
}

function nextPreShowImage() {
	preshow_current += 1
	if((preshow_current + 1) > preshow_imagesTotal) {
		preshow_current = 0
	}

	$("#preso").empty()
	tmpImg = preshow_images.eq(preshow_current).clone()
	$(tmpImg).attr('width', '1020')
	$("#preso").html(tmpImg)
}

/********************
 End PreShow Code
 ********************/
<commit_msg>js/showoff.js: strip trailing whitespace<commit_after>/* ShowOff JS Logic */

var ShowOff = {};

var preso_started = false
var slidenum = 0
var slideTotal = 0
var slides
var currentSlide
var totalslides = 0
var slidesLoaded = false
var incrSteps = 0
var incrElem
var incrCurr = 0
var incrCode = false
var debugMode = false
var gotoSlidenum = 0
var shiftKeyActive = false

var loadSlidesBool
var loadSlidesPrefix

function setupPreso(load_slides, prefix) {
  if (preso_started)
  {
     alert("already started")
     return
  }
  preso_started = true

  loadSlidesBool = load_slides
  loadSlidesPrefix = prefix
  loadSlides(loadSlidesBool, loadSlidesPrefix)

  doDebugStuff()

  // bind event handlers
  document.onkeydown = keyDown
  document.onkeyup = keyUp
  /* window.onresize  = resized; */
  /* window.onscroll = scrolled; */
  /* window.onunload = unloaded; */
}

function loadSlides(load_slides, prefix) {
  //load slides offscreen, wait for images and then initialize
  if (load_slides) {
  	$("#slides").load("/slides", false, function(){
    	$("#slides img").batchImageLoad({
			loadingCompleteCallback: initializePresentation(prefix)
		})
  	})
  } else {
	$("#slides img").batchImageLoad({
		loadingCompleteCallback: initializePresentation(prefix)
	})
  }
}

function initializePresentation(prefix) {
  //center slides offscreen
  centerSlides($('#slides > .slide'))

  //copy into presentation area
  $("#preso").empty()
  $('#slides > .slide').appendTo($("#preso"))

  //populate vars
  slides = $('#preso > .slide')
  slideTotal = slides.size()

  //setup manual jquery cycle
  $('#preso').cycle({
    timeout: 0
  })

  setupMenu()
  if (slidesLoaded) {
    showSlide()
  } else {
    showFirstSlide();
    slidesLoaded = true
  }
  setupSlideParamsCheck();
  sh_highlightDocument(prefix+'/js/sh_lang/', '.min.js')
}

function centerSlides(slides) {
  slides.each(function(s, slide) {
    centerSlide(slide)
  })
}

function centerSlide(slide) {
  var slide_content = $(slide).children(".content").first()
  var height = slide_content.height()
  var mar_top = (0.5 * parseFloat($(slide).height())) - (0.5 * parseFloat(height))
  if (mar_top < 0) {
    mar_top = 0
  }
  slide_content.css('margin-top', mar_top)
}

function setupMenu() {
  $('#navmenu').hide();

  var currSlide = 0
  var menu = new ListMenu()

  slides.each(function(s, elem) {
    content = $(elem).children(".content")
    shortTxt = $(content).text().substr(0, 20)
    path = $(content).attr('ref').split('/')
    currSlide += 1
    menu.addItem(path, shortTxt, currSlide)
  })

  $('#navigation').html(menu.getList())
  $('#navmenu').menu({
    content: $('#navigation').html(),
    flyOut: true
  });
}

function checkSlideParameter() {
  if (slideParam = currentSlideFromParams()) {
    slidenum = slideParam;
  }
}

function currentSlideFromParams() {
  var result;
  if (result = window.location.hash.match(/#([0-9]+)/)) {
    return result[result.length - 1] - 1;
  }
}

function setupSlideParamsCheck() {
  var check = function() {
    var currentSlide = currentSlideFromParams();
    if (slidenum != currentSlide) {
      slidenum = currentSlide;
      showSlide();
    }
    setTimeout(check, 100);
  }
  setTimeout(check, 100);
}

function gotoSlide(slideNum) {
  slidenum = parseInt(slideNum)
  if (!isNaN(slidenum)) {
    showSlide()
  }
}

function showFirstSlide() {
  slidenum = 0
  checkSlideParameter();
  showSlide()
}

function showSlide(back_step) {

  if(slidenum < 0) {
    slidenum = 0
    return
  }

  if(slidenum > (slideTotal - 1)) {
    slidenum = slideTotal - 1
    return
  }

  currentSlide = slides.eq(slidenum)

  var transition = currentSlide.attr('data-transition')
  var fullPage = currentSlide.find(".content").is('.full-page');

  if (back_step || fullPage) {
    transition = 'none'
  }

  $('#preso').cycle(slidenum, transition)

  if (fullPage) {
    $('#preso').css({'width' : '100%', 'overflow' : 'visible'});
    currentSlide.css({'width' : '100%', 'text-align' : 'center', 'overflow' : 'visible'});
  } else {
    $('#preso').css({'width' : '1020px', 'overflow' : 'hidden'});
  }

  percent = getSlidePercent()
  $("#slideInfo").text((slidenum + 1) + '/' + slideTotal + '  - ' + percent + '%')

  if(!back_step) {
    // determine if there are incremental bullets to show
    // unless we are moving backward
    determineIncremental()
  } else {
    incrCurr = 0
    incrSteps = 0
  }
  location.hash = slidenum + 1;
  $('body').addSwipeEvents().
    bind('swipeleft',  swipeLeft).
    bind('swiperight', swipeRight)
  removeResults()

  $(currentSlide).find(".content").trigger("showoff:show");

  return getCurrentNotes()
}

function getSlideProgress()
{
  return (slidenum + 1) + '/' + slideTotal
}

function getCurrentNotes()
{
  return currentSlide.find("p.notes").text()
}

function getSlidePercent()
{
  return Math.ceil(((slidenum + 1) / slideTotal) * 100)
}

function determineIncremental()
{
  incrCurr = 0
  incrCode = false
  incrElem = currentSlide.find(".incremental > ul > li")
  incrSteps = incrElem.size()
  if(incrSteps == 0) {
    // also look for commandline
    incrElem = currentSlide.find(".incremental > pre > code > code")
    incrSteps = incrElem.size()
    incrCode = true
  }
  incrElem.each(function(s, elem) {
    $(elem).hide()
  })
}

function prevStep()
{

  var event = jQuery.Event("showoff:prev");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  slidenum--
  return showSlide(true) // We show the slide fully loaded
}

function nextStep()
{
  var event = jQuery.Event("showoff:next");
  $(currentSlide).find(".content").trigger(event);
  if (event.isDefaultPrevented()) {
      return;
  }

  if (incrCurr >= incrSteps) {
    slidenum++
    return showSlide()
  } else {
    elem = incrElem.eq(incrCurr)
    if (incrCode && elem.hasClass('command')) {
      incrElem.eq(incrCurr).show().jTypeWriter({duration:1.0})
    } else {
      incrElem.eq(incrCurr).show()
    }
    incrCurr++
  }
}

function doDebugStuff()
{
  if (debugMode) {
    $('#debugInfo').show()
    debug('debug mode on')
  } else {
    $('#debugInfo').hide()
  }
}

function debug(data)
{
  $('#debugInfo').text(data)
}

//  See e.g. http://www.quirksmode.org/js/keys.html for keycodes
function keyDown(event)
{
    var key = event.keyCode;

    if (event.ctrlKey || event.altKey || event.metaKey)
       return true;

    debug('keyDown: ' + key)

    if (key >= 48 && key <= 57) // 0 - 9
    {
      gotoSlidenum = gotoSlidenum * 10 + (key - 48);
      return true;
    }

    if (key == 13){
        if (gotoSlidenum > 0) {
            debug('go to ' + gotoSlidenum);
            slidenum = gotoSlidenum - 1;
            showSlide(true);
            gotoSlidenum = 0;
        } else {
            debug('executeCode');
            executeCode.call($('.sh_javaScript code:visible'));
        }

    }

    if (key == 16) // shift key
    {
      shiftKeyActive = true;
    }
    if (key == 32) // space bar
    {
      if (shiftKeyActive) { prevStep() }
      else                { nextStep() }
    }
    else if (key == 68) // 'd' for debug
    {
      debugMode = !debugMode
      doDebugStuff()
    }
    else if (key == 37 || key == 33 || key == 38) // Left arrow, page up, or up arrow
    {
      prevStep()
    }
    else if (key == 39 || key == 34 || key == 40) // Right arrow, page down, or down arrow
    {
      nextStep()
    }
    else if (key == 82) // R for reload
    {
      if (confirm('really reload slides?')) {
        loadSlides(loadSlidesBool, loadSlidesPrefix)
        showSlide()
      }
    }
    else if (key == 84 || key == 67)  // T or C for table of contents
    {
      $('#navmenu').toggle().trigger('click')
    }
    else if (key == 90) // z for help
    {
      $('#help').toggle()
    }
    else if (key == 66 || key == 70) // f for footer (also "b" which is what kensington remote "stop" button sends
    {
      toggleFooter()
    }
	else if (key == 27) // esc
	{
		removeResults();
	}
	else if (key == 80) // 'p' for preshow
	{
		runPreShow();
	}
    return true
}

function toggleFooter()
{
  $('#footer').toggle()
}

function keyUp(event) {
  var key = event.keyCode;
  debug('keyUp: ' + key);
  if (key == 16) // shift key
  {
    shiftKeyActive = false;
  }
}

function swipeLeft() {
  nextStep()
}

function swipeRight() {
  prevStep()
}

function ListMenu(s)
{
  this.slide = s
  this.typeName = 'ListMenu'
  this.itemLength = 0;
  this.items = new Array();
  this.addItem = function (key, text, slide) {
    if (key.length > 1) {
      thisKey = key.shift()
      if (!this.items[thisKey]) {
        this.items[thisKey] = new ListMenu(slide)
      }
      this.items[thisKey].addItem(key, text, slide)
    } else {
      thisKey = key.shift()
      this.items[thisKey] = new ListMenuItem(text, slide)
    }
  }
  this.getList = function() {
    var newMenu = $("
")
    for(var i in this.items) {
      var item = this.items[i]
      var domItem = $("
")
      if (item.typeName == 'ListMenu') {
        choice = $("" + i + "")
        domItem.append(choice)
        domItem.append(item.getList())
      }
      if (item.typeName == 'ListMenuItem') {
        choice = $("" + item.slide + '. ' + item.textName + "")
        domItem.append(choice)
      }
      newMenu.append(domItem)
    }
    return newMenu
  }
}

function ListMenuItem(t, s)
{
  this.typeName = "ListMenuItem"
  this.slide = s
  this.textName = t
}

var removeResults = function() {
  $('.results').remove();
};

var print = function(text) {
  removeResults();
  var _results = $('
').addClass('results').html($.print(text, {max_string:500}));
  $('body').append(_results);
  _results.click(removeResults);
};

function executeCode () {
    result = null;
    var codeDiv = $(this);
    codeDiv.addClass("executing");
    eval(codeDiv.text());
    setTimeout(function() { codeDiv.removeClass("executing");}, 250 );
    if (result != null) print(result);
}
$('.sh_javaScript code').live("click", executeCode);

/********************
 PreShow Code
 ********************/

var preshow_seconds = 0;
var preshow_secondsLeft = 0;
var preshow_secondsPer = 8;
var preshow_running = false;
var preshow_timerRunning = false;
var preshow_current = 0;
var preshow_images;
var preshow_imagesTotal = 0;
var preshow_des;

function runPreShow() {
	if(preshow_running) {
		stopPreShow()
	} else {
		var minutes = prompt("Minutes from now to start")
		preshow_secondsLeft = parseFloat(minutes) * 60
		toggleFooter()
		$.getJSON("preshow_files", false, function(data) {
			$('#preso').after("

")
			$.each(data, function(i, n) {
				if(n == "preshow.json") {
					// has a descriptions file
					$.getJSON("/file/_preshow/preshow.json", false, function(data) {
						preshow_des = data
					})
				} else {
					$('#preshow').append('')
				}
			})
			startPreShow()
		})
	}
}

function startPreShow() {
  if (!preshow_running) {
    preshow_running = true
    preshow_seconds = 0
    preshow_images = $('#preshow > img')
    preshow_imagesTotal = preshow_images.size()
    nextPreShowImage()

    if(!preshow_timerRunning) {
      setInterval(function() {
        preshow_timerRunning = true
        if (!preshow_running) { return }
        preshow_seconds++
        preshow_secondsLeft--
		if (preshow_secondsLeft < 0) {
			stopPreShow()
		}
        if (preshow_seconds == preshow_secondsPer) {
          preshow_seconds = 0
          nextPreShowImage()
        }
		addPreShowTips()
      }, 1000)
    }
  }
}

function addPreShowTips() {
	time = secondsToTime(preshow_secondsLeft)
	$('#preshow_timer').text(time + ' to go-time')
	var des = preshow_des[tmpImg.attr("ref")]
	if(des) {
		$('#tips').show()
		$('#tips').text(des)
	} else {
		$('#tips').hide()
	}
}

function secondsToTime(sec) {
	min = Math.floor(sec / 60)
	sec = sec - (min * 60)
	if(sec < 10) {
		sec = "0" + sec
	}
	return min + ":" + sec
}

function stopPreShow() {
	preshow_running = false

	$('#preshow').remove()
	$('#tips').remove()
	$('#preshow_timer').remove()

	toggleFooter()
	loadSlides(loadSlidesBool, loadSlidesPrefix);
}

function nextPreShowImage() {
	preshow_current += 1
	if((preshow_current + 1) > preshow_imagesTotal) {
		preshow_current = 0
	}

	$("#preso").empty()
	tmpImg = preshow_images.eq(preshow_current).clone()
	$(tmpImg).attr('width', '1020')
	$("#preso").html(tmpImg)
}

/********************
 End PreShow Code
 ********************/
<|endoftext|>


<commit_before>import d3 from "d3";

// datasets json: object of list (to ensure order) of list (to be flexible)
// until terminated by an empty list indicating that no further datasets
// resolution are made
export const datasets={
  'virus':{
    'flu':{
      'lineages':{
        'h3n2':     {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'h1n1pdm':  {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'Vic':      {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'Yam':      {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'default':'h3n2',
        }
      },
    'zika':{},
    'ebola':{},
    'default':'zika'
  }
}

export const colorOptions = {
    "country":{"key":"country", "legendTitle":"Country", "menuItem":"country", "type":"discrete"},
    "region":{"key":"region", "legendTitle":"Region", "menuItem":"region", "type":"discrete"},
    "num_date":{"key":"num_date", "legendTitle":"Sampling date", "menuItem":"date", "type":"continuous"},
    "ep":{"key":"ep", "legendTitle":"Epitope Mutations", "menuItem":"epitope mutations", "type":"continuous"},
    "ne":{"key":"ne", "legendTitle":"Non-epitope Mutations", "menuItem":"nonepitope mutations", "type":"continuous"},
    "rb":{"key":"rb", "legendTitle":"Receptor Binding Mutations", "menuItem":"RBS mutations", "type":"continuous"},
    "gt":{"key":"genotype", "legendTitle":"Genotype", "menuItem":"genotype", "type":"discrete"}
  }

/* static for now, then hand rolled version of https://github.com/digidem/react-dimensions */
export const width = 1126;
export const margin = 60;
export const controlsWidth = 250;
export const totalVerticalPadding = 160; // this includes the header + space between the bottom and the card
export const controlsHiddenWidth = 2000;
export const entropyChartHeight = 300;
export const defaultColorBy = "country";
export const defaultDateSliderFraction = 0.3;
export const defaultDateRange = 6;
export const maxMapWidth = 1000; /* just right for our default zoom level (which is also min) */
export const date_select = true;
export const file_prefix = "Zika_";
export const branchLabels = false;
export const restrictTo = {"region": "all"};
export const time_window = 3.0;
export const fullDataTimeWindow = 1.5;
export const time_ticks = [2013.0, 2013.5, 2014.0, 2014.5, 2015.0, 2015.5, 2016.0];
export const dfreq_dn = 2;
export const reallySmallNumber = -100000000;
export const reallyBigNumber = 10000000;
export const LBItime_window = 0.5;
export const LBItau = 0.0005;
export const mutType = "nuc";
export const default_gene = "nuc";
export const plot_frequencies = false;
export const genericDomain = [ 0, 0.111, 0.222, 0.333, 0.444, 0.555, 0.666, 0.777, 0.888, 1.0 ];
export const epiColorDomain = genericDomain;
export const nonEpiColorDomain = genericDomain;
export const rbsColorDomain = genericDomain;
export const dateColorDomain = genericDomain;
export const legendRectSize = 15;
export const legendSpacing = 4;
export const nonTipNodeRadius = 0;
export const tipRadius = 4;
export const tipRadiusOnLegendMatchMultiplier = 1.7;
export const defaultDistanceMeasures = ["num_date", "div"];
export const fastTransitionDuration = 300; // in milliseconds
export const mediumTransitionDuration = 600; // in milliseconds
export const slowTransitionDuration = 1200; // in milliseconds
export const HIColorDomain = genericDomain.map((d) => {
  return Math.round(100 * (d * 3.6)) / 100;
});
export const dfreqColorDomain = genericDomain.map((d) => {
  return Math.round(100 * (0.2 + d * 1.8)) / 100;
});
export const fitnessColorDomain = genericDomain.map((d) => {
  return Math.round(100 * ((d - 0.5) * 16.0)) / 100;
});
export const dHIScale = d3.scale.linear()
  .domain([0, 1])
  .range([2.0, 4.5]);

export const freqScale = d3.scale.sqrt()
  .domain([0, 1])
  .range([1, 10]);

export const distanceScale = d3.scale.sqrt()
  .domain([3, 20])
  .range([9, 3])
  .clamp([true]);

export const colors = [
  [],
  ["#8EBC66"],
  ["#4D92BF", "#E4662E"],
  ["#4B8FC1", "#AABD52", "#E3612D"],
  ["#4A8BC3", "#82BA72", "#CFB541", "#E25B2C"],
  ["#4988C5", "#6EB389", "#AABD52", "#DEA73C", "#E2562B"],
  ["#4785C7", "#64AD99", "#90BC65", "#C3BA46", "#E39A39", "#E1512A"],
  ["#4682C9", "#5CA7A4", "#7FB975", "#AABD52", "#D2B340", "#E68F36", "#E04C29"],
  ["#457FCB", "#57A1AD", "#73B584", "#96BD5F", "#BDBB49", "#DBAC3D", "#E68334", "#DF4628"],
  ["#447BCD", "#539CB4", "#6AB090", "#88BB6C", "#AABD52", "#CBB842", "#E0A23A", "#E67A32", "#DF4127"],
  ["#4377CD", "#5097BA", "#63AC9A", "#7CB879", "#9ABE5C", "#B9BC4A", "#D4B13F", "#E49938", "#E67030", "#DE3C26"],
  ["#4273CE", "#4D93BE", "#5DA8A3", "#73B584", "#8DBC68", "#AABD52", "#C6B945", "#DBAC3D", "#E69036", "#E4672E", "#DD3725"],
  ["#426FCE", "#4B8DC2", "#59A3AA", "#6BB18D", "#82BA71", "#9CBE5B", "#B7BD4B", "#CFB541", "#DFA43B", "#E68735", "#E35E2D", "#DD3124"]
];
export const genotypeColors = [
  "#60AA9E",
  "#D9AD3D",
  "#5097BA",
  "#E67030",
  "#8EBC66",
  "#E59637",
  "#AABD52",
  "#DF4327",
  "#C4B945",
  "#75B681"
];
export const regions = [
  ['southeast_asia',     '#462EB9'],
  ['oceania',            '#3F4FCC'],
  ['china',              '#4271CE'],
  ['japan_korea',        '#4B8DC2'],
  ['south_america',      '#69B091'],
  ['north_america',      '#E0A33B']
];
export const countries = [
// Asia: "#462EB9", "#403DC5", "#3F4FCC", "#3F60D0", "#4271CE", "#4580CA", "#4B8DC2", "#5199B8", "#58A2AC"
["thailand",           "#462EB9"],
["singapore",          "#403DC5"],
["french_polynesia",   "#3F4FCC"],
["american_samoa",	   "#3F60D0"],
["tonga",	             "#4271CE"],
["china",			         "#4580CA"],
["japan",			         "#4B8DC2"],
// South America: "#60AA9F", "#69B091", "#73B584", "#7DB877", "#89BB6B", "#95BD60", "#A2BE57", "#AFBD4F"
["brazil",  		       "#60AA9F"],
["ecuador",  		       "#7DB877"],
["colombia",  		     "#89BB6B"],
["french_guiana",  	   "#95BD60"],
["suriname",  		     "#A2BE57"],
["venezuela",  		     "#AFBD4F"],
// Central America: "#BBBC49", "#C6B944", "#D0B440", "#D9AD3D", "#E0A33B", "#E49838", "#E68835", "#E67732", "#E4632E", "#E04E2A", "#DE3926"
["panama",             "#BBBC49"],
["honduras",           "#C6B944"],
["guatemala",  		     "#D0B440"],
["mexico",             "#D9AD3D"],
["martinique",  	     "#E0A33B"],
["guadeloupe",         "#E49838"],
["puerto_rico",  	     "#E68835"],
["dominican_republic", "#E67732"],
["haiti",  			       "#E4632E"],
["usa",                "#E04E2A"]
];

//const filterAbbr = [["geo", "geographic location"]];
export const filterAbbrFwd = {"geo":"geographic location", "all":"all"};
export const filterAbbrRev = {"geographic location":"geo", "all":"all"};
<commit_msg>add two column breakpoint to globals<commit_after>import d3 from "d3";

// datasets json: object of list (to ensure order) of list (to be flexible)
// until terminated by an empty list indicating that no further datasets
// resolution are made
export const datasets={
  'virus':{
    'flu':{
      'lineages':{
        'h3n2':     {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'h1n1pdm':  {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'Vic':      {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'Yam':      {'duration':{'3y':{}, '6y':{}, '12y':{}, 'default':'3y'}},
        'default':'h3n2',
        }
      },
    'zika':{},
    'ebola':{},
    'default':'zika'
  }
}

export const colorOptions = {
    "country":{"key":"country", "legendTitle":"Country", "menuItem":"country", "type":"discrete"},
    "region":{"key":"region", "legendTitle":"Region", "menuItem":"region", "type":"discrete"},
    "num_date":{"key":"num_date", "legendTitle":"Sampling date", "menuItem":"date", "type":"continuous"},
    "ep":{"key":"ep", "legendTitle":"Epitope Mutations", "menuItem":"epitope mutations", "type":"continuous"},
    "ne":{"key":"ne", "legendTitle":"Non-epitope Mutations", "menuItem":"nonepitope mutations", "type":"continuous"},
    "rb":{"key":"rb", "legendTitle":"Receptor Binding Mutations", "menuItem":"RBS mutations", "type":"continuous"},
    "gt":{"key":"genotype", "legendTitle":"Genotype", "menuItem":"genotype", "type":"discrete"}
  }

/* static for now, then hand rolled version of https://github.com/digidem/react-dimensions */
export const width = 1126;
export const margin = 60;
export const controlsWidth = 250;
export const totalVerticalPadding = 160; // this includes the header + space between the bottom and the card (refactor.)
export const controlsHiddenWidth = 800;
export const entropyChartHeight = 300;
export const defaultColorBy = "country";
export const defaultDateSliderFraction = 0.3;
export const twoColumnBreakpoint = 1200;
export const defaultDateRange = 6;
export const maxMapWidth = 1000; /* just right for our default zoom level (which is also min) */
export const date_select = true;
export const file_prefix = "Zika_";
export const branchLabels = false;
export const restrictTo = {"region": "all"};
export const time_window = 3.0;
export const fullDataTimeWindow = 1.5;
export const time_ticks = [2013.0, 2013.5, 2014.0, 2014.5, 2015.0, 2015.5, 2016.0];
export const dfreq_dn = 2;
export const reallySmallNumber = -100000000;
export const reallyBigNumber = 10000000;
export const LBItime_window = 0.5;
export const LBItau = 0.0005;
export const mutType = "nuc";
export const default_gene = "nuc";
export const plot_frequencies = false;
export const genericDomain = [ 0, 0.111, 0.222, 0.333, 0.444, 0.555, 0.666, 0.777, 0.888, 1.0 ];
export const epiColorDomain = genericDomain;
export const nonEpiColorDomain = genericDomain;
export const rbsColorDomain = genericDomain;
export const dateColorDomain = genericDomain;
export const legendRectSize = 15;
export const legendSpacing = 4;
export const nonTipNodeRadius = 0;
export const tipRadius = 4;
export const tipRadiusOnLegendMatchMultiplier = 1.7;
export const defaultDistanceMeasures = ["num_date", "div"];
export const fastTransitionDuration = 300; // in milliseconds
export const mediumTransitionDuration = 600; // in milliseconds
export const slowTransitionDuration = 1200; // in milliseconds
export const HIColorDomain = genericDomain.map((d) => {
  return Math.round(100 * (d * 3.6)) / 100;
});
export const dfreqColorDomain = genericDomain.map((d) => {
  return Math.round(100 * (0.2 + d * 1.8)) / 100;
});
export const fitnessColorDomain = genericDomain.map((d) => {
  return Math.round(100 * ((d - 0.5) * 16.0)) / 100;
});
export const dHIScale = d3.scale.linear()
  .domain([0, 1])
  .range([2.0, 4.5]);

export const freqScale = d3.scale.sqrt()
  .domain([0, 1])
  .range([1, 10]);

export const distanceScale = d3.scale.sqrt()
  .domain([3, 20])
  .range([9, 3])
  .clamp([true]);

export const colors = [
  [],
  ["#8EBC66"],
  ["#4D92BF", "#E4662E"],
  ["#4B8FC1", "#AABD52", "#E3612D"],
  ["#4A8BC3", "#82BA72", "#CFB541", "#E25B2C"],
  ["#4988C5", "#6EB389", "#AABD52", "#DEA73C", "#E2562B"],
  ["#4785C7", "#64AD99", "#90BC65", "#C3BA46", "#E39A39", "#E1512A"],
  ["#4682C9", "#5CA7A4", "#7FB975", "#AABD52", "#D2B340", "#E68F36", "#E04C29"],
  ["#457FCB", "#57A1AD", "#73B584", "#96BD5F", "#BDBB49", "#DBAC3D", "#E68334", "#DF4628"],
  ["#447BCD", "#539CB4", "#6AB090", "#88BB6C", "#AABD52", "#CBB842", "#E0A23A", "#E67A32", "#DF4127"],
  ["#4377CD", "#5097BA", "#63AC9A", "#7CB879", "#9ABE5C", "#B9BC4A", "#D4B13F", "#E49938", "#E67030", "#DE3C26"],
  ["#4273CE", "#4D93BE", "#5DA8A3", "#73B584", "#8DBC68", "#AABD52", "#C6B945", "#DBAC3D", "#E69036", "#E4672E", "#DD3725"],
  ["#426FCE", "#4B8DC2", "#59A3AA", "#6BB18D", "#82BA71", "#9CBE5B", "#B7BD4B", "#CFB541", "#DFA43B", "#E68735", "#E35E2D", "#DD3124"]
];
export const genotypeColors = [
  "#60AA9E",
  "#D9AD3D",
  "#5097BA",
  "#E67030",
  "#8EBC66",
  "#E59637",
  "#AABD52",
  "#DF4327",
  "#C4B945",
  "#75B681"
];
export const regions = [
  ['southeast_asia',     '#462EB9'],
  ['oceania',            '#3F4FCC'],
  ['china',              '#4271CE'],
  ['japan_korea',        '#4B8DC2'],
  ['south_america',      '#69B091'],
  ['north_america',      '#E0A33B']
];
export const countries = [
// Asia: "#462EB9", "#403DC5", "#3F4FCC", "#3F60D0", "#4271CE", "#4580CA", "#4B8DC2", "#5199B8", "#58A2AC"
["thailand",           "#462EB9"],
["singapore",          "#403DC5"],
["french_polynesia",   "#3F4FCC"],
["american_samoa",	   "#3F60D0"],
["tonga",	             "#4271CE"],
["china",			         "#4580CA"],
["japan",			         "#4B8DC2"],
// South America: "#60AA9F", "#69B091", "#73B584", "#7DB877", "#89BB6B", "#95BD60", "#A2BE57", "#AFBD4F"
["brazil",  		       "#60AA9F"],
["ecuador",  		       "#7DB877"],
["colombia",  		     "#89BB6B"],
["french_guiana",  	   "#95BD60"],
["suriname",  		     "#A2BE57"],
["venezuela",  		     "#AFBD4F"],
// Central America: "#BBBC49", "#C6B944", "#D0B440", "#D9AD3D", "#E0A33B", "#E49838", "#E68835", "#E67732", "#E4632E", "#E04E2A", "#DE3926"
["panama",             "#BBBC49"],
["honduras",           "#C6B944"],
["guatemala",  		     "#D0B440"],
["mexico",             "#D9AD3D"],
["martinique",  	     "#E0A33B"],
["guadeloupe",         "#E49838"],
["puerto_rico",  	     "#E68835"],
["dominican_republic", "#E67732"],
["haiti",  			       "#E4632E"],
["usa",                "#E04E2A"]
];

//const filterAbbr = [["geo", "geographic location"]];
export const filterAbbrFwd = {"geo":"geographic location", "all":"all"};
export const filterAbbrRev = {"geographic location":"geo", "all":"all"};
<|endoftext|>


<commit_before>/**
 * sivart-ci v0.1.0
 *
 * A simple interactive CI Dashboard built on MEAN stack.
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 27 November, 2015
 *
 * Sivart CI Angular App.
 */

(function() {
    var sivartCI = angular.module('sivartCI', []);

    /*
     * Declare App Controllers
     */
    sivartCI.controller("MainController", MainController);

    /*
     * Main Controller
     */
    MainController.$inject = ["$scope"];
    function MainController($scope, $http) {

    };
})();
<commit_msg>Preprocessors added for Changelist table.<commit_after>/**
 * sivart-ci v0.1.0
 *
 * A simple interactive CI Dashboard built on MEAN stack.
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 27 November, 2015
 *
 * Sivart CI Angular App.
 */

(function() {
    var sivartCI = angular.module('sivartCI', []);

    /*
     * Declare App Controllers
     */
    sivartCI.controller("MainController", ["$scope", "$http", "$sce", MainController]);

    /*
     * Main Controller
     */
    MainController.$inject = ["$scope"];
    function MainController($scope, $http, $sce) {

        // Load Data
        $http.get('/api/changelists')
        .success(function(data) {
            $scope.changelistItems = data;
        })
        .error(function(data) {
            console.log('Error Loading Changelists');
        });

        // Item Preprocessors.
        $scope.getTimeStarted = function(timeStarted) {
            var timeStartedObj = new Date(timeStarted),
                hh = timeStartedObj.getHours(),
                mm = timeStartedObj.getMinutes(),
                ampm = hh >= 12 ? 'pm' : 'am',
                formattedString;

            hh = hh % 12;
            hh = hh ? hh : 12;
            mm = mm < 10 ? '0' + mm : mm;

            formattedString = timeStartedObj.getMonth() + '/' +
                              timeStartedObj.getDate() + '/' +
                              timeStartedObj.getUTCFullYear() + ' ' +
                              '' +
                              hh + ':' + mm + ' ' + ampm;

            return $sce.trustAsHtml(formattedString);
        };

        $scope.getStatus = function(status) {
            var statusEl = {
                "-1": "Failed",
                "0": "Pending",
                "1": "Passed",
                "2": "Running"
            };

            switch (status) {
                case -1:
                    statusEl = 'Failed';
                    break;
                case 0:
                    statusEl = 'Pending';
                    break;
                case 1:
                    statusEl = 'Passed';
                    break;
                default:
                    statusEl = 'Running';
            }

            return $sce.trustAsHtml(statusEl);
        };

        $scope.getInitialStatusClass = function(status) {
            var statusMap = {
                "-1": "item-fail",
                "0": "item-pending",
                "1": "item-pass",
                "2": "item-active"
            };

            return statusMap[status];
        };
    }
})();
<|endoftext|>


<commit_before>(function (global, factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = function (global) {
      var core = require('./core.js');
      return factory(global, core);
    };
  } else {
    factory(global, global._);
  }
}(this, function (global, _) {
  'use strict';

  var window = global.window;
  var document = window.document;
  var $ = global.$ || {};

  var patterns = [];

  $.register = function (pattern) {
    patterns.push(pattern);
  };

  function dispatchByObject (rule, url_6) {
    var matched = {};

    var passed = _.C(rule).all(function (pattern, part) {
      if (pattern instanceof RegExp) {
        matched[part] = url_6[part].match(pattern);
      } else if (pattern instanceof Array) {
        // may be an array of regexp
        var r = _.C(pattern).find(function (p) {
          var m = url_6[part].match(p);
          return m || _.nop;
        });
        matched[part] = r ? r.payload : null;
      }

      return !!matched[part];
    });

    return passed ? matched : null;
  }

  function dispatchByRegExp (rule, url_1) {
    return url_1.match(rule);
  }

  function dispatchByArray (byLocation, rules, url_1, url_3, url_6) {
    var tmp = _.C(rules).find(function (rule) {
      var m = dispatch(byLocation, rule, url_1, url_3, url_6);
      if (!m) {
        return _.nop;
      }
      return m;
    });
    return tmp ? tmp.payload : null;
  }

  function dispatchByString (rule, url_3) {
    // <scheme> := '*' | 'http' | 'https' | 'file' | 'ftp' | 'chrome-extension'
    var scheme = /\*|https?|file|ftp|chrome-extension/;
    // <host> := '*' | '*.' <any char except '/' and '*'>+
    var host = /\*|(\*\.)?([^\/*]+)/;
    // <path> := '/' <any chars>
    var path = /\/.*/;
    // <url-pattern> := <scheme>://<host><path>
    var up = new RegExp(_.T('^({scheme})://({host})?({path})$')({
      scheme: scheme.source,
      host: host.source,
      path: path.source,
    }));
    var matched = rule.match(up);

    if (!matched) {
      return null;
    }

    scheme = matched[1];
    host = matched[2];
    var wc = matched[3];
    var sd = matched[4];
    path = matched[5];

    if (scheme === '*' && !/https?/.test(url_3.scheme)) {
      return null;
    } else if (scheme !== url_3.scheme) {
      return null;
    }

    if (scheme !== 'file' && host !== '*') {
      if (wc) {
        up = url_3.host.indexOf(sd);
        if (up < 0 || up + sd.length !== url_3.host.length) {
          return null;
        }
      } else if (host !== url_3.host) {
        return null;
      }
    }

    path = new RegExp(_.T('^{0}$')(path.replace(/[*.\[\]?+#]/g, function (c) {
      if (c === '*') {
        return '.*';
      }
      return '\\' + c;
    })));
    if (!path.test(url_3.path)) {
      return null;
    }

    return url_3;
  }

  function dispatchByFunction (rule, url_1, url_3, url_6) {
    return rule(url_1, url_3, url_6);
  }

  function dispatch (byLocation, rule, url_1, url_3, url_6) {
    // recursively dispatching
    if (rule instanceof Array) {
      return dispatchByArray(byLocation, rule, url_1, url_3, url_6);
    }

    // dispatch by HTML content
    if (!byLocation) {
      if (typeof rule !== 'function') {
        return null;
      }
      return dispatchByFunction(rule, url_1, url_3, url_6);
    }

    // dispatch by URL
    if (rule instanceof RegExp) {
      return dispatchByRegExp(rule, url_1);
    }
    if (typeof rule === 'string' || rule instanceof String) {
      return dispatchByString(rule, url_3);
    }
    if (typeof rule === 'function') {
      return null;
    }
    return dispatchByObject(rule, url_6);
  }

  $._findHandler = function (byLocation) {
    var url_1 = window.location.toString();
    // <scheme>://<host><path>
    var url_3 = {
      scheme: window.location.protocol.slice(0, -1),
      host: window.location.host,
      path: window.location.pathname + window.location.search + window.location.hash,
    };
    // <scheme>//<host>:<port><path><query><hash>
    var url_6 = {
      scheme: window.location.protocol,
      host: window.location.hostname,
      port: window.location.port,
      path: window.location.pathname,
      query: window.location.search,
      hash: window.location.hash,
    };

    var pattern = _.C(patterns).find(function (pattern) {
      var m = dispatch(byLocation, pattern.rule, url_1, url_3, url_6);
      if (!m) {
        return _.nop;
      }
      return m;
    });
    if (!pattern) {
      return null;
    }

    var matched = pattern.payload;
    pattern = pattern.value;

    // exclude rule
    if (!pattern.start && !pattern.ready) {
      return null;
    }

    return {
      start: pattern.start ? _.P(pattern.start, matched) : _.nop,
      ready: pattern.ready ? _.P(pattern.ready, matched) : _.nop,
    };
  };

  return $;

}));

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Adjust dispatcher.<commit_after>(function (global, factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = function (global) {
      var core = require('./core.js');
      return factory(global, core);
    };
  } else {
    factory(global, global._);
  }
}(this, function (global, _) {
  'use strict';

  var window = global.window;
  var document = window.document;
  var $ = global.$ || {};

  var patterns = [];

  $.register = function (pattern) {
    patterns.push(pattern);
  };

  function dispatchByObject (rule, url_6) {
    var matched = {};

    var passed = _.C(rule).all(function (pattern, part) {
      if (pattern instanceof RegExp) {
        matched[part] = url_6[part].match(pattern);
      } else if (pattern instanceof Array) {
        // may be an array of regexp
        var r = _.C(pattern).find(function (p) {
          var m = url_6[part].match(p);
          return m || _.nop;
        });
        matched[part] = r ? r.payload : null;
      }

      return !!matched[part];
    });

    return passed ? matched : null;
  }

  function dispatchByRegExp (rule, url_1) {
    return url_1.match(rule);
  }

  function dispatchByArray (byLocation, rules, url_1, url_3, url_6) {
    var tmp = _.C(rules).find(function (rule) {
      var m = dispatch(byLocation, rule, url_1, url_3, url_6);
      if (!m) {
        return _.nop;
      }
      return m;
    });
    return tmp ? tmp.payload : null;
  }

  function dispatchByString (rule, url_3) {
    // <scheme> := '*' | 'http' | 'https' | 'file' | 'ftp' | 'chrome-extension'
    var scheme = /\*|https?|file|ftp|chrome-extension/;
    // <host> := '*' | '*.' <any char except '/' and '*'>+
    var host = /\*|(\*\.)?([^\/*]+)/;
    // <path> := '/' <any chars>
    var path = /\/.*/;
    // <url-pattern> := <scheme>://<host><path>
    var up = new RegExp(_.T('^({scheme})://({host})?({path})$')({
      scheme: scheme.source,
      host: host.source,
      path: path.source,
    }));
    var matched = rule.match(up);

    if (!matched) {
      return null;
    }

    scheme = matched[1];
    host = matched[2];
    var wc = matched[3];
    var sd = matched[4];
    path = matched[5];

    if (scheme === '*' && !/https?/.test(url_3.scheme)) {
      return null;
    } else if (scheme !== url_3.scheme) {
      return null;
    }

    if (scheme !== 'file' && host !== '*') {
      if (wc) {
        up = url_3.host.indexOf(sd);
        if (up < 0 || up + sd.length !== url_3.host.length) {
          return null;
        }
      } else if (host !== url_3.host) {
        return null;
      }
    }

    path = new RegExp(_.T('^{0}$')(path.replace(/[*.\[\]?+#]/g, function (c) {
      if (c === '*') {
        return '.*';
      }
      return '\\' + c;
    })));
    if (!path.test(url_3.path)) {
      return null;
    }

    return url_3;
  }

  function dispatchByFunction (rule, url_1, url_3, url_6) {
    return rule(url_1, url_3, url_6);
  }

  function dispatch (byLocation, rule, url_1, url_3, url_6) {
    // recursively dispatching
    if (rule instanceof Array) {
      return dispatchByArray(byLocation, rule, url_1, url_3, url_6);
    }

    // dispatch by HTML content
    if (typeof rule === 'function') {
      if (byLocation) {
        return null;
      }
      return dispatchByFunction(rule, url_1, url_3, url_6);
    }

    // dispatch by URL
    if (rule instanceof RegExp) {
      return dispatchByRegExp(rule, url_1);
    }
    if (typeof rule === 'string' || rule instanceof String) {
      return dispatchByString(rule, url_3);
    }
    return dispatchByObject(rule, url_6);
  }

  $._findHandler = function (byLocation) {
    var url_1 = window.location.toString();
    // <scheme>://<host><path>
    var url_3 = {
      scheme: window.location.protocol.slice(0, -1),
      host: window.location.host,
      path: window.location.pathname + window.location.search + window.location.hash,
    };
    // <scheme>//<host>:<port><path><query><hash>
    var url_6 = {
      scheme: window.location.protocol,
      host: window.location.hostname,
      port: window.location.port,
      path: window.location.pathname,
      query: window.location.search,
      hash: window.location.hash,
    };

    var pattern = _.C(patterns).find(function (pattern) {
      var m = dispatch(byLocation, pattern.rule, url_1, url_3, url_6);
      if (!m) {
        return _.nop;
      }
      return m;
    });
    if (!pattern) {
      return null;
    }

    var matched = pattern.payload;
    pattern = pattern.value;

    // exclude rule
    if (!pattern.start && !pattern.ready) {
      return null;
    }

    return {
      start: pattern.start ? _.P(pattern.start, matched) : _.nop,
      ready: pattern.ready ? _.P(pattern.ready, matched) : _.nop,
    };
  };

  return $;

}));

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>//clientY - does not work with all browsers?
//zoom is logarithmic - algebraicly establish range?
var parseTrack = function(track) {
    var altPitch, result, stack, i, l, j, start;
    altPitch = {
        A4: 5,
        Bb4: 10,
        B4: 15,
        C4: 20,
        Db4: 25,
        E4: 30,
        F4: 35,
        Gb4: 40,
        G4: 45,
        Ab4: 50,
        A5: 55,
        Bb5: 60,
        B5: 65
    };
    result = [];
    stack = [track.shift()];
    for (i = 0; i < track.length; ) {
        if (track[i][2] === 1) {
            stack.push(track.shift());
        } else {
            for (j = stack.length - 1; stack[j][1] !== track[i][1]; j -= 1) {
            }
            start = stack.splice(j, 1)[0];
            console.log(Tone.prototype.toSeconds(track[i][0])-Tone.prototype.toSeconds(start[0]));
            result.push({offset: Tone.prototype.toSeconds(start[0]) * 16,
                duration: (Tone.prototype.toSeconds(track[i][0]) - Tone.prototype.toSeconds(start[0])) * 16,
                pitch: altPitch[start[1]],
                volume: 10});
            track.shift();
        }
    }
    return result;
};
var showTrack = function(dataset) {
    var h = 95, w = 1000;
    // dataset to contain - offset, duration, pitch (height), volume
    dataset = dataset || [{offset: 10, duration: 10, pitch: 8, volume: 28}, {offset: 200, duration: 10, pitch: 8, volume: 28}];
    var dragmove = function(d) {
        d3.select(this)
            .attr("y", d.y = Math.floor((d3.event.sourceEvent.clientY - 5)/5) * 5);//Math.max(radius, Math.min(h - radius, d3.event.y)));
    };
    var zoomFn = function(d) {
        var col = Math.min(255, Math.floor(Math.pow(10, d3.event.scale)));
        d.volume = col;
        console.log(d);
        d3.select(this).attr('fill', 'rgb(' + col+ ',' +  col+','+ col+')');
    };
    var svg = d3.select('body')
        .append('svg')
        .attr('width', w + 'px')
        .attr('height', h + 'px');
    var drag = d3.behavior.drag()
        .origin(function(d) {return d;})
        .on('drag', dragmove);
    var zoom = d3.behavior.zoom()
        //.scaleExtent([0, 255])
        .on('zoom', zoomFn);
    var radius = 25;

    svg.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr({"x": function (d) {
            return d.offset;
        }, "y": function (d) {
            return d.pitch;
        }}).attr("class", "test").text(function (d) {
            return d;
        }).attr({"width": function(d){return d.duration}, "height": 10})
        .call(drag)
        .call(zoom);
    return svg;
};

<commit_msg>(fix) typos.<commit_after>//clientY - does not work with all browsers?
//zoom is logarithmic - algebraicly establish range?
var parseTrack = function(track) {
    var altPitch, result, stack, i, l, j, start;
    altPitch = {
        A4: 5,
        Bb4: 10,
        B4: 15,
        C4: 20,
        Db4: 25,
        E4: 30,
        F4: 35,
        Gb4: 40,
        G4: 45,
        Ab4: 50,
        A5: 55,
        Bb5: 60,
        B5: 65
    };
    result = [];
    stack = [track.shift()];
    for (i = 0; i < track.length; ) {
        if (track[i][2] === 1) {
            stack.push(track.shift());
        } else {
            for (j = stack.length - 1; stack[j][1] !== track[i][1]; j -= 1) {
            }
            start = stack.splice(j, 1)[0];
            result.push({offset: Tone.prototype.toSeconds(start[0]) * 16,
                duration: (Tone.prototype.toSeconds(track[i][0]) - Tone.prototype.toSeconds(start[0])) * 16,
                pitch: altPitch[start[1]],
                volume: 10});
            track.shift();
        }
    }
    return result;
};
var showTrack = function(dataset) {
    var h = 95, w = 1000;
    // dataset to contain - offset, duration, pitch (height), volume
    dataset = dataset || [{offset: 10, duration: 10, pitch: 8, volume: 28}, {offset: 200, duration: 10, pitch: 8, volume: 28}];
    var dragmove = function(d) {
        d3.select(this)
            .attr("y", d.y = Math.floor((d3.event.sourceEvent.clientY - 5)/5) * 5);//Math.max(radius, Math.min(h - radius, d3.event.y)));
    };
    var zoomFn = function(d) {
        var col = Math.min(255, Math.floor(Math.pow(10, d3.event.scale)));
        d.volume = col;
        d3.select(this).attr('fill', 'rgb(' + col+ ',' +  col+','+ col+')');
    };
    var svg = d3.select('body')
        .append('svg')
        .attr('width', w + 'px')
        .attr('height', h + 'px');
    var drag = d3.behavior.drag()
        .origin(function(d) {return d;})
        .on('drag', dragmove);
    var zoom = d3.behavior.zoom()
        //.scaleExtent([0, 255])
        .on('zoom', zoomFn);

    svg.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr({"x": function (d) {
            return d.offset;
        }, "y": function (d) {
            return d.pitch;
        }}).attr("class", "test").text(function (d) {
            return d;
        }).attr({"width": function(d){return d.duration}, "height": 10})
        .call(drag)
        .call(zoom);
    return svg;
};

<|endoftext|>


<commit_before>var app = new Vue({
    mounted: function (argument) {
        console.log("app is ready");
    },
    created() {
        this.fetchData();
        this.updateTheme();
    },
    el: '#app',
    data: {
        message: 'Hello Vue!',
        activities: [],
        currUser: '',
        searchEmail: '',
        emailSearchStatus: '',
        emailSearchStatusGroup: '',
        actDesc: '',
        showDescForm: 'm-fadeOut',
        errorMessage: '',
        symbolPath: '',
        theme: '',
        options: [
            { text: 'Hamburger', value: '/svg/hamburger.svg' },
            { text: 'Beer', value: '/svg/pint.svg' },
            { text: 'Resturant', value: '/svg/restaurant.svg' },
            { text: 'Taxi', value: '/svg/taxi.svg' },
            { text: 'Movie', value: '/svg/clapperboard.svg' },
            { text: 'Cocktail', value: '/svg/cocktail.svg' },
            { text: 'Coffee', value: '/svg/coffee-cup.svg' },
            { text: 'Steak', value: '/svg/food.svg' },
            { text: 'Drink', value: '/svg/glass.svg' },
            { text: 'Taco', value: '/svg/taco.svg' },
            { text: 'Tickets', value: '/svg/tickets.svg' },
            { text: 'Train', value: '/svg/train.svg' },
            { text: 'Travel', value: '/svg/luggage.svg' }
        ]
    },
    methods: {
        fetchData() {
            this.$http.get('/api/activities/get').then(response => {
                this.$set(this, 'activities', response.body.activities);
                this.$set(this, 'currUser', response.body.currUser);
                console.log('Heej + ' + this.currUser);
            });
        },
        updateTheme: function () {
            this.$http.get('/api/user/get').then(response => {
                var theme = response.body.profile.theme;
                switch (theme) {
                    case 1:
                        this.theme = 'theme-light';
                    case 2:
                        this.theme = 'theme-dark';
                    case 3:
                        this.theme = 'theme-color';
                    default:
                        this.theme = 'theme-light';
                }
            });
        },
        updatePost: function (data) {
            data._csrf = $('meta[name="csrf-token"]').attr('content');
            this.$http.post('/api/activities/changeturn', data)
                .then(function () {
                    this.fetchData();
                }
                    .bind(this),
                function () { });

        },
        findUser: function () {
            this.errorMessage = '';
            var data = {};
            data._csrf = $('meta[name="csrf-token"]').attr('content');
            data.email = this.searchEmail;
            this.$http.post('/api/user/find', data).then(response => {
                var userSearchStatus = JSON.stringify(response.body);
                if (userSearchStatus == 'true') {
                    this.emailSearchStatus = 'form-control-success';
                    this.emailSearchStatusGroup = 'has-success';
                    this.showDescForm = 'm-fadeIn';
                } else {
                    this.emailSearchStatus = 'form-control-danger';
                    this.emailSearchStatusGroup = 'has-danger';
                    this.showDescForm = 'm-fadeOut';
                    this.errorMessage = "Couldn't find that Moocher, want to send an invite?";
                }
            }, response => {
                this.emailSearchStatus = 'form-control-danger';
                this.showDescForm = 'm-fadeOut';
                this.emailSearchStatusGroup = 'has-danger';
                this.errorMessage = response.body.replace('"', '');
            }).bind(this),
                function () { };
        },
        newActivity: function () {
            this.$http.post('/api/activities/create', {
                email: this.searchEmail,
                desc: this.actDesc,
                symbolPath: this.symbolPath,
                _csrf: $('meta[name="csrf-token"]').attr('content')
            })
                .then(function (response) {
                    this.actDesc = '';
                    this.searchEmail = '';
                    this.showDescForm = 'm-fadeOut';
                    this.fetchData();
                }.bind(this),
                function () { });
        },
        getProfileImage: function (activity) {
            if (activity.turn.profile !== "undefined")
                return activity.turn.profile.picture;
            else
                // Twitter only, if FB then other implementation is needed.
                return "";
        },
        getOtherUsers: function (activity) {
            var currUser = this.currUser;
            var otherUser = activity.users.filter(function (user) {
                return user._id != currUser;
            });
            return otherUser[0].profile.name;
        }
    }
})<commit_msg>Removed debug text.<commit_after>var app = new Vue({
    mounted: function (argument) {
        console.log("app is ready");
    },
    created() {
        this.fetchData();
        this.updateTheme();
    },
    el: '#app',
    data: {
        message: 'Hello Vue!',
        activities: [],
        currUser: '',
        searchEmail: '',
        emailSearchStatus: '',
        emailSearchStatusGroup: '',
        actDesc: '',
        showDescForm: 'm-fadeOut',
        errorMessage: '',
        symbolPath: '',
        theme: '',
        options: [
            { text: 'Hamburger', value: '/svg/hamburger.svg' },
            { text: 'Beer', value: '/svg/pint.svg' },
            { text: 'Resturant', value: '/svg/restaurant.svg' },
            { text: 'Taxi', value: '/svg/taxi.svg' },
            { text: 'Movie', value: '/svg/clapperboard.svg' },
            { text: 'Cocktail', value: '/svg/cocktail.svg' },
            { text: 'Coffee', value: '/svg/coffee-cup.svg' },
            { text: 'Steak', value: '/svg/food.svg' },
            { text: 'Drink', value: '/svg/glass.svg' },
            { text: 'Taco', value: '/svg/taco.svg' },
            { text: 'Tickets', value: '/svg/tickets.svg' },
            { text: 'Train', value: '/svg/train.svg' },
            { text: 'Travel', value: '/svg/luggage.svg' }
        ]
    },
    methods: {
        fetchData() {
            this.$http.get('/api/activities/get').then(response => {
                this.$set(this, 'activities', response.body.activities);
                this.$set(this, 'currUser', response.body.currUser);
            });
        },
        updateTheme: function () {
            this.$http.get('/api/user/get').then(response => {
                var theme = response.body.profile.theme;
                switch (theme) {
                    case 1:
                        this.theme = 'theme-light';
                    case 2:
                        this.theme = 'theme-dark';
                    case 3:
                        this.theme = 'theme-color';
                    default:
                        this.theme = 'theme-light';
                }
            });
        },
        updatePost: function (data) {
            data._csrf = $('meta[name="csrf-token"]').attr('content');
            this.$http.post('/api/activities/changeturn', data)
                .then(function () {
                    this.fetchData();
                }
                    .bind(this),
                function () { });

        },
        findUser: function () {
            this.errorMessage = '';
            var data = {};
            data._csrf = $('meta[name="csrf-token"]').attr('content');
            data.email = this.searchEmail;
            this.$http.post('/api/user/find', data).then(response => {
                var userSearchStatus = JSON.stringify(response.body);
                if (userSearchStatus == 'true') {
                    this.emailSearchStatus = 'form-control-success';
                    this.emailSearchStatusGroup = 'has-success';
                    this.showDescForm = 'm-fadeIn';
                } else {
                    this.emailSearchStatus = 'form-control-danger';
                    this.emailSearchStatusGroup = 'has-danger';
                    this.showDescForm = 'm-fadeOut';
                    this.errorMessage = "Couldn't find that Moocher, want to send an invite?";
                }
            }, response => {
                this.emailSearchStatus = 'form-control-danger';
                this.showDescForm = 'm-fadeOut';
                this.emailSearchStatusGroup = 'has-danger';
                this.errorMessage = response.body.replace('"', '');
            }).bind(this),
                function () { };
        },
        newActivity: function () {
            this.$http.post('/api/activities/create', {
                email: this.searchEmail,
                desc: this.actDesc,
                symbolPath: this.symbolPath,
                _csrf: $('meta[name="csrf-token"]').attr('content')
            })
                .then(function (response) {
                    this.actDesc = '';
                    this.searchEmail = '';
                    this.showDescForm = 'm-fadeOut';
                    this.fetchData();
                }.bind(this),
                function () { });
        },
        getProfileImage: function (activity) {
            if (activity.turn.profile !== "undefined")
                return activity.turn.profile.picture;
            else
                // Twitter only, if FB then other implementation is needed.
                return "";
        },
        getOtherUsers: function (activity) {
            var currUser = this.currUser;
            var otherUser = activity.users.filter(function (user) {
                return user._id != currUser;
            });
            return otherUser[0].profile.name;
        }
    }
})<|endoftext|>


<commit_before>import Base from '../base'

const Recipes = class extends Base {

  constructor(config = {debug: false}) {
    super(config)
  }

  /**
   * Prefer to return the taskFn instead of a string, but return the string if that's all that is given to us.
   *
   * @param recipe
   * @returns {*}
   */
  toTask(recipe) {
    let taskName = null
    if (typeof recipe === "string") {
      // any given task name should be returned as-is
      taskName = recipe
      this.debug(`toTask(): ${taskName}`)
    }
    else {
      if (typeof recipe === "function") {
        // any given fn should be return as-is i.e. series/parallel
        taskName = recipe
      }
      else {
        // any recipe should be converted to string task name
        taskName = recipe.taskFn
      }
      this.debug(`toTask(): ${taskName.name || taskName.displayName}`)
    }
    return taskName
  }

  /**
   * Yield the nearest set of task names - return nested series/parallel fn - do not follow them and flatten them (they will do that themselves if using the helper methods)
   *
   * @param recipes
   * @returns {Array}
   */
  toTasks(recipes, tasks = []) {
    this.debugDump('toTasks: recipes', recipes)

    for (let recipe of recipes) {
      //this.debugDump(`recipe taskName[${recipe.taskName? recipe.taskName() : ''}] isArray[${Array.isArray(recipe)}]`, recipe)
      if (Array.isArray(recipe)) {
        tasks.push(this.toTasks(recipe, []))
      }
      else {
        let taskName = this.toTask(recipe)
        tasks.push(taskName)
      }
    }

    return tasks
  }
}

export default Recipes
<commit_msg>renaming var, move taskFn resolution up<commit_after>import Base from '../base'

const Recipes = class extends Base {

  constructor(config = {debug: false}) {
    super(config)
  }

  /**
   * Prefer to return the taskFn instead of a string, but return the string if that's all that is given to us.
   *
   * @param recipeOrAggregateOrString
   * @returns {*}
   */
  toTask(recipeOrAggregateOrString) {
    let task = null
    if (typeof recipeOrAggregateOrString === "string") {
      // any given task name should be returned as-is
      task = recipeOrAggregateOrString
      this.debug(`toTask(): ${task}`)
    }
    else {
      if (recipeOrAggregateOrString.taskFn) {
        // recipes and aggregates expose a taskFn
        task = recipeOrAggregateOrString.taskFn
      }
      else if (typeof recipeOrAggregateOrString === "function") {
        // any given fn should be return as-is i.e. series/parallel
        task = recipeOrAggregateOrString
      }

      this.debug(`toTask(): ${task.name || task.displayName}`)
    }
    return task
  }

  /**
   * Yield the nearest set of task names - return nested series/parallel fn - do not follow them and flatten them (they will do that themselves if using the helper methods)
   *
   * @param recipes
   * @returns {Array}
   */
  toTasks(recipes, tasks = []) {
    this.debugDump('toTasks: recipes', recipes)

    for (let recipe of recipes) {
      //this.debugDump(`recipe taskName[${recipe.taskName? recipe.taskName() : ''}] isArray[${Array.isArray(recipe)}]`, recipe)
      if (Array.isArray(recipe)) {
        tasks.push(this.toTasks(recipe, []))
      }
      else {
        let taskName = this.toTask(recipe)
        tasks.push(taskName)
      }
    }

    return tasks
  }
}

export default Recipes
<|endoftext|>


<commit_before>import { Resource } from 'kolibri.lib.apiResource';
import Store from 'kolibri.coreVue.vuex.store';

export default new Resource({
  name: 'contentnode',
  useContentCacheKey: true,
  fetchDescendants(ids, getParams = {}) {
    return this.getListEndpoint('descendants', { ids, ...getParams });
  },
  fetchDescendantsAssessments(ids) {
    return this.getListEndpoint('descendants_assessments', { ids });
  },
  fetchCopies(content_id) {
    return this.fetchDetailCollection('copies', content_id);
  },
  fetchCopiesCount(getParams = {}) {
    return this.fetchListCollection('copies_count', getParams);
  },
  fetchNextContent(id) {
    return this.fetchDetailModel('next_content', id);
  },
  fetchNodeAssessments(ids) {
    return this.getListEndpoint('node_assessments', { ids });
  },
  fetchRecommendationsFor(id, getParams) {
    return this.fetchDetailCollection('recommendations_for', id, getParams);
  },
  fetchResume(getParams) {
    return this.fetchDetailCollection('resume', Store.getters.currentUserId, getParams);
  },
  fetchPopular(getParams) {
    return this.fetchListCollection('popular', getParams);
  },
  fetchNextSteps(getParams) {
    return this.fetchDetailCollection('next_steps', Store.getters.currentUserId, getParams);
  },
});
<commit_msg>Add support for tree endpoint to contentnode resource. Simplify caching.<commit_after>import isPlainObject from 'lodash/isPlainObject';
import { Resource } from 'kolibri.lib.apiResource';
import Store from 'kolibri.coreVue.vuex.store';
import urls from 'kolibri.urls';
import cloneDeep from '../cloneDeep';

export default new Resource({
  name: 'contentnode',
  useContentCacheKey: true,
  fetchDescendants(ids, getParams = {}) {
    return this.getListEndpoint('descendants', { ids, ...getParams });
  },
  fetchDescendantsAssessments(ids) {
    return this.getListEndpoint('descendants_assessments', { ids });
  },
  fetchCopies(content_id) {
    return this.fetchDetailCollection('copies', content_id);
  },
  fetchCopiesCount(getParams = {}) {
    return this.fetchListCollection('copies_count', getParams);
  },
  fetchNextContent(id) {
    return this.fetchDetailModel('next_content', id);
  },
  fetchNodeAssessments(ids) {
    return this.getListEndpoint('node_assessments', { ids });
  },
  fetchRecommendationsFor(id, getParams) {
    return this.fetchDetailCollection('recommendations_for', id, getParams);
  },
  fetchResume(getParams) {
    return this.fetchDetailCollection('resume', Store.getters.currentUserId, getParams);
  },
  fetchPopular(getParams) {
    return this.fetchListCollection('popular', getParams);
  },
  fetchNextSteps(getParams) {
    return this.fetchDetailCollection('next_steps', Store.getters.currentUserId, getParams);
  },
  cache: {},
  fetchModel({ id }) {
    if (this.cache[id]) {
      return Promise.resolve(this.cache[id]);
    }
    return this.client({ url: this.modelUrl(id) }).then(response => {
      this.cacheData(response.data);
      return response.data;
    });
  },
  cacheData(data) {
    if (Array.isArray(data)) {
      for (let model of data) {
        this.cacheData(model);
      }
    } else if (isPlainObject(data)) {
      if (data[this.idKey]) {
        this.cache[data[this.idKey]] = Object.assign(
          this.cache[data[this.idKey]] || {},
          cloneDeep(data)
        );
        if (data.children) {
          this.cacheData(data.children);
        }
      } else if (data.results) {
        for (let model of data.results) {
          this.cacheData(model);
        }
      }
    }
  },
  fetchCollection(params) {
    return this.client({ url: this.collectionUrl(), params }).then(response => {
      this.cacheData(response.data);
      return response.data;
    });
  },
  fetchTree(id, params) {
    const url = urls['kolibri:core:contentnode_tree_detail'](id);
    return this.client({ url, params }).then(response => {
      this.cacheData(response.data);
      return response.data;
    });
  },
  fetchMoreTree({ id, params }) {
    return this.fetchTree(id, params);
  },
});
<|endoftext|>


<commit_before>module.exports = {
<<<<<<< HEAD
    name: 'AntD Admin',
    prefix: 'antdAdmin',
    footerText: 'Ant Design Admin  © 2017 zuiidea',
    logo: 'https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png',
    iconFontUrl: '//at.alicdn.com/t/font_c4y7asse3q1cq5mi.js',
    baseURL: 'http://139.199.27.165:8081/',
    YQL: ['http://www.zuimeitianqi.com'],
    CORS: ['http://localhost:7001', 'http://192.168.1.110:8000'],
    openPages: ['/login'],
    apiPrefix: '',
    api: {
        userLogin: '/user/login',
        userLogout: '/user/logout',
        userisLogin: '/user/isLogin',
        users: '/users',
        user: '/user/:id',
        dashboard: '/user/getManageArea',
    },
=======
	name: 'AntD Admin',
	prefix: 'antdAdmin',
	footerText: 'Ant Design Admin 版权所有 © 2016 由 zuiidea 支持',
	logo: 'https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png',
	iconFontUrl: '//at.alicdn.com/t/font_c4y7asse3q1cq5mi.js',
	baseURL: 'http://139.199.27.165:8081/',
	YQL: ['http://www.zuimeitianqi.com'],
	CORS: ['http://localhost:7001'],
	openPages: ['/login'],
	apiPrefix: '',
	api: {
		userLogin: '/user/login',
		userLogout: '/user/logout',
		userInfo: '/user/isLogin',
		users: '/user/getUserList',
		dashboard: '/user/getManageArea'
	}
>>>>>>> 522f3fe3774c02dd203c0af36c8ac010f6de5ab8
}
<commit_msg>'修改冲突'<commit_after>module.exports = {
    name: 'AntD Admin',
    prefix: 'antdAdmin',
    footerText: 'Ant Design Admin  © 2017 zuiidea',
    logo: 'https://t.alipayobjects.com/images/T1QUBfXo4fXXXXXXXX.png',
    iconFontUrl: '//at.alicdn.com/t/font_c4y7asse3q1cq5mi.js',
    baseURL: 'http://139.199.27.165:8081/',
    YQL: ['http://www.zuimeitianqi.com'],
    CORS: ['http://localhost:7001', 'http://192.168.1.110:8000'],
    openPages: ['/login'],
    apiPrefix: '',
    api: {
        userLogin: '/user/login',
        userLogout: '/user/logout',
        userisLogin: '/user/isLogin',
        users: '/users',
        user: '/user/:id',
        dashboard: '/user/getManageArea',
    },
}
<|endoftext|>


<commit_before>function getsnippet(code) {
  var js = "(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){\r\n  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n  })(window,document,\'script\',\'\/\/www.google-analytics.com\/analytics.js\',\'ga\');\r\n\r\n  ga(\'create\', \'" + code + "\', \'auto\');\r\n  ga(\'send\', \'pageview\');";
  var snippet = "<script>" + '\n' + js + '\n' + "</script>";

  return snippet;
}

function addsnippet(code) {
  var js = "(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){\r\n  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n  })(window,document,\'script\',\'\/\/www.google-analytics.com\/analytics.js\',\'ga\');\r\n\r\n  ga(\'create\', \'" + code + "\', \'auto\');\r\n  ga(\'send\', \'pageview\');";
  var snippet = '\n' + js + '\n';

  var script = document.createElement('script');
  script.innerHTML = snippet;

  document.getElementsByTagName('head')[0].appendChild(script);
}
<commit_msg>quickie<commit_after>function getsnippet(code) {
  var js = "(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){\r\n  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n  })(window,document,\'script\',\'\/\/www.google-analytics.com\/analytics.js\',\'ga\');\r\n\r\n  ga(\'create\', \'" + code + "\', \'auto\');\r\n  ga(\'send\', \'pageview\');";
  var snippet = "<script>" + '\n' + js + '\n' + "</script>";

  return snippet;
}
<|endoftext|>


<commit_before>import VectorLayer from 'ol/layer/Vector';
import 'utils.module';

export default {
    template: require('./partials/shape-toolbar.html'),
    controller: ['$scope', 'hs.map.service', 'hs.draw.service',
        'hs.utils.layerUtilsService', 'hs.query.vectorService', '$timeout',
        function ($scope, OlMap, drawService, layerUtilsService, queryVectorService, $timeout) {
            var map;
            angular.extend($scope, {
                service: drawService,
                selectedLayer: null,
                drawableLayers() {
                    if (map) {
                        const tmp = map.getLayers().getArray()
                            .filter($scope.isLayerDrawable)
                        if (tmp.length > 0 && $scope.selectedLayer == null) {
                            $scope.selectedLayer = tmp[0]
                        }
                        return tmp;
                    }
                },
                isLayerInManager: layerUtilsService.isLayerInManager,
                hasLayerTitle: layerUtilsService.hasLayerTitle,
                isLayerEditable: layerUtilsService.isLayerEditable,
                isLayerDrawable: layerUtilsService.isLayerDrawable,
                setType(what) {
                    drawService.type = what;
                    drawService.source = $scope.selectedLayer.getSource();
                    $scope.activateDrawing();
                },
                activateDrawing() {
                    drawService.activateDrawing(
                        $scope.onDrawStart,//Will add later
                        $scope.onDrawEnd,
                        $scope.onFeatureSelected, //Will add later
                        $scope.onFeatureDeselected, //Will add later
                        true //Activate drawing immediately
                    );
                },
                selectLayer(layer) {
                    $scope.selectedLayer = layer;
                    $scope.layersExpanded = false;
                },
                selectedLayerString() {
                    if ($scope.selectedLayer) {
                        return $scope.selectedLayer.get('title') || $scope.selectedLayer.get('name')
                    } else return 'Select layer'
                },
                toggleDrawToolbar() {
                    $scope.drawToolabrExpanded = !$scope.drawToolabrExpanded;
                    if (!$scope.drawToolabrExpanded) {
                        drawService.stopDrawing()
                    }
                },
                onDrawEnd(e) {
                    if (angular.isUndefined($scope.selectedLayer.get('editor')))
                        return;
                    const editorConfig = $scope.selectedLayer.get('editor');
                    if (editorConfig.defaultAttributes) {
                        angular.forEach(editorConfig.defaultAttributes,
                            (value, key) => {
                                e.feature.set(key, value);
                            })
                    }
                    /*Timeout is necessary because features are not imediately
                    * added to the layer and layer can't be retrieved from the
                    * feature, so they don't appear in Info panel */
                    $timeout(() => {
                        queryVectorService.selector.getFeatures().push(e.feature);
                        queryVectorService.createFeatureAttributeList();
                    })

                }
            });

            /**
             * @memberof hs.draw.shapeToolbar
             * @function init
             * @description Init function
             */
            function init() {
                map = OlMap.map;
            }

            OlMap.loaded().then(init);

            $scope.$emit('scope_loaded', "DrawToolbar");
        }]
}<commit_msg>Drawing on clustered layers not working fixes #435<commit_after>import VectorLayer from 'ol/layer/Vector';
import 'utils.module';

export default {
    template: require('./partials/shape-toolbar.html'),
    controller: ['$scope', 'hs.map.service', 'hs.draw.service',
        'hs.utils.layerUtilsService', 'hs.query.vectorService', '$timeout',
        function ($scope, OlMap, drawService, layerUtilsService, queryVectorService, $timeout) {
            var map;
            angular.extend($scope, {
                service: drawService,
                selectedLayer: null,
                drawableLayers() {
                    if (map) {
                        const tmp = map.getLayers().getArray()
                            .filter($scope.isLayerDrawable)
                        if (tmp.length > 0 && $scope.selectedLayer == null) {
                            $scope.selectedLayer = tmp[0]
                        }
                        return tmp;
                    }
                },
                isLayerInManager: layerUtilsService.isLayerInManager,
                hasLayerTitle: layerUtilsService.hasLayerTitle,
                isLayerEditable: layerUtilsService.isLayerEditable,
                isLayerDrawable: layerUtilsService.isLayerDrawable,
                setType(what) {
                    drawService.type = what;
                    drawService.source = angular.isDefined($scope.selectedLayer.getSource().getSource) ?
                        $scope.selectedLayer.getSource().getSource() : //Is it clustered vector layer?
                        drawService.source = $scope.selectedLayer.getSource();
                    $scope.activateDrawing();
                },
                activateDrawing() {
                    drawService.activateDrawing(
                        $scope.onDrawStart,//Will add later
                        $scope.onDrawEnd,
                        $scope.onFeatureSelected, //Will add later
                        $scope.onFeatureDeselected, //Will add later
                        true //Activate drawing immediately
                    );
                },
                selectLayer(layer) {
                    $scope.selectedLayer = layer;
                    $scope.layersExpanded = false;
                },
                selectedLayerString() {
                    if ($scope.selectedLayer) {
                        return $scope.selectedLayer.get('title') || $scope.selectedLayer.get('name')
                    } else return 'Select layer'
                },
                toggleDrawToolbar() {
                    $scope.drawToolabrExpanded = !$scope.drawToolabrExpanded;
                    if (!$scope.drawToolabrExpanded) {
                        drawService.stopDrawing()
                    }
                },
                onDrawEnd(e) {
                    if (angular.isUndefined($scope.selectedLayer.get('editor')))
                        return;
                    const editorConfig = $scope.selectedLayer.get('editor');
                    if (editorConfig.defaultAttributes) {
                        angular.forEach(editorConfig.defaultAttributes,
                            (value, key) => {
                                e.feature.set(key, value);
                            })
                    }
                    /*Timeout is necessary because features are not imediately
                    * added to the layer and layer can't be retrieved from the
                    * feature, so they don't appear in Info panel */
                    $timeout(() => {
                        queryVectorService.selector.getFeatures().push(e.feature);
                        queryVectorService.createFeatureAttributeList();
                    })

                }
            });

            /**
             * @memberof hs.draw.shapeToolbar
             * @function init
             * @description Init function
             */
            function init() {
                map = OlMap.map;
            }

            OlMap.loaded().then(init);

            $scope.$emit('scope_loaded', "DrawToolbar");
        }]
}<|endoftext|>


<commit_before>import * as transforms from '../transforms/index';
import {isObject, isString} from 'vega-util';
import {parse, context} from 'vega-runtime';
import {rgb, lab, hcl, hsl} from 'd3-color';

function scale(name, ctx) {
  var s = isString(name) ? ctx.scales[name]
    : isObject(name) && name.signal ? ctx.signals[name.signal]
    : undefined;
  return s && s.value;
}

function functions(fn, ctx) {
  fn.rgb = rgb;
  fn.lab = lab;
  fn.hcl = hcl;
  fn.hsl = hsl;

  fn.pinchDistance = function() {
    return 'Math.sqrt('
      + 'pow(event.touches[0].clientX - event.touches[1].clientX, 2) + '
      + 'pow(event.touches[0].clientY - event.touches[1].clientY, 2)'
      + ')';
  };

  fn.pinchAngle = function() {
    return 'Math.atan2('
      + 'event.touches[1].clientY - event.touches[0].clientY,'
      + 'event.touches[1].clientX - event.touches[0].clientX'
      + ')';
  };

  fn.span = function(array) {
    return array[array.length-1] - array[0];
  };

  fn.scale = function(name, value) {
    var s = scale(name, ctx);
    return s ? s(value) : undefined;
  };

  fn.scaleInvert = function(name, value) {
    var s = scale(name, ctx);
    // TODO: handle varied scale inversion methods
    return s ? s.invert(value) : undefined;
  };

  fn.scaleCopy = function(name) {
    var s = scale(name, ctx);
    return s ? s.copy() : undefined;
  };

  fn.indata = function(name, field, value) {
    var index = ctx.data['index:' + field];
    return index ? !!index.value.get(value) : undefined;
  };

  fn.encode = function(item, name, retval) {
    if (item) {
      var df = ctx.dataflow,
          target = item.mark.source;
      df.pulse(target, df.changeset().encode(item, name));
    }
    return retval !== undefined ? retval : item;
  };

  return ctx;
}

export default function(view, spec) {
  var fn = {},
      ctx = context(view, transforms, fn);
  return parse(spec, functions(fn, ctx));
}
<commit_msg>Add range expression function.<commit_after>import * as transforms from '../transforms/index';
import {isObject, isString} from 'vega-util';
import {parse, context} from 'vega-runtime';
import {rgb, lab, hcl, hsl} from 'd3-color';

function scale(name, ctx) {
  var s = isString(name) ? ctx.scales[name]
    : isObject(name) && name.signal ? ctx.signals[name.signal]
    : undefined;
  return s && s.value;
}

function functions(fn, ctx) {
  fn.rgb = rgb;
  fn.lab = lab;
  fn.hcl = hcl;
  fn.hsl = hsl;

  fn.pinchDistance = function() {
    return 'Math.sqrt('
      + 'pow(event.touches[0].clientX - event.touches[1].clientX, 2) + '
      + 'pow(event.touches[0].clientY - event.touches[1].clientY, 2)'
      + ')';
  };

  fn.pinchAngle = function() {
    return 'Math.atan2('
      + 'event.touches[1].clientY - event.touches[0].clientY,'
      + 'event.touches[1].clientX - event.touches[0].clientX'
      + ')';
  };

  fn.span = function(array) {
    return array[array.length-1] - array[0];
  };

  fn.range = function(name) {
    var s = scale(name, ctx);
    return s && s.range() ? s.range() : [0, 0];
  };

  fn.scale = function(name, value) {
    var s = scale(name, ctx);
    return s ? s(value) : undefined;
  };

  fn.scaleInvert = function(name, value) {
    var s = scale(name, ctx);
    // TODO: handle varied scale inversion methods
    return s ? s.invert(value) : undefined;
  };

  fn.scaleCopy = function(name) {
    var s = scale(name, ctx);
    return s ? s.copy() : undefined;
  };

  fn.indata = function(name, field, value) {
    var index = ctx.data['index:' + field];
    return index ? !!index.value.get(value) : undefined;
  };

  fn.encode = function(item, name, retval) {
    if (item) {
      var df = ctx.dataflow,
          target = item.mark.source;
      df.pulse(target, df.changeset().encode(item, name));
    }
    return retval !== undefined ? retval : item;
  };

  return ctx;
}

export default function(view, spec) {
  var fn = {},
      ctx = context(view, transforms, fn);
  return parse(spec, functions(fn, ctx));
}
<|endoftext|>