<commit_before>var fs = require('fs-extra')
var path = require('path')
var walker = require('walker')
var tweezers = require('./tweezers')
var batch = require('batchflow')
var dt = require('date-tokens')
var rlp = require('readline-prompter')
var ghdownload = require('github-download')
var rutil = require('./util')
var S = require('string')
var agent = require('superagent')

S.TMPL_OPEN = '{{'
S.TMPL_CLOSE = '}}'

function fetchFile (filePath, rock, options, callback) {
  if (typeof options === 'function') callback = options
  if (!options.defaultValues) options.defaultValues = {}
  if (!options.templateValues) options.templateValues = {}

  filePath = path.resolve(filePath)

  var topen = S.TMPL_OPEN
  var tclose = S.TMPL_CLOSE

  if (options.tokens) {
    topen = options.tokens.open || S.TMPL_OPEN
    tclose = options.tokens.close || S.TMPL_CLOSE
  }

  // Check if rock is local:
  fs.exists(rock, copyOrDownload)
  function copyOrDownload (itsLocal) {
    if (itsLocal) { // bug here if dir doesn't exist, TODO: fix
      fs.copy(rock, filePath, tweezeFiles)
    } else {
      agent.get(rock).buffer().end(function (res) {
        fs.outputFile(filePath, res.text, tweezeFiles)
      })
    }
  }
  function tweezeFiles (err) {
    if (err) return callback(err)
    var files = [filePath]
    tweezers.readFilesAndExtract(files, topen, tclose, promptUser)
  }
  function promptUser (err, tokenObj) {
    if (err) return callback(err)
    var replacements = {'file': topen + 'file' + tclose}

    replacements = rutil.extend(replacements, dt.eval('date-'))
    replacements = rutil.extend(replacements, options.templateValues)

    rlp(tokenObj.tokens, options.defaultValues, replacements).end(function (results) {
      outputFiles(tokenObj, results)
    })
  }
  function outputFiles (tokenObj, replacements) {
    delete tokenObj.tokens // we just want to process the files,objs

    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) return callback(err)
      replacements['file'] = path.basename(filePath)
      var newFileData = S(data).template(replacements, topen, tclose).s

      fs.writeFile(filePath, newFileData, callback)
    })
  }
}

function fetchRepo (projectPath, repoPath, options, callback) {
  projectPath = path.resolve(projectPath)
  var projectRockPath = path.join(projectPath, '.rock')
  var projectRockConf = path.join(projectRockPath, 'rock.json')
  var projectRockObj = {} // empty config

  if (typeof options === 'function') callback = options
  if (!options.defaultValues) options.defaultValues = {}
  if (!options.templateValues) options.templateValues = {}

  // Check if rock is local:
  fs.exists(repoPath, copyOrDownload)
  function copyOrDownload (itsLocal) {
    if (itsLocal) {
      fs.copy(repoPath, projectPath, checkRockConf)
    } else {
      ghdownload(repoPath, projectPath)
      .on('error', callback)
      .on('end', checkRockConf)
    }
  }
  function checkRockConf (err) {
    if (err) return callback(err)
    // console.log('checkRockConf')
    fs.exists(projectRockConf, loadRockConf)
  }
  function loadRockConf (rockConfExists) {
    if (rockConfExists) {
      fs.readJson(projectRockConf, walkFilesAndLoadTokenSettings)
    } else {
      walkFilesAndLoadTokenSettings()
    }
  }
  function walkFilesAndLoadTokenSettings (err, data) {
    if (err) return callback(err)
    // console.log('walkFiles')
    var files = []
    var ignoreDirs = []

    if (data) {
      projectRockObj = data
      ignoreDirs = projectRockObj.ignoreDirs || []
      for (var i = 0; i < ignoreDirs.length; ++i) {
        ignoreDirs[i] = path.resolve(projectPath, ignoreDirs[i])
      }

      if (projectRockObj.tokens) {
        S.TMPL_OPEN = projectRockObj.tokens.open || S.TMPL_OPEN
        S.TMPL_CLOSE = projectRockObj.tokens.close || S.TMPL_CLOSE
      }
    }

    walker(projectPath)
    .filterDir(function (dir, stat) { // return false if you want to filter
      // if current dir is the .rock filter, then obviously filter... else filter if it is found in ignoreDirs
      return (dir === projectRockPath) ? false : !(ignoreDirs.indexOf(dir) >= 0)
    })
    .on('file', function (file) { files.push(file) })
    .on('end', function () { tweezeFiles(files) })
  }
  function tweezeFiles (files) {
    // console.log('tweezefiles');
    tweezers.readFilesAndExtract(files, S.TMPL_OPEN, S.TMPL_CLOSE, promptUser)
  }
  function promptUser (err, tokenObj) {
    if (err) return callback(err)
    var replacements = {'file': S.TMPL_OPEN + 'file' + S.TMPL_CLOSE}

    replacements = rutil.extend(replacements, dt.eval('date-'))
    replacements = rutil.extend(replacements, options.templateValues)

    rlp(tokenObj.tokens, options.defaultValues, replacements).end(function (results) {
      outputFiles(tokenObj, results)
    })
  }
  function outputFiles (tokenObj, replacements) {
    delete tokenObj.tokens // we just want to process the files,objs

    batch(tokenObj).par().each(function (file, fileTokens, done) {
      fs.readFile(file, 'utf8', function (err, data) {
        if (err) throw err
        var newFileName = S(file).template(replacements).s
        replacements['file'] = path.basename(newFileName)

        var newFileData = S(data).template(replacements).s

        fs.writeFile(newFileName, newFileData, function (err) {
          if (err) throw err // this should be caught by ERROR above
          if (file !== newFileName) {
            fs.remove(file, function (err) {
              if (err) throw err
              done()
            })
          } else {
            done()
          }
        })
      })
    }).end(deleteRockFolder)
  }
  function deleteRockFolder (a) {
    fs.remove(projectRockPath, callback)
  }
}

module.exports.fetchRepo = fetchRepo
module.exports.fetchFile = fetchFile
<commit_msg>BREAKING: Do not copy .git directory from local rock<commit_after>var fs = require('fs-extra')
var path = require('path')
var walker = require('walker')
var tweezers = require('./tweezers')
var batch = require('batchflow')
var dt = require('date-tokens')
var rlp = require('readline-prompter')
var ghdownload = require('github-download')
var rutil = require('./util')
var S = require('string')
var agent = require('superagent')

S.TMPL_OPEN = '{{'
S.TMPL_CLOSE = '}}'

function fetchFile (filePath, rock, options, callback) {
  if (typeof options === 'function') callback = options
  if (!options.defaultValues) options.defaultValues = {}
  if (!options.templateValues) options.templateValues = {}

  filePath = path.resolve(filePath)

  var topen = S.TMPL_OPEN
  var tclose = S.TMPL_CLOSE

  if (options.tokens) {
    topen = options.tokens.open || S.TMPL_OPEN
    tclose = options.tokens.close || S.TMPL_CLOSE
  }

  // Check if rock is local:
  fs.exists(rock, copyOrDownload)
  function copyOrDownload (itsLocal) {
    if (itsLocal) { // bug here if dir doesn't exist, TODO: fix
      fs.copy(rock, filePath, tweezeFiles)
    } else {
      agent.get(rock).buffer().end(function (res) {
        fs.outputFile(filePath, res.text, tweezeFiles)
      })
    }
  }
  function tweezeFiles (err) {
    if (err) return callback(err)
    var files = [filePath]
    tweezers.readFilesAndExtract(files, topen, tclose, promptUser)
  }
  function promptUser (err, tokenObj) {
    if (err) return callback(err)
    var replacements = {'file': topen + 'file' + tclose}

    replacements = rutil.extend(replacements, dt.eval('date-'))
    replacements = rutil.extend(replacements, options.templateValues)

    rlp(tokenObj.tokens, options.defaultValues, replacements).end(function (results) {
      outputFiles(tokenObj, results)
    })
  }
  function outputFiles (tokenObj, replacements) {
    delete tokenObj.tokens // we just want to process the files,objs

    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) return callback(err)
      replacements['file'] = path.basename(filePath)
      var newFileData = S(data).template(replacements, topen, tclose).s

      fs.writeFile(filePath, newFileData, callback)
    })
  }
}

function fetchRepo (projectPath, repoPath, options, callback) {
  projectPath = path.resolve(projectPath)
  var projectRockPath = path.join(projectPath, '.rock')
  var projectRockConf = path.join(projectRockPath, 'rock.json')
  var projectRockObj = {} // empty config

  if (typeof options === 'function') callback = options
  if (!options.defaultValues) options.defaultValues = {}
  if (!options.templateValues) options.templateValues = {}

  // Check if rock is local:
  fs.exists(repoPath, copyOrDownload)
  function copyOrDownload (itsLocal) {
    if (itsLocal) {
      fs.copy(repoPath, projectPath, {filter: function (p) {
        return !/.*\/\.git$/.test(p)
      }}, checkRockConf)
    } else {
      ghdownload(repoPath, projectPath)
      .on('error', callback)
      .on('end', checkRockConf)
    }
  }
  function checkRockConf (err) {
    if (err) return callback(err)
    // console.log('checkRockConf')
    fs.exists(projectRockConf, loadRockConf)
  }
  function loadRockConf (rockConfExists) {
    if (rockConfExists) {
      fs.readJson(projectRockConf, walkFilesAndLoadTokenSettings)
    } else {
      walkFilesAndLoadTokenSettings()
    }
  }
  function walkFilesAndLoadTokenSettings (err, data) {
    if (err) return callback(err)
    // console.log('walkFiles')
    var files = []
    var ignoreDirs = []

    if (data) {
      projectRockObj = data
      ignoreDirs = projectRockObj.ignoreDirs || []
      for (var i = 0; i < ignoreDirs.length; ++i) {
        ignoreDirs[i] = path.resolve(projectPath, ignoreDirs[i])
      }

      if (projectRockObj.tokens) {
        S.TMPL_OPEN = projectRockObj.tokens.open || S.TMPL_OPEN
        S.TMPL_CLOSE = projectRockObj.tokens.close || S.TMPL_CLOSE
      }
    }

    walker(projectPath)
    .filterDir(function (dir, stat) { // return false if you want to filter
      // if current dir is the .rock filter, then obviously filter... else filter if it is found in ignoreDirs
      return (dir === projectRockPath) ? false : !(ignoreDirs.indexOf(dir) >= 0)
    })
    .on('file', function (file) { files.push(file) })
    .on('end', function () { tweezeFiles(files) })
  }
  function tweezeFiles (files) {
    // console.log('tweezefiles');
    tweezers.readFilesAndExtract(files, S.TMPL_OPEN, S.TMPL_CLOSE, promptUser)
  }
  function promptUser (err, tokenObj) {
    if (err) return callback(err)
    var replacements = {'file': S.TMPL_OPEN + 'file' + S.TMPL_CLOSE}

    replacements = rutil.extend(replacements, dt.eval('date-'))
    replacements = rutil.extend(replacements, options.templateValues)

    rlp(tokenObj.tokens, options.defaultValues, replacements).end(function (results) {
      outputFiles(tokenObj, results)
    })
  }
  function outputFiles (tokenObj, replacements) {
    delete tokenObj.tokens // we just want to process the files,objs

    batch(tokenObj).par().each(function (file, fileTokens, done) {
      fs.readFile(file, 'utf8', function (err, data) {
        if (err) throw err
        var newFileName = S(file).template(replacements).s
        replacements['file'] = path.basename(newFileName)

        var newFileData = S(data).template(replacements).s

        fs.writeFile(newFileName, newFileData, function (err) {
          if (err) throw err // this should be caught by ERROR above
          if (file !== newFileName) {
            fs.remove(file, function (err) {
              if (err) throw err
              done()
            })
          } else {
            done()
          }
        })
      })
    }).end(deleteRockFolder)
  }
  function deleteRockFolder (a) {
    fs.remove(projectRockPath, callback)
  }
}

