<commit_before>var config = require('./config.json');

var udp_config = config.udp;
var http_config = config.http;

var votes = [];
var status = {
	total : 0
};

// UDP Server

var dgram = require("dgram");
var udpServer = dgram.createSocket("udp4");

udpServer.on("error",function(err){
	console.log("Server error:\n", err.stack);
	udpServer.close();
});

udpServer.on("listening", function(){
	var address = udpServer.address();
	console.log("UDP Server listening ", address.address, ":", address.port);
});

udpServer.on("message", function(msg, rinfo){
	console.log("message: ", msg, rinfo.address, ":", rinfo.port);

	votes.push({id: votes.length});

	status.total++;
	socket.emit('vote', status);

	var res = new Buffer('OK');
	var client = dgram.createSocket("udp4");
	client.send(res, 0, res.length, rinfo.port, rinfo.host, function(err, bytes){
		client.close();
	});

});

udpServer.bind(udp_config.port, udp_config.host);

// HTTP Server

var http = require('http');
var io = require('socket.io');

var httpServer = http.createServer(function(req, res){
	res.writeHead(200, 'Content-Type: text/html');

	var html = '<!DOCTYPE html>';
	html += '';
	html += '	';
	html += '		<meta charset="UTF-8">';
	html += '		';
	html += '		';
	html += '	';
	html += '	';
	html += '
'+JSON.stringify(status)+'
';
	html += '	';
	html += '';

	res.end(html);
});

var socket = io(httpServer);

httpServer = httpServer.listen(http_config.port, http_config.host);
console.log("HTTP Server listening ", http_config.host, ":", http_config.port);<commit_msg>WS: Votation dynamics implemented<commit_after>var config = require('./config.json');

var udp_config = config.udp;
var http_config = config.http;

var votes = new Map();
var votation = {
	total : 0,
	votes: {
		"PRI": 0,
		"PAN": 0,
		"PRD": 0,
		"P_T": 0,
		"VDE": 0,
		"MVC": 0,
		"NVA": 0,
		"MOR": 0,
		"HUM": 0,
		"ENC": 0,
		"FRD": 0
	}
};

var appendVote = function(vote){

	votation.total++;

	if(votes.has(vote.curp) && votes.has(vote.rfc)){

		votation.votes["FRD"]++;

	}else{

		votes.set(vote.curp, vote);
		votes.set(vote.rfc, vote);

		votation.votes[vote.party]++;
	}

	socket.emit('vote', votation);
}

// UDP Server

var dgram = require("dgram");
var udpServer = dgram.createSocket("udp4");

udpServer.on("error",function(err){
	console.log("Server error:\n", err.stack);
	udpServer.close();
});

udpServer.on("listening", function(){
	var address = udpServer.address();
	console.log("UDP Server listening ", address.address, ":", address.port);
});

udpServer.on("message", function(msg, rinfo){

	var vote = JSON.parse(msg.toString());
	console.log("received message from: ",rinfo.address, ":", rinfo.port);

	appendVote(vote);

	var res = new Buffer('OK');
	var client = dgram.createSocket("udp4");

	client.send(res, 0, res.length, rinfo.port, rinfo.host, function(err, bytes){
		client.close();
	});

});

udpServer.bind(udp_config.port, udp_config.host);

// HTTP Server

var http = require('http');
var io = require('socket.io');

var httpServer = http.createServer(function(req, res){
	res.writeHead(200, 'Content-Type: text/html');

	var html = '<!DOCTYPE html>';
	html += '';
	html += '	';
	html += '		<meta charset="UTF-8">';
	html += '		';
	html += '		';
	html += '	';
	html += '	';
	html += '
'+JSON.stringify(votation)+'
';
	html += '	';
	html += '';

	res.end(html);
});

var socket = io(httpServer);

httpServer = httpServer.listen(http_config.port, http_config.host);
console.log("HTTP Server listening ", http_config.host, ":", http_config.port);<|endoftext|>


<commit_before>export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
export const INCREMENT_COUNTER_ASYNC = 'INCREMENT_COUNTER_ASYNC'

export const incrementCounter = () => ({
  type: INCREMENT_COUNTER
})

export const decrementCounter = () => ({
  type: DECREMENT_COUNTER
})

export const incrementCounterAsync = () => {
  return (dispatch, getState) => {
    setTimeout(() => {
      dispatch(incrementCounter())
    })
  }
}
<commit_msg>setTimeout for 1 second<commit_after>export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
export const INCREMENT_COUNTER_ASYNC = 'INCREMENT_COUNTER_ASYNC'

export const incrementCounter = () => ({
  type: INCREMENT_COUNTER
})

export const decrementCounter = () => ({
  type: DECREMENT_COUNTER
})

export const incrementCounterAsync = () => {
  return (dispatch, getState) => {
    setTimeout(() => {
      dispatch(incrementCounter())
    }, 1000)
  }
}
<|endoftext|>


