<commit_before>CloudFlare.define("dnschanger_detector", ["cloudflare/dom", "cloudflare/config"], function(dom, config){
    window.dnsChangerPresent = function(){
        var table = dom.createElement("table");
        var tr = dom.createElement("tr");
        table.appendChild(tr);
        dom.setAttribute(table, "style", 'z-index: 100000; width:100%; position: absolute; top: 0; left: 0; margin: 0 0 20px 0; padding: 10px; background-color: #f0f0f0; color: #404040; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; border-bottom: 1px solid #a5a5a5;');
        var message = dom.createElement("td");
        var warning = dom.createElement("p");
        dom.setAttribute(warning, "style", 'font-size: 16px; font-weight: bold; color: #be2424; margin-bottom: 5px; margin-left: 10px;');
        warning.innerHTML = 'Your computer has DNS settings that mean you probably have the DNS Changer malware.';
        message.appendChild(warning);
        var info = dom.createElement("p");
        dom.setAttribute(info, "style", 'color: #404040; font-size: 12px; margin-left: 10px; margin-top: 0;');
        var fix_url = ('fix_url' in config && fix_url !== "")? config.fix_url : "http://www.opendns.com/dns-changer";
        info.innerHTML = 'Please visit '+ fix_url +' for help fixing your DNS. You may lose access to the Internet after July 9, 2012 if you don\'t fix this. For additional information regarding the DNS changer malware, please visit the FBI\'s website. DNS Changer warning powered by CloudFlare.';
        message.appendChild(info);
        var icon = dom.createElement("td");
        dom.setAttribute(icon, "style", 'width: 50px; height: 50px; background: url("/cdn-cgi/custom/images/red-exclamation.png") no-repeat center top;');
        var closeButton = dom.createElement("button");
        dom.setAttribute(closeButton, "style", 'width: 20px; height: 20px; margin-left: 15px; background: url("/cdn-cgi/custom/images/button-x.png") no-repeat top left; border: none;');
        tr.appendChild(icon)
        tr.appendChild(message)
        tr.appendChild(closeButton)
        document.body.appendChild(table);

        dom.addEventListener(closeButton, "click", function(){
            document.body.removeChild(table);
        })
    }
    function detectorScript(){
        var test_site = "http://www.dns-ok.us/test.js"
        var script = dom.createElement("script")
        dom.setAttribute(script, "type", "text/javascript")
        dom.setAttribute(script, "src", test_site)
    }
    function detectorImage(){
        var img = new Image();
        dom.addEventListener(img, "load", function(){
            if (img.height == 55) {
                window.dnsChangerPresent()
            }
        })
        dom.setAttribute(img, "src", 'http://cfdnscheck.cloudflare.com/test.js')
    }

    detectorImage()
})
<commit_msg>check config better<commit_after>CloudFlare.define("dnschanger_detector", ["cloudflare/dom", "cloudflare/config"], function(dom, config){
    window.dnsChangerPresent = function(){
        var table = dom.createElement("table");
        var tr = dom.createElement("tr");
        table.appendChild(tr);
        dom.setAttribute(table, "style", 'z-index: 100000; width:100%; position: absolute; top: 0; left: 0; margin: 0 0 20px 0; padding: 10px; background-color: #f0f0f0; color: #404040; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; border-bottom: 1px solid #a5a5a5;');
        var message = dom.createElement("td");
        var warning = dom.createElement("p");
        dom.setAttribute(warning, "style", 'font-size: 16px; font-weight: bold; color: #be2424; margin-bottom: 5px; margin-left: 10px;');
        warning.innerHTML = 'Your computer has DNS settings that mean you probably have the DNS Changer malware.';
        message.appendChild(warning);
        var info = dom.createElement("p");
        dom.setAttribute(info, "style", 'color: #404040; font-size: 12px; margin-left: 10px; margin-top: 0;');
        var fix_url = ('fix_url' in config && config.fix_url !== "")? config.fix_url : "http://www.opendns.com/dns-changer";
        info.innerHTML = 'Please visit '+ fix_url +' for help fixing your DNS. You may lose access to the Internet after July 9, 2012 if you don\'t fix this. For additional information regarding the DNS changer malware, please visit the FBI\'s website. DNS Changer warning powered by CloudFlare.';
        message.appendChild(info);
        var icon = dom.createElement("td");
        dom.setAttribute(icon, "style", 'width: 50px; height: 50px; background: url("/cdn-cgi/custom/images/red-exclamation.png") no-repeat center top;');
        var closeButton = dom.createElement("button");
        dom.setAttribute(closeButton, "style", 'width: 20px; height: 20px; margin-left: 15px; background: url("/cdn-cgi/custom/images/button-x.png") no-repeat top left; border: none;');
        tr.appendChild(icon)
        tr.appendChild(message)
        tr.appendChild(closeButton)
        document.body.appendChild(table);

        dom.addEventListener(closeButton, "click", function(){
            document.body.removeChild(table);
        })
    }
    function detectorScript(){
        var test_site = "http://www.dns-ok.us/test.js"
        var script = dom.createElement("script")
        dom.setAttribute(script, "type", "text/javascript")
        dom.setAttribute(script, "src", test_site)
    }
    function detectorImage(){
        var img = new Image();
        dom.addEventListener(img, "load", function(){
            if (img.height == 55) {
                window.dnsChangerPresent()
            }
        })
        dom.setAttribute(img, "src", 'http://cfdnscheck.cloudflare.com/test.js')
    }

    detectorImage()
})
<|endoftext|>


<commit_before>//
// INTERACT WITH MESSAGES
//
var MessageManipulation = {
  last_message_number: 0,

  init: function() {
  },

  working_begin: function() {
    $('working').appear({ duration: 0.3 });
  },
  working_end: function() {
    $('working').fade({ duration: 0.3 });
  },

  handle_new_messages: function() {
    var new_last_msg_num = MessageManipulation.find_last_message_number();
    if (MessageManipulation.last_message_number < new_last_msg_num) { // shortcut if nothing's changed
      var newMessages = MessageManipulation.identify_new_messages(MessageManipulation.last_message_number + 1, new_last_msg_num);
      MessageManipulation.last_message_number = new_last_msg_num;
      WindowManager.moreMessagesHaveArrived(newMessages)
    }
    MessageManipulation.working_end();
  },

  handle_old_messages: function() {
	MessageManipulation.first_message_number = MessageManipulation.find_first_message_number();
  },

  find_last_message_number: function() {
    var last_msg = $('messages').childElements().last();
    var num = parseInt(last_msg.id.sub("message_",""));
    return num;
  },
  find_first_message_number: function() {
    var first_msg = $('messages').childElements().first();
    var num = parseInt(first_msg.id.sub("message_",""));
    return num;
  },

  identify_new_messages: function(first, last) {
    var newMessages = new Array();
    for (var i = first; i <= last; i++) {
      if ($("message_"+i)) { // some might be in other conversations
        newMessages.push(i);
      }
    }
    return newMessages;
  },

  // quote: function(msgnum) {
  //   var msgtxt = $$("#message_"+msgnum+" p.messagetext")[0].innerHTML.strip();
  //   // for now we have to undo all that markup we do at the back end.  bah
  //   msgtxt = msgtxt.gsub("<[Bb][Rr]/?>", "\n");
  //   msgtxt = msgtxt.gsub("</[Aa]>", "");
  //   msgtxt = msgtxt.gsub("<[Aa] .*?>", "");
  //
  //   var who = $$("#message_"+msgnum+" p.messagemeta .username")[0].innerHTML.strip();
  //   $("message_message").value = who + " said:\n---\n" + msgtxt + "\n---\n";
  //   $("message_message").focus();
  // }
};

Event.observe(window, 'load', MessageManipulation.init);
<commit_msg>Fix javascript functions for find messages<commit_after>//
// INTERACT WITH MESSAGES
//
var MessageManipulation = {
  last_message_number: 0,

  init: function() {
  },

  working_begin: function() {
    $('working').appear({ duration: 0.3 });
  },
  working_end: function() {
    $('working').fade({ duration: 0.3 });
  },

  handle_new_messages: function() {
    var new_last_msg_num = MessageManipulation.find_last_message_number();
    if (MessageManipulation.last_message_number < new_last_msg_num) { // shortcut if nothing's changed
      var newMessages = MessageManipulation.identify_new_messages(MessageManipulation.last_message_number + 1, new_last_msg_num);
      MessageManipulation.last_message_number = new_last_msg_num;
      WindowManager.moreMessagesHaveArrived(newMessages)
    }
    MessageManipulation.working_end();
  },

  handle_old_messages: function() {
	MessageManipulation.first_message_number = MessageManipulation.find_first_message_number();
  },

  find_last_message_number: function() {
    var last_msg = $('messages').childElements().first();
    var num = parseInt(last_msg.id.sub("message_",""));
    return num;
  },
  find_first_message_number: function() {
    var first_msg = $('messages').childElements().last();
    var num = parseInt(first_msg.id.sub("message_",""));
    return num;
  },

  identify_new_messages: function(first, last) {
    var newMessages = new Array();
    for (var i = first; i <= last; i++) {
      if ($("message_"+i)) { // some might be in other conversations
        newMessages.push(i);
      }
    }
    return newMessages;
  },

  // quote: function(msgnum) {
  //   var msgtxt = $$("#message_"+msgnum+" p.messagetext")[0].innerHTML.strip();
  //   // for now we have to undo all that markup we do at the back end.  bah
  //   msgtxt = msgtxt.gsub("<[Bb][Rr]/?>", "\n");
  //   msgtxt = msgtxt.gsub("</[Aa]>", "");
  //   msgtxt = msgtxt.gsub("<[Aa] .*?>", "");
  //
  //   var who = $$("#message_"+msgnum+" p.messagemeta .username")[0].innerHTML.strip();
  //   $("message_message").value = who + " said:\n---\n" + msgtxt + "\n---\n";
  //   $("message_message").focus();
  // }
};

Event.observe(window, 'load', MessageManipulation.init);
<|endoftext|>


