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

	var ScrollGallery = function(options) {
		var defaults = {
			PageSize: 3,
			Page: 0,
			RankAttribute: "sg-rank",
			Selectors : {
				Gallery: null,
				Next :  null,
				Previous: null,
				Indicators: null
			},
			IndicatorOptions: {
				Rounded: true,
				ShowPageNumber: false,
				ClickToJump: true
			}
		};

		options = $.extend(defaults, options);

		var rankAttribute = "data-"+ options.RankAttribute;

		var itemCount;

		function rankElements() {
			var $elements = $(options.Selectors.Gallery).find("*");
			$elements.each(function (i, element) {
				$(element).attr(rankAttribute,i);
			});
		}

		function makeElementsClassy() {
			$(options.Selectors.Gallery).addClass("scroll-gallery");
			var $elements = $(options.Selectors.Gallery).find("*");
			$elements.each(function (i, element) {
				$(element).addClass("scroll-gallery-element");
			});
		}

		function refreshItemCount() {
			itemCount = $(options.Selectors.Gallery).find("["+rankAttribute+"]").length;
		}

		function hasNextPage() {
			return (options.Page+1)*options.PageSize < itemCount;
		}

		function hasPreviousPage() {
			return options.Page > 0;
		}

		function checkButtons() {
			$(options.Selectors.Next).prop("disabled", !hasNextPage());
			$(options.Selectors.Previous).prop("disabled", !hasPreviousPage());
		}

		function scrollTo() {
			var $scrollElement = $(options.Selectors.Gallery).find("[" + rankAttribute+"='"+[options.Page * options.PageSize]+"']");

			var layout = ($scrollElement.outerWidth(true)-$scrollElement.innerWidth()) / 2;

			var pageAdjustment = options.Page > 0 ? layout : 0;

			var $parent = $scrollElement.parent();

			var elementScrollLeft = ($scrollElement.position().left - layout) + $parent.scrollLeft() + pageAdjustment - $parent.offset().left;

			$(options.Selectors.Gallery).stop().animate({ scrollLeft: elementScrollLeft }, 1000);
		}

		function createIndicators() {
			var container = $(options.Selectors.Indicators);
			var ul = $("

");
			if(options.IndicatorOptions.ShowPageNumber) {
				ul.attr("show-page-number",'');
			}
			if(options.IndicatorOptions.Rounded) {
				ul.attr("rounded", '');
			}
			for(var i = 0; i<Math.ceil(itemCount/options.PageSize); i++) {
				ul.append("
"+i+"
");
			}

			container.append(ul);

			$(options.Selectors.Indicators).find("[data-page-number]").on("click", function () {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: parseInt($(this).data("page-number"))-1
				});
			});
		}

		function checkIndicators () {
			$(options.Selectors.Indicators).find("[data-page-number]").removeAttr("current-page");
			$(options.Selectors.Indicators).find("[data-page-number="+(options.Page+1)+"]").attr("current-page", '');
		}

		function onPageChanged(event, data) {
			options.Page = data.Page;
			scrollTo();
			checkButtons();
			checkIndicators();
		}

		function onNextPage() {
			if (hasNextPage()) {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: options.Page + 1
				});
			}
		}

		function onPreviousPage() {
			if (hasPreviousPage()) {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: options.Page - 1
				});
			}
		}

		function initialize() {
			$(options.Selectors.Gallery).on("page-changed", onPageChanged);
			$(options.Selectors.Next).on("click", onNextPage);
			$(options.Selectors.Previous).on("click", onPreviousPage);

			rankElements();
			makeElementsClassy();
			refreshItemCount();

			if($(options.Selectors.Indicators).length) {
				createIndicators();
			}

			checkButtons();
			checkIndicators();
		}

		initialize();
	};

	window.ScrollGallery = window.ScrollGallery || ScrollGallery;
})();<commit_msg>RankAttribute => Prefix<commit_after>(function() {
	"use strict";

	var ScrollGallery = function(options) {
		var defaults = {
			PageSize: 3,
			Page: 0,
			Prefix: "sg",
			MaintainScrollPosition: false,
			Selectors : {
				Gallery: null,
				Next :  null,
				Previous: null,
				Indicators: null
			},
			IndicatorOptions: {
				Rounded: true,
				ShowPageNumber: false,
				ClickToJump: true
			}
		};

		options = $.extend(defaults, options);

		var Prefix = "data-"+ options.Prefix;

		var itemCount;

		function rankElements() {
			var $elements = $(options.Selectors.Gallery).find("*");
			$elements.each(function (i, element) {
				$(element).attr(Prefix+"-rank"	,i);
			});
		}

		function makeElementsClassy() {
			$(options.Selectors.Gallery).addClass("scroll-gallery");
			var $elements = $(options.Selectors.Gallery).find("*");
			$elements.each(function (i, element) {
				$(element).addClass("scroll-gallery-element");
			});
		}

		function refreshItemCount() {
			itemCount = $(options.Selectors.Gallery).find("["+Prefix+"-rank]").length;
		}

		function hasNextPage() {
			return (options.Page+1)*options.PageSize < itemCount;
		}

		function hasPreviousPage() {
			return options.Page > 0;
		}

		function checkButtons() {
			$(options.Selectors.Next).prop("disabled", !hasNextPage());
			$(options.Selectors.Previous).prop("disabled", !hasPreviousPage());
		}

		function scrollTo() {
			var $scrollElement = $(options.Selectors.Gallery).find("[" + Prefix+"-rank='"+[options.Page * options.PageSize]+"']");

			var layout = ($scrollElement.outerWidth(true)-$scrollElement.innerWidth()) / 2;

			var pageAdjustment = options.Page > 0 ? layout : 0;

			var $parent = $scrollElement.parent();

			var elementScrollLeft = ($scrollElement.position().left - layout) + $parent.scrollLeft() + pageAdjustment - $parent.offset().left;

			$(options.Selectors.Gallery).stop().animate({ scrollLeft: elementScrollLeft }, 1000);
		}

		function createIndicators() {
			var container = $(options.Selectors.Indicators);
			var ul = $("

");
			if(options.IndicatorOptions.ShowPageNumber) {
				ul.attr("show-page-number",'');
			}
			if(options.IndicatorOptions.Rounded) {
				ul.attr("rounded", '');
			}
			for(var i = 0; i<Math.ceil(itemCount/options.PageSize); i++) {
				ul.append("
"+i+"
");
			}

			container.append(ul);

			$(options.Selectors.Indicators).find("[data-page-number]").on("click", function () {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: parseInt($(this).data("page-number"))-1
				});
			});
		}

		function checkIndicators () {
			$(options.Selectors.Indicators).find("[data-page-number]").removeAttr("current-page");
			$(options.Selectors.Indicators).find("[data-page-number="+(options.Page+1)+"]").attr("current-page", '');
		}

		function onPageChanged(event, data) {
			options.Page = data.Page;
			scrollTo();
			checkButtons();
			checkIndicators();
		}

		function onNextPage() {
			if (hasNextPage()) {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: options.Page + 1
				});
			}
		}

		function onPreviousPage() {
			if (hasPreviousPage()) {
				$(options.Selectors.Gallery).trigger("page-changed", {
					Page: options.Page - 1
				});
			}
		}

		function initialize() {
			if(!options.MaintainScrollPosition) {
				$(document).ready(function() {
					$(options.Selectors.Gallery).scrollLeft(0);
				});
			}
			$(options.Selectors.Gallery).on("page-changed", onPageChanged);
			$(options.Selectors.Next).on("click", onNextPage);
			$(options.Selectors.Previous).on("click", onPreviousPage);

			rankElements();
			makeElementsClassy();
			refreshItemCount();

			checkButtons();
			if($(options.Selectors.Indicators).length) {
				createIndicators();
				checkIndicators();
			}

		}

		initialize();
	};

	window.ScrollGallery = window.ScrollGallery || ScrollGallery;
})();<|endoftext|>


