<commit_before>$(function() {
  var settings = {
    soundPack: [],
    fadeInVal: 0,
    fadeOutVal: null,
    loopStatus: null,
    currentCol: 1,
    colInterval: 120,
    measures: 1,
    beats: 4,
    subdivision: 4,
    defaulCols: 16,
    totalCol: 16,
    selectedBoxes: {}
  };

  //Initial setup
  createSoundPack();
  buildGrid();
  displaySettings();

  //Create settings knobs + knob event handlers
  $('.tempo-knob').knob({
    'min': 1,
    'max': 240,
    'width': 80,
    'angleOffset': -125,
    'angleArc': 250,
    'release': function (v) { setTempo('colInterval', v) }
  });

//Event Handlers
  //Toggles selected class
  $('body').on('click', '.box', boxSelected);

  //Event listeners for toggling Start/Stop
    //Click button
   $(".toggle").click(function() {
     toggleClicked();
   });

  //Press spacebar
  $(window).keypress(function(e) {
    if (e.keyCode == 0 || e.keyCode == 32) {
      if ("activeElement" in document) {
      document.activeElement.blur();
      }
      toggleClicked();
    }
  });

  //Reset button
  $(".reset").click(function() {
    $(".box").removeClass("selected");
    for (var i in settings.selectedBoxes) {
      settings.selectedBoxes[i] = [];
    }
  });

  //Measures/Beats/Subdivision settings
  $('.settings-button').click(function() {
    var settingsOption = $(this).attr('data-option');

    if ($(this).hasClass('settings-beats')) {
      settingsChange('beats', settingsOption);
    }
    else if ($(this).hasClass('settings-measures')) {
      settingsChange('measures', settingsOption);
    }
    else if ($(this).hasClass('settings-subdivision')) {
      settingsChange('subdivision', settingsOption);
    }
    buildGrid();
  });

//Settings Functions
  //When Box is Selected
  function boxSelected() {
    var col = $(this).attr('data-col');
    var row = $(this).attr('data-row');
    var array = settings.selectedBoxes["col"+col];
    if (array.indexOf(row) !== -1) {
      array.splice(array.indexOf(row), 1);
    } else {
      array.push(row);
    }
    $(this).toggleClass("selected");
  }

  //Start button <-> Stop Button
  function toggleClicked() {
    if ($('.toggle').html() == 'Start') {
      $('.toggle').html('Stop');
      settings.loopStatus = true;
      gridLoop();
    }
    else if ($('.toggle').html() == 'Stop') {
      $('.toggle').html('Start');
      settings.loopStatus = false;
    }
  }

  //Set tempo
  function setTempo(dataName, dataVal) {
    var milliseconds = Math.round((((60/dataVal)*1000)*100000)/100000)/settings.subdivision;
        //console.log("Sixteenth is precisely "+sixteenth+" milliseconds");
        settings[dataName] = milliseconds;
  }

  //Set Beats/Measures/Subdivision
  function settingsChange(settingsType, settingsVal) {
    if (settingsType == 'beats') {
      if (settingsVal == 'plus') {
        if (settings.beats < 4) {
          settings.beats++;
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.beats > 3) {
          settings.beats--;
        }
      }
    }
    if (settingsType == 'measures') {
      if (settingsVal == 'plus') {
        if (settings.measures < 4) {
          settings.measures++;
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.measures > 1) {
          settings.measures--;
        }
      }
    }
    else if (settingsType == 'subdivision') {
      if (settingsVal == 'plus') {
        if (settings.subdivision < 5) {
          settings.subdivision++;
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.subdivision > 3) {
          settings.subdivision--;
        }
      }
    }
    displaySettings();
  }

  //Display settings values
  function displaySettings() {
    if (settings.subdivision == 3) {
      $('.display-subdivision').html('Triplets');
    }
    else if (settings.subdivision == 4) {
      $('.display-subdivision').html('Sixteenths');
    }
    else if (settings.subdivision == 5) {
      $('.display-subdivision').html('Quintuplets');
    }
    $('.display-beats').html(settings.beats);
    $('.display-measures').html(settings.measures);
  }

//Tonal Sequencer Functions
  //Dynamically create sound file references
  function createSoundPack() {
    for(var soundIndex = 1; soundIndex<=16; soundIndex++) {
      settings.soundPack[soundIndex-1] = new Howl({
        urls: ['media/'+soundIndex+'.ogg', 'media/'+soundIndex+'.mp3'],
        fadeIn: settings.fadeInVal,
        fadeOut: settings.fadeOutVal,
      });
    }
  }

  //Dynamically build HTML grid
  function buildGrid() {
    var container = $(".grid");
    $(".grid").html("");
    settings.totalCol = settings.measures * settings.beats * settings.subdivision;
    //Loop through each row.
    for (var colIndex = 1; colIndex <= settings.totalCol; colIndex++) {
      //Create the skeleton for the row.
      var col = $("<div>", {
          "class": "col col-" + colIndex,
          "id": "col-"+colIndex
      });
      //Loop through each column
      for (var rowIndex = 1; rowIndex <= 16; rowIndex++) {
        //Create skeleton for the column.
        var row = $("<div>", {
            "class": "box row-"+rowIndex,
            "data-col": colIndex,
            "data-row": rowIndex,
        });
        //Append to the row div.
        col.append(row);
      }
      //Finally append this row to the container.
      container.append(col);

      if ((settings.selectedBoxes["col"+colIndex] != undefined) || (settings.selectedBoxes["col"+colIndex] != null)){
        console.log(settings.selectedBoxes["col"+colIndex]);
        populateColNotes(colIndex, settings.selectedBoxes["col"+colIndex]);
      } else {
        settings.selectedBoxes["col"+colIndex] = [];
      }
    }
    settings.currentCol = 1;
    findDownbeat();
    console.log(settings.selectedBoxes);
  }

  //Marks downbeats
  function findDownbeat() {
    var markedColumns = $('.grid').find(".col");
    var measureMarkers = settings.beats * settings.subdivision;

    $(markedColumns).children().removeClass('downbeat downbeat-measure');
    for (var i = 0; i < markedColumns.length; i++ ) {
      if (i % settings.subdivision === 0) {
        $(markedColumns[i]).children().addClass('downbeat');
        //console.log(i + "downbeats");
      }
    }
    for (var j = 0; j < markedColumns.length; j++ ) {
      if (j % measureMarkers === 0) {
        //console.log(j + "measure beats");
        $(markedColumns[j]).children().addClass('downbeat-measure');
      }
    }
  }

  //Populates grid with selected boxes
  function populateColNotes(col, array) {
    for (var i = 0; i < array.length; i++) {
      console.log("i is: "+i);
      console.log("Col is: "+col);
      console.log("Row is: "+array[i]);
      var selector = $(".col-"+col).find(".row-"+array[i]).addClass("selected");
      console.log(selector);
    }
  }

  //Loop through every column
  function gridLoop() {
    if (settings.loopStatus) {
      settings.totalCol = settings.measures * settings.beats * settings.subdivision;
      setTimeout( function() {
        $(".col-" + settings.currentCol).children().toggleClass("active");
        if (settings.currentCol === 1) {
          $(".col-" + settings.totalCol).children().removeClass("active");
        }
        else {
          $(".col-"+(settings.currentCol - 1)).children().removeClass("active");
        }
        playSound();
        settings.currentCol++;
        if (settings.currentCol <= settings.totalCol){
          gridLoop();
        }
        else if (settings.currentCol == settings.totalCol + 1) {
          settings.currentCol = 1;
          gridLoop();
        }
       }, settings.colInterval);
    }
    else {
      settings.currentCol = 1;
      $(".box").removeClass("active");
      return;
    }
  }

  //Play the notes that are selected
  function playSound() {
    var notesToPlay = settings.selectedBoxes["col" + settings.currentCol];
    for (var i = 0; i < notesToPlay.length; i++) {
      var soundToPlay = eval("settings.soundPack[" + (notesToPlay[i]-1) + "]");
      soundToPlay.play();
    }
    notesToPlay = [];
  }

});<commit_msg>Refined settings selection<commit_after>$(function() {
  var settings = {
    soundPack: [],
    fadeInVal: 0,
    fadeOutVal: null,
    loopStatus: null,
    currentCol: 1,
    colInterval: 120,
    measures: 1,
    beats: 4,
    subdivision: 4,
    defaulCols: 16,
    totalCol: 16,
    selectedBoxes: {}
  };

  //Initial setup
  createSoundPack();
  buildGrid();
  displaySettings();

  //Create settings knobs + knob event handlers
  $('.tempo-knob').knob({
    'min': 1,
    'max': 240,
    'width': 80,
    'angleOffset': -125,
    'angleArc': 250,
    'release': function (v) { setTempo('colInterval', v) }
  });

//Event Handlers
  //Toggles selected class
  $('body').on('click', '.box', boxSelected);

  //Event listeners for toggling Start/Stop
    //Click button
   $(".toggle").click(function() {
     toggleClicked();
   });

  //Press spacebar
  $(window).keypress(function(e) {
    if (e.keyCode == 0 || e.keyCode == 32) {
      if ("activeElement" in document) {
      document.activeElement.blur();
      }
      toggleClicked();
    }
  });

  //Reset button
  $(".reset").click(function() {
    $(".box").removeClass("selected");
    for (var i in settings.selectedBoxes) {
      settings.selectedBoxes[i] = [];
    }
  });

  //Measures/Beats/Subdivision settings
  $('.settings-button').click(function() {
    var settingsOption = $(this).attr('data-option');

    if ($(this).hasClass('settings-beats')) {
      settingsChange('beats', settingsOption);
    }
    else if ($(this).hasClass('settings-measures')) {
      settingsChange('measures', settingsOption);
    }
    else if ($(this).hasClass('settings-subdivision')) {
      settingsChange('subdivision', settingsOption);
    }
  });

//Settings Functions
  //When Box is Selected
  function boxSelected() {
    var col = $(this).attr('data-col');
    var row = $(this).attr('data-row');
    var array = settings.selectedBoxes["col"+col];
    if (array.indexOf(row) !== -1) {
      array.splice(array.indexOf(row), 1);
    } else {
      array.push(row);
    }
    $(this).toggleClass("selected");
  }

  //Start button <-> Stop Button
  function toggleClicked() {
    if ($('.toggle').html() == 'Start') {
      $('.toggle').html('Stop');
      settings.loopStatus = true;
      gridLoop();
    }
    else if ($('.toggle').html() == 'Stop') {
      $('.toggle').html('Start');
      settings.loopStatus = false;
    }
  }

  //Set tempo
  function setTempo(dataName, dataVal) {
    var milliseconds = Math.round((((60/dataVal)*1000)*100000)/100000)/settings.subdivision;
        //console.log("Sixteenth is precisely "+sixteenth+" milliseconds");
        settings[dataName] = milliseconds;
  }

  //Set Beats/Measures/Subdivision
  function settingsChange(settingsType, settingsVal) {
    if (settingsType == 'beats') {
      if (settingsVal == 'plus') {
        if (settings.beats < 4) {
          settings.beats++;
          buildGrid();
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.beats > 3) {
          settings.beats--;
          buildGrid();
        }
      }
    }
    if (settingsType == 'measures') {
      if (settingsVal == 'plus') {
        if (settings.measures < 4) {
          settings.measures++;
          buildGrid();
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.measures > 1) {
          settings.measures--;
          buildGrid();
        }
      }
    }
    else if (settingsType == 'subdivision') {
      if (settingsVal == 'plus') {
        if (settings.subdivision < 5) {
          settings.subdivision++;
          buildGrid();
        }
      }
      else if (settingsVal == 'minus') {
        if (settings.subdivision > 3) {
          settings.subdivision--;
          buildGrid();
        }
      }
    }
    displaySettings();
  }

  //Display settings values
  function displaySettings() {
    if (settings.subdivision == 3) {
      $('.display-subdivision').html('Triplets');
    }
    else if (settings.subdivision == 4) {
      $('.display-subdivision').html('Sixteenths');
    }
    else if (settings.subdivision == 5) {
      $('.display-subdivision').html('Quintuplets');
    }
    $('.display-beats').html(settings.beats);
    $('.display-measures').html(settings.measures);
  }

//Tonal Sequencer Functions
  //Dynamically create sound file references
  function createSoundPack() {
    for(var soundIndex = 1; soundIndex<=16; soundIndex++) {
      settings.soundPack[soundIndex-1] = new Howl({
        urls: ['media/'+soundIndex+'.ogg', 'media/'+soundIndex+'.mp3'],
        fadeIn: settings.fadeInVal,
        fadeOut: settings.fadeOutVal,
      });
    }
  }

  //Dynamically build HTML grid
  function buildGrid() {
    var container = $(".grid");
    $(".grid").html("");
    settings.totalCol = settings.measures * settings.beats * settings.subdivision;
    //Loop through each row.
    for (var colIndex = 1; colIndex <= settings.totalCol; colIndex++) {
      //Create the skeleton for the row.
      var col = $("<div>", {
          "class": "col col-" + colIndex,
          "id": "col-"+colIndex
      });
      //Loop through each column
      for (var rowIndex = 1; rowIndex <= 16; rowIndex++) {
        //Create skeleton for the column.
        var row = $("<div>", {
            "class": "box row-"+rowIndex,
            "data-col": colIndex,
            "data-row": rowIndex,
        });
        //Append to the row div.
        col.append(row);
      }
      //Finally append this row to the container.
      container.append(col);

      if ((settings.selectedBoxes["col"+colIndex] != undefined) || (settings.selectedBoxes["col"+colIndex] != null)){
        console.log(settings.selectedBoxes["col"+colIndex]);
        populateColNotes(colIndex, settings.selectedBoxes["col"+colIndex]);
      } else {
        settings.selectedBoxes["col"+colIndex] = [];
      }
    }
    settings.currentCol = 1;
    findDownbeat();
    console.log(settings.selectedBoxes);
  }

  //Marks downbeats
  function findDownbeat() {
    var markedColumns = $('.grid').find(".col");
    var measureMarkers = settings.beats * settings.subdivision;

    $(markedColumns).children().removeClass('downbeat downbeat-measure');
    for (var i = 0; i < markedColumns.length; i++ ) {
      if (i % settings.subdivision === 0) {
        $(markedColumns[i]).children().addClass('downbeat');
        //console.log(i + "downbeats");
      }
    }
    for (var j = 0; j < markedColumns.length; j++ ) {
      if (j % measureMarkers === 0) {
        //console.log(j + "measure beats");
        $(markedColumns[j]).children().addClass('downbeat-measure');
      }
    }
  }

  //Populates grid with selected boxes
  function populateColNotes(col, array) {
    for (var i = 0; i < array.length; i++) {
      console.log("i is: "+i);
      console.log("Col is: "+col);
      console.log("Row is: "+array[i]);
      var selector = $(".col-"+col).find(".row-"+array[i]).addClass("selected");
      console.log(selector);
    }
  }

  //Loop through every column
  function gridLoop() {
    if (settings.loopStatus) {
      settings.totalCol = settings.measures * settings.beats * settings.subdivision;
      setTimeout( function() {
        $(".col-" + settings.currentCol).children().toggleClass("active");
        if (settings.currentCol === 1) {
          $(".col-" + settings.totalCol).children().removeClass("active");
        }
        else {
          $(".col-"+(settings.currentCol - 1)).children().removeClass("active");
        }
        playSound();
        settings.currentCol++;
        if (settings.currentCol <= settings.totalCol){
          gridLoop();
        }
        else if (settings.currentCol == settings.totalCol + 1) {
          settings.currentCol = 1;
          gridLoop();
        }
       }, settings.colInterval);
    }
    else {
      settings.currentCol = 1;
      $(".box").removeClass("active");
      return;
    }
  }

  //Play the notes that are selected
  function playSound() {
    var notesToPlay = settings.selectedBoxes["col" + settings.currentCol];
    for (var i = 0; i < notesToPlay.length; i++) {
      var soundToPlay = eval("settings.soundPack[" + (notesToPlay[i]-1) + "]");
      soundToPlay.play();
    }
    notesToPlay = [];
  }

});<|endoftext|>