<commit_before>MusicXMLAnalyzer.ResultController = function(){

	var that = {},

	model = null,
	view = null,
	once = true,
	once2 = true,
	stop = false,
	tooLong = false,
	tonika = { 'C':0, 'D':2, 'E':4, 'F':5, 'G':7, 'A':9, 'B':11 },

	init = function(){
		console.info('MusicXMLAnalyzer.ResultController.init');

		model = MusicXMLAnalyzer.ResultModel();
		$(model).on('resultExtractReceived', onResultExtractReceived);
		model.init();

		view = MusicXMLAnalyzer.ResultView();
		$(view).on('addResultItem', onAddResultItem);
		view.init();

		//init MIDI
		MIDI.loadPlugin({
			soundfontUrl: "../../../libs/midijs/soundfont/",
			instrument: "acoustic_grand_piano",
			callback: function() {
			}
		});

		$playResult = $('.playResult');
		$stopResult = $('.stopResult');

		// disable stop button
		$stopResult.prop('disabled', true);

		$playResult.click(function(){
			stop = false;
			once2 = true;
			once = true;
			playResult();
			$playResult.prop('disabled', true);
			$stopResult.prop('disabled', false);
		});

		$stopResult.click(function(){
			stop = true;
			$playResult.prop('disabled', false);
			$stopResult.prop('disabled', true);

		});

		$(document).ajaxStop(onModelReady);

	},

	onAddResultItem = function(event, numItems, result) {
		model.setNumItems(numItems);
		model.addResultItem(result);
	},

	onResultExtractReceived = function(event, index, data) {
		view.renderResultExtract(index, data);
	},

	onModelReady = function(event) {
		view.setModelReady();
	},

	getDuration = function(type){
		var duration;

		if (type == "whole"){
			duration = 1;
		} else if (type == "half") {
			duration = 0.5;
		} else if (type == "quarter") {
			duration = 0.25;
		} else if (type == "eighth") {
			duration = 0.125;
		} else if (type == "16th") {
			duration = 0.0625;
		} else if (type == "32nd") {
			duration = 0.03125;
		} else if (type == "64th") {
			duration = 0.015625;
		}

		return duration;
	},

	getMidiValue = function(step, octave, alter) {
		return (parseInt(octave) * 12) + (tonika[step] + parseInt(alter));
	},

	playResult = function(){
		console.log("playResult: ");
		var notesToBePlayed = [];
		// console.log("playResult keyToNote: ",MIDI.keyToNote['A0']); //<-- returns key for var note
		// console.log("playResult keytonote: ",MIDI.noteToKey); // 21 => A0

		// TODO:
		// # set duration correctly if dotted note
		// # determine velocity
		// # anschlags pausen bei notenlängen wechsel entfernen!

		//get notes of current extract:
		var currentResultNotes = JSON.parse($('#extract-carousel').find('div.carousel-inner').find('div.item.active').find('.resultExtract').val());
		console.log("currentResultNotes: ",currentResultNotes);

		//determine MIDI values for currentResultNotes
		for(var i = 0; i < currentResultNotes.measures.length; i++){
			for(var j = 0; j < currentResultNotes.measures[i].notes.length; j++){
				// check if rest
				if(currentResultNotes.measures[i].notes[j].type == 'rest'){
					var rest = currentResultNotes.measures[i].notes[j];
					var restDuration = getDuration(currentResultNotes.measures[i].notes[j].duration);
					notesToBePlayed.push({'note': 0, 'noteDuration': restDuration});

				}else if(currentResultNotes.measures[i].notes[j].type == 'note'){
					var note = currentResultNotes.measures[i].notes[j];
					var noteStep = note.pitch.step;
					var noteOctave = note.pitch.octave;
					var noteAlter = note.pitch.alter;
					var noteDuration = getDuration(note.pitch.type);
					var noteBeam = note.pitch.beam;
					if(typeof noteDuration === 'undefined'){
						console.log("noteduration is undefined");
						noteDuration = 0.25;
					}
					if(note.pitch.dot){
						noteDuration += 0.5*noteDuration;
					}
					if(typeof noteBeam === 'undefined'){
						console.log("beam is undefined");
						noteBeam = false;
					}
					var chord = note.pitch.chord;

					var midiNote = getMidiValue(noteStep, noteOctave, noteAlter);
					console.log(noteStep, noteOctave, noteAlter, noteDuration, "midiNote: ", midiNote);

					notesToBePlayed.push({'note': midiNote, 'noteDuration': noteDuration, 'chord': chord, 'noteBeam' : noteBeam});
				}
			}
		}

		// console.log("notesToBePlayed: ",notesToBePlayed);

		var i = 0;
		playTune = function(){

			var chordsToBePlayed = [];

			if(i < notesToBePlayed.length) {
				// console.log("notesToBePlayed: ",notesToBePlayed[i]);
				// console.log("pause: ", pause);
				var note = notesToBePlayed[i].note;
				var noteDuration = notesToBePlayed[i].noteDuration;
				var velocity = 127; // how hard the note hits
				var delay = 0;
				// var chord = notesToBePlayed[i].chord;
				var timeout = 0;
				if(!once){
					// timeout needs adjustment
					// currently trial&error values
					timeout = notesToBePlayed[i-1].noteDuration*2000;
					if(notesToBePlayed[i-1].noteBeam != false) {
						timeout = (timeout * 2) / 3;
					}
				}
				once = false;
				// console.log("delay till note is played: ",timeout);

				setTimeout(function() {
					if(stop){
						// console.log("STOP: ",stop);
						// MIDI.setVolume(0, 0);
						i = notesToBePlayed.length;
					}else{
						// console.log("STOP: ",stop);
						MIDI.setVolume(0, 127);
						// delay --> https://stackoverflow.com/questions/21296450/midi-js-note-duration-does-not-change

						if(i + 1 < notesToBePlayed.length) {
							tooLong = false;
						}else{
							tooLong = true;
						}

						// console.log("tooLong? ",tooLong);

						if(!tooLong && notesToBePlayed[i].chord == false && notesToBePlayed[i + 1].chord == true) {
							// var kCounter = 0;
							do{
								chordsToBePlayed.push(notesToBePlayed[i].note);
								i++;
								// console.log("notesToBePlayed[i].chord: ",notesToBePlayed[i].chord," i: ",i," notesToBePlayed.length: ",notesToBePlayed.length);
							}while(notesToBePlayed[i] && notesToBePlayed[i].chord == true && i < notesToBePlayed.length)
							// console.log("chordsToBePlayed	: ",chordsToBePlayed);
							MIDI.chordOn(0, chordsToBePlayed, velocity, delay);
							MIDI.chordOff(0, chordsToBePlayed, delay + 0.75);
							// TODO:
							// adjust timeout for chords?
						}
						// else:
						else{
							MIDI.noteOn(0, note, velocity, delay);
							MIDI.noteOff(0, note, delay + 0.75);
							i++;
						}
						MIDI.Player.stop();
					}
					// recursively call playTune()
					playTune();
				 }, timeout);
			}
			// else when finished - reset play&stop buttons after 1.5 sec
			else{
				setTimeout(function(){
					$playResult.prop('disabled', false);
					$stopResult.prop('disabled', true);
				}, 1500);
			}
		}
		if(once2){
			once2 = false;
			playTune();
		 }
	};

	that.init = init;

	return that;
}<commit_msg>midi js fix result controller<commit_after>MusicXMLAnalyzer.ResultController = function(){

	var that = {},

	model = null,
	view = null,
	once = true,
	once2 = true,
	stop = false,
	tooLong = false,
	tonika = { 'C':0, 'D':2, 'E':4, 'F':5, 'G':7, 'A':9, 'B':11 },

	init = function(){
		console.info('MusicXMLAnalyzer.ResultController.init');

		model = MusicXMLAnalyzer.ResultModel();
		$(model).on('resultExtractReceived', onResultExtractReceived);
		model.init();

		view = MusicXMLAnalyzer.ResultView();
		$(view).on('addResultItem', onAddResultItem);
		view.init();

		//init MIDI
		MIDI.loadPlugin({
			soundfontUrl: "../../../libs/midijs/soundfont/",
			instrument: "acoustic_grand_piano",
			callback: function() {
			}
		});

		$playResult = $('.playResult');
		$stopResult = $('.stopResult');

		// disable stop button
		$stopResult.prop('disabled', true);

		$playResult.click(function(){
			stop = false;
			once2 = true;
			once = true;
			playResult();
			$playResult.prop('disabled', true);
			$stopResult.prop('disabled', false);
		});

		$stopResult.click(function(){
			stop = true;
			$playResult.prop('disabled', false);
			$stopResult.prop('disabled', true);

		});

		$(document).ajaxStop(onModelReady);

	},

	onAddResultItem = function(event, numItems, result) {
		model.setNumItems(numItems);
		model.addResultItem(result);
	},

	onResultExtractReceived = function(event, index, data) {
		view.renderResultExtract(index, data);
	},

	onModelReady = function(event) {
		view.setModelReady();
	},

	getDuration = function(type){
		var duration;

		if (type == "whole"){
			duration = 1;
		} else if (type == "half") {
			duration = 0.5;
		} else if (type == "quarter") {
			duration = 0.25;
		} else if (type == "eighth") {
			duration = 0.125;
		} else if (type == "16th") {
			duration = 0.0625;
		} else if (type == "32nd") {
			duration = 0.03125;
		} else if (type == "64th") {
			duration = 0.015625;
		}

		return duration;
	},

	getMidiValue = function(step, octave, alter) {
		return (parseInt(octave) * 12) + (tonika[step] + parseInt(alter));
	},

	playResult = function(){
		console.log("playResult: ");
		var notesToBePlayed = [];
		// console.log("playResult keyToNote: ",MIDI.keyToNote['A0']); //<-- returns key for var note
		// console.log("playResult keytonote: ",MIDI.noteToKey); // 21 => A0

		// TODO:
		// # set duration correctly if dotted note
		// # determine velocity
		// # anschlags pausen bei notenlängen wechsel entfernen!

		//get notes of current extract:
		var currentResultNotes = JSON.parse($('#extract-carousel').find('div.carousel-inner').find('div.item.active').find('.resultExtract').val());
		console.log("currentResultNotes: ",currentResultNotes);

		MIDI.setVolume(0, 127);

		//determine MIDI values for currentResultNotes
		for(var i = 0; i < currentResultNotes.measures.length; i++){
			for(var j = 0; j < currentResultNotes.measures[i].notes.length; j++){
				// check if rest
				if(currentResultNotes.measures[i].notes[j].type == 'rest'){
					var rest = currentResultNotes.measures[i].notes[j];
					var restDuration = getDuration(currentResultNotes.measures[i].notes[j].duration);
					notesToBePlayed.push({'note': 0, 'noteDuration': restDuration});

				}else if(currentResultNotes.measures[i].notes[j].type == 'note'){
					var note = currentResultNotes.measures[i].notes[j];
					var noteStep = note.pitch.step;
					var noteOctave = note.pitch.octave;
					var noteAlter = note.pitch.alter;
					var noteDuration = getDuration(note.pitch.type);
					var noteBeam = note.pitch.beam;
					if(typeof noteDuration === 'undefined'){
						console.log("noteduration is undefined");
						noteDuration = 0.25;
					}
					if(note.pitch.dot){
						noteDuration += 0.5*noteDuration;
					}
					if(typeof noteBeam === 'undefined'){
						console.log("beam is undefined");
						noteBeam = false;
					}
					var chord = note.pitch.chord;

					var midiNote = getMidiValue(noteStep, noteOctave, noteAlter);
					console.log(noteStep, noteOctave, noteAlter, noteDuration, "midiNote: ", midiNote);

					notesToBePlayed.push({'note': midiNote, 'noteDuration': noteDuration, 'chord': chord, 'noteBeam' : noteBeam});
				}
			}
		}

		// console.log("notesToBePlayed: ",notesToBePlayed);

		var i = 0;
		playTune = function(){

			var chordsToBePlayed = [];

			if(i < notesToBePlayed.length) {
				// console.log("notesToBePlayed: ",notesToBePlayed[i]);
				// console.log("pause: ", pause);
				var note = notesToBePlayed[i].note;
				var noteDuration = notesToBePlayed[i].noteDuration;
				var velocity = 127; // how hard the note hits
				var delay = 0;
				// var chord = notesToBePlayed[i].chord;
				var timeout = 0;
				if(!once){
					// timeout needs adjustment
					// currently trial&error values
					timeout = notesToBePlayed[i-1].noteDuration*2000;
					if(notesToBePlayed[i-1].noteBeam != false) {
						timeout = (timeout * 2) / 3;
					}
				}
				once = false;
				// console.log("delay till note is played: ",timeout);

				setTimeout(function() {
					if(stop){
						// console.log("STOP: ",stop);
						// MIDI.setVolume(0, 0);
						i = notesToBePlayed.length;
					}else{
						// console.log("STOP: ",stop);
						// MIDI.setVolume(0, 127);
						// delay --> https://stackoverflow.com/questions/21296450/midi-js-note-duration-does-not-change

						if(i + 1 < notesToBePlayed.length) {
							tooLong = false;
						}else{
							tooLong = true;
						}

						// console.log("tooLong? ",tooLong);

						if(!tooLong && notesToBePlayed[i].chord == false && notesToBePlayed[i + 1].chord == true) {
							// var kCounter = 0;
							do{
								chordsToBePlayed.push(notesToBePlayed[i].note);
								i++;
								// console.log("notesToBePlayed[i].chord: ",notesToBePlayed[i].chord," i: ",i," notesToBePlayed.length: ",notesToBePlayed.length);
							}while(notesToBePlayed[i] && notesToBePlayed[i].chord == true && i < notesToBePlayed.length)
							// console.log("chordsToBePlayed	: ",chordsToBePlayed);
							MIDI.chordOn(0, chordsToBePlayed, velocity, delay);
							MIDI.chordOff(0, chordsToBePlayed, delay + 0.75);
							// TODO:
							// adjust timeout for chords?
						}
						// else:
						else{
							MIDI.noteOn(0, note, velocity, delay);
							MIDI.noteOff(0, note, delay + 0.75);
							i++;
						}
						MIDI.Player.stop();
					}
					// recursively call playTune()
					playTune();
				 }, timeout);
			}
			// else when finished - reset play&stop buttons after 1.5 sec
			else{
				setTimeout(function(){
					$playResult.prop('disabled', false);
					$stopResult.prop('disabled', true);
				}, 1500);
			}
		}
		if(once2){
			once2 = false;
			playTune();
		 }
	};

	that.init = init;

	return that;
}<|endoftext|>