module.exports.fetchRepo = fetchRepo
module.exports.fetchFile = fetchFile
<|endoftext|>


<commit_before>/*
var THREE = require('three');

module.exports = {
  transformSVGPath: transformSVGPath
};
*/

function createShape( shape, color, x, y, z, rx, ry, rz, s ) {
  // flat shape

  var geometry = new THREE.ShapeGeometry( shape );
  var material = new THREE.MeshBasicMaterial({
    color: color,
    side: THREE.DoubleSide,
    overdraw: true
  });

  var mesh = new THREE.Mesh( geometry, material );
  mesh.position.set( x, y, z );
  mesh.rotation.set( rx, ry, rz );
  mesh.scale.set( s, s, s );

  return mesh;
}

function transformSVGPath(pathStr) {

  const DIGIT_0 = 48, DIGIT_9 = 57, COMMA = 44, SPACE = 32, PERIOD = 46,
      MINUS = 45;

  var path = new THREE.Shape();

  var idx = 1, len = pathStr.length, activeCmd,
      x = 0, y = 0, nx = 0, ny = 0, firstX = null, firstY = null,
      x1 = 0, x2 = 0, y1 = 0, y2 = 0,
      rx = 0, ry = 0, xar = 0, laf = 0, sf = 0, cx, cy;

  function eatNum() {
    var sidx, c, isFloat = false, s;
    // eat delims
    while (idx < len) {
      c = pathStr.charCodeAt(idx);
      if (c !== COMMA && c !== SPACE)
        break;
      idx++;
    }
    if (c === MINUS)
      sidx = idx++;
    else
      sidx = idx;
    // eat number
    while (idx < len) {
      c = pathStr.charCodeAt(idx);
      if (DIGIT_0 <= c && c <= DIGIT_9) {
        idx++;
        continue;
      }
      else if (c === PERIOD) {
        idx++;
        isFloat = true;
        continue;
      }

      s = pathStr.substring(sidx, idx);
      return isFloat ? parseFloat(s) : parseInt(s);
    }

    s = pathStr.substring(sidx);
    return isFloat ? parseFloat(s) : parseInt(s);
  }

  function nextIsNum() {
    var c;
    // do permanently eat any delims...
    while (idx < len) {
      c = pathStr.charCodeAt(idx);
      if (c !== COMMA && c !== SPACE)
        break;
      idx++;
    }
    c = pathStr.charCodeAt(idx);
    return (c === MINUS || (DIGIT_0 <= c && c <= DIGIT_9));
  }

  var canRepeat;
  activeCmd = pathStr[0];
  while (idx <= len) {
    canRepeat = true;
    switch (activeCmd) {
        // moveto commands, become lineto's if repeated
      case 'M':
        x = eatNum();
        y = eatNum();
        path.moveTo(x, y);
        activeCmd = 'L';
        break;
      case 'm':
        x += eatNum();
        y += eatNum();
        path.moveTo(x, y);
        activeCmd = 'l';
        break;
      case 'Z':
      case 'z':
        canRepeat = false;
        if (x !== firstX || y !== firstY)
          path.lineTo(firstX, firstY);
        break;
        // - lines!
      case 'L':
      case 'H':
      case 'V':
        nx = (activeCmd === 'V') ? x : eatNum();
        ny = (activeCmd === 'H') ? y : eatNum();
        path.lineTo(nx, ny);
        x = nx;
        y = ny;
        break;
      case 'l':
      case 'h':
      case 'v':
        nx = (activeCmd === 'v') ? x : (x + eatNum());
        ny = (activeCmd === 'h') ? y : (y + eatNum());
        path.lineTo(nx, ny);
        x = nx;
        y = ny;
        break;
        // - cubic bezier
      case 'C':
        x1 = eatNum(); y1 = eatNum();
      case 'S':
        if (activeCmd === 'S') {
          x1 = 2 * x - x2; y1 = 2 * y - y2;
        }
        x2 = eatNum();
        y2 = eatNum();
        nx = eatNum();
        ny = eatNum();
        path.bezierCurveTo(x1, y1, x2, y2, nx, ny);
        x = nx; y = ny;
        break;
      case 'c':
        x1 = x + eatNum();
        y1 = y + eatNum();
      case 's':
        if (activeCmd === 's') {
          x1 = 2 * x - x2;
          y1 = 2 * y - y2;
        }
        x2 = x + eatNum();
        y2 = y + eatNum();
        nx = x + eatNum();
        ny = y + eatNum();
        path.bezierCurveTo(x1, y1, x2, y2, nx, ny);
        x = nx; y = ny;
        break;
        // - quadratic bezier
      case 'Q':
        x1 = eatNum(); y1 = eatNum();
      case 'T':
        if (activeCmd === 'T') {
          x1 = 2 * x - x1;
          y1 = 2 * y - y1;
        }
        nx = eatNum();
        ny = eatNum();
        path.quadraticCurveTo(x1, y1, nx, ny);
        x = nx;
        y = ny;
        break;
      case 'q':
        x1 = x + eatNum();
        y1 = y + eatNum();
      case 't':
        if (activeCmd === 't') {
          x1 = 2 * x - x1;
          y1 = 2 * y - y1;
        }
        nx = x + eatNum();
        ny = y + eatNum();
        path.quadraticCurveTo(x1, y1, nx, ny);
        x = nx; y = ny;
        break;
        // - elliptical arc
      case 'A':
        rx = eatNum();
        ry = eatNum();
        xar = eatNum() * DEGS_TO_RADS;
        laf = eatNum();
        sf = eatNum();
        nx = eatNum();
        ny = eatNum();
        if (rx !== ry) {
          console.warn("Forcing elliptical arc to be a circular one :(",
                       rx, ry);
        }
        // SVG implementation notes does all the math for us! woo!
        // http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
        // step1, using x1 as x1'
        x1 = Math.cos(xar) * (x - nx) / 2 + Math.sin(xar) * (y - ny) / 2;
        y1 = -Math.sin(xar) * (x - nx) / 2 + Math.cos(xar) * (y - ny) / 2;
        // step 2, using x2 as cx'
        var norm = Math.sqrt(
          (rx*rx * ry*ry - rx*rx * y1*y1 - ry*ry * x1*x1) /
          (rx*rx * y1*y1 + ry*ry * x1*x1));
        if (laf === sf)
          norm = -norm;
        x2 = norm * rx * y1 / ry;
        y2 = norm * -ry * x1 / rx;
        // step 3
        cx = Math.cos(xar) * x2 - Math.sin(xar) * y2 + (x + nx) / 2;
        cy = Math.sin(xar) * x2 + Math.cos(xar) * y2 + (y + ny) / 2;

        var u = new THREE.Vector2(1, 0),
            v = new THREE.Vector2((x1 - x2) / rx,
                                  (y1 - y2) / ry);
        var startAng = Math.acos(u.dot(v) / u.length() / v.length());
        if (u.x * v.y - u.y * v.x < 0)
          startAng = -startAng;

        // we can reuse 'v' from start angle as our 'u' for delta angle
        u.x = (-x1 - x2) / rx;
        u.y = (-y1 - y2) / ry;

        var deltaAng = Math.acos(v.dot(u) / v.length() / u.length());
        // This normalization ends up making our curves fail to triangulate...
        if (v.x * u.y - v.y * u.x < 0)
          deltaAng = -deltaAng;
        if (!sf && deltaAng > 0)
          deltaAng -= Math.PI * 2;
        if (sf && deltaAng < 0)
          deltaAng += Math.PI * 2;

        path.absarc(cx, cy, rx, startAng, startAng + deltaAng, sf);
        x = nx;
        y = ny;
        break;
      default:
        throw new Error("weird path command: " + activeCmd);
    }
    if (firstX === null) {
      firstX = x;
      firstY = y;
    }
    // just reissue the command
    if (canRepeat && nextIsNum())
      continue;
    activeCmd = pathStr[idx++];
  }

  return path;
}
<commit_msg>Updates pathToShape<commit_after>/*
var THREE = require('three');

module.exports = {
  transformSVGPath: transformSVGPath
};
*/

function createShape( shape, color, x, y, z, rx, ry, rz, s ) {
  // flat shape

  var geometry = new THREE.ShapeGeometry( shape );
  var material = new THREE.MeshBasicMaterial({
    color: color,
    side: THREE.DoubleSide,
    overdraw: true
  });

  var mesh = new THREE.Mesh( geometry, material );
  mesh.position.set( x, y, z );
  mesh.rotation.set( rx, ry, rz );
  mesh.scale.set( s, s, s );

  return mesh;
}

const DEGS_TO_RADS = Math.PI / 180, UNIT_SIZE = 100;

const DIGIT_0 = 48, DIGIT_9 = 57, COMMA = 44, SPACE = 32, PERIOD = 46, MINUS = 45;