<commit_before>wp.customize.controlConstructor['kirki-date'] = wp.customize.kirkiDynamicControl.extend({

	initKirkiControl: function() {

		var control  = this,
		    selector = control.selector + ' input.datepicker';

		// Only add in WP 4.9+.
		if ( _.isUndefined( wp.customize.DateTimeControl ) ) {
			return;
		}

		// New method for the DateTime control.
		wp.customize.control.add( new wp.customize.DateTimeControl( control.id, {
			section: control.params.section,
			priority: control.params.priority,
			label: control.params.label,
			description: control.params.description,
			settings: { 'default': control.id },
			'default': control.params['default']
		} ) );
	}
});
<commit_msg>remove unused var<commit_after>wp.customize.controlConstructor['kirki-date'] = wp.customize.kirkiDynamicControl.extend({

	initKirkiControl: function() {

		var control  = this;

		// Only add in WP 4.9+.
		if ( _.isUndefined( wp.customize.DateTimeControl ) ) {
			return;
		}

		// New method for the DateTime control.
		wp.customize.control.add( new wp.customize.DateTimeControl( control.id, {
			section: control.params.section,
			priority: control.params.priority,
			label: control.params.label,
			description: control.params.description,
			settings: { 'default': control.id },
			'default': control.params['default']
		} ) );
	}
});
<|endoftext|>


<commit_before>(function ($){
  $.fn.instagram = function (options) {
    var that = this,
        apiEndpoint = "https://api.instagram.com/v1",
        settings = {
            hash: null
          , userId: null
          , locationId: null
          , search: null
          , accessToken: null
          , clientId: null
          , show: null
          , onLoad: null
          , onComplete: null
          , maxId: null
          , minId: null
          , next_url: null
          , image_size: null
        };

    options && $.extend(settings, options);

    function createPhotoElement(photo) {
      var image_url = photo.images.thumbnail.url;

      if (settings.image_size == 'low_resolution') {
        image_url = photo.images.low_resolution.url;
      }
      else if (settings.image_size == 'thumbnail') {
        image_url = photo.images.thumbnail.url;
      }
      else if (settings.image_size == 'standard_resolution') {
        image_url = photo.images.standard_resolution.url;
      }

      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', photo.id)
        .append(
          $('<a>')
            .attr('target', '_blank')
            .attr('href', photo.link)
            .append(
              $('<img>')
                .addClass('instagram-image')
                .attr('src', image_url)
            )
        );
    }

    function createEmptyElement() {
      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', 'empty')
        .append($('<p>').html('No photos for this query'));
    }

    function composeRequestURL() {

      var url = apiEndpoint,
          params = {};

      if (settings.next_url != null) {
        return settings.next_url;
      }

      if (settings.hash != null) {
        url += "/tags/" + settings.hash + "/media/recent";
      }
      else if (settings.search != null) {
        url += "/media/search";
        params.lat = settings.search.lat;
        params.lng = settings.search.lng;
        settings.search.max_timestamp != null && (params.max_timestamp = settings.search.max_timestamp);
        settings.search.min_timestamp != null && (params.min_timestamp = settings.search.min_timestamp);
        settings.search.distance != null && (params.distance = settings.search.distance);
      }
      else if (settings.userId != null) {
        url += "/users/" + settings.userId + "/media/recent";
      }
      else if (settings.locationId != null) {
        url += "/locations/" + settings.locationId + "/media/recent";
      }
      else {
        url += "/media/popular";
      }

      settings.accessToken != null && (params.access_token = settings.accessToken);
      settings.clientId != null && (params.client_id = settings.clientId);
      settings.minId != null && (params.min_id = settings.minId);
      settings.maxId != null && (params.max_id = settings.maxId);
      settings.show != null && (params.count = settings.show);

      url += "?" + $.param(params)

      return url;
    }

    settings.onLoad != null && typeof settings.onLoad == 'function' && settings.onLoad();

    $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: composeRequestURL(),
      success: function (res) {
        var length = typeof res.data != 'undefined' ? res.data.length : 0;
        var limit = settings.show != null && settings.show < length ? settings.show : length;

        if (limit > 0) {
          for (var i = 0; i < limit; i++) {
            that.append(createPhotoElement(res.data[i]));
          }
        }
        else {
          that.append(createEmptyElement());
        }

        settings.onComplete != null && typeof settings.onComplete == 'function' && settings.onComplete(res.data, res);
      }
    });

    return this;
  };
})(jQuery);
<commit_msg>Add plugin info header<commit_after>/*
 * Instagram jQuery plugin
 * v0.2.1
 * http://potomak.github.com/jquery-instagram/
 * Copyright (c) 2012 Giovanni Cappellotto
 * Licensed MIT
 */

(function ($){
  $.fn.instagram = function (options) {
    var that = this,
        apiEndpoint = "https://api.instagram.com/v1",
        settings = {
            hash: null
          , userId: null
          , locationId: null
          , search: null
          , accessToken: null
          , clientId: null
          , show: null
          , onLoad: null
          , onComplete: null
          , maxId: null
          , minId: null
          , next_url: null
          , image_size: null
        };

    options && $.extend(settings, options);

    function createPhotoElement(photo) {
      var image_url = photo.images.thumbnail.url;

      if (settings.image_size == 'low_resolution') {
        image_url = photo.images.low_resolution.url;
      }
      else if (settings.image_size == 'thumbnail') {
        image_url = photo.images.thumbnail.url;
      }
      else if (settings.image_size == 'standard_resolution') {
        image_url = photo.images.standard_resolution.url;
      }

      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', photo.id)
        .append(
          $('<a>')
            .attr('target', '_blank')
            .attr('href', photo.link)
            .append(
              $('<img>')
                .addClass('instagram-image')
                .attr('src', image_url)
            )
        );
    }

    function createEmptyElement() {
      return $('<div>')
        .addClass('instagram-placeholder')
        .attr('id', 'empty')
        .append($('<p>').html('No photos for this query'));
    }

    function composeRequestURL() {

      var url = apiEndpoint,
          params = {};

      if (settings.next_url != null) {
        return settings.next_url;
      }

      if (settings.hash != null) {
        url += "/tags/" + settings.hash + "/media/recent";
      }
      else if (settings.search != null) {
        url += "/media/search";
        params.lat = settings.search.lat;
        params.lng = settings.search.lng;
        settings.search.max_timestamp != null && (params.max_timestamp = settings.search.max_timestamp);
        settings.search.min_timestamp != null && (params.min_timestamp = settings.search.min_timestamp);
        settings.search.distance != null && (params.distance = settings.search.distance);
      }
      else if (settings.userId != null) {
        url += "/users/" + settings.userId + "/media/recent";
      }
      else if (settings.locationId != null) {
        url += "/locations/" + settings.locationId + "/media/recent";
      }
      else {
        url += "/media/popular";
      }

      settings.accessToken != null && (params.access_token = settings.accessToken);
      settings.clientId != null && (params.client_id = settings.clientId);
      settings.minId != null && (params.min_id = settings.minId);
      settings.maxId != null && (params.max_id = settings.maxId);
      settings.show != null && (params.count = settings.show);

      url += "?" + $.param(params)

      return url;
    }

    settings.onLoad != null && typeof settings.onLoad == 'function' && settings.onLoad();

    $.ajax({
      type: "GET",
      dataType: "jsonp",
      cache: false,
      url: composeRequestURL(),
      success: function (res) {
        var length = typeof res.data != 'undefined' ? res.data.length : 0;
        var limit = settings.show != null && settings.show < length ? settings.show : length;

        if (limit > 0) {
          for (var i = 0; i < limit; i++) {
            that.append(createPhotoElement(res.data[i]));
          }
        }
        else {
          that.append(createEmptyElement());
        }

        settings.onComplete != null && typeof settings.onComplete == 'function' && settings.onComplete(res.data, res);
      }
    });

    return this;
  };
})(jQuery);
<|endoftext|>


