<commit_before>var uploadUrl = '../loader/upload/start/';
var checkUrl = '../loader/data/one/';
var thumbUrl = '../loader/data/thumbnail/';
var deleteSlideUrl = '../loader/slide/delete';
var downloadURL = '../loader/getSlide/';

var store = new Store('../data/');

function changeStatus(step, text, reset=true) {
  // Reset the status bar
  console.log('Previous: ', document.getElementById('load_status').innerHTML);
  document.getElementById('load_status').innerHTML='';

  // Display JSON as table:
  if (typeof text === 'object') { // If the text arg is a JSON
    var col = []; // List of column headers
    for (var key in text) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }

    var table;
    var responsiveContainer;
    if (reset) {
      responsiveContainer = document.createElement('div');
      responsiveContainer.classList = 'table-responsive';
      table = document.createElement('table');
      table.id = 'statusTable';
      table.classList = 'table';

      // Add table headers:
      var tr = table.insertRow(-1);
      for (var i = 0; i < col.length; i++) {
        var th = document.createElement('th');
        th.innerHTML = col[i];
        tr.appendChild(th);
      }
    } else {
      table=document.getElementById('statusTable');
    }

    if (step == 'POST' && !reset) {
      tr = table.rows[table.rows.length-1];
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.cells[tr.cells.length-1];
        tabCell.innerHTML = Number(Number(tabCell.innerHTML) + 1);
      }
    } else {
      // Add JSON data to the table as rows:
      tr = table.insertRow(-1);
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        if (text[col[j]].length>65&&step == 'CHECK') {
          tabCell.innerHTML= `${text[col[j]].substr(0, 65)}
             ${text[col[j]].substr(65)}
    ... `;
        } else {
          tabCell.innerHTML = text[col[j]];
        }
      }
      if (step == 'CHECK') {
        // During check, thumbnail needs to be fetched & added to the table
        // In this case, text[col[col.length - 1]] is the filename
        console.log(text['location'], "H1")
        fetch(thumbUrl + text[col[col.length - 1]], {credentials: 'same-origin'}).then(
            (response) => response.json(), // if the response is a JSON object
        ).then((x)=>{
          var tabCell = tr.cells[tr.cells.length-1];
          tabCell.innerHTML = '';
          const img = new Image();
          img.src = x.slide;
          tabCell.appendChild(img);
          if (text['location']) {
            // indicating successful check
            checkSuccess = true;
            if (finishUploadSuccess === true) {
              $('#post_btn').show();
            } else {
              $('#post_btn').hide();
            }
          } else {
            checkSuccess = false;
            $('#post_btn').hide();
          }
        });
      }
    }

    var divContainer = document.getElementById('json_table');
    divContainer.innerHTML = '';
    responsiveContainer.appendChild(table);
    divContainer.appendChild(responsiveContainer);
    $('#statusTable').stacktable();
    document.getElementById('load_status').innerHTML=step;
  } else {
    text = JSON.stringify(text);
    text = step + ' | ' + text;
    document.getElementById('load_status').innerHTML=text;
  }
}

function handleUpload(file, filename) {
  var data = new FormData();
  data.append('file', file);
  data.append('filename', filename);
  changeStatus('UPLOAD', 'Begun upload');
  fetch(uploadUrl, {
    credentials: 'same-origin',
    method: 'POST',
    body: data,
  }).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (success) => changeStatus('UPLOAD', success), // Handle the success response object
  ).catch(
      (error) => changeStatus('UPLOAD', error), // Handle the error response object
  );
}

function handleDownload(id) {
  var fileName='';
  store.getSlide(id)
      .then((response) => {
        if (response[0]) {
          return response[0]['location'];
        } else {
          throw new Error('Slide not found');
        }
      }).then((location) => {
        fileName= location.substring(location.lastIndexOf('/')+1, location.length);
        console.log(fileName);
        return fileName;
      }).then((fileName) =>{
        fetch(downloadURL + fileName, {
          credentials: 'same-origin',
          method: 'GET',
        }).then((response) => {
          if (response.status == 404) {
            throw response;
          } else {
            return response.blob();
          }
        })
            .then((blob) => {
              var url = window.URL.createObjectURL(blob);
              var a = document.createElement('a');
              a.href = url;
              a.download = fileName;
              document.body.appendChild(a);
              a.click();
              a.remove(); // afterwards we remove the element again
              window.URL.revokeObjectURL(blob);
            }).catch((error) =>{
              console.log(error);
              alert('Error! Can\'t download file.');
            },
            );
      }).catch((error) => {
        console.log(error);
      });
}

function handleCheck(filename, reset, id) {
  fetch(checkUrl + filename, {credentials: 'same-origin'}).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (success) => {
        success['ID'] = id;
        // Add the filename, to be able to fetch the thumbnail.
        success['preview'] = filename;
        changeStatus('CHECK', success, reset);
      }, // Handle the success response object
  ).catch(
      (error) => changeStatus('CHECK', error, reset), // Handle the error response object
  );
}

function handlePost(filename, slidename, filter, reset) {
  fetch(checkUrl + filename, {credentials: 'same-origin'}).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (data) => {
        data['upload_date'] = new Date(Date.now()).toLocaleString();
        data.name = slidename;
        if (filter) {
          data.filter = filter;
        }
        data.location = '/images/' + filename;
        data.study = '';
        data.specimen = '';
        data.mpp = parseFloat(data['mpp-x']) || parseFloat(data['mpp-y']) || 0;
        data.mpp_x = parseFloat(data['mpp-x']);
        data.mpp_y = parseFloat(data['mpp-y']);
        store.post('Slide', data).then(
            (success) => {
              initialize();
              $('#upload-dialog').modal('hide');
              showSuccessPopup('Slide uploaded successfully');
              return changeStatus('POST', success.result, reset);
            }, // Handle the success response object
        ).catch(
            (error) => changeStatus('POST', error, reset), // Handle the error response object
        );
      },
  ).catch(
      (error) => changeStatus('POST', error, reset), // Handle the error response object
  );
}

// register events for file upload
function UploadBtn() {
  const fileInput = document.getElementById('fileinput');
  var filename = document.getElementById('filename').value;
  handleUpload(fileInput.files[0], filename);
}

function CheckBtn() {
  var filename = document.getElementById('filename'+0).value;
  handleCheck(filename, true, 1);
}

function PostBtn() {
  var filename = document.getElementById('filename'+0).value;
  var slidename = document.getElementById('slidename'+0).value;
  var filter = document.getElementById('filter'+0).value;
  handlePost(filename, slidename, filter, true);
}

function deleteSlideFromSystem(id, filename, reqId=null) {
  // var data = new FormData();
  // data.append('filename', filename);
  data = {
    'filename': filename,
  };
  data = JSON.stringify(data);
  fetch(deleteSlideUrl, {
    credentials: 'include',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: data,
  }).then(
      (response) => response.json())
      .then((data) => {
        if (data.success) {
        // return true;
          store.deleteSlide(id)
              .then(function() {
                if (reqId) {
                  store.cancelRequestToDeleteSlide(requestId=reqId, onlyRequestCancel=false);
                }
              })
              .then(showSuccessPopup('Slide deleted successfully'));
        } else {
          alert('There was an error in deleting the file. Please try again or refresh the page.');
        }
        return true;
      },
      ).catch(
          (error) => {
            console.log('ERROR: ' + error);
          }, // Handle the error response object
      );
}
<commit_msg>Resolve camicroscope/Distro#144<commit_after>var uploadUrl = '../loader/upload/start/';
var checkUrl = '../loader/data/one/';
var thumbUrl = '../loader/data/thumbnail/';
var deleteSlideUrl = '../loader/slide/delete';
var downloadURL = '../loader/getSlide/';

var store = new Store('../data/');

function changeStatus(step, text, reset=true) {
  // Reset the status bar
  console.log('Previous: ', document.getElementById('load_status').innerHTML);
  document.getElementById('load_status').innerHTML='';
  console.log(text, "h2")
  // Display JSON as table:
  if (typeof text === 'object') { // If the text arg is a JSON
    var col = []; // List of column headers
    for (var key in text) {
      if (col.indexOf(key) === -1) {
        col.push(key);
      }
    }

    var table;
    var responsiveContainer;
    if (reset) {
      responsiveContainer = document.createElement('div');
      responsiveContainer.classList = 'table-responsive';
      table = document.createElement('table');
      table.id = 'statusTable';
      table.classList = 'table';

      // Add table headers:
      var tr = table.insertRow(-1);
      for (var i = 0; i < col.length; i++) {
        var th = document.createElement('th');
        th.innerHTML = col[i];
        tr.appendChild(th);
      }
    } else {
      table=document.getElementById('statusTable');
    }

    if (step == 'POST' && !reset) {
      tr = table.rows[table.rows.length-1];
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.cells[tr.cells.length-1];
        tabCell.innerHTML = Number(Number(tabCell.innerHTML) + 1);
      }
    } else {
      // Add JSON data to the table as rows:
      tr = table.insertRow(-1);
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        if (text[col[j]] && text[col[j]].length>65&&step == 'CHECK') {
          tabCell.innerHTML= `${text[col[j]].substr(0, 65)}
             ${text[col[j]].substr(65)}
    ... `;
        } else {
          tabCell.innerHTML = text[col[j]];
        }
      }
      if (step == 'CHECK') {
        // During check, thumbnail needs to be fetched & added to the table
        // In this case, text[col[col.length - 1]] is the filename
        console.log(text, "H1")
        fetch(thumbUrl + text[col[col.length - 1]], {credentials: 'same-origin'}).then(
            (response) => response.json(), // if the response is a JSON object
        ).then((x)=>{
          var tabCell = tr.cells[tr.cells.length-1];
          tabCell.innerHTML = '';
          const img = new Image();
          img.src = x.slide;
          tabCell.appendChild(img);
          if (text['location']) {
            // indicating successful check
            checkSuccess = true;
            if (finishUploadSuccess === true) {
              $('#post_btn').show();
            } else {
              $('#post_btn').hide();
            }
          } else {
            checkSuccess = false;
            $('#post_btn').hide();
          }
        });
      }
    }

    var divContainer = document.getElementById('json_table');
    divContainer.innerHTML = '';
    responsiveContainer.appendChild(table);
    divContainer.appendChild(responsiveContainer);
    $('#statusTable').stacktable();
    document.getElementById('load_status').innerHTML=step;
  } else {
    text = JSON.stringify(text);
    text = step + ' | ' + text;
    document.getElementById('load_status').innerHTML=text;
  }
}