<commit_before>/* TODO:
- sources/links
- slider/calendar picker
*/
(function(ns){
  // config
  ns.transitions = 600;
  ns.selecterHeight = 200;
  ns.selectedExpanded = false;
  ns.selectedVisual = "screen";
  ns.diffExpanded = null;
  ns.currentwin = "copy";

  // internal
  ns.last = ns.versions[ns.versions.length - 1];
  ns.previous = ns.versions[ns.versions.length - 2];
  ns.links = {"orig": null, "copy": null};
  ns.text = {"orig": null, "copy": null};
  ns.mergely = {"links": null, "text": null};

  ns.buildUrl = function(version, typ){
    return ["monitor", ns.channel, ns.name, version+"."+typ].join("/");
  };

  ns.nameVersion = function(version, clean){
    if (clean)
      return new Date(version.replace(/^(..)(..)(..)-(..)(..)$/, "20$1-$2-$3 $4:$5")).toUTCString().replace(/:00 GMT/, "");
    return version.replace(/^(..)(..)(..)-(..)(..)$/, "$3/$2/$1 $4:$5");
  };

  ns.addDiffer = function(typ){
    ns.mergely[typ] = $("#mergely-" + typ);
    ns.mergely[typ].width($("#mergely-" + typ).width() + 1);
    ns.mergely[typ].mergely({
      width: 'auto',
      height: 'auto',
      cmsettings: {
        readOnly: true,
        mode: 'text/plain',
        lineNumbers: true,
        lineWrapping: true
      },
      ignorews: true,
      viewport: true,
      bgcolor: "#ddeeff",
      fgcolor: {
        a: "lightgreen",
        c: "lightblue",
        d: "lightpink"
      }
    });
  };

  ns.updateDiffer = function(typ, curwin, version){
    ns[typ][curwin] = ns[typ][version];
    ns.mergely[typ].mergely(
      (curwin === "copy" ? 'l' : 'r') + 'hs',
      ns[typ][version]
    );
    if (ns[typ]["orig"] && ns[typ]["copy"]) {
      ns.mergely[typ].mergely('scrollToDiff', 'next');
    }
  };

  ns.loadVersion = function(version, curwin){
    var url = ns.buildUrl(version, "html"),
      name = ns.nameVersion(version, true);
    curwin = curwin || ns.currentwin;
    $(".select" + curwin).removeClass('select' + curwin);
    $("." + version).addClass('select' + curwin);
    $("." + curwin + " .name").text(name)
    $("." + curwin + " a").attr("href", url);
    $("." + curwin + " iframe").attr("src", url);
    $("#screen" + curwin).attr("src", ns.buildUrl(version, "png"));
    ["links", "text"].forEach(function(typ){
      ns.mergely[typ].mergely('scrollTo', 'l', 0);
      ns.mergely[typ].mergely('scrollTo', 'r', 0);
      if (ns[typ][version]) {
        ns.updateDiffer(typ, curwin, version);
      } else $.ajax({
        url: ns.buildUrl(version, typ.replace('e', '')),
        dataType: "text",
        success: function(result){
          ns[typ][version] = result;
          ns.updateDiffer(typ, curwin, version);
        }
      });
    });
  };

  ns.loadReal = function(){
    var url = ns.url || "http://regardscitoyens.org";
    $(".selectorig").removeClass('selectorig');
    $(".real").addClass('selectorig');
    $(".orig a").text("live web " + url)
                .attr("href", url);
    $(".orig .content").empty();
    $(".orig iframe").attr("src", url);
  };

  ns.toggleCurrentWindow = function(){
    ns.currentwin = (ns.currentwin === "orig" ? "copy" : "orig");
  };

  ns.toggleExpandButton = function(sel, reduce){
    $("#" + sel + " .expand").attr("title", reduce ? "Reduce" : "Expand");
    $("#" + sel + " .expand .glyphicon")
      .removeClass("glyphicon-resize-" + (reduce ? "full" : "small"))
      .addClass("glyphicon-resize-" + (reduce ? "small" : "full"));
  };

  ns.toggleExpandSelecter = function(){
    ns.selectedExpanded = !ns.selectedExpanded;
    ns.toggleExpandButton("selecter", ns.selectedExpanded);
    if (ns.selectedExpanded) {
      $("#diff").hide();
      $("#selecter").animate({height: ns.selecterMaxHeight}, ns.transitions);
    } else {
      setTimeout(function(){
        $("#diff").show();
      }, ns.transitions);
      $("#selecter").animate({height: ns.selecterHeight - 2}, ns.transitions);
    }
  };

  ns.expandDiff = function(typ){
    if (typ === "visual") {
      $("#fullshots, #iframes .orig, #iframes .copy").animate({height: 3 * ns.pieceHeight - 2}, ns.transitions);
      $("iframe").animate({height: 3 * ns.pieceHeight - 4}, ns.transitions);
    } else {
      var gap = 3 * ns.pieceHeight - (typ === "text" ? 2 : 5);
      $("#diff" + typ).animate({height: gap}, ns.transitions);
      $("#diff" + typ + " .differ").height(gap);
      $(".differ").width($("#selecter").width() + 6);
      ns.mergely[typ].mergely('resize');
    }
  };

  ns.reduceDiff = function(typ){
    if (typ === "visual") {
      $("#iframes .orig, #iframes .copy, iframe").animate({height: 0}, ns.transitions);
      $("#fullshots").animate({height: 0}, ns.transitions);
    } else {
      $("#diff" + typ).animate({height: 0}, ns.transitions);
      $("#diff" + typ + " .differ").height(0);
    }
  };

  ns.toggleExpandDiff = function(typ){
    if (ns.diffExpanded === typ) {
      ns.toggleExpandButton(typ);
      ns.resetDiffHeights(true);
      ns.diffExpanded = null;
    } else {
      ns.toggleExpandButton(ns.diffExpanded);
      ns.toggleExpandButton(typ, true);
      ns.expandDiff(typ);
      ["links", "text", "visual"].filter(function(a){
        return a !== typ;
      }).forEach(ns.reduceDiff);
      ns.diffExpanded = typ;
    }
  };

  ns.toggleVisual = function(){
    ns.selectedVisual = $("input[name=visual]:checked").val();
    if (ns.selectedVisual === "screen") {
      $("#fullshots").show();
      $("#iframes .orig, #iframes .copy").hide();
    } else {
      $("#fullshots").hide();
      $("#iframes .orig, #iframes .copy").show();
    }
  };

  ns.resetDiffHeights = function(animate){
    $("#difflinks, #difftext").animate({'height': ns.pieceHeight}, (animate ? ns.transitions : 0));
    $("#fullshots, #iframes .orig, #iframes .copy").animate({'height': ns.pieceHeight - 1}, (animate ? ns.transitions : 0));
    $("iframe").animate({'height': ns.pieceHeight - 2}, (animate ? ns.transitions : 0));
    $(".differ").height(ns.pieceHeight);
    if (animate) {
      ["links", "text"].forEach(function(typ){
        ns.mergely[typ].mergely('resize');
      });
    }
  };

  ns.setDimensions = function(){
    var winW = $("#selecter").width(),
      winH = $(window).innerHeight(),
      imgW = Math.max(200, Math.min(350, parseInt(winW/ns.versions.length)));
    $("#selecter").height(ns.selecterHeight - 2);
    $("#selecter_large, #screenshots").width((ns.versions.length) * (imgW + 2) + 1);
    $("#versions p").width(imgW);
    $("#screenshots img").width(imgW - 8);
    ns.diffHeight = winH - ns.selecterHeight - 62;
    ns.selecterMaxHeight = winH - 50;
    ns.pieceHeight = (ns.diffHeight - 22 * 4) / 3;
    $(".differ").width(winW - 20);
    //$(".copy iframe, .orig iframe").width((winW - 3) / 2);
    $("#diff").height(ns.diffHeight);
    ns.resetDiffHeights();
  };

  $(document).ready(function(){
    var versions = $("#versions"),
      screens = $("#screenshots");
    ns.versions.forEach(function(version){
      var textVersion = ns.nameVersion(version),
        p = document.createElement('p'),
        i = document.createElement('img'),
        onclic = function(){
          ns.loadVersion(version);
        };
      p.className = version;
      p.textContent = textVersion;
      i.className = version;
      i.src = ns.buildUrl(version, "png").replace(/.png$/, "-small.png");
      i.title = textVersion;
      i.alt = textVersion;
      versions.append(p);
      screens.append(i);
      $(p).click(onclic);
      $(i).click(onclic);
    });
    /*var p = document.createElement('p');
    p.id = "real";
    p.textContent = "live web";
    $(p).click(ns.loadReal);
    versions.append(p);*/
    ns.setDimensions();
    $("#selecter").scrollLeft($("#selecter_large").width());
    ns.addDiffer("links");
    ns.addDiffer("text");
    ns.loadVersion(ns.previous, "copy");
    ns.loadVersion(ns.last, "orig");
    //ns.loadReal();
    $("input[type=radio][name=curwin]").change(ns.toggleCurrentWindow);
    $("#selecter .expand").click(ns.toggleExpandSelecter);
    ["links", "text", "visual"].forEach(function(typ){
      $("#" + typ + " .expand").click(function(){
        ns.toggleExpandDiff(typ)
      });
    });
    $("input[type=radio][name=visual]").change(ns.toggleVisual);
    $(window).resize(ns.setDimensions);
  });

})(window.gazouilleur = window.gazouilleur || {});
<commit_msg>fix displayed dates<commit_after>/* TODO:
- sources/links
- slider/calendar picker
*/
(function(ns){
  // config
  ns.transitions = 600;
  ns.selecterHeight = 200;
  ns.selectedExpanded = false;
  ns.selectedVisual = "screen";
  ns.diffExpanded = null;
  ns.currentwin = "copy";

  // internal
  ns.last = ns.versions[ns.versions.length - 1];
  ns.previous = ns.versions[ns.versions.length - 2];
  ns.links = {"orig": null, "copy": null};
  ns.text = {"orig": null, "copy": null};
  ns.mergely = {"links": null, "text": null};

  ns.buildUrl = function(version, typ){
    return ["monitor", ns.channel, ns.name, version+"."+typ].join("/");
  };

  ns.nameVersion = function(version, clean){
    var dat = new Date(version.replace(/^(..)(..)(..)-(..)(..)$/, "20$1-$2-$3 $4:$5"));
    if (clean) {
      dat.setTime(dat.getTime() - dat.getTimezoneOffset()*60*1000);
      return dat.toGMTString().replace(/:00 GMT/, "");
    }
    return dat.toLocaleString().replace(/:00$/, "");
  };

  ns.addDiffer = function(typ){
    ns.mergely[typ] = $("#mergely-" + typ);
    ns.mergely[typ].width($("#mergely-" + typ).width() + 1);
    ns.mergely[typ].mergely({
      width: 'auto',
      height: 'auto',
      cmsettings: {
        readOnly: true,
        mode: 'text/plain',
        lineNumbers: true,
        lineWrapping: true
      },
      ignorews: true,
      viewport: true,
      bgcolor: "#ddeeff",
      fgcolor: {
        a: "lightgreen",
        c: "lightblue",
        d: "lightpink"
      }
    });
  };

  ns.updateDiffer = function(typ, curwin, version){
    ns[typ][curwin] = ns[typ][version];
    ns.mergely[typ].mergely(
      (curwin === "copy" ? 'l' : 'r') + 'hs',
      ns[typ][version]
    );
    if (ns[typ]["orig"] && ns[typ]["copy"]) {
      ns.mergely[typ].mergely('scrollToDiff', 'next');
    }
  };

  ns.loadVersion = function(version, curwin){
    var url = ns.buildUrl(version, "html"),
      name = ns.nameVersion(version, true);
    curwin = curwin || ns.currentwin;
    $(".select" + curwin).removeClass('select' + curwin);
    $("." + version).addClass('select' + curwin);
    $("." + curwin + " .name").text(name)
    $("." + curwin + " a").attr("href", url);
    $("." + curwin + " iframe").attr("src", url);
    $("#screen" + curwin).attr("src", ns.buildUrl(version, "png"));
    ["links", "text"].forEach(function(typ){
      ns.mergely[typ].mergely('scrollTo', 'l', 0);
      ns.mergely[typ].mergely('scrollTo', 'r', 0);
      if (ns[typ][version]) {
        ns.updateDiffer(typ, curwin, version);
      } else $.ajax({
        url: ns.buildUrl(version, typ.replace('e', '')),
        dataType: "text",
        success: function(result){
          ns[typ][version] = result;
          ns.updateDiffer(typ, curwin, version);
        }
      });
    });
  };

  ns.loadReal = function(){
    var url = ns.url || "http://regardscitoyens.org";
    $(".selectorig").removeClass('selectorig');
    $(".real").addClass('selectorig');
    $(".orig a").text("live web " + url)
                .attr("href", url);
    $(".orig .content").empty();
    $(".orig iframe").attr("src", url);
  };

  ns.toggleCurrentWindow = function(){
    ns.currentwin = (ns.currentwin === "orig" ? "copy" : "orig");
  };

  ns.toggleExpandButton = function(sel, reduce){
    $("#" + sel + " .expand").attr("title", reduce ? "Reduce" : "Expand");
    $("#" + sel + " .expand .glyphicon")
      .removeClass("glyphicon-resize-" + (reduce ? "full" : "small"))
      .addClass("glyphicon-resize-" + (reduce ? "small" : "full"));
  };

  ns.toggleExpandSelecter = function(){
    ns.selectedExpanded = !ns.selectedExpanded;
    ns.toggleExpandButton("selecter", ns.selectedExpanded);
    if (ns.selectedExpanded) {
      $("#diff").hide();
      $("#selecter").animate({height: ns.selecterMaxHeight}, ns.transitions);
    } else {
      setTimeout(function(){
        $("#diff").show();
      }, ns.transitions);
      $("#selecter").animate({height: ns.selecterHeight - 2}, ns.transitions);
    }
  };

  ns.expandDiff = function(typ){
    if (typ === "visual") {
      $("#fullshots, #iframes .orig, #iframes .copy").animate({height: 3 * ns.pieceHeight - 2}, ns.transitions);
      $("iframe").animate({height: 3 * ns.pieceHeight - 4}, ns.transitions);
    } else {
      var gap = 3 * ns.pieceHeight - (typ === "text" ? 2 : 5);
      $("#diff" + typ).animate({height: gap}, ns.transitions);
      $("#diff" + typ + " .differ").height(gap);
      $(".differ").width($("#selecter").width() + 6);
      ns.mergely[typ].mergely('resize');
    }
  };

  ns.reduceDiff = function(typ){
    if (typ === "visual") {
      $("#iframes .orig, #iframes .copy, iframe").animate({height: 0}, ns.transitions);
      $("#fullshots").animate({height: 0}, ns.transitions);
    } else {
      $("#diff" + typ).animate({height: 0}, ns.transitions);
      $("#diff" + typ + " .differ").height(0);
    }
  };

  ns.toggleExpandDiff = function(typ){
    if (ns.diffExpanded === typ) {
      ns.toggleExpandButton(typ);
      ns.resetDiffHeights(true);
      ns.diffExpanded = null;
    } else {
      ns.toggleExpandButton(ns.diffExpanded);
      ns.toggleExpandButton(typ, true);
      ns.expandDiff(typ);
      ["links", "text", "visual"].filter(function(a){
        return a !== typ;
      }).forEach(ns.reduceDiff);
      ns.diffExpanded = typ;
    }
  };

  ns.toggleVisual = function(){
    ns.selectedVisual = $("input[name=visual]:checked").val();
    if (ns.selectedVisual === "screen") {
      $("#fullshots").show();
      $("#iframes .orig, #iframes .copy").hide();
    } else {
      $("#fullshots").hide();
      $("#iframes .orig, #iframes .copy").show();
    }
  };

  ns.resetDiffHeights = function(animate){
    $("#difflinks, #difftext").animate({'height': ns.pieceHeight}, (animate ? ns.transitions : 0));
    $("#fullshots, #iframes .orig, #iframes .copy").animate({'height': ns.pieceHeight - 1}, (animate ? ns.transitions : 0));
    $("iframe").animate({'height': ns.pieceHeight - 2}, (animate ? ns.transitions : 0));
    $(".differ").height(ns.pieceHeight);
    if (animate) {
      ["links", "text"].forEach(function(typ){
        ns.mergely[typ].mergely('resize');
      });
    }
  };

  ns.setDimensions = function(){
    var winW = $("#selecter").width(),
      winH = $(window).innerHeight(),
      imgW = Math.max(200, Math.min(350, parseInt(winW/ns.versions.length)));
    $("#selecter").height(ns.selecterHeight - 2);
    $("#selecter_large, #screenshots").width((ns.versions.length) * (imgW + 2) + 1);
    $("#versions p").width(imgW);
    $("#screenshots img").width(imgW - 8);
    ns.diffHeight = winH - ns.selecterHeight - 62;
    ns.selecterMaxHeight = winH - 50;
    ns.pieceHeight = (ns.diffHeight - 22 * 4) / 3;
    $(".differ").width(winW - 20);
    //$(".copy iframe, .orig iframe").width((winW - 3) / 2);
    $("#diff").height(ns.diffHeight);
    ns.resetDiffHeights();
  };

  $(document).ready(function(){
    var versions = $("#versions"),
      screens = $("#screenshots");
    ns.versions.forEach(function(version){
      var textVersion = ns.nameVersion(version),
        p = document.createElement('p'),
        i = document.createElement('img'),
        onclic = function(){
          ns.loadVersion(version);
        };
      p.className = version;
      p.textContent = textVersion;
      i.className = version;
      i.src = ns.buildUrl(version, "png").replace(/.png$/, "-small.png");
      i.title = textVersion;
      i.alt = textVersion;
      versions.append(p);
      screens.append(i);
      $(p).click(onclic);
      $(i).click(onclic);
    });
    /*var p = document.createElement('p');
    p.id = "real";
    p.textContent = "live web";
    $(p).click(ns.loadReal);
    versions.append(p);*/
    ns.setDimensions();
    $("#selecter").scrollLeft($("#selecter_large").width());
    ns.addDiffer("links");
    ns.addDiffer("text");
    ns.loadVersion(ns.previous, "copy");
    ns.loadVersion(ns.last, "orig");
    //ns.loadReal();
    $("input[type=radio][name=curwin]").change(ns.toggleCurrentWindow);
    $("#selecter .expand").click(ns.toggleExpandSelecter);
    ["links", "text", "visual"].forEach(function(typ){
      $("#" + typ + " .expand").click(function(){
        ns.toggleExpandDiff(typ)
      });
    });
    $("input[type=radio][name=visual]").change(ns.toggleVisual);
    $(window).resize(ns.setDimensions);
  });

})(window.gazouilleur = window.gazouilleur || {});
<|endoftext|>