<commit_before>// 2 color	["#5097BA", "#DF4327"]

var colors = [
	[],
	["#8EBC66"],
	["#5EA9A1", "#E0A23A"],
	["#5CA7A4", "#A4BE56", "#E39B39"],
	["#5AA5A7", "#8ABB6A", "#C3BA46", "#E69237"],
	["#59A3AA", "#7CB879", "#AABD52", "#D4B13F", "#E68634"],
	["#57A1AD", "#73B583", "#98BD5E", "#C0BA47", "#DEA73C", "#E67B32"],
	["#559EB1", "#6DB28B", "#8CBB68", "#AFBD4F", "#CFB541", "#E39B39", "#E56E30"],
	["#539CB4", "#68AF92", "#83BA71", "#A2BE57", "#C1BA47", "#DAAC3D", "#E68E36", "#E35F2D"],
	["#519AB7", "#64AC99", "#7BB879", "#97BD5F", "#B5BD4C", "#CFB541", "#E0A13A", "#E67F33", "#E1512A"],
	["#5097BA", "#60AA9E", "#75B681", "#8EBC66", "#AABD52", "#C4B945", "#D9AD3D", "#E59637", "#E67030", "#DF4327"],
	["#4E95BD", "#5DA8A3", "#70B487", "#87BB6D", "#A0BE58", "#BABC4A", "#D0B440", "#E0A23A", "#E68634", "#E35F2D", "#DD3425"],
	["#4D92BF", "#5AA5A8", "#6BB18D", "#80B974", "#98BD5E", "#B1BD4E", "#C8B944", "#DAAC3D", "#E59738", "#E67732", "#E14F2A", "#DB2522"]
];
var genotypeColors = ["#60AA9E", "#D9AD3D", "#5097BA", "#E67030", "#8EBC66", "#E59637", "#AABD52", "#DF4327", "#C4B945", "#75B681"]

var epitopeColorScale = d3.scale.linear().clamp([true])
	.domain(epiColorDomain)
	.range(colors[10]);

var nonepitopeColorScale = d3.scale.linear().clamp([true])
	.domain(nonEpiColorDomain)
	.range(colors[10]);

var receptorBindingColorScale = d3.scale.linear().clamp([true])
	.domain(rbsColorDomain)
	.range(colors[4]);

var lbiColorScale = d3.scale.linear()
	.domain([0.0, 0.02, 0.04, 0.07, 0.1, 0.2, 0.4, 0.7, 0.9, 1.0])
	.range(colors[10]);

var dfreqColorScale = d3.scale.linear()
	.domain(dfreqColorDomain)
	.range(colors[10]);

var dateColorScale = d3.scale.linear().clamp([true])
	.domain(dateColorDomain)
	.range(colors[10]);

var regionColorScale = d3.scale.ordinal()
	.domain(regions.map(function(d){return d[0];}))
	.range(regions.map(function(d){return d[1];}));

// "ep", "ne" and "rb" need no adjustments
function adjust_coloring_by_date() {
	if (colorBy == "lbi") {
		calcLBI(rootNode, nodes, false);
		nodes.forEach(function (d) {
			d.coloring = d.LBI;
		});
	}
	else if (colorBy == "dfreq") {
		calcDfreq(rootNode, freq_ii);
		nodes.forEach(function (d) {
			d.coloring = d.dfreq;
		});
	}
	else if (colorBy == "date") {
		nodes.forEach(function (d) {
			d.coloring = d.num_date;
		});
	}
}

function stateAtPosition(clade, gene, pos){
	if (typeof cladeToSeq[clade][gene][pos] == "undefined"){
		return cladeToSeq["root"][gene][pos];
	}else{
		return cladeToSeq[clade][gene][pos];
	}
}

function colorByTrait() {

	colorBy = document.getElementById("coloring").value;
	console.log(colorBy);

	if (colorBy == "ep") {
		colorScale = epitopeColorScale;
		nodes.map(function(d) { d.coloring = d.ep; });
	}
	else if (colorBy == "ne") {
		colorScale = nonepitopeColorScale;
		nodes.map(function(d) { d.coloring = d.ne; });
	}
	else if (colorBy == "rb") {
		colorScale = receptorBindingColorScale;
		nodes.map(function(d) { d.coloring = d.rb; });
	}
	else if (colorBy == "lbi") {
		colorScale = lbiColorScale;
		adjust_coloring_by_date();
	}
	else if (colorBy == "dfreq") {
		colorScale = dfreqColorScale;
		adjust_coloring_by_date();
	}
	else if (colorBy == "region") {
		colorScale = regionColorScale;
		nodes.map(function(d) { d.coloring = d.region; });
	}
	else if (colorBy == "date") {
		colorScale = dateColorScale;
		nodes.map(function(d) { d.coloring = d.num_date; });
	}

	treeplot.selectAll(".link")
		.style("stroke", branchStrokeColor);

	d3.selectAll(".tip")
		.style("visibility", tipVisibility)
		.style("fill", tipFillColor)
		.style("stroke", tipStrokeColor);

	if (typeof tree_legend != undefined){
		removeLegend();
	}
	tree_legend = makeLegend();
}

function tipStrokeColor(d) {
	var col = colorScale(d.coloring);
	return d3.rgb(col).toString();
}

function tipFillColor(d) {
	var col = colorScale(d.coloring);	;
	return d3.rgb(col).brighter([0.65]).toString();
}

function branchStrokeColor(d) {
	var col;
	if (colorBy == "region" || colorBy == "date") {
		col = "#AAA";
	}
	else {
		col = colorScale(d.target.coloring);
	}
	var modCol = d3.interpolateRgb(col, "#BBB")(0.6);
	return d3.rgb(modCol).toString();
}

function colorByGenotype() {
	var positions_string = document.getElementById("gt-color").value.split(',');
	var positions_list = []
	positions_string.map(function(d) {
		val = parseInt(d)-1;
		if (!isNaN(val)) {
			if (val < 551) {
				positions_list.push(val);
			}
		}
	});
	console.log(positions_list);
	if (positions_list.length > 0) {
		colorBy = "genotype";
		colorByGenotypePosition(positions_list);
	}
	else {
		d3.select("#coloring").each(colorByTrait);
		gt = parse_gt_string(freqdefault);
		make_gt_chart(gt);
		document.getElementById("gtspec").value = freqdefault;
	}
}

function colorByGenotypePosition (positions) {
	var gts = nodes.map(function (d) {
		var tmp = [];
		for (var i=0; i<positions.length; i++){
			tmp[tmp.length] = (positions[i]+1)+stateAtPosition(d.clade, gene, positions[i]);
		}
		d.coloring = tmp.join(" / ");
		return d.coloring;});
	var unique_gts = d3.set(gts).values();
	var gt_counts = {};
	for (var i=0; i<unique_gts.length; i++){gt_counts[unique_gts[i]]=0;}
	gts.forEach(function (d) {gt_counts[d]+=1;});
	var filtered_gts = unique_gts.filter(function (d) {return gt_counts[d]>=10;});
	filtered_gts.sort(function (a,b){
		var res;
		if (gt_counts[a]>gt_counts[b]){ res=-1;}
		else if (gt_counts[a]<gt_counts[b]){ res=1;}
		else {res=0;}
		return res;});
	console.log("genotypes passed filtering:"+filtered_gts);
	colorScale = d3.scale.ordinal()
		.domain(filtered_gts)
		.range(genotypeColors);
	treeplot.selectAll(".link")
		.style("stroke", branchStrokeColor);
	treeplot.selectAll(".tip")
		.style("fill", tipFillColor)
		.style("stroke", tipStrokeColor);
	if (typeof tree_legend != undefined){
		removeLegend();
	}
	tree_legend = makeLegend();

	if ((positions.length==1)&&(filtered_gts.length>1)){
		var tmp_gts=[];
		for (var ii=0; ii<filtered_gts.length; ii+=1){
			tmp_gts.push(["global", filtered_gts[ii]])
		}
		make_gt_chart(tmp_gts);
		document.getElementById("gtspec").value = tmp_gts.map( function (d) {return d[1];}).join(', ');
	}
}

d3.select("#coloring")
	.style("cursor", "pointer")
	.on("change", colorByTrait);

var genotypeColoringEvent;
d3.select("#gt-color")
	.on("keyup", function(){
		if (typeof genotypeColoringEvent != "undefined"){clearTimeout(genotypeColoringEvent);}
		genotypeColoringEvent = setTimeout(colorByGenotype, 200);
	});

<commit_msg>added gene argumnet to coloring<commit_after>// 2 color	["#5097BA", "#DF4327"]

var colors = [
	[],
	["#8EBC66"],
	["#5EA9A1", "#E0A23A"],
	["#5CA7A4", "#A4BE56", "#E39B39"],
	["#5AA5A7", "#8ABB6A", "#C3BA46", "#E69237"],
	["#59A3AA", "#7CB879", "#AABD52", "#D4B13F", "#E68634"],
	["#57A1AD", "#73B583", "#98BD5E", "#C0BA47", "#DEA73C", "#E67B32"],
	["#559EB1", "#6DB28B", "#8CBB68", "#AFBD4F", "#CFB541", "#E39B39", "#E56E30"],
	["#539CB4", "#68AF92", "#83BA71", "#A2BE57", "#C1BA47", "#DAAC3D", "#E68E36", "#E35F2D"],
	["#519AB7", "#64AC99", "#7BB879", "#97BD5F", "#B5BD4C", "#CFB541", "#E0A13A", "#E67F33", "#E1512A"],
	["#5097BA", "#60AA9E", "#75B681", "#8EBC66", "#AABD52", "#C4B945", "#D9AD3D", "#E59637", "#E67030", "#DF4327"],
	["#4E95BD", "#5DA8A3", "#70B487", "#87BB6D", "#A0BE58", "#BABC4A", "#D0B440", "#E0A23A", "#E68634", "#E35F2D", "#DD3425"],
	["#4D92BF", "#5AA5A8", "#6BB18D", "#80B974", "#98BD5E", "#B1BD4E", "#C8B944", "#DAAC3D", "#E59738", "#E67732", "#E14F2A", "#DB2522"]
];
var genotypeColors = ["#60AA9E", "#D9AD3D", "#5097BA", "#E67030", "#8EBC66", "#E59637", "#AABD52", "#DF4327", "#C4B945", "#75B681"]

var epitopeColorScale = d3.scale.linear().clamp([true])
	.domain(epiColorDomain)
	.range(colors[10]);

var nonepitopeColorScale = d3.scale.linear().clamp([true])
	.domain(nonEpiColorDomain)
	.range(colors[10]);

var receptorBindingColorScale = d3.scale.linear().clamp([true])
	.domain(rbsColorDomain)
	.range(colors[4]);

var lbiColorScale = d3.scale.linear()
	.domain([0.0, 0.02, 0.04, 0.07, 0.1, 0.2, 0.4, 0.7, 0.9, 1.0])
	.range(colors[10]);

var dfreqColorScale = d3.scale.linear()
	.domain(dfreqColorDomain)
	.range(colors[10]);

var dateColorScale = d3.scale.linear().clamp([true])
	.domain(dateColorDomain)
	.range(colors[10]);

var regionColorScale = d3.scale.ordinal()
	.domain(regions.map(function(d){return d[0];}))
	.range(regions.map(function(d){return d[1];}));

