<commit_before>// OpenWrap v2
// Author: Nuno Aguiar
// Python

OpenWrap.python = function() {
	this.python = "python";
	this.reset(true);
	this.cServer = $atomic();
	this.running = false;

	return ow.python;
};

OpenWrap.python.prototype.initCode = function(includeCoding) {
	if (isDef(this.token)) {
		var s = (includeCoding ? "# -*- coding: utf-8 -*-\n\n" : "");
		s += "import json\n";
		s += "import socket\n\n";
		s += "def _(e):\n";
		s += "   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n";
		s += "   s.connect(('127.0.0.1', " + this.port + "))\n";
		s += "   sR = {'e':e,'t':'" + this.token + "'}\n";
		s += "   s.sendall(bytearray(json.dumps(sR) + '\\n', 'utf-8'))\n";
		s += "   res = ''\n";
		s += "   while True:\n";
		s += "      data = s.recv(1024).decode('utf-8')\n";
		s += "      if not data:\n";
		s += "         break\n";
		s += "      res += data\n";
		s += "   s.close()\n";
		s += "   if res.startswith('__OAF__Exception'):\n";
		s += "      raise Exception(res)\n";
		s += "   else:\n";
		s += "      try:\n"
		s += "         return json.loads(res)\n";
		s += "      except:\n";
		s += "         return None\n\n";
		s += "def _oaf(e):\n";
		s += "   return _(e)\n\n";
		return s;
	} else {
		return "# -*- coding: utf-8 -*-\n\n";
	}
};

OpenWrap.python.prototype.startServer = function(aPort, aSendPort, aFn) {
	if (this.version >= 2 && this.version <= 3) {
		ow.python.cServer.inc();
		if (isUnDef(this.token)) {
			this.token = md5(nowNano());
			aFn = _$(aFn).isFunction().default((t, e) => { if (t == "error") printErr(e); });

			// Receive
			ow.loadServer();
			if (isUnDef(aPort)) aPort = findRandomOpenPort();
			this.port = aPort;
			this.server = ow.server.socket.start(aPort, (clt, srv) => {
				aFn("connect", clt.getInetAddress().getHostAddress());
				ioStreamReadLines(clt.getInputStream(), stream => {
					try {
						var inR = jsonParse(stream), res = "";
						if (isDef(inR) && isDef(inR.e) && isDef(inR.t) && inR.t == this.token) {
							aFn("exec", inR);
							try {
								res = stringify(af.eval(inR.e),void 0, "");
							} catch(ee) {
								res = "__OAF__Exception: " + String(ee);
							}
						}
						ioStreamWrite(clt.getOutputStream(), res);
						clt.getOutputStream().flush();
						clt.shutdownInput();
						clt.shutdownOutput();
						return true;
					} catch(e) {
						aFn("error", e);
					}
				}, "\n", false);
				clt.close();
			}, void 0, "127.0.0.1");

			// Send
			if (isUnDef(aSendPort)) aSendPort = findRandomOpenPort();
			this.sport = aSendPort;
			this.pidfile = getOpenAFPath() + "/openaf_python.pid";
			var s = "# -*- coding: utf-8 -*-\n";
			s += "import json\n";
			s += "import sys\n";
			s += "import os\n";
			s += "\n";
			s += "_newpid = os.fork()\n";
			s += "if _newpid != 0:\n";
			s += "  os._exit(os.EX_OK)\n";
			s += "if sys.version_info[0] == 2:\n";
			s += "  from StringIO import StringIO\n";
			s += "  import SocketServer\n";
			s += "  __h = SocketServer.BaseRequestHandler\n";
			s += "else:\n";
			s += "  from io import StringIO\n";
			s += "  import socketserver\n";
			s += "  __h = socketserver.BaseRequestHandler\n";
			s += "\n";
			s += "class oafHandler(__h):\n";
			s += "  def handle(self):\n";
			s += "      res = ''\n";
			s += "      self.request.settimeout(1500)\n";
			s += "      while True:\n";
			s += "          res += self.request.recv(1024).decode('utf-8')\n";
			s += "          if str(res).endswith('}\\n') or str(res) == '':\n";
			s += "              break\n";
			s += "      \n";
			s += "      try:\n";
			s += "          mm = json.loads(res)\n";
			s += "      except:\n";
			s += "          mm = {}\n";
			s += "      if 'exit' in mm.keys() and mm['t'] == '" + this.token + "':\n";
			s += "          os._exit(os.EX_OK)\n";
			s += "      if 'e' in mm.keys() and mm['t'] == '" + this.token + "':\n";
			s += "          myStdOut = StringIO()\n";
			s += "          myStdErr = StringIO()\n";
			s += "          sys.stdout = myStdOut\n";
			s += "          sys.stderr = myStdErr\n";
			s += "          try:\n";
			s += "              exec(mm['e'])\n";
			s += "              mm['stdout'] = myStdOut.getvalue()\n";
			s += "              mm['stderr'] = myStdErr.getvalue()\n";
			s += "          except:\n";
			s += "              mm['stderr'] = str(sys.exc_info())\n";
			s += "      try:\n";
			s += "        del mm['e']\n";
			s += "        del mm['t']\n";
			s += "        self.request.sendall(json.dumps(mm).encode('utf-8'))\n";
			s += "      except:\n";
			s += "        pass\n";
			s += "\n";
			s += ow.python.initCode(false) + "\n\n";
			s += "_oafF = open('" + this.pidfile + "', 'w')\n";
			s += "_oafF.write(str(os.getpid()))\n";
			s += "_oafF.close()\n";
			s += "if sys.version_info[0] == 2:\n";
			s += "  server = SocketServer.ThreadingTCPServer(('127.0.0.1', " + aSendPort + "), oafHandler)\n";
			s += "else:\n";
			s += "  server = socketserver.ThreadingTCPServer(('127.0.0.1', " + aSendPort + "), oafHandler)\n";
			s += "server.serve_forever()\n";
			s += "\n";

			af.sh("python -", s, void 0, void 0, void 0, void 0, void 0, void 0, true);

			ow.loadFormat(); var init = now();
			do {
				sleep(100, true);
			} while((now() - init) < 1500);
			sleep(150, true);
			ow.format.testPort("127.0.0.1", this.sport, 1500);

			addOnOpenAFShutdown(() => { ow.python.stopServer(void 0, true); });
		}

		return this.token;
	} else {
		throw "Can't start python 2 or 3.";
	}
};

OpenWrap.python.prototype.stopServer = function(aPort, force) {
	if (this.version >= 2 && this.version <= 3) {
		if (force || ow.python.cServer.get() > 0) {
			ow.python.cServer.dec();
			aPort = _$(aPort).isNumber().default(this.port);

			ow.server.socket.stop(aPort);
			ow.loadObj();

			ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ exit: true, t: this.token }, void 0, "")+"\n");
			pidKill(io.readFileString(this.pidfile), true);
			//this.threads.stop(true);
			delete this.sport;
			delete this.server;
			delete this.port;
			delete this.token;

			io.rm(this.pidfile);

			return true;
		} else {
			return false;
		}
	} else {
		throw "Can't stop python 2 or 3.";
	}
};

OpenWrap.python.prototype.reset = function(noException) {
	try {
		var res = $sh(this.python + " --version").get(0);
		this.version = (res.stderr.match(/ 2\./) ? 2 : (res.stdout.match(/ 3\./) ? 3 : -1) );
		if (this.version < 0) throw res.stderr;
	} catch(e) {
		this.version = -1;
		if (!noException) throw "Can't find or determine python version (" + e + ")";
	}
};

/**
 * <odoc>
 * <key>ow.python.setPython(aPythonPath)</key>
 * Sets the aPythonPath to the python interpreter process to use.
 * </odoc>
 */
OpenWrap.python.prototype.setPython = function(aPython) {
	this.python = aPython;
	ow.python.reset();
};

/**
 * <odoc>
 * <key>ow.python.getVersion() : String</key>
 * The majoy python version detected.
 * </odoc>
 */
OpenWrap.python.prototype.getVersion = function() {
	return this.version;
};

/**
 * <odoc>
 * <key>ow.python.execPM(aPythonCode, aInput) : Map</key>
 * Tries to execute aPythonCode with the current interpreter providing the aInput map as a python variable __pm. Any changes to this python variable will be returned.
 * </odoc>
 */
OpenWrap.python.prototype.execPM = function(aPythonCode, aInput, throwExceptions, shouldFork) {
	if (this.version < 0) throw "Appropriate Python version not found. Please setPython to a python version 2 or version 3 command-line interpreter.";

	_$(aPythonCode, "python code").isString().$_();
	aInput = _$(aInput, "input").isMap().default({});
	throwExceptions = _$(throwExceptions, "throwExceptions").isBoolean().default(false);

	var code = (shouldFork ? this.initCode(true) : ""), delim = nowNano();
	code += "import json\n";
	code += "__pm = json.loads('" + stringify(aInput, void 0, "" ).replace(/\'/g, "\\'").replace(/\\n/g, "\\\n") + "')\n";
	code += aPythonCode;
	code += "\nprint(\"" + delim + "\\n\" + json.dumps(__pm, indent=0, separators=(',',':') ))\n";

	var res;
    if (shouldFork || isUnDef(this.sport)) {
		res = af.sh(this.python + " -", code, void 0, void 0, void 0, true);
	} else {
		ow.loadObj();
		code = code.replace("# -*- coding: utf-8 -*-\n", "#\n");

		res = jsonParse(ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ e: code, t: this.token }, void 0, "")+"\n"));
	}
	var rres = [];
	if (res.stdout.indexOf(delim) >= 0) {
		rres = res.stdout.split(new RegExp("^" + delim + "\r?\n", "mg"));
	}
	if (isDef(rres[0]) && rres[0] != "") print(rres[0]);
	if (isDef(res.stderr) && res.stderr != "") {
		if (throwExceptions) {
			printErr(res.stderr);
			throw "python: " + String(res.stderr);
		} else {
			printErr(res.stderr);
		}
	}
	return jsonParse(rres[1], true);
};