function transformSVGPath(pathStr) {
	var path = new THREE.Shape();

	var idx = 1, len = pathStr.length, activeCmd,
		x = 0, y = 0, nx = 0, ny = 0, firstX = null, firstY = null,
		x1 = 0, x2 = 0, y1 = 0, y2 = 0,
		rx = 0, ry = 0, xar = 0, laf = 0, sf = 0, cx, cy;

	function eatNum() {
		var sidx, c, isFloat = false, s;
		// eat delims
		while (idx < len) {
			c = pathStr.charCodeAt(idx);
			if (c !== COMMA && c !== SPACE)
				break;
			idx++;
		}
		if (c === MINUS)
			sidx = idx++;
		else
			sidx = idx;
		// eat number
		while (idx < len) {
			c = pathStr.charCodeAt(idx);
			if (DIGIT_0 <= c && c <= DIGIT_9) {
				idx++;
				continue;
			}
			else if (c === PERIOD) {
				idx++;
				isFloat = true;
				continue;
			}

			s = pathStr.substring(sidx, idx);
			return isFloat ? parseFloat(s) : parseInt(s);
		}

		s = pathStr.substring(sidx);
		return isFloat ? parseFloat(s) : parseInt(s);
	}

	function nextIsNum() {
		var c;
		// do permanently eat any delims...
		while (idx < len) {
			c = pathStr.charCodeAt(idx);
			if (c !== COMMA && c !== SPACE)
				break;
			idx++;
		}
		c = pathStr.charCodeAt(idx);
		return (c === MINUS || (DIGIT_0 <= c && c <= DIGIT_9));
	}

	var canRepeat;
	activeCmd = pathStr[0];
	while (idx <= len) {
		canRepeat = true;
		switch (activeCmd) {
			// moveto commands, become lineto's if repeated
			case 'M':
				x = eatNum();
				y = eatNum();
				path.moveTo(x, y);
				activeCmd = 'L';
				firstX = x;
				firstY = y;
				break;
			case 'm':
				x += eatNum();
				y += eatNum();
				path.moveTo(x, y);
				activeCmd = 'l';
				firstX = x;
				firstY = y;
				break;
			case 'Z':
			case 'z':
				canRepeat = false;
				if (x !== firstX || y !== firstY)
					path.lineTo(firstX, firstY);
				break;
			// - lines!
			case 'L':
			case 'H':
			case 'V':
				nx = (activeCmd === 'V') ? x : eatNum();
				ny = (activeCmd === 'H') ? y : eatNum();
				path.lineTo(nx, ny);
				x = nx;
				y = ny;
				break;
			case 'l':
			case 'h':
			case 'v':
				nx = (activeCmd === 'v') ? x : (x + eatNum());
				ny = (activeCmd === 'h') ? y : (y + eatNum());
				path.lineTo(nx, ny);
				x = nx;
				y = ny;
				break;
			// - cubic bezier
			case 'C':
				x1 = eatNum(); y1 = eatNum();
			case 'S':
				if (activeCmd === 'S') {
					x1 = 2 * x - x2; y1 = 2 * y - y2;
				}
				x2 = eatNum();
				y2 = eatNum();
				nx = eatNum();
				ny = eatNum();
				path.bezierCurveTo(x1, y1, x2, y2, nx, ny);
				x = nx; y = ny;
				break;
			case 'c':
				x1 = x + eatNum();
				y1 = y + eatNum();
			case 's':
				if (activeCmd === 's') {
					x1 = 2 * x - x2;
					y1 = 2 * y - y2;
				}
				x2 = x + eatNum();
				y2 = y + eatNum();
				nx = x + eatNum();
				ny = y + eatNum();
				path.bezierCurveTo(x1, y1, x2, y2, nx, ny);
				x = nx; y = ny;
				break;
			// - quadratic bezier
			case 'Q':
				x1 = eatNum(); y1 = eatNum();
			case 'T':
				if (activeCmd === 'T') {
					x1 = 2 * x - x1;
					y1 = 2 * y - y1;
				}
				nx = eatNum();
				ny = eatNum();
				path.quadraticCurveTo(x1, y1, nx, ny);
				x = nx;
				y = ny;
				break;
			case 'q':
				x1 = x + eatNum();
				y1 = y + eatNum();
			case 't':
				if (activeCmd === 't') {
					x1 = 2 * x - x1;
					y1 = 2 * y - y1;
				}
				nx = x + eatNum();
				ny = y + eatNum();
				path.quadraticCurveTo(x1, y1, nx, ny);
				x = nx; y = ny;
				break;
			// - elliptical arc
			case 'A':
				rx = eatNum();
				ry = eatNum();
				xar = eatNum() * DEGS_TO_RADS;
				laf = eatNum();
				sf = eatNum();
				nx = eatNum();
				ny = eatNum();
				if (rx !== ry) {
					console.warn("Forcing elliptical arc to be a circular one :(",
						rx, ry);
				}
				// SVG implementation notes does all the math for us! woo!
				// http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
				// step1, using x1 as x1'
				x1 = Math.cos(xar) * (x - nx) / 2 + Math.sin(xar) * (y - ny) / 2;
				y1 = -Math.sin(xar) * (x - nx) / 2 + Math.cos(xar) * (y - ny) / 2;
				// step 2, using x2 as cx'
				var norm = Math.sqrt(
					 (rx*rx * ry*ry - rx*rx * y1*y1 - ry*ry * x1*x1) /
					 (rx*rx * y1*y1 + ry*ry * x1*x1));
				if (laf === sf)
					norm = -norm;
				x2 = norm * rx * y1 / ry;
				y2 = norm * -ry * x1 / rx;
				// step 3
				cx = Math.cos(xar) * x2 - Math.sin(xar) * y2 + (x + nx) / 2;
				cy = Math.sin(xar) * x2 + Math.cos(xar) * y2 + (y + ny) / 2;

				var u = new THREE.Vector2(1, 0),
					v = new THREE.Vector2((x1 - x2) / rx,
					                      (y1 - y2) / ry);
				var startAng = Math.acos(u.dot(v) / u.length() / v.length());
				if (u.x * v.y - u.y * v.x < 0)
					startAng = -startAng;

				// we can reuse 'v' from start angle as our 'u' for delta angle
				u.x = (-x1 - x2) / rx;
				u.y = (-y1 - y2) / ry;

				var deltaAng = Math.acos(v.dot(u) / v.length() / u.length());
				// This normalization ends up making our curves fail to triangulate...
				if (v.x * u.y - v.y * u.x < 0)
					deltaAng = -deltaAng;
				if (!sf && deltaAng > 0)
					deltaAng -= Math.PI * 2;
				if (sf && deltaAng < 0)
					deltaAng += Math.PI * 2;

				path.absarc(cx, cy, rx, startAng, startAng + deltaAng, sf);
				x = nx;
				y = ny;
				break;
			default:
				throw new Error("weird path command: " + activeCmd);
		}
		// just reissue the command
		if (canRepeat && nextIsNum())
			continue;
		activeCmd = pathStr[idx++];
	}

	return path;
}
<|endoftext|>