function handleUpload(file, filename) {
  var data = new FormData();
  data.append('file', file);
  data.append('filename', filename);
  changeStatus('UPLOAD', 'Begun upload');
  fetch(uploadUrl, {
    credentials: 'same-origin',
    method: 'POST',
    body: data,
  }).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (success) => changeStatus('UPLOAD', success), // Handle the success response object
  ).catch(
      (error) => changeStatus('UPLOAD', error), // Handle the error response object
  );
}

function handleDownload(id) {
  var fileName='';
  store.getSlide(id)
      .then((response) => {
        if (response[0]) {
          return response[0]['location'];
        } else {
          throw new Error('Slide not found');
        }
      }).then((location) => {
        fileName = location.substring(location.lastIndexOf('/')+1, location.length);
        console.log(fileName);
        return fileName;
      }).then((fileName) =>{
        fetch(downloadURL + fileName, {
          credentials: 'same-origin',
          method: 'GET',
        }).then((response) => {
          if (response.status == 404) {
            throw response;
          } else {
            return response.blob();
          }
        })
            .then((blob) => {
              var url = window.URL.createObjectURL(blob);
              var a = document.createElement('a');
              a.href = url;
              a.download = fileName;
              document.body.appendChild(a);
              a.click();
              a.remove(); // afterwards we remove the element again
              window.URL.revokeObjectURL(blob);
            }).catch((error) =>{
              console.log(error);
              alert('Error! Can\'t download file.');
            },
            );
      }).catch((error) => {
        console.log(error);
      });
}

function handleCheck(filename, reset, id) {
  fetch(checkUrl + filename, {credentials: 'same-origin'}).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (success) => {
        success['ID'] = id;
        // Add the filename, to be able to fetch the thumbnail.
        success['preview'] = filename;
        changeStatus('CHECK', success, reset);
      }, // Handle the success response object
  ).catch(
      (error) => changeStatus('CHECK', error, reset), // Handle the error response object
  );
}

function handlePost(filename, slidename, filter, reset) {
  fetch(checkUrl + filename, {credentials: 'same-origin'}).then(
      (response) => response.json(), // if the response is a JSON object
  ).then(
      (data) => {
        data['upload_date'] = new Date(Date.now()).toLocaleString();
        data.name = slidename;
        if (filter) {
          data.filter = filter;
        }
        data.location = '/images/' + filename;
        data.study = '';
        data.specimen = '';
        data.mpp = parseFloat(data['mpp-x']) || parseFloat(data['mpp-y']) || 0;
        data.mpp_x = parseFloat(data['mpp-x']);
        data.mpp_y = parseFloat(data['mpp-y']);
        store.post('Slide', data).then(
            (success) => {
              initialize();
              $('#upload-dialog').modal('hide');
              showSuccessPopup('Slide uploaded successfully');
              return changeStatus('POST', success.result, reset);
            }, // Handle the success response object
        ).catch(
            (error) => changeStatus('POST', error, reset), // Handle the error response object
        );
      },
  ).catch(
      (error) => changeStatus('POST', error, reset), // Handle the error response object
  );
}

// register events for file upload
function UploadBtn() {
  const fileInput = document.getElementById('fileinput');
  var filename = document.getElementById('filename').value;
  handleUpload(fileInput.files[0], filename);
}

function CheckBtn() {
  var filename = document.getElementById('filename'+0).value;
  handleCheck(filename, true, 1);
}

function PostBtn() {
  var filename = document.getElementById('filename'+0).value;
  var slidename = document.getElementById('slidename'+0).value;
  var filter = document.getElementById('filter'+0).value;
  handlePost(filename, slidename, filter, true);
}

function deleteSlideFromSystem(id, filename, reqId=null) {
  // var data = new FormData();
  // data.append('filename', filename);
  data = {
    'filename': filename,
  };
  data = JSON.stringify(data);
  fetch(deleteSlideUrl, {
    credentials: 'include',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: data,
  }).then(
      (response) => response.json())
      .then((data) => {
        if (data.success) {
        // return true;
          store.deleteSlide(id)
              .then(function() {
                if (reqId) {
                  store.cancelRequestToDeleteSlide(requestId=reqId, onlyRequestCancel=false);
                }
              })
              .then(showSuccessPopup('Slide deleted successfully'));
        } else {
          alert('There was an error in deleting the file. Please try again or refresh the page.');
        }
        return true;
      },
      ).catch(
          (error) => {
            console.log('ERROR: ' + error);
          }, // Handle the error response object
      );
}
<|endoftext|>


<commit_before>var express = require("express");
var app = express();
var port = 8080;

//app.set('port',process.env.PORT || 80);

app.set('view engine', "jade");
app.engine('jade', require('jade').__express);

app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(express.cookieParser());
app.use(express.session({
	secret : 'this is a secret'
}));

//app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());

app.use(express.methodOverride());

app.get("/", function(req, res) {
	res.render("index");
});

var io = require('socket.io').listen(app.listen(port,"0.0.0.0"));
io.set('log level', 1);
io.set('transports', ['websocket']);

var FPS = 30;
var W = 1000;
var H = 500;
var KEY_UP = 38;
var KEY_DOWN = 40;
var TOP = 0;
var LEFT = 1;
var BOT = 2;
var RIGHT = 3;
var STARTED = 1;
var STOPPED = 0;

var Actor = (function(x, y, w, h, vx, vy) {
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.vx = vx;
	this.vy = vy;
});

var Paddle = (function(x, y, w, h, vx, vy) {
	Actor.call(this, x, y, w, h, vx, vy);
	this.points = 0;
	this.dir=0;

	this.lastKey=(function(key){
		this.dir=key;
	});

	this.move = (function() {
		switch(this.dir) {
			case KEY_UP:
				if (this.y > 0) {
					this.y -= this.vy;
				}
				break;
			case KEY_DOWN:
				if ((this.y + this.h) < H) {
					this.y += this.vy;
				}
				break;
			default:

		}
		this.dir=0;
	});
});
Paddle.prototype = new Actor();

var Ball = (function(x, y, w, h, vx, vy, angle) {
	Actor.call(this, x, y, w, h, vx, vy);
	// en radianes
	this.angle = angle;

	this.move = (function() {
		var vyt = (this.vy * Math.sin(this.angle));
		var vxt = (this.vx * Math.cos(this.angle));
		this.x += vxt;
		this.y -= vyt;
	});

	this.collide = (function(pos) {
		switch(pos) {
			case TOP:
				this.angle = -this.angle;
				break;
			case LEFT:
				if (this.angle>0){
					this.angle -= Math.PI / 2;
				}else{
					this.angle += Math.PI / 2;
				}
				break;
			case BOT:
				this.angle= -this.angle;
				break;
			case RIGHT:
				if (this.angle>0){
					this.angle += Math.PI / 2;
				}else{
					this.angle -= Math.PI / 2;
				}
				break;
		}
	});

	this.resetBall= (function (dir) {
		b.x = W / 2 - b.w / 2;
		b.y = H / 2 - b.h / 2;
		if(dir==LEFT){
			b.angle=-Math.PI/4;
		}else{
			b.angle=(Math.PI/4)*3;
		}
	});
});
Ball.prototype = new Actor();

var gameStatus=STOPPED;
var interval;

var paddleW = 15;
var paddleH = 100;
var ballDiam = 20;

var p1 = new Paddle(10 					, H/2-paddleH/2 , paddleW , paddleH , 0 , 20 );
var p2 = new Paddle(W-10-paddleW		, H/2-paddleH/2 , paddleW , paddleH , 0 , 20 );
var b  = new Ball  (W / 2 - ballDiam/2	, H/2-ballDiam/2, ballDiam, ballDiam, 10, 10, -Math.PI/4);

var player1 = null;
var player2 = null;
var users = [];

function collides(a, b) {
    return !(
        ((a.y + a.h) < (b.y)) ||
        (a.y > (b.y + b.h)) ||
        ((a.x + a.w) < b.x) ||
        (a.x > (b.x + b.w))
    );
}

function checkCollisions() {
	//goles
	if ((b.x + b.w) < 0) {
		b.resetBall(LEFT);
		p2.points++;
	}

	if (b.x > W) {
		b.resetBall(RIGHT);
		p1.points++;
	}

	//colisiones
	if (b.y <= 0) {
		b.collide(TOP);
	}
	if ((b.y + b.h) >= H) {
		b.collide(BOT);
	}

	//colision con palas
	if (collides(p1, b)) {
		b.collide(LEFT);
	}

	if (collides(p2, b)) {
		b.collide(RIGHT);
	}
}

function gameStart() {
	interval = setInterval(update, 1000 / FPS);
	gameStatus=STARTED;
}

function gameStop() {
	clearInterval(interval);
	gameStatus=STOPPED;
}

function gameReset() {
	b.resetBall();
	p1.points = 0;
	p2.points = 0;
}

function chagePlayer(){
	for (var i = 0; i < users.length; ++i){
		if(users[i]!=player1 && users[i]!=player2){
			if(player1==null){
				player1=users[i];
				return true;
			}else if(player2==null){
				player2=users[i];
				return true;
			}
		}
	}
	return false;
}

function update() {
	p1.move();
	p2.move();
	b.move();
	checkCollisions();
	io.sockets.emit('draw', {
		'p1' : p1,
		'p2' : p2,
		'ball' : b
	});
}

var playerIDCounter = 0;
//var game=require('./game.js');

io.sockets.on('connection', function(socket) {
	//socket.set('id',playerIDCounter);
	//console.log(socket);
	var myid = playerIDCounter;

	playerIDCounter++;

	console.log("Mi ide es: " + myid);
	socket.on('adduser', function() {
		users.push(myid);
		if(gameStatus==STOPPED /*player1==null || player2==null*/){
			chagePlayer();
		}

		if (gameStatus==STOPPED && player1!=null && player2!=null) {
			gameStart();
		}
	});

	socket.emit('initData', {
		'width' : W,
		'height' : H,
		'p1' : p1,
		'p2' : p2,
		'ball' : b
	});

	socket.on('keypress', function(data) {
		if (myid == player1) {
			p1.lastKey((data.key));
		} else if (myid == player2) {
			p2.lastKey((data.key));
		}
	});

	socket.on('disconnect', function() {
		users.splice(users.indexOf(myid), 1);
		if(myid==player1 || myid==player2){
			if (myid == player1) {
				player1=null;
			} else if (myid == player2) {
				player2=null;
			}
			if(chagePlayer()){
				gameStart();
			}
		}
	});

});