<commit_before>class Requester {
  constructor(){
    this.counter = 0;
    this.message = "Ready.";
    this.timeout = window.setTimeout(0);
  }

  update_state(message){
    this.counter += 1;
    if (this.message != message){
      // do we have a different message? change it!
      // will toggle modal to show here
      this.message = message;
      clearTimeout(this.timeout)
      if (this.message != "Ready.") {
        $.notify(this.message,
          { className: 'info', globalPosition: 'top center' })
        console.log(this.message)
      }
      else if ((this.message == "Ready.") && (this.counter%2 == 0)){
        // timeout here will hide modal. need even number of sent
        // and completed ajax requests and a "Ready" message for 2s
        this.timeout = window.setTimeout(() => {$.notify(this.message,
          { className: 'success', globalPosition: 'top center' })}, 2000)
        console.log(this.message)
      }
    }
  }

  grabJSON (url, dtype='json') {
    var ajax_params = {
      "url": url,
      "dataType": dtype,
    }
    ajax_params["beforeSend"] = () => (this.update_state("Getting JSON."))
    ajax_params["complete"] = () => (this.update_state("Ready."))
    return $.ajax(ajax_params);
  }

  make_request (ajax_params, message) {
    var ajax_params = ajax_params;
    ajax_params["beforeSend"] = () => (this.update_state(message))
    ajax_params["complete"] = () => (this.update_state("Ready."))
    return $.ajax(ajax_params);
  }

  txtProcess(txt, parser) {
    var input_txt = {'text':txt};
    var ajax_params = {
      "url": indra_server_addr + "/"+ parser + "/process_text",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt)
    };
    var message = ("Processing text.");
    stmts = this.make_request(ajax_params, message)
    return stmts
  }

  groundingMapper(res) {
    var ajax_params = {
      "url": indra_server_addr + "/preassembly/map_grounding",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res),
    };
    var message = ("Grounding INDRA statements.");
    stmts = this.make_request(ajax_params, message)
    return stmts
  }

  getEvidence(res) {
    var ajax_params = {
      "url": indra_server_addr + "/indra_db_rest/get_evidence",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res),
      }
    var message = ("Querying INDRA DB for statement evidence.");
    var stmts_db = this.make_request(ajax_params, message)
    return stmts_db
  }

  assembleCyJS(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/cyjs",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Assembling CytoscapeJS model.");
    var cyjs_model = this.make_request(ajax_params, message)
    return cyjs_model
  }

  assembleEnglish(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/english",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Assembling English language sentences for each statement.");
    var sentences = this.make_request(ajax_params, message)
    return sentences
  }

  assembleCX(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/cx",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    res_json['cyjs_model'] = JSON.stringify(cy.json())
    var message = ("Assembling Cytoscape CX model.");
    var cx_model = this.make_request(ajax_params, message)
    return cx_model
  }

  shareNDEX(model_elements, preset_pos, stmts, sentences, evidence, cell_line,
            mrna, mutations, txt_input, parser) {
    var res_json = {};
    res_json['stmts'] = JSON.stringify(stmts);
    res_json['model_elements'] = JSON.stringify(model_elements);
    res_json['preset_pos'] = JSON.stringify(preset_pos);
    res_json['sentences'] = JSON.stringify(sentences);
    res_json['evidence'] = JSON.stringify(evidence);
    res_json['cell_line'] = cell_line;
    res_json['mrna'] = JSON.stringify(mrna);
    res_json['mutations'] = JSON.stringify(mutations);
    res_json['txt_input'] = txt_input;
    res_json['parser'] = parser;
    var ajax_params = {
      "url": indra_server_addr + "/share_model_ndex",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Uploading model to NDEX.");
    var ndex_push = this.make_request(ajax_params, message)
    return ndex_push;
  }

  getNDEX(network_id) {
    var res_json = {"network_id": network_id};
    var ajax_params = {
      "url": indra_server_addr + "/fetch_model_ndex",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Downloading model from NDEX.");
    var ndex_pull = this.make_request(ajax_params, message)
    return ndex_pull;
  }

  requestPySB(res, export_format, message) {
    var res_json = res;
    res_json['export_format'] = export_format;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/pysb",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var pysb_model = this.make_request(ajax_params, message)
    return pysb_model
  }

  assemblePySB(res) {
    var message = "Assembling PySB model."
    return this.requestPySB(res, null, message);
  }

  assembleSBML(res) {
    var message = "Assembling SBML model."
    return this.requestPySB(res, 'sbml', message);
  }

  assembleSBGN(res) {
    var message = "Assembling SBGN model."
    return this.requestPySB(res, 'sbgn', message);
  }

  assembleBNGL(res) {
    var message = "Assembling BNGL model."
    return this.requestPySB(res, 'bngl', message);
  }

  assembleKappa(res) {
    var message = "Assembling Kappa model."
    return this.requestPySB(res, 'kappa', message);
  }

  get_ccle_mrna(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_mrna",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
     }
     var message = ("Retreiving CCLE mRNA expression.");
     var mrna = this.make_request(ajax_params, message);
     return mrna
  }

  get_ccle_cna(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_cna",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
    }
    var message = ("Getting CCLE CNA.");
    var cna = this.make_request(ajax_params, message);
    return cna
  }

  get_ccle_mutations(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_mutations",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
     }
    var message = ("Getting CCLE mutation status.");
    var mutations = this.make_request(ajax_params, message);
    return mutations
  }
}

//build bootstrap-select dropdown using json
//***************************************
function dropdownFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(name));
    });
  $('.selectpicker').selectpicker('refresh');
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownCtxtSelectFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(file));
    });
}
//***************************************

//download a model
//***************************************
function download(exportName, exportObj){
  if (exportName.includes('.png')){
    encoding_type = "image/png";
    var data = atob( exportObj.substring( "data:image/png;base64,".length ) ),
    asArray = new Uint8Array(data.length);
    for( var i = 0, len = data.length; i < len; ++i ) {
        asArray[i] = data.charCodeAt(i);
    }
    var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
  }
  else {
    var blob = new Blob([exportObj], {type: "text/plain;charset=utf-8"});
  }
  saveAs(blob, exportName);
}

function assembleLoopy(res) {
  var res_json = res;
  return $.ajax({
      url: indra_server_addr + "/assemblers/sif/loopy",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function bind_this (target) {
// taken from https://ponyfoo.com/articles/binding-methods-to-class-instance-objects
  const cache = new WeakMap();
  const handler = {
    get (target, key) {
      const value = Reflect.get(target, key);
      if (typeof value !== 'function') {
        return value;
      }
      if (!cache.has(value)) {
        cache.set(value, value.bind(target));
      }
      return cache.get(value);
    }
  };
  const proxy = new Proxy(target, handler);
  return proxy;
}
<commit_msg>fix bug which was modifying stmts object passed to assemblers<commit_after>class Requester {
  constructor(){
    this.counter = 0;
    this.message = "Ready.";
    this.timeout = window.setTimeout(0);
  }

  update_state(message){
    this.counter += 1;
    if (this.message != message){
      // do we have a different message? change it!
      // will toggle modal to show here
      this.message = message;
      clearTimeout(this.timeout)
      if (this.message != "Ready.") {
        $.notify(this.message,
          { className: 'info', globalPosition: 'top center' })
        console.log(this.message)
      }
      else if ((this.message == "Ready.") && (this.counter%2 == 0)){
        // timeout here will hide modal. need even number of sent
        // and completed ajax requests and a "Ready" message for 2s
        this.timeout = window.setTimeout(() => {$.notify(this.message,
          { className: 'success', globalPosition: 'top center' })}, 2000)
        console.log(this.message)
      }
    }
  }

  grabJSON (url, dtype='json') {
    var ajax_params = {
      "url": url,
      "dataType": dtype,
    }
    ajax_params["beforeSend"] = () => (this.update_state("Getting JSON."))
    ajax_params["complete"] = () => (this.update_state("Ready."))
    return $.ajax(ajax_params);
  }

  make_request (ajax_params, message) {
    var ajax_params = ajax_params;
    ajax_params["beforeSend"] = () => (this.update_state(message))
    ajax_params["complete"] = () => (this.update_state("Ready."))
    return $.ajax(ajax_params);
  }

  txtProcess(txt, parser) {
    var input_txt = {'text':txt};
    var ajax_params = {
      "url": indra_server_addr + "/"+ parser + "/process_text",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt)
    };
    var message = ("Processing text.");
    stmts = this.make_request(ajax_params, message)
    return stmts
  }

  groundingMapper(res) {
    var ajax_params = {
      "url": indra_server_addr + "/preassembly/map_grounding",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res),
    };
    var message = ("Grounding INDRA statements.");
    stmts = this.make_request(ajax_params, message)
    return stmts
  }

  getEvidence(res) {
    var ajax_params = {
      "url": indra_server_addr + "/indra_db_rest/get_evidence",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res),
      }
    var message = ("Querying INDRA DB for statement evidence.");
    var stmts_db = this.make_request(ajax_params, message)
    return stmts_db
  }

  assembleCyJS(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/cyjs",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Assembling CytoscapeJS model.");
    var cyjs_model = this.make_request(ajax_params, message)
    return cyjs_model
  }

  assembleEnglish(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/english",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Assembling English language sentences for each statement.");
    var sentences = this.make_request(ajax_params, message)
    return sentences
  }

  assembleCX(res) {
    var res_json = res;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/cx",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Assembling Cytoscape CX model.");
    var cx_model = this.make_request(ajax_params, message)
    return cx_model
  }

  shareNDEX(model_elements, preset_pos, stmts, sentences, evidence, cell_line,
            mrna, mutations, txt_input, parser) {
    var res_json = {};
    res_json['stmts'] = JSON.stringify(stmts);
    res_json['model_elements'] = JSON.stringify(model_elements);
    res_json['preset_pos'] = JSON.stringify(preset_pos);
    res_json['sentences'] = JSON.stringify(sentences);
    res_json['evidence'] = JSON.stringify(evidence);
    res_json['cell_line'] = cell_line;
    res_json['mrna'] = JSON.stringify(mrna);
    res_json['mutations'] = JSON.stringify(mutations);
    res_json['txt_input'] = txt_input;
    res_json['parser'] = parser;
    var ajax_params = {
      "url": indra_server_addr + "/share_model_ndex",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Uploading model to NDEX.");
    var ndex_push = this.make_request(ajax_params, message)
    return ndex_push;
  }

  getNDEX(network_id) {
    var res_json = {"network_id": network_id};
    var ajax_params = {
      "url": indra_server_addr + "/fetch_model_ndex",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var message = ("Downloading model from NDEX.");
    var ndex_pull = this.make_request(ajax_params, message)
    return ndex_pull;
  }

  requestPySB(stmts, export_format, message) {
    var res_json = {};
    res_json['statements'] = stmts['statements']
    res_json['export_format'] = export_format;
    var ajax_params = {
      "url": indra_server_addr + "/assemblers/pysb",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(res_json),
    }
    var pysb_model = this.make_request(ajax_params, message)
    return pysb_model
  }

  assemblePySB(res) {
    var message = "Assembling PySB model."
    return this.requestPySB(res, null, message);
  }

  assembleSBML(res) {
    var message = "Assembling SBML model."
    return this.requestPySB(res, 'sbml', message);
  }

  assembleSBGN(res) {
    var message = "Assembling SBGN model."
    return this.requestPySB(res, 'sbgn', message);
  }

  assembleBNGL(res) {
    var message = "Assembling BNGL model."
    return this.requestPySB(res, 'bngl', message);
  }

  assembleKappa(res) {
    var message = "Assembling Kappa model."
    return this.requestPySB(res, 'kappa', message);
  }

  get_ccle_mrna(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_mrna",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
     }
     var message = ("Retreiving CCLE mRNA expression.");
     var mrna = this.make_request(ajax_params, message);
     return mrna
  }

  get_ccle_cna(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_cna",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
    }
    var message = ("Getting CCLE CNA.");
    var cna = this.make_request(ajax_params, message);
    return cna
  }

  get_ccle_mutations(gene_list, cell_line) {
    var input_txt = {'gene_list': gene_list,
                     'cell_lines': [cell_line]};
    var ajax_params = {
      "url": indra_server_addr + "/databases/cbio/get_ccle_mutations",
      "type": "POST",
      "dataType": "json",
      "data": JSON.stringify(input_txt),
     }
    var message = ("Getting CCLE mutation status.");
    var mutations = this.make_request(ajax_params, message);
    return mutations
  }
}

//build bootstrap-select dropdown using json
//***************************************
function dropdownFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(name));
    });
  $('.selectpicker').selectpicker('refresh');
}
//***************************************

//build bootstrap-select dropdown using json
//***************************************
function dropdownCtxtSelectFromJSON (div_id, ajax_response) {
  $.each(ajax_response, function(name, file) {
       $(div_id).append($('<option/>').attr("value", file).text(file));
    });
}
//***************************************

