<commit_before>var default_opacity = 0.2;
var animate_time = 1000;
var default_animate_time = 1000;
var num_images = 152;
var skip_opacity_to_0 = true;
var start = new Date();
var cors_proxy = "https://cors-anywhere.herokuapp.com/";

function menu_inout() {
    var layout   = $('#layout'),
        menu     = $('#menu'),
        menuLink = $('#menuLink'),
        content  = $('#main');

    function toggleAll(e) {
        var active = 'active';

        e.preventDefault();
        layout.toggleClass(active);
        menu.toggleClass(active);
        menuLink.toggleClass(active);
    }

    menuLink.click(function (e) {
        toggleAll(e);
    });

    content.click(function(e) {
        if (menu.hasClass('active')) {
            toggleAll(e);
        }
    });
}

function fix_resolutions() {
  var img = $('#imgloader').get(0);
  var img_ratio = img.naturalWidth / img.naturalHeight;
  var wnd_ratio = window.innerWidth / window.innerHeight;
  $("#background").css("background-size", img_ratio > wnd_ratio ? "auto 100%" : "100% auto");
}

function set_random_img() {
  var img = $('#imgloader').attr('src');
  var back = $('#background');
  var current_animate_time = animate_time;

  if(skip_opacity_to_0) {
    skip_opacity_to_0 = false;
    animate_time = 0;
  }
  else {
    back.css('opacity', 0);
  }

  setTimeout(function() {
      back.css("background-image", "url('" + img + "')");
      back.css('opacity', default_opacity);
      fix_resolutions();
  }, animate_time);
}

function select_random_img() {
  $('#imgloader').attr('src', "/static/imgs/" + (Math.floor(Math.random() * num_images) + 1) + ".jpg");
}

function load_chess() {
    var request = new XMLHttpRequest();
    request.open('GET', 'https://chesspuzzle.net/Daily/Api', true);
    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var result = JSON.parse(request.responseText);
            document.getElementById("puzzleText").textContent = result.Text;
            document.getElementById("puzzleLink").href = result.Link;

            var img = $("#puzzleImage");
            img.attr('src', result.Image);
            img.on('load', function() {
                $('#chesspuzzle').css('opacity', 1);
            });
        }
    };
    request.send();
}

function contact_stuff() {
    $('#contact-send').click(function() {
        if($('#contact-email').val().length > 0) {
            return;
        }
        if(new Date() - start < 1000 * 10) { //minimal 10 seconds
            return;
        }

        var url = "http://maker.ifttt.com/trigger/contact/with/key/eOrfK0j7evebgwTmwSt3D-HngdZPB8tBQPblCcR2At4";
        var obj = {
            value1: $('#contact-email-real').val(),
            value2: $('#contact-name').val(),
            value3: $('#contact-message').val(),
        };

        $.ajax({
            type: 'POST',
            url: cors_proxy + url,
            data: JSON.stringify (obj),
            success: function(d) { alert("Thank you!"); },
            error: function(d) { alert("error sending :("); },
            contentType: "application/json",
            dataType: 'text'
        });
    });
}

$( document ).ready(function() {
  $('#imgloader').attr('src', '').on("load", set_random_img);
  $(window).resize(fix_resolutions);

  select_random_img();
  menu_inout();
  contact_stuff();

  if(window.location.pathname == "/") { // only on index page
    window.setInterval(select_random_img, 10000);
  }

  load_chess();
  hljs.initHighlightingOnLoad();
});
<commit_msg>Fixed opacity transition for background image<commit_after>var default_opacity = 0.2;
var animate_time = 1000;
var default_animate_time = 1000;
var num_images = 152;
var skip_opacity_to_0 = true;
var start = new Date();
var cors_proxy = "https://cors-anywhere.herokuapp.com/";

function menu_inout() {
    var layout   = $('#layout'),
        menu     = $('#menu'),
        menuLink = $('#menuLink'),
        content  = $('#main');

    function toggleAll(e) {
        var active = 'active';

        e.preventDefault();
        layout.toggleClass(active);
        menu.toggleClass(active);
        menuLink.toggleClass(active);
    }

    menuLink.click(function (e) {
        toggleAll(e);
    });

    content.click(function(e) {
        if (menu.hasClass('active')) {
            toggleAll(e);
        }
    });
}

function fix_resolutions() {
  var img = $('#imgloader').get(0);
  var img_ratio = img.naturalWidth / img.naturalHeight;
  var wnd_ratio = window.innerWidth / window.innerHeight;
  $("#background").css("background-size", img_ratio > wnd_ratio ? "auto 100%" : "100% auto");
}

function set_random_img() {
  var img = $('#imgloader').attr('src');
  var back = $('#background');
  var current_animate_time = animate_time;

  if(skip_opacity_to_0) {
    skip_opacity_to_0 = false;
    current_animate_time = 0;
  }
  else {
    back.css('opacity', 0);
  }

  setTimeout(function() {
      back.css("background-image", "url('" + img + "')");
      fix_resolutions();
      back.css('opacity', default_opacity);
  }, animate_time);
}

function select_random_img() {
  $('#imgloader').attr('src', "/static/imgs/" + (Math.floor(Math.random() * num_images) + 1) + ".jpg");
}

function load_chess() {
    var request = new XMLHttpRequest();
    request.open('GET', 'https://chesspuzzle.net/Daily/Api', true);
    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var result = JSON.parse(request.responseText);
            document.getElementById("puzzleText").textContent = result.Text;
            document.getElementById("puzzleLink").href = result.Link;

            var img = $("#puzzleImage");
            img.attr('src', result.Image);
            img.on('load', function() {
                $('#chesspuzzle').css('opacity', 1);
            });
        }
    };
    request.send();
}

function contact_stuff() {
    $('#contact-send').click(function() {
        if($('#contact-email').val().length > 0) {
            return;
        }
        if(new Date() - start < 1000 * 10) { //minimal 10 seconds
            return;
        }

        var url = "http://maker.ifttt.com/trigger/contact/with/key/eOrfK0j7evebgwTmwSt3D-HngdZPB8tBQPblCcR2At4";
        var obj = {
            value1: $('#contact-email-real').val(),
            value2: $('#contact-name').val(),
            value3: $('#contact-message').val(),
        };

        $.ajax({
            type: 'POST',
            url: cors_proxy + url,
            data: JSON.stringify (obj),
            success: function(d) { alert("Thank you!"); },
            error: function(d) { alert("error sending :("); },
            contentType: "application/json",
            dataType: 'text'
        });
    });
}

$( document ).ready(function() {
  $('#imgloader').attr('src', '').on("load", set_random_img);
  $(window).resize(fix_resolutions);

  select_random_img();
  menu_inout();
  contact_stuff();

  if(window.location.pathname == "/") { // only on index page
    window.setInterval(select_random_img, 10000);
  }

  load_chess();
  hljs.initHighlightingOnLoad();
});
<|endoftext|>


