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

/* Copyright 2017 Mozilla
 *
 * 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. */

'use strict';

// Polyfill Promise.prototype.finally().
require('promise.prototype.finally').shim();

const path = require('path');
const spawn = require('child_process').spawn;
const tap = require('tap');

let exitCode = 0;

const expectedOutput = `
Developer Tools - data:text/plain;charset=US-ASCII,browser-chrome
Developer Tools - data:text/plain;charset=US-ASCII,browser-content-primary
Developer Tools - data:text/plain;charset=US-ASCII,browser-content
Developer Tools - chrome://app/content/window.xul
`;

new Promise((resolve, reject) => {
  // Paths are relative to the top-level directory in which `npm test` is run.
  const child = spawn('node', [ path.join('bin', 'cli.js'), 'run', 'test/devtools/' ]);

  let totalOutput = '';

  child.stdout.on('data', data => {
    const output = data.toString('utf8');
    console.log(output.trim());
    totalOutput += output;
  });

  child.stderr.on('data', data => {
    console.error(data.toString('utf8').trim());
  });

  child.on('close', code => {
    tap.equal(totalOutput.trim(), expectedOutput.trim());
    tap.equal(code, 0, 'app exited with success code');
  });

  child.on('close', (code, signal) => {
    resolve();
  });
})
.catch(error => {
  console.error(error);
  exitCode = 1;
})
.finally(() => {
  process.exit(exitCode);
});
<commit_msg>match each output line individually<commit_after>#!/usr/bin/env node

/* Copyright 2017 Mozilla
 *
 * 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. */

'use strict';

// Polyfill Promise.prototype.finally().
require('promise.prototype.finally').shim();

const path = require('path');
const spawn = require('child_process').spawn;
const tap = require('tap');

let exitCode = 0;

const expectedOutput = [
  'Developer Tools - data:text/plain;charset=US-ASCII,browser-chrome',
  'Developer Tools - data:text/plain;charset=US-ASCII,browser-content-primary',
  'Developer Tools - data:text/plain;charset=US-ASCII,browser-content',
  'Developer Tools - chrome://app/content/window.xul',
];

new Promise((resolve, reject) => {
  // Paths are relative to the top-level directory in which `npm test` is run.
  const child = spawn('node', [ path.join('bin', 'cli.js'), 'run', 'test/devtools/' ]);

  let totalOutput = '';

  child.stdout.on('data', data => {
    const output = data.toString('utf8');
    console.log(output.trim());
    totalOutput += output;
  });

  child.stderr.on('data', data => {
    console.error(data.toString('utf8').trim());
  });

  child.on('close', code => {
    tap.true(totalOutput.indexOf(expectedOutput[0]) !== -1);
    tap.true(totalOutput.indexOf(expectedOutput[1]) !== -1);
    tap.true(totalOutput.indexOf(expectedOutput[2]) !== -1);
    tap.true(totalOutput.indexOf(expectedOutput[3]) !== -1);
    tap.equal(code, 0, 'app exited with success code');
  });

  child.on('close', (code, signal) => {
    resolve();
  });
})
.catch(error => {
  console.error(error);
  exitCode = 1;
})
.finally(() => {
  process.exit(exitCode);
});
<|endoftext|>


<commit_before>/*
Copyright 2015 Jonathon Hare / The University of Southampton

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.
*/

function initialiseVideo(sourceName, sinkName, cb) {
  gumInit();

  window.ocvl = {
    video: document.querySelector('video'),
    source: document.getElementById(sourceName).getContext('2d'),
    sink: document.getElementById(sinkName).getContext('2d'),
    process: function(input, output) {
      var x, y;
      for (y=0, i=0; y<output.height; y++) {
        for (x=0; x<output.width; x++) {
          output[y][x].r = input[y][x].r;
          output[y][x].g = input[y][x].g;
          output[y][x].b = input[y][x].b;
        }
      }
    }
  }

  // shim layer with setTimeout fallback - from Paul Irish
  window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function(callback) {
              window.setTimeout(callback, 1000 / 60);
            };
  })();

  // note: video is defined in gum.js
  ocvl.video.addEventListener('loadedmetadata', function () {
    // due to bug in Chrome: http://crbug.com/168700
    if (ocvl.video.videoWidth) {
      ocvl.source.canvas.width = ocvl.video.videoWidth;
      ocvl.source.canvas.height = ocvl.video.videoHeight;
      ocvl.sink.canvas.width = ocvl.video.videoWidth;
      ocvl.sink.canvas.height = ocvl.video.videoHeight;
    }
    draw();
    cb();
    ocvl.sourceframes = 0;
    ocvl.sinkframes = 0;
    ocvl.lsourceframes = 0;
    ocvl.lsinkframes = 0;
    ocvl.sourcefps = $("#sourcefps");
    ocvl.sinkfps = $("#sinkfps");
    setInterval(function() {
      ocvl.lsourceframes = (ocvl.sourceframes + ocvl.lsourceframes) / 2;
      ocvl.lsinkframes = (ocvl.sinkframes + ocvl.lsinkframes) / 2;
      ocvl.sourcefps.text(ocvl.lsourceframes.toFixed(1));
      ocvl.sinkfps.text(ocvl.lsinkframes.toFixed(1));
      ocvl.sourceframes = 0;
      ocvl.sinkframes = 0;
    }, 1000);
  });
}