console.log("Listening on port " + port);
<commit_msg>refactorizando<commit_after>var express = require("express");
var app = express();
var port = 8080;

//app.set('port',process.env.PORT || 80);

app.set('view engine', "jade");
app.engine('jade', require('jade').__express);

app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(express.cookieParser());
app.use(express.session({
	secret : 'this is a secret'
}));

//app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());

app.use(express.methodOverride());

app.get("/", function(req, res) {
	res.render("index");
});

var io = require('socket.io').listen(app.listen(port,"0.0.0.0"));
io.set('log level', 1);
io.set('transports', ['websocket']);

var FPS = 30;
var W = 1000;
var H = 500;
var KEY_UP = 38;
var KEY_DOWN = 40;
var TOP = 0;
var LEFT = 1;
var BOT = 2;
var RIGHT = 3;
var STARTED = 1;
var STOPPED = 0;

var Actor = (function(x, y, w, h, vx, vy) {
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.vx = vx;
	this.vy = vy;
});

var Paddle = (function(x, y, w, h, vx, vy) {
	Actor.call(this, x, y, w, h, vx, vy);
	this.points = 0;
	this.dir=0;

	this.lastKey=(function(key){
		this.dir=key;
	});

	this.move = (function() {
		switch(this.dir) {
			case KEY_UP:
				if (this.y > 0) {
					this.y -= this.vy;
				}
				break;
			case KEY_DOWN:
				if ((this.y + this.h) < H) {
					this.y += this.vy;
				}
				break;
			default:

		}
		this.dir=0;
	});
});
Paddle.prototype = new Actor();

var Ball = (function(x, y, w, h, vx, vy, angle) {
	Actor.call(this, x, y, w, h, vx, vy);
	// en radianes
	this.angle = angle;

	this.move = (function() {
		var vyt = (this.vy * Math.sin(this.angle));
		var vxt = (this.vx * Math.cos(this.angle));
		this.x += vxt;
		this.y -= vyt;
	});

	this.collide = (function(pos) {
		switch(pos) {
			case TOP:
				this.angle = -this.angle;
				break;
			case LEFT:
				if (this.angle>0){
					this.angle -= Math.PI / 2;
				}else{
					this.angle += Math.PI / 2;
				}
				break;
			case BOT:
				this.angle= -this.angle;
				break;
			case RIGHT:
				if (this.angle>0){
					this.angle += Math.PI / 2;
				}else{
					this.angle -= Math.PI / 2;
				}
				break;
		}
	});

	this.resetBall= (function (dir) {
		b.x = W / 2 - b.w / 2;
		b.y = H / 2 - b.h / 2;
		if(dir==LEFT){
			b.angle=-Math.PI/4;
		}else{
			b.angle=(Math.PI/4)*3;
		}
	});
});
Ball.prototype = new Actor();

var gameStatus=STOPPED;
var interval;

var paddleW = 15;
var paddleH = 100;
var ballDiam = 20;

var p1 = new Paddle(10 					, H/2-paddleH/2 , paddleW , paddleH , 0 , 20 );
var p2 = new Paddle(W-10-paddleW		, H/2-paddleH/2 , paddleW , paddleH , 0 , 20 );
var b  = new Ball  (W / 2 - ballDiam/2	, H/2-ballDiam/2, ballDiam, ballDiam, 10, 10, -Math.PI/4);

var player1 = null;
var player2 = null;
var users = [];

function collides(a, b) {
    return !(
        ((a.y + a.h) < (b.y)) ||
        (a.y > (b.y + b.h)) ||
        ((a.x + a.w) < b.x) ||
        (a.x > (b.x + b.w))
    );
}

function checkCollisions() {
	//goles
	if ((b.x + b.w) < 0) {
		b.resetBall(LEFT);
		p2.points++;
	}

	if (b.x > W) {
		b.resetBall(RIGHT);
		p1.points++;
	}

	//colisiones
	if (b.y <= 0) {
		b.collide(TOP);
	}
	if ((b.y + b.h) >= H) {
		b.collide(BOT);
	}

	//colision con palas
	if (collides(p1, b)) {
		b.collide(LEFT);
	}

	if (collides(p2, b)) {
		b.collide(RIGHT);
	}
}

function gameStart() {
	interval = setInterval(update, 1000 / FPS);
	gameStatus=STARTED;
}

function gameStop() {
	clearInterval(interval);
	gameStatus=STOPPED;
}

function gameReset() {
	b.resetBall();
	p1.points = 0;
	p2.points = 0;
}

function chagePlayer(){
	for (var i = 0; i < users.length; ++i){
		if(users[i]!=player1 && users[i]!=player2){
			if(player1==null){
				player1=users[i];
				return true;
			}else if(player2==null){
				player2=users[i];
				return true;
			}
		}
	}
	return false;
}

function update() {
	p1.move();
	p2.move();
	b.move();
	checkCollisions();
	io.sockets.emit('draw', {
		'p1' : p1,
		'p2' : p2,
		'ball' : b
	});
}

var playerIDCounter = 0;
//var game=require('./game.js');

io.sockets.on('connection', function(socket) {
	//socket.set('id',playerIDCounter);
	//console.log(socket);
	var myid = playerIDCounter;

	playerIDCounter++;

	console.log("Mi ide es: " + myid);
	socket.on('adduser', function() {
		users.push(myid);
		if(gameStatus==STOPPED /*player1==null || player2==null*/){
			chagePlayer();
		}

		if (gameStatus==STOPPED && player1!=null && player2!=null) {
			gameStart();
		}
	});

	socket.emit('initData', {
		'width' : W,
		'height' : H,
		'p1' : p1,
		'p2' : p2,
		'ball' : b
	});

	socket.on('keypress', function(data) {
		if (myid == player1) {
			p1.lastKey((data.key));
		} else if (myid == player2) {
			p2.lastKey((data.key));
		}
	});

	socket.on('disconnect', function() {
		users.splice(users.indexOf(myid), 1);
		if(myid==player1 || myid==player2){
			gameStop();
			gameReset();

			if (myid == player1) {
				player1=null;
			} else if (myid == player2) {
				player2=null;
			}
			if(chagePlayer()){
				gameStart();
			}
		}
	});

});

console.log("Listening on port " + port);
<|endoftext|>


<commit_before>/**
 * Blockly Apps: Puzzle
 *
 * Copyright 2013 Google Inc.
 * http://blockly.googlecode.com/
 *
 * 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.
 */

/**
 * @fileoverview JavaScript for Blockly's Puzzle application.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

/**
 * Create a namespace for the application.
 */
var Puzzle = {};

// Supported languages.
BlocklyApps.LANGUAGES = {
  // Format: ['Language name', 'direction', 'XX_compressed.js']
  af: ['Afrikaans', 'ltr', 'en_compressed.js'],
  ar: ['العربية', 'rtl', 'en_compressed.js'],
  cs: ['Česky', 'ltr', 'en_compressed.js'],
  'be-tarask': ['Taraškievica', 'ltr', 'en_compressed.js'],
  br: ['Brezhoneg', 'ltr', 'en_compressed.js'],
  ca: ['Català', 'ltr', 'en_compressed.js'],
  cdo: ['閩東語', 'ltr', 'zh_tw_compressed.js'],
  da: ['Dansk', 'ltr', 'en_compressed.js'],
  de: ['Deutsch', 'ltr', 'de_compressed.js'],
  el: ['Ελληνικά', 'ltr', 'en_compressed.js'],
  en: ['English', 'ltr', 'en_compressed.js'],
  eu: ['Euskara', 'ltr', 'en_compressed.js'],
  fa: ['یسراف', 'rtl', 'en_compressed.js'],
  fi: ['Suomi', 'ltr', 'en_compressed.js'],
  fo: ['Føroyskt', 'ltr', 'en_compressed.js'],
  fr: ['Français', 'ltr', 'en_compressed.js'],
  frr: ['Frasch', 'ltr', 'de_compressed.js'],
  gl: ['Galego', 'ltr', 'en_compressed.js'],
  hak: ['客家話', 'ltr', 'en_compressed.js'],
  he: ['עברית', 'rtl', 'en_compressed.js'],
  hu: ['Magyar', 'ltr', 'en_compressed.js'],
  ia: ['Interlingua', 'ltr', 'en_compressed.js'],
  it: ['Italiano', 'ltr', 'en_compressed.js'],
  ja: ['日本語', 'ltr', 'en_compressed.js'],
  ka: ['ქართული', 'ltr', 'en_compressed.js'],
  km: ['ភាសាខ្មែរ', 'ltr', 'en_compressed.js'],
  ko: ['한국어', 'ltr', 'en_compressed.js'],
  ksh: ['Ripoarėsch', 'ltr', 'de_compressed.js'],
  ky: ['Кыргызча', 'ltr', 'en_compressed.js'],
  la: ['Latine', 'ltr', 'en_compressed.js'],
  lb: ['Lëtzebuergesch', 'ltr', 'de_compressed.js'],
  lt: ['Lietuvių', 'ltr', 'en_compressed.js'],
  lv: ['Latviešu', 'ltr', 'en_compressed.js'],
  ml: ['മലയാളം', 'ltr', 'en_compressed.js'],
  mk: ['Македонски', 'ltr', 'en_compressed.js'],
  ms: ['Bahasa Melayu', 'ltr', 'en_compressed.js'],
  mzn: ['مازِرونی', 'rtl', 'en_compressed.js'],
  nb: ['Norsk Bokmål', 'ltr', 'en_compressed.js'],
  nl: ['Nederlands, Vlaams', 'ltr', 'en_compressed.js'],
  oc: ['Lenga d\'òc', 'ltr', 'en_compressed.js'],
  pa: ['पंजाबी', 'ltr', 'en_compressed.js'],
  pl: ['Polski', 'ltr', 'en_compressed.js'],
  pms: ['Piemontèis', 'ltr', 'en_compressed.js'],
  ps: ['پښتو', 'rtl', 'en_compressed.js'],
  'pt-br': ['Português', 'ltr', 'pt_br_compressed.js'],
  ru: ['Русский', 'ltr', 'en_compressed.js'],
  sk: ['Slovenčina', 'ltr', 'en_compressed.js'],
  sv: ['Svenska', 'ltr', 'en_compressed.js'],
  sw: ['Kishwahili', 'ltr', 'en_compressed.js'],
  tr: ['Türkçe', 'ltr', 'en_compressed.js'],
  uk: ['Українська', 'ltr', 'en_compressed.js'],
  vi: ['Tiếng Việt', 'ltr', 'vi_compressed.js'],
  'zh-hans': ['简体字', 'ltr', 'zh_tw_compressed.js'],
  'zh-hant': ['中文', 'ltr', 'zh_tw_compressed.js']
};
BlocklyApps.LANG = BlocklyApps.getLang();
Puzzle.RTL = BlocklyApps.LANGUAGES[BlocklyApps.LANG][1] == 'rtl';