<commit_before>var w = 600;
var h = 400;

void setup() {
  size(w, h);
}

void draw() {
  //fill(255,0,0);
  //ellipse(200,200,10,10);
  //rect(200,205,10,10);
  //fill(255,255,255);
  //text('e',200,210);

  // face
  fill(player.skin[0],player.skin[1],player.skin[2]);
  ellipse(player.x,player.y-10,12+player.face*4,20);

  // arms
  rect(player.x-14,player.y+4,4.6);
  rect(player.x+10,player.y+4,4.6);

  // tshirt
  fill(player.tColor[0],player.tColor[1],player.tColor[2]);
  rect(player.x-10,player.y,20,20);
  rect(player.x-14,player.y,4.4);
  rect(player.x+10,player.y,4.4);

  // tshirt logo
  fill(255,255,255);
  text(player.tshirt,player.x-5,player.y+15);
  // eye whites
  ellipse(player.x-3-player.face,player.y-15,3,3);
  ellipse(player.x+3+player.face,player.y-15,3,3);

  fill(0,0,0);
  ellipse(player.x-3-player.face,player.y-15,1,1);
  ellipse(player.x+3+player.face,player.y-15,1,1);
}
<commit_msg>Update drawgame.js<commit_after>var w = 600;
var h = 400;

void setup() {
  size(w, h);
}

void draw() {
  //fill(255,0,0);
  //ellipse(200,200,10,10);
  //rect(200,205,10,10);
  //fill(255,255,255);
  //text('e',200,210);

  // face
  fill(player.skin[0],player.skin[1],player.skin[2]);
  ellipse(player.x,player.y-10,12+player.face*4,20);

  // arms
  rect(player.x-14,player.y+4,4,6);
  rect(player.x+10,player.y+4,4,6);

  // tshirt
  fill(player.tColor[0],player.tColor[1],player.tColor[2]);
  rect(player.x-10,player.y,20,20);
  rect(player.x-14,player.y,4,4);
  rect(player.x+10,player.y,4,4);

  // tshirt logo
  fill(255,255,255);
  text(player.tshirt,player.x-5,player.y+15);

  // eye whites
  ellipse(player.x-4-player.face,player.y-15,4,4);
  ellipse(player.x+4+player.face,player.y-15,4,4);

  fill(0,0,0);
  ellipse(player.x-4-player.face,player.y-15,1,1);
  ellipse(player.x+4+player.face,player.y-15,1,1);
}
<|endoftext|>


<commit_before>/*
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Regenerates the translations base file by walking the source tree and
 * parsing each file with flow-parser. Emits a JSON file with the
 * translatable strings mapped to themselves in the order they appeared
 * in the files and grouped by the file they appeared in.
 *
 * Usage: node scripts/gen-i18n.js
 */
const fs = require('fs');
const path = require('path');

const walk = require('walk');

const flowParser = require('flow-parser');
const estreeWalker = require('estree-walker');

const TRANSLATIONS_FUNCS = ['_t', '_td', '_tJsx'];

const INPUT_TRANSLATIONS_FILE = 'src/i18n/strings/en_EN.json';

const FLOW_PARSER_OPTS = {
  esproposal_class_instance_fields: true,
  esproposal_class_static_fields: true,
  esproposal_decorators: true,
  esproposal_export_star_as: true,
  types: true,
};

function getObjectValue(obj, key) {
    for (const prop of obj.properties) {
        if (prop.key.type == 'Identifier' && prop.key.name == key) {
            return prop.value;
        }
    }
    return null;
}

function getTKey(arg) {
    if (arg.type == 'Literal') {
        return arg.value;
    } else if (arg.type == 'BinaryExpression' && arg.operator == '+') {
        return getTKey(arg.left) + getTKey(arg.right);
    } else if (arg.type == 'TemplateLiteral') {
        return arg.quasis.map((q) => {
            return q.value.raw;
        }).join('');
    }
    return null;
}

function getTranslations(file) {
    const tree = flowParser.parse(fs.readFileSync(file, { encoding: 'utf8' }), FLOW_PARSER_OPTS);

    const trs = new Set();

    estreeWalker.walk(tree, {
        enter: function(node, parent) {
            if (
                node.type == 'CallExpression' &&
                TRANSLATIONS_FUNCS.includes(node.callee.name)
            ) {
                const tKey = getTKey(node.arguments[0]);
                // This happens whenever we call _t with non-literals (ie. whenever we've
                // had to use a _td to compensate) so is expected.
                if (tKey === null) return;

                let isPlural = false;
                if (node.arguments.length > 1 && node.arguments[1].type == 'ObjectExpression') {
                    const countVal = getObjectValue(node.arguments[1], 'count');
                    if (countVal) {
                        isPlural = true;
                    }
                }

                if (isPlural) {
                    trs.add(tKey + "|other");
                    const plurals = enPlurals[tKey];
                    if (plurals) {
                        for (const pluralType of Object.keys(plurals)) {
                            trs.add(tKey + "|" + pluralType);
                        }
                    }
                } else {
                    trs.add(tKey);
                }
            }
        }
    });

    return trs;
}

// gather en_EN plural strings from the input translations file:
// the en_EN strings are all in the source with the exception of
// pluralised strings, which we need to pull in from elsewhere.
const inputTranslationsRaw = JSON.parse(fs.readFileSync(INPUT_TRANSLATIONS_FILE, { encoding: 'utf8' }));
const enPlurals = {};

for (const key of Object.keys(inputTranslationsRaw)) {
    const parts = key.split("|");
    if (parts.length > 1) {
        const plurals = enPlurals[parts[0]] || {};
        plurals[parts[1]] = inputTranslationsRaw[key];
        enPlurals[parts[0]] = plurals;
    }
}

const translatables = new Set();

walk.walkSync("src", {
    listeners: {
        file: function(root, fileStats, next) {
            if (!fileStats.name.endsWith('.js')) return;

            const fullPath = path.join(root, fileStats.name);
            const trs = getTranslations(fullPath);
            console.log(`${fullPath} (${trs.size} strings)`);
            for (const tr of trs.values()) {
                translatables.add(tr);
            }
        },
    }
});

const trObj = {};
for (const tr of translatables) {
    trObj[tr] = tr;
    if (tr.includes("|")) {
        trObj[tr] = inputTranslationsRaw[tr];
    }
}

fs.writeFileSync(
    "src/i18n/strings/en_EN.json",
    JSON.stringify(trObj, translatables.values(), 4) + "\n"
);

<commit_msg>'base file' is a bit overloaded by weblate<commit_after>/*
Copyright 2017 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Regenerates the translations en_EN file by walking the source tree and
 * parsing each file with flow-parser. Emits a JSON file with the
 * translatable strings mapped to themselves in the order they appeared
 * in the files and grouped by the file they appeared in.
 *
 * Usage: node scripts/gen-i18n.js
 */
const fs = require('fs');
const path = require('path');

const walk = require('walk');

const flowParser = require('flow-parser');
const estreeWalker = require('estree-walker');

const TRANSLATIONS_FUNCS = ['_t', '_td', '_tJsx'];

const INPUT_TRANSLATIONS_FILE = 'src/i18n/strings/en_EN.json';

const FLOW_PARSER_OPTS = {
  esproposal_class_instance_fields: true,
  esproposal_class_static_fields: true,
  esproposal_decorators: true,
  esproposal_export_star_as: true,
  types: true,
};

function getObjectValue(obj, key) {
    for (const prop of obj.properties) {
        if (prop.key.type == 'Identifier' && prop.key.name == key) {
            return prop.value;
        }
    }
    return null;
}

function getTKey(arg) {
    if (arg.type == 'Literal') {
        return arg.value;
    } else if (arg.type == 'BinaryExpression' && arg.operator == '+') {
        return getTKey(arg.left) + getTKey(arg.right);
    } else if (arg.type == 'TemplateLiteral') {
        return arg.quasis.map((q) => {
            return q.value.raw;
        }).join('');
    }
    return null;
}