//download a model
//***************************************
function download(exportName, exportObj){
  if (exportName.includes('.png')){
    encoding_type = "image/png";
    var data = atob( exportObj.substring( "data:image/png;base64,".length ) ),
    asArray = new Uint8Array(data.length);
    for( var i = 0, len = data.length; i < len; ++i ) {
        asArray[i] = data.charCodeAt(i);
    }
    var blob = new Blob( [ asArray.buffer ], {type: "image/png"} );
  }
  else {
    var blob = new Blob([exportObj], {type: "text/plain;charset=utf-8"});
  }
  saveAs(blob, exportName);
}

function assembleLoopy(res) {
  var res_json = res;
  return $.ajax({
      url: indra_server_addr + "/assemblers/sif/loopy",
      type: "POST",
      dataType: "json",
      data: JSON.stringify(res_json),
  });
}

function bind_this (target) {
// taken from https://ponyfoo.com/articles/binding-methods-to-class-instance-objects
  const cache = new WeakMap();
  const handler = {
    get (target, key) {
      const value = Reflect.get(target, key);
      if (typeof value !== 'function') {
        return value;
      }
      if (!cache.has(value)) {
        cache.set(value, value.bind(target));
      }
      return cache.get(value);
    }
  };
  const proxy = new Proxy(target, handler);
  return proxy;
}
<|endoftext|>


<commit_before>var https = require("https");
var http = require("http");
var fs   = require("fs");
var url = require('url');
var semver = require('semver');

/*

// https://github.com/mapbox/node-pre-gyp/wiki/Node-ABI
node scripts/abi_crosswalk.js > lib/util/abi_crosswalk.json

*/

var cross = {};

var template = 'https://raw.github.com/joyent/node/v{VERSION}/src/';
var v8template = 'https://raw.github.com/joyent/node/v{VERSION}/deps/v8/src/version.cc';

var sortObjectByKey = function(obj){
    var keys = [];
    var sorted_obj = {};
    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            keys.push(key);
        }
    }
    // sort keys
    keys.sort(function(a,b) {
      if (semver.gt(a, b)) {
        return 1
      }
      return -1;
    });
    len = keys.length;

    for (i = 0; i < len; i++)
    {
      key = keys[i];
      sorted_obj[key] = obj[key];
    }
    return sorted_obj;
};

function get(ver,callback) {
  var header = 'node.h';
  if (semver.gt(ver, 'v0.11.4')) {
    // https://github.com/joyent/node/commit/44ed42bd971d58b294222d983cfe2908e021fb5d#src/node_version.h
    header = 'node_version.h';
  }
  var path = template.replace('{VERSION}',ver) + header;
  var uri = url.parse(path);
  https.get(uri, function(res) {
      if (res.statusCode != 200) {
        throw new Error("server returned " + res.statusCode + ' for: ' + path);
      }
      res.setEncoding('utf8');
      var body = '';
      res.on('data', function (chunk) {
        body += chunk;
      });
      res.on('end',function(err) {
        var term = 'define NODE_MODULE_VERSION'
        var idx = body.indexOf(term);
        var following = body.slice(idx);
        var end = following.indexOf('\n');
        var value = following.slice(term.length,end).trim();
        if (value[0] === '(' && value[value.length-1] == ')') {
          value = value.slice(1,value.length-1);
        } else if (value.indexOf(' ') > -1) {
          value = value.slice(0,value.indexOf(' '));
        }
        var int_val = +value;
        if (int_val != undefined) {
          // TODO - if val is 1 then we need to get the v8 version from
          // https://github.com/joyent/node/blob/master/deps/v8/src/version.cc
          var v8path = v8template.replace('{VERSION}',ver);
          var v8uri = url.parse(v8path);
          https.get(v8uri, function(res) {
              if (res.statusCode != 200) {
                throw new Error("server returned " + res.statusCode + ' for: ' + path);
              }
              res.setEncoding('utf8');
              var body = '';
              res.on('data', function (chunk) {
                body += chunk;
              });
              res.on('end',function(err) {
                  var term = 'define MAJOR_VERSION'
                  var idx = body.indexOf(term);
                  var following = body.slice(idx);
                  var end = following.indexOf('\n');
                  var major = following.slice(term.length,end).trim();
                  var term1 = 'define MINOR_VERSION'
                  var idx1 = body.indexOf(term1);
                  var following1 = body.slice(idx1);
                  var end1 = following1.indexOf('\n');
                  var minor = following1.slice(term1.length,end1).trim();
                  var v8_version = major+'.'+minor;
                  return callback(null,ver,int_val,v8_version);
              });
          });
        }
      })
    });
}

process.on('exit', function(err) {
    var sorted = sortObjectByKey(cross);
    console.log(JSON.stringify(sorted,null,2));
})

var versions_doc = 'http://nodejs.org/dist/npm-versions.txt';
http.get(url.parse(versions_doc), function(res) {
    if (res.statusCode != 200) {
      throw new Error("server returned " + res.statusCode + ' for: ' + versions_doc);
    }
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end',function(err) {
      var lines = body.split('\n').map(function(line) { return line.split(' ')[0].slice(1); }).filter(function(line) { return (line.length && line != 'node'); });
      lines.forEach(function(ver) {
          get(ver,function(err,version,node_abi,v8_version) {
            cross[version] = {node_abi:node_abi,v8:v8_version};
          });
      });
    });
});

/*
get("0.8.1",function(err,version,node_abi,v8_version) {
    cross[version] = {node_abi:node_abi,v8:v8_version};
});
*/<commit_msg>Cleanup script cruft<commit_after>var https = require("https");
var http = require("http");
var url = require('url');
var semver = require('semver');

/*

// usage:
node scripts/abi_crosswalk.js > lib/util/abi_crosswalk.json

*/

var cross = {};

var template = 'https://raw.github.com/joyent/node/v{VERSION}/src/';
var v8template = 'https://raw.github.com/joyent/node/v{VERSION}/deps/v8/src/version.cc';

var sortObjectByKey = function(obj){
    var keys = [];
    var sorted_obj = {};
    for(var key in obj){
        if(obj.hasOwnProperty(key)){
            keys.push(key);
        }
    }
    // sort keys
    keys.sort(function(a,b) {
      if (semver.gt(a, b)) {
        return 1
      }
      return -1;
    });
    len = keys.length;

    for (i = 0; i < len; i++)
    {
      key = keys[i];
      sorted_obj[key] = obj[key];
    }
    return sorted_obj;
};

function get(ver,callback) {
  var header = 'node.h';
  if (semver.gt(ver, 'v0.11.4')) {
    // https://github.com/joyent/node/commit/44ed42bd971d58b294222d983cfe2908e021fb5d#src/node_version.h
    header = 'node_version.h';
  }
  var path = template.replace('{VERSION}',ver) + header;
  var uri = url.parse(path);
  https.get(uri, function(res) {
      if (res.statusCode != 200) {
        throw new Error("server returned " + res.statusCode + ' for: ' + path);
      }
      res.setEncoding('utf8');
      var body = '';
      res.on('data', function (chunk) {
        body += chunk;
      });
      res.on('end',function(err) {
        var term = 'define NODE_MODULE_VERSION'
        var idx = body.indexOf(term);
        var following = body.slice(idx);
        var end = following.indexOf('\n');
        var value = following.slice(term.length,end).trim();
        if (value[0] === '(' && value[value.length-1] == ')') {
          value = value.slice(1,value.length-1);
        } else if (value.indexOf(' ') > -1) {
          value = value.slice(0,value.indexOf(' '));
        }
        var int_val = +value;
        if (int_val != undefined) {
          // TODO - if val is 1 then we need to get the v8 version from
          // https://github.com/joyent/node/blob/master/deps/v8/src/version.cc
          var v8path = v8template.replace('{VERSION}',ver);
          var v8uri = url.parse(v8path);
          https.get(v8uri, function(res) {
              if (res.statusCode != 200) {
                throw new Error("server returned " + res.statusCode + ' for: ' + path);
              }
              res.setEncoding('utf8');
              var body = '';
              res.on('data', function (chunk) {
                body += chunk;
              });
              res.on('end',function(err) {
                  var term = 'define MAJOR_VERSION'
                  var idx = body.indexOf(term);
                  var following = body.slice(idx);
                  var end = following.indexOf('\n');
                  var major = following.slice(term.length,end).trim();
                  var term1 = 'define MINOR_VERSION'
                  var idx1 = body.indexOf(term1);
                  var following1 = body.slice(idx1);
                  var end1 = following1.indexOf('\n');
                  var minor = following1.slice(term1.length,end1).trim();
                  var v8_version = major+'.'+minor;
                  return callback(null,ver,int_val,v8_version);
              });
          });
        }
      })
    });
}

process.on('exit', function(err) {
    var sorted = sortObjectByKey(cross);
    console.log(JSON.stringify(sorted,null,2));
})

var versions_doc = 'http://nodejs.org/dist/npm-versions.txt';
http.get(url.parse(versions_doc), function(res) {
    if (res.statusCode != 200) {
      throw new Error("server returned " + res.statusCode + ' for: ' + versions_doc);
    }
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end',function(err) {
      var lines = body.split('\n').map(function(line) { return line.split(' ')[0].slice(1); }).filter(function(line) { return (line.length && line != 'node'); });
      lines.forEach(function(ver) {
          get(ver,function(err,version,node_abi,v8_version) {
            cross[version] = {node_abi:node_abi,v8:v8_version};
          });
      });
    });
});

/*
get("0.8.1",function(err,version,node_abi,v8_version) {
    cross[version] = {node_abi:node_abi,v8:v8_version};
});
*/<|endoftext|>


<commit_before>'use strict';
var decimalSeparator = localizedNum[1];
function localizeNum(num) {
   return num.toString().replace(".", decimalSeparator);
}

var ajaxUploaderCompatible = (function() {
   // Test for FileReader
   if (!window.FileReader) {
      return false;
   }

   // Test for AJAX2
   var xhr = new XMLHttpRequest();
   if (!xhr.upload) {
      return false;
   }

   // Everything OK, this browser is compatible
   return true;
})();

function $id(id) {
   var element = document.getElementById(id);
   if (element) {
      return element;
   } else {
      throw "no element with id \"" + id + "\"";
   }
}

// Global variables
var dropBox = $id("form_container"); // where files are drop
var file; // file to upload
var xhr; // AJAX upload request
var ceHack; // Firefox contenteditable hack
var disableCeHack = false; // Avoid the hack if possible