/**
 * <odoc>
 * <key>ow.python.exec(aPythonCode, aInput, aOutputArray, shouldFork) : Map</key>
 * Tries to execute aPythonCode with the current interpreter providing the aInput map keys as python variables. It tries to return the values of the aOutputArray name variables. Example:\
 * \
 *    var res = ow.python.exec("c = a + b", { a: 2, b: 1 }, [ "c" ]);\
 *    print(res.c); // 3\
 * \
 * </odoc>
 */
OpenWrap.python.prototype.exec = function(aPythonCode, aInput, aOutputArray, throwExceptions, shouldFork) {
	if (this.version < 0) throw "Appropriate Python version not found. Please setPython to a python version 2 or version 3 command-line interpreter.";

	_$(aPythonCode, "python code").isString().$_();

	aInput = _$(aInput, "input").isMap().default({});
	aOutputArray = _$(aOutputArray, "output").isArray().default([]);
	throwExceptions = _$(throwExceptions, "throwExceptions").isBoolean().default(false);

	var code = (shouldFork ? this.initCode(true) : ""), delim = nowNano();
	code += "import json\n";
	Object.keys(aInput).map(k => {
		if (isDef(aInput[k])) code += k + " = json.loads('" + stringify(aInput[k], void 0, "" ).replace(/\'/g, "\\'").replace(/\\n/g, "\\\n") + "')\n";
	});
	code += aPythonCode;

	var res;
	code += "\nprint(\"" + delim + "\\n\" + json.dumps({ " + Object.keys(aOutputArray).map(k => "\"" + aOutputArray[k] + "\": " + aOutputArray[k]).join(", ") + " }, indent=0, separators=(',',':') ))\n";
    if (shouldFork || isUnDef(this.sport)) {
		res = af.sh(this.python + " -", code, void 0, void 0, void 0, true);
	} else {
		ow.loadObj();
		code = code.replace("# -*- coding: utf-8 -*-\n", "#\n");

		res = jsonParse(ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ e: code, t: this.token }, void 0, "")+"\n"));
	}

	var rres = [];
	if (isMap(res) && isDef(res.stdout) && res.stdout.indexOf(delim) >= 0) {
		rres = res.stdout.split(new RegExp("^" + delim + "\r?\n", "mg"));
	}
	if (isDef(rres[0]) && rres[0] != "") print(rres[0]);
	if (isDef(res.stderr) && res.stderr != "") {
		if (throwExceptions) {
			printErr(res.stderr);
			throw "python: " + String(res.stderr);
		} else {
			printErr(res.stderr);
		}
	}
	return jsonParse(rres[1], true);
};<commit_msg>python: small error on startServer<commit_after>// OpenWrap v2
// Author: Nuno Aguiar
// Python

OpenWrap.python = function() {
	this.python = "python";
	this.reset(true);
	this.cServer = $atomic();
	this.running = false;

	return ow.python;
};

OpenWrap.python.prototype.initCode = function(includeCoding) {
	if (isDef(this.token)) {
		var s = (includeCoding ? "# -*- coding: utf-8 -*-\n\n" : "");
		s += "import json\n";
		s += "import socket\n\n";
		s += "def _(e):\n";
		s += "   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n";
		s += "   s.connect(('127.0.0.1', " + this.port + "))\n";
		s += "   sR = {'e':e,'t':'" + this.token + "'}\n";
		s += "   s.sendall(bytearray(json.dumps(sR) + '\\n', 'utf-8'))\n";
		s += "   res = ''\n";
		s += "   while True:\n";
		s += "      data = s.recv(1024).decode('utf-8')\n";
		s += "      if not data:\n";
		s += "         break\n";
		s += "      res += data\n";
		s += "   s.close()\n";
		s += "   if res.startswith('__OAF__Exception'):\n";
		s += "      raise Exception(res)\n";
		s += "   else:\n";
		s += "      try:\n"
		s += "         return json.loads(res)\n";
		s += "      except:\n";
		s += "         return None\n\n";
		s += "def _oaf(e):\n";
		s += "   return _(e)\n\n";
		return s;
	} else {
		return "# -*- coding: utf-8 -*-\n\n";
	}
};

OpenWrap.python.prototype.startServer = function(aPort, aSendPort, aFn) {
	if (this.version >= 2 && this.version <= 3) {
		ow.python.cServer.inc();
		if (isUnDef(this.token)) {
			this.token = md5(nowNano());
			aFn = _$(aFn).isFunction().default((t, e) => { if (t == "error") printErr(e); });

			// Receive
			ow.loadServer();
			if (isUnDef(aPort)) aPort = findRandomOpenPort();
			this.port = aPort;
			this.server = ow.server.socket.start(aPort, (clt, srv) => {
				aFn("connect", clt.getInetAddress().getHostAddress());
				ioStreamReadLines(clt.getInputStream(), stream => {
					try {
						var inR = jsonParse(stream), res = "";
						if (isDef(inR) && isDef(inR.e) && isDef(inR.t) && inR.t == this.token) {
							aFn("exec", inR);
							try {
								res = stringify(af.eval(inR.e),void 0, "");
							} catch(ee) {
								res = "__OAF__Exception: " + String(ee);
							}
						}
						ioStreamWrite(clt.getOutputStream(), res);
						clt.getOutputStream().flush();
						clt.shutdownInput();
						clt.shutdownOutput();
						return true;
					} catch(e) {
						aFn("error", e);
					}
				}, "\n", false);
				clt.close();
			}, void 0, "127.0.0.1");

			// Send
			if (isUnDef(aSendPort)) aSendPort = findRandomOpenPort();
			this.sport = aSendPort;
			this.pidfile = getOpenAFPath() + "/openaf_python.pid";
			var s = "# -*- coding: utf-8 -*-\n";
			s += "import json\n";
			s += "import sys\n";
			s += "import os\n";
			s += "\n";
			s += "_newpid = os.fork()\n";
			s += "if _newpid != 0:\n";
			s += "  os._exit(os.EX_OK)\n";
			s += "if sys.version_info[0] == 2:\n";
			s += "  from StringIO import StringIO\n";
			s += "  import SocketServer\n";
			s += "  __h = SocketServer.BaseRequestHandler\n";
			s += "else:\n";
			s += "  from io import StringIO\n";
			s += "  import socketserver\n";
			s += "  __h = socketserver.BaseRequestHandler\n";
			s += "\n";
			s += "class oafHandler(__h):\n";
			s += "  def handle(self):\n";
			s += "      res = ''\n";
			s += "      self.request.settimeout(1500)\n";
			s += "      while True:\n";
			s += "          res += self.request.recv(1024).decode('utf-8')\n";
			s += "          if str(res).endswith('}\\n') or str(res) == '':\n";
			s += "              break\n";
			s += "      \n";
			s += "      try:\n";
			s += "          mm = json.loads(res)\n";
			s += "      except:\n";
			s += "          mm = {}\n";
			s += "      if 'exit' in mm.keys() and mm['t'] == '" + this.token + "':\n";
			s += "          os._exit(os.EX_OK)\n";
			s += "      if 'e' in mm.keys() and mm['t'] == '" + this.token + "':\n";
			s += "          myStdOut = StringIO()\n";
			s += "          myStdErr = StringIO()\n";
			s += "          sys.stdout = myStdOut\n";
			s += "          sys.stderr = myStdErr\n";
			s += "          try:\n";
			s += "              exec(mm['e'])\n";
			s += "              mm['stdout'] = myStdOut.getvalue()\n";
			s += "              mm['stderr'] = myStdErr.getvalue()\n";
			s += "          except:\n";
			s += "              mm['stderr'] = str(sys.exc_info())\n";
			s += "      try:\n";
			s += "        del mm['e']\n";
			s += "        del mm['t']\n";
			s += "        self.request.sendall(json.dumps(mm).encode('utf-8'))\n";
			s += "      except:\n";
			s += "        pass\n";
			s += "\n";
			s += ow.python.initCode(false) + "\n\n";
			s += "_oafF = open('" + this.pidfile + "', 'w')\n";
			s += "_oafF.write(str(os.getpid()))\n";
			s += "_oafF.close()\n";
			s += "if sys.version_info[0] == 2:\n";
			s += "  server = SocketServer.ThreadingTCPServer(('127.0.0.1', " + aSendPort + "), oafHandler)\n";
			s += "else:\n";
			s += "  server = socketserver.ThreadingTCPServer(('127.0.0.1', " + aSendPort + "), oafHandler)\n";
			s += "server.serve_forever()\n";
			s += "\n";

			af.sh(this.python + " -", s, void 0, void 0, void 0, void 0, void 0, void 0, true);

			ow.loadFormat(); var init = now();
			do {
				sleep(100, true);
			} while((now() - init) < 1500);
			sleep(150, true);
			ow.format.testPort("127.0.0.1", this.sport, 1500);

			addOnOpenAFShutdown(() => { ow.python.stopServer(void 0, true); });
		}

		return this.token;
	} else {
		throw "Can't start python 2 or 3.";
	}
};

OpenWrap.python.prototype.stopServer = function(aPort, force) {
	if (this.version >= 2 && this.version <= 3) {
		if (force || ow.python.cServer.get() > 0) {
			ow.python.cServer.dec();
			aPort = _$(aPort).isNumber().default(this.port);

			ow.server.socket.stop(aPort);
			ow.loadObj();

			ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ exit: true, t: this.token }, void 0, "")+"\n");
			pidKill(io.readFileString(this.pidfile), true);
			//this.threads.stop(true);
			delete this.sport;
			delete this.server;
			delete this.port;
			delete this.token;

			io.rm(this.pidfile);

			return true;
		} else {
			return false;
		}
	} else {
		throw "Can't stop python 2 or 3.";
	}
};

OpenWrap.python.prototype.reset = function(noException) {
	try {
		var res = $sh(this.python + " --version").get(0);
		this.version = (res.stderr.match(/ 2\./) ? 2 : (res.stdout.match(/ 3\./) ? 3 : -1) );
		if (this.version < 0) throw res.stderr;
	} catch(e) {
		this.version = -1;
		if (!noException) throw "Can't find or determine python version (" + e + ")";
	}
};

/**
 * <odoc>
 * <key>ow.python.setPython(aPythonPath)</key>
 * Sets the aPythonPath to the python interpreter process to use.
 * </odoc>
 */