<commit_before>app.controller('showListEmployeeCtrl', ['$scope', 'QLNS', function ($scope, QLNS) {
    $scope.phongban = 'Phòng/ Ban';
    $scope.chungchi = 'Chứng chỉ';
    $scope.loading = false;

    $scope.email = {
        ten: '',
        email: '',
        content: '',
        subject: ''
    };

    //Lấy toàn bộ danh sách nhân viên
    $scope.getEmployee = function () {
        QLNS.employee.GET().then(function (res) {
            $scope.employee = res.data;
            $scope.loading = true;
            //console.log(res);
            //console.log(res.data[0])
        });
    };

    //Lấy toàn bộ các chứng chỉ
    $scope.getCertificate = function () {
        QLNS.certificate.GET().then(function (res) {
            $scope.certificate = res.data;
            //console.log(res);
            //console.log(res.data[0])
        });
    };

    // Tìm kiếm theo tên nhân viên
    $scope.search = function () {
        QLNS.employee.GET_WITH_NAME($scope.searchName).then(function (res) {
            $scope.employee = res.data;
        });
    };
   //Lấy danh sách nhân viên theo chứng chỉ
    $scope.listCertificate = function (id, name) {
        //$scope.renamePhongban(); //Rename dropdown box Phòng ban về mặc cmn định
        if(idd == null)
        {
            console.log('idd:',idd);
            $scope.chungchi = name;
            QLNS.employee.GET_BY_CERTIFICATE(id).then(function(res){
                $scope.employee = res.data;
            });
            $scope.getIDC(id);
        }
        else if(idd != null)
        {
            $scope.chungchi = name;
            $scope.listEmployeeByDepAndCer(idd,id);
            idc = id;
        }
    };

    //Lấy danh sách nhân viên theo phòng ban
     $scope.listEmployeeByDepartment = function (id, name) {
       // $scope.renameChungchi(); //Rename dropdown box Chứng chỉ về mặc định
        if(idc == null)
        {
            console.log('idc:',idc);
            $scope.phongban = name;
            QLNS.employee.GET_BY_DEPARTMENT(id).then(function(res){
                $scope.employee = res.data;
            });
             $scope.getIDD(id);
        }

        else if (idc != null)
        {
            $scope.phongban = name;
            $scope.listEmployeeByDepAndCer(id,idc);
            idd = id;

        }
    };
    //Lấy danh sách nhân viên theo phòng ban + chứng chỉ
    $scope.listEmployeeByDepAndCer = function(idd,idc){
        // $scope.phongban=nameD;
        // $scope.chungchi=nameC;
        QLNS.employee.GET_BY_CER_DEP(idd,idc).then(function(res){
            $scope.employee = res.data;
        });
        // idd = null;
        // idc = null;
        console.log('idd:'+idd+';idc:'+idc);
    };
    //Lấy id của phòng ban
    var idd = null;
    $scope.getIDD = function(id){
        idd = id;
        console.log('idd:',idd);
        return idd;
    };
    //Lấy id của chứng chỉ
    var idc = null;
    $scope.getIDC = function(id){
        idc = id;
         console.log('idc:',idc);
        return idc;
    };
    //Đổ danh sách phòng ban vào dropdown box phòng ban
    $scope.listDepartment = function (id) {
        QLNS.department.GET().then(function (res) {
            $scope.department = res.data;
        });
    };

    // Lấy mã nhân viên lưu vào biến toàn cục
    $scope.saveIdGobal = function (id) {
        QLNS.values.SET_ID_EMPLOYEE(id);
    };

    // Làm mới trang
    $scope.refesh = function () {
        $scope.getEmployee();
        $scope.getCertificate();
        $scope.listDepartment();
    };

    //Rename dropdown box chứng chỉ và phòng ban
    $scope.renameChungchi = function () {
        if ($scope.chungchi != 'Chứng chỉ') {
            $scope.chungchi = 'Chứng chỉ';
        }
    };

    $scope.renamePhongban = function () {
        if ($scope.phongban != 'Phòng/ Ban') {
            $scope.phongban = 'Phòng/ Ban';
        }
    }
    // Xóa nhân viên
    $scope.delete = function (id) {
        QLNS.employee.DELETE(id).then(function (res) {
            $scope.refesh();
        });
    };

    // Chi tiết nhân viên
    $scope.detail = function (id) {
        QLNS.employee.GET_WITH_ID(id).then(function (res) {
            $scope.oneEmployee = res.data[0];
            $scope.email.ten = res.data[0].TENNV;
            $scope.email.email = res.data[0].EMAIL;
        });
    };

    // Gửi mail cho một nhân viên
    $scope.sendMail = function(){
        QLNS.employee.SENDMAIL($scope.email).then(function(res){
            alert(res.data);
            $scope.clearMail();
        });
    };

    // Làm mới Mail
    $scope.clearMail = function(){
        $scope.email = {
            ten: '',
            email: '',
            content: '',
            subject: ''
        };
    };

    // load dữ liệu khi vào trang
    $scope.refesh();

}]);<commit_msg>fix refresh<commit_after>app.controller('showListEmployeeCtrl', ['$scope', 'QLNS', function ($scope, QLNS) {
    $scope.phongban = 'Phòng/ Ban';
    $scope.chungchi = 'Chứng chỉ';
    $scope.loading = false;

    $scope.email = {
        ten: '',
        email: '',
        content: '',
        subject: ''
    };

    //Lấy toàn bộ danh sách nhân viên
    $scope.getEmployee = function () {
        QLNS.employee.GET().then(function (res) {
            $scope.employee = res.data;
            $scope.loading = true;
            //console.log(res);
            //console.log(res.data[0])
        });
    };

    //Lấy toàn bộ các chứng chỉ
    $scope.getCertificate = function () {
        QLNS.certificate.GET().then(function (res) {
            $scope.certificate = res.data;
            //console.log(res);
            //console.log(res.data[0])
        });
    };

    // Tìm kiếm theo tên nhân viên
    $scope.search = function () {
        QLNS.employee.GET_WITH_NAME($scope.searchName).then(function (res) {
            $scope.employee = res.data;
        });
    };
   //Lấy danh sách nhân viên theo chứng chỉ
    $scope.listCertificate = function (id, name) {
        //$scope.renamePhongban(); //Rename dropdown box Phòng ban về mặc cmn định
        if(idd == null)
        {
            console.log('idd:',idd);
            $scope.chungchi = name;
            QLNS.employee.GET_BY_CERTIFICATE(id).then(function(res){
                $scope.employee = res.data;
            });
            $scope.getIDC(id);
        }
        else if(idd != null)
        {
            $scope.chungchi = name;
            $scope.listEmployeeByDepAndCer(idd,id);
            idc = id;
        }
    };

    //Lấy danh sách nhân viên theo phòng ban
     $scope.listEmployeeByDepartment = function (id, name) {
       // $scope.renameChungchi(); //Rename dropdown box Chứng chỉ về mặc định
        if(idc == null)
        {
            console.log('idc:',idc);
            $scope.phongban = name;
            QLNS.employee.GET_BY_DEPARTMENT(id).then(function(res){
                $scope.employee = res.data;
            });
             $scope.getIDD(id);
        }

        else if (idc != null)
        {
            $scope.phongban = name;
            $scope.listEmployeeByDepAndCer(id,idc);
            idd = id;

        }
    };
    //Lấy danh sách nhân viên theo phòng ban + chứng chỉ
    $scope.listEmployeeByDepAndCer = function(idd,idc){
        // $scope.phongban=nameD;
        // $scope.chungchi=nameC;
        QLNS.employee.GET_BY_CER_DEP(idd,idc).then(function(res){
            $scope.employee = res.data;
        });
        // idd = null;
        // idc = null;
        console.log('idd:'+idd+';idc:'+idc);
    };
    //Lấy id của phòng ban
    var idd = null;
    $scope.getIDD = function(id){
        idd = id;
        console.log('idd:',idd);
        return idd;
    };
    //Lấy id của chứng chỉ
    var idc = null;
    $scope.getIDC = function(id){
        idc = id;
         console.log('idc:',idc);
        return idc;
    };
    //Đổ danh sách phòng ban vào dropdown box phòng ban
    $scope.listDepartment = function (id) {
        QLNS.department.GET().then(function (res) {
            $scope.department = res.data;
        });
    };

    // Lấy mã nhân viên lưu vào biến toàn cục
    $scope.saveIdGobal = function (id) {
        QLNS.values.SET_ID_EMPLOYEE(id);
    };

    // Làm mới trang
    $scope.refesh = function () {
        $scope.getEmployee();
        $scope.getCertificate();
        $scope.listDepartment();
        $scope.phongban = 'Phòng/ Ban';
        $scope.chungchi = 'Chứng chỉ';
    };

    //Rename dropdown box chứng chỉ và phòng ban
    $scope.renameChungchi = function () {
        if ($scope.chungchi != 'Chứng chỉ') {
            $scope.chungchi = 'Chứng chỉ';
        }
    };

    $scope.renamePhongban = function () {
        if ($scope.phongban != 'Phòng/ Ban') {
            $scope.phongban = 'Phòng/ Ban';
        }
    }
    // Xóa nhân viên
    $scope.delete = function (id) {
        QLNS.employee.DELETE(id).then(function (res) {
            $scope.refesh();
        });
    };

    // Chi tiết nhân viên
    $scope.detail = function (id) {
        QLNS.employee.GET_WITH_ID(id).then(function (res) {
            $scope.oneEmployee = res.data[0];
            $scope.email.ten = res.data[0].TENNV;
            $scope.email.email = res.data[0].EMAIL;
        });
    };

    // Gửi mail cho một nhân viên
    $scope.sendMail = function(){
        QLNS.employee.SENDMAIL($scope.email).then(function(res){
            alert(res.data);
            $scope.clearMail();
        });
    };

    // Làm mới Mail
    $scope.clearMail = function(){
        $scope.email = {
            ten: '',
            email: '',
            content: '',
            subject: ''
        };
    };

    // load dữ liệu khi vào trang
    $scope.refesh();

}]);<|endoftext|>