<commit_before><commit_msg>[feature #141878519] Delete unnecesary roles seeder<commit_after><|endoftext|>


<commit_before>// miner ver01
//Thanks to Giulia Alfonsi <electric.g@gmail.com>
//for providing the stopwatch timer JS (stopwatch.js)
// James & Matt of WDI Purple-Rain for some troubleshooting!

$(document).ready(function(){

// define some items on the DOM using Jquery
var $button = $('.start-pass');
var $button2 = $('.guess').hide();
var $button3 = $('.pass').hide();
var $input = $('input').hide();
var $rebus = $('img');
var $h1 = $('h1');
var $time = $('#time').hide();
var answer = '';
var location = '';
var P1totalTime = 0
var P2totalTime = 0
var play2
var play1
var p1Score = 0
var p2Score = 0
var guesses = 0
var pass
// player turns
var roundNo = 0
var pointAward =0
//two arrays for images & answers, need to not repeat used items

var usedImages =[ ]
var rebusArray =
 [
          {
          answer:"changing times",
          location: "img/01.jpg"
          },
          {
          answer:"not for all the tea in china",
          location: "img/02.jpg"
          },
           {
          answer:"it doesn't ring a bell",
          location: "img/03.jpg"
          },
           {
          answer:"richard nixon",
          location: "img/04.jpg"
          },
           {
          answer:"take it or leave it",
          location: "img/06.jpg"
          },
];

//length of the array in a varaible
var RebusL = rebusArray.length

var playerScore = function (){

  if ( play2 === 'Player 2') {
        P2totalTime += (m * 60 + s)
        if (P2totalTime < 5) {

          p2Score += 1000
        } else if (P2totalTime < 10 ) {
          p2Score += 500
        } else if (P2totalTime < 20 ) {
          p2Score += 100
        } else {
          P2totalTime += 10
        }

    } else {
        P1totalTime += (m * 60 + s)

if (P1totalTime < 5) {

          p1Score += 1000
        } else if (P2totalTime < 10 ) {
          p1Score += 500
        } else if (P2totalTime < 20 ) {
          p1Score += 100
        } else {
          p1Score += 10
        }

    }
}
// match'em or else
var compareGuess = function(){
  var guess = $('#guess').val();
  // console.log(randomRedbus.answer);
  if (guess === answer) {
    stop();
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2');
    $button2.hide();
    playerScore();

    // var totalTime =   (m *60) + s

    $input.hide();

  } else if (guesses === 3) {

    stop()
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2')
    $button2.hide();
    $input.hide();
    $h1.html(answer);
    playerScore();
    $input = ' ';
   // trying to add slicer here
  // splicer();

    // randomRebus.splice(push(usedImages), 1)[0];
    }
    console.log('you guessed wrong')
    guesses++
    $('#wrong').text(guesses)
}

// checks (even /odd) goes to next round, updates player no.
var turner = function() {
  roundNo++;
  if (roundNo > RebusL) {
    winState()
    } else if (roundNo %2 === 0) {
        playerState = 'p1'
        play2 = ('Player 2');
        $h1.text(play2)
        reset();
        start();
        $input.show();
        guesses=0;
        // var P1totalTime += (m *60) + s
      } else {
        play1 = ('Player 1');
        playerState = 'p2'
        $h1.text(play1)
          reset();
          start();
          $input.show();
          guesses=0;

      }
     $('#wrong').text(guesses)
}

//random number function
var randomNo = function () {

  return Math.floor(Math.random()*RebusL)
  }

// var randomRebus = RebusArray[randomNo()];

//button one click  (PASS & Start)

$button.click(function(){

  var randomRebus = rebusArray[randomNo()];
  $button.text('PASS');
  $button2.show();
  $input.show();
  $time.fadeTo('1000', 0.2);
  turner();
  start();

$rebus.attr("src", randomRebus.location);
// answer values stored in variable, avoids confusion on repeatedly calling function
  answer = randomRebus.answer;
  location = randomRebus.location;
  itemPlace = rebusArray.indexOf(randomRebus);

});

// pointscheme

// var awardPoints = function () {

// switch (totalTime) {
//     case totalTime < 10:
//       pointAward += 100;
//       break;
//     case totalTime < 20:
//       pointAward += 50;
//       break;
//     default:
//       pointAward += 0;
//       }

// }

var winState = function(){

   stop()
    $time.hide();
    $button.hide()
    $button2.hide();
    $input.hide();
    $rebus = $('img').hide();
    console.log(P1totalTime)
    console.log(P2totalTime)
    if ( p1Score > p2Score ) {

      $h1.html('Player 1 Wins' + ' -- ' + p1Score + ' p2 score ' + p2Score  );
    } else {

       $h1.html('Player 2 Wins'+ ' -- ' + p2Score + ' p1 Score: ' +  p1Score  );
    }

}

// how to get rid of selected images?? splicer so image

// function splicer(){
//   // var k = rebusArray.indexOf(randomRebus);
//     if(itemPlace != -1)
//     // rebusArray.delete(itemPlace, 1);
//     console.log(itemPlace)
//       console.log(itemPlace)
//         console.log(itemPlace)
//         rebusArray.splice(itemPlace);

//   }

$button3.click(function(){
$button3.hide();
$button2.hide();
pass = 'skipped'
$button.show();

 // stop();
 //    $time.fadeTo('1000', 1);
 //    $button.text('Next Round / P2');

 //    playerScore();

});

$button2.click(function(){

compareGuess();
});
show()

});
<commit_msg>Update script.js<commit_after>// miner ver01
//Thanks to Giulia Alfonsi <electric.g@gmail.com>
//for providing the stopwatch timer JS (stopwatch.js)
// James & Matt of WDI Purple-Rain for some troubleshooting!

$(document).ready(function(){

// define some items on the DOM using Jquery
var $button = $('.start-pass');
var $button2 = $('.guess').hide();
var $button3 = $('.pass').hide();
var $input = $('input').hide();
var $rebus = $('img');
var $h1 = $('h1');
var $time = $('#time').hide();
var answer = '';
var location = '';
var P1totalTime = 0
var P2totalTime = 0
var play2
var play1
var p1Score = 0
var p2Score = 0
var guesses = 0
var pass
// player turns
var roundNo = 0
var pointAward =0
//two arrays for images & answers, need to not repeat used items

var usedImages =[ ]
var rebusArray =
 [
          {
          answer:"changing times",
          location: "img/01.jpg"
          },
          {
          answer:"not for all the tea in china",
          location: "img/02.jpg"
          },
           {
          answer:"it doesn't ring a bell",
          location: "img/03.jpg"
          },
           {
          answer:"richard nixon",
          location: "img/04.jpg"
          },
           {
          answer:"take it or leave it",
          location: "img/06.jpg"
          },
];

//length of the array in a varaible
var RebusL = rebusArray.length

var playerScore = function (){

  if ( play2 === 'Player 2') {
        P2totalTime += (m * 60 + s)
        if (P2totalTime < 5) {

          p2Score += 1000
        } else if (P2totalTime < 10 ) {
          p2Score += 500
        } else if (P2totalTime < 20 ) {
          p2Score += 100
        } else {
          P2totalTime += 10
        }

    } else {
        P1totalTime += (m * 60 + s)

if (P1totalTime < 5) {

          p1Score += 1000
        } else if (P2totalTime < 10 ) {
          p1Score += 500
        } else if (P2totalTime < 20 ) {
          p1Score += 100
        } else {
          p1Score += 10
        }

    }
}
// match'em or else
var compareGuess = function(){
  var guess = $('#guess').val();
  // console.log(randomRedbus.answer);
  if (guess === answer) {
    stop();
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2');
    $button2.hide();
    playerScore();
      $input = ' ';

    // var totalTime =   (m *60) + s

    $input.hide();

  } else if (guesses === 3) {

    stop()
    $time.fadeTo('1000', 1);
    $button.text('Next Round / P2')
    $button2.hide();
    $input.hide();
    $h1.html(answer);
    playerScore();
    $input = ' ';
   // trying to add slicer here
  // splicer();

    // randomRebus.splice(push(usedImages), 1)[0];
    }
    console.log('you guessed wrong')
    guesses++
    $('#wrong').text(guesses)
}

// checks (even /odd) goes to next round, updates player no.
var turner = function() {
  roundNo++;
  if (roundNo > RebusL) {
    winState()
    } else if (roundNo %2 === 0) {
        playerState = 'p1'
        play2 = ('Player 2');
        $h1.text(play2)
        reset();
        start();
        $input.show();
        guesses=0;
        // var P1totalTime += (m *60) + s
      } else {
        play1 = ('Player 1');
        playerState = 'p2'
        $h1.text(play1)
          reset();
          start();
          $input.show();
          guesses=0;

      }
     $('#wrong').text(guesses)
}

//random number function
var randomNo = function () {

  return Math.floor(Math.random()*RebusL)
  }

// var randomRebus = RebusArray[randomNo()];

//button one click  (PASS & Start)

$button.click(function(){

  var randomRebus = rebusArray[randomNo()];
  $button.text('PASS');
  $button2.show();
  $input.show();
  $time.fadeTo('1000', 0.2);
  turner();
  start();

$rebus.attr("src", randomRebus.location);
// answer values stored in variable, avoids confusion on repeatedly calling function
  answer = randomRebus.answer;
  location = randomRebus.location;
  itemPlace = rebusArray.indexOf(randomRebus);

});

// pointscheme

// var awardPoints = function () {

// switch (totalTime) {
//     case totalTime < 10:
//       pointAward += 100;
//       break;
//     case totalTime < 20:
//       pointAward += 50;
//       break;
//     default:
//       pointAward += 0;
//       }

// }

var winState = function(){

   stop()
    $time.hide();
    $button.hide()
    $button2.hide();
    $input.hide();
    $rebus = $('img').hide();
    console.log(P1totalTime)
    console.log(P2totalTime)
    if ( p1Score > p2Score ) {

      $h1.html('Player 1 Wins' + ' -- ' + p1Score + ' p2 score ' + p2Score  );
    } else {

       $h1.html('Player 2 Wins'+ ' -- ' + p2Score + ' p1 Score: ' +  p1Score  );
    }

}

// how to get rid of selected images?? splicer so image

// function splicer(){
//   // var k = rebusArray.indexOf(randomRebus);
//     if(itemPlace != -1)
//     // rebusArray.delete(itemPlace, 1);
//     console.log(itemPlace)
//       console.log(itemPlace)
//         console.log(itemPlace)
//         rebusArray.splice(itemPlace);

//   }

$button3.click(function(){
$button3.hide();
$button2.hide();
pass = 'skipped'
$button.show();

 // stop();
 //    $time.fadeTo('1000', 1);
 //    $button.text('Next Round / P2');

 //    playerScore();

});

$button2.click(function(){

compareGuess();
});
show()

});
<|endoftext|>


<commit_before>var screen = $(window).width();
var inviteList = $('#invite-list button');
var saveButton = $('#save');

if (screen > 420) {
    $('.blackout').css('display', 'block')
}

saveButton.click(function () {
    $('.confirm').css('display', 'none');
    $('.question').text('¿Querés saber quienes vienen?');
    inviteList.css('display', 'block');
})

// LISTA DE CONFIRMADOS!
var invitedPep = {
	"invitados": [
		{ "name":"Nacho Pueta", "subsecretary":"SSCI", "direction":"DGCyT"  },
		{ "name":"Lore", "subsecretary":"SSCI", "direction":"DGCyT"  },
		{ "name":"Pablo Icardi", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Tomi Casagrande", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Pitu", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Yorland", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Sol", "subsecretary":"Economica", "direction":"PAPP"  },
		{ "name":"Puchu", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Florchi", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Ernesto", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  },
		{ "name":"Ponja", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  }
	]
}

var listInvited = ( function () {

	var name;
	var subse;
	var direction;
	var listElement = $('.invited-list');

	for (var i = 0; i < invitedPep.invitados.length; i++) {
		name = invitedPep.invitados[i].name;
		subse = invitedPep.invitados[i].subsecretary;
		direction = invitedPep.invitados[i].direction;

		listElement.append('
 ' + name + ' ' + '' + subse + ', ' + direction + '
');
	}
})()

<commit_msg>Update script.js<commit_after>var screen = $(window).width();
var inviteList = $('#invite-list button');
var saveButton = $('#save');

if (screen > 420) {
    $('.blackout').css('display', 'block')
}

saveButton.click(function () {
    $('.confirm').css('display', 'none');
    $('.question').text('¿Querés saber quienes vienen?');
    inviteList.css('display', 'block');
})

// LISTA DE CONFIRMADOS!
var invitedPep = {
	"invitados": [
		{ "name":"Diego Guillen", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Nacho Pueta", "subsecretary":"SSCI", "direction":"DGCyT"  },
		{ "name":"Lore", "subsecretary":"SSCI", "direction":"DGCyT"  },
		{ "name":"Pablo Icardi", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Tomi Casagrande", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Pitu", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Yorland", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Sol", "subsecretary":"Economica", "direction":"PAPP"  },
		{ "name":"Puchu", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Florchi", "subsecretary":"SSCI", "direction":"GEDI"  },
		{ "name":"Ernesto", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  },
		{ "name":"Ponja", "subsecretary":"Ciudad Inteligente", "direction":"GEDI"  }
	]
}

var listInvited = ( function () {

	var name;
	var subse;
	var direction;
	var listElement = $('.invited-list');

	for (var i = 0; i < invitedPep.invitados.length; i++) {
		name = invitedPep.invitados[i].name;
		subse = invitedPep.invitados[i].subsecretary;
		direction = invitedPep.invitados[i].direction;

		listElement.append('
 ' + name + ' ' + '' + subse + ', ' + direction + '
');
	}
})()

<|endoftext|>


<commit_before>/* Author:
	Gabriel Florit
*/

var aigua = (function () {

	return {

		loadExample: function(name) {

			$('svg').remove();
			$('#display').append('<svg></svg>');

			aigua.codeMirror.setValue('');
			aigua.switchMode('css', true);

			d3.text('data/' + name + '.css', function(css) {

				aigua.codeMirror.setValue(css);

				d3.text('data/' + name + '.js', function(js) {

					aigua.switchMode('javascript', true);
					aigua.codeMirror.setValue(js);
					aigua.switchMode('javascript'); // don't know why i have to do this twice

				});
			});
		},

		// modify a number by a certain distance
		// e.g. modifyNumber(5.89, 10) = 5.89 + 10 * 0.1
		// e.g. modifyNumber(58.9, 20) = 58.9 + 20 * 1
		modifyNumber: function(number, distance) {

			var parts;
			var exponent;
			var factor;
			var result;

			// say we have a number: 5.89
			// we first calculate its exponent: 0
			parts = number.toExponential().split('e');
			exponent = Number(parts[1]);

			// next we subtract 1 from the exponent: -1
			exponent = exponent - 1;

			// then we calculate our desired factor: 10^-1 = 0.1
			factor = Math.pow(10, exponent);

			// next we modify the number by the distance
			result = number + distance * factor;

			// finally we make sure not to add rounding errors
			return Number(result.toPrecision(parts[0].replace('.', '').length));
		},

		// run the code and update the display
		renderCode: function() {

			// get the current code
			var code = aigua.codeMirror.getValue();

			try {

				switch (aigua.modes[aigua.currentModeIndex].name) {

					case 'javascript':

						// clear out the display contents
						$('svg').empty();

						// run the code
						eval(code);

					break;

					case 'css':
						$('#aiguaStyle').get(0).textContent = code;
					break;

				}

			}
			catch (error) {}
			finally {};
		},

		respondToKey: function(cm) {

			if (aigua.modes[aigua.currentModeIndex].name == 'javascript') {

				var cursor;
				var token;
				var startCoords;
				var endCoords;
				var center;

				// is the slider hidden?
				if (!aigua.slider.is(':visible')) {

					// grab the current token
					cursor = cm.getCursor();
					token = cm.getTokenAt(cursor);

					// are we on a number?
					if (token.className == 'number') {

						// show the slider
						aigua.slider.show();

						// save the original number
						if (aigua.originalNumber == null) {
							aigua.originalNumber = Number(token.string);
						}

						// select token
						cm.setSelection({line: cursor.line, ch: token.start}, {line: cursor.line, ch: token.end});

						// find coords at token start
						startCoords = cm.cursorCoords(true);
						endCoords = cm.cursorCoords(false);

						// center marker on token
						center = startCoords.x + (endCoords.x - startCoords.x)/2;
						aigua.marker.css('left', center);

						// center handle on token
						aigua.handle.css('left', center - aigua.handle.width()/2);

						// center bar above token
						aigua.bar.css('left', center - aigua.bar.width()/2 - aigua.borderWidth);
						aigua.bar.css('top', startCoords.y - aigua.lineHeight);

						// center triangle on token
						aigua.triangle.css('left', center - aigua.triangleWidth);
						aigua.triangle.css('top', aigua.bar.offset().top + aigua.bar.height() + aigua.borderWidth * 2);
					}
				}
			}
		},

		// reset bar position and width:
		// center bar over the token
		// set bar width to default starting width
		resetBar: function(markerCenter) {
			aigua.bar.width(aigua.startingBarWidth);
			aigua.bar.css('left', markerCenter - aigua.startingBarWidth/2 - aigua.borderWidth);
			aigua.filler.removeClass('filler-edge-left');
			aigua.filler.removeClass('filler-edge-right');
		},

		switchMode: function(mode, noTab) {

			if (!noTab) {
				$('#modes h2').attr('class', 'passive');
				$("#modes h2:contains('" + mode + "')").attr('class', 'active');
			}

			aigua.modes[aigua.currentModeIndex].code = aigua.codeMirror.getValue();

			aigua.currentModeIndex = _.indexOf(_.pluck(aigua.modes, 'name'), mode);

			aigua.codeMirror.setValue(aigua.modes[aigua.currentModeIndex].code || '');

			aigua.codeMirror.setOption("mode", aigua.modes[aigua.currentModeIndex].name);
			CodeMirror.autoLoadMode(editor, aigua.modes[aigua.currentModeIndex].name);

		},

		bar: null,
		borderWidth: 2,
		currentModeIndex: 1,
		filler: null,
		handle: null,
		lineHeight: 19,
		marker: null,
		modes: [
			{
				name: 'css',
				code: null
			}, {
				name: 'javascript',
				code: null
			}
		],
		originalNumber: null,
		samples: ['data/chord.txt'],
		slider: null,
		startingBarWidth: 300,
		triangle: null,
		triangleHeight: 7,
		triangleWidth: 12

	}
}());

$(function() {

	// ----------- initialization section

	// setup the key correctly (linux/windows)
	var theKey = (navigator && navigator.platform && navigator.platform.toLowerCase().indexOf('linux') != -1)
		? 'Ctrl'
		: 'Ctrl-Ctrl';
	var extraKeys = {};
	{extraKeys[theKey] = aigua.respondToKey};

	// set various dom elements
	aigua.slider = $('#slider');
	aigua.handle = $('#handle');
	aigua.bar = $('#bar');
	aigua.marker = $('#marker');
	aigua.filler = $('#filler');
	aigua.triangle = $('#triangle');

	// set the handle's default width
	aigua.handle.width(aigua.startingBarWidth);

	// set the bar's border width and default width
	aigua.bar.css('border-width', aigua.borderWidth);
	aigua.bar.width(aigua.startingBarWidth);

	// set the triangle
	aigua.triangle.css('border-width', aigua.triangleHeight + 'px ' + aigua.triangleWidth + 'px 0px ' + aigua.triangleWidth + 'px');

	// create codemirror instance
	aigua.codeMirror = CodeMirror($('#code').get(0), {

		onChange: function(cm, e) {
			aigua.renderCode();
		},

		extraKeys: extraKeys,
		lineNumbers: true,
		matchBrackets: true,
		mode:  'javascript',
		modeURL: '/mode/%N.js',
		theme: 'lesser-dark'
	});

	// load sample code
	// d3.text(aigua.samples[0], function(data) {
	// 	aigua.codeMirror.setValue(data);
	// });

	// initialize slider
	aigua.handle.draggable({

		axis: 'x',

		drag: function(ui, event) {

			var position = event.position.left + aigua.handle.width()/2;
			var markerCenter = aigua.marker.offset().left;
			var offset = position - markerCenter;
			var newNumber;

			// calculate the new number based on the original number
			// plus the dragging offset
			newNumber = aigua.modifyNumber(aigua.originalNumber, offset);

			// replace the selection with the new number
			aigua.codeMirror.replaceSelection(String(newNumber));

			// is the dragging cursor to the right of the marker?
			if (offset > 0) {

				// if the left bar got stuck, reset the bar width and position
				if (markerCenter - aigua.bar.offset().left - aigua.borderWidth > aigua.startingBarWidth/2) {
					aigua.resetBar(markerCenter);
				}

				// set the filler width and position
				aigua.filler.width(offset);
				aigua.filler.css('left', aigua.startingBarWidth/2);

				// are we dragging past the initial bar width?
				if (offset > aigua.startingBarWidth/2 - (aigua.borderWidth)) {

					// round the filler edges
					aigua.filler.addClass('filler-edge-right');

					 // add 1 pixel to filler width to prevent square edges
					 // from hitting the round borders prematurely
					aigua.filler.width(offset + 1);

					// set bar right edge to dragging position
					aigua.bar.width(position - aigua.bar.offset().left);
				}

				// reset the width, since fast drags won't trigger a drag call every pixel.
				else {
					aigua.resetBar(markerCenter);
				}

			// is the dragging cursor to the left of the marker?
			} else if (offset < 0) {

				// set the filler width
				aigua.filler.width(-offset);

				// adjust the filler position
				aigua.filler.css('left', aigua.startingBarWidth/2 - -offset + aigua.borderWidth/2);

				// are we dragging past the initial bar width?
				if (-offset > aigua.startingBarWidth/2) {

					// adjust the filler position
					aigua.filler.css('left', aigua.borderWidth/2);

					// round the filler edges
					aigua.filler.addClass('filler-edge-left');

					// set bar left edge to dragging position
					aigua.bar.width(-offset + aigua.startingBarWidth/2);
					aigua.bar.css('left', position - aigua.borderWidth);
				}

				// reset the width, since fast drags won't trigger a drag call every pixel.
				else {
					aigua.resetBar(markerCenter);
				}

			// are we at the middle?
			} else {
				aigua.filler.width(0);
			}
		}
	});

	// populate mode switcher
	_.each(aigua.modes, function(mode, index) {

		var div = $("

");
		var h2 = $("

");
		div.append(h2);

		h2.attr('class', index == aigua.currentModeIndex ? 'active' : 'passive');
		h2.text(mode.name);

		$('#modes').append(div);
	});

	// ----------- event handlers section

	// did we keyup the handle key?
	$(window).keyup(function(e) {

		if (e.which == 17) {

			// hide the slider
			aigua.slider.hide();

			// reset filler width
			aigua.filler.width(0);

			// reset bar width
			aigua.bar.width(aigua.startingBarWidth);

			// clear out the original number
			aigua.originalNumber = null;
		}
	});

	// force svg contents to occupy the entire svg container
	// by rerendering code on window resize
	$(window).on('resize', function() {
		aigua.renderCode();
	});

	// handle modes switcher
	$('#modes .item h2').on('click', function(e) {
		aigua.switchMode($(this).text());
	});

	// handle menu mouseover/mouseout events
	$('#menu .item h2').on('mouseover', function(e) {
		var item = $(this).parents('.item');

		$('ul', item).show(); // show this dropdown
		$(this).addClass('hover'); // add hover class to this h2
	});

	// handle menu mouseover/mouseout events
	$('#menu .item').on('mouseout', function(e) {

		if ($(e.toElement).parents('.item').get(0) == $(this).get(0)) {

		} else {

			var menu = $(this).parents('#menu');

			$('ul', menu).hide(); // hide all the dropdowns
			$('h2', menu).removeClass('hover'); // remove hover class from all the h2's
		}
	});

	// handle menu mouseover/mouseout events
	$('#menu .item li').on('mouseover', function(e) {
		$(this).addClass('hover');
	});

	// handle menu mouseover/mouseout events
	$('#menu .item li').on('mouseout', function(e) {
		$(this).removeClass('hover');
	});

	// handle menu item choices
	$('#menu .item ul li').on('click', function(e) {
		e.preventDefault();

		var choice = $(this);
		var itemName = $('h2', choice.parents('.item')).text();

		switch(itemName) {
			case 'file':
				switch (choice.text()) {
					case 'new':
						var result = confirm('Are you sure? You will lose any unsaved changes.');
						if (result) {
							aigua.codeMirror.setValue('');
						}
						break;
				}
			break;
			case 'examples':
				var result = confirm('Are you sure? You will lose any unsaved changes.');
				if (result) {
					aigua.loadExample(choice.attr('rel'));
				}
			break;
		}
	});

});

<commit_msg>don't eval code when switching tabs<commit_after>/* Author:
	Gabriel Florit
*/

var aigua = (function () {

	return {

		loadExample: function(name) {

			$('svg').remove();
			$('#display').append('<svg></svg>');

			aigua.codeMirror.setValue('');
			aigua.switchMode('css', true);

			d3.text('data/' + name + '.css', function(css) {

				aigua.codeMirror.setValue(css);

				d3.text('data/' + name + '.js', function(js) {

					aigua.switchMode('javascript');
					aigua.codeMirror.setValue(js);
					aigua.codeMirror.setValue(js); // don't know why i have to do this twice

				});
			});
		},

		// modify a number by a certain distance
		// e.g. modifyNumber(5.89, 10) = 5.89 + 10 * 0.1
		// e.g. modifyNumber(58.9, 20) = 58.9 + 20 * 1
		modifyNumber: function(number, distance) {

			var parts;
			var exponent;
			var factor;
			var result;

			// say we have a number: 5.89
			// we first calculate its exponent: 0
			parts = number.toExponential().split('e');
			exponent = Number(parts[1]);

			// next we subtract 1 from the exponent: -1
			exponent = exponent - 1;

			// then we calculate our desired factor: 10^-1 = 0.1
			factor = Math.pow(10, exponent);

			// next we modify the number by the distance
			result = number + distance * factor;

			// finally we make sure not to add rounding errors
			return Number(result.toPrecision(parts[0].replace('.', '').length));
		},

		// run the code and update the display
		renderCode: function() {

			// get the current code
			var code = aigua.codeMirror.getValue();

			try {

				switch (aigua.modes[aigua.currentModeIndex].name) {

					case 'javascript':

						// clear out the display contents
						$('svg').empty();

						// run the code
						eval(code);

					break;

					case 'css':
						$('#aiguaStyle').get(0).textContent = code;
					break;

				}

			}
			catch (error) {}
			finally {};
		},

		respondToKey: function(cm) {

			if (aigua.modes[aigua.currentModeIndex].name == 'javascript') {

				var cursor;
				var token;
				var startCoords;
				var endCoords;
				var center;

				// is the slider hidden?
				if (!aigua.slider.is(':visible')) {

					// grab the current token
					cursor = cm.getCursor();
					token = cm.getTokenAt(cursor);

					// are we on a number?
					if (token.className == 'number') {

						// show the slider
						aigua.slider.show();

						// save the original number
						if (aigua.originalNumber == null) {
							aigua.originalNumber = Number(token.string);
						}

						// select token
						cm.setSelection({line: cursor.line, ch: token.start}, {line: cursor.line, ch: token.end});

						// find coords at token start
						startCoords = cm.cursorCoords(true);
						endCoords = cm.cursorCoords(false);

						// center marker on token
						center = startCoords.x + (endCoords.x - startCoords.x)/2;
						aigua.marker.css('left', center);

						// center handle on token
						aigua.handle.css('left', center - aigua.handle.width()/2);

						// center bar above token
						aigua.bar.css('left', center - aigua.bar.width()/2 - aigua.borderWidth);
						aigua.bar.css('top', startCoords.y - aigua.lineHeight);

						// center triangle on token
						aigua.triangle.css('left', center - aigua.triangleWidth);
						aigua.triangle.css('top', aigua.bar.offset().top + aigua.bar.height() + aigua.borderWidth * 2);
					}
				}
			}
		},

		// reset bar position and width:
		// center bar over the token
		// set bar width to default starting width
		resetBar: function(markerCenter) {
			aigua.bar.width(aigua.startingBarWidth);
			aigua.bar.css('left', markerCenter - aigua.startingBarWidth/2 - aigua.borderWidth);
			aigua.filler.removeClass('filler-edge-left');
			aigua.filler.removeClass('filler-edge-right');
		},

		switchMode: function(mode, noTab) {

			aigua.pause = true;

			if (!noTab) {
				$('#modes h2').attr('class', 'passive');
				$("#modes h2:contains('" + mode + "')").attr('class', 'active');
			}

			aigua.modes[aigua.currentModeIndex].code = aigua.codeMirror.getValue();

			aigua.currentModeIndex = _.indexOf(_.pluck(aigua.modes, 'name'), mode);

			aigua.codeMirror.setValue(aigua.modes[aigua.currentModeIndex].code || '');

			aigua.codeMirror.setOption("mode", aigua.modes[aigua.currentModeIndex].name);
			CodeMirror.autoLoadMode(editor, aigua.modes[aigua.currentModeIndex].name);

			aigua.pause = false;
		},

		bar: null,
		borderWidth: 2,
		currentModeIndex: 1,
		filler: null,
		handle: null,
		lineHeight: 19,
		marker: null,
		modes: [
			{
				name: 'css',
				code: null
			}, {
				name: 'javascript',
				code: null
			}
		],
		originalNumber: null,
		pause: false,
		samples: ['data/chord.txt'],
		slider: null,
		startingBarWidth: 300,
		triangle: null,
		triangleHeight: 7,
		triangleWidth: 12

	}
}());

$(function() {

	// ----------- initialization section

	// setup the key correctly (linux/windows)
	var theKey = (navigator && navigator.platform && navigator.platform.toLowerCase().indexOf('linux') != -1)
		? 'Ctrl'
		: 'Ctrl-Ctrl';
	var extraKeys = {};
	{extraKeys[theKey] = aigua.respondToKey};

	// set various dom elements
	aigua.slider = $('#slider');
	aigua.handle = $('#handle');
	aigua.bar = $('#bar');
	aigua.marker = $('#marker');
	aigua.filler = $('#filler');
	aigua.triangle = $('#triangle');

	// set the handle's default width
	aigua.handle.width(aigua.startingBarWidth);

	// set the bar's border width and default width
	aigua.bar.css('border-width', aigua.borderWidth);
	aigua.bar.width(aigua.startingBarWidth);

	// set the triangle
	aigua.triangle.css('border-width', aigua.triangleHeight + 'px ' + aigua.triangleWidth + 'px 0px ' + aigua.triangleWidth + 'px');

	// create codemirror instance
	aigua.codeMirror = CodeMirror($('#code').get(0), {

		onChange: function(cm, e) {
			if (!aigua.pause) {
				aigua.renderCode();
			}
		},

		extraKeys: extraKeys,
		lineNumbers: true,
		matchBrackets: true,
		mode:  'javascript',
		modeURL: '/mode/%N.js',
		theme: 'lesser-dark'
	});

	// load the first example
	aigua.loadExample($("#menu .item h2:contains('examples') + ul li:first").attr('rel'));

	// initialize slider
	aigua.handle.draggable({

		axis: 'x',

		drag: function(ui, event) {

			var position = event.position.left + aigua.handle.width()/2;
			var markerCenter = aigua.marker.offset().left;
			var offset = position - markerCenter;
			var newNumber;

			// calculate the new number based on the original number
			// plus the dragging offset
			newNumber = aigua.modifyNumber(aigua.originalNumber, offset);

			// replace the selection with the new number
			aigua.codeMirror.replaceSelection(String(newNumber));

			// is the dragging cursor to the right of the marker?
			if (offset > 0) {

				// if the left bar got stuck, reset the bar width and position
				if (markerCenter - aigua.bar.offset().left - aigua.borderWidth > aigua.startingBarWidth/2) {
					aigua.resetBar(markerCenter);
				}

				// set the filler width and position
				aigua.filler.width(offset);
				aigua.filler.css('left', aigua.startingBarWidth/2);

				// are we dragging past the initial bar width?
				if (offset > aigua.startingBarWidth/2 - (aigua.borderWidth)) {

					// round the filler edges
					aigua.filler.addClass('filler-edge-right');

					 // add 1 pixel to filler width to prevent square edges
					 // from hitting the round borders prematurely
					aigua.filler.width(offset + 1);

					// set bar right edge to dragging position
					aigua.bar.width(position - aigua.bar.offset().left);
				}

				// reset the width, since fast drags won't trigger a drag call every pixel.
				else {
					aigua.resetBar(markerCenter);
				}

			// is the dragging cursor to the left of the marker?
			} else if (offset < 0) {

				// set the filler width
				aigua.filler.width(-offset);

				// adjust the filler position
				aigua.filler.css('left', aigua.startingBarWidth/2 - -offset + aigua.borderWidth/2);

				// are we dragging past the initial bar width?
				if (-offset > aigua.startingBarWidth/2) {

					// adjust the filler position
					aigua.filler.css('left', aigua.borderWidth/2);

					// round the filler edges
					aigua.filler.addClass('filler-edge-left');

					// set bar left edge to dragging position
					aigua.bar.width(-offset + aigua.startingBarWidth/2);
					aigua.bar.css('left', position - aigua.borderWidth);
				}

				// reset the width, since fast drags won't trigger a drag call every pixel.
				else {
					aigua.resetBar(markerCenter);
				}

			// are we at the middle?
			} else {
				aigua.filler.width(0);
			}
		}
	});

	// populate mode switcher
	_.each(aigua.modes, function(mode, index) {

		var div = $("

");
		var h2 = $("

");
		div.append(h2);

		h2.attr('class', index == aigua.currentModeIndex ? 'active' : 'passive');
		h2.text(mode.name);

		$('#modes').append(div);
	});

	// ----------- event handlers section

	// did we keyup the handle key?
	$(window).keyup(function(e) {

		if (e.which == 17) {

			// hide the slider
			aigua.slider.hide();

			// reset filler width
			aigua.filler.width(0);

			// reset bar width
			aigua.bar.width(aigua.startingBarWidth);

			// clear out the original number
			aigua.originalNumber = null;
		}
	});

	// force svg contents to occupy the entire svg container
	// by rerendering code on window resize
	$(window).on('resize', function() {
		aigua.renderCode();
	});

	// handle modes switcher
	$('#modes .item h2').on('click', function(e) {
		aigua.switchMode($(this).text());
	});

	// handle menu mouseover/mouseout events
	$('#menu .item h2').on('mouseover', function(e) {
		var item = $(this).parents('.item');

		$('ul', item).show(); // show this dropdown
		$(this).addClass('hover'); // add hover class to this h2
	});

	// handle menu mouseover/mouseout events
	$('#menu .item').on('mouseout', function(e) {

		if ($(e.toElement).parents('.item').get(0) == $(this).get(0)) {

		} else {

			var menu = $(this).parents('#menu');

			$('ul', menu).hide(); // hide all the dropdowns
			$('h2', menu).removeClass('hover'); // remove hover class from all the h2's
		}
	});

	// handle menu mouseover/mouseout events
	$('#menu .item li').on('mouseover', function(e) {
		$(this).addClass('hover');
	});

	// handle menu mouseover/mouseout events
	$('#menu .item li').on('mouseout', function(e) {
		$(this).removeClass('hover');
	});

	// handle menu item choices
	$('#menu .item ul li').on('click', function(e) {
		e.preventDefault();

		var choice = $(this);
		var itemName = $('h2', choice.parents('.item')).text();

		switch(itemName) {
			case 'file':
				switch (choice.text()) {
					case 'new':
						var result = confirm('Are you sure? You will lose any unsaved changes.');
						if (result) {
							aigua.codeMirror.setValue('');
						}
						break;
				}
			break;
			case 'examples':
				var result = confirm('Are you sure? You will lose any unsaved changes.');
				if (result) {
					aigua.loadExample(choice.attr('rel'));
				}
			break;
		}
	});

});

<|endoftext|>


<commit_before>var sssheet = (function() {
	var style = document.createElement("style");
	style.appendChild(document.createTextNode(""));
	document.head.appendChild(style);
	return style.sheet;
})();

if (window.location.href.indexOf('yukiblog.tw')!=-1) {
	$('.adsbygoogle').remove();$('.postad').remove();$("iframe").remove();
}
else if (window.location.href.indexOf('wiselyview.cc')!=-1) {
	sssheet.insertRule("#top-btn { display: none !important; }", 0);
}
else if (window.location.href.indexOf('mshw.info')!=-1) {
	sssheet.insertRule("#page { overflow: hidden; }", 0);
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
	sssheet.insertRule(".shr_ss { display: none !important; }", 0);
}
else if (window.location.href.indexOf('meishijournal.com')!=-1) {
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
}
else if (window.location.href.indexOf('wiselyview.cc')!=-1) {
	jQuery("iframe").remove();jQuery("#aswift_0_expand").remove();jQuery("#aswift_3_expand").remove();
}
else if (window.location.href.indexOf('lanlan-life.com')!=-1) {
	sssheet.insertRule("#header { display: none !important; }", 0);
	sssheet.insertRule("#sharebar { display: none !important; }", 0);
	sssheet.insertRule("#sharebar-block { display: none !important; }", 0);
}
else if (window.location.href.indexOf('candicecity.com')!=-1) {
	jQuery('.adsbygoogle, .sharedaddy').remove();
	sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
	sssheet.insertRule(".pi-Ad-mb-stick { display: none !important; }", 0);
}
else if (window.location.href.indexOf('starwing.cc')!=-1) {
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
}
else if (window.location.href.indexOf('yuann.tw')!=-1) {
	jQuery("a[href='http://radarurl.com/monitor']").remove();
}
else if (window.location.href.indexOf('ladymoko.com')!=-1) {
	jQuery('.adsbygoogle').remove();
}
else if (window.location.href.indexOf('xuite.net')!=-1) {
	jQuery('#rmiad').remove();
	sssheet.insertRule("#rmiad { display: none !important; }", 0);
}

sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
sssheet.insertRule(".pi-Ad-mb-stick { display: none !important; }", 0);
sssheet.insertRule(".pi-Ad-mb-stick { visibility: hidden !important; }", 0);
// sssheet.insertRule(".adsbygoogle ins { display: none !important; }", 0);
sssheet.insertRule(".nc_wrapper .floatBottom { display: none !important; }", 0);
sssheet.insertRule(".header-advertise { display: none !important; }", 0);

if (Math.random() > 0.2) {
	sssheet.insertRule(".pop-ad-cover { display: none !important; }", 0);
	sssheet.insertRule("#scupio_interstitialad { display: none !important; }", 0);
	sssheet.insertRule("#scupio_interstitial { display: none !important; }", 0);
}

if (jQuery) {
	jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();
	jQuery('#main').css('overflow', 'hidden');jQuery('.article-body iframe').remove();
	jQuery('.article-body .adsbygoogle').remove();jQuery('.article-body').removeClass('show-summary');
	jQuery('.article-header .adsbygoogle').remove();
	jQuery('.header-ad').css({height: '120px'});

	jQuery('a img').parent().css('pointer-events', 'none');
	jQuery("iframe[src*='maps.google.com']").remove();
	jQuery("iframe[src*='www.google.com/maps']").remove();
	jQuery("iframe[src*='facebook.com']").remove();
	jQuery('#main .relative-article').remove();jQuery('.article-body').css('overflow-x', 'hidden');
	jQuery('#recommend-tools').remove();jQuery('#main .comment-form').remove();
	jQuery('#main .article-comments').remove(); jQuery('#header-bar__share-tools').remove();
	jQuery('#header .bar--reading span').remove();

	jQuery('#sb-site #logo').remove(); jQuery('#wrapper #toggleMenu').remove(); jQuery('#float_fb_plugin').remove();

	sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
	sssheet.insertRule(".right-nav-stream-button { display: none !important; }", 0);
	sssheet.insertRule(".right-nav-share-button { display: none !important; }", 0);
	sssheet.insertRule(".sticky-box { display: none !important; }", 0);

	if (window.location.href.indexOf('bluehero.pixnet')!=-1) {
		jQuery('table,embed').width('100%');
	}

}

// Yuki
// jQuery('.article-header .adsbygoogle').css({height: '120px', overflow: 'hidden'});<commit_msg>remove ifoodie header<commit_after>var sssheet = (function() {
	var style = document.createElement("style");
	style.appendChild(document.createTextNode(""));
	document.head.appendChild(style);
	return style.sheet;
})();

if (window.location.href.indexOf('ifoodie.tw/post')!=-1) {
	sssheet.insertRule("#header { display: none !important; }", 0);
}

else if (window.location.href.indexOf('yukiblog.tw')!=-1) {
	$('.adsbygoogle').remove();$('.postad').remove();$("iframe").remove();
}
else if (window.location.href.indexOf('wiselyview.cc')!=-1) {
	sssheet.insertRule("#top-btn { display: none !important; }", 0);
}
else if (window.location.href.indexOf('mshw.info')!=-1) {
	sssheet.insertRule("#page { overflow: hidden; }", 0);
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
	sssheet.insertRule(".shr_ss { display: none !important; }", 0);
}
else if (window.location.href.indexOf('meishijournal.com')!=-1) {
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
}
else if (window.location.href.indexOf('wiselyview.cc')!=-1) {
	jQuery("iframe").remove();jQuery("#aswift_0_expand").remove();jQuery("#aswift_3_expand").remove();
}
else if (window.location.href.indexOf('lanlan-life.com')!=-1) {
	sssheet.insertRule("#header { display: none !important; }", 0);
	sssheet.insertRule("#sharebar { display: none !important; }", 0);
	sssheet.insertRule("#sharebar-block { display: none !important; }", 0);
}
else if (window.location.href.indexOf('candicecity.com')!=-1) {
	jQuery('.adsbygoogle, .sharedaddy').remove();
	sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
	sssheet.insertRule(".pi-Ad-mb-stick { display: none !important; }", 0);
}
else if (window.location.href.indexOf('starwing.cc')!=-1) {
	sssheet.insertRule(".adsbygoogle { display: none !important; }", 0);
}
else if (window.location.href.indexOf('yuann.tw')!=-1) {
	jQuery("a[href='http://radarurl.com/monitor']").remove();
}
else if (window.location.href.indexOf('ladymoko.com')!=-1) {
	jQuery('.adsbygoogle').remove();
}
else if (window.location.href.indexOf('xuite.net')!=-1) {
	jQuery('#rmiad').remove();
	sssheet.insertRule("#rmiad { display: none !important; }", 0);
}

sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
sssheet.insertRule(".pi-Ad-mb-stick { display: none !important; }", 0);
sssheet.insertRule(".pi-Ad-mb-stick { visibility: hidden !important; }", 0);
// sssheet.insertRule(".adsbygoogle ins { display: none !important; }", 0);
sssheet.insertRule(".nc_wrapper .floatBottom { display: none !important; }", 0);
sssheet.insertRule(".header-advertise { display: none !important; }", 0);

if (Math.random() > 0.2) {
	sssheet.insertRule(".pop-ad-cover { display: none !important; }", 0);
	sssheet.insertRule("#scupio_interstitialad { display: none !important; }", 0);
	sssheet.insertRule("#scupio_interstitial { display: none !important; }", 0);
}

if (jQuery) {
	jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();
	jQuery('#main').css('overflow', 'hidden');jQuery('.article-body iframe').remove();
	jQuery('.article-body .adsbygoogle').remove();jQuery('.article-body').removeClass('show-summary');
	jQuery('.article-header .adsbygoogle').remove();
	jQuery('.header-ad').css({height: '120px'});

	jQuery('a img').parent().css('pointer-events', 'none');
	jQuery("iframe[src*='maps.google.com']").remove();
	jQuery("iframe[src*='www.google.com/maps']").remove();
	jQuery("iframe[src*='facebook.com']").remove();
	jQuery('#main .relative-article').remove();jQuery('.article-body').css('overflow-x', 'hidden');
	jQuery('#recommend-tools').remove();jQuery('#main .comment-form').remove();
	jQuery('#main .article-comments').remove(); jQuery('#header-bar__share-tools').remove();
	jQuery('#header .bar--reading span').remove();

	jQuery('#sb-site #logo').remove(); jQuery('#wrapper #toggleMenu').remove(); jQuery('#float_fb_plugin').remove();

	sssheet.insertRule(".pi-ad-mobile-tag-outer { display: none !important; }", 0);
	sssheet.insertRule(".right-nav-stream-button { display: none !important; }", 0);
	sssheet.insertRule(".right-nav-share-button { display: none !important; }", 0);
	sssheet.insertRule(".sticky-box { display: none !important; }", 0);

	if (window.location.href.indexOf('bluehero.pixnet')!=-1) {
		jQuery('table,embed').width('100%');
	}

}

// Yuki
// jQuery('.article-header .adsbygoogle').css({height: '120px', overflow: 'hidden'});<|endoftext|>


<commit_before>'use strict'

const $userInputTitle = $('.input-title');
const $userInputBody = $('.input-body');
const $searchValue = $('.search-input');

function checkIdeas() {
  let currentIdeas = localStorage.getItem("ideas");
  if (currentIdeas === null || currentIdeas === undefined) {
    localStorage.setItem("ideas", JSON.stringify([]))
  }
}

function Idea (title, body, quality){
  this.title = title;
  this.body = body;
  this.quality = quality;
  this.id = Date.now();
}

Idea.prototype.storeIdea = function (idea) {
  let newIdeas = JSON.parse(localStorage.getItem("ideas"))
  newIdeas.push(idea)
  localStorage.setItem("ideas", JSON.stringify(newIdeas))
}

const deleteIdeaFromStorage = function(ideaId) {
  let currentIdeas = JSON.parse(localStorage.getItem('ideas'))
  currentIdeas.forEach(function(idea, index) {
    if (idea.id === ideaId) {
      currentIdeas.splice(index, 1)
      localStorage.setItem('ideas', JSON.stringify(currentIdeas))
    }
  })
}

function getAndParseIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}

function deleteIdeasFromDom() {
  $('.delete').on('click', function(){
    let $idea = $(this).parent()
    deleteIdeaFromStorage($idea.data("id"))
    $idea.remove();
  });
}

function getIdeasFromStorageAndAppendThem() {
  let ideas = getAndParseIdeas();
  if (typeof ideas[0] !== "object") {
    console.log("NOTHINGGG");
  } else {
    for (let i = 0; i < ideas.length; i++) {
      let idea = ideas[i]
      createOutput(idea.title, idea.body, idea.id);
    }
    deleteIdeasFromDom()
  }
}

function createOutput(title, body, ideaId) {
  $('.all-ideas').prepend(
    `

${title}

      <button class="idea-button delete" type="button"></button>

${body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: swill

`
  );
};

$('.save-button').on('click', function(event) {
  event.preventDefault();
  const title = $userInputTitle.val();
  const body = $userInputBody.val();
  const newIdea = new Idea(title, body);
  createOutput(title, body, newIdea.id);
  newIdea.storeIdea(newIdea);
  deleteIdeasFromDom();
  $userInputTitle.val('');
  $userInputBody.val('');
});

checkIdeas();
getIdeasFromStorageAndAppendThem();

// $('.search-input').on('keyup', function() {
//   var searchedValue = $('.layout-section-user-output').has('.user-idea-title').val(searchValue.val());
//   // allIdeas.title = searchedValue;
// });
<commit_msg>have working upvote and downvote buttons on the page that work through local storage also refactored delete ideas from the Dom everytime we getideasfromstorage so they are reprinted properly<commit_after>"use strict";

var $userInputTitle = $('.input-title');
var $userInputBody = $('.input-body');
var $searchValue = $('.search-input');
var qualities = ['swill', 'plausible', 'genius'];

function checkIdeas() {
  var currentIdeas = localStorage.getItem("ideas");
  if (currentIdeas === null || currentIdeas === undefined) {
    localStorage.setItem("ideas", JSON.stringify([]))
  }
}

function Idea (title, body) {
  this.title = title;
  this.body = body;
  this.quality = 'swill';
  this.id = Date.now();
}

Idea.prototype.storeIdea = function (idea) {
  var newIdeas = getAndParseIdeas();
  newIdeas.push(idea)
  localStorage.setItem("ideas", JSON.stringify(newIdeas))
}

var deleteIdeaFromStorage = function(ideaId) {
  var currentIdeas = getAndParseIdeas();
  currentIdeas.forEach(function(idea, index) {
    if (idea.id === ideaId) {
      currentIdeas.splice(index, 1)
      localStorage.setItem('ideas', JSON.stringify(currentIdeas))
    }
  })
}

function getAndParseIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}

function deleteIdeasFromDom() {
  $('.delete').on('click', function(){
    var $idea = $(this).parent()
    deleteIdeaFromStorage($idea.data("id"))
    $idea.remove();
  });
}

function getIdeasFromStorageAndAppendThem() {
  var ideas = getAndParseIdeas();
  if (typeof ideas[0] !== "object") {
    console.log("NOTHINGGG");
  } else {
    for (var i = 0; i < ideas.length; i++) {
      createOutput(ideas[i]);
    }
    deleteIdeasFromDom();
  }
}

function createOutput(idea) {
  $('.all-ideas').prepend(
    `

${idea.title}

      <button class="idea-button delete" type="button"></button>

${idea.body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: ${idea.quality}

`
  );
  upvoteIdea();
  downvoteIdea();
};

function upvoteIdea() {
  $('.upvote').on('click', function(event) {
    console.log('click upvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = incrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
        $('.all-ideas').children().remove();
        getIdeasFromStorageAndAppendThem();
      }
    };
  });
}

function incrementQuality(idea) {
  if (idea.quality !== 'genius') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i + 1];
      }
    };
  } else {
    return 'genius';
  };
}