function setPage(name) {
   $id("page_select").style.display = "none";
   $id("page_confirm").style.display = "none";

   if (name == "select") {
      $id("page_"+name).style.display = "block";
   } else {
      $id("subpage_confirm").style.display = "none";
      $id("subpage_progress").style.display = "none";
      $id("subpage_finished").style.display = "none";
      $id("subpage_error").style.display = "none";

      // Show subpage
      if (name == "confirm") {
         $id("subpage_confirm").style.display = "block";
      } else if (name == "progress") {
         $id("subpage_progress").style.display = "block";
      } else if (name == "finished") {
         $id("subpage_finished").style.display = "block";
      } else if (name == "error") {
         $id("subpage_error").style.display = "block";
      }

      // Show page
      $id("page_confirm").style.display = "block";
   }
}

function initAjaxUploader() {
   $id("form_container").className = "ajax";

   // Create a hidden file input
   var fileHack = document.createElement("input");
   fileHack.setAttribute("type", "file");
   fileHack.setAttribute("id", "file_hack");
   // Internet Explorer 10 needs a bit more of tweaking in order for show the
   // file dialog on a single click.
   if (window.navigator.appName == "Microsoft Internet Explorer") {
      fileHack.style.fontSize = "200px";
   }
   fileHack.addEventListener("change", handleFileSelect);
   $id("page_select").appendChild(fileHack);

   // Focus file selector so it can be opened with Return key
   fileHack.focus();

   // Bind drag and drop events
   dropBox.addEventListener("dragover", function(e) {
      e.preventDefault();
      e.stopPropagation();
      dropBox.className = "ajax hover";
   }, false);
   dropBox.addEventListener("dragleave", function() {
      dropBox.className = "ajax";
   }, false);
   dropBox.addEventListener("drop", handleDrop, false);

   // Bind paste events
   initPasteHandler();

   // Bind buttons
   $id("upload_button").addEventListener("click", startUpload, false);
   $id("confirm_cancel").addEventListener("click", function() {
      setPage("select"); }, false);
   $id("cancel_upload").addEventListener("click", cancelUpload, false);
   $id("store_more_button").addEventListener("click", storeMore, false);
   $id("retry_button").addEventListener("click", function() {
      setPage("confirm"); }, false);
}

function handleFileSelect(e) {
   // Called when the user picks a file in the file dialog

   var files = e.target.files;
   if (files.length == 1) {
      confirmFile(files[0]);
   }
}

function handleDrop(e) {
   // Prevent the browser from taking the default action (leaving the page)
   e.stopPropagation();
   e.preventDefault();

   // Remove .hover class
   dropBox.className = "ajax";

   var files = e.dataTransfer.files;
   if (files.length == 1) {
      confirmFile(files[0]);
   }
}

function fileIsPicture(file) {
   var types = [
      "image/png",
      "image/jpeg",
      "image/gif"
   ];
   for (var i=0; i < types.length; i++) {
      if (file.type == types[i]) {
         return true;
      }
   }
   return false;
}

function humanSize(byteSize) {
   var KiB = 1024;
   var MiB = 1024 * 1024;
   var GiB = 1024 * 1024 * 1024;
   var prec = 1;

   if (byteSize < KiB) {
      return byteSize + " bytes";
   } else if (byteSize < MiB) {
      return (byteSize / KiB).toFixed(prec) + " KiB";
   } else if (byteSize < GiB) {
      return (byteSize / MiB).toFixed(prec) + " MiB";
   } else {
      return (byteSize / GiB).toFixed(prec) + " GiB";
   }
}

function confirmFile(new_file) {
   file = new_file; // Make global
   $id("file_name").textContent = file.name;
   $id("file_size").textContent = localizeNum(humanSize(file.size));

   var imagePane = $id("image_pane");
   imagePane.innerHTML = "";
   if (fileIsPicture(file)) {
      imagePane.style.visibility = "visible";
      $id("page_confirm").className = "";

      var reader = new FileReader();
      reader.onload = function() {
         var img = document.createElement("img");
         img.setAttribute("src", reader.result);
         imagePane.appendChild(img);
      };
      reader.readAsDataURL(file);
   } else {
      imagePane.style.visibility = "hidden";
      $id("page_confirm").className = "no_image";
   }

   setPage("confirm");
}

function setProgress(completed, total) {
   var ratio = completed / total;
   $id("percent").textContent = (ratio * 100).toFixed(0) + " %";
   $id("filled_area").style.width = Math.min(100, ratio * 100) + "%";
}

function uploadProgress(e) {
   setProgress(e.loaded, file.size);
}

function startUpload() {
   setProgress(0, 100);
   setPage("progress");

   var formData = new FormData();
   formData.append("expires_in", $id("ajax_expires_in").value);
   formData.append("file", file);
   // If this is not a real File object, but a Blob object with a name
   // property, append a file name override field, as the browser will send
   // filename=blob.
   if (!(file instanceof File)) {
      formData.append("file_name_override", file.name);
   }

   xhr = new XMLHttpRequest();

   xhr.upload.onprogress = uploadProgress;
   xhr.onload = uploadComplete;
   xhr.error = uploadFailed;

   xhr.open("POST", "/api/v1/", true);
   //xhr.open("POST", "https://lasana.rufian.eu/api/v1/", true);
   xhr.send(formData);
}

function uploadComplete(e) {
   if (this.status == 200) {
      var data = JSON.parse(this.response);
      var urlField = $id("lasagna_url_field");
      urlField.value = data.url;
      setPage("finished");

      urlField.setSelectionRange(0, urlField.value.length);
      urlField.select();
   } else {
      uploadFailed();
   }
}

function cancelUpload() {
   xhr.abort();
   setPage("confirm");
}

function uploadFailed(e) {
   setPage("error");
}

function storeMore() {
   setPage("select");
}

function initPasteHandler() {
   // For Chrome
   document.addEventListener("paste", pasteHandler, false);

   // The rest of this function is the contenteditable hack for Firefox

   // Create a focusable but mostly hidden contenteditable div
   ceHack = document.createElement("div");
   ceHack.setAttribute("contenteditable", "true");
   ceHack.setAttribute("tabindex", "-1");
   ceHack.style.opacity = "0";
   ceHack.style.position = "absolute";
   ceHack.style.left = "-10000px";
   ceHack.style.top = "-10000px";
   document.getElementsByTagName("body")[0].appendChild(ceHack);

   // Focus ceHack on <C-v>
   window.addEventListener("keydown", function(e) {
      if (!disableCeHack && (e.ctrlKey || e.metaKey) && e.keyCode == 86) {
         ceHack.focus();
      }
   });

   // Listen for changes in ceHack
   var observer = new MutationObserver(firefoxPasteHandler);
   observer.observe(ceHack, {childList: true});
}

function pad(number, positions) {
   var numStr = new String(number);
   for (var i = positions - numStr.length; i > 0; i--) {
      numStr = "0" + numStr;
   }
   return numStr;
}

function defaultName(type) {
   var date = new Date();
   var dateStr = date.getFullYear() + "-" +
                  pad(date.getMonth() + 1, 2) + "-" +
                  pad(date.getDate(), 2) + "-" +
                  pad(date.getHours(), 2) + "-" +
                  pad(date.getMinutes(), 2) + "-" +
                  pad(date.getSeconds(), 2);
   var extensions = {
      "image/png": "png",
      "image/jpeg": "jpeg",
      "image/gif": "gif",
      "text/plain": "txt"
   }

   return dateStr + ("." + extensions[type] || "");
}

function pasteHandler(e) {
   var items = e.clipboardData.items;
   if (!items) return; // items is undefined in Firefox :(
   var file = null;
   for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.kind == "file") {
         file = item.getAsFile();
         break;
      }
   }
   if (file) {
      disableCeHack = true;
      file.name = file.name || defaultName(file.type);
      confirmFile(file);
   }
}

// http://stackoverflow.com/a/14930686/1777162
function dataURItoBlob(dataURI) {
   var byteString,
       mimestring

   if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
       byteString = atob(dataURI.split(',')[1])
   } else {
       byteString = decodeURI(dataURI.split(',')[1])
   }

   mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

   var content = new Array();
   for (var i = 0; i < byteString.length; i++) {
       content[i] = byteString.charCodeAt(i)
   }

   return new Blob([new Uint8Array(content)], {type: mimestring});
}

function firefoxPasteHandler() {
   if (!disableCeHack) {
      var images = ceHack.getElementsByTagName("img");
      if (images.length > 0) {
         var img = images[0];
         var src = img.getAttribute("src");
         var blob;
         if (src.match(/https?:/)) {
            alert(noBrowserImagesError);
         } else if (src.lastIndexOf("data:", 0) === 0) {
            blob = dataURItoBlob(src);

            // A File object is a Blob plus a file name, but I'm not aware of
            // any way to convert a Blob in a File object with name.

            // File constructor should be able to do this, but it raises a
            // security exception on Firefox.

            // Instead, I'll put a name property in the Blob object itself.
            // Later, startUpload will detect that it does not have a real File
            // object, read this property and add an override field for the
            // file name.
            blob.name = defaultName(blob.type);
            confirmFile(blob);
         }
      }
   }
   // Don't leave old elements in the ceHack
   ceHack.innerHTML = "";
}

if (ajaxUploaderCompatible) {
   initAjaxUploader();
}
<commit_msg>Removed debug comment<commit_after>'use strict';
var decimalSeparator = localizedNum[1];
function localizeNum(num) {
   return num.toString().replace(".", decimalSeparator);
}

var ajaxUploaderCompatible = (function() {
   // Test for FileReader
   if (!window.FileReader) {
      return false;
   }

   // Test for AJAX2
   var xhr = new XMLHttpRequest();
   if (!xhr.upload) {
      return false;
   }

   // Everything OK, this browser is compatible
   return true;
})();

function $id(id) {
   var element = document.getElementById(id);
   if (element) {
      return element;
   } else {
      throw "no element with id \"" + id + "\"";
   }
}

// Global variables
var dropBox = $id("form_container"); // where files are drop
var file; // file to upload
var xhr; // AJAX upload request
var ceHack; // Firefox contenteditable hack
var disableCeHack = false; // Avoid the hack if possible

function setPage(name) {
   $id("page_select").style.display = "none";
   $id("page_confirm").style.display = "none";

   if (name == "select") {
      $id("page_"+name).style.display = "block";
   } else {
      $id("subpage_confirm").style.display = "none";
      $id("subpage_progress").style.display = "none";
      $id("subpage_finished").style.display = "none";
      $id("subpage_error").style.display = "none";

      // Show subpage
      if (name == "confirm") {
         $id("subpage_confirm").style.display = "block";
      } else if (name == "progress") {
         $id("subpage_progress").style.display = "block";
      } else if (name == "finished") {
         $id("subpage_finished").style.display = "block";
      } else if (name == "error") {
         $id("subpage_error").style.display = "block";
      }

      // Show page
      $id("page_confirm").style.display = "block";
   }
}