<commit_before>L.TileLayer.MetaInfoTiles = L.TileLayer.extend({
    includes: L.Mixin.Events,

    initialize: function(url, options) {
        options.unloadInvisibleTiles = true;
        options.reuseTiles = false;

        L.TileLayer.prototype.initialize.call(this, url, options);
    },

    onAdd: function(map) {
        this._resetQueue();

        L.TileLayer.prototype.onAdd.call(this, map);

        L.DomEvent
            .on(document, 'mousemove', this._onMouseMove, this) //L.Util.throttle(this._onMouseMove, 32, tile), tile)
            .on(document, 'click', this._onClick, this);
    },

    onRemove: function(map) {
        this._resetQueue();

        L.TileLayer.prototype.onRemove.call(this, map);
    },

    _initContainer: function() {
        var tilePane = this._map._panes.overlayPane;

        if (!this._container) {
            this._container = L.DomUtil.create('div', 'leaflet-layer');

            this._updateZIndex();

            if (this._animated) {
                var className = 'leaflet-tile-container';

                this._bgBuffer = L.DomUtil.create('div', className, this._container);
                this._tileContainer = L.DomUtil.create('div', className, this._container);

            } else {
                this._tileContainer = this._container;
            }

            this._tileContainer.style.zIndex = this.options.zIndex;

            tilePane.appendChild(this._container);
            this._container.style['pointer-events'] = 'none';

            if (this.options.opacity < 1) {
                this._updateOpacity();
            }
        }
    },

    findElement: function(e, container) {
        if (!container)
            return null;

        var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
            i, len, tile;

        for (i = 0, len = tiles.length; i < len; i++) {
            tile = tiles[i];
            var mp = L.DomEvent.getMousePosition(e, tile);

            for (var j = tile._layers.length - 1; j >= 0; j--) {
                var layer = tile._layers[j];
				var width = Math.abs(layer.pixelBoundingBox.right - layer.pixelBoundingBox.left);
				var height = Math.abs(layer.pixelBoundingBox.top - layer.pixelBoundingBox.bottom);
                if ((layer.referencePixelPoint.x - width/2 <= mp.x) && (layer.referencePixelPoint.x + width/2 >= mp.x) &&
                    (layer.referencePixelPoint.y - height/2 <= mp.y) && (layer.referencePixelPoint.y + height/2 >= mp.y)) {
                    return layer;
                }
            }
        }

        return null;
    },

    _onMouseMove: function(e) {
        if (!this._map || this._map.dragging._draggable._moving || this._map._animatingZoom) {
            return;
        }

        if (this.findElement(e, this._container)) {
            e.preventDefault();

            this._container.style['pointer-events'] = 'auto';
            L.DomUtil.addClass(this._container, 'leaflet-clickable'); // change cursor
        } else {
            this._container.style['pointer-events'] = 'none';
            L.DomUtil.removeClass(this._container, 'leaflet-clickable');
        }
    },

    _onClick: function(e) {
        var found = this.findElement(e, this._container);
        if (found) {
            e.preventDefault();

            var description = '';
            for (var i = 0; i < found.attributes.length; i++) {
                var attribute = found.attributes[i];
                description = description.concat(
                    attribute.key.replace(/[A-Z]/g, " $&") + ': ' +
                    attribute.value.replace("_", " ") + '
');
            }

            L.popup()
                .setLatLng(found.latLng)
                .setContent(description
                    .toLowerCase())
                .openOn(map);

            e.stopPropagation();
            return false;
        }
    },

    pixToLatLng: function(tileKey, point) {
        var earthHalfCircum = Math.PI;
        var earthCircum = earthHalfCircum * 2.0
        var arc = earthCircum / Math.pow(2, tileKey.z);
        var x = -earthHalfCircum + (tileKey.x + (point.x / 256.0)) * arc;
        var y = earthHalfCircum - (tileKey.y + (point.y / 256.0)) * arc;

        return L.latLng(
            (360 / Math.PI) * (Math.atan(Math.exp(y)) - (Math.PI / 4)),
            (180.0 / Math.PI) * x);
    },

    maxConcurrentRequests: 4,

    activeRequestCount: 0,

    requestQueue: [],

    currentRequests: [],

    _reset: function() {
        this._resetQueue();
        for (var key in this._tiles) {
            this._resetTile(this._tiles[key]);
        }

        for (var key in this._unusedTiles) {
            this._resetTile(this._unusedTiles[key]);
        }

        L.TileLayer.prototype._reset.call(this);
    },

    cnt: 0,

    _resetQueue: function() {
        this.requestQueue = [];
        this.cnt = this.cnt + 1;
        for (var i = 0; i < this.currentRequests.length; i++)
            this.currentRequests[i].abort();
        this.currentRequests = [];

        this.activeRequestCount = 0;
    },

    runRequestQ: function(url, handleSuccess, force) {
        if (!force && this.activeRequestCount >= this.maxConcurrentRequests) {
            this.requestQueue.push({
                url: url,
                handleSuccess: handleSuccess
            });
            return;
        }
        if (!force)
            this.activeRequestCount++;

        var that = this;
        var cnt = this.cnt;

        var request = corslite(url,
            function(err, resp) {
                that.currentRequests.splice(that.currentRequests.indexOf(request), 1);
                if (that.cnt == cnt && that.requestQueue.length) {
                    var pendingRequest = that.requestQueue.shift();
                    that.runRequestQ(pendingRequest.url, pendingRequest.handleSuccess, true);
                } else {
                    that.activeRequestCount--;
                }
                handleSuccess(err, resp);
            }
			, true); // cross origin?

        this.currentRequests.push(request);
    },

    _loadTile: function(tile, coords) {
        //        var tile = document.createElement('img');
        //        tile.style['pointer-events'] = 'auto';
        if (!this._map)
            return;

        tile._map = this._map;
        tile._layers = [];
        tile._layer = this;
        tile.onload = this._tileOnLoad;
        tile.onerror = this._tileOnError;

        this._adjustTilePoint(coords);

        var url = this.getTileUrl(coords);

        this.runRequestQ(url,
            L.bind(function(error, response) {
                if (!this._map)
                    return;

				if(error)
					return;

				var resp = JSON.parse(response.responseText)

                var prefixMap = {
                    "iVBOR": "data:image/png;base64,",
                    "R0lGO": "data:image/gif;base64,",
                    "/9j/4": "data:image/jpeg;base64,",
                    "Qk02U": "data:image/bmp;base64,"
                };

                var rawImage = resp.image;
                tile.src = prefixMap[rawImage.substr(0, 5)] + rawImage;
                this._resetTile(tile);

                if (resp.features &&
                    this._container &&
                    this._tileContainer.style.visibility !== 'hidden') {
                    var objectInfos = resp.features;

                    for (var i = 0; i < objectInfos.length; i++) {
                        var oi = objectInfos[i];
                        oi.latLng = this.pixToLatLng(coords, oi.referencePixelPoint);
                        tile._layers.push(oi);
                    }
                }
            }, this));

        this.fire('tileloadstart', {
            tile: tile,
            url: tile.src
        });
    }
});<commit_msg>using pixel bbox for objectInfos<commit_after>L.TileLayer.MetaInfoTiles = L.TileLayer.extend({
    includes: L.Mixin.Events,

    initialize: function(url, options) {
        options.unloadInvisibleTiles = true;
        options.reuseTiles = false;

        L.TileLayer.prototype.initialize.call(this, url, options);
    },

    onAdd: function(map) {
        this._resetQueue();

        L.TileLayer.prototype.onAdd.call(this, map);

        L.DomEvent
            .on(document, 'mousemove', this._onMouseMove, this) //L.Util.throttle(this._onMouseMove, 32, tile), tile)
            .on(document, 'click', this._onClick, this);
    },

    onRemove: function(map) {
        this._resetQueue();

        L.TileLayer.prototype.onRemove.call(this, map);
    },

    _initContainer: function() {
        var tilePane = this._map._panes.overlayPane;

        if (!this._container) {
            this._container = L.DomUtil.create('div', 'leaflet-layer');

            this._updateZIndex();

            if (this._animated) {
                var className = 'leaflet-tile-container';

                this._bgBuffer = L.DomUtil.create('div', className, this._container);
                this._tileContainer = L.DomUtil.create('div', className, this._container);

            } else {
                this._tileContainer = this._container;
            }

            this._tileContainer.style.zIndex = this.options.zIndex;

            tilePane.appendChild(this._container);
            this._container.style['pointer-events'] = 'none';

            if (this.options.opacity < 1) {
                this._updateOpacity();
            }
        }
    },

    findElement: function(e, container) {
        if (!container)
            return null;

        var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
            i, len, tile;

        for (i = 0, len = tiles.length; i < len; i++) {
            tile = tiles[i];
            var mp = L.DomEvent.getMousePosition(e, tile);

            for (var j = tile._layers.length - 1; j >= 0; j--) {
                var layer = tile._layers[j];
				var width = Math.abs(layer.pixelBoundingBox.right - layer.pixelBoundingBox.left);
				var height = Math.abs(layer.pixelBoundingBox.top - layer.pixelBoundingBox.bottom);
                if ((layer.referencePixelPoint.x - width/2 <= mp.x) && (layer.referencePixelPoint.x + width/2 >= mp.x) &&
                    (layer.referencePixelPoint.y - height/2 <= mp.y) && (layer.referencePixelPoint.y + height/2 >= mp.y)) {
                    return layer;
                }
            }
        }

        return null;
    },

    _onMouseMove: function(e) {
        if (!this._map || this._map.dragging._draggable._moving || this._map._animatingZoom) {
            return;
        }

        if (this.findElement(e, this._container)) {
            e.preventDefault();

            this._container.style['pointer-events'] = 'auto';
            L.DomUtil.addClass(this._container, 'leaflet-clickable'); // change cursor
        } else {
            this._container.style['pointer-events'] = 'none';
            L.DomUtil.removeClass(this._container, 'leaflet-clickable');
        }
    },

    _onClick: function(e) {
        var found = this.findElement(e, this._container);
        if (found) {
            e.preventDefault();

            var description = '';
            for (var i = 0; i < found.attributes.length; i++) {
                var attribute = found.attributes[i];
                description = description.concat(
                    attribute.key.replace(/[A-Z]/g, " $&") + ': ' +
                    attribute.value.replace("_", " ") + '
');
            }

            L.popup()
                .setLatLng(found.latLng)
                .setContent(description
                    .toLowerCase())
                .openOn(map);

            e.stopPropagation();
            return false;
        }
    },

    pixToLatLng: function(tileKey, point) {
        var earthHalfCircum = Math.PI;
        var earthCircum = earthHalfCircum * 2.0
        var arc = earthCircum / Math.pow(2, tileKey.z);
        var x = -earthHalfCircum + (tileKey.x + (point.x / 256.0)) * arc;
        var y = earthHalfCircum - (tileKey.y + (point.y / 256.0)) * arc;

        return L.latLng(
            (360 / Math.PI) * (Math.atan(Math.exp(y)) - (Math.PI / 4)),
            (180.0 / Math.PI) * x);
    },

    maxConcurrentRequests: 4,

    activeRequestCount: 0,

    requestQueue: [],

    currentRequests: [],

    _reset: function() {
        this._resetQueue();
        for (var key in this._tiles) {
            this._resetTile(this._tiles[key]);
        }

        for (var key in this._unusedTiles) {
            this._resetTile(this._unusedTiles[key]);
        }

        L.TileLayer.prototype._reset.call(this);
    },

    cnt: 0,

    _resetQueue: function() {
        this.requestQueue = [];
        this.cnt = this.cnt + 1;
        for (var i = 0; i < this.currentRequests.length; i++)
            this.currentRequests[i].abort();
        this.currentRequests = [];

        this.activeRequestCount = 0;
    },

    runRequestQ: function(url, handleSuccess, force) {
        if (!force && this.activeRequestCount >= this.maxConcurrentRequests) {
            this.requestQueue.push({
                url: url,
                handleSuccess: handleSuccess
            });
            return;
        }
        if (!force)
            this.activeRequestCount++;

        var that = this;
        var cnt = this.cnt;

        var request = corslite(url,
            function(err, resp) {
                that.currentRequests.splice(that.currentRequests.indexOf(request), 1);
                if (that.cnt == cnt && that.requestQueue.length) {
                    var pendingRequest = that.requestQueue.shift();
                    that.runRequestQ(pendingRequest.url, pendingRequest.handleSuccess, true);
                } else {
                    that.activeRequestCount--;
                }
                handleSuccess(err, resp);
            }
			, true); // cross origin?

        this.currentRequests.push(request);
    },

    _loadTile: function(tile, coords) {
        if (!this._map)
            return;

        tile._map = this._map;
        tile._layers = [];
        tile._layer = this;
        tile.onload = this._tileOnLoad;
        tile.onerror = this._tileOnError;

        this._adjustTilePoint(coords);

        var url = this.getTileUrl(coords);

        this.runRequestQ(url,
            L.bind(function(error, response) {
                if (!this._map)
                    return;

				if(error) {
					tile.src = '//';
					return;
				}

				var resp = JSON.parse(response.responseText)

                var prefixMap = {
                    "iVBOR": "data:image/png;base64,",
                    "R0lGO": "data:image/gif;base64,",
                    "/9j/4": "data:image/jpeg;base64,",
                    "Qk02U": "data:image/bmp;base64,"
                };

                var rawImage = resp.image;
                tile.src = prefixMap[rawImage.substr(0, 5)] + rawImage;
                this._resetTile(tile);

                if (resp.features &&
                    this._container &&
                    this._tileContainer.style.visibility !== 'hidden') {
                    var objectInfos = resp.features;

                    for (var i = 0; i < objectInfos.length; i++) {
                        var oi = objectInfos[i];
                        oi.latLng = this.pixToLatLng(coords, oi.referencePixelPoint);
                        tile._layers.push(oi);
                    }
                }
            }, this));

        this.fire('tileloadstart', {
            tile: tile,
            url: tile.src
        });
    }
});<|endoftext|>


<commit_before>yaml = require('js-yaml') ,
utils = require('./utils'),
util = require('util'),
docker = require('./docker')

function generate(data) {
	return yaml.dump(data)
}

function getContainerID(path, service, callback) {
	return utils.cmd('cd '+path+'; docker-compose ps -q '+ service,function(err, data) {

			if(err)
				callback(err, data)
			else {
				var containerID = data
				//Replace newlines
				containerID = containerID.replace(/(\r\n|\n|\r)/gm,"");
				callback(null,containerID)
			}

	})

}

//Call docker-compose up in path and returns the process pid
function up(path, callback, dataNotify) {

	var pid =  utils.cmd('cd '+path+'; docker-compose  up -d', callback)
	//TODO Check if callback is defined
	utils.docker_logs(pid, dataNotify)
	return pid

}
//Call docker-compose down in path and returns the process pid
function down(path, callback, dataNotify) {

	var pid= utils.cmd('cd '+path+'; docker-compose down', callback)
	utils.docker_logs(pid, dataNotify)

	return pid

}

function cp(path, service, src, dst, callback) {

		getContainerID(path, service, function(err, data) {
			//No err : get containerID = data
			if(!err)
			{
				var containerID = data
				//Cal docker exec
				return docker.cp(containerID, src, dst, callback)
			}
			else   {
			callback(err)
			return null
			}

		})

}

function exec(path, service, command, callback, paramsInput) {

	var paramsProto = {
		detached: false
	}

	//Get the params
	var params = _.extend({}, paramsProto, paramsInput)

	if(!params.detached)
		return utils.cmd('cd '+path+'; docker-compose exec '+ service + ' ' +command, callback)

	//Workaround for detached mode docker-compose
	else {
		getContainerID(path, service, function(err, data) {
			//No err : get containerID = data
			if(!err)
			{

				var containerID = data
				//Cal docker exec
				return docker.exec(containerID, command, callback, params)

			}
			else callback(err)

		})
	//	return cmd.get('cd '+path+'; docker-compose exec '+ service + ' ' +command, callback)
		}
}

exports.generate = generate
exports.up = up
exports.down = down
exports.exec = exec
exports.cp = cp
exports.getContainerID = getContainerID
<commit_msg>Resolved a bug of underscore<commit_after>yaml = require('js-yaml') ,
utils = require('./utils'),
util = require('util'),
_ = require('underscore');
docker = require('./docker')

function generate(data) {
	return yaml.dump(data)
}

function getContainerID(path, service, callback) {
	return utils.cmd('cd '+path+'; docker-compose ps -q '+ service,function(err, data) {

			if(err)
				callback(err, data)
			else {
				var containerID = data
				//Replace newlines
				containerID = containerID.replace(/(\r\n|\n|\r)/gm,"");
				callback(null,containerID)
			}

	})

}

//Call docker-compose up in path and returns the process pid
function up(path, callback, dataNotify) {

	var pid =  utils.cmd('cd '+path+'; docker-compose  up -d', callback)
	//TODO Check if callback is defined
	utils.docker_logs(pid, dataNotify)
	return pid

}
//Call docker-compose down in path and returns the process pid
function down(path, callback, dataNotify) {

	var pid= utils.cmd('cd '+path+'; docker-compose down', callback)
	utils.docker_logs(pid, dataNotify)

	return pid

}

function cp(path, service, src, dst, callback) {

		getContainerID(path, service, function(err, data) {
			//No err : get containerID = data
			if(!err)
			{
				var containerID = data
				//Cal docker exec
				return docker.cp(containerID, src, dst, callback)
			}
			else   {
			callback(err)
			return null
			}

		})

}

function exec(path, service, command, callback, paramsInput) {

	var paramsProto = {
		detached: false
	}

	//Get the params
	var params = _.extend({}, paramsProto, paramsInput)

	if(!params.detached)
		return utils.cmd('cd '+path+'; docker-compose exec '+ service + ' ' +command, callback)

	//Workaround for detached mode docker-compose
	else {
		getContainerID(path, service, function(err, data) {
			//No err : get containerID = data
			if(!err)
			{

				var containerID = data
				//Cal docker exec
				return docker.exec(containerID, command, callback, params)

			}
			else callback(err)

		})
	//	return cmd.get('cd '+path+'; docker-compose exec '+ service + ' ' +command, callback)
		}
}

exports.generate = generate
exports.up = up
exports.down = down
exports.exec = exec
exports.cp = cp
exports.getContainerID = getContainerID
<|endoftext|>


<commit_before>/** const */
var REST_MATCH_PATH = 'rest';
var REST_PATH = REST_MATCH_PATH + '/';
var USECASE_PATH = 'main/';

/** globals to remove */
var notify = null;
var validationManager = null;
var errorManager = null;
var formatManager = null;
var notifyManager = null;
var localeManager = null;
var securityManager;
var dateRangePickerManager = null;
var momentManager;
var moment;

/**
 * Log info function.
 */
function traceLog(msg, context) {
	if (navigator.appVersion.indexOf('MSIE 7.') !== -1) {
		// FIX IE7, no format available
		if (typeof context === 'undefined') {
			window.console && window.console.log(msg);
		} else {
			window.console && window.console.log(msg + ' ' + (context || this));
		}
	} else if (typeof context === 'undefined') {
		window.console && window.console.log('%s', msg);
	} else {
		window.console && window.console.log('%s: %o', msg, context || this);
	}
	return this;
}

/**
 * Log debug function.
 */
function traceDebug(msg, context) {
	return window.console && applicationManager.debug && traceLog(msg, context);
}

/**
 * Shorthand of $(#id) and fastest.
 */
function _(id) {
	return $(document.getElementById(id));
}

/**
 * Protect window.console method calls, e.g. console is not defined on IE unless dev tools are open,
 * and IE doesn't define console.debug
 */
(function () {
	if (!window.console) {
		window.console = {};
	}
	// union of Chrome, FF, IE, and Safari console methods
	var m = ['log', 'info', 'warn', 'error', 'debug', 'trace', 'dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'profile', 'profileEnd', 'dirxml', 'assert', 'count', 'markTimeline', 'timeStamp', 'clear'];
	var i;
	// define undefined methods as noops to prevent errors
	for (i = 0; i < m.length; i++) {
		if (!window.console[m[i]]) {
			window.console[m[i]] = $.noop;
		}
	}

	/**
	 * Register some basic utilities.
	 */
	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function (val) {
			return $.inArray(val, this);
		};
	}
	if (typeof String.prototype.endsWith !== 'function') {
		String.prototype.endsWith = function (suffix) {
			return this.indexOf(suffix, this.length - suffix.length) !== -1;
		};
	}
	if (typeof String.prototype.startsWith !== 'function') {
		String.prototype.startsWith = function (str) {
			return this.indexOf(str) === 0;
		};
	}

	/**
	 * Register some basic utilities.
	 */
	String.prototype.capitalize = function () {
		return this.replace(/(?:^|\s)\S/g, function (a) {
			return a.toUpperCase();
		});
	};

	// Function transforming "sample-property" to "sampleProperty"
	String.prototype.toProperty = function () {
		return this.replace(/(?:-|\s)\S/g, function (a) {
			return a.toUpperCase();
		}).replace(/[\-\s]/g, '');
	};

	// Function to get the Max value in Array
	Array.max = function (array) {
		return Math.max.apply(Math, array);
	};

	// Function to get the Min value in Array
	Array.min = function (array) {
		return Math.min.apply(Math, array);
	};

	Array.maxAuto = function (array) {
		return Array.max(array) || Array.maxSparse(array);
	};
	Array.minAuto = function (array) {
		return Array.min(array) || Array.minSparse(array);
	};
	Array.maxSparse = function (array) {
		var narray = [];
		var i;
		for (i = 0; i < array.length; i++) {
			if (array[i]) {
				narray.push(array[i]);
			}
		}
		return Math.max.apply(Math, narray);
	};
	Array.minSparse = function (array) {
		var narray = [];
		var i;
		for (i = 0; i < array.length; i++) {
			if (array[i]) {
				narray.push(array[i]);
			}
		}
		return Math.min.apply(Math, narray);
	};
	Array.prototype.binarySearch = function (find) {
		var low = 0;
		var high = this.length - 1;
		var i;
		while (low <= high) {
			i = Math.floor((low + high) / 2);
			if (this[i] < find) {
				low = i + 1;
			} else if (this[i] > find) {
				high = i - 1;
			} else {
				return i;
			}
		}
		return null;
	};
})();

/**
 * Global error handler.
 */
window.onerror = function (message, url, line) {
	if (typeof errorManager === 'undefined' || errorManager === null) {
		traceLog('Uncaught error : ' + message + ':' + line);
	} else {
		errorManager.manageScriptError(message, url, line);
	}
	return false;
};
<commit_msg>Export the parameters management from the subscription wizard<commit_after>/** const */
var REST_MATCH_PATH = 'rest';
var REST_PATH = REST_MATCH_PATH + '/';
var USECASE_PATH = 'main/';

/** globals to remove */
var notify = null;
var validationManager = null;
var errorManager = null;
var formatManager = null;
var notifyManager = null;
var localeManager = null;
var securityManager;
var dateRangePickerManager = null;
var momentManager;
var moment;

/**
 * Log info function.
 */
function traceLog(msg, context) {
	if (navigator.appVersion.indexOf('MSIE 7.') !== -1) {
		// FIX IE7, no format available
		if (typeof context === 'undefined') {
			window.console && window.console.log(msg);
		} else {
			window.console && window.console.log(msg + ' ' + (context || this));
		}
	} else if (typeof context === 'undefined') {
		window.console && window.console.log('%s', msg);
	} else {
		window.console && window.console.log('%s: %o', msg, context || this);
	}
	return this;
}

/**
 * Log debug function.
 */
function traceDebug(msg, context) {
	return window.console && applicationManager.debug && traceLog(msg, context);
}

/**
 * Shorthand of $(#id) and fastest.
 */
function _(id) {
	return $(document.getElementById(id));
}

/**
 * Protect window.console method calls, e.g. console is not defined on IE unless dev tools are open,
 * and IE doesn't define console.debug
 */
(function () {
	if (!window.console) {
		window.console = {};
	}
	// union of Chrome, FF, IE, and Safari console methods
	var m = ['log', 'info', 'warn', 'error', 'debug', 'trace', 'dir', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'profile', 'profileEnd', 'dirxml', 'assert', 'count', 'markTimeline', 'timeStamp', 'clear'];
	var i;
	// define undefined methods as noops to prevent errors
	for (i = 0; i < m.length; i++) {
		if (!window.console[m[i]]) {
			window.console[m[i]] = $.noop;
		}
	}

	/**
	 * Register some basic utilities.
	 */
	if (!Array.prototype.indexOf) {
		Array.prototype.indexOf = function (val) {
			return $.inArray(val, this);
		};
	}
	if (typeof String.prototype.endsWith !== 'function') {
		String.prototype.endsWith = function (suffix) {
			return this.indexOf(suffix, this.length - suffix.length) !== -1;
		};
	}
	if (typeof String.prototype.startsWith !== 'function') {
		String.prototype.startsWith = function (str) {
			return this.indexOf(str) === 0;
		};
	}

	/**
	 * Register some basic utilities.
	 */
	String.prototype.capitalize = function () {
		return this.replace(/(?:^|\s)\S/g, function (a) {
			return a.toUpperCase();
		});
	};

	// Function transforming "sample-property" to "sampleProperty"
	String.prototype.toProperty = function () {
		return this.replace(/(?:-|\s)\S/g, function (a) {
			return a.toUpperCase();
		}).replace(/[\-\s]/g, '');
	};

	// Function to get the Max value in Array
	Array.max = function (array) {
		return Math.max.apply(Math, array);
	};

	// Function to get the Min value in Array
	Array.min = function (array) {
		return Math.min.apply(Math, array);
	};

	Array.maxAuto = function (array) {
		return Array.max(array) || Array.maxSparse(array);
	};
	Array.minAuto = function (array) {
		return Array.min(array) || Array.minSparse(array);
	};
	Array.maxSparse = function (array) {
		var narray = [];
		var i;
		for (i = 0; i < array.length; i++) {
			if (array[i]) {
				narray.push(array[i]);
			}
		}
		return Math.max.apply(Math, narray);
	};
	Array.minSparse = function (array) {
		var narray = [];
		var i;
		for (i = 0; i < array.length; i++) {
			if (array[i]) {
				narray.push(array[i]);
			}
		}
		return Math.min.apply(Math, narray);
	};
	Array.binarySearch = function (array, find) {
		var low = 0;
		var high = array.length - 1;
		var i;
		while (low <= high) {
			i = Math.floor((low + high) / 2);
			if (this[i] < find) {
				low = i + 1;
			} else if (this[i] > find) {
				high = i - 1;
			} else {
				return i;
			}
		}
		return null;
	};
})();

/**
 * Global error handler.
 */
window.onerror = function (message, url, line) {
	if (typeof errorManager === 'undefined' || errorManager === null) {
		traceLog('Uncaught error : ' + message + ':' + line);
	} else {
		errorManager.manageScriptError(message, url, line);
	}
	return false;
};
<|endoftext|>


<commit_before>var boot_params = require('./boot_params');
var platforms = require('./platforms');
var servers = require('./servers');
var tasks = require('./tasks');
var ur = require('./ur');
var vms = require('./vms');
var zfs = require('./zfs');
var verror = require('verror');
var restify = require('restify');
var ModelServer = require('../models/server');
var assert = require('assert-plus');

var CONNECTION_CHECKS = {
    moray: ensureConnectedToMoray,
    amqp: ensureConnectedToAMQP,
    redis: ensureConnectedToRedis
};

var PREPOPULATE_FNS = {
    server: prepopulateServer,
    vm: prepopulateVm
};

function ensureConnectedToMoray(opts, req, res, next) {
    opts.log.debug('ensuring connected to Moray');
    if (!opts.model.moray.connected) {
        next(
            new restify.InternalError(
                'Precondition failed: no connection moray'));
    }
    next();
}

function ensureConnectedToAMQP(opts, req, res, next) {
    next();
}

function ensureConnectedToRedis(opts, req, res, next) {
    next();
}

function ensureConnectionTimeout(opts, req, res, next) {
    req.connection.setTimeout(opts.timeout);
    next();
}

function prepopulateServer(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');

    req.params.server = new ModelServer(req.params.server_uuid);
    req.params.server.getRaw(function (error, server) {
        // Check if any servers were returned
        if (!server) {
            var errorMsg = 'Server ' + req.params.server_uuid + ' not found';
            next(new restify.ResourceNotFoundError(errorMsg));
            return;
        }
        next();
    });
}

function prepopulateVm(opts, req, res, next) {
    assert.string(req.params.uuid, 'uuid');

    var uuid = req.params.uuid;
    req.params.server.cacheCheckVmExists(
        req.params.uuid,
        function (cacheError, exists) {
            var errorMsg;
            if (!exists) {
                errorMsg = 'VM ' + uuid + ' not found';
                next(
                    new restify.ResourceNotFoundError(
                        errorMsg));
                    return;
            }

            req.params.vm = req.params.server.getVM(uuid);
            next();
        });
}

function ensure(opts) {
    var fns = [];

    opts.log = opts.model.getLog();
    opts.timeout = opts.timeout || 60 * 60;
    // Override timeout
    fns.push(function (req, res, next) {
        ensureConnectionTimeout(opts, req, res, next);
    });

    var connected = opts.connected || {};
    var prepopulate = opts.prepopulate || [];

    connected.forEach(function (service) {
        if (!CONNECTION_CHECKS.hasOwnProperty(service)) {
            throw (
                new verror.VError(
                    'unknown service for precondition check, %s', service));
        }

        fns.push(function (req, res, next) {
            CONNECTION_CHECKS[service](opts, req, res, next);
        });
    });

    prepopulate.forEach(function (resource) {
        if (!PREPOPULATE_FNS.hasOwnProperty(resource)) {
            throw (
                new verror.VError(
                    'unknown resource for prepopulation, %s', resource));
        }

        fns.push(function (req, res, next) {
            PREPOPULATE_FNS[resource](opts, req, res, next);
        });
    });

    return fns;
}

function attachTo(http, model) {
    http.post(
        '/loglevel',
        function (req, res, next) {
            var level = req.params.level;
            model.log.debug('Setting loglevel to %s', level);
            model.log.level(level);
            res.send();
            return next();
        });

    http.get(
        '/loglevel',
        function (req, res, next) {
            res.send({ level: model.log.level() });
            return next();
        });

    platforms.attachTo(http, model);
    servers.attachTo(http, model);
    vms.attachTo(http, model);
    tasks.attachTo(http, model);
    boot_params.attachTo(http, model);
    ur.attachTo(http, model);
    zfs.attachTo(http, model);
}

exports.attachTo = attachTo;
exports.ensure = ensure;
<commit_msg>CNAPI-146: CNAPI http endpoint timeout off by a factor for 1000<commit_after>var boot_params = require('./boot_params');
var platforms = require('./platforms');
var servers = require('./servers');
var tasks = require('./tasks');
var ur = require('./ur');
var vms = require('./vms');
var zfs = require('./zfs');
var verror = require('verror');
var restify = require('restify');
var ModelServer = require('../models/server');
var assert = require('assert-plus');

var CONNECTION_CHECKS = {
    moray: ensureConnectedToMoray,
    amqp: ensureConnectedToAMQP,
    redis: ensureConnectedToRedis
};

var PREPOPULATE_FNS = {
    server: prepopulateServer,
    vm: prepopulateVm
};

function ensureConnectedToMoray(opts, req, res, next) {
    opts.log.debug('ensuring connected to Moray');
    if (!opts.model.moray.connected) {
        next(
            new restify.InternalError(
                'Precondition failed: no connection moray'));
    }
    next();
}

function ensureConnectedToAMQP(opts, req, res, next) {
    next();
}

function ensureConnectedToRedis(opts, req, res, next) {
    next();
}

function ensureConnectionTimeout(opts, req, res, next) {
    req.connection.setTimeout(opts.connectionTimeoutSeconds * 1000);
    next();
}

function prepopulateServer(opts, req, res, next) {
    assert.string(req.params.server_uuid, 'server_uuid');

    req.params.server = new ModelServer(req.params.server_uuid);
    req.params.server.getRaw(function (error, server) {
        // Check if any servers were returned
        if (!server) {
            var errorMsg = 'Server ' + req.params.server_uuid + ' not found';
            next(new restify.ResourceNotFoundError(errorMsg));
            return;
        }
        next();
    });
}

function prepopulateVm(opts, req, res, next) {
    assert.string(req.params.uuid, 'uuid');

    var uuid = req.params.uuid;
    req.params.server.cacheCheckVmExists(
        req.params.uuid,
        function (cacheError, exists) {
            var errorMsg;
            if (!exists) {
                errorMsg = 'VM ' + uuid + ' not found';
                next(
                    new restify.ResourceNotFoundError(
                        errorMsg));
                    return;
            }

            req.params.vm = req.params.server.getVM(uuid);
            next();
        });
}

function ensure(opts) {
    var fns = [];

    opts.log = opts.model.getLog();
    opts.connectionTimeoutSeconds = opts.connectionTimeoutSeconds || 60 * 60;
    // Override timeout
    fns.push(function (req, res, next) {
        ensureConnectionTimeout(opts, req, res, next);
    });

    var connected = opts.connected || {};
    var prepopulate = opts.prepopulate || [];

    connected.forEach(function (service) {
        if (!CONNECTION_CHECKS.hasOwnProperty(service)) {
            throw (
                new verror.VError(
                    'unknown service for precondition check, %s', service));
        }

        fns.push(function (req, res, next) {
            CONNECTION_CHECKS[service](opts, req, res, next);
        });
    });

    prepopulate.forEach(function (resource) {
        if (!PREPOPULATE_FNS.hasOwnProperty(resource)) {
            throw (
                new verror.VError(
                    'unknown resource for prepopulation, %s', resource));
        }

        fns.push(function (req, res, next) {
            PREPOPULATE_FNS[resource](opts, req, res, next);
        });
    });

    return fns;
}

function attachTo(http, model) {
    http.post(
        '/loglevel',
        function (req, res, next) {
            var level = req.params.level;
            model.log.debug('Setting loglevel to %s', level);
            model.log.level(level);
            res.send();
            return next();
        });

    http.get(
        '/loglevel',
        function (req, res, next) {
            res.send({ level: model.log.level() });
            return next();
        });

    platforms.attachTo(http, model);
    servers.attachTo(http, model);
    vms.attachTo(http, model);
    tasks.attachTo(http, model);
    boot_params.attachTo(http, model);
    ur.attachTo(http, model);
    zfs.attachTo(http, model);
}

exports.attachTo = attachTo;
exports.ensure = ensure;
<|endoftext|>


<commit_before>var _ = require('lodash');
var BPromise = require('bluebird');
var mongodb = BPromise.promisifyAll(require('mongodb'));
BPromise.promisifyAll(mongodb.Cursor.prototype);

var objectifyID = function( obj ) {
	if ( obj._id && !(obj._id instanceof mongodb.ObjectID) )
	{
		if ( obj._id.length != 12 && obj._id.length != 24 )
			throw new Error("Invalid object ID " + obj._id );
		obj._id = mongodb.ObjectID(obj._id);
	}
};
var stringifyID = function( obj ) {
	if ( obj._id && (obj._id instanceof mongodb.ObjectID) )
		obj._id = obj._id.toString();
};

var MongoCursor = function(original) {
	this.original = original;
};
MongoCursor.prototype.limit = function(count) {
	this.original.limit(count);
	return this;
};
MongoCursor.prototype.skip = function(count) {
	this.original.skip(count);
	return this;
};
MongoCursor.prototype.sort = function(order) {
	this.original.sort(order);
	return this;
};
MongoCursor.prototype.toArray = function(callback) {
	return this.original.toArrayAsync()
	.then(function(arr) {
		_.forEach(arr, function(obj) {
			stringifyID(obj);
		});
		return arr;
	})
	.nodeify(callback);
};
MongoCursor.prototype.stream = function() {
	var stream = this.original.stream();
	stream.on('data', function(obj) {
		stringifyID(obj);
	});
	return stream;
};

var MongoCollection = function(engine, name) {
	this.db = engine.db.collection(name);
};

MongoCollection.prototype.findOne = function(query, projection, callback) {
	objectifyID( query );
	return this.db.findOneAsync(query, projection)
		.then(function(item) {
			if ( item )
				stringifyID(item);
			return item;
		})
		.nodeify(callback);
};
MongoCollection.prototype.find = function(query, projection) {
	objectifyID( query );
	return new MongoCursor( this.db.find(query, projection) );
};
MongoCollection.prototype.insert = function(obj, opt, callback) {
	return this.db.insertAsync(obj, opt)
		.then(function(arr) {
			_.forEach(arr, function(item) {
				stringifyID(item);
			});
			return arr;
		})
		.nodeify(callback);
};
MongoCollection.prototype.update = function(query, obj, opt, callback) {
	objectifyID( query );
	return this.db.updateAsync(query, obj, opt)
		.nodeify(callback);
};
MongoCollection.prototype.remove = function(query, opt, callback) {
	objectifyID( query );
	console.log(query);
	return this.db.removeAsync(query, opt)
		.then(function(result) {
			console.log(result);
			if _.isArray(result)
				result = result[0];
			return result;
		})
		.nodeify(callback);
};

var MongoEngine = function(options) {
	this.options = _.clone(options);
	this.db = this.options.db || null;
	this.collections = [];
};
MongoEngine.prototype.connect = function() {
	console.log('connect');
	if ( this.db )
		return BPromise.delay(this, 1);

	this.db = new mongodb.Db(this.options.dbname, new mongodb.Server(this.options.host, this.options.port), {safe:true});
	return this.db.openAsync()
	.catch(function(e) {
		throw new Error("Failed to connect to MongoDB.");
	})
	.bind(this)
	.then(function(db) {
		BPromise.map( _.keys(this.options.resources), function(colName) {
		  return db.collectionAsync(colName, {strict:true})
		  .catch( function(e) {
		  	return db.createCollectionAsync(colName);
		  })
		  .catch( function(e) {
		  	throw new Error("Failed to create collection '" + colName + "'.");
		  });
		})
		.then(function() {
			console.log('connected');
		})
		.return(this);
	});
};
MongoEngine.prototype.collection = function(name) {
	if ( !this.collections[name] )
		this.collections[name] = new MongoCollection(this, name);
	return this.collections[name];
};

module.exports = function(options) {
	return new MongoEngine(options);
};<commit_msg>Fix syntax error.<commit_after>var _ = require('lodash');
var BPromise = require('bluebird');
var mongodb = BPromise.promisifyAll(require('mongodb'));
BPromise.promisifyAll(mongodb.Cursor.prototype);

var objectifyID = function( obj ) {
	if ( obj._id && !(obj._id instanceof mongodb.ObjectID) )
	{
		if ( obj._id.length != 12 && obj._id.length != 24 )
			throw new Error("Invalid object ID " + obj._id );
		obj._id = mongodb.ObjectID(obj._id);
	}
};
var stringifyID = function( obj ) {
	if ( obj._id && (obj._id instanceof mongodb.ObjectID) )
		obj._id = obj._id.toString();
};

var MongoCursor = function(original) {
	this.original = original;
};
MongoCursor.prototype.limit = function(count) {
	this.original.limit(count);
	return this;
};
MongoCursor.prototype.skip = function(count) {
	this.original.skip(count);
	return this;
};
MongoCursor.prototype.sort = function(order) {
	this.original.sort(order);
	return this;
};
MongoCursor.prototype.toArray = function(callback) {
	return this.original.toArrayAsync()
	.then(function(arr) {
		_.forEach(arr, function(obj) {
			stringifyID(obj);
		});
		return arr;
	})
	.nodeify(callback);
};
MongoCursor.prototype.stream = function() {
	var stream = this.original.stream();
	stream.on('data', function(obj) {
		stringifyID(obj);
	});
	return stream;
};

var MongoCollection = function(engine, name) {
	this.db = engine.db.collection(name);
};

MongoCollection.prototype.findOne = function(query, projection, callback) {
	objectifyID( query );
	return this.db.findOneAsync(query, projection)
		.then(function(item) {
			if ( item )
				stringifyID(item);
			return item;
		})
		.nodeify(callback);
};
MongoCollection.prototype.find = function(query, projection) {
	objectifyID( query );
	return new MongoCursor( this.db.find(query, projection) );
};
MongoCollection.prototype.insert = function(obj, opt, callback) {
	return this.db.insertAsync(obj, opt)
		.then(function(arr) {
			_.forEach(arr, function(item) {
				stringifyID(item);
			});
			return arr;
		})
		.nodeify(callback);
};
MongoCollection.prototype.update = function(query, obj, opt, callback) {
	objectifyID( query );
	return this.db.updateAsync(query, obj, opt)
		.nodeify(callback);
};
MongoCollection.prototype.remove = function(query, opt, callback) {
	objectifyID( query );
	console.log(query);
	return this.db.removeAsync(query, opt)
		.then(function(result) {
			console.log(result);
			if ( _.isArray(result) )
				result = result[0];
			return result;
		})
		.nodeify(callback);
};

var MongoEngine = function(options) {
	this.options = _.clone(options);
	this.db = this.options.db || null;
	this.collections = [];
};
MongoEngine.prototype.connect = function() {
	console.log('connect');
	if ( this.db )
		return BPromise.delay(this, 1);

	this.db = new mongodb.Db(this.options.dbname, new mongodb.Server(this.options.host, this.options.port), {safe:true});
	return this.db.openAsync()
	.catch(function(e) {
		throw new Error("Failed to connect to MongoDB.");
	})
	.bind(this)
	.then(function(db) {
		BPromise.map( _.keys(this.options.resources), function(colName) {
		  return db.collectionAsync(colName, {strict:true})
		  .catch( function(e) {
		  	return db.createCollectionAsync(colName);
		  })
		  .catch( function(e) {
		  	throw new Error("Failed to create collection '" + colName + "'.");
		  });
		})
		.then(function() {
			console.log('connected');
		})
		.return(this);
	});
};
MongoEngine.prototype.collection = function(name) {
	if ( !this.collections[name] )
		this.collections[name] = new MongoCollection(this, name);
	return this.collections[name];
};

module.exports = function(options) {
	return new MongoEngine(options);
};<|endoftext|>


<commit_before>var loadedTreebanks = [];
var selectedTreebanks = [];
var enabledMetrics = retrieveMetrics();
var disabledMetrics = [];

function openTab(event, tabName){
    var i;
    var metricTabContent = document.getElementsByClassName("metricTabContent");
    for (i = 0; i < metricTabContent.length; i++){
        metricTabContent[i].style.display = "none";
    }

    var metricTabs = document.getElementsByClassName("metricTab");
    for (i = 0; i < metricTabs.length; i++){
        metricTabs[i].className = metricTabs[i].className.replace(" active", "");
    }

    document.getElementById(tabName).style.display = "block";
    event.currentTarget.className += " active";
}

/**
 *
 * @param newTree Reference to tree to be added to the array of loaded treebanks
 * @returns {boolean} Returns true if a tree was successfully added or false otherwise.
 * @constructor
 */
function AddLoadedTree(newTree){
    for (var index = 0; index < loadedTreebanks.length; index++){
        if (loadedTreebanks[index].id === newTree.id){
            output.println("Treebank " + newTree.id + " has been loaded previously");
            return false;
        }
    }

    loadedTreebanks.push(newTree);
    return true;
}

/**
 *
 * @param id Id of tree which should be removed from the loaded array
 * @returns {boolean} Returns true if a tree was successfully removed or false otherwise.
 * @constructor
 */
function RemoveLoadedTreeById(id){
    for (var index = 0; index < loadedTreebanks.length; index++){
        if (loadedTreebanks[index].id === id){
            loadedTreebanks.splice(index, 1);
            output.println("Treebank " + id + " has been unloaded");
            return true; //Should not have to worry about duplicates.
        }
    }
    output.println("Treebank " + id + " was not previously loaded");
    return false;
}

/**
 *
 * @param name
 * @returns {boolean}
 * @constructor
 */
function EnableMetric(name){
    for (var index = 0; index < disabledMetrics.length; index++){
        if (disabledMetrics[index].title === name){
            enabledMetrics.push(disabledMetrics[index]);
            disabledMetrics.splice(index, 1);
            output.println("The " + name + " metric has been enabled.");

        }
    }
    output.println("No metric with the name \"" + name + "\" exists.")
    return false;
}

/**
 *
 * @param name
 * @returns {boolean}
 * @constructor
 */
function DisableMetric(name){
    for (var index = 0; index < enabledMetrics.length; index++){
        if (disabledMetrics[index].title === name){
            disabledMetrics.splice(index, 1);
            output.println("The " + name + " metric has been disabled.");
        }
    }
    output.println("No metric with the name \"" + name + "\" exists.")
    return false;
}

/**
 * Override
 */
VNConsoleWindow.prototype.init=function()
{
    var d=''+new Date();
    var i=d.indexOf('GMT');
    if(i>-1) d=d.substring(0,i-1);
    this.println(d);
    this.println('---- Console started. Type \'help\' for a list of commands. ----');
};

VNConsoleWindow.prototype.processCommand=function(command){
    console.log("Command received in window controller: " + command);

    var args = command.split(" ");
    switch (args[0].toLowerCase()){
        case "help":
            output.println("Welcome to the metreex analysis tool, type 'load <metreex id>' to load a Treebank file.");
            output.println("Type list to see all loaded treebanks.");
            return true;
        case "load":
            if (args.length > 1 && args[1]) {
                if (args[1] === "-c"){
                    //load collection
                    output.println("Attempting to load treebank collection");
                    var t=new TreebankCollection();
                    t.onload=function(){
                        t.treebank.forEach(function(tree){
                            AddLoadedTree(tree);
                        });
                    };
                    t.load();
                }
                else {
                    output.println("Attempting to load tree with id " + args[1]);
                    var newTree = new TreebankFile();
                    newTree.onload = function () {
                        if (newTree.getNumOfSentences() > 0) {
                            AddLoadedTree(newTree);
                        }
                    };
                    newTree.load(args[1]);
                }
            }
            else{
                output.println("Not enough parameters. Usage: load <metreex database id>");
            }
            return true;
        case "unload":
            if (args.length > 1 && args[1]){
                if (args[1] === "-a"){
                    loadedTreebanks = [];
                    output.println("All treebanks have been unloaded.");
                }
                else{
                    RemoveLoadedTreeById(args[1]);
                }
            }
            else{
                output.println("The unload command should be used as either 'unload -a' or 'unload <treebank id>'");
            }
            return true;
        case "list":
            if (args.length > 1) {
                switch (args[1]) {
                    case "trees":
                        if (loadedTreebanks.length > 0) {
                            output.println("The following " + loadedTreebanks.length + " treebank(s) have been loaded:");
                            loadedTreebanks.forEach(function (tree) {
                                output.println(tree.id + ": " + tree.getTitle());
                            });
                        }
                        else {
                            output.println("No treebanks have been loaded yet. Use the \'load\' command to load a new treebank.");
                        }
                        break;
                    case "metrics":
                        if (disabledMetrics.length + enabledMetrics.length == 0) {
                            output.println("No metrics have been loaded. Check for the metric source file.");
                            break;
                        }

                        if (enabledMetrics.length > 0) {
                            output.println("The following " + enabledMetrics.length + " metric(s) are enabled:");
                            enabledMetrics.forEach(function (metric) {
                                output.println(metric.name);
                            })
                        }

                        if (disabledMetrics.length > 0){
                            output.println("The following " + enabledMetrics.length + " metric(s) are disabled:");
                            disabledMetrics.forEach(function (metric) {
                                output.println(metric.name);
                            })
                        }
                        break;
                    default:
                        break;
                }
            }
            else{
                output.println("The list command should be used as 'list trees' or 'list metrics'");
            }
            return true;
        case "apply":
            if (selectedTreebanks.length == 0){
                output.println("No treebanks were selected, applying to all loaded treebanks.");
                selectedTreebanks = loadedTreebanks;
            }

            selectedTreebanks.forEach(function(tree){
                output.println(tree.getTitle() + " - " + tree.id);
                tree.apply(enabledMetrics,{progress:output.getProgress()});
            });
            return true;
            /*
        case "enable":
            if (args.length > 1 && args[1]){
                if (args[1] === "-a"){
                    loadedTreebanks = [];
                    output.println("All treebanks have been unloaded.");
                }
                else{
                    RemoveLoadedTreeById(args[1]);
                }
            }
            return true;
        case "disable":
            return true;
            */
        case "clear":
            output.clear();
            return true;
        default:
            return false;
    }

    //return false;
};

function buildMetricList(array){
    var list = document.createElement('form');
    list.action = "metric_form.asp";
    list.method = "get";

    for (var i = 0; i < array.length; i++){
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "metric";
        checkbox.value = i;
        checkbox.checked = true;

        var label = document.createElement('label');
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(array[i].name));

        list.appendChild(label);
        list.appendChild(document.createElement('br'));
    }

    return list;
}

window.onload = function () {
    vn = new VisiNeatAPI();
    vn.setScreen("visualDiv");

    // Console creation
    var windowManager = vn.getWindowManager();
    output = windowManager.createConsole({left:0,top:50,width:1000,height:800,title:"metreex analysis"});

    // Initialization of metric list
    document.getElementById("Metrics").appendChild(buildMetricList(enabledMetrics));
    openTab(event, 'Metrics');

   // var guiManager = new GUIManager("buttonDiv");
   // var toolbar = new RetractableToolbar(guiManager, 50, 1);
   // var button1 = new RetractableToolbarButton(toolbar);
   // button1.initButton1();

/*
    var tree = new TreebankFile();
    tree.onload = function(){
        console.log(tree.getTitle());
        output.println(tree.getTitle());
    };

    tree.load('wuxmwtm934d917x2');
*/
};
<commit_msg>Treebanks can now be added (through console still) and shown dynamically in sidebar<commit_after>var loadedTreebanks = [];
var selectedTreebanks = [];
var enabledMetrics = retrieveMetrics();
var disabledMetrics = [];
var USING_SIDEBAR = false;

function openTab(event, tabName){
    var i;
    var metricTabContent = document.getElementsByClassName("metricTabContent");
    for (i = 0; i < metricTabContent.length; i++){
        metricTabContent[i].style.display = "none";
    }

    var metricTabs = document.getElementsByClassName("metricTab");
    for (i = 0; i < metricTabs.length; i++){
        metricTabs[i].className = metricTabs[i].className.replace(" active", "");
    }

    document.getElementById(tabName).style.display = "block";
    event.currentTarget.className += " active";
}

/**
 *
 * @param newTree Reference to tree to be added to the array of loaded treebanks
 * @returns {boolean} Returns true if a tree was successfully added or false otherwise.
 * @constructor
 */
function AddLoadedTree(newTree){
    for (var index = 0; index < loadedTreebanks.length; index++){
        if (loadedTreebanks[index].id === newTree.id){
            output.println("Treebank " + newTree.id + " has been loaded previously");
            return false;
        }
    }

    loadedTreebanks.push(newTree);

    if (USING_SIDEBAR){
        AddTreeToSidebar(newTree);
    }

    return true;
}

/**
 *
 * @param id Id of tree which should be removed from the loaded array
 * @returns {boolean} Returns true if a tree was successfully removed or false otherwise.
 * @constructor
 */
function RemoveLoadedTreeById(id){
    for (var index = 0; index < loadedTreebanks.length; index++){
        if (loadedTreebanks[index].id === id){
            loadedTreebanks.splice(index, 1);
            output.println("Treebank " + id + " has been unloaded");

            if (USING_SIDEBAR){
                RemoveTreeFromSidebar(id)
            }

            return true; //Should not have to worry about duplicates.
        }
    }
    output.println("Treebank " + id + " was not previously loaded");
    return false;
}

function loadTreebankFile(id){
    output.println("Attempting to load tree with id " + id);
    var newTree = new TreebankFile();
    newTree.onload = function () {
        if (newTree.getNumOfSentences() > 0) {
            AddLoadedTree(newTree);
        }
    };
    newTree.load(id);
}

function loadTreebankCollection(){
    output.println("Attempting to load treebank collection");
    var t=new TreebankCollection();
    t.onload=function(){
        t.treebank.forEach(function(tree){
            AddLoadedTree(tree);
        });
    };
    t.load();
}

/**
 *
 * @param name
 * @returns {boolean}
 * @constructor
 */
function EnableMetric(name){
    for (var index = 0; index < disabledMetrics.length; index++){
        if (disabledMetrics[index].title === name){
            enabledMetrics.push(disabledMetrics[index]);
            disabledMetrics.splice(index, 1);
            output.println("The " + name + " metric has been enabled.");

        }
    }
    output.println("No metric with the name \"" + name + "\" exists.")
    return false;
}

/**
 *
 * @param name
 * @returns {boolean}
 * @constructor
 */
function DisableMetric(name){
    for (var index = 0; index < enabledMetrics.length; index++){
        if (disabledMetrics[index].title === name){
            disabledMetrics.splice(index, 1);
            output.println("The " + name + " metric has been disabled.");
        }
    }
    output.println("No metric with the name \"" + name + "\" exists.")
    return false;
}

/**
 * Override
 */
VNConsoleWindow.prototype.init=function()
{
    var d=''+new Date();
    var i=d.indexOf('GMT');
    if(i>-1) d=d.substring(0,i-1);
    this.println(d);
    this.println('---- Console started. Type \'help\' for a list of commands. ----');
};

VNConsoleWindow.prototype.processCommand=function(command){
    console.log("Command received in window controller: " + command);

    var args = command.split(" ");
    switch (args[0].toLowerCase()){
        case "help":
            output.println("Welcome to the metreex analysis tool, type 'load <metreex id>' to load a Treebank file.");
            output.println("Type list to see all loaded treebanks.");
            return true;
        case "load":
            if (args.length > 1 && args[1]) {
                if (args[1] === "-c"){
                    loadTreebankCollection();
                }
                else {
                    loadTreebankFile(args[1]);
                }
            }
            else{
                output.println("Not enough parameters. Usage: load <metreex database id> or load -c (for collection)");
            }
            return true;
        case "unload":
            if (args.length > 1 && args[1]){
                if (args[1] === "-a"){
                    loadedTreebanks = [];
                    output.println("All treebanks have been unloaded.");
                }
                else{
                    RemoveLoadedTreeById(args[1]);
                }
            }
            else{
                output.println("The unload command should be used as either 'unload -a' or 'unload <treebank id>'");
            }
            return true;
        case "list":
            if (args.length > 1) {
                switch (args[1]) {
                    case "trees":
                        if (loadedTreebanks.length > 0) {
                            output.println("The following " + loadedTreebanks.length + " treebank(s) have been loaded:");
                            loadedTreebanks.forEach(function (tree) {
                                output.println(tree.id + ": " + tree.getTitle());
                            });
                        }
                        else {
                            output.println("No treebanks have been loaded yet. Use the \'load\' command to load a new treebank.");
                        }
                        break;
                    case "metrics":
                        if (disabledMetrics.length + enabledMetrics.length == 0) {
                            output.println("No metrics have been loaded. Check for the metric source file.");
                            break;
                        }

                        if (enabledMetrics.length > 0) {
                            output.println("The following " + enabledMetrics.length + " metric(s) are enabled:");
                            enabledMetrics.forEach(function (metric) {
                                output.println(metric.name);
                            })
                        }

                        if (disabledMetrics.length > 0){
                            output.println("The following " + enabledMetrics.length + " metric(s) are disabled:");
                            disabledMetrics.forEach(function (metric) {
                                output.println(metric.name);
                            })
                        }
                        break;
                    default:
                        break;
                }
            }
            else{
                output.println("The list command should be used as 'list trees' or 'list metrics'");
            }
            return true;
        case "apply":
            if (loadedTreebanks.length == 0){
                output.println("No treebanks have been loaded, please use the load <treebank id> command before this one.")
                return true;
            }

            if (selectedTreebanks.length == 0){
                output.println("No treebanks were selected, applying to all loaded treebanks.");
                selectedTreebanks = loadedTreebanks;
            }

            selectedTreebanks.forEach(function(tree){
                output.println(tree.getTitle() + " - " + tree.id);
                tree.apply(enabledMetrics,{progress:output.getProgress()});
            });
            return true;
            /*
        case "enable":
            if (args.length > 1 && args[1]){
                if (args[1] === "-a"){
                    loadedTreebanks = [];
                    output.println("All treebanks have been unloaded.");
                }
                else{
                    RemoveLoadedTreeById(args[1]);
                }
            }
            return true;
        case "disable":
            return true;
            */
        case "clear":
            output.clear();
            return true;
        default:
            return false;
    }

    //return false;
};

function buildDefaultMetricList(array){
    var list = document.createElement('form');
    list.id = "metricList";
    list.action = "metric_form.asp";
    list.method = "get";

    for (var i = 0; i < array.length; i++){
        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "metric";
        checkbox.value = i;
        checkbox.checked = true;

        var label = document.createElement('label');
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(array[i].name));

        list.appendChild(label);
        list.appendChild(document.createElement('br'));
    }

    return list;
}