function downvoteIdea() {
  $('.downvote').on('click', function(event) {
    console.log('click downvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = decrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
        $('.all-ideas').children().remove();
        getIdeasFromStorageAndAppendThem();
      }
    };
  });
}

function decrementQuality(idea) {
  if (idea.quality !== 'swill') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i - 1];
      }
    };
  } else {
    return 'swill';
  };
}

$('.save-button').on('click', function(event) {
  event.preventDefault();
  var title = $userInputTitle.val();
  var body = $userInputBody.val();
  var newIdea = new Idea(title, body);
  createOutput(newIdea);
  newIdea.storeIdea(newIdea);
  upvoteIdea();
  downvoteIdea();
  deleteIdeasFromDom();
  $userInputTitle.val('');
  $userInputBody.val('');
});

checkIdeas();
getIdeasFromStorageAndAppendThem();
<|endoftext|>


<commit_before>/**
 * ownCloud - quicknotes
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Matias De lellis <mati86dl@gmail.com>
 * @copyright Matias De lellis 2016
 */

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newNote: $('#new-note-string').text()
};

// this notes object holds all our notes
var Notes = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._notes = [];
    this._activeNote = undefined;
};

Notes.prototype = {
    load: function (id) {
        var self = this;
        this._notes.forEach(function (note) {
            if (note.id === id) {
                note.active = true;
                self._activeNote = note;
            } else {
                note.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeNote;
    },
    unsetActive: function () {
        this._activeNote = undefined;
        this._notes.forEach(function (note) {
            note.active = false;
        });
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeNote.id;
        this._notes.forEach(function (note, counter) {
            if (note.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active note if necessary
            if (this._activeNote === this._notes[index]) {
                delete this._activeNote;
            }

            this._notes.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (note) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(note)
        }).done(function (note) {
            self._notes.push(note);
            self._activeNote = note;
            self.load(note.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._notes;
    },
    getColors: function () {
        var colors = [];
        var Ccolors = [];
        $.each(this._notes, function(index, value) {
            if ($.inArray(value.color, colors) == -1) {
                colors.push(value.color);
            }
        });
        $.each(colors, function(index, value) {
            Ccolors.push({color: value});
        });
        return Ccolors;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (notes) {
            self._activeNote = undefined;
            self._notes = notes.reverse();
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, color) {
        var note = this.getActive();
        note.title = title;
        note.content = content;
        note.color = color;

        return $.ajax({
            url: this._baseUrl + '/' + note.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(note)
        });
    },
    updateId: function (id, title, content, color) {
        this.load(id);
        return this.updateActive(title, content, color);
    }
};

// this will be the view that is used to update the html
var View = function (notes) {
    this._notes = notes;
};

View.prototype = {

    showAll: function () {
        //self._notes.unsetActive();
        $('.notes-grid').isotope({ filter: '*'});
    },
    editNote: function (id) {
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-div #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        var note = $('.notes-grid [data-id=' + id + ']').parent();

        var title = note.find("#title-editable").html();
        var content = note.find("#content-editable").html();
        var color = note.children().css("background-color");

        var modalid = modalnote.data('id');

        if (id == modalid)
            return;

        modalnote.data('id', id);
        modaltitle.html(title);
        modalcontent.html(content);
        modalnote.css("background-color", color);

        /* Positioning the modal to the original size */
        $(".modal-content").css({
            "position" : "absolute",
            "left"     : note.offset().left,
            "top"      : note.offset().top,
            "width"    : note.width(),
            "min-height": note.height(),
            "height:"  : "auto"
        });
        modal.removeClass("hide-modal-note");
        modal.addClass("show-modal-note");
        modalcontent.focus();
    },
    cancelEdit: function () {
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-dive #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        this._notes.unsetActive();
        this.showAll();

        modal.removeClass("show-modal-note");
        modal.addClass("hide-modal-note");

        modalnote.data('id', -1);
        modaltitle.html("");
        modalcontent.html("");
    },
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({notes: this._notes.getAll()});

        $('#div-content').html(html);

        // Init masonty grid to notes.
        $('.notes-grid').isotope({
            itemSelector: '.note-grid-item',
            layoutMode: 'masonry',
            masonry: {
                isFitWidth: true,
                fitWidth: true,
                gutter: 10,
            }
        });

        // Handle click event to open note.
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-div #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        // Show delete icon on hover.
        $(".quicknote").hover(function() {
            $(this).find(".icon-delete").addClass( "show-delete-icon");
        }, function(){
            $(this).find(".icon-delete").removeClass("show-delete-icon");
        });

        // Open notes when clicking them.
        $(".quicknote").click(function (event) {
            event.stopPropagation();

            var modalnote = $("#modal-note-editable .quicknote");
            var modalid = modalnote.data('id');
            if (modalid > 0) return;
            var id = parseInt($(this).data('id'), 10);

            self.editNote(id);
        });

        // Cancel when click outside the modal.
        $(".modal-note-background").click(function () {
            self.cancelEdit();
        });

        // Cancel with escape key
        $(document).keyup(function(event) {
            if (event.keyCode == 27) {
                self.cancelEdit();
            }
        });

        // Remove note icon
        var self = this;
        $('#app-content .icon-delete-note').click(function (event) {
            event.stopPropagation();
            var id = parseInt($(this).parent().data('id'), 10);
            self._notes.load(id);
            self._notes.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete note, not found');
            });

        });

        // Handle colors.
        $('#app-content .circle-toolbar').click(function (event) {
            event.stopPropagation();

            var color = $(this).css("background-color");
            modalnote.css("background-color", color);
        });

        // handle cancel and saves note.
        $('#app-content #cancel-button').click(function (event) {
           self.cancelEdit();
        });

        $('#app-content #save-button').click(function (event) {
            event.stopPropagation();

            var id = modalnote.data('id');
            var title = modaltitle.html();
            var content = modalcontent.html();
            var color = modalnote.css("background-color");

            self._notes.updateId(id, title, content, color).done(function () {
                self._notes.unsetActive();

                modal.removeClass("show-modal-note");
                modal.addClass("hide-modal-note");

                modalnote.data('id', -1);
                modaltitle.html("");
                modalcontent.html("");

                self.render();
            }).fail(function () {
                alert('DOh!. Could not update note!.');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({colors: this._notes.getColors(), notes: this._notes.getAll()});

        $('#app-navigation ul').html(html);

        // show all notes
        $('#all-notes').click(function () {
            self._notes.unsetActive();
            $('.notes-grid').isotope({ filter: '*'});
        });

        // create a new note
        var self = this;
        $('#new-note').click(function () {
            var note = {
                title: translations.newNote,
                content: '',
                color: '#F7EB96'
            };

            self._notes.create(note).done(function() {
                self.render();
                $('#div-content .text-note').focus();
            }).fail(function () {
                alert('Could not create note');
            });
        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.note');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a note
        $('#app-navigation .note .delete').click(function () {
            var entry = $(this).closest('.note');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._notes.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete note, not found');
            });
        });

        // show a note
        $('#app-navigation .note > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            $('.notes-grid').isotope({ filter: function() {
                var itemId = parseInt($(this).children().data('id'), 10);
                return id == itemId;
            } });
        });

        // Handle colors.
        $('#app-navigation .circle-toolbar').click(function (event) {
            event.stopPropagation();

            var color = $(this).css("background-color");
            if (color != 'transparent') {
                $('.notes-grid').isotope({ filter: function() {
                    var itemColor = $(this).children().css("background-color");
                    return color == itemColor;
                }});
            }
            else {
                self.showAll();
            }
        });

    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var notes = new Notes(OC.generateUrl('/apps/quicknotes/notes'));
var view = new View(notes);
notes.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load notes');
});

});

})(OC, window, jQuery);
<commit_msg>Not refilter anything when cancel edit. \nShow animation when remove a note insted redraw everything<commit_after>/**
 * ownCloud - quicknotes
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Matias De lellis <mati86dl@gmail.com>
 * @copyright Matias De lellis 2016
 */

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newNote: $('#new-note-string').text()
};