// "ep", "ne" and "rb" need no adjustments
function adjust_coloring_by_date() {
	if (colorBy == "lbi") {
		calcLBI(rootNode, nodes, false);
		nodes.forEach(function (d) {
			d.coloring = d.LBI;
		});
	}
	else if (colorBy == "dfreq") {
		calcDfreq(rootNode, freq_ii);
		nodes.forEach(function (d) {
			d.coloring = d.dfreq;
		});
	}
	else if (colorBy == "date") {
		nodes.forEach(function (d) {
			d.coloring = d.num_date;
		});
	}
}

function stateAtPosition(clade, gene, pos){
	if (typeof cladeToSeq[clade][gene][pos] == "undefined"){
		return cladeToSeq["root"][gene][pos];
	}else{
		return cladeToSeq[clade][gene][pos];
	}
}

function colorByTrait() {

	colorBy = document.getElementById("coloring").value;
	console.log(colorBy);

	if (colorBy == "ep") {
		colorScale = epitopeColorScale;
		nodes.map(function(d) { d.coloring = d.ep; });
	}
	else if (colorBy == "ne") {
		colorScale = nonepitopeColorScale;
		nodes.map(function(d) { d.coloring = d.ne; });
	}
	else if (colorBy == "rb") {
		colorScale = receptorBindingColorScale;
		nodes.map(function(d) { d.coloring = d.rb; });
	}
	else if (colorBy == "lbi") {
		colorScale = lbiColorScale;
		adjust_coloring_by_date();
	}
	else if (colorBy == "dfreq") {
		colorScale = dfreqColorScale;
		adjust_coloring_by_date();
	}
	else if (colorBy == "region") {
		colorScale = regionColorScale;
		nodes.map(function(d) { d.coloring = d.region; });
	}
	else if (colorBy == "date") {
		colorScale = dateColorScale;
		nodes.map(function(d) { d.coloring = d.num_date; });
	}

	treeplot.selectAll(".link")
		.style("stroke", branchStrokeColor);

	d3.selectAll(".tip")
		.style("visibility", tipVisibility)
		.style("fill", tipFillColor)
		.style("stroke", tipStrokeColor);

	if (typeof tree_legend != undefined){
		removeLegend();
	}
	tree_legend = makeLegend();
}

function tipStrokeColor(d) {
	var col = colorScale(d.coloring);
	return d3.rgb(col).toString();
}

function tipFillColor(d) {
	var col = colorScale(d.coloring);	;
	return d3.rgb(col).brighter([0.65]).toString();
}

function branchStrokeColor(d) {
	var col;
	if (colorBy == "region" || colorBy == "date") {
		col = "#AAA";
	}
	else {
		col = colorScale(d.target.coloring);
	}
	var modCol = d3.interpolateRgb(col, "#BBB")(0.6);
	return d3.rgb(modCol).toString();
}

function colorByGenotype() {
	var positions_string = document.getElementById("gt-color").value.split(',');
	var positions_list = []
	positions_string.map(function(d) {
		val = parseInt(d)-1;
		if (!isNaN(val)) {
			if (val < 551) {
				positions_list.push(val);
			}
		}
	});
	console.log(positions_list);
	if (positions_list.length > 0) {
		colorBy = "genotype";
		colorByGenotypePosition(positions_list, 'nuc');
	}
	else {
		d3.select("#coloring").each(colorByTrait);
		gt = parse_gt_string(freqdefault);
		make_gt_chart(gt);
		document.getElementById("gtspec").value = freqdefault;
	}
}

function colorByGenotypePosition (positions, gene) {
	var gts = nodes.map(function (d) {
		var tmp = [];
		for (var i=0; i<positions.length; i++){
			tmp[tmp.length] = (positions[i]+1)+stateAtPosition(d.clade, gene, positions[i]);
		}
		d.coloring = tmp.join(" / ");
		return d.coloring;});
	var unique_gts = d3.set(gts).values();
	var gt_counts = {};
	for (var i=0; i<unique_gts.length; i++){gt_counts[unique_gts[i]]=0;}
	gts.forEach(function (d) {gt_counts[d]+=1;});
	var filtered_gts = unique_gts.filter(function (d) {return gt_counts[d]>=10;});
	filtered_gts.sort(function (a,b){
		var res;
		if (gt_counts[a]>gt_counts[b]){ res=-1;}
		else if (gt_counts[a]<gt_counts[b]){ res=1;}
		else {res=0;}
		return res;});
	console.log("genotypes passed filtering:"+filtered_gts);
	colorScale = d3.scale.ordinal()
		.domain(filtered_gts)
		.range(genotypeColors);
	treeplot.selectAll(".link")
		.style("stroke", branchStrokeColor);
	treeplot.selectAll(".tip")
		.style("fill", tipFillColor)
		.style("stroke", tipStrokeColor);
	if (typeof tree_legend != undefined){
		removeLegend();
	}
	tree_legend = makeLegend();

	if ((positions.length==1)&&(filtered_gts.length>1)){
		var tmp_gts=[];
		for (var ii=0; ii<filtered_gts.length; ii+=1){
			tmp_gts.push(["global", filtered_gts[ii]])
		}
		make_gt_chart(tmp_gts);
		document.getElementById("gtspec").value = tmp_gts.map( function (d) {return d[1];}).join(', ');
	}
}

d3.select("#coloring")
	.style("cursor", "pointer")
	.on("change", colorByTrait);

var genotypeColoringEvent;
d3.select("#gt-color")
	.on("keyup", function(){
		if (typeof genotypeColoringEvent != "undefined"){clearTimeout(genotypeColoringEvent);}
		genotypeColoringEvent = setTimeout(colorByGenotype, 200);
	});

<|endoftext|>


<commit_before>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('unisubs.translate.TranslationWidget');

/**
 * @constructor
 * @param {Object.<string, *>} subtitle Base language subtitle in json format
 * @param {unisubs.subtitle.EditableCaption} translation
 */
unisubs.translate.TranslationWidget = function(subtitle, translation, dialog) {
    goog.ui.Component.call(this);
    this.subtitle_ = subtitle;
    this.dialog_ = dialog;
    this.videoURL_ = this.dialog_.getVideoPlayerInternal().videoSource_.videoURL_ || '';

    /**
     * @type {unisubs.subtitle.EditableCaption}
     */
    this.translation_ = translation;
};

goog.inherits(unisubs.translate.TranslationWidget, goog.ui.Component);

unisubs.translate.TranslationWidget.prototype.getSubtitle = function(){
    return this.subtitle_;
};
unisubs.translate.TranslationWidget.prototype.getOriginalValue = function(){
    return this.subtitle_.text;
};
unisubs.translate.TranslationWidget.prototype.getSubJson = function() {
    return {
        'subtitle_id': this.getCaptionID(),
        'text': this.translateInput_.value
    };
};
unisubs.translate.TranslationWidget.prototype.createDom = function() {

    var $d = goog.bind(this.getDomHelper().createDom, this.getDomHelper());

    this.setElementInternal(
        $d('li', null,
           $d('div', null,
              $d('span', {'className': 'unisubs-timestamp-time-fixed'},
                         unisubs.formatTime(this.subtitle_['start_time'])),
              $d('span', 'unisubs-title unisubs-title-notime', this.subtitle_['text']),
              this.loadingIndicator_ = $d('span', 'unisubs-loading-indicator', 'loading...')
           ),
           this.translateInput_ = $d('textarea', 'unisubs-translateField')
        )
    );

    this.getHandler()
        .listen(
            this.translateInput_, goog.events.EventType.KEYUP,
            goog.bind(this.inputKeyUp_, this, true))
        .listen(
            this.translateInput_, goog.events.EventType.BLUR,
            goog.bind(this.inputLostFocus_, this, true))
        .listen(
            this.translateInput_, goog.events.EventType.FOCUS,
            this.inputGainedFocus_);
    this.translateInput_.value = this.translation_ ? this.translation_.getText() : '';
};
unisubs.translate.TranslationWidget.prototype.inputGainedFocus_ = function(event) {
    this.onFocusText_ = this.translateInput_.value;

    if (this.videoURL_.indexOf('vimeo.com') === -1) {
        this.dialog_.getVideoPlayerInternal().setPlayheadTime(this.subtitle_['start_time']);
        this.dialog_.getVideoPlayerInternal().pause();
    }
};
unisubs.translate.TranslationWidget.prototype.inputKeyUp_ = function(track) {
    this.onKeyUpText_ = this.translateInput_.value;

    if (this.videoURL_.indexOf('vimeo.com') === -1) {
        var editableCaptionSet = this.dialog_.translationPanel_.getTranslationList().baseLanguageCaptionSet_;
        var editableCaption = editableCaptionSet.captionByID(this.subtitle_['subtitle_id']);

        if (this.onKeyUpText_ !== '') {
            editableCaption.setText(this.onKeyUpText_);
            this.dialog_.getVideoPlayerInternal().showCaptionText(this.onKeyUpText_);
            this.textHasBeenChanged_ = true;
        } else {
            if (this.textHasBeenChanged_) {
                var originalText = editableCaption.getOriginalText();
                editableCaption.setText(originalText);
                this.dialog_.getVideoPlayerInternal().showCaptionText(originalText);
                this.textHasBeenChanged_ = false;
            }
        }
    }
}
unisubs.translate.TranslationWidget.prototype.inputLostFocus_ = function(track) {
    var value = goog.string.trim(this.translateInput_.value);
    var edited = value != this.onFocusText_;
    if (track && edited) {
        if (this.onFocusText_ == "")
            unisubs.SubTracker.getInstance().trackAdd(this.getCaptionID());
        else
            unisubs.SubTracker.getInstance().trackEdit(this.getCaptionID());
    }
    this.translation_.setText(value);
};
unisubs.translate.TranslationWidget.prototype.setTranslationContent = function(value){
    this.translateInput_.value = value;
    this.inputLostFocus_(false);
};
unisubs.translate.TranslationWidget.prototype.setEnabled = function(enabled) {
    this.translateInput_.disabled = !enabled;
    if (!enabled)
        this.translateInput_.value = '';
};
unisubs.translate.TranslationWidget.prototype.getCaptionID = function() {
    return this.subtitle_['subtitle_id'];
};

/**
 * Return if translate input has some value
 * @return {boolean}
 */
unisubs.translate.TranslationWidget.prototype.isEmpty = function(){
    return ! goog.string.trim(this.translateInput_.value);
};

unisubs.translate.TranslationWidget.prototype.showLoadingIndicator = function(){
    unisubs.style.showElement(this.loadingIndicator_, true);
};
unisubs.translate.TranslationWidget.prototype.hideLoadingIndicator = function(){
    unisubs.style.showElement(this.loadingIndicator_, false);
};
<commit_msg>Seek Vimeo playhead to approximate subtitle start time, but don't display the subtitle (since Vimeo doesn't support finer timing)<commit_after>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('unisubs.translate.TranslationWidget');

/**
 * @constructor
 * @param {Object.<string, *>} subtitle Base language subtitle in json format
 * @param {unisubs.subtitle.EditableCaption} translation
 */
unisubs.translate.TranslationWidget = function(subtitle, translation, dialog) {
    goog.ui.Component.call(this);
    this.subtitle_ = subtitle;
    this.dialog_ = dialog;
    this.videoURL_ = this.dialog_.getVideoPlayerInternal().videoSource_.videoURL_ || '';

    /**
     * @type {unisubs.subtitle.EditableCaption}
     */
    this.translation_ = translation;
};

goog.inherits(unisubs.translate.TranslationWidget, goog.ui.Component);