function draw() {
  requestAnimFrame(draw);
  ocvl.sourceframes++;
  ocvl.source.drawImage(ocvl.video, 0, 0, ocvl.video.videoWidth, ocvl.video.videoHeight, 0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
}

function log(message) {
  var log = $("#log");
  var currentText = log.text().split("\n");
  currentText.push(message);
  if (currentText.length > 100)
    currentText = currentText.splice(currentText.length - 100, currentText.length);
  log.text(currentText.join("\n"));
  log.scrollTop(log.prop("scrollHeight"));
}

function clearLog(message) {
  $("#log").html("");
}

var worker;
function run(code) {
  if (!worker) {
    worker = new Worker("js/worker.js");
    worker.addEventListener('message', handleMessage);
  }
  worker.postMessage({"message": "code", "code": code});
}

function handleMessage(e) {
  if (e.data.message === "getImage") {
    var pixels = ocvl.source.getImageData(0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
    worker.postMessage({"message": "image", "pixels":pixels});
  } else if (e.data.message === "setImage") {
    ocvl.sinkframes++;
    ocvl.sink.putImageData(e.data.pixels, 0, 0);

    var pixels = ocvl.source.getImageData(0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
    worker.postMessage({"message": "image", "pixels":pixels});
  } else if (e.data.message === "log") {
    log(e.data.data);
  } else if (e.data.message === "clearLog") {
    clearLog();
  } else {
    console.log(e.data.message);
  }
}

function gumSuccess(stream) {
  if ('mozSrcObject' in ocvl.video) {
    ocvl.video.mozSrcObject = stream;
  } else if (window.URL) {
    ocvl.video.src = window.URL.createObjectURL(stream);
  } else {
    ocvl.video.src = stream;
  }
  ocvl.video.play();

  $("#nowebcam").css("display", "none");
}

function gumError(error) {
  console.error('Error on getUserMedia', error);
}

function gumInit() {
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

  if (navigator.getUserMedia) {
    navigator.getUserMedia({video: true }, gumSuccess, gumError);
  }
}

function save(title, code) {
  var data = {
    'name': title,
    'code': code
  };

  $.post(
    "save.php",
    {data: JSON.stringify(data)},
    function(result) {
      showSave(result);
    }
  );
}

function showSave (code) {
  $("#code").text(code);
  $("#dialogBackground").css("display", "block");
  $("#saveDialog").css("display", "block");
}

function dismissSave() {
  $("#saveDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function showLoad () {
  $("#codeInput").val("");
  setTimeout(function(){
    $("#codeInput").focus();
  }, 1);
  $("#dialogBackground").css("display", "block");
  $("#loadDialog").css("display", "block");
}

function dismissLoad() {
  $("#loadDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function showHelp() {
  $("#dialogBackground").css("display", "block");
  $("#helpDialog").css("display", "block");
}

function dismissHelp() {
  $("#helpDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function browse() {
  var url = window.location + "";
  var base = url.substring(0,url.lastIndexOf("/"));
  url = base + "/filelist #content";

  $("#loadDialog").css("display", "none");
  $("#browseContents").load(url);
  $("#browseDialog").css("display", "block");
}

function dismissBrowse() {
  $("#browseDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}
<commit_msg>fixing mediastream<commit_after>/*
Copyright 2015 Jonathon Hare / The University of Southampton

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.
*/

function initialiseVideo(sourceName, sinkName, cb) {
  gumInit();

  window.ocvl = {
    video: document.querySelector('video'),
    source: document.getElementById(sourceName).getContext('2d'),
    sink: document.getElementById(sinkName).getContext('2d'),
    process: function(input, output) {
      var x, y;
      for (y=0, i=0; y<output.height; y++) {
        for (x=0; x<output.width; x++) {
          output[y][x].r = input[y][x].r;
          output[y][x].g = input[y][x].g;
          output[y][x].b = input[y][x].b;
        }
      }
    }
  }

  // shim layer with setTimeout fallback - from Paul Irish
  window.requestAnimFrame = (function() {
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
            function(callback) {
              window.setTimeout(callback, 1000 / 60);
            };
  })();

  // note: video is defined in gum.js
  ocvl.video.addEventListener('loadedmetadata', function () {
    // due to bug in Chrome: http://crbug.com/168700
    if (ocvl.video.videoWidth) {
      ocvl.source.canvas.width = ocvl.video.videoWidth;
      ocvl.source.canvas.height = ocvl.video.videoHeight;
      ocvl.sink.canvas.width = ocvl.video.videoWidth;
      ocvl.sink.canvas.height = ocvl.video.videoHeight;
    }
    draw();
    cb();
    ocvl.sourceframes = 0;
    ocvl.sinkframes = 0;
    ocvl.lsourceframes = 0;
    ocvl.lsinkframes = 0;
    ocvl.sourcefps = $("#sourcefps");
    ocvl.sinkfps = $("#sinkfps");
    setInterval(function() {
      ocvl.lsourceframes = (ocvl.sourceframes + ocvl.lsourceframes) / 2;
      ocvl.lsinkframes = (ocvl.sinkframes + ocvl.lsinkframes) / 2;
      ocvl.sourcefps.text(ocvl.lsourceframes.toFixed(1));
      ocvl.sinkfps.text(ocvl.lsinkframes.toFixed(1));
      ocvl.sourceframes = 0;
      ocvl.sinkframes = 0;
    }, 1000);
  });
}

function draw() {
  requestAnimFrame(draw);
  ocvl.sourceframes++;
  ocvl.source.drawImage(ocvl.video, 0, 0, ocvl.video.videoWidth, ocvl.video.videoHeight, 0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
}

function log(message) {
  var log = $("#log");
  var currentText = log.text().split("\n");
  currentText.push(message);
  if (currentText.length > 100)
    currentText = currentText.splice(currentText.length - 100, currentText.length);
  log.text(currentText.join("\n"));
  log.scrollTop(log.prop("scrollHeight"));
}

function clearLog(message) {
  $("#log").html("");
}

var worker;
function run(code) {
  if (!worker) {
    worker = new Worker("js/worker.js");
    worker.addEventListener('message', handleMessage);
  }
  worker.postMessage({"message": "code", "code": code});
}

function handleMessage(e) {
  if (e.data.message === "getImage") {
    var pixels = ocvl.source.getImageData(0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
    worker.postMessage({"message": "image", "pixels":pixels});
  } else if (e.data.message === "setImage") {
    ocvl.sinkframes++;
    ocvl.sink.putImageData(e.data.pixels, 0, 0);

    var pixels = ocvl.source.getImageData(0, 0, ocvl.source.canvas.width, ocvl.source.canvas.height);
    worker.postMessage({"message": "image", "pixels":pixels});
  } else if (e.data.message === "log") {
    log(e.data.data);
  } else if (e.data.message === "clearLog") {
    clearLog();
  } else {
    console.log(e.data.message);
  }
}

function gumSuccess(stream) {
  if ('mozSrcObject' in ocvl.video) {
    ocvl.video.mozSrcObject = stream;
  // } else if (window.URL) {
  //   ocvl.video.src = window.URL.createObjectURL(stream);
  } else {
    ocvl.video.src = stream;
  }
  ocvl.video.play();

  $("#nowebcam").css("display", "none");
}

function gumError(error) {
  console.error('Error on getUserMedia', error);
}

function gumInit() {
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

  if (navigator.getUserMedia) {
    navigator.getUserMedia({video: true }, gumSuccess, gumError);
  }
}

function save(title, code) {
  var data = {
    'name': title,
    'code': code
  };

  $.post(
    "save.php",
    {data: JSON.stringify(data)},
    function(result) {
      showSave(result);
    }
  );
}

function showSave (code) {
  $("#code").text(code);
  $("#dialogBackground").css("display", "block");
  $("#saveDialog").css("display", "block");
}

function dismissSave() {
  $("#saveDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function showLoad () {
  $("#codeInput").val("");
  setTimeout(function(){
    $("#codeInput").focus();
  }, 1);
  $("#dialogBackground").css("display", "block");
  $("#loadDialog").css("display", "block");
}

function dismissLoad() {
  $("#loadDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function showHelp() {
  $("#dialogBackground").css("display", "block");
  $("#helpDialog").css("display", "block");
}

function dismissHelp() {
  $("#helpDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}

function browse() {
  var url = window.location + "";
  var base = url.substring(0,url.lastIndexOf("/"));
  url = base + "/filelist #content";

  $("#loadDialog").css("display", "none");
  $("#browseContents").load(url);
  $("#browseDialog").css("display", "block");
}

function dismissBrowse() {
  $("#browseDialog").css("display", "none");
  $("#dialogBackground").css("display", "none");
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var cluster = require('cluster')
  , numCPUs = require('os').cpus().length
  , http = require('http')
  , url = require('url')
  , Sequelize = require('sequelize')
  , async = require('async')
  , mongoose = require('mongoose')
  , conn = mongoose.connect('mongodb://localhost/hello_world')
  , MongoClient = require('mongodb').MongoClient;

var collection = null;
MongoClient.connect('mongodb://localhost/hello_world?maxPoolSize=5', function(err, db) {
  collection = db.collection('world');
});

var WorldSchema = new mongoose.Schema({
    id          : Number,
    randomNumber: Number
  }, {
    collection: 'world'
  }),
  MWorld = conn.model('World', WorldSchema);

// Helper functions
function getRandomNumber() {
  return Math.floor(Math.random() * 10000) + 1;
}

function mongooseQuery(callback) {
  MWorld.findOne({ id: getRandomNumber()}).exec(function (err, world) {
    callback(err, world);
  });
}

function mongodbDriverQuery(callback) {
  collection.findOne({ id: getRandomNumber()}, function(err, world) {
    callback(err, world);
  });
}

function mongodbDriverUpdateQuery(callback) {
  collection.findAndModify({ id: getRandomNumber()}, [['_id','asc']], {$set: {randomNumber: getRandomNumber()}}, {}, function(err, world) {
    callback(err, world && world.value);
  });
}

function sequelizeQuery(callback) {
  World.findById(getRandomNumber(), function (err, world) {
    callback(null, world);
  });
}

if(cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.pid + ' died');
  });

  return;
} else {
  http.createServer(function (req, res) {
    // JSON response object
    var hello = {message: "Hello, World!"};
    var helloStr = "Hello, World!";
    var path = url.parse(req.url).pathname;

    switch (path) {
    case '/json':
      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Server': 'Node'
      });
      res.end(JSON.stringify(hello));
      break;

    case '/plaintext':
      // JSON Response Test
      res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
      // Write JSON object to response
      res.end(helloStr);
      break;

    case '/mongodbdriver':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongodbDriverQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mongoose':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongooseQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mysql-orm':
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = sequelizeQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (queries == 1) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mysql':
      function libmysqlQuery(callback) {
        libmysql.query("SELECT * FROM world WHERE id = " + getRandomNumber(), function (err, res) {
          if (err) {
  	        throw err;
  	      }

  	      res.fetchAll(function(err, rows) {
        	  if (err) {
        	    throw err;
        	  }

        	  res.freeSync();
        	  callback(null, rows[0]);
          });
        });
      }

      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = libmysqlQuery;
      }
      async.parallel(queryFunctions, function(err, results) {
        if (err) {
          res.writeHead(500);
          return res.end('MYSQL CONNECTION ERROR.');
        }
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/update':

      function libmysqlQuery(callback) {
        libmysql.query("SELECT * FROM world WHERE id = " + getRandomNumber(), function (err, res) {
          if (err) {
            throw err;
          }

          res.fetchAll(function(err, rows) {
            if (err) {
              throw err;
            }

            res.freeSync();

            rows[0].randomNumber = getRandomNumber();
            libmysql.query("UPDATE World SET randomNumber = " + rows[0].randomNumber + " WHERE id = " + rows[0]['id'], function (err, res) {
              if (err) {
                throw err;
              }
              callback(null, rows[0]);
            });
          });
        });
      }

      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      if(queries < 1) {
        queries = 1;
      } else if(queries > 500) {
        queries = 500;
      }
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = libmysqlQuery;
      }
      async.parallel(queryFunctions, function(err, results) {
        if (err) {
          res.writeHead(500);
          return res.end('MYSQL CONNECTION ERROR.');
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/update-mongodb':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      if (queries < 1) {
        queries = 1;
      } else if (queries > 500) {
        queries = 500;
      }

      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongodbDriverUpdateQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    default:
      // File not found handler
      res.writeHead(501, {'Content-Type': 'text/plain; charset=UTF-8'});
      res.end("NOT IMPLEMENTED");
    }
  }).listen(8080);
}
<commit_msg>Add Sequelize to nodejs.<commit_after>/**
 * Module dependencies.
 */

var cluster = require('cluster')
  , numCPUs = require('os').cpus().length
  , http = require('http')
  , url = require('url')
  , Sequelize = require('sequelize')
  , async = require('async')
  , mongoose = require('mongoose')
  , conn = mongoose.connect('mongodb://localhost/hello_world')
  , MongoClient = require('mongodb').MongoClient;

var collection = null;
MongoClient.connect('mongodb://localhost/hello_world?maxPoolSize=5', function(err, db) {
  collection = db.collection('world');
});

var WorldSchema = new mongoose.Schema({
    id          : Number,
    randomNumber: Number
  }, {
    collection: 'world'
  }),
  MWorld = conn.model('World', WorldSchema);

var sequelize = new Sequelize('hello_world', 'benchmarkdbuser', 'benchmarkdbpass', {
  host: 'localhost',
  dialect: 'mysql',
  logging: false,
  pool: {
    max: 5000,
    min: 0,
    idle: 5000
  }
});

var World = sequelize.define('World', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  randomNumber: {
    type: 'Sequelize.INTEGER'
  }
}, {
  timestamps: false,
  freezeTableName: true
});
var Fortune = sequelize.define('Fortune', {
  id: {
    type: 'Sequelize.INTEGER'
  },
  message: {
    type: 'Sequelize.STRING'
  }
}, {
  timestamps: false,
  freezeTableName: true
});

// Helper functions
function getRandomNumber() {
  return Math.floor(Math.random() * 10000) + 1;
}

function mongooseQuery(callback) {
  MWorld.findOne({ id: getRandomNumber()}).exec(function (err, world) {
    callback(err, world);
  });
}

function mongodbDriverQuery(callback) {
  collection.findOne({ id: getRandomNumber()}, function(err, world) {
    callback(err, world);
  });
}

function mongodbDriverUpdateQuery(callback) {
  collection.findAndModify({ id: getRandomNumber()}, [['_id','asc']], {$set: {randomNumber: getRandomNumber()}}, {}, function(err, world) {
    callback(err, world && world.value);
  });
}

function sequelizeQuery(callback) {
  World.findById(getRandomNumber(), function (err, world) {
    callback(null, world);
  });
}

if(cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.pid + ' died');
  });

  return;
} else {
  http.createServer(function (req, res) {
    // JSON response object
    var hello = {message: "Hello, World!"};
    var helloStr = "Hello, World!";
    var path = url.parse(req.url).pathname;

    switch (path) {
    case '/json':
      res.writeHead(200, {
        'Content-Type': 'application/json',
        'Server': 'Node'
      });
      res.end(JSON.stringify(hello));
      break;

    case '/plaintext':
      // JSON Response Test
      res.writeHead(200, {'Content-Type': 'text/plain; charset=UTF-8'});
      // Write JSON object to response
      res.end(helloStr);
      break;

    case '/mongodbdriver':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongodbDriverQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mongoose':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongooseQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mysql-orm':
      var values = url.parse(req.url, true);
      var queries = Math.min(Math.max(values.query.queries, 1), 500);
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = sequelizeQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        if (queries == 1) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/mysql':
      function libmysqlQuery(callback) {
        libmysql.query("SELECT * FROM world WHERE id = " + getRandomNumber(), function (err, res) {
          if (err) {
  	        throw err;
  	      }

  	      res.fetchAll(function(err, rows) {
        	  if (err) {
        	    throw err;
        	  }

        	  res.freeSync();
        	  callback(null, rows[0]);
          });
        });
      }

      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = libmysqlQuery;
      }
      async.parallel(queryFunctions, function(err, results) {
        if (err) {
          res.writeHead(500);
          return res.end('MYSQL CONNECTION ERROR.');
        }
        if (!values.query.queries) {
          results = results[0];
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/update':

      function libmysqlQuery(callback) {
        libmysql.query("SELECT * FROM world WHERE id = " + getRandomNumber(), function (err, res) {
          if (err) {
            throw err;
          }

          res.fetchAll(function(err, rows) {
            if (err) {
              throw err;
            }

            res.freeSync();

            rows[0].randomNumber = getRandomNumber();
            libmysql.query("UPDATE World SET randomNumber = " + rows[0].randomNumber + " WHERE id = " + rows[0]['id'], function (err, res) {
              if (err) {
                throw err;
              }
              callback(null, rows[0]);
            });
          });
        });
      }

      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      if(queries < 1) {
        queries = 1;
      } else if(queries > 500) {
        queries = 500;
      }
      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = libmysqlQuery;
      }
      async.parallel(queryFunctions, function(err, results) {
        if (err) {
          res.writeHead(500);
          return res.end('MYSQL CONNECTION ERROR.');
        }
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    case '/update-mongodb':
      // Database Test
      var values = url.parse(req.url, true);
      var queries = values.query.queries || 1;
      if (queries < 1) {
        queries = 1;
      } else if (queries > 500) {
        queries = 500;
      }

      var queryFunctions = new Array(queries);

      for (var i = 0; i < queries; i += 1) {
        queryFunctions[i] = mongodbDriverUpdateQuery;
      }

      async.parallel(queryFunctions, function(err, results) {
        res.writeHead(200, {
          'Content-Type': 'application/json',
          'Server': 'Node'
        });
        res.end(JSON.stringify(results));
      });
      break;

    default:
      // File not found handler
      res.writeHead(501, {'Content-Type': 'text/plain; charset=UTF-8'});
      res.end("NOT IMPLEMENTED");
    }
  }).listen(8080);
}
<|endoftext|>


<commit_before>World = function(camera) {
  this.cells_ = new Uint8Array(World.TOTAL_SIZE);

  this.root_ = new THREE.Object3D();
  this.root_.position.x = -World.X_SIZE / 2;
  this.root_.position.z = -World.Z_SIZE / 2;

  this.camera_ = camera;
};

World.X_SIZE = 50;
World.Y_SIZE = 40;
World.Z_SIZE = 50;

World.TOTAL_SIZE = World.X_SIZE * World.Y_SIZE * World.Z_SIZE;

World.Y_OFFSET = World.X_SIZE;
World.Z_OFFSET = World.X_SIZE * World.Y_SIZE;

World.CELL_TX_SIZE = 1 / 4;
World.CELL_TY_SIZE = 1 / 2;

World.CellType = {
  EMPTY: 0,
  UNKNOWN: 1,
  DIRT: 2,
  ROCK: 3,
  WATER: 4,
  WOOD: 5
};

World.CELL_TX_OFFSET = [
  (World.CELL_TX_SIZE * 3),  // EMPTY
  (World.CELL_TX_SIZE * 1),  // UNKNOWN
  (World.CELL_TX_SIZE * 0),  // DIRT
  (World.CELL_TX_SIZE * 1),  // ROCK
  (World.CELL_TX_SIZE * 2),  // WATER
  (World.CELL_TX_SIZE * 0)   // WOOD
];

World.CELL_TY_OFFSET = [
  (World.CELL_TY_SIZE * 0),  // EMPTY
  (World.CELL_TY_SIZE * 0),  // UNKNOWN
  (World.CELL_TY_SIZE * 1),  // DIRT
  (World.CELL_TY_SIZE * 1),  // ROCK
  (World.CELL_TY_SIZE * 0),  // WATER
  (World.CELL_TY_SIZE * 0)   // WOOD
];

World.FACES = [
  [0, 2, 1, 3],
  [1, 6, 5, 2],
  [5, 7, 4, 6],
  [4, 3, 0, 7],
  [3, 6, 2, 7],
  [1, 4, 0, 5]
];

World.NEXT_OFFSET = [
  [0, 0, -1],
  [1, 0, 0],
  [0, 0, 1],
  [-1, 0, 0],
  [0, 1, 0],
  [0, -1, 0]
];

World.MAX_WATER_ITER = World.Y_SIZE * 3;

World.WATER_MOVES = [
  [0, 0, -1],
  [1, 0, 0],
  [0, 0, 1],
  [-1, 0, 0]
];

World.isIn = function(x, y, z) {
  return x >= 0 && y >= 0 && z >= 0 &&
      x < World.X_SIZE && y < World.Y_SIZE && z < World.Z_SIZE;
};

/**
 * @private
 */
World.isTransparent_ = function(cellType) {
  return cellType == World.CellType.EMPTY ||
      cellType == World.CellType.WATER;
};

World.prototype.init = function() {
  this.createRandomWorld_();
  this.buildMesh_();
  this.moveCamera_();
};

World.prototype.getRoot = function() {
  return this.root_;
};

/**
 * @private
 */
World.prototype.createRandomWorld_ = function() {
  for (var i = 0; i < World.TOTAL_SIZE; ++i) {
    this.cells_[i] = World.EMPTY;
  }
  var w = this;

  var drop = function(x, z, cellType, radius) {
    for (var i = -radius; i <= radius; ++i) {
      for (var j = -radius; j <= radius; ++j) {
        if (!World.isIn(x + i, 0, z + j)) {
          continue;
        }
        var h = Math.round(Math.sqrt(radius * radius - i * i - j * j));
        var k;
        for (k = World.Y_SIZE; k > 0; --k) {
          if (w.getCell(x + i, k - 1, z + j) != World.CellType.EMPTY) {
            break;
          }
        }
        for (; h > 0 && k < World.Y_SIZE; --h,++k) {
          w.setCell(x + i, k, z + j, cellType);
        }
      }
    }
  };

  for (var i = 0; i < World.X_SIZE; ++i) {
    for (var j = 0; j < World.Z_SIZE; ++j) {
      this.setCell(i, 0, j, World.CellType.DIRT);
    }
  }
  var cts = [World.CellType.DIRT, World.CellType.WOOD, World.CellType.ROCK];
  var sts = [2, 4, 6];
  var rs = [3, 4, 5]
  for (var ct = 0; ct < cts.length; ++ct) {
    var cellType = cts[ct];
    var st = sts[ct];
    for (var i = 0; i < World.X_SIZE; i += st) {
      for (var j = 0; j < World.Z_SIZE; j += st) {
        var x = i + Math.floor(Math.random() * (st * 2 + 1)) - st;
        var z = j + Math.floor(Math.random() * (st * 2 + 1)) - st;
        var r = Math.floor(Math.random() * rs[ct]);
        drop(x, z, cellType, r);
      }
    }
  }

  // Spawn water
  var wcs = [];
  for (var i = 0; i < World.X_SIZE; ++i) {
    for (var j = 0; j < World.Z_SIZE; ++j) {
      if (this.getCell(i, World.Y_SIZE - 1, j) == World.CellType.EMPTY) {
        wcs.push([i, World.Y_SIZE - 1, j, 0]);
        this.setCell(i, World.Y_SIZE - 1, j, World.CellType.WATER);
      }
    }
  }
  var n = wcs.length;
  for (var iter = 0; iter < World.MAX_WATER_ITER; ++iter) {
    for (var i = 0; i < n; ++i) {
      if (World.isIn(wcs[i][0], wcs[i][1] - 1, wcs[i][2]) &&
          this.getCell(wcs[i][0], wcs[i][1] - 1, wcs[i][2]) == World.CellType.EMPTY) {
        this.setCell(wcs[i][0], wcs[i][1] - 1, wcs[i][2], World.CellType.WATER);
        this.setCell(wcs[i][0], wcs[i][1], wcs[i][2], World.CellType.EMPTY);
        --wcs[i][1];
      } else {
        for (var j = 0; j < 4; ++j) {
          var nx = wcs[i][0] + World.WATER_MOVES[wcs[i][3]][0];
          var ny = wcs[i][1] + World.WATER_MOVES[wcs[i][3]][1];
          var nz = wcs[i][2] + World.WATER_MOVES[wcs[i][3]][2];
          if (World.isIn(nx, ny, nz) &&
              this.getCell(nx, ny, nz) == World.CellType.EMPTY) {
            this.setCell(nx, ny, nz, World.CellType.WATER);
            this.setCell(wcs[i][0], wcs[i][1], wcs[i][2], World.CellType.EMPTY);
            wcs[i][0] = nx;
            wcs[i][1] = ny;
            wcs[i][2] = nz;
            break;
          }
          wcs[i][3] = (wcs[i][3] + 1) & 3;
        }
      }
    }
  }
};

/**
 * @private
 */
World.prototype.buildMesh_ = function() {
  var geo = new THREE.Geometry();
  var vi = 0;
  for (var i = 0; i < World.TOTAL_SIZE; ++i) {
    var cellType = this.cells_[i];
    if (!cellType || cellType == World.CellType.EMPTY) {
      continue;
    }

    var x = i % World.X_SIZE;
    var y = Math.floor(i / World.Y_OFFSET) % World.Y_SIZE;
    var z = Math.floor(i / World.Z_OFFSET) % World.Z_SIZE;

    var tx = World.CELL_TX_OFFSET[cellType];
    var ty = World.CELL_TY_OFFSET[cellType];

    var materialIndex = World.isTransparent_(cellType) ? 1 : 0;

    var addedFace = false;
    for (var j = 0; j < 6; ++j) {
      var norm = World.NEXT_OFFSET[j];
      var nextCell = this.getCell(
        x + norm[0],
        y + norm[1],
        z + norm[2]
      );
      if (nextCell != cellType && World.isTransparent_(nextCell)) {
        addedFace = true;
        var f = World.FACES[j];

        var face = new THREE.Face3(vi+f[0], vi+f[1], vi+f[2]);
        face.normal.set(norm[0], norm[1], norm[2]);
        face.materialIndex = materialIndex;
        geo.faces.push(face);

        face = new THREE.Face3(vi+f[0], vi+f[3], vi+f[1]);
        face.normal.set(norm[0], norm[1], norm[2]);
        face.materialIndex = materialIndex;
        geo.faces.push(face);

        geo.faceVertexUvs[0].push([
          new THREE.Vector2(tx, ty),
          new THREE.Vector2(tx + World.CELL_TX_SIZE, ty + World.CELL_TY_SIZE),
          new THREE.Vector2(tx + World.CELL_TX_SIZE, ty)
        ], [
          new THREE.Vector2(tx, ty),
          new THREE.Vector2(tx, ty + World.CELL_TY_SIZE),
          new THREE.Vector2(tx + World.CELL_TX_SIZE, ty + World.CELL_TY_SIZE)
        ]);
      }
    }
    if (addedFace) {
      geo.vertices.push(
        new THREE.Vector3(x, y, z),
        new THREE.Vector3(x + 1, y, z),
        new THREE.Vector3(x + 1, y + 1, z),
        new THREE.Vector3(x, y + 1, z),
        new THREE.Vector3(x, y, z + 1),
        new THREE.Vector3(x + 1, y, z + 1),
        new THREE.Vector3(x + 1, y + 1, z + 1),
        new THREE.Vector3(x, y + 1, z + 1)
      );
      vi += 8;
    }
  }
  geo.mergeVertices();
  geo.computeVertexNormals();
  // geo.computeFaceNormals();
  var materials = [
    Materials.getMaterial(Materials.SOLID_CELLS),
    Materials.getMaterial(Materials.TRANSPARENT_CELLS)
  ];
  var mesh = new THREE.Mesh(geo, new THREE.MeshFaceMaterial(materials));
  this.root_.add(mesh);
};

/**
 * @private
 */
World.prototype.moveCamera_ = function() {
  //  this.camera.position = new THREE.Vector3(0.5, 0.5);
};

World.prototype.getCell = function(x, y, z) {
  if (!World.isIn(x, y, z)) {
    return World.CellType.EMPTY;
  }
  return this.cells_[x + y * World.Y_OFFSET + z * World.Z_OFFSET];
};

/**
 * @private
 */
World.prototype.getCellById_ = function(id) {
  if (id < 0 || id >= World.TOTAL_SIZE) {
    return World.CellType.EMPTY;
  }
  return this.cells_[id];
};

World.prototype.setCell = function(x, y, z, cell) {
  if (!World.isIn(x, y, z)) {
    // TODO(hru): log error
    return;
  }
  this.cells_[x + y * World.Y_OFFSET + z * World.Z_OFFSET] = cell;
};

World.prototype.update = function(dt) {

};<commit_msg>Fix texture sizes<commit_after>World = function(camera) {
  this.cells_ = new Uint8Array(World.TOTAL_SIZE);

  this.root_ = new THREE.Object3D();
  this.root_.position.x = -World.X_SIZE / 2;
  this.root_.position.z = -World.Z_SIZE / 2;

  this.camera_ = camera;
};

World.X_SIZE = 50;
World.Y_SIZE = 40;
World.Z_SIZE = 50;

World.TOTAL_SIZE = World.X_SIZE * World.Y_SIZE * World.Z_SIZE;

World.Y_OFFSET = World.X_SIZE;
World.Z_OFFSET = World.X_SIZE * World.Y_SIZE;

World.CELL_TX_SIZE = 1 / 4;
World.CELL_TY_SIZE = 1 / 2;

World.CellType = {
  EMPTY: 0,
  UNKNOWN: 1,
  DIRT: 2,
  ROCK: 3,
  WATER: 4,
  WOOD: 5
};

World.CELL_TX_OFFSET = [
  (World.CELL_TX_SIZE * 3),  // EMPTY
  (World.CELL_TX_SIZE * 1),  // UNKNOWN
  (World.CELL_TX_SIZE * 0),  // DIRT
  (World.CELL_TX_SIZE * 1),  // ROCK
  (World.CELL_TX_SIZE * 2),  // WATER
  (World.CELL_TX_SIZE * 0)   // WOOD
];

World.CELL_TY_OFFSET = [
  (World.CELL_TY_SIZE * 0),  // EMPTY
  (World.CELL_TY_SIZE * 0),  // UNKNOWN
  (World.CELL_TY_SIZE * 1),  // DIRT
  (World.CELL_TY_SIZE * 1),  // ROCK
  (World.CELL_TY_SIZE * 0),  // WATER
  (World.CELL_TY_SIZE * 0)   // WOOD
];

World.FACES = [
  [0, 2, 1, 3],
  [1, 6, 5, 2],
  [5, 7, 4, 6],
  [4, 3, 0, 7],
  [3, 6, 2, 7],
  [1, 4, 0, 5]
];

World.NEXT_OFFSET = [
  [0, 0, -1],
  [1, 0, 0],
  [0, 0, 1],
  [-1, 0, 0],
  [0, 1, 0],
  [0, -1, 0]
];

World.MAX_WATER_ITER = World.Y_SIZE * 3;

World.WATER_MOVES = [
  [0, 0, -1],
  [1, 0, 0],
  [0, 0, 1],
  [-1, 0, 0]
];

World.isIn = function(x, y, z) {
  return x >= 0 && y >= 0 && z >= 0 &&
      x < World.X_SIZE && y < World.Y_SIZE && z < World.Z_SIZE;
};

/**
 * @private
 */
World.isTransparent_ = function(cellType) {
  return cellType == World.CellType.EMPTY ||
      cellType == World.CellType.WATER;
};

World.prototype.init = function() {
  this.createRandomWorld_();
  this.buildMesh_();
  this.moveCamera_();
};

World.prototype.getRoot = function() {
  return this.root_;
};

/**
 * @private
 */
World.prototype.createRandomWorld_ = function() {
  for (var i = 0; i < World.TOTAL_SIZE; ++i) {
    this.cells_[i] = World.EMPTY;
  }
  var w = this;

  var drop = function(x, z, cellType, radius) {
    for (var i = -radius; i <= radius; ++i) {
      for (var j = -radius; j <= radius; ++j) {
        if (!World.isIn(x + i, 0, z + j)) {
          continue;
        }
        var h = Math.round(Math.sqrt(radius * radius - i * i - j * j));
        var k;
        for (k = World.Y_SIZE; k > 0; --k) {
          if (w.getCell(x + i, k - 1, z + j) != World.CellType.EMPTY) {
            break;
          }
        }
        for (; h > 0 && k < World.Y_SIZE; --h,++k) {
          w.setCell(x + i, k, z + j, cellType);
        }
      }
    }
  };

  for (var i = 0; i < World.X_SIZE; ++i) {
    for (var j = 0; j < World.Z_SIZE; ++j) {
      this.setCell(i, 0, j, World.CellType.DIRT);
    }
  }
  var cts = [World.CellType.DIRT, World.CellType.WOOD, World.CellType.ROCK];
  var sts = [2, 4, 6];
  var rs = [3, 4, 5]
  for (var ct = 0; ct < cts.length; ++ct) {
    var cellType = cts[ct];
    var st = sts[ct];
    for (var i = 0; i < World.X_SIZE; i += st) {
      for (var j = 0; j < World.Z_SIZE; j += st) {
        var x = i + Math.floor(Math.random() * (st * 2 + 1)) - st;
        var z = j + Math.floor(Math.random() * (st * 2 + 1)) - st;
        var r = Math.floor(Math.random() * rs[ct]);
        drop(x, z, cellType, r);
      }
    }
  }

  // Spawn water
  var wcs = [];
  for (var i = 0; i < World.X_SIZE; ++i) {
    for (var j = 0; j < World.Z_SIZE; ++j) {
      if (this.getCell(i, World.Y_SIZE - 1, j) == World.CellType.EMPTY) {
        wcs.push([i, World.Y_SIZE - 1, j, 0]);
        this.setCell(i, World.Y_SIZE - 1, j, World.CellType.WATER);
      }
    }
  }
  var n = wcs.length;
  for (var iter = 0; iter < World.MAX_WATER_ITER; ++iter) {
    for (var i = 0; i < n; ++i) {
      if (World.isIn(wcs[i][0], wcs[i][1] - 1, wcs[i][2]) &&
          this.getCell(wcs[i][0], wcs[i][1] - 1, wcs[i][2]) == World.CellType.EMPTY) {
        this.setCell(wcs[i][0], wcs[i][1] - 1, wcs[i][2], World.CellType.WATER);
        this.setCell(wcs[i][0], wcs[i][1], wcs[i][2], World.CellType.EMPTY);
        --wcs[i][1];
      } else {
        for (var j = 0; j < 4; ++j) {
          var nx = wcs[i][0] + World.WATER_MOVES[wcs[i][3]][0];
          var ny = wcs[i][1] + World.WATER_MOVES[wcs[i][3]][1];
          var nz = wcs[i][2] + World.WATER_MOVES[wcs[i][3]][2];
          if (World.isIn(nx, ny, nz) &&
              this.getCell(nx, ny, nz) == World.CellType.EMPTY) {
            this.setCell(nx, ny, nz, World.CellType.WATER);
            this.setCell(wcs[i][0], wcs[i][1], wcs[i][2], World.CellType.EMPTY);
            wcs[i][0] = nx;
            wcs[i][1] = ny;
            wcs[i][2] = nz;
            break;
          }
          wcs[i][3] = (wcs[i][3] + 1) & 3;
        }
      }
    }
  }
};

/**
 * @private
 */
World.prototype.buildMesh_ = function() {
  var geo = new THREE.Geometry();
  var vi = 0;
  for (var i = 0; i < World.TOTAL_SIZE; ++i) {
    var cellType = this.cells_[i];
    if (!cellType || cellType == World.CellType.EMPTY) {
      continue;
    }

    var x = i % World.X_SIZE;
    var y = Math.floor(i / World.Y_OFFSET) % World.Y_SIZE;
    var z = Math.floor(i / World.Z_OFFSET) % World.Z_SIZE;

    var tx = World.CELL_TX_OFFSET[cellType] + eps;
    var ty = World.CELL_TY_OFFSET[cellType] + eps;

    var materialIndex = World.isTransparent_(cellType) ? 1 : 0;

    var addedFace = false;
    var eps = World.CELL_TX_SIZE * 0.05;
    for (var j = 0; j < 6; ++j) {
      var norm = World.NEXT_OFFSET[j];
      var nextCell = this.getCell(
        x + norm[0],
        y + norm[1],
        z + norm[2]
      );
      if (nextCell != cellType && World.isTransparent_(nextCell)) {
        addedFace = true;
        var f = World.FACES[j];

        var face = new THREE.Face3(vi+f[0], vi+f[1], vi+f[2]);
        face.normal.set(norm[0], norm[1], norm[2]);
        face.materialIndex = materialIndex;
        geo.faces.push(face);

        face = new THREE.Face3(vi+f[0], vi+f[3], vi+f[1]);
        face.normal.set(norm[0], norm[1], norm[2]);
        face.materialIndex = materialIndex;
        geo.faces.push(face);

        geo.faceVertexUvs[0].push([
          new THREE.Vector2(tx, ty),
          new THREE.Vector2(tx + World.CELL_TX_SIZE - 2 * eps, ty + World.CELL_TY_SIZE - 2 * eps),
          new THREE.Vector2(tx + World.CELL_TX_SIZE - 2 * eps, ty)
        ], [
          new THREE.Vector2(tx, ty),
          new THREE.Vector2(tx, ty + World.CELL_TY_SIZE - 2 * eps),
          new THREE.Vector2(tx + World.CELL_TX_SIZE - 2 * eps, ty + World.CELL_TY_SIZE - 2 * eps)
        ]);
      }
    }
    if (addedFace) {
      geo.vertices.push(
        new THREE.Vector3(x, y, z),
        new THREE.Vector3(x + 1, y, z),
        new THREE.Vector3(x + 1, y + 1, z),
        new THREE.Vector3(x, y + 1, z),
        new THREE.Vector3(x, y, z + 1),
        new THREE.Vector3(x + 1, y, z + 1),
        new THREE.Vector3(x + 1, y + 1, z + 1),
        new THREE.Vector3(x, y + 1, z + 1)
      );
      vi += 8;
    }
  }
  geo.mergeVertices();
  geo.computeVertexNormals();
  // geo.computeFaceNormals();
  var materials = [
    Materials.getMaterial(Materials.SOLID_CELLS),
    Materials.getMaterial(Materials.TRANSPARENT_CELLS)
  ];
  var mesh = new THREE.Mesh(geo, new THREE.MeshFaceMaterial(materials));
  this.root_.add(mesh);
};

/**
 * @private
 */
World.prototype.moveCamera_ = function() {
  //  this.camera.position = new THREE.Vector3(0.5, 0.5);
};

World.prototype.getCell = function(x, y, z) {
  if (!World.isIn(x, y, z)) {
    return World.CellType.EMPTY;
  }
  return this.cells_[x + y * World.Y_OFFSET + z * World.Z_OFFSET];
};

/**
 * @private
 */
World.prototype.getCellById_ = function(id) {
  if (id < 0 || id >= World.TOTAL_SIZE) {
    return World.CellType.EMPTY;
  }
  return this.cells_[id];
};

World.prototype.setCell = function(x, y, z, cell) {
  if (!World.isIn(x, y, z)) {
    // TODO(hru): log error
    return;
  }
  this.cells_[x + y * World.Y_OFFSET + z * World.Z_OFFSET] = cell;
};

World.prototype.update = function(dt) {

};<|endoftext|>


<commit_before>function SpazPhotoMailer(opts) {

	this.apis = this.getAPIs();

}

SpazPhotoMailer.prototype.getAPILabels = function() {
	var labels = [];
	for ( var key in this.getAPIs() ) {
		labels.push(key);
	}
	return labels;
};

SpazPhotoMailer.prototype.getAPIs = function() {

	thisSPM = this;

	var apis = {
		"yfrog": {
			"email_tpl"  :"{{username}}.??????@yfrog.com",
			"message_in" :"subject",
			"email_info_url":"http://yfrog.com/froggy.php",
			'help_text'  :"Log-in to yfrog.com with your Twitter username and password, and click 'my yfrog.' Your customized posting email will be listed on the right.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['yfrog'].email_tpl.replace('{{username}}', username);
			}
		},

		"twitgoo": {
			"email_tpl"  :"m@twitgoo.com",
			"message_in" :"subject",
			"email_info_url":"http://twitgoo.com/-settings/mobile",
			'help_text'  :"Log-in to twitgoo.com and click 'Settings.' Add the email address from which you'll be sending messages.",
			'getToAddress': function(opts) {
				return thisSPM.apis['twitgoo'].email_tpl;
			}
		},

		"twitpic": {
			"email_tpl"  :"{{username}}.####@twitpic.com",
			"message_in" :"subject",
			"email_info_url":"http://twitpic.com/settings.do",
			'help_text'  :"Log-in to twitpic.com, and click 'Settings.' Your custom email address will be listed.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['twitpic'].email_tpl.replace('{{username}}', username);
			}
		},

		"tweetphoto": {
			"email_tpl"  :"{{username}}.####@tweetphoto.com",
			"message_in" :"subject",
			"email_info_url":"http://www.tweetphoto.com/mysettings.php",
			'help_text'  :"Log-in to tweetphoto.com and click 'My Settings.' Your custom email address will be listed.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['tweetphoto'].email_tpl.replace('{{username}}', username);
			},
			'retrievePostingAddress': function(username, password, success, failure) {

				function getTweetPhotoProfile(username, password) {

					var url = "http://tweetphotoapi.com/api/tpapi.svc/json/users/"+username;
					var TPAPI_header = 'TPAPI: '+username+","+password;

					jQuery.ajax({

						'success':function(data, textStatus) {
							var profile = sch.deJSON(data);

						},

						'error':function(xhr, testStatus, errorThrown) {
							failure(xhr, testStatus, errorThrown);
						},

						'beforeSend':function(xhr){
							xhr.setRequestHeader("TPAPI", username+","+password);
				        },

						'url':url

					});

				};

				function getTweetPhoto(username, password, settings_url) {

					var TPAPI_header = 'TPAPI: '+username+","+password;

					jQuery.ajax({

						'success':function(data, textStatus) {
							var settings = sch.deJSON(data);
							success(settings.Email);
						},

						'error':function(xhr, testStatus, errorThrown) {
							failure(xhr, testStatus, errorThrown);
						},

						'beforeSend':function(xhr){
							xhr.setRequestHeader("TPAPI", username+","+password);
				        },

						'url':settings_url

					});

				}

			},
		}
	}

	return apis;

};

SpazPhotoMailer.prototype.setAPI = function(apilabel) {
	this.api = this.apis[apilabel];
};

SpazPhotoMailer.prototype.send = function(api, photo_url, message) {

};
<commit_msg>Added Posterous to photomailer<commit_after>function SpazPhotoMailer(opts) {

	this.apis = this.getAPIs();

}

SpazPhotoMailer.prototype.getAPILabels = function() {
	var labels = [];
	for ( var key in this.getAPIs() ) {
		labels.push(key);
	}
	return labels;
};

SpazPhotoMailer.prototype.getAPIs = function() {

	thisSPM = this;

	var apis = {
		"yfrog": {
			"email_tpl"  :"{{username}}.??????@yfrog.com",
			"message_in" :"subject",
			"email_info_url":"http://yfrog.com/froggy.php",
			'help_text'  :"Log-in to yfrog.com with your Twitter username and password, and click 'my yfrog.' Your customized posting email will be listed on the right.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['yfrog'].email_tpl.replace('{{username}}', username);
			}
		},

		"posterous": {
			"email_tpl"  :"post@posterous.com",
			"message_in" :"subject",
			"email_info_url":"http://posterous.com/main/editemails",
			'help_text'  :"Log into posterous, click 'Manage' submit your email address for posting",
			'getToAddress': function(opts) {
				return thisSPM.apis['posterous'].email_tpl;
			}
		},

		"twitgoo": {
			"email_tpl"  :"m@twitgoo.com",
			"message_in" :"subject",
			"email_info_url":"http://twitgoo.com/-settings/mobile",
			'help_text'  :"Log-in to twitgoo.com and click 'Settings.' Add the email address from which you'll be sending messages.",
			'getToAddress': function(opts) {
				return thisSPM.apis['twitgoo'].email_tpl;
			}
		},

		"twitpic": {
			"email_tpl"  :"{{username}}.####@twitpic.com",
			"message_in" :"subject",
			"email_info_url":"http://twitpic.com/settings.do",
			'help_text'  :"Log-in to twitpic.com, and click 'Settings.' Your custom email address will be listed.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['twitpic'].email_tpl.replace('{{username}}', username);
			}
		},

		"tweetphoto": {
			"email_tpl"  :"{{username}}.####@tweetphoto.com",
			"message_in" :"subject",
			"email_info_url":"http://www.tweetphoto.com/mysettings.php",
			'help_text'  :"Log-in to tweetphoto.com and click 'My Settings.' Your custom email address will be listed.",
			'getToAddress': function(opts) {
				var username = opts.username;
				return thisSPM.apis['tweetphoto'].email_tpl.replace('{{username}}', username);
			},
			'retrievePostingAddress': function(username, password, success, failure) {

				function getTweetPhotoProfile(username, password) {

					var url = "http://tweetphotoapi.com/api/tpapi.svc/json/users/"+username;
					var TPAPI_header = 'TPAPI: '+username+","+password;

					jQuery.ajax({

						'success':function(data, textStatus) {
							var profile = sch.deJSON(data);

						},

						'error':function(xhr, testStatus, errorThrown) {
							failure(xhr, testStatus, errorThrown);
						},

						'beforeSend':function(xhr){
							xhr.setRequestHeader("TPAPI", username+","+password);
				        },

						'url':url

					});

				};

				function getTweetPhoto(username, password, settings_url) {

					var TPAPI_header = 'TPAPI: '+username+","+password;

					jQuery.ajax({

						'success':function(data, textStatus) {
							var settings = sch.deJSON(data);
							success(settings.Email);
						},

						'error':function(xhr, testStatus, errorThrown) {
							failure(xhr, testStatus, errorThrown);
						},

						'beforeSend':function(xhr){
							xhr.setRequestHeader("TPAPI", username+","+password);
				        },

						'url':settings_url

					});

				}

			},
		}
	}

	return apis;

};

SpazPhotoMailer.prototype.setAPI = function(apilabel) {
	this.api = this.apis[apilabel];
};

SpazPhotoMailer.prototype.send = function(api, photo_url, message) {

};
<|endoftext|>


<commit_before><commit_msg>syntax<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.perm");

// backward compatibilty
Object.assign(window, {
	READ: "read",
	WRITE: "write",
	CREATE: "create",
	DELETE: "delete",
	SUBMIT: "submit",
	CANCEL: "cancel",
	AMEND: "amend",
});

$.extend(frappe.perm, {
	rights: [
		"select",
		"read",
		"write",
		"create",
		"delete",
		"submit",
		"cancel",
		"amend",
		"report",
		"import",
		"export",
		"print",
		"email",
		"share",
		"set_user_permissions",
	],

	doctype_perm: {},

	has_perm: (doctype, permlevel, ptype, doc) => {
		if (!permlevel) permlevel = 0;

		// if document object is passed, get fresh doc based perms
		// (with ownership and user perms applied) else cached doctype perms
		const perms = doc
			? frappe.perm.get_perm(doctype, doc)
			: (frappe.perm.doctype_perm[doctype] ??= frappe.perm.get_perm(doctype));

		return !!perms?.[permlevel]?.[ptype];
	},

	get_perm: (doctype, doc) => {
		let perm = [{ read: 0, permlevel: 0 }];

		let meta = frappe.get_doc("DocType", doctype);
		const user = frappe.session.user;

		if (user === "Administrator" || frappe.user_roles.includes("Administrator")) {
			perm[0].read = 1;
		}

		if (!meta) return perm;

		perm = frappe.perm.get_role_permissions(meta);
		const base_perm = perm[0];

		if (doc) {
			// apply user permissions via docinfo (which is processed server-side)
			let docinfo = frappe.model.get_docinfo(doctype, doc.name);
			if (docinfo && docinfo.permissions) {
				Object.keys(docinfo.permissions).forEach((ptype) => {
					base_perm[ptype] = docinfo.permissions[ptype];
				});
			}

			// if owner
			if (doc.owner !== user) {
				for (const right of frappe.perm.rights) {
					if (base_perm[right] && !base_perm.rights_without_if_owner.has(right)) {
						base_perm[right] = 0;
					}
				}
			}

			// apply permissions from shared
			if (docinfo && docinfo.shared) {
				for (const s of docinfo.shared) {
					if (s.user !== user) continue;

					for (const right of ["read", "write", "submit", "share"]) {
						if (!base_perm[right]) base_perm[right] = s[right];
					}

					if (s.read) {
						// also give print, email permissions if read
						// and these permissions exist at level [0]
						base_perm.email =
							frappe.boot.user.can_email.indexOf(doctype) !== -1 ? 1 : 0;
						base_perm.print =
							frappe.boot.user.can_print.indexOf(doctype) !== -1 ? 1 : 0;
					}
				}
			}
		}

		if (frappe.model.can_read(doctype) && !base_perm.read) {
			// read via sharing
			base_perm.read = 1;
		}

		return perm;
	},

	get_role_permissions: (meta) => {
		/** Returns a `dict` of evaluated Role Permissions like:
		{
			"read": 1,
			"write": 0,
			"rights_without_if_owner": {"read", "write"}  // for permlevel 0
		}
		*/

		let perm = [{ read: 0, permlevel: 0 }];

		(meta.permissions || []).forEach((p) => {
			const permlevel = cint(p.permlevel);
			const current_perm = (perm[permlevel] ??= { permlevel });

			if (permlevel === 0) {
				current_perm.rights_without_if_owner ??= new Set();
			}

			// if user has this role
			if (frappe.user_roles.includes(p.role)) {
				frappe.perm.rights.forEach((right) => {
					if (!p[right]) return;

					current_perm[right] = 1;

					if (permlevel === 0 && !p.if_owner) {
						current_perm.rights_without_if_owner.add(right);
					}
				});
			}
		});

		// fill gaps with empty object
		perm = perm.map((p) => p || {});
		return perm;
	},

	get_match_rules: (doctype, ptype) => {
		let match_rules = [];

		if (!ptype) ptype = "read";

		let perm = frappe.perm.get_perm(doctype);

		let user_permissions = frappe.defaults.get_user_permissions();

		if (user_permissions && !$.isEmptyObject(user_permissions)) {
			let rules = {};
			let fields_to_check = frappe.meta.get_fields_to_check_permissions(doctype);
			$.each(fields_to_check, (i, df) => {
				const user_permissions_for_doctype = user_permissions[df.options] || [];
				const allowed_records = frappe.perm.get_allowed_docs_for_doctype(
					user_permissions_for_doctype,
					doctype
				);
				if (allowed_records.length) {
					rules[df.label] = allowed_records;
				}
			});
			if (!$.isEmptyObject(rules)) {
				match_rules.push(rules);
			}
		}

		const base_perm = perm[0];
		if (base_perm.read && !base_perm.rights_without_if_owner.has("read")) {
			match_rules.push({ Owner: frappe.session.user });
		}
		return match_rules;
	},

	get_field_display_status: (df, doc, perm, explain) => {
		// returns the display status of a particular field
		// returns one of "Read", "Write" or "None"
		if (!perm && doc) {
			perm = frappe.perm.get_perm(doc.doctype, doc);
		}

		if (!perm) {
			return df && (cint(df.hidden) || cint(df.hidden_due_to_dependency)) ? "None" : "Write";
		}

		if (!df.permlevel) df.permlevel = 0;
		let p = perm[df.permlevel];
		let status = "None";

		// permission
		if (p) {
			if (p.write && !df.disabled) {
				status = "Write";
			} else if (p.read) {
				status = "Read";
			}
		}
		if (explain) console.log("By Permission:" + status);

		// hidden
		if (cint(df.hidden)) status = "None";
		if (explain) console.log("By Hidden:" + status);

		// hidden due to dependency
		if (cint(df.hidden_due_to_dependency)) status = "None";
		if (explain) console.log("By Hidden Due To Dependency:" + status);

		if (!doc) {
			return status;
		}

		// submit
		if (status === "Write" && cint(doc.docstatus) > 0) status = "Read";
		if (explain) console.log("By Submit:" + status);

		// allow on submit
		// let allow_on_submit = df.fieldtype==="Table" ? 0 : cint(df.allow_on_submit);
		let allow_on_submit = cint(df.allow_on_submit);
		if (status === "Read" && allow_on_submit && cint(doc.docstatus) === 1 && p.write) {
			status = "Write";
		}
		if (explain) console.log("By Allow on Submit:" + status);

		// workflow state
		if (status === "Read" && cur_frm && cur_frm.state_fieldname) {
			// fields updated by workflow must be read-only
			if (
				cint(cur_frm.read_only) ||
				in_list(cur_frm.states.update_fields, df.fieldname) ||
				df.fieldname == cur_frm.state_fieldname
			) {
				status = "Read";
			}
		}
		if (explain) console.log("By Workflow:" + status);

		// read only field is checked
		if (status === "Write" && (cint(df.read_only) || df.fieldtype === "Read Only")) {
			status = "Read";
		}
		if (explain) console.log("By Read Only:" + status);

		if (status === "Write" && df.set_only_once && !doc.__islocal) {
			status = "Read";
		}
		if (explain) console.log("By Set Only Once:" + status);

		return status;
	},

	is_visible: (df, doc, perm) => {
		if (typeof df === "string") {
			// df is fieldname
			df = frappe.meta.get_docfield(doc.doctype, df, doc.parent || doc.name);
		}

		let status = frappe.perm.get_field_display_status(df, doc, perm);

		return status === "None" ? false : true;
	},

	get_allowed_docs_for_doctype: (user_permissions, doctype) => {
		// returns docs from the list of user permissions that are allowed under provided doctype
		return frappe.perm.filter_allowed_docs_for_doctype(user_permissions, doctype, false);
	},

	filter_allowed_docs_for_doctype: (user_permissions, doctype, with_default_doc = true) => {
		// returns docs from the list of user permissions that are allowed under provided doctype
		// also returns default doc when with_default_doc is set
		const filtered_perms = (user_permissions || []).filter((perm) => {
			return perm.applicable_for === doctype || !perm.applicable_for;
		});

		const allowed_docs = filtered_perms.map((perm) => perm.doc);

		if (with_default_doc) {
			const default_doc =
				allowed_docs.length === 1
					? allowed_docs
					: filtered_perms.filter((perm) => perm.is_default).map((record) => record.doc);

			return {
				allowed_records: allowed_docs,
				default_doc: default_doc[0],
			};
		} else {
			return allowed_docs;
		}
	},
});
<commit_msg>chore: Cache Document level perms as well in `has_perm`<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.perm");

// backward compatibilty
Object.assign(window, {
	READ: "read",
	WRITE: "write",
	CREATE: "create",
	DELETE: "delete",
	SUBMIT: "submit",
	CANCEL: "cancel",
	AMEND: "amend",
});

$.extend(frappe.perm, {
	rights: [
		"select",
		"read",
		"write",
		"create",
		"delete",
		"submit",
		"cancel",
		"amend",
		"report",
		"import",
		"export",
		"print",
		"email",
		"share",
		"set_user_permissions",
	],

	doc_perm: {},

	has_perm: (doctype, permlevel, ptype, doc) => {
		if (!permlevel) permlevel = 0;

		/** frappe.perm.doc_perm structure:
		 * {
		 * 	DocType: {
		 * 		"doctype_perm": {...perms},
		 * 		<docname_1>: {...document perms},
		 * 		<docname_2>: {...document perms},
		 * 	}
		 * }
		 */
		// Cache doctype perms and document perms (with user perms and ownership) if absent
		const doctype_perm = (frappe.perm.doc_perm[doctype] ??= {});
		const perms = (doctype_perm[doc ? doc.name : "doctype_perm"] ??= frappe.perm.get_perm(
			doctype,
			doc
		));

		return !!perms?.[permlevel]?.[ptype];
	},

	get_perm: (doctype, doc) => {
		let perm = [{ read: 0, permlevel: 0 }];

		let meta = frappe.get_doc("DocType", doctype);
		const user = frappe.session.user;

		if (user === "Administrator" || frappe.user_roles.includes("Administrator")) {
			perm[0].read = 1;
		}

		if (!meta) return perm;

		perm = frappe.perm.get_role_permissions(meta);
		const base_perm = perm[0];

		if (doc) {
			// apply user permissions via docinfo (which is processed server-side)
			let docinfo = frappe.model.get_docinfo(doctype, doc.name);
			if (docinfo && docinfo.permissions) {
				Object.keys(docinfo.permissions).forEach((ptype) => {
					base_perm[ptype] = docinfo.permissions[ptype];
				});
			}

			// if owner
			if (doc.owner !== user) {
				for (const right of frappe.perm.rights) {
					if (base_perm[right] && !base_perm.rights_without_if_owner.has(right)) {
						base_perm[right] = 0;
					}
				}
			}

			// apply permissions from shared
			if (docinfo && docinfo.shared) {
				for (const s of docinfo.shared) {
					if (s.user !== user) continue;

					for (const right of ["read", "write", "submit", "share"]) {
						if (!base_perm[right]) base_perm[right] = s[right];
					}

					if (s.read) {
						// also give print, email permissions if read
						// and these permissions exist at level [0]
						base_perm.email =
							frappe.boot.user.can_email.indexOf(doctype) !== -1 ? 1 : 0;
						base_perm.print =
							frappe.boot.user.can_print.indexOf(doctype) !== -1 ? 1 : 0;
					}
				}
			}
		}

		if (frappe.model.can_read(doctype) && !base_perm.read) {
			// read via sharing
			base_perm.read = 1;
		}

		return perm;
	},

	get_role_permissions: (meta) => {
		/** Returns a `dict` of evaluated Role Permissions like:
		{
			"read": 1,
			"write": 0,
			"rights_without_if_owner": {"read", "write"}  // for permlevel 0
		}
		*/

		let perm = [{ read: 0, permlevel: 0 }];

		(meta.permissions || []).forEach((p) => {
			const permlevel = cint(p.permlevel);
			const current_perm = (perm[permlevel] ??= { permlevel });

			if (permlevel === 0) {
				current_perm.rights_without_if_owner ??= new Set();
			}

			// if user has this role
			if (frappe.user_roles.includes(p.role)) {
				frappe.perm.rights.forEach((right) => {
					if (!p[right]) return;

					current_perm[right] = 1;

					if (permlevel === 0 && !p.if_owner) {
						current_perm.rights_without_if_owner.add(right);
					}
				});
			}
		});

		// fill gaps with empty object
		perm = perm.map((p) => p || {});
		return perm;
	},

	get_match_rules: (doctype, ptype) => {
		let match_rules = [];

		if (!ptype) ptype = "read";

		let perm = frappe.perm.get_perm(doctype);

		let user_permissions = frappe.defaults.get_user_permissions();

		if (user_permissions && !$.isEmptyObject(user_permissions)) {
			let rules = {};
			let fields_to_check = frappe.meta.get_fields_to_check_permissions(doctype);
			$.each(fields_to_check, (i, df) => {
				const user_permissions_for_doctype = user_permissions[df.options] || [];
				const allowed_records = frappe.perm.get_allowed_docs_for_doctype(
					user_permissions_for_doctype,
					doctype
				);
				if (allowed_records.length) {
					rules[df.label] = allowed_records;
				}
			});
			if (!$.isEmptyObject(rules)) {
				match_rules.push(rules);
			}
		}

		const base_perm = perm[0];
		if (base_perm.read && !base_perm.rights_without_if_owner.has("read")) {
			match_rules.push({ Owner: frappe.session.user });
		}
		return match_rules;
	},

	get_field_display_status: (df, doc, perm, explain) => {
		// returns the display status of a particular field
		// returns one of "Read", "Write" or "None"
		if (!perm && doc) {
			perm = frappe.perm.get_perm(doc.doctype, doc);
		}

		if (!perm) {
			return df && (cint(df.hidden) || cint(df.hidden_due_to_dependency)) ? "None" : "Write";
		}

		if (!df.permlevel) df.permlevel = 0;
		let p = perm[df.permlevel];
		let status = "None";

		// permission
		if (p) {
			if (p.write && !df.disabled) {
				status = "Write";
			} else if (p.read) {
				status = "Read";
			}
		}
		if (explain) console.log("By Permission:" + status);

		// hidden
		if (cint(df.hidden)) status = "None";
		if (explain) console.log("By Hidden:" + status);

		// hidden due to dependency
		if (cint(df.hidden_due_to_dependency)) status = "None";
		if (explain) console.log("By Hidden Due To Dependency:" + status);

		if (!doc) {
			return status;
		}

		// submit
		if (status === "Write" && cint(doc.docstatus) > 0) status = "Read";
		if (explain) console.log("By Submit:" + status);

		// allow on submit
		// let allow_on_submit = df.fieldtype==="Table" ? 0 : cint(df.allow_on_submit);
		let allow_on_submit = cint(df.allow_on_submit);
		if (status === "Read" && allow_on_submit && cint(doc.docstatus) === 1 && p.write) {
			status = "Write";
		}
		if (explain) console.log("By Allow on Submit:" + status);

		// workflow state
		if (status === "Read" && cur_frm && cur_frm.state_fieldname) {
			// fields updated by workflow must be read-only
			if (
				cint(cur_frm.read_only) ||
				in_list(cur_frm.states.update_fields, df.fieldname) ||
				df.fieldname == cur_frm.state_fieldname
			) {
				status = "Read";
			}
		}
		if (explain) console.log("By Workflow:" + status);

		// read only field is checked
		if (status === "Write" && (cint(df.read_only) || df.fieldtype === "Read Only")) {
			status = "Read";
		}
		if (explain) console.log("By Read Only:" + status);

		if (status === "Write" && df.set_only_once && !doc.__islocal) {
			status = "Read";
		}
		if (explain) console.log("By Set Only Once:" + status);

		return status;
	},

	is_visible: (df, doc, perm) => {
		if (typeof df === "string") {
			// df is fieldname
			df = frappe.meta.get_docfield(doc.doctype, df, doc.parent || doc.name);
		}

		let status = frappe.perm.get_field_display_status(df, doc, perm);

		return status === "None" ? false : true;
	},

	get_allowed_docs_for_doctype: (user_permissions, doctype) => {
		// returns docs from the list of user permissions that are allowed under provided doctype
		return frappe.perm.filter_allowed_docs_for_doctype(user_permissions, doctype, false);
	},

	filter_allowed_docs_for_doctype: (user_permissions, doctype, with_default_doc = true) => {
		// returns docs from the list of user permissions that are allowed under provided doctype
		// also returns default doc when with_default_doc is set
		const filtered_perms = (user_permissions || []).filter((perm) => {
			return perm.applicable_for === doctype || !perm.applicable_for;
		});

		const allowed_docs = filtered_perms.map((perm) => perm.doc);

		if (with_default_doc) {
			const default_doc =
				allowed_docs.length === 1
					? allowed_docs
					: filtered_perms.filter((perm) => perm.is_default).map((record) => record.doc);

			return {
				allowed_records: allowed_docs,
				default_doc: default_doc[0],
			};
		} else {
			return allowed_docs;
		}
	},
});
<|endoftext|>


<commit_before>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, DDoSProtection } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': 'RU',
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',
                'AST': 'Astral',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BLN': 'Bulleon',
                'BTS': 'Bitshares2',
                'CS': 'CryptoSpots',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'ICN': 'iCoin',
                'LIZI': 'LiZi',
                'LOC': 'LocoCoin',
                'LOCX': 'LOC',
                'LUN': 'LunarCoin',
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'OMG': 'OMGame',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
                'XIN': 'XINCoin',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if (account['total'] && account['free'])
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response,
        };
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency,
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('success' in response) {
            if (!response['success']) {
                if (response['error'].indexOf ('Insufficient funds') >= 0) { // not enougTh is a typo inside Liqui's own API...
                    throw new InsufficientFunds (this.id + ' ' + this.json (response));
                } else if (response['error'] === 'Requests too often') {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else if ((response['error'] === 'not available') || (response['error'] === 'external service unavailable')) {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else {
                    throw new ExchangeError (this.id + ' ' + this.json (response));
                }
            }
        }
        return response;
    }
};
<commit_msg>yobit ERT → Eristica Token fix #2536<commit_after>'use strict';

// ---------------------------------------------------------------------------

const liqui = require ('./liqui.js');
const { ExchangeError, InsufficientFunds, DDoSProtection } = require ('./base/errors');

// ---------------------------------------------------------------------------

module.exports = class yobit extends liqui {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'yobit',
            'name': 'YoBit',
            'countries': 'RU',
            'rateLimit': 3000, // responses are cached every 2 seconds
            'version': '3',
            'has': {
                'createDepositAddress': true,
                'fetchDepositAddress': true,
                'CORS': false,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
                'api': {
                    'public': 'https://yobit.net/api',
                    'private': 'https://yobit.net/tapi',
                },
                'www': 'https://www.yobit.net',
                'doc': 'https://www.yobit.net/en/api/',
                'fees': 'https://www.yobit.net/en/fees/',
            },
            'api': {
                'public': {
                    'get': [
                        'depth/{pair}',
                        'info',
                        'ticker/{pair}',
                        'trades/{pair}',
                    ],
                },
                'private': {
                    'post': [
                        'ActiveOrders',
                        'CancelOrder',
                        'GetDepositAddress',
                        'getInfo',
                        'OrderInfo',
                        'Trade',
                        'TradeHistory',
                        'WithdrawCoinsToAddress',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.002,
                    'taker': 0.002,
                },
                'funding': {
                    'withdraw': {},
                },
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'ANI': 'ANICoin',
                'ANT': 'AntsCoin',
                'AST': 'Astral',
                'ATM': 'Autumncoin',
                'BCC': 'BCH',
                'BCS': 'BitcoinStake',
                'BLN': 'Bulleon',
                'BTS': 'Bitshares2',
                'CS': 'CryptoSpots',
                'DCT': 'Discount',
                'DGD': 'DarkGoldCoin',
                'ERT': 'Eristica Token',
                'ICN': 'iCoin',
                'LIZI': 'LiZi',
                'LOC': 'LocoCoin',
                'LOCX': 'LOC',
                'LUN': 'LunarCoin',
                'MDT': 'Midnight',
                'NAV': 'NavajoCoin',
                'OMG': 'OMGame',
                'PAY': 'EPAY',
                'PLC': 'Platin Coin',
                'REP': 'Republicoin',
                'RUR': 'RUB',
                'XIN': 'XINCoin',
            },
            'options': {
                'fetchOrdersRequiresSymbol': true,
            },
        });
    }

    parseOrderStatus (status) {
        let statuses = {
            '0': 'open',
            '1': 'closed',
            '2': 'canceled',
            '3': 'open', // or partially-filled and closed? https://github.com/ccxt/ccxt/issues/1594
        };
        if (status in statuses)
            return statuses[status];
        return status;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let response = await this.privatePostGetInfo ();
        let balances = response['return'];
        let result = { 'info': balances };
        let sides = { 'free': 'funds', 'total': 'funds_incl_orders' };
        let keys = Object.keys (sides);
        for (let i = 0; i < keys.length; i++) {
            let key = keys[i];
            let side = sides[key];
            if (side in balances) {
                let currencies = Object.keys (balances[side]);
                for (let j = 0; j < currencies.length; j++) {
                    let lowercase = currencies[j];
                    let uppercase = lowercase.toUpperCase ();
                    let currency = this.commonCurrencyCode (uppercase);
                    let account = undefined;
                    if (currency in result) {
                        account = result[currency];
                    } else {
                        account = this.account ();
                    }
                    account[key] = balances[side][lowercase];
                    if (account['total'] && account['free'])
                        account['used'] = account['total'] - account['free'];
                    result[currency] = account;
                }
            }
        }
        return this.parseBalance (result);
    }

    async createDepositAddress (code, params = {}) {
        let response = await this.fetchDepositAddress (code, this.extend ({
            'need_new': 1,
        }, params));
        let address = this.safeString (response, 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response['info'],
        };
    }

    async fetchDepositAddress (code, params = {}) {
        let currency = this.currency (code);
        let request = {
            'coinName': currency['id'],
            'need_new': 0,
        };
        let response = await this.privatePostGetDepositAddress (this.extend (request, params));
        let address = this.safeString (response['return'], 'address');
        this.checkAddress (address);
        return {
            'currency': code,
            'address': address,
            'status': 'ok',
            'info': response,
        };
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        let response = await this.privatePostWithdrawCoinsToAddress (this.extend ({
            'coinName': currency,
            'amount': amount,
            'address': address,
        }, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('success' in response) {
            if (!response['success']) {
                if (response['error'].indexOf ('Insufficient funds') >= 0) { // not enougTh is a typo inside Liqui's own API...
                    throw new InsufficientFunds (this.id + ' ' + this.json (response));
                } else if (response['error'] === 'Requests too often') {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else if ((response['error'] === 'not available') || (response['error'] === 'external service unavailable')) {
                    throw new DDoSProtection (this.id + ' ' + this.json (response));
                } else {
                    throw new ExchangeError (this.id + ' ' + this.json (response));
                }
            }
        }
        return response;
    }
};
<|endoftext|>