function getTranslations(file) {
    const tree = flowParser.parse(fs.readFileSync(file, { encoding: 'utf8' }), FLOW_PARSER_OPTS);

    const trs = new Set();

    estreeWalker.walk(tree, {
        enter: function(node, parent) {
            if (
                node.type == 'CallExpression' &&
                TRANSLATIONS_FUNCS.includes(node.callee.name)
            ) {
                const tKey = getTKey(node.arguments[0]);
                // This happens whenever we call _t with non-literals (ie. whenever we've
                // had to use a _td to compensate) so is expected.
                if (tKey === null) return;

                let isPlural = false;
                if (node.arguments.length > 1 && node.arguments[1].type == 'ObjectExpression') {
                    const countVal = getObjectValue(node.arguments[1], 'count');
                    if (countVal) {
                        isPlural = true;
                    }
                }

                if (isPlural) {
                    trs.add(tKey + "|other");
                    const plurals = enPlurals[tKey];
                    if (plurals) {
                        for (const pluralType of Object.keys(plurals)) {
                            trs.add(tKey + "|" + pluralType);
                        }
                    }
                } else {
                    trs.add(tKey);
                }
            }
        }
    });

    return trs;
}

// gather en_EN plural strings from the input translations file:
// the en_EN strings are all in the source with the exception of
// pluralised strings, which we need to pull in from elsewhere.
const inputTranslationsRaw = JSON.parse(fs.readFileSync(INPUT_TRANSLATIONS_FILE, { encoding: 'utf8' }));
const enPlurals = {};

for (const key of Object.keys(inputTranslationsRaw)) {
    const parts = key.split("|");
    if (parts.length > 1) {
        const plurals = enPlurals[parts[0]] || {};
        plurals[parts[1]] = inputTranslationsRaw[key];
        enPlurals[parts[0]] = plurals;
    }
}

const translatables = new Set();

walk.walkSync("src", {
    listeners: {
        file: function(root, fileStats, next) {
            if (!fileStats.name.endsWith('.js')) return;

            const fullPath = path.join(root, fileStats.name);
            const trs = getTranslations(fullPath);
            console.log(`${fullPath} (${trs.size} strings)`);
            for (const tr of trs.values()) {
                translatables.add(tr);
            }
        },
    }
});

const trObj = {};
for (const tr of translatables) {
    trObj[tr] = tr;
    if (tr.includes("|")) {
        trObj[tr] = inputTranslationsRaw[tr];
    }
}

fs.writeFileSync(
    "src/i18n/strings/en_EN.json",
    JSON.stringify(trObj, translatables.values(), 4) + "\n"
);

<|endoftext|>


<commit_before>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService',
  function ($scope, display, party, page, constants) {

    var getUsers = function(volumes){

      var users = {};

      users.sponsors = [];
      users.labGroupMembers = [];
      users.nonGroupAffiliates = [];
      users.otherCollaborators = [];

      _(volumes).pluck('access').flatten().each(function(v){
        if(v.children > 0 ){
          users.sponsors.push(v);
        } else if(v.parents && v.parents.length > 0 && v.party.members && v.party.members.length > 0) {
          users.labGroupMembers.push(v);
        } else if(v.parents && v.parents.length > 0){
          users.nonGroupAffiliates.push(v);
        } else {
          users.otherCollaborators.push(v);
        }

      }).value();

      console.log(users);
      return users;
    };

    // This is a quick helper function to make sure that the isSelected
    // class is set to empty and to avoid repeating code.
    var unSetSelected = function(v){
      v.isSelected = '';
      return v;
    };

    var unselectAll = function(){
      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);
      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);
      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);
      $scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected);
      $scope.users.nonGroupAffiliates = _.map($scope.users.nonGroupAffiliates, unSetSelected);
      $scope.users.labGroupMembers = _.map($scope.users.labGroupMembers, unSetSelected);
      $scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected);
    };

    $scope.clickVolume = function(volume) {
      unselectAll();
      for(var i = 0; i < volume.access.length; i += 1 ){
        var j;
        for (j = 0; j < $scope.users.sponsors.length; j += 1){
          if($scope.users.sponsors[j].id === volume.access[i].party.id){
            $scope.users.sponsors[j].isSelected = 'userSelected';
            console.log($scope.users.sponsors[j]);
          }
        }
        for (j = 0; j < $scope.users.labGroupMembers.length; j += 1){
          if($scope.users.labGroupMembers[j].id === volume.access[i].party.id){
            $scope.users.labGroupMembers[j].isSelected = 'userSelected';
          }
        }
        for (j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){
          if($scope.users.nonGroupAffiliates[j].id === volume.access[i].party.id){
            $scope.users.nonGroupAffiliates[j].isSelected = 'userSelected';
          }
        }
        for (j = 0; j < $scope.users.otherCollaborators.length; j += 1){
          if($scope.users.otherCollaborators[j].id === volume.access[i].party.id){
            $scope.users.otherCollaborators[j].isSelected = 'userSelected';
          }
        }
      }
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user){
      unselectAll();
      var iterateVolume = function(_item, i, volumeArray){
        for(var j = 0; j < volumeArray[i].v.length; j += 1){
          for (var k = 0; k < volumeArray[i].v[j].access.length; k += 1){
            if(volumeArray[i].v[j].access[k] == user){
              volumeArray[i].v[j].access[k].isSelected = 'volumeSelected';
            }
          }
        }
      };

      _.each($scope.volumes.individual, iterateVolume);
      _.each($scope.volumes.collaborator, iterateVolume);
      _.each($scope.volumes.inherited, iterateVolume);

    };

    var getParents = function(parents) {
      var tempParents = [];
      _.each(parents, function(p){
        if(p.member){
          var v = [];
          var tempThing = {
            p: p,
            v: v
          };
          tempParents.push(tempThing);
        }
      });
      return tempParents;
    };

    var getVolumes = function(volumes) {
      var tempVolumes = {};
      tempVolumes.individual = [];
      tempVolumes.collaborator = [];

      tempVolumes.inherited = getParents(party.parents);

      _.each(volumes, function(v){
        if(v.isIndividual){
          tempVolumes.individual.push({v: [v]});
        } else if(tempVolumes.isCollaborator){
          tempVolumes.individual.push({v: [v]});
        } else{
          for (var i=0;i<v.access.length;i++){
            for (var j=0;j<tempVolumes.inherited.length;j++){
              if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id){
                tempVolumes.inherited[j].v.push(v);
                break;
              }
            }
          }
        }
      });
      return tempVolumes;
    };

    $scope.party = party;
    $scope.volumes = getVolumes(party.volumes);
    $scope.users = getUsers(party.volumes);
    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;

    console.log($scope.volumes.inherited);
  }
]);
<commit_msg>Compare on ID instead of raw object.<commit_after>'use strict';

app.controller('party/profile', [
  '$scope', 'displayService', 'party', 'pageService','constantService',
  function ($scope, display, party, page, constants) {

    var getUsers = function(volumes){

      var users = {};

      users.sponsors = [];
      users.labGroupMembers = [];
      users.nonGroupAffiliates = [];
      users.otherCollaborators = [];

      _(volumes).pluck('access').flatten().each(function(v){
        console.log("V: ", v);
        if(v.children > 0 ){
          users.sponsors.push(v);
        } else if(v.parents && v.parents.length > 0 && v.party.members && v.party.members.length > 0) {
          users.labGroupMembers.push(v);
        } else if(v.parents && v.parents.length > 0){
          users.nonGroupAffiliates.push(v);
        } else {
          users.otherCollaborators.push(v);
        }

      }).value();

      console.log(users);
      return users;
    };

    // This is a quick helper function to make sure that the isSelected
    // class is set to empty and to avoid repeating code.
    var unSetSelected = function(v){
      v.isSelected = '';
      return v;
    };

    var unselectAll = function(){
      $scope.volumes.individual = _.map($scope.volumes.individual, unSetSelected);
      $scope.volumes.collaborator = _.map($scope.volumes.collaborator, unSetSelected);
      $scope.volumes.inherited = _.map($scope.volumes.inherited, unSetSelected);
      $scope.users.sponsors = _.map($scope.users.sponsors, unSetSelected);
      $scope.users.nonGroupAffiliates = _.map($scope.users.nonGroupAffiliates, unSetSelected);
      $scope.users.labGroupMembers = _.map($scope.users.labGroupMembers, unSetSelected);
      $scope.users.otherCollaborators = _.map($scope.users.otherCollaborators, unSetSelected);
    };

    $scope.clickVolume = function(volume) {
      unselectAll();
      for(var i = 0; i < volume.access.length; i += 1 ){
        var j;
        for (j = 0; j < $scope.users.sponsors.length; j += 1){
          if($scope.users.sponsors[j].id === volume.access[i].party.id){
            $scope.users.sponsors[j].isSelected = 'userSelected';
            console.log($scope.users.sponsors[j]);
          }
        }
        for (j = 0; j < $scope.users.labGroupMembers.length; j += 1){
          if($scope.users.labGroupMembers[j].id === volume.access[i].party.id){
            $scope.users.labGroupMembers[j].isSelected = 'userSelected';
          }
        }
        for (j = 0; j < $scope.users.nonGroupAffiliates.length; j += 1){
          if($scope.users.nonGroupAffiliates[j].id === volume.access[i].party.id){
            $scope.users.nonGroupAffiliates[j].isSelected = 'userSelected';
          }
        }
        for (j = 0; j < $scope.users.otherCollaborators.length; j += 1){
          if($scope.users.otherCollaborators[j].id === volume.access[i].party.id){
            $scope.users.otherCollaborators[j].isSelected = 'userSelected';
          }
        }
      }
    };

    // This should take in a user, then select volumes on each thing.
    $scope.clickUser = function(user){
      unselectAll();
      var iterateVolume = function(_item, i, volumeArray){
        for(var j = 0; j < volumeArray[i].v.length; j += 1){
          for (var k = 0; k < volumeArray[i].v[j].access.length; k += 1){
            if(volumeArray[i].v[j].access[k].party.id == user.id){
              volumeArray[i].v[j].access[k].isSelected = 'volumeSelected';
            }
          }
        }
      };

      _.each($scope.volumes.individual, iterateVolume);
      _.each($scope.volumes.collaborator, iterateVolume);
      _.each($scope.volumes.inherited, iterateVolume);

    };

    var getParents = function(parents) {
      var tempParents = [];
      _.each(parents, function(p){
        if(p.member){
          var v = [];
          var tempThing = {
            p: p,
            v: v
          };
          tempParents.push(tempThing);
        }
      });
      return tempParents;
    };

    var getVolumes = function(volumes) {
      var tempVolumes = {};
      tempVolumes.individual = [];
      tempVolumes.collaborator = [];

      tempVolumes.inherited = getParents(party.parents);

      _.each(volumes, function(v){
        if(v.isIndividual){
          tempVolumes.individual.push({v: [v]});
        } else if(tempVolumes.isCollaborator){
          tempVolumes.individual.push({v: [v]});
        } else{
          for (var i=0;i<v.access.length;i++){
            for (var j=0;j<tempVolumes.inherited.length;j++){
              if (v.access[i].children && v.access[i].party.id === tempVolumes.inherited[j].p.party.id){
                tempVolumes.inherited[j].v.push(v);
                break;
              }
            }
          }
        }
      });
      return tempVolumes;
    };

    $scope.party = party;
    $scope.volumes = getVolumes(party.volumes);
    $scope.users = getUsers(party.volumes);
    $scope.page = page;
    $scope.profile = page.$location.path() === '/profile';
    display.title = party.name;

    console.log($scope.volumes.inherited);
  }
]);
<|endoftext|>