function initAjaxUploader() {
   $id("form_container").className = "ajax";

   // Create a hidden file input
   var fileHack = document.createElement("input");
   fileHack.setAttribute("type", "file");
   fileHack.setAttribute("id", "file_hack");
   // Internet Explorer 10 needs a bit more of tweaking in order for show the
   // file dialog on a single click.
   if (window.navigator.appName == "Microsoft Internet Explorer") {
      fileHack.style.fontSize = "200px";
   }
   fileHack.addEventListener("change", handleFileSelect);
   $id("page_select").appendChild(fileHack);

   // Focus file selector so it can be opened with Return key
   fileHack.focus();

   // Bind drag and drop events
   dropBox.addEventListener("dragover", function(e) {
      e.preventDefault();
      e.stopPropagation();
      dropBox.className = "ajax hover";
   }, false);
   dropBox.addEventListener("dragleave", function() {
      dropBox.className = "ajax";
   }, false);
   dropBox.addEventListener("drop", handleDrop, false);

   // Bind paste events
   initPasteHandler();

   // Bind buttons
   $id("upload_button").addEventListener("click", startUpload, false);
   $id("confirm_cancel").addEventListener("click", function() {
      setPage("select"); }, false);
   $id("cancel_upload").addEventListener("click", cancelUpload, false);
   $id("store_more_button").addEventListener("click", storeMore, false);
   $id("retry_button").addEventListener("click", function() {
      setPage("confirm"); }, false);
}

function handleFileSelect(e) {
   // Called when the user picks a file in the file dialog

   var files = e.target.files;
   if (files.length == 1) {
      confirmFile(files[0]);
   }
}

function handleDrop(e) {
   // Prevent the browser from taking the default action (leaving the page)
   e.stopPropagation();
   e.preventDefault();

   // Remove .hover class
   dropBox.className = "ajax";

   var files = e.dataTransfer.files;
   if (files.length == 1) {
      confirmFile(files[0]);
   }
}

function fileIsPicture(file) {
   var types = [
      "image/png",
      "image/jpeg",
      "image/gif"
   ];
   for (var i=0; i < types.length; i++) {
      if (file.type == types[i]) {
         return true;
      }
   }
   return false;
}

function humanSize(byteSize) {
   var KiB = 1024;
   var MiB = 1024 * 1024;
   var GiB = 1024 * 1024 * 1024;
   var prec = 1;

   if (byteSize < KiB) {
      return byteSize + " bytes";
   } else if (byteSize < MiB) {
      return (byteSize / KiB).toFixed(prec) + " KiB";
   } else if (byteSize < GiB) {
      return (byteSize / MiB).toFixed(prec) + " MiB";
   } else {
      return (byteSize / GiB).toFixed(prec) + " GiB";
   }
}

function confirmFile(new_file) {
   file = new_file; // Make global
   $id("file_name").textContent = file.name;
   $id("file_size").textContent = localizeNum(humanSize(file.size));

   var imagePane = $id("image_pane");
   imagePane.innerHTML = "";
   if (fileIsPicture(file)) {
      imagePane.style.visibility = "visible";
      $id("page_confirm").className = "";

      var reader = new FileReader();
      reader.onload = function() {
         var img = document.createElement("img");
         img.setAttribute("src", reader.result);
         imagePane.appendChild(img);
      };
      reader.readAsDataURL(file);
   } else {
      imagePane.style.visibility = "hidden";
      $id("page_confirm").className = "no_image";
   }

   setPage("confirm");
}

function setProgress(completed, total) {
   var ratio = completed / total;
   $id("percent").textContent = (ratio * 100).toFixed(0) + " %";
   $id("filled_area").style.width = Math.min(100, ratio * 100) + "%";
}

function uploadProgress(e) {
   setProgress(e.loaded, file.size);
}

function startUpload() {
   setProgress(0, 100);
   setPage("progress");

   var formData = new FormData();
   formData.append("expires_in", $id("ajax_expires_in").value);
   formData.append("file", file);
   // If this is not a real File object, but a Blob object with a name
   // property, append a file name override field, as the browser will send
   // filename=blob.
   if (!(file instanceof File)) {
      formData.append("file_name_override", file.name);
   }

   xhr = new XMLHttpRequest();

   xhr.upload.onprogress = uploadProgress;
   xhr.onload = uploadComplete;
   xhr.error = uploadFailed;

   xhr.open("POST", "/api/v1/", true);
   xhr.send(formData);
}

function uploadComplete(e) {
   if (this.status == 200) {
      var data = JSON.parse(this.response);
      var urlField = $id("lasagna_url_field");
      urlField.value = data.url;
      setPage("finished");

      urlField.setSelectionRange(0, urlField.value.length);
      urlField.select();
   } else {
      uploadFailed();
   }
}

function cancelUpload() {
   xhr.abort();
   setPage("confirm");
}

function uploadFailed(e) {
   setPage("error");
}

function storeMore() {
   setPage("select");
}

function initPasteHandler() {
   // For Chrome
   document.addEventListener("paste", pasteHandler, false);

   // The rest of this function is the contenteditable hack for Firefox

   // Create a focusable but mostly hidden contenteditable div
   ceHack = document.createElement("div");
   ceHack.setAttribute("contenteditable", "true");
   ceHack.setAttribute("tabindex", "-1");
   ceHack.style.opacity = "0";
   ceHack.style.position = "absolute";
   ceHack.style.left = "-10000px";
   ceHack.style.top = "-10000px";
   document.getElementsByTagName("body")[0].appendChild(ceHack);

   // Focus ceHack on <C-v>
   window.addEventListener("keydown", function(e) {
      if (!disableCeHack && (e.ctrlKey || e.metaKey) && e.keyCode == 86) {
         ceHack.focus();
      }
   });

   // Listen for changes in ceHack
   var observer = new MutationObserver(firefoxPasteHandler);
   observer.observe(ceHack, {childList: true});
}

function pad(number, positions) {
   var numStr = new String(number);
   for (var i = positions - numStr.length; i > 0; i--) {
      numStr = "0" + numStr;
   }
   return numStr;
}

function defaultName(type) {
   var date = new Date();
   var dateStr = date.getFullYear() + "-" +
                  pad(date.getMonth() + 1, 2) + "-" +
                  pad(date.getDate(), 2) + "-" +
                  pad(date.getHours(), 2) + "-" +
                  pad(date.getMinutes(), 2) + "-" +
                  pad(date.getSeconds(), 2);
   var extensions = {
      "image/png": "png",
      "image/jpeg": "jpeg",
      "image/gif": "gif",
      "text/plain": "txt"
   }

   return dateStr + ("." + extensions[type] || "");
}

function pasteHandler(e) {
   var items = e.clipboardData.items;
   if (!items) return; // items is undefined in Firefox :(
   var file = null;
   for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.kind == "file") {
         file = item.getAsFile();
         break;
      }
   }
   if (file) {
      disableCeHack = true;
      file.name = file.name || defaultName(file.type);
      confirmFile(file);
   }
}

// http://stackoverflow.com/a/14930686/1777162
function dataURItoBlob(dataURI) {
   var byteString,
       mimestring

   if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
       byteString = atob(dataURI.split(',')[1])
   } else {
       byteString = decodeURI(dataURI.split(',')[1])
   }

   mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

   var content = new Array();
   for (var i = 0; i < byteString.length; i++) {
       content[i] = byteString.charCodeAt(i)
   }

   return new Blob([new Uint8Array(content)], {type: mimestring});
}

function firefoxPasteHandler() {
   if (!disableCeHack) {
      var images = ceHack.getElementsByTagName("img");
      if (images.length > 0) {
         var img = images[0];
         var src = img.getAttribute("src");
         var blob;
         if (src.match(/https?:/)) {
            alert(noBrowserImagesError);
         } else if (src.lastIndexOf("data:", 0) === 0) {
            blob = dataURItoBlob(src);

            // A File object is a Blob plus a file name, but I'm not aware of
            // any way to convert a Blob in a File object with name.

            // File constructor should be able to do this, but it raises a
            // security exception on Firefox.

            // Instead, I'll put a name property in the Blob object itself.
            // Later, startUpload will detect that it does not have a real File
            // object, read this property and add an override field for the
            // file name.
            blob.name = defaultName(blob.type);
            confirmFile(blob);
         }
      }
   }
   // Don't leave old elements in the ceHack
   ceHack.innerHTML = "";
}

if (ajaxUploaderCompatible) {
   initAjaxUploader();
}
<|endoftext|>


<commit_before>// Copyright (c) 2021, Tom Ritter
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

'use strict';

var FontScale = require('../fontscale');
var monaco = require('monaco-editor');
var _ = require('underscore');
var $ = require('jquery');
var ga = require('../analytics');
var monacoConfig = require('../monaco-config');
var local = require('../local');

require('../modes/asm-mode');

function Flags(hub, container, state) {
    state = state || {};
    this.container = container;
    this.eventHub = hub.createEventHub();
    this.domRoot = container.getElement();
    this.domRoot.html($('#flags').html());
    this.source = state.source || '';
    var root = this.domRoot.find('.monaco-placeholder');

    this.settings = JSON.parse(local.get('settings', '{}'));

    this.editor = monaco.editor.create(root[0], monacoConfig.extendConfig({
        value: state.compilerFlags ? state.compilerFlags.replaceAll(' ', '\n') : '',
        language: 'plaintext',
        readOnly: false,
        glyphMargin: true,
    }));

    this._compilerid = state.id;
    this._compilerName = state.compilerName;

    this.awaitingInitialResults = false;
    this.selection = state.selection;

    this.initButtons(state);
    this.initCallbacks();

    this.setTitle();
    this.onSettingsChange(this.settings);
    this.eventHub.emit('flagsViewOpened', this._compilerid);
    ga.proxy('send', {
        hitType: 'event',
        eventCategory: 'OpenViewPane',
        eventAction: 'detailedCompilerFlags',
    });
}

Flags.prototype.initButtons = function (state) {
    this.fontScale = new FontScale(this.domRoot, state, this.editor);

    this.topBar = this.domRoot.find('.top-bar');
};