document.write('<script type="text/javascript" src="generated/' +
               BlocklyApps.LANG + '.js"></script>\n');

/**
 * Initialize Blockly and the puzzle.  Called on page load.
 */
Puzzle.init = function() {
  BlocklyApps.init();

  Blockly.inject(document.getElementById('blockly'),
      {path: '../../',
       rtl: Puzzle.RTL,
       scrollbars: false,
       trashcan: false});

  var blocklyDiv = document.getElementById('blockly');
  var onresize = function(e) {
    blocklyDiv.style.width = (window.innerWidth - 20) + 'px';
    blocklyDiv.style.height =
        (window.innerHeight - blocklyDiv.offsetTop - 15) + 'px';
  };
  onresize();
  window.addEventListener('resize', onresize);
  Blockly.fireUiEvent(window, 'resize');

  // Add the blocks.
  if (window.sessionStorage.loadOnceBlocks) {
    var text = window.sessionStorage.loadOnceBlocks;
    delete window.sessionStorage.loadOnceBlocks;
    var xml = Blockly.Xml.textToDom(text);
    Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
  } else {
    // Create one of every block.
    var blocksCountries = [];
    var blocksFlags = [];
    var blocksCities = [];
    var i = 1;
    while (BlocklyApps.getMsgOrNull('Puzzle_country' + i)) {
      var block = new Blockly.Block(Blockly.mainWorkspace, 'country');
      block.populate(i);
      blocksCountries.push(block);
      var block = new Blockly.Block(Blockly.mainWorkspace, 'flag');
      block.populate(i);
      blocksFlags.push(block);
      var j = 1;
      while (BlocklyApps.getMsgOrNull('Puzzle_country' + i + 'City' + j)) {
        var block = new Blockly.Block(Blockly.mainWorkspace, 'city');
        block.populate(i, j);
        blocksCities.push(block);
        j++;
      }
      i++;
    }
    Puzzle.shuffle(blocksCountries);
    Puzzle.shuffle(blocksFlags);
    Puzzle.shuffle(blocksCities);
    var blocks = [].concat(blocksCountries, blocksFlags, blocksCities);
    if (Puzzle.RTL) {
      blocks.reverse();
    }
    // Initialize all the blocks.
    for (var i = 0, block; block = blocks[i]; i++) {
      block.setDeletable(false);
      block.initSvg();
      block.render();
    }
    var totalArea = 0;
    // Measure the surface area of each block.
    for (var i = 0, block; block = blocks[i]; i++) {
      var blockBox = block.svg_.getRootElement().getBBox();
      block.cached_width_ = blockBox.width;
      block.cached_height_ = blockBox.height;
      block.cached_area_ = blockBox.width * blockBox.height;
      totalArea += block.cached_area_;
    }
    // Position the blocks randomly.
    var MARGIN = 50;
    Blockly.svgResize();
    var workspaceBox = Blockly.svgSize();
    workspaceBox.width -= MARGIN;
    workspaceBox.height -= MARGIN;
    var countedArea = 0;
    for (var i = 0, block; block = blocks[i]; i++) {
      var blockBox = block.svg_.getRootElement().getBBox();
      // Spread the blocks horizontally, grouped by type.
      // Spacing is proportional to block's area.
      if (Puzzle.RTL) {
        var dx = blockBox.width +
                 (countedArea / totalArea) * workspaceBox.width;
      } else {
        var dx = (countedArea / totalArea) *
                 (workspaceBox.width - blockBox.width);
      }
      dx = Math.round(dx + Math.random() * MARGIN);
      var dy = Math.round(Math.random() *
                          (workspaceBox.height - blockBox.height));
      block.moveBy(dx, dy);
      countedArea += block.cached_area_;
    }
    Puzzle.showHelp(false);
    /**
     * HACK:
     * Chrome (v28) displays a broken image tag on any image that is also
     * shown in the help dialog.  Selecting the block fixes the problem.
     * If Chrome stops corrupting the Australian flag, delete this entire hack.
     */
    if (goog.userAgent.WEBKIT) {
      var blocks = Blockly.mainWorkspace.getAllBlocks();
      for (var i = 0, block; block = blocks[i]; i++) {
        block.select();
      }
      Blockly.selected.unselect();
    }
  }
};

if (window.location.pathname.match(/readonly.html$/)) {
  window.addEventListener('load', BlocklyApps.initReadonly);
} else {
  window.addEventListener('load', Puzzle.init);
}

/**
 * Shuffles the values in the specified array using the Fisher-Yates in-place
 * shuffle (also known as the Knuth Shuffle).
 * Runtime: O(n)
 * Based on Closure's goog.array.shuffle.
 * @param {!Array} arr The array to be shuffled.
 */