<commit_before>import { default as React, Component } from 'react';
import { GoogleMapLoader, GoogleMap, Marker } from "react-google-maps";
import canUseDOM from "can-use-dom";

const geolocation = (
    canUseDOM && navigator.geolocation ?
        navigator.geolocation :
        ({
            getCurrentPosition(success, failure) {
                failure(`Your browser doesn't support geolocation.`);
            },
        })
);

export default class GoogleMapAddBird extends React.Component {

    static mapStyle = [{"elementType":"geometry","stylers":[{"hue":"#ff4400"},{"saturation":-68},{"lightness":-4},
        {"gamma":0.72}]},
        {"featureType":"road","elementType":"labels.icon"},
        {"featureType":"landscape.man_made","elementType":"geometry",
        "stylers":[{"hue":"#0077ff"},{"gamma":3.1}]},{"featureType":"water",
        "stylers":[{"hue":"#00ccff"},{"gamma":0.44},{"saturation":-33}]},{"featureType":"poi.park",
        "stylers":[{"hue":"#44ff00"},{"saturation":-23}]},{"featureType":"water","elementType":"labels.text.fill",
        "stylers":[{"hue":"#007fff"},{"gamma":0.77},{"saturation":65},{"lightness":99}]},
        {"featureType":"water","elementType":"labels.text.stroke",
        "stylers":[{"gamma":0.11},{"weight":5.6},{"saturation":99},{"hue":"#0091ff"},{"lightness":-86}]},
        {"featureType":"transit.line","elementType":"geometry","stylers":[{"lightness":-48},{"hue":"#ff5e00"},
        {"gamma":1.2},{"saturation":-23}]},{"featureType":"transit","elementType":"labels.text.stroke",
        "stylers":[{"saturation":-64},{"hue":"#ff9100"},{"lightness":16},{"gamma":0.47},{"weight":2.7}]}];

    state = {
        center: {
            lat: 46.867453,
            lng: 2.329102,
        },
    };

    componentDidMount() {
        geolocation.getCurrentPosition((position) => {
            if (this.isUnmounted) {
                return;
            }
            this.setState({
                center: {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                },
            });
        });
    }

    markerCoords(event){
        this.setState({
            center: {
                lat: event.latLng.lat(),
                lng: event.latLng.lng(),
            },
        });
    }

    render() {
        let position = this.state.center;
        return (
            <GoogleMapLoader
                containerElement={

                }
                googleMapElement={
                    <GoogleMap
                        center={position}
                        defaultZoom={13}
                        ref='map'
                        defaultOptions={{ styles: GoogleMapAddBird.mapStyle}}>
                        <Marker draggable
                                ref={`position`}
                                position={new google.maps.LatLng(position.lat, position.lng)}
                                onDragend={this.markerCoords.bind(this)}
                        />
                        {this.props.form}
                        <input id="birds_longitude" name="birds[longitude]" type="hidden" value={position.lng}></input>
                        <input id="birds_latitude" name="birds[latitude]" type="hidden" value={position.lat}></input>

Placez le marker a l'endroit exact de l'observation :

                     </GoogleMap>
                }
            />
        );
    }
}<commit_msg>remove
 tag in GoogleAddBirdMap<commit_after>import { default as React, Component } from 'react';
import { GoogleMapLoader, GoogleMap, Marker } from "react-google-maps";
import canUseDOM from "can-use-dom";

const geolocation = (
    canUseDOM && navigator.geolocation ?
        navigator.geolocation :
        ({
            getCurrentPosition(success, failure) {
                failure(`Your browser doesn't support geolocation.`);
            },
        })
);

export default class GoogleMapAddBird extends React.Component {

    static mapStyle = [{"elementType":"geometry","stylers":[{"hue":"#ff4400"},{"saturation":-68},{"lightness":-4},
        {"gamma":0.72}]},
        {"featureType":"road","elementType":"labels.icon"},
        {"featureType":"landscape.man_made","elementType":"geometry",
        "stylers":[{"hue":"#0077ff"},{"gamma":3.1}]},{"featureType":"water",
        "stylers":[{"hue":"#00ccff"},{"gamma":0.44},{"saturation":-33}]},{"featureType":"poi.park",
        "stylers":[{"hue":"#44ff00"},{"saturation":-23}]},{"featureType":"water","elementType":"labels.text.fill",
        "stylers":[{"hue":"#007fff"},{"gamma":0.77},{"saturation":65},{"lightness":99}]},
        {"featureType":"water","elementType":"labels.text.stroke",
        "stylers":[{"gamma":0.11},{"weight":5.6},{"saturation":99},{"hue":"#0091ff"},{"lightness":-86}]},
        {"featureType":"transit.line","elementType":"geometry","stylers":[{"lightness":-48},{"hue":"#ff5e00"},
        {"gamma":1.2},{"saturation":-23}]},{"featureType":"transit","elementType":"labels.text.stroke",
        "stylers":[{"saturation":-64},{"hue":"#ff9100"},{"lightness":16},{"gamma":0.47},{"weight":2.7}]}];

    state = {
        center: {
            lat: 46.867453,
            lng: 2.329102,
        },
    };

    componentDidMount() {
        geolocation.getCurrentPosition((position) => {
            if (this.isUnmounted) {
                return;
            }
            this.setState({
                center: {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                },
            });
        });
    }

    markerCoords(event){
        this.setState({
            center: {
                lat: event.latLng.lat(),
                lng: event.latLng.lng(),
            },
        });
    }

    render() {
        let position = this.state.center;
        return (
            <GoogleMapLoader
                containerElement={

                }
                googleMapElement={
                    <GoogleMap
                        center={position}
                        defaultZoom={13}
                        ref='map'
                        defaultOptions={{ styles: GoogleMapAddBird.mapStyle}}>
                        <Marker draggable
                                ref={`position`}
                                position={new google.maps.LatLng(position.lat, position.lng)}
                                onDragend={this.markerCoords.bind(this)}
                        />
                        {this.props.form}
                        <input id="birds_longitude" name="birds[longitude]" type="hidden" value={position.lng}></input>
                        <input id="birds_latitude" name="birds[latitude]" type="hidden" value={position.lat}></input>

                     </GoogleMap>
                }
            />
        );
    }
}<|endoftext|>


<commit_before>/* Load paths for frameworks */

require.config({
	baseUrl: 'scripts',

	paths: {
		/* Using AMD forks for non AMD compliant libraries */
		'text':     'library/require.text',
		'jed':      'library/jed',
		'qrcode':   'library/qrcode',

		'jquery':   'library/jquery',
		'cookie':   'library/jquery.cookie',
		'jquidrag': 'library/jquery.ui.draggable',
		'panzoom':  'library/jquery.panzoom',

		/* Backbone */
		'underscore':          'library/underscore',
		'backbone':            'library/backbone',
		'underscore.string':   'library/underscore.string',

		/* Marionette */
		'backbone.babysitter': 'library/backbone.babysitter',
		'backbone.wreqr':      'library/backbone.wreqr',
		'marionette':          'library/backbone.marionette',

		/* Bootstrap */
		'bootstrap': 'library/bootstrap',

		/* App Config */
		'config': 'config',

		/* Templages */
		'templates': '../templates',

		/* Images */
		'images': '../images'
	},

	shim: {
	   'underscore.string': {
			deps: ['underscore'],
		},

        "jqueryui": {
            exports: "$",
            deps: ['jquery']
        },

        "jquerypan": {
            exports: "$",
            deps: ['jquery']
        },

		'bootstrap' : {
			deps: ['jquery']
		},

		'qrcode': {
			exports: "QRCode"
		}
	},

	/* Visual Debugging */
	config: {
		text: {
			xrayTemplateDebugging: (typeof document !== 'undefined') ? document.URL.match(/xray-goggles/) : false
		},

		moduleLog: (typeof document !== 'undefined') ? document.URL.match(/module-log/) : false
	}
});
<commit_msg>indentation includes<commit_after>/* Load paths for frameworks */

require.config(
{
  baseUrl:'scripts',

  paths:
  {
    /* Using AMD forks for non AMD compliant libraries */
    'text':  'library/require.text',
    'jed':   'library/jed',
    'qrcode':'library/qrcode',

    'jquery':  'library/jquery',
    'cookie':  'library/jquery.cookie',
    'jquidrag':'library/jquery.ui.draggable',
    'panzoom': 'library/jquery.panzoom',

    /* Backbone */
    'underscore':       'library/underscore',
    'backbone':         'library/backbone',
    'underscore.string':'library/underscore.string',

    /* Marionette */
    'backbone.babysitter':'library/backbone.babysitter',
    'backbone.wreqr':     'library/backbone.wreqr',
    'marionette':         'library/backbone.marionette',

    /* Bootstrap */
    'bootstrap':'library/bootstrap',

    /* App Config */
    'config':'config',

    /* Templages */
    'templates':'../templates',

    /* Images */
    'images':'../images'
  },

  shim:
  {
    'underscore.string':
    {
      deps:['underscore'],
    },

    "jqueryui":
    {
      exports:"$",
      deps:['jquery']
    },

    "jquerypan":
    {
      exports:"$",
      deps:['jquery']
    },

    'bootstrap':
    {
      deps:['jquery']
    },

    'qrcode':
    {
      exports:"QRCode"
    }
  },

  /* Visual Debugging */
  config:
  {
    text:
    {
      xrayTemplateDebugging: (typeof document !== 'undefined') ? document.URL.match(/xray-goggles/) : false
    },

    moduleLog: (typeof document !== 'undefined') ? document.URL.match(/module-log/) : false
  }
});
<|endoftext|>


<commit_before>/**
 * Client side logic for playlists.
 *
 * - Show/hide playlists.
 * - Keep track of position in playlist.
 */

import i18n from './i18n.js';