<commit_before>locations = new Class({
    name : null,
    url  : null,

    initialize : function(name, value, url) {
        this.name = name;
        this.url  = url;
        this.fill(value);
    },

    fill : function(value) {
        this.default_value = value;
        new Request.JSON({
            url      : this.url+'/locations/frontend/search/getSiblings/'+value,
            onSuccess: this.create.bind(this)
        }).get();
    },

    select : function() {
        new_select = new Element('select', {
                                    name : this.name+'[]',
                                    class : 'locations_'+this.name
                                });
        new_select.addEvent('change', function(e) { this.refresh(e.target); }.bind(this));
        return new_select;
    },

    option : function(location) {
        var option = new Element('option');

        if (location) {
            option.set({value:location.id});

            if (location.name.length > 1) {
                option.set({html:location.name});
            } else if(location.english.length > 1) {
                option.set({html:location.english});
            } else {
                option.set({html:location.code});
            }
            if (this.default_value == location.id) {
                option.set({selected:'selected'});
            }
        }
        return option;
    },

    container : function() {
        return $('container_'+this.name);
    },

    create : function(locations) {
        if (!locations || locations.length == 0)
            return false;

        var blank = this.option().set({value:'', html:'--', selected:'selected'});
        new_select = this.select();
        new_select.adopt(blank);

        locations.each(function(location) {
            new_select.adopt(this.option(location));
        }.bind(this));

        var br = new Element('br').inject(this.container(), 'after');
        new_select.inject(br, 'after');

        var parent = locations['0']['parent'];

        if (parent > 0) {
            new Request.JSON({
                url      : this.url+'/locations/frontend/search/getSiblings/'+parent,
                onSuccess: function(parents) {
                                this.default_value = parent;
                                this.create(parents);
                           }.bind(this)
            }).get();
        }
    },

    refresh : function(select) {
        select.getAllNext('.'+select.get('class')).dispose(); //Destroy all 'Next' elements.

        if (select.get('value') == '') // Blank is selected, do nothing.
            return false;

        var location = select.get('value'); //Get the selected option's value.

        new Request.JSON({
            url      : this.url+'/locations/frontend/search/getByParent/'+location,
            onSuccess: function(locations) {
                if (!locations || locations.length == 0)
                    return false;

                var blank = this.option().set({value:'', html:'--', selected:'selected'});
                new_select = this.select();
                new_select.adopt(blank);

                locations.each(function(location) {
                    new_select.adopt(this.option(location));
                }.bind(this));

                var br = new Element('br').inject(select, 'after');
                new_select.inject(br, 'after');
            }.bind(this)
        }).get();
    }
});<commit_msg>locations now works in crap ie<commit_after>locations = new Class({
    name : null,
    url  : null,

    initialize : function(name, value, url) {
        this.name = name;
        this.url  = url;
        this.fill(value);
    },

    fill : function(value) {
        this.default_value = value;
        new Request.JSON({
            url      : this.url+'/locations/frontend/search/getSiblings/'+value,
            onSuccess: this.create.bind(this)
        }).get();
    },

    select : function() {
        new_select = new Element('select', {name : this.name+'[]'}).set('class', 'locations_'+this.name);
        new_select.addEvent('change', function(e) { this.refresh(e.target); }.bind(this));
        return new_select;
    },

    option : function(location) {
        var option = new Element('option');

        if (location) {
            option.set({value:location.id});

            if (location.name.length > 1) {
                option.set({html:location.name});
            } else if(location.english.length > 1) {
                option.set({html:location.english});
            } else {
                option.set({html:location.code});
            }
            if (this.default_value == location.id) {
                option.set({selected:'selected'});
            }
        }
        return option;
    },

    container : function() {
        return $('container_'+this.name);
    },

    create : function(locations) {
        if (!locations || locations.length == 0)
            return false;

        var blank = this.option().set({value:'', html:'--', selected:'selected'});
        new_select = this.select();
        new_select.adopt(blank);

        locations.each(function(location) {
            new_select.adopt(this.option(location));
        }.bind(this));

        var br = new Element('br').inject(this.container(), 'after');
        new_select.inject(br, 'after');

        var parent = locations['0']['parent'];

        if (parent > 0) {
            new Request.JSON({
                url      : this.url+'/locations/frontend/search/getSiblings/'+parent,
                onSuccess: function(parents) {
                                this.default_value = parent;
                                this.create(parents);
                           }.bind(this)
            }).get();
        }
    },

    refresh : function(select) {
        select.getAllNext('.'+select.get('class')).dispose(); //Destroy all 'Next' elements.

        if (select.get('value') == '') // Blank is selected, do nothing.
            return false;

        var location = select.get('value'); //Get the selected option's value.

        new Request.JSON({
            url      : this.url+'/locations/frontend/search/getByParent/'+location,
            onSuccess: function(locations) {
                if (!locations || locations.length == 0)
                    return false;

                var blank = this.option().set({value:'', html:'--', selected:'selected'});
                new_select = this.select();
                new_select.adopt(blank);

                locations.each(function(location) {
                    new_select.adopt(this.option(location));
                }.bind(this));

                var br = new Element('br').inject(select, 'after');
                new_select.inject(br, 'after');
            }.bind(this)
        }).get();
    }
});<|endoftext|>


<commit_before>window.urb.seqn_s = 0

window.urb.send = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.send.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.send.")
    params.appl = urb.appl
  }
  if(!params.data) { params.data = {}; }

  var method, perm, url, $this

  type = params.type ? params.type : "mes"
  perm = this.perms[type]

  params.ship = params.ship ? params.ship : this.ship
  params.mark = params.mark ? params.mark : "json"

  method = "put"
  url = [perm,this.user,this.port,this.seqn_s]
  url = "/"+url.join("/")

  this.seqn_s++

  $this = this
  this.qreq(method,url,params,true,function(err,data) {
    if(err) { $this.seqn_s--; }
    if(cb) { cb.apply(this,arguments); }
  })
}

window.urb.subscribe = function(params,cb) {
  if(!cb)
    throw new Error("You must supply a callback to urb.subscribe.")
  if(!params)
    throw new Error("You must supply params to urb.subscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.subscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.subscribe.")
  params.ship = params.ship ? params.ship : this.ship

  var method, perm, url, $this

  params.type = "sub"

  this.cabs[this.gsig(params)] = cb

  url = [this.perms["sub"],this.user,this.port]
  url = "/"+url.join("/")
  method = "put"

  $this = this
  this.qreq(method,url,params,true,function(err,data) {
    if(cb) { cb.apply(this,[err,{status: data.status, data: data.data}])}
    if(!err && $this.puls == 0) {
      params.type = "pol"
      $this.poll(params)
    }
  })
}

window.urb.unsubscribe = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.unsubscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.unsubscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.unsubscribe.")
  params.ship = params.ship ? params.ship : this.ship

  method = "put"
  type = "uns"
  url = [this.perms[type],this.user,this.port]
  url = "/"+url.join("/")

  var $this = this
  this.req(method,url,params,true,function(err,data) {
    $this.cabs[$this.gsig(params)]('subscription closed')
    delete $this.cabs[$this.gsig(params)]
  })
}

window.urb.util = {
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + dat.getUTCHours() +
            '.' + dat.getUTCMinutes() +
            '.' + dat.getUTCSeconds() +
           '..' + ('0000' + mils).substr(-4, 4)
  }
}
<commit_msg>unsubscribe correctly<commit_after>window.urb.seqn_s = 0

window.urb.send = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.send.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.send.")
    params.appl = urb.appl
  }
  if(!params.data) { params.data = {}; }

  var method, perm, url, $this

  type = params.type ? params.type : "mes"
  perm = this.perms[type]

  params.ship = params.ship ? params.ship : this.ship
  params.mark = params.mark ? params.mark : "json"

  method = "put"
  url = [perm,this.user,this.port,this.seqn_s]
  url = "/"+url.join("/")

  this.seqn_s++

  $this = this
  this.qreq(method,url,params,true,function(err,data) {
    if(err) { $this.seqn_s--; }
    if(cb) { cb.apply(this,arguments); }
  })
}

window.urb.subscribe = function(params,cb) {
  if(!cb)
    throw new Error("You must supply a callback to urb.subscribe.")
  if(!params)
    throw new Error("You must supply params to urb.subscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.subscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.subscribe.")
  params.ship = params.ship ? params.ship : this.ship

  var method, perm, url, $this

  params.type = "sub"

  this.cabs[this.gsig(params)] = cb

  url = [this.perms["sub"],this.user,this.port]
  url = "/"+url.join("/")
  method = "put"

  $this = this
  this.qreq(method,url,params,true,function(err,data) {
    if(cb) { cb.apply(this,[err,{status: data.status, data: data.data}])}
    if(!err && $this.puls == 0) {
      params.type = "pol"
      $this.poll(params)
    }
  })
}

window.urb.unsubscribe = function(params,cb) {
  if(!params)
    throw new Error("You must supply params to urb.unsubscribe.")
  if(!params.appl) {
    if(!urb.appl)
      throw new Error("You must specify an appl for urb.unsubscribe.")
    params.appl = urb.appl
  }
  if(!params.path)
    throw new Error("You must specify a path for urb.unsubscribe.")
  params.ship = params.ship ? params.ship : this.ship

  method = "put"
  type = "uns"
  url = [this.perms[type],this.user,this.port]
  url = "/"+url.join("/")

  var $this = this
  this.req(method,url,params,true,function(err,data) {
    cb(err,data)
  })
}

window.urb.util = {
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + dat.getUTCHours() +
            '.' + dat.getUTCMinutes() +
            '.' + dat.getUTCSeconds() +
           '..' + ('0000' + mils).substr(-4, 4)
  }
}
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.delay = delay;

var _ = require('.');

/**
 * Wraps a tree-returning function with a tree proxy that will shallow evaluate
 * as soon as a method is called on it.
 *
 * @param Function thunk The function that evaluates to the underlying tree.
 * @returns {Tree} The lazy tree.
 */