Puzzle.shuffle = function(arr) {
  for (var i = arr.length - 1; i > 0; i--) {
    // Choose a random array index in [0, i] (inclusive with i).
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
};

/**
 * Return a list of all languages.
 * @return {!Array<!Array<string>>} Array of human-readable and
 *   language-neutral tuples.
 */
Puzzle.languages = function() {
  var list = [[BlocklyApps.getMsg('Puzzle_languageChoose'), '0']];
  var i = 1;
  var lang;
  while (lang = BlocklyApps.getMsgOrNull('Puzzle_country' + i + 'Language')) {
    list[i] = [lang, String(i)];
    i++;
  }
  return list;
};

/**
 * Count and highlight the errors.
 */
Puzzle.checkAnswers = function() {
  var blocks = Blockly.mainWorkspace.getAllBlocks();
  var errors = 0;
  for (var b = 0, block; block = blocks[b]; b++) {
    if (!block.isCorrect()) {
      errors++;
      // Bring the offending block to the front.
      block.select();
    }
  }

  var graphValue = document.getElementById('graphValue');
  window.setTimeout(function() {
      graphValue.style.width =
          (100 * (blocks.length - errors) / blocks.length) + 'px';
  }, 500);

  var messages;
  if (errors == 1) {
    messages = [BlocklyApps.getMsg('Puzzle_error1'),
                BlocklyApps.getMsg('Puzzle_tryAgain')];
  } else if (errors) {
    messages = [BlocklyApps.getMsg('Puzzle_error2').replace('%1', errors),
                BlocklyApps.getMsg('Puzzle_tryAgain')];
  } else {
    messages = [BlocklyApps.getMsg('Puzzle_error0').replace(
        '%1', blocks.length)];
  }
  var textDiv = document.getElementById('answerMessage');
  textDiv.textContent = '';
  for (var i = 0; i < messages.length; i++) {
    var line = document.createElement('div');
    line.appendChild(document.createTextNode(messages[i]));
    textDiv.appendChild(line);
  }

  var content = document.getElementById('answers');
  var button = document.getElementById('checkButton');
  var style = {
    width: '25%',
    left: Puzzle.RTL ? '5%' : '70%',
    top: '5em'
  };
  BlocklyApps.showDialog(content, button, true, true, style,
      BlocklyApps.stopDialogKeyDown);
  BlocklyApps.startDialogKeyDown();
};

/**
 * Show the help pop-up.
 * @param {boolean} animate Animate the pop-up opening.
 */
Puzzle.showHelp = function(animate) {
  var help = document.getElementById('help');
  var button = document.getElementById('helpButton');
  var style = {
    width: '50%',
    left: '25%',
    top: '5em'
  };
  BlocklyApps.showDialog(help, button, animate, true, style,
      BlocklyApps.stopDialogKeyDown);
  BlocklyApps.startDialogKeyDown();
};
<commit_msg>Added Spanish to Puzzle.<commit_after>/**
 * Blockly Apps: Puzzle
 *
 * Copyright 2013 Google Inc.
 * http://blockly.googlecode.com/
 *
 * 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.
 */

/**
 * @fileoverview JavaScript for Blockly's Puzzle application.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

/**
 * Create a namespace for the application.
 */
var Puzzle = {};

// Supported languages.
BlocklyApps.LANGUAGES = {
  // Format: ['Language name', 'direction', 'XX_compressed.js']
  af: ['Afrikaans', 'ltr', 'en_compressed.js'],
  ar: ['العربية', 'rtl', 'en_compressed.js'],
  cs: ['Česky', 'ltr', 'en_compressed.js'],
  'be-tarask': ['Taraškievica', 'ltr', 'en_compressed.js'],
  br: ['Brezhoneg', 'ltr', 'en_compressed.js'],
  ca: ['Català', 'ltr', 'en_compressed.js'],
  cdo: ['閩東語', 'ltr', 'zh_tw_compressed.js'],
  da: ['Dansk', 'ltr', 'en_compressed.js'],
  de: ['Deutsch', 'ltr', 'de_compressed.js'],
  el: ['Ελληνικά', 'ltr', 'en_compressed.js'],
  en: ['English', 'ltr', 'en_compressed.js'],
  es: ['Español', 'ltr', 'en_compressed.js'],
  eu: ['Euskara', 'ltr', 'en_compressed.js'],
  fa: ['یسراف', 'rtl', 'en_compressed.js'],
  fi: ['Suomi', 'ltr', 'en_compressed.js'],
  fo: ['Føroyskt', 'ltr', 'en_compressed.js'],
  fr: ['Français', 'ltr', 'en_compressed.js'],
  frr: ['Frasch', 'ltr', 'de_compressed.js'],
  gl: ['Galego', 'ltr', 'en_compressed.js'],
  hak: ['客家話', 'ltr', 'en_compressed.js'],
  he: ['עברית', 'rtl', 'en_compressed.js'],
  hu: ['Magyar', 'ltr', 'en_compressed.js'],
  ia: ['Interlingua', 'ltr', 'en_compressed.js'],
  it: ['Italiano', 'ltr', 'en_compressed.js'],
  ja: ['日本語', 'ltr', 'en_compressed.js'],
  ka: ['ქართული', 'ltr', 'en_compressed.js'],
  km: ['ភាសាខ្មែរ', 'ltr', 'en_compressed.js'],
  ko: ['한국어', 'ltr', 'en_compressed.js'],
  ksh: ['Ripoarėsch', 'ltr', 'de_compressed.js'],
  ky: ['Кыргызча', 'ltr', 'en_compressed.js'],
  la: ['Latine', 'ltr', 'en_compressed.js'],
  lb: ['Lëtzebuergesch', 'ltr', 'de_compressed.js'],
  lt: ['Lietuvių', 'ltr', 'en_compressed.js'],
  lv: ['Latviešu', 'ltr', 'en_compressed.js'],
  ml: ['മലയാളം', 'ltr', 'en_compressed.js'],
  mk: ['Македонски', 'ltr', 'en_compressed.js'],
  ms: ['Bahasa Melayu', 'ltr', 'en_compressed.js'],
  mzn: ['مازِرونی', 'rtl', 'en_compressed.js'],
  nb: ['Norsk Bokmål', 'ltr', 'en_compressed.js'],
  nl: ['Nederlands, Vlaams', 'ltr', 'en_compressed.js'],
  oc: ['Lenga d\'òc', 'ltr', 'en_compressed.js'],
  pa: ['पंजाबी', 'ltr', 'en_compressed.js'],
  pl: ['Polski', 'ltr', 'en_compressed.js'],
  pms: ['Piemontèis', 'ltr', 'en_compressed.js'],
  ps: ['پښتو', 'rtl', 'en_compressed.js'],
  'pt-br': ['Português', 'ltr', 'pt_br_compressed.js'],
  ru: ['Русский', 'ltr', 'en_compressed.js'],
  sk: ['Slovenčina', 'ltr', 'en_compressed.js'],
  sv: ['Svenska', 'ltr', 'en_compressed.js'],
  sw: ['Kishwahili', 'ltr', 'en_compressed.js'],
  tr: ['Türkçe', 'ltr', 'en_compressed.js'],
  uk: ['Українська', 'ltr', 'en_compressed.js'],
  vi: ['Tiếng Việt', 'ltr', 'vi_compressed.js'],
  'zh-hans': ['简体字', 'ltr', 'zh_tw_compressed.js'],
  'zh-hant': ['中文', 'ltr', 'zh_tw_compressed.js']
};
BlocklyApps.LANG = BlocklyApps.getLang();
Puzzle.RTL = BlocklyApps.LANGUAGES[BlocklyApps.LANG][1] == 'rtl';

document.write('<script type="text/javascript" src="generated/' +
               BlocklyApps.LANG + '.js"></script>\n');

/**
 * Initialize Blockly and the puzzle.  Called on page load.
 */
Puzzle.init = function() {
  BlocklyApps.init();

  Blockly.inject(document.getElementById('blockly'),
      {path: '../../',
       rtl: Puzzle.RTL,
       scrollbars: false,
       trashcan: false});

  var blocklyDiv = document.getElementById('blockly');
  var onresize = function(e) {
    blocklyDiv.style.width = (window.innerWidth - 20) + 'px';
    blocklyDiv.style.height =
        (window.innerHeight - blocklyDiv.offsetTop - 15) + 'px';
  };
  onresize();
  window.addEventListener('resize', onresize);
  Blockly.fireUiEvent(window, 'resize');

  // Add the blocks.
  if (window.sessionStorage.loadOnceBlocks) {
    var text = window.sessionStorage.loadOnceBlocks;
    delete window.sessionStorage.loadOnceBlocks;
    var xml = Blockly.Xml.textToDom(text);
    Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
  } else {
    // Create one of every block.
    var blocksCountries = [];
    var blocksFlags = [];
    var blocksCities = [];
    var i = 1;
    while (BlocklyApps.getMsgOrNull('Puzzle_country' + i)) {
      var block = new Blockly.Block(Blockly.mainWorkspace, 'country');
      block.populate(i);
      blocksCountries.push(block);
      var block = new Blockly.Block(Blockly.mainWorkspace, 'flag');
      block.populate(i);
      blocksFlags.push(block);
      var j = 1;
      while (BlocklyApps.getMsgOrNull('Puzzle_country' + i + 'City' + j)) {
        var block = new Blockly.Block(Blockly.mainWorkspace, 'city');
        block.populate(i, j);
        blocksCities.push(block);
        j++;
      }
      i++;
    }
    Puzzle.shuffle(blocksCountries);
    Puzzle.shuffle(blocksFlags);
    Puzzle.shuffle(blocksCities);
    var blocks = [].concat(blocksCountries, blocksFlags, blocksCities);
    if (Puzzle.RTL) {
      blocks.reverse();
    }
    // Initialize all the blocks.
    for (var i = 0, block; block = blocks[i]; i++) {
      block.setDeletable(false);
      block.initSvg();
      block.render();
    }
    var totalArea = 0;
    // Measure the surface area of each block.
    for (var i = 0, block; block = blocks[i]; i++) {
      var blockBox = block.svg_.getRootElement().getBBox();
      block.cached_width_ = blockBox.width;
      block.cached_height_ = blockBox.height;
      block.cached_area_ = blockBox.width * blockBox.height;
      totalArea += block.cached_area_;
    }
    // Position the blocks randomly.
    var MARGIN = 50;
    Blockly.svgResize();
    var workspaceBox = Blockly.svgSize();
    workspaceBox.width -= MARGIN;
    workspaceBox.height -= MARGIN;
    var countedArea = 0;
    for (var i = 0, block; block = blocks[i]; i++) {
      var blockBox = block.svg_.getRootElement().getBBox();
      // Spread the blocks horizontally, grouped by type.
      // Spacing is proportional to block's area.
      if (Puzzle.RTL) {
        var dx = blockBox.width +
                 (countedArea / totalArea) * workspaceBox.width;
      } else {
        var dx = (countedArea / totalArea) *
                 (workspaceBox.width - blockBox.width);
      }
      dx = Math.round(dx + Math.random() * MARGIN);
      var dy = Math.round(Math.random() *
                          (workspaceBox.height - blockBox.height));
      block.moveBy(dx, dy);
      countedArea += block.cached_area_;
    }
    Puzzle.showHelp(false);
    /**
     * HACK:
     * Chrome (v28) displays a broken image tag on any image that is also
     * shown in the help dialog.  Selecting the block fixes the problem.
     * If Chrome stops corrupting the Australian flag, delete this entire hack.
     */
    if (goog.userAgent.WEBKIT) {
      var blocks = Blockly.mainWorkspace.getAllBlocks();
      for (var i = 0, block; block = blocks[i]; i++) {
        block.select();
      }
      Blockly.selected.unselect();
    }
  }
};

if (window.location.pathname.match(/readonly.html$/)) {
  window.addEventListener('load', BlocklyApps.initReadonly);
} else {
  window.addEventListener('load', Puzzle.init);
}

/**
 * Shuffles the values in the specified array using the Fisher-Yates in-place
 * shuffle (also known as the Knuth Shuffle).
 * Runtime: O(n)
 * Based on Closure's goog.array.shuffle.
 * @param {!Array} arr The array to be shuffled.
 */
Puzzle.shuffle = function(arr) {
  for (var i = arr.length - 1; i > 0; i--) {
    // Choose a random array index in [0, i] (inclusive with i).
    var j = Math.floor(Math.random() * (i + 1));
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
};

/**
 * Return a list of all languages.
 * @return {!Array<!Array<string>>} Array of human-readable and
 *   language-neutral tuples.
 */
Puzzle.languages = function() {
  var list = [[BlocklyApps.getMsg('Puzzle_languageChoose'), '0']];
  var i = 1;
  var lang;
  while (lang = BlocklyApps.getMsgOrNull('Puzzle_country' + i + 'Language')) {
    list[i] = [lang, String(i)];
    i++;
  }
  return list;
};

/**
 * Count and highlight the errors.
 */
Puzzle.checkAnswers = function() {
  var blocks = Blockly.mainWorkspace.getAllBlocks();
  var errors = 0;
  for (var b = 0, block; block = blocks[b]; b++) {
    if (!block.isCorrect()) {
      errors++;
      // Bring the offending block to the front.
      block.select();
    }
  }

  var graphValue = document.getElementById('graphValue');
  window.setTimeout(function() {
      graphValue.style.width =
          (100 * (blocks.length - errors) / blocks.length) + 'px';
  }, 500);

  var messages;
  if (errors == 1) {
    messages = [BlocklyApps.getMsg('Puzzle_error1'),
                BlocklyApps.getMsg('Puzzle_tryAgain')];
  } else if (errors) {
    messages = [BlocklyApps.getMsg('Puzzle_error2').replace('%1', errors),
                BlocklyApps.getMsg('Puzzle_tryAgain')];
  } else {
    messages = [BlocklyApps.getMsg('Puzzle_error0').replace(
        '%1', blocks.length)];
  }
  var textDiv = document.getElementById('answerMessage');
  textDiv.textContent = '';
  for (var i = 0; i < messages.length; i++) {
    var line = document.createElement('div');
    line.appendChild(document.createTextNode(messages[i]));
    textDiv.appendChild(line);
  }

  var content = document.getElementById('answers');
  var button = document.getElementById('checkButton');
  var style = {
    width: '25%',
    left: Puzzle.RTL ? '5%' : '70%',
    top: '5em'
  };
  BlocklyApps.showDialog(content, button, true, true, style,
      BlocklyApps.stopDialogKeyDown);
  BlocklyApps.startDialogKeyDown();
};

/**
 * Show the help pop-up.
 * @param {boolean} animate Animate the pop-up opening.
 */
Puzzle.showHelp = function(animate) {
  var help = document.getElementById('help');
  var button = document.getElementById('helpButton');
  var style = {
    width: '50%',
    left: '25%',
    top: '5em'
  };
  BlocklyApps.showDialog(help, button, animate, true, style,
      BlocklyApps.stopDialogKeyDown);
  BlocklyApps.startDialogKeyDown();
};
<|endoftext|>


<commit_before>// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

let webview = document.getElementById('webcontent');
let body = document.getElementsByTagName('body')[0];

const {screen, remote} = require('electron');
const {Menu, MenuItem} = remote;
const _ = require('lodash');

const globalSettings = remote.getCurrentWindow().globalSettings;
const displaySettings = remote.getCurrentWindow().display;
console.log('globalSettings', globalSettings, 'displaySettings', displaySettings);

window.addEventListener('load', function() {
  displayInfoPage(`Loading..`, `Please wait while the page is initially loaded.`);
  setDefaultPosition();
  webview.src = displaySettings.url;
});

webview.addEventListener('did-fail-load',   function(event, errorCode, errorDescription, validatedURL, isMainFrame) {
  console.log('did-fail-load', {
    event:event,
    errorCode:errorCode,
    errorDescription:errorDescription,
    validatedURL:validatedURL,
    isMainFrame:isMainFrame});

  lastHttpResponse = null;
  displayInfoPage(`Error`, `Page failed to load: ${errorDescription} (${errorCode})`);

  setTimeout(function() {
    webview.src = displaySettings.url;
  }, globalSettings.failureRetryTime);
});

webview.addEventListener('did-get-response-details', function(details) {
  console.log('did-get-response-details', details);

  hideInfo();

  if (details.httpResponseCode < 200 || details.httpResponseCode >= 300)
  {
    console.log(`last response code is ${details.httpResponseCode}, re-loading URL ${displaySettings.url}`);
    // TODO: display overlay message

    setTimeout(function() {
      webview.src = displaySettings.url;
    }, globalSettings.nonSuccessRetryTime);
  }
});
webview.addEventListener('crashed', function() {
  console.log('crashed');
});

const menu = Menu.buildFromTemplate([
  {
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click (item, focusedWindow) {
      if (focusedWindow) focusedWindow.reload()
    }
  },
  {type: 'separator'},
  {
    label: "Move to display",
    submenu: _.map(screen.getAllDisplays(), function(display,index) {
      return {
        label: `Display ${index+1}`,
        click: function() { moveToDisplay(index) },
      };
    })
  },
  {
    label: 'Toggle Fullscreen',
    accelerator: 'F11',
    click (item, focusedWindow) {
      focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
    }
  },
  {
    label: 'Reset to configured position',
    click (item, focusedWindow) {
      setDefaultPosition();
    }
  },
  {
    label: 'Toggle Developer Tools',
    accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
    click (item, focusedWindow) {
      if (focusedWindow) focusedWindow.webContents.toggleDevTools()
    }
  },
  {type: 'separator'},
  {
    label:'Close Window',
    accelerator: 'Alt+F4',
    role:'close'
  },
  {
    label:'Exit',
    click (item, focusedWindow) {
      remote.getCurrentWindow().exit();
    }
  }
]);

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  menu.popup(remote.getCurrentWindow())
}, false)