let t;
i18n.on('initialized', () => {
  t = i18n.getFixedT();

  /**
   * If in lesson of playlist
   */
  var playlist = localStorage.getItem('playlist');
  if (playlist) {
    if (indexOf(playlist.lessons, window.location.href) !== undefined) {
      // current lesson is this very page -> add navigation
      addNavigation(playlist);
    } else {
      // remove playlist from localStorage, we are no longer in a playlist
      localStorage.removeItem('playlist');
    }
  }
})

/**
 * show/hide playlist
 */
$('.playlist > li').click(function(){
  $('.' + this.id).slideToggle();
});

/**
 * save playlist to localStorage when clicking lesson in playlist
 */
$('.playlist a').click(function(event){
  event.preventDefault();
  var playlist = getPlaylist(this);
  localStorage.setItem('playlist', playlist);
  window.location.href = this.attributes.href.value;
});

/**
 * Create a playlist object from a playlist lesson link.
 */
function getPlaylist(link) {
  var parent = $(link).parent();
  var res = {};
  res.name = $('.name', parent).text();
  res.lessons = getLessons(parent);
  return res;
}

function getLessons(playlist) {
  var base = window.location.href.replace('index.html', '');
  var links = $('a', playlist);
  return $.map(links, function(elm){
    var url = base + elm.attributes.href.value;
    var name = $('> li', elm).text();
    return {url: url, name: name};
  });
}

function addNavigation(playlist) {
  var navigation = '
';
  navigation += '
'+ playlist.name +'
';

  navigation += '
';
  navigation += '
«
';
  for (var i=0, l=playlist.lessons.length; i<l; ++i) {
    var lesson = playlist.lessons[i];
    navigation += '
';
    navigation += ''+ (i + 1) +'';
    navigation += '
';
  }
  navigation += '
»
'; // FIXME: translate
  navigation += '
';
  navigation += '

';

  $('header').parent().prepend(navigation);
  $('#footer').parent().prepend(navigation);

  $('.playlist-navigation select').change(function(){
    window.location.href = this.value;
  });

  $('.playlist-navigation a').click(function(){
    var i = indexOf(playlist.lessons, window.location.href);
    if ($(this).hasClass('prev')) {
      i -= 1;
    } else if ($(this).hasClass('next')) {
      i += 1;
    } else { return }  // not next/prev button
    if (playlist.lessons[i]) {
      var url = playlist.lessons[i].url;
      localStorage.setItem('playlist', playlist);
      window.location.href = url;
    }
  })
}

function indexOf(lessons, current) {
  for (var i=0, l=lessons.length; i<l; ++i) {
    if (lessons[i].url === current) {
      return i;
    }
  }
}
<commit_msg>fix playlist, localStorage can only store strings<commit_after>/**
 * Client side logic for playlists.
 *
 * - Show/hide playlists.
 * - Keep track of position in playlist.
 */

import i18n from './i18n.js';

let t;
i18n.on('initialized', () => {
  t = i18n.getFixedT();

  /**
   * If in lesson of playlist
   */
  var playlist = JSON.parse(localStorage.getItem('playlist'));
  if (playlist) {
    if (indexOf(playlist.lessons, window.location.href) !== undefined) {
      // current lesson is this very page -> add navigation
      addNavigation(playlist);
    } else {
      // remove playlist from localStorage, we are no longer in a playlist
      localStorage.removeItem('playlist');
    }
  }
})

/**
 * show/hide playlist
 */
$('.playlist > li').click(function(){
  $('.' + this.id).slideToggle();
});

/**
 * save playlist to localStorage when clicking lesson in playlist
 */
$('.playlist a').click(function(event){
  event.preventDefault();
  var playlist = getPlaylist(this);
  localStorage.setItem('playlist', JSON.stringify(playlist));
  window.location.href = this.attributes.href.value;
});

/**
 * Create a playlist object from a playlist lesson link.
 */
function getPlaylist(link) {
  var parent = $(link).parent();
  var res = {};
  res.name = $('.name', parent).text();
  res.lessons = getLessons(parent);
  return res;
}

function getLessons(playlist) {
  var base = window.location.href.replace('index.html', '');
  var links = $('a', playlist);
  return $.map(links, function(elm){
    var url = base + elm.attributes.href.value;
    var name = $('> li', elm).text();
    return {url: url, name: name};
  });
}

function addNavigation(playlist) {
  var navigation = '
';
  navigation += '
'+ playlist.name +'
';

  navigation += '
';
  navigation += '
«
';
  for (var i=0, l=playlist.lessons.length; i<l; ++i) {
    var lesson = playlist.lessons[i];
    navigation += '
';
    navigation += ''+ (i + 1) +'';
    navigation += '
';
  }
  navigation += '
»
'; // FIXME: translate
  navigation += '
';
  navigation += '

';

  $('header').parent().prepend(navigation);
  $('#footer').parent().prepend(navigation);

  $('.playlist-navigation select').change(function(){
    window.location.href = this.value;
  });

  $('.playlist-navigation a').click(function(){
    var i = indexOf(playlist.lessons, window.location.href);
    if ($(this).hasClass('prev')) {
      i -= 1;
    } else if ($(this).hasClass('next')) {
      i += 1;
    } else { return }  // not next/prev button
    if (playlist.lessons[i]) {
      var url = playlist.lessons[i].url;
      localStorage.setItem('playlist', JSON.stringify(playlist));
      window.location.href = url;
    }
  })
}

function indexOf(lessons, current) {
  for (var i=0, l=lessons.length; i<l; ++i) {
    if (lessons[i].url === current) {
      return i;
    }
  }
}
<|endoftext|>


<commit_before>function initiateViima(viimaId, imgUrl, borderColor, tabOpacity){

  //Initializing variables
  if(!viimaId){
    viimaId = 'viima'
  }

  if(!imgUrl){
    imgUrl = ' https://app.viima.com/static/img/feedback.png'
  }

  //Appending tab to body
  $('body').append('

');

  //Setting CSS
	$('#feedback-tab').css({
          'position': 'fixed',
           'top': '30%',
           'left': '0',
           'cursor': 'pointer',
           '-webkit-transition-duration': '0.3s',
           '-moz-transition-duration': '0.3s',
           '-o-transition-duration': '0.3s',
           'transition-duration': '0.3s',
  });

  $('#feedback-inner').css({
          'position': 'fixed',
          'top': '30%',
          'left': '-1000px',
          '-webkit-transition-duration': '0.3s',
          '-moz-transition-duration': '0.3s',
          '-o-transition-duration': '0.3s',
          'transition-duration': '0.3s',
          'height': '400px',
          'width': '700px',
          'overflow': 'hidden',
  });

  $('#feedback-inner iframe').css({
          'height': '100%',
          'width': '100%',
  });

  //Settings
  if(borderColor){
    $('#feedback-inner iframe').css('border', '2px solid ' + borderColor);
  };

  if(tabOpacity){
    $('#feedback-tab img').css('opacity', tabOpacity);
  }

  $('#feedback-tab').click(toggleViima);
}

function toggleViima(){
  //If the feedback tab is hidden, show it, otherwise hide it
  if($('#feedback-inner').css('left').indexOf('-') != -1){
    $('#feedback-tab').css('left', '700px');
    $('#feedback-tab #feedback-inner').css('left', '0px');
  } else {
    $('#feedback-tab').css('left', '0px');
    $('#feedback-tab #feedback-inner').css('left', '-700px');
  }
}

//Hide the feedback widget on clicks outside the container
$(document).mouseup(function (e)
{
    var container = $('#feedback-tab');

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        $('#feedback-tab').css('left', '0px');
        $('#feedback-tab #feedback-inner').css('left', '-700px');
    }
});<commit_msg>Made the widget responsive and added many more options: now you can specify the relative height and width of the application as well as position from bottom of the page and add a custom css class<commit_after>function initiateViima(viimaId, tabImgUrl, heightFactor, widthFactor, tabOffsetFromBottom, customClassForTab, borderColor, tabOpacity){

  //Initializing variables
  if(!viimaId){
    viimaId = 'viima'
  }

  if(!tabImgUrl){
    tabImgUrl = 'https://app.viima.com/static/img/feedback.png'
  }

  if(!heightFactor){
    heightFactor = 0.8;
  }

  if(!widthFactor){
    widthFactor = 0.8;
  }

  if(!tabOffsetFromBottom){
    //Calculated based on the actual visible screen size, just applying a percentage for bottom doesn't do the trick
    tabOffsetFromBottom = 0.3;
  }

  //Calculate width and height for container based on visible screen size
  var height = heightFactor * window.innerHeight;
  var width = widthFactor * window.innerWidth;
  var containerOffset = (1-heightFactor)/2 * window.innerHeight;
  var tabOffset = tabOffsetFromBottom * window.innerHeight;

  //Appending tab to body
  $('body').append('

');

  //Setting CSS
	$('#feedback-tab').css({
          'position': 'fixed',
           'bottom':  tabOffset + 'px',
           'left': '0',
           'cursor': 'pointer',
           '-webkit-transition-duration': '0.3s',
           '-moz-transition-duration': '0.3s',
           '-o-transition-duration': '0.3s',
           'transition-duration': '0.3s',
           'z-index': '10000'
  });

  $('#feedback-inner').css({
          'position': 'fixed',
          'bottom': containerOffset + 'px',
          'left': '-' + width + 'px',
          '-webkit-transition-duration': '0.3s',
          '-moz-transition-duration': '0.3s',
          '-o-transition-duration': '0.3s',
          'transition-duration': '0.3s',
          'height': height + 'px',
          'width': width + 'px',
          'overflow': 'hidden',
          'z-index': '10000'
  });

  $('#feedback-inner iframe').css({
          'height': '100%',
          'width': '100%',
          'z-index': '10001'
  });

  //Extra style settings
  if(borderColor){
    $('#feedback-inner iframe').css('border', '3px solid ' + borderColor);
  };

  if(tabOpacity){
    $('#feedback-tab img').css('opacity', tabOpacity);
  }

  if(customClassForTab){
    $('#feedback-tab').addClass(customClassForTab);
  }

  $('#feedback-tab').click(toggleViima);

  function toggleViima(){
    //If the feedback tab is hidden, show it, otherwise hide it
    if($('#feedback-inner').css('left').indexOf('-') != -1){
      $('#feedback-tab').css('left', width + 'px');
      $('#feedback-tab #feedback-inner').css('left', '0px');
      $('#feedback-tab #feedback-inner').css('bottom', containerOffset + 'px');
    } else {
      $('#feedback-tab').css('left', '0px');
      $('#feedback-tab #feedback-inner').css('left', '-' + width + 'px');
    }
  }

  //Hide the feedback widget on clicks outside the container
  $(document).mouseup(function (e)
  {
      var container = $('#feedback-tab');

      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          $('#feedback-tab').css('left', '0px');
          $('#feedback-tab #feedback-inner').css('left', '-' + width + 'px');
      }
  });
}<|endoftext|>


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