Flags.prototype.initCallbacks = function () {
    this.fontScale.on('change', _.bind(this.updateState, this));

    this.eventHub.on('compiler', this.onCompiler, this);
    this.eventHub.on('compilerClose', this.onCompilerClose, this);
    this.eventHub.on('settingsChange', this.onSettingsChange, this);
    this.eventHub.on('resize', this.resize, this);
    this.container.on('destroy', this.close, this);
    this.eventHub.emit('requestSettings');
    this.eventHub.emit('findCompilers');

    this.container.on('resize', this.resize, this);
    this.container.on('shown', this.resize, this);

    this.container.layoutManager.on('initialised', function () {
        // Once initialized, let everyone know what text we have.
        this.maybeEmitChange();
    }, this);
    this.eventHub.on('initialised', this.maybeEmitChange, this);

    this.editor.getModel().onDidChangeContent(_.bind(function () {
        this.debouncedEmitChange();
        this.updateState();
    }, this));

    this.cursorSelectionThrottledFunction =
        _.throttle(_.bind(this.onDidChangeCursorSelection, this), 500);
    this.editor.onDidChangeCursorSelection(_.bind(function (e) {
        this.cursorSelectionThrottledFunction(e);
    }, this));
};

Flags.prototype.setTitle = function () {
    this.container.setTitle(
        this._compilerName + ' Detailed Compiler Flags (Compiler #' + this._compilerid + ')');
};

Flags.prototype.onCompiler = function (id, compiler) {
    if (id === this._compilerid) {
        this._compilerName = compiler ? compiler.name : '';
        this.setTitle();
    }
};

Flags.prototype.resize = function () {
    var topBarHeight = this.topBar.outerHeight(true);
    this.editor.layout({
        width: this.domRoot.width(),
        height: this.domRoot.height() - topBarHeight,
    });
};

Flags.prototype.updateState = function () {
    this.container.setState(this.currentState());
};

Flags.prototype.currentState = function () {
    var state = {
        id: this._compilerid,
        selection: this.selection,
        compilerFlags: this.getOptions(),
    };
    this.fontScale.addState(state);
    return state;
};

Flags.prototype.close = function () {
    this.eventHub.unsubscribe();
    this.eventHub.emit('flagsViewClosed', this._compilerid, this.getOptions());
    this.editor.dispose();
};

Flags.prototype.onCompilerClose = function (id) {
    if (id === this._compilerid) {
        // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
        // the hierarchy. We can't modify while it's being iterated over.
        this.close();
        _.defer(function (self) {
            self.container.close();
        }, this);
    }
};

Flags.prototype.onSettingsChange = function (newSettings) {
    this.editor.updateOptions({
        contextmenu: newSettings.useCustomContextMenu,
        minimap: {
            enabled: newSettings.showMinimap,
        },
        fontFamily: newSettings.editorsFFont,
        fontLigatures: newSettings.editorsFLigatures,
    });

    this.debouncedEmitChange = _.debounce(_.bind(function () {
        this.maybeEmitChange();
    }, this), newSettings.delayAfterChange);
};

Flags.prototype.onDidChangeCursorSelection = function (e) {
    if (this.awaitingInitialResults) {
        this.selection = e.selection;
        this.updateState();
    }
};

Flags.prototype.getOptions = function () {
    var lines = this.editor.getModel().getValue();
    return lines.replaceAll('\n', ' ');
};

Flags.prototype.maybeEmitChange = function (force) {
    var options = this.getOptions();
    if (!force && options === this.lastChangeEmitted) return;

    this.lastChangeEmitted = options;
    this.eventHub.emit('compilerFlagsChange', this._compilerid, this.lastChangeEmitted);
};

module.exports = {
    Flags: Flags,
};
<commit_msg>replaceAll => replace with /../g<commit_after>// Copyright (c) 2021, Tom Ritter
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

'use strict';

var FontScale = require('../fontscale');
var monaco = require('monaco-editor');
var _ = require('underscore');
var $ = require('jquery');
var ga = require('../analytics');
var monacoConfig = require('../monaco-config');
var local = require('../local');

require('../modes/asm-mode');

function Flags(hub, container, state) {
    state = state || {};
    this.container = container;
    this.eventHub = hub.createEventHub();
    this.domRoot = container.getElement();
    this.domRoot.html($('#flags').html());
    this.source = state.source || '';
    var root = this.domRoot.find('.monaco-placeholder');

    this.settings = JSON.parse(local.get('settings', '{}'));

    var value = '';
    if (state.compilerFlags) {
        value = state.compilerFlags.replace(/ /g, '\n');
    }
    this.editor = monaco.editor.create(root[0], monacoConfig.extendConfig({
        value: value,
        language: 'plaintext',
        readOnly: false,
        glyphMargin: true,
    }));

    this._compilerid = state.id;
    this._compilerName = state.compilerName;

    this.awaitingInitialResults = false;
    this.selection = state.selection;

    this.initButtons(state);
    this.initCallbacks();

    this.setTitle();
    this.onSettingsChange(this.settings);
    this.eventHub.emit('flagsViewOpened', this._compilerid);
    ga.proxy('send', {
        hitType: 'event',
        eventCategory: 'OpenViewPane',
        eventAction: 'detailedCompilerFlags',
    });
}

Flags.prototype.initButtons = function (state) {
    this.fontScale = new FontScale(this.domRoot, state, this.editor);

    this.topBar = this.domRoot.find('.top-bar');
};

Flags.prototype.initCallbacks = function () {
    this.fontScale.on('change', _.bind(this.updateState, this));

    this.eventHub.on('compiler', this.onCompiler, this);
    this.eventHub.on('compilerClose', this.onCompilerClose, this);
    this.eventHub.on('settingsChange', this.onSettingsChange, this);
    this.eventHub.on('resize', this.resize, this);
    this.container.on('destroy', this.close, this);
    this.eventHub.emit('requestSettings');
    this.eventHub.emit('findCompilers');

    this.container.on('resize', this.resize, this);
    this.container.on('shown', this.resize, this);

    this.container.layoutManager.on('initialised', function () {
        // Once initialized, let everyone know what text we have.
        this.maybeEmitChange();
    }, this);
    this.eventHub.on('initialised', this.maybeEmitChange, this);

    this.editor.getModel().onDidChangeContent(_.bind(function () {
        this.debouncedEmitChange();
        this.updateState();
    }, this));

    this.cursorSelectionThrottledFunction =
        _.throttle(_.bind(this.onDidChangeCursorSelection, this), 500);
    this.editor.onDidChangeCursorSelection(_.bind(function (e) {
        this.cursorSelectionThrottledFunction(e);
    }, this));
};

Flags.prototype.setTitle = function () {
    this.container.setTitle(
        this._compilerName + ' Detailed Compiler Flags (Compiler #' + this._compilerid + ')');
};

Flags.prototype.onCompiler = function (id, compiler) {
    if (id === this._compilerid) {
        this._compilerName = compiler ? compiler.name : '';
        this.setTitle();
    }
};

Flags.prototype.resize = function () {
    var topBarHeight = this.topBar.outerHeight(true);
    this.editor.layout({
        width: this.domRoot.width(),
        height: this.domRoot.height() - topBarHeight,
    });
};

Flags.prototype.updateState = function () {
    this.container.setState(this.currentState());
};

Flags.prototype.currentState = function () {
    var state = {
        id: this._compilerid,
        selection: this.selection,
        compilerFlags: this.getOptions(),
    };
    this.fontScale.addState(state);
    return state;
};

Flags.prototype.close = function () {
    this.eventHub.unsubscribe();
    this.eventHub.emit('flagsViewClosed', this._compilerid, this.getOptions());
    this.editor.dispose();
};

Flags.prototype.onCompilerClose = function (id) {
    if (id === this._compilerid) {
        // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
        // the hierarchy. We can't modify while it's being iterated over.
        this.close();
        _.defer(function (self) {
            self.container.close();
        }, this);
    }
};

Flags.prototype.onSettingsChange = function (newSettings) {
    this.editor.updateOptions({
        contextmenu: newSettings.useCustomContextMenu,
        minimap: {
            enabled: newSettings.showMinimap,
        },
        fontFamily: newSettings.editorsFFont,
        fontLigatures: newSettings.editorsFLigatures,
    });

    this.debouncedEmitChange = _.debounce(_.bind(function () {
        this.maybeEmitChange();
    }, this), newSettings.delayAfterChange);
};

Flags.prototype.onDidChangeCursorSelection = function (e) {
    if (this.awaitingInitialResults) {
        this.selection = e.selection;
        this.updateState();
    }
};

Flags.prototype.getOptions = function () {
    var lines = this.editor.getModel().getValue();
    return lines.replace(/\n/g, ' ');
};

Flags.prototype.maybeEmitChange = function (force) {
    var options = this.getOptions();
    if (!force && options === this.lastChangeEmitted) return;

    this.lastChangeEmitted = options;
    this.eventHub.emit('compilerFlagsChange', this._compilerid, this.lastChangeEmitted);
};

module.exports = {
    Flags: Flags,
};
<|endoftext|>


<commit_before>/**
 * Slidey will manage the slideMode and textMode
 */