function displayInfoPage(header, details)
{
    body.className = 'info';
    document.getElementById('infoTitle').innerHTML = header;
    document.getElementById('infoText').innerHTML = details;
}
function hideInfo()
{
    body.className = '';
}

function moveToDisplay(displayIndex)
{
  setPosition(displayIndex, null, null);
}

function setDefaultPosition() {
  setPosition(displaySettings.screen - 1, displaySettings.position, displaySettings.size);
}

function setPosition(displayIndex, position, size) {
  let displays = screen.getAllDisplays();
  let thisWindow = remote.getCurrentWindow();

  let displayBasePosition = [displays[displayIndex].workArea.x, displays[displayIndex].workArea.y];
  let currentPosition = thisWindow.getPosition();

  // preserve fullscreen
  if (size == null && thisWindow.isFullScreen()) {
    size = 'fullscreen';
  }
  // preserve offset on display, if not specified
  if (position == null) {
    // get current offset on current display
    let currentDisplay = screen.getDisplayNearestPoint({x:currentPosition[0], y:currentPosition[1]});
    position = [currentPosition[0] - currentDisplay.workArea.x, currentPosition[1] - currentDisplay.workArea.y];
  }

  if (position == 'fullscreen' || size == 'fullscreen') {
    // if not currently fullscreen, or x or y position is wrong (wrong display), move to proper screen
    if (!thisWindow.isFullScreen() || (currentPosition[0] != displayBasePosition[0]) || (currentPosition[1] != displayBasePosition[1])) {
      thisWindow.setFullScreen(false); // must be non-fullscreen to move screens
      thisWindow.setPosition(displayBasePosition[0], displayBasePosition[1]);
      thisWindow.setFullScreen(true);
    }
  } else {
    thisWindow.setFullScreen(false);

    if (size != null) thisWindow.setSize(size[0], size[1]);

    let targetX = displayBasePosition[0] + position[0];
    let targetY = displayBasePosition[1] + position[1];
    // todo check within bounds of display
    thisWindow.setPosition(targetX,targetY);

  }

}<commit_msg>#10: Fix error if display property is not defined<commit_after>// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.

let webview = document.getElementById('webcontent');
let body = document.getElementsByTagName('body')[0];

const {screen, remote} = require('electron');
const {Menu, MenuItem} = remote;
const _ = require('lodash');

const globalSettings = remote.getCurrentWindow().globalSettings;
const displaySettings = remote.getCurrentWindow().display;
console.log('globalSettings', globalSettings, 'displaySettings', displaySettings);

window.addEventListener('load', function() {
  displayInfoPage(`Loading..`, `Please wait while the page is initially loaded.`);
  setDefaultPosition();
  webview.src = displaySettings.url;
});

webview.addEventListener('did-fail-load',   function(event, errorCode, errorDescription, validatedURL, isMainFrame) {
  console.log('did-fail-load', {
    event:event,
    errorCode:errorCode,
    errorDescription:errorDescription,
    validatedURL:validatedURL,
    isMainFrame:isMainFrame});

  lastHttpResponse = null;
  displayInfoPage(`Error`, `Page failed to load: ${errorDescription} (${errorCode})`);

  setTimeout(function() {
    webview.src = displaySettings.url;
  }, globalSettings.failureRetryTime);
});

webview.addEventListener('did-get-response-details', function(details) {
  console.log('did-get-response-details', details);

  hideInfo();

  if (details.httpResponseCode < 200 || details.httpResponseCode >= 300)
  {
    console.log(`last response code is ${details.httpResponseCode}, re-loading URL ${displaySettings.url}`);
    // TODO: display overlay message

    setTimeout(function() {
      webview.src = displaySettings.url;
    }, globalSettings.nonSuccessRetryTime);
  }
});
webview.addEventListener('crashed', function() {
  console.log('crashed');
});

const menu = Menu.buildFromTemplate([
  {
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click (item, focusedWindow) {
      if (focusedWindow) focusedWindow.reload()
    }
  },
  {type: 'separator'},
  {
    label: "Move to display",
    submenu: _.map(screen.getAllDisplays(), function(display,index) {
      return {
        label: `Display ${index+1}`,
        click: function() { moveToDisplay(index) },
      };
    })
  },
  {
    label: 'Toggle Fullscreen',
    accelerator: 'F11',
    click (item, focusedWindow) {
      focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
    }
  },
  {
    label: 'Reset to configured position',
    click (item, focusedWindow) {
      setDefaultPosition();
    }
  },
  {
    label: 'Toggle Developer Tools',
    accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
    click (item, focusedWindow) {
      if (focusedWindow) focusedWindow.webContents.toggleDevTools()
    }
  },
  {type: 'separator'},
  {
    label:'Close Window',
    accelerator: 'Alt+F4',
    role:'close'
  },
  {
    label:'Exit',
    click (item, focusedWindow) {
      remote.getCurrentWindow().exit();
    }
  }
]);

window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  menu.popup(remote.getCurrentWindow())
}, false)

function displayInfoPage(header, details)
{
    body.className = 'info';
    document.getElementById('infoTitle').innerHTML = header;
    document.getElementById('infoText').innerHTML = details;
}
function hideInfo()
{
    body.className = '';
}

function moveToDisplay(displayIndex)
{
  setPosition(displayIndex, null, null);
}

function setDefaultPosition() {
  setPosition(displaySettings.screen - 1, displaySettings.position, displaySettings.size);
}