// this notes object holds all our notes
var Notes = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._notes = [];
    this._activeNote = undefined;
};

Notes.prototype = {
    load: function (id) {
        var self = this;
        this._notes.forEach(function (note) {
            if (note.id === id) {
                note.active = true;
                self._activeNote = note;
            } else {
                note.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeNote;
    },
    unsetActive: function () {
        this._activeNote = undefined;
        this._notes.forEach(function (note) {
            note.active = false;
        });
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeNote.id;
        this._notes.forEach(function (note, counter) {
            if (note.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active note if necessary
            if (this._activeNote === this._notes[index]) {
                delete this._activeNote;
            }

            this._notes.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (note) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(note)
        }).done(function (note) {
            self._notes.push(note);
            self._activeNote = note;
            self.load(note.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._notes;
    },
    getColors: function () {
        var colors = [];
        var Ccolors = [];
        $.each(this._notes, function(index, value) {
            if ($.inArray(value.color, colors) == -1) {
                colors.push(value.color);
            }
        });
        $.each(colors, function(index, value) {
            Ccolors.push({color: value});
        });
        return Ccolors;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (notes) {
            self._activeNote = undefined;
            self._notes = notes.reverse();
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, color) {
        var note = this.getActive();
        note.title = title;
        note.content = content;
        note.color = color;

        return $.ajax({
            url: this._baseUrl + '/' + note.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(note)
        });
    },
    updateId: function (id, title, content, color) {
        this.load(id);
        return this.updateActive(title, content, color);
    }
};

// this will be the view that is used to update the html
var View = function (notes) {
    this._notes = notes;
};

View.prototype = {

    showAll: function () {
        //self._notes.unsetActive();
        $('.notes-grid').isotope({ filter: '*'});
    },
    editNote: function (id) {
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-div #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        var note = $('.notes-grid [data-id=' + id + ']').parent();

        var title = note.find("#title-editable").html();
        var content = note.find("#content-editable").html();
        var color = note.children().css("background-color");

        var modalid = modalnote.data('id');

        if (id == modalid)
            return;

        modalnote.data('id', id);
        modaltitle.html(title);
        modalcontent.html(content);
        modalnote.css("background-color", color);

        /* Positioning the modal to the original size */
        $(".modal-content").css({
            "position" : "absolute",
            "left"     : note.offset().left,
            "top"      : note.offset().top,
            "width"    : note.width(),
            "min-height": note.height(),
            "height:"  : "auto"
        });
        modal.removeClass("hide-modal-note");
        modal.addClass("show-modal-note");
        modalcontent.focus();
    },
    cancelEdit: function () {
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-dive #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        this._notes.unsetActive();

        modal.removeClass("show-modal-note");
        modal.addClass("hide-modal-note");

        modalnote.data('id', -1);
        modaltitle.html("");
        modalcontent.html("");
    },
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({notes: this._notes.getAll()});

        $('#div-content').html(html);

        // Init masonty grid to notes.
        $('.notes-grid').isotope({
            itemSelector: '.note-grid-item',
            layoutMode: 'masonry',
            masonry: {
                isFitWidth: true,
                fitWidth: true,
                gutter: 10,
            }
        });

        // Handle click event to open note.
        var modal = $('#modal-note-div');
        var modaltitle = $('#modal-note-div #title-editable');
        var modalcontent = $('#modal-note-div #content-editable');
        var modalnote = $("#modal-note-div .quicknote");

        // Show delete icon on hover.
        $(".quicknote").hover(function() {
            $(this).find(".icon-delete").addClass( "show-delete-icon");
        }, function(){
            $(this).find(".icon-delete").removeClass("show-delete-icon");
        });

        // Open notes when clicking them.
        $(".quicknote").click(function (event) {
            event.stopPropagation();

            var modalnote = $("#modal-note-editable .quicknote");
            var modalid = modalnote.data('id');
            if (modalid > 0) return;
            var id = parseInt($(this).data('id'), 10);

            self.editNote(id);
        });

        // Cancel when click outside the modal.
        $(".modal-note-background").click(function () {
            self.cancelEdit();
        });

        // Cancel with escape key
        $(document).keyup(function(event) {
            if (event.keyCode == 27) {
                self.cancelEdit();
            }
        });

        // Remove note icon
        var self = this;
        $('#app-content .icon-delete-note').click(function (event) {
            var note = $(this).parent();
            var id = parseInt(note.data('id'), 10);

            event.stopPropagation();

            self._notes.load(id);
            self._notes.removeActive().done(function () {
                $(".notes-grid").isotope('remove', note.parent())
                                .isotope('layout');
                self.renderNavigation();
            }).fail(function () {
                alert('Could not delete note, not found');
            });

        });

        // Handle colors.
        $('#app-content .circle-toolbar').click(function (event) {
            event.stopPropagation();

            var color = $(this).css("background-color");
            modalnote.css("background-color", color);
        });

        // handle cancel and saves note.
        $('#app-content #cancel-button').click(function (event) {
           self.cancelEdit();
        });

        $('#app-content #save-button').click(function (event) {
            event.stopPropagation();

            var id = modalnote.data('id');
            var title = modaltitle.html();
            var content = modalcontent.html();
            var color = modalnote.css("background-color");

            self._notes.updateId(id, title, content, color).done(function () {
                self._notes.unsetActive();

                modal.removeClass("show-modal-note");
                modal.addClass("hide-modal-note");

                modalnote.data('id', -1);
                modaltitle.html("");
                modalcontent.html("");

                self.render();
            }).fail(function () {
                alert('DOh!. Could not update note!.');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({colors: this._notes.getColors(), notes: this._notes.getAll()});

        $('#app-navigation ul').html(html);

        // show all notes
        $('#all-notes').click(function () {
            self._notes.unsetActive();
            $('.notes-grid').isotope({ filter: '*'});
        });

        // create a new note
        var self = this;
        $('#new-note').click(function () {
            var note = {
                title: translations.newNote,
                content: '',
                color: '#F7EB96'
            };

            self._notes.create(note).done(function() {
                self.render();
                $('#div-content .text-note').focus();
            }).fail(function () {
                alert('Could not create note');
            });
        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.note');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a note
        $('#app-navigation .note .delete').click(function () {
            var entry = $(this).closest('.note');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._notes.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete note, not found');
            });
        });

        // show a note
        $('#app-navigation .note > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            $('.notes-grid').isotope({ filter: function() {
                var itemId = parseInt($(this).children().data('id'), 10);
                return id == itemId;
            } });
        });

        // Handle colors.
        $('#app-navigation .circle-toolbar').click(function (event) {
            event.stopPropagation();

            var color = $(this).css("background-color");
            if (color != 'transparent') {
                $('.notes-grid').isotope({ filter: function() {
                    var itemColor = $(this).children().css("background-color");
                    return color == itemColor;
                }});
            }
            else {
                self.showAll();
            }
        });

    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var notes = new Notes(OC.generateUrl('/apps/quicknotes/notes'));
var view = new View(notes);
notes.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load notes');
});

});

})(OC, window, jQuery);
<|endoftext|>


<commit_before>
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    let muted = message.guild.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non'))
            return r;
    })
    if (message.member.permissions.has("MANAGE_MESSAGES")) {
        message.mentions.users
            .map(u => msg.guild.member(u))
            .map(m => m.removeRole(muted))
    }
    else
        message.reply("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif")
}
/**
 * description of the command
 */