function AddTreeToSidebar(newTree){
    var treeList = document.getElementById("treebankList");

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.name = "treebank";
    checkbox.value = newTree.id;
    checkbox.checked = true;

    var label = document.createElement('label');
    label.id = newTree.id;
    label.appendChild(checkbox);
    label.appendChild(document.createTextNode(newTree.getTitle()));

    treeList.appendChild(label);
    treeList.appendChild(document.createElement('br'));
}

function RemoveTreeFromSidebar(id){
    var treeToRemove = document.getElementById(id);
    treeToRemove.parentNode.removeChild(treeToRemove.nextSibling); //Takes care of the extra <br>
    treeToRemove.parentNode.removeChild(treeToRemove);
}

function buildDefaultTreebankList(){
    var list = document.createElement('form');
    list.id = "treebankList";
    list.action = "treebank_form.asp";
    list.method = "get";

    return list;
}

window.onload = function () {
    vn = new VisiNeatAPI();
    vn.setScreen("visualDiv");

    // Console creation
    var windowManager = vn.getWindowManager();
    output = windowManager.createConsole({left:0,top:50,width:1000,height:800,title:"metreex analysis"});

    // Initialization of treebank and metric lists
    USING_SIDEBAR = true;
    document.getElementById("Treebanks").appendChild(buildDefaultTreebankList());
    document.getElementById("Metrics").appendChild(buildDefaultMetricList(enabledMetrics));
    openTab(event, 'Metrics');
};
<|endoftext|>