function setPosition(displayIndex, position, size) {
  let displays = screen.getAllDisplays();
  let thisWindow = remote.getCurrentWindow();

  if (!displayIndex) displayIndex = 0;
  let displayBasePosition = [displays[displayIndex].workArea.x, displays[displayIndex].workArea.y];
  let currentPosition = thisWindow.getPosition();

  // preserve fullscreen
  if (size == null && thisWindow.isFullScreen()) {
    size = 'fullscreen';
  }
  // preserve offset on display, if not specified
  if (position == null) {
    // get current offset on current display
    let currentDisplay = screen.getDisplayNearestPoint({x:currentPosition[0], y:currentPosition[1]});
    position = [currentPosition[0] - currentDisplay.workArea.x, currentPosition[1] - currentDisplay.workArea.y];
  }

  if (position == 'fullscreen' || size == 'fullscreen') {
    // if not currently fullscreen, or x or y position is wrong (wrong display), move to proper screen
    if (!thisWindow.isFullScreen() || (currentPosition[0] != displayBasePosition[0]) || (currentPosition[1] != displayBasePosition[1])) {
      thisWindow.setFullScreen(false); // must be non-fullscreen to move screens
      thisWindow.setPosition(displayBasePosition[0], displayBasePosition[1]);
      thisWindow.setFullScreen(true);
    }
  } else {
    thisWindow.setFullScreen(false);

    if (size != null) thisWindow.setSize(size[0], size[1]);

    let targetX = displayBasePosition[0] + position[0];
    let targetY = displayBasePosition[1] + position[1];
    // todo check within bounds of display
    thisWindow.setPosition(targetX,targetY);

  }

}<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var readline = require('line-input-stream');
var exec = require('child_process').exec;
var args = process.argv.slice(2);
var colors = require('colors');
var verbose = false;
if (args[1] === 'verbose' || args[2] === 'verbose') {
  verbose = true;
}
var Replacer = module.exports = function Replacer(file, options) {
  var module = {},
          searches = [],
          seds = [];
  /*
   * Add string for the replace
   *
   * @param string search
   * @param string replace
   */
  module.add = function(search, replace) {
    searches.push({search: search, replace: replace});
  };

  /*
   * Remove the string with a blank line
   *
   * @param string search
   */
  module.rm = function(search) {
    searches.push({search: search, replace: ''});
  };

  /*
   * The rows for sed
   *
   * @param number _start
   * @param number _end
   */
  module.addsed = function(_start, _end) {
    seds.push({start: _start, end: _end});
  };

  module.file = file;

  Base replacements
  module.add(/plugin-name/g, options.pluginSlug);
  module.add(/Plugin_Name_Admin/g, options.pluginClassName + '_Admin');
  module.add(/Plugin_Name/g, options.pluginClassName);
  module.add(/Plugin Name\./g, options.pluginName);
  module.add(/Your Name <email@example\.com>/g, options.author + ' <' + options.authorEmail + '>');
  module.add(/1\.0\.0/g, options.pluginVersion);
  module.add(/Your Name or Company Name/g, options.pluginCopyright);
  module.add(new RegExp('http://example.com', 'g'), options.authorURI);
  module.add(/pn_/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_');
  module.add(/pn-/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '-');

  /*
   * Replace the strings
   *
   */
  module.replace = function() {
    fs.exists(file, function(exists) {
      if (exists) {
        fs.readFile(file, 'utf8', function(err, data) {
          var i, total;
          if (err) {
            return console.log(err);
          }

          total = searches.length;
          for (i = 0; i < total; i += 1) {
            data = data.replace(searches[i].search, searches[i].replace);
          }

          fs.writeFile(file, data, 'utf8', function(err) {
            if (err) {
              return console.log((err).red);
            }
            if(verbose){
              console.log(('Replace ' + file).italic);
            }
          });
        });
      }
    });
  };

  /*
   * Search the block of rows for sed
   *
   * @param number start
   * @param number end
   * @param number count_initial
   * @param number count_end
   */
  module.rmsearch = function(start, end, count_initial, count_end) {
    var stream, _start, _end;
    var i = -1;
    start = start.replace(/ /g, '');
    end = end.replace(/ /g, '');
    fs.exists(file, function(exists) {
      if (exists) {
        stream = readline(fs.createReadStream(file, {flags: 'r'}));
        stream.setDelimiter("\n");

        //start reading the file
        stream.on('line', function(line) {
          i++;
          line = line.replace(/(\r\n|\n|\r|\t)/gm, '').replace(/ /g, '');

          if (line === start) {
            _start = i - count_initial;
            if (!end.length) {
              _end = i + count_end;
            }
          } else if (line === end && end && (i - count_end > _start)) {
            _end = i - count_end;
          }
        });

        stream.on("end", function() {
          if (typeof _start === 'undefined') {
            console.log(('Not found start line in ' + file + ': ' + _start).red);
          }

          if (typeof _end === 'undefined') {
            console.log(('Not found end line in ' + file + ': ' + _end).red);
          }

          if (_start > _end) {
            console.log(('Problem when parsing ' + file).red);
          }

          module.addsed(_start, _end);
        });
      }
    });
  };

  /*
   * Call sed command and replace method
   *
   */
  module.sed = function() {
    fs.exists(process.cwd() + '/' + file, function(exists) {
      if (exists) {
        if (seds.length !== 0) {
          var total = seds.length;
          var line = '';
          var i;

          for (i = 0; i < total; i += 1) {
            line += seds[i].start + ',' + seds[i].end + "d;";
          }

          exec("sed -i '" + line + "' " + process.cwd() + '/' + file, {cwd: process.cwd() + '/'},
          function(err, stdout, stderr) {
            if (stderr.length > 0) {
              console.log(('stderr: ' + stderr).red);
            }
            if (err !== null) {
              console.log(('exec error: ' + err).red);
            }
            if(verbose){
              console.log(('Sed ' + file).italic);
            }
            module.replace();
          });
        } else {
          module.replace();
        }
      }
    });
  };

  return module;
};<commit_msg>replace with blank lines? fixed<commit_after>'use strict';

var fs = require('fs');
var readline = require('line-input-stream');
var exec = require('child_process').exec;
var args = process.argv.slice(2);
var colors = require('colors');
var verbose = false;
if (args[1] === 'verbose' || args[2] === 'verbose') {
  verbose = true;
}
var Replacer = module.exports = function Replacer(file, options) {
  var module = {},
          searches = [],
          seds = [];
  /*
   * Add string for the replace
   *
   * @param string search
   * @param string replace
   */
  module.add = function(search, replace) {
    searches.push({search: search, replace: replace});
  };

  /*
   * Remove the string with a blank line
   *
   * @param string search
   */
  module.rm = function(search) {
    searches.push({search: search + "\r\n", replace: ''});
  };

  /*
   * The rows for sed
   *
   * @param number _start
   * @param number _end
   */
  module.addsed = function(_start, _end) {
    seds.push({start: _start, end: _end});
  };

  module.file = file;

  //Base replacements
  module.add(/plugin-name/g, options.pluginSlug);
  module.add(/Plugin_Name_Admin/g, options.pluginClassName + '_Admin');
  module.add(/Plugin_Name/g, options.pluginClassName);
  module.add(/Plugin Name\./g, options.pluginName);
  module.add(/Your Name <email@example\.com>/g, options.author + ' <' + options.authorEmail + '>');
  module.add(/1\.0\.0/g, options.pluginVersion);
  module.add(/Your Name or Company Name/g, options.pluginCopyright);
  module.add(new RegExp('http://example.com', 'g'), options.authorURI);
  module.add(/pn_/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '_');
  module.add(/pn-/g, options.pluginName.match(/\b(\w)/g).join('').toLowerCase() + '-');

  /*
   * Replace the strings
   *
   */
  module.replace = function() {
    fs.exists(file, function(exists) {
      if (exists) {
        fs.readFile(file, 'utf8', function(err, data) {
          var i, total;
          if (err) {
            return console.log(err);
          }

          total = searches.length;
          for (i = 0; i < total; i += 1) {
            data = data.replace(searches[i].search, searches[i].replace);
          }

          fs.writeFile(file, data, 'utf8', function(err) {
            if (err) {
              return console.log((err).red);
            }
            if(verbose){
              console.log(('Replace ' + file).italic);
            }
          });
        });
      }
    });
  };

  /*
   * Search the block of rows for sed
   *
   * @param number start
   * @param number end
   * @param number count_initial
   * @param number count_end
   */
  module.rmsearch = function(start, end, count_initial, count_end) {
    var stream, _start, _end;
    var i = -1;
    start = start.replace(/ /g, '');
    end = end.replace(/ /g, '');
    fs.exists(file, function(exists) {
      if (exists) {
        stream = readline(fs.createReadStream(file, {flags: 'r'}));
        stream.setDelimiter("\n");

        //start reading the file
        stream.on('line', function(line) {
          i++;
          line = line.replace(/(\r\n|\n|\r|\t)/gm, '').replace(/ /g, '');

          if (line === start) {
            _start = i - count_initial;
            if (!end.length) {
              _end = i + count_end;
            }
          } else if (line === end && end && (i - count_end > _start)) {
            _end = i - count_end;
          }
        });

        stream.on("end", function() {
          if (typeof _start === 'undefined') {
            console.log(('Not found start line in ' + file + ': ' + _start).red);
          }

          if (typeof _end === 'undefined') {
            console.log(('Not found end line in ' + file + ': ' + _end).red);
          }

          if (_start > _end) {
            console.log(('Problem when parsing ' + file).red);
          }

          module.addsed(_start, _end);
        });
      }
    });
  };

  /*
   * Call sed command and replace method
   *
   */
  module.sed = function() {
    fs.exists(process.cwd() + '/' + file, function(exists) {
      if (exists) {
        if (seds.length !== 0) {
          var total = seds.length;
          var line = '';
          var i;

          for (i = 0; i < total; i += 1) {
            line += seds[i].start + ',' + seds[i].end + "d;";
          }

          exec("sed -i '" + line + "' " + process.cwd() + '/' + file, {cwd: process.cwd() + '/'},
          function(err, stdout, stderr) {
            if (stderr.length > 0) {
              console.log(('stderr: ' + stderr).red);
            }
            if (err !== null) {
              console.log(('exec error: ' + err).red);
            }
            if(verbose){
              console.log(('Sed ' + file).italic);
            }
            module.replace();
          });
        } else {
          module.replace();
        }
      }
    });
  };

  return module;
};<|endoftext|>


<commit_before>'use strict';
import fs from 'fs-extra';
import Promise from 'bluebird';

import S3, { bucket } from './';
import { removeObject, putObjectFromFile, listObjects, emptyBucket, putObject } from './structure';

const readFile = Promise.promisify(fs.readFile);

export function getPresignedUrl (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.presignedPutObject(bucket, file, 24 * 60 * 60, (err, presignedUrl) => {
      if (err) {
        return reject(err);
      }
      return resolve(presignedUrl);
    });
  });
}

// Proxy of removeObject function, assuming the bucket.
export function removeFile (file) {
  return removeObject(bucket, file);
}

// Proxy of emptyBucket function, assuming the bucket.
export function removeDir (dir) {
  return emptyBucket(bucket, dir);
}

// Get file.
export function getFile (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.getObject(bucket, file, (err, dataStream) => {
      if (err) {
        return reject(err);
      }
      return resolve(dataStream);
    });
  });
}

// Get s3 file to file.
export function fGetFile (file, dest) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.fGetObject(bucket, file, dest, (err) => {
      if (err) {
        return reject(err);
      }
      return resolve(dest);
    });
  });
}

// Copy file.
export function copyFile (oldFile, newFile) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.copyObject(bucket, newFile, `${bucket}/${oldFile}`, null, (err, data) => {
      if (err) {
        return reject(err);
      }
      return resolve();
    });
  });
}

// File stats.
export function getFileInfo (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.statObject(bucket, file, (err, stat) => {
      if (err) {
        return reject(err);
      }
      return resolve(stat);
    });
  });
}

// Copy directory.
export async function copyDirectory (sourceDir, destDir) {
  const files = await listFiles(sourceDir);
  return Promise.map(files, file => {
    const newName = file.name.replace(sourceDir, destDir);
    return copyFile(file.name, newName);
  }, { concurrency: 10 });
}

// Get file content.
export function getFileContents (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.getObject(bucket, file, (err, dataStream) => {
      if (err) return reject(err);

      var data = '';
      dataStream.on('data', chunk => (data += chunk));
      dataStream.on('end', () => resolve(data));
      dataStream.on('error', () => reject(err));
    });
  });
}

// Get file content in JSON.
export async function getJSONFileContents (file) {
  const result = await getFileContents(file);
  return JSON.parse(result);
}

// Put object
// Proxy of putObject function, assuming the bucket.
export function putFileStream (file, stream) {
  return putObject(bucket, file, stream);
}

// Put file
// Proxy of putObjectFromFile function, assuming the bucket.
export function putFile (name, filepath) {
  return putObjectFromFile(bucket, name, filepath);
}

// List files
// Proxy of listObjects function, assuming the bucket.
export function listFiles (namePrefix) {
  return listObjects(bucket, namePrefix);
}

// Put directory
export function putDirectory (sourceDir, destDir) {
  let files = getLocalFilesInDir(sourceDir);
  return Promise.map(files, file => {
    let newName = file.replace(sourceDir, destDir);
    return putFile(newName, file);
  }, { concurrency: 10 });
}

// Local file operation.

export function removeLocalFile (path, quiet = false) {
  return new Promise((resolve, reject) => {
    fs.unlink(path, err => {
      if (err && !quiet) {
        return reject(err);
      }
      return resolve();
    });
  });
}