unisubs.translate.TranslationWidget.prototype.getSubtitle = function(){
    return this.subtitle_;
};
unisubs.translate.TranslationWidget.prototype.getOriginalValue = function(){
    return this.subtitle_.text;
};
unisubs.translate.TranslationWidget.prototype.getSubJson = function() {
    return {
        'subtitle_id': this.getCaptionID(),
        'text': this.translateInput_.value
    };
};
unisubs.translate.TranslationWidget.prototype.createDom = function() {

    var $d = goog.bind(this.getDomHelper().createDom, this.getDomHelper());

    this.setElementInternal(
        $d('li', null,
           $d('div', null,
              $d('span', {'className': 'unisubs-timestamp-time-fixed'},
                         unisubs.formatTime(this.subtitle_['start_time'])),
              $d('span', 'unisubs-title unisubs-title-notime', this.subtitle_['text']),
              this.loadingIndicator_ = $d('span', 'unisubs-loading-indicator', 'loading...')
           ),
           this.translateInput_ = $d('textarea', 'unisubs-translateField')
        )
    );

    this.getHandler()
        .listen(
            this.translateInput_, goog.events.EventType.KEYUP,
            goog.bind(this.inputKeyUp_, this, true))
        .listen(
            this.translateInput_, goog.events.EventType.BLUR,
            goog.bind(this.inputLostFocus_, this, true))
        .listen(
            this.translateInput_, goog.events.EventType.FOCUS,
            this.inputGainedFocus_);
    this.translateInput_.value = this.translation_ ? this.translation_.getText() : '';
};
unisubs.translate.TranslationWidget.prototype.inputGainedFocus_ = function(event) {
    this.onFocusText_ = this.translateInput_.value;

    this.dialog_.getVideoPlayerInternal().setPlayheadTime(this.subtitle_['start_time']);
    this.dialog_.getVideoPlayerInternal().pause();
};
unisubs.translate.TranslationWidget.prototype.inputKeyUp_ = function(track) {
    this.onKeyUpText_ = this.translateInput_.value;

    if (this.videoURL_.indexOf('vimeo.com') === -1) {
        var editableCaptionSet = this.dialog_.translationPanel_.getTranslationList().baseLanguageCaptionSet_;
        var editableCaption = editableCaptionSet.captionByID(this.subtitle_['subtitle_id']);

        if (this.onKeyUpText_ !== '') {
            editableCaption.setText(this.onKeyUpText_);
            this.dialog_.getVideoPlayerInternal().showCaptionText(this.onKeyUpText_);
            this.textHasBeenChanged_ = true;
        } else {
            if (this.textHasBeenChanged_) {
                var originalText = editableCaption.getOriginalText();
                editableCaption.setText(originalText);
                this.dialog_.getVideoPlayerInternal().showCaptionText(originalText);
                this.textHasBeenChanged_ = false;
            }
        }
    }
}
unisubs.translate.TranslationWidget.prototype.inputLostFocus_ = function(track) {
    var value = goog.string.trim(this.translateInput_.value);
    var edited = value != this.onFocusText_;
    if (track && edited) {
        if (this.onFocusText_ == "")
            unisubs.SubTracker.getInstance().trackAdd(this.getCaptionID());
        else
            unisubs.SubTracker.getInstance().trackEdit(this.getCaptionID());
    }
    this.translation_.setText(value);
};
unisubs.translate.TranslationWidget.prototype.setTranslationContent = function(value){
    this.translateInput_.value = value;
    this.inputLostFocus_(false);
};
unisubs.translate.TranslationWidget.prototype.setEnabled = function(enabled) {
    this.translateInput_.disabled = !enabled;
    if (!enabled)
        this.translateInput_.value = '';
};
unisubs.translate.TranslationWidget.prototype.getCaptionID = function() {
    return this.subtitle_['subtitle_id'];
};

/**
 * Return if translate input has some value
 * @return {boolean}
 */
unisubs.translate.TranslationWidget.prototype.isEmpty = function(){
    return ! goog.string.trim(this.translateInput_.value);
};

unisubs.translate.TranslationWidget.prototype.showLoadingIndicator = function(){
    unisubs.style.showElement(this.loadingIndicator_, true);
};
unisubs.translate.TranslationWidget.prototype.hideLoadingIndicator = function(){
    unisubs.style.showElement(this.loadingIndicator_, false);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var coffee = require('coffee-script');
var UglifyJS = require("uglify-js");

var coffeeSrcPath = process.argv[2];
var coffeeSrcName = process.argv[3];
var coffeeDestDir = process.argv[4];
var minify = process.argv[5] === 'true';

var mkdirsSync = function(dir) {
  var dirs = dir.split('/');
  var s = '';
  for (var i = 0; i < dirs.length; i++) {
    s += (s.length == 0 ? '' : '/') + dirs[i];
    if (!fs.existsSync(s)) {
      fs.mkdirSync(s);
    }
  }
}

if (!fs.existsSync(coffeeDestDir)) {
  mkdirsSync(coffeeDestDir);
}
coffeeConvert(coffeeSrcPath, coffeeSrcName, [path.dirname(coffeeSrcPath)], path.join(coffeeDestDir, coffeeSrcName.replace(/\.coffee/, '.js')));

function coffeeConvert(filepath, filename, searchPaths, outputPath) {
  var coffeeString = fs.readFileSync(filepath, 'utf8');

  var js = coffee.compile(coffeeString, {});
  if (minify) {
    var minified = UglifyJS.minify(js, {fromString: true, compress: {evaluate: false}});
    js = minified.code;
  }

  if (!fs.existsSync(path.dirname(outputPath))) {
    mkdirsSync(path.dirname(outputPath));
  }

  fs.writeFile(outputPath, js, function(err) {
    if (err) {
      console.log(err);
    }
    console.log('CoffeeScript: processed ' + filepath);
  });
}
<commit_msg>Refactor. Use ' instead of ".<commit_after>var fs = require('fs');
var path = require('path');
var coffee = require('coffee-script');
var UglifyJS = require('uglify-js');

var coffeeSrcPath = process.argv[2];
var coffeeSrcName = process.argv[3];
var coffeeDestDir = process.argv[4];
var minify = process.argv[5] === 'true';

var mkdirsSync = function(dir) {
  var dirs = dir.split('/');
  var s = '';
  for (var i = 0; i < dirs.length; i++) {
    s += (s.length == 0 ? '' : '/') + dirs[i];
    if (!fs.existsSync(s)) {
      fs.mkdirSync(s);
    }
  }
}

if (!fs.existsSync(coffeeDestDir)) {
  mkdirsSync(coffeeDestDir);
}
coffeeConvert(coffeeSrcPath, coffeeSrcName, [path.dirname(coffeeSrcPath)], path.join(coffeeDestDir, coffeeSrcName.replace(/\.coffee/, '.js')));

function coffeeConvert(filepath, filename, searchPaths, outputPath) {
  var coffeeString = fs.readFileSync(filepath, 'utf8');

  var js = coffee.compile(coffeeString, {});
  if (minify) {
    var minified = UglifyJS.minify(js, {fromString: true, compress: {evaluate: false}});
    js = minified.code;
  }

  if (!fs.existsSync(path.dirname(outputPath))) {
    mkdirsSync(path.dirname(outputPath));
  }

  fs.writeFile(outputPath, js, function(err) {
    if (err) {
      console.log(err);
    }
    console.log('CoffeeScript: processed ' + filepath);
  });
}
<|endoftext|>


<commit_before>import * as DynamoDBProvider from './feedback-dynamodb-provider';
import * as InMemoryProvider from './feedback-inmemory-provider';

import log from '../lib/logger-service';

let db = null;

module.exports = class Feedback {
  constructor() {
    if (db != null) {
      this.db = db;
      return;
    }

    log.debug('Initializing Feedback-provider');

    // Use in-memory db when running in local client (npm run bot-client)
    this.db = db = (process.env.RUN_ENV === 'dev') ?
        new InMemoryProvider() :
        new DynamoDBProvider();
  }

  createFeedback({ giver, pair, feedback }) {
    return this.db.write({ date: Date.now(), giver, pair, feedback });
  }
};
<commit_msg>feedback is now working<commit_after>import * as DynamoDBProvider from './feedback-dynamodb-provider';
import * as InMemoryProvider from './feedback-inmemory-provider';

import log from '../lib/logger-service';

let db = null;

module.exports = class Feedback {
  constructor() {
    if (db != null) {
      this.db = db;
      return;
    }

    log.debug('Initializing Feedback-provider');

    // Use in-memory db when running in local client (npm run bot-client)
    this.db = db = (process.env.RUN_ENV === 'dev') ?
        new InMemoryProvider() :
        new DynamoDBProvider();
  }

  createFeedback({ giver, pair, feedback }) {
    return this.db.write({ date: new Date(), giver, pair, feedback });
  }
};
<|endoftext|>


<commit_before>export var ObjectUtilities = {
    isEqual: function (objA, objB) {
        var aKeys = Object.keys(objA);
        var bKeys = Object.keys(objB);
        if (aKeys.length !== bKeys.length) {
            return false;
        }
        for (var i = 0, len = aKeys.length; i < len; i++) {
            var key = aKeys[i];
            if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) {
                return false;
            }
        }
        return true;
    }
};

export var StringUtil = {
    pluralize: function (str, count) {
        var s = str;
        if (count > 1) {
            if (str.endsWith("y")) {
                s = str.substring(0, str.length - 2) + 'ies';
            } else {
                s += 's';
            }
        }
        return s;
    }
};
<commit_msg>Fix bug where object comparison is done on null object.<commit_after>export var ObjectUtilities = {
    isEqual: function (objA, objB) {
        if( !objA || !objB ) {
            return (!objA && !objB);
        }
        var aKeys = Object.keys(objA);
        var bKeys = Object.keys(objB);
        if (aKeys.length !== bKeys.length) {
            return false;
        }
        for (var i = 0, len = aKeys.length; i < len; i++) {
            var key = aKeys[i];
            if (!objB.hasOwnProperty(key) || objA[key] !== objB[key]) {
                return false;
            }
        }
        return true;
    }
};

export var StringUtil = {
    pluralize: function (str, count) {
        var s = str;
        if (count > 1) {
            if (str.endsWith("y")) {
                s = str.substring(0, str.length - 2) + 'ies';
            } else {
                s += 's';
            }
        }
        return s;
    }
};
<|endoftext|>


<commit_before>;(function($) {
  $.fn.textFlood = function(options) {
    var THRESHOLD = 4
    return this.each(function() {
      var $container = $(this)
      var height = $container.height()
      var width = $container.width()
      var content = $container.contents()
      var $wrap = $('<span>').append(content)
      $container.append($wrap)
      ;(function f(size, scan) {
        $wrap.css('font-size', size)
        if ($wrap.height() > height || $wrap.width() > width)
          size -= scan
        else
          size += scan
        if (size > 5 && Math.abs(scan) > THRESHOLD)
          f(size, ~~(scan/2))
        else {
          $wrap.replaceWith(content)
          $container.css('font-size', size)
        }
      })(height, height/2)
    })
  }
})(jQuery);
<commit_msg>Remove unused options argument<commit_after>;(function($) {
  $.fn.textFlood = function() {
    var THRESHOLD = 4
    return this.each(function() {
      var $container = $(this)
      var height = $container.height()
      var width = $container.width()
      var content = $container.contents()
      var $wrap = $('<span>').append(content)
      $container.append($wrap)
      ;(function f(size, scan) {
        $wrap.css('font-size', size)
        if ($wrap.height() > height || $wrap.width() > width)
          size -= scan
        else
          size += scan
        if (size > 5 && Math.abs(scan) > THRESHOLD)
          f(size, ~~(scan/2))
        else {
          $wrap.replaceWith(content)
          $container.css('font-size', size)
        }
      })(height, height/2)
    })
  }
})(jQuery);
<|endoftext|>