const description = "Unmutes a user";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<commit_msg>Update unmute.js<commit_after>
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    let muted = message.guild.roles.find(function (r) {
        if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non'))
            return r;
    })
    if (message.member.permissions.has("MANAGE_MESSAGES")) {
        message.mentions.users
            .map(u => message.guild.member(u))
            .map(m => m.removeRole(muted))
    }
    else
        message.reply("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif")
}
/**
 * description of the command
 */
const description = "Unmutes a user";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<|endoftext|>


<commit_before>var express = require('express')
	, router = express.Router()
	, MPD = require("./lib/mpd.js")
    , events = require('events')
    , eventEmitter = new events.EventEmitter()
    , UiPanel = require('./ui-panel');

	var mpd_client = new MPD(6600, 'localhost');
	//mpd_client.enableLogging();
	//mpd_client.on('Connect', function (){
	//	mpd_client.updateDatabase();
	//});
	mpd_client.on('Event', function (state) {
		//console.log("->-> Evento: " + state.type);
	});

    mpd_client.on('SocketClosed', function(){
        console.log('SocketClosed -> new connection!')
        mpd_client = new MPD(6600, 'localhost');
    });

    var uiPanel = new UiPanel(mpd_client, eventEmitter);

	router.use('/', require('./search.js')(mpd_client, eventEmitter));
	router.use('/', require('./rfid.js')(mpd_client, eventEmitter));
	router.use('/player', require('./player.js')(mpd_client));

    router.get('/update-stream', function (req, res) {
        var sse = startSees(res);
        registerEvents();

        function startSees() {
            res.writeHead(200, {
                'Content-Type': 'text/event-stream',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive'
            });
            res.write("\n");

            return function sendSse(name, data, id) {
                res.write("event: " + name + "\n");
                if (id) res.write("id: " + id + "\n");
                res.write("data: " + data + "\n\n");
            };
        }
        function sendSearchResults(datos) {
            sse("message", JSON.stringify(datos));
        }
        function registerEvents() {
            eventEmitter.on("searchResultsFound", sendSearchResults);
            //eventEmitter.on("rfidRead", sendRfidRead);
            req.once("end", function () {
                eventEmitter.removeListener("searchResultsFound", sendSearchResults);
                //eventEmitter.removeListener("rfidRead", sendRfidRead);
            });
        };
        function sendRfidRead(rfid) {
           // sse("rfidRead", JSON.stringify(rfid));
        };
    });