export async function getLocalFileContents (path) {
  const data = await readFile(path, 'utf8');

  // https://github.com/sindresorhus/strip-bom
  // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
  // conversion translates it to FEFF (UTF-16 BOM)
  return data.charCodeAt(0) === 0xFEFF ? data.slice(1) : data;
}

export async function getLocalJSONFileContents (path) {
  const result = await getLocalFileContents(path);
  return JSON.parse(result);
}

export async function getLocalFilesInDir (dir) {
  const files = await fs.readdir(dir);

  return files.reduce((acc, file) => {
    let name = dir + '/' + file;
    if (fs.statSync(name).isDirectory()) {
      acc = acc.concat(getLocalFilesInDir(name));
    } else {
      acc.push(name);
    }

    return acc;
  }, []);
}
<commit_msg>Convert getLocalFilesInDir to async<commit_after>'use strict';
import fs from 'fs-extra';
import Promise from 'bluebird';

import S3, { bucket } from './';
import { removeObject, putObjectFromFile, listObjects, emptyBucket, putObject } from './structure';

const readFile = Promise.promisify(fs.readFile);

export function getPresignedUrl (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.presignedPutObject(bucket, file, 24 * 60 * 60, (err, presignedUrl) => {
      if (err) {
        return reject(err);
      }
      return resolve(presignedUrl);
    });
  });
}

// Proxy of removeObject function, assuming the bucket.
export function removeFile (file) {
  return removeObject(bucket, file);
}

// Proxy of emptyBucket function, assuming the bucket.
export function removeDir (dir) {
  return emptyBucket(bucket, dir);
}

// Get file.
export function getFile (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.getObject(bucket, file, (err, dataStream) => {
      if (err) {
        return reject(err);
      }
      return resolve(dataStream);
    });
  });
}

// Get s3 file to file.
export function fGetFile (file, dest) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.fGetObject(bucket, file, dest, (err) => {
      if (err) {
        return reject(err);
      }
      return resolve(dest);
    });
  });
}

// Copy file.
export function copyFile (oldFile, newFile) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.copyObject(bucket, newFile, `${bucket}/${oldFile}`, null, (err, data) => {
      if (err) {
        return reject(err);
      }
      return resolve();
    });
  });
}

// File stats.
export function getFileInfo (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.statObject(bucket, file, (err, stat) => {
      if (err) {
        return reject(err);
      }
      return resolve(stat);
    });
  });
}

// Copy directory.
export async function copyDirectory (sourceDir, destDir) {
  const files = await listFiles(sourceDir);
  return Promise.map(files, file => {
    const newName = file.name.replace(sourceDir, destDir);
    return copyFile(file.name, newName);
  }, { concurrency: 10 });
}

// Get file content.
export function getFileContents (file) {
  return new Promise(async (resolve, reject) => {
    const s3 = await S3();
    s3.getObject(bucket, file, (err, dataStream) => {
      if (err) return reject(err);

      var data = '';
      dataStream.on('data', chunk => (data += chunk));
      dataStream.on('end', () => resolve(data));
      dataStream.on('error', () => reject(err));
    });
  });
}

// Get file content in JSON.
export async function getJSONFileContents (file) {
  const result = await getFileContents(file);
  return JSON.parse(result);
}

// Put object
// Proxy of putObject function, assuming the bucket.
export function putFileStream (file, stream) {
  return putObject(bucket, file, stream);
}

// Put file
// Proxy of putObjectFromFile function, assuming the bucket.
export function putFile (name, filepath) {
  return putObjectFromFile(bucket, name, filepath);
}

// List files
// Proxy of listObjects function, assuming the bucket.
export function listFiles (namePrefix) {
  return listObjects(bucket, namePrefix);
}

// Put directory
export async function putDirectory (sourceDir, destDir) {
  let files = await getLocalFilesInDir(sourceDir);
  return Promise.map(files, file => {
    let newName = file.replace(sourceDir, destDir);
    return putFile(newName, file);
  }, { concurrency: 10 });
}

// Local file operation.

export function removeLocalFile (path, quiet = false) {
  return new Promise((resolve, reject) => {
    fs.unlink(path, err => {
      if (err && !quiet) {
        return reject(err);
      }
      return resolve();
    });
  });
}

export async function getLocalFileContents (path) {
  const data = await readFile(path, 'utf8');

  // https://github.com/sindresorhus/strip-bom
  // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
  // conversion translates it to FEFF (UTF-16 BOM)
  return data.charCodeAt(0) === 0xFEFF ? data.slice(1) : data;
}

export async function getLocalJSONFileContents (path) {
  const result = await getLocalFileContents(path);
  return JSON.parse(result);
}

export async function getLocalFilesInDir (dir) {
  const files = await fs.readdir(dir);

  return Promise.reduce(files, async (acc, file) => {
    const name = dir + '/' + file;
    const stats = await fs.stat(name);

    return stats.isDirectory()
      ? acc.concat(await getLocalFilesInDir(name))
      : acc.concat(name);
  }, []);
}
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
const acorn = require('acorn-jsx/inject')(require('acorn'));

/**
 * Takes in directory name and generates an AST based on the File.
 * If it is a React Component an object is returned with the corresponding key/value pair
 * ComponentName: AST
 * @param {directory} file directory
 * @returns {Object} Object with Component name and AST
 */

function astGenerator(directory, entry) {
  // TODO: support for stateless functional components
  // using directory of component to turn into string for acorn
  const stringed = fs.readFileSync(directory, { encoding: 'utf-8' });
  const result = {};
  let name;
  let splicing;
  let found;

  // ast generation
  const ast = acorn.parse(stringed, {
    sourceType: 'module',
    plugins: { jsx: true },
  });

  function nameFinder(node) {
    if ((node.superClass.type === 'MemberExpression' && node.superClass.object.name === 'React' && node.superClass.property.name === 'Component')
     || (node.superClass.type === 'Identifier' && node.superClass.name === 'Component')) return node.id.name;
  }

//  starting backwards because export statements are likely to be at the end of a file
  // for (let i = ast.body.length - 1; i >= 0; i--) {
  //     // finding ES6 export default
  //   if (ast.body[i].type === 'ExportDefaultDeclaration') {
  //     name = ast.body[i].declaration.name || ast.body[i].declaration.id.name;
  //     if (entry) result.ENTRY = name;
  //     else result[name] = ast;
  //   } else if (ast.body[i].type === 'ExpressionStatement') {
  //     // finding CJS module.exports
  //     if (ast.body[i].expression.left && ast.body[i].expression.left.object.name === 'module') {
  //       name = ast.body[i].expression.right.name;
  //       if (entry) result.ENTRY = name;
  //       else result[name] = ast;
  //       // finding entry point
  //     } else if (ast.body[i].expression.callee && ast.body[i].expression.callee.object.name === 'ReactDOM' && ast.body[i].expression.callee.property.name === 'render') {
  //       console.log('splicing');
  //       splicing = i;
  //       name = ast.body[i].expression.arguments[0].openingElement.name.name;
  //       result.ENTRY = name;
  //       result[name] = ast;
  //     }
  //   }
  // }
  ast.body.forEach((node, i) => {
    if (node.type === 'ClassDeclaration' && node.superClass) {
      name = nameFinder(node);
      found = true;
    } else if (node.type === 'ExportDefaultDeclaration' && node.declaration.type === 'ClassDeclaration'
      && node.declaration.superClass) {
      name = nameFinder(node.declaration);
      found = true;
    } else if (node.type === 'VariableDeclaration' && node.declarations[0].init && node.declarations[0].init.callee
      && node.declarations[0].init.callee.object && node.declarations[0].init.callee.object.name === 'React'
      && node.declarations[0].init.callee.property.name === 'createClass') {
      name = node.declarations[0].id.name;
      found = true;
    } else if (node.type === 'ExpressionStatement' && node.expression.callee) {
      if ((node.expression.callee.type === 'MemberExpression' && node.expression.callee.object.name === 'ReactDOM'
        && node.expression.callee.property.name === 'render') || (node.expression.callee.type === 'Identifier' && node.expression.callee.name === 'render')) {
        name = node.expression.arguments[0].openingElement.name.name;
        result.ENTRY = name;
        splicing = i;
      }
    }
  });

  if (splicing) ast.body.splice(splicing, 1);
  if (found) result[name] = ast;
  return result;
}

module.exports = astGenerator;
<commit_msg>deleted comments<commit_after>'use strict';
const fs = require('fs');
const acorn = require('acorn-jsx/inject')(require('acorn'));

/**
 * Takes in directory name and generates an AST based on the File.
 * If it is a React Component an object is returned with the corresponding key/value pair
 * ComponentName: AST
 * @param {directory} file directory
 * @returns {Object} Object with Component name and AST
 */

function astGenerator(directory, entry) {
  // TODO: support for stateless functional components
  // using directory of component to turn into string for acorn
  const stringed = fs.readFileSync(directory, { encoding: 'utf-8' });
  const result = {};
  let name;
  let splicing;
  let found;

  // ast generation
  const ast = acorn.parse(stringed, {
    sourceType: 'module',
    plugins: { jsx: true },
  });

  function nameFinder(node) {
    if ((node.superClass.type === 'MemberExpression' && node.superClass.object.name === 'React' && node.superClass.property.name === 'Component')
     || (node.superClass.type === 'Identifier' && node.superClass.name === 'Component')) return node.id.name;
  }

  ast.body.forEach((node, i) => {
    if (node.type === 'ClassDeclaration' && node.superClass) {
      name = nameFinder(node);
      found = true;
    } else if (node.type === 'ExportDefaultDeclaration' && node.declaration.type === 'ClassDeclaration'
      && node.declaration.superClass) {
      name = nameFinder(node.declaration);
      found = true;
    } else if (node.type === 'VariableDeclaration' && node.declarations[0].init && node.declarations[0].init.callee
      && node.declarations[0].init.callee.object && node.declarations[0].init.callee.object.name === 'React'
      && node.declarations[0].init.callee.property.name === 'createClass') {
      name = node.declarations[0].id.name;
      found = true;
    } else if (node.type === 'ExpressionStatement' && node.expression.callee) {
      if ((node.expression.callee.type === 'MemberExpression' && node.expression.callee.object.name === 'ReactDOM'
        && node.expression.callee.property.name === 'render') || (node.expression.callee.type === 'Identifier' && node.expression.callee.name === 'render')) {
        name = node.expression.arguments[0].openingElement.name.name;
        result.ENTRY = name;
        splicing = i;
      }
    }
  });

  if (splicing) ast.body.splice(splicing, 1);
  if (found) result[name] = ast;
  return result;
}

module.exports = astGenerator;
<|endoftext|>