<commit_before>var DScriptActionMap = (function () {
    function DScriptActionMap() {
        this.ActionMap = [];
        this.ContextArray = [];
    }
    DScriptActionMap.prototype.GetContextLabel = function (Element) {
        for (var i = 0; i < Element.Children.length; i++) {
            var Children = Element.Children[i];
            if (Children.Type == AssureIt.NodeType.Context) {
                this.ContextArray.push(Children.Label);
            }
            this.GetContextLabel(Children);
        }
        return;
    };

    DScriptActionMap.prototype.GetReaction = function (Context) {
        var Parent = Context.Parent;
        for (var i = 0; i < Parent.Children.length; i++) {
            var Child = Parent.Children[i];
            if (Child.Type == AssureIt.NodeType.Evidence) {
                return Child.Label;
            }
        }
        return "";
    };

    DScriptActionMap.prototype.GetAction = function (Context) {
        var NotesKeys = Object.keys(Context.Notes);
        var Action = "";
        var Reaction = "";

        for (var i = 0; i < NotesKeys.length; i++) {
            if (NotesKeys[i] == "Reaction") {
                Action = Context.Notes["Reaction"];
                Reaction = this.GetReaction(Context);
                this.ActionMap[Action] = Reaction;
            }
        }
        return;
    };

    DScriptActionMap.prototype.GetActionMap = function (ViewMap, Node, ASNData) {
        var ActionMapScript = "";
        this.GetContextLabel(Node);
        for (var i = 0; i < this.ContextArray.length; i++) {
            var Context = ViewMap[this.ContextArray[i]];
            if (Context.Annotations.length > 0) {
                this.GetAction(Context);
            }
        }
        for (var key in this.ActionMap) {
            console.log(key + " : " + this.ActionMap[key]);
            ActionMapScript += key + " : " + this.ActionMap[key] + "\n";
        }
        return ActionMapScript;
    };
    return DScriptActionMap;
})();
<commit_msg>modified Reaction Condition<commit_after>var DScriptActionMap = (function () {
    function DScriptActionMap() {
        this.ActionMap = [];
        this.ContextArray = [];
    }
    DScriptActionMap.prototype.GetContextLabel = function (Element) {
        for (var i = 0; i < Element.Children.length; i++) {
            var Children = Element.Children[i];
            if (Children.Type == AssureIt.NodeType.Context) {
                this.ContextArray.push(Children.Label);
            }
            this.GetContextLabel(Children);
        }
        return;
    };

    DScriptActionMap.prototype.GetReaction = function (Context) {
        var Parent = Context.Parent;
        for (var i = 0; i < Parent.Children.length; i++) {
            var Child = Parent.Children[i];
            if (Child.Type != AssureIt.NodeType.Context) {
                return Child.Label;
            }
        }
        return "";
    };

    DScriptActionMap.prototype.GetAction = function (Context) {
        var NotesKeys = Object.keys(Context.Notes);
        var Action = "";
        var Reaction = "";

        for (var i = 0; i < NotesKeys.length; i++) {
            if (NotesKeys[i] == "Reaction") {
                Action = Context.Notes["Reaction"];
                Reaction = this.GetReaction(Context);
                this.ActionMap[Action] = Reaction;
            }
        }
        return;
    };

    DScriptActionMap.prototype.GetActionMap = function (ViewMap, Node, ASNData) {
        var ActionMapScript = "";
        this.GetContextLabel(Node);
        for (var i = 0; i < this.ContextArray.length; i++) {
            var Context = ViewMap[this.ContextArray[i]];
            if (Context.Annotations.length > 0) {
                this.GetAction(Context);
            }
        }
        for (var key in this.ActionMap) {
            console.log(key + " : " + this.ActionMap[key]);
            ActionMapScript += key + " : " + this.ActionMap[key] + "\n";
        }
        return ActionMapScript;
    };
    return DScriptActionMap;
})();
<|endoftext|>


<commit_before>(function() {
    /**
     * For the given node calls the handler method xfmChanged() when
     * the global transformation changed. This is the case if the transform
     * attribute of the target node or of one of the parent nodes changed.
     * Since transform attributes point to transform elements the transformation of
     * the target node also changes if corresponding transform elements are modified.
     *
     * This observer tracks only these changes, though. It does not track whether some local fields
     * of the target node change since it does not know which there might be.
     *
     * The observer registers itself as listener in all parent nodes that have a transform attribute
     * to find out when changes to that attribute happen.
     *
     * @constructor
     * @param {!Object} _targetNode the node to track
     */
    var TransformTracker = function(_targetNode)
    {
        if(!_targetNode)
            throw "TransformTracker: no target node specified.";

        this.xml3d = XMOT.util.getXml3dRoot(_targetNode);
        if(!this.xml3d)
            throw "TransformTracker: given node is not a child of an xml3d element.";

        this.targetNode = _targetNode;

        /** @private */
        this._attached = false;

        this.attach();
    };

    var p = TransformTracker.prototype;

    /** Event handler to be overriden by the user
     *
     * @param {!Object} targetNode the node this observer tracks
     * @param {!Event} evt the original DOM event that caused the change
     */
    p.xfmChanged = function(targetNode, evt) { };

    /**
     * Register callbacks in the given node and all parent nodes.
     *
     * @this {TransformTracker}
     * @param {!Object} [node] (internal) the node to register. If not given the
     *  target node is taken.
     */
    p.attach = function(node)
    {
        if(!this._attached)
        {
            if(!node)
                node = this.targetNode;

            if(node.tagName == "xml3d")
                return;

            if(node.tagName == "group")
            {
                node.addEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onGrpAttrModified), false);

                var xfm = XMOT.util.transform(node);
                if(xfm)
                    xfm.addEventListener("DOMAttrModified",
                        XMOT.util.wrapCallback(this, _onXfmAttrModified), false);
            }
            else if(node.tagName == "view")
            {
                node.addEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onViewAttrModified), false);
            }

            this.attach(node.parentNode);

            this._attached = true;
        }
    };

    /**
     * Deregister callbacks in the given node and all parent nodes.
     *
     * @this {TransformTracker}
     * @param {Object} node (internal) the node to register. If not given the
     *  target node is taken.
     */
    p.detach = function(node)
    {
        if(this._attached)
        {
            if(!node)
                node = this.targetNode;

            if(node.tagName == "xml3d")
                return;

            if(node.tagName == "group")
            {
                node.removeEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onGrpAttrModified), false);

                var xfm = XMOT.util.transform(node);
                if(xfm)
                    node.removeEventListener("DOMAttrModified",
                        XMOT.util.wrapCallback(this, _onXfmAttrModified), false);
            }
            else if(node.tagName == "view")
            {
                node.removeEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onViewAttrModified), false);
            }

            this.detach(node.parentNode);

            this._attached = false;
        }
    };

    function _onGrpAttrModified(evt)
    {
        if(evt.attrName !== "transform")
            return;

        this.xfmChanged(this.targetNode, evt);
    };

    function _onViewAttrModified(evt)
    {
        if(evt.attrName !== "position"
        && evt.attrName !== "orientation")
            return;

        this.xfmChanged(this.targetNode, evt);
    };

    function _onXfmAttrModified(evt)
    {
        this.xfmChanged(this.targetNode, evt);
    };

    // export
    XMOT.TransformTracker = TransformTracker;
}());

<commit_msg>transformtracker: added optional constructor argument for callback<commit_after>(function() {
    /**
     * For the given node calls the handler method xfmChanged() when
     * the global transformation changed. This is the case if the transform
     * attribute of the target node or of one of the parent nodes changed.
     * Since transform attributes point to transform elements the transformation of
     * the target node also changes if corresponding transform elements are modified.
     *
     * This observer tracks only these changes, though. It does not track whether some local fields
     * of the target node change since it does not know which there might be.
     *
     * The observer registers itself as listener in all parent nodes that have a transform attribute
     * to find out when changes to that attribute happen.
     *
     * @constructor
     * @param {!Object} _targetNode the node to track
     * @param {function(targetNode:!Object,evt:!Event)=} onXfmChanged method that should be called when transformation changed
     */
    var TransformTracker = function(_targetNode, onXfmChanged)
    {
        if(!_targetNode)
            throw "TransformTracker: no target node specified.";

        this.xml3d = XMOT.util.getXml3dRoot(_targetNode);
        if(!this.xml3d)
            throw "TransformTracker: given node is not a child of an xml3d element.";

        this.targetNode = _targetNode;

        if(onXfmChanged)
        	this.xfmChanged = onXfmChanged;

        /** @private */
        this._attached = false;

        this.attach();
    };

    var p = TransformTracker.prototype;

    /** Event handler to be overriden by the user
     *
     * @param {!Object} targetNode the node this observer tracks
     * @param {!Event} evt the original DOM event that caused the change
     */
    p.xfmChanged = function(targetNode, evt) { };

    /**
     * Register callbacks in the given node and all parent nodes.
     *
     * @this {TransformTracker}
     * @param {!Object} [node] (internal) the node to register. If not given the
     *  target node is taken.
     */
    p.attach = function(node)
    {
        if(!this._attached)
        {
            if(!node)
                node = this.targetNode;

            if(node.tagName == "xml3d")
                return;

            if(node.tagName == "group")
            {
                node.addEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onGrpAttrModified), false);

                var xfm = XMOT.util.transform(node);
                if(xfm)
                    xfm.addEventListener("DOMAttrModified",
                        XMOT.util.wrapCallback(this, _onXfmAttrModified), false);
            }
            else if(node.tagName == "view")
            {
                node.addEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onViewAttrModified), false);
            }

            this.attach(node.parentNode);

            this._attached = true;
        }
    };

    /**
     * Deregister callbacks in the given node and all parent nodes.
     *
     * @this {TransformTracker}
     * @param {Object} node (internal) the node to register. If not given the
     *  target node is taken.
     */
    p.detach = function(node)
    {
        if(this._attached)
        {
            if(!node)
                node = this.targetNode;

            if(node.tagName == "xml3d")
                return;

            if(node.tagName == "group")
            {
                node.removeEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onGrpAttrModified), false);

                var xfm = XMOT.util.transform(node);
                if(xfm)
                    node.removeEventListener("DOMAttrModified",
                        XMOT.util.wrapCallback(this, _onXfmAttrModified), false);
            }
            else if(node.tagName == "view")
            {
                node.removeEventListener("DOMAttrModified",
                    XMOT.util.wrapCallback(this, _onViewAttrModified), false);
            }

            this.detach(node.parentNode);

            this._attached = false;
        }
    };

    function _onGrpAttrModified(evt)
    {
        if(evt.attrName !== "transform")
            return;

        this.xfmChanged(this.targetNode, evt);
    };

    function _onViewAttrModified(evt)
    {
        if(evt.attrName !== "position"
        && evt.attrName !== "orientation")
            return;

        this.xfmChanged(this.targetNode, evt);
    };

    function _onXfmAttrModified(evt)
    {
        this.xfmChanged(this.targetNode, evt);
    };

    // export
    XMOT.TransformTracker = TransformTracker;
}());

<|endoftext|>


<commit_before>'use strict';

(function($){
    $.confirm = function(params){
        if($('#confirm-dialog').length){
            $('#confirm-dialog').remove();
        }

        var markup = [
            '
' + params.msg,
            '',
            '
'
        ].join('');

        $(markup).hide().appendTo('body').fadeToggle(99);
        $("#confirm-dialog").dialog({
          resizable: false,
          height:120,
          width:350,
          modal: true,
          buttons: {
            "Confirm": function() {
                if(typeof params.url == 'function') {
                  params.url();
                  return;
                }
                document.location.href = params.url;
            },
            Cancel: function() {
              $(this).dialog("close");
            }
          }
        });
    }

})(jQuery);
<commit_msg>Auto close dialog with done<commit_after>'use strict';