module.exports = router;
<commit_msg>avoid loading ui-panel<commit_after>var express = require('express')
	, router = express.Router()
	, MPD = require("./lib/mpd.js")
    , events = require('events')
    , eventEmitter = new events.EventEmitter()
    //, UiPanel = require('./ui-panel')

	var mpd_client = new MPD(6600, 'localhost');
	//mpd_client.enableLogging();
	//mpd_client.on('Connect', function (){
	//	mpd_client.updateDatabase();
	//});
	mpd_client.on('Event', function (state) {
		//console.log("->-> Evento: " + state.type);
	});

    //mpd_client.on('SocketClosed', function(){
    //    console.log('SocketClosed -> new connection!')
    //    mpd_client = new MPD(6600, 'localhost');
    //});

    //var uiPanel = new UiPanel(mpd_client, eventEmitter);

	router.use('/', require('./search.js')(mpd_client, eventEmitter));
	router.use('/', require('./rfid.js')(mpd_client, eventEmitter));
	router.use('/player', require('./player.js')(mpd_client));

    router.get('/update-stream', function (req, res) {
        var sse = startSees(res);
        registerEvents();

        function startSees() {
            res.writeHead(200, {
                'Content-Type': 'text/event-stream',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive'
            });
            res.write("\n");

            return function sendSse(name, data, id) {
                res.write("event: " + name + "\n");
                if (id) res.write("id: " + id + "\n");
                res.write("data: " + data + "\n\n");
            };
        }
        function sendSearchResults(datos) {
            sse("message", JSON.stringify(datos));
        }
        function registerEvents() {
            eventEmitter.on("searchResultsFound", sendSearchResults);
            //eventEmitter.on("rfidRead", sendRfidRead);
            req.once("end", function () {
                eventEmitter.removeListener("searchResultsFound", sendSearchResults);
                //eventEmitter.removeListener("rfidRead", sendRfidRead);
            });
        };
        function sendRfidRead(rfid) {
           // sse("rfidRead", JSON.stringify(rfid));
        };
    });