<commit_before>import resourceRest from '../rest/resource'

export default function rest(spec) {
  const resource = resourceRest(spec)
  let {idParam} = spec

  idParam = idParam || 'id'

  return async function(req, res) {
    const method = req.method

    if (method === 'GET' && !req.params[idParam]) {
      res.body = await resource.list(req, res)
      return res.status(200)
    }

    if (method === 'POST') {
      res.body = await resource.create(req, res)
      return res.status(201)
    }

    if (method === 'GET') {
      res.body = await resource.read(req, res)
      return res.status(200)
    }

    if (method === 'PUT') {
      res.body = await resource.update(req, res)
      return res.status(200)
    }

    if (method === 'DELETE') {
      res.body = await resource.remove(req, res)
      return res.status(204)
    }
  }
}
<commit_msg>feat: support PATCH requests<commit_after>import resourceRest from '../rest/resource'

export default function rest(spec) {
  const resource = resourceRest(spec)
  let {idParam} = spec

  idParam = idParam || 'id'

  return async function(req, res) {
    const method = req.method

    if (method === 'GET' && !req.params[idParam]) {
      res.body = await resource.list(req, res)
      return res.status(200)
    }

    if (method === 'POST') {
      res.body = await resource.create(req, res)
      return res.status(201)
    }

    if (method === 'GET') {
      res.body = await resource.read(req, res)
      return res.status(200)
    }

    if (method === 'PUT' || method === 'PATCH') {
      res.body = await resource.update(req, res)
      return res.status(200)
    }

    if (method === 'DELETE') {
      res.body = await resource.remove(req, res)
      return res.status(204)
    }
  }
}
<|endoftext|>