/* eslint-disable import/no-extraneous-dependencies, no-console */
const program    = require('commander');
const fs         = require('fs');
const HtmlDiffer = require('html-differ').HtmlDiffer;
const logger     = require('html-differ/lib/logger');
const path       = require('path');
const common     = require('./common');

program
    .version('0.1.0')
    .description('Get html diff between two files in /dist & /dist-perl folder')
    .option('-p, --path [save_as]', 'Diff only the template/s that match the regex save_as, REQUIRED')
    .option('-l, --lang [language]', 'Diff only for the language that matches the regex')
    .parse(process.argv);

if (!program.path) {
    console.log('validate.js --path option is required, try --help to see the options.'.red);
    process.exit(0);
}

const options = {
    ignoreAttributes         : [],
    compareAttributesAsJSON  : [],
    ignoreWhitespaces        : true,
    ignoreComments           : false,
    ignoreEndTags            : false,
    ignoreDuplicateAttributes: false,
};

const htmlDiffer = new HtmlDiffer(options);

const diff = (save_as) => {

    const impl = (p1, p2) => {
        console.warn('\n\n', p1.white.bold, ' <=====> '.yellow.bold, p2.white.bold);
        const path1 = path.join(common.root_path, p1);
        const path2 = path.join(common.root_path, p2);
        if (!fs.existsSync(path1) || !fs.existsSync(path2)) {
            console.error('NOT FOUND ', path1, path2);
            return ;
        }

        const html1 = fs.readFileSync(path1, 'utf-8');
        const html2 = fs.readFileSync(path2, 'utf-8');

        const diffHTML = htmlDiffer.diffHtml(html1, html2);
        const isEqual  = htmlDiffer.isEqual(html1, html2);

        if (!isEqual) {
            logger.logDiffText(diffHTML, { charsAroundDiff: 40 });
        }
    };

    const reg_lang = new RegExp(program.lang, 'i');
    common.languages
        .filter(l => reg_lang.test(l))
        .forEach(lang => {
            const language = lang.toLowerCase();

            impl(
                `dist/${language}/${save_as}.html`,
                `dist-perl/${language}/${save_as}.html`
            );
            impl(
                `dist/${language}/pjax/${save_as}.html`,
                `dist-perl/${language}/pjax/${save_as}.html`
            );
        });
};

const regx = new RegExp(program.path, 'i');
common.pages
    .filter(p => regx.test(p.save_as))
    .map(p => p.save_as)
    .forEach(diff);
<commit_msg>Fix untracked files<commit_after><|endoftext|>


<commit_before>/* global hexo */

'use strict';

const { join } = require('path');

const { listDir } = require('hexo-fs');
const { log } = hexo;
const sizeOf = require('image-size');

async function validateThemeThumbnail() {
  let isValidationPassed = true;
  const screenshotsPath = join(hexo.source_dir, 'themes/screenshots');
  const screenshots = await listDir(screenshotsPath);

  screenshots.forEach(filename => {
    if (!filename.endsWith('.png')) {
      log.fatal(`The theme thumbnail "${filename}" is not a png image.`);
      isValidationPassed = false;
    }

    const screenshot = join(screenshotsPath, filename);

    const { width, height } = sizeOf(screenshot);
    if (width !== 800 || height !== 500) {
      log.fatal(`The theme thumbnail "${filename}" is not sized in 800x500 (got ${width}x${height}).`);
      isValidationPassed = false;
    }
  });

  if (!isValidationPassed) {
    throw new Error('Theme thumbnails validation failed');
  } else {
    log.info('Theme thumbnails validation completed');
  }
}

hexo.extend.filter.register('before_generate', validateThemeThumbnail);
<commit_msg>chore: only validate thumbnail on exit event<commit_after>/* global hexo */

'use strict';

const { join } = require('path');

const { listDir } = require('hexo-fs');
const { log } = hexo;
const sizeOf = require('image-size');

async function validateThemeThumbnail() {
  let isValidationPassed = true;
  const screenshotsPath = join(hexo.source_dir, 'themes/screenshots');
  const screenshots = await listDir(screenshotsPath);

  screenshots.forEach(filename => {
    if (!filename.endsWith('.png')) {
      log.fatal(`The theme thumbnail "${filename}" is not a png image.`);
      isValidationPassed = false;
    }

    const screenshot = join(screenshotsPath, filename);

    const { width, height } = sizeOf(screenshot);
    if (width !== 800 || height !== 500) {
      log.fatal(`The theme thumbnail "${filename}" is not sized in 800x500 (got ${width}x${height}).`);
      isValidationPassed = false;
    }
  });

  if (!isValidationPassed) {
    throw new Error('Theme thumbnails validation failed');
  } else {
    log.info('Theme thumbnails validation completed');
  }
}

hexo.extend.filter.register('before_exit', validateThemeThumbnail);
<|endoftext|>


<commit_before>/*! https://mths.be/scrollingelement v1.1.0 by @diegoperini & @mathias | MIT license */
if (!('scrollingElement' in document)) {
	(function() {

		var html = document.documentElement;
		var isCompliant = false;
		var isStandardsMode = /^CSS1/.test(document.compatMode);

		if (isStandardsMode) {
			var iframe = document.createElement('iframe');
			iframe.style.height = '1px';
			(document.body || html).appendChild(iframe);
			var doc = iframe.contentWindow.document;
			doc.write('<!DOCTYPE html>
x
');
			doc.close();
			isCompliant = doc.documentElement.scrollHeight > doc.body.scrollHeight;
			iframe.parentNode.removeChild(iframe);
		}

		var scrollingElement = function() {
			var body = document.body;
			if (isCompliant) { // Note: this is `isStandardsMode && isCompliant`.
				return html;
			}
			// Note: `document.body` could be a `frameset` element, or `null`.
			// `tagName` is uppercase in HTML, but lowercase in XML.
			var isFrameset = body && !/body/i.test(body.tagName);
			return isFrameset ? null : body;
		};

		if ('defineProperty' in Object) {
			// Support modern browsers that lack a native implementation.
			Object.defineProperty(document, 'scrollingElement', {
				'get': scrollingElement
			});
		} else if ('__defineGetter__' in document) {
			// Support Firefox ≤ 3.6.9, Safari ≤ 4.1.3.
			document.__defineGetter__('scrollingElement', scrollingElement);
		} else if ('attachEvent' in document) {
			// Support IE ≤ 7.
			document.scrollingElement = scrollingElement();
			document.attachEvent('onpropertychange', function() {
				// A `propertychange` event fires when `<body>` is parsed because
				// `document.activeElement` then changes.
				if (window.event.propertyName == 'activeElement') {
					document.scrollingElement = scrollingElement();
				}
			});
		}

	}());
}
<commit_msg>Save one level of indentation<commit_after>/*! https://mths.be/scrollingelement v1.1.0 by @diegoperini & @mathias | MIT license */
if (!('scrollingElement' in document)) (function() {

	var html = document.documentElement;
	var isCompliant = false;
	var isStandardsMode = /^CSS1/.test(document.compatMode);

	if (isStandardsMode) {
		var iframe = document.createElement('iframe');
		iframe.style.height = '1px';
		(document.body || html).appendChild(iframe);
		var doc = iframe.contentWindow.document;
		doc.write('<!DOCTYPE html>
x
');
		doc.close();
		isCompliant = doc.documentElement.scrollHeight > doc.body.scrollHeight;
		iframe.parentNode.removeChild(iframe);
	}

	var scrollingElement = function() {
		var body = document.body;
		if (isCompliant) { // Note: this is `isStandardsMode && isCompliant`.
			return html;
		}
		// Note: `document.body` could be a `frameset` element, or `null`.
		// `tagName` is uppercase in HTML, but lowercase in XML.
		var isFrameset = body && !/body/i.test(body.tagName);
		return isFrameset ? null : body;
	};

	if ('defineProperty' in Object) {
		// Support modern browsers that lack a native implementation.
		Object.defineProperty(document, 'scrollingElement', {
			'get': scrollingElement
		});
	} else if ('__defineGetter__' in document) {
		// Support Firefox ≤ 3.6.9, Safari ≤ 4.1.3.
		document.__defineGetter__('scrollingElement', scrollingElement);
	} else if ('attachEvent' in document) {
		// Support IE ≤ 7.
		document.scrollingElement = scrollingElement();
		document.attachEvent('onpropertychange', function() {
			// A `propertychange` event fires when `<body>` is parsed because
			// `document.activeElement` then changes.
			if (window.event.propertyName == 'activeElement') {
				document.scrollingElement = scrollingElement();
			}
		});
	}

}());
<|endoftext|>


<commit_before>/*
Daf-collage is made up of two Moodle modules which help in the process of
German language learning. It facilitates the content organization like
vocabulary or the main grammar features and gives the chance to create
exercises in order to consolidate knowledge.

Copyright (C) 2011

Coordination:
Ruth Burbat

Source code:
Francisco Javier Rodríguez López (seiyadesagitario@gmail.com)
Simeón Ruiz Romero (simeonruiz@gmail.com)

Original idea and content design:
Ruth Burbat
Inmaculada Almahano Güeto
Andrea Bies
Julia Möller Runge
Blanca Rodríguez Gómez
Antonio Salmerón Matilla
María José Varela Salinas
Karin Vilar Sánchez

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/

/**
 * Busca una palabra en el diccionario online seleccionado
 *
 * @param elemento Indice para seleccionar el elemento del que obtener la palabra
 */

function traducir(elemento) {
    var palabra;
    switch (elemento) {
        case 1:
            palabra = document.getElementById("id_palabra_sus").value;
            break;
        case 2:
            palabra = document.getElementById("id_infinitivo").value;
            break;
        case 3:
            palabra = document.getElementById("id_sindeclinar").value;
            break;
        case 4:
            palabra = document.getElementById("id_palabra_otr").value;
            break;
        default:
            break;
    }
    var url;
    var dic = document.getElementById("id_diccionario").value;
    if(dic == 1) {
        url = "http://dict.leo.org/esde?lp=esde&lang=de&search=" + palabra;
    } else if(dic == 0) {
        url = "http://www.dwds.de/?qu=" + palabra + "&view=1";
    } else if(dic == 2) {
        url = "http://de.pons.eu/dict/search/results/?q=" + palabra + "&l=dees";
    } else if(dic == 3) {
        url = "http://www.openthesaurus.de/synonyme/" + palabra;
    } else if(dic == 4) {
        url = "http://www.duden.de/suchen/dudenonline/" + palabra;
    }
    window.open(url, 'diccionario');
}

/**
 * Carga el contenido de un fichero php
 * @param miselect
 * @param otroselect
 * @param tipo
 */

function cargaContenido(miselect, otroselect, tipo) {

    var elselect = document.getElementById(miselect).value;
    var nombre = document.getElementById(miselect).name;

    if(elselect == 0 || elselect == 1) {
        document.getElementById(otroselect).innerHTML = "";
    } else {
        document.getElementById(otroselect).innerHTML = '

';
        if(window.XMLHttpRequest) {//para que se vea en IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {//para que se vea en IE6, IE5 y otros
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById(otroselect).innerHTML = xmlhttp.responseText;
            }
        }
        if(tipo == 0) {//campos lexicos
            xmlhttp.open("GET", "subcampos.php?id=" + elselect + "&nombre=" + nombre, true);
        } else if(tipo == 1) {//gramaticas
            xmlhttp.open("GET", "subgramaticas.php?id=" + elselect + "&nombre=" + nombre, true);
        } else if(tipo == 2) {//intenciones comunicativas
            xmlhttp.open("GET", "subintenciones.php?id=" + elselect + "&nombre=" + nombre, true);
        }
        xmlhttp.send();
    }
}

/**
 * Establece al valor "none" el atributo de estilo 'display' de todos aquellos
 * elementos que estén marcados en su id con el prefijo "ocultador_".
 *
 * @param seccion Id de los elementos a ocultar (sin incluir el prefijo 'ocultador_')
 */

function ocultar(seccion) {
    ocu = document.getElementById("ocultador_" + seccion);
    ocu.style.display = "none";
    enlace = document.getElementById("mc" + seccion);
    enlace.href = "javascript:desocultar('" + seccion + "')";
}

/**
 * Elimina el contenido del atributo de estilo 'display' de todos aquellos
 * elementos que estén marcados en su id con el prefijo "ocultador_" para usar
 * el valor por defecto de este atributo.
 *
 * @param seccion Id de los elementos a ocultar (sin incluir el prefijo 'ocultador_')
 */

function desocultar(seccion) {
    ocu = document.getElementById("ocultador_" + seccion);
    ocu.style.display = "";
    enlace = document.getElementById("mc" + seccion);
    enlace.href = "javascript:ocultar('" + seccion + "')";
}

/**
 * Establece a "true" el valor del atributo 'disabled' de todos los elementos
 * de un formulario con id "mform1" desde un cierto índice hasta el final.
 *
 * @param ini Índice a partir del cual se comienzan a deshabilitar elementos.
 */

function desactivar_todo(ini) {
    for( i = ini; i < document.getElementById("mform1").elements.length - 3; i++)
        document.getElementById("mform1").elements[i].disabled = true;
}

/**
 * Establece a "false" el valor del atributo 'disabled' de todos los elementos
 * de un formulario con id "mform1".
 */

function activar_todo() {
    for( i = 0; i < document.getElementById("mform1").elements.length; i++)
        document.getElementById("mform1").elements[i].disabled = false;
}

/**
 * Comprueba si tienes las cookies habilitadas, y en caso contrario te manda a un tutorial
 */

function comprobar_cookies(){
    if (navigator.cookieEnabled == 0) {
        alert("Este sitio necesita tener habilitadas cookies. Pulse aceptar para saber cómo puede habilitarlas");
        window.open('./habilitar_cookies.html','','location=no,directories=no, status=no,menubar=no,resizable=no');
    }
}

/**
 * @author Antonio Fernández Ares
 */

function la_tabla_nube() {
    var oTable = $('#palabras').dataTable({
        "bJQueryUI": true,
        "oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ entradas por página",
            "sZeroRecords": "No se encontró nada",
            "sInfo": "Mostrando _START_ de _END_ de un total de _TOTAL_ entradas",
            "sInfoEmpty": "Mostrando 0 de 0 de un total de 0 entradas",
            "sInfoFiltered": "(Filtrado de _MAX_ entradas)"
        }

    });

    $('#palabras tbody tr td').live('click', function (){
        var nTds = $(this);
        //alert (nTds.html());
        oTable.fnFilter(nTds.html());
    });
}
<commit_msg><commit_after>/*
Daf-collage is made up of two Moodle modules which help in the process of
German language learning. It facilitates the content organization like
vocabulary or the main grammar features and gives the chance to create
exercises in order to consolidate knowledge.

Copyright (C) 2011

Coordination:
Ruth Burbat

Source code:
Francisco Javier Rodríguez López (seiyadesagitario@gmail.com)
Simeón Ruiz Romero (simeonruiz@gmail.com)

Original idea and content design:
Ruth Burbat
Inmaculada Almahano Güeto
Andrea Bies
Julia Möller Runge
Blanca Rodríguez Gómez
Antonio Salmerón Matilla
María José Varela Salinas
Karin Vilar Sánchez

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/

/**
 * Busca una palabra en el diccionario online seleccionado
 *
 * @param elemento Indice para seleccionar el elemento del que obtener la palabra
 */