function delay(thunk) {
  return new _.Lazy(thunk);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy80LWxhenkvMS1kZWxheS5qcyJdLCJuYW1lcyI6WyJkZWxheSIsInRodW5rIl0sIm1hcHBpbmdzIjoiOzs7OztRQVNnQkEsSyxHQUFBQSxLOztBQVRoQjs7QUFFQTs7Ozs7OztBQU9PLFNBQVNBLEtBQVQsQ0FBaUJDLEtBQWpCLEVBQXlCO0FBQy9CLFNBQU8sV0FBVUEsS0FBVixDQUFQO0FBQ0EiLCJmaWxlIjoiMS1kZWxheS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IExhenkgfSBmcm9tICcuJyA7XG5cbi8qKlxuICogV3JhcHMgYSB0cmVlLXJldHVybmluZyBmdW5jdGlvbiB3aXRoIGEgdHJlZSBwcm94eSB0aGF0IHdpbGwgc2hhbGxvdyBldmFsdWF0ZVxuICogYXMgc29vbiBhcyBhIG1ldGhvZCBpcyBjYWxsZWQgb24gaXQuXG4gKlxuICogQHBhcmFtIEZ1bmN0aW9uIHRodW5rIFRoZSBmdW5jdGlvbiB0aGF0IGV2YWx1YXRlcyB0byB0aGUgdW5kZXJseWluZyB0cmVlLlxuICogQHJldHVybnMge1RyZWV9IFRoZSBsYXp5IHRyZWUuXG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBkZWxheSAoIHRodW5rICkge1xuXHRyZXR1cm4gbmV3IExhenkoIHRodW5rICkgO1xufVxuIl19<commit_msg>rebuild<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.delay = delay;

var _ = require('.');

/**
 * Wraps a tree-returning function with a tree proxy that will shallow evaluate
 * as soon as a method is called on it.
 *
 * @param {Function} thunk The function that evaluates to the underlying tree.
 * @returns {Tree} The lazy tree.
 */
function delay(thunk) {
  return new _.Lazy(thunk);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy80LWxhenkvMS1kZWxheS5qcyJdLCJuYW1lcyI6WyJkZWxheSIsInRodW5rIl0sIm1hcHBpbmdzIjoiOzs7OztRQVNnQkEsSyxHQUFBQSxLOztBQVRoQjs7QUFFQTs7Ozs7OztBQU9PLFNBQVNBLEtBQVQsQ0FBaUJDLEtBQWpCLEVBQXlCO0FBQy9CLFNBQU8sV0FBVUEsS0FBVixDQUFQO0FBQ0EiLCJmaWxlIjoiMS1kZWxheS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IExhenkgfSBmcm9tICcuJyA7XG5cbi8qKlxuICogV3JhcHMgYSB0cmVlLXJldHVybmluZyBmdW5jdGlvbiB3aXRoIGEgdHJlZSBwcm94eSB0aGF0IHdpbGwgc2hhbGxvdyBldmFsdWF0ZVxuICogYXMgc29vbiBhcyBhIG1ldGhvZCBpcyBjYWxsZWQgb24gaXQuXG4gKlxuICogQHBhcmFtIHtGdW5jdGlvbn0gdGh1bmsgVGhlIGZ1bmN0aW9uIHRoYXQgZXZhbHVhdGVzIHRvIHRoZSB1bmRlcmx5aW5nIHRyZWUuXG4gKiBAcmV0dXJucyB7VHJlZX0gVGhlIGxhenkgdHJlZS5cbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGRlbGF5ICggdGh1bmsgKSB7XG5cdHJldHVybiBuZXcgTGF6eSggdGh1bmsgKSA7XG59XG4iXX0=<|endoftext|>


<commit_before>var http = require('http'),
  request = require('request'),
  _ = require('underscore')._,
  querystring = require('querystring');

function EchoNestAPI_v4(apiKey, options) {
  this.version = '4';
  this.apiKey = apiKey;
  this.apiUrl = 'http://developer.echonest.com/api/v4/'
}

module.exports = EchoNestAPI_v4;

EchoNestAPI_v4.prototype.howdy = function() {
  return "Howdy!";
};

EchoNestAPI_v4.prototype.execute = function(type, method, availableParams, givenParams, callback) {
  var finalParams = { api_key : this.apiKey, format : 'json' };

  for (var i = 0; i < availableParams.length; i++) {
    currentParam = availableParams[i];
    if (typeof givenParams[currentParam] !== 'undefined')
      finalParams[currentParam] = givenParams[currentParam];
  }
  var uri = this.apiUrl + type + '/' + method + '?' + querystring.stringify(finalParams);
  request(uri, function (error, response, body) {
    var parsedResponse;
    if (error) {
      return callback({
        error : 'Unable to connect to the Echo Nest API endpoint.',
        code : 'xxx'
      });
    }
    try {
      parsedResponse = JSON.parse(body);
    } catch (error) {
      callback({ error : 'Error parsing JSON answer from the Echo Nest API.', code : 'xxx'});
    }
    callback(parsedResponse);
  });
};<commit_msg>tweaking echonest execute code<commit_after>var http = require('http'),
  request = require('request'),
  _ = require('underscore')._,
  querystring = require('querystring');

function EchoNestAPI_v4(apiKey, options) {
  this.version = '4';
  this.apiKey = apiKey;
  this.apiUrl = 'http://developer.echonest.com/api/v4/'
}

module.exports = EchoNestAPI_v4;

EchoNestAPI_v4.prototype.howdy = function() {
  return "Howdy!";
};

EchoNestAPI_v4.prototype.execute = function(type, method, availableParams, givenParams, callback) {
  var finalParams = { api_key : this.apiKey, format : 'json' };

  for (var i = 0; i < availableParams.length; i++) {
    currentParam = availableParams[i];
    if (typeof givenParams[currentParam] !== 'undefined')
      finalParams[currentParam] = givenParams[currentParam];
  }
  var uri = this.apiUrl + type + '/' + method + '?' + querystring.stringify(finalParams);
  request(uri, function (error, response, body) {
    var parsedResponse;
    if (error) {
      callback({
        error : 'Unable to connect to the Echo Nest API endpoint.',
        code : 'xxx'
      });
    } else {
      try {
        parsedResponse = JSON.parse(body);
      } catch (error) {
        callback({ error : 'Error parsing JSON answer from the Echo Nest API.', code : 'xxx'});
      }
      callback(parsedResponse);
    }
  });
};<|endoftext|>


<commit_before>/*jslint node: true */
/*jshint laxbreak: true */
/*jshint laxcomma: true */
//'use strict';

var _ = require("underscore");
var DataLoader = require("./dataLoader");
var CategoryFactory = require("./CategoryFactory");
var d3 = require("d3");
var ViewerFactory = require("./ViewerFactory");

var FeaturesViewer = function(opts) {
    var fv = this;

    fv.dispatcher = d3.dispatch("featureSelected", "featureDeselected", "ready");
    fv.width = 760;
    fv.maxZoomSize = 30;
    fv.selectedFeature = undefined;
    fv.selectedFeatureElement = undefined;
    fv.sequence = "";

    var	padding = {
        top:2,
        right:10,
        bottom:2,
        left:10
    };

    var categories = [];

    var updateZoomFromChart = function() {
        fv.zoom.x(fv.xScale);

        var fullDomain = fv.maxPos - 1,
            currentDomain = fv.xScale.domain()[1] - fv.xScale.domain()[0];

        var minScale = currentDomain / fullDomain,
            maxScale = minScale * 20;

        fv.zoom.scaleExtent([minScale, maxScale]);
    };

    var updateViewportFromChart = function () {
        if ((fv.xScale.domain()[0] <= 1) && (fv.xScale.domain()[1] >= fv.maxPos)) {
            fv.viewport.clear();
        } else {
            fv.viewport.extent(fv.xScale.domain());
        }
        d3.select('.up_pftv_viewport').call(fv.viewport);
        if (((fv.xScale.domain()[0] <= 1) && (fv.xScale.domain()[1] >= fv.maxPos))) {
            fv.viewport.clearTrapezoid();
        } else {
            fv.viewport.updateTrapezoid();
        }
    };

    var update = function() {
        fv.aaViewer.update();
        _.each(categories, function(category) {
            category.update();
        });
    };

    var zoomIn = function() {
        fv.xScale.domain([
            1,
            fv.maxZoomSize
        ]);
        update();
        updateViewportFromChart();
        updateZoomFromChart();
    };

    var resetZoomAndSelection = function() {
        fv.xScale.domain([
            1,
            fv.maxPos
        ]);
        if (fv.selectedFeature) {
            ViewerFactory.selectFeature(fv.selectedFeature, fv.selectedFeatureElement, fv);
        }
        update();
        updateViewportFromChart();
        updateZoomFromChart();
    };

    var createZoom = function() {
        var zoom = d3.behavior.zoom()
            .x(fv.xScale)
            .on('zoom', function() {
                if (fv.xScale.domain()[0] < 1) {
                    var tempX = zoom.translate()[0] - fv.xScale(1) + fv.xScale.range()[0];
                    zoom.translate([tempX, 0]);
                } else if (fv.xScale.domain()[1] > fv.maxPos) {
                    var translatedX = zoom.translate()[0] - fv.xScale(fv.maxPos) + fv.xScale.range()[1];
                    zoom.translate([translatedX, 0]);
                }
                update();
                updateViewportFromChart();
            });
        return zoom;
    };

    var createNavRuler = function(container) {
        var navWidth = fv.width
            , navHeight = 40
            , navWithTrapezoid = 50;

        var navXScale = d3.scale.linear()
            .domain([1,fv.maxPos])
            .range([0,navWidth]);

        var svg = container
            .append('div')
            .attr('class', 'up_pftv_navruler')
            .append('svg')
            .attr('id','up_pftv_svg-navruler')
            .attr('width', fv.width)
            .attr('height', (navWithTrapezoid));

        var navXAxis = d3.svg.axis()
            .scale(fv.xScale)
            .ticks(20)
            .orient('bottom');

        svg.append('g')
            .attr('class', 'x axis')
            .call(navXAxis);

        var viewport = d3.svg.brush()
            .x(navXScale)
            .on("brush", function() {
                var s = d3.event.target.extent();
                if((s[1] - s[0]) < fv.maxZoomSize) {
                    d3.event.target.extent([s[0],s[0] + fv.maxZoomSize]);
                    d3.event.target(d3.select(this));
                }
                fv.xScale.domain(viewport.empty() ? navXScale.domain() : viewport.extent());
                update(s[1] - s[0]);
                viewport.updateTrapezoid();
            });

        viewport.on("brushend", function () {
            updateZoomFromChart();
        });

        svg.append("g")
            .attr("class", "up_pftv_viewport")
            .call(viewport)
            .selectAll("rect")
            .attr("height", navHeight);

        viewport.trapezoid = svg.append("g")
            .selectAll("path")
            .data([0]).enter().append("path")
            .classed("up_pftv_trapezoid", true);

        viewport.updateTrapezoid = function() {
            var begin = d3.select(".up_pftv_navruler .extent").attr("x");
            var tWidth = d3.select(".up_pftv_navruler .extent").attr("width");
            var end = (+begin) + (+tWidth);
            var path =  "M0," + (navWithTrapezoid)
                + "L0" + "," + (navWithTrapezoid-2)
                + "L" + begin + "," + navHeight
                + "L" + end + "," + navHeight
                + "L" + fv.width + "," + (navWithTrapezoid-2)
                + "L" + fv.width + "," + (navWithTrapezoid) + "Z";
            this.trapezoid.attr("d", path);
        };

        viewport.clearTrapezoid = function() {
            this.trapezoid.attr("d", "M0,0");
        };

        return viewport;
    };

    var createButtons = function(container) {
        var buttons = container.append('div')
            .attr('class','up_pftv_buttons');
        buttons.append('span')
            .attr('class','up_pftv_icon-arrows-cw')
            .attr('title','Reset view')
            .on('click', function(){
                resetZoomAndSelection();
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-zoom-in')
            .attr('title','Zoom in')
            .on('click', function(){
                zoomIn();
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-filter')
            .attr('title','Filter')
            .on('click', function(){
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-info')
            .attr('title','Help')
            .on('click', function(){
            });
    };

    var createAAViewer = function(container, sequence) {
        var aaViewer = this;
        var aaViewWidth = fv.width,
            aaViewHeight = 15;

        var svg = container
            .append('div')
            .attr('class','up_pftv_aaviewer')
            .append('svg')
            .attr('width', aaViewWidth)
            .attr('height',aaViewHeight);

        //amino acids
        var aaPlot = function(){
            var series,
                aminoAcids;

            var aaPlot = function(selection){

                selection.each(function(data){
                    series = d3.select(this);
                    aminoAcids = series.selectAll('.up_pftv_amino-acid')
                        .data(data);

                    aminoAcids.enter().append('text').style('text-anchor','middle');

                    aminoAcids.attr('x', function(d, i) {
                        return fv.xScale(i+1);
                    })
                        .attr('y', aaViewHeight / 2)
                        .text(function(d) {
                            return d.toUpperCase();
                        })
                        .attr('class','up_pftv_amino-acid');

                    aminoAcids.exit().remove();
                });
            };

            return aaPlot;
        };

        var series = aaPlot();

        var g = svg.append('g')
            .attr('clip-path','url(#aaViewClip)')
            .attr('transform','translate(0,' + aaViewHeight/5 +  ')')
            .style('opacity',0);

        g.datum(sequence.split(''))
            .call(series);

        //amino acids selector
        var aaSelectorPlot = function(){
            var series,
                aminoAcids;

            var aaSelectorPlot = function(selection) {
                selection.each(function(data) {
                    series = d3.select(this);
                    aminoAcids = series.selectAll('.up_pftv_amino_acid_selector')
                        .data(data);

                    aminoAcids.enter().append('rect');

                    aminoAcids.attr('x', function(d) {
                        gapRegion = (fv.xScale(2)-fv.xScale(1))/2;
                        return fv.xScale(d.feature.begin) - gapRegion;
                    })
                        .attr('y', 0)
                        .attr('width', function(d) {
                            return ((d.feature.end) ? d.feature.end - d.feature.begin + 1 : 1) * (fv.xScale(2)-fv.xScale(1));
                        })
                        .attr('height', 12)
                        .classed('up_pftv_amino_acid_selector', true);

                    aminoAcids.exit().remove();
                });
            };

            return aaSelectorPlot;
        };

        var selectorSeries = aaSelectorPlot();

        var selectorGroup = svg.append('g')
            .attr('clip-path','url(#aaSelectorViewClip)')
            .style('opacity',0);

        selectorGroup.datum([{"feature": {"begin": -10, "end": -10}, "clazz": ""}])
            .call(selectorSeries);

        aaViewer.update = function() {
            g.call(series);
            selectorGroup.call(selectorSeries);
            var count = fv.xScale.domain()[1] - fv.xScale.domain()[0];
            if(count>70) {
                g.transition(50).style('opacity',0);
                selectorGroup.transition(50).style('opacity',0);
            }
            else {
                g.transition(50).style('opacity',1);
                selectorGroup.transition(50).style('opacity',1);
            }
        };

        aaViewer.selectFeature = function(clazz) {
            if (fv.selectedFeature) {
                selectorGroup.datum([{"feature": fv.selectedFeature, "clazz": clazz}]).call(selectorSeries);
            } else {
                selectorGroup.datum([{"feature": {"begin": -10, "end": -10}, "clazz": ""}]).call(selectorSeries);
            }

        };

        return aaViewer;
    };

    var addCategory = function(category) {
        categories.push(category);
    };

    var init = function(d) {
        fv.sequence = d.sequence;
        fv.maxPos = d.sequence.length;
        fv.xScale = d3.scale.linear()
            .domain([1, d.sequence.length + 1])
            .range([padding.left, fv.width - padding.right]);
        //remove any previous text
        var fvContainer = d3.select(opts.el)
            .text('')
            .append('div')
            .attr('class', 'up_pftv_container');

        fv.viewport = createNavRuler(fvContainer);
        createButtons(fvContainer);
        fv.aaViewer = createAAViewer(fvContainer, d.sequence);
        fv.zoom = createZoom(d.sequence.length + 1);

        fv.container = fvContainer
            .append('div')
            .attr('class', 'up_pftv_category-container');

        addCategory(CategoryFactory.createCategory(d.domainsAndSites, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.moleculeProcessing, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.ptm, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.seqInfo, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.structural, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.topology, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.mutagenesis, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.variants, 'variant', fv));
    };

    fv.load = function() {
        var dataLoader = DataLoader.get(opts.uniprotacc);
        dataLoader.done(function(d) {
            init(d);
            fv.dispatcher.ready(d);
        });
    };

    fv.load();
};

FeaturesViewer.prototype.getDispatcher = function getDispatcher() {
    return this.dispatcher;
};

module.exports = FeaturesViewer;<commit_msg>Revert "Reduce? Sonar issues."<commit_after>/*jslint node: true */
/*jshint laxbreak: true */
/*jshint laxcomma: true */
//'use strict';

var _ = require("underscore");
var DataLoader = require("./dataLoader");
var CategoryFactory = require("./CategoryFactory");
var d3 = require("d3");
var ViewerFactory = require("./ViewerFactory");

var FeaturesViewer = function(opts) {
    var fv = this;

    fv.dispatcher = d3.dispatch("featureSelected", "featureDeselected", "ready");
    fv.width = 760;
    fv.maxZoomSize = 30;
    fv.selectedFeature = undefined;
    fv.selectedFeatureElement = undefined;
    fv.sequence = "";

    var	padding = {
        top:2,
        right:10,
        bottom:2,
        left:10
    };

    var categories = [];

    var updateZoomFromChart = function() {
        fv.zoom.x(fv.xScale);

        var fullDomain = fv.maxPos - 1,
            currentDomain = fv.xScale.domain()[1] - fv.xScale.domain()[0];

        var minScale = currentDomain / fullDomain,
            maxScale = minScale * 20;

        fv.zoom.scaleExtent([minScale, maxScale]);
    };

    var updateViewportFromChart = function () {
        if ((fv.xScale.domain()[0] <= 1) && (fv.xScale.domain()[1] >= fv.maxPos)) {
            fv.viewport.clear();
        } else {
            fv.viewport.extent(fv.xScale.domain());
        }
        d3.select('.up_pftv_viewport').call(fv.viewport);
        if (((fv.xScale.domain()[0] <= 1) && (fv.xScale.domain()[1] >= fv.maxPos))) {
            fv.viewport.clearTrapezoid();
        } else {
            fv.viewport.updateTrapezoid();
        }
    };

    var update = function() {
        fv.aaViewer.update();
        _.each(categories, function(category) {
            category.update();
        });
    };

    var zoomIn = function() {
        fv.xScale.domain([
            1,
            fv.maxZoomSize
        ]);
        update();
        updateViewportFromChart();
        updateZoomFromChart();
    };

    var resetZoomAndSelection = function() {
        fv.xScale.domain([
            1,
            fv.maxPos
        ]);
        if (fv.selectedFeature) {
            ViewerFactory.selectFeature(fv.selectedFeature, fv.selectedFeatureElement, fv);
        }
        update();
        updateViewportFromChart();
        updateZoomFromChart();
    };

    var createZoom = function() {
        var zoom = d3.behavior.zoom()
            .x(fv.xScale)
            .on('zoom', function() {
                if (fv.xScale.domain()[0] < 1) {
                    var tempX = zoom.translate()[0] - fv.xScale(1) + fv.xScale.range()[0];
                    zoom.translate([tempX, 0]);
                } else if (fv.xScale.domain()[1] > fv.maxPos) {
                    var translatedX = zoom.translate()[0] - fv.xScale(fv.maxPos) + fv.xScale.range()[1];
                    zoom.translate([translatedX, 0]);
                }
                update();
                updateViewportFromChart();
            });
        return zoom;
    };

    var createNavRuler = function(container) {
        var navWidth = fv.width
            , navHeight = 40
            , navWithTrapezoid = 50;

        var navXScale = d3.scale.linear()
            .domain([1,fv.maxPos])
            .range([0,navWidth]);

        var svg = container
            .append('div')
            .attr('class', 'up_pftv_navruler')
            .append('svg')
            .attr('id','up_pftv_svg-navruler')
            .attr('width', fv.width)
            .attr('height', (navWithTrapezoid));

        var navXAxis = d3.svg.axis()
            .scale(fv.xScale)
            .ticks(20)
            .orient('bottom');

        var g = svg.append('g')
            .attr('class', 'x axis')
            .call(navXAxis);

        var viewport = d3.svg.brush()
            .x(navXScale)
            .on("brush", function() {
                var s = d3.event.target.extent();
                if((s[1] - s[0]) < fv.maxZoomSize) {
                    d3.event.target.extent([s[0],s[0] + fv.maxZoomSize]);
                    d3.event.target(d3.select(this));
                }
                fv.xScale.domain(viewport.empty() ? navXScale.domain() : viewport.extent());
                update(s[1] - s[0]);
                viewport.updateTrapezoid();
            });

        viewport.on("brushend", function () {
            updateZoomFromChart();
        });

        svg.append("g")
            .attr("class", "up_pftv_viewport")
            .call(viewport)
            .selectAll("rect")
            .attr("height", navHeight);

        viewport.trapezoid = svg.append("g")
            .selectAll("path")
            .data([0]).enter().append("path")
            .classed("up_pftv_trapezoid", true);

        viewport.updateTrapezoid = function() {
            var begin = d3.select(".up_pftv_navruler .extent").attr("x");
            var tWidth = d3.select(".up_pftv_navruler .extent").attr("width");
            var end = (+begin) + (+tWidth);
            var path =  "M0," + (navWithTrapezoid)
                + "L0" + "," + (navWithTrapezoid-2)
                + "L" + begin + "," + navHeight
                + "L" + end + "," + navHeight
                + "L" + fv.width + "," + (navWithTrapezoid-2)
                + "L" + fv.width + "," + (navWithTrapezoid) + "Z";
            this.trapezoid.attr("d", path);
        };

        viewport.clearTrapezoid = function() {
            this.trapezoid.attr("d", "M0,0");
        };

        return viewport;
    };

    var createButtons = function(container) {
        var buttons = container.append('div')
            .attr('class','up_pftv_buttons');
        buttons.append('span')
            .attr('class','up_pftv_icon-arrows-cw')
            .attr('title','Reset view')
            .on('click', function(){
                resetZoomAndSelection();
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-zoom-in')
            .attr('title','Zoom in')
            .on('click', function(){
                zoomIn();
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-filter')
            .attr('title','Filter')
            .on('click', function(){
            });
        buttons.append('span')
            .attr('class','up_pftv_icon-info')
            .attr('title','Help')
            .on('click', function(){
            });
    };

    var createAAViewer = function(container, sequence) {
        var aaViewer = this;
        var aaViewWidth = fv.width,
            aaViewHeight = 15;

        var svg = container
            .append('div')
            .attr('class','up_pftv_aaviewer')
            .append('svg')
            .attr('width', aaViewWidth)
            .attr('height',aaViewHeight);

        //amino acids
        var aaPlot = function(){
            var series,
                aminoAcids;

            var aaPlot = function(selection){

                selection.each(function(data){
                    series = d3.select(this);
                    aminoAcids = series.selectAll('.up_pftv_amino-acid')
                        .data(data);

                    aminoAcids.enter().append('text').style('text-anchor','middle');

                    aminoAcids.attr('x', function(d, i) {
                        return fv.xScale(i+1);
                    })
                        .attr('y', aaViewHeight / 2)
                        .text(function(d) {
                            return d.toUpperCase();
                        })
                        .attr('class','up_pftv_amino-acid');

                    aminoAcids.exit().remove();
                });
            };

            return aaPlot;
        };

        var series = aaPlot();

        var g = svg.append('g')
            .attr('clip-path','url(#aaViewClip)')
            .attr('transform','translate(0,' + aaViewHeight/5 +  ')')
            .style('opacity',0);

        g.datum(sequence.split(''))
            .call(series);

        //amino acids selector
        var aaSelectorPlot = function(){
            var series,
                aminoAcids;

            var aaSelectorPlot = function(selection) {
                selection.each(function(data) {
                    series = d3.select(this);
                    aminoAcids = series.selectAll('.up_pftv_amino_acid_selector')
                        .data(data);

                    aminoAcids.enter().append('rect');

                    aminoAcids.attr('x', function(d, i) {
                        gapRegion = (fv.xScale(2)-fv.xScale(1))/2;
                        return fv.xScale(d.feature.begin) - gapRegion;
                    })
                        .attr('y', 0)
                        .attr('width', function(d, i) {
                            return ((d.feature.end) ? d.feature.end - d.feature.begin + 1 : 1) * (fv.xScale(2)-fv.xScale(1));
                        })
                        .attr('height', 12)
                        .classed('up_pftv_amino_acid_selector', true);

                    aminoAcids.exit().remove();
                });
            };

            return aaSelectorPlot;
        };

        var selectorSeries = aaSelectorPlot();

        var selectorGroup = svg.append('g')
            .attr('clip-path','url(#aaSelectorViewClip)')
            .style('opacity',0);

        selectorGroup.datum([{"feature": {"begin": -10, "end": -10}, "clazz": ""}])
            .call(selectorSeries);

        aaViewer.update = function() {
            g.call(series);
            selectorGroup.call(selectorSeries);
            var count = fv.xScale.domain()[1] - fv.xScale.domain()[0];
            if(count>70) {
                g.transition(50).style('opacity',0);
                selectorGroup.transition(50).style('opacity',0);
            }
            else {
                g.transition(50).style('opacity',1);
                selectorGroup.transition(50).style('opacity',1);
            }
        };

        aaViewer.selectFeature = function(clazz) {
            if (fv.selectedFeature) {
                selectorGroup.datum([{"feature": fv.selectedFeature, "clazz": clazz}]).call(selectorSeries);
            } else {
                selectorGroup.datum([{"feature": {"begin": -10, "end": -10}, "clazz": ""}]).call(selectorSeries);
            }

        };

        return aaViewer;
    };

    var addCategory = function(category) {
        categories.push(category);
    };

    var init = function(d) {
        fv.sequence = d.sequence;
        fv.maxPos = d.sequence.length;
        fv.xScale = d3.scale.linear()
            .domain([1, d.sequence.length + 1])
            .range([padding.left, fv.width - padding.right]);
        //remove any previous text
        var fvContainer = d3.select(opts.el)
            .text('')
            .append('div')
            .attr('class', 'up_pftv_container');

        fv.viewport = createNavRuler(fvContainer);
        createButtons(fvContainer);
        fv.aaViewer = createAAViewer(fvContainer, d.sequence);
        fv.zoom = createZoom(d.sequence.length + 1);

        fv.container = fvContainer
            .append('div')
            .attr('class', 'up_pftv_category-container');

        addCategory(CategoryFactory.createCategory(d.domainsAndSites, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.moleculeProcessing, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.ptm, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.seqInfo, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.structural, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.topology, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.mutagenesis, 'basic', fv));
        addCategory(CategoryFactory.createCategory(d.variants, 'variant', fv));
    };

    fv.load = function() {
        var dataLoader = DataLoader.get(opts.uniprotacc);
        dataLoader.done(function(d) {
            init(d);
            fv.dispatcher.ready(d);
        });
    };

    fv.load();
};

FeaturesViewer.prototype.getDispatcher = function getDispatcher() {
    return this.dispatcher;
};

module.exports = FeaturesViewer;<|endoftext|>


<commit_before>/*

Autogenerating Music Exercises for education program "Muusika Kompositsiooniõpetus" https://et.wikibooks.org/wiki/Muusika_kompositsiooni%C3%B5petus/N%C3%84IDISKURSUS._G%C3%9CMNAASIUM
Commissioned by Estonian Ministry of Education and Research, Tallinn University,  in the frame of Digital Learning Resources project DigiÕppeVaramu https://htk.tlu.ee/oppevara/

Copyright 2018, by Tarmo Johannes trmjhnns@gmail.com

License: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

// Base class for Music Exercises
// uses VexTab / VexFlow for notation
// WebAudiofontPlayer for audio playback

// the host webpage must load:
// <script src="https://unpkg.com/vextab/releases/vextab-div.js"></script>
// <script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
// <script src='https://surikov.github.io/webaudiofontdata/sound/0000_JCLive_sf2_file.js'></script>

function MusicExercise(containerNode, canvasClassName, width, x, y, scale, ) {
	this.containerNode = containerNode===undefined ? document.body : containerNode; // to  make it independent and enable to use several exercises per page

	if (canvasClassName === undefined) { // if not given, create div for canvas
		this.canvas = document.createElement("div");
		this.canvas.className = "mainCanvas";
		this.containerNode.appendChild(this.canvas);
	} else {
		this.canvas = this.containerNode.getElementsByClassName(canvasClassName)[0]; // but always try to give the element, to have it in certain place!
	}

	var _this = this;

	// Notation elements
	this.canvasWidth = width === undefined ? 600 : width; // NB! if set to 0, don't create notation
	this.canvasX = x === undefined ? 10 : x;
	this.canvasY = y === undefined ? 10 : y;
	this.canvasScale = scale === undefined ? 0.8 : scale;

	this.notes = ""; // notenames, durations  and octaves in vextab format like ":4 C/4" -  and other parts of VT notation
	this.numberOfVoices = 1;
	this.currentVoice = 0; // index of voice/stave

	this.key = "C";
	this.time = "4/4";
	this.clef = "treble";

    this.vtEndString = "\noptions space=20\n";

	//results and feedback
	this.attempts = 0;
	this.score = 0;

    // for tests -------------
    this.timer = -1;
	this.timeToThink = 15; // Could be also il levels:  slow/medium/fast
	this.maxQuestions = 5;
	this.currentQuestion = 0; // should be local variables defined with var but this is not reachable from countdown() if it is executed from setTimeout callbaclk. javascript.....
	this.countdownReference = NaN;

	// main methods -----------------
	this.createVexTabString = function() {
		var startString = "options space=20\n stave \n "; // was tabstave before but this is not needed
		var clefString = (this.clef.length>0) ? "clef="+this.clef+"\n" : "";
		var keyString = (this.key.length>0) ? "key="+this.key+"\n" : "";
		var timeString = (this.time.length>0) ?  "time="+this.time+"\n" : "";
		var notesString = (this.notes==="") ? ""  : "\nnotes " + this.notes + "\n";
		var endString = "\noptions space=20\n";
		return startString + clefString + keyString + timeString + notesString + endString;
	}

	this.clickActions = function(x,y){ console.log("clickactions", x,y)}; // you can define other things to be done connected to click event

	this.handleClick = function(event) {
		var _x = event.layerX / _this.canvasScale; // This is not consistent. Requires handling in exercises (drawx= x-canvas.X). Think
		var _y =  (event.layerY - _this.canvas.offsetTop) / _this.canvasScale; // was: clientX, clientY
		//console.log("Click coordinates: ",_x,_y, event);
		_this.clickActions(_x,_y); // this workaround is necessary to be able to overload clickActions to reach "this." properties
	}

	this.init = function() {
			// for SVG -  remove everything what is inside the div:
			while (this.canvas.firstChild) {
				this.canvas.removeChild(this.canvas.firstChild);
			}
			// Feedback and results, hide test div
			this.containerNode.getElementsByClassName("attempts")[0].innerHTML = "0";
			this.containerNode.getElementsByClassName("score")[0].innerHTML = "0";
			this.containerNode.getElementsByClassName("testDiv")[0].style.visibility="hidden";
			this.containerNode.getElementsByClassName("responseDiv")[0].innerHTML = "";

			// VexTab
			if (this.canvasWidth>0) {
				var vt = VexTabDiv;
				var VexTab = vt.VexTab;
				var Artist = vt.Artist;
				var Renderer = Vex.Flow.Renderer;
				this.renderer = new Renderer(this.canvas, Renderer.Backends.SVG);
				this.artist = new Artist(this.canvasX, this.canvasY , this.canvasWidth, {scale: this.canvasScale});
				this.vextab = new VexTab(this.artist);

				//Audio renderer
				this.selectedPreset=_tone_0000_JCLive_sf2_file;
				var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
				this.audioContext = new AudioContextFunc();
				this.player=new WebAudioFontPlayer();
				this.player.loader.decodeAfterLoading(this.audioContext, '_tone_0000_JCLive_sf2_file');

				// add event listener for canvas clicks (SVG)
				this.renderer.getContext().svg.addEventListener('click',this.handleClick, false);
			} else {
				console.log("Canvas width is 0, renderer and player not created.");
			}

	}

	this.init();

	this.generate = function() {console.log("generate(). Implement in derived object.");}

	this.draw = function (string) { // if string is given (full vectab notation string), use that to generate notation from
		try {
			this.vextab.reset();
			this.artist.reset();
			var parseString = (string===undefined) ? this.createVexTabString() : string; // allow to set the string by user;
			this.vextab.parse(parseString);
			this.artist.render(this.renderer);
		} catch (e) {
			console.log(e);
		}
	}

	this.renew = function() { // in some exercise you may need to add more functionality, like hide() or similar
		this.containerNode.getElementsByClassName("feedback")[0].innerHTML = "";
        this.generate();
        this.draw();
    }

	this.getNotes = function(staff) {
		if (typeof(staff)=="undefined") {
			staff=0
		}
		return this.artist.staves[staff].note_notes;
	}

	this.responseFunction = function()  {console.log("Implement in derived object;")}

	this.checkResponse = function() {
		this.responseFunction();
		if (this.testIsRunning() ) {
			this.nextQuestion(); // this also stops the countdown of test question
		}
	}

	// methods for making tests ----------------

	// TODO: add timeSpent + feedback "Testi tegemiseks kulus aega: "+ this.timeSpent

	function countdown() {
        //console.log(_this.timer);
        this.containerNode.getElementsByClassName("timer")[0].innerHTML = _this.timer.toString();
		if (_this.timer>0) {
            _this.timer--;
            _this.countdownReference = setTimeout(function(){countdown();}, 1000); // recursive
            return;
		}

		if (_this.timer==0) {
			if (_this.currentQuestion<_this.maxQuestions) {
                _this.checkResponse(); // checkResponse calls nextQuestion(), renew() and resets the timer
			} else {
                console.log("Test ended");
				clearTimeout(_this.countdownReference);
				_this.stopTest();
			}
		}
	}

	this.startTest = function() {
        this.attempts=0; this.score=0;
        this.containerNode.getElementsByClassName("attempts")[0].innerHTML="0"; this.containerNode.getElementsByClassName("score")[0].innerHTML = "0";
        this.timer = this.timeToThink;
		this.currentQuestion = 0;
		this.nextQuestion();
	}

	this.testIsRunning = function() {
        return (this.timer>=0)
    }

    this.nextQuestion = function() {
		clearTimeout(_this.countdownReference); // stop timer
		if (this.currentQuestion<this.maxQuestions) {
			this.currentQuestion++;
			this.containerNode.getElementsByClassName("questionNumber")[0].innerHTML = this.currentQuestion.toString();
			exercise.renew();
			this.timer = this.timeToThink;
			countdown();
		} else {
			console.log("Test finished")
			this.stopTest();
		}

	}

    this.stopTest= function() {
        console.log("Stop");
        clearTimeout(_this.countdownReference);
		this.timer = -1;
        this.currentQuestion = 0;
		this.containerNode.getElementsByClassName("questionNumber")[0].innerHTML = "0";
		this.containerNode.getElementsByClassName("timer")[0].innerHTML = "0";
    }

	//audio -------------------------------------
	this.volume = 0.3;
	this.tempo = 60.0;
	this.playNote = function(midiNote, start, duration) {
		this.player.queueWaveTable(this.audioContext, this.audioContext.destination,
		this.selectedPreset, this.audioContext.currentTime+start, midiNote, duration, this.volume);
	}

	this.play = function() {
		var _start = 0, _duration = 1;
		var notes = this.artist.staves[0].note_notes ;
		console.log("notes: ", notes)
		for (var i=0; i<notes.length; i++ ) {
			var _note = notes[i];
			//console.log("Note to play:", _note);
			if (_note.duration!=="b") { // check if not barline
				_duration = _note.getTicks().value()/4096.0 * 60.0/this.tempo;
				var keys = _note.getPlayNote(); // can be an array if chord
				for (var j=0; j<keys.length; j++) {
					var noteName = keys[j].split("/")[0];
					var octave = keys[j].split("/")[1];
					noteName = noteName.trim().toLowerCase();
					var noteValue =Vex.Flow.Music.noteValues[noteName];
					var midiNote = (24 + ((octave-1) * 12)) + noteValue.int_val
					// get start from note, maybe
					//console.log(midiNote, _start, _duration); //
					if (_note.noteType=="n") {
						this.playNote(midiNote, _start, _duration);
					}
				}
				_start += _duration;
			}
		}
	}
}

<commit_msg>Removed one extra comma<commit_after>/*

Autogenerating Music Exercises for education program "Muusika Kompositsiooniõpetus" https://et.wikibooks.org/wiki/Muusika_kompositsiooni%C3%B5petus/N%C3%84IDISKURSUS._G%C3%9CMNAASIUM
Commissioned by Estonian Ministry of Education and Research, Tallinn University,  in the frame of Digital Learning Resources project DigiÕppeVaramu https://htk.tlu.ee/oppevara/

Copyright 2018, by Tarmo Johannes trmjhnns@gmail.com

License: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

// Base class for Music Exercises
// uses VexTab / VexFlow for notation
// WebAudiofontPlayer for audio playback

// the host webpage must load:
// <script src="https://unpkg.com/vextab/releases/vextab-div.js"></script>
// <script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>
// <script src='https://surikov.github.io/webaudiofontdata/sound/0000_JCLive_sf2_file.js'></script>

function MusicExercise(containerNode, canvasClassName, width, x, y, scale ) {
	this.containerNode = containerNode===undefined ? document.body : containerNode; // to  make it independent and enable to use several exercises per page

	if (canvasClassName === undefined) { // if not given, create div for canvas
		this.canvas = document.createElement("div");
		this.canvas.className = "mainCanvas";
		this.containerNode.appendChild(this.canvas);
	} else {
		this.canvas = this.containerNode.getElementsByClassName(canvasClassName)[0]; // but always try to give the element, to have it in certain place!
	}

	var _this = this;

	// Notation elements
	this.canvasWidth = width === undefined ? 600 : width; // NB! if set to 0, don't create notation
	this.canvasX = x === undefined ? 10 : x;
	this.canvasY = y === undefined ? 10 : y;
	this.canvasScale = scale === undefined ? 0.8 : scale;

	this.notes = ""; // notenames, durations  and octaves in vextab format like ":4 C/4" -  and other parts of VT notation
	this.numberOfVoices = 1;
	this.currentVoice = 0; // index of voice/stave

	this.key = "C";
	this.time = "4/4";
	this.clef = "treble";

    this.vtEndString = "\noptions space=20\n";

	//results and feedback
	this.attempts = 0;
	this.score = 0;

    // for tests -------------
    this.timer = -1;
	this.timeToThink = 15; // Could be also il levels:  slow/medium/fast
	this.maxQuestions = 5;
	this.currentQuestion = 0; // should be local variables defined with var but this is not reachable from countdown() if it is executed from setTimeout callbaclk. javascript.....
	this.countdownReference = NaN;

	// main methods -----------------
	this.createVexTabString = function() {
		var startString = "options space=20\n stave \n "; // was tabstave before but this is not needed
		var clefString = (this.clef.length>0) ? "clef="+this.clef+"\n" : "";
		var keyString = (this.key.length>0) ? "key="+this.key+"\n" : "";
		var timeString = (this.time.length>0) ?  "time="+this.time+"\n" : "";
		var notesString = (this.notes==="") ? ""  : "\nnotes " + this.notes + "\n";
		var endString = "\noptions space=20\n";
		return startString + clefString + keyString + timeString + notesString + endString;
	}

	this.clickActions = function(x,y){ console.log("clickactions", x,y)}; // you can define other things to be done connected to click event

	this.handleClick = function(event) {
		var _x = event.layerX / _this.canvasScale; // This is not consistent. Requires handling in exercises (drawx= x-canvas.X). Think
		var _y =  (event.layerY - _this.canvas.offsetTop) / _this.canvasScale; // was: clientX, clientY
		//console.log("Click coordinates: ",_x,_y, event);
		_this.clickActions(_x,_y); // this workaround is necessary to be able to overload clickActions to reach "this." properties
	}

	this.init = function() {
			// for SVG -  remove everything what is inside the div:
			while (this.canvas.firstChild) {
				this.canvas.removeChild(this.canvas.firstChild);
			}
			// Feedback and results, hide test div
			this.containerNode.getElementsByClassName("attempts")[0].innerHTML = "0";
			this.containerNode.getElementsByClassName("score")[0].innerHTML = "0";
			this.containerNode.getElementsByClassName("testDiv")[0].style.visibility="hidden";
			this.containerNode.getElementsByClassName("responseDiv")[0].innerHTML = "";

			// VexTab
			if (this.canvasWidth>0) {
				var vt = VexTabDiv;
				var VexTab = vt.VexTab;
				var Artist = vt.Artist;
				var Renderer = Vex.Flow.Renderer;
				this.renderer = new Renderer(this.canvas, Renderer.Backends.SVG);
				this.artist = new Artist(this.canvasX, this.canvasY , this.canvasWidth, {scale: this.canvasScale});
				this.vextab = new VexTab(this.artist);

				//Audio renderer
				this.selectedPreset=_tone_0000_JCLive_sf2_file;
				var AudioContextFunc = window.AudioContext || window.webkitAudioContext;
				this.audioContext = new AudioContextFunc();
				this.player=new WebAudioFontPlayer();
				this.player.loader.decodeAfterLoading(this.audioContext, '_tone_0000_JCLive_sf2_file');

				// add event listener for canvas clicks (SVG)
				this.renderer.getContext().svg.addEventListener('click',this.handleClick, false);
			} else {
				console.log("Canvas width is 0, renderer and player not created.");
			}

	}

	this.init();

	this.generate = function() {console.log("generate(). Implement in derived object.");}

	this.draw = function (string) { // if string is given (full vectab notation string), use that to generate notation from
		try {
			this.vextab.reset();
			this.artist.reset();
			var parseString = (string===undefined) ? this.createVexTabString() : string; // allow to set the string by user;
			this.vextab.parse(parseString);
			this.artist.render(this.renderer);
		} catch (e) {
			console.log(e);
		}
	}

	this.renew = function() { // in some exercise you may need to add more functionality, like hide() or similar
		this.containerNode.getElementsByClassName("feedback")[0].innerHTML = "";
        this.generate();
        this.draw();
    }

	this.getNotes = function(staff) {
		if (typeof(staff)=="undefined") {
			staff=0
		}
		return this.artist.staves[staff].note_notes;
	}

	this.responseFunction = function()  {console.log("Implement in derived object;")}

	this.checkResponse = function() {
		this.responseFunction();
		if (this.testIsRunning() ) {
			this.nextQuestion(); // this also stops the countdown of test question
		}
	}

	// methods for making tests ----------------

	// TODO: add timeSpent + feedback "Testi tegemiseks kulus aega: "+ this.timeSpent

	function countdown() {
        //console.log(_this.timer);
        this.containerNode.getElementsByClassName("timer")[0].innerHTML = _this.timer.toString();
		if (_this.timer>0) {
            _this.timer--;
            _this.countdownReference = setTimeout(function(){countdown();}, 1000); // recursive
            return;
		}

		if (_this.timer==0) {
			if (_this.currentQuestion<_this.maxQuestions) {
                _this.checkResponse(); // checkResponse calls nextQuestion(), renew() and resets the timer
			} else {
                console.log("Test ended");
				clearTimeout(_this.countdownReference);
				_this.stopTest();
			}
		}
	}

	this.startTest = function() {
        this.attempts=0; this.score=0;
        this.containerNode.getElementsByClassName("attempts")[0].innerHTML="0"; this.containerNode.getElementsByClassName("score")[0].innerHTML = "0";
        this.timer = this.timeToThink;
		this.currentQuestion = 0;
		this.nextQuestion();
	}

	this.testIsRunning = function() {
        return (this.timer>=0)
    }

    this.nextQuestion = function() {
		clearTimeout(_this.countdownReference); // stop timer
		if (this.currentQuestion<this.maxQuestions) {
			this.currentQuestion++;
			this.containerNode.getElementsByClassName("questionNumber")[0].innerHTML = this.currentQuestion.toString();
			exercise.renew();
			this.timer = this.timeToThink;
			countdown();
		} else {
			console.log("Test finished")
			this.stopTest();
		}

	}

    this.stopTest= function() {
        console.log("Stop");
        clearTimeout(_this.countdownReference);
		this.timer = -1;
        this.currentQuestion = 0;
		this.containerNode.getElementsByClassName("questionNumber")[0].innerHTML = "0";
		this.containerNode.getElementsByClassName("timer")[0].innerHTML = "0";
    }

	//audio -------------------------------------
	this.volume = 0.3;
	this.tempo = 60.0;
	this.playNote = function(midiNote, start, duration) {
		this.player.queueWaveTable(this.audioContext, this.audioContext.destination,
		this.selectedPreset, this.audioContext.currentTime+start, midiNote, duration, this.volume);
	}

	this.play = function() {
		var _start = 0, _duration = 1;
		var notes = this.artist.staves[0].note_notes ;
		console.log("notes: ", notes)
		for (var i=0; i<notes.length; i++ ) {
			var _note = notes[i];
			//console.log("Note to play:", _note);
			if (_note.duration!=="b") { // check if not barline
				_duration = _note.getTicks().value()/4096.0 * 60.0/this.tempo;
				var keys = _note.getPlayNote(); // can be an array if chord
				for (var j=0; j<keys.length; j++) {
					var noteName = keys[j].split("/")[0];
					var octave = keys[j].split("/")[1];
					noteName = noteName.trim().toLowerCase();
					var noteValue =Vex.Flow.Music.noteValues[noteName];
					var midiNote = (24 + ((octave-1) * 12)) + noteValue.int_val
					// get start from note, maybe
					//console.log(midiNote, _start, _duration); //
					if (_note.noteType=="n") {
						this.playNote(midiNote, _start, _duration);
					}
				}
				_start += _duration;
			}
		}
	}
}

<|endoftext|>


<commit_before>var Messages = new Meteor.Collection('messages');

Messages.add = function(message) {
	if (typeof message === 'string') {
		this.insert({message: message, isRead: false});
		return true;
	}
	return false;
};

if (Meteor.is_server) {
	Meteor.publish('messages', function() {
		return Messages.find({}, {sort: {$natural: -1}, limit: 1});
	});
}

if (Meteor.is_client) {
	Meteor.subscribe('messages');

	var submit = function() {
		var textbox = document.getElementById('text');
		if (Messages.add(textbox.value)) textbox.value = '';
	};

	var getMessage = function() {
		return Messages.findOne({});
	};

	Template.main.messages = function() {
		return Messages.find({});
	};

	Template.main.inputClassName = function() {
		return getMessage() && getMessage().isRead ? 'read' : 'unread';
	};

	Template.main.events = {
		'click button': submit,
		'keypress input': function(e) {
			e.which === 13 && submit();
		}
	};

	Template.message.className = function() {
		return this.isRead ? 'read' : 'unread';
	};

	Template.message.events = {
		'click' : function() {
			Messages.update(this, {$set: {isRead: true}});
		}
	};
}<commit_msg>Rename messages collection<commit_after>var messages = new Meteor.Collection('messages');

messages.add = function(message) {
	if (typeof message === 'string') {
		this.insert({message: message, isRead: false});
		return true;
	}
	return false;
};

if (Meteor.is_server) {
	Meteor.publish('messages', function() {
		return messages.find({}, {sort: {$natural: -1}, limit: 1});
	});
}

if (Meteor.is_client) {
	Meteor.subscribe('messages');

	var submit = function() {
		var textbox = document.getElementById('text');
		if (messages.add(textbox.value)) textbox.value = '';
	};

	var getMessage = function() {
		return messages.findOne({});
	};

	Template.main.messages = function() {
		return messages.find({});
	};

	Template.main.inputClassName = function() {
		return getMessage() && getMessage().isRead ? 'read' : 'unread';
	};

	Template.main.events = {
		'click button': submit,
		'keypress input': function(e) {
			e.which === 13 && submit();
		}
	};

	Template.message.className = function() {
		return this.isRead ? 'read' : 'unread';
	};

	Template.message.events = {
		'click' : function() {
			messages.update(this, {$set: {isRead: true}});
		}
	};
}<|endoftext|>