(function($){
    $.confirm = function(params){
        if($('#confirm-dialog').length){
            $('#confirm-dialog').remove();
        }

        var markup = [
            '
' + params.msg,
            '',
            '
'
        ].join('');

        $(markup).hide().appendTo('body').fadeToggle(99);
        $("#confirm-dialog").dialog({
          resizable: false,
          height:200,
          width:350,
          modal: true,
          buttons: {
            "Confirm": function() {
                if(typeof params.url == 'function') {
                  params.url();
                  $('#confirm-dialog').dialog('close');
                  return;
                }
                document.location.href = params.url;
            },
            Cancel: function() {
              $(this).dialog("close");
            }
          }
        });
    }

})(jQuery);
<|endoftext|>


<commit_before>/*
 * Extended Neat Features Plugin
 * Draws introns and paints gradient subfeatures.
 */
/*
    Created on : Aug 5, 2015
    Author     : EY
*/

define([
        'dojo/_base/declare',
        'dojo/_base/lang',
        'dojo/Deferred',
        'dojo/dom-construct',
        'dojo/query',
        'JBrowse/Plugin'
       ],
       function(
        declare,
        lang,
        Deferred,
        domConstruct,
        query,
        JBrowsePlugin
       ) {
return declare( JBrowsePlugin,
{
    constructor: function( args ) {
        console.log("plugin: NeatHTMLFeatures");
        //console.dir(args);

        var thisB = this;
        var browser = this.browser;

        this.gradient = 1;
        if(typeof args.gradientFeatures != 'undefined' && args.gradientFeatures == 0) {
            this.gradient = 0;
        }

        // trap the redraw event for handling resize
        dojo.subscribe("/jbrowse/v1/n/tracks/redraw", function(data){
            setTimeout(function(){
                thisB.updateFeatures();
            }, 100);
        });

        // create function intercept after view initialization (because the view object doesn't exist before that)
        browser.afterMilestone( 'initView', function() {

            // reroute renderTrack function
            browser.view.oldRenderTrack = browser.view.renderTrack;

            // this is the replacement renderTrack function
            browser.view.renderTrack = function (trackConfig) {
                //console.log("view.renderTrack() intercepted!");

                // call the original renderTrack function
                var trackDiv = browser.view.oldRenderTrack(trackConfig);

                // we add neat-track class as a flag to indicate this is a track to be "painted"
                if(typeof trackConfig.gradientFeatures != 'undefined' && trackConfig.gradientFeatures != 0) {
                    dojo.addClass(trackDiv,"neat-track");
                }
                return trackDiv;
            };

        });

    },
    updateFeatures: function( args ) {
        //console.log("updateFeatures");

        var thisB = this;

        var divQuery = "div.feature";       // by default, paint all feature divs
        if (this.gradient==0)
            divQuery = "div.neat-track div.feature";    // paint only selected tracks

            query(divQuery).forEach(function(featureNode, index, arr){

                //console.dir(featureNode);

                // scan and insert introns, where applicable
                thisB.insertIntrons(featureNode);

                //Process Gradent Features
                thisB.paintGradientFeatures(featureNode);
            });

        //});
    },
    insertIntrons: function(featureNode) {

    var intronCount = 0;

        // ignore if we have already processed this node
        if (! dojo.hasClass(featureNode,"has-neat-introns")) {

            // get the subfeatures nodes (only immediate children)
            var subNodesX = query('> .subfeature',featureNode);

            // filter nodes - eliminate nodes that are splice sites (for Apollo)
            var subNodes = [];
            for(var i=0;i < subNodesX.length;i++){
                var attr = dojo.attr(subNodesX[i],"class");
                if (attr.indexOf("splice-site") === -1)
                    subNodes.push(subNodesX[i]);
            }

            if (subNodes.length) {

                // identify directionality
                var classAttr = dojo.attr(featureNode, "class")
                var direction = 1;
                if (classAttr.indexOf("minus") > -1) {
                    direction = -1;
                }
                //console.log("direction = "+ direction);

                //extract some left & width -  more convient to access
                for(var i=0; i < subNodes.length;i++) {
                    subNodes[i].left = dojo.getStyle(subNodes[i], "left");
                    subNodes[i].width = dojo.getStyle(subNodes[i], "width");
                }
                // sort the subfeatures
                if (subNodes.length >= 2) {
                    subNodes.sort(function(a, b){ return a.left - b.left; });
                }

                /* debug display subfeature list
                console.dir(subNodes);
                for(var i=0; i < subNodes.length;i++) {
                    console.log(i + " subfeature left,width: "+subNodes[i].left+", "+subNodes[i].width);
                }
                */

                // insert introns between subfeature gaps
                for(var i=0; i< subNodes.length-1;++i) {
                    var gap = subNodes[i+1].left-(subNodes[i].left+subNodes[i].width);
                    //console.log("gap "+gap);
                    if (gap > .02) {
                        //console.log("gap of "+gap+" between "+i+" and "+(i+1));

                        var subLeft = subNodes[i].left + subNodes[i].width;
                        var subWidth = subNodes[i+1].left - (subNodes[i].left + subNodes[i].width);

                        var left = subLeft;
                        var width = subWidth;
                        //console.log("inserting left "+subLeft+" width "+subWidth);

                        var height = "100%";

                        // invert hat if reverse direction
                        var dir = "50,5";
                        if (direction==-1) dir = "50,95";

                        var str = "";
                        str += "<svg class='jb-intron' viewBox='0 0 100 100' preserveAspectRatio='none' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' ";
                        str += "style='position:absolute;z-index: 15;";  // this must be here and not in CSS file
                        str += "left: "+left+"px;width: "+width+"px;height: "+height+"'>";
                        str += "<polyline points='0,50 "+ dir +" 100,50' style='fill:none;stroke:black;stroke-width:5' shape-rendering='optimizeQuality' />";
                        str += "</svg>";

                        // note: dojo.create("svg") does not render due to namespace issue between DOM and SVG

                        domConstruct.place(str, featureNode);

                        intronCount ++;

                    }
                }
                if (intronCount) {
                    // mark that we have processed this node
                    dojo.addClass(featureNode, "has-neat-introns");
                }
            }
        }
    },
    /*
     * Paint gradient features and subfeatures
     */
    paintGradientFeatures: function(featureNode) {

        // get the subfeature nodes (only immediate children)
        var subNodesX = query('> .subfeature',featureNode);
        var thisB = this;

        // filter nodes - eliminate nodes that are splice sites (for Apollo)
        var subNodes = [];
        for(var i=0;i < subNodesX.length;i++){
            var attr = dojo.attr(subNodesX[i],"class");
            if (attr.indexOf("splice-site") === -1)
                subNodes.push(subNodesX[i]);
        }

        // if feature has subfeatures
        if (subNodes.length) {

            dojo.setStyle(featureNode, {
                'background-color': 'transparent',
                'border-width':'0px'
            });

            // paint subfeatures
            for(var i=0;i < subNodes.length;i++) {

                // if this is Apollo, we have another subfeature level to traverse
                if (subNodes[i].childElementCount) {
                    // get the subfeature nodes (only immediate children)
                    var childNodes = query('> .subfeature',subNodes[i]);

                    for(var j=0;j<childNodes.length;j++){
                        thisB.paintSubNode(childNodes[j]);
                    }
                }
                // handle the first level subfeature
                else {
                    thisB.paintSubNode(subNodes[i]);
                }
            }

        }
        // paint features that have no subfeatures
        else {

            // ignore if we have already processed node
            if (! dojo.hasClass(featureNode,"neat-feature")) {

                var classAttr = dojo.attr(featureNode,'class');
                var color = dojo.getStyle(featureNode,'background-color');
                //console.log("F "+classAttr+" "+color);

                // update the element with new styling
                dojo.setStyle(featureNode, {
                    'background': 'linear-gradient(to bottom,  '+color+' 0%,#e5e5e5 50%,'+color+' 100%)'
                });
                // mark that we have processed the node
                dojo.addClass(featureNode, "neat-feature");
            }
        }

    },
    /*
     * apply gradient background to feature node
     */
    paintSubNode: function(subNode) {
        //console.log("paintSubNode");
        //console.dir(subNode);
        var classAttr = dojo.attr(subNode,'class');
        var color = dojo.getStyle(subNode,'background-color');
        //console.log(classAttr+" "+color);

        // ignore if we have already processed node
        if (! dojo.hasClass(subNode,"neat-subfeature")) {

            // restyle UTR
            if(classAttr.indexOf('UTR') > -1) {
                dojo.setStyle(subNode, {
                    //'background-color': 'white',
                    //'height': '100%',
                    'top': '0px',
                    //'margin-top': '0px',
                    'border': '1px solid '+color
                });
                // mark as neat subfeature
                dojo.addClass(subNode, "neat-UTR");
            }
            // restyle other subfeatures
            else {
            //if(classAttr.indexOf('CDS') > -1 || classAttr.indexOf('exon') > -1) {
                dojo.setStyle(subNode, {
                    //'height': '100%',
                    'top': '0px',
                    //'border-width': '0px',
                    'background': 'linear-gradient(to bottom,  '+color+' 0%,#e5e5e5 50%,'+color+' 100%)'
                });
            }
            // mark that we have processed the node
            dojo.addClass(subNode, "neat-subfeature");
        }

    }
});
});

<commit_msg>removed linear gradients<commit_after>/*
 * Extended Neat Features Plugin
 * Draws introns and paints gradient subfeatures.
 */
/*
    Created on : Aug 5, 2015
    Author     : EY
*/