function traducir(elemento) {
    var palabra;
    switch (elemento) {
        case 1:
            palabra = document.getElementById("id_palabra_sus").value;
            break;
        case 2:
            palabra = document.getElementById("id_infinitivo").value;
            break;
        case 3:
            palabra = document.getElementById("id_sindeclinar").value;
            break;
        case 4:
            palabra = document.getElementById("id_palabra_otr").value;
            break;
        default:
            break;
    }
    var url;
    var dic = document.getElementById("id_diccionario").value;
    if(dic == 1) {
        url = "http://dict.leo.org/esde?lp=esde&lang=de&search=" + palabra;
    } else if(dic == 0) {
        url = "http://www.dwds.de/?qu=" + palabra + "&view=1";
    } else if(dic == 2) {
        url = "http://de.pons.eu/dict/search/results/?q=" + palabra + "&l=dees";
    } else if(dic == 3) {
        url = "http://www.openthesaurus.de/synonyme/" + palabra;
    } else if(dic == 4) {
        url = "http://www.duden.de/suchen/dudenonline/" + palabra;
    }
    window.open(url, 'diccionario');
}

/**
 * Carga el contenido de un fichero php
 * @param miselect
 * @param otroselect
 * @param tipo
 */

function cargaContenido(miselect, otroselect, tipo) {

    var objeto = document.getElementById(miselect);
    var elselect = objeto.value;
    var nombre = objeto.name;
    var eltxt = objeto.options[objeto.selectedIndex].text;

    oculto = document.getElementById('id_desc_btn'); // Ocultar
    if (oculto) oculto.disabled = true;

    if(elselect == 0 || elselect == 1 || eltxt == "Seleccionar") {
        document.getElementById(otroselect).innerHTML = "";
    } else {
        document.getElementById(otroselect).innerHTML = '

';
        if(window.XMLHttpRequest) {//para que se vea en IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {//para que se vea en IE6, IE5 y otros
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById(otroselect).innerHTML = xmlhttp.responseText;
            }
        }
        if(tipo == 0) {//campos lexicos
            xmlhttp.open("GET", "subcampos.php?id=" + elselect + "&nombre=" + nombre, true);
        } else if(tipo == 1 && eltxt != "Seleccionar") {//gramaticas
            xmlhttp.open("GET", "subgramaticas.php?id=" + elselect + "&nombre=" + nombre, true);
        } else if(tipo == 2 && eltxt != "Seleccionar") {//intenciones comunicativas
            xmlhttp.open("GET", "subintenciones.php?id=" + elselect + "&nombre=" + nombre, true);
        }
        xmlhttp.send();
    }
}

/**
 * Establece al valor "none" el atributo de estilo 'display' de todos aquellos
 * elementos que estén marcados en su id con el prefijo "ocultador_".
 *
 * @param seccion Id de los elementos a ocultar (sin incluir el prefijo 'ocultador_')
 */

function ocultar(seccion) {
    ocu = document.getElementById("ocultador_" + seccion);
    ocu.style.display = "none";
    enlace = document.getElementById("mc" + seccion);
    enlace.href = "javascript:desocultar('" + seccion + "')";
}

/**
 * Elimina el contenido del atributo de estilo 'display' de todos aquellos
 * elementos que estén marcados en su id con el prefijo "ocultador_" para usar
 * el valor por defecto de este atributo.
 *
 * @param seccion Id de los elementos a ocultar (sin incluir el prefijo 'ocultador_')
 */

function desocultar(seccion) {
    ocu = document.getElementById("ocultador_" + seccion);
    ocu.style.display = "";
    enlace = document.getElementById("mc" + seccion);
    enlace.href = "javascript:ocultar('" + seccion + "')";
}

/**
 * Establece a "true" el valor del atributo 'disabled' de todos los elementos
 * de un formulario con id "mform1" desde un cierto índice hasta el final.
 *
 * @param ini Índice a partir del cual se comienzan a deshabilitar elementos.
 */

function desactivar_todo(ini) {
    for( i = ini; i < document.getElementById("mform1").elements.length - 3; i++)
        document.getElementById("mform1").elements[i].disabled = true;
}

/**
 * Establece a "false" el valor del atributo 'disabled' de todos los elementos
 * de un formulario con id "mform1".
 */

function activar_todo() {
    for( i = 0; i < document.getElementById("mform1").elements.length; i++)
        document.getElementById("mform1").elements[i].disabled = false;
}

/**
 * Comprueba si tienes las cookies habilitadas, y en caso contrario te manda a un tutorial
 */

function comprobar_cookies(){
    if (navigator.cookieEnabled == 0) {
        alert("Este sitio necesita tener habilitadas cookies. Pulse aceptar para saber cómo puede habilitarlas");
        window.open('./habilitar_cookies.html','','location=no,directories=no, status=no,menubar=no,resizable=no');
    }
}

/**
 * @author Antonio Fernández Ares
 */

function la_tabla_nube() {
    var oTable = $('#palabras').dataTable({
        "bJQueryUI": true,
        "oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ entradas por página",
            "sZeroRecords": "No se encontró nada",
            "sInfo": "Mostrando _START_ de _END_ de un total de _TOTAL_ entradas",
            "sInfoEmpty": "Mostrando 0 de 0 de un total de 0 entradas",
            "sInfoFiltered": "(Filtrado de _MAX_ entradas)"
        }

    });

    $('#palabras tbody tr td').live('click', function (){
        var nTds = $(this);
        //alert (nTds.html());
        oTable.fnFilter(nTds.html());
    });
}
<|endoftext|>