module.exports = router;
<|endoftext|>


<commit_before>var config = require('config.json');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
//db.bind(process.env.PHONE_LIST);
db.bind('listin');
var Q = require('q');
var service = {};

service.findOne = findOne;

module.exports = service;

function findOne(phoneNumber)
{
	 var deferred = Q.defer();
	 db.listin.findOne({NVOMSISDN:phoneNumber},
			 function(err,doc)
			 {
				 if (err) deferred.reject(err.name + ': ' + err.message);

				 deferred.resolve();
			 });
	 return deferred.promise;
}
<commit_msg>Solución a la consulta<commit_after>var config = require('config.json');
var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, { native_parser: true });
//db.bind(process.env.PHONE_LIST);
db.bind('listin');
var Q = require('q');
var service = {};

service.findOne = findOne;

module.exports = service;

function findOne(phoneNumber)
{
	 var deferred = Q.defer();
	 db.listin.findOne({ NVOMSISDN: parseInt(phoneNumber) },
			 function(err,doc)
			 {
				 if (err) deferred.reject(err.name + ': ' + err.message);

				 deferred.resolve();
			 });
	 return deferred.promise;
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $.get("domains.json", function(data) {
        $(".scan").removeClass("disabled");
        $(".infotext").html($(".infotext").html().replace("list of domains", "list of " + data.domains.length + " domains"));
        $(".scan").click(function() {
            var domains = data.domains;
            var faileddomains = {};
            var cnt = 0;
            $(".count").html("0 / " + domains.length);
            $(".scanbutton").hide();
            $(".loadingbar").show();
            $.each(domains.reverse(), function(i, data) {
                var image = new Image();
                image.setAttribute("domain", data.domain.replace("~", ""));
                image.setAttribute("title", data.title);
                image.onerror = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    /* This is a server-side check to determine if a domain might be fully offline. The server just replies '1' or '0' depending if it can reach the domain. Keep in mind that CensorRadar will never rely on this backup server. It's just an extra feature for the end user. Source code: https://pastebin.com/bsGuBHxt */
                    $.get("https://luithollander.nl/censorradar.php?url=" + encodeURIComponent(image.src), function(online) {
                        faileddomains[data.title] = parseInt(online);
                    }.bind(this)).fail(function() {
                        faileddomains[data.title] = 2;
                    }.bind(this)).always(function() {
                        $(".bar").width(((cnt / domains.length) * 100) + '%');
                        $(".failedresults").fadeIn(500);
                        if (Object.keys(faileddomains).length == 1) {
                            $(".failed").html(Object.keys(faileddomains).length + ' domain could not be reached');
                        } else {
                            $(".failed").html(Object.keys(faileddomains).length + ' domains could not be reached');
                        }
                        if (cnt == domains.length) {
                            $(".loadingbar").fadeOut(500);
                        }
                        if (faileddomains[data.title] == 0) {
                            new_row = $("
" + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached on both server and client. This probably means the website is offline.','warning');\">

");
                        } else if (faileddomains[data.title] == 1 || faileddomains[data.title] == 2) {
                            new_row = $("
 " + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached','error');\">

");
                        }
                        new_row.hide();
                        $(".table tbody").prepend(new_row);
                        new_row.fadeIn(200);
                    })
                };

                image.onload = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    $(".bar").width(((cnt / domains.length) * 100) + '%');
                    if (cnt == domains.length && Object.keys(faileddomains).length == 0) {
                        $(".loadingbar").fadeOut(500);
                        $(".successresults").fadeIn(500);
                    } else if (cnt == domains.length) {
                        $(".loadingbar").fadeOut(500);
                    }
                };
                if (data.domain.match("^~")) {
                    image.src = 'http://' + data.domain.replace("~", "") + '/' + data.img + '?no-cache=' + (new Date).getTime();
                } else {
                    image.src = 'http://www.' + data.domain + '/' + data.img + '?no-cache=' + (new Date).getTime();
                }
            });
        });
    }).fail(function() {
        swal('Connection error', 'The domains database could not be loaded', 'error');
    })
});
<commit_msg>Added ie and edge check<commit_after>$(document).ready(function() {
    if (navigator.appName == 'Microsoft Internet Explorer' || window.navigator.userAgent.indexOf("Edge") > -1 || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {
        swal('Unsupported', 'Please note that IE and Edge are not supported', 'warning');
    }
    $.get("domains.json", function(data) {
        $(".scan").removeClass("disabled");
        $(".infotext").html($(".infotext").html().replace("list of domains", "list of " + data.domains.length + " domains"));
        $(".scan").click(function() {
            var domains = data.domains;
            var faileddomains = {};
            var cnt = 0;
            $(".count").html("0 / " + domains.length);
            $(".scanbutton").hide();
            $(".loadingbar").show();
            $.each(domains.reverse(), function(i, data) {
                var image = new Image();
                image.setAttribute("domain", data.domain.replace("~", ""));
                image.setAttribute("title", data.title);
                image.onerror = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    /* This is a server-side check to determine if a domain might be fully offline. The server just replies '1' or '0' depending if it can reach the domain. Keep in mind that CensorRadar will never rely on this backup server. It's just an extra feature for the end user. Source code: https://pastebin.com/bsGuBHxt */
                    $.get("https://luithollander.nl/censorradar.php?url=" + encodeURIComponent(image.src), function(online) {
                        faileddomains[data.title] = parseInt(online);
                    }.bind(this)).fail(function() {
                        faileddomains[data.title] = 2;
                    }.bind(this)).always(function() {
                        $(".bar").width(((cnt / domains.length) * 100) + '%');
                        $(".failedresults").fadeIn(500);
                        if (Object.keys(faileddomains).length == 1) {
                            $(".failed").html(Object.keys(faileddomains).length + ' domain could not be reached');
                        } else {
                            $(".failed").html(Object.keys(faileddomains).length + ' domains could not be reached');
                        }
                        if (cnt == domains.length) {
                            $(".loadingbar").fadeOut(500);
                        }
                        if (faileddomains[data.title] == 0) {
                            new_row = $("
" + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached on both server and client. This probably means the website is offline.','warning');\">

");
                        } else if (faileddomains[data.title] == 1 || faileddomains[data.title] == 2) {
                            new_row = $("
 " + data.title + "
<a href='javascript:void(0);' onclick=\"swal('" + data.title + "','" + data.domain.replace("~", "") + " could not be reached','error');\">

");
                        }
                        new_row.hide();
                        $(".table tbody").prepend(new_row);
                        new_row.fadeIn(200);
                    })
                };

                image.onload = function() {
                    cnt++;
                    $(".count").html(cnt + " / " + domains.length);
                    $(".bar").width(((cnt / domains.length) * 100) + '%');
                    if (cnt == domains.length && Object.keys(faileddomains).length == 0) {
                        $(".loadingbar").fadeOut(500);
                        $(".successresults").fadeIn(500);
                    } else if (cnt == domains.length) {
                        $(".loadingbar").fadeOut(500);
                    }
                };
                if (data.domain.match("^~")) {
                    image.src = 'http://' + data.domain.replace("~", "") + '/' + data.img + '?no-cache=' + (new Date).getTime();
                } else {
                    image.src = 'http://www.' + data.domain + '/' + data.img + '?no-cache=' + (new Date).getTime();
                }
            });
        });
    }).fail(function() {
        swal('Connection error', 'The domains database could not be loaded', 'error');
    })
});<|endoftext|>