OpenWrap.python.prototype.setPython = function(aPython) {
	this.python = aPython;
	ow.python.reset();
};

/**
 * <odoc>
 * <key>ow.python.getVersion() : String</key>
 * The majoy python version detected.
 * </odoc>
 */
OpenWrap.python.prototype.getVersion = function() {
	return this.version;
};

/**
 * <odoc>
 * <key>ow.python.execPM(aPythonCode, aInput) : Map</key>
 * Tries to execute aPythonCode with the current interpreter providing the aInput map as a python variable __pm. Any changes to this python variable will be returned.
 * </odoc>
 */
OpenWrap.python.prototype.execPM = function(aPythonCode, aInput, throwExceptions, shouldFork) {
	if (this.version < 0) throw "Appropriate Python version not found. Please setPython to a python version 2 or version 3 command-line interpreter.";

	_$(aPythonCode, "python code").isString().$_();
	aInput = _$(aInput, "input").isMap().default({});
	throwExceptions = _$(throwExceptions, "throwExceptions").isBoolean().default(false);

	var code = (shouldFork ? this.initCode(true) : ""), delim = nowNano();
	code += "import json\n";
	code += "__pm = json.loads('" + stringify(aInput, void 0, "" ).replace(/\'/g, "\\'").replace(/\\n/g, "\\\n") + "')\n";
	code += aPythonCode;
	code += "\nprint(\"" + delim + "\\n\" + json.dumps(__pm, indent=0, separators=(',',':') ))\n";

	var res;
    if (shouldFork || isUnDef(this.sport)) {
		res = af.sh(this.python + " -", code, void 0, void 0, void 0, true);
	} else {
		ow.loadObj();
		code = code.replace("# -*- coding: utf-8 -*-\n", "#\n");

		res = jsonParse(ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ e: code, t: this.token }, void 0, "")+"\n"));
	}
	var rres = [];
	if (res.stdout.indexOf(delim) >= 0) {
		rres = res.stdout.split(new RegExp("^" + delim + "\r?\n", "mg"));
	}
	if (isDef(rres[0]) && rres[0] != "") print(rres[0]);
	if (isDef(res.stderr) && res.stderr != "") {
		if (throwExceptions) {
			printErr(res.stderr);
			throw "python: " + String(res.stderr);
		} else {
			printErr(res.stderr);
		}
	}
	return jsonParse(rres[1], true);
};

/**
 * <odoc>
 * <key>ow.python.exec(aPythonCode, aInput, aOutputArray, shouldFork) : Map</key>
 * Tries to execute aPythonCode with the current interpreter providing the aInput map keys as python variables. It tries to return the values of the aOutputArray name variables. Example:\
 * \
 *    var res = ow.python.exec("c = a + b", { a: 2, b: 1 }, [ "c" ]);\
 *    print(res.c); // 3\
 * \
 * </odoc>
 */