function Slidey()
{
    var slidey = this;

    /**
     * Is the slide Mode enabled ?
     */
    this.slideMode = false;

    /**
     * Are the controls enabled ?
     */
    this.controlsEnabled = true;

    /**
     * Slide count and current
     */
    this.slidesCount = 0;
    this.currentSlide = 0;

    /**
     * Discover count and current
     */
    this.discoverCount = 0;
    this.currentDiscover = 0;

    /**
     * Ticking interval
     */
    this.interval = null;

    /**
     * Events
     */
    this.events = {};

    /**
     * Add an event
     */
    this.on = function(evt, callback)
    {
        if (this.events[evt] == undefined) {
            this.events[evt] = [];
        }

        this.events[evt].push(callback);
    };

    /**
     * Invoke an event
     */
    this.dispatch = function(evt, argument)
    {
        if (this.events[evt] != undefined) {
            var callbacks = this.events[evt];
            for (k in callbacks) {
                callbacks[k](argument);
            }
        }
    };

    /**
     * Resizes the slide to fit the screen size
     */
    this.resizeSlides = function(force)
    {
        var width = $(document.body).width();
        var height = $(window).height();

        if (this.slideMode)
        {
            $('.slideEnabled').height(height);

            $('.slideNumber').each(function() {
                $(this).css('margin-left', width-$(this).width()+20);
                $(this).css('margin-top', height-$(this).height()-100);
            });
        } else {
            if (force) {
                width = $('.contents').width();
                $('.slideNumber').each(function() {
                    $(this).css('margin-left', width - 20);
                    $(this).css('margin-top', 5);
                });
            }
        }
    };

    /**
     * Move the menu in slide mode
     */
    this.moveMenu = function()
    {
        if (this.slideMode) {
            $('.contents').css('margin-left', 0);
            $('.menu').css('margin-left', -250);
            $('.contents').css('width', $('body').width());
        } else {
            $('.contents').css('margin-left', 200);
            $('.menu').css('margin-left', 0);
            $('.contents').css('width', 750);
        }
    }

    /**
     * Go to the given slide & discover
     */
    this.goTo = function(slide, discover)
    {
        if (slidey.currentSlide != slide) {
            slidey.currentSlide = slide;
            slidey.scrollTo(slidey.currentSlide);
        }

        $('#slide' + this.currentSlide + ' .discover').hide();

        for (i=0; i<discover; i++) {
            $('#discover_' + slide + '_' + i).show();
        }
    };

    /**
     * Update the discovers visibility
     */
    this.updateDiscovers = function()
    {
        $('.discover').hide();

        for (i=0; i<this.currentSlide-1; i++) {
            $('#slide' + i + ' .discover').show();
        }

        this.updateCurrentDiscover(0);
    };

    /**
     * Update the current slide discover visibility
     *
     * If end is set, starts with the end (all discovered)
     */
    this.updateCurrentDiscover = function(end)
    {
        this.discoverCount = $('#slide' + this.currentSlide + ' .discover').length;

        if (end) {
            $('#slide' + this.currentSlide + ' .discover').show();
            this.currentDiscover = this.discoverCount;
        } else {
            $('#slide' + this.currentSlide + ' .discover').hide();
            this.currentDiscover = 0;
        }
    };

    /**
     * Scrolls to a given slide
     */
    this.scrollTo = function(slideId)
    {
        $('html,body').animate({scrollTop:$('#slide' + slideId).offset().top}, 300, 0, function() {
            if (slidey.slideMode) {
               $('body').css('background-color', $('#slide' + slideId + ' .slide').css('background-color'));
            }
        });
    };

    /**
     * Scrolls to the current slide
     */
    this.scrollToCurrentSlide = function()
    {
        this.scrollTo(this.currentSlide);
    };

    /**
     * Go to the slide just before
     */
    this.precSlide = function()
    {
        if (this.currentSlide > 0) {
            this.currentSlide--;
            this.scrollToCurrentSlide();
            this.updateCurrentDiscover(1);
            this.dispatch('moved');
            return 1;
        }

        return 0;
    };

    /**
     * Go to the slide just after
     */
    this.nextSlide = function()
    {
        if (this.currentSlide < this.slidesCount-1) {
            this.currentSlide++;
            this.scrollToCurrentSlide();
            this.updateCurrentDiscover(1);
            this.dispatch('moved');
            return 1;
        }

        return 0;
    };

    /**
     * Go to the discover just before
     */
    this.precDiscover = function()
    {
        if (this.currentDiscover == 0) {
            if (this.precSlide()) {
               this.updateCurrentDiscover(1);
            }
        } else {
            this.currentDiscover--;
            $('#discover_' + this.currentSlide + '_' + this.currentDiscover).hide();
        }

        this.dispatch('moved');
    };

    /**
     * Go to the discover just after
     */
    this.nextDiscover = function()
    {
        if (this.currentDiscover == this.discoverCount) {
            if (this.nextSlide()) {
                this.updateCurrentDiscover(0);
            }
        } else {
            $('#discover_' + this.currentSlide + '_' + this.currentDiscover).show();
            this.currentDiscover++;
        }

        this.dispatch('moved');
    };

    /**
     * Initializes IDs
     */
    this.on('init', function()
    {
        var id = 0;
        slidey.slidesCount = $('.slide').length;

        $('.slide').each(function() {
            $(this).wrap('

');

            $('#slide' + id).prepend('
' + (id+1) + '/' + slidey.slidesCount + '
');

            var discover_id = 0;

            $(this).find('.discover').each(function() {
                $(this).attr('id', 'discover_' + id + '_' + discover_id);
                discover_id++;
            });

            id++;
        });

        var titleId = 0;
        $('h1, h2, h3').each(function() {
            if (!$(this).attr('id')) {
                $(this).attr('id', 'title'+(titleId++));
            }
        });
    });

    /**
     * Go to slide mode
     */
    this.runSlideMode = function()
    {
        $('.slideModeNormal').removeClass('active');
        $('.slideModeSlide').addClass('active');
        $('.slideOnly').show();
        $('.textOnly').hide();
        this.slideMode = true;
        $('.slideWrapper').addClass('slideEnabled');
        this.moveMenu();
        this.resizeSlides(true);
        this.updateDiscovers();
        this.dispatch('slideMode');
        this.dispatch('moved');
    };

    /**
     * Go to text mode
     */
    this.runTextMode = function()
    {
        $('body').css('background-color', 'transparent');
        $('.slideModeSlide').removeClass('active');
        $('.slideModeNormal').addClass('active');
        $('.discover').show();
        $('.slideOnly').hide();
        $('.textOnly').show();
        this.slideMode = false;
        $('.slideEnabled').height('auto');
        this.moveMenu();
        this.resizeSlides(true);
        $('.slideWrapper').removeClass('slideEnabled');
        this.dispatch('textMode');
    };

    /**
     * Called on each tick
     */
    this.on('tick', function()
    {
        slidey.resizeSlides(false);
    });

    this.tick = function()
    {
        slidey.dispatch('tick');
    };

    this.stopInterval = function()
    {
        if (this.interval) {
            clearInterval(this.interval);
        }
    };

    this.resetInterval = function()
    {
        this.stopInterval();
        this.interval = setInterval(slidey.tick, 500);
    };

    this.init = function() {
        $(document).ready(function()
        {
            slidey.dispatch('init');
            slidey.resetInterval();

            if (window.location.hash) {
                obj = $(window.location.hash);

                if (obj.length) {
                    slidey.currentSlide = obj.closest('.slideWrapper').attr('rel');
                }
            }

            $('.slideModeNormal').click(function() {
                slidey.runTextMode();
                slidey.scrollToCurrentSlide();
            });

            $('.slideModeSlide').click(function() {
                slidey.runSlideMode();
                slidey.scrollToCurrentSlide();
            });

            $('.slideNumber').click(function() {
                if (!slidey.slideMode) {
                    slidey.currentSlide = parseInt($(this).attr('rel'));
                    slidey.runSlideMode();
                } else {
                    slidey.runTextMode();
                }
                slidey.scrollToCurrentSlide();
                slidey.dispatch('moved');
            });

            slidey.runSlideMode();
            slidey.runTextMode();

            slidey.dispatch('tick');
        });

        $(document).keydown(function(e){
            slidey.dispatch('keypress', e.keyCode);

            if (!slidey.slideMode || !slidey.controlsEnabled) {
                return;
            }

            switch (e.keyCode) {
                case 37: // Left
                    slidey.precDiscover();
                   break;
                case 39: // Right
                    slidey.nextDiscover();
                    break;
                case 38: // Up
                    slidey.precSlide();
                break;
                case 40: // Down
                    slidey.nextSlide();
                break;
            }
        });
    };
};

var slidey = new Slidey();
new SlideyMenuExtension(slidey);
new SlideyImagesExtension(slidey);
new SlideySpoilersExtension(slidey);
new SlideyMobileExtension(slidey);
new SlideyStepsExtension(slidey);
if (typeof(SlideyInteractiveExtension) != 'undefined') {
    interactive = new SlideyInteractiveExtension(slidey);
}
if (typeof(SlideyPollExtension) != 'undefined') {
    new SlideyPollExtension(slidey, interactive);
}
slidey.init();
<commit_msg>Adding preventDefault() for navigation keys<commit_after>/**
 * Slidey will manage the slideMode and textMode
 */
function Slidey()
{
    var slidey = this;

    /**
     * Is the slide Mode enabled ?
     */
    this.slideMode = false;

    /**
     * Are the controls enabled ?
     */
    this.controlsEnabled = true;

    /**
     * Slide count and current
     */
    this.slidesCount = 0;
    this.currentSlide = 0;

    /**
     * Discover count and current
     */
    this.discoverCount = 0;
    this.currentDiscover = 0;

    /**
     * Ticking interval
     */
    this.interval = null;

    /**
     * Events
     */
    this.events = {};

    /**
     * Add an event
     */
    this.on = function(evt, callback)
    {
        if (this.events[evt] == undefined) {
            this.events[evt] = [];
        }

        this.events[evt].push(callback);
    };

    /**
     * Invoke an event
     */
    this.dispatch = function(evt, argument)
    {
        if (this.events[evt] != undefined) {
            var callbacks = this.events[evt];
            for (k in callbacks) {
                callbacks[k](argument);
            }
        }
    };

    /**
     * Resizes the slide to fit the screen size
     */
    this.resizeSlides = function(force)
    {
        var width = $(document.body).width();
        var height = $(window).height();

        if (this.slideMode)
        {
            $('.slideEnabled').height(height);

            $('.slideNumber').each(function() {
                $(this).css('margin-left', width-$(this).width()+20);
                $(this).css('margin-top', height-$(this).height()-100);
            });
        } else {
            if (force) {
                width = $('.contents').width();
                $('.slideNumber').each(function() {
                    $(this).css('margin-left', width - 20);
                    $(this).css('margin-top', 5);
                });
            }
        }
    };

    /**
     * Move the menu in slide mode
     */
    this.moveMenu = function()
    {
        if (this.slideMode) {
            $('.contents').css('margin-left', 0);
            $('.menu').css('margin-left', -250);
            $('.contents').css('width', $('body').width());
        } else {
            $('.contents').css('margin-left', 200);
            $('.menu').css('margin-left', 0);
            $('.contents').css('width', 750);
        }
    }

    /**
     * Go to the given slide & discover
     */
    this.goTo = function(slide, discover)
    {
        if (slidey.currentSlide != slide) {
            slidey.currentSlide = slide;
            slidey.scrollTo(slidey.currentSlide);
        }

        $('#slide' + this.currentSlide + ' .discover').hide();

        for (i=0; i<discover; i++) {
            $('#discover_' + slide + '_' + i).show();
        }
    };

    /**
     * Update the discovers visibility
     */
    this.updateDiscovers = function()
    {
        $('.discover').hide();

        for (i=0; i<this.currentSlide-1; i++) {
            $('#slide' + i + ' .discover').show();
        }

        this.updateCurrentDiscover(0);
    };

    /**
     * Update the current slide discover visibility
     *
     * If end is set, starts with the end (all discovered)
     */
    this.updateCurrentDiscover = function(end)
    {
        this.discoverCount = $('#slide' + this.currentSlide + ' .discover').length;

        if (end) {
            $('#slide' + this.currentSlide + ' .discover').show();
            this.currentDiscover = this.discoverCount;
        } else {
            $('#slide' + this.currentSlide + ' .discover').hide();
            this.currentDiscover = 0;
        }
    };

    /**
     * Scrolls to a given slide
     */
    this.scrollTo = function(slideId)
    {
        $('html,body').animate({scrollTop:$('#slide' + slideId).offset().top}, 300, 0, function() {
            if (slidey.slideMode) {
               $('body').css('background-color', $('#slide' + slideId + ' .slide').css('background-color'));
            }
        });
    };

    /**
     * Scrolls to the current slide
     */
    this.scrollToCurrentSlide = function()
    {
        this.scrollTo(this.currentSlide);
    };

    /**
     * Go to the slide just before
     */
    this.precSlide = function()
    {
        if (this.currentSlide > 0) {
            this.currentSlide--;
            this.scrollToCurrentSlide();
            this.updateCurrentDiscover(1);
            this.dispatch('moved');
            return 1;
        }

        return 0;
    };

    /**
     * Go to the slide just after
     */
    this.nextSlide = function()
    {
        if (this.currentSlide < this.slidesCount-1) {
            this.currentSlide++;
            this.scrollToCurrentSlide();
            this.updateCurrentDiscover(1);
            this.dispatch('moved');
            return 1;
        }

        return 0;
    };

    /**
     * Go to the discover just before
     */
    this.precDiscover = function()
    {
        if (this.currentDiscover == 0) {
            if (this.precSlide()) {
               this.updateCurrentDiscover(1);
            }
        } else {
            this.currentDiscover--;
            $('#discover_' + this.currentSlide + '_' + this.currentDiscover).hide();
        }

        this.dispatch('moved');
    };

    /**
     * Go to the discover just after
     */
    this.nextDiscover = function()
    {
        if (this.currentDiscover == this.discoverCount) {
            if (this.nextSlide()) {
                this.updateCurrentDiscover(0);
            }
        } else {
            $('#discover_' + this.currentSlide + '_' + this.currentDiscover).show();
            this.currentDiscover++;
        }

        this.dispatch('moved');
    };

    /**
     * Initializes IDs
     */
    this.on('init', function()
    {
        var id = 0;
        slidey.slidesCount = $('.slide').length;

        $('.slide').each(function() {
            $(this).wrap('

');

            $('#slide' + id).prepend('
' + (id+1) + '/' + slidey.slidesCount + '
');

            var discover_id = 0;

            $(this).find('.discover').each(function() {
                $(this).attr('id', 'discover_' + id + '_' + discover_id);
                discover_id++;
            });

            id++;
        });

        var titleId = 0;
        $('h1, h2, h3').each(function() {
            if (!$(this).attr('id')) {
                $(this).attr('id', 'title'+(titleId++));
            }
        });
    });

    /**
     * Go to slide mode
     */
    this.runSlideMode = function()
    {
        $('.slideModeNormal').removeClass('active');
        $('.slideModeSlide').addClass('active');
        $('.slideOnly').show();
        $('.textOnly').hide();
        this.slideMode = true;
        $('.slideWrapper').addClass('slideEnabled');
        this.moveMenu();
        this.resizeSlides(true);
        this.updateDiscovers();
        this.dispatch('slideMode');
        this.dispatch('moved');
    };

    /**
     * Go to text mode
     */
    this.runTextMode = function()
    {
        $('body').css('background-color', 'transparent');
        $('.slideModeSlide').removeClass('active');
        $('.slideModeNormal').addClass('active');
        $('.discover').show();
        $('.slideOnly').hide();
        $('.textOnly').show();
        this.slideMode = false;
        $('.slideEnabled').height('auto');
        this.moveMenu();
        this.resizeSlides(true);
        $('.slideWrapper').removeClass('slideEnabled');
        this.dispatch('textMode');
    };

    /**
     * Called on each tick
     */
    this.on('tick', function()
    {
        slidey.resizeSlides(false);
    });

    this.tick = function()
    {
        slidey.dispatch('tick');
    };

    this.stopInterval = function()
    {
        if (this.interval) {
            clearInterval(this.interval);
        }
    };

    this.resetInterval = function()
    {
        this.stopInterval();
        this.interval = setInterval(slidey.tick, 500);
    };

    this.init = function() {
        $(document).ready(function()
        {
            slidey.dispatch('init');
            slidey.resetInterval();

            if (window.location.hash) {
                obj = $(window.location.hash);

                if (obj.length) {
                    slidey.currentSlide = obj.closest('.slideWrapper').attr('rel');
                }
            }

            $('.slideModeNormal').click(function() {
                slidey.runTextMode();
                slidey.scrollToCurrentSlide();
            });

            $('.slideModeSlide').click(function() {
                slidey.runSlideMode();
                slidey.scrollToCurrentSlide();
            });

            $('.slideNumber').click(function() {
                if (!slidey.slideMode) {
                    slidey.currentSlide = parseInt($(this).attr('rel'));
                    slidey.runSlideMode();
                } else {
                    slidey.runTextMode();
                }
                slidey.scrollToCurrentSlide();
                slidey.dispatch('moved');
            });

            slidey.runSlideMode();
            slidey.runTextMode();

            slidey.dispatch('tick');
        });

        $(document).keydown(function(e){
            slidey.dispatch('keypress', e.keyCode);

            if (!slidey.slideMode || !slidey.controlsEnabled) {
                return;
            }

            switch (e.keyCode) {
                case 37: // Left
                    e.preventDefault();
                    slidey.precDiscover();
                   break;
                case 39: // Right
                    e.preventDefault();
                    slidey.nextDiscover();
                    break;
                case 38: // Up
                    e.preventDefault();
                    slidey.precSlide();
                break;
                case 40: // Down
                    e.preventDefault();
                    slidey.nextSlide();
                break;
            }
        });
    };
};

var slidey = new Slidey();
new SlideyMenuExtension(slidey);
new SlideyImagesExtension(slidey);
new SlideySpoilersExtension(slidey);
new SlideyMobileExtension(slidey);
new SlideyStepsExtension(slidey);
if (typeof(SlideyInteractiveExtension) != 'undefined') {
    interactive = new SlideyInteractiveExtension(slidey);
}
if (typeof(SlideyPollExtension) != 'undefined') {
    new SlideyPollExtension(slidey, interactive);
}
slidey.init();
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * @file
 * The script generates index files for submodules.
 *
 * It's a part of the build process.
 */

const fs = require('fs')
const path = require('path')
const prettier = require('./_lib/prettier')
const listFns = require('../_lib/listFns')
const listFPFns = require('../_lib/listFPFns')
const listLocales = require('../_lib/listLocales')

const outdatedLocales = require('../../outdatedLocales.json')

const generatedAutomaticallyMessage =
  "// This file is generated automatically by `scripts/build/indices.js`. Please, don't change it."

listFns().then(fns => {
  const fpFns = listFPFns()
  const locales = listLocales().filter(
    ({ code }) => !outdatedLocales.includes(code)
  )

  writeFile('src/index.js', generateIndex(fns, false, true))
  writeFile('src/fp/index.js', generateIndex(fpFns, true, true))
  writeFile('src/locale/index.js', generateIndex(locales, false, false))
})

function writeFile(relativePath, content) {
  return fs.writeFileSync(
    path.resolve(process.cwd(), relativePath),
    prettier(content)
  )
}

function generateIndex(files, isFP, includeConstants) {
  const fileLines = files
    .map(
      fn =>
        `export { default as ${fn.name} } from '${fn.path.replace(
          /\.js$/,
          ''
        )}/index.js'`
    )
    .concat(
      includeConstants
        ? `export * from '${isFP ? '..' : '.'}/constants/index.js'`
        : []
    )

  const indexLines = [generatedAutomaticallyMessage]
    .concat('')
    .concat(fileLines)
    .join('\n')

  return `${indexLines}\n`
}
<commit_msg>Stop adding .js in indicies generation<commit_after>#!/usr/bin/env node

/**
 * @file
 * The script generates index files for submodules.
 *
 * It's a part of the build process.
 */

const fs = require('fs')
const path = require('path')
const prettier = require('./_lib/prettier')
const listFns = require('../_lib/listFns')
const listFPFns = require('../_lib/listFPFns')
const listLocales = require('../_lib/listLocales')

const outdatedLocales = require('../../outdatedLocales.json')

const generatedAutomaticallyMessage =
  "// This file is generated automatically by `scripts/build/indices.js`. Please, don't change it."

listFns().then((fns) => {
  const fpFns = listFPFns()
  const locales = listLocales().filter(
    ({ code }) => !outdatedLocales.includes(code)
  )

  writeFile('src/index.js', generateIndex(fns, false, true))
  writeFile('src/fp/index.js', generateIndex(fpFns, true, true))
  writeFile('src/locale/index.js', generateIndex(locales, false, false))
})

function writeFile(relativePath, content) {
  return fs.writeFileSync(
    path.resolve(process.cwd(), relativePath),
    prettier(content)
  )
}

function generateIndex(files, isFP, includeConstants) {
  const fileLines = files
    .map(
      (fn) =>
        `export { default as ${fn.name} } from '${fn.path.replace(
          /\.js$/,
          ''
        )}/index'`
    )
    .concat(
      includeConstants
        ? `export * from '${isFP ? '..' : '.'}/constants/index'`
        : []
    )

  const indexLines = [generatedAutomaticallyMessage]
    .concat('')
    .concat(fileLines)
    .join('\n')

  return `${indexLines}\n`
}
<|endoftext|>


<commit_before>var assert = require('assert');

function toEnglish(a){
    return "one";

}

it('should return 1 as string "one"', function(){
    assert.equal(toEnglish(1), "one");
})

<commit_msg>@eklemen @carolinapowers<commit_after>var assert = require('assert');

/*function toEnglish(a){
    return "one";

}

it('should return 1 as string "one"', function(){
    assert.equal(toEnglish(1), "one");
})
*/

function toEnglish (a){
    if(a == 2) {
        return "two";
    } else {
        return "this is not the number 2";
    }

}

console.log(toEnglish(3));

it('should return "two" when 2 is entered and "not two" if any other number is entered', function(){
    assert.equal(toEnglish(2), "two")
})<|endoftext|>