define([
        'dojo/_base/declare',
        'dojo/_base/lang',
        'dojo/Deferred',
        'dojo/dom-construct',
        'dojo/query',
        'JBrowse/Plugin'
       ],
       function(
        declare,
        lang,
        Deferred,
        domConstruct,
        query,
        JBrowsePlugin
       ) {
return declare( JBrowsePlugin,
{
    constructor: function( args ) {
        console.log("plugin: NeatHTMLFeatures");
        //console.dir(args);

        var thisB = this;
        var browser = this.browser;

        this.gradient = 1;
        if(typeof args.gradientFeatures != 'undefined' && args.gradientFeatures == 0) {
            this.gradient = 0;
        }

        // trap the redraw event for handling resize
        dojo.subscribe("/jbrowse/v1/n/tracks/redraw", function(data){
            setTimeout(function(){
                thisB.updateFeatures();
            }, 100);
        });

        // create function intercept after view initialization (because the view object doesn't exist before that)
        browser.afterMilestone( 'initView', function() {

            // reroute renderTrack function
            browser.view.oldRenderTrack = browser.view.renderTrack;

            // this is the replacement renderTrack function
            browser.view.renderTrack = function (trackConfig) {
                //console.log("view.renderTrack() intercepted!");

                // call the original renderTrack function
                var trackDiv = browser.view.oldRenderTrack(trackConfig);

                // we add neat-track class as a flag to indicate this is a track to be "painted"
                if(typeof trackConfig.gradientFeatures != 'undefined' && trackConfig.gradientFeatures != 0) {
                    dojo.addClass(trackDiv,"neat-track");
                }
                return trackDiv;
            };

        });

    },
    updateFeatures: function( args ) {
        //console.log("updateFeatures");

        var thisB = this;

        var divQuery = "div.feature";       // by default, paint all feature divs
        if (this.gradient==0)
            divQuery = "div.neat-track div.feature";    // paint only selected tracks

            query(divQuery).forEach(function(featureNode, index, arr){

                //console.dir(featureNode);

                // scan and insert introns, where applicable
                thisB.insertIntrons(featureNode);

                //Process Gradent Features
                thisB.paintGradientFeatures(featureNode);
            });

        //});
    },
    insertIntrons: function(featureNode) {

    var intronCount = 0;

        // ignore if we have already processed this node
        if (! dojo.hasClass(featureNode,"has-neat-introns")) {

            // get the subfeatures nodes (only immediate children)
            var subNodesX = query('> .subfeature',featureNode);

            // filter nodes - eliminate nodes that are splice sites (for Apollo)
            var subNodes = [];
            for(var i=0;i < subNodesX.length;i++){
                var attr = dojo.attr(subNodesX[i],"class");
                if (attr.indexOf("splice-site") === -1)
                    subNodes.push(subNodesX[i]);
            }

            if (subNodes.length) {

                // identify directionality
                var classAttr = dojo.attr(featureNode, "class")
                var direction = 1;
                if (classAttr.indexOf("minus") > -1) {
                    direction = -1;
                }
                //console.log("direction = "+ direction);

                //extract some left & width -  more convient to access
                for(var i=0; i < subNodes.length;i++) {
                    subNodes[i].left = dojo.getStyle(subNodes[i], "left");
                    subNodes[i].width = dojo.getStyle(subNodes[i], "width");
                }
                // sort the subfeatures
                if (subNodes.length >= 2) {
                    subNodes.sort(function(a, b){ return a.left - b.left; });
                }

                /* debug display subfeature list
                console.dir(subNodes);
                for(var i=0; i < subNodes.length;i++) {
                    console.log(i + " subfeature left,width: "+subNodes[i].left+", "+subNodes[i].width);
                }
                */

                // insert introns between subfeature gaps
                for(var i=0; i< subNodes.length-1;++i) {
                    var gap = subNodes[i+1].left-(subNodes[i].left+subNodes[i].width);
                    //console.log("gap "+gap);
                    if (gap > .02) {
                        //console.log("gap of "+gap+" between "+i+" and "+(i+1));

                        var subLeft = subNodes[i].left + subNodes[i].width;
                        var subWidth = subNodes[i+1].left - (subNodes[i].left + subNodes[i].width);

                        var left = subLeft;
                        var width = subWidth;
                        //console.log("inserting left "+subLeft+" width "+subWidth);

                        var height = "100%";

                        // invert hat if reverse direction
                        var dir = "50,5";
                        if (direction==-1) dir = "50,95";

                        var str = "";
                        str += "<svg class='jb-intron' viewBox='0 0 100 100' preserveAspectRatio='none' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' ";
                        str += "style='position:absolute;z-index: 15;";  // this must be here and not in CSS file
                        str += "left: "+left+"px;width: "+width+"px;height: "+height+"'>";
                        str += "<polyline points='0,50 "+ dir +" 100,50' style='fill:none;stroke:black;stroke-width:5' shape-rendering='optimizeQuality' />";
                        str += "</svg>";

                        // note: dojo.create("svg") does not render due to namespace issue between DOM and SVG

                        domConstruct.place(str, featureNode);

                        intronCount ++;

                    }
                }
                if (intronCount) {
                    // mark that we have processed this node
                    dojo.addClass(featureNode, "has-neat-introns");
                }
            }
        }
    },
    /*
     * Paint gradient features and subfeatures
     */
    paintGradientFeatures: function(featureNode) {

        // get the subfeature nodes (only immediate children)
        var subNodesX = query('> .subfeature',featureNode);
        var thisB = this;

        // filter nodes - eliminate nodes that are splice sites (for Apollo)
        var subNodes = [];
        for(var i=0;i < subNodesX.length;i++){
            var attr = dojo.attr(subNodesX[i],"class");
            if (attr.indexOf("splice-site") === -1)
                subNodes.push(subNodesX[i]);
        }

        // if feature has subfeatures
        if (subNodes.length) {

            dojo.setStyle(featureNode, {
                'background-color': 'transparent',
                'border-width':'0px'
            });

            // paint subfeatures
            for(var i=0;i < subNodes.length;i++) {

                // if this is Apollo, we have another subfeature level to traverse
                if (subNodes[i].childElementCount) {
                    // get the subfeature nodes (only immediate children)
                    var childNodes = query('> .subfeature',subNodes[i]);

                    for(var j=0;j<childNodes.length;j++){
                        thisB.paintSubNode(childNodes[j]);
                    }
                }
                // handle the first level subfeature
                else {
                    thisB.paintSubNode(subNodes[i]);
                }
            }

        }
        // paint features that have no subfeatures
        else {

            // ignore if we have already processed node
            if (! dojo.hasClass(featureNode,"neat-feature")) {

                var classAttr = dojo.attr(featureNode,'class');
                var color = dojo.getStyle(featureNode,'background-color');
                //console.log("F "+classAttr+" "+color);

                // update the element with new styling
                dojo.setStyle(featureNode, {
                    'background': 'linear-gradient(to bottom,  '+color+' 0%,#e5e5e5 50%,'+color+' 100%)'
                });
                // mark that we have processed the node
                dojo.addClass(featureNode, "neat-feature");
            }
        }

    },
    /*
     * apply gradient background to feature node
     */
    paintSubNode: function(subNode) {
        //console.log("paintSubNode");
        //console.dir(subNode);
        var classAttr = dojo.attr(subNode,'class');
        var color = dojo.getStyle(subNode,'background-color');
        //console.log(classAttr+" "+color);

        // ignore if we have already processed node
        if (! dojo.hasClass(subNode,"neat-subfeature")) {

            // restyle UTR
            if(classAttr.indexOf('UTR') > -1) {
                dojo.setStyle(subNode, {
                    //'background-color': 'white',
                    //'height': '100%',
                    'top': '0px',
                    //'margin-top': '0px',
                    'border': '1px solid '+color
                });
                // mark as neat subfeature
                dojo.addClass(subNode, "neat-UTR");
            }
            // restyle other subfeatures
            else {
            //if(classAttr.indexOf('CDS') > -1 || classAttr.indexOf('exon') > -1) {
//                dojo.setStyle(subNode, {
//                    //'height': '100%',
//                    'top': '0px',
//                    //'border-width': '0px',
//                    'background': 'linear-gradient(to bottom,  '+color+' 0%,#e5e5e5 50%,'+color+' 100%)'
//                });
            }
            // mark that we have processed the node
            dojo.addClass(subNode, "neat-subfeature");
        }

    }
});
});

<|endoftext|>


<commit_before>var redis = require("redis");
var express = require("express");

var app = express();

var db = redis.createClient();
db.select(8, function(err, replies) {
    app.listen(3000);
    console.log("Listening on port 3000.");
});

var hex = "0123456789abcdef";
var hexID = function(len) {
    var id = [];
    for(var i = 0; i < 16; i++) {
        id.push(hex[Math.floor(Math.random() * hex.length)]);
    }
    return id.join("");
}

var sendMoves = function(req, res) {
    db.lrange(req.id, 0, -1, function(err, replies) {
        res.json({"moves" : replies, "player": req.player});
    });
}

var moveRE = /^[a-h][0-7]-[a-h][0-7][qrbnp]?$/

app.use(express.logger());
app.use('/js', express.static(__dirname + '/static/js'));
app.use('/pieces', express.static(__dirname + '/static/pieces'));

app.get('/game', function(req, res) {
    res.sendfile(__dirname + "/static/page.html");
});

app.get('/new', function(req, res) {
    res.sendfile(__dirname + "/static/new.html");
});

app.get('/health', function(req, res) {
  res.send({
    pid: process.pid,
    memory: process.memoryUsage(),
    uptime: process.uptime()
  })
})

app.post("/new", function(req, res) {
    var root = hexID();
    var ids = {}
    ids.white = hexID();
    ids.black = hexID();
    ids.spec = hexID();
    db.multi()
        .set(ids.white, "white:" + root)
        .set(ids.black, "black:" + root)
        .set(ids.spec, "spec:" + root)
        .exec(function(err, replies) {
            res.json(ids);
        })
});

var gameID = /^([^:]+):(.*)/

var route = /^\/([a-f0-9]{16})$/
app.all(route, function(req, res, next) {
    db.get(req.params[0], function(err, replies) {
        if(replies === null) {
            res.send(404, "game doesn't exist!");
            res.end();
        }
        else {
            var info = replies.match(gameID);
            req.id = info[2] + ":moves";
            req.player = info[1];
            console.log("%s => %s %s", req.params[0], req.player, req.id);
            db.llen(req.id, function(err, replies) {
                req.turn = replies;
                console.log("turn: %s", req.turn);
                next();
            });
        }
    });
});

app.get(route, function(req, res) {
    sendMoves(req, res);
});

app.post(route, function(req, res) {
    if(moveRE.exec(req.param("move")) === null) {
        res.send(422, "invalid move!");
        res.end();
    }
    else {
        db.watch(req.id);
        db.llen(req.id, function(err, len) {
            if(parseInt(req.param("turn")) !== len) {
                res.send(422, "wrong turn: " + len + " not " +
                         req.param("turn") + "!");
                res.end();
            }
            else {
                db.multi()
                    .rpush(req.id, req.param("move"))
                    .exec(function() { sendMoves(req, res) });
            }
        });
    }
});
<commit_msg>Organize and comment the root chess.js routes.<commit_after>/* This is just a dumb server that records rules for now. It'd be nice to
   implement rules checking in the future (that's actually the primary reason
   I decided to go with Node on the server - no need to duplicate code that
   checks move validity. */
var redis = require("redis");
var express = require("express");

var app = express();

var db = redis.createClient();
db.select(8, function(err, replies) {
    app.listen(3000);
    console.log("Listening on port 3000.");
});

var hex = "0123456789abcdef";
var hexID = function(len) {
    var id = [];
    for(var i = 0; i < 16; i++) {
        id.push(hex[Math.floor(Math.random() * hex.length)]);
    }
    return id.join("");
}

app.use(express.logger());

/* Static Routes */
app.use('/js', express.static(__dirname + '/static/js'));
app.use('/pieces', express.static(__dirname + '/static/pieces'));

app.get('/game', function(req, res) {
    res.sendfile(__dirname + "/static/page.html");
});

app.get('/new', function(req, res) {
    res.sendfile(__dirname + "/static/new.html");
});

/* Health monitoring endpoint. */
app.get('/health', function(req, res) {
  res.send({
    pid: process.pid,
    memory: process.memoryUsage(),
    uptime: process.uptime()
  })
})

/* This route is POSTed to by the static /new page when a new game is
   requested. */
app.post("/new", function(req, res) {
    var root = hexID();
    var ids = {}
    ids.white = hexID();
    ids.black = hexID();
    ids.spec = hexID();
    db.multi()
        .set(ids.white, "white:" + root)
        .set(ids.black, "black:" + root)
        .set(ids.spec, "spec:" + root)
        .exec(function(err, replies) {
            res.json(ids);
        })
});

var gameID = /^([^:]+):(.*)/

/* Game view / move routes */
var route = /^\/([a-f0-9]{16})$/
app.all(route, function(req, res, next) {
    db.get(req.params[0], function(err, replies) {
        if(replies === null) {
            res.send(404, "game doesn't exist!");
            res.end();
        }
        else {
            var info = replies.match(gameID);
            req.id = info[2] + ":moves";
            req.player = info[1];
            console.log("%s => %s %s", req.params[0], req.player, req.id);
            db.llen(req.id, function(err, replies) {
                req.turn = replies;
                console.log("turn: %s", req.turn);
                next();
            });
        }
    });
});

var sendMoves = function(req, res) {
    db.lrange(req.id, 0, -1, function(err, replies) {
        res.json({"moves" : replies, "player": req.player});
    });
}

app.get(route, function(req, res) {
    sendMoves(req, res);
});

var moveRE = /^[a-h][0-7]-[a-h][0-7][qrbnp]?$/
app.post(route, function(req, res) {
    if(moveRE.exec(req.param("move")) === null) {
        res.send(422, "invalid move!");
        res.end();
    }
    else {
        db.watch(req.id);
        db.llen(req.id, function(err, len) {
            if(parseInt(req.param("turn")) !== len) {
                res.send(422, "wrong turn: " + len + " not " +
                         req.param("turn") + "!");
                res.end();
            }
            else {
                db.multi()
                    .rpush(req.id, req.param("move"))
                    .exec(function() { sendMoves(req, res) });
            }
        });
    }
});
<|endoftext|>