OpenWrap.python.prototype.exec = function(aPythonCode, aInput, aOutputArray, throwExceptions, shouldFork) {
	if (this.version < 0) throw "Appropriate Python version not found. Please setPython to a python version 2 or version 3 command-line interpreter.";

	_$(aPythonCode, "python code").isString().$_();

	aInput = _$(aInput, "input").isMap().default({});
	aOutputArray = _$(aOutputArray, "output").isArray().default([]);
	throwExceptions = _$(throwExceptions, "throwExceptions").isBoolean().default(false);

	var code = (shouldFork ? this.initCode(true) : ""), delim = nowNano();
	code += "import json\n";
	Object.keys(aInput).map(k => {
		if (isDef(aInput[k])) code += k + " = json.loads('" + stringify(aInput[k], void 0, "" ).replace(/\'/g, "\\'").replace(/\\n/g, "\\\n") + "')\n";
	});
	code += aPythonCode;

	var res;
	code += "\nprint(\"" + delim + "\\n\" + json.dumps({ " + Object.keys(aOutputArray).map(k => "\"" + aOutputArray[k] + "\": " + aOutputArray[k]).join(", ") + " }, indent=0, separators=(',',':') ))\n";
    if (shouldFork || isUnDef(this.sport)) {
		res = af.sh(this.python + " -", code, void 0, void 0, void 0, true);
	} else {
		ow.loadObj();
		code = code.replace("# -*- coding: utf-8 -*-\n", "#\n");

		res = jsonParse(ow.obj.socket.string2string("127.0.0.1", this.sport, stringify({ e: code, t: this.token }, void 0, "")+"\n"));
	}

	var rres = [];
	if (isMap(res) && isDef(res.stdout) && res.stdout.indexOf(delim) >= 0) {
		rres = res.stdout.split(new RegExp("^" + delim + "\r?\n", "mg"));
	}
	if (isDef(rres[0]) && rres[0] != "") print(rres[0]);
	if (isDef(res.stderr) && res.stderr != "") {
		if (throwExceptions) {
			printErr(res.stderr);
			throw "python: " + String(res.stderr);
		} else {
			printErr(res.stderr);
		}
	}
	return jsonParse(rres[1], true);
};<|endoftext|>


<commit_before>//Peg, has 2 coordinates and a state
function Peg(row, col, id, index, isEmpty){
    this.isEmpty = isEmpty;
    this.row = row;
    this.col = col;
    this.id = id;
    this.index = index;
}

//Game board
function Board(){
    this.boardType = 'Triangle';
    this.numPegs = 0;
    this.pegs = [];
    this.moveFrom = -1;
    this.moveTo = -1;
}

Board.prototype = {
    setPegs: function(){
        this.pegs = [];
        var alphabet = 'abcdefghijklmnopqrstuvwxyz'
        switch(this.boardType){
            case 'Triangle':
            default:
                //Defines a triangular board with 5 pegs per side
                for(i = 0; i < 5; i++){
                  for(j = 0; j <= i; j++){
                    var id = alphabet[j] + i.toString();
                    var index = (i*(i + 1)/2) + j;
                    if (i === 0 && j === 0){
                        //Set top corner as empty
                        this.pegs.push(new Peg(i, j, id, index, true));
                    } else{
                        //Set all other pegs as occupied
                        this.pegs.push(new Peg(i, j, id, index, false));
                    }
                    this.numPegs++;
                  }
                }
                break;
        }
        return;
    },

    make_html: function(){
        var gameBoard = $("#game-board"); //Get the game-board div
        gameBoard.svg(); //Attach svg canvas
        var svg = gameBoard.svg("get"); //Get the svg canvas
        svg.configure({width: '63vw', height: '63vw', viewBox: '0 0 200 200'},
                      true);
        var grp = svg.group('theBoard');
        switch(this.boardType){
            case 'Triangle':
            default:
                var pitchX = 40;
                var pitchY = 25;
                var radius = 10;
                for (i=0; i<this.numPegs; i++){
                  var curPeg = this.pegs[i];
                  var left = 100 - 20*curPeg.row;
                  var cy = 50 + pitchY*curPeg.row;
                  var cx = left + pitchX*curPeg.col;
                  var curCircle = $('<circle></circle>');
                  var pegState = curPeg.isEmpty ? 'empty':'occupied';
                  var pegId = curPeg.id;
                  var txtId = pegId +'-txt';
                  var pegIndex = curPeg.index;
                  svg.circle(grp,cx,cy,radius,
                             {id:pegId, index: pegIndex, state:pegState});
                  svg.text(grp,cx,cy,pegId,
                           {id:txtId, index: pegIndex, state:pegState,
                            stroke:'white', textAnchor:'middle'});
                }
                break;
        }
        var movesLog = $("

")
        movesLog.attr("id", "move-log");
        movesLog.text("Moves:");
        gameBoard.append(movesLog);
    },

    make_a_move: function(){
        var result = {movedFrom:'', movedTo:'', removed:'', status:'', msg:''};
        if (this.moveFrom >= 0 && this.moveTo >= 0){
            var nP1 = this.moveFrom;
            var nP2 = this.moveTo;
            var peg1 = this.pegs[nP1];
            var peg2 = this.pegs[nP2];
            result.movedFrom = peg1.id;
            result.movedTo = peg2.id;
            if (!peg1.isEmpty && peg2.isEmpty){
                //Check if a valid move can be made
                var iRow = -1;
                var iCol = -1;
                if ((Math.abs(peg1.row - peg2.row) === 2 ||
                    (peg1.row - peg2.row) === 0) &&
                    (Math.abs(peg1.col - peg2.col) === 2 ||
                        (peg1.col - peg2.col) === 0)){
                    iRow = (peg1.row + peg2.row)/2;
                    iCol = (peg1.col + peg2.col)/2;
                }
                if (iRow >= 0 && iCol >= 0){
                    //Check if intermediate peg is filled
                    var iPegIndex = (iRow*(iRow + 1)/2) + iCol;
                    if (!this.pegs[iPegIndex].isEmpty){
                        //Make the valid move
                        this.pegs[nP1].isEmpty = true;
                        this.pegs[nP2].isEmpty = false;
                        this.pegs[iPegIndex].isEmpty = true;
                        result.removed = this.pegs[iPegIndex].id;
                        result.status = "success"
                        result.msg = result.movedFrom + " - " +
                                     result.movedTo + "; removed " +
                                     result.removed;
                    } else{
                        result.status = "error";
                        result.msg = "Invalid move"
                    }
                } else {
                    result.status = "error";
                    result.msg = "Invalid move"
                }
              } else {
                  result.status = "error";
                  result.msg = "Invalid move"
              }
        } else{
            result.status = "error";
            result.msg = "Nothing selected."
        }
        return result;
    }
}

var myBoard = null;

function onClick(curIndex){
    if (myBoard.moveFrom < 0){
        myBoard.moveFrom = curIndex;
    } else if (myBoard.moveTo < 0){
        myBoard.moveTo = curIndex;
        var res = myBoard.make_a_move();
        if (res.status === "success"){
          var mFrom = "#" + res.movedFrom;
          var mTo = "#" + res.movedTo;
          var remv = "#" + res.removed;
          $(mFrom).attr("state", "empty");
          $(mTo).attr("state", "occupied");
          $(remv).attr("state", "empty");
          var newMove = $("");
          newMove.text(res.msg);
          $("#move-log").append($("
"));
          $("#move-log").append(newMove);
        }
        myBoard.moveFrom = -1;
        myBoard.moveTo = -1;
    }
}

$(document).ready( function(){
    //Toggle rules when rules heading is clicked
    $("#rules").on('click', function(){
        console.log("Rules button clicked.");
        $("#rulestext").toggle();
    });

    $("#new-game").on('click', function(){
        myBoard = new Board();
        myBoard.setPegs();
        myBoard.make_html();

        $("circle").on('click', function(){
            var curIndex = $(this).attr("index");
            onClick(curIndex);
        });
        $("text").on('click', function(){
            var curIndex = $(this).attr("index");
            onClick(curIndex);
        });

    });
});
<commit_msg>Update viewBox dimensions. Make X and Y pitch better.<commit_after>//Peg, has 2 coordinates and a state
function Peg(row, col, id, index, isEmpty){
    this.isEmpty = isEmpty;
    this.row = row;
    this.col = col;
    this.id = id;
    this.index = index;
}

//Game board
function Board(){
    this.boardType = 'Triangle';
    this.numPegs = 0;
    this.pegs = [];
    this.moveFrom = -1;
    this.moveTo = -1;
}

Board.prototype = {
    setPegs: function(){
        this.pegs = [];
        var alphabet = 'abcdefghijklmnopqrstuvwxyz'
        switch(this.boardType){
            case 'Triangle':
            default:
                //Defines a triangular board with 5 pegs per side
                for(i = 0; i < 5; i++){
                  for(j = 0; j <= i; j++){
                    var id = alphabet[j] + i.toString();
                    var index = (i*(i + 1)/2) + j;
                    if (i === 0 && j === 0){
                        //Set top corner as empty
                        this.pegs.push(new Peg(i, j, id, index, true));
                    } else{
                        //Set all other pegs as occupied
                        this.pegs.push(new Peg(i, j, id, index, false));
                    }
                    this.numPegs++;
                  }
                }
                break;
        }
        return;
    },

    make_html: function(){
        var gameBoard = $("#game-board"); //Get the game-board div
        gameBoard.svg(); //Attach svg canvas
        var svg = gameBoard.svg("get"); //Get the svg canvas
        //Inline svg will occupy container width, so no need to set width and
        // height attributes here.
        svg.configure({viewBox: '0 0 160 144'}, true);
        var grp = svg.group('theBoard');
        switch(this.boardType){
            case 'Triangle':
            default:
                var pitchX = 30;
                var pitchY = 26; //(pitchY/pitchX = sin(60deg))
                var radius = 10;
                for (i=0; i<this.numPegs; i++){
                  var curPeg = this.pegs[i];
                  var left = 80 - (pitchX/2)*curPeg.row;
                  var cy = 20 + pitchY*curPeg.row;
                  var cx = left + pitchX*curPeg.col;
                  var curCircle = $('<circle></circle>');
                  var pegState = curPeg.isEmpty ? 'empty':'occupied';
                  var pegId = curPeg.id;
                  var txtId = pegId +'-txt';
                  var pegIndex = curPeg.index;
                  svg.circle(grp,cx,cy,radius,
                             {id:pegId, index: pegIndex, state:pegState});
                  svg.text(grp,cx,cy,pegId,
                           {id:txtId, index: pegIndex, state:pegState,
                            stroke:'white', textAnchor:'middle'});
                }
                break;
        }
        var movesLog = $("

")
        movesLog.attr("id", "move-log");
        movesLog.text("Moves:");
        gameBoard.append(movesLog);
    },

    make_a_move: function(){
        var result = {movedFrom:'', movedTo:'', removed:'', status:'', msg:''};
        if (this.moveFrom >= 0 && this.moveTo >= 0){
            var nP1 = this.moveFrom;
            var nP2 = this.moveTo;
            var peg1 = this.pegs[nP1];
            var peg2 = this.pegs[nP2];
            result.movedFrom = peg1.id;
            result.movedTo = peg2.id;
            if (!peg1.isEmpty && peg2.isEmpty){
                //Check if a valid move can be made
                var iRow = -1;
                var iCol = -1;
                if ((Math.abs(peg1.row - peg2.row) === 2 ||
                    (peg1.row - peg2.row) === 0) &&
                    (Math.abs(peg1.col - peg2.col) === 2 ||
                        (peg1.col - peg2.col) === 0)){
                    iRow = (peg1.row + peg2.row)/2;
                    iCol = (peg1.col + peg2.col)/2;
                }
                if (iRow >= 0 && iCol >= 0){
                    //Check if intermediate peg is filled
                    var iPegIndex = (iRow*(iRow + 1)/2) + iCol;
                    if (!this.pegs[iPegIndex].isEmpty){
                        //Make the valid move
                        this.pegs[nP1].isEmpty = true;
                        this.pegs[nP2].isEmpty = false;
                        this.pegs[iPegIndex].isEmpty = true;
                        result.removed = this.pegs[iPegIndex].id;
                        result.status = "success"
                        result.msg = result.movedFrom + " - " +
                                     result.movedTo + "; removed " +
                                     result.removed;
                    } else{
                        result.status = "error";
                        result.msg = "Invalid move"
                    }
                } else {
                    result.status = "error";
                    result.msg = "Invalid move"
                }
              } else {
                  result.status = "error";
                  result.msg = "Invalid move"
              }
        } else{
            result.status = "error";
            result.msg = "Nothing selected."
        }
        return result;
    }
}

var myBoard = null;

function onClick(curIndex){
    if (myBoard.moveFrom < 0){
        myBoard.moveFrom = curIndex;
    } else if (myBoard.moveTo < 0){
        myBoard.moveTo = curIndex;
        var res = myBoard.make_a_move();
        if (res.status === "success"){
          var mFrom = "#" + res.movedFrom;
          var mTo = "#" + res.movedTo;
          var remv = "#" + res.removed;
          $(mFrom).attr("state", "empty");
          $(mTo).attr("state", "occupied");
          $(remv).attr("state", "empty");
          var newMove = $("");
          newMove.text(res.msg);
          $("#move-log").append($("
"));
          $("#move-log").append(newMove);
        }
        myBoard.moveFrom = -1;
        myBoard.moveTo = -1;
    }
}

$(document).ready( function(){
    //Toggle rules when rules heading is clicked
    $("#rules").on('click', function(){
        console.log("Rules button clicked.");
        $("#rulestext").toggle();
    });

    $("#new-game").on('click', function(){
        myBoard = new Board();
        myBoard.setPegs();
        myBoard.make_html();

        $("circle").on('click', function(){
            var curIndex = $(this).attr("index");
            onClick(curIndex);
        });
        $("text").on('click', function(){
            var curIndex = $(this).attr("index");
            onClick(curIndex);
        });

    });
});
<|endoftext|>


<commit_before><commit_msg>Fixed Neuroscience Methods to Journal of Neuroscience Methods in Publications<commit_after><|endoftext|>


<commit_before>var imported = document.createElement('script');
imported.src = 'js/structure.js';
document.head.appendChild(imported);

var data = new Array();

function loadLocal(arg) {
	$(function() {
		clearAll();
		clearLexicalCheck();
            $.get(arg, function(dados) {
                readerResult = dados;
			$('#editor').val(dados);

			//read file line by line
            var lines = readerResult.split(/(?:\\[rn]|[\r\n]+)+/g);

			//console.log(lines[0]);
			if(!verifyTags(lines))
				return;
			var i= 0;
			while(i < lines.length)
			{
				//transitions Table
				if(lines[i] == "transitions.start")
				{
					var e = 1;
					i++;
					while(lines[i] != "transitions.end")
					{
						var line= lines[i].split("->");
						console.log(line[0]);
						line[0]= line[0].replace("(", "").replace(")", "");
						line[1]= line[1].replace("(", "").replace(")", "");
						var current= line[0].split(",");
						var nextAux= line[1].split(";");
						var next= nextAux[0].split(",");

						if (current.length != 2) {
							document.getElementById('output').style.color = "Red";
							document.getElementById('output').innerHTML = "Syntax error on line: " + i + ". Wrong sequence of tokens, " + "expected to have 2 tokens but has " + current.length + ".";
							return;
						}

						if (next.length != 3) {
							document.getElementById('output').style.color = "Red";
							document.getElementById('output').innerHTML = "Syntax error on line: " + i + ". Wrong sequence of tokens, " + "expected to have 3 tokens but has " + current.length + ".";
							return;
						}

						var state= current[0];
						var symbol= current[1];
						var nextState= next[0];
						var nextSymbol= next[1];
						var direction= next[2];

						data.push(new Transition(state, nextState, symbol, nextSymbol, direction));

						addEdge(e.toString(), state, nextState, symbol + " / " + nextSymbol + " , " + direction);

						e++;

						i++;
					}
				}

				//Formal Definition
				if(lines[i] == "formalDefinition.start")
				{
					i++;
					while(lines[i] != "formalDefinition.end")
					{
						var variableDeclaration= lines[i].split("=");
						var variableName= variableDeclaration[0];
						var variableContent= variableDeclaration[1].split(";");

						if(variableName == "States")
						{
							document.getElementById('statesSet').value = variableContent[0];
						}
						else if(variableName == "Alphabet")
						{
							document.getElementById('alphabetSet').value = variableContent[0];
						}
						else if(variableName == "BlankSymbol")
						{
							document.getElementById('blankSymbol').value = variableContent[0];
						}
						else if(variableName == "TapeAlphabet")
						{
							document.getElementById('inputSymbols').value = variableContent[0];
						}
						else if(variableName == "InitialState")
						{
							document.getElementById('initialState').value = variableContent[0];
						}
						else if(variableName == "FinalStates")
						{
							document.getElementById('finalStates').value = variableContent[0];
						}
						else
						{
						}

						i++;
					}
				}

				if(lines[i] == "input.start")
				{
					i++;
					while(lines[i] != "input.end")
					{

						var variableDeclaration= lines[i].split("=");
						var variableName= variableDeclaration[0];

						if(variableName == "Input")
						{
							var inputContent= variableDeclaration[1].split(";");
							document.getElementById('inputString').value = inputContent[0];
						}
						else
						{
						}

						i++;
					}
				}

				i++;
			}

			loadTransitionsTable();

            });
        });
}

function loadTransitionsTable() {
    for (var i = 1; i < data.length; i++) {
        cloneRow()
    }

    var currentStateInputs = document.getElementsByName('currentState');

    var nextStateInputs = document.getElementsByName('nextState');

    var scanSymbolInputs = document.getElementsByName('scanSymbol');

    var printSymbolInputs = document.getElementsByName('printSymbol');

    var directionInputs = document.getElementsByName('direction');

    for (var i = 0; i < data.length; i++) {
        currentStateInputs[i].value = data[i].currentState;

        nextStateInputs[i].value = data[i].nextState;

        scanSymbolInputs[i].value = data[i].scanSymbol;

        printSymbolInputs[i].value = data[i].printSymbol;

        directionInputs[i].value = data[i].direction;
    }
}

<commit_msg>Fixed load example<commit_after>var imported = document.createElement('script');
imported.src = 'js/structure.js';
document.head.appendChild(imported);

var data = new Array();

function loadLocal(arg) {
	$(function() {
		clearAll();
		clearLexicalCheck();
            $.get(arg, function(dados) {
                readerResult = dados;
			$('#editor').val(dados);

			//read file line by line
            var lines = readerResult.split(/(?:\\[rn]|[\r\n]+)+/g);

			//console.log(lines[0]);
			if(!verifyTags(lines))
				return;
			var i= 0;
			while(i < lines.length)
			{
				//transitions Table
				if(lines[i] == "transitions.start")
				{
					var e = 1;
					i++;
					while(lines[i] != "transitions.end")
					{
						var line= lines[i].trim().split("->");
						line[0]= line[0].replace("(", "").replace(")", "");
						line[1]= line[1].replace("(", "").replace(")", "");
						var current= line[0].split(",");
						var nextAux= line[1].split(";");
						var next= nextAux[0].split(",");

						if (current.length != 2) {
							document.getElementById('output').style.color = "Red";
							document.getElementById('output').innerHTML = "Syntax error on line: " + i + ". Wrong sequence of tokens, " + "expected to have 2 tokens but has " + current.length + ".";
							return;
						}

						if (next.length != 3) {
							document.getElementById('output').style.color = "Red";
							document.getElementById('output').innerHTML = "Syntax error on line: " + i + ". Wrong sequence of tokens, " + "expected to have 3 tokens but has " + current.length + ".";
							return;
						}

						var state= current[0];
						var symbol= current[1];
						var nextState= next[0];
						var nextSymbol= next[1];
						var direction= next[2];

						data.push(new Transition(state, nextState, symbol, nextSymbol, direction));

						addEdge(e.toString(), state, nextState, symbol + " / " + nextSymbol + " , " + direction);

						e++;

						i++;
					}
				}

				//Formal Definition
				if(lines[i] == "formalDefinition.start")
				{
					i++;
					while(lines[i] != "formalDefinition.end")
					{
						var variableDeclaration= lines[i].trim().split("=");
						var variableName= variableDeclaration[0];
						var variableContent= variableDeclaration[1].split(";");

						if(variableName == "States")
						{
							document.getElementById('statesSet').value = variableContent[0];
						}
						else if(variableName == "Alphabet")
						{
							document.getElementById('alphabetSet').value = variableContent[0];
						}
						else if(variableName == "BlankSymbol")
						{
							document.getElementById('blankSymbol').value = variableContent[0];
						}
						else if(variableName == "TapeAlphabet")
						{
							document.getElementById('inputSymbols').value = variableContent[0];
						}
						else if(variableName == "InitialState")
						{
							document.getElementById('initialState').value = variableContent[0];
						}
						else if(variableName == "FinalStates")
						{
							document.getElementById('finalStates').value = variableContent[0];
						}
						else
						{
						}

						i++;
					}
				}

				if(lines[i] == "input.start")
				{
					i++;
					while(lines[i] != "input.end")
					{

						var variableDeclaration= lines[i].trim().split("=");
						var variableName= variableDeclaration[0];

						if(variableName == "Input")
						{
							var inputContent= variableDeclaration[1].split(";");
							document.getElementById('inputString').value = inputContent[0];
						}
						else
						{
						}

						i++;
					}
				}

				if(lines[i] == "breakpoints.start")
				{
					i++;

					while(lines[i] != "breakpoints.end")
					{
						if(lines[i].trim().indexOf("state") != -1)
						{
							var where = lines[i].trim().split(")")[0].split("(")[1];

							var betweenBrackets = lines[i].trim().split("}")[0].split("{")[1];

							var betweenBracketsSplit = betweenBrackets.split(";");

							var j = 0;

							var times = 0;

							var message = "";

							while(j < betweenBracketsSplit.length)
							{
								var instructionName = betweenBracketsSplit[j].split("=")[0];

								var instructionValue = betweenBracketsSplit[j].split("=")[1];

								if(instructionName == "times")
								{
									times = instructionValue;
								}
								else
								{
									if(instructionName == "message")
									{
										message = instructionValue;
									}
								}

								j++;
							}

							breakpoints.push(new Breakpoint("state", where, times, message));
						}
						else
						{
							if(lines[i].trim().indexOf("inputPosition") != -1)
							{
								var where = lines[i].trim().split(")")[0].split("(")[1];

								var betweenBrackets = lines[i].trim().split("}")[0].split("{")[1];

								var betweenBracketsSplit = betweenBrackets.split(";");

								var j = 0;

								var times = 0;

								var message = "";

								while(j < betweenBracketsSplit.length)
								{
									var instructionName = betweenBracketsSplit[j].split("=")[0];

									var instructionValue = betweenBracketsSplit[j].split("=")[1];

									if(instructionName == "times")
									{
										times = instructionValue;
									}
									else
									{
										if(instructionName == "message")
										{
											message = instructionValue;
										}
									}

									j++;
								}

								breakpoints.push(new Breakpoint("inputPosition", where, times, message));
							}
						}

						i++;
					}
				}

				i++;
			}

			loadTransitionsTable();

            });
        });
}

function loadTransitionsTable() {
    for (var i = 1; i < data.length; i++) {
        cloneRow()
    }

    var currentStateInputs = document.getElementsByName('currentState');

    var nextStateInputs = document.getElementsByName('nextState');

    var scanSymbolInputs = document.getElementsByName('scanSymbol');

    var printSymbolInputs = document.getElementsByName('printSymbol');

    var directionInputs = document.getElementsByName('direction');

    for (var i = 0; i < data.length; i++) {
        currentStateInputs[i].value = data[i].currentState;

        nextStateInputs[i].value = data[i].nextState;

        scanSymbolInputs[i].value = data[i].scanSymbol;

        printSymbolInputs[i].value = data[i].printSymbol;

        directionInputs[i].value = data[i].direction;
    }
}

<|endoftext|>


<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

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

module.exports = class southxchange extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'southxchange',
            'name': 'SouthXchange',
            'countries': [ 'AR' ], // Argentina
            'rateLimit': 1000,
            'has': {
                'CORS': true,
                'createDepositAddress': true,
                'fetchOpenOrders': true,
                'fetchTickers': true,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27838912-4f94ec8a-60f6-11e7-9e5d-bbf9bd50a559.jpg',
                'api': 'https://www.southxchange.com/api',
                'www': 'https://www.southxchange.com',
                'doc': 'https://www.southxchange.com/Home/Api',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'price/{symbol}',
                        'prices',
                        'book/{symbol}',
                        'trades/{symbol}',
                    ],
                },
                'private': {
                    'post': [
                        'cancelMarketOrders',
                        'cancelOrder',
                        'generatenewaddress',
                        'listOrders',
                        'listBalances',
                        'placeOrder',
                        'withdraw',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.2 / 100,
                    'taker': 0.2 / 100,
                },
            },
            'commonCurrencies': {
                'SMT': 'SmartNode',
                'MTC': 'Marinecoin',
            },
        });
    }

    async fetchMarkets (params = {}) {
        const markets = await this.publicGetMarkets (params);
        const result = [];
        for (let i = 0; i < markets.length; i++) {
            const market = markets[i];
            const baseId = market[0];
            const quoteId = market[1];
            const base = this.commonCurrencyCode (baseId);
            const quote = this.commonCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const id = symbol;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': undefined,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.privatePostListBalances (params);
        const result = { 'info': response };
        for (let i = 0; i < response.length; i++) {
            const balance = response[i];
            const currencyId = this.safeString (balance, 'Currency');
            let code = currencyId;
            if (currencyId in this.currencies_by_id) {
                code = this.currencies_by_id[currencyId]['code'];
            } else {
                code = this.commonCurrencyCode (currencyId.toUpperCase ());
            }
            const deposited = this.safeFloat (balance, 'Deposited');
            const unconfirmed = this.safeFloat (balance, 'Unconfirmed');
            const account = this.account ();
            account['free'] = this.safeFloat (balance, 'Available');
            account['total'] = this.sum (deposited, unconfirmed);
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'symbol': this.marketId (symbol),
        };
        const response = await this.publicGetBookSymbol (this.extend (request, params));
        return this.parseOrderBook (response, undefined, 'BuyOrders', 'SellOrders', 'Price', 'Amount');
    }

    parseTicker (ticker, market = undefined) {
        const timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market) {
            symbol = market['symbol'];
        }
        const last = this.safeFloat (ticker, 'Last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': this.safeFloat (ticker, 'Bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'Ask'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeFloat (ticker, 'Variation24Hr'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'Volume24Hr'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        const response = await this.publicGetPrices (params);
        const tickers = this.indexBy (response, 'Market');
        const ids = Object.keys (tickers);
        const result = {};
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            let symbol = id;
            let market = undefined;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            }
            const ticker = tickers[id];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
        };
        const response = await this.publicGetPriceSymbol (this.extend (request, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.safeInteger (trade, 'At');
        if (timestamp !== undefined) {
            timestamp = timestamp * 1000;
        }
        const price = this.safeFloat (trade, 'Price');
        const amount = this.safeFloat (trade, 'Amount');
        let cost = undefined;
        if (price !== undefined) {
            if (amount !== undefined) {
                cost = price * amount;
            }
        }
        const side = this.safeString (trade, 'Type');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': undefined,
            'order': undefined,
            'type': undefined,
            'side': side,
            'price': price,
            'takerOrMaker': undefined,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
        };
        const response = await this.publicGetTradesSymbol (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOrder (order, market = undefined) {
        const status = 'open';
        const baseId = this.safeString (order, 'ListingCurrency');
        const quoteId = this.safeString (order, 'ReferenceCurrency');
        const base = this.commonCurrencyCode (baseId);
        const quote = this.commonCurrencyCode (quoteId);
        const symbol = base + '/' + quote;
        const timestamp = undefined;
        const price = this.safeFloat (order, 'LimitPrice');
        const amount = this.safeFloat (order, 'OriginalAmount');
        const remaining = this.safeFloat (order, 'Amount');
        let filled = undefined;
        let cost = undefined;
        if (amount !== undefined) {
            cost = price * amount;
            if (remaining !== undefined) {
                filled = amount - remaining;
            }
        }
        const type = 'limit';
        let side = this.safeString (order, 'Type');
        if (side !== undefined) {
            side = side.toLowerCase ();
        }
        const id = this.safeString (order, 'Code');
        const result = {
            'info': order,
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': undefined,
        };
        return result;
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        if (symbol !== undefined) {
            market = this.market (symbol);
        }
        const response = await this.privatePostListOrders (params);
        return this.parseOrders (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'listingCurrency': market['base'],
            'referenceCurrency': market['quote'],
            'type': side,
            'amount': amount,
        };
        if (type === 'limit') {
            request['limitPrice'] = price;
        }
        const response = await this.privatePostPlaceOrder (this.extend (request, params));
        return {
            'info': response,
            'id': response.toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderCode': id,
        };
        return await this.privatePostCancelOrder (this.extend (request, params));
    }

    async createDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        const request = {
            'currency': currency['id'],
        };
        const response = await this.privatePostGeneratenewaddress (this.extend (request, params));
        const parts = response.split ('|');
        const numParts = parts.length;
        const address = parts[0];
        this.checkAddress (address);
        let tag = undefined;
        if (numParts > 1) {
            tag = parts[1];
        }
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        const currency = this.currency (code);
        const request = {
            'currency': currency['id'],
            'address': address,
            'amount': amount,
        };
        if (tag !== undefined) {
            request['address'] = address + '|' + tag;
        }
        const response = await this.privatePostWithdraw (this.extend (request, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        const url = this.urls['api'] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'private') {
            this.checkRequiredCredentials ();
            const nonce = this.nonce ();
            query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
            }, query);
            body = this.json (query);
            headers = {
                'Content-Type': 'application/json',
                'Hash': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>southxchange fixup<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');

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

module.exports = class southxchange extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'southxchange',
            'name': 'SouthXchange',
            'countries': [ 'AR' ], // Argentina
            'rateLimit': 1000,
            'has': {
                'CORS': true,
                'createDepositAddress': true,
                'fetchOpenOrders': true,
                'fetchTickers': true,
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27838912-4f94ec8a-60f6-11e7-9e5d-bbf9bd50a559.jpg',
                'api': 'https://www.southxchange.com/api',
                'www': 'https://www.southxchange.com',
                'doc': 'https://www.southxchange.com/Home/Api',
            },
            'api': {
                'public': {
                    'get': [
                        'markets',
                        'price/{symbol}',
                        'prices',
                        'book/{symbol}',
                        'trades/{symbol}',
                    ],
                },
                'private': {
                    'post': [
                        'cancelMarketOrders',
                        'cancelOrder',
                        'generatenewaddress',
                        'listOrders',
                        'listBalances',
                        'placeOrder',
                        'withdraw',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.2 / 100,
                    'taker': 0.2 / 100,
                },
            },
            'commonCurrencies': {
                'SMT': 'SmartNode',
                'MTC': 'Marinecoin',
            },
        });
    }

    async fetchMarkets (params = {}) {
        const markets = await this.publicGetMarkets (params);
        const result = [];
        for (let i = 0; i < markets.length; i++) {
            const market = markets[i];
            const baseId = market[0];
            const quoteId = market[1];
            const base = this.commonCurrencyCode (baseId);
            const quote = this.commonCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const id = symbol;
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': undefined,
                'info': market,
            });
        }
        return result;
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.privatePostListBalances (params);
        const result = { 'info': response };
        for (let i = 0; i < response.length; i++) {
            const balance = response[i];
            const currencyId = this.safeString (balance, 'Currency');
            let code = currencyId;
            if (currencyId in this.currencies_by_id) {
                code = this.currencies_by_id[currencyId]['code'];
            } else {
                code = this.commonCurrencyCode (currencyId.toUpperCase ());
            }
            const deposited = this.safeFloat (balance, 'Deposited');
            const unconfirmed = this.safeFloat (balance, 'Unconfirmed');
            const account = this.account ();
            account['free'] = this.safeFloat (balance, 'Available');
            account['total'] = this.sum (deposited, unconfirmed);
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'symbol': this.marketId (symbol),
        };
        const response = await this.publicGetBookSymbol (this.extend (request, params));
        return this.parseOrderBook (response, undefined, 'BuyOrders', 'SellOrders', 'Price', 'Amount');
    }

    parseTicker (ticker, market = undefined) {
        const timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market) {
            symbol = market['symbol'];
        }
        const last = this.safeFloat (ticker, 'Last');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': this.safeFloat (ticker, 'Bid'),
            'bidVolume': undefined,
            'ask': this.safeFloat (ticker, 'Ask'),
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeFloat (ticker, 'Variation24Hr'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker, 'Volume24Hr'),
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        const response = await this.publicGetPrices (params);
        const tickers = this.indexBy (response, 'Market');
        const ids = Object.keys (tickers);
        const result = {};
        for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            let symbol = id;
            let market = undefined;
            if (id in this.markets_by_id) {
                market = this.markets_by_id[id];
                symbol = market['symbol'];
            }
            const ticker = tickers[id];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
        };
        const response = await this.publicGetPriceSymbol (this.extend (request, params));
        return this.parseTicker (response, market);
    }

    parseTrade (trade, market) {
        let timestamp = this.safeInteger (trade, 'At');
        if (timestamp !== undefined) {
            timestamp = timestamp * 1000;
        }
        const price = this.safeFloat (trade, 'Price');
        const amount = this.safeFloat (trade, 'Amount');
        let cost = undefined;
        if (price !== undefined) {
            if (amount !== undefined) {
                cost = price * amount;
            }
        }
        const side = this.safeString (trade, 'Type');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'id': undefined,
            'order': undefined,
            'type': undefined,
            'side': side,
            'price': price,
            'takerOrMaker': undefined,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': market['id'],
        };
        const response = await this.publicGetTradesSymbol (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseOrder (order, market = undefined) {
        const status = 'open';
        const baseId = this.safeString (order, 'ListingCurrency');
        const quoteId = this.safeString (order, 'ReferenceCurrency');
        const base = this.commonCurrencyCode (baseId);
        const quote = this.commonCurrencyCode (quoteId);
        const symbol = base + '/' + quote;
        const timestamp = undefined;
        const price = this.safeFloat (order, 'LimitPrice');
        const amount = this.safeFloat (order, 'OriginalAmount');
        const remaining = this.safeFloat (order, 'Amount');
        let filled = undefined;
        let cost = undefined;
        if (amount !== undefined) {
            cost = price * amount;
            if (remaining !== undefined) {
                filled = amount - remaining;
            }
        }
        const type = 'limit';
        let side = this.safeString (order, 'Type');
        if (side !== undefined) {
            side = side.toLowerCase ();
        }
        const id = this.safeString (order, 'Code');
        const result = {
            'info': order,
            'id': id,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'symbol': symbol,
            'type': type,
            'side': side,
            'price': price,
            'amount': amount,
            'cost': cost,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': undefined,
        };
        return result;
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let market = undefined;
        if (symbol !== undefined) {
            market = this.market (symbol);
        }
        const response = await this.privatePostListOrders (params);
        return this.parseOrders (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'listingCurrency': market['base'],
            'referenceCurrency': market['quote'],
            'type': side,
            'amount': amount,
        };
        if (type === 'limit') {
            request['limitPrice'] = price;
        }
        const response = await this.privatePostPlaceOrder (this.extend (request, params));
        return {
            'info': response,
            'id': response.toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderCode': id,
        };
        return await this.privatePostCancelOrder (this.extend (request, params));
    }

    async createDepositAddress (code, params = {}) {
        await this.loadMarkets ();
        const currency = this.currency (code);
        const request = {
            'currency': currency['id'],
        };
        const response = await this.privatePostGeneratenewaddress (this.extend (request, params));
        const parts = response.split ('|');
        const numParts = parts.length;
        const address = parts[0];
        this.checkAddress (address);
        let tag = undefined;
        if (numParts > 1) {
            tag = parts[1];
        }
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'info': response,
        };
    }

    async withdraw (code, amount, address, tag = undefined, params = {}) {
        this.checkAddress (address);
        await this.loadMarkets ();
        const currency = this.currency (code);
        const request = {
            'currency': currency['id'],
            'address': address,
            'amount': amount,
        };
        if (tag !== undefined) {
            request['address'] = address + '|' + tag;
        }
        const response = await this.privatePostWithdraw (this.extend (request, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        const url = this.urls['api'] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'private') {
            this.checkRequiredCredentials ();
            const nonce = this.nonce ();
            query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
            }, query);
            body = this.json (query);
            headers = {
                'Content-Type': 'application/json',
                'Hash': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before><script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>

$(document).ready(function(){
    $("#testimonial-slider").owlCarousel({
        items:1,
        itemsDesktop:[1000,1],
        itemsDesktopSmall:[979,1],
        itemsTablet:[768,1],
        pagination:true,
        navigation:true,
        navigationText:["",""],
        slideSpeed:1000,
        autoPlay:true
    });
});
<commit_msg>Update testimonials.js<commit_after>
$(document).ready(function(){
    $("#testimonial-slider").owlCarousel({
        items:1,
        itemsDesktop:[1000,1],
        itemsDesktopSmall:[979,1],
        itemsTablet:[768,1],
        pagination:true,
        navigation:true,
        navigationText:["",""],
        slideSpeed:1000,
        autoPlay:true
    });
});
<|endoftext|>


<commit_before>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2013
//
// tier-actions.js
//

Browser.prototype.mergeSelectedTiers = function() {
    var sources = [];
    var styles = [];

    for (var sti = 0; sti < this.selectedTiers.length; ++sti) {
        var tier = this.tiers[this.selectedTiers[sti]];
	    sources.push(shallowCopy(tier.dasSource));
        var ss = tier.stylesheet.styles;
        for (var si = 0; si < ss.length; ++si) {
            var sh = ss[si];
            var nsh = shallowCopy(sh);
            nsh.method = tier.dasSource.name.replace(/[()+*?]/g, '\\$&');
            nsh._methodRE = null;
            nsh.style = shallowCopy(sh.style);
            if (nsh.style.ZINDEX === undefined)
                nsh.style.ZINDEX = sti;

            styles.push(nsh);
        }
    }

    this.addTier(
	{name: 'Merged',
	 merge: 'concat',
	 overlay: sources,
	 noDownsample: true,
     style: styles});

    this.setSelectedTier(this.tiers.length - 1);
}
<commit_msg>Write forceMin/forceMax into the synthetic stylesheet of merged tracks.<commit_after>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2013
//
// tier-actions.js
//

Browser.prototype.mergeSelectedTiers = function() {
    var sources = [];
    var styles = [];

    for (var sti = 0; sti < this.selectedTiers.length; ++sti) {
        var tier = this.tiers[this.selectedTiers[sti]];
	    sources.push(shallowCopy(tier.dasSource));
        var ss = tier.stylesheet.styles;
        for (var si = 0; si < ss.length; ++si) {
            var sh = ss[si];
            var nsh = shallowCopy(sh);
            nsh.method = tier.dasSource.name.replace(/[()+*?]/g, '\\$&');
            nsh._methodRE = null;
            nsh.style = shallowCopy(sh.style);
            if (nsh.style.ZINDEX === undefined)
                nsh.style.ZINDEX = sti;

            if (tier.forceMin) {
                nsh.style.MIN = tier.forceMin;
            }
            if (tier.forceMax) {
                nsh.style.MAX = tier.forceMax;
            }

            styles.push(nsh);
        }
    }

    this.addTier(
	{name: 'Merged',
	 merge: 'concat',
	 overlay: sources,
	 noDownsample: true,
     style: styles});

    this.setSelectedTier(this.tiers.length - 1);
}
<|endoftext|>


<commit_before>/* UITools Script */
var UI = {
    textbox: function (label_text) {
        var section = document.createElement("div");
        var label = document.createElement("label");
        var input = document.createElement("input");
        input.setAttribute("type", "text");
        label.innerHTML = label_text;
        section.appendChild(label);
        section.appendChild(input);
        return {
            elem: section,
            label_elem: label,
            input_elem: input,
            label: function (text) {
                this.label_elem.innerHTML = text;
            },
            onchange: function (evt) {
                this.input_elem.onpaste = evt;
                this.input_elem.onkeydown = evt;
                this.input_elem.onchange = evt;
                this.input_elem.oninput = evt;
            },
            onclick: function (evt) {
                this.elem.onclick = evt;
            },
            value: function (text) {
                if(text) {
                    this.input_elem.value = text;
                }
                return this.input_elem.value;
            }
        };
    },
    button: function (button_text) {
        var button = document.createElement("button");
        button.innerHTML = button_text;
        return {
            elem: button,
            onclick: function (evt) {
                this.elem.onclick = evt;
            },
            label: function (button_text) {
                this.elem.innerHTML = button_text;
            }
        };
    },
    h1: function (text) {
        var h1 = document.createElement("h1");
        h1.innerHTML = text;
        return {
            elem: h1,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    h2: function (text) {
        var h2 = document.createElement("h2");
        h2.innerHTML = text;
        return {
            elem: h2,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    para: function (text) {
        var p = document.createElement("p");
        p.innerHTML = text;
        return {
            elem: p,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    symbols: function (text) {
        var s = document.createElement("span");
        s.innerHTML = text;
        s.className = "pict";
        return {
            elem: s,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    }
};
<commit_msg>fixes #4<commit_after>/****

    glumal UI tools: For creating a consistent UI across all glumal windows.

****/
var UI = {
    textbox: function (label_text) {
        var section = document.createElement("div");
        var label = document.createElement("label");
        var input = document.createElement("input");
        input.setAttribute("type", "text");
        label.innerHTML = label_text;
        section.appendChild(label);
        section.appendChild(input);
        return {
            elem: section,
            label_elem: label,
            input_elem: input,
            label: function (text) {
                this.label_elem.innerHTML = text;
            },
            onchange: function (evt) {
                this.input_elem.onpaste = evt;
                this.input_elem.onkeydown = evt;
                this.input_elem.onchange = evt;
                this.input_elem.oninput = evt;
            },
            onclick: function (evt) {
                this.elem.onclick = evt;
            },
            value: function (text) {
                if(text) {
                    this.input_elem.value = text;
                }
                return this.input_elem.value;
            }
        };
    },
    button: function (button_text) {
        var button = document.createElement("button");
        button.innerHTML = button_text;
        return {
            elem: button,
            onclick: function (evt) {
                this.elem.onclick = evt;
            },
            label: function (button_text) {
                this.elem.innerHTML = button_text;
            }
        };
    },
    h1: function (text) {
        var h1 = document.createElement("h1");
        h1.innerHTML = text;
        return {
            elem: h1,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    h2: function (text) {
        var h2 = document.createElement("h2");
        h2.innerHTML = text;
        return {
            elem: h2,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    para: function (text) {
        var p = document.createElement("p");
        p.innerHTML = text;
        return {
            elem: p,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    },
    symbols: function (text) {
        var s = document.createElement("span");
        s.innerHTML = text;
        s.className = "pict";
        return {
            elem: s,
            label: function (text) {
                this.elem.innerHTML = text;
            }
        };
    }
};
<|endoftext|>


<commit_before>define(['../../module'], function (controllers) {
  'use strict';
  controllers.controller('EditarTransaccionGiroController', ["$scope", "$state", "PersonaNaturalService", "AgenciaService", "SessionService", "GiroService",
    function ($scope, $state, PersonaNaturalService, AgenciaService, SessionService, GiroService) {

      $scope.giro = {};

      $scope.loadGiro = function () {
        GiroService.findById($scope.id).then(function (data) {
          $scope.giro = data;
        });
      };
      $scope.loadGiro();

      //transaccion
      $scope.desembolsar = function () {
        var giro = angular.copy($scope.giro);
        giro.estadoPagoComision = true;
        giro.estado = "COBRADO";

        GiroService.update(giro.id, giro).then(
          function (data) {
            $scope.alerts = [{type: "success", msg: "Monto Desembolsado..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };

            $scope.loadGiro();
          },
          function error(error) {
            $scope.alerts = [{type: "danger", msg: "Error: No se pudo desembolsar..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };
          }
        );
      };

      $scope.extornar = function () {
        var giro = angular.copy($scope.giro);
        giro.estadoPagoComision = false;
        giro.estado = "EXTORNADO";

        GiroService.update(giro.id, giro).then(
          function (data) {
            $scope.alerts = [{type: "success", msg: "Giro Extornado..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };

            $scope.loadGiro();
          },
          function error(error) {
            $scope.alerts = [{type: "danger", msg: "Error: No se pudo extornar..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };
          }
        );
      };

      $scope.imprimir = function () {

        if (notReady()) {
          return;
        }

        qz.append("\x1B\x40");															//reset printer
        qz.append("\x1B\x21\x08");														//texto en negrita
        qz.append(String.fromCharCode(27) + "\x61" + "\x31");							//texto centrado
        qz.append("CASA DE CAMBIOS VENTURA\r\n");											// \r\n salto de linea

        qz.append(" OPERACION EN EFECTIVO: GIRO " + "\r\n");
        // \t tabulador
        qz.append("\x1B\x21\x01");														//texto normal (no negrita)
        qz.append(String.fromCharCode(27) + "\x61" + "\x30");							//texto a la izquierda

        qz.append("CAJA:" + "\t" + ($scope.cajaSession.abreviatura) + "\t\t" + "Nro OP:" + "\t" + ($scope.giro.id) + "\r\n");
        qz.append("FECHA:" + "\t" + ($filter('date')($scope.giro.fechaEnvio, 'dd/MM/yyyy')) + " " + ($filter('date')($scope.giro.fechaEnvio, 'HH:mm:ss')) + "\r\n");
        qz.append("ORDENANTE:" + "\t" + ($scope.giro.clienteEmisor) + "\r\n");
        qz.append("BENEFICIARIO:" + "\t" + ($scope.giro.numeroDocumentoReceptor + ' ' + $scope.giro.clienteReceptor) + "\r\n");
        qz.append("MONEDA:" + "\t" + ($scope.giro.moneda.denominacion) + "\r\n");

        if (($scope.giro.estado) == "ENVIADO") {
          qz.append("\r\n");
          qz.append("MONTO:" + "\t" + ($filter('currency')($scope.giro.monto, $scope.giro.moneda.simbolo)) + "\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("Verifique su dinero antes  de retirarse de ventanilla" + "\r\n");
        } else if (($scope.giro.estado) == "DESEMBOLSADO") {
          qz.append("\r\n");
          qz.append("MONTO:" + "\t" + ($filter('currency')($scope.giro.monto, $scope.giro.moneda.simbolo)) + "\r\n");
          qz.append("\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("_________________" + "\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          //qz.append("Firma Titular(es)" + "\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("Verifique su dinero antes de retirarse  de ventanilla" + "\r\n");
        }
        qz.append("\x1D\x56\x41");														//cortar papel
        qz.append("\x1B\x40");
        qz.print();

      };

      $scope.cancelar = function () {
        $state.transitionTo("app.transaccion.buscarGiros");
      };

    }]);
});
<commit_msg>$filter error<commit_after>define(['../../module'], function (controllers) {
  'use strict';
  controllers.controller('EditarTransaccionGiroController', ["$scope","$state","$filter","PersonaNaturalService", "AgenciaService", "SessionService", "GiroService",
    function ($scope, $state, $filter, PersonaNaturalService, AgenciaService, SessionService, GiroService) {

      $scope.giro = {};

      $scope.loadGiro = function () {
        GiroService.findById($scope.id).then(function (data) {
          $scope.giro = data;
        });
      };
      $scope.loadGiro();

      //transaccion
      $scope.desembolsar = function () {
        var giro = angular.copy($scope.giro);
        giro.estadoPagoComision = true;
        giro.estado = "COBRADO";

        GiroService.update(giro.id, giro).then(
          function (data) {
            $scope.alerts = [{type: "success", msg: "Monto Desembolsado..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };

            $scope.loadGiro();
          },
          function error(error) {
            $scope.alerts = [{type: "danger", msg: "Error: No se pudo desembolsar..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };
          }
        );
      };

      $scope.extornar = function () {
        var giro = angular.copy($scope.giro);
        giro.estadoPagoComision = false;
        giro.estado = "EXTORNADO";

        GiroService.update(giro.id, giro).then(
          function (data) {
            $scope.alerts = [{type: "success", msg: "Giro Extornado..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };

            $scope.loadGiro();
          },
          function error(error) {
            $scope.alerts = [{type: "danger", msg: "Error: No se pudo extornar..."}];
            $scope.closeAlert = function (index) {
              $scope.alerts.splice(index, 1);
            };
          }
        );
      };

      $scope.imprimir = function () {

        if (notReady()) {
          return;
        }

        qz.append("\x1B\x40");															//reset printer
        qz.append("\x1B\x21\x08");														//texto en negrita
        qz.append(String.fromCharCode(27) + "\x61" + "\x31");							//texto centrado
        qz.append("CASA DE CAMBIOS VENTURA\r\n");											// \r\n salto de linea

        qz.append(" OPERACION EN EFECTIVO: GIRO " + "\r\n");
        // \t tabulador
        qz.append("\x1B\x21\x01");														//texto normal (no negrita)
        qz.append(String.fromCharCode(27) + "\x61" + "\x30");							//texto a la izquierda

        qz.append("CAJA:" + "\t" + ($scope.cajaSession.abreviatura) + "\t\t" + "Nro OP:" + "\t" + ($scope.giro.id) + "\r\n");
        qz.append("FECHA:" + "\t" + ($filter('date')($scope.giro.fechaEnvio, 'dd/MM/yyyy')) + " " + ($filter('date')($scope.giro.fechaEnvio, 'HH:mm:ss')) + "\r\n");
        qz.append("ORDENANTE:" + "\t" + ($scope.giro.clienteEmisor) + "\r\n");
        qz.append("BENEFICIARIO:" + "\t" + ($scope.giro.numeroDocumentoReceptor + ' ' + $scope.giro.clienteReceptor) + "\r\n");
        qz.append("MONEDA:" + "\t" + ($scope.giro.moneda.denominacion) + "\r\n");

        if (($scope.giro.estado) == "ENVIADO") {
          qz.append("\r\n");
          qz.append("MONTO:" + "\t" + ($filter('currency')($scope.giro.monto, $scope.giro.moneda.simbolo)) + "\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("Verifique su dinero antes  de retirarse de ventanilla" + "\r\n");
        } else if (($scope.giro.estado) == "DESEMBOLSADO") {
          qz.append("\r\n");
          qz.append("MONTO:" + "\t" + ($filter('currency')($scope.giro.monto, $scope.giro.moneda.simbolo)) + "\r\n");
          qz.append("\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("_________________" + "\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          //qz.append("Firma Titular(es)" + "\r\n");
          qz.append("\r\n");
          qz.append(String.fromCharCode(27) + "\x61" + "\x31");
          qz.append("Verifique su dinero antes de retirarse  de ventanilla" + "\r\n");
        }
        qz.append("\x1D\x56\x41");														//cortar papel
        qz.append("\x1B\x40");
        qz.print();

      };

      $scope.cancelar = function () {
        $state.transitionTo("app.transaccion.buscarGiros");
      };

    }]);
});
<|endoftext|>


<commit_before>ManageIQ.angular.app.controller('orchestrationTemplateCopyController', ['$http', '$scope', 'stackId', 'miqService', function($http, $scope, stackId, miqService) {
  $scope.stackId = stackId;
  $scope.templateInfo = {
    templateId: null,
    templateName: null,
    templateDescription: null,
    templateDraft: null,
    templateContent: null
  };
  $scope.modelCopy = _.extend({}, $scope.templateInfo);
  $scope.model = 'templateInfo';
  $scope.newRecord = true;
  $scope.saveable = miqService.saveable;

  var otinfoUrl = '/orchestration_stack/stacks_ot_info';
  var submitUrl = '/orchestration_stack/stacks_ot_copy';

  $http.get(otinfoUrl + '/' + stackId).success(function(response) {
    $scope.templateInfo.templateId = response.template_id;
    $scope.templateInfo.templateName = "Copy of " + response.template_name;
    $scope.templateInfo.templateDescription = response.template_description;
    $scope.templateInfo.templateDraft = response.template_draft;
    $scope.templateInfo.templateContent = response.template_content;
    $scope.modelCopy = _.extend({}, $scope.templateInfo);
  });

  $scope.$watch('templateInfo.templateContent', function() {
    if ($scope.templateInfo.templateContent != null) {
      var cursor = ManageIQ.editor.getDoc().getCursor();
      ManageIQ.editor.getDoc().setValue($scope.templateInfo.templateContent);
      ManageIQ.editor.getDoc().setCursor(cursor);
    }
  });

  $scope.cancelClicked = function() {
    miqService.sparkleOn();
    miqService.miqAjaxButton(submitUrl + '?button=cancel&id=' + $scope.stackId);
  };

  $scope.addClicked = function() {
    miqService.sparkleOn();
    miqService.miqAjaxButton(submitUrl + '?button=add', $scope.templateInfo);
  };
}]);
<commit_msg>Orch. Template Form -- Replace .success calls with .then/.catch<commit_after>ManageIQ.angular.app.controller('orchestrationTemplateCopyController', ['$http', '$scope', 'stackId', 'miqService', function($http, $scope, stackId, miqService) {
  $scope.stackId = stackId;
  $scope.templateInfo = {
    templateId: null,
    templateName: null,
    templateDescription: null,
    templateDraft: null,
    templateContent: null
  };
  $scope.modelCopy = _.extend({}, $scope.templateInfo);
  $scope.model = 'templateInfo';
  $scope.newRecord = true;
  $scope.saveable = miqService.saveable;

  var otinfoUrl = '/orchestration_stack/stacks_ot_info';
  var submitUrl = '/orchestration_stack/stacks_ot_copy';

  $http.get(otinfoUrl + '/' + stackId)
    .then(getOrchestrationInfoFormData)
    .catch(miqService.handleFailure);

  $scope.$watch('templateInfo.templateContent', function() {
    if ($scope.templateInfo.templateContent != null) {
      var cursor = ManageIQ.editor.getDoc().getCursor();
      ManageIQ.editor.getDoc().setValue($scope.templateInfo.templateContent);
      ManageIQ.editor.getDoc().setCursor(cursor);
    }
  });

  $scope.cancelClicked = function() {
    miqService.sparkleOn();
    miqService.miqAjaxButton(submitUrl + '?button=cancel&id=' + $scope.stackId);
  };

  $scope.addClicked = function() {
    miqService.sparkleOn();
    miqService.miqAjaxButton(submitUrl + '?button=add', $scope.templateInfo);
  };

  function getOrchestrationInfoFormData(response) {
    var data = response.data;

    $scope.templateInfo.templateId = data.template_id;
    $scope.templateInfo.templateName = "Copy of " + data.template_name;
    $scope.templateInfo.templateDescription = data.template_description;
    $scope.templateInfo.templateDraft = data.template_draft;
    $scope.templateInfo.templateContent = data.template_content;
    $scope.modelCopy = _.extend({}, $scope.templateInfo);
  }
}]);
<|endoftext|>


<commit_before>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';

import initialState from './my-cw-vis-graph-initial-state';
import * as reducers from './my-cw-vis-graph-reducers';
import * as actions from './my-cw-vis-graph-actions';

import MyVisGraphComponent from './my-cw-vis-graph-component';

const mapStateToProps = (state, { location }) => {
  const { data } = state.vizGraph;
  const isEmbed = location.pathname.includes('/embed');
  return {
    location,
    isEmbed,
    data
  };
};

class MyVisGraphContainer extends PureComponent {
  componentDidMount() {
    const { location, fetchVisualisation } = this.props;
    if (location) {
      fetchVisualisation(1);
    }
  }

  render() {
    return createElement(MyVisGraphComponent, {
      ...this.props
    });
  }
}

MyVisGraphContainer.propTypes = {
  location: PropTypes.object.isRequired,
  fetchVisualisation: PropTypes.func.isRequired
};

export { actions, reducers, initialState };
export default withRouter(
  connect(mapStateToProps, actions)(MyVisGraphContainer)
);
<commit_msg>get param from the url<commit_after>import { PureComponent, createElement } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';

import initialState from './my-cw-vis-graph-initial-state';
import * as reducers from './my-cw-vis-graph-reducers';
import * as actions from './my-cw-vis-graph-actions';

import MyVisGraphComponent from './my-cw-vis-graph-component';

const mapStateToProps = (state, { location, match }) => {
  const id = match.params.id;
  const { data } = state.vizGraph;
  const isEmbed = location.pathname.includes('/embed');
  return {
    location,
    isEmbed,
    id,
    data
  };
};

class MyVisGraphContainer extends PureComponent {
  componentDidMount() {
    const { location, id, fetchVisualisation } = this.props;
    if (location) {
      fetchVisualisation(id);
    }
  }

  render() {
    return createElement(MyVisGraphComponent, {
      ...this.props
    });
  }
}

MyVisGraphContainer.propTypes = {
  location: PropTypes.object.isRequired,
  id: PropTypes.string.isRequired,
  fetchVisualisation: PropTypes.func.isRequired
};

export { actions, reducers, initialState };
export default withRouter(
  connect(mapStateToProps, actions)(MyVisGraphContainer)
);
<|endoftext|>