skulpt-stdlib.js 625 KB

1
  1. Sk.builtinFiles={"files": {"src/builtin/this.py": "s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref\n\nOrnhgvshy vf orggre guna htyl.\nRkcyvpvg vf orggre guna vzcyvpvg.\nFvzcyr vf orggre guna pbzcyrk.\nPbzcyrk vf orggre guna pbzcyvpngrq.\nSyng vf orggre guna arfgrq.\nFcnefr vf orggre guna qrafr.\nErnqnovyvgl pbhagf.\nFcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.\nNygubhtu cenpgvpnyvgl orngf chevgl.\nReebef fubhyq arire cnff fvyragyl.\nHayrff rkcyvpvgyl fvyraprq.\nVa gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.\nGurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.\nNygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.\nAbj vf orggre guna arire.\nNygubhtu arire vf bsgra orggre guna *evtug* abj.\nVs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.\nVs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.\nAnzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!\"\"\"\n\nd = {}\nfor c in (65, 97):\n for i in range(26):\n d[chr(i+c)] = chr((i+13) % 26 + c)\n\nprint \"\".join([d.get(c, c) for c in s])\n", "src/builtin/sys.js": "var $builtinmodule = function (name) {\n var i;\n var sys = {};\n\n var args = [];\n var argv = Sk.getSysArgv();\n for (i = 0; i < argv.length; ++i) {\n args.push(new Sk.builtin.str(argv[i]));\n }\n sys.argv = new Sk.builtins[\"list\"](args);\n\n sys.copyright = Sk.builtin[\"str\"](\"Copyright 2009-2010 Scott Graham.\\nAll Rights Reserved.\\n\");\n\n sys.maxint = new Sk.builtin.int_(Math.pow(2,53)-1);\n\n /* The largest positive integer supported by the platform\u2019s Py_ssize_t type,\n * and thus the maximum size lists, strings, dicts, and many other containers can have.\n *\n * In skulpt this is the same as maxint, due to the underlying implementation in javascript\n */\n sys.maxsize = new Sk.builtin.int_(Math.pow(2,53)-1);\n\n sys.modules = Sk.sysmodules;\n\n sys.path = Sk.realsyspath;\n\n sys.getExecutionLimit = new Sk.builtin.func(function () {\n if (Sk.execLimit === null) {\n return Sk.builtin.none.none$;\n }\n return new Sk.builtin.int_(Sk.execLimit);\n });\n\n sys.setExecutionLimit = new Sk.builtin.func(function (t) {\n if (Sk.execLimit === null) {\n throw new Sk.builtin.NotImplementedError(\"Execution limiting is not enabled\");\n }\n if (t !== undefined) {\n Sk.execLimit = Sk.builtin.asnum$(t);\n }\n });\n\n sys.resetTimeout = new Sk.builtin.func(function () {\n Sk.execStart = new Date();\n });\n\n sys.getYieldLimit = new Sk.builtin.func(function () {\n if (Sk.yieldLimit === null) {\n return Sk.builtin.none.none$;\n }\n return new Sk.builtin.int_(Sk.yieldLimit);\n });\n\n sys.setYieldLimit = new Sk.builtin.func(function (t) {\n if (Sk.yieldLimit === null) {\n throw new Sk.builtin.NotImplementedError(\"Yielding is not enabled\");\n }\n if (t !== undefined) {\n Sk.yieldLimit = Sk.builtin.asnum$(t);\n }\n });\n\n sys.debug = new Sk.builtin.func(function () {\n return Sk.builtin.none.none$;\n });\n\n sys.__stdout__ = new Sk.builtin.file(new Sk.builtin.str(\"/dev/stdout\"), \"w\");\n sys.__stdin__ = new Sk.builtin.file(new Sk.builtin.str(\"/dev/stdin\"), \"r\");\n\n sys.stdout = sys.__stdout__;\n sys.stdin = sys.__stdin__;\n\n return sys;\n};\n", "src/lib/zipfile.py": "raise NotImplementedError(\"zipfile is not yet implemented in Skulpt\")\n", "src/lib/shutil.py": "raise NotImplementedError(\"shutil is not yet implemented in Skulpt\")\n", "src/lib/tempfile.py": "raise NotImplementedError(\"tempfile is not yet implemented in Skulpt\")\n", "src/lib/Queue.py": "raise NotImplementedError(\"Queue is not yet implemented in Skulpt\")\n", "src/lib/macpath.py": "raise NotImplementedError(\"macpath is not yet implemented in Skulpt\")\n", "src/lib/pkgutil.py": "raise NotImplementedError(\"pkgutil is not yet implemented in Skulpt\")\n", "src/lib/asyncore.py": "raise NotImplementedError(\"asyncore is not yet implemented in Skulpt\")\n", "src/lib/__phello__.foo.py": "raise NotImplementedError(\"__phello__.foo is not yet implemented in Skulpt\")\n", "src/lib/sndhdr.py": "raise NotImplementedError(\"sndhdr is not yet implemented in Skulpt\")\n", "src/lib/rlcompleter.py": "raise NotImplementedError(\"rlcompleter is not yet implemented in Skulpt\")\n", "src/lib/gzip.py": "raise NotImplementedError(\"gzip is not yet implemented in Skulpt\")\n", "src/lib/user.py": "raise NotImplementedError(\"user is not yet implemented in Skulpt\")\n", "src/lib/urllib2.py": "raise NotImplementedError(\"urllib2 is not yet implemented in Skulpt\")\n", "src/lib/trace.py": "raise NotImplementedError(\"trace is not yet implemented in Skulpt\")\n", "src/lib/webbrowser.py": "raise NotImplementedError(\"webbrowser is not yet implemented in Skulpt\")\n", "src/lib/nntplib.py": "raise NotImplementedError(\"nntplib is not yet implemented in Skulpt\")\n", "src/lib/DocXMLRPCServer.py": "raise NotImplementedError(\"DocXMLRPCServer is not yet implemented in Skulpt\")\n", "src/lib/UserString.py": "raise NotImplementedError(\"UserString is not yet implemented in Skulpt\")\n", "src/lib/dircache.py": "raise NotImplementedError(\"dircache is not yet implemented in Skulpt\")\n", "src/lib/dis.py": "raise NotImplementedError(\"dis is not yet implemented in Skulpt\")\n", "src/lib/formatter.py": "raise NotImplementedError(\"formatter is not yet implemented in Skulpt\")\n", "src/lib/bdb.py": "raise NotImplementedError(\"bdb is not yet implemented in Skulpt\")\n", "src/lib/cmd.py": "raise NotImplementedError(\"cmd is not yet implemented in Skulpt\")\n", "src/lib/tty.py": "raise NotImplementedError(\"tty is not yet implemented in Skulpt\")\n", "src/lib/tabnanny.py": "raise NotImplementedError(\"tabnanny is not yet implemented in Skulpt\")\n", "src/lib/cProfile.py": "raise NotImplementedError(\"cProfile is not yet implemented in Skulpt\")\n", "src/lib/token.py": "raise NotImplementedError(\"token is not yet implemented in Skulpt\")\n", "src/lib/textwrap.py": "raise NotImplementedError(\"textwrap is not yet implemented in Skulpt\")\n", "src/lib/base64.py": "raise NotImplementedError(\"base64 is not yet implemented in Skulpt\")\n", "src/lib/random.js": "/*\n I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace\n so it's better encapsulated. Now you can have multiple random number generators\n and they won't stomp all over eachother's state.\n\n If you want to use this as a substitute for Math.random(), use the random()\n method like so:\n\n var m = new MersenneTwister();\n var randomNumber = m.random();\n\n You can also call the other genrand_{foo}() methods on the instance.\n\n If you want to use a specific seed in order to get a repeatable random\n sequence, pass an integer into the constructor:\n\n var m = new MersenneTwister(123);\n\n and that will always produce the same random sequence.\n\n Sean McCullough (banksean@gmail.com)\n */\n\n/* \n A C-program for MT19937, with initialization improved 2002/1/26.\n Coded by Takuji Nishimura and Makoto Matsumoto.\n\n Before using, initialize the state by using init_genrand(seed)\n or init_by_array(init_key, key_length).\n\n Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n 3. The names of its contributors may not be used to endorse or promote\n products derived from this software without specific prior written\n permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n Any feedback is very welcome.\n http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html\n email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)\n */\n\nvar MersenneTwister = function (seed) {\n if (seed == undefined) {\n seed = new Date().getTime();\n }\n /* Period parameters */\n this.N = 624;\n this.M = 397;\n this.MATRIX_A = 0x9908b0df;\n /* constant vector a */\n this.UPPER_MASK = 0x80000000;\n /* most significant w-r bits */\n this.LOWER_MASK = 0x7fffffff;\n /* least significant r bits */\n\n this.mt = new Array(this.N);\n /* the array for the state vector */\n this.mti = this.N + 1;\n /* mti==N+1 means mt[N] is not initialized */\n\n this.init_genrand(seed);\n}\n\n/* initializes mt[N] with a seed */\nMersenneTwister.prototype.init_genrand = function (s) {\n this.mt[0] = s >>> 0;\n for (this.mti = 1; this.mti < this.N; this.mti++) {\n var s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);\n this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)\n + this.mti;\n /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */\n /* In the previous versions, MSBs of the seed affect */\n /* only MSBs of the array mt[]. */\n /* 2002/01/09 modified by Makoto Matsumoto */\n this.mt[this.mti] >>>= 0;\n /* for >32 bit machines */\n }\n}\n\n/* initialize by an array with array-length */\n/* init_key is the array for initializing keys */\n/* key_length is its length */\n/* slight change for C++, 2004/2/26 */\nMersenneTwister.prototype.init_by_array = function (init_key, key_length) {\n var i, j, k;\n this.init_genrand(19650218);\n i = 1;\n j = 0;\n k = (this.N > key_length ? this.N : key_length);\n for (; k; k--) {\n var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30)\n this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))\n + init_key[j] + j;\n /* non linear */\n this.mt[i] >>>= 0;\n /* for WORDSIZE > 32 machines */\n i++;\n j++;\n if (i >= this.N) {\n this.mt[0] = this.mt[this.N - 1];\n i = 1;\n }\n if (j >= key_length) {\n j = 0;\n }\n }\n for (k = this.N - 1; k; k--) {\n var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);\n this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))\n - i;\n /* non linear */\n this.mt[i] >>>= 0;\n /* for WORDSIZE > 32 machines */\n i++;\n if (i >= this.N) {\n this.mt[0] = this.mt[this.N - 1];\n i = 1;\n }\n }\n\n this.mt[0] = 0x80000000;\n /* MSB is 1; assuring non-zero initial array */\n}\n\n/* generates a random number on [0,0xffffffff]-interval */\nMersenneTwister.prototype.genrand_int32 = function () {\n var y;\n var mag01 = new Array(0x0, this.MATRIX_A);\n /* mag01[x] = x * MATRIX_A for x=0,1 */\n\n if (this.mti >= this.N) { /* generate N words at one time */\n var kk;\n\n if (this.mti == this.N + 1) /* if init_genrand() has not been called, */\n {\n this.init_genrand(5489);\n }\n /* a default initial seed is used */\n\n for (kk = 0; kk < this.N - this.M; kk++) {\n y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);\n this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n for (; kk < this.N - 1; kk++) {\n y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);\n this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];\n }\n y = (this.mt[this.N - 1] & this.UPPER_MASK) | (this.mt[0] & this.LOWER_MASK);\n this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];\n\n this.mti = 0;\n }\n\n y = this.mt[this.mti++];\n\n /* Tempering */\n y ^= (y >>> 11);\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= (y >>> 18);\n\n return y >>> 0;\n}\n\n/* generates a random number on [0,0x7fffffff]-interval */\nMersenneTwister.prototype.genrand_int31 = function () {\n return (this.genrand_int32() >>> 1);\n}\n\n/* generates a random number on [0,1]-real-interval */\nMersenneTwister.prototype.genrand_real1 = function () {\n return this.genrand_int32() * (1.0 / 4294967295.0);\n /* divided by 2^32-1 */\n}\n\n/* generates a random number on [0,1)-real-interval */\nMersenneTwister.prototype.random = function () {\n return this.genrand_int32() * (1.0 / 4294967296.0);\n /* divided by 2^32 */\n}\n\n/* generates a random number on (0,1)-real-interval */\nMersenneTwister.prototype.genrand_real3 = function () {\n return (this.genrand_int32() + 0.5) * (1.0 / 4294967296.0);\n /* divided by 2^32 */\n}\n\n/* generates a random number on [0,1) with 53-bit resolution*/\nMersenneTwister.prototype.genrand_res53 = function () {\n var a = this.genrand_int32() >>> 5, b = this.genrand_int32() >>> 6;\n return(a * 67108864.0 + b) * (1.0 / 9007199254740992.0);\n}\n\n/* These real versions are due to Isaku Wada, 2002/01/09 added */\n\n\nvar $builtinmodule = function (name) {\n\n var mod = {};\n\n var myGenerator = new MersenneTwister();\n var nextNormalSample = undefined;\n\n mod.seed = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"seed\", arguments, 0, 1);\n x = Sk.builtin.asnum$(x);\n\n if (arguments.length > 0) {\n myGenerator = new MersenneTwister(x);\n }\n else {\n myGenerator = new MersenneTwister();\n }\n\n return Sk.builtin.none.none$;\n });\n\n mod.random = new Sk.builtin.func(function () {\n Sk.builtin.pyCheckArgs(\"random\", arguments, 0, 0);\n\n return new Sk.builtin.float_(myGenerator.genrand_res53());\n });\n\n var toInt = function (num) {\n return num | 0;\n };\n\n var randrange = function (start, stop, step) {\n // Ported from CPython 2.7\n var width, n, ret;\n\n if (!Sk.builtin.checkInt(start)) {\n throw new Sk.builtin.ValueError(\"non-integer first argument for randrange()\");\n }\n ;\n\n if (stop === undefined) {\n // Random in [0, start)\n ret = toInt(myGenerator.genrand_res53() * start);\n return new Sk.builtin.int_(ret);\n }\n ;\n\n if (!Sk.builtin.checkInt(stop)) {\n throw new Sk.builtin.ValueError(\"non-integer stop for randrange()\");\n }\n ;\n\n if (step === undefined) {\n step = 1;\n }\n ;\n\n width = stop - start;\n\n if ((step == 1) && (width > 0)) {\n // Random in [start, stop), must use toInt on product for correct results with negative ranges\n ret = start + toInt(myGenerator.genrand_res53() * width);\n return new Sk.builtin.int_(ret);\n }\n ;\n\n if (step == 1) {\n throw new Sk.builtin.ValueError(\"empty range for randrange() (\" + start + \", \" + stop + \", \" + width + \")\");\n }\n ;\n\n if (!Sk.builtin.checkInt(step)) {\n throw new Sk.builtin.ValueError(\"non-integer step for randrange()\");\n }\n ;\n\n if (step > 0) {\n n = toInt((width + step - 1) / step);\n } else if (step < 0) {\n n = toInt((width + step + 1) / step);\n } else {\n throw new Sk.builtin.ValueError(\"zero step for randrange()\");\n }\n ;\n\n if (n <= 0) {\n throw new Sk.builtin.ValueError(\"empty range for randrange()\");\n }\n ;\n\n // Random in range(start, stop, step)\n ret = start + (step * toInt(myGenerator.genrand_res53() * n));\n return new Sk.builtin.int_(ret);\n };\n\n mod.randint = new Sk.builtin.func(function (a, b) {\n Sk.builtin.pyCheckArgs(\"randint\", arguments, 2, 2);\n\n a = Sk.builtin.asnum$(a);\n b = Sk.builtin.asnum$(b);\n return randrange(a, b + 1);\n });\n\n mod.randrange = new Sk.builtin.func(function (start, stop, step) {\n Sk.builtin.pyCheckArgs(\"randrange\", arguments, 1, 3);\n\n start = Sk.builtin.asnum$(start);\n stop = Sk.builtin.asnum$(stop);\n step = Sk.builtin.asnum$(step);\n return randrange(start, stop, step);\n });\n \n mod.uniform = new Sk.builtin.func(function (a, b) {\n Sk.builtin.pyCheckArgs(\"uniform\", arguments, 2, 2);\n\n a = Sk.builtin.asnum$(a);\n b = Sk.builtin.asnum$(b);\n var rnd = myGenerator.genrand_res53();\n c = a + rnd * (b - a)\n return new Sk.builtin.float_(c);\n });\n\n mod.triangular = new Sk.builtin.func(function (low, high, mode) {\n Sk.builtin.pyCheckArgs(\"triangular\", arguments, 2, 3);\n Sk.builtin.pyCheckType(\"low\", \"number\", Sk.builtin.checkNumber(low));\n Sk.builtin.pyCheckType(\"high\", \"number\", Sk.builtin.checkNumber(high));\n\n var rnd, sample, swap;\n\n low = Sk.builtin.asnum$(low);\n high = Sk.builtin.asnum$(high);\n if (low > high) {\n swap = low;\n low = high;\n high = swap;\n }\n if ((mode === undefined) || (mode instanceof Sk.builtin.none)) {\n mode = (high - low)/2.0;\n } else {\n Sk.builtin.pyCheckType(\"mode\", \"number\", Sk.builtin.checkNumber(mode));\n mode = Sk.builtin.asnum$(mode);\n }\n\n // https://en.wikipedia.org/wiki/Triangular_distribution\n rnd = myGenerator.genrand_res53();\n if (rnd < (mode - low)/(high - low)) {\n sample = low + Math.sqrt(rnd * (high - low) * (mode - low));\n } else {\n sample = high - Math.sqrt((1 - rnd) * (high - low) * (high - mode));\n }\n\n return new Sk.builtin.float_(sample);\n });\n\n var normalSample = function(mu, sigma) {\n var r1, r2, u, v, s;\n\n // Box-Muller transform\n // (https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform)\n // generates two independent samples from a Gaussian\n // distribution. Return one of them and store the another one\n // and return it next time.\n\n if (nextNormalSample !== undefined) {\n s = nextNormalSample;\n nextNormalSample = undefined;\n } else {\n r1 = myGenerator.genrand_res53();\n r2 = myGenerator.genrand_res53();\n u = Math.sqrt(-2*Math.log(r1));\n v = 2*Math.PI*r2;\n s = u * Math.cos(v);\n nextNormalSample = u * Math.sin(v);\n }\n\n return mu + sigma*s;\n };\n \n mod.gauss = new Sk.builtin.func(function (mu, sigma) {\n Sk.builtin.pyCheckArgs(\"gauss\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"mu\", \"number\", Sk.builtin.checkNumber(mu));\n Sk.builtin.pyCheckType(\"sigma\", \"number\", Sk.builtin.checkNumber(sigma));\n\n mu = Sk.builtin.asnum$(mu);\n sigma = Sk.builtin.asnum$(sigma);\n\n return new Sk.builtin.float_(normalSample(mu, sigma));\n });\n\n // CPython uses a different (slower but thread-safe) algorithm for\n // normalvariate. We use the same algorithm for normalvariate and\n // gauss.\n mod.normalvariate = mod.gauss;\n\n mod.lognormvariate = new Sk.builtin.func(function (mu, sigma) {\n Sk.builtin.pyCheckArgs(\"lognormvariate\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"mu\", \"number\", Sk.builtin.checkNumber(mu));\n Sk.builtin.pyCheckType(\"sigma\", \"number\", Sk.builtin.checkNumber(sigma));\n\n mu = Sk.builtin.asnum$(mu);\n sigma = Sk.builtin.asnum$(sigma);\n\n return new Sk.builtin.float_(Math.exp(normalSample(mu, sigma)));\n });\n\n mod.expovariate = new Sk.builtin.func(function (lambd) {\n Sk.builtin.pyCheckArgs(\"expovariate\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"lambd\", \"number\", Sk.builtin.checkNumber(lambd));\n\n lambd = Sk.builtin.asnum$(lambd);\n\n var rnd = myGenerator.genrand_res53();\n return new Sk.builtin.float_(-Math.log(rnd)/lambd);\n });\n\n mod.choice = new Sk.builtin.func(function (seq) {\n Sk.builtin.pyCheckArgs(\"choice\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"seq\", \"sequence\", Sk.builtin.checkSequence(seq));\n\n if (seq.sq$length !== undefined) {\n var r = toInt(myGenerator.genrand_res53() * seq.sq$length());\n return seq.mp$subscript(r);\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n }\n });\n\n mod.shuffle = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"shuffle\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"sequence\", Sk.builtin.checkSequence(x));\n\n if (x.sq$length !== undefined) {\n if (x.mp$ass_subscript !== undefined) {\n for (var i = x.sq$length() - 1; i > 0; i -= 1) {\n var r = toInt(myGenerator.genrand_res53() * (i + 1));\n var tmp = x.mp$subscript(r);\n x.mp$ass_subscript(r, x.mp$subscript(i));\n x.mp$ass_subscript(i, tmp);\n }\n ;\n } else {\n throw new Sk.builtin.TypeError(\"object is immutable\");\n }\n ;\n } else {\n throw new Sk.builtin.TypeError(\"object has no length\");\n }\n ;\n\n return Sk.builtin.none.none$;\n });\n\n mod.sample = new Sk.builtin.func(function (population, k) {\n var i, j, iter, elem, reservoir;\n\n Sk.builtin.pyCheckArgs(\"sample\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"population\", \"iterable\", Sk.builtin.checkIterable(population));\n Sk.builtin.pyCheckType(\"k\", \"integer\", Sk.builtin.checkInt(k));\n k = Sk.builtin.asnum$(k);\n \n // \"Algorithm R\" in\n // https://en.wikipedia.org/wiki/Reservoir_sampling\n //\n // This algorithm guarantees that each element has\n // equal probability of being included in the\n // resulting list. See the Wikipedia page for a proof.\n //\n // This requires no extra space but the runtime is\n // proportional to len(population). CPython implements a fast\n // path for the case when k is much smaller than\n // len(population). A similar optimization could be\n // implemented here.\n reservoir = [];\n iter = Sk.abstr.iter(population);\n for (i = 0, elem = iter.tp$iternext();\n elem !== undefined;\n i++, elem = iter.tp$iternext()) {\n j = Math.floor(myGenerator.genrand_res53() * (i + 1));\n if (i < k) {\n // Fill the reservoir\n if (j < i) {\n // Shuffle the existing elements to ensure that\n // subslices are valid random samples\n reservoir[i] = reservoir[j];\n }\n reservoir[j] = elem;\n } else {\n // Replace elements with a probability that decreases\n // the further we get\n if (j < k) {\n reservoir[j] = elem;\n }\n }\n }\n \n if (i < k) {\n throw new Sk.builtin.ValueError(\"sample larger than population\");\n }\n\n return Sk.builtin.list(reservoir);\n });\n\n return mod;\n}\n", "src/lib/Bastion.py": "raise NotImplementedError(\"Bastion is not yet implemented in Skulpt\")\n", "src/lib/HTMLParser.py": "raise NotImplementedError(\"HTMLParser is not yet implemented in Skulpt\")\n", "src/lib/sre_constants.py": "raise NotImplementedError(\"sre_constants is not yet implemented in Skulpt\")\n", "src/lib/cgitb.py": "raise NotImplementedError(\"cgitb is not yet implemented in Skulpt\")\n", "src/lib/statvfs.py": "raise NotImplementedError(\"statvfs is not yet implemented in Skulpt\")\n", "src/lib/macurl2path.py": "raise NotImplementedError(\"macurl2path is not yet implemented in Skulpt\")\n", "src/lib/StringIO.py": "r\"\"\"File-like objects that read from or write to a string buffer.\n\nThis implements (nearly) all stdio methods.\n\nf = StringIO() # ready for writing\nf = StringIO(buf) # ready for reading\nf.close() # explicitly release resources held\nflag = f.isatty() # always false\npos = f.tell() # get current position\nf.seek(pos) # set current position\nf.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF\nbuf = f.read() # read until EOF\nbuf = f.read(n) # read up to n bytes\nbuf = f.readline() # read until end of line ('\\n') or EOF\nlist = f.readlines()# list of f.readline() results until EOF\nf.truncate([size]) # truncate file at to at most size (default: current pos)\nf.write(buf) # write at current position\nf.writelines(list) # for line in list: f.write(line)\nf.getvalue() # return whole file's contents as a string\n\nNotes:\n- Using a real file is often faster (but less convenient).\n- There's also a much faster implementation in C, called cStringIO, but\n it's not subclassable.\n- fileno() is left unimplemented so that code which uses it triggers\n an exception early.\n- Seeking far beyond EOF and then writing will insert real null\n bytes that occupy space in the buffer.\n- There's a simple test set (see end of this file).\n\"\"\"\n\n__all__ = [\"StringIO\"]\n\ndef _complain_ifclosed(closed):\n if closed:\n raise ValueError, \"I/O operation on closed file\"\n\nclass StringIO:\n \"\"\"class StringIO([buffer])\n\n When a StringIO object is created, it can be initialized to an existing\n string by passing the string to the constructor. If no string is given,\n the StringIO will start empty.\n\n The StringIO object can accept either Unicode or 8-bit strings, but\n mixing the two may take some care. If both are used, 8-bit strings that\n cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause\n a UnicodeError to be raised when getvalue() is called.\n \"\"\"\n def __init__(self, buf = ''):\n # Force self.buf to be a string or unicode\n if not isinstance(buf, str):\n buf = str(buf)\n self.buf = buf\n self.len = len(buf)\n self.buflist = []\n self.pos = 0\n self.closed = False\n self.softspace = 0\n\n def __iter__(self):\n return self\n\n def next(self):\n \"\"\"A file object is its own iterator, for example iter(f) returns f\n (unless f is closed). When a file is used as an iterator, typically\n in a for loop (for example, for line in f: print line), the next()\n method is called repeatedly. This method returns the next input line,\n or raises StopIteration when EOF is hit.\n \"\"\"\n _complain_ifclosed(self.closed)\n r = self.readline()\n if not r:\n raise StopIteration\n return r\n\n def close(self):\n \"\"\"Free the memory buffer.\n \"\"\"\n if not self.closed:\n self.closed = True\n self.buf = None\n self.pos = None\n\n def isatty(self):\n \"\"\"Returns False because StringIO objects are not connected to a\n tty-like device.\n \"\"\"\n _complain_ifclosed(self.closed)\n return False\n\n def seek(self, pos, mode = 0):\n \"\"\"Set the file's current position.\n\n The mode argument is optional and defaults to 0 (absolute file\n positioning); other values are 1 (seek relative to the current\n position) and 2 (seek relative to the file's end).\n\n There is no return value.\n \"\"\"\n _complain_ifclosed(self.closed)\n if self.buflist:\n self.buf += ''.join(self.buflist)\n self.buflist = []\n if mode == 1:\n pos += self.pos\n elif mode == 2:\n pos += self.len\n self.pos = max(0, pos)\n\n def tell(self):\n \"\"\"Return the file's current position.\"\"\"\n _complain_ifclosed(self.closed)\n return self.pos\n\n def read(self, n = -1):\n \"\"\"Read at most size bytes from the file\n (less if the read hits EOF before obtaining size bytes).\n\n If the size argument is negative or omitted, read all data until EOF\n is reached. The bytes are returned as a string object. An empty\n string is returned when EOF is encountered immediately.\n \"\"\"\n _complain_ifclosed(self.closed)\n if self.buflist:\n self.buf += ''.join(self.buflist)\n self.buflist = []\n if n is None or n < 0:\n newpos = self.len\n else:\n newpos = min(self.pos+n, self.len)\n r = self.buf[self.pos:newpos]\n self.pos = newpos\n return r\n\n def readline(self, length=None):\n r\"\"\"Read one entire line from the file.\n\n A trailing newline character is kept in the string (but may be absent\n when a file ends with an incomplete line). If the size argument is\n present and non-negative, it is a maximum byte count (including the\n trailing newline) and an incomplete line may be returned.\n\n An empty string is returned only when EOF is encountered immediately.\n\n Note: Unlike stdio's fgets(), the returned string contains null\n characters ('\\0') if they occurred in the input.\n \"\"\"\n _complain_ifclosed(self.closed)\n if self.buflist:\n self.buf += ''.join(self.buflist)\n self.buflist = []\n i = self.buf.find('\\n', self.pos)\n if i < 0:\n newpos = self.len\n else:\n newpos = i+1\n if length is not None and length >= 0:\n if self.pos + length < newpos:\n newpos = self.pos + length\n r = self.buf[self.pos:newpos]\n self.pos = newpos\n return r\n\n def readlines(self, sizehint = 0):\n \"\"\"Read until EOF using readline() and return a list containing the\n lines thus read.\n\n If the optional sizehint argument is present, instead of reading up\n to EOF, whole lines totalling approximately sizehint bytes (or more\n to accommodate a final whole line).\n \"\"\"\n total = 0\n lines = []\n line = self.readline()\n while line:\n lines.append(line)\n total += len(line)\n if 0 < sizehint <= total:\n break\n line = self.readline()\n return lines\n\n def truncate(self, size=None):\n \"\"\"Truncate the file's size.\n\n If the optional size argument is present, the file is truncated to\n (at most) that size. The size defaults to the current position.\n The current file position is not changed unless the position\n is beyond the new file size.\n\n If the specified size exceeds the file's current size, the\n file remains unchanged.\n \"\"\"\n _complain_ifclosed(self.closed)\n if size is None:\n size = self.pos\n elif size < 0:\n raise IOError(22, \"Negative size not allowed\")\n elif size < self.pos:\n self.pos = size\n self.buf = self.getvalue()[:size]\n self.len = size\n\n def write(self, s):\n \"\"\"Write a string to the file.\n\n There is no return value.\n \"\"\"\n _complain_ifclosed(self.closed)\n if not s: return\n # Force s to be a string or unicode\n if not isinstance(s, str):\n s = str(s)\n spos = self.pos\n slen = self.len\n if spos == slen:\n self.buflist.append(s)\n self.len = self.pos = spos + len(s)\n return\n if spos > slen:\n self.buflist.append('\\0'*(spos - slen))\n slen = spos\n newpos = spos + len(s)\n if spos < slen:\n if self.buflist:\n self.buf += ''.join(self.buflist)\n self.buflist = [self.buf[:spos], s, self.buf[newpos:]]\n self.buf = ''\n if newpos > slen:\n slen = newpos\n else:\n self.buflist.append(s)\n slen = newpos\n self.len = slen\n self.pos = newpos\n\n def writelines(self, iterable):\n \"\"\"Write a sequence of strings to the file. The sequence can be any\n iterable object producing strings, typically a list of strings. There\n is no return value.\n\n (The name is intended to match readlines(); writelines() does not add\n line separators.)\n \"\"\"\n write = self.write\n for line in iterable:\n write(line)\n\n def flush(self):\n \"\"\"Flush the internal buffer\n \"\"\"\n _complain_ifclosed(self.closed)\n\n def getvalue(self):\n \"\"\"\n Retrieve the entire contents of the \"file\" at any time before\n the StringIO object's close() method is called.\n\n The StringIO object can accept either Unicode or 8-bit strings,\n but mixing the two may take some care. If both are used, 8-bit\n strings that cannot be interpreted as 7-bit ASCII (that use the\n 8th bit) will cause a UnicodeError to be raised when getvalue()\n is called.\n \"\"\"\n _complain_ifclosed(self.closed)\n if self.buflist:\n self.buf += ''.join(self.buflist)\n self.buflist = []\n return self.buf\n", "src/lib/htmllib.py": "raise NotImplementedError(\"htmllib is not yet implemented in Skulpt\")\n", "src/lib/_threading_local.py": "raise NotImplementedError(\"_threading_local is not yet implemented in Skulpt\")\n", "src/lib/pyclbr.py": "raise NotImplementedError(\"pyclbr is not yet implemented in Skulpt\")\n", "src/lib/gettext.py": "raise NotImplementedError(\"gettext is not yet implemented in Skulpt\")\n", "src/lib/operator.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python operator module.\n */\n\nvar $builtinmodule = function (name) {\n var mod = {};\n\n mod.lt = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Lt'));\n });\n mod.__lt__ = mod.lt;\n\n mod.le = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'LtE'));\n });\n mod.__le__ = mod.le;\n\n mod.eq = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Eq'));\n });\n mod.__eq__ = mod.eq;\n\n mod.ne = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'NotEq'));\n });\n mod.__ne__ = mod.ne;\n\n mod.ge = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'GtE'));\n });\n mod.__ge__ = mod.ge;\n\n mod.gt = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Gt'));\n });\n mod.__gt__ = mod.gt;\n\n mod.not_ = new Sk.builtin.func(function (obj) {\n throw new Sk.builtin.NotImplementedError(\"operator.not_() is not yet implemented in Skulpt\");\n });\n\n mod.truth = new Sk.builtin.func(function (obj) {\n return Sk.builtin.bool(obj);\n });\n\n mod.is_ = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'Is'));\n });\n\n mod.is_not = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.misceval.richCompareBool(a, b, 'IsNot'));\n });\n\n mod.abs = new Sk.builtin.func(function (obj) {\n return Sk.misceval.callsim(Sk.builtin.abs, obj);\n });\n mod.__abs__ = mod.abs;\n\n // The documentation says that operator.add() is defined for a and b numbers, but\n // CPython (2.6) allows a and b to be other types (e.g. str)\n mod.add = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.objectAdd(a, b);\n });\n mod.__add__ = mod.add;\n\n mod.and_ = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"BitAnd\");\n });\n mod.__and__ = mod.and_;\n\n mod.div = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"Div\");\n });\n mod.__div__ = mod.div;\n\n mod.floordiv = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"FloorDiv\");\n });\n mod.__floordiv__ = mod.floordiv;\n\n mod.index = new Sk.builtin.func(function (a) {\n return new Sk.builtin.int_(Sk.misceval.asIndex(a));\n });\n mod.__index__ = mod.index;\n\n // Note: Sk.abstr.numberUnaryOp(obj, 'Invert') looks for the function nb$invert() on obj.\n // However, it doesn't look like that function has been implemented for any existing object types.\n // I've gone ahead and created this function for completeness' sake, but expect any use of it to\n // result in an error.\n mod.inv = new Sk.builtin.func(function (obj) {\n return Sk.abstr.numberUnaryOp(obj, 'Invert');\n });\n mod.__inv__ = mod.inv;\n mod.invert = mod.inv;\n mod.__invert__ = mod.inv;\n\n mod.lshift = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"LShift\");\n });\n mod.__lshift__ = mod.lshift;\n\n mod.mod = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"Mod\");\n });\n mod.__mod__ = mod.mod;\n\n mod.divmod = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"DivMod\");\n });\n mod.__divmod__ = mod.divmod;\n\n mod.mul = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"Mult\");\n });\n mod.__mul__ = mod.mul;\n\n mod.neg = new Sk.builtin.func(function (obj) {\n return Sk.abstr.objectNegative(obj);\n });\n mod.__neg__ = mod.neg;\n\n mod.or_ = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"BitOr\");\n });\n mod.__or__ = mod.or_;\n\n mod.pos = new Sk.builtin.func(function (obj) {\n return Sk.abstr.objectPositive(obj);\n });\n mod.__pos__ = mod.pos;\n\n mod.pow = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"Pow\");\n });\n mod.__pow__ = mod.pow;\n\n mod.rshift = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"RShift\");\n });\n mod.__rshift__ = mod.rshift;\n\n mod.sub = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"Sub\");\n });\n mod.__sub__ = mod.sub;\n\n mod.truediv = mod.div;\n mod.__truediv__ = mod.div;\n\n mod.xor = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.binary_op_(a, b, \"BitXor\");\n });\n mod.__xor__ = mod.xor;\n\n mod.concat = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.sequenceConcat(a, b);\n });\n mod.__concat__ = mod.concat;\n\n mod.contains = new Sk.builtin.func(function (a, b) {\n return Sk.builtin.bool(Sk.abstr.sequenceContains(a, b));\n });\n mod.__contains__ = mod.contains;\n\n mod.countOf = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.sequenceGetCountOf(a, b);\n });\n\n mod.delitem = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.sequenceDelItem(a, b);\n });\n mod.__delitem__ = mod.delitem;\n\n mod.getitem = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.sequenceGetItem(a, b);\n });\n mod.__getitem__ = mod.getitem;\n\n mod.indexOf = new Sk.builtin.func(function (a, b) {\n return Sk.abstr.sequenceGetIndexOf(a, b);\n });\n\n mod.setitem = new Sk.builtin.func(function (a, b, c) {\n return Sk.abstr.sequenceSetItem(a, b, c);\n });\n mod.__setitem__ = mod.setitem;\n\n return mod;\n};\n", "src/lib/wave.py": "raise NotImplementedError(\"wave is not yet implemented in Skulpt\")\n", "src/lib/rfc822.py": "raise NotImplementedError(\"rfc822 is not yet implemented in Skulpt\")\n", "src/lib/weakref.py": "raise NotImplementedError(\"weakref is not yet implemented in Skulpt\")\n", "src/lib/bisect.py": "raise NotImplementedError(\"bisect is not yet implemented in Skulpt\")\n", "src/lib/opcode.py": "raise NotImplementedError(\"opcode is not yet implemented in Skulpt\")\n", "src/lib/netrc.py": "raise NotImplementedError(\"netrc is not yet implemented in Skulpt\")\n", "src/lib/heapq.py": "raise NotImplementedError(\"heapq is not yet implemented in Skulpt\")\n", "src/lib/functools.py": "raise NotImplementedError(\"functools is not yet implemented in Skulpt\")\n", "src/lib/multifile.py": "raise NotImplementedError(\"multifile is not yet implemented in Skulpt\")\n", "src/lib/modulefinder.py": "raise NotImplementedError(\"modulefinder is not yet implemented in Skulpt\")\n", "src/lib/hashlib.py": "raise NotImplementedError(\"hashlib is not yet implemented in Skulpt\")\n", "src/lib/markupbase.py": "raise NotImplementedError(\"markupbase is not yet implemented in Skulpt\")\n", "src/lib/cgi.py": "raise NotImplementedError(\"cgi is not yet implemented in Skulpt\")\n", "src/lib/codeop.py": "raise NotImplementedError(\"codeop is not yet implemented in Skulpt\")\n", "src/lib/fnmatch.py": "raise NotImplementedError(\"fnmatch is not yet implemented in Skulpt\")\n", "src/lib/traceback.py": "raise NotImplementedError(\"traceback is not yet implemented in Skulpt\")\n", "src/lib/rexec.py": "raise NotImplementedError(\"rexec is not yet implemented in Skulpt\")\n", "src/lib/nturl2path.py": "raise NotImplementedError(\"nturl2path is not yet implemented in Skulpt\")\n", "src/lib/warnings.py": "raise NotImplementedError(\"warnings is not yet implemented in Skulpt\")\n", "src/lib/SimpleHTTPServer.py": "raise NotImplementedError(\"SimpleHTTPServer is not yet implemented in Skulpt\")\n", "src/lib/subprocess.py": "raise NotImplementedError(\"subprocess is not yet implemented in Skulpt\")\n", "src/lib/SimpleXMLRPCServer.py": "raise NotImplementedError(\"SimpleXMLRPCServer is not yet implemented in Skulpt\")\n", "src/lib/imputil.py": "raise NotImplementedError(\"imputil is not yet implemented in Skulpt\")\n", "src/lib/time.js": "/*\n implementation of the Python time package.\n\n For higher res time we could use following apart from new Date:\n window.performance.now()\n\n notes:\n - struct_time is a structseq but structseq does not implement methods: 'n_fields', 'n_sequence_fields', 'n_unnamed_fields' yet\n\n ['__doc__', '__file__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']\n */\n\nvar $builtinmodule = function (name) {\n var mod = {};\n\n mod.__file__ = \"/src/lib/time/__init__.js\";\n\n mod.__package__ = Sk.builtin.none.none$;\n\n var struct_time_fields = {\n \"tm_year\": \"year, for example, 1993\", \n \"tm_mon\": \"month of year, range [1, 12]\", \n \"tm_mday\": \"day of month, range [1, 31]\", \n \"tm_hour\": \"hours, range [0, 23]\", \n \"tm_min\": \"minutes, range [0, 59]\", \n \"tm_sec\": \"seconds, range [0, 61]\", \n \"tm_wday\": \"day of week, range [0, 6], Monday is 0\", \n \"tm_yday\": \"day of year, range [1, 366]\", \n \"tm_isdst\": \"1 if summer time is in effect, 0 if not, and -1 if unknown\"\n };\n\n var struct_time_f = Sk.builtin.make_structseq('time', 'struct_time', struct_time_fields);\n\n mod.struct_time = struct_time_f;\n\n function check_struct_time(t) {\n if (!(t instanceof struct_time_f)) {\n throw new Sk.builtin.TypeError(\"Required argument 'struct_time' must be of type: 'struct_time'\");\n }\n var i;\n var len = t.v.length;\n var obj = t.v;\n for (i = 0; i < len; ++i) {\n if (!Sk.builtin.checkInt(obj[i])) {\n throw new Sk.builtin.TypeError(\"struct_time may only contain integers\");\n }\n }\n return true;\n }\n\n mod.time = new Sk.builtin.func(function () {\n Sk.builtin.pyCheckArgs(\"time\", arguments, 0, 0);\n var res = Date.now();\n if (performance && performance.now)\n {\n res = res + performance.now() % 1;\n }\n return Sk.builtin.assk$(res / 1000, undefined);\n });\n\n // This is an experimental implementation of time.sleep(), using suspensions\n mod.sleep = new Sk.builtin.func(function(delay) {\n Sk.builtin.pyCheckArgs(\"sleep\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"delay\", \"float\", Sk.builtin.checkNumber(delay));\n var susp = new Sk.misceval.Suspension();\n susp.resume = function() { return Sk.builtin.none.none$; }\n susp.data = {type: \"Sk.promise\", promise: new Promise(function(resolve) {\n Sk.setTimeout(resolve, Sk.ffi.remapToJs(delay)*1000);\n })};\n return susp;\n });\n\n function padLeft(str, l, c) {\n var _str = str.toString();\n return Array(l - _str.length + 1).join(c || \" \") + _str;\n }\n\n function isLeapYear(year) {\n if((year & 3) != 0) return false;\n return ((year % 100) != 0 || (year % 400) == 0);\n }\n\n function getDayOfYear(date,utc) {\n utc = utc || false;\n var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];\n var mn = utc ? date.getUTCMonth() : date.getMonth();\n var dn = utc ? date.getUTCDate() : date.getDate();\n var dayOfYear = dayCount[mn] + dn;\n if(mn > 1 && isLeapYear(utc ? date.getUTCFullYear() : date.getFullYear())) dayOfYear++;\n return dayOfYear;\n }\n\n function stdTimezoneOffset() {\n var jan = new Date(2002, 0, 1);\n var jul = new Date(2002, 6, 1);\n return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());\n }\n\n function altTimezoneOffset() {\n var jan = new Date(2002, 0, 1);\n var jul = new Date(2002, 6, 1);\n return Math.min(jan.getTimezoneOffset(), jul.getTimezoneOffset());\n } \n\n function dst(date) {\n return date.getTimezoneOffset() < stdTimezoneOffset();\n }\n\n function timeZoneName(date) {\n return /\\((.*)\\)/.exec(date.toString())[1];\n }\n\n function timeZoneNames() {\n var jan = new Date(2002, 0, 1);\n var jul = new Date(2002, 6, 1); \n if (dst(jan)) {\n return [Sk.builtin.str(timeZoneName(jul)), Sk.builtin.str(timeZoneName(jan))];\n } else {\n return [Sk.builtin.str(timeZoneName(jan)), Sk.builtin.str(timeZoneName(jul))];\n }\n }\n\n function date_to_struct_time(date, utc) {\n utc = utc || false;\n // y, m, d, hh, mm, ss, weekday, jday, dst\n return new struct_time_f(\n [\n Sk.builtin.assk$(utc ? date.getUTCFullYear() : date.getFullYear()), \n Sk.builtin.assk$((utc ? date.getUTCMonth() : date.getMonth()) + 1), // want January == 1\n Sk.builtin.assk$(utc ? date.getUTCDate() : date.getDate()), \n Sk.builtin.assk$(utc ? date.getUTCHours() : date.getHours()), \n Sk.builtin.assk$(utc ? date.getUTCMinutes() : date.getMinutes()), \n Sk.builtin.assk$(utc ? date.getUTCSeconds() : date.getSeconds()), \n Sk.builtin.assk$(((utc ? date.getUTCDay() : date.getDay()) + 6) % 7), // Want Monday == 0\n Sk.builtin.assk$(getDayOfYear(date, utc)), // Want January, 1 == 1\n Sk.builtin.assk$(utc ? 0 : (dst(date) ? 1 : 0)) // 1 for DST /0 for non-DST /-1 for unknown\n ]\n );\n }\n\n function localtime_f(secs) {\n Sk.builtin.pyCheckArgs(\"localtime\", arguments, 0, 1);\n var d = new Date();\n if (secs) {\n Sk.builtin.pyCheckType(\"secs\", \"number\", Sk.builtin.checkNumber(secs));\n var seconds = Sk.builtin.asnum$(secs);\n d.setTime(seconds * 1000);\n }\n return date_to_struct_time(d);\n }\n\n mod.localtime = new Sk.builtin.func(localtime_f);\n\n mod.gmtime = new Sk.builtin.func(function(secs) {\n Sk.builtin.pyCheckArgs(\"localtime\", arguments, 0, 1);\n var d = new Date();\n if (secs) {\n Sk.builtin.pyCheckType(\"secs\", \"number\", Sk.builtin.checkNumber(secs));\n var seconds = Sk.builtin.asnum$(secs);\n d.setTime(seconds * 1000);\n }\n return date_to_struct_time(d, true);\n });\n\n var monthnames = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n var daynames = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\n\n function asctime_f(time) {\n if (!time || Sk.builtin.checkNone(time))\n {\n time = localtime_f();\n } else if (!(time instanceof struct_time_f)) {\n time = new struct_time_f(time);\n }\n if (time instanceof Sk.builtin.tuple && time.v.length == 9)\n {\n // todo: test validity??\n var parts = [];\n parts.push(daynames[Sk.builtin.asnum$(time.v[6])]);\n parts.push(monthnames[Sk.builtin.asnum$(time.v[1])-1]); \n parts.push(padLeft(Sk.builtin.asnum$(time.v[2]).toString(), 2, '0'));\n parts.push(\n padLeft(Sk.builtin.asnum$(time.v[3]).toString(), 2, '0') + \":\" +\n padLeft(Sk.builtin.asnum$(time.v[4]).toString(), 2, '0') + \":\" +\n padLeft(Sk.builtin.asnum$(time.v[5]).toString(), 2, '0')\n );\n parts.push(padLeft(Sk.builtin.asnum$(time.v[0]).toString(), 4, '0'));\n\n return Sk.builtin.str(parts.join(\" \"));\n }\n }\n\n mod.asctime = new Sk.builtin.func(asctime_f);\n\n mod.ctime = new Sk.builtin.func(function(secs) {\n return asctime_f(localtime_f(secs));\n });\n\n function mktime_f(time) {\n if (time instanceof Sk.builtin.tuple && time.v.length == 9)\n {\n var d = new Date();\n d.setFullYear(Sk.builtin.asnum$(time.v[0]));\n d.setMonth(Sk.builtin.asnum$(time.v[1])-1);\n d.setDate(Sk.builtin.asnum$(time.v[2]));\n d.setHours(Sk.builtin.asnum$(time.v[3]));\n d.setMinutes(Sk.builtin.asnum$(time.v[4]));\n d.setSeconds(Sk.builtin.asnum$(time.v[5]));\n return Sk.builtin.assk$(d.getTime() / 1000, undefined);\n } else {\n throw new Sk.builtin.TypeError(\"mktime() requires a struct_time or 9-tuple\");\n }\n }\n\n mod.mktime = new Sk.builtin.func(mktime_f);\n\n /*\n The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, \n positive in the US, zero in the UK).\n */\n mod.timezone = new Sk.builtin.int_(stdTimezoneOffset() * 60);\n\n /*\n The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the\n local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.\n */\n mod.altzone = new Sk.builtin.int_(altTimezoneOffset() * 60);\n\n /*\n Nonzero if a DST timezone is defined.\n */\n mod.daylight = new Sk.builtin.int_(dst(new Date()) ? 1 : 0);\n\n /*\n A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local \n DST timezone. If no DST timezone is defined, the second string should not be used.\n */\n mod.tzname = Sk.builtin.tuple(timeZoneNames());\n\n mod.accept2dyear = Sk.builtin.assk$(1, Sk.builtin.nmber.int$);\n\n mod.clock = new Sk.builtin.func(function() {\n var res = 0.0;\n if (performance && performance.now)\n {\n res = performance.now() / 1000;\n } else {\n res = new Date().getTime() / 1000;\n }\n return new Sk.builtin.float_(res);\n });\n\n function strftime_f(format, t) {\n var jsFormat;\n\n Sk.builtin.pyCheckArgs(\"strftime\", arguments, 1, 2);\n if (!Sk.builtin.checkString(format)) {\n throw new Sk.builtin.TypeError(\"format must be a string\");\n }\n if (!t)\n {\n t = localtime_f();\n } else if (!(t instanceof struct_time_f)) {\n t = new struct_time_f(t);\n }\n\n check_struct_time(t);\n \n jsFormat = Sk.ffi.remapToJs(format);\n\n return Sk.ffi.remapToPy(strftime(jsFormat, new Date(mktime_f(t).v*1000)));\n }\n\n mod.strftime = new Sk.builtin.func(strftime_f);\n\n function tzset_f()\n {\n throw new Sk.builtin.NotImplementedError(\"time.tzset() is not yet implemented\");\n Sk.builtin.pyCheckArgs(\"tzset\", arguments, 0, 0);\n }\n\n mod.tzset = new Sk.builtin.func(tzset_f);\n\n function strptime_f(s, format)\n {\n Sk.builtin.pyCheckArgs(\"strptime\", arguments, 1, 2);\n Sk.builtin.pyCheckType(\"string\", \"string\", Sk.builtin.checkString(s));\n if (format !== undefined) {\n Sk.builtin.pyCheckType(\"format\", \"string\", Sk.builtin.checkString(format));\n } else {\n format = new Sk.builtin.str(\"%a %b %d %H:%M:%S %Y\");\n }\n\n return date_to_struct_time(strptime(Sk.ffi.remapToJs(s), Sk.ffi.remapToJs(format), true));\n }\n\n mod.strptime = new Sk.builtin.func(strptime_f);\n\n return mod;\n};\n", "src/lib/profile.py": "raise NotImplementedError(\"profile is not yet implemented in Skulpt\")\n", "src/lib/imghdr.py": "raise NotImplementedError(\"imghdr is not yet implemented in Skulpt\")\n", "src/lib/mimetools.py": "raise NotImplementedError(\"mimetools is not yet implemented in Skulpt\")\n", "src/lib/this.py": "raise NotImplementedError(\"this is not yet implemented in Skulpt\")\n", "src/lib/filecmp.py": "raise NotImplementedError(\"filecmp is not yet implemented in Skulpt\")\n", "src/lib/codecs.py": "raise NotImplementedError(\"codecs is not yet implemented in Skulpt\")\n", "src/lib/uu.py": "raise NotImplementedError(\"uu is not yet implemented in Skulpt\")\n", "src/lib/io.py": "raise NotImplementedError(\"io is not yet implemented in Skulpt\")\n", "src/lib/MimeWriter.py": "raise NotImplementedError(\"MimeWriter is not yet implemented in Skulpt\")\n", "src/lib/code.py": "raise NotImplementedError(\"code is not yet implemented in Skulpt\")\n", "src/lib/fileinput.py": "raise NotImplementedError(\"fileinput is not yet implemented in Skulpt\")\n", "src/lib/os.py": "raise NotImplementedError(\"os is not yet implemented in Skulpt\")\n", "src/lib/difflib.py": "raise NotImplementedError(\"difflib is not yet implemented in Skulpt\")\n", "src/lib/pydoc.py": "raise NotImplementedError(\"pydoc is not yet implemented in Skulpt\")\n", "src/lib/symbol.py": "raise NotImplementedError(\"symbol is not yet implemented in Skulpt\")\n", "src/lib/pydoc_topics.py": "raise NotImplementedError(\"pydoc_topics is not yet implemented in Skulpt\")\n", "src/lib/atexit.py": "raise NotImplementedError(\"atexit is not yet implemented in Skulpt\")\n", "src/lib/sgmllib.py": "raise NotImplementedError(\"sgmllib is not yet implemented in Skulpt\")\n", "src/lib/decimal.py": "raise NotImplementedError(\"decimal is not yet implemented in Skulpt\")\n", "src/lib/SocketServer.py": "raise NotImplementedError(\"SocketServer is not yet implemented in Skulpt\")\n", "src/lib/copy.py": "\"\"\"\nThis file was modified from CPython.\nCopyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,\n2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved\n\"\"\"\nimport types\nclass Error(Exception):\n pass\nerror = Error \nclass _EmptyClass:\n pass\n\ndef copy(x):\n cls = type(x)\n if callable(x):\n return x\n copier = getattr(cls, \"__copy__\", None)\n if copier:\n return copier(x)\n if cls in (type(None), int, float, bool, long, str, tuple, type):\n return x\n if (cls == list) or (cls == dict) or (cls == set) or (cls == slice):\n return cls(x)\n try:\n getstate = getattr(x, \"__getstate__\", None)\n setstate = getattr(x, \"__setstate__\", None)\n initargs = getattr(x, \"__getinitargs__\", None)\n except:\n reductor = False\n if getstate or setstate or initargs:\n raise NotImplementedError(\"Skulpt does not yet support copying with user-defined __getstate__, __setstate__ or __getinitargs__()\")\n reductor = getattr(x, \"__reduce_ex__\", None)\n if reductor:\n rv = reductor(4)\n else:\n reductor = getattr(x, \"__reduce__\", None)\n if reductor:\n rv = reductor()\n elif str(cls)[1:6] == \"class\":\n copier = _copy_inst\n return copier(x)\n else:\n raise Error(\"un(shallow)copyable object of type %s\" % cls)\n if isinstance(rv, str):\n return x\n return _reconstruct(x, rv, 0)\n\ndef _copy_inst(x):\n if hasattr(x, '__copy__'):\n return x.__copy__()\n if hasattr(x, '__getinitargs__'):\n args = x.__getinitargs__()\n y = x.__class__(*args)\n else:\n y = _EmptyClass()\n y.__class__ = x.__class__\n if hasattr(x, '__getstate__'):\n state = x.__getstate__()\n else:\n state = x.__dict__\n if hasattr(y, '__setstate__'):\n y.__setstate__(state)\n else:\n y.__dict__.update(state)\n return y\n\nd = _deepcopy_dispatch = {}\n\ndef deepcopy(x, memo=None, _nil=[]):\n \"\"\"Deep copy operation on arbitrary Python objects.\n See the module's __doc__ string for more info.\n \"\"\"\n if memo is None:\n memo = {}\n idx = id(x)\n y = memo.get(idx, _nil)\n if y is not _nil:\n return y\n cls = type(x)\n try:\n getstate = getattr(x, \"__getstate__\", None)\n setstate = getattr(x, \"__setstate__\", None)\n initargs = getattr(x, \"__getinitargs__\", None)\n except:\n reductor = False\n if getstate or setstate or initargs:\n raise NotImplementedError(\"Skulpt does not yet support copying with user-defined __getstate__, __setstate__ or __getinitargs__()\")\n copier = _deepcopy_dispatch.get(cls)\n if copier:\n y = copier(x, memo)\n elif str(cls)[1:6] == \"class\":\n copier = _deepcopy_dispatch[\"InstanceType\"]\n y = copier(x, memo)\n else:\n try:\n issc = issubclass(cls, type)\n except TypeError: # cls is not a class (old Boost; see SF #502085)\n issc = 0\n if issc:\n y = _deepcopy_atomic(x, memo)\n else:\n copier = getattr(x, \"__deepcopy__\", None)\n if copier:\n y = copier(memo)\n else:\n reductor = getattr(x, \"__reduce_ex__\", None)\n if reductor:\n rv = reductor(2)\n else:\n reductor = getattr(x, \"__reduce__\", None)\n if reductor:\n rv = reductor()\n else:\n raise Error(\n \"un(deep)copyable object of type %s\" % cls)\n y = _reconstruct(x, rv, 1, memo)\n memo[idx] = y\n _keep_alive(x, memo) # Make sure x lives at least as long as d\n return y\n\ndef _deepcopy_atomic(x, memo):\n return x\nd[type(None)] = _deepcopy_atomic\n# d[type(Ellipsis)] = _deepcopy_atomic\nd[type(NotImplemented)] = _deepcopy_atomic\nd[int] = _deepcopy_atomic\nd[float] = _deepcopy_atomic\nd[bool] = _deepcopy_atomic\nd[complex] = _deepcopy_atomic\n# d[bytes] = _deepcopy_atomic\nd[str] = _deepcopy_atomic\n# try:\n# d[types.CodeType] = _deepcopy_atomic\n# except AttributeError:\n# pass\nd[type] = _deepcopy_atomic\n# d[types.BuiltinFunctionType] = _deepcopy_atomic\nd[types.FunctionType] = _deepcopy_atomic\n# d[weakref.ref] = _deepcopy_atomic\n\ndef _deepcopy_list(x, memo):\n y = []\n memo[id(x)] = y\n for a in x:\n y.append(deepcopy(a, memo))\n return y\nd[list] = _deepcopy_list\n\ndef _deepcopy_set(x, memo):\n result = set([]) # make empty set\n memo[id(x)] = result # register this set in the memo for loop checking\n for a in x: # go through elements of set\n result.add(deepcopy(a, memo)) # add the copied elements into the new set\n return result # return the new set\nd[set] = _deepcopy_set\n\ndef _deepcopy_tuple(x, memo):\n y = [deepcopy(a, memo) for a in x]\n # We're not going to put the tuple in the memo, but it's still important we\n # check for it, in case the tuple contains recursive mutable structures.\n try:\n return memo[id(x)]\n except KeyError:\n pass\n for k, j in zip(x, y):\n if k is not j:\n y = tuple(y)\n break\n else:\n y = x\n return y\nd[tuple] = _deepcopy_tuple\n\ndef _deepcopy_dict(x, memo):\n y = {}\n memo[id(x)] = y\n for key, value in x.items():\n y[deepcopy(key, memo)] = deepcopy(value, memo)\n return y\nd[dict] = _deepcopy_dict\n\ndef _deepcopy_method(x, memo): # Copy instance methods\n y = type(x)(x.im_func, deepcopy(x.im_self, memo), x.im_class);\n return y\nd[types.MethodType] = _deepcopy_method\n\ndef _deepcopy_inst(x, memo):\n if hasattr(x, '__deepcopy__'):\n return x.__deepcopy__(memo)\n if hasattr(x, '__getinitargs__'):\n args = x.__getinitargs__()\n args = deepcopy(args, memo)\n y = x.__class__(*args)\n else:\n y = _EmptyClass()\n y.__class__ = x.__class__\n memo[id(x)] = y\n if hasattr(x, '__getstate__'):\n state = x.__getstate__()\n else:\n state = x.__dict__\n state = deepcopy(state, memo)\n if hasattr(y, '__setstate__'):\n y.__setstate__(state)\n else:\n y.__dict__.update(state)\n return y\nd[\"InstanceType\"] = _deepcopy_inst\n\ndef _keep_alive(x, memo):\n \"\"\"Keeps a reference to the object x in the memo.\n Because we remember objects by their id, we have\n to assure that possibly temporary objects are kept\n alive by referencing them.\n We store a reference at the id of the memo, which should\n normally not be used unless someone tries to deepcopy\n the memo itself...\n \"\"\"\n try:\n memo[id(memo)].append(x)\n except KeyError:\n # aha, this is the first one :-)\n memo[id(memo)]=[x]\n\ndef _reconstruct(x, info, deep, memo=None):\n if isinstance(info, str):\n return x\n assert isinstance(info, tuple)\n if memo is None:\n memo = {}\n n = len(info)\n assert n in (2, 3, 4, 5)\n callable, args = info[:2]\n if n > 2:\n state = info[2]\n else:\n state = None\n if n > 3:\n listiter = info[3]\n else:\n listiter = None\n if n > 4:\n dictiter = info[4]\n else:\n dictiter = None\n if deep:\n args = deepcopy(args, memo)\n y = callable(*args)\n memo[id(x)] = y\n\n if state is not None:\n if deep:\n state = deepcopy(state, memo)\n if hasattr(y, '__setstate__'):\n y.__setstate__(state)\n else:\n if isinstance(state, tuple) and len(state) == 2:\n state, slotstate = state\n else:\n slotstate = None\n if state is not None:\n y.__dict__.update(state)\n if slotstate is not None:\n for key, value in slotstate.items():\n setattr(y, key, value)\n\n if listiter is not None:\n for item in listiter:\n if deep:\n item = deepcopy(item, memo)\n y.append(item)\n if dictiter is not None:\n for key, value in dictiter:\n if deep:\n key = deepcopy(key, memo)\n value = deepcopy(value, memo)\n y[key] = value\n return y\n\ndel d\n\ndel types\n\n# Helper for instance creation without calling __init__\nclass _EmptyClass:\n pass", "src/lib/genericpath.py": "raise NotImplementedError(\"genericpath is not yet implemented in Skulpt\")\n", "src/lib/linecache.py": "raise NotImplementedError(\"linecache is not yet implemented in Skulpt\")\n", "src/lib/audiodev.py": "raise NotImplementedError(\"audiodev is not yet implemented in Skulpt\")\n", "src/lib/types.py": "\"\"\"\nThis file was modified from CPython.\nCopyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,\n2011, 2012, 2013, 2014, 2015 Python Software Foundation; All Rights Reserved\n\"\"\"\n\"\"\"Define names for all type symbols known in the standard interpreter.\nTypes that are part of optional modules (e.g. array) are not listed.\n\"\"\"\nimport sys\n\n# Iterators in Python aren't a matter of type but of protocol. A large\n# and changing number of builtin types implement *some* flavor of\n# iterator. Don't check the type! Use hasattr to check for both\n# \"__iter__\" and \"next\" attributes instead.\n\nNoneType = type(None)\nTypeType = type\nObjectType = object\nIntType = int\nLongType = long\nFloatType = float\nBooleanType = bool\ntry:\n ComplexType = complex\nexcept NameError:\n pass\nStringType = str\n\n# StringTypes is already outdated. Instead of writing \"type(x) in\n# types.StringTypes\", you should use \"isinstance(x, basestring)\". But\n# we keep around for compatibility with Python 2.2.\ntry:\n UnicodeType = unicode\n StringTypes = (StringType, UnicodeType)\nexcept NameError:\n StringTypes = (StringType,)\n\nBufferType = buffer\n\nTupleType = tuple\nListType = list\nDictType = DictionaryType = dict\n\ndef _f(): pass\nFunctionType = type(_f)\nLambdaType = type(lambda: None) # Same as FunctionType\nCodeType = type(_f.func_code)\n\ndef _g():\n yield 1\nGeneratorType = type(_g())\n\nclass _C:\n def _m(self): pass\nClassType = type(_C)\nUnboundMethodType = type(_C._m) # Same as MethodType\n_x = _C()\nInstanceType = type(_x)\nMethodType = type(_x._m)\nBuiltinFunctionType = type(len)\nBuiltinMethodType = type([].append) # Same as BuiltinFunctionType\n\nModuleType = type(sys)\nFileType = file\nXRangeType = xrange\n\n# try:\n# raise TypeError\n# except TypeError:\n# tb = sys.exc_info()[2]\n# TracebackType = type(tb)\n# FrameType = type(tb.tb_frame)\n# del tb\n\nSliceType = slice\n# EllipsisType = type(Ellipsis)\n\n# DictProxyType = type(TypeType.__dict__)\nNotImplementedType = type(NotImplemented)\n\n# For Jython, the following two types are identical\n# GetSetDescriptorType = type(FunctionType.func_code)\n# MemberDescriptorType = type(FunctionType.func_globals)\n\ndel sys, _f, _g, _C, _x # Not for export\n__all__ = list(n for n in globals() if n[:1] != '_')\n", "src/lib/cory.py": "alpha = 0", "src/lib/sre.py": "raise NotImplementedError(\"sre is not yet implemented in Skulpt\")\n", "src/lib/mimetypes.py": "raise NotImplementedError(\"mimetypes is not yet implemented in Skulpt\")\n", "src/lib/xdrlib.py": "raise NotImplementedError(\"xdrlib is not yet implemented in Skulpt\")\n", "src/lib/colorsys.py": "raise NotImplementedError(\"colorsys is not yet implemented in Skulpt\")\n", "src/lib/UserList.py": "raise NotImplementedError(\"UserList is not yet implemented in Skulpt\")\n", "src/lib/numbers.py": "raise NotImplementedError(\"numbers is not yet implemented in Skulpt\")\n", "src/lib/_strptime.py": "raise NotImplementedError(\"_strptime is not yet implemented in Skulpt\")\n", "src/lib/_abcoll.py": "raise NotImplementedError(\"_abcoll is not yet implemented in Skulpt\")\n", "src/lib/dummy_threading.py": "raise NotImplementedError(\"dummy_threading is not yet implemented in Skulpt\")\n", "src/lib/anydbm.py": "raise NotImplementedError(\"anydbm is not yet implemented in Skulpt\")\n", "src/lib/ftplib.py": "raise NotImplementedError(\"ftplib is not yet implemented in Skulpt\")\n", "src/lib/chunk.py": "raise NotImplementedError(\"chunk is not yet implemented in Skulpt\")\n", "src/lib/mimify.py": "raise NotImplementedError(\"mimify is not yet implemented in Skulpt\")\n", "src/lib/optparse.py": "raise NotImplementedError(\"optparse is not yet implemented in Skulpt\")\n", "src/lib/pdb.py": "raise NotImplementedError(\"pdb is not yet implemented in Skulpt\")\n", "src/lib/repr.py": "raise NotImplementedError(\"repr is not yet implemented in Skulpt\")\n", "src/lib/Cookie.py": "raise NotImplementedError(\"Cookie is not yet implemented in Skulpt\")\n", "src/lib/threading.py": "raise NotImplementedError(\"threading is not yet implemented in Skulpt\")\n", "src/lib/platform.py": "raise NotImplementedError(\"platform is not yet implemented in Skulpt\")\n", "src/lib/pstats.py": "raise NotImplementedError(\"pstats is not yet implemented in Skulpt\")\n", "src/lib/glob.py": "raise NotImplementedError(\"glob is not yet implemented in Skulpt\")\n", "src/lib/urlparse.py": "raise NotImplementedError(\"urlparse is not yet implemented in Skulpt\")\n", "src/lib/copy_reg.py": "raise NotImplementedError(\"copy_reg is not yet implemented in Skulpt\")\n", "src/lib/quopri.py": "raise NotImplementedError(\"quopri is not yet implemented in Skulpt\")\n", "src/lib/symtable.py": "raise NotImplementedError(\"symtable is not yet implemented in Skulpt\")\n", "src/lib/fpformat.py": "raise NotImplementedError(\"fpformat is not yet implemented in Skulpt\")\n", "src/lib/pprint.py": "import json\n\ndef pprint(obj, indent=1):\n print(json.dumps(obj))", "src/lib/_MozillaCookieJar.py": "raise NotImplementedError(\"_MozillaCookieJar is not yet implemented in Skulpt\")\n", "src/lib/calendar.py": "raise NotImplementedError(\"calendar is not yet implemented in Skulpt\")\n", "src/lib/inspect.py": "raise NotImplementedError(\"inspect is not yet implemented in Skulpt\")\n", "src/lib/poplib.py": "raise NotImplementedError(\"poplib is not yet implemented in Skulpt\")\n", "src/lib/binhex.py": "raise NotImplementedError(\"binhex is not yet implemented in Skulpt\")\n", "src/lib/plistlib.py": "raise NotImplementedError(\"plistlib is not yet implemented in Skulpt\")\n", "src/lib/pickletools.py": "raise NotImplementedError(\"pickletools is not yet implemented in Skulpt\")\n", "src/lib/pipes.py": "raise NotImplementedError(\"pipes is not yet implemented in Skulpt\")\n", "src/lib/site.py": "raise NotImplementedError(\"site is not yet implemented in Skulpt\")\n", "src/lib/string.js": "/*\n * __author__: Isaac Dontje Lindell (i@isaacdontjelindell.com)\n *\n * Implementation of the Python string module.\n */\n\n\nvar $builtinmodule = function (name) {\n var mod = {};\n\n mod.ascii_lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.ascii_uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.ascii_letters = Sk.builtin.str(mod.ascii_lowercase.v + mod.ascii_uppercase.v);\n\n mod.lowercase = Sk.builtin.str('abcdefghijklmnopqrstuvwxyz');\n mod.uppercase = Sk.builtin.str('ABCDEFGHIJKLMNOPQRSTUVWXYZ');\n mod.letters = Sk.builtin.str(mod.lowercase.v + mod.uppercase.v);\n\n mod.digits = Sk.builtin.str('0123456789', Sk.builtin.str);\n mod.hexdigits = Sk.builtin.str('0123456789abcdefABCDEF');\n mod.octdigits = Sk.builtin.str('01234567');\n\n mod.punctuation = Sk.builtin.str('!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~');\n mod.whitespace = Sk.builtin.str('\\t\\n\\x0b\\x0c\\r ');\n\n /* Note: The docs for string.printable say that it's the concatenation of string.digits,\n * string.letters, string.punctuation, and string.whitespace. The CPython interpreter\n * outputs the whitespace characters in one order when string.whitespace is used, and a\n * slightly different order when string.printable is used. I've elected to follow the\n * behavior of CPython here rather than the spec. */\n mod.printable = Sk.builtin.str(mod.digits.v + mod.letters.v + mod.punctuation.v + \" \\t\\n\\r\\x0b\\x0c\");\n\n\n mod.split = new Sk.builtin.func(function (s, sep, maxsplit) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['split'], s, sep, maxsplit);\n });\n\n /* Return a copy of word with only its first character capitalized. */\n mod.capitalize = new Sk.builtin.func(function (word) {\n return Sk.misceval.callsim(Sk.builtin.str.prototype['capitalize'], word);\n });\n\n /* Concatenate a list or tuple of words with intervening occurrences\n * of sep. The default value for sep is a single space character. */\n mod.join = new Sk.builtin.func(function (words, sep) {\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n return Sk.misceval.callsim(Sk.builtin.str.prototype['join'], sep, words);\n });\n\n\n /* Split the argument into words using split(), capitalize each word\n * using capitalize(), and join the capitalized words using join().\n * Note that this replaces runs of whitespace characters by a single\n * space, and removes leading and trailing whitespace. */\n mod.capwords = new Sk.builtin.func(function (s, sep) {\n Sk.builtin.pyCheckArgs('capwords', arguments, 1, 2);\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"s must be a string\");\n }\n if (sep === undefined) {\n sep = Sk.builtin.str(' ');\n }\n if (!Sk.builtin.checkString(sep)) {\n throw new Sk.builtin.TypeError(\"sep must be a string\");\n }\n\n var words = Sk.misceval.callsim(mod.split, s, sep);\n var capWords = [];\n for (var i = 0; i < words.v.length; i++) {\n var word = Sk.builtin.list.prototype['list_subscript_'].call(words, i);\n var cap = Sk.misceval.callsim(mod.capitalize, word);\n capWords.push(cap);\n }\n\n return Sk.misceval.callsim(mod.join, new Sk.builtin.list(capWords), sep);\n });\n\n\n return mod;\n};\n", "src/lib/telnetlib.py": "raise NotImplementedError(\"telnetlib is not yet implemented in Skulpt\")\n", "src/lib/_LWPCookieJar.py": "raise NotImplementedError(\"_LWPCookieJar is not yet implemented in Skulpt\")\n", "src/lib/processing.js": "/*\n Skulpt Processing\n\n Testing/debugging:\n\n ProcessingJS from Skulpt:\n Sk.misceval.callsim(Sk.globals.processing.$d.PShapeSVG, \n new Sk.builtin.str(\"string\"), \n new Sk.builtin.str(\"bot1.svg\"))\n\n ProcessingJS direct:\n p = Processing.instances[0]\n p.PShapeSVG(\"string\", \"bot1.svg\")\n*/\n\nvar $builtinmodule = function (name) {\n var imageClass;\n var colorClass;\n var screenClass;\n var environmentClass;\n var keyboardClass;\n var mouseClass;\n var vectorClass\n\n var mod = {};\n var imList = [];\n var looping = true;\n var instance = null;\n\n // We need this to store a reference to the actual processing object which is not created\n // until the run function is called. Even then the processing object is passed by the\n // processing-js sytem as a parameter to the sketchProc function. Why not set it to None here\n //\n\n // See: http://processingjs.org/reference/\n\n mod.processing = null;\n mod.p = null;\n\n mod.X = new Sk.builtin.int_(0);\n mod.Y = new Sk.builtin.int_(1);\n mod.Z = new Sk.builtin.int_(2);\n\n mod.R = new Sk.builtin.int_( 3);\n mod.G = new Sk.builtin.int_( 4);\n mod.B = new Sk.builtin.int_( 5);\n mod.A = new Sk.builtin.int_( 6);\n \n mod.U = new Sk.builtin.int_( 7);\n mod.V = new Sk.builtin.int_( 8);\n \n mod.NX = new Sk.builtin.int_( 9);\n mod.NY = new Sk.builtin.int_( 10);\n mod.NZ = new Sk.builtin.int_( 11);\n \n mod.EDGE = new Sk.builtin.int_( 12);\n \n // Stroke\n mod.SR = new Sk.builtin.int_( 13);\n mod.SG = new Sk.builtin.int_( 14);\n mod.SB = new Sk.builtin.int_( 15);\n mod.SA = new Sk.builtin.int_( 16);\n \n mod.SW = new Sk.builtin.int_( 17);\n \n // Transformations (2D and 3D)\n mod.TX = new Sk.builtin.int_( 18);\n mod.TY = new Sk.builtin.int_( 19);\n mod.TZ = new Sk.builtin.int_( 20);\n \n mod.VX = new Sk.builtin.int_( 21);\n mod.VY = new Sk.builtin.int_( 22);\n mod.VZ = new Sk.builtin.int_( 23);\n mod.VW = new Sk.builtin.int_( 24);\n \n // Material properties\n mod.AR = new Sk.builtin.int_( 25);\n mod.AG = new Sk.builtin.int_( 26);\n mod.AB = new Sk.builtin.int_( 27);\n \n mod.DR = new Sk.builtin.int_( 3);\n mod.DG = new Sk.builtin.int_( 4);\n mod.DB = new Sk.builtin.int_( 5);\n mod.DA = new Sk.builtin.int_( 6);\n \n mod.SPR = new Sk.builtin.int_( 28);\n mod.SPG = new Sk.builtin.int_( 29);\n mod.SPB = new Sk.builtin.int_( 30);\n \n mod.SHINE = new Sk.builtin.int_( 31);\n \n mod.ER = new Sk.builtin.int_( 32);\n mod.EG = new Sk.builtin.int_( 33);\n mod.EB = new Sk.builtin.int_( 34);\n \n mod.BEEN_LIT = new Sk.builtin.int_( 35);\n \n mod.VERTEX_FIELD_COUNT = new Sk.builtin.int_( 36);\n \n // Shape drawing modes\n mod.CENTER = new Sk.builtin.int_(3);\n mod.RADIUS = new Sk.builtin.int_(2);\n mod.CORNERS = new Sk.builtin.int_(1);\n mod.CORNER = new Sk.builtin.int_(0);\n mod.DIAMETER = new Sk.builtin.int_(3);\n \n // Text vertical alignment modes\n // Default vertical alignment for text placement\n mod.BASELINE = new Sk.builtin.int_( 0);\n // Align text to the top\n mod.TOP = new Sk.builtin.int_( 101);\n // Align text from the bottom, using the baseline\n mod.BOTTOM = new Sk.builtin.int_( 102);\n \n // UV Texture coordinate modes\n mod.NORMAL = new Sk.builtin.int_( 1);\n mod.NORMALIZED = new Sk.builtin.int_( 1);\n mod.IMAGE = new Sk.builtin.int_( 2);\n \n // Text placement modes\n mod.MODEL = new Sk.builtin.int_( 4);\n mod.SHAPE = new Sk.builtin.int_( 5);\n \n // Lighting modes\n mod.AMBIENT = new Sk.builtin.int_( 0);\n mod.DIRECTIONAL = new Sk.builtin.int_( 1);\n //POINT: 2, Shared with Shape constant\n mod.SPOT = new Sk.builtin.int_( 3);\n\n // Color modes\n mod.RGB = new Sk.builtin.int_(1);\n mod.ARGB = new Sk.builtin.int_(2);\n mod.HSB = new Sk.builtin.int_(3);\n mod.ALPHA = new Sk.builtin.int_(4);\n mod.CMYK = new Sk.builtin.int_(5);\n \n // Image file types\n mod.TIFF = new Sk.builtin.int_(0);\n mod.TARGA = new Sk.builtin.int_(1);\n mod.JPEG = new Sk.builtin.int_(2);\n mod.GIF = new Sk.builtin.int_(3);\n\n // Stroke modes\n mod.MITER = new Sk.builtin.str(\"miter\");\n mod.BEVEL = new Sk.builtin.str(\"bevel\");\n mod.ROUND = new Sk.builtin.str(\"round\");\n mod.SQUARE = new Sk.builtin.str(\"butt\");\n mod.PROJECT = new Sk.builtin.str(\"square\");\n\n // Renderer modes\n mod.P2D = new Sk.builtin.int_(1);\n mod.JAVA2D = new Sk.builtin.int_(1);\n mod.WEBGL = new Sk.builtin.int_(2);\n mod.P3D = new Sk.builtin.int_(2);\n mod.OPENGL = new Sk.builtin.int_(2);\n mod.PDF = new Sk.builtin.int_(0);\n mod.DXF = new Sk.builtin.int_(0);\n\n // Platform IDs\n mod.OTHER = new Sk.builtin.int_( 0);\n mod.WINDOWS = new Sk.builtin.int_( 1);\n mod.MAXOSX = new Sk.builtin.int_( 2);\n mod.LINUX = new Sk.builtin.int_( 3);\n \n mod.EPSILON = new Sk.builtin.float_( 0.0001);\n\n mod.MAX_FLOAT = new Sk.builtin.float_( 3.4028235e+38);\n mod.MIN_FLOAT = new Sk.builtin.float_( -3.4028235e+38);\n mod.MAX_INT = new Sk.builtin.int_( 2147483647);\n mod.MIN_INT = new Sk.builtin.int_( -2147483648);\n \n // Constants\n mod.HALF_PI = new Sk.builtin.float_(Math.PI / 2.0);\n mod.THIRD_PI = new Sk.builtin.float_(Math.PI / 3.0);\n mod.PI = new Sk.builtin.float_(Math.PI);\n mod.TWO_PI = new Sk.builtin.float_(Math.PI * 2.0);\n mod.TAU = new Sk.builtin.float_(Math.PI * 2.0);\n mod.QUARTER_PI = new Sk.builtin.float_(Math.PI / 4.0);\n\n mod.DEG_TO_RAD = new Sk.builtin.float_( Math.PI / 180);\n mod.RAD_TO_DEG = new Sk.builtin.float_( 180 / Math.PI);\n\n mod.WHITESPACE = Sk.builtin.str(\" \\t\\n\\r\\f\\u00A0\");\n // Shape modes\n mod.POINT = new Sk.builtin.int_(2);\n mod.POINTS = new Sk.builtin.int_(2);\n mod.LINE = new Sk.builtin.int_(4);\n mod.LINES = new Sk.builtin.int_(4);\n mod.TRIANGLE = new Sk.builtin.int_(8);\n mod.TRIANGLES = new Sk.builtin.int_(9);\n mod.TRIANGLE_FAN = new Sk.builtin.int_(11);\n mod.TRIANGLE_STRIP = new Sk.builtin.int_(10);\n mod.QUAD = new Sk.builtin.int_(16);\n mod.QUADS = new Sk.builtin.int_(16);\n mod.QUAD_STRIP = new Sk.builtin.int_(17);\n mod.POLYGON = new Sk.builtin.int_(20);\n\n mod.PATH = new Sk.builtin.int_(21);\n mod.RECT = new Sk.builtin.int_(30);\n mod.ELLIPSE = new Sk.builtin.int_(31);\n mod.ARC = new Sk.builtin.int_(32);\n mod.SPHERE = new Sk.builtin.int_(40);\n mod.BOX = new Sk.builtin.int_(41);\n\n mod.GROUP = new Sk.builtin.int_( 0);\n mod.PRIMITIVE = new Sk.builtin.int_( 1);\n //PATH: 21, // shared with Shape PATH\n mod.GEOMETRY = new Sk.builtin.int_( 3);\n \n // Shape Vertex\n mod.VERTEX = new Sk.builtin.int_( 0);\n mod.BEZIER_VERTEX = new Sk.builtin.int_( 1);\n mod.CURVE_VERTEX = new Sk.builtin.int_( 2);\n mod.BREAK = new Sk.builtin.int_( 3);\n mod.CLOSESHAPE = new Sk.builtin.int_( 4);\n \n // Blend modes\n mod.REPLACE = new Sk.builtin.int_(0);\n mod.BLEND = new Sk.builtin.int_(1 << 0);\n mod.ADD = new Sk.builtin.int_(1 << 1);\n mod.SUBTRACT = new Sk.builtin.int_(1 << 2);\n mod.LIGHTEST = new Sk.builtin.int_(1 << 3);\n mod.DARKEST = new Sk.builtin.int_(1 << 4);\n mod.DIFFERENCE = new Sk.builtin.int_(1 << 5);\n mod.EXCLUSION = new Sk.builtin.int_(1 << 6);\n mod.MULTIPLY = new Sk.builtin.int_(1 << 7);\n mod.SCREEN = new Sk.builtin.int_(1 << 8);\n mod.OVERLAY = new Sk.builtin.int_(1 << 9);\n mod.HARD_LIGHT = new Sk.builtin.int_(1 << 10);\n mod.SOFT_LIGHT = new Sk.builtin.int_(1 << 11);\n mod.DODGE = new Sk.builtin.int_(1 << 12);\n mod.BURN = new Sk.builtin.int_(1 << 13);\n\n // Color component bit masks\n mod.ALPHA_MASK = new Sk.builtin.int_( 0xff000000);\n mod.RED_MASK = new Sk.builtin.int_( 0x00ff0000);\n mod.GREEN_MASK = new Sk.builtin.int_( 0x0000ff00);\n mod.BLUE_MASK = new Sk.builtin.int_( 0x000000ff);\n \n // Projection matrices\n mod.CUSTOM = new Sk.builtin.int_( 0);\n mod.ORTHOGRAPHIC = new Sk.builtin.int_( 2);\n mod.PERSPECTIVE = new Sk.builtin.int_( 3);\n \n // Cursors\n mod.ARROW = new Sk.builtin.str(\"default\");\n mod.CROSS = new Sk.builtin.str(\"crosshair\");\n mod.HAND = new Sk.builtin.str(\"pointer\");\n mod.MOVE = new Sk.builtin.str(\"move\");\n mod.TEXT = new Sk.builtin.str(\"text\");\n mod.WAIT = new Sk.builtin.str(\"wait\");\n mod.NOCURSOR = Sk.builtin.assk$(\"url('data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='), auto\", Sk.builtin.nmber.str);\n\n // Hints\n mod.DISABLE_OPENGL_2X_SMOOTH = new Sk.builtin.int_(1);\n mod.ENABLE_OPENGL_2X_SMOOTH = new Sk.builtin.int_(-1);\n mod.ENABLE_OPENGL_4X_SMOOTH = new Sk.builtin.int_(2);\n mod.ENABLE_NATIVE_FONTS = new Sk.builtin.int_(3);\n mod.DISABLE_DEPTH_TEST = new Sk.builtin.int_(4);\n mod.ENABLE_DEPTH_TEST = new Sk.builtin.int_(-4);\n mod.ENABLE_DEPTH_SORT = new Sk.builtin.int_(5);\n mod.DISABLE_DEPTH_SORT = new Sk.builtin.int_(-5);\n mod.DISABLE_OPENGL_ERROR_REPORT = new Sk.builtin.int_(6);\n mod.ENABLE_OPENGL_ERROR_REPORT = new Sk.builtin.int_(-6);\n mod.ENABLE_ACCURATE_TEXTURES = new Sk.builtin.int_(7);\n mod.DISABLE_ACCURATE_TEXTURES = new Sk.builtin.int_(-7);\n mod.HINT_COUNT = new Sk.builtin.int_(10);\n\n // Shape closing modes\n mod.OPEN = new Sk.builtin.int_(1);\n mod.CLOSE = new Sk.builtin.int_(2);\n\n // Filter/convert types\n mod.BLUR = new Sk.builtin.int_(11);\n mod.GRAY = new Sk.builtin.int_(12);\n mod.INVERT = new Sk.builtin.int_(13);\n mod.OPAQUE = new Sk.builtin.int_(14);\n mod.POSTERIZE = new Sk.builtin.int_(15);\n mod.THRESHOLD = new Sk.builtin.int_(16);\n mod.ERODE = new Sk.builtin.int_(17);\n mod.DILATE = new Sk.builtin.int_(18);\n\n // Both key and keyCode will be equal to these values\n mod.BACKSPACE = new Sk.builtin.int_( 8);\n mod.TAB = new Sk.builtin.int_(9);\n mod.ENTER = new Sk.builtin.int_(10);\n mod.RETURN = new Sk.builtin.int_(13);\n mod.ESC = new Sk.builtin.int_(27);\n mod.DELETE = new Sk.builtin.int_(127);\n mod.CODED = new Sk.builtin.int_(0xffff);\n\n // p.key will be CODED and p.keyCode will be this value\n mod.SHIFT = new Sk.builtin.int_(16);\n mod.CONTROL = new Sk.builtin.int_(17);\n mod.ALT = new Sk.builtin.int_(18);\n mod.CAPSLK = new Sk.builtin.int_(20);\n mod.PGUP = new Sk.builtin.int_(33);\n mod.PGDN = new Sk.builtin.int_(34);\n mod.END = new Sk.builtin.int_(35);\n mod.HOME = new Sk.builtin.int_(36);\n mod.LEFT = new Sk.builtin.int_(37);\n mod.UP = new Sk.builtin.int_(38);\n mod.RIGHT = new Sk.builtin.int_(39);\n mod.DOWN = new Sk.builtin.int_(40);\n mod.F1 = new Sk.builtin.int_(112);\n mod.F2 = new Sk.builtin.int_(113);\n mod.F3 = new Sk.builtin.int_(114);\n mod.F4 = new Sk.builtin.int_(115);\n mod.F5 = new Sk.builtin.int_(116);\n mod.F6 = new Sk.builtin.int_(117);\n mod.F7 = new Sk.builtin.int_(118);\n mod.F8 = new Sk.builtin.int_(119);\n mod.F9 = new Sk.builtin.int_(120);\n mod.F10 = new Sk.builtin.int_(121);\n mod.F11 = new Sk.builtin.int_(122);\n mod.F12 = new Sk.builtin.int_(123);\n mod.NUMLK = new Sk.builtin.int_(144);\n mod.META = new Sk.builtin.int_(157);\n mod.INSERT = new Sk.builtin.int_(155);\n\n // PJS defined constants\n mod.SINCOS_LENGTH = new Sk.builtin.int_(720);\n mod.PRECISIONB = new Sk.builtin.int_(15);\n mod.PRECISIONF = new Sk.builtin.int_(1 << 15);\n mod.PREC_MAXVAL = new Sk.builtin.int_((1 << 15) - 1);\n mod.PREC_ALPHA_SHIFT = new Sk.builtin.int_(24 - 15);\n mod.PREC_RED_SHIFT = new Sk.builtin.int_(16 - 15);\n mod.NORMAL_MODE_AUTO = new Sk.builtin.int_(0);\n mod.NORMAL_MODE_SHAPE = new Sk.builtin.int_(1);\n mod.NORMAL_MODE_VERTEX = new Sk.builtin.int_(2);\n mod.MAX_LIGHTS = new Sk.builtin.int_(8);\n\n // 2D - Primitives\n mod.line = new Sk.builtin.func(function (x1, y1, x2, y2) {\n mod.processing.line(x1.v, y1.v, x2.v, y2.v);\n });\n\n mod.ellipse = new Sk.builtin.func(function (x, y, r1, r2) {\n mod.processing.ellipse(x.v, y.v, r1.v, r2.v);\n\n });\n\n mod.text = new Sk.builtin.func(function (theText, x, y) {\n mod.processing.text(theText.v, x.v, y.v);\n });\n\n mod.point = new Sk.builtin.func(function (x1, y1) {\n mod.processing.point(x1.v, y1.v);\n });\n\n mod.arc = new Sk.builtin.func(function (x, y, width, height, start, stop) {\n mod.processing.arc(x.v, y.v, width.v, height.v, start.v, stop.v);\n });\n\n mod.quad = new Sk.builtin.func(function (x1, y1, x2, y2, x3, y3, x4, y4) {\n mod.processing.quad(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v, x4.v, y4.v);\n });\n\n mod.rect = new Sk.builtin.func(function (x, y, width, height, radius) {\n var rad;\n if (typeof(radius) === \"undefined\") {\n mod.processing.rect(x.v, y.v, width.v, height.v);\n } else {\n mod.processing.rect(x.v, y.v, width.v, height.v, radius.v);\n }\n });\n\n mod.triangle = new Sk.builtin.func(function (x1, y1, x2, y2, x3, y3) {\n mod.processing.triangle(x1.v, y1.v, x2.v, y2.v, x3.v, y3.v);\n });\n\n mod.bezier = new Sk.builtin.func(function (x1, y1, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {\n if (typeof(a7) === \"undefined\") {\n\t // bezier(x1, y1, cx1, cy1, cx2, cy2, x2, y2);\n mod.processing.bezier(x1.v, y1.v, a1.v, a2.v, a3.v, a4.v, a5.v, a6.v);\n\t} else {\n\t // bezier(x1, y1, z1, cx1, cy1, cz1, cx2, cy2, cz2, x2, y2, z2);\n mod.processing.bezier(x1.v, y1.v, a1.v, a2.v, a3.v, a4.v, a5.v, a6.v, a7.v, a8.v, a9.v, a10.v);\n\t}\n });\n\n mod.alpha = new Sk.builtin.func(function (r, g, b) {\n // r will be either:\n // a number in which case the fill will be grayscale\n // a color object\n // g, and b may be undefined. If they hold values it will\n // be assumed that we have an r,g,b color tuple\n if (typeof(g) === \"undefined\") {\n return new Sk.builtin.float_(mod.processing.alpha(r.v));\n } else if (typeof(b) === \"undefined\") {\n return new Sk.builtin.float_(mod.processing.alpha(r.v, g.v));\n } else {\n return new Sk.builtin.float_(mod.processing.alpha(r.v, g.v, b.v));\n\t}\n });\n\n mod.ambient = new Sk.builtin.func(function (r, g, b) {\n\t// ambient(gray)\n\t// ambient(red, green blue)\n // r will be either:\n // a number in which case the fill will be grayscale\n // a color object\n // g, and b may be undefined. If they hold values it will\n // be assumed that we have an r,g,b color tuple\n if (typeof(g) === \"undefined\") {\n mod.processing.ambient(r.v);\n } else if (typeof(b) === \"undefined\") {\n mod.processing.ambient(r.v, g.v);\n } else {\n mod.processing.ambient(r.v, g.v, b.v);\n\t}\n });\n\n mod.ambientLight = new Sk.builtin.func(function (v1, v2, v3, x, y, z) {\n\t// ambientLight(v1,v2,v3)\n\t// ambientLight(v1,v2,v3,x,y,z)\n if (typeof(x) === \"undefined\") {\n mod.processing.ambientLight(v1.v, v2.v, v3.v);\n } else if (typeof(y) === \"undefined\") {\n mod.processing.ambientLight(v1.v, v2.v, v3.v, x.v);\n } else if (typeof(z) === \"undefined\") {\n mod.processing.ambientLight(v1.v, v2.v, v3.v, x.v, y.v);\n } else {\n mod.processing.ambientLight(v1.v, v2.v, v3.v, x.v, y.v, z.v);\n\t}\n });\n\n mod.beginCamera = new Sk.builtin.func(function () {\n\tmod.processing.beginCamera();\n });\n\n mod.beginShape = new Sk.builtin.func(function (mode) {\n if (typeof(mode) === \"undefined\") {\n mode = mod.POLYGON;\n }\n mod.processing.beginShape(mode.v);\n });\n\n mod.bezierDetail = new Sk.builtin.func(function (resolution) {\n\t// Sets the resolution at which Beziers display. The default\n\t// value is 20. This function is only useful when using the\n\t// P3D or OPENGL renderer as the default (JAVA2D) renderer\n\t// does not use this information.\n if (typeof(resolution) !== \"undefined\") {\n resolution = resolution.v;\n } else {\n resolution = 20;\n\t}\n mod.processing.bezierDetail(resolution);\n });\n\n mod.bezierPoint = new Sk.builtin.func(function (a,b,c,d,t) {\n mod.processing.bezierPoint(a.v,b.v,c.v,d.v,t.v);\n });\n\n mod.bezierTangent = new Sk.builtin.func(function (a,b,c,d,t) {\n\tmod.processing.bezierTangent(a.v,b.v,c.v,d.v,t.v);\n });\n\n mod.bezierVertex = new Sk.builtin.func(function (v1, v2, v3, v4, v5, v6,\n\t\t\t\t\t\t v7, v8, v9) {\n\t// bezierVertex(cx1, cy1, cx2, cy2, x, y)\n\t// bezierVertex(cx1, cy1, cz1, cx2, cy2, cz2, x, y, z)\n if (typeof(v7) === \"undefined\") {\n\t mod.processing.bezierVertex(v1.v, v2.v, v3.v, v4.v, v5.v, v6.v);\n\t} else if (typeof(v8) === \"undefined\") {\n\t mod.processing.bezierVertex(v1.v, v2.v, v3.v, v4.v, v5.v, v6.v,\n\t\t\t\t\tv7.v);\n\t} else if (typeof(v9) === \"undefined\") {\n\t mod.processing.bezierVertex(v1.v, v2.v, v3.v, v4.v, v5.v, v6.v,\n\t\t\t\t\tv7.v, v8.v);\n\t} else {\n\t mod.processing.bezierVertex(v1.v, v2.v, v3.v, v4.v, v5.v, v6.v,\n\t\t\t\t\tv7.v, v8.v, v9.v);\n\t}\n });\n\n mod.blend = new Sk.builtin.func(function (v1, v2, v3, v4, v5,\n\t\t\t\t\t v6, v7, v8, v9, v10) {\n\tif (other instanceof Sk.builtin.int_ || other instanceof Sk.builtin.float_) {\n\t // blend(x, y,width,height,dx, dy,dwidth,dheight,MODE)\n\t mod.processing.blend(v1.v, v2.v, v3.v, v4.v, v5.v,\n\t\t\t\t v6.v, v7.v, v8.v, v9.v);\n\t} else {\n\t // blend(srcImg,x,y, width, height,dx,dy, dwidth, dheight,MODE)\n\t mod.processing.blend(v1.v, v2.v, v3.v, v4.v, v5.v,\n\t\t\t\t v6.v, v7.v, v8.v, v9.v, v10.v);\n\t}\n });\n\n mod.blendColor = new Sk.builtin.func(function (c1, c2, mode) {\n\t// blendColor(c1,c2,MODE)\n var c = Sk.misceval.callsim(mod.color,\n\t\t\t\t new Sk.builtin.int_(0),\n\t\t\t\t new Sk.builtin.int_(0),\n\t\t\t\t new Sk.builtin.int_(0));\n\tc.v = mod.processing.blendColor(c1.v, c2.v, mode.v);\n\treturn c;\n });\n\n mod.brightness = new Sk.builtin.func(function (r, g, b) {\n if (typeof(g) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.brightness(r.v));\n } else if (typeof(b) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.brightness(r.v, g.v));\n } else {\n\t return new Sk.builtin.float_(mod.processing.brightness(r.v, g.v, b.v));\n\t}\n });\n\n mod.camera = new Sk.builtin.func(function (eyeX, eyeY, eyeZ,\n\t\t\t\t\t centerX, centerY, centerZ,\n\t\t\t\t\t upX, upY, upZ) {\n\t// camera()\n\t// camera(eyeX, eyeY, eyeZ,centerX, centerY, centerZ,upX, upY, upZ)\n if (typeof(eyeX) === \"undefined\") {\n\t mod.processing.camera();\n\t} else {\n\t mod.processing.camera(eyeX.v, eyeY.v, eyeZ.v,\n\t\t\t\t centerX.v, centerY.v, centerZ.v,\n\t\t\t\t upX.v, upY.v, upZ.v);\n\t}\n });\n\n mod.constrain = new Sk.builtin.func(function (value, min, max) {\n\treturn new Sk.builtin.float_(mod.processing.constrain(value.v, min.v, max.v));\n });\n\n mod.copy = new Sk.builtin.func(function (v1, v2, v3, v4, v5,\n\t\t\t\t\t v6, v7, v8, v9) {\n\tif (other instanceof Sk.builtin.int_ || other instanceof Sk.builtin.float_) {\n\t // copy(x, y,width,height,dx, dy,dwidth,dheight)\n\t mod.processing.copy(v1.v, v2.v, v3.v, v4.v, v5.v,\n\t\t\t\tv6.v, v7.v, v8.v);\n\t} else {\n\t // copy(srcImg,x,y, width, height,dx,dy, dwidth, dheight)\n\t mod.processing.copy(v1.v, v2.v, v3.v, v4.v, v5.v,\n\t\t\t\tv6.v, v7.v, v8.v, v9.v);\n\t}\n });\n\n mod.createFont = new Sk.builtin.func(function (name, size, smooth, charset) {\n\t// createFont(name, size)\n\t// createFont(name, size, smooth)\n\t// createFont(name, size, smooth, charset)\n\tvar font = Sk.misceval.callsim(mod.PFont);\n if (typeof(smooth) === \"undefined\") {\n\t font.v = mod.processing.createFont(name.v, size.v);\n\t} else if (typeof(charset) === \"undefined\") {\n\t font.v = mod.processing.createFont(name.v, size.v, smooth.v);\n\t} else {\n\t font.v = mod.processing.createFont(name.v, size.v, smooth.v, charset.v);\n\t}\n\treturn font;\n });\n\n mod.createGraphics = new Sk.builtin.func(function (width, height, renderer, filename) {\n\t// createGraphics(width, height, renderer)\n\t// createGraphics(width, height, renderer, filename)\n\tvar graphics = Sk.misceval.callsim(mod.PGraphics);\n if (typeof(filename) === \"undefined\") {\n\t graphics.v = mod.processing.createGraphics(width.v, height.v, renderer.v);\n\t} else {\n\t graphics.v = mod.processing.createGraphics(width.v, height.v, renderer.v, filename.v);\n\t}\n\treturn graphics;\n });\n\n mod.createImage = new Sk.builtin.func(function (width, height, format) {\n\tvar image = Sk.misceval.callsim(mod.PImage);\n\timage.v = mod.processing.createImage(width.v, height.v, format.v);\n\treturn image;\n });\n\n mod.cursor = new Sk.builtin.func(function (v, x, y) {\n\t// cursor()\n\t// cursor(MODE)\n\t// cursor(image,x,y)\n if (typeof(v) === \"undefined\") {\n\t mod.processing.cursor();\n\t} else if (typeof(x) === \"undefined\") {\n\t mod.processing.cursor(v.v);\n\t} else if (typeof(y) === \"undefined\") {\n\t mod.processing.cursor(v.v, x.v);\n\t} else {\n\t mod.processing.cursor(v.v, x.v, y.v);\n\t}\n });\n\n mod.curve = new Sk.builtin.func(function (v1, v2, v3, v4,\n\t\t\t\t\t v5, v6, v7, v8,\n\t\t\t\t\t v9, v10, v11, v12) {\n\t// curve(x1, y1, x2, y2, x3, y3, x4, y4);\n\t// curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);\n if (typeof(v9) === \"undefined\") {\n\t mod.processing.curve(v1.v, v2.v, v3.v, v4.v,\n\t\t\t\t v5.v, v6.v, v7.v, v8.v);\n\t} else if (typeof(v10) === \"undefined\") {\n\t mod.processing.curve(v1.v, v2.v, v3.v, v4.v,\n\t\t\t\t v5.v, v6.v, v7.v, v8.v,\n\t\t\t\t v9.v);\n\t} else if (typeof(v11) === \"undefined\") {\n\t mod.processing.curve(v1.v, v2.v, v3.v, v4.v,\n\t\t\t\t v5.v, v6.v, v7.v, v8.v,\n\t\t\t\t v9.v, v10.v);\n\t} else if (typeof(v12) === \"undefined\") {\n\t mod.processing.curve(v1.v, v2.v, v3.v, v4.v,\n\t\t\t\t v5.v, v6.v, v7.v, v8.v,\n\t\t\t\t v9.v, v10.v, v11.v);\n\t} else {\n\t mod.processing.curve(v1.v, v2.v, v3.v, v4.v,\n\t\t\t\t v5.v, v6.v, v7.v, v8.v,\n\t\t\t\t v9.v, v10.v, v11.v, v12.v);\n\t}\n });\n\n mod.curveDetail = new Sk.builtin.func(function (detail) {\n\t// curveDetail(detail)\n\tmod.processing.curveDetail(detail.v);\n });\n\n mod.curvePoint = new Sk.builtin.func(function (a,b,c,d,t) {\n\t// curvePoint(a,b,c,d,t)\n\tmod.processing.curvePoint(a.v,b.v,c.v,d.v,t.v);\n });\n\n mod.curveTangent = new Sk.builtin.func(function (a,b,c,d,t) {\n\t// curveTangent(a,b,c,d,t)\n\tmod.processing.curveTangent(a.v,b.v,c.v,d.v,t.v);\n });\n\n mod.curveTightness = new Sk.builtin.func(function (squishy) {\n\t// curveTightness(squishy)\n\tmod.processing.curveTightness(squishy.v);\n });\n\n mod.curveVertex = new Sk.builtin.func(function (x, y, z) {\n\t// curveVertex(x, y) \n\t// curveVertex(x, y, z)\n if (typeof(z) === \"undefined\") {\n\t mod.processing.curveVertex(x.v, y.v);\n\t} else {\n\t mod.processing.curveVertex(x.v, y.v, z.v);\n\t}\n });\n\n mod.day = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.day());\n });\n\n mod.degrees = new Sk.builtin.func(function (angle) {\n\t// degrees(angle)\n\treturn new Sk.builtin.float_(mod.processing.degrees(angle.v));\n });\n\n mod.directionalLight = new Sk.builtin.func(function (v1,v2,v3,nx,ny,nz) {\n\t// directionalLight(v1,v2,v3,nx,ny,nz)\n\tmod.processing.directionalLight(v1.v,v2.v,v3.v,nx.v,ny.v,nz.v);\n });\n\n mod.dist = new Sk.builtin.func(function (x1, y1, z1, x2, y2, z2) {\n\t// dist(x1, y1, x2, y2)\n\t// dist(x1, y1, z1, x2, y2, z2)\n if (typeof(y2) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.dist(x1.v, y1.v, z1.v, x2.v));\n\t} else if (typeof(z2) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.dist(x1.v, y1.v, z1.v, x2.v, y2.v));\n\t} else {\n\t return new Sk.builtin.float_(mod.processing.dist(x1.v, y1.v, z1.v, x2.v, y2.v, z2.v));\n\t}\n });\n\n mod.emissive = new Sk.builtin.func(function (v1, v2, v3) {\n\t// emissive(gray)\n\t// emissive(color)\n\t// emissive(v1,v2,v3)\n if (typeof(v2) === \"undefined\") {\n\t mod.processing.emissive(v1.v);\n\t} else if (typeof(v3) === \"undefined\") {\n\t mod.processing.emissive(v1.v, v2.v);\n\t} else {\n\t mod.processing.emissive(v1.v, v2.v, v3.v);\n\t}\n });\n\n mod.endCamera = new Sk.builtin.func(function () {\n\t// endCamera()\n\tmod.processing.endCamera();\n });\n\n mod.endShape = new Sk.builtin.func(function (mode) {\n\t// endShape()\n\t// endShape(MODE)\n if (typeof(mode) === \"undefined\") {\n\t mod.processing.endShape();\n\t} else {\n\t mod.processing.endShape(mode.v);\n\t}\n });\n\n mod.filter = new Sk.builtin.func(function (mode, srcImg) {\n\t// filter(MODE)\n\t// filter(MODE, srcImg)\n if (typeof(srcImg) === \"undefined\") {\n\t mod.processing.filter(mode.v);\n\t} else {\n\t mod.processing.filter(mode.v, srcImg.v);\n\t}\n });\n\n mod.frustum = new Sk.builtin.func(function (left, right, bottom, top, near, far) {\n\t// frustum(left, right, bottom,top, near, far)\n\tmod.processing.frustum(left, right, bottom, top, near, far);\n });\n\n mod.hint = new Sk.builtin.func(function (item) {\n\t// hint(item)\n\tmod.processing.hint(item);\n });\n\n mod.hour = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.hour());\n });\n\n mod.hue = new Sk.builtin.func(function (color) {\n\t// hue(color)\n\treturn new Sk.builtin.float_(mod.processing.hue(color.v));\n });\n\n mod.imageMode = new Sk.builtin.func(function (mode) {\n\tmod.processing.imageMode(mode.v);\n });\n\n mod.lerp = new Sk.builtin.func(function (value1, value2, amt) {\n\t// lerp(value1, value2, amt)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.lerp(value1.v, value2.v, amt.v));\n });\n\n mod.lerpColor = new Sk.builtin.func(function (c1, c2, amt) {\n\t// lerpColor(c1, c2, amt)\n\t// returns color\n var c = Sk.misceval.callsim(mod.color,\n\t\t\t\t new Sk.builtin.int_(0),\n\t\t\t\t new Sk.builtin.int_(0),\n\t\t\t\t new Sk.builtin.int_(0));\n\tc.v = mod.processing.lerpColor(c1.v, c2.v, amt.v);\n\treturn c;\n });\n\n mod.lightFalloff = new Sk.builtin.func(function (constant, linear, quadratic) {\n\t// lightFalloff(constant,linear,quadratic)\n\tmod.processing.lightFalloff(constant.v, linear.v, quadratic.v);\n });\n\n mod.lights = new Sk.builtin.func(function () {\n\tmod.processing.lights();\n });\n\n mod.lightSpecular = new Sk.builtin.func(function (v1, v2, v3) {\n\t// lightSpecular(v1,v2,v3)\n\tmod.processing.lightSpecular(v1.v, v2.v, v3.v);\n });\n\n mod.loadBytes = new Sk.builtin.func(function (filename) {\n\t// loadBytes(filename)\n\t// returns byte[]\n\treturn new Sk.builtin.list(mod.processing.loadBytes(filename.v));\n });\n\n mod.loadFont = new Sk.builtin.func(function (fontname) {\n\t// loadFont(fontname)\n\t// returns font\n\tvar font = Sk.misceval.callsim(mod.PFont);\n\tfont.v = mod.processing.loadFont(fontname.v);\n\treturn font;\n });\n\n mod.loadShape = new Sk.builtin.func(function (filename) {\n\t// loadShape(filename)\n\t// returns shape\n\tvar shape = Sk.misceval.callsim(mod.PShapeSVG, \n\t\t\t\t\tnew Sk.builtin.str(\"string\"),\n\t\t\t\t\tfilename);\n\treturn shape;\n });\n\n mod.loadStrings = new Sk.builtin.func(function (filename) {\n\t// loadStrings(filename)\n\t// returns string []\n\treturn new Sk.builtin.list(mod.processing.loadStrings(filename.v));\n });\n\n mod.mag = new Sk.builtin.func(function (a, b, c) {\n\t// mag(a,b)\n\t// mag(a,b,c)\n\t// returns magnitude as float\n if (typeof(c) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.mag(a.v, b.v));\n } else {\n\t return new Sk.builtin.float_(mod.processing.mag(a.v, b.v, c.v));\n\t}\n });\n\n mod.map = new Sk.builtin.func(function (value,low1,high1,low2,high2) {\n\t// map(value,low1,high1,low2,high2)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.map(value.v,low1.v,high1.v,\n\t\t\t\t\t\t low2.v,high2.v));\n });\n\n mod.millis = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.millis());\n });\n\n mod.minute = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.minute());\n });\n\n mod.modelX = new Sk.builtin.func(function (x, y, z) {\n\t// modelX(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.modelX(x.v, y.v, z.v));\n });\n\n mod.modelY = new Sk.builtin.func(function (x, y, z) {\n\t// modelY(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.modelY(x.v, y.v, z.v));\n });\n\n mod.modelZ = new Sk.builtin.func(function (x, y, z) {\n\t// modelZ(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.modelZ(x.v, y.v, z.v));\n });\n\n mod.month = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.month());\n });\n\n mod.noCursor = new Sk.builtin.func(function () {\n\tmod.processing.noCursor();\n });\n\n mod.noise = new Sk.builtin.func(function (x, y, z) {\n\t// noise(x)\n\t// noise(x, y)\n\t// noise(x, y, z)\n\t// returns float\n if (typeof(y) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.noise(x.v));\n } else if (typeof(z) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.noise(x.v, y.v));\n } else {\n\t return new Sk.builtin.float_(mod.processing.noise(x.v, y.v, z.v));\n\t}\n });\n\n mod.noiseDetail = new Sk.builtin.func(function (octaves, falloff) {\n\t// noiseDetail(octaves);\n\t// noiseDetail(octaves,falloff);\n\tmod.processing.noiseDetail(octaves.v, falloff.v);\n });\n\n mod.noiseSeed = new Sk.builtin.func(function (value) {\n\t// noiseSeed(value); int\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.noiseSeed(value.v));\n });\n\n mod.noLights = new Sk.builtin.func(function () {\n\tmod.processing.noLights();\n });\n\n mod.norm = new Sk.builtin.func(function (value, low, high) {\n\t// norm(value, low, high)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.norm(value.v, low.v, high.v));\n });\n\n mod.normal = new Sk.builtin.func(function (nx, ny, nz) {\n\t// normal(nx,ny,nz)\n\t// returns None\n\tmod.processing.normal(nx.v, ny.v, nz.v);\n });\n\n mod.noTint = new Sk.builtin.func(function () {\n\tmod.processing.noTint();\n });\n\n mod.ortho = new Sk.builtin.func(function (left, right, bottom, top, near, far) {\n\t// ortho(left, right, bottom,top, near,far)\n\t// returns None\n\tmod.processing.ortho(left.v, right.v, bottom.v, top.v, near.v, far.v);\n });\n\n mod.perspective = new Sk.builtin.func(function (fov, aspect, zNear, zFar) {\n\t// perspective()\n\t// perspective(fov, aspect, zNear, zFar)\n\t// returns None\n if (typeof(fov) === \"undefined\") {\n\t mod.processing.perspective();\n } else if (typeof(aspect) === \"undefined\") {\n\t mod.processing.perspective(fov.v);\n } else if (typeof(zNear) === \"undefined\") {\n\t mod.processing.perspective(fov.v, aspect.v);\n } else if (typeof(zFar) === \"undefined\") {\n\t mod.processing.perspective(fov.v, aspect.v, zNear.v);\n } else {\n\t mod.processing.perspective(fov.v, aspect.v, zNear.v, zFar.v);\n\t}\n });\n\n mod.pointLight = new Sk.builtin.func(function (v1,v2,v3,nx,ny,nz) {\n\t// pointLight(v1,v2,v3,nx,ny,nz)\n\t// returns None\n\tmod.processing.pointLight(v1.v,v2.v,v3.v,nx.v,ny.v,nz.v);\n });\n\n mod.printCamera = new Sk.builtin.func(function () {\n\t// printCamera()\n\t// returns None\n\tmod.processing.printCamera();\n });\n\n mod.println = new Sk.builtin.func(function (data) {\n\t// println(data)\n\tmod.processing.println(data.v);\n });\n\n mod.printProjection = new Sk.builtin.func(function () {\n\t// printProjection()\n\t// returns None\n\tmod.processing.printProjection();\n });\n\n mod.radians = new Sk.builtin.func(function (angle) {\n\t// radians(angle)\n\t// returns int or float\n\treturn new Sk.builtin.float_(mod.processing.radians(angle.v));\n });\n\n mod.randomSeed = new Sk.builtin.func(function (value) {\n\t// noiseSeed(value);\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.randomSeed(value.v));\n });\n\n mod.random = new Sk.builtin.func(function (v1, v2) {\n\t// random();\n\t// random(high);\n\t// random(low, high);\n\t// returns float\n if (typeof(v1) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.random());\n } else if (typeof(v2) === \"undefined\") {\n\t return new Sk.builtin.float_(mod.processing.random(v1.v));\n } else {\n\t return new Sk.builtin.float_(mod.processing.random(v1.v, v2.v));\n\t}\n });\n\n mod.requestImage = new Sk.builtin.func(function (filename, extension) {\n\t// requestImage(filename)\n\t// requestImage(filename, extension)\n\tvar image = Sk.misceval.callsim(mod.PImage);\n if (typeof(extension) === \"undefined\") {\n\t image.v = mod.processing.requestImage(filename.v);\n } else {\n\t image.v = mod.processing.requestImage(filename.v, extension.v);\n\t}\n\treturn image;\n });\n\n mod.saturation = new Sk.builtin.func(function (color) {\n\t// saturation(color)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.saturation(color.v));\n });\n\n mod.save = new Sk.builtin.func(function (filename) {\n\t// save(filename)\n\t// returns None\n\tmod.processing.save(filename.v);\n });\n\n mod.saveFrame = new Sk.builtin.func(function (filename) {\n\t// saveFrame()\n\t// saveFrame(filename-####.ext)\n\t// returns None\n if (typeof(filename) === \"undefined\") {\n\t mod.processing.saveFrame();\n } else {\n\t mod.processing.saveFrame(filename.v);\n\t}\n });\n\n mod.saveStrings = new Sk.builtin.func(function (filename, strings) {\n\t// saveStrings(filename,strings)\n\tmod.processing.saveStrings(filename.v, strings.v);\n });\n\n mod.screenX = new Sk.builtin.func(function (x, y, z) {\n\t// screenX(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.screenX(x.v, y.v, z.v));\n });\n\n mod.screenY = new Sk.builtin.func(function (x, y, z) {\n\t// screenY(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.screenY(x.v, y.v, z.v));\n });\n\n mod.screenZ = new Sk.builtin.func(function (x, y, z) {\n\t// screenZ(x,y,z)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.screenZ(x.v, y.v, z.v));\n });\n\n mod.second = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.second());\n });\n\n mod.shape = new Sk.builtin.func(function (sh, x, y, width, height) {\n\t// shape(sh)\n\t// shape(sh,x,y)\n\t// shape(sh,x,y,width,height)\n\t// returns?\n if (typeof(x) === \"undefined\") {\n\t mod.processing.shape(sh.v);\n } else if (typeof(y) === \"undefined\") {\n\t mod.processing.shape(sh.v,x.v);\n } else if (typeof(width) === \"undefined\") {\n\t mod.processing.shape(sh.v,x.v,y.v);\n } else if (typeof(height) === \"undefined\") {\n\t mod.processing.shape(sh.v,x.v,y.v,width.v);\n } else {\n\t mod.processing.shape(sh.v,x.v,y.v,width.v,height.v);\n\t}\n });\n\n mod.shapeMode = new Sk.builtin.func(function (mode) {\n\t// shapeMode(MODE)\n\tmod.processing.shapeMode(mode.v);\n });\n\n mod.shininess = new Sk.builtin.func(function (shine) {\n\t// shininess(shine)\n\t// returns None\n\tmod.processing.shininess(shine.v);\n });\n\n mod.specular = new Sk.builtin.func(function (v1,v2,v3) {\n\t// specular(gray)\n\t// specular(color)\n\t// specular(v1,v2,v3)\n if (typeof(v2) === \"undefined\") {\n\t mod.processing.specular(v1.v);\n } else if (typeof(v3) === \"undefined\") {\n\t mod.processing.specular(v1.v,v2.v);\n } else {\n\t mod.processing.specular(v1.v,v2.v,v3.v);\n\t}\n });\n\n mod.spotLight = new Sk.builtin.func(function (v1,v2,v3,nx,ny,nz,angle,concentration) {\n\t// spotLight(v1,v2,v3,nx,ny,nz,angle,concentration)\n\t// returns None\n\tmod.processing.spotLight(v1.v,v2.v,v3.v,nx.v,ny.v,nz.v,angle.v,concentration.v);\n });\n\n mod.sq = new Sk.builtin.func(function (value) {\n\t// sq(value)\n\t// returns squared number\n\treturn new Sk.builtin.float_(mod.processing.sq(value));\n });\n\n mod.status = new Sk.builtin.func(function (text) {\n\t// status(text)\n\tmod.processing.status(text.v);\n });\n\n mod.textAlign = new Sk.builtin.func(function (align, yalign) {\n\t// textAlign(ALIGN)\n\t// textAlign(ALIGN, YALIGN)\n\t// returns None\n if (typeof(yalign) === \"undefined\") {\n\t mod.processing.textAlign(align.v);\n } else {\n\t mod.processing.textAlign(align.v, yalign.v);\n\t}\n });\n\n mod.textAscent = new Sk.builtin.func(function () {\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.textAscent());\n });\n\n mod.textDescent = new Sk.builtin.func(function () {\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.textDescent());\n });\n\n mod.textFont = new Sk.builtin.func(function (font, size) {\n\t// textFont(font)\n\t// textFont(font, size)\n if (typeof(size) === \"undefined\") {\n\t mod.processing.textFont(font.v);\n } else {\n\t mod.processing.textFont(font.v, size.v);\n\t}\n });\n\n mod.textLeading = new Sk.builtin.func(function (dist) {\n\t// textLeading(dist)\n\t// returns None\n\tmod.processing.textLeading(dist.v);\n });\n\n mod.textMode = new Sk.builtin.func(function (mode) {\n\t// textMode(MODE)\n\t// returns None\n\tmod.processing.textMode(mode.v);\n });\n\n mod.textSize = new Sk.builtin.func(function (size) {\n\t// textSize(size)\n\t// returns None\n\tmod.processing.textSize(size.v);\n });\n\n mod.texture = new Sk.builtin.func(function (img) {\n\t// texture(img)\n\t// returns None\n\tmod.processing.texture(img.v);\n });\n\n mod.textureMode = new Sk.builtin.func(function (mode) {\n\t// textureMode(MODE)\n\t// returns None\n\tmod.processing.textureMode(mode.v);\n });\n\n mod.textWidth = new Sk.builtin.func(function (data) {\n\t// textWidth(data)\n\t// returns float\n\treturn new Sk.builtin.float_(mod.processing.textWidth(data.v));\n });\n\n mod.tint = new Sk.builtin.func(function (v1, v2, v3, v4) {\n\t// tint(gray)\n\t// tint(gray, alpha)\n\t// tint(value1, value2, value3)\n\t// tint(value1, value2, value3, alpha)\n\t// tint(color)\n\t// tint(color, alpha)\n\t// tint(hex)\n\t// tint(hex, alpha)\n if (typeof(v2) === \"undefined\") {\n\t mod.processing.tint(v1.v);\n } else if (typeof(v3) === \"undefined\") {\n\t mod.processing.tint(v1.v, v2.v);\n } else if (typeof(v4) === \"undefined\") {\n\t mod.processing.tint(v1.v, v2.v, v3.v);\n } else {\n\t mod.processing.tint(v1.v, v2.v, v3.v, v4.v);\n\t}\n });\n\n mod.updatePixels = new Sk.builtin.func(function () {\n\t// updatePixels()\n\tmod.processing.updatePixels();\n });\n\n mod.vertex = new Sk.builtin.func(function (x, y, z, u, v) {\n\t// vertex(x, y); \n\t// vertex(x, y, z); \n\t// vertex(x, y, u, v); \n\t// vertex(x, y, z, u, v);\n if (typeof(z) === \"undefined\") {\n\t mod.processing.vertex(x.v, y.v);\n } else if (typeof(u) === \"undefined\") {\n\t mod.processing.vertex(x.v, y.v, z.v);\n } else if (typeof(v) === \"undefined\") {\n\t mod.processing.vertex(x.v, y.v, z.v, u.v);\n } else {\n\t mod.processing.vertex(x.v, y.v, z.v, u.v, v.v);\n\t}\n });\n\n mod.year = new Sk.builtin.func(function () {\n\treturn new Sk.builtin.int_(mod.processing.year());\n });\n\n // 3D Primitives\n\n mod.box = new Sk.builtin.func(function(size) {\n mod.processing.box(size.v);\n });\n\n mod.sphere = new Sk.builtin.func(function(radius) {\n mod.processing.sphere(radius.v);\n });\n\n mod.sphereDetail = new Sk.builtin.func(function(res,vres) {\n if (typeof(vres) === \"undefined\") {\n mod.processing.sphereDetail(res.v);\n }\n else {\n mod.processing.sphereDetail(res.v, vres.v);\n }\n });\n\n // Color\n mod.background = new Sk.builtin.func(function (r, g, b) {\n\n if (typeof(g) !== \"undefined\") {\n g = g.v;\n }\n if (typeof(b) !== \"undefined\") {\n b = b.v;\n }\n\n mod.processing.background(r.v, g, b);\n\n });\n\n mod.fill = new Sk.builtin.func(function (r, g, b, alpha) {\n // r will be either:\n // a number in which case the fill will be grayscale\n // a color object\n // g, and b may be undefined. If they hold values it will\n // be assumed that we have an r,g,b color tuple\n // alpha may also be undefined - if defined, it is the opacity of the fill\n if (typeof(g) !== \"undefined\") {\n g = g.v;\n }\n if (typeof(b) !== \"undefined\") {\n b = b.v;\n }\n if (typeof(alpha) !== \"undefined\") {\n alpha = alpha.v;\n }\n\n mod.processing.fill(r.v, g, b, alpha);\n\n });\n\n\n mod.stroke = new Sk.builtin.func(function (r, g, b) {\n\n if (typeof(g) !== \"undefined\") {\n g = g.v;\n }\n if (typeof(b) !== \"undefined\") {\n b = b.v;\n }\n\n mod.processing.stroke(r.v, g, b);\n\n });\n\n mod.noStroke = new Sk.builtin.func(function () {\n mod.processing.noStroke();\n });\n\n\n mod.colorMode = new Sk.builtin.func(function (mode, maxV, maxG, maxB, maxAlpha) {\n // mode is one of RGB or HSB\n // maxV is either the max value for all color elements\n // or the range for Red/Hue (depending on mode) if maxG and maxB are defined\n if (typeof(maxV) === \"undefined\") {\n maxV = 255;\n }\n else {\n maxV = maxV.v;\n }\n if (typeof(maxG) !== \"undefined\") {\n maxG = maxG.v;\n }\n if (typeof(maxB) !== \"undefined\") {\n maxB = maxB.v;\n }\n if (typeof(maxAlpha) !== \"undefined\") {\n maxAlpha = maxAlpha.v;\n }\n\n mod.processing.colorMode(mode.v, maxV, maxG, maxB, maxAlpha);\n });\n\n mod.noFill = new Sk.builtin.func(function () {\n mod.processing.noFill();\n });\n\n\n // Environment\n\n mod.loop = new Sk.builtin.func(function () {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"loop() should be called after run()\");\n }\n looping = true;\n mod.processing.loop();\n });\n\n mod.noLoop = new Sk.builtin.func(function () {\n if (mod.processing === null) {\n throw new Sk.builtin.Exception(\"noLoop() should be called after run()\");\n }\n looping = false;\n mod.processing.noLoop();\n });\n\n // NOTE: difference with ProcessingJS\n // frameRate is only a function, not a variable: \n // use environment.frameRate for value\n mod.frameRate = new Sk.builtin.func(function (fr) {\n mod.processing.frameRate(fr.v);\n });\n\n // NOTE: difference with ProcessingJS\n // Use mouse.pressed rather than mousePressed\n\n // NOTE: difference with ProcessingJS\n // Use environment.keyPressed rather than keyPressed\n\n // NOTE: difference with ProcessingJS\n // Use environment.frameCount \n\n // NOTE: difference with ProcessingJS\n // Use environment.frameCount\n \n // NOTE: difference with ProcessingJS\n // Use environment.online\n\n // NOTE: difference with ProcessingJS\n // Use environment.focused\n\n mod.width = new Sk.builtin.int_(100);\n mod.height = new Sk.builtin.int_(100);\n\n mod.size = new Sk.builtin.func(function (w, h, mode) {\n if (typeof(mode) === \"undefined\") {\n mode = mod.P2D;\n }\n mod.processing.size(w.v, h.v, mode.v);\n\tmod.width = new Sk.builtin.int_(mod.processing.width);\n\tmod.height = new Sk.builtin.int_(mod.processing.height);\n });\n\n mod.exitp = new Sk.builtin.func(function (h, w) {\n mod.processing.exit();\n });\n\n // NOTE: difference with ProcessingJS\n // Use mouseX() or mouse.x rather than mouseX\n mod.mouseX = new Sk.builtin.func(function () {\n return new Sk.builtin.int_(mod.processing.mouseX);\n });\n\n // NOTE: difference with ProcessingJS\n // Use mouseY() or mouse.y rather than mouseY\n mod.mouseY = new Sk.builtin.func(function () {\n return new Sk.builtin.int_(mod.processing.mouseY);\n });\n\n // NOTE: difference with ProcessingJS\n // Use pmouseX() or mouse.px rather than pmouseX\n mod.pmouseX = new Sk.builtin.func(function () {\n return new Sk.builtin.int_(mod.processing.pmouseX);\n });\n\n // NOTE: difference with ProcessingJS\n // Use pmouseY() or mouse.py rather than pmouseY\n mod.pmouseY = new Sk.builtin.func(function () {\n return new Sk.builtin.int_(mod.processing.pmouseY);\n });\n\n // Attributes\n mod.rectMode = new Sk.builtin.func(function (mode) {\n mod.processing.rectMode(mode.v);\n });\n\n mod.strokeWeight = new Sk.builtin.func(function (wt) {\n mod.processing.strokeWeight(wt.v);\n\n });\n\n mod.smooth = new Sk.builtin.func(function () {\n mod.processing.smooth();\n });\n\n mod.noSmooth = new Sk.builtin.func(function () {\n mod.processing.noSmooth();\n });\n\n mod.ellipseMode = new Sk.builtin.func(function (mode) {\n mod.processing.ellipseMode(mode.v);\n });\n\n mod.strokeCap = new Sk.builtin.func(function (mode) {\n mod.processing.strokeCap(mode.v);\n });\n\n mod.strokeJoin = new Sk.builtin.func(function (mode) {\n mod.processing.strokeJoin(mode.v);\n });\n\n\n // Transforms\n mod.rotate = new Sk.builtin.func(function (rads) {\n // rotation in radians\n mod.processing.rotate(rads.v);\n });\n\n mod.rotateX = new Sk.builtin.func(function(rads) {\n mod.processing.rotateX(rads.v);\n });\n\n mod.rotateY = new Sk.builtin.func(function(rads) {\n mod.processing.rotateY(rads.v);\n });\n\n mod.rotateZ = new Sk.builtin.func(function(rads) {\n mod.processing.rotateZ(rads.v);\n });\n\n mod.scale = new Sk.builtin.func(function (sx, sy, sz) {\n if (typeof(sy) === \"undefined\") {\n sy = 1.0;\n } else {\n sy = sy.v;\n }\n if (typeof(sz) === \"undefined\") {\n sz = 1.0;\n } else {\n sz = sz.v;\n }\n mod.processing.scale(sx.v, sy, sz);\n });\n\n mod.translate = new Sk.builtin.func(function (sx, sy, sz) {\n if (typeof(sy) === \"undefined\") {\n sy = 1.0;\n } else {\n sy = sy.v;\n }\n if (typeof(sz) === \"undefined\") {\n sz = 1.0;\n } else {\n sz = sz.v;\n }\n mod.processing.translate(sx.v, sy, sz);\n });\n\n mod.popMatrix = new Sk.builtin.func(function() {\n mod.processing.popMatrix();\n });\n\n mod.pushMatrix = new Sk.builtin.func(function() {\n mod.processing.pushMatrix();\n });\n\n mod.applyMatrix = new Sk.builtin.func(function() {\n var args = Array.prototype.slice.call(arguments, 0, 16),\n i;\n\n for (i = 0; i < args.length; i++) {\n args[i] = typeof(args[i]) === \"undefined\" ? 0.0 : args[i].v;\n }\n\n mod.processing.applyMatrix.apply(mod.processing, args);\n });\n\n mod.resetMatrix = new Sk.builtin.func(function() {\n mod.processing.resetMatrix();\n });\n\n mod.printMatrix = new Sk.builtin.func(function() {\n return Sk.ffi.remapToPy(mod.processing.printMatrix());\n });\n\n // //////////////////////////////////////////////////////////////////////\n // Run\n // \n // Create the processing context and setup of calls to setup, draw etc.\n //\n //\n // ////////////////////////////////////////////////////////////////////// \n mod.run = new Sk.builtin.func(function () {\n function sketchProc (processing) {\n mod.processing = processing;\n\n // processing.setup = function() {\n // if Sk.globals[\"setup\"]\n // Sk.misceval.callsim(Sk.globals[\"setup\"])\n // }\n\n\n // FIXME if no Sk.globals[\"draw\"], then no need for this\n processing.draw = function () {\n // if there are pending image loads then just use the natural looping calls to \n // retry until all the images are loaded. If noLoop was called in setup then make\n // sure to revert to that after all the images in hand.\n var wait = false;\n for (var i in imList) {\n if (imList[i].width === 0) {\n wait = true;\n }\n }\n if (wait === true) {\n if (looping === true) {\n return;\n }\n else {\n processing.loop();\n return;\n }\n\n } else {\n if (looping === false) {\n processing.noLoop();\n }\n }\n\n mod.frameCount = processing.frameCount;\n if (Sk.globals[\"draw\"]) {\n \ttry {\n \t Sk.misceval.callsim(Sk.globals[\"draw\"]);\n }\n catch(e) {\n Sk.uncaughtException(e);\n }\n\t\t\t\t}\n };\n\n var callBacks = [\"setup\", \"mouseMoved\", \"mouseClicked\", \"mouseDragged\", \"mouseMoved\", \"mouseOut\",\n \"mouseOver\", \"mousePressed\", \"mouseReleased\", \"keyPressed\", \"keyReleased\", \"keyTyped\"\n ];\n for (var cb in callBacks) {\n if (Sk.globals[callBacks[cb]]) {\n processing[callBacks[cb]] = new Function(\"try {Sk.misceval.callsim(Sk.globals['\" + callBacks[cb] + \"']);} catch(e) {Sk.uncaughtException(e);}\");\n }\n }\n }\n\n var canvas = document.getElementById(Sk.canvas);\n if (canvas.tagName !== \"CANVAS\") {\n var mydiv = canvas;\n canvas = document.createElement('canvas');\n while (mydiv.firstChild) {\n mydiv.removeChild(mydiv.firstChild);\n }\n mydiv.appendChild(canvas);\n }\n window.$(canvas).show();\n window.Processing.logger = { log : function(message) {\n Sk.misceval.print_(message);\n }};\n // if a Processing instance already exists it's likely still running, stop it by exiting\n instance = window.Processing.getInstanceById(Sk.canvas);\n if (instance) {\n instance.exit();\n }\n mod.p = new window.Processing(canvas, sketchProc);\n\n\n });\n\n mouseClass = function ($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"x\") {\n return Sk.builtin.assk$(mod.processing.mouseX);\n }\n else if (key === \"y\") {\n return Sk.builtin.assk$(mod.processing.mouseY);\n }\n else if (key === \"px\") {\n return Sk.builtin.assk$(mod.processing.pmouseX);\n }\n else if (key === \"py\") {\n return Sk.builtin.assk$(mod.processing.pmouseY);\n }\n else if (key === \"pressed\") {\n return new Sk.builtin.bool(mod.processing.__mousePressed);\n }\n else if (key === \"button\") {\n return Sk.builtin.assk$(mod.processing.mouseButton);\n }\n });\n\n };\n\n\n mod.Mouse = Sk.misceval.buildClass(mod, mouseClass, \"Mouse\", []);\n\n mod.mouse = Sk.misceval.callsim(mod.Mouse);\n\n keyboardClass = function ($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"key\") {\n return new Sk.builtin.str(mod.processing.key.toString());\n }\n else if (key === \"keyCode\") {\n return Sk.builtin.assk$(mod.processing.keyCode);\n }\n else if (key === \"keyPressed\") {\n return new Sk.builtin.str(mod.processing.keyPressed);\n } // todo bool\n });\n\n };\n\n mod.Keyboard = Sk.misceval.buildClass(mod, keyboardClass, \"Keyboard\", []);\n\n mod.keyboard = Sk.misceval.callsim(mod.Keyboard);\n\n\n environmentClass = function ($gbl, $loc) {\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"frameCount\") {\n return Sk.builtin.assk$(mod.processing.frameCount);\n }\n else if (key === \"frameRate\") {\n return Sk.builtin.assk$(mod.processing.frameRate);\n }\n else if (key === \"height\") {\n return Sk.builtin.assk$(mod.processing.height);\n }\n else if (key === \"width\") {\n return Sk.builtin.assk$(mod.processing.width);\n }\n else if (key === \"online\") {\n return new Sk.builtin.bool(mod.processing.online);\n }\n else if (key === \"focused\") {\n return new Sk.builtin.bool(mod.processing.focused);\n }\n });\n\n };\n\n mod.Environment = Sk.misceval.buildClass(mod, environmentClass, \"Environment\", []);\n\n mod.environment = Sk.misceval.callsim(mod.Environment);\n\n screenClass = function ($gbl, $loc) {\n\n $loc.__init__ = new Sk.builtin.func(function (self) {\n self.pixels = null;\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"height\") {\n return Sk.builtin.assk$(mod.processing.height);\n }\n else if (key === \"width\") {\n return Sk.builtin.assk$(mod.processing.width);\n }\n else if (key === \"pixels\") {\n if (self.pixels == null) {\n self.pixels = new Sk.builtin.list(mod.processing.pixels.toArray());\n }\n }\n return self.pixels;\n });\n\n };\n\n mod.Screen = Sk.misceval.buildClass(mod, screenClass, \"Screen\", []);\n\n mod.screen = Sk.misceval.callsim(mod.Screen);\n\n mod.loadPixels = new Sk.builtin.func(function () {\n mod.processing.loadPixels();\n });\n\n\n colorClass = function ($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function (self, val1, val2, val3, alpha) {\n if (typeof(val2) !== \"undefined\") {\n val2 = val2.v;\n }\n if (typeof(val3) !== \"undefined\") {\n val3 = val3.v;\n }\n if (typeof(alpha) !== \"undefined\") {\n alpha = alpha.v;\n }\n self.v = mod.processing.color(val1.v, val2, val3, alpha);\n });\n\n };\n\n mod.color = Sk.misceval.buildClass(mod, colorClass, \"color\", []);\n\n mod.red = new Sk.builtin.func(function (clr) {\n return new Sk.builtin.int_(mod.processing.red(clr.v));\n });\n\n mod.green = new Sk.builtin.func(function (clr) {\n return new Sk.builtin.int_(mod.processing.green(clr.v));\n });\n\n mod.blue = new Sk.builtin.func(function (clr) {\n return new Sk.builtin.int_(mod.processing.blue(clr.v));\n });\n\n // Image class and functions\n //\n imageClass = function ($gbl, $loc) {\n /* images are loaded async.. so its best to preload them */\n $loc.__init__ = new Sk.builtin.func(function (self, arg1, arg2, arg3) {\n\t // PImage()\n\t // PImage(img)\n\t // PImage(width,height)\n\t // PImage(width,height,format)\n\t if (typeof(arg1) === \"undefined\") {\n\t\tself.v = new mod.processing.PImage();\n\t } else if (typeof(arg2) === \"undefined\") {\n\t\tself.v = new mod.processing.PImage(arg1.v);\n\t } else if (typeof(arg3) === \"undefined\") {\n\t\tself.v = new mod.processing.PImage(arg1.v, arg2.v);\n\t } else {\n\t\tself.v = new mod.processing.PImage(arg1.v, arg2.v, arg3.v);\n\t }\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"width\") {\n return Sk.builtin.assk$(self.v.width);\n }\n if (key === \"height\") {\n return Sk.builtin.assk$(self.v.height);\n }\n });\n\n };\n\n mod.loadImage = new Sk.builtin.func(function (imfile) {\n var i = mod.processing.loadImage(imfile.v);\n imList.push(i);\n\tvar image = Sk.misceval.callsim(mod.PImage);\n\timage.v = i;\n return image;\n });\n\n mod.image = new Sk.builtin.func(function (im, x, y, w, h) {\n\t// image(img, x, y)\n\t// image(img, x, y, width, height)\n\tif (typeof(w) === \"undefined\") {\n mod.processing.image(im.v, x.v, y.v);\n\t} else {\n mod.processing.image(im.v, x.v, y.v, w.v, h.v);\n }\n });\n\n mod.get = new Sk.builtin.func(function (x, y) {\n var clr = mod.processing.get(x.v, y.v);\n return Sk.misceval.callsim(mod.color,\n new Sk.builtin.int_(mod.processing.red(clr)),\n new Sk.builtin.int_(mod.processing.green(clr)),\n new Sk.builtin.int_(mod.processing.blue(clr)));\n });\n\n mod.set = new Sk.builtin.func(function (x, y, color) {\n mod.processing.set(x.v, y.v, color.v);\n });\n\n // --- classes\n\n vectorClass = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, x, y, z) {\n\t // PVector()\n\t // PVector(x,y)\n\t // PVector(x,y,z)\n if (typeof(x) === \"undefined\") {\n\t\tself.v = new mod.processing.PVector();\n } else if (typeof(z) === \"undefined\") {\n\t\tself.v = new mod.processing.PVector(x.v, y.v);\n } else {\n\t\tself.v = new mod.processing.PVector(x.v, y.v, z.v);\n\t }\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"x\") {\n return Sk.builtin.assk$(self.v.x);\n } else if (key === \"y\") {\n return Sk.builtin.assk$(self.v.y);\n } else if (key === \"z\") {\n return Sk.builtin.assk$(self.v.z);\n\t }\n\t});\n\t \n $loc.get = new Sk.builtin.func(function (self) {\n\t // get() Gets a copy of the vector\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.get();\n\t return new_vec;\n\t});\n\t\n\t$loc.set = new Sk.builtin.func(function (self, x, y, x) {\n\t // set() Sets the x, y, z component of the vector\n\t if (typeof(z) === \"undefined\") {\n\t\tself.v.set(x.v, y.v);\n\t } else {\n\t\tself.v.set(x.v, y.v, z.v);\n\t }\n\t});\n\n\t$loc.mag = new Sk.builtin.func(function (self) {\n\t // mag() Calculates the magnitude (length) of the vector\n\t // and returns the result as a float\n\t return Sk.builtin.assk$(self.v.mag());\n\t});\n\n\t$loc.add = new Sk.builtin.func(function (self, vec) {\n\t // add()\tAdds one vector to another\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.add(vec.v);\n\t return new_vec;\n\t});\n\n\t$loc.sub = new Sk.builtin.func(function (self, vec) {\n\t // sub()\tSubtracts one vector from another\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.sub(vec.v);\n\t return new_vec;\n\t});\n\n\t$loc.mult = new Sk.builtin.func(function (self, vec) {\n\t // mult()\tMultiplies the vector by a scalar\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.mult(vec.v);\n\t return new_vec;\n\t});\n\n\t$loc.div = new Sk.builtin.func(function (self, vec) {\n\t // div()\tDivides the vector by a scalar\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.dic(vec.v);\n\t return new_vec;\n\t});\n\n\t$loc.dist = new Sk.builtin.func(function (self, vec) {\n\t // dist()\tCalculate the Euclidean distance between two points\n\t return Sk.builtin.assk$(self.v.dist(vec.v));\n\t});\n\n\t$loc.dot = new Sk.builtin.func(function (self, v1, v2, v3) {\n\t // dot()\tCalculates the dot product\n\t // returns float\n\t // vec.dot(x,y,z)\n\t // vec.dot(v)\t \n\t if (typeof(v2) === 'undefined') {\n\t\treturn Sk.builtin.assk$(self.v.dot(v1.v));\n\t } else {\n\t\treturn Sk.builtin.assk$(self.v.dot(v1.v, v2.v, v3.v));\n\t }\n\t});\n\n\t$loc.cross = new Sk.builtin.func(function (self, vec) {\n\t // cross()\tCalculates the cross product\n var new_vec = Sk.misceval.callsim(mod.PVector);\n\t new_vec.v = self.v.cross(vec.v);\n\t return new_vec;\n\t});\n\n\t$loc.normalize = new Sk.builtin.func(function (self) {\n\t // normalize()\tNormalizes the vector\n\t self.v.normalize();\n\t});\n\n\t$loc.limit = new Sk.builtin.func(function (self, value) {\n\t // limit()\tLimits the magnitude of the vector\n\t self.v.limit(value.v);\n\t});\n\n\t$loc.angleBetween = new Sk.builtin.func(function (self, vec) {\n\t // angleBetween()\tCalculates the angle between two vectors\n\t return Sk.builtin.assk$(self.v.angleBetween(vec.v));\n\t});\n\n\t$loc.array = new Sk.builtin.func(function (self) {\n\t // array()\t\n\t return new Sk.builtin.list(self.v.array());\n\t});\n };\n\n fontClass = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, input) {\n\t // PFont()\n\t // PFont(input)\n if (typeof(input) === \"undefined\") {\n\t\tself.v = new mod.processing.PFont();\n } else {\n\t\tself.v = new mod.processing.PVector(input.v);\n\t }\n });\n\n $loc.list = new Sk.builtin.func(function (self) {\n\t // font.list()\n\t return new Sk.builtin.list(self.v.list());\n\t});\n };\n\n graphicsClass = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, x, y, z) {\n\t // PGraphics()\n\t // PGraphics(width,height)\n\t // PGraphics(width,height,applet)\n if (typeof(x) === \"undefined\") {\n\t\tself.v = new mod.processing.PVector();\n } else if (typeof(z) === \"undefined\") {\n\t\tself.v = new mod.processing.PVector(x.v, y.v);\n } else {\n\t\tself.v = new mod.processing.PVector(x.v, y.v, z.v);\n\t }\n });\n\n $loc.beginDraw = new Sk.builtin.func(function (self) {\n\t self.v.beginDraw();\n\t});\n\n $loc.endDraw = new Sk.builtin.func(function (self) {\n\t self.v.endDraw();\n\t});\n };\n \n shapeClass = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, arg1, arg2, arg3) {\n\t if (typeof(arg1) === \"undefined\") {\n\t\t// special version for Skulpt\n\t\tself.v = null;\n\t\t// Will fill in manually in getChild()\n\t } else if (typeof(arg2) === \"undefined\") {\n\t\tself.v = new mod.processing.PShapeSVG(arg1.v);\n\t } else if (typeof(arg3) === \"undefined\") {\n\t\tself.v = new mod.processing.PShapeSVG(arg1.v, arg2.v);\n\t } else {\n\t\tself.v = new mod.processing.PShapeSVG(arg1.v, arg2.v, arg3.v);\n\t }\n });\n\n $loc.__getattr__ = new Sk.builtin.func(function (self, key) {\n\t key = Sk.ffi.remapToJs(key);\n if (key === \"width\") {\n return Sk.builtin.assk$(self.v.width);\n } else if (key === \"height\") {\n return Sk.builtin.assk$(self.v.height);\n\t }\n\t});\n\n $loc.isVisible = new Sk.builtin.func(function (self) {\n\t // isVisible() Returns a boolean value \"true\" if the image is set to be visible, \"false\" if not\n\t return new Sk.builtin.bool(self.v.isVisible());\n\t});\n\n $loc.setVisible = new Sk.builtin.func(function (self, value) {\n\t // setVisible() Sets the shape to be visible or invisible\n\t self.v.setVisible(value.v);\n\t});\n\n $loc.disableStyle = new Sk.builtin.func(function (self) {\n\t // disableStyle() Disables the shape's style data and uses Processing styles\n\t self.v.disableStyle();\n\t});\n\n $loc.enableStyle = new Sk.builtin.func(function (self) {\n\t // enableStyle() Enables the shape's style data and ignores the Processing styles\n\t self.v.enableStyle();\n\t});\n\n $loc.getChild = new Sk.builtin.func(function (self, shape) {\n\t // getChild() Returns a child element of a shape as a PShapeSVG object\n\t var child = self.v.getChild(shape.v);\n\t if (child != null) {\n\t\t// special method for Skulpt:\n\t\tvar new_shape = Sk.misceval.callsim(mod.PShapeSVG);\n\t\t// Now fill in value:\n\t\tnew_shape.v = child;\n\t\treturn new_shape;\n\t } else {\n\t\treturn null;\n\t }\n\t});\n\n $loc.translate = new Sk.builtin.func(function (self, x, y, z) {\n\t // translate() Displaces the shape\n\t // sh.translate(x,y)\n\t // sh.translate(x,y,z)\n if (typeof(z) === \"undefined\") {\n\t\tself.v.translate(x.v, y.v);\n\t } else {\n\t\tself.v.translate(x.v, y.v, z.v);\n\t }\n\t});\n\n $loc.rotate = new Sk.builtin.func(function (self, angle) {\n\t // rotate() Rotates the shape\n\t self.v.rotate(angle.v);\n\t});\n\n $loc.rotateX = new Sk.builtin.func(function (self, angle) {\n\t // rotateX() Rotates the shape around the x-axis\n\t self.v.rotateX(angle.v);\n\t});\n\n $loc.rotateY = new Sk.builtin.func(function (self) {\n\t // rotateY() Rotates the shape around the y-axis\n\t self.v.rotateY(angle.v);\n\t});\n\n $loc.rotateZ = new Sk.builtin.func(function (self) {\n\t // rotateZ() Rotates the shape around the z-axis\n\t self.v.rotateZ(angle.v);\n\t});\n\n $loc.scale = new Sk.builtin.func(function (self, x, y, z) {\n\t // scale() Increases and decreases the size of a shape\n\t // sh.scale(size)\n\t // sh.scale(x,y)\n\t // sh.scale(x,y,z)\n if (typeof(y) === \"undefined\") {\n\t\tself.v.scale(x.v);\n\t } else if (typeof(z) === \"undefined\") {\n\t\tself.v.scale(x.v, y.v);\n\t } else {\n\t\tself.v.scale(x.v, y.v, z.v);\n\t }\n\t});\n };\n\n mod.PFont = Sk.misceval.buildClass(mod, fontClass, \"PFont\", []);\n mod.PGraphics = Sk.misceval.buildClass(mod, graphicsClass, \"PGraphics\", []);\n mod.PShapeSVG = Sk.misceval.buildClass(mod, shapeClass, \"PShapeSVG\", []);\n mod.PVector = Sk.misceval.buildClass(mod, vectorClass, \"PVector\", []);\n mod.PImage = Sk.misceval.buildClass(mod, imageClass, \"PImage\", []);\n\n return mod;\n};\n", "src/lib/keyword.py": "\n__all__ = [\"iskeyword\", \"kwlist\"]\n\nkwlist = [\n#--start keywords--\n 'and',\n 'as',\n 'assert',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'exec',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'not',\n 'or',\n 'pass',\n 'print',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n#--end keywords--\n ]\n\ndef iskeyword(wd):\n return wd in kwlist\n\n", "src/lib/ConfigParser.py": "raise NotImplementedError(\"ConfigParser is not yet implemented in Skulpt\")\n", "src/lib/UserDict.py": "raise NotImplementedError(\"UserDict is not yet implemented in Skulpt\")\n", "src/lib/robotparser.py": "raise NotImplementedError(\"robotparser is not yet implemented in Skulpt\")\n", "src/lib/sha.py": "raise NotImplementedError(\"sha is not yet implemented in Skulpt\")\n", "src/lib/math.js": "var $builtinmodule = function (name) {\n var mod = {};\n mod.pi = new Sk.builtin.float_(Math.PI);\n mod.e = new Sk.builtin.float_(Math.E);\n\n mod.fabs = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"fabs\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.abs(Sk.builtin.asnum$(x)));\n });\n\n mod.asin = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"asin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.asin(Sk.builtin.asnum$(rad)));\n });\n\n mod.acos = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"acos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.acos(Sk.builtin.asnum$(rad)));\n });\n\n mod.atan = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"atan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.atan(Sk.builtin.asnum$(rad)));\n });\n\n mod.atan2 = new Sk.builtin.func(function (y, x) {\n Sk.builtin.pyCheckArgs(\"atan2\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.atan2(Sk.builtin.asnum$(y), Sk.builtin.asnum$(x)));\n });\n\n mod.sin = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"sin\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.sin(Sk.builtin.asnum$(rad)));\n });\n\n mod.cos = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"cos\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.cos(Sk.builtin.asnum$(rad)));\n });\n\n mod.tan = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"tan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n return new Sk.builtin.float_(Math.tan(Sk.builtin.asnum$(rad)));\n });\n\n mod.asinh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"asinh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var L = x + Math.sqrt(x * x + 1);\n\n return new Sk.builtin.float_(Math.log(L));\n });\n\n mod.acosh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"acosh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var L = x + Math.sqrt(x * x - 1);\n\n return new Sk.builtin.float_(Math.log(L));\n });\n\n mod.atanh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"atanh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var L = (1 + x) / (1 - x);\n\n return new Sk.builtin.float_(Math.log(L) / 2);\n });\n\n mod.sinh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"sinh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var e = Math.E;\n var p = Math.pow(e, x);\n var n = 1 / p;\n var result = (p - n) / 2;\n\n return new Sk.builtin.float_(result);\n });\n\n mod.cosh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"cosh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var e = Math.E;\n var p = Math.pow(e, x);\n var n = 1 / p;\n var result = (p + n) / 2;\n\n return new Sk.builtin.float_(result);\n });\n\n mod.tanh = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"tanh\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Sk.builtin.asnum$(x);\n\n var e = Math.E;\n var p = Math.pow(e, x);\n var n = 1 / p;\n var result = ((p - n) / 2) / ((p + n) / 2);\n\n return new Sk.builtin.float_(result);\n });\n\n mod.ceil = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"ceil\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.ceil(Sk.builtin.asnum$(x)));\n });\n\n // returns y with the sign of x\n mod.copysign = new Sk.builtin.func(function (x, y) {\n Sk.builtin.pyCheckArgs(\"ceil\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n var _x = Sk.ffi.remapToJs(x);\n var _y = Sk.ffi.remapToJs(y);\n var res;\n\n var isNeg_x = _x < 0;\n var isNeg_y = _x < 0;\n\n // special case for floats with negative zero\n if(Sk.builtin.checkFloat(x)) {\n if(_x === 0) {\n isNeg_x = 1/_x === -Infinity ? true : false;\n }\n }\n\n if(Sk.builtin.checkFloat(y)) {\n if(_y === 0) {\n isNeg_y = 1/_y === -Infinity ? true : false;\n }\n }\n\n // if both signs are equal, just return _y\n if((isNeg_x && isNeg_y) || (!isNeg_x && !isNeg_y)) {\n res = _y;\n } else if((isNeg_x && !isNeg_y) || (!isNeg_x && isNeg_y)) {\n // if different, invert sign\n if(y === 0) {\n // special case for zero\n res = isNeg_x ? -0.0 : 0.0;\n } else {\n res = _y * -1;\n }\n }\n\n return new Sk.builtin.float_(res);\n });\n\n mod.floor = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"floor\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.floor(Sk.builtin.asnum$(x)));\n });\n\n mod.sqrt = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"sqrt\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.sqrt(Sk.builtin.asnum$(x)));\n });\n\n mod.trunc = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"trunc\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.int_(Sk.builtin.asnum$(x) | 0);\n });\n\n mod.log = new Sk.builtin.func(function (x, base) {\n Sk.builtin.pyCheckArgs(\"log\", arguments, 1, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n if (base === undefined) {\n return new Sk.builtin.float_(Math.log(Sk.builtin.asnum$(x)));\n } else {\n Sk.builtin.pyCheckType(\"base\", \"number\", Sk.builtin.checkNumber(base));\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(Sk.builtin.asnum$(base));\n return new Sk.builtin.float_(ret);\n }\n });\n\n mod.log10 = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"log10\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n var ret = Math.log(Sk.builtin.asnum$(x)) / Math.log(10);\n return new Sk.builtin.float_(ret);\n });\n\n /* Return True if x is infinite, and False otherwise. */\n mod.isinf = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"isinf\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n var _x = Sk.builtin.asnum$(x);\n if(isFinite(_x) && !isNaN(_x)) {\n return Sk.builtin.bool.false$;\n } else {\n return Sk.builtin.bool.true$\n }\n });\n\n /* Return True if x is a NaN (not a number), and False otherwise. */\n mod.isnan = new Sk.builtin.func(function(x) {\n Sk.builtin.pyCheckArgs(\"isnan\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"float\", Sk.builtin.checkFloat(x));\n\n var _x = Sk.builtin.asnum$(x);\n if(isNaN(_x)) {\n return Sk.builtin.bool.true$;\n } else {\n return Sk.builtin.bool.false$;\n }\n });\n\n mod.exp = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"exp\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n return new Sk.builtin.float_(Math.exp(Sk.builtin.asnum$(x)));\n });\n\n mod.pow = new Sk.builtin.func(function (x, y) {\n Sk.builtin.pyCheckArgs(\"pow\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n return new Sk.builtin.float_(Math.pow(Sk.builtin.asnum$(x), Sk.builtin.asnum$(y)));\n });\n\n mod.radians = new Sk.builtin.func(function (deg) {\n Sk.builtin.pyCheckArgs(\"radians\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"deg\", \"number\", Sk.builtin.checkNumber(deg));\n\n var ret = Math.PI / 180.0 * Sk.builtin.asnum$(deg);\n return new Sk.builtin.float_(ret);\n });\n\n mod.degrees = new Sk.builtin.func(function (rad) {\n Sk.builtin.pyCheckArgs(\"degrees\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"rad\", \"number\", Sk.builtin.checkNumber(rad));\n\n var ret = 180.0 / Math.PI * Sk.builtin.asnum$(rad);\n return new Sk.builtin.float_(ret);\n });\n\n mod.hypot = new Sk.builtin.func(function (x, y) {\n Sk.builtin.pyCheckArgs(\"hypot\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n Sk.builtin.pyCheckType(\"y\", \"number\", Sk.builtin.checkNumber(y));\n\n x = Sk.builtin.asnum$(x);\n y = Sk.builtin.asnum$(y);\n return new Sk.builtin.float_(Math.sqrt((x * x) + (y * y)));\n });\n\n mod.factorial = new Sk.builtin.func(function (x) {\n Sk.builtin.pyCheckArgs(\"factorial\", arguments, 1, 1);\n Sk.builtin.pyCheckType(\"x\", \"number\", Sk.builtin.checkNumber(x));\n\n x = Math.floor(Sk.builtin.asnum$(x));\n var r = 1;\n for (var i = 2; i <= x; i++) {\n r *= i;\n }\n return new Sk.builtin.int_(r);\n });\n\n return mod;\n}", "src/lib/shlex.py": "raise NotImplementedError(\"shlex is not yet implemented in Skulpt\")\n", "src/lib/CGIHTTPServer.py": "raise NotImplementedError(\"CGIHTTPServer is not yet implemented in Skulpt\")\n", "src/lib/posixpath.py": "raise NotImplementedError(\"posixpath is not yet implemented in Skulpt\")\n", "src/lib/py_compile.py": "raise NotImplementedError(\"py_compile is not yet implemented in Skulpt\")\n", "src/lib/sunaudio.py": "raise NotImplementedError(\"sunaudio is not yet implemented in Skulpt\")\n", "src/lib/stat.py": "raise NotImplementedError(\"stat is not yet implemented in Skulpt\")\n", "src/lib/compileall.py": "raise NotImplementedError(\"compileall is not yet implemented in Skulpt\")\n", "src/lib/csv.py": "raise NotImplementedError(\"csv is not yet implemented in Skulpt\")\n", "src/lib/fractions.py": "raise NotImplementedError(\"fractions is not yet implemented in Skulpt\")\n", "src/lib/sched.py": "raise NotImplementedError(\"sched is not yet implemented in Skulpt\")\n", "src/lib/xmlrpclib.py": "raise NotImplementedError(\"xmlrpclib is not yet implemented in Skulpt\")\n", "src/lib/imaplib.py": "raise NotImplementedError(\"imaplib is not yet implemented in Skulpt\")\n", "src/lib/htmlentitydefs.py": "raise NotImplementedError(\"htmlentitydefs is not yet implemented in Skulpt\")\n", "src/lib/image.js": "var ImageMod; // the single identifier needed in the global scope\nvar $builtinmodule;\n\nif (!ImageMod) {\n ImageMod = {};\n ImageMod.canvasLib = [];\n}\n\n$builtinmodule = function (name) {\n var screen;\n var pixel;\n var eImage;\n var mod = {};\n var updateCanvasAndSuspend;\n var initializeImage;\n var checkPixelRange;\n var remapImageIdToURL;\n\n var image = function ($gbl, $loc) {\n initializeImage = function (self) {\n self.width = self.image.width;\n self.height = self.image.height;\n self.delay = 0;\n self.updateCount = 0;\n self.updateInterval = 1;\n self.lastx = 0;\n self.lasty = 0;\n self.canvas = document.createElement(\"canvas\");\n self.canvas.height = self.height;\n self.canvas.width = self.width;\n self.ctx = self.canvas.getContext(\"2d\");\n self.ctx.drawImage(self.image, 0, 0);\n self.imagedata = self.ctx.getImageData(0, 0, self.width, self.height);\n };\n\n\n $loc.__init__ = new Sk.builtin.func(function (self, imageId) {\n var susp;\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n try {\n self.image = document.getElementById(Sk.ffi.remapToJs(imageId));\n initializeImage(self);\n } catch (e) {\n self.image = null;\n }\n if (self.image == null) {\n susp = new Sk.misceval.Suspension();\n susp.resume = function () {\n // Should the post image get stuff go here??\n if (susp.data[\"error\"]) {\n throw new Sk.builtin.IOError(susp.data[\"error\"].message);\n }\n };\n susp.data = {\n type: \"Sk.promise\",\n promise: new Promise(function (resolve, reject) {\n var newImg = new Image();\n newImg.crossOrigin = \"\";\n newImg.onerror = function () {\n reject(Error(\"Failed to load URL: \" + newImg.src));\n };\n newImg.onload = function () {\n self.image = this;\n initializeImage(self);\n resolve();\n };\n // look for mapping from imagename to url and possible an image proxy server\n newImg.src = remapImageIdToURL(imageId);\n }\n )\n };\n return susp;\n }\n\n });\n\n remapImageIdToURL = function (imageId) {\n // if imageId starts with http -- OK\n // if imageId is in Sk.imageMap -- look it up\n // if imageId is the name of an image file prepend http://host/app/book/_static/\n // if image proxy server is configured construct url for proxy\n // return the final URL\n var url;\n var ret;\n ret = Sk.ffi.remapToJs(imageId);\n url = document.createElement(\"a\");\n url.href = ret;\n if (window.location.host !== url.host) {\n ret = Sk.imageProxy + \"/\" + ret;\n }\n return ret;\n };\n\n checkPixelRange = function (self, x, y) {\n if (x < 0 || y < 0 || x >= self.width || y >= self.height) {\n throw new Sk.builtin.ValueError(\"Pixel index out of range.\");\n }\n };\n\n $loc.setDelay = new Sk.builtin.func(function (self, delay, interval) {\n var i;\n Sk.builtin.pyCheckArgs(\"setDelay\", arguments, 2, 3);\n self.delay = Sk.ffi.remapToJs(delay);\n i = Sk.builtin.asnum$(interval);\n if (!i) {\n self.updateInterval = 1;\n } else {\n self.updateInterval = i;\n }\n });\n\n\n //get a one-dimensional array of pixel objects - Zhu\n $loc.getPixels = new Sk.builtin.func(function (self) {\n var arr = [];//initial array\n var i;\n Sk.builtin.pyCheckArgs(\"getPixels\", arguments, 1, 1);\n\n for (i = 0; i < self.image.height * self.image.width; i++) {\n\n arr[i] = Sk.misceval.callsim(self.getPixel, self,\n i % self.image.width, Math.floor(i / self.image.width));\n }\n return new Sk.builtin.tuple(arr);\n });\n\n $loc.getPixel = new Sk.builtin.func(function (self, x, y) {\n var red;\n var blue;\n var green;\n var index;\n Sk.builtin.pyCheckArgs(\"getPixel\", arguments, 3, 3);\n x = Sk.builtin.asnum$(x);\n y = Sk.builtin.asnum$(y);\n checkPixelRange(self, x, y);\n index = (y * 4) * self.width + (x * 4);\n red = self.imagedata.data[index];\n green = self.imagedata.data[index + 1];\n blue = self.imagedata.data[index + 2];\n return Sk.misceval.callsim(mod.Pixel, red, green, blue, x, y);\n });\n\n updateCanvasAndSuspend = function (self, x, y) {\n var susp = new Sk.misceval.Suspension();\n susp.resume = function () {\n return Sk.builtin.none.none$;\n };\n susp.data = {\n type: \"Sk.promise\",\n promise: new Promise(function (resolve, reject) {\n self.updateCount++;\n if ((self.updateCount % self.updateInterval) === 0) {\n if (self.lastx + self.updateInterval >= self.width) {\n self.lastCtx.putImageData(self.imagedata, self.lastUlx, self.lastUly,\n 0, self.lasty, self.width, 2);\n } else if (self.lasty + self.updateInterval >= self.height) {\n self.lastCtx.putImageData(self.imagedata, self.lastUlx, self.lastUly,\n self.lastx, 0, 2, self.height);\n } else {\n self.lastCtx.putImageData(self.imagedata, self.lastUlx, self.lastUly,\n Math.min(x, self.lastx),\n Math.min(y, self.lasty),\n Math.max(Math.abs(x - self.lastx), 1),\n Math.max(Math.abs(y - self.lasty), 1));\n }\n self.lastx = x;\n self.lasty = y;\n if (self.delay > 0) {\n window.setTimeout(resolve, self.delay);\n } else {\n resolve();\n }\n } else {\n resolve();\n }\n })\n };\n return susp;\n };\n\n $loc.setPixel = new Sk.builtin.func(function (self, x, y, pix) {\n var index;\n Sk.builtin.pyCheckArgs(\"setPixel\", arguments, 4, 4);\n x = Sk.builtin.asnum$(x);\n y = Sk.builtin.asnum$(y);\n checkPixelRange(self, x, y);\n index = (y * 4) * self.width + (x * 4);\n self.imagedata.data[index] = Sk.builtin.asnum$(Sk.misceval.callsim(pix.getRed, pix));\n self.imagedata.data[index + 1] = Sk.builtin.asnum$(Sk.misceval.callsim(pix.getGreen, pix));\n self.imagedata.data[index + 2] = Sk.builtin.asnum$(Sk.misceval.callsim(pix.getBlue, pix));\n self.imagedata.data[index + 3] = 255;\n return updateCanvasAndSuspend(self, x, y);\n });\n\n // update the image with the pixel at the given count - Zhu\n $loc.setPixelAt = new Sk.builtin.func(function (self, count, pixel) {\n var x;\n var y;\n var index;\n Sk.builtin.pyCheckArgs(\"setPixelAt\", arguments, 3, 3);\n count = Sk.builtin.asnum$(count);\n x = count % self.image.width;\n y = Math.floor(count / self.image.width);\n checkPixelRange(self, x, y);\n index = (y * 4) * self.width + (x * 4);\n self.imagedata.data[index] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getRed, pixel));\n self.imagedata.data[index + 1] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getGreen, pixel));\n self.imagedata.data[index + 2] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getBlue, pixel));\n self.imagedata.data[index + 3] = 255;\n return updateCanvasAndSuspend(self, x, y);\n });\n\n // new updatePixel that uses the saved x and y location in the pixel - Barb Ericson\n $loc.updatePixel = new Sk.builtin.func(function (self, pixel) {\n var x;\n var y;\n var index;\n Sk.builtin.pyCheckArgs(\"updatePixel\", arguments, 2, 2);\n x = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getX, pixel));\n y = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getY, pixel));\n checkPixelRange(self, x, y);\n index = (y * 4) * self.width + (x * 4);\n self.imagedata.data[index] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getRed, pixel));\n self.imagedata.data[index + 1] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getGreen, pixel));\n self.imagedata.data[index + 2] = Sk.builtin.asnum$(Sk.misceval.callsim(pixel.getBlue, pixel));\n self.imagedata.data[index + 3] = 255;\n return updateCanvasAndSuspend(self, x, y);\n });\n\n $loc.getHeight = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getHeight\", arguments, 1, 1);\n return new Sk.builtin.int_(self.image.height);\n });\n\n $loc.getWidth = new Sk.builtin.func(function (self, titlestring) {\n Sk.builtin.pyCheckArgs(\"getWidth\", arguments, 1, 1);\n return new Sk.builtin.int_(self.image.width);\n });\n\n $loc.draw = new Sk.builtin.func(function (self, win, ulx, uly) {\n var susp;\n Sk.builtin.pyCheckArgs(\"draw\", arguments, 2, 4);\n susp = new Sk.misceval.Suspension();\n susp.resume = function () {\n return Sk.builtin.none.none$;\n };\n susp.data = {\n type: \"Sk.promise\",\n promise: new Promise(function (resolve, reject) {\n var can;\n var ctx;\n win = Sk.builtin.asnum$(win);\n ulx = Sk.builtin.asnum$(ulx);\n uly = Sk.builtin.asnum$(uly);\n can = Sk.misceval.callsim(win.getWin, win);\n ctx = can.getContext(\"2d\");\n if (!ulx) {\n ulx = 0;\n uly = 0;\n }\n self.lastUlx = ulx;\n self.lastUly = uly;\n self.lastCtx = ctx; // save a reference to the context of the window the image was last drawn in\n //ctx.putImageData(self.imagedata,0,0,0,0,self.imagedata.width,self.imagedata.height);\n ctx.putImageData(self.imagedata, ulx, uly);\n\n if (self.delay > 0) {\n window.setTimeout(resolve, self.delay);\n } else {\n window.setTimeout(resolve, 200);\n }\n })\n };\n return susp;\n\n });\n\n // toList\n\n };\n\n mod.Image = Sk.misceval.buildClass(mod, image, \"Image\", []);\n\n eImage = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, width, height) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 3, 3);\n self.width = Sk.builtin.asnum$(width);\n self.height = Sk.builtin.asnum$(height);\n self.canvas = document.createElement(\"canvas\");\n self.ctx = self.canvas.getContext(\"2d\");\n self.canvas.height = self.height;\n self.canvas.width = self.width;\n self.imagedata = self.ctx.getImageData(0, 0, self.width, self.height);\n });\n\n };\n\n mod.EmptyImage = Sk.misceval.buildClass(mod, eImage, \"EmptyImage\", [mod.Image]);\n\n // create a ListImage object\n\n\n pixel = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, r, g, b, x, y) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 4, 6);\n self.red = Sk.builtin.asnum$(r);\n self.green = Sk.builtin.asnum$(g);\n self.blue = Sk.builtin.asnum$(b);\n self.x = Sk.builtin.asnum$(x);\n self.y = Sk.builtin.asnum$(y);\n });\n\n $loc.getRed = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getRed\", arguments, 1, 1);\n return Sk.builtin.assk$(self.red);\n });\n\n $loc.getGreen = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getGreen\", arguments, 1, 1);\n return Sk.builtin.assk$(self.green);\n });\n\n $loc.getBlue = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getBlue\", arguments, 1, 1);\n return Sk.builtin.assk$(self.blue);\n });\n\n $loc.getX = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getX\", arguments, 1, 1);\n return Sk.builtin.assk$(self.x);\n });\n\n $loc.getY = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"getY\", arguments, 1, 1);\n return Sk.builtin.assk$(self.y);\n });\n\n $loc.setRed = new Sk.builtin.func(function (self, r) {\n Sk.builtin.pyCheckArgs(\"setRed\", arguments, 2, 2);\n self.red = Sk.builtin.asnum$(r);\n });\n\n $loc.setGreen = new Sk.builtin.func(function (self, g) {\n Sk.builtin.pyCheckArgs(\"setGreen\", arguments, 2, 2);\n self.green = Sk.builtin.asnum$(g);\n });\n\n $loc.setBlue = new Sk.builtin.func(function (self, b) {\n Sk.builtin.pyCheckArgs(\"setBlue\", arguments, 2, 2);\n self.blue = Sk.builtin.asnum$(b);\n });\n\n $loc.setX = new Sk.builtin.func(function (self, x) {\n Sk.builtin.pyCheckArgs(\"setX\", arguments, 2, 2);\n self.x = Sk.builtin.asnum$(x);\n });\n\n $loc.setY = new Sk.builtin.func(function (self, y) {\n Sk.builtin.pyCheckArgs(\"setY\", arguments, 2, 2);\n self.y = Sk.builtin.asnum$(y);\n });\n\n $loc.__getitem__ = new Sk.builtin.func(function (self, k) {\n k = Sk.builtin.asnum$(k);\n if (k === 0) {\n return self.red;\n } else if (k == 1) {\n return self.green;\n } else if (k == 2) {\n return self.blue;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function (self) {\n return \"[\" + self.red + \",\" + self.green + \",\" + self.blue + \"]\";\n });\n\n //getColorTuple\n $loc.getColorTuple = new Sk.builtin.func(function (self, x, y) {\n\n });\n\n //setRange -- change from 0..255 to 0.0 .. 1.0\n $loc.setRange = new Sk.builtin.func(function (self, mx) {\n self.max = Sk.builtin.asnum$(mx);\n });\n\n };\n mod.Pixel = Sk.misceval.buildClass(mod, pixel, \"Pixel\", []);\n\n\n screen = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, width, height) {\n var currentCanvas;\n var tmpCan, tmpDiv;\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 1, 3);\n currentCanvas = ImageMod.canvasLib[Sk.canvas];\n if (currentCanvas === undefined) {\n tmpCan = document.createElement(\"canvas\");\n tmpDiv = document.getElementById(Sk.canvas);\n self.theScreen = tmpCan;\n tmpDiv.appendChild(tmpCan);\n ImageMod.canvasLib[Sk.canvas] = tmpCan;\n ImageMod.canvasLib[Sk.canvas] = self.theScreen;\n } else {\n self.theScreen = currentCanvas;\n self.theScreen.height = self.theScreen.height;\n }\n if (width !== undefined) {\n self.theScreen.height = height.v;\n self.theScreen.width = width.v;\n } else {\n if (Sk.availableHeight) {\n self.theScreen.height = Sk.availableHeight;\n }\n if (Sk.availableWidth) {\n self.theScreen.width = Sk.availableWidth;\n }\n }\n\n self.theScreen.style.display = \"block\";\n });\n\n $loc.getWin = new Sk.builtin.func(function (self) {\n return self.theScreen;\n });\n\n // exitonclick\n $loc.exitonclick = new Sk.builtin.func(function (self) {\n var canvas_id = self.theScreen.id;\n self.theScreen.onclick = function () {\n document.getElementById(canvas_id).style.display = \"none\";\n document.getElementById(canvas_id).onclick = null;\n delete ImageMod.canvasLib[canvas_id];\n };\n\n });\n //getMouse\n };\n\n mod.ImageWin = Sk.misceval.buildClass(mod, screen, \"ImageWin\", []);\n\n return mod;\n};\n", "src/lib/mailbox.py": "raise NotImplementedError(\"mailbox is not yet implemented in Skulpt\")\n", "src/lib/sre_compile.py": "raise NotImplementedError(\"sre_compile is not yet implemented in Skulpt\")\n", "src/lib/re.js": "var $builtinmodule = function (name) {\n var mod = {};\n\n // Constants (mostly unsupported)\n mod.I = 2;\n mod.IGNORECASE = 2;\n // mod.L = 4;\n // mod.LOCALE = 4;\n mod.M = 8;\n mod.MULTILINE = 8;\n // mod.S = 16;\n // mod.DOTALL = 16;\n // mod.U = 32;\n // mod.UNICODE = 32;\n // mod.X = 64;\n // mod.VERBOSE = 64;\n\n var validGroups = [\"(?:\", \"(?=\", \"(?!\"];\n\n var convert = function (pattern) {\n var newpattern;\n var match;\n var i;\n\n // Look for disallowed constructs\n match = pattern.match(/\\(\\?./g);\n if (match) {\n for (i = 0; i < match.length; i++) {\n if (validGroups.indexOf(match[i]) == -1) {\n throw new Sk.builtin.ValueError(\"Disallowed group in pattern: '\"\n + match[i] + \"'\");\n }\n ;\n }\n ;\n }\n ;\n\n newpattern = pattern.replace('/\\\\/g', '\\\\\\\\');\n newpattern = pattern.replace(/([^\\\\]){,(?![^\\[]*\\])/g, '$1{0,');\n\n return newpattern;\n };\n\n var getFlags = function (flags) {\n var jsflags = \"g\";\n if ((flags & mod.IGNORECASE) == mod.IGNORECASE) {\n jsflags += \"i\";\n }\n ;\n if ((flags & mod.MULTILINE) == mod.MULTILINE) {\n jsflags += \"m\";\n }\n ;\n return jsflags;\n };\n\n mod.split = Sk.nativejs.func(function split (pattern, string, maxsplit, flags) {\n Sk.builtin.pyCheckArgs(\"split\", arguments, 2, 4);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n }\n ;\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n }\n ;\n if (maxsplit === undefined) {\n maxsplit = 0;\n }\n ;\n if (!Sk.builtin.checkNumber(maxsplit)) {\n throw new Sk.builtin.TypeError(\"maxsplit must be a number\");\n }\n ;\n if (flags === undefined) {\n flags = 0;\n }\n ;\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n }\n ;\n\n maxsplit = Sk.builtin.asnum$(maxsplit);\n var pat = Sk.ffi.unwrapo(pattern);\n var str = Sk.ffi.unwrapo(string);\n\n // Convert pat from Python to Javascript regex syntax\n pat = convert(pat);\n //print(\"Pat: \" + pat);\n //print(\"Str: \" + str);\n\n var captured = !(pat.match(/^\\(.*\\)$/) === null);\n //print(\"Captured: \", captured);\n\n var jsflags = getFlags(flags);\n //print(\"Flags: \", jsflags);\n\n var regex = new RegExp(pat, jsflags);\n\n var result = [];\n var match;\n var index = 0;\n var splits = 0;\n while ((match = regex.exec(str)) != null) {\n //print(\"Matched '\" + match[0] + \"' at position \" + match.index + \n // \"; next search at \" + regex.lastIndex);\n if (match.index === regex.lastIndex) {\n // empty match\n break;\n }\n ;\n result.push(new Sk.builtin.str(str.substring(index, match.index)));\n if (captured) {\n // Add matching pattern, too\n result.push(new Sk.builtin.str(match[0]));\n }\n ;\n index = regex.lastIndex;\n splits += 1;\n if (maxsplit && (splits >= maxsplit)) {\n break;\n }\n ;\n }\n ;\n result.push(new Sk.builtin.str(str.substring(index)));\n\n return new Sk.builtin.list(result);\n });\n\n mod.findall = Sk.nativejs.func(function findall (pattern, string, flags) {\n Sk.builtin.pyCheckArgs(\"findall\", arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n }\n ;\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n }\n ;\n if (flags === undefined) {\n flags = 0;\n }\n ;\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n }\n ;\n\n var pat = Sk.ffi.unwrapo(pattern);\n var str = Sk.ffi.unwrapo(string);\n\n // Convert pat from Python to Javascript regex syntax\n pat = convert(pat);\n //print(\"Pat: \" + pat);\n //print(\"Str: \" + str);\n\n var jsflags = getFlags(flags);\n //print(\"Flags: \", jsflags);\n\n var regex = new RegExp(pat, jsflags);\n\n if (pat.match(/\\$/)) {\n var newline_at_end = new RegExp(/\\n$/);\n if (str.match(newline_at_end)) {\n str = str.slice(0, -1);\n }\n }\n\n var result = [];\n var match;\n while ((match = regex.exec(str)) != null) {\n //print(\"Matched '\" + match[0] + \"' at position \" + match.index + \n // \"; next search at \" + regex.lastIndex);\n // print(\"match: \" + JSON.stringify(match));\n if (match.length < 2) {\n result.push(new Sk.builtin.str(match[0]));\n } else if (match.length == 2) {\n result.push(new Sk.builtin.str(match[1]));\n } else {\n var groups = [];\n for (var i = 1; i < match.length; i++) {\n groups.push(new Sk.builtin.str(match[i]));\n }\n ;\n result.push(new Sk.builtin.tuple(groups));\n }\n ;\n if (match.index === regex.lastIndex) {\n regex.lastIndex += 1;\n }\n ;\n }\n ;\n\n return new Sk.builtin.list(result);\n });\n\n\n var matchobj = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, thematch, pattern, string) {\n self.thematch = thematch;\n self.re = pattern;\n self.string = string;\n });\n\n $loc.groups = new Sk.builtin.func(function (self) {\n return new Sk.builtin.tuple(self.thematch.v.slice(1))\n });\n\n $loc.group = new Sk.builtin.func(function (self, grpnum) {\n if (grpnum === undefined) {\n grpnum = 0;\n }\n else {\n grpnum = Sk.builtin.asnum$(grpnum);\n }\n if (grpnum >= self.thematch.v.length) {\n throw new Sk.builtin.IndexError(\"Index out of range: \" + grpnum);\n }\n return self.thematch.v[grpnum]\n });\n\n }\n\n mod.MatchObject = Sk.misceval.buildClass(mod, matchobj, 'MatchObject', []);\n\n // Internal function to return a Python list of strings \n // From a JS regular expression string\n mod._findre = function (res, string) {\n res = res.replace(/([^\\\\]){,(?![^\\[]*\\])/g, '$1{0,');\n var re = eval(res);\n var patt = new RegExp('\\n$');\n if (string.v.match(patt)) {\n var matches = string.v.slice(0, -1).match(re);\n }\n else {\n var matches = string.v.match(re);\n }\n retval = new Sk.builtin.list();\n if (matches == null) {\n return retval;\n }\n for (var i = 0; i < matches.length; ++i) {\n var sitem = new Sk.builtin.str(matches[i]);\n retval.v.push(sitem);\n }\n return retval;\n }\n\n mod.search = new Sk.builtin.func(function (pattern, string, flags) {\n Sk.builtin.pyCheckArgs('search', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n }\n ;\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n }\n ;\n if (flags === undefined) {\n flags = 0;\n }\n ;\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n }\n ;\n var res = \"/\" + pattern.v.replace(/\\//g, \"\\\\/\") + \"/\";\n lst = mod._findre(res, string);\n if (lst.v.length < 1) {\n return Sk.builtin.none.none$;\n }\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n mod.match = new Sk.builtin.func(function (pattern, string, flags) {\n Sk.builtin.pyCheckArgs('match', arguments, 2, 3);\n if (!Sk.builtin.checkString(pattern)) {\n throw new Sk.builtin.TypeError(\"pattern must be a string\");\n }\n ;\n if (!Sk.builtin.checkString(string)) {\n throw new Sk.builtin.TypeError(\"string must be a string\");\n }\n ;\n if (flags === undefined) {\n flags = 0;\n }\n ;\n if (!Sk.builtin.checkNumber(flags)) {\n throw new Sk.builtin.TypeError(\"flags must be a number\");\n }\n ;\n var res = \"/^\" + pattern.v.replace(/\\//g, \"\\\\/\") + \"/\";\n lst = mod._findre(res, string);\n if (lst.v.length < 1) {\n return Sk.builtin.none.none$;\n }\n var mob = Sk.misceval.callsim(mod.MatchObject, lst, pattern, string);\n return mob;\n });\n\n return mod;\n}\n", "src/lib/locale.py": "raise NotImplementedError(\"locale is not yet implemented in Skulpt\")\n", "src/lib/ast.py": "raise NotImplementedError(\"ast is not yet implemented in Skulpt\")\n", "src/lib/doctest.py": "raise NotImplementedError(\"doctest is not yet implemented in Skulpt\")\n", "src/lib/new.py": "raise NotImplementedError(\"new is not yet implemented in Skulpt\")\n", "src/lib/getpass.py": "raise NotImplementedError(\"getpass is not yet implemented in Skulpt\")\n", "src/lib/dumbdbm.py": "raise NotImplementedError(\"dumbdbm is not yet implemented in Skulpt\")\n", "src/lib/pickle.py": "raise NotImplementedError(\"pickle is not yet implemented in Skulpt\")\n", "src/lib/pty.py": "raise NotImplementedError(\"pty is not yet implemented in Skulpt\")\n", "src/lib/dummy_thread.py": "raise NotImplementedError(\"dummy_thread is not yet implemented in Skulpt\")\n", "src/lib/whichdb.py": "raise NotImplementedError(\"whichdb is not yet implemented in Skulpt\")\n", "src/lib/contextlib.py": "raise NotImplementedError(\"contextlib is not yet implemented in Skulpt\")\n", "src/lib/sunau.py": "raise NotImplementedError(\"sunau is not yet implemented in Skulpt\")\n", "src/lib/__future__.py": "raise NotImplementedError(\"__future__ is not yet implemented in Skulpt\")\n", "src/lib/shelve.py": "raise NotImplementedError(\"shelve is not yet implemented in Skulpt\")\n", "src/lib/collections.js": "var $builtinmodule = function (name) {\n\n var mod = {};\n\n // defaultdict object\n\n mod.defaultdict = function defaultdict(default_, args) {\n if (!(this instanceof mod.defaultdict)) {\n return new mod.defaultdict(default_, args);\n }\n\n Sk.abstr.superConstructor(mod.defaultdict, this, args);\n\n if (default_ === undefined) {\n this.default_factory = Sk.builtin.none.none$;\n }\n else {\n if (!Sk.builtin.checkCallable(default_) && !(default_ instanceof Sk.builtin.none)) {\n throw new Sk.builtin.TypeError(\"first argument must be callable\");\n }\n this.default_factory = default_;\n }\n\n if (this['$d']) {\n this['$d']['default_factory'] = this.default_factory;\n }\n else {\n this['$d'] = {'default_factory': this.default_factory};\n }\n\n return this;\n };\n\n Sk.abstr.setUpInheritance(\"defaultdict\", mod.defaultdict, Sk.builtin.dict);\n\n mod.defaultdict.prototype['$r'] = function () {\n var def_str = Sk.misceval.objectRepr(this.default_factory).v;\n var dict_str = Sk.builtin.dict.prototype['$r'].call(this).v;\n return new Sk.builtin.str(\"defaultdict(\" + def_str + \", \" + dict_str + \")\");\n };\n\n mod.defaultdict.prototype['__missing__'] = function (key) {\n Sk.builtin.pyCheckArgs('__missing__', arguments, 0, 1);\n if (key) {\n throw new Sk.builtin.KeyError(Sk.misceval.objectRepr(key));\n }\n else {\n return Sk.misceval.callsim(this.default_factory);\n }\n };\n\n mod.defaultdict.prototype.mp$subscript = function (key) {\n try {\n return Sk.builtin.dict.prototype.mp$subscript.call(this, key);\n }\n catch (e) {\n if (this.default_factory instanceof Sk.builtin.none) {\n return this.__missing__(key);\n }\n else {\n ret = this.__missing__();\n this.mp$ass_subscript(key, ret);\n return ret;\n }\n }\n };\n\n // Counter object\n\n mod.Counter = function Counter(iter_or_map) {\n if (!(this instanceof mod.Counter)) {\n return new mod.Counter(iter_or_map);\n }\n\n\n if (iter_or_map instanceof Sk.builtin.dict || iter_or_map === undefined) {\n Sk.abstr.superConstructor(mod.Counter, this, iter_or_map);\n\n }\n else {\n if (!(Sk.builtin.checkIterable(iter_or_map))) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(iter_or_map) + \"' object is not iterable\");\n }\n\n Sk.abstr.superConstructor(mod.Counter, this);\n var one = new Sk.builtin.int_(1);\n\n for (var iter = iter_or_map.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n var count = this.mp$subscript(k);\n count = count.nb$add(one);\n this.mp$ass_subscript(k, count);\n }\n }\n\n return this;\n };\n\n Sk.abstr.setUpInheritance(\"Counter\", mod.Counter, Sk.builtin.dict);\n\n mod.Counter.prototype['$r'] = function () {\n var dict_str = this.size > 0 ? Sk.builtin.dict.prototype['$r'].call(this).v : '';\n return new Sk.builtin.str('Counter(' + dict_str + ')');\n };\n\n mod.Counter.prototype.mp$subscript = function (key) {\n try {\n return Sk.builtin.dict.prototype.mp$subscript.call(this, key);\n }\n catch (e) {\n return new Sk.builtin.int_(0);\n }\n };\n\n mod.Counter.prototype['elements'] = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs('elements', arguments, 1, 1);\n var all_elements = [];\n for (var iter = self.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n for (var i = 0; i < self.mp$subscript(k).v; i++) {\n all_elements.push(k);\n }\n }\n\n var ret =\n {\n tp$iter: function () {\n return ret;\n },\n $obj: this,\n $index: 0,\n $elem: all_elements,\n tp$iternext: function () {\n if (ret.$index >= ret.$elem.length) {\n return undefined;\n }\n return ret.$elem[ret.$index++];\n }\n };\n\n return ret;\n\n });\n\n mod.Counter.prototype['most_common'] = new Sk.builtin.func(function (self, n) {\n Sk.builtin.pyCheckArgs('most_common', arguments, 1, 2);\n var length = self.mp$length();\n\n if (n === undefined) {\n n = length;\n }\n else {\n if (!Sk.builtin.checkInt(n)) {\n if (n instanceof Sk.builtin.float_) {\n throw new Sk.builtin.TypeError(\"integer argument expected, got float\");\n }\n else {\n throw new Sk.builtin.TypeError(\"an integer is required\");\n }\n }\n\n n = Sk.builtin.asnum$(n);\n n = n <= length ? n : length;\n n = n >= 0 ? n : 0;\n }\n\n var most_common_elem = [];\n for (var iter = self.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n most_common_elem.push([k, self.mp$subscript(k)]);\n }\n\n var sort_func = function (a, b) {\n if (a[1].v < b[1].v) {\n return 1;\n } else if (a[1].v > b[1].v) {\n return -1;\n } else {\n return 0;\n }\n };\n most_common_elem = most_common_elem.sort(sort_func);\n\n var ret = [];\n for (var i = 0; i < n; i++) {\n ret.push(new Sk.builtin.tuple(most_common_elem.shift()));\n }\n\n return new Sk.builtin.list(ret);\n });\n\n mod.Counter.prototype['update'] = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs('update', arguments, 1, 2);\n\n if (other instanceof Sk.builtin.dict) {\n for (var iter = other.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n var count = self.mp$subscript(k);\n self.mp$ass_subscript(k, count.nb$add(other.mp$subscript(k)));\n }\n }\n else if (other !== undefined) {\n if (!Sk.builtin.checkIterable(other)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(other) + \"' object is not iterable\");\n }\n\n var one = new Sk.builtin.int_(1);\n for (var iter = other.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n var count = self.mp$subscript(k);\n self.mp$ass_subscript(k, count.nb$add(one));\n }\n }\n });\n\n mod.Counter.prototype['subtract'] = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs('subtract', arguments, 1, 2);\n\n if (other instanceof Sk.builtin.dict) {\n for (var iter = other.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n var count = self.mp$subscript(k);\n self.mp$ass_subscript(k, count.nb$subtract(other.mp$subscript(k)));\n }\n }\n else if (other !== undefined) {\n if (!Sk.builtin.checkIterable(other)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(other) + \"' object is not iterable\");\n }\n\n var one = new Sk.builtin.int_(1);\n for (var iter = other.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n var count = self.mp$subscript(k);\n self.mp$ass_subscript(k, count.nb$subtract(one));\n }\n }\n });\n\n\n // OrderedDict\n mod.OrderedDict = function OrderedDict(items)\n {\n if (!(this instanceof mod.OrderedDict))\n {\n return new mod.OrderedDict(items);\n }\n\n this.orderedkeys = [];\n\n Sk.abstr.superConstructor(mod.OrderedDict, this, items);\n\n return this;\n }\n\n Sk.abstr.setUpInheritance(\"OrderedDict\", mod.OrderedDict, Sk.builtin.dict);\n\n mod.OrderedDict.prototype['$r'] = function()\n {\n var v;\n var iter, k;\n var ret = [];\n var pairstr;\n for (iter = this.tp$iter(), k = iter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext()) {\n v = this.mp$subscript(k);\n if (v === undefined) {\n //print(k, \"had undefined v\");\n v = null;\n }\n ret.push(\"(\" + Sk.misceval.objectRepr(k).v + \", \" + Sk.misceval.objectRepr(v).v + \")\");\n }\n pairstr = ret.join(\", \");\n if (ret.length > 0)\n {\n pairstr = \"[\" + pairstr + \"]\";\n }\n return new Sk.builtin.str(\"OrderedDict(\" + pairstr + \")\");\n }\n\n mod.OrderedDict.prototype.mp$ass_subscript = function(key, w)\n {\n var idx = this.orderedkeys.indexOf(key);\n if (idx == -1)\n {\n this.orderedkeys.push(key);\n }\n\n return Sk.builtin.dict.prototype.mp$ass_subscript.call(this, key, w);\n }\n\n mod.OrderedDict.prototype.mp$del_subscript = function(key)\n {\n var idx = this.orderedkeys.indexOf(key);\n if (idx != -1)\n {\n this.orderedkeys.splice(idx, 1);\n }\n\n return Sk.builtin.dict.prototype.mp$del_subscript.call(this, key);\n }\n\n mod.OrderedDict.prototype.__iter__ = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs(\"__iter__\", arguments, 0, 0, false, true);\n\n return mod.OrderedDict.prototype.tp$iter.call(self);\n });\n\n mod.OrderedDict.prototype.tp$iter = function()\n {\n var ret;\n ret =\n {\n tp$iter : function () {\n return ret;\n },\n $obj : this,\n $index : 0,\n $keys : this.orderedkeys.slice(0),\n tp$iternext: function () {\n // todo; StopIteration\n if (ret.$index >= ret.$keys.length) {\n return undefined;\n }\n return ret.$keys[ret.$index++];\n }\n };\n return ret;\n }\n\n mod.OrderedDict.prototype.ob$eq = function (other) {\n var l;\n var otherl;\n var iter;\n var k;\n var v;\n\n if (!(other instanceof mod.OrderedDict))\n {\n return Sk.builtin.dict.prototype.ob$eq.call(this, other);\n }\n\n l = this.mp$length();\n otherl = other.mp$length();\n\n if (l !== otherl) {\n return Sk.builtin.bool.false$;\n }\n\n for (iter = this.tp$iter(), otheriter = other.tp$iter(),\n k = iter.tp$iternext(), otherk = otheriter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext(), otherk = otheriter.tp$iternext()) \n {\n if (!Sk.misceval.isTrue(Sk.misceval.richCompareBool(k, otherk, \"Eq\")))\n {\n return Sk.builtin.bool.false$;\n }\n v = this.mp$subscript(k);\n otherv = other.mp$subscript(otherk);\n\n if (!Sk.misceval.isTrue(Sk.misceval.richCompareBool(v, otherv, \"Eq\"))) {\n return Sk.builtin.bool.false$;\n }\n }\n\n return Sk.builtin.bool.true$;\n };\n\n mod.OrderedDict.prototype.ob$ne = function (other) {\n var l;\n var otherl;\n var iter;\n var k;\n var v;\n\n if (!(other instanceof mod.OrderedDict))\n {\n return Sk.builtin.dict.prototype.ob$ne.call(this, other);\n }\n\n l = this.size;\n otherl = other.size;\n\n if (l !== otherl) {\n return Sk.builtin.bool.true$;\n }\n\n for (iter = this.tp$iter(), otheriter = other.tp$iter(),\n k = iter.tp$iternext(), otherk = otheriter.tp$iternext();\n k !== undefined;\n k = iter.tp$iternext(), otherk = otheriter.tp$iternext()) \n {\n if (!Sk.misceval.isTrue(Sk.misceval.richCompareBool(k, otherk, \"Eq\")))\n {\n return Sk.builtin.bool.true$;\n }\n v = this.mp$subscript(k);\n otherv = other.mp$subscript(otherk);\n\n if (!Sk.misceval.isTrue(Sk.misceval.richCompareBool(v, otherv, \"Eq\"))) {\n return Sk.builtin.bool.true$;\n }\n }\n\n return Sk.builtin.bool.false$;\n };\n\n mod.OrderedDict.prototype[\"pop\"] = new Sk.builtin.func(function (self, key, d) {\n var s;\n var idx;\n\n Sk.builtin.pyCheckArgs('pop', arguments, 2, 3);\n\n idx = self.orderedkeys.indexOf(key);\n if (idx != -1)\n {\n self.orderedkeys.splice(idx, 1);\n }\n\n return Sk.misceval.callsim(Sk.builtin.dict.prototype[\"pop\"], self, key, d);\n });\n\n mod.OrderedDict.prototype[\"popitem\"] = new Sk.builtin.func(function (self, last) {\n var key, val;\n var s;\n\n Sk.builtin.pyCheckArgs('popitem', arguments, 1, 2);\n\n // Empty dictionary\n if (self.orderedkeys.length == 0)\n {\n s = new Sk.builtin.str('dictionary is empty');\n throw new Sk.builtin.KeyError(s.v);\n }\n\n key = self.orderedkeys[0];\n if (last === undefined || Sk.misceval.isTrue(last))\n {\n key = self.orderedkeys[self.orderedkeys.length - 1];\n }\n\n val = Sk.misceval.callsim(self[\"pop\"], self, key);\n return Sk.builtin.tuple([key, val]);\n });\n\n // deque\n mod.deque = function deque(iterable, maxlen) {\n throw new Sk.builtin.NotImplementedError(\"deque is not implemented\")\n };\n\n // namedtuple\n mod.namedtuples = {};\n var keywds = Sk.importModule(\"keyword\", false, false);\n // should cover most things. Does not:\n // * keyword args\n // _make\n // _replace\n // _asdict\n // _fields\n\n\n var hasDupes = function(a) {\n var counts = [];\n for(var i = 0; i <= a.length; i++) {\n if(counts[a[i]] === undefined) {\n counts[a[i]] = 1;\n } else {\n return true;\n }\n }\n return false;\n }\n\n var Skinherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {};\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n };\n\n mod.namedtuple = function (name, fields) {\n if (Sk.ffi.remapToJs(Sk.misceval.callsim(keywds.$d['iskeyword'],name ))) {\n throw new Sk.builtin.ValueError(\"Type names and field names cannot be a keyword: \" + name.v);\n }\n var nm = Sk.ffi.remapToJs(name);\n startsw = new RegExp(/^[0-9].*/);\n startsw2 = new RegExp(/^[0-9_].*/);\n alnum = new RegExp(/^\\w*$/);\n if (startsw.test(nm) || (! alnum.test(nm))) {\n throw new Sk.builtin.ValueError(\" Bad type name \" + nm);\n }\n // fields could be a string or a tuple or list of strings\n var flds = Sk.ffi.remapToJs(fields);\n\n if (typeof(flds) === 'string') {\n flds = flds.split(/\\s+/);\n }\n // import the keyword module here and use iskeyword\n for (i = 0; i < flds.length; i++) {\n if (Sk.ffi.remapToJs(Sk.misceval.callsim(keywds.$d['iskeyword'],Sk.ffi.remapToPy(flds[i]))) ||\n startsw2.test(flds[i]) || (! alnum.test(flds[i]))\n ) {\n throw new Sk.builtin.ValueError(\"Type names and field names cannot be a keyword: \" + flds[i]);\n }\n }\n if (hasDupes(flds)) {\n throw new Sk.builtin.ValueError(\"Field names must be unique.\");\n }\n\n var cons = function nametuple_constructor() {\n var o;\n if (arguments.length !== flds.length ) {\n throw new Sk.builtin.TypeError(\"Number of arguments must match\");\n }\n if (!(this instanceof mod.namedtuples[nm])) {\n o = Object.create(mod.namedtuples[nm].prototype);\n o.constructor.apply(o, arguments);\n return o;\n }\n this.__class__ = mod.namedtuples[nm];\n this.v = Array.prototype.slice.call(arguments);\n };\n mod.namedtuples[nm] = cons;\n\n Skinherits(cons, Sk.builtin.tuple);\n cons.prototype.tp$name = nm;\n cons.prototype.ob$type = Sk.builtin.type.makeIntoTypeObj(nm, mod.namedtuples[nm]);\n cons.prototype[\"$r\"] = function () {\n var ret;\n var i;\n var bits;\n if (this.v.length === 0) {\n return new Sk.builtin.str(nm + \"()\");\n }\n bits = [];\n for (i = 0; i < this.v.length; ++i) {\n bits[i] = flds[i] + \"=\" + Sk.misceval.objectRepr(this.v[i]).v;\n }\n ret = bits.join(\", \");\n if (this.v.length === 1) {\n ret += \",\";\n }\n return new Sk.builtin.str(nm + \"(\" + ret + \")\");\n };\n\n cons.prototype.tp$getattr = function (name) {\n var i = flds.indexOf(name);\n if (i >= 0) {\n return this.v[i];\n }\n return undefined;\n };\n\n cons.prototype.tp$setattr = function (name, value) {\n throw new Sk.builtin.AttributeError(\"can't set attribute\");\n };\n\n return cons;\n };\n\n return mod;\n};\n", "src/lib/httplib.py": "raise NotImplementedError(\"httplib is not yet implemented in Skulpt\")\n", "src/lib/string.py": "raise NotImplementedError(\"string is not yet implemented in Skulpt\")\n", "src/lib/smtplib.py": "raise NotImplementedError(\"smtplib is not yet implemented in Skulpt\")\n", "src/lib/getopt.py": "raise NotImplementedError(\"getopt is not yet implemented in Skulpt\")\n", "src/lib/toaiff.py": "raise NotImplementedError(\"toaiff is not yet implemented in Skulpt\")\n", "src/lib/timeit.py": "raise NotImplementedError(\"timeit is not yet implemented in Skulpt\")\n", "src/lib/hmac.py": "raise NotImplementedError(\"hmac is not yet implemented in Skulpt\")\n", "src/lib/tarfile.py": "raise NotImplementedError(\"tarfile is not yet implemented in Skulpt\")\n", "src/lib/stringprep.py": "raise NotImplementedError(\"stringprep is not yet implemented in Skulpt\")\n", "src/lib/posixfile.py": "raise NotImplementedError(\"posixfile is not yet implemented in Skulpt\")\n", "src/lib/ssl.py": "raise NotImplementedError(\"ssl is not yet implemented in Skulpt\")\n", "src/lib/turtle.js": "var $builtinmodule = function (name) {\n\"use strict\";\n\nfunction getConfiguredTarget() {\n var selector, target;\n\n selector = (Sk.TurtleGraphics && Sk.TurtleGraphics.target) || \"turtle\",\n target = typeof selector === \"string\" ?\n document.getElementById(selector) :\n selector;\n // ensure that the canvas container is empty\n while (target.firstChild) {\n target.removeChild(target.firstChild);\n }\n return target;\n}\n\nfunction generateTurtleModule(_target) {\n var _module = {},\n _durationSinceRedraw = 0,\n _focus = true,\n OPTIMAL_FRAME_RATE = 1000/30,\n SHAPES = {},\n TURTLE_COUNT = 0,\n Types = {},\n _frameRequest,\n _frameRequestTimeout,\n _screenInstance,\n _config,\n _anonymousTurtle,\n _mouseHandler;\n\n // Ensure that the turtle DOM target has a tabindex\n // so that it can accept keyboard focus and events\n if (!_target.hasAttribute(\"tabindex\")) {\n _target.setAttribute(\"tabindex\", 0);\n }\n\n Types.FLOAT = function(value) {\n return Sk.builtin.float_(value);\n };\n Types.COLOR = function(value) {\n if (typeof value === \"string\") {\n return new Sk.builtin.str(value);\n }\n else {\n for(var i = 0; i < 3; i++) {\n value[i] = Sk.builtin.assk$(value[i]);\n }\n if (value.length === 4) {\n value[3] = Sk.builtin.float_(value[3]);\n }\n return new Sk.builtin.tuple(value);\n }\n };\n Types.TURTLE_LIST = function(value) {\n var skValues = [];\n for (var i = 0; i < value.length; i++) {\n skValues.push(value[i].skInstance);\n }\n return new Sk.builtin.tuple(skValues);\n };\n\n SHAPES.arrow = [[-10,0],[10,0],[0,10]];\n SHAPES.square = [[ 10,-10],[10,10],[-10,10],[-10, -10]];\n SHAPES.triangle = [[10,-5.77],[0,11.55],[-10,-5.77]];\n SHAPES.classic = [[0,0],[-5,-9],[0,-7],[5,-9]];\n SHAPES.turtle = [\n [0,16],[-2,14],[-1,10],[-4,7],[-7,9],[-9,8],[-6,5],[-7,1],[-5,-3],[-8,-6],\n [-6,-8],[-4,-5],[0,-7],[4,-5],[6,-8],[8,-6],[5,-3],[7,1],[6,5],[9,8],[7,9],\n [4,7],[1,10],[2,14]\n ];\n\n SHAPES.circle = [\n [10,0],[9.51,3.09],[8.09,5.88],[5.88,8.09],[3.09,9.51],[0,10],[-3.09,9.51],\n [-5.88,8.09],[-8.09,5.88],[-9.51,3.09],[-10,0],[-9.51,-3.09],[-8.09,-5.88],\n [-5.88,-8.09],[-3.09,-9.51],[-0,-10],[3.09,-9.51],[5.88,-8.09],[8.09,-5.88],\n [9.51,-3.09]\n ];\n\n _config = (function() {\n var defaultSetup = {\n target : \"turtle\", // DOM element or id of parent container\n width : 400, // if set to 0 it will use the target width\n height : 400, // if set to 0 it will use the target height\n animate : true, // enabled/disable all animated rendering\n bufferSize : 0, // default turtle buffer size\n allowUndo : true, // enable ability to use the undo buffer\n },\n key;\n\n if (!Sk.TurtleGraphics) {\n Sk.TurtleGraphics = {};\n }\n\n for(key in defaultSetup) {\n if (!Sk.TurtleGraphics.hasOwnProperty(key)) {\n Sk.TurtleGraphics[key] = defaultSetup[key];\n }\n }\n\n return Sk.TurtleGraphics;\n })();\n\n // InstantPromise is a workaround to allow usage of the clean promise-style\n // then/catch syntax but to instantly call resolve the then/catch chain so we\n // can avoid creating Suspensions in unnecessary cases. This is desirable\n // because Suspensions have a fairly large negative impact on overall\n // performance. These 'instant promises' come into play when a tracer()\n // call is made with a value other than 1. When tracer is 0 or greater than 1\n // , we can bypass the creation of a Suspension and proceed to the next line of\n // code immediately if the current line is not going to incur involve a screen\n // update. We determine if a real promise or InstantPromise is necessary by\n // checking FrameManager.willRenderNext()\n function InstantPromise() {\n this.lastResult = undefined;\n this.lastError = undefined;\n }\n\n InstantPromise.prototype.then = function(cb) {\n if (this.lastError) {\n return this;\n }\n\n try {\n this.lastResult = cb(this.lastResult);\n } catch(e) {\n this.lastResult = undefined;\n this.lastError = e;\n }\n\n return this.lastResult instanceof Promise ? this.lastResult : this;\n };\n\n InstantPromise.prototype.catch = function(cb) {\n if (this.lastError) {\n try {\n this.lastResult = cb(this.lastError);\n this.lastError = undefined;\n } catch(e) {\n this.lastResult = undefined;\n this.lastError = e;\n }\n }\n\n return this.lastResult instanceof Promise ? this.lastResult : this;\n };\n\n function FrameManager() {\n this.reset();\n }\n\n var _frameManager;\n function getFrameManager() {\n if (!_frameManager) {\n _frameManager = new FrameManager();\n }\n return _frameManager;\n }\n\n (function(proto) {\n var browserFrame;\n (function(frame) {\n if (frame) {\n browserFrame = function(method) {\n return (_frameRequest = frame(method));\n };\n }\n })(window.requestAnimationFrame || window.mozRequestAnimationFrame);\n\n function animationFrame(delay) {\n if (!_config.animate) {\n return function(method) {\n method();\n };\n }\n\n if (!delay && browserFrame) {\n return browserFrame;\n }\n\n return function(method) {\n _frameRequestTimeout = window.setTimeout(\n method,\n delay || OPTIMAL_FRAME_RATE\n );\n return _frameRequestTimeout;\n };\n }\n\n proto.willRenderNext = function() {\n return !!(this._buffer && this._frameCount+1 === this.frameBuffer());\n };\n\n proto.turtles = function() {\n return this._turtles;\n };\n\n proto.addTurtle = function(turtle) {\n this._turtles.push(turtle);\n };\n\n proto.reset = function() {\n if (this._turtles) {\n for(var i = this._turtles.length; --i >= 0;) {\n this._turtles[i].reset();\n }\n }\n this._turtles = [];\n this._frames = [];\n this._frameCount = 0;\n this._buffer = 1;\n this._rate = 0;\n this._animationFrame = animationFrame();\n };\n\n proto.addFrame = function(method, countAsFrame) {\n var instant = false;\n\n if (countAsFrame) {\n this._frameCount += 1;\n }\n\n this.frames().push(method);\n\n instant = (\n !_config.animate ||\n (this._buffer && this._frameCount === this.frameBuffer())\n );\n\n return instant ? this.update() : new InstantPromise();\n };\n\n proto.frames = function() {\n return this._frames;\n };\n\n proto.frameBuffer = function(buffer) {\n if (typeof buffer === \"number\") {\n this._buffer = buffer | 0;\n if (buffer && buffer <= this._frameCount) {\n return this.update();\n }\n }\n return this._buffer;\n };\n\n proto.refreshInterval = function(rate) {\n if (typeof rate === \"number\") {\n this._rate = rate | 0;\n this._animationFrame = animationFrame(rate);\n }\n return this._rate;\n };\n\n proto.update = function() {\n return (this._frames && this._frames.length) ?\n this.requestAnimationFrame() :\n new InstantPromise();\n };\n\n proto.requestAnimationFrame = function() {\n var frames = this._frames,\n animationFrame = this._animationFrame,\n turtles = this._turtles,\n sprites = getScreen().spriteLayer(),\n turtle, i;\n\n this._frames = [];\n this._frameCount = 0;\n\n return new Promise(function(resolve) {\n animationFrame(function paint() {\n for (i = 0; i < frames.length; i++) {\n if (frames[i]) {\n frames[i]();\n }\n }\n clearLayer(sprites);\n for (i = 0; i < turtles.length; i++) {\n turtle = turtles[i];\n if (turtle.getState().shown) {\n drawTurtle(turtle.getState(), sprites);\n }\n }\n resolve();\n });\n });\n };\n })(FrameManager.prototype);\n\n function MouseHandler() {\n var self = this;\n\n this._target = getTarget();\n this._managers = {};\n this._handlers = {\n mousedown : function(e) {\n self.onEvent(\"mousedown\", e);\n },\n mouseup : function(e) {\n self.onEvent(\"mouseup\", e);\n },\n mousemove : function(e) {\n self.onEvent(\"mousemove\", e);\n }\n };\n for (var key in this._handlers) {\n this._target.addEventListener(key, this._handlers[key]);\n }\n }\n\n (function(proto) {\n proto.onEvent = function(type, e) {\n var managers = this._managers[type],\n moveManagers = this._managers[\"mousemove\"],\n computed = false,\n x, y, localX, localY, i;\n\n function computeCoordinates() {\n if (computed) return;\n var world = getScreen();\n var rect = world.spriteLayer().canvas.getBoundingClientRect();\n x = e.clientX - rect.left | 0;\n y = e.clientY - rect.top | 0;\n localX = x * world.xScale + world.llx;\n localY = y * world.yScale + world.ury;\n computed = true;\n }\n\n if ((type === \"mousedown\" || type === \"mouseup\") && moveManagers && moveManagers.length) {\n computeCoordinates();\n for (i = moveManagers.length; --i >= 0;) {\n if (moveManagers[i].test(x, y, localX, localY)) {\n moveManagers[i].canMove(type === \"mousedown\");\n }\n }\n }\n\n if (managers && managers.length) {\n computeCoordinates();\n for (i = managers.length; --i >= 0;) {\n if (type === \"mousemove\") {\n if (managers[i].canMove()) {\n managers[i].trigger([localX, localY]);\n }\n continue;\n }\n\n if (managers[i].test(x, y, localX, localY)) {\n managers[i].trigger([localX, localY]);\n }\n }\n }\n };\n\n proto.reset = function() {\n this._managers = {};\n };\n\n proto.addManager = function(type, manager) {\n if (!this._managers[type]) {\n this._managers[type] = [];\n }\n\n this._managers[type].push(manager);\n };\n\n })(MouseHandler.prototype);\n\n function EventManager(type, target) {\n this._type = type;\n this._target = target;\n this._handlers = undefined;\n getMouseHandler().addManager(type, this);\n }\n\n (function(proto) {\n proto.reset = function() {\n this._handlers = undefined;\n };\n\n proto.canMove = function(value) {\n if (!this._target || !this._target.hitTest) return false;\n\n if (value !== undefined) {\n this._target.hitTest.hit = value;\n }\n\n return this._target.hitTest.hit;\n };\n\n proto.test = function(x, y, localX, localY) {\n return this._target && this._target.hitTest ?\n this._target.hitTest(x, y, localX, localY) :\n !!this._target;\n };\n\n proto.trigger = function(args) {\n var handlers = this._handlers,\n i;\n\n if (handlers && handlers.length) {\n for (i = 0; i < handlers.length; i++) {\n handlers[i].apply({}, args);\n }\n }\n };\n\n proto.addHandler = function(handler, add) {\n var handlers = this._handlers;\n\n if (!add && handlers && handlers.length) {\n // remove all existing handlers\n while (handlers.shift()) {/* noop */}\n }\n\n if (typeof handler !== \"function\") {\n if (handlers && !handlers.length) {\n this.reset();\n }\n return;\n }\n\n if (!handlers) {\n handlers = this._handlers = [];\n }\n\n handlers.push(handler);\n };\n })(EventManager.prototype);\n\n function Turtle() {\n getFrameManager().addTurtle(this);\n this._screen = getScreen();\n this._managers = {};\n this.reset();\n }\n\n Turtle.RADIANS = 2 * Math.PI;\n\n (function(proto) {\n proto.hitTest = function(mouseX, mouseY, localX, localY) {\n var context = getScreen().hitTestLayer();\n clearLayer(context);\n drawTurtle(this.getState(), context);\n var pixel = context.getImageData(mouseX,mouseY,1,1).data;\n // check alpha first since it is most likely to have a value\n return pixel[3] ||pixel[0] || pixel[1] || pixel[2];\n };\n\n proto.addUpdate = function(method, countAsFrame, stateChanges) {\n var self = this,\n state = this.getState(),\n args = Array.prototype.slice.call(arguments, stateChanges ? 2 : 3);\n\n return getFrameManager().addFrame(function() {\n if (method) {\n method.apply(state, args);\n }\n if (stateChanges) {\n for(var key in stateChanges) {\n state[key] = stateChanges[key];\n }\n }\n }, countAsFrame);\n };\n\n proto.getState = function() {\n var self = this;\n\n if (!this._state) {\n this._state = {\n x : this._x,\n y : this._y,\n angle : this._angle,\n radians : this._radians,\n shape : this._shape,\n color : this._color,\n fill : this._fill,\n filling : this._filling,\n size : this._size,\n speed : this._computed_speed,\n down : this._down,\n shown : this._shown,\n context : function() {\n return self.getPaper();\n }\n };\n }\n return this._state;\n };\n\n proto.translate = function(startX, startY, dx, dy, beginPath, isCircle) {\n var self = this;\n return translate(this, startX, startY, dx, dy, beginPath, isCircle)\n .then(function(coords) {\n self._x = coords[0];\n self._y = coords[1];\n });\n };\n\n proto.rotate = function(startAngle, delta, isCircle) {\n var self = this;\n return rotate(this, startAngle, delta, isCircle)\n .then(function(heading) {\n self._angle = heading.angle;\n self._radians = heading.radians;\n });\n };\n\n proto.queueMoveBy = function(startX, startY, theta, distance) {\n var dx = Math.cos(theta) * distance,\n dy = Math.sin(theta) * distance;\n\n return this.translate(startX, startY, dx, dy, true);\n };\n\n proto.queueTurnTo = function(startAngle, endAngle) {\n endAngle = endAngle % this._fullCircle;\n if (endAngle < 0) {\n endAngle += this._fullCircle;\n }\n return this.rotate(startAngle, endAngle - startAngle);\n };\n\n proto.getManager = function(type) {\n if (!this._managers[type]) {\n this._managers[type] = new EventManager(type, this);\n }\n return this._managers[type];\n };\n\n proto.getPaper = function() {\n return this._paper || (this._paper = createLayer(2));\n };\n\n proto.reset = function() {\n this._x = 0;\n this._y = 0;\n this._radians = 0;\n this._angle = 0;\n this._shown = true;\n this._down = true;\n this._color = \"black\";\n this._fill = \"black\";\n this._shape = \"classic\";\n this._size = 1;\n this._filling = false;\n this._undoBuffer = [];\n this._speed = 3;\n this._computed_speed = 5;\n this._state = undefined;\n\n for(var key in this._managers) {\n this._managers[key].reset();\n }\n\n this._isRadians = false;\n this._fullCircle = 360;\n this._bufferSize = typeof _config.bufferSize === \"number\" ?\n _config.bufferSize :\n 0;\n\n removeLayer(this._paper);\n this._paper = undefined;\n };\n\n proto.$degrees = function(fullCircle) {\n fullCircle = (typeof fullCircle === \"number\") ?\n Math.abs(fullCircle) :\n 360;\n\n this._isRadians = false;\n if (!fullCircle || !this._fullCircle) {\n this._angle = this._radians = 0;\n }\n else {\n this._angle = this._angle / this._fullCircle * fullCircle;\n }\n this._fullCircle = fullCircle;\n return this.addUpdate(\n undefined,\n false,\n {angle:this._angle, radians: this._radians}\n );\n };\n proto.$degrees.minArgs = 0;\n proto.$degrees.keywordArgs = [\"fullcircle\"];\n proto.$degrees.returnType = Types.FLOAT;\n\n proto.$radians = function() {\n if (!this._isRadians) {\n this._isRadians = true;\n this._angle = this._radians;\n this._fullCircle = Turtle.RADIANS;\n }\n\n return this._angle;\n };\n proto.$radians.returnType = Types.FLOAT;\n\n proto.$position = proto.$pos = function() {\n return [this.$xcor(), this.$ycor()];\n };\n proto.$position.returnType = function(value) {\n return new Sk.builtin.tuple([\n Sk.builtin.float_(value[0]),\n Sk.builtin.float_(value[1])\n ]);\n };\n\n proto.$towards = function(x,y) {\n var coords = getCoordinates(x,y),\n radians = Math.PI + Math.atan2(this._y - coords.y, this._x - coords.x),\n angle = radians * (this._fullCircle / Turtle.RADIANS);\n\n return angle;\n };\n proto.$towards.minArgs = 1;\n proto.$towards.returnType = Types.FLOAT;\n\n proto.$distance = function(x,y) {\n var coords = getCoordinates(x,y),\n dx = coords.x - this._x,\n dy = coords.y - this._y;\n\n return Math.sqrt(dx * dx + dy * dy);\n };\n proto.$distance.minArgs = 1;\n proto.$distance.returnType = Types.FLOAT;\n\n proto.$heading = function() {\n return Math.abs(this._angle) < 1e-13 ? 0 : this._angle;\n };\n proto.$heading.returnType = Types.FLOAT;\n\n proto.$xcor = function() {\n return Math.abs(this._x) < 1e-13 ? 0 : this._x;\n };\n proto.$xcor.returnType = Types.FLOAT;\n\n proto.$ycor = function() {\n return Math.abs(this._y) < 1e-13 ? 0 : this._y;\n };\n proto.$ycor.returnType = Types.FLOAT;\n\n proto.$forward = proto.$fd = function(distance) {\n pushUndo(this);\n return this.queueMoveBy(this._x, this._y, this._radians, distance);\n };\n\n proto.$undo = function() {\n popUndo(this);\n };\n\n proto.$undobufferentries = function() {\n return this._undoBuffer.length;\n };\n\n proto.$setundobuffer = function(size) {\n this._bufferSize = typeof size === \"number\" ?\n Math.min(Math.abs(size), 1000) :\n 0;\n };\n\n proto.$backward = proto.$back = proto.$bk = function(distance) {\n pushUndo(this);\n return this.queueMoveBy(this._x, this._y, this._radians, -distance);\n };\n\n proto.$goto_$rw$ = proto.$setpos = proto.$setposition = function(x,y) {\n var coords = getCoordinates(x,y);\n\n pushUndo(this);\n\n return this.translate(\n this._x, this._y,\n coords.x - this._x, coords.y - this._y,\n true\n );\n };\n proto.$goto_$rw$.minArgs = 1;\n\n proto.$setx = function(x) {\n return this.translate(this._x, this._y, x - this._x, 0, true);\n };\n\n proto.$sety = function(y) {\n return this.translate(this._x, this._y, 0, y - this._y, true);\n };\n\n proto.$home = function() {\n var self = this,\n angle = this._angle;\n\n pushUndo(this);\n return self.translate(this._x, this._y, -this._x, -this._y, true)\n .then(function(position) {\n return self.queueTurnTo(angle, 0);\n })\n .then(function(heading) {\n return undefined;\n });\n };\n\n proto.$right = proto.$rt = function(angle) {\n pushUndo(this);\n return this.rotate(this._angle, -angle);\n };\n\n proto.$left = proto.$lt = function(angle) {\n pushUndo(this);\n return this.rotate(this._angle, angle);\n };\n\n proto.$setheading = proto.$seth = function(angle) {\n pushUndo(this);\n return this.queueTurnTo(this._angle, angle);\n };\n\n function circleRotate(turtle, angle, radians) {\n return function() {\n return turtle.addUpdate(\n undefined,\n false,{angle:angle, radians:radians}\n );\n };\n }\n\n function circleSegment(turtle, x, y, dx, dy, beginPath) {\n return function() {\n return turtle.translate(x, y, dx, dy, beginPath, true);\n };\n }\n\n proto.$circle = function(radius, extent, steps) {\n var self = this,\n x = this._x,\n y = this._y,\n angle = this._angle,\n heading = {},\n states = [],\n scale = 1/getScreen().lineScale,\n beginPath = true,\n endAngle, frac, w, w2, l, i, dx, dy, promise;\n\n pushUndo(this);\n\n if (extent === undefined) {\n extent = self._fullCircle;\n }\n\n if (steps === undefined) {\n frac = Math.abs(extent)/self._fullCircle;\n steps = 1 + ((Math.min(11+Math.abs(radius*scale)/6, 59)*frac) | 0);\n }\n w = extent / steps;\n w2 = 0.5 * w;\n l = 2 * radius * Math.sin(w*Math.PI/self._fullCircle);\n\n if (radius < 0) {\n l = -l;\n w = -w;\n w2 = -w2;\n endAngle = angle - extent;\n }\n else {\n endAngle = angle + extent;\n }\n\n promise = getFrameManager().willRenderNext() ? Promise.resolve() : new InstantPromise();\n\n angle += w2;\n\n for(i = 0; i < steps; i++) {\n calculateHeading(self, angle + w * i, heading);\n dx = Math.cos(heading.radians) * l;\n dy = Math.sin(heading.radians) * l;\n promise = promise\n .then(circleRotate(self, heading.angle, heading.radians))\n .then(circleSegment(self, x, y, dx, dy, beginPath));\n x += dx;\n y += dy;\n beginPath = false;\n }\n\n promise = promise.then(function() {\n calculateHeading(self, endAngle, heading);\n self._angle = heading.angle;\n self._radians = heading.radians;\n return self.addUpdate(undefined, true, heading);\n });\n\n return promise;\n };\n proto.$circle.keywordArgs = [\"extent\", \"steps\"];\n proto.$circle.minArgs = 1;\n\n proto.$penup = proto.$up = proto.$pu = function() {\n this._down = false;\n return this.addUpdate(undefined, false, {down:false});\n };\n\n proto.$pendown = proto.$down = proto.$pd = function() {\n this._down = true;\n return this.addUpdate(undefined, false, {down:true});\n };\n\n proto.$isdown = function() {\n return this._down;\n };\n\n proto.$speed = function(speed) {\n if (arguments.length) {\n this._speed = Math.max(0, Math.min(1000, speed));\n this._computed_speed = Math.max(0, speed * 2 - 1);\n return this.addUpdate(undefined, false, {speed:this._computed_speed});\n }\n\n return this._speed;\n };\n proto.$speed.minArgs = 0;\n proto.$speed.keywordArgs = [\"speed\"];\n\n proto.$pencolor = function(r,g,b,a) {\n var color;\n\n if (arguments.length) {\n this._color = createColor(r,g,b,a);\n return this.addUpdate(undefined, this._shown, {color : this._color});\n }\n\n return hexToRGB(this._color);\n };\n proto.$pencolor.minArgs = 0;\n proto.$pencolor.returnType = Types.COLOR;\n\n proto.$fillcolor = function(r,g,b,a) {\n var color;\n\n if (arguments.length) {\n this._fill = createColor(r,g,b,a);\n return this.addUpdate(undefined, this._shown, {fill : this._fill});\n }\n\n return hexToRGB(this._fill);\n };\n proto.$fillcolor.minArgs = 0;\n proto.$fillcolor.returnType = Types.COLOR;\n\n proto.$color = function(color, fill, b, a) {\n if (arguments.length) {\n if (arguments.length === 1 || arguments.length >= 3) {\n this._color = createColor(color, fill, b, a);\n this._fill = this._color;\n }\n else {\n this._color = createColor(color);\n this._fill = createColor(fill);\n }\n return this.addUpdate(undefined, this._shown, {\n color : this._color,\n fill : this._fill\n });\n }\n return [this.$pencolor(), this.$fillcolor()];\n };\n proto.$color.minArgs = 0;\n proto.$color.returnType = function(value) {\n return new Sk.builtin.tuple([\n Types.COLOR(value[0]),\n Types.COLOR(value[1])\n ]);\n };\n\n proto.$fill = function(flag) {\n var self = this;\n\n if (flag !== undefined) {\n flag = !!flag;\n if (flag === this._filling) return;\n this._filling = flag;\n if (flag) {\n pushUndo(this);\n return this.addUpdate(undefined, false, {\n filling : true,\n fillBuffer : [{x : this._x, y : this._y}]\n });\n }\n else {\n pushUndo(this);\n return this.addUpdate(\n function() {\n this.fillBuffer.push(this);\n drawFill.call(this);\n },\n true,\n {\n filling : false,\n fillBuffer : undefined\n }\n );\n }\n }\n\n return this._filling;\n };\n proto.$fill.minArgs = 0;\n\n proto.$begin_fill = function() {\n return this.$fill(true);\n };\n\n proto.$end_fill = function() {\n return this.$fill(false);\n };\n\n proto.$stamp = function() {\n pushUndo(this);\n return this.addUpdate(function() {\n drawTurtle(this, this.context());\n }, true);\n };\n\n proto.$dot = function(size, color, g, b, a) {\n pushUndo(this);\n size = Sk.builtin.asnum$(size);\n size = (typeof size === \"number\") ?\n Math.max(1, Math.abs(size) | 0) :\n Math.max(this._size + 4, this._size * 2);\n\n color = (color !== undefined) ?\n createColor(color, g, b, a) :\n this._color;\n\n return this.addUpdate(drawDot, true, undefined, size, color);\n };\n\n proto.$write = function(message,move,align,font) {\n var self = this,\n promise, face, size, type, width;\n\n pushUndo(this);\n\n message = String(message);\n\n if (font && font.constructor === Array) {\n face = typeof font[0] === \"string\" ? font[0] : \"Arial\";\n size = String(font[1] || \"12pt\");\n type = typeof font[2] === \"string\" ? font[2] : \"normal\";\n if (/^\\d+$/.test(size)) {\n size += \"pt\";\n }\n\n font = [type, size, face].join(\" \");\n }\n\n if (!align) {\n align = \"left\";\n }\n\n promise = this.addUpdate(\n drawText, true, undefined, message, align, font\n );\n\n if (move && (align === \"left\" || align === \"center\")) {\n width = measureText(message, font);\n if (align === \"center\") {\n width = width/2;\n }\n promise = promise.then(function() {\n var state = self.getState();\n return self.translate(state.x, state.y, width, 0, true);\n });\n }\n\n return promise;\n };\n proto.$write.keywordArgs = [\"move\",\"align\",\"font\"];\n proto.$write.minArgs = 1;\n\n proto.$pensize = proto.$width = function(size) {\n if (arguments.length) {\n this._size = size;\n return this.addUpdate(undefined, this._shown, {size : size});\n }\n\n return this._size;\n };\n proto.$pensize.minArgs = proto.$width.minArgs = 0;\n proto.$pensize.keywordArgs = proto.$width.keywordArgs = [\"width\"];\n\n proto.$showturtle = proto.$st = function() {\n this._shown = true;\n return this.addUpdate(undefined, true, {shown : true});\n };\n\n proto.$hideturtle = proto.$ht = function() {\n this._shown = false;\n return this.addUpdate(undefined, true, {shown : false});\n };\n\n proto.$isvisible = function() {\n return this._shown;\n };\n\n proto.$shape = function(shape) {\n if (shape && SHAPES[shape]) {\n this._shape = shape;\n return this.addUpdate(undefined, this._shown, {shape : shape});\n }\n\n return this._shape;\n };\n proto.$shape.minArgs = 0;\n proto.$shape.keywordArgs = [\"name\"];\n\n proto.$window_width = function() {\n return this._screen.$window_width();\n };\n \n proto.$window_height = function() {\n return this._screen.$window_height();\n };\n \n proto.$tracer = function(n, delay) {\n return this._screen.$tracer(n, delay);\n };\n proto.$tracer.minArgs = 0;\n proto.$tracer.keywordArgs = [\"n\", \"delay\"];\n \n proto.$update = function() {\n return this._screen.$update();\n };\n \n proto.$delay = function(delay) {\n return this._screen.$delay(delay);\n };\n proto.$delay.minArgs = 0;\n proto.$delay.keywordArgs = [\"delay\"];\n\n proto.$reset = function() {\n this.reset();\n return this.$clear();\n };\n\n proto.$mainloop = proto.$done = function() {\n return this._screen.$mainloop();\n };\n\n proto.$clear = function() {\n return this.addUpdate(function() {\n clearLayer(this.context());\n }, true);\n };\n proto.$dot.minArgs = 0;\n\n proto.$onclick = function(method,btn,add) {\n this.getManager(\"mousedown\").addHandler(method, add);\n };\n proto.$onclick.minArgs = 1;\n proto.$onclick.keywordArgs = [\"btn\",\"add\"];\n\n proto.$onrelease = function(method,btn,add) {\n this.getManager(\"mouseup\").addHandler(method, add);\n };\n proto.$onrelease.minArgs = 1;\n proto.$onrelease.keywordArgs = [\"btn\",\"add\"];\n\n proto.$ondrag = function(method,btn,add) {\n this.getManager(\"mousemove\").addHandler(method, add);\n };\n proto.$ondrag.minArgs = 1;\n proto.$ondrag.keywordArgs = [\"btn\",\"add\"];\n\n proto.$getscreen = function() {\n return _module.Screen();\n };\n proto.$getscreen.isSk = true;\n\n proto.$clone = function() {\n\n var newTurtleInstance = Sk.misceval.callsimOrSuspend(_module.Turtle);\n\n // All the properties that are in getState()\n newTurtleInstance.instance._x = this._x;\n newTurtleInstance.instance._y = this._y;\n newTurtleInstance.instance._angle = this._angle;\n newTurtleInstance.instance._radians = this._radians;\n newTurtleInstance.instance._shape = this._shape;\n newTurtleInstance.instance._color = this._color;\n newTurtleInstance.instance._fill = this._fill;\n newTurtleInstance.instance._filling = this._filling;\n newTurtleInstance.instance._size = this._size;\n newTurtleInstance.instance._computed_speed = this._computed_speed;\n newTurtleInstance.instance._down = this._down;\n newTurtleInstance.instance._shown = this._shown;\n\n // Other properties to copy\n newTurtleInstance.instance._isRadians = this._isRadians;\n newTurtleInstance.instance._fullCircle = this._fullCircle;\n newTurtleInstance.instance._bufferSize = this._bufferSize;\n newTurtleInstance.instance._undoBuffer = this._undoBuffer;\n\n\n newTurtleInstance._clonedFrom = this;\n\n return newTurtleInstance;\n };\n proto.$clone.returnType = function(value) {\n // When I return the instance here, I'm not sure if it ends up with the right \"Turtle\" python type.\n return value\n };\n\n proto.$getturtle = proto.$getpen = function() {\n return this.skInstance;\n };\n proto.$getturtle.isSk = true;\n })(Turtle.prototype);\n\n function Screen() {\n var w,h;\n this._frames = 1;\n this._delay = undefined;\n this._bgcolor = \"none\";\n this._mode = \"standard\";\n this._managers = {};\n this._keyLogger = {};\n if (_config.height && _config.width) {\n w = _config.width/2;\n h = _config.height/2;\n } else {\n w = _config.defaultSetup.width/2;\n h = _config.defaultSetup.height/2;\n }\n this.setUpWorld(-w,-h,w,h);\n }\n\n (function(proto) {\n proto.spriteLayer = function() {\n return this._sprites || (this._sprites = createLayer(3));\n };\n\n proto.bgLayer = function() {\n return this._background || (this._background = createLayer(1));\n };\n\n proto.hitTestLayer = function() {\n return this._hitTest || (this._hitTest = createLayer(0,true));\n };\n\n proto.getManager = function(type) {\n if (!this._managers[type]) {\n this._managers[type] = new EventManager(type, this);\n }\n return this._managers[type];\n };\n\n proto.reset = function() {\n var key;\n\n this._keyListeners = undefined;\n\n for (key in this._keyLogger) {\n window.clearInterval(this._keyLogger[key]);\n window.clearTimeout(this._keyLogger[key]);\n delete this._keyLogger[key];\n }\n\n if (this._keyDownListener) {\n getTarget().removeEventListener(\"keydown\", this._keyDownListener);\n this._keyDownListener = undefined;\n }\n\n if (this._keyUpListener) {\n getTarget().removeEventListener(\"keyup\", this._keyUpListener);\n this._keyUpListener = undefined;\n }\n\n if (this._timer) {\n window.clearTimeout(this._timer);\n this._timer = undefined;\n }\n\n for(key in this._managers) {\n this._managers[key].reset();\n }\n\n this._mode = \"standard\";\n removeLayer(this._sprites);\n this._sprites = undefined;\n removeLayer(this._background);\n this._background = undefined;\n };\n\n proto.setUpWorld = function(llx, lly, urx, ury) {\n var world = this;\n\n world.llx = llx;\n world.lly = lly;\n world.urx = urx;\n world.ury = ury;\n world.xScale = (urx - llx) / getWidth();\n world.yScale = -1 * (ury - lly) / getHeight();\n world.lineScale = Math.min(Math.abs(world.xScale), Math.abs(world.yScale));\n };\n\n proto.$setup = function(width, height, startX, startY) {\n if (isNaN(parseFloat(width))) {\n width = getWidth();\n }\n if (isNaN(parseFloat(height))) {\n height = getHeight();\n }\n\n if (width <= 1) {\n width = getWidth() * width;\n }\n if (height <= 1) {\n height = getHeight() * height;\n }\n\n this._width = width;\n this._height = height;\n\n this._xOffset = (startX !== undefined && !isNaN(parseInt(startX))) ?\n parseInt(startX) :\n 0;\n\n this._yOffset = (startY !== undefined && !isNaN(parseInt(startY))) ?\n parseInt(startY) :\n 0;\n\n if (this._mode === \"world\") {\n return this._setworldcoordinates(this.llx, this.lly, this.urx, this.ury);\n }\n\n return this._setworldcoordinates(-width/2, -height/2, width/2, height/2);\n };\n proto.$setup.minArgs = 0;\n proto.$setup.keywordArgs = [\"width\", \"height\", \"startx\", \"starty\"];\n\n proto.$register_shape = proto.$addshape = function(name, points) {\n SHAPES[name] = points;\n };\n\n proto.$getshapes = function() {\n return Object.keys(SHAPES);\n };\n\n proto.$tracer = function(frames, delay) {\n if (frames !== undefined || delay !== undefined) {\n if (typeof delay === \"number\") {\n this._delay = delay;\n getFrameManager().refreshInterval(delay);\n }\n if (typeof frames === \"number\") {\n this._frames = frames;\n return getFrameManager().frameBuffer(frames);\n }\n\n return;\n }\n\n return this._frames;\n };\n proto.$tracer.minArgs = 0;\n\n proto.$delay = function(delay) {\n if (delay !== undefined) {\n return this.$tracer(undefined, delay);\n }\n\n return this._delay === undefined ? OPTIMAL_FRAME_RATE : this._delay;\n };\n\n proto._setworldcoordinates = function(llx, lly, urx, ury) {\n var world = this,\n turtles = getFrameManager().turtles();\n\n this.setUpWorld(llx, lly, urx, ury);\n\n if (this._sprites) {\n applyWorld(this, this._sprites);\n }\n\n if (this._background) {\n applyWorld(this, this._background);\n }\n\n return this.$clear();\n };\n\n proto.$setworldcoordinates = function(llx, lly, urx, ury) {\n this._mode = \"world\";\n return this._setworldcoordinates(llx, lly, urx, ury);\n };\n\n proto.$clear = proto.$clearscreen = function() {\n this.reset();\n return this.$reset();\n };\n\n proto.$update = function() {\n return getFrameManager().update();\n };\n\n proto.$reset = proto.$resetscreen = function() {\n var self = this,\n turtles = getFrameManager().turtles();\n\n return getFrameManager().addFrame(function() {\n applyWorld(self, self._sprites);\n applyWorld(self, self._background);\n for(var i = 0; i < turtles.length; i++) {\n turtles[i].reset();\n applyWorld(self, turtles[i]._paper);\n }\n }, true);\n };\n\n proto.$window_width = function() {\n return getWidth();\n };\n\n proto.$window_height = function() {\n return getHeight();\n };\n proto.$delay.minArgs = 0;\n\n proto.$turtles = function() {\n return getFrameManager().turtles();\n };\n proto.$turtles.returnType = Types.TURTLE_LIST;\n\n proto.$bgcolor = function(color, g, b, a) {\n if (arguments.length) {\n this._bgcolor = createColor(color, g, b, a);\n clearLayer(this.bgLayer(), this._bgcolor);\n return;\n }\n\n return hexToRGB(this._bgcolor);\n };\n proto.$bgcolor.minArgs = 0;\n proto.$bgcolor.returnType = Types.COLOR;\n\n // no-op - just defined for consistency with python version\n proto.$mainloop = proto.$done = function() {\n return undefined;\n };\n\n proto.$bye = function() {\n return Sk.TurtleGraphics.reset();\n };\n\n proto.$exitonclick = function() {\n this._exitOnClick = true;\n return this.getManager(\"mousedown\").addHandler(function() {\n resetTurtle();\n }, false);\n };\n\n proto.$onclick = function(method,btn,add) {\n if (this._exitOnClick) return;\n this.getManager(\"mousedown\").addHandler(method, add);\n };\n proto.$onclick.minArgs = 1;\n proto.$onclick.keywordArgs = [\"btn\",\"add\"];\n\n var KEY_MAP = {\n \"8\" : /^back(space)?$/i,\n \"9\" : /^tab$/i,\n \"13\" : /^(enter|return)$/i,\n \"16\" : /^shift$/i,\n \"17\" : /^(ctrl|control)$/i,\n \"18\" : /^alt$/i,\n \"27\" : /^esc(ape)?$/i,\n \"32\" : /^space$/i,\n \"33\" : /^page[\\s\\-]?up$/i,\n \"34\" : /^page[\\s\\-]?down$/i,\n \"35\" : /^end$/i,\n \"36\" : /^home$/i,\n \"37\" : /^left([\\s\\-]?arrow)?$/i,\n \"38\" : /^up([\\s\\-]?arrow)?$/i,\n \"39\" : /^right([\\s\\-]?arrow)?$/i,\n \"40\" : /^down([\\s\\-]?arrow)?$/i,\n \"45\" : /^insert$/i,\n \"46\" : /^del(ete)?$/i\n };\n\n proto._createKeyRepeater = function(key, code) {\n var self = this;\n // set a timeout for 333ms and if key has not yet been\n // released, fire another event and continue firing\n // at a rate of ~20 times per second until key is released\n self._keyLogger[code] = window.setTimeout(function() {\n // trigger the first repeat after the longer delay\n self._keyListeners[key]();\n // set up the repeat interval with the quick delay\n self._keyLogger[code] = window.setInterval(function() {\n self._keyListeners[key]();\n }, 50);\n }, 333);\n };\n\n proto._createKeyDownListener = function() {\n var self = this;\n\n if (this._keyDownListener) return;\n\n this._keyDownListener = function(e) {\n if (!focusTurtle()) return;\n\n var code = e.charCode || e.keyCode,\n pressed = String.fromCharCode(code).toLowerCase(),\n key, inKeyMap;\n\n if (self._keyLogger[code]) return;\n\n for (key in self._keyListeners) {\n inKeyMap = (key.length > 1 && KEY_MAP[code] && KEY_MAP[code].test(key));\n if (key === pressed || inKeyMap) {\n // trigger the intial keydown handler\n self._keyListeners[key]();\n self._createKeyRepeater(key, code);\n e.preventDefault();\n break;\n }\n }\n };\n\n getTarget().addEventListener(\"keydown\", this._keyDownListener);\n };\n\n proto._createKeyUpListener = function() {\n var self = this;\n\n if (this._keyUpListener) return;\n\n this._keyUpListener = function(e) {\n var interval = self._keyLogger[e.charCode || e.keyCode];\n if (interval !== undefined) {\n e.preventDefault();\n window.clearInterval(interval);\n window.clearTimeout(interval);\n delete(self._keyLogger[e.charCode || e.keyCode]);\n }\n };\n \n getTarget().addEventListener(\"keyup\", this._keyUpListener);\n };\n\n proto.$listen = function() {\n this._createKeyUpListener();\n this._createKeyDownListener();\n };\n\n proto.$onkey = function(method, keyValue) {\n if (typeof keyValue === \"function\") {\n var temp = method;\n method = keyValue;\n keyValue = temp;\n }\n\n keyValue = String(keyValue).toLowerCase();\n\n if (method && typeof method === \"function\") {\n if (!this._keyListeners) this._keyListeners = {};\n this._keyListeners[keyValue] = method;\n }\n else {\n delete this._keyListeners[keyValue];\n }\n };\n\n proto.$onscreenclick = function(method,btn,add) {\n this.getManager(\"mousedown\").addHandler(method, add);\n };\n proto.$onscreenclick.minArgs = 1;\n proto.$onscreenclick.keywordArgs = [\"btn\",\"add\"];\n\n proto.$ontimer = function(method, interval) {\n if (this._timer) {\n window.clearTimeout(this._timer);\n this._timer = undefined;\n }\n\n if (method && typeof interval === \"number\") {\n this._timer = window.setTimeout(method, Math.max(0, interval|0));\n }\n };\n proto.$ontimer.minArgs = 0;\n\n })(Screen.prototype);\n\n function ensureAnonymous() {\n if (!_anonymousTurtle) {\n _anonymousTurtle = _module.Turtle();\n }\n\n return _anonymousTurtle.instance;\n }\n\n function getTarget() {\n return _target;\n }\n\n function getScreen() {\n if (!_screenInstance) {\n _screenInstance = new Screen();\n }\n return _screenInstance;\n }\n\n function getMouseHandler() {\n if (!_mouseHandler) {\n _mouseHandler = new MouseHandler();\n }\n return _mouseHandler;\n }\n\n function getWidth() {\n return (\n (_screenInstance && _screenInstance._width) ||\n _config.width ||\n getTarget().clientWidth\n ) | 0;\n }\n\n function getHeight() {\n return (\n (_screenInstance && _screenInstance._height) ||\n _config.height ||\n getTarget().clientHeight\n ) | 0;\n }\n\n function createLayer(zIndex, isHidden) {\n var canvas = document.createElement(\"canvas\"),\n width = getWidth(),\n height = getHeight(),\n offset = getTarget().firstChild ? (-height) + \"px\" : \"0\",\n context;\n\n canvas.width = width;\n canvas.height = height;\n canvas.style.position = \"relative\";\n canvas.style.display = \"block\";\n canvas.style.setProperty(\"margin-top\",offset);\n canvas.style.setProperty(\"z-index\", zIndex);\n if (isHidden) {\n canvas.style.display = \"none\";\n }\n\n getTarget().appendChild(canvas);\n\n context = canvas.getContext(\"2d\");\n context.lineCap = \"round\";\n context.lineJoin = \"round\";\n\n applyWorld(getScreen(), context);\n\n return context;\n }\n\n function cancelAnimationFrame() {\n if (_frameRequest) {\n (window.cancelAnimationFrame || window.mozCancelAnimationFrame)(_frameRequest);\n _frameRequest = undefined;\n }\n if (_frameRequestTimeout) {\n window.clearTimeout(_frameRequestTimeout);\n _frameRequestTimeout = undefined;\n }\n }\n\n function applyWorld(world, context) {\n var llx = world.llx,\n lly = world.lly,\n urx = world.urx,\n ury = world.ury,\n xScale = world.xScale,\n yScale = world.yScale;\n\n if (!context) return;\n\n clearLayer(context);\n\n context.restore();\n context.save();\n context.scale(1 / xScale, 1 / yScale);\n if (lly === 0) {\n context.translate(-llx, lly - (ury - lly));\n } else if (lly > 0) {\n context.translate(-llx, -lly * 2);\n } else {\n context.translate(-llx, -ury);\n }\n }\n\n function pushUndo(turtle) {\n var properties, undoState, i;\n\n if (!_config.allowUndo || !turtle._bufferSize) {\n return;\n }\n\n if (!turtle._undoBuffer) {\n turtle._undoBuffer = [];\n }\n\n while(turtle._undoBuffer.length > turtle._bufferSize) {\n turtle._undoBuffer.shift();\n }\n\n undoState = {};\n properties = \"x y angle radians color fill down filling shown shape size\".split(\" \");\n for(i = 0; i < properties.length; i++) {\n undoState[properties[i]] = turtle[\"_\" + properties[i]];\n }\n\n turtle._undoBuffer.push(undoState);\n\n return turtle.addUpdate(function() {\n undoState.fillBuffer = this.fillBuffer ? this.fillBuffer.slice() : undefined;\n if (turtle._paper && turtle._paper.canvas) {\n undoState.image = turtle._paper.canvas.toDataURL();\n }\n }, false);\n }\n\n var undoImage = new Image();\n function popUndo(turtle) {\n var undoState;\n\n if (!turtle._bufferSize || !turtle._undoBuffer) {\n return;\n }\n\n undoState = turtle._undoBuffer.pop();\n\n if (!undoState) {\n return;\n }\n\n for(var key in undoState) {\n if (key === \"image\" || key === \"fillBuffer\") continue;\n turtle[\"_\" + key] = undoState[key];\n }\n\n return turtle.addUpdate(function() {\n var img;\n if (undoState.image) {\n undoImage.src = undoState.image;\n img = undoImage;\n }\n\n clearLayer(this.context(), false, undoImage);\n delete undoState.image;\n }, true, undoState);\n }\n\n function removeLayer(layer) {\n if (layer && layer.canvas && layer.canvas.parentNode) {\n layer.canvas.parentNode.removeChild(layer.canvas);\n }\n }\n\n function clearLayer(context, color, image) {\n if (!context) return;\n\n context.save();\n context.setTransform(1,0,0,1,0,0);\n if (color) {\n context.fillStyle = color;\n context.fillRect(0, 0, context.canvas.width, context.canvas.height);\n }\n else {\n context.clearRect(0, 0, context.canvas.width, context.canvas.height);\n }\n\n if (image) {\n context.drawImage(image, 0, 0);\n }\n\n context.restore();\n }\n\n function drawTurtle(state, context) {\n var shape = SHAPES[state.shape],\n world = getScreen(),\n width = getWidth(),\n height = getHeight(),\n xScale = world.xScale,\n yScale = world.yScale,\n x, y, bearing;\n\n if (!context) return;\n\n x = Math.cos(state.radians) / xScale;\n y = Math.sin(state.radians) / yScale;\n bearing = Math.atan2(y, x) - Math.PI/2;\n\n context.save();\n context.translate(state.x, state.y);\n context.scale(xScale,yScale);\n context.rotate(bearing);\n context.beginPath();\n context.lineWidth = 1;\n context.strokeStyle = state.color;\n context.fillStyle = state.fill;\n context.moveTo(shape[0][0], shape[0][1]);\n for(var i = 1; i < shape.length; i++) {\n context.lineTo(shape[i][0], shape[i][1]);\n }\n context.closePath();\n context.fill();\n context.stroke();\n context.restore();\n }\n\n function drawDot(size, color) {\n var context = this.context(),\n screen = getScreen(),\n xScale = screen.xScale,\n yScale = screen.yScale;\n\n if (!context) return;\n context.beginPath();\n context.moveTo(this.x, this.y);\n size = size * Math.min(Math.abs(xScale),Math.abs(yScale));\n context.arc(this.x, this.y, size, 0, Turtle.RADIANS);\n context.closePath();\n context.fillStyle = color || this.color;\n context.fill();\n }\n\n var textMeasuringContext = document.createElement(\"canvas\").getContext(\"2d\");\n function measureText(message, font) {\n if (font) {\n textMeasuringContext.font = font;\n }\n return textMeasuringContext.measureText(message).width;\n }\n\n function drawText(message, align, font) {\n var context = this.context();\n\n if (!context) return;\n\n context.save();\n if (font) {\n context.font = font;\n }\n if (align && align.match(/^(left|right|center)$/)) {\n context.textAlign = align;\n }\n\n context.scale(1,-1);\n context.fillStyle = this.fill;\n context.fillText(message, this.x, -this.y);\n context.restore();\n }\n\n function drawLine(loc, beginPath, endPath) {\n // TODO: make steps in path use square ends of lines\n // and open and close path at the right times.\n // See if we can minimize calls to stroke\n var context = this.context();\n\n if (!context) return;\n\n if (beginPath) {\n context.beginPath();\n context.moveTo(this.x, this.y);\n }\n\n context.lineWidth = this.size * getScreen().lineScale;\n context.strokeStyle = this.color;\n context.lineTo(loc.x, loc.y);\n context.stroke();\n }\n\n function drawFill() {\n var context = this.context(),\n path = this.fillBuffer,\n i;\n\n if (!context || !path || !path.length) return;\n\n context.save();\n context.beginPath();\n context.moveTo(path[0].x,path[0].y);\n for(i = 1; i < path.length; i++) {\n context.lineTo(path[i].x, path[i].y);\n }\n context.closePath();\n context.fillStyle = this.fill;\n context.fill();\n for(i = 1; i < path.length; i++) {\n if (!path[i].stroke) {\n continue;\n }\n\n context.beginPath();\n context.moveTo(path[i-1].x, path[i-1].y);\n context.lineWidth = path[i].size * getScreen().lineScale;\n context.strokeStyle = path[i].color;\n context.lineTo(path[i].x, path[i].y);\n context.stroke();\n }\n context.restore();\n }\n\n function partialTranslate(turtle, x, y, beginPath, countAsFrame) {\n return function() {\n return turtle.addUpdate(\n function(loc) {\n if (this.down) {\n drawLine.call(this, loc, beginPath);\n }\n },\n countAsFrame,\n {x : x, y : y},\n beginPath\n );\n };\n }\n\n function translate(turtle, startX, startY, dx, dy, beginPath, isCircle) {\n // speed is in pixels per ms\n var speed = turtle._computed_speed,\n screen = getScreen(),\n xScale = Math.abs(screen.xScale),\n yScale = Math.abs(screen.yScale),\n x = startX,\n y = startY,\n pixels = Math.sqrt(dx * dx * xScale + dy * dy * yScale),\n // TODO: allow fractional frame updates?\n frames = speed ? Math.round(Math.max(1, pixels / speed)) : 1,\n xStep = dx / frames,\n yStep = dy / frames,\n promise = getFrameManager().willRenderNext() ?\n Promise.resolve() :\n new InstantPromise(),\n countAsFrame = (!speed && isCircle) ? false : true,\n i;\n\n turtle.addUpdate(function() {\n if (this.filling) {\n this.fillBuffer.push({\n x : this.x,\n y : this.y,\n stroke : this.down,\n color : this.color,\n size : this.size\n });\n }\n }, false);\n\n for(i = 0; i < frames; i++) {\n x = startX + xStep * (i+1);\n y = startY + yStep * (i+1);\n promise = promise.then(\n partialTranslate(turtle, x, y, beginPath, countAsFrame)\n );\n beginPath = false;\n }\n\n return promise.then(function() {\n return [startX + dx, startY + dy];\n });\n }\n\n function partialRotate(turtle, angle, radians, countAsFrame) {\n return function() {\n return turtle.addUpdate(undefined, countAsFrame, {angle:angle, radians:radians});\n };\n }\n\n function rotate(turtle, startAngle, delta, isCircle) {\n var speed = turtle._computed_speed,\n degrees = delta / turtle._fullCircle * 360,\n frames = speed ? Math.round(Math.max(1, Math.abs(degrees) / speed)) : 1,\n dAngle = delta / frames,\n heading = {},\n countAsFrame = (!speed && isCircle) ? false : true,\n promise = getFrameManager().willRenderNext() ?\n Promise.resolve() :\n new InstantPromise(),\n i;\n\n // TODO: request how many frames are remaining and only queue up\n // a single rotation per screen update\n\n for(i = 0; i < frames; i++) {\n calculateHeading(turtle, startAngle + dAngle * (i+1), heading);\n promise = promise.then(\n partialRotate(turtle, heading.angle, heading.radians, countAsFrame)\n );\n }\n\n return promise.then(function() {\n return calculateHeading(turtle, startAngle + delta);\n });\n }\n\n function getCoordinates(x, y) {\n if (y === undefined) {\n y = (x && (x.y || x._y || x[1])) || 0;\n x = (x && (x.x || x._x || x[0])) || 0;\n }\n return {x:x, y:y};\n }\n\n // Modified solution of Tim Down's version from stackoverflow\n // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb\n function hexToRGB(hex) {\n var rgbForm, hexForm, result;\n\n if (rgbForm = /^rgba?\\((\\d+),(\\d+),(\\d+)(?:,([.\\d]+))?\\)$/.exec(hex)) {\n result = [\n parseInt(rgbForm[1]),\n parseInt(rgbForm[2]),\n parseInt(rgbForm[3])\n ];\n if (rgbForm[4]) {\n result.push(parseFloat(rgbForm[4]));\n }\n }\n else if (/^#?[a-f\\d]{3}|[a-f\\d]{6}$/i.exec(hex)) {\n if (hex.length === 4) {\n // Expand shorthand form (e.g. \"03F\") to full form (e.g. \"0033FF\")\n hex = hex.replace(/^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i, function(m, r, g, b) {\n return r + r + g + g + b + b;\n });\n }\n\n hexForm = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n result = [\n parseInt(hexForm[1], 16),\n parseInt(hexForm[2], 16),\n parseInt(hexForm[3], 16)\n ];\n }\n else {\n result = hex;\n }\n\n return result;\n }\n\n function createColor(color, g, b, a) {\n var i;\n\n if (g !== undefined) {\n color = [color, g, b, a];\n }\n\n if (color.constructor === Array && color.length) {\n for(i = 0; i < 3; i++) {\n color[i] = (typeof color[i] === \"number\") ?\n Math.max(0, Math.min(255, parseInt(color[i]))) :\n 0;\n }\n if (typeof color[i] === \"number\") {\n color[3] = Math.max(0, Math.min(1, color[i]));\n color = \"rgba(\" + color.join(\",\") + \")\";\n }\n else {\n color = \"rgb(\" + color.slice(0,3).join(\",\") + \")\";\n }\n }\n else if (typeof color === \"string\" && !color.match(/\\s*url\\s*\\(/i)) {\n color = color.replace(/\\s+/g, \"\");\n }\n else {\n return \"black\";\n }\n\n return color;\n }\n\n function calculateHeading(turtle, value, heading) {\n var angle = turtle._angle || 0,\n radians = turtle._radians || 0;\n\n heading || (heading = {});\n\n if (typeof value === \"number\") {\n if (turtle._isRadians) {\n angle = radians = value % Turtle.RADIANS;\n }\n else if (turtle._fullCircle) {\n angle = (value % turtle._fullCircle);\n radians = angle / turtle._fullCircle * Turtle.RADIANS;\n }\n else {\n angle = radians = 0;\n }\n\n if (angle < 0) {\n angle += turtle._fullCircle;\n radians += Turtle.RADIANS;\n }\n }\n\n heading.angle = angle;\n heading.radians = radians;\n\n return heading;\n }\n\n function pythonToJavascriptFunction(pyValue, scope) {\n return function() {\n var argsJs = Array.prototype.slice.call(arguments),\n argsPy = argsJs.map(\n function(argJs) {return Sk.ffi.remapToPy(argJs);}\n );\n\n if (typeof(scope) !== \"undefined\") {\n argsPy.unshift(scope);\n }\n return Sk.misceval.applyAsync(\n undefined, pyValue, undefined, undefined, undefined, argsPy\n ).catch(Sk.uncaughtException);\n };\n }\n\n function addModuleMethod(klass, module, method, scopeGenerator) {\n var publicMethodName = method.replace(/^\\$/, \"\"),\n displayName = publicMethodName.replace(/_\\$[a-z]+\\$$/i, \"\"),\n maxArgs = klass.prototype[method].length,\n minArgs = klass.prototype[method].minArgs,\n keywordArgs = klass.prototype[method].keywordArgs,\n returnType = klass.prototype[method].returnType,\n isSk = klass.prototype[method].isSk,\n wrapperFn;\n\n if (minArgs === undefined) {\n minArgs = maxArgs;\n }\n\n wrapperFn = function() {\n var args = Array.prototype.slice.call(arguments, 0),\n instance = scopeGenerator ? scopeGenerator() : args.shift().instance,\n i, result, susp, resolution, lengthError;\n\n if (args < minArgs || args.length > maxArgs) {\n lengthError = minArgs === maxArgs ?\n \"exactly \" + maxArgs :\n \"between \" + minArgs + \" and \" + maxArgs;\n\n throw new Sk.builtin.TypeError(displayName + \"() takes \" + lengthError + \" positional argument(s) (\" + args.length + \" given)\");\n }\n\n for (i = args.length; --i >= 0;) {\n if (args[i] !== undefined) {\n if (args[i] instanceof Sk.builtin.func) {\n args[i] = pythonToJavascriptFunction(args[i]);\n }\n else if (args[i] instanceof Sk.builtin.method) {\n args[i] = pythonToJavascriptFunction(args[i].im_func, args[i].im_self);\n }\n else if (args[i] && args[i].$d instanceof Sk.builtin.dict && args[i].instance) {\n args[i] = args[i].instance;\n }\n else {\n args[i] = Sk.ffi.remapToJs(args[i]);\n }\n }\n }\n\n try {\n result = instance[method].apply(instance, args);\n } catch(e) {\n if (window && window.console) {\n window.console.log(\"wrapped method failed\");\n window.console.log(e.stack);\n }\n throw e;\n }\n\n if (result instanceof InstantPromise) {\n result = result.lastResult;\n }\n\n if (result instanceof Promise) {\n result = result.catch(function(e) {\n if (window && window.console) {\n window.console.log(\"promise failed\");\n window.console.log(e.stack);\n }\n throw e;\n });\n\n susp = new Sk.misceval.Suspension();\n\n susp.resume = function() {\n return (resolution === undefined) ?\n Sk.builtin.none.none$ :\n Sk.ffi.remapToPy(resolution);\n };\n\n susp.data = {\n type: \"Sk.promise\",\n promise: result.then(function(value) {\n resolution = value;\n return value;\n })\n };\n\n return susp;\n }\n else {\n if (result === undefined) return Sk.builtin.none.none$;\n if (isSk) return result;\n if (typeof returnType === \"function\") {\n return returnType(result);\n }\n\n return Sk.ffi.remapToPy(result);\n }\n };\n\n if (keywordArgs) {\n wrapperFn.co_varnames = keywordArgs.slice();\n // make room for required arguments\n for(var i = 0; i < minArgs; i++) {\n wrapperFn.co_varnames.unshift(\"\");\n }\n if (!scopeGenerator) {\n // make room for the \"self\" argument\n wrapperFn.co_varnames.unshift(\"\");\n }\n }\n\n module[publicMethodName] = new Sk.builtin.func(wrapperFn);\n }\n\n function TurtleWrapper($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n self.instance = new Turtle();\n self.instance.skInstance = self;\n });\n\n for(var key in Turtle.prototype) {\n if (/^\\$[a-z_]+/.test(key)) {\n addModuleMethod(Turtle, $loc, key);\n }\n }\n }\n\n function ScreenWrapper($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self) {\n self.instance = getScreen();\n });\n\n for(var key in Screen.prototype) {\n if (/^\\$[a-z_]+/.test(key)) {\n addModuleMethod(Screen, $loc, key);\n }\n }\n }\n\n for(var key in Turtle.prototype) {\n if (/^\\$[a-z_]+/.test(key)) {\n addModuleMethod(Turtle, _module, key, ensureAnonymous);\n }\n }\n\n // add Screen method aliases to the main turtle module\n // to allow things like:\n // import turtle\n // turtle.mainloop()\n addModuleMethod(Screen, _module, \"$mainloop\", getScreen);\n addModuleMethod(Screen, _module, \"$done\", getScreen);\n addModuleMethod(Screen, _module, \"$bye\", getScreen);\n addModuleMethod(Screen, _module, \"$tracer\", getScreen);\n addModuleMethod(Screen, _module, \"$update\", getScreen);\n addModuleMethod(Screen, _module, \"$delay\", getScreen);\n addModuleMethod(Screen, _module, \"$window_width\", getScreen);\n addModuleMethod(Screen, _module, \"$window_height\", getScreen);\n\n _module.Turtle = Sk.misceval.buildClass(_module, TurtleWrapper, \"Turtle\", []);\n _module.Screen = Sk.misceval.buildClass(_module, ScreenWrapper, \"Screen\", []);\n\n // Calling focus(false) will block turtle key/mouse events\n // until focus(true) is called again or until the turtle DOM target\n // is clicked/tabbed into.\n function focusTurtle(value) {\n if (value !== undefined) {\n _focus = !!value;\n if (_focus) {\n getTarget().focus();\n }\n else {\n getTarget().blur();\n }\n }\n\n return _focus;\n }\n\n function resetTurtle() {\n cancelAnimationFrame();\n getScreen().reset();\n getFrameManager().reset();\n\n while (_target.firstChild) {\n _target.removeChild(_target.firstChild);\n }\n\n if (_mouseHandler) {\n _mouseHandler.reset();\n }\n\n _durationSinceRedraw = 0;\n _screenInstance = undefined;\n _anonymousTurtle = undefined;\n _mouseHandler = undefined;\n TURTLE_COUNT = 0;\n }\n\n function stopTurtle() {\n cancelAnimationFrame();\n\n if (_mouseHandler) {\n _mouseHandler.reset();\n }\n\n _durationSinceRedraw = 0;\n _screenInstance = undefined;\n _anonymousTurtle = undefined;\n _mouseHandler = undefined;\n TURTLE_COUNT = 0;\n }\n\n return {\n skModule : _module,\n reset : resetTurtle,\n stop : stopTurtle,\n focus : focusTurtle,\n Turtle : Turtle,\n Screen : Screen\n };\n}\n\n// See if the TurtleGraphics module has already been loaded\n// for the currently configured DOM target element.\nvar currentTarget = getConfiguredTarget();\n\nif (!currentTarget.turtleInstance) {\n currentTarget.turtleInstance = generateTurtleModule(currentTarget);\n}\nelse {\n currentTarget.turtleInstance.reset();\n}\n\nSk.TurtleGraphics.module = currentTarget.turtleInstance.skModule;\nSk.TurtleGraphics.reset = currentTarget.turtleInstance.reset;\nSk.TurtleGraphics.stop = currentTarget.turtleInstance.stop;\nSk.TurtleGraphics.focus = currentTarget.turtleInstance.focus;\nSk.TurtleGraphics.raw = {\n Turtle : currentTarget.turtleInstance.Turtle,\n Screen : currentTarget.turtleInstance.Screen\n};\n\nreturn currentTarget.turtleInstance.skModule;\n\n};", "src/lib/sets.py": "raise NotImplementedError(\"sets is not yet implemented in Skulpt\")\n", "src/lib/socket.py": "raise NotImplementedError(\"socket is not yet implemented in Skulpt\")\n", "src/lib/ihooks.py": "raise NotImplementedError(\"ihooks is not yet implemented in Skulpt\")\n", "src/lib/mhlib.py": "raise NotImplementedError(\"mhlib is not yet implemented in Skulpt\")\n", "src/lib/BaseHTTPServer.py": "raise NotImplementedError(\"BaseHTTPServer is not yet implemented in Skulpt\")\n", "src/lib/ntpath.py": "raise NotImplementedError(\"ntpath is not yet implemented in Skulpt\")\n", "src/lib/tokenize.py": "raise NotImplementedError(\"tokenize is not yet implemented in Skulpt\")\n", "src/lib/stringold.py": "raise NotImplementedError(\"stringold is not yet implemented in Skulpt\")\n", "src/lib/commands.py": "raise NotImplementedError(\"commands is not yet implemented in Skulpt\")\n", "src/lib/uuid.py": "raise NotImplementedError(\"uuid is not yet implemented in Skulpt\")\n", "src/lib/popen2.py": "raise NotImplementedError(\"popen2 is not yet implemented in Skulpt\")\n", "src/lib/xmllib.py": "raise NotImplementedError(\"xmllib is not yet implemented in Skulpt\")\n", "src/lib/smtpd.py": "raise NotImplementedError(\"smtpd is not yet implemented in Skulpt\")\n", "src/lib/mutex.py": "raise NotImplementedError(\"mutex is not yet implemented in Skulpt\")\n", "src/lib/mailcap.py": "raise NotImplementedError(\"mailcap is not yet implemented in Skulpt\")\n", "src/lib/aifc.py": "raise NotImplementedError(\"aifc is not yet implemented in Skulpt\")\n", "src/lib/struct.py": "raise NotImplementedError(\"struct is not yet implemented in Skulpt\")\n", "src/lib/asynchat.py": "raise NotImplementedError(\"asynchat is not yet implemented in Skulpt\")\n", "src/lib/os2emxpath.py": "raise NotImplementedError(\"os2emxpath is not yet implemented in Skulpt\")\n", "src/lib/md5.py": "raise NotImplementedError(\"md5 is not yet implemented in Skulpt\")\n", "src/lib/document.js": "var $builtinmodule = function (name) {\n var elementClass;\n var mod = {};\n\n mod.getElementById = new Sk.builtin.func(function (id) {\n var result = document.getElementById(id.v);\n if (result) {\n return Sk.misceval.callsim(mod.Element, result);\n }\n return Sk.builtin.none.none$;\n });\n\n mod.createElement = new Sk.builtin.func(function (eName) {\n var r = document.createElement(eName.v);\n if (r) {\n return Sk.misceval.callsim(mod.Element, r);\n }\n });\n\n\n mod.getElementsByTagName = new Sk.builtin.func(function (tag) {\n var r = document.getElementsByTagName(tag.v)\n var reslist = [];\n for (var i = r.length - 1; i >= 0; i--) {\n reslist.push(Sk.misceval.callsim(mod.Element, r[i]))\n }\n return new Sk.builtin.list(reslist)\n });\n\n mod.getElementsByClassName = new Sk.builtin.func(function (cname) {\n var r = document.getElementsByClassName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element, r[i]));\n }\n ;\n return new Sk.builtin.list(reslist);\n });\n\n mod.getElementsByName = new Sk.builtin.func(function (cname) {\n var r = document.getElementsByName(cname.v);\n var reslist = [];\n for (var i = 0; i < r.length; i++) {\n reslist.push(Sk.misceval.callsim(mod.Element, r[i]));\n }\n ;\n return new Sk.builtin.list(reslist);\n });\n\n mod.currentDiv = new Sk.builtin.func(function () {\n if (Sk.divid !== undefined) {\n return new Sk.builtin.str(Sk.divid)\n }\n else {\n throw new Sk.builtin.AttributeError(\"There is no value set for divid\");\n }\n })\n\n elementClass = function ($gbl, $loc) {\n /*\n Notes: self['$d'] is the dictionary used by the GenericGetAttr mechanism for an object.\n for various reasons if you create a class in Javascript and have self.xxxx instance\n variables, you cannot say instance.xxx and get the value of the instance variable unless\n it is stored in the self['$d'] object. This seems like a duplication of storage to me\n but that is how it works right now (5/2013)\n\n Writing your own __getattr__ is also an option but this gets very tricky when an attr is\n a method...\n */\n $loc.__init__ = new Sk.builtin.func(function (self, elem) {\n self.v = elem\n self.innerHTML = elem.innerHTML\n self.innerText = elem.innerText\n if (elem.value !== undefined) {\n self.value = elem.value\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('value'), new Sk.builtin.str(self.value))\n }\n\n if (elem.checked !== undefined) {\n self.checked = elem.checked\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('checked'), new Sk.builtin.str(self.checked))\n }\n\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), new Sk.builtin.str(self.innerHTML))\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), new Sk.builtin.str(self.innerText))\n\n })\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.__setattr__ = new Sk.builtin.func(function (self, key, value) {\n key = Sk.ffi.remapToJs(key);\n if (key === 'innerHTML') {\n self.innerHTML = value\n self.v.innerHTML = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerHTML'), value)\n }\n if (key === 'innerText') {\n self.innerText = value\n self.v.innerText = value.v\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str('innerText'), value)\n }\n });\n\n\n $loc.appendChild = new Sk.builtin.func(function (self, ch) {\n self.v.appendChild(ch.v);\n });\n\n $loc.removeChild = new Sk.builtin.func(function (self, node) {\n self.v.removeChild(node.v)\n })\n\n // getCSS\n\n $loc.getCSS = new Sk.builtin.func(function (self, key) {\n return new Sk.builtin.str(self.v.style[key.v]);\n });\n\n\n $loc.setCSS = new Sk.builtin.func(function (self, attr, value) {\n self.v.style[attr.v] = value.v\n\n })\n\n $loc.getAttribute = new Sk.builtin.func(function (self, key) {\n var res = self.v.getAttribute(key.v)\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.setAttribute = new Sk.builtin.func(function (self, attr, value) {\n self.v.setAttribute(attr.v, value.v)\n });\n\n $loc.getProperty = new Sk.builtin.func(function (self, key) {\n var res = self.v[key.v]\n if (res) {\n return new Sk.builtin.str(res)\n } else {\n return Sk.builtin.none.none$;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function (self) {\n console.log(self.v.tagName);\n return new Sk.builtin.str(self.v.tagName)\n })\n\n $loc.__repr__ = new Sk.builtin.func(function (self) {\n return new Sk.builtin.str('[DOM Element]')\n })\n\n\n };\n\n mod.Element = Sk.misceval.buildClass(mod, elementClass, 'Element', []);\n\n return mod;\n\n}\n", "src/lib/sre_parse.py": "raise NotImplementedError(\"sre_parse is not yet implemented in Skulpt\")\n", "src/lib/cookielib.py": "raise NotImplementedError(\"cookielib is not yet implemented in Skulpt\")\n", "src/lib/dbhash.py": "raise NotImplementedError(\"dbhash is not yet implemented in Skulpt\")\n", "src/lib/abc.py": "raise NotImplementedError(\"abc is not yet implemented in Skulpt\")\n", "src/lib/runpy.py": "raise NotImplementedError(\"runpy is not yet implemented in Skulpt\")\n", "src/lib/lib-dynload/__init__.py": "raise NotImplementedError(\"lib-dynload is not yet implemented in Skulpt\")\n", "src/lib/encodings/__init__.py": "raise NotImplementedError(\"encodings is not yet implemented in Skulpt\")\n", "src/lib/distutils/__init__.py": "raise NotImplementedError(\"distutils is not yet implemented in Skulpt\")\n", "src/lib/distutils/tests/__init__.py": "raise NotImplementedError(\"tests is not yet implemented in Skulpt\")\n", "src/lib/distutils/command/__init__.py": "raise NotImplementedError(\"command is not yet implemented in Skulpt\")\n", "src/lib/lib-tk/__init__.py": "raise NotImplementedError(\"lib-tk is not yet implemented in Skulpt\")\n", "src/lib/ctypes/__init__.py": "raise NotImplementedError(\"ctypes is not yet implemented in Skulpt\")\n", "src/lib/ctypes/macholib/__init__.py": "raise NotImplementedError(\"macholib is not yet implemented in Skulpt\")\n", "src/lib/unittest/__init__.py": "__author__ = 'bmiller'\n'''\nThis is the start of something that behaves like\nthe unittest module from cpython.\n\n'''\n\nclass TestCase:\n def __init__(self):\n self.numPassed = 0\n self.numFailed = 0\n self.assertPassed = 0\n self.assertFailed = 0\n self.verbosity = 1\n self.tlist = []\n testNames = {}\n for name in dir(self):\n if name[:4] == 'test' and name not in testNames:\n self.tlist.append(getattr(self,name))\n testNames[name]=True\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n \n def cleanName(self,funcName):\n # work around skulpts lack of an __name__\n funcName = str(funcName)\n funcName = funcName[13:]\n funcName = funcName[:funcName.find('<')-3]\n return funcName\n\n def main(self):\n\n for func in self.tlist:\n if self.verbosity > 1:\n print('Running %s' % self.cleanName(func))\n try:\n self.setUp()\n self.assertPassed = 0\n self.assertFailed = 0\n func()\n self.tearDown()\n if self.assertFailed == 0:\n self.numPassed += 1\n else:\n self.numFailed += 1\n print('Tests failed in %s ' % self.cleanName(func))\n except Exception as e:\n self.assertFailed += 1\n self.numFailed += 1\n print('Test threw exception in %s (%s)' % (self.cleanName(func), e))\n self.showSummary()\n\n def assertEqual(self, actual, expected, feedback=\"\"):\n res = actual==expected\n if not res and feedback == \"\":\n feedback = \"Expected %s to equal %s\" % (str(actual),str(expected))\n self.appendResult(res, actual ,expected, feedback)\n\n def assertNotEqual(self, actual, expected, feedback=\"\"):\n res = actual != expected\n if not res and feedback == \"\":\n feedback = \"Expected %s to not equal %s\" % (str(actual),str(expected))\n self.appendResult(res, actual, expected, feedback)\n\n def assertTrue(self,x, feedback=\"\"):\n res = bool(x) is True\n if not res and feedback == \"\":\n feedback = \"Expected %s to be True\" % (str(x))\n self.appendResult(res, x, True, feedback)\n\n def assertFalse(self,x, feedback=\"\"):\n res = not bool(x)\n if not res and feedback == \"\":\n feedback = \"Expected %s to be False\" % (str(x))\n self.appendResult(res, x, False, feedback)\n\n def assertIs(self,a,b, feedback=\"\"):\n res = a is b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be the same object as %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertIsNot(self,a,b, feedback=\"\"):\n res = a is not b\n if not res and feedback == \"\":\n feedback = \"Expected %s to not be the same object as %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertIsNone(self,x, feedback=\"\"):\n res = x is None\n if not res and feedback == \"\":\n feedback = \"Expected %s to be None\" % (str(x))\n self.appendResult(res, x, None, feedback)\n\n def assertIsNotNone(self,x, feedback=\"\"):\n res = x is not None\n if not res and feedback == \"\":\n feedback = \"Expected %s to not be None\" % (str(x))\n self.appendResult(res, x, None, feedback)\n\n def assertIn(self, a, b, feedback=\"\"):\n res = a in b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be in %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertNotIn(self, a, b, feedback=\"\"):\n res = a not in b\n if not res and feedback == \"\":\n feedback = \"Expected %s to not be in %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertIsInstance(self,a,b, feedback=\"\"):\n res = isinstance(a,b)\n if not res and feedback == \"\":\n feedback = \"Expected %s to be an instance of %s\" % (str(a), str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertNotIsInstance(self,a,b, feedback=\"\"):\n res = not isinstance(a,b)\n if not res and feedback == \"\":\n feedback = \"Expected %s to not be an instance of %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertAlmostEqual(self, a, b, places=7, feedback=\"\", delta=None):\n\n if delta is not None:\n res = abs(a-b) <= delta\n else:\n if places is None:\n places = 7\n res = round(a-b, places) == 0\n \n if not res and feedback == \"\":\n feedback = \"Expected %s to equal %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertNotAlmostEqual(self, a, b, places=7, feedback=\"\", delta=None):\n\n if delta is not None:\n res = not (a == b) and abs(a - b) > delta\n else:\n if places is None:\n places = 7\n res = round(a-b, places) != 0\n\n if not res and feedback == \"\":\n feedback = \"Expected %s to not equal %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n\n def assertGreater(self,a,b, feedback=\"\"):\n res = a > b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be greater than %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertGreaterEqual(self,a,b, feedback=\"\"):\n res = a >= b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be >= %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertLess(self, a, b, feedback=\"\"):\n res = a < b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be less than %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def assertLessEqual(self,a,b, feedback=\"\"):\n res = a <= b\n if not res and feedback == \"\":\n feedback = \"Expected %s to be <= %s\" % (str(a),str(b))\n self.appendResult(res, a, b, feedback)\n\n def appendResult(self,res,actual,expected,feedback):\n if res:\n msg = 'Pass'\n self.assertPassed += 1\n else:\n msg = 'Fail: ' + feedback\n print(msg)\n self.assertFailed += 1\n\n def assertRaises(self, exception, callable=None, *args, **kwds):\n # with is currently not supported hence we just try and catch\n if callable is None:\n raise NotImplementedError(\"assertRaises does currently not support assert contexts\")\n if kwds:\n raise NotImplementedError(\"assertRaises does currently not support **kwds\")\n\n res = False\n actualerror = str(exception())\n try:\n callable(*args)\n except exception as ex:\n res = True\n except Exception as inst:\n actualerror = str(inst)\n print(\"ACT = \", actualerror, str(exception()))\n else:\n actualerror = \"No Error\"\n\n self.appendResult(res, str(exception()), actualerror, \"\")\n\n def fail(self, msg=None):\n if msg is None:\n msg = 'Fail'\n else:\n msg = 'Fail: ' + msg\n print(msg)\n self.assertFailed += 1\n\n def showSummary(self):\n pct = self.numPassed / (self.numPassed+self.numFailed) * 100\n print(\"Ran %d tests, passed: %d failed: %d\\n\" % (self.numPassed+self.numFailed,\n self.numPassed, self.numFailed))\n\n\n\ndef main(verbosity=1):\n glob = globals() # globals() still needs work\n for name in glob:\n if issubclass(glob[name],TestCase):\n try:\n tc = glob[name]()\n tc.verbosity = verbosity\n tc.main()\n except:\n print(\"Uncaught Error in: \", name)\n", "src/lib/unittest/gui.py": "import document\nfrom unittest import TestCase\n\nclass TestCaseGui(TestCase):\n def __init__(self):\n TestCase.__init__(self)\n self.divid = document.currentDiv()\n self.mydiv = document.getElementById(self.divid)\n res = document.getElementById(self.divid+'_unit_results')\n if res:\n self.resdiv = res\n res.innerHTML = ''\n else:\n self.resdiv = document.createElement('div')\n self.resdiv.setAttribute('id',self.divid+'_unit_results')\n self.resdiv.setAttribute('class','unittest-results')\n self.mydiv.appendChild(self.resdiv)\n\n\n def main(self):\n t = document.createElement('table')\n self.resTable = t\n self.resdiv.appendChild(self.resTable)\n\n headers = ['Result','Actual Value','Expected Value','Notes']\n row = document.createElement('tr')\n for item in headers:\n head = document.createElement('th')\n head.setAttribute('class','ac-feedback')\n head.innerHTML = item\n head.setCSS('text-align','center')\n row.appendChild(head)\n self.resTable.appendChild(row)\n\n for func in self.tlist:\n try:\n self.setUp()\n func()\n self.tearDown()\n except Exception as e:\n self.appendResult('Error', None, None, e)\n self.numFailed += 1\n self.showSummary()\n\n def appendResult(self,res,actual,expected,param):\n trimActual = False\n if len(str(actual)) > 15:\n trimActual = True\n actualType = type(actual)\n trimExpected = False\n if len(str(expected)) > 15:\n trimExpected = True\n expectedType = type(expected)\n row = document.createElement('tr')\n err = False\n if res == 'Error':\n err = True\n msg = 'Error: %s' % param\n errorData = document.createElement('td')\n errorData.setAttribute('class','ac-feedback')\n errorData.innerHTML = 'ERROR'\n errorData.setCSS('background-color','#de8e96')\n errorData.setCSS('text-align','center')\n row.appendChild(errorData)\n elif res:\n passed = document.createElement('td')\n passed.setAttribute('class','ac-feedback')\n passed.innerHTML = 'Pass'\n passed.setCSS('background-color','#83d382')\n passed.setCSS('text-align','center')\n row.appendChild(passed)\n self.numPassed += 1\n else:\n fail = document.createElement('td')\n fail.setAttribute('class','ac-feedback')\n fail.innerHTML = 'Fail'\n fail.setCSS('background-color','#de8e96')\n fail.setCSS('text-align','center')\n row.appendChild(fail)\n self.numFailed += 1\n\n\n act = document.createElement('td')\n act.setAttribute('class','ac-feedback')\n if trimActual:\n actHTML = str(actual)[:5] + \"...\" + str(actual)[-5:]\n if actualType == str:\n actHTML = repr(actHTML)\n act.innerHTML = actHTML\n else:\n act.innerHTML = repr(actual)\n act.setCSS('text-align','center')\n row.appendChild(act)\n\n expect = document.createElement('td')\n expect.setAttribute('class','ac-feedback')\n\n if trimExpected:\n expectedHTML = str(expected)[:5] + \"...\" + str(expected)[-5:]\n if expectedType == str:\n expectedHTML = repr(expectedHTML)\n expect.innerHTML = expectedHTML\n else:\n expect.innerHTML = repr(expected)\n expect.setCSS('text-align','center')\n row.appendChild(expect)\n inp = document.createElement('td')\n inp.setAttribute('class','ac-feedback')\n\n if err:\n inp.innerHTML = msg\n else:\n inp.innerHTML = param\n inp.setCSS('text-align','center')\n row.appendChild(inp)\n self.resTable.appendChild(row)\n\n\n def showSummary(self):\n pct = self.numPassed / (self.numPassed+self.numFailed) * 100\n pTag = document.createElement('p')\n pTag.innerHTML = \"You passed: \" + str(pct) + \"% of the tests\"\n self.resdiv.appendChild(pTag)\n", "src/lib/curses/__init__.py": "raise NotImplementedError(\"curses is not yet implemented in Skulpt\")\n", "src/lib/test/test_support.py": "\"\"\"Supporting definitions for the Python regression tests.\"\"\"\n\nif __name__ != 'test.test_support':\n raise ImportError('test_support must be imported from the test package')\n\nimport unittest\n\n\n# def run_unittest(*classes):\n# \"\"\"Run tests from unittest.TestCase-derived classes.\"\"\"\n# valid_types = (unittest.TestSuite, unittest.TestCase)\n# suite = unittest.TestSuite()\n# for cls in classes:\n# if isinstance(cls, str):\n# if cls in sys.modules:\n# suite.addTest(unittest.findTestCases(sys.modules[cls]))\n# else:\n# raise ValueError(\"str arguments must be keys in sys.modules\")\n# elif isinstance(cls, valid_types):\n# suite.addTest(cls)\n# else:\n# suite.addTest(unittest.makeSuite(cls))\n# _run_suite(suite)\n\ndef run_unittest(*classes):\n \"\"\"Run tests from unittest.TestCase-derived classes.\"\"\"\n for cls in classes:\n print cls\n if issubclass(cls, unittest.TestCase):\n cls().main()\n else:\n print \"Don't know what to do with \", cls\n", "src/lib/test/__init__.py": "__author__ = 'bmiller'\n\ndef testEqual(actual, expected):\n if type(expected) == type(1):\n if actual == expected:\n print('Pass')\n return True\n elif type(expected) == type(1.11):\n if abs(actual-expected) < 0.00001:\n print('Pass')\n return True\n else:\n if actual == expected:\n print('Pass')\n return True\n print('Test Failed: expected ' + str(expected) + ' but got ' + str(actual))\n return False\n\ndef testNotEqual(actual, expected):\n pass\n\n", "src/lib/test/decimaltestdata/__init__.py": "raise NotImplementedError(\"decimaltestdata is not yet implemented in Skulpt\")\n", "src/lib/config/__init__.py": "raise NotImplementedError(\"config is not yet implemented in Skulpt\")\n", "src/lib/hotshot/__init__.py": "raise NotImplementedError(\"hotshot is not yet implemented in Skulpt\")\n", "src/lib/multiprocessing/__init__.py": "raise NotImplementedError(\"multiprocessing is not yet implemented in Skulpt\")\n", "src/lib/multiprocessing/dummy/__init__.py": "raise NotImplementedError(\"dummy is not yet implemented in Skulpt\")\n", "src/lib/urllib/__init__.js": "var $builtinmodule = function (name) {\n var urllib = {};\n\n return urllib;\n};\n", "src/lib/urllib/request/__init__.js": "var $builtinmodule = function (name) {\n var request = {};\n\n\n //~ Classes .................................................................\n\n // Response class\n //\n // Response objects are returned by the request, get, post, etc.\n // methods, allowing the user to access the response text, status\n // code, and other information.\n\n // ------------------------------------------------------------\n var response = function ($gbl, $loc) {\n\n // ------------------------------------------------------------\n $loc.__init__ = new Sk.builtin.func(function (self, xhr) {\n self.data$ = xhr.responseText;\n self.lineList = self.data$.split(\"\\n\");\n self.lineList = self.lineList.slice(0, -1);\n for (var i = 0; i < self.lineList.length; i++) {\n self.lineList[i] = self.lineList[i] + '\\n';\n }\n self.currentLine = 0;\n self.pos$ = 0;\n });\n\n\n // ------------------------------------------------------------\n $loc.__str__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<Response>');\n });\n\n\n // ------------------------------------------------------------\n $loc.__iter__ = new Sk.builtin.func(function (self) {\n var allLines = self.lineList;\n\n return Sk.builtin.makeGenerator(function () {\n if (this.$index >= this.$lines.length) {\n return undefined;\n }\n return new Sk.builtin.str(this.$lines[this.$index++]);\n }, {\n $obj : self,\n $index: 0,\n $lines: allLines\n });\n });\n\n\n // ------------------------------------------------------------\n $loc.read = new Sk.builtin.func(function (self, size) {\n if (self.closed) {\n throw new Sk.builtin.ValueError(\"I/O operation on closed file\");\n }\n var len = self.data$.length;\n if (size === undefined) {\n size = len;\n }\n var ret = new Sk.builtin.str(self.data$.substr(self.pos$, size));\n self.pos$ += size;\n if (self.pos$ >= len) {\n self.pos$ = len;\n }\n return ret;\n });\n\n\n // ------------------------------------------------------------\n $loc.readline = new Sk.builtin.func(function (self, size) {\n var line = \"\";\n if (self.currentLine < self.lineList.length) {\n line = self.lineList[self.currentLine];\n self.currentLine++;\n }\n return new Sk.builtin.str(line);\n });\n\n\n // ------------------------------------------------------------\n $loc.readlines = new Sk.builtin.func(function (self, sizehint) {\n var arr = [];\n for (var i = self.currentLine; i < self.lineList.length; i++) {\n arr.push(new Sk.builtin.str(self.lineList[i]));\n }\n return new Sk.builtin.list(arr);\n });\n\n };\n\n request.Response =\n Sk.misceval.buildClass(request, response, 'Response', []);\n\n\n //~ Module functions ........................................................\n\n // ------------------------------------------------------------\n /**\n * Constructs and sends a Request. Returns Response object.\n *\n * http://docs.python-requests.org/en/latest/api/#requests.request\n *\n * For now, this implementation doesn't actually construct a Request\n * object; it just makes the request through jQuery.ajax and then\n * constructs a Response.\n */\n request.urlopen = new Sk.builtin.func(function (url, data, timeout) {\n var prom = new Promise(function(resolve, reject) {\n var xmlhttp = new XMLHttpRequest();\n\n xmlhttp.addEventListener(\"loadend\", function (e) {\n resolve(Sk.misceval.callsim(request.Response, xmlhttp));\n });\n\n if (!data) {\n xmlhttp.open(\"GET\", url.v);\n xmlhttp.send(null);\n } else {\n xmlhttp.open(\"POST\", url.v);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.setRequestHeader(\"Content-length\", data.v.length);\n xmlhttp.send(data.v);\n }\n });\n\n var susp = new Sk.misceval.Suspension();\n\n susp.resume = function() {\n return resolution;\n };\n\n susp.data = {\n type: \"Sk.promise\",\n promise: prom.then(function(value) {\n resolution = value;\n return value;\n }, function(err) {\n resolution = \"\";\n return err;\n })\n };\n\n return susp;\n });\n\n\n return request;\n};", "src/lib/matplotlib2/__init__.js": "var $builtinmodule = function(name)\n{\n var matplotlib = {};\n\n return matplotlib;\n};\n", "src/lib/matplotlib2/pyplot/__init__.js": "/**\n Made by Michael Ebert for skulpt, see this modules at https://github.com/waywaaard/skulpt\n\n matplotlib.pyplot inspired by https://github.com/rameshvs/jsplotlib, though heavily modified.\n\n jsplotlib for supporting plot commands and kwargs for the matplotlib skulpt module\n Supports:\n - kwargs\n - all color specs\n - color cycle\n - rc params\n - ., o, x, s markers\n - resize function for markers\n - -, --, .- line styles\n - various Line2D attributes\n - auto scaling for axes\n**/\nvar jsplotlib = {\n // empty object creation\n};\n\njsplotlib.rc = {\n \"lines.linewidth\": 1.0,\n \"lines.linestyle\": \"-\",\n \"lines.color\": \"blue\",\n \"lines.marker\": \"None\",\n \"lines.markeredgewidth\": 0.5,\n \"lines.markersize\": 6,\n \"lines.dash_joinstyle\": \"miter\",\n \"lines.dash_capstyle\": \"butt\",\n \"lines.solid_jointyle\": \"miter\",\n \"lines.solid_capstyle\": \"projecting\",\n \"lines.antialiased\": true,\n \"patch.linewidth\": 1.0,\n \"patch.facecolor\": \"blue\",\n \"patch.edgecolor\": \"black\",\n \"patch.antialiased\": true,\n \"text.color\": \"black\",\n \"axes.hold\": true, // whether to clear the axes by default on\n \"axes.facecolor\": \"white\", // axes background color\n \"axes.edgecolor\": \"black\", // axes edge color\n \"axes.grid\": false,\n \"axes.titlesize\": \"large\",\n \"axes.labelsize\": \"medium\",\n \"axes.labelweigth\": \"normal\",\n \"axes.labelcolor\": \"black\",\n \"axes.axisbelow\": false,\n \"axes.color_cycle\": [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\"]\n};\n\nvar chart_counter = 0; // for creating unique ids\n\njsplotlib.Bars = function(ydata, color) {\n var that = {};\n \n // Initialize parameter defaults\n that._y = ydata;\n that._color = color || null;\n \n that.color = function(cs) {\n if (cs)\n this._color = jsplotlib.color_to_hex(cs);\n return this;\n };\n \n that.draw = function(parent_chart) {\n // should be called in the pplot command\n // each plot call adds a new set of bars to our existing plot\n // object and draws them all, when show is called\n // this._init_common();\n var number_of_points = this._y.length; // implement need to move those from the original construct_graph class to lines\n if (!this._linestyle && !this._marker) {\n this._linestyle = jsplotlib.rc['lines.linestyle'];\n }\n\n /*\n if (!this._marker && !this._linestyle) {\n this._marker = jsplotlib.rc['lines.marker'];\n }\n */\n\n if (!this._color) {\n this._color = jsplotlib.color_to_hex(parent_chart.get_next_color());\n }\n\n // set defaults for all attributes\n if (!this._markersize) {\n this._markersize = jsplotlib.rc['lines.markersize'];\n }\n\n if (!this._markeredgecolor) {\n this._markeredgecolor = 'k';\n }\n\n if (!this._linewidth) {\n this._linewidth = jsplotlib.rc['lines.linewidth'];\n }\n\n if (!this._dash_capstyle) {\n this._dash_capstyle = \"butt\";\n }\n\n if (!this._solid_capstyle) {\n this._solid_capstyle = \"butt\";\n }\n\n if (!this._solid_joinstyle) {\n this._solid_joinstyle = \"miter\";\n }\n\n if (!this._dash_joinstyle) {\n this._dash_joinstyle = \"miter\";\n }\n\n // default markerfacecolor is linecolor\n if (!this._markerfacecolor) {\n this._markerfacecolor = jsplotlib.color_to_hex(this._color);\n }\n\n if (!this._markeredgewidth) {\n this._markeredgewidth = 0.75;\n }\n\n if (!this._alpha) {\n this._alpha = 1;\n }\n\n // local storage for drawing\n var y = this._y;\n \n /*\n var bins = parseInt(8);\n tempScale = d3.scale.linear().domain([0, bins]).range(d3.extent(y));\n tickArray = d3.range(1+bins).map(tempScale).map(function(e) {\n return e;\n });\n var histMapper = d3.layout.histogram().bins(tickArray)(ys);\n y.domain([0, d3.max(histMapper, function(d) { return d.y; })]);\n */\n\n // create array of point pairs with optional s value\n // from [x1,x2], [y1, y2], [s1, s2]\n // to [[x1,y1,s1],[x2,y2,s2]]\n var xscale = parent_chart.get_xscale(); // should come from axis o.O\n var yscale = parent_chart.get_yscale();\n\n var xformat = parent_chart._xaxis._formatter || function(x) {\n return x;\n };\n\n var yformat = parent_chart._yaxis._formatter || function(x) {\n return x;\n };\n\n // this adds the bars to the chart\n this._bars = parent_chart.chart.append(\"svg:g\").attr(\"id\", this._artist_id);\n this._bars_containers = this._bars.selectAll(\"g.pplot_bars\").data(y).enter()\n .append(\"g\").attr(\"class\", \"pplot_bars\");\n \n /*\n bars.enter().append(\"rect\")\n .attr(\"class\", \"bar\")\n .attr(\"y\", y(0))\n .style('fill', mainModel.settings.color().fill)\n .style('outline', '1px solid '+mainModel.settings.color().stroke)\n .attr(\"height\", height - y(0));\n */\n\n // set appropriate line style\n this._bars = this._bars_containers.append(\"rect\")\n .attr(\"x1\", function(d) {\n return xscale(d[0][0]);\n })\n .attr(\"x2\", function(d) {\n return xscale(d[1][0]);\n })\n .attr(\"y1\", function(d) {\n return yscale(d[0][1]);\n })\n .attr(\"y2\", function(d) {\n return yscale(d[1][1]);\n })\n .style(\"stroke\", jsplotlib.color_to_hex(this._color))\n .style(\"stroke-linecap\", this._solid_capstyle)\n .style(\"stroke-linejoin\", this._solid_joinstyle)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"stroke-width\", this._linewidth);\n\n return this;\n };\n \n /**\n Updates possible attributes provided as kwargs\n **/\n that.update = function(kwargs) {\n // we assume key value pairs\n if (kwargs && typeof kwargs === \"object\") {\n for (var key in kwargs) {\n if (kwargs.hasOwnProperty(key)) {\n var val = kwargs[key];\n\n switch (key) {\n }\n }\n }\n }\n\n return this;\n };\n \n return that;\n}\n\njsplotlib._line_counter = 0;\n\n/** Line2D class for encapsulating all line relevant attributes and methods\n Rebuilds partial matplotlib.Line2D functionality. Does not inherit from\n abstract Artist class. Rather more a data representation.\n **/\njsplotlib.Line2D = function(xdata, ydata, linewidth, linestyle, color, marker,\n markersize, markeredgewidth, markeredgecolor, markerfacecolor,\n markerfacecoloralt, fillstyle, antialiased, dash_capstyle,\n solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius,\n drawstyle, markevery, kwargs) {\n\n // \"that\": completed Line2D object that is returned\n var that = {}, x_values= [], y_values = [];\n // Initialize parameter defaults\n var skip = Math.max(1, ydata.length / 500);\n for (var i = 0, len = ydata.length; i < len; i=i+skip) {\n var index = Math.floor(i+Math.random()*skip);\n if (xdata.length == ydata.length) {\n x_values.push(xdata[index]);\n }\n y_values.push(ydata[index]);\n } \n that._x = x_values; //xdata;\n that._y = y_values; //ydata;\n that._linewidth = linewidth || null;\n that._linestyle = linestyle || null;\n that._color = color || null;\n that._marker = marker || null;\n that._markersize = markersize || null;\n that._markeredgewidth = markeredgewidth || null;\n that._markeredgecolor = markeredgecolor || null;\n that._markerfacecolor = markerfacecolor || null;\n that._markerfacecoloralt = markerfacecoloralt || 'none';\n that._fillstyle = fillstyle || 'full';\n that._antialiased = antialiased || null;\n that._dash_capstyle = dash_capstyle || null;\n that._solid_capstyle = solid_capstyle || null;\n that._dash_joinstyle = dash_joinstyle || null;\n that._solid_joinstyle = solid_joinstyle || null;\n that._pickradius = pickradius || 5;\n that._drawstyle = drawstyle || null;\n that._markevery = markevery || null;\n this._line_id = jsplotlib._line_counter;\n jsplotlib._line_counter += 1;\n //kwargs\n\n // if only y provided, create Array from 1 to N\n if (!that._x || that._x.length === 0) {\n that._x = jsplotlib.linspace(1, that._y.length, that._y.length);\n }\n\n that.antialiased = function(a) {\n if (a)\n this._antialiased = a;\n return this;\n };\n\n that.markerfacecoloralt = function(mfca) {\n if (mfca)\n this._markerfacecoloralt = mfca;\n return this;\n };\n\n that.pickradius = function(pr) {\n if (pr)\n this._pickradius = pr;\n return this;\n };\n\n that.drawstyle = function(ds) {\n if (ds)\n this._drawstyle = ds;\n return this;\n };\n\n that.markevery = function(me) {\n if (me)\n this._markevery = me;\n return this;\n };\n\n that.color = function(cs) {\n if (cs)\n this._color = jsplotlib.color_to_hex(cs);\n return this;\n };\n\n that.alpha = function(a) {\n if (a)\n this._alpha = a;\n return this;\n };\n\n /* supports butt, round, projecting*/\n that.dash_capstyle = function(dcs) {\n if (dcs)\n this._dash_capstyle = dcs;\n return this;\n };\n\n /* supports butt, round, projecting*/\n that.solid_capstyle = function(scs) {\n if (scs)\n this._solid_capstyle = scs;\n return this;\n };\n\n /* supports miter, round, bevel' */\n that.solid_jointyle = function(sjs) {\n if (sjs)\n this._solid_joinstyle = sjs;\n return this;\n };\n\n /* supports miter, round, bevel' */\n that.dash_joinstyle = function(djs) {\n if (djs)\n this._dash_joinstyle = djs;\n return this;\n };\n\n /* random float */\n that.markersize = function(ms) {\n if (ms)\n this._markersize = ms;\n return this;\n };\n\n that.marker = function(ms) {\n if (ms)\n this._marker = ms;\n return this;\n };\n\n that.markerfacecolor = function(mfc) {\n if (mfc)\n this._markerfacecolor = jsplotlib.color_to_hex(mfc);\n return this;\n };\n\n that.markeredgecolor = function(mec) {\n if (mec)\n this._markeredgecolor = jsplotlib.color_to_hex(mec);\n return this;\n };\n\n that.markeredgewidth = function(mec) {\n if (mec)\n this._markeredgewidth = mec;\n return this;\n };\n\n that.linestyle = function(ls) {\n if (ls)\n ls = ls.trim();\n this._linestyle = ls;\n return this;\n };\n\n that.linewidth = function(lw) {\n if (lw)\n this._linewidth = lw;\n return this;\n };\n\n that.line_id = function(lid) {\n this._line_id = lid;\n return this;\n };\n\n that.xrange = function(min, max, N) {\n this._x = jsplotlib.linspace(min, max, N);\n return this;\n };\n\n that.yrange = function(min, max, N) {\n this._y = jsplotlib.linspace(min, max, N);\n return this;\n };\n\n /**\n Updates possible attributes provided as kwargs\n **/\n that.update = function(kwargs) {\n // we assume key value pairs\n if (kwargs && typeof kwargs === \"object\") {\n for (var key in kwargs) {\n if (kwargs.hasOwnProperty(key)) {\n var val = kwargs[key];\n\n switch (key) {\n case 'linewidth':\n this.linewidth(val);\n break;\n case 'linestyle':\n this.linestyle(val);\n break;\n case 'color':\n val = jsplotlib.to_rgb(val);\n this.color(val);\n break;\n case 'marker':\n this.marker(val);\n break;\n case 'markersize':\n this.markersize(val);\n break;\n case 'markeredgewidth':\n this.markeredgewidth(val);\n break;\n case 'markeredgecolor':\n val = jsplotlib.to_rgb(val);\n this.markeredgecolor(val);\n break;\n case 'markerfacecolor':\n val = jsplotlib.to_rgb(val);\n this.markerfacecolor(val);\n break;\n case 'markerfacecoloralt':\n val = jsplotlib.to_rgb(val);\n this.markerfacecoloralt(val);\n break;\n case 'fillstyle':\n this.fillstyle(val);\n break;\n case 'antialiased':\n this.antialiased(val);\n break;\n case 'dash_capstyle':\n this.dash_capstyle(val);\n break;\n case 'solid_capstyle':\n this.solid_capstyle(val);\n break;\n case 'dash_joinstyle':\n this.dash_joinstyle(val);\n break;\n case 'solid_jointyle':\n this.solid_jointyle(val);\n break;\n case 'pickradius':\n this.pickradius(val);\n break;\n case 'drawstyle':\n this.drawstyle(val);\n break;\n case 'markevery':\n this.markevery(val);\n break;\n }\n }\n }\n }\n\n return this;\n };\n\n that.draw = function(parent_chart) {\n // should be called in the pplot command\n // each plot call adds a new line to our existing plot\n // object and draws them all, when show is called\n // this._init_common();\n var number_of_points = this._y.length || this._x.length; // implement need to move those from the original construct_graph class to lines\n if (!this._linestyle && !this._marker) {\n this._linestyle = jsplotlib.rc['lines.linestyle'];\n }\n\n /*\n if (!this._marker && !this._linestyle) {\n this._marker = jsplotlib.rc['lines.marker'];\n }\n */\n\n if (!this._color) {\n this._color = jsplotlib.color_to_hex(parent_chart.get_next_color());\n }\n\n // set defaults for all attributes\n if (!this._markersize) {\n this._markersize = jsplotlib.rc['lines.markersize'];\n }\n\n if (!this._markeredgecolor) {\n this._markeredgecolor = 'k';\n }\n\n if (!this._linewidth) {\n this._linewidth = jsplotlib.rc['lines.linewidth'];\n }\n\n if (!this._dash_capstyle) {\n this._dash_capstyle = \"butt\";\n }\n\n if (!this._solid_capstyle) {\n this._solid_capstyle = \"butt\";\n }\n\n if (!this._solid_joinstyle) {\n this._solid_joinstyle = \"miter\";\n }\n\n if (!this._dash_joinstyle) {\n this._dash_joinstyle = \"miter\";\n }\n\n // default markerfacecolor is linecolor\n if (!this._markerfacecolor) {\n this._markerfacecolor = jsplotlib.color_to_hex(this._color);\n }\n\n if (!this._markeredgewidth) {\n this._markeredgewidth = 0.75;\n }\n\n if (!this._alpha) {\n this._alpha = 1;\n }\n\n // local storage for drawing\n var x = this._x;\n var y = this._y;\n\n // create array of point pairs with optional s value\n // from [x1,x2], [y1, y2], [s1, s2]\n // to [[x1,y1,s1],[x2,y2,s2]]\n var xys = d3.zip(x, y);\n var pairs = d3.zip(xys.slice(0, -1), xys.slice(1));\n var xscale = parent_chart.get_xscale(); // should come from axis o.O\n var yscale = parent_chart.get_yscale();\n\n var xformat = parent_chart._xaxis._formatter || function(x) {\n return x;\n };\n\n var yformat = parent_chart._yaxis._formatter || function(x) {\n return x;\n };\n\n // this adds the line to the chart\n this._line = parent_chart.chart.append(\"svg:g\").attr(\"id\", this._line_id);\n this._line_containers = this._line.selectAll(\"g.pplot_lines\").data(pairs).enter()\n .append(\"g\").attr(\"class\", \"pplot_lines\");\n\n // set appropriate line style\n if (this._linestyle === \"-\") {\n this._lines = this._line_containers.append(\"line\")\n .attr(\"x1\", function(d) {\n return xscale(d[0][0]);\n })\n .attr(\"x2\", function(d) {\n return xscale(d[1][0]);\n })\n .attr(\"y1\", function(d) {\n return yscale(d[0][1]);\n })\n .attr(\"y2\", function(d) {\n return yscale(d[1][1]);\n })\n .style(\"stroke\", jsplotlib.color_to_hex(this._color))\n .style(\"stroke-linecap\", this._solid_capstyle)\n .style(\"stroke-linejoin\", this._solid_joinstyle)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"stroke-width\", this._linewidth);\n } else if (this._linestyle === \"--\") {\n this._lines = this._line_containers.append(\"line\")\n .attr(\"x1\", function(d) {\n return xscale(d[0][0]);\n })\n .attr(\"x2\", function(d) {\n return xscale(d[1][0]);\n })\n .attr(\"y1\", function(d) {\n return yscale(d[0][1]);\n })\n .attr(\"y2\", function(d) {\n return yscale(d[1][1]);\n })\n .style(\"stroke\", jsplotlib.color_to_hex(this._color))\n .style(\"stroke-width\", this._linewidth)\n .style(\"stroke-linecap\", this._dash_capstyle)\n .style(\"stroke-linejoin\", this._dash_joinstyle)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"stroke-dasharray\", \"5,5\");\n } else if (this._linestyle === \":\") {\n this._lines = this._line_containers.append(\"line\")\n .attr(\"x1\", function(d) {\n return xscale(d[0][0]);\n })\n .attr(\"x2\", function(d) {\n return xscale(d[1][0]);\n })\n .attr(\"y1\", function(d) {\n return yscale(d[0][1]);\n })\n .attr(\"y2\", function(d) {\n return yscale(d[1][1]);\n })\n .style(\"stroke\", jsplotlib.color_to_hex(this._color))\n .style(\"stroke-width\", this._linewidth)\n .style(\"stroke-dasharray\", \"2,5\")\n .style(\"stroke-linejoin\", this._dash_joinstyle)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"stroke-linecap\", \"round\");\n } else if (this._linestyle === \"-.\") {\n this._lines = this._line_containers.append(\"line\")\n .attr(\"x1\", function(d) {\n return xscale(d[0][0]);\n })\n .attr(\"x2\", function(d) {\n return xscale(d[1][0]);\n })\n .attr(\"y1\", function(d) {\n return yscale(d[0][1]);\n })\n .attr(\"y2\", function(d) {\n return yscale(d[1][1]);\n })\n .style(\"stroke\", jsplotlib.color_to_hex(this._color))\n .style(\"stroke-width\", this._linewidth)\n .style(\"stroke-linecap\", this._dash_capstyle)\n .style(\"stroke-linejoin\", this._dash_joinstyle)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"stroke-dasharray\", \"5, 5, 2, 5\");\n }\n\n // append points\n this._points = parent_chart.chart.selectAll(\"g.pplot_points\" + this._line_id)\n .data(xys).enter().append(\"g\")\n .attr(\"x\", function(d) {\n return d[0];\n })\n .attr(\"y\", function(d) {\n return d[1];\n })\n //.attr(\"s\", function(d) {\n // return d[2];\n //})\n .attr(\"class\", \"pplot_points\" + this._line_id);\n\n // init hover popups\n /*\n $(\"#\" + chart.attr(\"id\") + \" g.pplot_points\" + this._line_id).tipsy({\n gravity: \"nw\",\n html: true,\n title: function() {\n var d = this.__data__;\n var output = \"(\" + xformat(d[0]) + \",\" + yformat(d[1]) + \")\";\n return output;\n }\n }); */\n\n // set appropriate marker styles\n // http://matplotlib.org/api/markers_api.html\n var marker_size = this._markersize; // store for nested call\n switch (this._marker) {\n case undefined:\n case \" \":\n case \"None\":\n case \"\":\n break;\n case \".\":\n this._markers = this._points.append(\"circle\").attr(\"cx\", function(d) {\n return xscale(d[0]);\n }).attr(\"cy\", function(d) {\n return yscale(d[1]);\n }).attr(\"r\", function(d) {\n return 1;\n });\n break;\n case \"o\":\n this._markers = this._points.append(\"circle\").attr(\"cx\", function(d) {\n return xscale(d[0]);\n }).attr(\"cy\", function(d) {\n return yscale(d[1]);\n }).attr(\"r\", function(d) {\n return marker_size;\n });\n break;\n case \"x\":\n this._points.append(\"line\").attr(\"x1\", function(d) {\n return xscale(d[0]) - marker_size;\n }).attr(\"x2\", function(d) {\n return xscale(d[0]) + marker_size;\n }).attr(\"y1\", function(d) {\n return yscale(d[1]) - marker_size;\n }).attr(\"y2\", function(d) {\n return yscale(d[1]) + marker_size;\n });\n this._points.append(\"line\").attr(\"x1\", function(d) {\n return xscale(d[0]) + marker_size;\n }).attr(\"x2\", function(d) {\n return xscale(d[0]) - marker_size;\n }).attr(\"y1\", function(d) {\n return yscale(d[1]) - marker_size;\n }).attr(\"y2\", function(d) {\n return yscale(d[1]) + marker_size;\n });\n this._markers = this._points.selectAll(\"line\");\n break;\n case 's':\n this._points.append(\"rect\")\n .attr(\"x\", function(d) {\n return xscale(d[0]) - marker_size / 2;\n })\n .attr(\"y\", function(d) {\n return yscale(d[1]) - marker_size / 2;\n })\n .attr(\"width\", function(d) {\n return marker_size;\n })\n .attr(\"height\", function(d) {\n return marker_size;\n });\n this._markers = this._points.selectAll(\"rect\");\n break;\n }\n\n // resize function only supports 'o'\n var resize_function = function(resize_amount) {\n return function() {\n var marker = d3.select(this);\n if (marker.attr(\"r\")) {\n marker.attr(\"r\", marker.attr(\"r\") * resize_amount);\n } else if (marker.attr(\"width\") && marker.attr(\"height\")) {\n // resizes square marker\n var old_marker_size = parseFloat(marker.attr(\"width\"));\n var new_marker_size = old_marker_size * resize_amount;\n var diff_marker_size = (new_marker_size - old_marker_size) / 2;\n\n var new_x = parseFloat(marker.attr(\"x\")) - diff_marker_size;\n var new_y = parseFloat(marker.attr(\"y\")) - diff_marker_size;\n marker.attr(\"width\", new_marker_size);\n marker.attr(\"height\", new_marker_size);\n marker.attr(\"x\", new_x);\n marker.attr(\"y\", new_y);\n } else {\n return true;\n }\n };\n };\n\n // add marker attributes\n if (this._markers) {\n this._markers\n .style(\"stroke\", jsplotlib.color_to_hex(this._markeredgecolor))\n .style(\"stroke-width\", this._markeredgewidth)\n .style(\"stroke-opacity\", this._alpha)\n .style(\"fill\", jsplotlib.color_to_hex(this._markerfacecolor))\n .on(\"mouseover\", resize_function(1.25))\n .on(\"mouseout\", resize_function(0.8));\n }\n\n return this;\n };\n\n return that;\n};\n\njsplotlib.plot = function(chart) {\n /*\n list of responsibilites\n - holds all lines, bars, etc. (\"artists\")\n - updates axis\n - construct axis\n - knows color_cycle\n - scatter? s() functions?\n */\n\n // store chart object and append own methods\n var that = {\n chart: chart\n };\n\n that.axes_colorcycle_position = 0;\n that.artist_count = 0;\n that._artists = []; // we support multiple artists\n\n that.add_artist = function(artist) {\n if (artist) {\n this._artists.push(artist);\n artist._artist_id = this.artist_count++;\n this._update_limits();\n }\n\n return this;\n };\n\n // set graph attributes\n that._chartheight = parseInt(chart.attr(\"height\"), 10);\n that._chartwidth = parseInt(chart.attr(\"width\"));\n that._title_string = \"\";\n that._title_size = 0;\n that._xaxis = jsplotlib.construct_axis(that, \"x\");\n that._yaxis = jsplotlib.construct_axis(that, \"y\");\n that._axes = [that._xaxis, that._yaxis];\n\n // returns the next color in the cycle\n that.get_next_color = function() {\n var cs = jsplotlib.rc['axes.color_cycle'][this.axes_colorcycle_position];\n this.axes_colorcycle_position = (this.axes_colorcycle_position + 1) %\n jsplotlib.rc['axes.color_cycle'].length;\n return cs;\n };\n\n // setter functions\n that.xlabel = function(xl) {\n this._xaxis.set_label(xl);\n return this;\n };\n\n that.ylabel = function(yl) {\n this._yaxis.set_label(yl);\n return this;\n };\n\n that.xaxis_off = function() {\n this._xaxis._turn_off();\n return this;\n };\n\n that.yaxis_off = function() {\n this._yaxis._turn_off();\n return this;\n };\n\n that.xaxis_on = function() {\n this._xaxis._turn_on();\n return this;\n };\n\n that.yaxis_on = function() {\n this._yaxis._turn_on();\n return this;\n };\n\n that.axis_on = function() {\n this.yaxis_on();\n this.xaxis_on();\n return this;\n };\n\n that.axis_off = function() {\n this.yaxis_off();\n this.xaxis_off();\n return this;\n };\n\n that.title = function(title_string) {\n this._title_string = title_string;\n this._title_size = this._chartheight * 0.1;\n this._title_transform_string = \"translate(\" + this._chartwidth / 2 + \",\" +\n this._title_size / 2 + \")\";\n return this;\n };\n\n // sets the ylimits based on a minmax array/tuple\n that._ylimits = function(min_max_tuple) {\n this._yaxis._set_data_range(min_max_tuple);\n return this;\n };\n\n that._xlimits = function(min_max_tuple) {\n this._xaxis._set_data_range(min_max_tuple);\n return this;\n };\n\n that._update_limits = function() {\n //TODO: rework for histogram/bar charts\n var i;\n var xs = []; // all x-values\n var ys = []; // all y-values\n\n // calculate limits\n for (i = 0; i < this._artists.length; i++) {\n xs = xs.concat(this._artists[i]._x);\n ys = ys.concat(this._artists[i]._y);\n }\n\n this._xlimits([d3.min(xs), d3.max(xs)]);\n this._ylimits([d3.min(ys), d3.max(ys)]);\n\n return this;\n };\n\n that.yformat = function(formatter) {\n this._yaxis._set_formatter(formatter);\n return this;\n };\n\n that.xformat = function(formatter) {\n this._xaxis._set_formatter(formatter);\n return this;\n };\n\n that.get_yscale = function() {\n return this._yaxis.get_scale();\n };\n\n that.get_xscale = function() {\n return this._xaxis.get_scale();\n };\n\n // creates axes\n that._init_common = function() {\n for (var i = 0; i < 2; i++) {\n this._axes[i]._init(this);\n }\n this._height = this._chartheight - this._xaxis._size;\n this._width = this._chartwidth - this._yaxis._size;\n return this;\n };\n\n // draw axes and append graph title\n that._draw_axes = function() {\n for (var i = 0; i < this._axes.length; i++) {\n this._axes[i]._draw_axis(this);\n this._axes[i]._draw_label(this);\n }\n\n var myselector = \"#\" + chart.attr(\"id\") + \" .axis line, #\" + chart.attr(\n \"id\") + \" .axis path\";\n $(myselector).css(\"fill\", \"none\").css(\"stroke\", \"#000\");\n d3.svg.axis(chart);\n if (this._title_string !== \"\") {\n that.chart.append(\"svg:g\").attr(\"class\", \"graph_title\").attr(\n \"transform\", this._title_transform_string).append(\"text\").append(\n \"tspan\").attr(\"text-anchor\", \"middle\").attr(\"class\", \"graph_title\").attr(\n \"writing-mode\", \"rl-tb\").text(this._title_string);\n }\n return this;\n };\n\n // resize function for the chart\n var chart_id = that.chart.attr(\"id\");\n that.resize_function = function(resize_amount, direction) {\n return function() {\n var node = this;\n while (node.id !== chart_id) {\n node.parentNode.appendChild(node);\n node = node.parentNode;\n }\n var object = d3.select(this);\n var x0 = parseInt(object.attr(\"x\") || \"0\", 10);\n var width0 = parseInt(object.attr(\"width\"), 10);\n var y0 = parseInt(object.attr(\"y\") || \"0\", 10);\n var height0 = parseInt(object.attr(\"height\"), 10);\n var newwidth, newheight, newx, newy;\n if (direction === \"grow\") {\n object.attr(\"x_orig\", x0).attr(\"y_orig\", y0).attr(\"width_orig\",\n width0).attr(\"height_orig\", height0);\n newwidth = width0 * resize_amount;\n newheight = height0 * resize_amount;\n newx = x0 - (resize_amount - 1) * width0 / 2;\n newy = y0 - (resize_amount - 1) * height0 / 2;\n } else if (direction === \"shrink\") {\n newwidth = object.attr(\"width_orig\");\n newheight = object.attr(\"height_orig\");\n newx = object.attr(\"x_orig\");\n newy = object.attr(\"y_orig\");\n }\n object.attr(\"x\", newx).attr(\"y\", newy).attr(\"height\", newheight).attr(\n \"width\", newwidth);\n };\n };\n /**\n Draws the artists. Artists are respnsible for their drawing. Here we just initialize\n the axes and the scaling.\n **/\n that.draw = function() {\n var i;\n\n this._init_common(); //\n\n // draw lines\n for (i = 0; i < this._artists.length; i++) {\n this._artists[i].draw(this);\n }\n\n this._draw_axes();\n };\n\n that.update = function(kwargs) {\n var i;\n\n // pass to lines\n for (i = 0; i < this._artists.length; i++) {\n this._artists[i].update(kwargs);\n }\n\n // update own kwargs\n if (kwargs && typeof kwargs === \"object\") {\n for (var key in kwargs) {\n if (kwargs.hasOwnProperty(key)) {\n var val = kwargs[key];\n\n switch (key) {\n case 'title':\n this.title(val);\n break;\n case 'xlabel':\n this.xlabel(val);\n break;\n case 'ylabel':\n this.ylabel(val);\n break;\n }\n }\n }\n }\n\n return this;\n };\n\n return that;\n};\n\n\n\n/** List of all supported line styles **/\njsplotlib.Line2D.lineStyles = {\n '-': '_draw_solid',\n '--': '_draw_dashed',\n '-.': '_draw_dash_dot',\n ':': '_draw_dotted',\n 'None': '_draw_nothing',\n ' ': '_draw_nothing',\n '': '_draw_nothing',\n};\n\njsplotlib.Line2D.lineMarkers = {\n '.': 'point',\n ',': 'pixel',\n 'o': 'circle',\n 'v': 'triangle_down',\n '^': 'triangle_up',\n '<': 'triangle_left',\n '>': 'triangle_right',\n '1': 'tri_down',\n '2': 'tri_up',\n '3': 'tri_left',\n '4': 'tri_right',\n '8': 'octagon',\n 's': 'square',\n 'p': 'pentagon',\n '*': 'star',\n 'h': 'hexagon1',\n 'H': 'hexagon2',\n '+': 'plus',\n 'x': 'x',\n 'D': 'diamond',\n 'd': 'thin_diamond',\n '|': 'vline',\n '_': 'hline',\n //TICKLEFT: 'tickleft',\n //TICKRIGHT: 'tickright',\n //TICKUP: 'tickup',\n //TICKDOWN: 'tickdown',\n //CARETLEFT: 'caretleft',\n //CARETRIGHT: 'caretright',\n //CARETUP: 'caretup',\n //CARETDOWN: 'caretdown',\n \"None\": 'nothing',\n //Sk.builtin.none.none$: 'nothing',\n ' ': 'nothing',\n '': 'nothing'\n};\n\n/**\n Color short keys\n**/\njsplotlib.colors = {\n 'b': 'blue',\n 'g': 'green',\n 'r': 'red',\n 'c': 'cyan',\n 'm': 'magenta',\n 'y': 'yellow',\n 'k': 'black',\n 'w': 'white'\n};\n\n/**\n Mapping of all possible CSS colors, that are supported by matplotlib\n**/\njsplotlib.cnames = {\n 'aliceblue': '#F0F8FF',\n 'antiquewhite': '#FAEBD7',\n 'aqua': '#00FFFF',\n 'aquamarine': '#7FFFD4',\n 'azure': '#F0FFFF',\n 'beige': '#F5F5DC',\n 'bisque': '#FFE4C4',\n 'black': '#000000',\n 'blanchedalmond': '#FFEBCD',\n 'blue': '#0000FF',\n 'blueviolet': '#8A2BE2',\n 'brown': '#A52A2A',\n 'burlywood': '#DEB887',\n 'cadetblue': '#5F9EA0',\n 'chartreuse': '#7FFF00',\n 'chocolate': '#D2691E',\n 'coral': '#FF7F50',\n 'cornflowerblue': '#6495ED',\n 'cornsilk': '#FFF8DC',\n 'crimson': '#DC143C',\n 'cyan': '#00FFFF',\n 'darkblue': '#00008B',\n 'darkcyan': '#008B8B',\n 'darkgoldenrod': '#B8860B',\n 'darkgray': '#A9A9A9',\n 'darkgreen': '#006400',\n 'darkkhaki': '#BDB76B',\n 'darkmagenta': '#8B008B',\n 'darkolivegreen': '#556B2F',\n 'darkorange': '#FF8C00',\n 'darkorchid': '#9932CC',\n 'darkred': '#8B0000',\n 'darksage': '#598556',\n 'darksalmon': '#E9967A',\n 'darkseagreen': '#8FBC8F',\n 'darkslateblue': '#483D8B',\n 'darkslategray': '#2F4F4F',\n 'darkturquoise': '#00CED1',\n 'darkviolet': '#9400D3',\n 'deeppink': '#FF1493',\n 'deepskyblue': '#00BFFF',\n 'dimgray': '#696969',\n 'dodgerblue': '#1E90FF',\n 'firebrick': '#B22222',\n 'floralwhite': '#FFFAF0',\n 'forestgreen': '#228B22',\n 'fuchsia': '#FF00FF',\n 'gainsboro': '#DCDCDC',\n 'ghostwhite': '#F8F8FF',\n 'gold': '#FFD700',\n 'goldenrod': '#DAA520',\n 'gray': '#808080',\n 'green': '#008000',\n 'greenyellow': '#ADFF2F',\n 'honeydew': '#F0FFF0',\n 'hotpink': '#FF69B4',\n 'indianred': '#CD5C5C',\n 'indigo': '#4B0082',\n 'ivory': '#FFFFF0',\n 'khaki': '#F0E68C',\n 'lavender': '#E6E6FA',\n 'lavenderblush': '#FFF0F5',\n 'lawngreen': '#7CFC00',\n 'lemonchiffon': '#FFFACD',\n 'lightblue': '#ADD8E6',\n 'lightcoral': '#F08080',\n 'lightcyan': '#E0FFFF',\n 'lightgoldenrodyellow': '#FAFAD2',\n 'lightgreen': '#90EE90',\n 'lightgray': '#D3D3D3',\n 'lightpink': '#FFB6C1',\n 'lightsage': '#BCECAC',\n 'lightsalmon': '#FFA07A',\n 'lightseagreen': '#20B2AA',\n 'lightskyblue': '#87CEFA',\n 'lightslategray': '#778899',\n 'lightsteelblue': '#B0C4DE',\n 'lightyellow': '#FFFFE0',\n 'lime': '#00FF00',\n 'limegreen': '#32CD32',\n 'linen': '#FAF0E6',\n 'magenta': '#FF00FF',\n 'maroon': '#800000',\n 'mediumaquamarine': '#66CDAA',\n 'mediumblue': '#0000CD',\n 'mediumorchid': '#BA55D3',\n 'mediumpurple': '#9370DB',\n 'mediumseagreen': '#3CB371',\n 'mediumslateblue': '#7B68EE',\n 'mediumspringgreen': '#00FA9A',\n 'mediumturquoise': '#48D1CC',\n 'mediumvioletred': '#C71585',\n 'midnightblue': '#191970',\n 'mintcream': '#F5FFFA',\n 'mistyrose': '#FFE4E1',\n 'moccasin': '#FFE4B5',\n 'navajowhite': '#FFDEAD',\n 'navy': '#000080',\n 'oldlace': '#FDF5E6',\n 'olive': '#808000',\n 'olivedrab': '#6B8E23',\n 'orange': '#FFA500',\n 'orangered': '#FF4500',\n 'orchid': '#DA70D6',\n 'palegoldenrod': '#EEE8AA',\n 'palegreen': '#98FB98',\n 'paleturquoise': '#AFEEEE',\n 'palevioletred': '#DB7093',\n 'papayawhip': '#FFEFD5',\n 'peachpuff': '#FFDAB9',\n 'peru': '#CD853F',\n 'pink': '#FFC0CB',\n 'plum': '#DDA0DD',\n 'powderblue': '#B0E0E6',\n 'purple': '#800080',\n 'red': '#FF0000',\n 'rosybrown': '#BC8F8F',\n 'royalblue': '#4169E1',\n 'saddlebrown': '#8B4513',\n 'salmon': '#FA8072',\n 'sage': '#87AE73',\n 'sandybrown': '#FAA460',\n 'seagreen': '#2E8B57',\n 'seashell': '#FFF5EE',\n 'sienna': '#A0522D',\n 'silver': '#C0C0C0',\n 'skyblue': '#87CEEB',\n 'slateblue': '#6A5ACD',\n 'slategray': '#708090',\n 'snow': '#FFFAFA',\n 'springgreen': '#00FF7F',\n 'steelblue': '#4682B4',\n 'tan': '#D2B48C',\n 'teal': '#008080',\n 'thistle': '#D8BFD8',\n 'tomato': '#FF6347',\n 'turquoise': '#40E0D0',\n 'violet': '#EE82EE',\n 'wheat': '#F5DEB3',\n 'white': '#FFFFFF',\n 'whitesmoke': '#F5F5F5',\n 'yellow': '#FFFF00',\n 'yellowgreen': '#9ACD32'\n};\n\njsplotlib.color_to_hex = function(color) {\n // is color a shortcut?\n if (jsplotlib.colors[color])\n color = jsplotlib.colors[color];\n\n // is inside cnames array?\n if (jsplotlib.cnames[color])\n return jsplotlib.cnames[color];\n\n // check if it is already a hex value\n if (typeof color == \"string\") {\n var match = color.match(/^#(?:[0-9a-fA-F]{3}){1,2}$/);\n if (match && match.length === 1)\n return match[0];\n }\n\n // add rgb colors here\n if (Array.isArray(color) && color.length === 3) {\n return jsplotlib.rgb2hex(color);\n }\n\n // back to default\n return jsplotlib.cnames[jsplotlib.rc['lines.color']];\n};\n\njsplotlib.get_color = function(cs) {\n return jsplotlib.colors[cs] ? jsplotlib.colors[cs] : jsplotlib.colors.b;\n};\n\n/**\n Creates the d3 svg element at the specified dom element with given width and height\n**/\njsplotlib.make_chart = function(width, height, console, insert_mode,\n attributes) {\n chart_counter++;\n var DEFAULT_PADDING = 30;\n console = console || document.body;\n width = width - 2 * DEFAULT_PADDING || 500;\n height = height - 2 * DEFAULT_PADDING || 200;\n attributes = attributes || {};\n\n // create id, if not given\n if (!('id' in attributes)) {\n attributes.id = 'chart' + chart_counter;\n }\n\n var chart = d3.select(console.console).append('div').append('svg');\n /*\n if (!insert_mode) {\n chart = d3.select(insert_container).append('svg');\n } else {\n chart = d3.select(insert_container).insert('svg', insert_mode);\n }\n */\n\n // set css classes\n $(chart[0]).parent().hide();\n chart.attr('class', 'chart');\n chart.attr('width', width);\n chart.attr('height', height);\n chart.attr('chart_count', chart_counter);\n // set additional given attributes\n for (var attribute in attributes) {\n if (attributes.hasOwnProperty(attribute)) {\n chart.attr(attribute, attributes[attribute]);\n }\n }\n\n $('.chart#' + attributes.id).css('padding-left', DEFAULT_PADDING + 'px');\n return chart;\n};\n\n/**\n Creates x or y axis and auto scales them\n**/\njsplotlib.construct_axis = function() {\n var axis_count = 0;\n return function(parent_graph, x_or_y) {\n var that = {};\n that._id = \"axis\" + axis_count++;\n that._will_draw_label = false;\n that._will_draw_axis = true;\n that._x_or_y = x_or_y;\n that._size = 0;\n that._label_offset = 0;\n that._label_string = \"\";\n if (x_or_y === \"x\") {\n that._axis_proportion = 0.12;\n that._label_proportion = 0.12;\n } else if (x_or_y === \"y\") {\n that._axis_proportion = 0.07;\n that._label_proportion = 0.05;\n } else {\n throw \"Invalid axis type (must be x or y): \" + this._x_or_y;\n }\n that._proportion = that._axis_proportion;\n that.n_ticks = 4;\n that.set_n_ticks = function(n) {\n this.n_ticks = n;\n };\n that.set_label = function(label_string) {\n this._label_string = label_string;\n this._will_draw_label = true;\n this._proportion = this._axis_proportion + this._label_proportion;\n return this;\n };\n that._turn_off = function() {\n this._will_draw_axis = false;\n return this;\n };\n that._turn_on = function() {\n this._will_draw_axis = true;\n return this;\n };\n that.set_bar_limits = function(minmaxplus) {\n var min = minmaxplus[0];\n var oldmax = minmaxplus[1];\n var plus = minmaxplus[2];\n var newmax;\n if (oldmax instanceof Date) {\n newmax = new Date(oldmax.getTime() + plus);\n } else {\n newmax = oldmax + plus;\n }\n this._set_data_range([min, newmax]);\n };\n\n that._set_data_range = function(minmax) {\n this._min = minmax[0];\n this._max = minmax[1];\n if (this._min instanceof Date || this._max instanceof Date) {\n this._scale = d3.time.scale();\n this._min = new Date(this._min);\n this._max = new Date(this._max);\n } else {\n this._scale = d3.scale.linear();\n }\n this._domain = [this._min, this._max*1.1];\n return this;\n };\n that._set_formatter = function(formatter) {\n this._formatter = formatter;\n return this;\n };\n that.get_scale = function() {\n if (this._x_or_y === \"x\") {\n this._range = [parent_graph._yaxis._size, parent_graph._chartwidth];\n } else if (this._x_or_y === \"y\") {\n this._range = [parent_graph._height, parent_graph._title_size];\n }\n this._scale\n .domain(this._domain)\n .range(this._range);\n return this._scale;\n };\n that._init = function(chart) {\n var dimension;\n if (this._will_draw_axis) {\n var proportion_increase = 0;\n if (this._x_or_y === \"x\") {\n dimension = parent_graph._chartheight;\n } else if (this._x_or_y === \"y\") {\n // Handle digits on the y-axis!\n proportion_increase += .015*this._max.toLocaleString().length;\n dimension = parent_graph._chartwidth;\n } else {\n throw \"Invalid axis type (must be x or y): \" + this._x_or_y;\n }\n this._size = dimension * (this._proportion+proportion_increase);\n this._label_offset = this._size * this._label_proportion;\n } else {\n this._size = 0;\n }\n return this;\n };\n that._compute_transform_string = function() {\n var offset_h, offset_v;\n var offset_label_h, offset_label_v;\n var label_rotation = \"\";\n if (this._x_or_y === \"x\") {\n offset_h = 0;\n offset_v = parent_graph._height;\n offset_label_h = parent_graph._yaxis._size + parent_graph._chartwidth /\n 4;\n offset_label_v = parent_graph._height + this._size - this._label_offset;\n this._writing_mode = \"lr-tb\";\n this._orientation = \"bottom\";\n } else if (this._x_or_y === \"y\") {\n offset_h = this._size;\n offset_v = 0;\n offset_label_h = this._label_offset;\n offset_label_v = parent_graph._chartheight / 2;\n label_rotation = \"rotate(180)\";\n this._writing_mode = \"tb-rl\";\n this._orientation = \"left\";\n } else {\n throw \"Invalid axis type (must be x or y): \" + this._x_or_y;\n }\n this._transform_string = \"translate(\" + offset_h + \",\" + offset_v +\n \")scale(1,1)\";\n this._label_transform_string = \"translate(\" + offset_label_h + \",\" +\n offset_label_v + \")\" + label_rotation;\n };\n that._draw_axis = function() {\n if (this._will_draw_axis) {\n this._formatter = this._formatter || this.get_scale().tickFormat(this\n .n_ticks);\n this._compute_transform_string();\n this._axis = d3.svg.axis().scale(this.get_scale()).ticks(this.n_ticks)\n .orient(this._orientation).tickSubdivide(0).tickFormat(this._formatter);\n parent_graph.chart.append(\"svg:g\").attr(\"id\", this._id).attr(\"class\",\n this._x_or_y + \" axis\").attr(\"transform\", this._transform_string).call(\n this._axis);\n }\n };\n that._draw_label = function() {\n this._compute_transform_string();\n if (this._will_draw_axis && this._will_draw_label) {\n parent_graph.chart.append(\"svg:g\").attr(\"class\", this._x_or_y +\n \" axis_label\").attr(\"transform\", this._label_transform_string).append(\n \"text\").append(\"tspan\").attr(\"text-anchor\", \"middle\").attr(\"class\",\n this._x_or_y + \" axis_label\").attr(\"writing-mode\", this._writing_mode)\n .text(this._label_string);\n }\n };\n return that;\n };\n}();\n\njsplotlib.parse_marker = function(style) {\n if (!style) return \"x\";\n switch (style) {\n case '.':\n return \".\";\n case ',':\n return \"x\";\n case 'o':\n return \"o\";\n case 'v':\n return \"x\";\n case '^':\n return \"x\";\n case '<':\n return \"x\";\n case '>':\n return \"x\";\n case '1':\n return \"x\";\n case '2':\n return \"x\";\n case '3':\n return \"x\";\n case '4':\n return \"x\";\n case 's':\n return \"s\";\n case 'p':\n return \"x\";\n case '*':\n return \"x\";\n case 'h':\n return \"x\";\n case 'H':\n return \"x\";\n case '+':\n return \"x\";\n case 'x':\n return \"x\";\n case 'D':\n return \"x\";\n case 'd':\n return \"x\";\n case '|':\n return \"x\";\n case '_':\n return \"x\";\n default:\n return \"\";\n }\n};\n\n/**\nProcess a MATLAB style color/line style format string. Return a\n(*linestyle*, *color*) tuple as a result of the processing. Default\nvalues are ('-', 'b'). Example format strings include:\n\n* 'ko': black circles\n* '.b': blue dots\n* 'r--': red dashed lines\n\n.. seealso::\n\n :func:`~matplotlib.Line2D.lineStyles` and\n :func:`~matplotlib.pyplot.colors`\n for all possible styles and color format string.\n**/\njsplotlib._process_plot_format = function(fmt) {\n var linestyle = null;\n var marker = null;\n var color = null;\n\n // Is fmt just a colorspec\n try {\n color = jsplotlib.to_rgb(fmt);\n if (color) {\n return {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': color\n };\n }\n } catch (e) {}\n\n // handle the multi char special cases and strip them for the string\n if (fmt.search(/--/) >= 0) {\n linestyle = '--';\n fmt = fmt.replace(/--/, '');\n }\n if (fmt.search(/-\\./) >= 0) {\n linestyle = '-.';\n fmt = fmt.replace(/-\\./, '');\n }\n if (fmt.search(/ /) >= 0) {\n linestyle = '';\n fmt = fmt.replace(/ /, '');\n }\n\n var i;\n for (i = 0; i < fmt.length; i++) {\n var c = fmt.charAt(i);\n if (jsplotlib.Line2D.lineStyles[c]) {\n if (linestyle) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two linestyle symbols');\n }\n linestyle = c;\n } else if (jsplotlib.Line2D.lineMarkers[c]) {\n if (marker) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two marker symbols');\n }\n marker = c;\n } else if (jsplotlib.colors[c]) {\n if (color) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two color symbols');\n }\n color = c;\n } else {\n throw new Sk.builtin.ValueError('Unrecognized character ' + c +\n ' in format string');\n }\n }\n\n if (!linestyle && !marker) {\n // use defaults --> rcParams['lines.linestyle']\n linestyle = '-';\n }\n if (!linestyle) {\n linestyle = ' ';\n }\n if (!marker) {\n marker = '';\n }\n\n return {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': color\n };\n};\n\n/**\n https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py\n http://matplotlib.org/api/colors_api.html\n\n Returns an *RGB* tuple of three floats from 0-1.\n\n *arg* can be an *RGB* or *RGBA* sequence or a string in any of\n several forms:\n\n 1) a letter from the set 'rgbcmykw'\n 2) a hex color string, like '#00FFFF'\n 3) a standard name, like 'aqua'\n 4) a string representation of a float, like '0.4',\n indicating gray on a 0-1 scale\n\n if *arg* is *RGBA*, the *A* will simply be discarded.\n**/\njsplotlib.to_rgb = function(fmt) {\n if (!fmt) return null;\n\n var color = null;\n\n if (typeof fmt == \"string\") {\n fmt_lower = fmt.toLowerCase();\n\n if (jsplotlib.colors[fmt_lower])\n return jsplotlib.hex2color(jsplotlib.cnames[jsplotlib.colors[fmt_lower]]);\n\n // is inside cnames array?\n if (jsplotlib.cnames[fmt_lower])\n return jsplotlib.hex2color(jsplotlib.cnames[fmt_lower]);\n\n if (fmt_lower.indexOf('#') === 0) {\n return jsplotlib.hex2color(fmt_lower);\n }\n\n // is it simple grey shade?\n var fl = parseFloat(fmt_lower);\n if (isNaN(fl)) {\n throw new Sk.builtin.ValueError('cannot convert argument to rgb sequence');\n }\n\n if (fl < 0 || fl > 1) {\n throw new Sk.builtin.ValueError('gray (string) must be in range 0-1');\n }\n\n return [fl, fl, fl];\n }\n\n // check if its a color tuple [r,g,b, [a]] with values from [0-1]\n if (Array.isArray(fmt)) {\n if (fmt.length > 4 || fmt.length < 3)\n throw new Sk.builtin.ValueError('sequence length is ' + fmt.length +\n '; must be 3 or 4');\n\n color = fmt.slice(0, 3);\n var i;\n\n for (i = 0; i < 3; i++) {\n var fl_rgb = parseFloat(fmt);\n\n if (fl_rgb < 0 || fl_rgb > 1)\n throw new Sk.builtin.ValueError(\n 'number in rbg sequence outside 0-1 range');\n }\n }\n\n return color;\n};\n\n/**\n Take a hex string *s* and return the corresponding rgb 3-tuple\n Example: #efefef -> (0.93725, 0.93725, 0.93725)\n**/\njsplotlib.hex2color = function(s) {\n if (!s || typeof s != \"string\") {\n throw new Sk.builtin.TypeError(\"hex2color requires a string argument\");\n }\n // check if it is a hex value\n var i;\n var s_copy = s;\n var hex_tuple = [];\n for (i = 0; i < 3; i++) {\n var match = s_copy.match(/(?:[0-9a-fA-F]){1,2}$/);\n if (match && match.length === 1) {\n hex_tuple.push(match[0]);\n s_copy = s_copy.substring(0, match.index);\n }\n }\n //var match = s.match(/^#(?:[0-9a-fA-F]{3}){1,2}$/);\n if (hex_tuple.length === 3) {\n // yeah positiv --> convert into right color spec\n var color = [];\n color[0] = parseInt(hex_tuple[0], 16) / 255.0;\n color[1] = parseInt(hex_tuple[1], 16) / 255.0;\n color[2] = parseInt(hex_tuple[2], 16) / 255.0;\n\n return color.reverse();\n } else {\n throw new Sk.builtin.ValueError('invalid hex color string \"' + s + '\"');\n }\n};\n\n/**\n Expects and rgb tuple with values [0,1]\n**/\njsplotlib.rgb2hex = function(rgb) {\n if (!rgb) return null;\n\n if (rgb.length && rgb.length >= 3) {\n var i;\n // some hacky code to rebuild string format :(\n var hex_str = '#';\n for (i = 0; i < 3; i++) {\n var val = Math.round(rgb[i] * 255).toString(16);\n hex_str += val.length == 2 ? val : '0' + val;\n }\n\n return hex_str;\n }\n};\n\njsplotlib.linspace = function(min, max, N) {\n var newscale = d3.scale.linear().domain([1, N]).range([min, max]);\n var data = [];\n for (var i = 1; i <= N; i++) {\n var output = newscale(i);\n if (min instanceof Date) {\n output = new Date(output);\n }\n data.push(output);\n }\n return data;\n};\n\njsplotlib.range = function(N) {\n var l = [];\n for (var i = 0; i < N; i++) {\n l.push(i);\n }\n return l;\n};\n\njsplotlib.ones = function(N) {\n var l = [];\n for (var i = 0; i < N; i++) {\n l.push(1);\n }\n return l;\n};\n\n// Skulpt translation\nvar $builtinmodule = function(name) {\n var mod = {};\n var chart;\n var plot; // TODO, we should support multiple lines here\n var canvas;\n\n // import numpy\n var CLASS_NDARRAY = \"numpy.ndarray\"; // maybe make identifier accessible in numpy module\n var np = Sk.importModule(\"numpy\");\n var ndarray_f = np['$d'].array.func_code;\n var getitem_f = np['$d'][CLASS_NDARRAY]['__getitem__'].func_code;\n var ndarray = Sk.misceval.callsim(np['$d'].array.func_code, new Sk.builtin.list([1, 2, 3, 4]));\n\n var create_chart = function() {\n /* test if Canvas is available should be moved to create_chart function */\n if (Sk.console === undefined) {\n throw new Sk.builtin.NameError(\n \"Can not resolve drawing area. Sk.console is undefined!\");\n }\n\n if (!chart) {\n //$(Sk.matplotlibCanvas).empty();\n var width = Sk.console.height * 2;\n var height = Sk.console.height * 1.25;\n chart = jsplotlib.make_chart(width, height, Sk.console, false);\n }\n };\n\n mod.values = Array();\n // Main plotting function\n var plot_f = function(kwa) {\n // http://matplotlib.org/api/pyplot_api.html\n // http://matplotlib.org/api/artist_api.html#matplotlib.lines.Line2D\n //debugger;\n Sk.builtin.pyCheckArgs(\"plotk\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1);\n mod.values.push(args);\n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n\n // try parsing plot args\n // possible xdata, ydata, stylestring\n // or x1, y1, stylestring1, x2, y2, stylestring2\n // or ydata, stylestring\n /*\n plot(x, y) # plot x and y using default line style and color\n plot(x, y, 'bo') # plot x and y using blue circle markers\n plot(y) # plot y using x as index array 0..N-1\n plot(y, 'r+') # ditto, but with red plusses\n */\n\n // variable definitions for args\n var xdata = [];\n var ydata = [];\n var stylestring = []; // we support only one at the moment\n var i = 0;\n var lines = 0;\n var xdata_not_ydata_flag = true;\n var slice = new Sk.builtin.slice(0, undefined, 1); // getting complete first dimension of ndarray\n\n for (i = 0; i < args.length; i++) {\n if (args[i] instanceof Sk.builtin.list || Sk.abstr.typeName(args[i]) === CLASS_NDARRAY) {\n // special treatment for ndarrays, though we allow basic lists too\n var _unpacked;\n if (Sk.abstr.typeName(args[i]) === CLASS_NDARRAY) {\n // we get the first dimension, no 2-dim data\n _unpacked = Sk.ffi.unwrapn(args[i]);\n var first_dim_size = 0;\n if (_unpacked && _unpacked.shape && _unpacked.shape[0]) {\n first_dim_size = _unpacked.shape[0];\n } else {\n throw new Sk.builtin.ValueError('args contain \"' + CLASS_NDARRAY + '\" without elements or malformed shape.');\n }\n _unpacked = _unpacked.buffer.slice(0, first_dim_size); // buffer array of first dimension\n _unpacked = _unpacked.map(function(x) {\n return Sk.ffi.remapToJs(x);\n })\n } else {\n _unpacked = Sk.ffi.remapToJs(args[i]);\n }\n\n // unwraps x and y, but no 2-dim-data\n if (xdata_not_ydata_flag) {\n xdata.push(_unpacked);\n xdata_not_ydata_flag = false;\n } else {\n ydata.push(_unpacked);\n xdata_not_ydata_flag = true;\n }\n } else if (Sk.builtin.checkString(args[i])) {\n stylestring.push(Sk.ffi.remapToJs(args[i]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[i]) +\n \"' is not supported for *args[\" + i + \"].\");\n }\n }\n\n /* handle special cases\n only supplied y\n only supplied 1 array and stylestring\n */\n if ((args.length === 1) || (args.length === 2 && (xdata.length === 1 &&\n ydata.length === 0))) {\n // only y supplied\n xdata.forEach(function(element) {\n ydata.push(element);\n });\n xdata[0] = [];\n }\n \n \n if (Sk.skip_drawing !== true) {\n\n // empty canvas from previous plots\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n // create line objects\n var line;\n\n if (xdata.length === 1 && ydata.length === 1 && stylestring.length === 0) {\n // handle case for plot(x, y)\n // Where the x and y are integers, not lists\n line = new jsplotlib.Line2D(xdata[0], ydata[0]);\n plot.add_artist(line);\n } else if (xdata.length === ydata.length && xdata.length === stylestring.length) {\n for (i = 0; i < xdata.length; i++) {\n line = new jsplotlib.Line2D(xdata[i], ydata[i]);\n var ftm_tuple = jsplotlib._process_plot_format(stylestring[i]);\n line.update({\n 'linestyle': ftm_tuple.linestyle,\n 'marker': jsplotlib.parse_marker(ftm_tuple.marker),\n 'color': ftm_tuple.color\n });\n plot.add_artist(line);\n }\n } else {\n throw new Sk.builtin.ValueError('Cannot parse given combination of \"*args\"!');\n }\n\n // set kwargs that apply for all lines\n plot.update(kwargs);\n } else {\n if (!plot) {\n plot = {\"_artists\":[]};\n }\n var line;\n if (xdata.length === 1 && ydata.length === 1 && stylestring.length === 0) {\n plot._artists.push([xdata[0], ydata[0]]);\n } else if (xdata.length === ydata.length && xdata.length === stylestring.length) {\n for (i = 0; i < xdata.length; i++) {\n plot._artists.push([xdata[i], ydata[i]]);\n }\n } else {\n throw new Sk.builtin.ValueError('Cannot parse given combination of \"*args\"!');\n }\n \n }\n\n // result\n var result = [];\n\n return new Sk.builtins.tuple(result);\n };\n plot_f.co_kwargs = true;\n mod.plot = new Sk.builtin.func(plot_f);\n\n var show_f = function() {\n // call drawing routine\n if (Sk.skip_drawing !== true) {\n if (plot && plot.draw) {\n plot.draw();\n } else {\n throw new Sk.builtin.ValueError(\n \"Can not call show without any plot created.\");\n }\n if (Sk.console.png_mode) {\n var lines = plot._artists.map(function(elem) { return [elem._x, elem._y] })\n var xml = new XMLSerializer().serializeToString(chart[0][0]);\n var data = \"data:image/svg+xml;base64,\" + btoa(unescape(encodeURIComponent(xml)));\n var img = document.createElement(\"img\");\n img.setAttribute('src', data);\n img.style.display = 'block';\n img.onload = function() {\n img.onload = null;\n //TODO: Make this capture a class descendant. Cross the D3/Jquery barrier!\n var canvas = document.createElement('canvas');\n canvas.width = Sk.console.height * 2;\n canvas.height = Sk.console.height * 1.25;\n var ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n var canvasUrl = canvas.toDataURL(\"image/png\");\n img.setAttribute('src', canvasUrl);\n chart[0][0].parentNode.replaceChild(img, chart[0][0])\n Sk.console.printHtml(img, lines);\n }\n img.onerror = function() {\n \n }\n } else {\n Sk.console.printHtml(chart, lines);\n }\n } else {\n var lines = plot._artists;\n Sk.console.printHtml(chart, lines);\n }\n };\n mod.show = new Sk.builtin.func(show_f);\n\n var title_f = function(label, fontdict, loc) {\n Sk.builtin.pyCheckArgs(\"title\", arguments, 1, 3);\n\n if (!Sk.builtin.checkString(label)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(label) +\n \"' is not supported for title.\");\n }\n\n var label_unwrap = Sk.ffi.remapToJs(label);\n\n if (Sk.skip_drawing !== true) {\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n if (plot && plot.title) {\n plot.title(label_unwrap);\n }\n }\n\n return new Sk.builtin.str(label_unwrap);\n };\n\n title_f.co_varnames = ['label', 'fontdict', 'loc', ];\n title_f.$defaults = [null, Sk.builtin.none.none$, Sk.builtin.none.none$,\n Sk.builtin.none.none$\n ];\n mod.title = new Sk.builtin.func(title_f);\n\n var axis_f = function(label, fontdict, loc) {\n Sk.builtin.pyCheckArgs(\"axis\", arguments, 0, 3);\n\n // when called without any arguments it should return the current axis limits\n\n if (plot && plot._axes) {\n console.log(plot._axes);\n }\n\n // >>> axis(v)\n // sets the min and max of the x and y axes, with\n // ``v = [xmin, xmax, ymin, ymax]``.::\n\n //The xmin, xmax, ymin, ymax tuple is returned\n var res;\n\n return Sk.ffi.remapToPy([]);\n };\n\n axis_f.co_varnames = ['label', 'fontdict', 'loc', ];\n axis_f.$defaults = [null, Sk.builtin.none.none$, Sk.builtin.none.none$,\n Sk.builtin.none.none$\n ];\n mod.axis = new Sk.builtin.func(axis_f);\n\n var xlabel_f = function(s, fontdict, loc) {\n Sk.builtin.pyCheckArgs(\"xlabel\", arguments, 1, 3);\n\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(s) +\n \"' is not supported for s.\");\n }\n\n if (Sk.skip_drawing !== true) {\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n if (plot && plot.xlabel) {\n plot.xlabel(Sk.ffi.remapToJs(s));\n }\n }\n };\n\n xlabel_f.co_varnames = ['s', 'fontdict', 'loc', ];\n xlabel_f.$defaults = [null, Sk.builtin.none.none$, Sk.builtin.none.none$,\n Sk.builtin.none.none$\n ];\n mod.xlabel = new Sk.builtin.func(xlabel_f);\n\n var ylabel_f = function(s, fontdict, loc) {\n Sk.builtin.pyCheckArgs(\"ylabel\", arguments, 1, 3);\n\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(s) +\n \"' is not supported for s.\");\n }\n\n if (Sk.skip_drawing !== true) {\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n if (plot && plot.ylabel) {\n plot.ylabel(Sk.ffi.remapToJs(s));\n }\n }\n };\n\n ylabel_f.co_varnames = ['s', 'fontdict', 'loc', ];\n ylabel_f.$defaults = [null, Sk.builtin.none.none$, Sk.builtin.none.none$,\n Sk.builtin.none.none$\n ];\n mod.ylabel = new Sk.builtin.func(ylabel_f);\n\n // Clear the current figure\n var clf_f = function() {\n // clear all\n chart = null;\n plot = null;\n\n /*if (Sk.matplotlibCanvas !== undefined) {\n $(Sk.matplotlibCanvas).empty();\n }*/\n };\n\n mod.clf = new Sk.builtin.func(clf_f);\n\n /* list of not implemented methods */\n mod.findobj = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"findobj is not yet implemented\");\n });\n mod.switch_backend = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"switch_backend is not yet implemented\");\n });\n mod.isinteractive = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"isinteractive is not yet implemented\");\n });\n mod.ioff = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"ioff is not yet implemented\");\n });\n mod.ion = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"ion is not yet implemented\");\n });\n mod.pause = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"pause is not yet implemented\");\n });\n mod.rc = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"rc is not yet implemented\");\n });\n mod.rc_context = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"rc_context is not yet implemented\");\n });\n mod.rcdefaults = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"rcdefaults is not yet implemented\");\n });\n mod.gci = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"gci is not yet implemented\");\n });\n mod.sci = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"sci is not yet implemented\");\n });\n mod.xkcd = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"xkcd is not yet implemented\");\n });\n mod.figure = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"figure is not yet implemented\");\n });\n mod.gcf = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"gcf is not yet implemented\");\n });\n mod.get_fignums = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"get_fignums is not yet implemented\");\n });\n mod.get_figlabels = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"get_figlabels is not yet implemented\");\n });\n mod.get_current_fig_manager = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"get_current_fig_manager is not yet implemented\");\n });\n mod.connect = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"connect is not yet implemented\");\n });\n mod.disconnect = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"disconnect is not yet implemented\");\n });\n mod.close = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"close is not yet implemented\");\n });\n mod.savefig = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"savefig is not yet implemented\");\n });\n mod.ginput = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"ginput is not yet implemented\");\n });\n mod.waitforbuttonpress = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"waitforbuttonpress is not yet implemented\");\n });\n mod.figtext = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"figtext is not yet implemented\");\n });\n mod.suptitle = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"suptitle is not yet implemented\");\n });\n mod.figimage = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"figimage is not yet implemented\");\n });\n mod.figlegend = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"figlegend is not yet implemented\");\n });\n mod.hold = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"hold is not yet implemented\");\n });\n mod.ishold = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"ishold is not yet implemented\");\n });\n mod.over = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"over is not yet implemented\");\n });\n mod.delaxes = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"delaxes is not yet implemented\");\n });\n mod.sca = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"sca is not yet implemented\");\n });\n mod.gca = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"gca is not yet implemented\");\n });\n mod.subplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"subplot is not yet implemented\");\n });\n mod.subplots = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"subplots is not yet implemented\");\n });\n mod.subplot2grid = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"subplot2grid is not yet implemented\");\n });\n mod.twinx = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"twinx is not yet implemented\");\n });\n mod.twiny = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"twiny is not yet implemented\");\n });\n mod.subplots_adjust = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"subplots_adjust is not yet implemented\");\n });\n mod.subplot_tool = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"subplot_tool is not yet implemented\");\n });\n mod.tight_layout = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"tight_layout is not yet implemented\");\n });\n mod.box = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"box is not yet implemented\");\n });\n mod.xlim = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"xlim is not yet implemented\");\n });\n mod.ylim = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"ylim is not yet implemented\");\n });\n mod.xscale = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"xscale is not yet implemented\");\n });\n mod.yscale = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"yscale is not yet implemented\");\n });\n mod.xticks = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"xticks is not yet implemented\");\n });\n mod.yticks = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"yticks is not yet implemented\");\n });\n mod.minorticks_on = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"minorticks_on is not yet implemented\");\n });\n mod.minorticks_off = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"minorticks_off is not yet implemented\");\n });\n mod.rgrids = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"rgrids is not yet implemented\");\n });\n mod.thetagrids = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"thetagrids is not yet implemented\");\n });\n mod.plotting = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"plotting is not yet implemented\");\n });\n mod.get_plot_commands = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"get_plot_commands is not yet implemented\");\n });\n mod.colors = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"colors is not yet implemented\");\n });\n mod.colormaps = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"colormaps is not yet implemented\");\n });\n mod._setup_pyplot_info_docstrings = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"_setup_pyplot_info_docstrings is not yet implemented\");\n });\n mod.colorbar = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"colorbar is not yet implemented\");\n });\n mod.clim = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"clim is not yet implemented\");\n });\n mod.set_cmap = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"set_cmap is not yet implemented\");\n });\n mod.imread = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"imread is not yet implemented\");\n });\n mod.imsave = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"imsave is not yet implemented\");\n });\n mod.matshow = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"matshow is not yet implemented\");\n });\n mod.polar = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"polar is not yet implemented\");\n });\n mod.plotfile = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"plotfile is not yet implemented\");\n });\n mod._autogen_docstring = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"_autogen_docstring is not yet implemented\");\n });\n mod.acorr = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"acorr is not yet implemented\");\n });\n mod.arrow = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"arrow is not yet implemented\");\n });\n mod.axhline = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"axhline is not yet implemented\");\n });\n mod.axhspan = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"axhspan is not yet implemented\");\n });\n mod.axvline = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"axvline is not yet implemented\");\n });\n mod.axvspan = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"axvspan is not yet implemented\");\n });\n mod.bar = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"bar is not yet implemented\");\n });\n mod.barh = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"barh is not yet implemented\");\n });\n mod.broken_barh = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"broken_barh is not yet implemented\");\n });\n mod.boxplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"boxplot is not yet implemented\");\n });\n mod.cohere = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"cohere is not yet implemented\");\n });\n mod.clabel = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"clabel is not yet implemented\");\n });\n mod.contour = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"contour is not yet implemented\");\n });\n mod.contourf = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"contourf is not yet implemented\");\n });\n mod.csd = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"csd is not yet implemented\");\n });\n mod.errorbar = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"errorbar is not yet implemented\");\n });\n mod.eventplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"eventplot is not yet implemented\");\n });\n mod.fill = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"fill is not yet implemented\");\n });\n mod.fill_between = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"fill_between is not yet implemented\");\n });\n mod.fill_betweenx = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"fill_betweenx is not yet implemented\");\n });\n mod.hexbin = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"hexbin is not yet implemented\");\n });\n \n var hist_f = function(kwa) {\n // Check kwarg argument\n Sk.builtin.pyCheckArgs(\"histk\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1);\n mod.values.push(args);\n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n \n // process arguments into a list\n var ydata = [];\n var stylestring = []; // we support only one at the moment\n \n if (args[0] instanceof Sk.builtin.list) {\n ydata.push(Sk.ffi.remapToJs(args[0]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[0]) +\n \"' is not supported for *args[\" + 0 + \"].\");\n }\n \n if (args[1]) {\n if (Sk.builtin.checkString(args[1])) {\n stylestring.push(Sk.ffi.remapToJs(args[1]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[1]) +\n \"' is not supported for *args[\" + 1 + \"].\");\n }\n } else {\n stylestring.push('');\n }\n \n if (Sk.skip_drawing !== true) {\n\n // empty canvas from previous plots\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n // create line objects\n var bar;\n\n for (i = 0; i < ydata.length; i++) {\n bars = new jsplotlib.Bars(ydata[i]);\n var ftm_tuple = jsplotlib._process_plot_format(stylestring[i]);\n bars.update({\n 'linestyle': ftm_tuple.linestyle,\n 'marker': jsplotlib.parse_marker(ftm_tuple.marker),\n 'color': ftm_tuple.color\n });\n plot.add_artist(bars);\n }\n\n // set kwargs that apply for all lines\n plot.update(kwargs);\n } else {\n if (!plot) {\n plot = {\"_artists\":[]};\n }\n for (i = 0; i < ydata.length; i++) {\n plot._artists.push([ydata[i]]);\n }\n \n }\n\n // result\n var result = [];\n\n return new Sk.builtins.tuple(result);\n }\n hist_f.co_kwargs = true;\n mod.hist = new Sk.builtin.func(hist_f);\n mod.hist2d = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"hist2d is not yet implemented\");\n });\n mod.hlines = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"hlines is not yet implemented\");\n });\n mod.loglog = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"loglog is not yet implemented\");\n });\n mod.magnitude_spectrum = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"magnitude_spectrum is not yet implemented\");\n });\n mod.pcolor = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"pcolor is not yet implemented\");\n });\n mod.pcolormesh = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"pcolormesh is not yet implemented\");\n });\n mod.phase_spectrum = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"phase_spectrum is not yet implemented\");\n });\n mod.pie = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"pie is not yet implemented\");\n });\n mod.plot_date = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"plot_date is not yet implemented\");\n });\n mod.psd = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"psd is not yet implemented\");\n });\n mod.quiver = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"quiver is not yet implemented\");\n });\n mod.quiverkey = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"quiverkey is not yet implemented\");\n });\n var scatter_f = function(kwa) {\n Sk.builtin.pyCheckArgs(\"scatter\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1);\n mod.values.push(args);\n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n\n // try parsing plot args\n // possible xdata, ydata, stylestring\n /*\n plot(x, y, 'bo') # plot x and y using blue circle markers\n */\n\n // variable definitions for args\n var xdata = [];\n var ydata = [];\n var stylestring = []; // we support only one at the moment\n var i = 0;\n var lines = 0;\n\n if (args[0] instanceof Sk.builtin.list) {\n xdata.push(Sk.ffi.remapToJs(args[0]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[0]) +\n \"' is not supported for *args[\" + 0 + \"].\");\n }\n if (args[1] instanceof Sk.builtin.list) {\n ydata.push(Sk.ffi.remapToJs(args[1]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[1]) +\n \"' is not supported for *args[\" + 1 + \"].\");\n }\n if (args[2] != undefined) {\n if (Sk.builtin.checkString(args[2])) {\n stylestring.push(Sk.ffi.remapToJs(args[2]));\n } else {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(args[2]) +\n \"' is not supported for *args[\" + 2 + \"].\");\n }\n } else {\n stylestring.push('o');\n }\n \n if (Sk.skip_drawing !== true) {\n\n // empty canvas from previous plots\n create_chart();\n // create new plot instance, should be replaced with Line2D and then added to the plot\n if (!plot) {\n plot = jsplotlib.plot(chart);\n }\n\n // create line objects\n var line;\n \n for (i = 0; i < xdata.length; i++) {\n line = new jsplotlib.Line2D(xdata[i], ydata[i]);\n var ftm_tuple = jsplotlib._process_plot_format(stylestring[i]);\n line.update({\n 'linestyle': ftm_tuple.linestyle,\n 'marker': jsplotlib.parse_marker(ftm_tuple.marker),\n 'color': ftm_tuple.color\n });\n plot.add_artist(line);\n }\n\n // set kwargs that apply for all lines\n plot.update(kwargs);\n } else {\n if (!plot) {\n plot = {\"_artists\":[]};\n }\n for (i = 0; i < xdata.length; i++) {\n plot._artists.push([xdata[i], ydata[i]]);\n }\n }\n\n // result\n var result = [];\n\n return new Sk.builtins.tuple(result);\n };\n scatter_f.co_kwargs = true;\n mod.scatter = new Sk.builtin.func(scatter_f);\n mod.semilogx = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"semilogx is not yet implemented\");\n });\n mod.semilogy = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"semilogy is not yet implemented\");\n });\n mod.specgram = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"specgram is not yet implemented\");\n });\n mod.stackplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"stackplot is not yet implemented\");\n });\n mod.stem = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"stem is not yet implemented\");\n });\n mod.step = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"step is not yet implemented\");\n });\n mod.streamplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"streamplot is not yet implemented\");\n });\n mod.tricontour = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"tricontour is not yet implemented\");\n });\n mod.tricontourf = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"tricontourf is not yet implemented\");\n });\n mod.tripcolor = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"tripcolor is not yet implemented\");\n });\n mod.triplot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"triplot is not yet implemented\");\n });\n mod.vlines = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"vlines is not yet implemented\");\n });\n mod.xcorr = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"xcorr is not yet implemented\");\n });\n mod.barbs = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"barbs is not yet implemented\");\n });\n mod.cla = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"cla is not yet implemented\");\n });\n mod.grid = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"grid is not yet implemented\");\n });\n mod.legend = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"legend is not yet implemented\");\n });\n mod.table = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"table is not yet implemented\");\n });\n mod.text = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"text is not yet implemented\");\n });\n mod.annotate = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"annotate is not yet implemented\");\n });\n mod.ticklabel_format = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"ticklabel_format is not yet implemented\");\n });\n mod.locator_params = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"locator_params is not yet implemented\");\n });\n mod.tick_params = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"tick_params is not yet implemented\");\n });\n mod.margins = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"margins is not yet implemented\");\n });\n mod.autoscale = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"autoscale is not yet implemented\");\n });\n mod.autumn = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"autumn is not yet implemented\");\n });\n mod.cool = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"cool is not yet implemented\");\n });\n mod.copper = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"copper is not yet implemented\");\n });\n mod.flag = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"flag is not yet implemented\");\n });\n mod.gray = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"gray is not yet implemented\");\n });\n mod.hot = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"hot is not yet implemented\");\n });\n mod.hsv = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"hsv is not yet implemented\");\n });\n mod.jet = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\"jet is not yet implemented\");\n });\n mod.pink = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"pink is not yet implemented\");\n });\n mod.prism = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"prism is not yet implemented\");\n });\n mod.spring = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"spring is not yet implemented\");\n });\n mod.summer = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"summer is not yet implemented\");\n });\n mod.winter = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"winter is not yet implemented\");\n });\n mod.spectral = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(\n \"spectral is not yet implemented\");\n });\n\n return mod;\n};\n", "src/lib/webgl/primitives.js": "// most of this file is from 'tdl'\n\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n\n\n /**\n * AttribBuffer manages a TypedArray as an array of vectors.\n *\n * @param {number} numComponents Number of components per\n * vector.\n * @param {number|!Array.<number>} numElements Number of vectors or the data.\n * @param {string} opt_type The type of the TypedArray to\n * create. Default = 'Float32Array'.\n * @param {!Array.<number>} opt_data The data for the array.\n */\n var AttribBuffer = function(\n numComponents, numElements, opt_type) {\n opt_type = opt_type || 'Float32Array';\n var type = window[opt_type];\n if (numElements.length) {\n this.buffer = new type(numElements);\n numElements = this.buffer.length / numComponents;\n this.cursor = numElements;\n } else {\n this.buffer = new type(numComponents * numElements);\n this.cursor = 0;\n }\n this.numComponents = numComponents;\n this.numElements = numElements;\n this.type = opt_type;\n };\n\n AttribBuffer.prototype.stride = function() {\n return 0;\n };\n\n AttribBuffer.prototype.offset = function() {\n return 0;\n };\n\n AttribBuffer.prototype.getElement = function(index) {\n var offset = index * this.numComponents;\n var value = [];\n for (var ii = 0; ii < this.numComponents; ++ii) {\n value.push(this.buffer[offset + ii]);\n }\n return value;\n };\n\n AttribBuffer.prototype.setElement = function(index, value) {\n var offset = index * this.numComponents;\n for (var ii = 0; ii < this.numComponents; ++ii) {\n this.buffer[offset + ii] = value[ii];\n }\n };\n\n AttribBuffer.prototype.clone = function() {\n var copy = new AttribBuffer(\n this.numComponents, this.numElements, this.type);\n copy.pushArray(this);\n return copy;\n }\n\n AttribBuffer.prototype.push = function(value) {\n this.setElement(this.cursor++, value);\n };\n\n AttribBuffer.prototype.pushArray = function(array) {\n // this.buffer.set(array, this.cursor * this.numComponents);\n // this.cursor += array.numElements;\n for (var ii = 0; ii < array.numElements; ++ii) {\n this.push(array.getElement(ii));\n }\n };\n\n AttribBuffer.prototype.pushArrayWithOffset =\n function(array, offset) {\n for (var ii = 0; ii < array.numElements; ++ii) {\n var elem = array.getElement(ii);\n for (var jj = 0; jj < offset.length; ++jj) {\n elem[jj] += offset[jj];\n }\n this.push(elem);\n }\n };\n\n /**\n * Computes the extents\n * @param {!AttribBuffer} positions The positions\n * @return {!{min: !tdl.math.Vector3, max:!tdl.math.Vector3}}\n * The min and max extents.\n */\n AttribBuffer.prototype.computeExtents = function() {\n var numElements = this.numElements;\n var numComponents = this.numComponents;\n var minExtent = this.getElement(0);\n var maxExtent = this.getElement(0);\n for (var ii = 1; ii < numElements; ++ii) {\n var element = this.getElement(ii);\n for (var jj = 0; jj < numComponents; ++jj) {\n minExtent[jj] = Math.min(minExtent[jj], element[jj]);\n maxExtent[jj] = Math.max(maxExtent[jj], element[jj]);\n }\n }\n return {min: minExtent, max: maxExtent};\n };\n\n\n /**\n * Creates the vertices and indices for a cube. The\n * cube will be created around the origin. (-size / 2, size / 2)\n *\n * @param {number} size Width, height and depth of the cube.\n * @return {!Object.<string, !tdl.primitives.AttribBuffer>} The\n * created plane vertices.\n */\n mod.createCube = new Sk.builtin.func(function(size)\n {\n var CUBE_FACE_INDICES_ = [\n [3, 7, 5, 1],\n [0, 4, 6, 2],\n [6, 7, 3, 2],\n [0, 1, 5, 4],\n [5, 7, 6, 4],\n [2, 3, 1, 0]\n ];\n\n var k = size / 2;\n\n var cornerVertices = [\n [-k, -k, -k],\n [+k, -k, -k],\n [-k, +k, -k],\n [+k, +k, -k],\n [-k, -k, +k],\n [+k, -k, +k],\n [-k, +k, +k],\n [+k, +k, +k]\n ];\n\n var faceNormals = [\n [+1, +0, +0],\n [-1, +0, +0],\n [+0, +1, +0],\n [+0, -1, +0],\n [+0, +0, +1],\n [+0, +0, -1]\n ];\n\n var uvCoords = [\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1]\n ];\n\n var numVertices = 6 * 4;\n var positions = new AttribBuffer(3, numVertices);\n var normals = new AttribBuffer(3, numVertices);\n var texCoords = new AttribBuffer(2, numVertices);\n var indices = new AttribBuffer(3, 6 * 2, 'Uint16Array');\n\n for (var f = 0; f < 6; ++f) {\n var faceIndices = CUBE_FACE_INDICES_[f];\n for (var v = 0; v < 4; ++v) {\n var position = cornerVertices[faceIndices[v]];\n var normal = faceNormals[f];\n var uv = uvCoords[v];\n\n // Each face needs all four vertices because the normals and texture\n // coordinates are not all the same.\n positions.push(position);\n normals.push(normal);\n texCoords.push(uv);\n\n }\n // Two triangles make a square face.\n var offset = 4 * f;\n indices.push([offset + 0, offset + 1, offset + 2]);\n indices.push([offset + 0, offset + 2, offset + 3]);\n }\n\n return {\n position: positions,\n normal: normals,\n texCoord: texCoords,\n indices: indices\n };\n });\n\n return mod;\n};\n", "src/lib/webgl/__init__.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n\n var makeFailHTML = function(msg) {\n return '' +\n '<table style=\"background-color: #8CE; width: 100%; height: 100%;\"><tr>' +\n '<td align=\"center\">' +\n '<div style=\"display: table-cell; vertical-align: middle;\">' +\n '<div style=\"\">' + msg + '</div>' +\n '</div>' +\n '</td></tr></table>';\n };\n\n var GET_A_WEBGL_BROWSER = '' +\n 'This page requires a browser that supports WebGL.<br/>' +\n '<a href=\"http://get.webgl.org\">Click here to upgrade your browser.</a>';\n\n var NEED_HARDWARE = '' +\n \"It doesn't appear your computer can support WebGL.<br/>\" +\n '<a href=\"http://get.webgl.org\">Click here for more information.</a>';\n \n var create3DContext = function(canvas) {\n var names = [\"webgl\", \"experimental-webgl\", \"webkit-3d\", \"moz-webgl\"];\n var gl = null;\n for (var ii = 0; ii < names.length; ++ii) {\n try {\n gl = canvas.getContext(names[ii]);\n }\n catch(e) {\n }\n if (gl) {\n break;\n }\n }\n if (gl) {\n // Disallow selection by default. This keeps the cursor from changing to an\n // I-beam when the user clicks and drags. It's easier on the eyes.\n function returnFalse() {\n return false;\n }\n\n canvas.onselectstart = returnFalse;\n canvas.onmousedown = returnFalse;\n }\n return gl;\n };\n\n var setupWebGL = function(canvasContainerId, opt_canvas) {\n var container = document.getElementById(canvasContainerId);\n var context;\n if (!opt_canvas) {\n opt_canvas = container.getElementsByTagName(\"canvas\")[0];\n }\n if (!opt_canvas) {\n // this browser doesn't support the canvas tag at all. Not even 2d.\n container.innerHTML = makeFailHTML(GET_A_WEBGL_BROWSER);\n return;\n }\n\n var gl = create3DContext(opt_canvas);\n if (!gl) {\n // TODO(gman): fix to official way to detect that it's the user's machine, not the browser.\n var browserStrings = navigator.userAgent.match(/(\\w+\\/.*? )/g);\n var browsers = {};\n try {\n for (var b = 0; b < browserStrings.length; ++b) {\n var parts = browserStrings[b].match(/(\\w+)/g);\n var bb = [];\n for (var ii = 1; ii < parts.length; ++ii) {\n bb.push(parseInt(parts[ii]));\n }\n browsers[parts[0]] = bb;\n }\n }\n catch (e) {\n }\n if (browsers.Chrome &&\n (browsers.Chrome[0] > 7 ||\n (browsers.Chrome[0] == 7 && browsers.Chrome[1] > 0) ||\n (browsers.Chrome[0] == 7 && browsers.Chrome[1] == 0 && browsers.Chrome[2] >= 521))) {\n container.innerHTML = makeFailHTML(NEED_HARDWARE);\n }\n else {\n container.innerHTML = makeFailHTML(GET_A_WEBGL_BROWSER);\n }\n }\n return gl;\n };\n\n /**\n * The Context encapsulates the underlying WebGL native JavaScript API.\n */\n mod.Context = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(\n function(self, canvasid) {\n var canvas = document.getElementById(canvasid.v);\n var gl = setupWebGL(canvasid.v, canvas)\n if (!gl) {\n throw new Error(\"Your browser does not appear to support WebGL.\");\n }\n\n self.gl = gl;\n\n // Copy symbolic constants and functions from native WebGL, encapsulating where necessary. \n for (var k in gl.__proto__) {\n if (typeof gl.__proto__[k] === 'number') {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), gl.__proto__[k]);\n }\n else if (typeof gl.__proto__[k] === \"function\") {\n switch(k) {\n case 'bufferData': {\n }\n break;\n case 'clearColor': {\n }\n break;\n case 'drawArrays': {\n }\n break;\n case 'getAttribLocation': {\n }\n break;\n case 'getUniformLocation': {\n }\n break;\n case 'shaderSource': {\n }\n break;\n case 'uniformMatrix4fv': {\n }\n break;\n case 'vertexAttribPointer': {\n }\n break;\n case 'viewport': {\n }\n break;\n default: {\n (function(key) {\n Sk.abstr.objectSetItem(self['$d'], new Sk.builtin.str(k), new Sk.builtin.func(function() {\n var f = gl.__proto__[key];\n return f.apply(gl, arguments);\n }));\n }(k));\n }\n }\n }\n }\n\n gl.clearColor(100.0/255.0, 149.0/255.0, 237.0/255.0, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n }\n );\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n $loc.bufferData = new Sk.builtin.func(\n function(self, target, data, usage) {\n self.gl.bufferData(target, data.v, usage);\n }\n );\n\n $loc.clearColor = new Sk.builtin.func(\n function(self, red, green, blue, alpha) {\n self.gl.clearColor(Sk.builtin.asnum$(red), Sk.builtin.asnum$(green), Sk.builtin.asnum$(blue), Sk.builtin.asnum$(alpha));\n }\n );\n\n $loc.getAttribLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getAttribLocation(program, name.v);\n }\n );\n\n $loc.getUniformLocation = new Sk.builtin.func(\n function(self, program, name) {\n return self.gl.getUniformLocation(program, name.v);\n }\n );\n\n $loc.shaderSource = new Sk.builtin.func(\n function(self, shader, src) {\n self.gl.shaderSource(shader, src.v);\n }\n );\n\n $loc.drawArrays = new Sk.builtin.func(\n function(self, mode, first, count) {\n self.gl.drawArrays(Sk.builtin.asnum$(mode), Sk.builtin.asnum$(first), Sk.builtin.asnum$(count));\n }\n );\n\n $loc.vertexAttribPointer = new Sk.builtin.func(\n function(self, index, size, type, normalized, stride, dunno) {\n self.gl.vertexAttribPointer(index, Sk.builtin.asnum$(size), Sk.builtin.asnum$(type), normalized, Sk.builtin.asnum$(stride), Sk.builtin.asnum$(dunno));\n }\n );\n\n $loc.viewport = new Sk.builtin.func(\n function(self, x, y, width, height) {\n self.gl.viewport(Sk.builtin.asnum$(x), Sk.builtin.asnum$(y), Sk.builtin.asnum$(width), Sk.builtin.asnum$(height));\n }\n );\n\n $loc.uniformMatrix4fv = new Sk.builtin.func(\n function(self, location, transpose, values) {\n// console.log(\"location \" + (typeof location));\n// console.log(\"transpose \" + (typeof transpose));\n// console.log(\"values.v \" + (typeof values.v));\n self.gl.uniformMatrix4fv(Sk.builtin.asnum$(location), transpose, values.v);\n }\n );\n\n $loc.setDrawFunc = new Sk.builtin.func(function(self, func) {\n var startTime = (new Date()).getTime();\n var intervalId = setInterval(\n function() {\n Sk.misceval.callsim(func, self, (new Date()).getTime() - startTime);\n }, 1000.0 / 60.0); // 60 fps\n });\n\n }, 'Context', []);\n\n mod.Float32Array = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n if (typeof data === \"number\") {\n self.v = new Float32Array(data);\n }\n else {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n }\n });\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Float32Array', []);\n\n /**\n * A 4x4 (mutable) matrix suitable for OpenGL.\n *\n * Mutability is chosen for performance.\n * The inderlying implementation is Float32Array.\n * The indexing of the elements is\n * 0 4 8 12\n * 1 5 9 13\n * 2 6 10 14\n * 3 7 11 15\n */\n mod.Matrix4x4 = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, data) {\n self.v = new Float32Array(Sk.ffi.remapToJs(data));\n });\n\n $loc.identity = new Sk.builtin.func(\n function(self) {\n\n var m = self.v;\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = 0;\n m[15] = 1;\n }\n );\n\n $loc.perspective = new Sk.builtin.func(\n function(self, fov, aspect, near, far) {\n \n var t = Math.tan(Math.PI * 0.5 - 0.5 * (Sk.builtin.asnum$(fov) * Math.PI / 180));\n var a = Sk.builtin.asnum$(aspect)\n var n = Sk.builtin.asnum$(near)\n var f = Sk.builtin.asnum$(far)\n var k = 1.0 / (n - f);\n\n var m = self.v;\n\n m[0] = t / a;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = t;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = (n + f) * k;\n m[11] = -1;\n\n m[12] = 0;\n m[13] = 0;\n m[14] = n * f * k * 2;\n m[15] = 0;\n }\n );\n\n $loc.translate = new Sk.builtin.func(\n function(self, translation) {\n\n var m = self.v;\n var t = Sk.ffi.remapToJs(translation);\n\n m[0] = 1;\n m[1] = 0;\n m[2] = 0;\n m[3] = 0;\n\n m[4] = 0;\n m[5] = 1;\n m[6] = 0;\n m[7] = 0;\n\n m[8] = 0;\n m[9] = 0;\n m[10] = 1;\n m[11] = 0;\n\n m[12] = t[0];\n m[13] = t[1];\n m[14] = t[2];\n m[15] = 1;\n }\n );\n\n $loc.__repr__ = new Sk.builtin.func(function(self) {\n var copy = [];\n for (var i = 0; i < self.v.length; ++i) {\n copy.push(self.v[i]);\n }\n return new Sk.builtin.str(\"[\" + copy.join(', ') + \"]\");\n });\n }, 'Matrix4x4', []);\n\n return mod;\n};", "src/lib/webgl/models.js": "// most of this file is from/based on 'tdl'\n\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n var Buffer = function(array, opt_target) {\n var target = opt_target || gl.ARRAY_BUFFER;\n var buf = gl.createBuffer();\n this.target = target;\n this.buf = buf;\n this.set(array);\n this.numComponents_ = array.numComponents;\n this.numElements_ = array.numElements;\n this.totalComponents_ = this.numComponents_ * this.numElements_;\n if (array.buffer instanceof Float32Array) {\n this.type_ = gl.FLOAT;\n } else if (array.buffer instanceof Uint8Array) {\n this.type_ = gl.UNSIGNED_BYTE;\n } else if (array.buffer instanceof Int8Array) {\n this.type_ = gl._BYTE;\n } else if (array.buffer instanceof Uint16Array) {\n this.type_ = gl.UNSIGNED_SHORT;\n } else if (array.buffer instanceof Int16Array) {\n this.type_ = gl.SHORT;\n } else {\n throw(\"unhandled type:\" + (typeof array.buffer));\n }\n };\n\n Buffer.prototype.set = function(array) {\n gl.bindBuffer(this.target, this.buf);\n gl.bufferData(this.target, array.buffer, gl.STATIC_DRAW);\n }\n\n Buffer.prototype.type = function() {\n return this.type_;\n };\n\n Buffer.prototype.numComponents = function() {\n return this.numComponents_;\n };\n\n Buffer.prototype.numElements = function() {\n return this.numElements_;\n };\n\n Buffer.prototype.totalComponents = function() {\n return this.totalComponents_;\n };\n\n Buffer.prototype.buffer = function() {\n return this.buf;\n };\n\n Buffer.prototype.stride = function() {\n return 0;\n };\n\n Buffer.prototype.offset = function() {\n return 0;\n };\n\n\n\n mod.Model = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, shader, arrays, textures)\n {\n self.buffers = {};\n var setBuffer = function(name, array)\n {\n var target = (name == 'indices') ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;\n b = self.buffers[name];\n if (!b)\n b = new Buffer(array, target);\n else\n b.set(array);\n self.buffers[name] = b;\n };\n for (name in arrays)\n setBuffer(name, arrays[name]);\n\n var textureUnits = {};\n var unit = 0;\n for (var texture in textures)\n {\n textureUnits[texture] = unit++;\n }\n\n self.mode = gl.TRIANGLES;\n self.textures = textures.v;\n self.textureUnits = textureUnits;\n self.shader = shader;\n });\n\n /**\n * Sets up the shared parts of drawing this model. Uses the\n * program, binds the buffers, sets the textures.\n *\n * @param {!Object.<string, *>} uniforms An object of names to\n * values to set on this models uniforms.\n */\n $loc.drawPrep = new Sk.builtin.func(function(self, uniforms)\n {\n var shader = self.shader;\n var buffers = self.buffers;\n var textures = self.textures;\n\n uniforms = Sk.ffi.remapToJs(uniforms);\n\n Sk.misceval.callsim(shader.use, shader);\n\n for (var buffer in buffers) {\n var b = buffers[buffer];\n if (buffer == 'indices') {\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b.buffer());\n } else {\n var attrib = shader.attrib[buffer];\n if (attrib) {\n attrib(b);\n }\n }\n }\n\n for (var texture in textures) {\n var unit = self.textureUnits[texture];\n shader.setUniform$impl(shader, textuer, unit);\n textures[texture].bindToUnit(unit);\n }\n\n for (var uniform in uniforms) {\n shader.setUniform$impl(shader, uniform, uniforms[uniform]);\n }\n });\n\n /**\n * Draws this model.\n *\n * After calling tdl.models.Model.drawPrep you can call this\n * function multiple times to draw this model.\n *\n * @param {!Object.<string, *>} uniforms An object of names to\n * values to set on this models uniforms.\n */\n $loc.draw = new Sk.builtin.func(function(self, uniforms, opt_textures)\n {\n var shader = self.shader;\n uniforms = Sk.ffi.remapToJs(uniforms);\n for (uniform in uniforms) {\n shader.setUniform$impl(shader, uniform, uniforms[uniform]);\n }\n\n if (opt_textures) {\n for (var texture in opt_textures) {\n var unit = self.textureUnits[texture];\n shader.setUniform$impl(shader, texture, unit);\n opt_textures[texture].bindToUnit(unit);\n }\n }\n\n var buffers = self.buffers;\n gl.drawElements(self.mode, buffers.indices.totalComponents(), gl.UNSIGNED_SHORT, 0);\n });\n },\n 'Model', []);\n\n return mod;\n};\n", "src/lib/webgl/math.js": "var $builtinmodule = function(name)\n{\n var mod = {};\n\n // todo; should probably put this in a math package\n mod.Mat44 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self)\n {\n Sk.misceval.callsim($loc.loadIdentity, self);\n self.stack = [];\n });\n\n $loc.push = new Sk.builtin.func(function(self)\n {\n self.stack.push(self.elements.slice(0));\n });\n\n $loc.pop = new Sk.builtin.func(function(self)\n {\n self.elements = self.stack.pop();\n });\n\n $loc.loadIdentity = new Sk.builtin.func(function(self)\n {\n self.elements = [1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0];\n });\n\n $loc.transform3 = new Sk.builtin.func(function(self, v)\n {\n var e = self.elements;\n return Sk.misceval.callsim(mod.Vec3,\n e[0] * v.x + e[4] * v.y + e[8] * v.z,\n e[1] * v.x + e[5] * v.y + e[9] * v.z,\n e[2] * v.x + e[6] * v.y + e[10] * v.z);\n });\n\n $loc.scale = new Sk.builtin.func(function(self, sx, sy, sz)\n {\n self.elements[0*4+0] *= sx;\n self.elements[0*4+1] *= sx;\n self.elements[0*4+2] *= sx;\n self.elements[0*4+3] *= sx;\n\n self.elements[1*4+0] *= sy;\n self.elements[1*4+1] *= sy;\n self.elements[1*4+2] *= sy;\n self.elements[1*4+3] *= sy;\n\n self.elements[2*4+0] *= sz;\n self.elements[2*4+1] *= sz;\n self.elements[2*4+2] *= sz;\n self.elements[2*4+3] *= sz;\n\n return self;\n });\n\n $loc.translate = new Sk.builtin.func(function(self, tx, ty, tz)\n {\n self.elements[3*4+0] += self.elements[0*4+0] * tx + self.elements[1*4+0] * ty + self.elements[2*4+0] * tz;\n self.elements[3*4+1] += self.elements[0*4+1] * tx + self.elements[1*4+1] * ty + self.elements[2*4+1] * tz;\n self.elements[3*4+2] += self.elements[0*4+2] * tx + self.elements[1*4+2] * ty + self.elements[2*4+2] * tz;\n self.elements[3*4+3] += self.elements[0*4+3] * tx + self.elements[1*4+3] * ty + self.elements[2*4+3] * tz;\n return self;\n });\n\n $loc.rotate = new Sk.builtin.func(function(self, angle, x, y, z)\n {\n var mag = Math.sqrt(x*x + y*y + z*z);\n var sinAngle = Math.sin(angle * Math.PI / 180.0);\n var cosAngle = Math.cos(angle * Math.PI / 180.0);\n\n if (mag > 0)\n {\n var xx, yy, zz, xy, yz, zx, xs, ys, zs;\n var oneMinusCos;\n var rotMat;\n\n x /= mag;\n y /= mag;\n z /= mag;\n\n xx = x * x;\n yy = y * y;\n zz = z * z;\n xy = x * y;\n yz = y * z;\n zx = z * x;\n xs = x * sinAngle;\n ys = y * sinAngle;\n zs = z * sinAngle;\n oneMinusCos = 1.0 - cosAngle;\n\n rotMat = Sk.misceval.callsim(mod.Mat44);\n\n rotMat.elements[0*4+0] = (oneMinusCos * xx) + cosAngle;\n rotMat.elements[0*4+1] = (oneMinusCos * xy) - zs;\n rotMat.elements[0*4+2] = (oneMinusCos * zx) + ys;\n rotMat.elements[0*4+3] = 0.0;\n\n rotMat.elements[1*4+0] = (oneMinusCos * xy) + zs;\n rotMat.elements[1*4+1] = (oneMinusCos * yy) + cosAngle;\n rotMat.elements[1*4+2] = (oneMinusCos * yz) - xs;\n rotMat.elements[1*4+3] = 0.0;\n\n rotMat.elements[2*4+0] = (oneMinusCos * zx) - ys;\n rotMat.elements[2*4+1] = (oneMinusCos * yz) + xs;\n rotMat.elements[2*4+2] = (oneMinusCos * zz) + cosAngle;\n rotMat.elements[2*4+3] = 0.0;\n\n rotMat.elements[3*4+0] = 0.0;\n rotMat.elements[3*4+1] = 0.0;\n rotMat.elements[3*4+2] = 0.0;\n rotMat.elements[3*4+3] = 1.0;\n\n rotMat = rotMat.multiply(self);\n self.elements = rotMat.elements;\n }\n return self;\n });\n\n $loc.multiply = new Sk.builtin.func(function(self, right)\n {\n var tmp = Sk.misceval.callsim(mod.Mat44);\n\n for (var i = 0; i < 4; i++)\n {\n tmp.elements[i*4+0] =\n (self.elements[i*4+0] * right.elements[0*4+0]) +\n (self.elements[i*4+1] * right.elements[1*4+0]) +\n (self.elements[i*4+2] * right.elements[2*4+0]) +\n (self.elements[i*4+3] * right.elements[3*4+0]) ;\n\n tmp.elements[i*4+1] =\n (self.elements[i*4+0] * right.elements[0*4+1]) +\n (self.elements[i*4+1] * right.elements[1*4+1]) +\n (self.elements[i*4+2] * right.elements[2*4+1]) +\n (self.elements[i*4+3] * right.elements[3*4+1]) ;\n\n tmp.elements[i*4+2] =\n (self.elements[i*4+0] * right.elements[0*4+2]) +\n (self.elements[i*4+1] * right.elements[1*4+2]) +\n (self.elements[i*4+2] * right.elements[2*4+2]) +\n (self.elements[i*4+3] * right.elements[3*4+2]) ;\n\n tmp.elements[i*4+3] =\n (self.elements[i*4+0] * right.elements[0*4+3]) +\n (self.elements[i*4+1] * right.elements[1*4+3]) +\n (self.elements[i*4+2] * right.elements[2*4+3]) +\n (self.elements[i*4+3] * right.elements[3*4+3]) ;\n }\n\n self.elements = tmp.elements;\n return self;\n });\n\n /* Following gluLookAt implementation is adapted from\n * the Mesa 3D Graphics library. http://www.mesa3d.org\n */\n // todo; rewrite this with proper vec/mat ops\n $loc.lookAt = new Sk.builtin.func(function(self, eyeX, eyeY, eyeZ,\n centerX, centerY, centerZ,\n upX, upY, upZ)\n {\n /* Z vector */\n var z = [\n eyeX - centerX,\n eyeY - centerY,\n eyeZ - centerZ\n ];\n var mag = Math.sqrt(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]);\n if (mag)\n {\n z[0] /= mag;\n z[1] /= mag;\n z[2] /= mag;\n }\n\n /* Y vector */\n var y = [ upX, upY, upZ ];\n\n /* X vector = Y cross Z */\n var x = [];\n x[0] = y[1] * z[2] - y[2] * z[1];\n x[1] = -y[0] * z[2] + y[2] * z[0];\n x[2] = y[0] * z[1] - y[1] * z[0];\n\n /* Recompute Y = Z cross X */\n y[0] = z[1] * x[2] - z[2] * x[1];\n y[1] = -z[0] * x[2] + z[2] * x[0];\n y[2] = z[0] * x[1] - z[1] * x[0];\n\n /* mpichler, 19950515 */\n /* cross product gives area of parallelogram, which is < 1.0 for\n * non-perpendicular unit-length vectors; so normalize x, y here\n */\n\n mag = Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);\n if (mag) {\n x[0] /= mag;\n x[1] /= mag;\n x[2] /= mag;\n }\n\n mag = Math.sqrt(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);\n if (mag) {\n y[0] /= mag;\n y[1] /= mag;\n y[2] /= mag;\n }\n\n var lookAt = Sk.misceval.callsim(mod.Mat44);\n lookAt.elements[0 * 4 + 0] = x[0];\n lookAt.elements[1 * 4 + 0] = x[1];\n lookAt.elements[2 * 4 + 0] = x[2];\n lookAt.elements[3 * 4 + 0] = 0.;\n lookAt.elements[0 * 4 + 1] = y[0];\n lookAt.elements[1 * 4 + 1] = y[1];\n lookAt.elements[2 * 4 + 1] = y[2];\n lookAt.elements[3 * 4 + 1] = 0.;\n lookAt.elements[0 * 4 + 2] = z[0];\n lookAt.elements[1 * 4 + 2] = z[1];\n lookAt.elements[2 * 4 + 2] = z[2];\n lookAt.elements[3 * 4 + 2] = 0.;\n lookAt.elements[0 * 4 + 3] = 0.;\n lookAt.elements[1 * 4 + 3] = 0.;\n lookAt.elements[2 * 4 + 3] = 0.;\n lookAt.elements[3 * 4 + 3] = 1.;\n\n // log(lookAt.elements);\n\n lookAt = lookAt.multiply(self);\n self.elements = lookAt.elements;\n self.translate(-eyeX, -eyeY, -eyeZ);\n\n // log(this.elements);\n\n return self;\n });\n },\n 'Mat44', []);\n\n // todo; should probably put this in a math package\n mod.Mat33 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self)\n {\n Sk.misceval.callsim($loc.loadIdentity, self);\n });\n\n $loc.loadIdentity = new Sk.builtin.func(function(self)\n {\n self.elements = [1.0, 0.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, 1.0];\n });\n },\n 'Mat33', []);\n\n mod.Vec3 = Sk.misceval.buildClass(mod, function($gbl, $loc)\n {\n $loc.__init__ = new Sk.builtin.func(function(self, x, y, z)\n {\n self.x = x;\n self.y = y;\n self.z = z;\n });\n $loc.__sub__ = new Sk.builtin.func(function(self, other)\n {\n return Sk.misceval.callsim(mod.Vec3, self.x - other.x, self.y - other.y, self.z - other.z);\n });\n },\n 'Vec3', []);\n \n mod.cross = new Sk.builtin.func(function(v1, v2)\n {\n goog.asserts.assert(v1 instanceof mod.Vec3 && v2 instanceof mod.Vec3);\n return Sk.misceval.callsim(mod.Vec3,\n v1.y * v2.z - v1.z * v2.y,\n v1.z * v2.x - v1.x * v2.z,\n v1.x * v2.y - v1.y * v2.x);\n });\n\n return mod;\n};\n", "src/lib/webgl/matrix4.js": "// more from 'tdl'\nvar $builtinmodule = function(name)\n{\n var mod = {};\n\n var temp0v3_ = new Float32Array(3);\n var temp1v3_ = new Float32Array(3);\n var temp2v3_ = new Float32Array(3);\n\n var temp0v4_ = new Float32Array(4);\n var temp1v4_ = new Float32Array(4);\n var temp2v4_ = new Float32Array(4);\n\n var temp0m4_ = new Float32Array(16);\n var temp1m4_ = new Float32Array(16);\n var temp2m4_ = new Float32Array(16);\n\n var normalize = function(dst, a) {\n var n = 0.0;\n var aLength = a.length;\n for (var i = 0; i < aLength; ++i)\n n += a[i] * a[i];\n n = Math.sqrt(n);\n if (n > 0.00001) {\n for (var i = 0; i < aLength; ++i)\n dst[i] = a[i] / n;\n } else {\n for (var i = 0; i < aLength; ++i)\n dst[i] = 0;\n }\n return dst;\n };\n\n var cross = function(dst, a, b) {\n dst[0] = a[1] * b[2] - a[2] * b[1];\n dst[1] = a[2] * b[0] - a[0] * b[2];\n dst[2] = a[0] * b[1] - a[1] * b[0];\n return dst;\n };\n\n var subVector = function(dst, a, b) {\n var aLength = a.length;\n for (var i = 0; i < aLength; ++i)\n dst[i] = a[i] - b[i];\n return dst;\n };\n\n var dot = function(a, b) {\n return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);\n };\n\n mod.lookAt = new Sk.builtin.func(function(view, eye, target, up)\n {\n var t0 = temp0v3_;\n var t1 = temp1v3_;\n var t2 = temp2v3_;\n\n var vz = normalize(t0, subVector(t0, eye.v, target.v));\n var vx = normalize(t1, cross(t1, up.v, vz));\n var vy = cross(t2, vz, vx);\n\n var dst = view.v;\n dst[ 0] = vx[0];\n dst[ 1] = vy[0];\n dst[ 2] = vz[0];\n dst[ 3] = 0;\n dst[ 4] = vx[1];\n dst[ 5] = vy[1];\n dst[ 6] = vz[1];\n dst[ 7] = 0;\n dst[ 8] = vx[2];\n dst[ 9] = vy[2];\n dst[10] = vz[2];\n dst[11] = 0;\n dst[12] = -dot(vx, eye.v);\n dst[13] = -dot(vy, eye.v);\n dst[14] = -dot(vz, eye.v);\n dst[15] = 1;\n\n return view;\n });\n\n mod.perspective = new Sk.builtin.func(function(proj, angle, aspect, near, far)\n {\n var f = Math.tan(Math.PI * 0.5 - 0.5 * (angle * Math.PI / 180));\n var rangeInv = 1.0 / (near - far);\n\n var dst = proj.v;\n\n dst[0] = f / aspect;\n dst[1] = 0;\n dst[2] = 0;\n dst[3] = 0;\n\n dst[4] = 0;\n dst[5] = f;\n dst[6] = 0;\n dst[7] = 0;\n\n dst[8] = 0;\n dst[9] = 0;\n dst[10] = (near + far) * rangeInv;\n dst[11] = -1;\n\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = near * far * rangeInv * 2;\n dst[15] = 0;\n\n return proj;\n });\n\n // builds, not appending\n mod.rotationY = new Sk.builtin.func(function(target, angle)\n {\n var dst = target.v;\n var c = Math.cos(angle * Math.PI / 180);\n var s = Math.sin(angle * Math.PI / 180);\n\n dst[ 0] = c;\n dst[ 1] = 0;\n dst[ 2] = -s;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = s;\n dst[ 9] = 0;\n dst[10] = c;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n\n return target;\n });\n\n mod.identity = new Sk.builtin.func(function(target)\n {\n var dst = target.v;\n dst[ 0] = 1;\n dst[ 1] = 0;\n dst[ 2] = 0;\n dst[ 3] = 0;\n dst[ 4] = 0;\n dst[ 5] = 1;\n dst[ 6] = 0;\n dst[ 7] = 0;\n dst[ 8] = 0;\n dst[ 9] = 0;\n dst[10] = 1;\n dst[11] = 0;\n dst[12] = 0;\n dst[13] = 0;\n dst[14] = 0;\n dst[15] = 1;\n return target;\n });\n\n // row major\n mod.mul = new Sk.builtin.func(function(target, x, y)\n {\n var dst = target.v;\n var a = x.v;\n var b = y.v;\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[ 4 + 0];\n var a11 = a[ 4 + 1];\n var a12 = a[ 4 + 2];\n var a13 = a[ 4 + 3];\n var a20 = a[ 8 + 0];\n var a21 = a[ 8 + 1];\n var a22 = a[ 8 + 2];\n var a23 = a[ 8 + 3];\n var a30 = a[12 + 0];\n var a31 = a[12 + 1];\n var a32 = a[12 + 2];\n var a33 = a[12 + 3];\n var b00 = b[0];\n var b01 = b[1];\n var b02 = b[2];\n var b03 = b[3];\n var b10 = b[ 4 + 0];\n var b11 = b[ 4 + 1];\n var b12 = b[ 4 + 2];\n var b13 = b[ 4 + 3];\n var b20 = b[ 8 + 0];\n var b21 = b[ 8 + 1];\n var b22 = b[ 8 + 2];\n var b23 = b[ 8 + 3];\n var b30 = b[12 + 0];\n var b31 = b[12 + 1];\n var b32 = b[12 + 2];\n var b33 = b[12 + 3];\n dst[ 0] = a00 * b00 + a01 * b10 + a02 * b20 + a03 * b30;\n dst[ 1] = a00 * b01 + a01 * b11 + a02 * b21 + a03 * b31;\n dst[ 2] = a00 * b02 + a01 * b12 + a02 * b22 + a03 * b32;\n dst[ 3] = a00 * b03 + a01 * b13 + a02 * b23 + a03 * b33;\n dst[ 4] = a10 * b00 + a11 * b10 + a12 * b20 + a13 * b30;\n dst[ 5] = a10 * b01 + a11 * b11 + a12 * b21 + a13 * b31;\n dst[ 6] = a10 * b02 + a11 * b12 + a12 * b22 + a13 * b32;\n dst[ 7] = a10 * b03 + a11 * b13 + a12 * b23 + a13 * b33;\n dst[ 8] = a20 * b00 + a21 * b10 + a22 * b20 + a23 * b30;\n dst[ 9] = a20 * b01 + a21 * b11 + a22 * b21 + a23 * b31;\n dst[10] = a20 * b02 + a21 * b12 + a22 * b22 + a23 * b32;\n dst[11] = a20 * b03 + a21 * b13 + a22 * b23 + a23 * b33;\n dst[12] = a30 * b00 + a31 * b10 + a32 * b20 + a33 * b30;\n dst[13] = a30 * b01 + a31 * b11 + a32 * b21 + a33 * b31;\n dst[14] = a30 * b02 + a31 * b12 + a32 * b22 + a33 * b32;\n dst[15] = a30 * b03 + a31 * b13 + a32 * b23 + a33 * b33;\n return target;\n });\n\n mod.invert = new Sk.builtin.func(function(target, mat)\n {\n var dst = target.v;\n var m = mat.v;\n var m00 = m[0 * 4 + 0];\n var m01 = m[0 * 4 + 1];\n var m02 = m[0 * 4 + 2];\n var m03 = m[0 * 4 + 3];\n var m10 = m[1 * 4 + 0];\n var m11 = m[1 * 4 + 1];\n var m12 = m[1 * 4 + 2];\n var m13 = m[1 * 4 + 3];\n var m20 = m[2 * 4 + 0];\n var m21 = m[2 * 4 + 1];\n var m22 = m[2 * 4 + 2];\n var m23 = m[2 * 4 + 3];\n var m30 = m[3 * 4 + 0];\n var m31 = m[3 * 4 + 1];\n var m32 = m[3 * 4 + 2];\n var m33 = m[3 * 4 + 3];\n var tmp_0 = m22 * m33;\n var tmp_1 = m32 * m23;\n var tmp_2 = m12 * m33;\n var tmp_3 = m32 * m13;\n var tmp_4 = m12 * m23;\n var tmp_5 = m22 * m13;\n var tmp_6 = m02 * m33;\n var tmp_7 = m32 * m03;\n var tmp_8 = m02 * m23;\n var tmp_9 = m22 * m03;\n var tmp_10 = m02 * m13;\n var tmp_11 = m12 * m03;\n var tmp_12 = m20 * m31;\n var tmp_13 = m30 * m21;\n var tmp_14 = m10 * m31;\n var tmp_15 = m30 * m11;\n var tmp_16 = m10 * m21;\n var tmp_17 = m20 * m11;\n var tmp_18 = m00 * m31;\n var tmp_19 = m30 * m01;\n var tmp_20 = m00 * m21;\n var tmp_21 = m20 * m01;\n var tmp_22 = m00 * m11;\n var tmp_23 = m10 * m01;\n\n var t0 = (tmp_0 * m11 + tmp_3 * m21 + tmp_4 * m31) -\n (tmp_1 * m11 + tmp_2 * m21 + tmp_5 * m31);\n var t1 = (tmp_1 * m01 + tmp_6 * m21 + tmp_9 * m31) -\n (tmp_0 * m01 + tmp_7 * m21 + tmp_8 * m31);\n var t2 = (tmp_2 * m01 + tmp_7 * m11 + tmp_10 * m31) -\n (tmp_3 * m01 + tmp_6 * m11 + tmp_11 * m31);\n var t3 = (tmp_5 * m01 + tmp_8 * m11 + tmp_11 * m21) -\n (tmp_4 * m01 + tmp_9 * m11 + tmp_10 * m21);\n\n var d = 1.0 / (m00 * t0 + m10 * t1 + m20 * t2 + m30 * t3);\n\n dst[ 0] = d * t0;\n dst[ 1] = d * t1;\n dst[ 2] = d * t2;\n dst[ 3] = d * t3;\n dst[ 4] = d * ((tmp_1 * m10 + tmp_2 * m20 + tmp_5 * m30) -\n (tmp_0 * m10 + tmp_3 * m20 + tmp_4 * m30));\n dst[ 5] = d * ((tmp_0 * m00 + tmp_7 * m20 + tmp_8 * m30) -\n (tmp_1 * m00 + tmp_6 * m20 + tmp_9 * m30));\n dst[ 6] = d * ((tmp_3 * m00 + tmp_6 * m10 + tmp_11 * m30) -\n (tmp_2 * m00 + tmp_7 * m10 + tmp_10 * m30));\n dst[ 7] = d * ((tmp_4 * m00 + tmp_9 * m10 + tmp_10 * m20) -\n (tmp_5 * m00 + tmp_8 * m10 + tmp_11 * m20));\n dst[ 8] = d * ((tmp_12 * m13 + tmp_15 * m23 + tmp_16 * m33) -\n (tmp_13 * m13 + tmp_14 * m23 + tmp_17 * m33));\n dst[ 9] = d * ((tmp_13 * m03 + tmp_18 * m23 + tmp_21 * m33) -\n (tmp_12 * m03 + tmp_19 * m23 + tmp_20 * m33));\n dst[10] = d * ((tmp_14 * m03 + tmp_19 * m13 + tmp_22 * m33) -\n (tmp_15 * m03 + tmp_18 * m13 + tmp_23 * m33));\n dst[11] = d * ((tmp_17 * m03 + tmp_20 * m13 + tmp_23 * m23) -\n (tmp_16 * m03 + tmp_21 * m13 + tmp_22 * m23));\n dst[12] = d * ((tmp_14 * m22 + tmp_17 * m32 + tmp_13 * m12) -\n (tmp_16 * m32 + tmp_12 * m12 + tmp_15 * m22));\n dst[13] = d * ((tmp_20 * m32 + tmp_12 * m02 + tmp_19 * m22) -\n (tmp_18 * m22 + tmp_21 * m32 + tmp_13 * m02));\n dst[14] = d * ((tmp_18 * m12 + tmp_23 * m32 + tmp_15 * m02) -\n (tmp_22 * m32 + tmp_14 * m02 + tmp_19 * m12));\n dst[15] = d * ((tmp_22 * m22 + tmp_16 * m02 + tmp_21 * m12) -\n (tmp_20 * m12 + tmp_23 * m22 + tmp_17 * m02));\n return target;\n });\n\n mod.transpose = new Sk.builtin.func(function(target, mat)\n {\n var dst = target.v;\n var m = mat.v;\n for (var j = 0; j < 4; ++j) {\n for (var i = 0; i < 4; ++i)\n dst[j * 4 + i] = m[i * 4 + j];\n }\n return dst;\n });\n\n return mod;\n};\n", "src/lib/numpy/__init__.js": "/**\n\tMade by Michael Ebert for https://github.com/skulpt/skulpt\n\tndarray implementation inspired by https://github.com/geometryzen/davinci-dev (not compatible with skulpt)\n\n\tSome methods are based on the original numpy implementation.\n\n\tSee http://waywaaard.github.io/skulpt/ for more information.\n**/\nvar numpy = function () {\n if (typeof mathjs == 'function') {\n // load mathjs instance\n this.math = mathjs;\n } else {\n Sk.debugout(\"mathjs not included and callable\");\n }\n};\n\nnumpy.prototype.wrapasfloats = function (values) {\n var i;\n for (i = 0; i < values.length; i++) {\n values[i] = new Sk.builtin.nmber(values[i], Sk.builtin.nmber.float$);\n }\n\n return values;\n};\n\nnumpy.prototype.arange = function (start, stop, step) {\n if (step === undefined)\n step = 1.0;\n\n start *= 1.0;\n stop *= 1.0;\n step *= 1.0;\n\n var res = [];\n for (var i = start; i < stop; i += step) {\n res.push(i);\n }\n\n return res;\n};\n\nvar $builtinmodule = function (name) {\n var np = new numpy();\n\n var mod = {};\n\n /**\n\t\tClass for numpy.ndarray\n\t**/\n var CLASS_NDARRAY = \"numpy.ndarray\";\n\n function remapToJs_shallow(obj, shallow) {\n var _shallow = shallow || true;\n if (obj instanceof Sk.builtin.list) {\n if (!_shallow) {\n var ret = [];\n for (var i = 0; i < obj.v.length; ++i) {\n ret.push(Sk.ffi.remapToJs(obj.v[i]));\n }\n return ret;\n } else {\n return obj.v;\n }\n } else if (obj instanceof Sk.builtin.float_) {\n return Sk.builtin.asnum$nofloat(obj);\n } else {\n return Sk.ffi.remapToJs(obj);\n }\n }\n\n /**\n\t\tUnpacks in any form fo nested Lists\n\t**/\n function unpack(py_obj, buffer, state) {\n if (py_obj instanceof Sk.builtin.list || py_obj instanceof Sk.builtin.tuple) {\n var py_items = remapToJs_shallow(py_obj);\n state.level += 1;\n\n if (state.level > state.shape.length) {\n state.shape.push(py_items.length);\n }\n var i;\n var len = py_items.length;\n for (i = 0; i < len; i++) {\n unpack(py_items[i], buffer, state);\n }\n state.level -= 1;\n } else {\n buffer.push(py_obj);\n }\n }\n\n /**\n Computes the strides for columns and rows\n **/\n function computeStrides(shape) {\n var strides = shape.slice(0);\n strides.reverse();\n var prod = 1;\n var temp;\n for (var i = 0, len = strides.length; i < len; i++) {\n temp = strides[i];\n strides[i] = prod;\n prod *= temp;\n }\n\n return strides.reverse();\n }\n\n /**\n Computes the offset for the ndarray for given index and strides\n [1, ..., n]\n **/\n function computeOffset(strides, index) {\n var offset = 0;\n for (var k = 0, len = strides.length; k < len; k++) {\n offset += strides[k] * index[k];\n }\n return offset;\n }\n\n /**\n Calculates the size of the ndarray, dummy\n\t**/\n function prod(numbers) {\n var size = 1;\n var i;\n for (i = 0; i < numbers.length; i++) {\n size *= numbers[i];\n }\n return size;\n }\n\n /**\n\t\tCreates a string representation for given buffer and shape\n\t\tbuffer is an ndarray\n\t**/\n function stringify(buffer, shape, dtype) {\n var emits = shape.map(function (x) {\n return 0;\n });\n var uBound = shape.length - 1;\n var idxLevel = 0;\n var str = \"[\";\n var i = 0;\n while (idxLevel !== -1) {\n if (emits[idxLevel] < shape[idxLevel]) {\n if (emits[idxLevel] !== 0) {\n str += \", \";\n }\n\n if (idxLevel < uBound) {\n str += \"[\";\n idxLevel += 1;\n } else {\n if (dtype === Sk.builtin.float_)\n str += Sk.ffi.remapToJs(Sk.builtin.str(new Sk.builtin.float_(buffer[\n i++])));\n else\n str += Sk.ffi.remapToJs(Sk.builtin.str(buffer[i++]));\n emits[idxLevel] += 1;\n }\n } else {\n emits[idxLevel] = 0;\n str += \"]\";\n idxLevel -= 1;\n if (idxLevel >= 0) {\n emits[idxLevel] += 1;\n }\n }\n }\n return str;\n }\n\n /*\n http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html?highlight=tolist#numpy.ndarray.tolist\n */\n function tolistrecursive(buffer, shape, strides, startdim, dtype) {\n var i, n, stride;\n var arr, item;\n\n /* Base case */\n if (startdim >= shape.length) {\n if (dtype && dtype === Sk.builtin.float_) {\n return new Sk.builtin.float_(buffer[0]); // handle float special case\n } else {\n return Sk.ffi.remapToPy(buffer[0]);\n }\n }\n\n n = shape[startdim];\n stride = strides[startdim];\n\n arr = [];\n\n for (i = 0; i < n; i++) {\n item = tolistrecursive(buffer, shape, strides, startdim + 1, dtype);\n arr.push(item);\n\n buffer = buffer.slice(stride);\n }\n\n return new Sk.builtin.list(arr);\n }\n\n /**\n\t internal tolist interface\n\t**/\n function tolist(buffer, shape, strides, dtype) {\n var buffer_copy = buffer.slice(0);\n return tolistrecursive(buffer_copy, shape, strides, 0, dtype);\n }\n\n /**\n Updates all attributes of the numpy.ndarray\n **/\n function updateAttributes(self, ndarrayJs) {\n Sk.abstr.sattr(self, 'ndmin', new Sk.builtin.int_(ndarrayJs.shape.length));\n Sk.abstr.sattr(self, 'dtype', ndarrayJs.dtype);\n Sk.abstr.sattr(self, 'shape', new Sk.builtin.tuple(ndarrayJs.shape.map(\n function (x) {\n return new Sk.builtin.int_(x);\n })));\n Sk.abstr.sattr(self, 'strides', new Sk.builtin.tuple(ndarrayJs.strides.map(\n function (x) {\n return new Sk.builtin.int_(x);\n })));\n Sk.abstr.sattr(self, 'size', new Sk.builtin.int_(prod(ndarrayJs.shape)));\n Sk.abstr.sattr(self, 'data', new Sk.ffi.remapToPy(ndarrayJs.buffer));\n }\n\n /**\n An array object represents a multidimensional, homogeneous array of fixed-size items.\n An associated data-type object describes the format of each element in the array\n (its byte-order, how many bytes it occupies in memory, whether it is an integer, a\n floating point number, or something else, etc.)\n\n Arrays should be constructed using array, zeros or empty (refer to the See Also\n section below). The parameters given here refer to a low-level method (ndarray(...)) for\n instantiating an array.\n\n For more information, refer to the numpy module and examine the the methods and\n attributes of an array.\n **/\n var ndarray_f = function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, shape, dtype, buffer,\n offset, strides, order) {\n var ndarrayJs = {}; // js object holding the actual array\n ndarrayJs.shape = Sk.ffi.remapToJs(shape);\n\n ndarrayJs.strides = computeStrides(ndarrayJs.shape);\n ndarrayJs.dtype = dtype || Sk.builtin.none.none$;\n\n if (buffer && buffer instanceof Sk.builtin.list) {\n ndarrayJs.buffer = Sk.ffi.remapToJs(buffer);\n }\n\n self.v = ndarrayJs; // value holding the actual js object and array\n self.tp$name = CLASS_NDARRAY; // set class name\n\n updateAttributes(self, ndarrayJs);\n });\n\n $loc.tp$getattr = Sk.builtin.object.prototype.GenericGetAttr;\n\n // ToDo: setAttribute should be implemented, change of shape causes resize\n // ndmin cannot be set, etc...\n $loc.tp$setattr = Sk.builtin.object.prototype.GenericSetAttr;\n\n /*\n Return the array as a (possibly nested) list.\n\n Return a copy of the array data as a (nested) Python list. Data items are\n converted to the nearest compatible Python type.\n */\n $loc.tolist = new Sk.builtin.func(function (self) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var list = tolist(ndarrayJs.buffer, ndarrayJs.shape, ndarrayJs.strides,\n ndarrayJs.dtype);\n\n return list;\n });\n\n $loc.reshape = new Sk.builtin.func(function (self, shape, order) {\n Sk.builtin.pyCheckArgs(\"reshape\", arguments, 2, 3);\n var ndarrayJs = Sk.ffi.remapToJs(self);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, ndarrayJs.dtype,\n new Sk.builtin.list(ndarrayJs.buffer));\n });\n\n $loc.copy = new Sk.builtin.func(function (self, order) {\n Sk.builtin.pyCheckArgs(\"copy\", arguments, 1, 2);\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var buffer = ndarrayJs.buffer.map(function (x) {\n return x;\n });\n var shape = new Sk.builtin.tuplePy(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, ndarrayJs.dtype,\n new Sk.builtin.list(buffer));\n });\n\n /**\n Fill the array with a scalar value.\n Parameters: value: scalar\n All elements of a will be assigned this value\n **/\n $loc.fill = new Sk.builtin.func(function (self, value) {\n Sk.builtin.pyCheckArgs(\"fill\", arguments, 2, 2);\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var buffer = ndarrayJs.buffer.map(function (x) {\n return x;\n });\n var i;\n for (i = 0; i < ndarrayJs.buffer.length; i++) {\n if (ndarrayJs.dtype) {\n ndarrayJs.buffer[i] = Sk.misceval.callsim(ndarrayJs.dtype,\n value);\n }\n }\n });\n\n $loc.__getitem__ = new Sk.builtin.func(function (self, index) {\n Sk.builtin.pyCheckArgs(\"[]\", arguments, 2, 2);\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var _index; // current index\n var _buffer; // buffer as python type\n var buffer_internal; // buffer als js array\n var _stride; // stride\n var _shape; // shape as js\n var i;\n\n // single index e.g. [3]\n if (Sk.builtin.checkInt(index)) {\n var offset = Sk.ffi.remapToJs(index);\n\n if (ndarrayJs.shape.length > 1) {\n _stride = ndarrayJs.strides[0];\n buffer_internal = [];\n _index = 0;\n\n for (i = offset * _stride, ubound = (offset + 1) * _stride; i <\n ubound; i++) {\n buffer_internal[_index++] = ndarrayJs.buffer[i];\n }\n\n _buffer = new Sk.builtin.list(buffer_internal);\n _shape = new Sk.builtin.tuple(Array.prototype.slice.call(\n ndarrayJs.shape,\n 1)\n .map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], _shape,\n undefined,\n _buffer);\n } else {\n if (offset >= 0 && offset < ndarrayJs.buffer.length) {\n return ndarrayJs.buffer[offset];\n } else {\n throw new Sk.builtin.IndexError(\"array index out of range\");\n }\n }\n } else if (index instanceof Sk.builtin.tuple) {\n // index like [1,3]\n var keyJs = Sk.ffi.remapToJs(index);\n return ndarrayJs.buffer[computeOffset(ndarrayJs.strides, keyJs)];\n } else if (index instanceof Sk.builtin.slice) {\n // support for slices e.g. [1:4]\n var indices = index.indices();\n var start = typeof indices[0] !== 'undefined' ? indices[0] : 0;\n var stop = typeof indices[1] !== 'undefined' ? indices[1] :\n ndarrayJs\n .buffer.length;\n stop = stop > ndarrayJs.buffer.length ? ndarrayJs.buffer.length :\n stop;\n var step = typeof indices[2] !== 'undefined' ? indices[2] : 1;\n buffer_internal = [];\n _index = 0;\n if (step > 0) {\n for (i = start; i < stop; i += step) {\n buffer_internal[_index++] = ndarrayJs.buffer[i];\n }\n }\n _buffer = new Sk.builtin.list(buffer_internal);\n _shape = new Sk.builtin.tuple([buffer_internal.length].map(\n function (\n x) {\n return new Sk.builtin.int_(x);\n }));\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], _shape, undefined,\n _buffer);\n } else {\n throw new Sk.builtin.ValueError('Index \"' + index +\n '\" must be int, slice or tuple');\n }\n });\n\n $loc.__setitem__ = new Sk.builtin.func(function (self, index, value) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n Sk.builtin.pyCheckArgs(\"[]\", arguments, 3, 3);\n if (index instanceof Sk.builtin.int_) {\n var _offset = Sk.ffi.remapToJs(index);\n if (ndarrayJs.shape.length > 1) {\n var _value = Sk.ffi.remapToJs(value);\n var _stride = ndarrayJs.strides[0];\n var _index = 0;\n\n var _ubound = (_offset + 1) * _stride;\n var i;\n for (i = _offset * _stride; i < _ubound; i++) {\n ndarrayJs.buffer[i] = _value.buffer[_index++];\n }\n } else {\n if (_offset >= 0 && _offset < ndarrayJs.buffer.length) {\n ndarrayJs.buffer[_offset] = value;\n } else {\n throw new Sk.builtin.IndexError(\"array index out of range\");\n }\n }\n } else if (index instanceof Sk.builtin.tuple) {\n _key = Sk.ffi.remapToJs(index);\n ndarrayJs.buffer[computeOffset(ndarrayJs.strides, _key)] = value;\n } else {\n throw new Sk.builtin.TypeError(\n 'argument \"index\" must be int or tuple');\n }\n });\n\n $loc.__len__ = new Sk.builtin.func(function (self) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n return new Sk.builtin.int_(ndarrayJs.shape[0]);\n });\n\n $loc.__iter__ = new Sk.builtin.func(function (self) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var ret = {\n tp$iter: function () {\n return ret;\n },\n $obj: ndarrayJs,\n $index: 0,\n tp$iternext: function () {\n if (ret.$index >= ret.$obj.buffer.length) return undefined;\n return ret.$obj.buffer[ret.$index++];\n }\n };\n return ret;\n });\n\n $loc.__str__ = new Sk.builtin.func(function (self) {\n var ndarrayJs = remapToJs_shallow(self, false);\n return new Sk.builtin.str(stringify(ndarrayJs.buffer,\n ndarrayJs.shape, ndarrayJs.dtype));\n });\n\n $loc.__repr__ = new Sk.builtin.func(function (self) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n return new Sk.builtin.str(\"array(\" + stringify(ndarrayJs.buffer,\n ndarrayJs.shape, ndarrayJs.dtype) + \")\");\n });\n\n /**\n Creates left hand side operations for given binary operator\n **/\n function makeNumericBinaryOpLhs(operation) {\n return function (self, other) {\n var lhs;\n var rhs;\n var buffer; // external\n var _buffer; // internal use\n var shape; // new shape of returned ndarray\n var i;\n\n\n var ndarrayJs = Sk.ffi.remapToJs(self);\n\n if (Sk.abstr.typeName(other) === CLASS_NDARRAY) {\n lhs = ndarrayJs.buffer;\n rhs = Sk.ffi.remapToJs(other)\n .buffer;\n _buffer = [];\n for (i = 0, len = lhs.length; i < len; i++) {\n //_buffer[i] = operation(lhs[i], rhs[i]);\n _buffer[i] = Sk.abstr.binary_op_(lhs[i], rhs[i], operation);\n }\n } else {\n lhs = ndarrayJs.buffer;\n _buffer = [];\n for (i = 0, len = lhs.length; i < len; i++) {\n _buffer[i] = Sk.abstr.numberBinOp(lhs[i], other, operation);\n }\n }\n\n // create return ndarray\n shape = new Sk.builtin.tuple(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n buffer = new Sk.builtin.list(_buffer);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, undefined,\n buffer);\n };\n }\n\n function makeNumericBinaryOpRhs(operation) {\n return function (self, other) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var rhsBuffer = ndarrayJs.buffer;\n var _buffer = [];\n for (var i = 0, len = rhsBuffer.length; i < len; i++) {\n _buffer[i] = Sk.abstr.numberBinOp(other, rhsBuffer[i], operation);\n }\n var shape = new Sk.builtin.tuple(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n buffer = new Sk.builtin.list(_buffer);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, undefined, buffer);\n };\n }\n\n /*\n Applies given operation on each element of the ndarray.\n */\n function makeUnaryOp(operation) {\n return function (self) {\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var _buffer = ndarrayJs.buffer.map(function (value) {\n return Sk.abstr.numberUnaryOp(Sk.ffi.remapToPy(value), operation);\n });\n var shape = new Sk.builtin.tuple(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n buffer = new Sk.builtin.list(_buffer);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, undefined, buffer);\n };\n }\n\n $loc.__add__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"Add\"));\n $loc.__radd__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"Add\"));\n\n $loc.__sub__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"Sub\"));\n $loc.__rsub__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"Sub\"));\n\n $loc.__mul__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"Mult\"));\n $loc.__rmul__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"Mult\"));\n\n $loc.__div__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"Div\"));\n $loc.__rdiv__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"Div\"));\n\n $loc.__mod__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"Mod\"));\n $loc.__rmod__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"Mod\"));\n\n $loc.__xor__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"BitXor\"));\n $loc.__rxor__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"BitXor\"));\n\n $loc.__lshift__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"LShift\"));\n $loc.__rlshift__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"LShift\"));\n\n $loc.__rshift__ = new Sk.builtin.func(makeNumericBinaryOpLhs(\"RShift\"));\n $loc.__rrshift__ = new Sk.builtin.func(makeNumericBinaryOpRhs(\"RShift\"));\n\n $loc.__pos__ = new Sk.builtin.func(makeUnaryOp(\"UAdd\"));\n $loc.__neg__ = new Sk.builtin.func(makeUnaryOp(\"USub\"));\n\n /**\n Simple pow implementation that faciliates the pow builtin\n **/\n $loc.__pow__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__pow__\", arguments, 2, 2);\n var ndarrayJs = Sk.ffi.remapToJs(self);\n var _buffer = ndarrayJs.buffer.map(function (value) {\n return Sk.builtin.pow(Sk.ffi.remapToPy(value), other);\n });\n var shape = new Sk.builtin.tuple(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n buffer = new Sk.builtin.list(_buffer);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, undefined, buffer);\n });\n\n // end of ndarray_f\n };\n\n mod[CLASS_NDARRAY] = Sk.misceval.buildClass(mod, ndarray_f,\n CLASS_NDARRAY, []);\n\n /**\n Trigonometric functions, all element wise\n **/\n mod.pi = Sk.builtin.assk$(np.math ? np.math.PI : Math.PI, Sk.builtin.nmber.float$);\n mod.e = Sk.builtin.assk$(np.math ? np.math.E : Math.E, Sk.builtin.nmber.float$);\n /**\n Trigonometric sine, element-wise.\n **/\n\n function callTrigonometricFunc(x, op) {\n var res;\n var num;\n if (x instanceof Sk.builtin.list || x instanceof Sk.builtin.tuple) {\n x = Sk.misceval.callsim(mod.array, x);\n }\n\n if (Sk.abstr.typeName(x) === CLASS_NDARRAY) {\n var ndarrayJs = Sk.ffi.remapToJs(x);\n\n var _buffer = ndarrayJs.buffer.map(function (value) {\n num = Sk.builtin.asnum$(value);\n res = op.call(null, num);\n return new Sk.builtin.nmber(res, Sk.builtin.nmber\n .float$);\n });\n\n var shape = new Sk.builtin.tuple(ndarrayJs.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n\n buffer = new Sk.builtin.list(_buffer);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, undefined, buffer);\n } else if (Sk.builtin.checkNumber(x)) {\n num = Sk.builtin.asnum$(x);\n res = op.call(null, num);\n return new Sk.builtin.nmber(res, Sk.builtin.nmber\n .float$);\n }\n\n throw new Sk.builtin.TypeError('Unsupported argument type for \"x\"');\n }\n\n // Sine, element-wise.\n var sin_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"sin\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.sin : Math.sin);\n };\n sin_f.co_varnames = ['x', 'out'];\n sin_f.$defaults = [0, new Sk.builtin.list([])];\n mod.sin = new Sk.builtin.func(sin_f);\n\n // Hyperbolic sine, element-wise.\n var sinh_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"sinh\", arguments, 1, 2);\n if (!np.math) throw new Sk.builtin.OperationError(\"sinh requires mathjs\");\n return callTrigonometricFunc(x, np.math.sinh);\n };\n sinh_f.co_varnames = ['x', 'out'];\n sinh_f.$defaults = [0, new Sk.builtin.list([])];\n mod.sinh = new Sk.builtin.func(sinh_f);\n\n // Inverse sine, element-wise.\n var arcsin_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"arcsin\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.asin : Math.asin);\n };\n arcsin_f.co_varnames = ['x', 'out'];\n arcsin_f.$defaults = [0, new Sk.builtin.list([])];\n mod.arcsin = new Sk.builtin.func(arcsin_f);\n\n // Cosine, element-wise.\n var cos_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"cos\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.cos : Math.cos);\n };\n cos_f.co_varnames = ['x', 'out'];\n cos_f.$defaults = [0, new Sk.builtin.list([])];\n mod.cos = new Sk.builtin.func(cos_f);\n\n // Hyperbolic cosine, element-wise.\n var cosh_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"cosh\", arguments, 1, 2);\n if (!np.math) throw new Sk.builtin.OperationError(\"cosh requires mathjs\");\n return callTrigonometricFunc(x, np.math.cosh);\n };\n cosh_f.co_varnames = ['x', 'out'];\n cosh_f.$defaults = [0, new Sk.builtin.list([])];\n mod.cosh = new Sk.builtin.func(cosh_f);\n\n // Inverse cosine, element-wise.\n var arccos_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"arccos\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.acos : Math.acos);\n };\n arccos_f.co_varnames = ['x', 'out'];\n arccos_f.$defaults = [0, new Sk.builtin.list([])];\n mod.arccos = new Sk.builtin.func(arccos_f);\n\n // Inverse tangens, element-wise.\n var arctan_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"arctan\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.atan : Math.atan);\n };\n arctan_f.co_varnames = ['x', 'out'];\n arctan_f.$defaults = [0, new Sk.builtin.list([])];\n mod.arctan = new Sk.builtin.func(arctan_f);\n\n // Tangens, element-wise.\n var tan_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"tan\", arguments, 1, 2);\n return callTrigonometricFunc(x, np.math ? np.math.tan : Math.tan);\n };\n tan_f.co_varnames = ['x', 'out'];\n tan_f.$defaults = [0, new Sk.builtin.list([])];\n mod.tan = new Sk.builtin.func(tan_f);\n\n // Hyperbolic cosine, element-wise.\n var tanh_f = function (x, out) {\n Sk.builtin.pyCheckArgs(\"tanh\", arguments, 1, 2);\n if (!np.math) throw new Sk.builtin.OperationError(\"tanh requires mathjs\");\n return callTrigonometricFunc(x, np.math.tanh);\n };\n tanh_f.co_varnames = ['x', 'out'];\n tanh_f.$defaults = [0, new Sk.builtin.list([])];\n mod.tanh = new Sk.builtin.func(tanh_f);\n\n /* Simple reimplementation of the linspace function\n * http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html\n */\n var linspace_f = function (start, stop, num, endpoint, retstep) {\n Sk.builtin.pyCheckArgs(\"linspace\", arguments, 3, 5);\n Sk.builtin.pyCheckType(\"start\", \"number\", Sk.builtin.checkNumber(\n start));\n Sk.builtin.pyCheckType(\"stop\", \"number\", Sk.builtin.checkNumber(\n stop));\n if (num === undefined) {\n num = 50;\n }\n var num_num = Sk.builtin.asnum$(num);\n var endpoint_bool;\n\n if (endpoint === undefined) {\n endpoint_bool = true;\n } else if (endpoint.constructor === Sk.builtin.bool) {\n endpoint_bool = endpoint.v;\n }\n\n var retstep_bool;\n if (retstep === undefined) {\n retstep_bool = false;\n } else if (retstep.constructor === Sk.builtin.bool) {\n retstep_bool = retstep.v;\n }\n\n var samples;\n var step;\n\n start_num = Sk.builtin.asnum$(start) * 1.0;\n stop_num = Sk.builtin.asnum$(stop) * 1.0;\n\n if (num_num <= 0) {\n samples = [];\n } else {\n\n var samples_array;\n if (endpoint_bool) {\n if (num_num == 1) {\n samples = [start_num];\n } else {\n step = (stop_num - start_num) / (num_num - 1);\n samples_array = np.arange(0, num_num);\n samples = samples_array.map(function (v) {\n return v * step + start_num;\n });\n samples[samples.length - 1] = stop_num;\n }\n } else {\n step = (stop_num - start_num) / num_num;\n samples_array = np.arange(0, num_num);\n samples = samples_array.map(function (v) {\n return v * step + start_num;\n });\n }\n }\n\n //return as ndarray! dtype:float\n var dtype = Sk.builtin.float_;\n for (i = 0; i < samples.length; i++) {\n samples[i] = Sk.misceval.callsim(dtype, samples[i]);\n }\n\n var buffer = Sk.builtin.list(samples);\n var shape = new Sk.builtin.tuple([samples.length]);\n var ndarray = Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, dtype,\n buffer);\n\n if (retstep_bool === true)\n return new Sk.builtin.tuple([ndarray, step]);\n else\n return ndarray;\n };\n\n // this should allow for named parameters\n linspace_f.co_varnames = ['start', 'stop', 'num', 'endpoint',\n 'retstep'\n ];\n linspace_f.$defaults = [0, 0, 50, true, false];\n mod.linspace =\n new Sk.builtin.func(linspace_f);\n\n /* Simple reimplementation of the arange function\n * http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html#numpy.arange\n */\n var arange_f = function (start, stop, step, dtype) {\n Sk.builtin.pyCheckArgs(\"arange\", arguments, 1, 4);\n Sk.builtin.pyCheckType(\"start\", \"number\", Sk.builtin.checkNumber(\n start));\n var start_num;\n var stop_num;\n var step_num;\n\n if (stop === undefined && step === undefined) {\n start_num = Sk.builtin.asnum$(0);\n stop_num = Sk.builtin.asnum$(start);\n step_num = Sk.builtin.asnum$(1);\n } else if (step === undefined) {\n start_num = Sk.builtin.asnum$(start);\n stop_num = Sk.builtin.asnum$(stop);\n step_num = Sk.builtin.asnum$(1);\n } else {\n start_num = Sk.builtin.asnum$(start);\n stop_num = Sk.builtin.asnum$(stop);\n step_num = Sk.builtin.asnum$(step);\n }\n\n // set to float\n if (!dtype || dtype == Sk.builtin.none.none$) {\n if (Sk.builtin.checkInt(start))\n dtype = Sk.builtin.int_;\n else\n dtype = Sk.builtin.float_;\n }\n\n // return ndarray\n var arange_buffer = np.arange(start_num, stop_num, step_num);\n // apply dtype casting function, if it has been provided\n if (dtype && Sk.builtin.checkClass(dtype)) {\n for (i = 0; i < arange_buffer.length; i++) {\n arange_buffer[i] = Sk.misceval.callsim(dtype, arange_buffer[i]);\n }\n }\n\n buffer = Sk.builtin.list(arange_buffer);\n var shape = new Sk.builtin.tuple([arange_buffer.length]);\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, dtype,\n buffer);\n };\n\n arange_f.co_varnames = ['start', 'stop', 'step', 'dtype'];\n arange_f\n .$defaults = [0, 1, 1, Sk.builtin.none.none$];\n mod.arange = new Sk.builtin\n .func(arange_f);\n\n /* implementation for numpy.array\n\t------------------------------------------------------------------------------------------------\n\t\thttp://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html#numpy.array\n\n\t\tobject : array_like\n\t\tAn array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.\n\n\t\tdtype : data-type, optional\n\t\tThe desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to \u2018upcast\u2019 the array. For downcasting, use the .astype(t) method.\n\n\t\tcopy : bool, optional\n\t\tIf true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).\n\n\t\torder : {\u2018C\u2019, \u2018F\u2019, \u2018A\u2019}, optional\n\t\tSpecify the order of the array. If order is \u2018C\u2019 (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is \u2018F\u2019, then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is \u2018A\u2019, then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous).\n\n\t\tsubok : bool, optional\n\t\tIf True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).\n\n\t\tndmin : int, optional\n\t\tSpecifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.\n\n\t\tReturns :\n\t\tout : ndarray\n\t\tAn array object satisfying the specified requirements\n\t*/\n // https://github.com/geometryzen/davinci-dev/blob/master/src/stdlib/numpy.js\n // https://github.com/geometryzen/davinci-dev/blob/master/src/ffh.js\n // http://docs.scipy.org/doc/numpy/reference/arrays.html\n var array_f = function (object, dtype, copy, order, subok, ndmin) {\n Sk.builtin.pyCheckArgs(\"array\", arguments, 1, 6);\n\n if (object === undefined)\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(object) +\n \"' object is undefined\");\n\n var elements = [];\n var state = {};\n state.level = 0;\n state.shape = [];\n\n unpack(object, elements, state);\n\n var i;\n // apply dtype casting function, if it has been provided\n if (dtype && Sk.builtin.checkClass(dtype)) {\n for (i = 0; i < elements.length; i++) {\n elements[i] = Sk.misceval.callsim(dtype, elements[i]);\n }\n } else {\n // check elements and find first usable type\n // should be refactored\n for (i = 0; i < elements.length; i++) {\n if (elements[i] && isNaN(elements[i])) {\n dtype = Sk.builtin.float_;\n break;\n } else if (typeof elements[i] == 'string') {\n dtype = Sk.builtin.str;\n } else {\n dtype = Sk.builtin.float_;\n }\n }\n }\n\n // check for ndmin param\n if (ndmin) {\n if (Sk.builtin.checkNumber(ndmin)) {\n var _ndmin = Sk.builtin.asnum$(ndmin);\n if (_ndmin >= 0 && _ndmin > state.shape.length) {\n var _ndmin_array = [];\n for (i = 0; i < _ndmin - state.shape.length; i++) {\n _ndmin_array.push(1);\n }\n state.shape = _ndmin_array.concat(state.shape);\n }\n } else {\n throw new Sk.builtin.TypeError(\n 'Parameter \"ndmin\" must be of type \"int\"');\n }\n }\n\n var _shape = new Sk.builtin.tuple(state.shape.map(function (x) {\n return new Sk.builtin.int_(x);\n }));\n\n var _buffer = new Sk.builtin.list(elements);\n // create new ndarray instance\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], _shape, dtype,\n _buffer);\n };\n\n array_f.co_varnames = ['object', 'dtype', 'copy', 'order',\n 'subok', 'ndmin'\n ];\n array_f.$defaults = [null, Sk.builtin.none.none$, true, new Sk.builtin.str(\n 'C'), false, new Sk.builtin.int_(0)];\n mod.array = new Sk.builtin.func(array_f);\n\n /**\n Return a new array of given shape and type, filled with zeros.\n **/\n var zeros_f = function (shape, dtype, order) {\n Sk.builtin.pyCheckArgs(\"zeros\", arguments, 1, 3);\n Sk.builtin.pyCheckType(\"shape\", \"tuple\", shape instanceof Sk.builtin.tuple);\n if (dtype instanceof Sk.builtin.list) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(dtype) +\n \"' is not supported for dtype.\");\n }\n\n var _zero = new Sk.builtin.float_(0.0);\n\n return Sk.misceval.callsim(mod.full, shape, _zero, dtype, order);\n };\n zeros_f.co_varnames = ['shape', 'dtype', 'order'];\n zeros_f.$defaults = [\n new Sk.builtin.tuple([]), Sk.builtin.none.none$, new Sk.builtin.str('C')\n ];\n mod.zeros = new Sk.builtin.func(zeros_f);\n\n /**\n Return a new array of given shape and type, filled with `fill_value`.\n **/\n var full_f = function (shape, fill_value, dtype, order) {\n Sk.builtin.pyCheckArgs(\"full\", arguments, 2, 4);\n Sk.builtin.pyCheckType(\"shape\", \"tuple\", shape instanceof Sk.builtin.tuple);\n if (dtype instanceof Sk.builtin.list) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(dtype) +\n \"' is currently not supported for dtype.\");\n }\n\n // generate an array of the dimensions for the generic array method\n var _shape = Sk.ffi.remapToJs(shape);\n var _size = prod(_shape);\n var _buffer = [];\n var _fill_value = fill_value;\n var i;\n\n for (i = 0; i < _size; i++) {\n _buffer[i] = _fill_value;\n }\n\n // if no dtype given and type of fill_value is numeric, assume float\n if (!dtype && Sk.builtin.checkNumber(fill_value)) {\n dtype = Sk.builtin.float_;\n }\n\n // apply dtype casting function, if it has been provided\n if (Sk.builtin.checkClass(dtype)) {\n for (i = 0; i < _buffer.length; i++) {\n _buffer[i] = Sk.misceval.callsim(dtype, _buffer[i]);\n }\n }\n\n return Sk.misceval.callsim(mod[CLASS_NDARRAY], shape, dtype, new Sk.builtin\n .list(\n _buffer));\n };\n full_f.co_varnames = ['shape', 'fill_value', 'dtype', 'order'];\n full_f.$defaults = [\n new Sk.builtin.tuple([]), Sk.builtin.none.none$, Sk.builtin.none.none$, new Sk\n .builtin\n .str('C')\n ];\n mod.full = new Sk.builtin.func(full_f);\n\n\n /**\n Return a new array of given shape and type, filled with ones.\n **/\n var ones_f = function (shape, dtype, order) {\n Sk.builtin.pyCheckArgs(\"ones\", arguments, 1, 3);\n Sk.builtin.pyCheckType(\"shape\", \"tuple\", shape instanceof Sk.builtin.tuple);\n if (dtype instanceof Sk.builtin.list) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(dtype) +\n \"' is not supported for dtype.\");\n }\n\n var _one = new Sk.builtin.float_(1.0);\n return Sk.misceval.callsim(mod.full, shape, _one, dtype, order);\n };\n ones_f.co_varnames = ['shape', 'dtype', 'order'];\n ones_f.$defaults = [\n new Sk.builtin.tuple([]), Sk.builtin.none.none$, new Sk.builtin.str('C')\n ];\n mod.ones = new Sk.builtin.func(ones_f);\n\n\n /**\n Dot product\n **/\n var dot_f = function (a, b) {\n Sk.builtin.pyCheckArgs(\"dot\", arguments, 2, 2);\n\n // ToDo: add support for ndarray args\n\n if (!(a instanceof Sk.builtin.list) && !Sk.builtin.checkNumber(\n a) && (Sk.abstr.typeName(a) !== CLASS_NDARRAY)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(a) +\n \"' is not supported for a.\");\n }\n\n if (!(b instanceof Sk.builtin.list) && !Sk.builtin.checkNumber(\n b) && (Sk.abstr.typeName(b) !== CLASS_NDARRAY)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(b) +\n \"' is not supported for b.\");\n }\n\n var res;\n\n var b_matrix;\n var a_matrix;\n\n if (Sk.abstr.typeName(a) === CLASS_NDARRAY) {\n a_matrix = a.v.buffer;\n\t\t\ta_matrix = a_matrix.map(function (x) {\n\t\t\t\treturn Sk.ffi.remapToJs(x);\n\t\t\t});\n } else {\n a_matrix = Sk.ffi.remapToJs(a);\n }\n\n if (Sk.abstr.typeName(b) === CLASS_NDARRAY) {\n b_matrix = b.v.buffer;\n\t\t\tb_matrix = b_matrix.map(function (x) {\n\t\t\t\treturn Sk.ffi.remapToJs(x);\n\t\t\t});\n } else {\n b_matrix = Sk.ffi.remapToJs(b);\n }\n\n var a_size = np.math.size(a_matrix);\n var b_size = np.math.size(b_matrix);\n\n\n if (a_size.length >= 1 && b_size.length > 1) {\n if (a_size[a_size.length - 1] != b_size[b_size - 2]) {\n throw new Sk.builtin.ValueError(\n \"The last dimension of a is not the same size as the second-to-last dimension of b.\"\n );\n }\n }\n\n res = np.math.multiply(a_matrix, b_matrix);\n\t\t\n\t\tif (!Array.isArray(res)) { // if result\n\t\t\treturn Sk.ffi.remapToPy(res);\n\t\t}\n\t\t\n // return ndarray\n buffer = new Sk.builtin.list(res);\n return Sk.misceval.callsim(mod.array, buffer, Sk.builtin.float_);\n };\n dot_f.co_varnames = ['a', 'b'];\n dot_f.$defaults = [Sk.builtin.none.none$,\n Sk.builtin.none.none$\n ];\n mod.dot = new Sk.builtin.func(dot_f);\n\n /* not implemented methods */\n mod.ones_like = new Sk.builtin.func(function () {\n throw new Sk.builtin.NotImplementedError(\n \"ones_like is not yet implemented\");\n });\n mod.empty_like = new Sk.builtin.func(function () {\n throw new Sk.builtin.NotImplementedError(\n \"empty_like is not yet implemented\");\n });\n mod.ones_like = new Sk.builtin.func(function () {\n throw new Sk.builtin.NotImplementedError(\n \"ones_like is not yet implemented\");\n });\n mod.empty = new Sk.builtin.func(function () {\n throw new Sk.builtin.NotImplementedError(\n \"empty is not yet implemented\");\n });\n mod.arctan2 = new Sk.builtin.func(function () {\n throw new Sk.builtin.NotImplementedError(\n \"arctan2 is not yet implemented\");\n });\n mod.asarray = new Sk.builtin.func(array_f);\n return mod;\n};\n", "src/lib/image/__init__.js": "var $builtinmodule = function(name) {\n var mod, Canvas2Image, importAllSubmodules, DrawUtils, mediaPath;\n\n mod = {};\n\n DrawUtils = {\n drawInto : function(picture, callback) {\n var canvas, ctx;\n\n canvas = document.createElement('canvas');\n canvas.width = picture._width;\n canvas.height = picture._height;\n ctx = canvas.getContext('2d');\n ctx.putImageData(picture._imageData, 0, 0);\n \n callback(ctx, canvas);\n\n picture._imageData = ctx.getImageData(0, 0, picture._width, picture._height);\n },\n }\n\n // The Canvas2Image library is used to convert a canvas into an image that\n // can be saved to the media library. Credit for the original goes to\n // https://github.com/hongru/canvas2image.\n Canvas2Image = {\n $support : (function () {\n var canvas, ctx;\n\n canvas = document.createElement('canvas');\n ctx = canvas.getContext('2d');\n\n return {\n canvas: !!ctx,\n imageData: !!ctx.getImageData,\n dataURL: !!canvas.toDataURL,\n btoa: !!window.btoa\n };\n }()),\n\n _scaleCanvas : function (canvas, width, height) {\n var w, h, retCanvas, retCtx;\n\n w = canvas.width;\n h = canvas.height;\n\n if (!width) { width = w; }\n if (!height) { height = h; }\n\n retCanvas = document.createElement('canvas');\n retCanvas.width = width;\n retCanvas.height = height;\n\n retCtx = retCanvas.getContext('2d');\n retCtx.drawImage(canvas, 0, 0, w, h, 0, 0, width, height);\n\n return retCanvas;\n },\n\n _getDataURL : function (canvas, type, width, height) {\n return this._scaleCanvas(canvas, width, height).toDataURL(type);\n },\n\n _fixType : function (type) {\n var r;\n\n type = type.toLowerCase().replace(/jpg/i, 'jpeg');\n r = type.match(/png|jpeg|bmp|gif/)[0];\n\n return 'image/' + r;\n },\n\n _encodeData : function (data) {\n var str;\n\n if (!window.btoa) { throw new Error('btoa undefined'); }\n\n str = '';\n\n if (typeof(data) === 'string') {\n str = data;\n } else {\n for (var i = 0; i < data.length; i++) {\n str += String.fromCharCode(data[i]);\n }\n }\n\n return btoa(str);\n },\n\n _getImageData : function (canvas) {\n return canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);\n },\n\n _makeURI : function (strData, type) {\n return 'data:' + type + ';base64,' + strData;\n },\n\n _genBitmapImage : function (data) {\n var imgHeader, imgInfoHeader, width, height, fsize, _width, _height;\n var dataSize, padding, imgData, strPixelData, y, offsetX, offsetY, strPixelRow;\n\n imgHeader = [];\n imgInfoHeader = [];\n\n width = data.width;\n height = data.height;\n fsize = width * height * 3 + 54; // header size:54 bytes\n\n imgHeader.push(0x42); // 66 -> B\n imgHeader.push(0x4d); // 77 -> M\n imgHeader.push(fsize % 256); // r\n\n fsize = Math.floor(fsize / 256);\n imgHeader.push(fsize % 256); // g\n\n fsize = Math.floor(fsize / 256);\n imgHeader.push(fsize % 256); // b\n\n fsize = Math.floor(fsize / 256);\n imgHeader.push(fsize % 256); // a\n\n imgHeader.push(0);\n imgHeader.push(0);\n imgHeader.push(0);\n imgHeader.push(0);\n\n imgHeader.push(54); // offset -> 6\n imgHeader.push(0);\n imgHeader.push(0);\n imgHeader.push(0);\n\n // info header\n imgInfoHeader.push(40); // info header size\n imgInfoHeader.push(0);\n imgInfoHeader.push(0);\n imgInfoHeader.push(0);\n\n // width info\n _width = width;\n\n imgInfoHeader.push(_width % 256);\n _width = Math.floor(_width / 256);\n\n imgInfoHeader.push(_width % 256);\n _width = Math.floor(_width / 256);\n\n imgInfoHeader.push(_width % 256);\n _width = Math.floor(_width / 256);\n\n imgInfoHeader.push(_width % 256);\n\n // height info\n _height = height;\n\n imgInfoHeader.push(_height % 256);\n _height = Math.floor(_height / 256);\n\n imgInfoHeader.push(_height % 256);\n _height = Math.floor(_height / 256);\n\n imgInfoHeader.push(_height % 256);\n _height = Math.floor(_height / 256);\n\n imgInfoHeader.push(_height % 256);\n\n imgInfoHeader.push(1);\n imgInfoHeader.push(0);\n imgInfoHeader.push(24); // 24-bit bitmap\n imgInfoHeader.push(0);\n\n // no compression\n imgInfoHeader.push(0);\n imgInfoHeader.push(0);\n imgInfoHeader.push(0);\n imgInfoHeader.push(0);\n\n // pixel data\n dataSize = width * height * 3;\n\n imgInfoHeader.push(dataSize % 256);\n dataSize = Math.floor(dataSize / 256);\n\n imgInfoHeader.push(dataSize % 256);\n dataSize = Math.floor(dataSize / 256);\n\n imgInfoHeader.push(dataSize % 256);\n dataSize = Math.floor(dataSize / 256);\n\n imgInfoHeader.push(dataSize % 256);\n\n // blank space\n for (var i = 0; i < 16; i ++) { imgInfoHeader.push(0); }\n\n padding = (4 - ((width * 3) % 4)) % 4;\n imgData = data.data;\n strPixelData = '';\n y = height;\n\n do {\n offsetY = width * (y - 1) * 4;\n strPixelRow = '';\n for (var x = 0; x < width; x ++) {\n offsetX = 4 * x;\n strPixelRow += String.fromCharCode(imgData[offsetY + offsetX + 2]);\n strPixelRow += String.fromCharCode(imgData[offsetY + offsetX + 1]);\n strPixelRow += String.fromCharCode(imgData[offsetY + offsetX]);\n }\n for (var n = 0; n < padding; n ++) {\n strPixelRow += String.fromCharCode(0);\n }\n\n strPixelData += strPixelRow;\n } while(-- y);\n\n return (this._encodeData(imgHeader.concat(imgInfoHeader)) + this._encodeData(strPixelData));\n },\n\n convertToURI : function (canvas, width, height, type) {\n var data, strData;\n\n if (this.$support.canvas && this.$support.dataURL) {\n if (!type) { type = 'png'; }\n type = this._fixType(type);\n\n if (/bmp/.test(type)) {\n data = this._getImageData(this._scaleCanvas(canvas, width, height));\n strData = this._genBitmapImage(data);\n return _makeURI(strData, 'image/bmp');\n } else {\n strData = this._getDataURL(canvas, type, width, height);\n return strData;\n }\n } else {\n //TODO throw error\n }\n }\n };\n\n goog.object.extend(mod, {\n pickAFile : new Sk.builtin.func(function () {\n Sk.ffi.checkArgs('pickAFile', arguments, 0);\n\n return Sk.future(function (continueWith) {\n window.pythy.showMediaModal({\n mediaLinkClicked: function (link) {\n var clientHost, url;\n\n clientHost = window.location.protocol + '//' + window.location.host;\n url = $(link).attr('href');\n if(url[0] === '/') { url = clientHost + url; }\n\n $('#media_library_modal').modal('hide');\n\n continueWith(new Sk.builtin.str(url));\n },\n cancelled: function () {\n continueWith(null);\n }\n });\n });\n }),\n\n setMediaPath : new Sk.builtin.func(function (path) {\n Sk.ffi.checkArgs('setMediaPath', arguments, 1);\n mediaPath = Sk.ffi.unwrapo(path);\n if(mediaPath[mediaPath.length - 1] === '/') {\n mediaPath = mediaPath.substring(0, mediaPath.length - 1);\n }\n }),\n\n getMediaPath : new Sk.builtin.func(function (url) {\n Sk.ffi.checkArgs('getMediaPath', arguments, [0, 1]);\n\n if(url) {\n url = Sk.ffi.unwrapo(url);\n } else {\n url = '';\n }\n if(!mediaPath) {\n return new Sk.builtin.str(window.mediaffi.customizeMediaURL(url));\n } else {\n return new Sk.builtin.str(mediaPath + '/' + url);\n }\n }),\n\n writePictureTo : new Sk.builtin.func(function(picture, path) {\n var type;\n\n Sk.ffi.checkArgs('writePictureTo', arguments, 2);\n\n // Extract the file extension. It looks bizarre at first; source is\n // http://stackoverflow.com/a/12900504/307266.\n path = Sk.ffi.unwrapo(path);\n type = path.substr((Math.max(0, path.lastIndexOf(\".\")) || Infinity) + 1);\n\n result = Sk.future(function(continueWith) {\n DrawUtils.drawInto(picture, function(ctx, canvas) {\n var dataUrl;\n\n dataUrl = Canvas2Image.convertToURI(\n canvas, picture.width, picture.height, type);\n\n window.mediaffi.writePictureTo(dataUrl, path, continueWith);\n });\n });\n if(result && result.errors && result.errors.length) {\n throw new Sk.builtin.ValueError(result.errors[0].file[0]);\n }\n }),\n\n openPictureTool : new Sk.builtin.func(function(picture) {\n Sk.ffi.checkArgs('openPictureTool', arguments, 1);\n window.pythy.pictureTool.show(picture._url);\n }),\n });\n\n return mod;\n};\n", "src/lib/image/picture.js": "// Do not include this module directly as has dependencies \nvar $builtinmodule = function(name) {\n var mod, pictureWrapper, DrawUtils, Pixel, Color;\n\n mod = {};\n\n // Get a reference to the dependencies \n // TODO Find a better way to do this?\n Pixel = Sk.sysmodules.mp$subscript('image.pixel').$d.Pixel;\n Color = Sk.sysmodules.mp$subscript('image.color').$d;\n\n DrawUtils = {\n drawEllipticalArc : function(ctx, x, y, w, h, startAngle, endAngle, reversed, fill) {\n var ratio, xr, cx, cy;\n\n ratio = h / w;\n xr = w / 2;\n cx = x + xr;\n cy = (y + h / 2) / ratio;\n\n ctx.save();\n ctx.scale(1, ratio);\n ctx.beginPath();\n if (fill) { ctx.moveTo(cx, cy); }\n ctx.arc(cx, cy, xr, startAngle, endAngle, reversed);\n if (fill) { ctx.moveTo(cx, cy); }\n ctx.restore();\n\n if (fill){ ctx.fill(); } else { ctx.stroke(); }\n },\n\n degToRad : function(degrees) {\n return degrees * Math.PI / 180;\n },\n\n drawEllipse : function(ctx, x, y, w, h, fill) {\n var ratio = h / w;\n var xr = w / 2;\n var yr = h / 2;\n\n ctx.save();\n ctx.scale(1, h / w);\n ctx.beginPath();\n ctx.arc(x + xr, (y + yr) / ratio, xr, 0, 2 * Math.PI);\n ctx.restore();\n\n if (fill) { ctx.fill(); } else { ctx.stroke(); }\n },\n\n styleFromColor : function(color) {\n return 'rgb(' + color._red + ',' + color._green + ',' + color._blue + ')';\n },\n\n /**\n * Creates a canvas, copies the specified picture onto it, then invokes the\n * callback so that additional drawing can be performed on the context. Once\n * the callback is complete, the canvas contents are copied back into the\n * original picture.\n *\n * @param picture\n * @param callback\n */\n drawInto : function(picture, callback) {\n var canvas, ctx;\n\n canvas = document.createElement('canvas');\n canvas.width = picture._width;\n canvas.height = picture._height;\n ctx = canvas.getContext('2d');\n ctx.putImageData(picture._imageData, 0, 0);\n \n callback(ctx, canvas);\n\n picture._imageData = ctx.getImageData(0, 0, picture._width, picture._height);\n },\n\n /**\n * Returns an object with width and height properties that describe the\n * pixel dimensions of a string of text.\n *\n * @param text the string to measure\n * @param font the CSS 'font' style for the text\n */\n measureText : function(text, font) {\n var div, size;\n\n div = $('<div>').text(text).css({\n position: 'absolute',\n 'top': '-1000px',\n left: '-1000px',\n font: font\n });\n\n $('body').append(div);\n \n size = { width: div.width(), height: div.height() };\n\n div.remove();\n\n return size;\n },\n };\n\n pictureWrapper = {\n show : new Sk.builtin.func(function (self) {\n var canvas, ctx;\n\n Sk.ffi.checkArgs('show', arguments, 1);\n\n canvas = document.createElement('canvas');\n canvas.width = self._width;\n canvas.height = self._height;\n\n ctx = canvas.getContext('2d');\n ctx.putImageData(self._imageData, 0, 0);\n\n window.pythy.pictureTool.show(canvas);\n }),\n\n repaint : new Sk.builtin.func(function (self) {\n var canvas, ctx;\n\n Sk.ffi.checkArgs('repaint', arguments, 1);\n\n canvas = document.createElement('canvas');\n canvas.width = self._width;\n canvas.height = self._height;\n\n ctx = canvas.getContext('2d');\n ctx.putImageData(self._imageData, 0, 0);\n\n window.pythy.pictureTool.show(canvas);\n }),\n\n addArc : new Sk.builtin.func(function(self, x, y, width, height,\n startAngle, arcAngle, color) {\n Sk.ffi.checkArgs('addArc', arguments, [7, 8]);\n\n DrawUtils.drawInto(self, function(ctx) {\n var startRads, angleRads, endRads, reversed;\n\n ctx.lineWidth = 1;\n ctx.strokeStyle = DrawUtils.styleFromColor(color || Color.black);\n\n startRads = -DrawUtils.degToRad(Sk.ffi.unwrapo(startAngle));\n angleRads = DrawUtils.degToRad(Sk.ffi.unwrapo(arcAngle));\n endRads = startRads - angleRads;\n reversed = (angleRads >= 0);\n\n DrawUtils.drawEllipticalArc(ctx, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height), startRads, endRads,\n reversed, false);\n });\n }),\n\n addArcFilled : new Sk.builtin.func(function(self, x, y, width, height,\n startAngle, arcAngle, color) {\n Sk.ffi.checkArgs('addArcFilled', arguments, [7, 8]);\n\n DrawUtils.drawInto(self, function(ctx) {\n var startRads, angleRads, endRads, reversed;\n\n ctx.lineWidth = 1;\n ctx.fillStyle = DrawUtils.styleFromColor(color || Color.black);\n\n startRads = -DrawUtils.degToRad(Sk.ffi.unwrapo(startAngle));\n angleRads = DrawUtils.degToRad(Sk.ffi.unwrapo(arcAngle));\n endRads = startRads - angleRads;\n reversed = (angleRads >= 0);\n\n DrawUtils.drawEllipticalArc(ctx, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height), startRads, endRads,\n reversed, true);\n });\n }),\n\n addLine : new Sk.builtin.func(function(self, x1, y1, x2, y2, color) {\n Sk.ffi.checkArgs('addLine', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n ctx.lineWidth = 1;\n ctx.strokeStyle = DrawUtils.styleFromColor(color || Color.black);\n\n ctx.beginPath();\n ctx.moveTo(Sk.ffi.unwrapo(x1), Sk.ffi.unwrapo(y1));\n ctx.lineTo(Sk.ffi.unwrapo(x2), Sk.ffi.unwrapo(y2));\n ctx.stroke();\n });\n }),\n\n addOval : new Sk.builtin.func(function(self, x, y, width, height, color) {\n Sk.ffi.checkArgs('addOval', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n ctx.lineWidth = 1;\n ctx.strokeStyle = DrawUtils.styleFromColor(color || Color.black);\n DrawUtils.drawEllipse(ctx, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height), false);\n });\n }),\n\n addOvalFilled : new Sk.builtin.func(function(self, x, y, width, height, color) {\n Sk.ffi.checkArgs('addOvalFilled', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n ctx.lineWidth = 1;\n ctx.fillStyle = DrawUtils.styleFromColor(color || Color.black);\n DrawUtils.drawEllipse(ctx, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height), true);\n });\n }),\n\n addRect : new Sk.builtin.func(function(self, x, y, width, height, color) {\n Sk.ffi.checkArgs('addRect', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n ctx.lineWidth = 1;\n ctx.strokeStyle = DrawUtils.styleFromColor(color || Color.black);\n ctx.strokeRect(Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height));\n });\n }),\n\n addRectFilled : new Sk.builtin.func(function(self, x, y, width, height, color) {\n Sk.ffi.checkArgs('addRectFilled', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n ctx.lineWidth = 1;\n ctx.fillStyle = DrawUtils.styleFromColor(color || Color.black);\n ctx.fillRect(Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y),\n Sk.ffi.unwrapo(width), Sk.ffi.unwrapo(height));\n });\n }),\n\n addText : new Sk.builtin.func(function(self, x, y, string, color) {\n Sk.ffi.checkArgs('addText', arguments, [4, 5]);\n\n DrawUtils.drawInto(self, function(ctx) {\n var height, text;\n\n text = Sk.ffi.unwrapo(string);\n ctx.fillStyle = DrawUtils.styleFromColor(color || Color.black);\n height = DrawUtils.measureText(text, ctx.font).height;\n ctx.fillText(text, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y) + height);\n });\n }),\n\n addTextWithStyle : new Sk.builtin.func(function(self, x, y, text, style, color) {\n Sk.ffi.checkArgs('addTextWithStyle', arguments, [5, 6]);\n\n DrawUtils.drawInto(self, function(ctx) {\n var height;\n\n text = Sk.ffi.unwrapo(text);\n ctx.fillStyle = DrawUtils.styleFromColor(color || Color.black);\n ctx.font = Sk.misceval.callsim(style._toJSString, style);\n height = DrawUtils.measureText(text, ctx.font).height;\n ctx.fillText(text, Sk.ffi.unwrapo(x), Sk.ffi.unwrapo(y) + height);\n });\n }),\n\n getHeight : new Sk.builtin.func(function (self) {\n Sk.ffi.checkArgs('getHeight', arguments, 1);\n return new Sk.builtin.int_(self._height);\n }),\n\n getWidth : new Sk.builtin.func(function (self) {\n Sk.ffi.checkArgs('getWidth', arguments, 1);\n return new Sk.builtin.int_(self._width);\n }),\n\n getPixel : new Sk.builtin.func(function (picture, x, y) {\n Sk.ffi.checkArgs('getPixel', arguments, 3);\n return Sk.misceval.callsim(Pixel, picture, x, y);\n }),\n\n getPixelAt : new Sk.builtin.func(function (picture, x, y) {\n Sk.ffi.checkArgs('getPixelAt', arguments, 3);\n return Sk.misceval.callsim(Pixel, picture, x, y);\n }),\n\n getPixels : new Sk.builtin.func(function (picture) {\n var pixels;\n\n Sk.ffi.checkArgs('getPixels', arguments, 1);\n\n pixels = [];\n for(var r = 0; r < picture._height; r++) {\n for(var c = 0; c < picture._width; c++) {\n pixels.push(Sk.misceval.callsim(Pixel, picture, c, r));\n }\n }\n\n return new Sk.builtin.list(pixels);\n }),\n\n getAllPixels : new Sk.builtin.func(function (picture) {\n var pixels;\n\n Sk.ffi.checkArgs('getAllPixels', arguments, 1);\n\n pixels = [];\n for(var r = 0; r < picture._height; r++) {\n for(var c = 0; c < picture._width; c++) {\n pixels.push(Sk.misceval.callsim(Pixel, picture, c, r));\n }\n }\n\n return new Sk.builtin.list(pixels);\n }),\n\n copyInto: new Sk.builtin.func(function (smallPic, bigPic, startX, startY) {\n Sk.ffi.checkArgs('copyInto', arguments, 4);\n\n DrawUtils.drawInto(bigPic, function (ctx) {\n ctx.putImageData(smallPic._imageData, Sk.ffi.unwrapo(startX), Sk.ffi.unwrapo(startY));\n });\n }),\n\n setAllPixelsToAColor: new Sk.builtin.func(function (picture, color) {\n Sk.ffi.checkArgs('setAllPixelsToAColor', arguments, 2);\n\n DrawUtils.drawInto(picture, function (ctx) {\n ctx.fillStyle = DrawUtils.styleFromColor(color);\n ctx.fillRect(0, 0, picture._width, picture._height);\n });\n })\n };\n\n mod.Picture = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, imageUrl) {\n var url, res, origUrl;\n\n Sk.ffi.checkArgs('__init__', arguments, 2);\n\n origUrl = window.mediaffi.customizeMediaURL(Sk.ffi.unwrapo(imageUrl));\n\n url = Sk.transformUrl(origUrl);\n\n res = Sk.future(function (continueWith) {\n $('<img>').load(function() {\n var canvas, ctx;\n\n self._url = origUrl;\n self._width = this.width;\n self._height = this.height;\n\n canvas = document.createElement('canvas');\n canvas.width = self._width;\n canvas.height = self._height;\n ctx = canvas.getContext('2d');\n ctx.drawImage(this, 0, 0);\n\n self._ctx = ctx;\n self._imageData = ctx.getImageData(0, 0, self._width, self._height);\n continueWith(null);\n }).error(function() {\n continueWith(new Sk.builtin.ValueError('The picture could not be ' +\n 'loaded. Is the URL incorrect?'));\n }).attr('src', url);\n });\n if (res) { throw res; };\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n Sk.ffi.checkArgs('__str__', arguments, 1);\n return new Sk.builtin.str('Picture' +\n ', url ' + self._url +\n ', height ' + self._height +\n ', width ' + self._width);\n });\n\n $loc.duplicate = new Sk.builtin.func(function (picture) {\n var newPic;\n\n Sk.ffi.checkArgs('duplicate', arguments, 1);\n\n newPic = Sk.misceval.callsim(mod.EmptyPicture, picture._width, picture._height);\n Sk.misceval.callsim(mod.copyInto, picture, newPic, 0, 0);\n return newPic;\n });\n\n goog.object.extend($loc, pictureWrapper);\n\n }, 'Picture', []);\n\n mod.EmptyPicture = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, width, height) {\n var canvas, ctx;\n\n Sk.ffi.checkArgs('__init__', arguments, 3);\n\n self._width = Sk.builtin.asnum$(width);\n self._height = Sk.builtin.asnum$(height);\n canvas = document.createElement(\"canvas\");\n ctx = canvas.getContext('2d');\n canvas.height = self.height;\n canvas.width = self.width;\n self._imageData = ctx.getImageData(0, 0, self._width, self._height);\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n Sk.ffi.checkArgs('__str__', arguments, 1);\n return new Sk.builtin.str('Picture' +\n ', height ' + self._height +\n ', width ' + self._width);\n });\n }, 'EmptyPicture', [mod.Picture]);\n\n goog.object.extend(mod, pictureWrapper);\n\n goog.object.extend(mod, {\n makePicture : new Sk.builtin.func(function (imageUrl) {\n Sk.ffi.checkArgs('makePicture', arguments, 1);\n return Sk.misceval.callsim(mod.Picture, imageUrl);\n }),\n\n makeEmptyPicture : new Sk.builtin.func(function(width, height, color) {\n var picture;\n\n Sk.ffi.checkArgs('makeEmptyPicture', arguments, [2, 3]);\n color = color || Color.white\n picture = Sk.misceval.callsim(mod.EmptyPicture, width, height);\n\n DrawUtils.drawInto(picture, function (ctx) {\n ctx.fillStyle = DrawUtils.styleFromColor(color);\n ctx.fillRect(0, 0, picture._width, picture._height);\n });\n\n return picture;\n }),\n\n duplicatePicture: new Sk.builtin.func(function (picture) {\n var newPic;\n\n Sk.ffi.checkArgs('duplicatePicture', arguments, 1);\n newPic = Sk.misceval.callsim(mod.EmptyPicture, picture._width, picture._height);\n Sk.misceval.callsim(mod.copyInto, picture, newPic, 0, 0);\n return newPic;\n })\n });\n\n return mod;\n};\n", "src/lib/image/style.js": "var $builtinmodule = function(name) {\n var mod, styleWrapper;\n\n mod = {};\n\n mod.Style = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, family, emph, size) {\n Sk.ffi.checkArgs('__init__', arguments, 4);\n self._family = family;\n self._emph = emph;\n self._size = Sk.ffi.unwrapo(size);\n }); \n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n Sk.ffi.checkArgs('__str__', arguments, 1);\n return new Sk.builtin.str('Style' +\n ', family ' + self._family +\n ', emph ' + self._emph +\n ', size ' + self._size);\n });\n\n $loc._toJSString = new Sk.builtin.func(function(self) {\n var styleString;\n\n switch(self._emph) {\n case 1:\n styleString = 'bold';\n break;\n case 2:\n styleString = 'italic';\n break;\n case 3:\n styleString = 'bold italic';\n break;\n default:\n styleString = '';\n }\n\n styleString += ' ' + self._size + 'pt';\n styleString += ' ' + self._family;\n\n return styleString;\n });\n }, 'Style', []);\n\n goog.object.extend(mod, {\n makeStyle : new Sk.builtin.func(function(family, emph, size) {\n Sk.ffi.checkArgs('makeStyle', arguments, 3);\n return Sk.misceval.callsim(mod.Style, family, emph, size);\n }),\n PLAIN : 0,\n BOLD : 1,\n ITALIC : 2,\n sansSerif : 'Sans Serif',\n serif : 'Serif',\n mono : 'Monospaced',\n comicSans : 'Comic Sans MS',\n });\n\n return mod;\n};\n", "src/lib/image/color.js": "var $builtinmodule = function(name) {\n var mod, colorWrapper, COLOR_FACTOR, noWrapColor, wrapColor;\n\n mod = {};\n\n COLOR_FACTOR = 0.70;\n\n noWrapColor = function (value) {\n var v;\n\n v = Sk.builtin.asnum$(value);\n if(v < 0) { v = 0; } else if (v > 255) { v = 255; } \n return v;\n };\n\n wrapColor = function (value) {\n var v;\n\n v = (Sk.builtin.asnum$(value) % 256);\n if(value < 0) { v += 256; } \n\n return v;\n };\n\n mod._validateColor = noWrapColor;\n\n mod._colorWrapAround = 0;\n\n colorWrapper = {\n makeDarker : new Sk.builtin.func(function(self) {\n Sk.ffi.checkArgs('makeDarker', arguments, 1);\n\n // This is from java.awt.Color\n return Sk.misceval.callsim(mod.Color, self._red * COLOR_FACTOR,\n self._green * COLOR_FACTOR, self._blue * COLOR_FACTOR);\n }),\n\n makeLighter : new Sk.builtin.func(function(self) {\n var r, g, b, factor;\n \n Sk.ffi.checkArgs('makeLighter', arguments, 1);\n\n r = self._red;\n g = self._green;\n b = self._blue;\n factor = 1.0 / (1.0 - COLOR_FACTOR);\n\n // This is from java.awt.Color\n if(r === 0 && b === 0 && g === 0) {\n return Sk.misceval.callsim(mod.Color, factor, factor, factor);\n }\n\n if(r > 0 && r < factor) { r = factor; }\n if(g > 0 && g < factor) { g = factor; }\n if(b > 0 && b < factor) { b = factor; }\n\n return Sk.misceval.callsim(mod.Color, r / COLOR_FACTOR, g / COLOR_FACTOR, b / COLOR_FACTOR);\n }),\n\n makeBrighter : new Sk.builtin.func(function(self) {\n var r, g, b, factor;\n \n Sk.ffi.checkArgs('makeBrighter', arguments, 1);\n\n r = self._red;\n g = self._green;\n b = self._blue;\n factor = 1.0 / (1.0 - COLOR_FACTOR);\n\n // This is from java.awt.Color\n if(r === 0 && b === 0 && g === 0) {\n return Sk.misceval.callsim(mod.Color, factor, factor, factor);\n }\n\n if(r > 0 && r < factor) { r = factor; }\n if(g > 0 && g < factor) { g = factor; }\n if(b > 0 && b < factor) { b = factor; }\n\n return Sk.misceval.callsim(mod.Color, r / COLOR_FACTOR, g / COLOR_FACTOR, b / COLOR_FACTOR);\n }),\n\n distance : new Sk.builtin.func(function(self, other) {\n Sk.ffi.checkArgs('distance', arguments, 2);\n\n return new Sk.builtin.float_(Math.sqrt(\n Math.pow(self._red - other._red, 2) +\n Math.pow(self._green - other._green, 2) +\n Math.pow(self._blue - other._blue, 2)));\n })\n };\n\n mod.Color = Sk.misceval.buildClass(mod, function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, red, green, blue) {\n Sk.ffi.checkArgs('__init__', arguments, [2, 4]);\n\n if(red.tp$name === 'Color') {\n self._red = mod._validateColor(parseInt(Sk.builtin.asnum$(red._red)));\n self._green = mod._validateColor(parseInt(Sk.builtin.asnum$(red._green)));\n self._blue = mod._validateColor(parseInt(Sk.builtin.asnum$(red._blue)));\n } else {\n self._red = mod._validateColor(parseInt(Sk.builtin.asnum$(red))); \n self._green = mod._validateColor(parseInt(Sk.builtin.asnum$(green)));\n self._green = self._green >= 0 ? self._green : self._red;\n self._blue = mod._validateColor(parseInt(Sk.builtin.asnum$(blue)));\n self._blue = self._blue >= 0 ? self._blue : self._red;\n }\n\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n Sk.ffi.checkArgs('__str__', arguments, 1);\n return new Sk.builtin.str('Color' + \n ', r=' + self._red +\n ', g=' + self._green +\n ', b=' + self._blue);\n });\n\n goog.object.extend($loc, colorWrapper);\n }, 'Color', []); \n\n goog.object.extend(mod, colorWrapper);\n\n goog.object.extend(mod, {\n makeColor : new Sk.builtin.func(function(red, green, blue) {\n Sk.ffi.checkArgs('makeColor', arguments, [1, 3]);\n return Sk.misceval.callsim(mod.Color, red, green, blue);\n }),\n\n pickAColor : new Sk.builtin.func(function() {\n Sk.ffi.checkArgs('pickAColor', arguments, 0);\n \n return Sk.future(function(continueWith) {\n window.pythy.colorPicker.show(function (r, g, b) {\n continueWith(Sk.misceval.callsim(mod.Color, r, g, b));\n });\n });\n }),\n\n setColorWrapAround: new Sk.builtin.func(function (flag) {\n Sk.ffi.checkArgs('setColorWrapAround', arguments, 1);\n\n mod._colorWrapAround = Sk.builtin.asnum$(flag);\n\n switch(mod._colorWrapAround) {\n case 0:\n mod._validateColor = noWrapColor;\n break;\n case 1:\n mod._validateColor = wrapColor;\n break;\n default:\n throw new Sk.builtin.TypeError('The flag must be a boolean value');\n }\n }),\n\n getColorWrapAround: new Sk.builtin.func(function () {\n Sk.ffi.checkArgs('getColorWrapAround', arguments, 0);\n return new Sk.builtin.bool(mod._colorWrapAround);\n }),\n\n black : Sk.misceval.callsim(mod.Color, 0, 0, 0),\n blue : Sk.misceval.callsim(mod.Color, 0, 0, 255),\n cyan : Sk.misceval.callsim(mod.Color, 0, 255, 255),\n darkGray : Sk.misceval.callsim(mod.Color, 64, 64, 64),\n gray : Sk.misceval.callsim(mod.Color, 128, 128, 128),\n green : Sk.misceval.callsim(mod.Color, 0, 255, 0),\n lightGray : Sk.misceval.callsim(mod.Color, 192, 192, 192),\n magenta : Sk.misceval.callsim(mod.Color, 255, 0, 255),\n orange : Sk.misceval.callsim(mod.Color, 255, 200, 0),\n pink : Sk.misceval.callsim(mod.Color, 255, 175, 175),\n red : Sk.misceval.callsim(mod.Color, 255, 0, 0),\n white : Sk.misceval.callsim(mod.Color, 255, 255, 255),\n yellow : Sk.misceval.callsim(mod.Color, 255, 255, 0)\n });\n\n return mod;\n};\n", "src/lib/image/pixel.js": "// Do not include this module directly as it has dependencies \nvar $builtinmodule = function(name) {\n var mod, pixelWrapper, Color, colorMod;\n\n mod = {};\n colorMod = Sk.sysmodules.mp$subscript('image.color').$d;\n Color = colorMod.Color;\n\n pixelWrapper = {\n setColor : new Sk.builtin.func(function (self, color) {\n var data, index;\n\n Sk.ffi.checkArgs('setColor', arguments, 2);\n\n data = self._picture._imageData.data;\n\n index = self._y * 4 * self._picture._width + self._x * 4;\n\n data[index] = color._red;\n data[index+1] = color._green;\n data[index+2] = color._blue;\n // Note: We have to set the alpha to 255 because the rgb values are\n // multiplied by the alpha before being set. So if alpha = 0, the rgb\n // values will become 0\n data[index+3] = 255;\n }),\n\n getColor : new Sk.builtin.func(function (self) {\n var red, green, blue;\n\n Sk.ffi.checkArgs('getColor', arguments, 1);\n\n red = Sk.misceval.callsim(self.getRed, self); \n green = Sk.misceval.callsim(self.getGreen, self); \n blue = Sk.misceval.callsim(self.getBlue, self);\n\n return Sk.misceval.callsim(Color, red, green, blue);\n }),\n\n getX : new Sk.builtin.func(function (self) {\n Sk.ffi.checkArgs('getX', arguments, 1);\n return new Sk.builtin.int_(self._x);\n }),\n\n getY : new Sk.builtin.func(function (self) {\n Sk.ffi.checkArgs('getY', arguments, 1);\n return new Sk.builtin.int_(self._y);\n }),\n\n getRed : new Sk.builtin.func(function (self) {\n var index;\n\n Sk.ffi.checkArgs('getRed', arguments, 1);\n\n index = (self._y * 4) * self._picture._width + (self._x * 4);\n\n return new Sk.builtin.int_(self._picture._imageData.data[index]);\n }),\n\n getGreen : new Sk.builtin.func(function (self) {\n var index;\n\n Sk.ffi.checkArgs('getGreen', arguments, 1);\n\n index = (self._y * 4) * self._picture._width + (self._x * 4);\n\n return new Sk.builtin.int_(self._picture._imageData.data[index + 1]);\n }),\n\n getBlue : new Sk.builtin.func(function (self) {\n var index;\n\n Sk.ffi.checkArgs('getBlue', arguments, 1);\n\n index = (self._y * 4) * self._picture._width + (self._x * 4);\n\n return new Sk.builtin.int_(self._picture._imageData.data[index + 2]);\n }),\n\n setRed : new Sk.builtin.func(function (self, red) {\n var index;\n\n Sk.ffi.checkArgs('setRed', arguments, 2);\n\n index = self._y * 4 * self._picture._width + self._x * 4;\n\n self._picture._imageData.data[index] = colorMod._validateColor(Sk.ffi.unwrapo(red));\n // Note: We have to set the alpha to 255 because the rgb values are\n // multiplied by the alpha before being set. So if alpha = 0, the rgb\n // values will become 0\n self._picture._imageData.data[index + 3] = 255;\n }),\n\n setGreen : new Sk.builtin.func(function (self, green) {\n var index;\n\n Sk.ffi.checkArgs('setGreen', arguments, 2);\n\n index = self._y * 4 * self._picture._width + self._x * 4;\n\n self._picture._imageData.data[index + 1] = colorMod._validateColor(Sk.ffi.unwrapo(green));\n // Note: We have to set the alpha to 255 because the rgb values are\n // multiplied by the alpha before being set. So if alpha = 0, the rgb\n // values will become 0\n self._picture._imageData.data[index + 3] = 255;\n }),\n\n setBlue : new Sk.builtin.func(function (self, blue) {\n var index;\n\n Sk.ffi.checkArgs('setBlue', arguments, 2);\n\n index = self._y * 4 * self._picture._width + self._x * 4;\n\n self._picture._imageData.data[index + 2] = colorMod._validateColor(Sk.ffi.unwrapo(blue));\n // Note: We have to set the alpha to 255 because the rgb values are\n // multiplied by the alpha before being set. So if alpha = 0, the rgb\n // values will become 0\n self._picture._imageData.data[index + 3] = 255;\n })\n };\n\n mod.Pixel = Sk.misceval.buildClass(mod, function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function(self, picture, x, y) {\n Sk.ffi.checkArgs('__init__', arguments, 4);\n\n self._x = Sk.builtin.asnum$(x);\n self._y = Sk.builtin.asnum$(y);\n self._picture = picture;\n });\n\n $loc.__str__ = new Sk.builtin.func(function(self) {\n var red, green, blue;\n\n Sk.ffi.checkArgs('__str__', arguments, 1);\n\n red = Sk.builtin.asnum$(Sk.misceval.callsim(self.getRed, self)); \n green = Sk.builtin.asnum$(Sk.misceval.callsim(self.getGreen, self)); \n blue = Sk.builtin.asnum$(Sk.misceval.callsim(self.getBlue, self));\n\n return new Sk.builtin.str('Pixel' + \n ', red=' + red +\n ', green=' + green +\n ', blue=' + blue);\n });\n\n goog.object.extend($loc, pixelWrapper);\n }, 'Pixel', []);\n\n goog.object.extend(mod, pixelWrapper);\n\n return mod;\n};\n", "src/lib/xml/__init__.py": "raise NotImplementedError(\"xml is not yet implemented in Skulpt\")\n", "src/lib/xml/parsers/__init__.py": "raise NotImplementedError(\"parsers is not yet implemented in Skulpt\")\n", "src/lib/xml/sax/__init__.py": "raise NotImplementedError(\"sax is not yet implemented in Skulpt\")\n", "src/lib/xml/dom/__init__.py": "raise NotImplementedError(\"dom is not yet implemented in Skulpt\")\n", "src/lib/xml/etree/__init__.py": "raise NotImplementedError(\"etree is not yet implemented in Skulpt\")\n", "src/lib/requests/__init__.js": "var $builtinmodule = function (name) {\n var request = {};\n\n\n //~ Classes .................................................................\n\n // Response class\n //\n // Response objects are returned by the request, get, post, etc.\n // methods, allowing the user to access the response text, status\n // code, and other information.\n\n // ------------------------------------------------------------\n var response = function ($gbl, $loc) {\n\n // ------------------------------------------------------------\n $loc.__init__ = new Sk.builtin.func(function (self, data) {\n self.data$ = data;\n self.lineList = self.data$.split(\"\\n\");\n self.lineList = self.lineList.slice(0, -1);\n for (var i = 0; i < self.lineList.length; i++) {\n self.lineList[i] = self.lineList[i] + '\\n';\n }\n self.currentLine = 0;\n self.pos$ = 0;\n Sk.abstr.sattr(self, 'text', Sk.ffi.remapToPy(self.data$), true);\n });\n\n\n // ------------------------------------------------------------\n $loc.__str__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<Response>');\n });\n \n $loc.__repr__ = $loc.__str__;\n\n // ------------------------------------------------------------\n $loc.__iter__ = new Sk.builtin.func(function (self) {\n var allLines = self.lineList;\n\n return Sk.builtin.makeGenerator(function () {\n if (this.$index >= this.$lines.length) {\n return undefined;\n }\n return new Sk.builtin.str(this.$lines[this.$index++]);\n }, {\n $obj : self,\n $index: 0,\n $lines: allLines\n });\n });\n\n\n // ------------------------------------------------------------\n $loc.read = new Sk.builtin.func(function (self, size) {\n if (self.closed) {\n throw new Sk.builtin.ValueError(\"I/O operation on closed file\");\n }\n var len = self.data$.length;\n if (size === undefined) {\n size = len;\n }\n var ret = new Sk.builtin.str(self.data$.substr(self.pos$, size));\n self.pos$ += size;\n if (self.pos$ >= len) {\n self.pos$ = len;\n }\n return ret;\n });\n\n\n // ------------------------------------------------------------\n $loc.readline = new Sk.builtin.func(function (self, size) {\n var line = \"\";\n if (self.currentLine < self.lineList.length) {\n line = self.lineList[self.currentLine];\n self.currentLine++;\n }\n return new Sk.builtin.str(line);\n });\n\n\n // ------------------------------------------------------------\n $loc.readlines = new Sk.builtin.func(function (self, sizehint) {\n var arr = [];\n for (var i = self.currentLine; i < self.lineList.length; i++) {\n arr.push(new Sk.builtin.str(self.lineList[i]));\n }\n return new Sk.builtin.list(arr);\n });\n \n // ------------------------------------------------------------\n $loc.json = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy(JSON.parse(self.data$));\n });\n\n };\n\n request.Response =\n Sk.misceval.buildClass(request, response, 'Response', []);\n\n\n //~ Module functions ........................................................\n\n // ------------------------------------------------------------\n /**\n * Constructs and sends a Request. Returns Response object.\n *\n * http://docs.python-requests.org/en/latest/api/#requests.request\n *\n * For now, this implementation doesn't actually construct a Request\n * object; it just makes the request through jQuery.ajax and then\n * constructs a Response.\n */\n request.get = new Sk.builtin.func(function (url, data, timeout) {\n var prom = new Promise(function(resolve, reject) {\n if (Sk.requestsGet) {\n Sk.requestsGet(Sk.ffi.remapToJs(url), data, timeout).then(function(result) {\n resolve(Sk.misceval.callsim(request.Response, result));\n }, function(err) {\n reject(err);\n //resolve(Sk.misceval.callsim(request.Response, err));\n });\n } else {\n var xmlhttp = new XMLHttpRequest();\n \n xmlhttp.addEventListener(\"loadend\", function (e) {\n resolve(Sk.misceval.callsim(request.Response, xmlhttp.responseText));\n });\n\n if (!data) {\n xmlhttp.open(\"GET\", url.v);\n xmlhttp.send(null);\n } else {\n xmlhttp.open(\"POST\", url.v);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.setRequestHeader(\"Content-length\", data.v.length);\n xmlhttp.send(data.v);\n }\n }\n });\n\n var susp = new Sk.misceval.Suspension();\n\n susp.resume = function() {\n if (susp.data[\"error\"]) {\n //throw new Sk.builtin.IOError(susp.data[\"error\"].message);\n throw susp.data[\"error\"];\n } else {\n return resolution;\n }\n };\n \n susp.data = {\n type: \"Sk.promise\",\n promise: prom.then(function(value) {\n resolution = value;\n return value;\n }, function(err) {\n resolution = \"\";\n throw err;\n //return err;\n })\n };\n\n return susp;\n });\n\n\n return request;\n};", "src/lib/wsgiref/__init__.py": "raise NotImplementedError(\"wsgiref is not yet implemented in Skulpt\")\n", "src/lib/json/__init__.js": "var $builtinmodule = function(name) {\n \"use strict\";\n var mod = {};\n\n // skipkeys=False,\n // ensure_ascii=True,\n // check_circular=True,\n // allow_nan=True,\n // cls=None,\n // indent=None,\n // separators=None,\n // encoding=\"utf-8\",\n // default=None,\n // sort_keys=False,\n // **kw\n\n var dumps_f = function(kwa) {\n Sk.builtin.pyCheckArgs(\"dumps\", arguments, 1, Infinity, true, false);\n\n var args = Array.prototype.slice.call(arguments, 1),\n kwargs = new Sk.builtins.dict(kwa),\n sort_keys = false,\n stringify_opts, default_, jsobj, str;\n\n // default stringify options\n stringify_opts = {\n ascii : true,\n separators : {\n item_separator : ', ',\n key_separator : ': '\n }\n };\n\n kwargs = Sk.ffi.remapToJs(kwargs);\n jsobj = Sk.ffi.remapToJs(args[0]);\n\n // TODO: likely need to go through character by character to enable this\n if (typeof(kwargs.ensure_ascii) === \"boolean\" && kwargs.ensure_ascii === false) {\n stringify_opts.ascii = false;\n }\n\n // TODO: javascript sort isn't entirely compatible with python's\n if (typeof(kwargs.sort_keys) === \"boolean\" && kwargs.sort_keys) {\n sort_keys = true;\n }\n\n if (!sort_keys) {\n // don't do any sorting unless sort_keys is true\n // if sort_keys use stringify's default sort, which is alphabetical\n stringify_opts.cmp = function(a, b) {\n return 0;\n };\n }\n\n // item_separator, key_separator) tuple. The default is (', ', ': ').\n if (typeof(kwargs.separators) === \"object\" && kwargs.separators.length == 2) {\n stringify_opts.separators.item_separator = kwargs.separators[0];\n stringify_opts.separators.key_separator = kwargs.separators[1];\n }\n\n // TODO: if indent is 0 it should add newlines\n if (kwargs.indent) {\n stringify_opts.space = kwargs.indent;\n }\n\n // Sk.ffi.remapToJs doesn't map functions\n if (kwargs.default) {\n }\n\n // may need to create a clone of this to have more control/options\n str = JSON.stringify(jsobj, stringify_opts, kwargs.indent || 1);\n\n return new Sk.builtin.str(str);\n };\n\n dumps_f.co_kwargs = true;\n mod.dumps = new Sk.builtin.func(dumps_f);\n\n // encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]\n var loads_f = function(kwa) {\n Sk.builtin.pyCheckArgs(\"loads\", arguments, 1, Infinity, true, false);\n\n var args = Array.prototype.slice.call(arguments, 1),\n kwargs = new Sk.builtins.dict(kwa),\n str, obj;\n\n kwargs = Sk.ffi.remapToJs(kwargs);\n str = args[0].v;\n obj = JSON.parse(str);\n\n return Sk.ffi.remapToPy(obj);\n };\n\n loads_f.co_kwargs = true;\n mod.loads = new Sk.builtin.func(loads_f);\n \n var load_f = function(kwa) {\n Sk.builtin.pyCheckArgs(\"load\", arguments, 1, Infinity, true, false);\n \n var args = Array.prototype.slice.call(arguments, 1),\n kwargs = new Sk.builtins.dict(kwa),\n str, obj, file;\n \n kwargs = Sk.ffi.remapToJs(kwargs);\n file = args[0];\n str = Sk.misceval.callsim(Sk.builtin.file.prototype['read'], file).v;\n obj = JSON.parse(str);\n \n return Sk.ffi.remapToPy(obj);\n }\n \n load_f.co_kwargs = true;\n mod.load = new Sk.builtin.func(load_f);\n\n return mod;\n};", "src/lib/json/tests/__init__.py": "raise NotImplementedError(\"tests is not yet implemented in Skulpt\")\n", "src/lib/sqlite3/__init__.js": "var $builtinmodule = function (name) {\n var mod = {};\n if (typeof SQL != 'object') {\n Sk.debugout(\"sql.js not included and callable\");\n }\n \n mod.version = '1';\n mod.connect = new Sk.builtin.func(function(database) {\n Sk.builtin.pyCheckArgs(\"connect\", arguments, 1, 7);\n \n console.log(SQL);\n });\n \n return mod;\n}", "src/lib/bsddb/__init__.py": "raise NotImplementedError(\"bsddb is not yet implemented in Skulpt\")\n", "src/lib/matplotlib/__init__.js": "var $builtinmodule = function(name)\n{\n var matplotlib = {};\n\n return matplotlib;\n};\n", "src/lib/matplotlib/pyplot/__init__.js": "var jsplotlib = {};\n\n// Skulpt translation\nvar $builtinmodule = function(name) {\n var mod = {};\n \n // Unique ID generator for charts\n var chartCounter = 0;\n \n var chart; // The aggregate object to hold multiple plots\n var labels; // Title, X-axis title, Y-axis title\n var plots; // All the plots to end up drawing\n var extents; // The highest and lowest values across each axis\n var colorCycle;\n \n function resetChart() {\n chart = null;\n colorCycle = 0;\n labels = {\n 'title': '',\n 'x-axis': '',\n 'y-axis': ''\n };\n plots = [];\n extents = {\n 'xMin': null, \n 'yMin': null, \n 'xMax': null, \n 'yMax': null\n };\n }\n resetChart();\n \n // Keep track of any plotted values for later checks\n mod.values = [];\n\n // Creates the aggregate chart object that will hold 1 or more plots\n var createChart = function(type) {\n if (Sk.console === undefined) {\n throw new Sk.builtin.NameError(\n \"Can not resolve drawing area. Sk.console is undefined!\");\n }\n\n if (!chart) {\n // Create a new chart\n chartCounter += 1;\n chart = {};\n \n chart.margin = {'top': 20, 'right': 30, 'bottom': 50, 'left': 40};\n chart.width = Sk.console.width - chart.margin.left - chart.margin.right;\n chart.height = Sk.console.height - chart.margin.top - chart.margin.bottom;\n chart.id = 'chart' + chartCounter;\n chart.type = type;\n \n if (Sk.console.skipDrawing) {\n return chart;\n }\n \n return chart;\n }\n };\n \n function updateMinMax(attr, array) {\n if (extents[attr+\"Min\"] === null) {\n extents[attr+\"Min\"] = d3.min(array);\n } else {\n extents[attr+\"Min\"] = Math.min(d3.min(array), extents[attr+\"Min\"])\n }\n if (extents[attr+\"Max\"] === null) {\n extents[attr+\"Max\"] = d3.max(array);\n } else {\n extents[attr+\"Max\"] = Math.max(d3.max(array), extents[attr+\"Max\"])\n }\n }\n \n function getRandomSubarray(arr, size) {\n var shuffled = arr.slice(0), i = arr.length, temp, index;\n while (i--) {\n index = Math.floor((i + 1) * Math.random());\n temp = shuffled[index];\n shuffled[index] = shuffled[i];\n shuffled[i] = temp;\n }\n return shuffled.slice(0, size);\n }\n\n // Main plotting function\n var plot_f = function(kwa) {\n // Parse arguments\n Sk.builtin.pyCheckArgs(\"plotk\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1); \n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n \n // Keep a backup of the arguments for checker\n mod.values.push(args);\n \n // Parse different argument combinations\n var xdata = null;\n var ydata = null;\n var stylestring = null;\n if (args.length == 1) {\n // ydata\n ydata = Sk.ffi.remapToJs(args[0]);\n } else if (args.length == 2) {\n if (Sk.builtin.checkString(args[1])) {\n // ydata, style\n ydata = Sk.ffi.remapToJs(args[0]);\n stylestring = Sk.ffi.remapToJs(args[1]);\n } else {\n // xdata, ydata\n xdata = Sk.ffi.remapToJs(args[0]);\n ydata = Sk.ffi.remapToJs(args[1]);\n }\n } else if (args.length == 3) {\n // xdata, ydata, style\n xdata = Sk.ffi.remapToJs(args[0]);\n ydata = Sk.ffi.remapToJs(args[1]);\n stylestring = Sk.ffi.remapToJs(args[2]);\n }\n if (xdata === null) {\n xdata = [];\n for (var i = 0; i < ydata.length; i++) {\n xdata.push(i);\n }\n }\n\n \n if (Sk.console.skipDrawing) {\n return;\n }\n \n // empty canvas from previous plots\n createChart('line');\n\n // Zip up the data\n var actualData = d3.zip(xdata, ydata).map(function(e) {\n return {'x': e[0], 'y': e[1]}\n });\n // Parse formatting, also keep ColorCycler updated\n var cycle = jsplotlib.rc[\"axes.color_cycle\"];\n var linestyle = '-', marker= '', \n color = cycle[colorCycle % cycle.length];\n if (stylestring !== null) {\n var ftm_tuple = jsplotlib._process_plot_format(stylestring);\n linestyle = ftm_tuple.linestyle;\n marker = jsplotlib.parse_marker(ftm_tuple.marker);\n color = ftm_tuple.color;\n } else {\n colorCycle += 1;\n }\n // Save\n plots.push({\n \"data\": actualData, \n \"type\": 'line',\n 'style': {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': jsplotlib.color_to_hex(color)\n }\n });\n // Update min/max\n updateMinMax(\"x\", xdata)\n updateMinMax(\"y\", ydata)\n };\n plot_f.co_kwargs = true;\n mod.plot = new Sk.builtin.func(plot_f);\n\n var show_f = function() {\n /*if (Sk.console.skipDrawing) {\n Sk.console.printHtml([0], plots);\n return;\n }*/\n \n if (!chart) {\n createChart('line');\n }\n if (chart.type == 'hist' && plots.length < 1) {\n resetChart();\n return;\n }\n if (plots.length == 0) {\n return;\n }\n if (extents['xMin'] === undefined || extents['yMin'] === undefined) {\n return;\n }\n \n var yAxisBuffer;\n \n // Establish x/y scalers and axes\n if (chart.type == 'scatter' || chart.type == 'line') {\n yAxisBuffer = 5*Math.max(extents['yMin'].toLocaleString().length, \n extents['yMax'].toLocaleString().length);\n chart.xScale = d3.scale.linear()\n .domain([extents['xMin'], extents['xMax']])\n .range([0, chart.width-yAxisBuffer]);\n chart.xAxis = d3.svg.axis()\n .scale(chart.xScale)\n .orient(\"bottom\");\n } else if (chart.type == 'hist') {\n yAxisBuffer = 5*Math.max(extents['xMin'].toLocaleString().length, \n extents['xMax'].toLocaleString().length);\n chart.xScale = d3.scale.linear()\n .domain([extents['xMin'], extents['xMax']])\n .range([0, chart.width-yAxisBuffer]);\n chart.xAxis = d3.svg.axis()\n .scale(chart.xScale)\n .orient(\"bottom\");\n var bins = plots[0]['bins'];\n var tempScale = d3.scale.linear()\n .domain([\n 0, bins\n ])\n .range([extents['xMin'], extents['xMax']]);\n var tickArray = d3.range(bins+1)\n .map(tempScale).map(function(e) {\n return e;\n });\n // TODO: support multiple histograms\n var histMapper = d3.layout.histogram().bins(\n tickArray\n //chart.xScale.ticks(bins)\n )(plots[0]['data']);\n } else if (chart.type == 'bar') {\n yAxisBuffer = 5*Math.max(extents['yMin'].toLocaleString().length, \n extents['yMax'].toLocaleString().length);\n chart.xScale = d3.scale.ordinal()\n .domain([extents['xMin'], extents['xMax']])\n .rangeBands([0, chart.width-yAxisBuffer]);\n chart.xAxis = d3.svg.axis()\n .scale(chart.xScale)\n .tickFormat(function(d) { return d.index })\n .orient(\"bottom\");\n }\n if (chart.type !== 'hist') {\n chart.yScale = d3.scale.linear()\n .domain([extents['yMin'], extents['yMax']])\n .range([chart.height, 0]);\n } else {\n chart.yScale = d3.scale.linear()\n .domain([0, d3.max(histMapper, function(d) { return d.y; })])\n .range([chart.height, 0]);\n }\n chart.yAxis = d3.svg.axis()\n .scale(chart.yScale)\n .orient(\"left\");\n \n chart.mapX = function(d) {return chart.xScale(d.x)};\n chart.mapY = function(d) {return chart.yScale(d.y)};\n chart.mapLine = d3.svg.line()\n .x(function(d) { return chart.xScale(d.x); })\n .y(function(d) { return chart.yScale(d.y); })\n .interpolate(\"linear\");\n \n // set css classes\n chart.svg = d3.select(Sk.console.container).append('div').append('svg');\n //$(chart.svg.node()).parent().hide();\n chart.svg.attr('class', 'chart');\n chart.svg.attr('width', Sk.console.width);\n chart.svg.attr('height', Sk.console.height);\n chart.svg.attr('chartCount', chartCounter);\n \n var translation = \"translate(\" + (chart.margin.left + yAxisBuffer) + \",\" + chart.margin.top + \")\";\n chart.canvas = chart.svg.append(\"g\")\n .attr(\"transform\", translation);\n \n chart.canvas.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + chart.height + \")\")\n .call(chart.xAxis);\n chart.canvas.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(chart.yAxis);\n chart.canvas.select(\".x.axis\")\n .selectAll(\"text\")\n .style(\"font-size\",\"12px\");\n chart.canvas.select(\".y.axis\")\n .selectAll(\"text\")\n .style(\"font-size\",\"12px\");\n translation = \"translate(\" + ( (chart.width-yAxisBuffer) / 2) + \" ,\" + (chart.height + chart.margin.bottom-14) + \")\";\n chart.canvas.append(\"text\") // text label for the x axis\n .attr(\"transform\", translation)\n .attr(\"class\", \"x-axis-label\")\n .style(\"font-size\", \"14px\") \n .text(labels['x-axis'])\n .style(\"text-anchor\", \"middle\");\n chart.canvas.append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"class\", \"y-axis-label\")\n .attr(\"y\", 0 - chart.margin.left-yAxisBuffer)\n .attr(\"x\", 0 - (chart.height / 2))\n .attr(\"dy\", \"1em\")\n .text(labels['y-axis'])\n .style(\"font-size\", \"14px\") \n .style(\"text-anchor\", \"middle\");\n chart.canvas.append(\"text\")\n .attr(\"x\", ( (chart.width-yAxisBuffer) / 2))\n .attr(\"y\", 0 - (chart.margin.top / 2))\n .attr(\"class\", \"title-text\")\n .text(labels['title'])\n .attr(\"text-anchor\", \"middle\") \n .style(\"font-size\", \"14px\") \n .style(\"text-decoration\", \"underline\");\n chart.canvas.append(\"text\")\n .attr(\"x\", 0)\n .attr(\"y\", 0)\n .text(\"BlockPy\")\n .style(\"stroke\", \"#FDFDFD\")\n .style(\"font-size\", \"8px\");\n chart.svg.insert('defs', \":first-child\")\n .append('style')\n .attr(\"type\", \"text/css\")\n .text(\"svg { background-color: white; }\\n\"+\n \".axis path,.axis line { fill: none; stroke: black; shape-rendering: crispEdges;}\\n\"+\n \".line { fill: none; stroke-width: 1px;}\\n\"+\n \".circle { r: 3; shape-rendering: crispEdges; }\\n\"+\n \".bar { shape-rendering: crispEdges;}\\n\")\n \n // Actually draw the chart objects\n for (var i = 0; i < plots.length; i += 1) {\n var plot = plots[i];\n if (plot['type'] == 'line') {\n chart.canvas.append(\"path\")\n .style('stroke', plot['style']['color'])\n .attr('class', \"line\")\n .data(plot['data'])\n .attr(\"d\", chart.mapLine(plot['data']));\n } else if (plot['type'] == 'scatter') {\n chart.canvas.append(\"g\")\n .attr(\"class\", \"series\")\n .selectAll(\".point\")\n .data(plot['data'])\n .enter()\n .append('circle')\n .style('fill', plot['style']['color'])\n .attr(\"class\", \"circle\")\n .attr(\"cx\", chart.mapX)\n .attr(\"cy\", chart.mapY)\n .attr('r', 2);\n } else if (plot['type'] == 'hist') {\n chart.canvas.selectAll('.bar')\n .data(histMapper)\n .enter().append(\"rect\")\n .attr(\"class\", \"bar\")\n .style('fill', plot['style']['color'])\n .style('stroke', 'black')\n .attr(\"x\", function(d) { return chart.xScale(d.x); })\n .attr(\"width\", (chart.width-yAxisBuffer)/(1+histMapper.length))\n .attr(\"y\", function(d) { return chart.yScale(d.y); })\n .attr(\"height\", function(d) { return chart.height - chart.yScale(d.y); });\n }\n }\n if (Sk.console.pngMode) {\n var doctype = '<?xml version=\"1.0\" standalone=\"no\"?>' + '<' + '!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">';\n var xml = new XMLSerializer().serializeToString(chart.svg[0][0]);\n var blob = new Blob([ doctype + xml], { type: 'image/svg+xml' });\n var url = window.URL.createObjectURL(blob);\n //var data = \"data:image/svg+xml;base64,\" + btoa(unescape(encodeURIComponent(xml)));\n var img = document.createElement(\"img\");\n img.style.display = 'block';\n var oldChart = chart;\n var oldPlots = plots;\n Sk.console.printHtml(img, oldPlots);\n resetChart();\n oldChart.svg[0][0].parentNode.replaceChild(img, oldChart.svg[0][0])\n img.onload = function() {\n img.onload = null;\n //TODO: Make this capture a class descendant. Cross the D3/Jquery barrier!\n var canvas = document.createElement('canvas');\n canvas.width = Sk.console.width;\n canvas.height = Sk.console.height;\n var ctx = canvas.getContext('2d');\n ctx.drawImage(img, 0, 0);\n var canvasUrl = canvas.toDataURL(\"image/png\");\n img.setAttribute('src', canvasUrl);\n // Snip off this chart, we can now start a new one.\n }\n img.onerror = function() {\n \n }\n img.setAttribute('src', url);\n } else {\n Sk.console.printHtml(chart.svg, plots);\n // Snip off this chart, we can now start a new one.\n resetChart();\n }\n };\n mod.show = new Sk.builtin.func(show_f);\n\n var title_f = function(s) {\n Sk.builtin.pyCheckArgs(\"title\", arguments, 1, 1);\n\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(s) +\n \"' is not supported for title; should be a string.\");\n }\n \n labels['title']= Sk.ffi.remapToJs(s);\n };\n mod.title = new Sk.builtin.func(title_f);\n\n var xlabel_f = function(s) {\n Sk.builtin.pyCheckArgs(\"xlabel\", arguments, 1, 1);\n\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(s) +\n \"' is not supported for xlabel; should be a string.\");\n }\n \n labels['x-axis']= Sk.ffi.remapToJs(s);\n };\n mod.xlabel = new Sk.builtin.func(xlabel_f);\n\n var ylabel_f = function(s) {\n Sk.builtin.pyCheckArgs(\"ylabel\", arguments, 1, 1);\n\n if (!Sk.builtin.checkString(s)) {\n throw new Sk.builtin.TypeError(\"'\" + Sk.abstr.typeName(s) +\n \"' is not supported for ylabel; should be a string.\");\n }\n \n labels['y-axis']= Sk.ffi.remapToJs(s);\n };\n mod.ylabel = new Sk.builtin.func(ylabel_f);\n\n // Clear the current figure\n var clf_f = function() {\n chart = null;\n resetChart();\n };\n mod.clf = new Sk.builtin.func(clf_f);\n\n UNSUPPORTED = [\"semilogx\", \"semilogy\", \"specgram\", \"stackplot\", \"stem\", \"step\", \"streamplot\", \"tricontour\", \"tricontourf\", \"tripcolor\", \"triplot\", \"vlines\", \"xcorr\", \"barbs\", \"cla\", \"grid\", \"table\", \"text\", \"annotate\", \"ticklabel_format\", \"locator_params\", \"tick_params\", \"margins\", \"autoscale\", \"autumn\", \"cool\", \"copper\", \"flag\", \"gray\", \"hot\", \"hsv\", \"jet\", \"pink\", \"prism\", \"spring\", \"summer\", \"winter\", \"spectral\", \"hlines\", \"loglog\", \"magnitude_spectrum\", \"pcolor\", \"pcolormesh\", \"phase_spectrum\", \"pie\", \"plot_date\", \"psd\", \"quiver\", \"quiverkey\", \"findobj\", \"switch_backend\", \"isinteractive\", \"ioff\", \"ion\", \"pause\", \"rc\", \"rc_context\", \"rcdefaults\", \"gci\", \"sci\", \"xkcd\", \"figure\", \"gcf\", \"get_fignums\", \"get_figlabels\", \"get_current_fig_manager\", \"connect\", \"disconnect\", \"close\", \"savefig\", \"ginput\", \"waitforbuttonpress\", \"figtext\", \"suptitle\", \"figimage\", \"figlegend\", \"hold\", \"ishold\", \"over\", \"delaxes\", \"sca\", \"gca\", \"subplot\", \"subplots\", \"subplot2grid\", \"twinx\", \"twiny\", \"subplots_adjust\", \"subplot_tool\", \"tight_layout\", \"box\", \"xlim\", \"ylim\", \"xscale\", \"yscale\", \"xticks\", \"yticks\", \"minorticks_on\", \"minorticks_off\", \"rgrids\", \"thetagrids\", \"plotting\", \"get_plot_commands\", \"colors\", \"colormaps\", \"_setup_pyplot_info_docstrings\", \"colorbar\", \"clim\", \"set_cmap\", \"imread\", \"imsave\", \"matshow\", \"polar\", \"plotfile\", \"_autogen_docstring\", \"acorr\", \"arrow\", \"axhline\", \"axhspan\", \"axvline\", \"axvspan\", \"bar\", \"barh\", \"broken_barh\", \"boxplot\", \"cohere\", \"clabel\", \"contour\", \"contourf\", \"csd\", \"errorbar\", \"eventplot\", \"fill\", \"fill_between\", \"fill_betweenx\", \"hexbin\", \"hist2d\", 'axis']\n for (var i = 0; i < UNSUPPORTED.length; i+= 1) {\n mod[UNSUPPORTED[i]] = new Sk.builtin.func(function() {\n throw new Sk.builtin.NotImplementedError(UNSUPPORTED[i]+\" is not yet implemented\");\n });\n }\n \n var legend_f = function() {\n return Sk.builtin.none.none$;\n }\n mod.legend = new Sk.builtin.func(legend_f);\n \n var hist_f = function(kwa) {\n // Parse arguments\n Sk.builtin.pyCheckArgs(\"hist\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1); \n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n \n var bins = 10;\n if (\"bins\" in kwargs) {\n bins = kwargs[\"bins\"];\n }\n \n // Keep a backup of the arguments for checker\n mod.values.push(args);\n \n // Parse different argument combinations\n var data = null;\n var stylestring = null;\n if (args.length == 1) {\n // xdata\n data = Sk.ffi.remapToJs(args[0]);\n } else if (args.length == 2) {\n // xdata, style\n data = Sk.ffi.remapToJs(args[0]);\n stylestring = Sk.ffi.remapToJs(args[1]);\n }\n \n if (Sk.console.skipDrawing) {\n return;\n }\n \n // empty canvas from previous plots\n createChart('hist');\n\n // Parse formatting, also keep ColorCycler updated\n var cycle = jsplotlib.rc[\"axes.color_cycle\"];\n var linestyle = ' ', marker= 'o', \n color = cycle[colorCycle % cycle.length];\n if (stylestring !== null) {\n var ftm_tuple = jsplotlib._process_plot_format(stylestring);\n linestyle = ftm_tuple.linestyle;\n marker = jsplotlib.parse_marker(ftm_tuple.marker);\n color = ftm_tuple.color;\n } else {\n colorCycle += 1;\n }\n // Save\n plots.push({\n \"data\": data, \n \"type\": 'hist',\n \"bins\": bins,\n 'style': {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': jsplotlib.color_to_hex(color)\n }\n });\n updateMinMax(\"x\", data);\n }\n hist_f.co_kwargs = true;\n mod.hist = new Sk.builtin.func(hist_f);\n \n var scatter_f = function(kwa) {\n // Parse arguments\n Sk.builtin.pyCheckArgs(\"scatter\", arguments, 1, Infinity, true, false);\n args = Array.prototype.slice.call(arguments, 1); \n kwargs = new Sk.builtins.dict(kwa); // is pretty useless for handling kwargs\n kwargs = Sk.ffi.remapToJs(kwargs); // create a proper dict\n \n var dot_limit = 256;\n if (\"dot_limit\" in kwargs) {\n dot_limit = kwargs[\"dot_limit\"];\n }\n \n // Keep a backup of the arguments for checker\n mod.values.push(args);\n \n // Parse different argument combinations\n var xdata = null;\n var ydata = null;\n var stylestring = null;\n if (args.length == 2) {\n // xdata, ydata\n xdata = Sk.ffi.remapToJs(args[0]);\n ydata = Sk.ffi.remapToJs(args[1]);\n } else if (args.length == 3) {\n // xdata, ydata, style\n xdata = Sk.ffi.remapToJs(args[0]);\n ydata = Sk.ffi.remapToJs(args[1]);\n stylestring = Sk.ffi.remapToJs(args[2]);\n }\n \n if (xdata.length > dot_limit) {\n var xdataSampled = [], ydataSampled = [];\n var LENGTH = xdata.length, RATE = LENGTH / dot_limit;\n for (var i = 0; i < dot_limit; i+= 1) {\n var index = Math.floor((i+Math.random())*RATE);\n xdataSampled.push(xdata[index])\n ydataSampled.push(ydata[index]);\n }\n xdata = xdataSampled;\n ydata = ydataSampled;\n }\n \n if (Sk.console.skipDrawing) {\n return;\n }\n \n // empty canvas from previous plots\n createChart('scatter');\n\n // Zip up the data\n var actualData = d3.zip(xdata, ydata).map(function(e) {\n return {'x': e[0], 'y': e[1]}\n });\n // Parse formatting, also keep ColorCycler updated\n var cycle = jsplotlib.rc[\"axes.color_cycle\"];\n var linestyle = ' ', marker= 'o', \n color = cycle[colorCycle % cycle.length];\n if (stylestring !== null) {\n var ftm_tuple = jsplotlib._process_plot_format(stylestring);\n linestyle = ftm_tuple.linestyle;\n marker = jsplotlib.parse_marker(ftm_tuple.marker);\n color = ftm_tuple.color;\n } else {\n colorCycle += 1;\n }\n // Save\n plots.push({\n \"data\": actualData, \n \"type\": 'scatter',\n 'style': {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': jsplotlib.color_to_hex(color)\n }\n });\n // Update min/max\n updateMinMax(\"x\", xdata)\n updateMinMax(\"y\", ydata)\n };\n scatter_f.co_kwargs = true;\n mod.scatter = new Sk.builtin.func(scatter_f);\n \n\n return mod;\n};\n\n\njsplotlib.rc = {\n \"lines.linewidth\": 1.0,\n \"lines.linestyle\": \"-\",\n \"lines.color\": \"blue\",\n \"lines.marker\": \"None\",\n \"lines.markeredgewidth\": 0.5,\n \"lines.markersize\": 6,\n \"lines.dash_joinstyle\": \"miter\",\n \"lines.dash_capstyle\": \"butt\",\n \"lines.solid_jointyle\": \"miter\",\n \"lines.solid_capstyle\": \"projecting\",\n \"lines.antialiased\": true,\n \"patch.linewidth\": 1.0,\n \"patch.facecolor\": \"blue\",\n \"patch.edgecolor\": \"black\",\n \"patch.antialiased\": true,\n \"text.color\": \"black\",\n \"axes.hold\": true, // whether to clear the axes by default on\n \"axes.facecolor\": \"white\", // axes background color\n \"axes.edgecolor\": \"black\", // axes edge color\n \"axes.grid\": false,\n \"axes.titlesize\": \"large\",\n \"axes.labelsize\": \"medium\",\n \"axes.labelweigth\": \"normal\",\n \"axes.labelcolor\": \"black\",\n \"axes.axisbelow\": false,\n \"axes.color_cycle\": [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\"]\n};\n\nvar chart_counter = 0; // for creating unique ids\njsplotlib._line_counter = 0;\n\n/** List of all supported line styles **/\njsplotlib.lineStyles = {\n '-': '_draw_solid',\n '--': '_draw_dashed',\n '-.': '_draw_dash_dot',\n ':': '_draw_dotted',\n 'None': '_draw_nothing',\n ' ': '_draw_nothing',\n '': '_draw_nothing',\n};\n\njsplotlib.lineMarkers = {\n '.': 'point',\n ',': 'pixel',\n 'o': 'circle',\n 'v': 'triangle_down',\n '^': 'triangle_up',\n '<': 'triangle_left',\n '>': 'triangle_right',\n '1': 'tri_down',\n '2': 'tri_up',\n '3': 'tri_left',\n '4': 'tri_right',\n '8': 'octagon',\n 's': 'square',\n 'p': 'pentagon',\n '*': 'star',\n 'h': 'hexagon1',\n 'H': 'hexagon2',\n '+': 'plus',\n 'x': 'x',\n 'D': 'diamond',\n 'd': 'thin_diamond',\n '|': 'vline',\n '_': 'hline',\n //TICKLEFT: 'tickleft',\n //TICKRIGHT: 'tickright',\n //TICKUP: 'tickup',\n //TICKDOWN: 'tickdown',\n //CARETLEFT: 'caretleft',\n //CARETRIGHT: 'caretright',\n //CARETUP: 'caretup',\n //CARETDOWN: 'caretdown',\n \"None\": 'nothing',\n //Sk.builtin.none.none$: 'nothing',\n ' ': 'nothing',\n '': 'nothing'\n};\n\n/**\n Color short keys\n**/\njsplotlib.colors = {\n 'b': 'blue',\n 'g': 'green',\n 'r': 'red',\n 'c': 'cyan',\n 'm': 'magenta',\n 'y': 'yellow',\n 'k': 'black',\n 'w': 'white'\n};\n\n/**\n Mapping of all possible CSS colors, that are supported by matplotlib\n**/\njsplotlib.cnames = {\n 'aliceblue': '#F0F8FF',\n 'antiquewhite': '#FAEBD7',\n 'aqua': '#00FFFF',\n 'aquamarine': '#7FFFD4',\n 'azure': '#F0FFFF',\n 'beige': '#F5F5DC',\n 'bisque': '#FFE4C4',\n 'black': '#000000',\n 'blanchedalmond': '#FFEBCD',\n 'blue': '#0000FF',\n 'blueviolet': '#8A2BE2',\n 'brown': '#A52A2A',\n 'burlywood': '#DEB887',\n 'cadetblue': '#5F9EA0',\n 'chartreuse': '#7FFF00',\n 'chocolate': '#D2691E',\n 'coral': '#FF7F50',\n 'cornflowerblue': '#6495ED',\n 'cornsilk': '#FFF8DC',\n 'crimson': '#DC143C',\n 'cyan': '#00FFFF',\n 'darkblue': '#00008B',\n 'darkcyan': '#008B8B',\n 'darkgoldenrod': '#B8860B',\n 'darkgray': '#A9A9A9',\n 'darkgreen': '#006400',\n 'darkkhaki': '#BDB76B',\n 'darkmagenta': '#8B008B',\n 'darkolivegreen': '#556B2F',\n 'darkorange': '#FF8C00',\n 'darkorchid': '#9932CC',\n 'darkred': '#8B0000',\n 'darksage': '#598556',\n 'darksalmon': '#E9967A',\n 'darkseagreen': '#8FBC8F',\n 'darkslateblue': '#483D8B',\n 'darkslategray': '#2F4F4F',\n 'darkturquoise': '#00CED1',\n 'darkviolet': '#9400D3',\n 'deeppink': '#FF1493',\n 'deepskyblue': '#00BFFF',\n 'dimgray': '#696969',\n 'dodgerblue': '#1E90FF',\n 'firebrick': '#B22222',\n 'floralwhite': '#FFFAF0',\n 'forestgreen': '#228B22',\n 'fuchsia': '#FF00FF',\n 'gainsboro': '#DCDCDC',\n 'ghostwhite': '#F8F8FF',\n 'gold': '#FFD700',\n 'goldenrod': '#DAA520',\n 'gray': '#808080',\n 'green': '#008000',\n 'greenyellow': '#ADFF2F',\n 'honeydew': '#F0FFF0',\n 'hotpink': '#FF69B4',\n 'indianred': '#CD5C5C',\n 'indigo': '#4B0082',\n 'ivory': '#FFFFF0',\n 'khaki': '#F0E68C',\n 'lavender': '#E6E6FA',\n 'lavenderblush': '#FFF0F5',\n 'lawngreen': '#7CFC00',\n 'lemonchiffon': '#FFFACD',\n 'lightblue': '#ADD8E6',\n 'lightcoral': '#F08080',\n 'lightcyan': '#E0FFFF',\n 'lightgoldenrodyellow': '#FAFAD2',\n 'lightgreen': '#90EE90',\n 'lightgray': '#D3D3D3',\n 'lightpink': '#FFB6C1',\n 'lightsage': '#BCECAC',\n 'lightsalmon': '#FFA07A',\n 'lightseagreen': '#20B2AA',\n 'lightskyblue': '#87CEFA',\n 'lightslategray': '#778899',\n 'lightsteelblue': '#B0C4DE',\n 'lightyellow': '#FFFFE0',\n 'lime': '#00FF00',\n 'limegreen': '#32CD32',\n 'linen': '#FAF0E6',\n 'magenta': '#FF00FF',\n 'maroon': '#800000',\n 'mediumaquamarine': '#66CDAA',\n 'mediumblue': '#0000CD',\n 'mediumorchid': '#BA55D3',\n 'mediumpurple': '#9370DB',\n 'mediumseagreen': '#3CB371',\n 'mediumslateblue': '#7B68EE',\n 'mediumspringgreen': '#00FA9A',\n 'mediumturquoise': '#48D1CC',\n 'mediumvioletred': '#C71585',\n 'midnightblue': '#191970',\n 'mintcream': '#F5FFFA',\n 'mistyrose': '#FFE4E1',\n 'moccasin': '#FFE4B5',\n 'navajowhite': '#FFDEAD',\n 'navy': '#000080',\n 'oldlace': '#FDF5E6',\n 'olive': '#808000',\n 'olivedrab': '#6B8E23',\n 'orange': '#FFA500',\n 'orangered': '#FF4500',\n 'orchid': '#DA70D6',\n 'palegoldenrod': '#EEE8AA',\n 'palegreen': '#98FB98',\n 'paleturquoise': '#AFEEEE',\n 'palevioletred': '#DB7093',\n 'papayawhip': '#FFEFD5',\n 'peachpuff': '#FFDAB9',\n 'peru': '#CD853F',\n 'pink': '#FFC0CB',\n 'plum': '#DDA0DD',\n 'powderblue': '#B0E0E6',\n 'purple': '#800080',\n 'red': '#FF0000',\n 'rosybrown': '#BC8F8F',\n 'royalblue': '#4169E1',\n 'saddlebrown': '#8B4513',\n 'salmon': '#FA8072',\n 'sage': '#87AE73',\n 'sandybrown': '#FAA460',\n 'seagreen': '#2E8B57',\n 'seashell': '#FFF5EE',\n 'sienna': '#A0522D',\n 'silver': '#C0C0C0',\n 'skyblue': '#87CEEB',\n 'slateblue': '#6A5ACD',\n 'slategray': '#708090',\n 'snow': '#FFFAFA',\n 'springgreen': '#00FF7F',\n 'steelblue': '#4682B4',\n 'tan': '#D2B48C',\n 'teal': '#008080',\n 'thistle': '#D8BFD8',\n 'tomato': '#FF6347',\n 'turquoise': '#40E0D0',\n 'violet': '#EE82EE',\n 'wheat': '#F5DEB3',\n 'white': '#FFFFFF',\n 'whitesmoke': '#F5F5F5',\n 'yellow': '#FFFF00',\n 'yellowgreen': '#9ACD32'\n};\n\njsplotlib.color_to_hex = function(color) {\n // is color a shortcut?\n if (jsplotlib.colors[color])\n color = jsplotlib.colors[color];\n\n // is inside cnames array?\n if (jsplotlib.cnames[color])\n return jsplotlib.cnames[color];\n\n // check if it is already a hex value\n if (typeof color == \"string\") {\n var match = color.match(/^#(?:[0-9a-fA-F]{3}){1,2}$/);\n if (match && match.length === 1)\n return match[0];\n }\n\n // add rgb colors here\n if (Array.isArray(color) && color.length === 3) {\n return jsplotlib.rgb2hex(color);\n }\n\n // back to default\n return jsplotlib.cnames[jsplotlib.rc['lines.color']];\n};\n\njsplotlib.get_color = function(cs) {\n return jsplotlib.colors[cs] ? jsplotlib.colors[cs] : jsplotlib.colors.b;\n};\n\njsplotlib.parse_marker = function(style) {\n if (!style) return \"x\";\n switch (style) {\n case '.':\n return \".\";\n case ',':\n return \"x\";\n case 'o':\n return \"o\";\n case 'v':\n return \"x\";\n case '^':\n return \"x\";\n case '<':\n return \"x\";\n case '>':\n return \"x\";\n case '1':\n return \"x\";\n case '2':\n return \"x\";\n case '3':\n return \"x\";\n case '4':\n return \"x\";\n case 's':\n return \"s\";\n case 'p':\n return \"x\";\n case '*':\n return \"x\";\n case 'h':\n return \"x\";\n case 'H':\n return \"x\";\n case '+':\n return \"x\";\n case 'x':\n return \"x\";\n case 'D':\n return \"x\";\n case 'd':\n return \"x\";\n case '|':\n return \"x\";\n case '_':\n return \"x\";\n default:\n return \"\";\n }\n};\n\n/**\nProcess a MATLAB style color/line style format string. Return a\n(*linestyle*, *color*) tuple as a result of the processing. Default\nvalues are ('-', 'b'). Example format strings include:\n\n* 'ko': black circles\n* '.b': blue dots\n* 'r--': red dashed lines\n\n.. seealso::\n\n :func:`~matplotlib.Line2D.lineStyles` and\n :func:`~matplotlib.pyplot.colors`\n for all possible styles and color format string.\n**/\njsplotlib._process_plot_format = function(fmt) {\n var linestyle = null;\n var marker = null;\n var color = null;\n\n // Is fmt just a colorspec\n try {\n color = jsplotlib.to_rgb(fmt);\n if (color) {\n return {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': color\n };\n }\n } catch (e) {}\n\n // handle the multi char special cases and strip them for the string\n if (fmt.search(/--/) >= 0) {\n linestyle = '--';\n fmt = fmt.replace(/--/, '');\n }\n if (fmt.search(/-\\./) >= 0) {\n linestyle = '-.';\n fmt = fmt.replace(/-\\./, '');\n }\n if (fmt.search(/ /) >= 0) {\n linestyle = '';\n fmt = fmt.replace(/ /, '');\n }\n\n var i;\n for (i = 0; i < fmt.length; i++) {\n var c = fmt.charAt(i);\n if (jsplotlib.lineStyles[c]) {\n if (linestyle) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two linestyle symbols');\n }\n linestyle = c;\n } else if (jsplotlib.lineMarkers[c]) {\n if (marker) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two marker symbols');\n }\n marker = c;\n } else if (jsplotlib.colors[c]) {\n if (color) {\n throw new Sk.builtin.ValueError('Illegal format string \"' + fmt +\n '\"; two color symbols');\n }\n color = c;\n } else {\n throw new Sk.builtin.ValueError('Unrecognized character ' + c +\n ' in format string');\n }\n }\n\n if (!linestyle && !marker) {\n // use defaults --> rcParams['lines.linestyle']\n linestyle = '-';\n }\n if (!linestyle) {\n linestyle = ' ';\n }\n if (!marker) {\n marker = '';\n }\n\n return {\n 'linestyle': linestyle,\n 'marker': marker,\n 'color': color\n };\n};\n\n/**\n https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py\n http://matplotlib.org/api/colors_api.html\n\n Returns an *RGB* tuple of three floats from 0-1.\n\n *arg* can be an *RGB* or *RGBA* sequence or a string in any of\n several forms:\n\n 1) a letter from the set 'rgbcmykw'\n 2) a hex color string, like '#00FFFF'\n 3) a standard name, like 'aqua'\n 4) a string representation of a float, like '0.4',\n indicating gray on a 0-1 scale\n\n if *arg* is *RGBA*, the *A* will simply be discarded.\n**/\njsplotlib.to_rgb = function(fmt) {\n if (!fmt) return null;\n\n var color = null;\n\n if (typeof fmt == \"string\") {\n fmt_lower = fmt.toLowerCase();\n\n if (jsplotlib.colors[fmt_lower])\n return jsplotlib.hex2color(jsplotlib.cnames[jsplotlib.colors[fmt_lower]]);\n\n // is inside cnames array?\n if (jsplotlib.cnames[fmt_lower])\n return jsplotlib.hex2color(jsplotlib.cnames[fmt_lower]);\n\n if (fmt_lower.indexOf('#') === 0) {\n return jsplotlib.hex2color(fmt_lower);\n }\n\n // is it simple grey shade?\n var fl = parseFloat(fmt_lower);\n if (isNaN(fl)) {\n throw new Sk.builtin.ValueError('cannot convert argument to rgb sequence');\n }\n\n if (fl < 0 || fl > 1) {\n throw new Sk.builtin.ValueError('gray (string) must be in range 0-1');\n }\n\n return [fl, fl, fl];\n }\n\n // check if its a color tuple [r,g,b, [a]] with values from [0-1]\n if (Array.isArray(fmt)) {\n if (fmt.length > 4 || fmt.length < 3)\n throw new Sk.builtin.ValueError('sequence length is ' + fmt.length +\n '; must be 3 or 4');\n\n color = fmt.slice(0, 3);\n var i;\n\n for (i = 0; i < 3; i++) {\n var fl_rgb = parseFloat(fmt);\n\n if (fl_rgb < 0 || fl_rgb > 1)\n throw new Sk.builtin.ValueError(\n 'number in rbg sequence outside 0-1 range');\n }\n }\n\n return color;\n};\n\n/**\n Take a hex string *s* and return the corresponding rgb 3-tuple\n Example: #efefef -> (0.93725, 0.93725, 0.93725)\n**/\njsplotlib.hex2color = function(s) {\n if (!s || typeof s != \"string\") {\n throw new Sk.builtin.TypeError(\"hex2color requires a string argument\");\n }\n // check if it is a hex value\n var i;\n var s_copy = s;\n var hex_tuple = [];\n for (i = 0; i < 3; i++) {\n var match = s_copy.match(/(?:[0-9a-fA-F]){1,2}$/);\n if (match && match.length === 1) {\n hex_tuple.push(match[0]);\n s_copy = s_copy.substring(0, match.index);\n }\n }\n //var match = s.match(/^#(?:[0-9a-fA-F]{3}){1,2}$/);\n if (hex_tuple.length === 3) {\n // yeah positiv --> convert into right color spec\n var color = [];\n color[0] = parseInt(hex_tuple[0], 16) / 255.0;\n color[1] = parseInt(hex_tuple[1], 16) / 255.0;\n color[2] = parseInt(hex_tuple[2], 16) / 255.0;\n\n return color.reverse();\n } else {\n throw new Sk.builtin.ValueError('invalid hex color string \"' + s + '\"');\n }\n};\n\n/**\n Expects and rgb tuple with values [0,1]\n**/\njsplotlib.rgb2hex = function(rgb) {\n if (!rgb) return null;\n\n if (rgb.length && rgb.length >= 3) {\n var i;\n // some hacky code to rebuild string format :(\n var hex_str = '#';\n for (i = 0; i < 3; i++) {\n var val = Math.round(rgb[i] * 255).toString(16);\n hex_str += val.length == 2 ? val : '0' + val;\n }\n\n return hex_str;\n }\n};\n", "src/lib/lib2to3/__init__.py": "raise NotImplementedError(\"lib2to3 is not yet implemented in Skulpt\")\n", "src/lib/lib2to3/fixes/__init__.py": "raise NotImplementedError(\"fixes is not yet implemented in Skulpt\")\n", "src/lib/lib2to3/tests/__init__.py": "raise NotImplementedError(\"tests is not yet implemented in Skulpt\")\n", "src/lib/lib2to3/pgen2/__init__.py": "raise NotImplementedError(\"pgen2 is not yet implemented in Skulpt\")\n", "src/lib/idlelib/__init__.py": "raise NotImplementedError(\"idlelib is not yet implemented in Skulpt\")\n", "src/lib/idlelib/Icons/__init__.py": "raise NotImplementedError(\"Icons is not yet implemented in Skulpt\")\n", "src/lib/pythonds/__init__.py": "", "src/lib/pythonds/trees/binaryTree.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n\nclass BinaryTree:\n \"\"\"\n A recursive implementation of Binary Tree\n Using links and Nodes approach.\n \"\"\" \n def __init__(self,rootObj):\n self.key = rootObj\n self.leftChild = None\n self.rightChild = None\n\n def insertLeft(self,newNode):\n if self.leftChild == None:\n self.leftChild = BinaryTree(newNode)\n else:\n t = BinaryTree(newNode)\n t.left = self.leftChild\n self.leftChild = t\n \n def insertRight(self,newNode):\n if self.rightChild == None:\n self.rightChild = BinaryTree(newNode)\n else:\n t = BinaryTree(newNode)\n t.right = self.rightChild\n self.rightChild = t\n\n def isLeaf(self):\n return ((not self.leftChild) and (not self.rightChild))\n\n def getRightChild(self):\n return self.rightChild\n\n def getLeftChild(self):\n return self.leftChild\n\n def setRootVal(self,obj):\n self.key = obj\n\n def getRootVal(self,):\n return self.key\n\n def inorder(self):\n if self.leftChild:\n self.leftChild.inorder()\n print(self.key)\n if self.rightChild:\n self.rightChild.inorder()\n\n def postorder(self):\n if self.leftChild:\n self.leftChild.postorder()\n if self.rightChild:\n self.rightChild.postorder()\n print(self.key)\n\n\n def preorder(self):\n print(self.key)\n if self.leftChild:\n self.leftChild.preorder()\n if self.rightChild:\n self.rightChild.preorder()\n\n def printexp(self):\n if self.leftChild:\n print('(')\n self.leftChild.printexp()\n print(self.key)\n if self.rightChild:\n self.rightChild.printexp()\n print(')')\n\n def postordereval(self):\n opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n res1 = None\n res2 = None\n if self.leftChild:\n res1 = self.leftChild.postordereval() #// \\label{peleft}\n if self.rightChild:\n res2 = self.rightChild.postordereval() #// \\label{peright}\n if res1 and res2:\n return opers[self.key](res1,res2) #// \\label{peeval}\n else:\n return self.key\n\ndef inorder(tree):\n if tree != None:\n inorder(tree.getLeftChild())\n print(tree.getRootVal())\n inorder(tree.getRightChild())\n\ndef printexp(tree):\n if tree.leftChild:\n print('(')\n printexp(tree.getLeftChild())\n print(tree.getRootVal())\n if tree.rightChild:\n printexp(tree.getRightChild())\n print(')') \n\ndef printexp(tree):\n sVal = \"\"\n if tree:\n sVal = '(' + printexp(tree.getLeftChild())\n sVal = sVal + str(tree.getRootVal())\n sVal = sVal + printexp(tree.getRightChild()) + ')'\n return sVal\n\ndef postordereval(tree):\n opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}\n res1 = None\n res2 = None\n if tree:\n res1 = postordereval(tree.getLeftChild()) #// \\label{peleft}\n res2 = postordereval(tree.getRightChild()) #// \\label{peright}\n if res1 and res2:\n return opers[tree.getRootVal()](res1,res2) #// \\label{peeval}\n else:\n return tree.getRootVal()\n\ndef height(tree):\n if tree == None:\n return -1\n else:\n return 1 + max(height(tree.leftChild),height(tree.rightChild))\n\n# t = BinaryTree(7)\n# t.insertLeft(3)\n# t.insertRight(9)\n# inorder(t)\n# import operator\n# x = BinaryTree('*')\n# x.insertLeft('+')\n# l = x.getLeftChild()\n# l.insertLeft(4)\n# l.insertRight(5)\n# x.insertRight(7)\n# print(printexp(x))\n# print(postordereval(x))\n# print(height(x))\n", "src/lib/pythonds/trees/bst.py": "#!/bin/env python3.1\n# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005, 2010\n# \n\nclass BinarySearchTree:\n '''\n Author: Brad Miller\n Date: 1/15/2005\n Description: Imlement a binary search tree with the following interface\n functions: \n __contains__(y) <==> y in x\n __getitem__(y) <==> x[y]\n __init__()\n __len__() <==> len(x)\n __setitem__(k,v) <==> x[k] = v\n clear()\n get(k)\n items() \n keys() \n values()\n put(k,v)\n in\n del <==> \n '''\n\n def __init__(self):\n self.root = None\n self.size = 0\n \n def put(self,key,val):\n if self.root:\n self._put(key,val,self.root)\n else:\n self.root = TreeNode(key,val)\n self.size = self.size + 1\n\n def _put(self,key,val,currentNode):\n if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key,val,currentNode.leftChild)\n else:\n currentNode.leftChild = TreeNode(key,val,parent=currentNode)\n else:\n if currentNode.hasRightChild():\n self._put(key,val,currentNode.rightChild)\n else:\n currentNode.rightChild = TreeNode(key,val,parent=currentNode)\n \n def __setitem__(self,k,v):\n self.put(k,v)\n\n def get(self,key):\n if self.root:\n res = self._get(key,self.root)\n if res:\n return res.payload\n else:\n return None\n else:\n return None\n \n def _get(self,key,currentNode):\n if not currentNode:\n return None\n elif currentNode.key == key:\n return currentNode\n elif key < currentNode.key:\n return self._get(key,currentNode.leftChild)\n else:\n return self._get(key,currentNode.rightChild)\n \n \n def __getitem__(self,key):\n res = self.get(key)\n if res:\n return res\n else:\n raise KeyError('Error, key not in tree')\n \n\n def __contains__(self,key):\n if self._get(key,self.root):\n return True\n else:\n return False\n \n def length(self):\n return self.size\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self.root.__iter__()\n \n def delete(self,key):\n if self.size > 1:\n nodeToRemove = self._get(key,self.root)\n if nodeToRemove:\n self.remove(nodeToRemove)\n self.size = self.size-1\n else:\n raise KeyError('Error, key not in tree')\n elif self.size == 1 and self.root.key == key:\n self.root = None\n self.size = self.size - 1\n else:\n raise KeyError('Error, key not in tree')\n\n def __delitem__(self,key):\n self.delete(key)\n \n def remove(self,currentNode):\n if currentNode.isLeaf(): #leaf\n if currentNode == currentNode.parent.leftChild:\n currentNode.parent.leftChild = None\n else:\n currentNode.parent.rightChild = None\n elif currentNode.hasBothChildren(): #interior\n succ = currentNode.findSuccessor()\n succ.spliceOut()\n currentNode.key = succ.key\n currentNode.payload = succ.payload\n else: # this node has one child\n if currentNode.hasLeftChild():\n if currentNode.isLeftChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.leftChild\n elif currentNode.isRightChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.leftChild\n else:\n currentNode.replaceNodeData(currentNode.leftChild.key,\n currentNode.leftChild.payload,\n currentNode.leftChild.leftChild,\n currentNode.leftChild.rightChild)\n else:\n if currentNode.isLeftChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.rightChild\n elif currentNode.isRightChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.rightChild\n else:\n currentNode.replaceNodeData(currentNode.rightChild.key,\n currentNode.rightChild.payload,\n currentNode.rightChild.leftChild,\n currentNode.rightChild.rightChild)\n\n def inorder(self):\n self._inorder(self.root)\n\n def _inorder(self,tree):\n if tree != None:\n self._inorder(tree.leftChild)\n print(tree.key)\n self._inorder(tree.rightChild)\n\n def postorder(self):\n self._postorder(self.root)\n\n def _postorder(self, tree):\n if tree:\n self._postorder(tree.rightChild)\n self._postorder(tree.leftChild)\n print(tree.key) \n\n def preorder(self):\n self._preorder(self,self.root)\n\n def _preorder(self,tree):\n if tree:\n print(tree.key) \n self._preorder(tree.leftChild)\n self._preorder(tree.rightChild)\n\n \nclass TreeNode:\n def __init__(self,key,val,left=None,right=None,parent=None):\n self.key = key\n self.payload = val\n self.leftChild = left\n self.rightChild = right\n self.parent = parent\n self.balanceFactor = 0\n \n def hasLeftChild(self):\n return self.leftChild\n\n def hasRightChild(self):\n return self.rightChild\n \n def isLeftChild(self):\n return self.parent and self.parent.leftChild == self\n\n def isRightChild(self):\n return self.parent and self.parent.rightChild == self\n\n def isRoot(self):\n return not self.parent\n\n def isLeaf(self):\n return not (self.rightChild or self.leftChild)\n\n def hasAnyChildren(self):\n return self.rightChild or self.leftChild\n\n def hasBothChildren(self):\n return self.rightChild and self.leftChild\n \n def replaceNodeData(self,key,value,lc,rc):\n self.key = key\n self.payload = value\n self.leftChild = lc\n self.rightChild = rc\n if self.hasLeftChild():\n self.leftChild.parent = self\n if self.hasRightChild():\n self.rightChild.parent = self\n \n def findSuccessor(self):\n succ = None\n if self.hasRightChild():\n succ = self.rightChild.findMin()\n else:\n if self.parent:\n if self.isLeftChild():\n succ = self.parent\n else:\n self.parent.rightChild = None\n succ = self.parent.findSuccessor()\n self.parent.rightChild = self\n return succ\n\n\n def spliceOut(self):\n if self.isLeaf():\n if self.isLeftChild():\n self.parent.leftChild = None\n else:\n self.parent.rightChild = None\n elif self.hasAnyChildren():\n if self.hasLeftChild():\n if self.isLeftChild():\n self.parent.leftChild = self.leftChild\n else:\n self.parent.rightChild = self.leftChild\n self.leftChild.parent = self.parent\n else:\n if self.isLeftChild():\n self.parent.leftChild = self.rightChild\n else:\n self.parent.rightChild = self.rightChild\n self.rightChild.parent = self.parent\n\n def findMin(self):\n current = self\n while current.hasLeftChild():\n current = current.leftChild\n return current\n\n def __iter__(self):\n \"\"\"The standard inorder traversal of a binary tree.\"\"\"\n if self:\n if self.hasLeftChild():\n for elem in self.leftChild:\n yield elem\n yield self.key\n if self.hasRightChild():\n for elem in self.rightChild:\n yield elem\n\n \n", "src/lib/pythonds/trees/__init__.py": "\n# from .binaryTree import BinaryTree\n# from .balance import AVLTree\n# from .bst import BinarySearchTree\n# from .binheap import BinHeap\n\n\n", "src/lib/pythonds/trees/binheap.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n\n# this heap takes key value pairs, we will assume that the keys are integers\nclass BinHeap:\n def __init__(self):\n self.heapList = [0]\n self.currentSize = 0\n\n\n def buildHeap(self,alist):\n i = len(alist) // 2\n self.currentSize = len(alist)\n self.heapList = [0] + alist[:]\n print(len(self.heapList), i)\n while (i > 0):\n print(self.heapList, i)\n self.percDown(i)\n i = i - 1\n print(self.heapList,i)\n \n def percDown(self,i):\n while (i * 2) <= self.currentSize:\n mc = self.minChild(i)\n if self.heapList[i] > self.heapList[mc]:\n tmp = self.heapList[i]\n self.heapList[i] = self.heapList[mc]\n self.heapList[mc] = tmp\n i = mc\n \n def minChild(self,i):\n if i * 2 + 1 > self.currentSize:\n return i * 2\n else:\n if self.heapList[i * 2] < self.heapList[i * 2 + 1]:\n return i * 2\n else:\n return i * 2 + 1\n\n def percUp(self,i):\n while i // 2 > 0:\n if self.heapList[i] < self.heapList[i//2]:\n tmp = self.heapList[i // 2]\n self.heapList[i // 2] = self.heapList[i]\n self.heapList[i] = tmp\n i = i // 2\n \n def insert(self,k):\n self.heapList.append(k)\n self.currentSize = self.currentSize + 1\n self.percUp(self.currentSize)\n\n def delMin(self):\n retval = self.heapList[1]\n self.heapList[1] = self.heapList[self.currentSize]\n self.currentSize = self.currentSize - 1\n self.heapList.pop()\n self.percDown(1)\n return retval\n \n def isEmpty(self):\n if currentSize == 0:\n return True\n else:\n return False\n", "src/lib/pythonds/trees/balance.py": "#!/bin/env python3.1\n# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005, 2010\n# \n\nfrom .bst import BinarySearchTree, TreeNode\n\nclass AVLTree(BinarySearchTree):\n '''\n Author: Brad Miller\n Date: 1/15/2005\n Description: Imlement a binary search tree with the following interface\n functions: \n __contains__(y) <==> y in x\n __getitem__(y) <==> x[y]\n __init__()\n __len__() <==> len(x)\n __setitem__(k,v) <==> x[k] = v\n clear()\n get(k)\n has_key(k)\n items() \n keys() \n values()\n put(k,v)\n '''\n\n\n def _put(self,key,val,currentNode):\n if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key,val,currentNode.leftChild)\n else:\n currentNode.leftChild = TreeNode(key,val,parent=currentNode)\n self.updateBalance(currentNode.leftChild)\n else:\n if currentNode.hasRightChild():\n self._put(key,val,currentNode.rightChild)\n else:\n currentNode.rightChild = TreeNode(key,val,parent=currentNode)\n self.updateBalance(currentNode.rightChild) \n\n def updateBalance(self,node):\n if node.balanceFactor > 1 or node.balanceFactor < -1:\n self.rebalance(node)\n return\n if node.parent != None:\n if node.isLeftChild():\n node.parent.balanceFactor += 1\n elif node.isRightChild():\n node.parent.balanceFactor -= 1\n\n if node.parent.balanceFactor != 0:\n self.updateBalance(node.parent)\n\n def rebalance(self,node):\n if node.balanceFactor < 0:\n if node.rightChild.balanceFactor > 0:\n # Do an LR Rotation\n self.rotateRight(node.rightChild)\n self.rotateLeft(node)\n else:\n # single left\n self.rotateLeft(node)\n elif node.balanceFactor > 0:\n if node.leftChild.balanceFactor < 0:\n # Do an RL Rotation\n self.rotateLeft(node.leftChild)\n self.rotateRight(node)\n else:\n # single right\n self.rotateRight(node)\n\n def rotateLeft(self,rotRoot):\n newRoot = rotRoot.rightChild\n rotRoot.rightChild = newRoot.leftChild\n if newRoot.leftChild != None:\n newRoot.leftChild.parent = rotRoot\n newRoot.parent = rotRoot.parent\n if rotRoot.isRoot():\n self.root = newRoot\n else:\n if rotRoot.isLeftChild():\n rotRoot.parent.leftChild = newRoot\n else:\n rotRoot.parent.rightChild = newRoot\n newRoot.leftChild = rotRoot\n rotRoot.parent = newRoot\n rotRoot.balanceFactor = rotRoot.balanceFactor + 1 - min(newRoot.balanceFactor, 0)\n newRoot.balanceFactor = newRoot.balanceFactor + 1 + max(rotRoot.balanceFactor, 0)\n\n\n def rotateRight(self,rotRoot):\n newRoot = rotRoot.leftChild\n rotRoot.leftChild = newRoot.rightChild\n if newRoot.rightChild != None:\n newRoot.rightChild.parent = rotRoot\n newRoot.parent = rotRoot.parent\n if rotRoot.isRoot():\n self.root = newRoot\n else:\n if rotRoot.isRightChild():\n rotRoot.parent.rightChild = newRoot\n else:\n rotRoot.parent.leftChild = newRoot\n newRoot.rightChild = rotRoot\n rotRoot.parent = newRoot\n rotRoot.balanceFactor = rotRoot.balanceFactor - 1 - max(newRoot.balanceFactor, 0)\n newRoot.balanceFactor = newRoot.balanceFactor - 1 + min(rotRoot.balanceFactor, 0)\n \n", "src/lib/pythonds/basic/queue.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#queue.py\n\nclass Queue:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0,item)\n\n def dequeue(self):\n return self.items.pop()\n\n def size(self):\n return len(self.items)\n", "src/lib/pythonds/basic/deque.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#deque.py\n\n\nclass Deque:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def addFront(self, item):\n self.items.append(item)\n\n def addRear(self, item):\n self.items.insert(0,item)\n\n def removeFront(self):\n return self.items.pop()\n\n def removeRear(self):\n return self.items.pop(0)\n\n def size(self):\n return len(self.items)\n", "src/lib/pythonds/basic/__init__.py": "\n#__all__ = [\"stack\"]\n\n\n#from .stack import Stack\n#from .queue import Queue\n\n\n\n", "src/lib/pythonds/basic/stack.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \n#stack.py\n\nclass Stack:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[len(self.items)-1]\n\n def size(self):\n return len(self.items)\n\n", "src/lib/pythonds/graphs/adjGraph.py": "#\n# adjGraph\n#\n# Created by Brad Miller on 2005-02-24.\n# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.\n#\n\nimport sys\nimport os\nimport unittest\n\nclass Graph:\n def __init__(self):\n self.vertices = {}\n self.numVertices = 0\n \n def addVertex(self,key):\n self.numVertices = self.numVertices + 1\n newVertex = Vertex(key)\n self.vertices[key] = newVertex\n return newVertex\n \n def getVertex(self,n):\n if n in self.vertices:\n return self.vertices[n]\n else:\n return None\n\n def __contains__(self,n):\n return n in self.vertices\n \n def addEdge(self,f,t,cost=0):\n if f not in self.vertices:\n nv = self.addVertex(f)\n if t not in self.vertices:\n nv = self.addVertex(t)\n self.vertices[f].addNeighbor(self.vertices[t],cost)\n \n def getVertices(self):\n return list(self.vertices.keys())\n \n def __iter__(self):\n return iter(self.vertices.values())\n \nclass Vertex:\n def __init__(self,num):\n self.id = num\n self.connectedTo = {}\n self.color = 'white'\n self.dist = sys.maxsize\n self.pred = None\n self.disc = 0\n self.fin = 0\n\n # def __lt__(self,o):\n # return self.id < o.id\n \n def addNeighbor(self,nbr,weight=0):\n self.connectedTo[nbr] = weight\n \n def setColor(self,color):\n self.color = color\n \n def setDistance(self,d):\n self.dist = d\n\n def setPred(self,p):\n self.pred = p\n\n def setDiscovery(self,dtime):\n self.disc = dtime\n \n def setFinish(self,ftime):\n self.fin = ftime\n \n def getFinish(self):\n return self.fin\n \n def getDiscovery(self):\n return self.disc\n \n def getPred(self):\n return self.pred\n \n def getDistance(self):\n return self.dist\n \n def getColor(self):\n return self.color\n \n def getConnections(self):\n return self.connectedTo.keys()\n \n def getWeight(self,nbr):\n return self.connectedTo[nbr]\n \n def __str__(self):\n return str(self.id) + \":color \" + self.color + \":disc \" + str(self.disc) + \":fin \" + str(self.fin) + \":dist \" + str(self.dist) + \":pred \\n\\t[\" + str(self.pred)+ \"]\\n\"\n \n def getId(self):\n return self.id\n\nclass adjGraphTests(unittest.TestCase):\n def setUp(self):\n self.tGraph = Graph()\n \n def testMakeGraph(self):\n gFile = open(\"test.dat\")\n for line in gFile:\n fVertex, tVertex = line.split('|')\n fVertex = int(fVertex)\n tVertex = int(tVertex)\n self.tGraph.addEdge(fVertex,tVertex)\n for i in self.tGraph:\n adj = i.getAdj()\n for k in adj:\n print(i, k)\n\n \nif __name__ == '__main__':\n unittest.main()\n \n", "src/lib/pythonds/graphs/__init__.py": "\n\nfrom .adjGraph import Graph\nfrom .adjGraph import Vertex\nfrom .priorityQueue import PriorityQueue\n", "src/lib/pythonds/graphs/priorityQueue.py": "# Bradley N. Miller, David L. Ranum\n# Introduction to Data Structures and Algorithms in Python\n# Copyright 2005\n# \nimport unittest\n\n# this implementation of binary heap takes key value pairs,\n# we will assume that the keys are all comparable\n\nclass PriorityQueue:\n def __init__(self):\n self.heapArray = [(0,0)]\n self.currentSize = 0\n\n def buildHeap(self,alist):\n self.currentSize = len(alist)\n self.heapArray = [(0,0)]\n for i in alist:\n self.heapArray.append(i)\n i = len(alist) // 2 \n while (i > 0):\n self.percDown(i)\n i = i - 1\n \n def percDown(self,i):\n while (i * 2) <= self.currentSize:\n mc = self.minChild(i)\n if self.heapArray[i][0] > self.heapArray[mc][0]:\n tmp = self.heapArray[i]\n self.heapArray[i] = self.heapArray[mc]\n self.heapArray[mc] = tmp\n i = mc\n \n def minChild(self,i):\n if i*2 > self.currentSize:\n return -1\n else:\n if i*2 + 1 > self.currentSize:\n return i*2\n else:\n if self.heapArray[i*2][0] < self.heapArray[i*2+1][0]:\n return i*2\n else:\n return i*2+1\n\n def percUp(self,i):\n while i // 2 > 0:\n if self.heapArray[i][0] < self.heapArray[i//2][0]:\n tmp = self.heapArray[i//2]\n self.heapArray[i//2] = self.heapArray[i]\n self.heapArray[i] = tmp\n i = i//2\n \n def add(self,k):\n self.heapArray.append(k)\n self.currentSize = self.currentSize + 1\n self.percUp(self.currentSize)\n\n def delMin(self):\n retval = self.heapArray[1][1]\n self.heapArray[1] = self.heapArray[self.currentSize]\n self.currentSize = self.currentSize - 1\n self.heapArray.pop()\n self.percDown(1)\n return retval\n \n def isEmpty(self):\n if self.currentSize == 0:\n return True\n else:\n return False\n\n def decreaseKey(self,val,amt):\n # this is a little wierd, but we need to find the heap thing to decrease by\n # looking at its value\n done = False\n i = 1\n myKey = 0\n while not done and i <= self.currentSize:\n if self.heapArray[i][1] == val:\n done = True\n myKey = i\n else:\n i = i + 1\n if myKey > 0:\n self.heapArray[myKey] = (amt,self.heapArray[myKey][1])\n self.percUp(myKey)\n \n def __contains__(self,vtx):\n for pair in self.heapArray:\n if pair[1] == vtx:\n return True\n return False\n \nclass TestBinHeap(unittest.TestCase):\n def setUp(self):\n self.theHeap = PriorityQueue()\n self.theHeap.add((2,'x'))\n self.theHeap.add((3,'y'))\n self.theHeap.add((5,'z'))\n self.theHeap.add((6,'a'))\n self.theHeap.add((4,'d'))\n\n\n def testInsert(self):\n assert self.theHeap.currentSize == 5\n\n def testDelmin(self):\n assert self.theHeap.delMin() == 'x'\n assert self.theHeap.delMin() == 'y'\n \n def testDecKey(self):\n self.theHeap.decreaseKey('d',1)\n assert self.theHeap.delMin() == 'd'\n \nif __name__ == '__main__':\n unittest.main()\n", "src/lib/parking/__init__.js": "var $builtinmodule = function(name)\n{\n var WEEKDAYS = [\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"];\n var FULL_DAYS = {\n \"mon\": \"Monday\", \"tue\": \"Tuesday\", \"wed\": \"Wednesday\",\n \"thu\": \"Thursday\", \"fri\": \"Friday\", \"sat\": \"Saturday\",\n \"sun\": \"Sunday\"\n }\n \n var convert_day = function(day) {\n return WEEKDAYS.indexOf(day.name.v);\n }\n var convert_day_string = function(day) {\n return WEEKDAYS.indexOf(day.v.toLowerCase().slice(0, 3));\n }\n var convert_time = function(hour, minute, meridian) {\n return hour*60 + minute + (meridian.toLowerCase() == \"pm\" ? 12*60 : 0);\n }\n \n var mod = {};\n \n var time = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, hour, minute, meridian) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 4, 4);\n Sk.builtin.pyCheckType(\"hour\", \"int\", Sk.builtin.checkInt(hour));\n Sk.builtin.pyCheckType(\"minute\", \"int\", Sk.builtin.checkInt(minute));\n Sk.builtin.pyCheckType(\"meridian\", \"int\", Sk.builtin.checkString(meridian));\n self.hour = hour;\n self.minute = minute;\n self.meridian = meridian;\n self.meridian.v = self.meridian.v.toLowerCase();\n });\n $loc.__str__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<'+(self.hour.v || 12) +':'+\n (self.minute.v < 10 ? '0'+self.minute.v : self.minute.v)+\n self.meridian.v+'>');\n });\n $loc.__repr__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<'+(self.hour.v || 12)+':'+\n (self.minute.v < 10 ? '0'+self.minute.v : self.minute.v)+\n self.meridian.v+'>');\n });\n var comparison = function (operation, self, other) {\n if (Sk.builtin.isinstance(other, mod.Time).v) {\n if (operation(convert_time(self.hour.v % 12, self.minute.v, self.meridian.v), \n convert_time(other.hour.v % 12, other.minute.v, other.meridian.v))) {\n return Sk.ffi.remapToPy(true);\n } else {\n return Sk.ffi.remapToPy(false);\n }\n } else {\n return Sk.ffi.remapToPy(false);\n }\n }\n $loc.__eq__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l==r}, self, other);\n })\n \n $loc.__ne__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n if (!Sk.builtin.isinstance(other, mod.Time).v) {\n return Sk.builtin.bool.true$;\n }\n return comparison(function(l,r) {return l!=r}, self, other);\n });\n \n $loc.__lt__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l < r}, self, other);\n });\n \n $loc.__gt__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l > r}, self, other);\n });\n \n $loc.__le__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l <= r}, self, other);\n });\n \n $loc.__ge__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l >= r}, self, other);\n });\n }\n \n var day = function($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, name) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n Sk.builtin.pyCheckType(\"name\", \"string\", Sk.builtin.checkString(name));\n self.name = name;\n self.name.v = self.name.v.toLowerCase().slice(0,3)\n });\n $loc.__str__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<'+FULL_DAYS[self.name.v]+'>');\n });\n $loc.__repr__ = new Sk.builtin.func(function (self) {\n return Sk.ffi.remapToPy('<'+FULL_DAYS[self.name.v]+'>');\n });\n var comparison = function (operation, self, other) {\n if (Sk.builtin.isinstance(other, mod.Day).v) {\n if (operation(convert_day(self), convert_day(other))) {\n return Sk.ffi.remapToPy(true);\n } else {\n return Sk.builtin.bool.false$;\n }\n } else {\n return Sk.builtin.bool.false$;\n }\n }\n $loc.__eq__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l==r}, self, other);\n })\n \n $loc.__ne__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n if (!Sk.builtin.isinstance(other, mod.Day).v) {\n return Sk.builtin.bool.true$;\n }\n return comparison(function(l,r) {return l!=r}, self, other);\n });\n \n $loc.__lt__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l < r}, self, other);\n });\n \n $loc.__gt__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l > r}, self, other);\n });\n \n $loc.__le__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l <= r}, self, other);\n });\n \n $loc.__ge__ = new Sk.builtin.func(function (self, other) {\n Sk.builtin.pyCheckArgs(\"__init__\", arguments, 2, 2);\n return comparison(function(l,r) {return l >= r}, self, other);\n });\n }\n \n mod.Day = Sk.misceval.buildClass(mod, day, 'Day', []);\n mod.Time = Sk.misceval.buildClass(mod, time, 'Time', []);\n \n mod._today = undefined;\n mod._hour = undefined;\n mod._minute = undefined;\n mod._meridian = undefined;\n \n mod.today = new Sk.builtin.func(function() {\n var t = ((new Date).getDay() + 6) % 7; // would be -1, but % is broken for negatives in JS\n t = Sk.today || mod._today || Sk.ffi.remapToPy(WEEKDAYS[t]);\n return Sk.misceval.callsim(mod.Day, t);\n });\n \n mod.now = new Sk.builtin.func(function() {\n var d = new Date();\n var hour = d.getHours() % 12,\n minute = d.getMinutes(),\n meridian = d.getHours() < 12 ? 'am' : 'pm';\n hour = Sk._hour || mod._hour || Sk.ffi.remapToPy(hour);\n minute = Sk._minute || mod._minute || Sk.ffi.remapToPy(minute);\n meridian = Sk._meridian || mod._meridian || Sk.ffi.remapToPy(meridian);\n return Sk.misceval.callsim(mod.Time, hour, minute, meridian);\n });\n \n mod.day_compare = new Sk.builtin.func(function(comparison, value, day) {\n Sk.builtin.pyCheckArgs(\"day_compare\", arguments, 3, 3);\n Sk.builtin.pyCheckType(\"comparison\", \"string\", Sk.builtin.checkString(comparison));\n Sk.builtin.pyCheckType(\"value\", \"Day\", Sk.builtin.isinstance(value, mod.Day).v);\n Sk.builtin.pyCheckType(\"day\", \"string\", Sk.builtin.checkString(day));\n var day_n = convert_day_string(day),\n value_n = convert_day(value);\n switch (comparison.v) {\n case 'IS': return Sk.ffi.remapToPy(value_n == day_n);\n case \"BEFORE_EQUAL\": return Sk.ffi.remapToPy(value_n <= day_n);\n case \"AFTER_EQUAL\": return Sk.ffi.remapToPy(value_n >= day_n);\n case \"BEFORE\": return Sk.ffi.remapToPy(value_n < day_n);\n case \"AFTER\": return Sk.ffi.remapToPy(value_n > day_n);\n case \"IS_NOT\": return Sk.ffi.remapToPy(value_n != day_n);\n default: throw new Sk.builtins.ValueError(\"Unknown comparison\")\n }\n });\n \n mod.time_compare = new Sk.builtin.func(function(comparison, left, hour, minute, meridian) {\n Sk.builtin.pyCheckArgs(\"time_compare\", arguments, 5, 5);\n Sk.builtin.pyCheckType(\"comparison\", \"string\", Sk.builtin.checkString(comparison));\n Sk.builtin.pyCheckType(\"left\", \"Time\", Sk.builtin.isinstance(left, mod.Time).v);\n Sk.builtin.pyCheckType(\"hour\", \"int\", Sk.builtin.checkInt(hour));\n Sk.builtin.pyCheckType(\"minute\", \"int\", Sk.builtin.checkInt(hour));\n Sk.builtin.pyCheckType(\"meridian\", \"string\", Sk.builtin.checkString(meridian));\n var right_time = convert_time(hour.v % 12, minute.v, meridian.v),\n left_time = convert_time(left.hour.v % 12, left.minute.v, left.meridian.v);\n switch (comparison.v) {\n case 'IS': return Sk.ffi.remapToPy(left_time == right_time);\n case \"BEFORE_EQUAL\": return Sk.ffi.remapToPy(left_time <= right_time);\n case \"AFTER_EQUAL\": return Sk.ffi.remapToPy(left_time >= right_time);\n case \"BEFORE\": return Sk.ffi.remapToPy(left_time < right_time);\n case \"AFTER\": return Sk.ffi.remapToPy(left_time > right_time);\n case \"IS_NOT\": return Sk.ffi.remapToPy(left_time != right_time);\n default: throw new Sk.builtins.ValueError(\"Unknown comparison\")\n }\n });\n\n return mod;\n}", "src/lib/sound/__init__.js": "var $builtinmodule = function() {\n return {};\n};\n", "src/lib/sound/sound.js": "// Do not include this module directly as it has dependencies \nvar $builtinmodule = function() {\n var soundWrapper, mod, Sample;\n\n mod = {};\n\n // Dependency\n Sample = Sk.sysmodules.mp$subscript('sound.sample').$d.Sample;\n\n soundWrapper = {\n stopPlaying: new Sk.builtin.func(function (sound) {\n Sk.builtin.pyCheckArgs('stopPlaying', arguments, 1);\n sound._sound.stop();\n }),\n\n play : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('play', arguments, 1);\n sound._sound.play();\n }),\n\n blockingPlay : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('blockingPlay', arguments, 1);\n Sk.future(function (continueWith) {\n sound._sound.play(continueWith);\n });\n }),\n\n getDuration : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('getDuration', arguments, 1);\n return new Sk.builtin.float_(sound._sound.getDuration());\n }),\n\n getNumSamples : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('getNumSamples', arguments, 1);\n return new Sk.builtin.int_(sound._sound.getLength());\n }),\n\n getLength : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('getLength', arguments, 1);\n return new Sk.builtin.int_(sound._sound.getLength());\n }),\n\n getSamplingRate : new Sk.builtin.func(function(sound) {\n Sk.builtin.pyCheckArgs('getSamplingRate', arguments, 1);\n return new Sk.builtin.int_(sound._sound.getSamplingRate());\n }),\n\n setSampleValueAt : new Sk.builtin.func(function(sound, index, value) {\n var length;\n\n Sk.builtin.pyCheckArgs('setSampleValueAt', arguments, 3);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n if(!(value instanceof Sk.builtin.int_)) {\n throw new Sk.builtin.TypeError('Value must be an integer');\n }\n\n value = Sk.ffi.unwrapo(value);\n\n if(value < -32768) { value = -32768; }\n if(value > 32767) { value = 32767; }\n\n sound._sound.setLeftSample(Sk.ffi.unwrapo(index), pythy.Sound.map16BitIntToFloat(value));\n }),\n\n setLeftSample : new Sk.builtin.func(function(sound, index, value) {\n var length;\n\n Sk.builtin.pyCheckArgs('setLeftSample', arguments, 3);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n if(!(value instanceof Sk.builtin.int_)) {\n throw new Sk.builtin.TypeError('Value must be an integer');\n }\n\n value = Sk.ffi.unwrapo(value);\n\n if(value < -32768) { value = -32768; }\n if(value > 32767) { value = 32767; }\n\n sound._sound.setLeftSample(Sk.ffi.unwrapo(index), pythy.Sound.map16BitIntToFloat(value));\n }),\n\n setRightSample : new Sk.builtin.func(function(sound, index, value) {\n var length;\n\n Sk.builtin.pyCheckArgs('setRightSample', arguments, 3);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n if(!(value instanceof Sk.builtin.int_)) {\n throw new Sk.builtin.TypeError('Value must be an integer');\n }\n\n value = Sk.ffi.unwrapo(value);\n\n if(value < -32768) { value = -32768; }\n if(value > 32767) { value = 32767; }\n\n sound._sound.setRightSample(Sk.ffi.unwrapo(index), pythy.Sound.map16BitIntToFloat(value));\n }),\n\n getSampleValueAt : new Sk.builtin.func(function(sound, index) {\n var length;\n\n Sk.builtin.pyCheckArgs('getSampleValueAt', arguments, 2);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n return new Sk.builtin.int_(pythy.Sound.mapFloatTo16BitInt(sound._sound.getLeftSample(Sk.ffi.unwrapo(index))));\n }),\n\n getLeftSample : new Sk.builtin.func(function(sound, index) {\n var length;\n\n Sk.builtin.pyCheckArgs('getLeftSample', arguments, 2);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n return new Sk.builtin.int_(pythy.Sound.mapFloatTo16BitInt(sound._sound.getLeftSample(Sk.ffi.unwrapo(index))));\n }),\n\n getRightSample : new Sk.builtin.func(function(sound, index) {\n var length;\n\n Sk.builtin.pyCheckArgs('getRightSample', arguments, 2);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n return new Sk.builtin.int_(pythy.Sound.mapFloatTo16BitInt(sound._sound.getRightSample(Sk.ffi.unwrapo(index))));\n }),\n\n getSampleObjectAt : new Sk.builtin.func(function (sound, index) {\n var length;\n\n Sk.builtin.pyCheckArgs('getSampleObjectAt', arguments, 2);\n\n length = sound._sound.getLength();\n\n if(index < 0 || index >= length) {\n throw new Sk.builtin.ValueError('Index must have a value between 0 and ' + length);\n }\n\n return Sk.misceval.callsim(Sample, sound, index);\n }),\n\n getSamples : new Sk.builtin.func(function (sound) {\n var samples, len;\n \n Sk.builtin.pyCheckArgs('getSamples', arguments, 1);\n\n samples = [];\n len = sound._sound.getLength();\n\n for(var i = 0; i < len; i++) {\n samples.push(Sk.misceval.callsim(Sample, sound, Sk.builtin.int_(i)));\n }\n\n return new Sk.builtin.list(samples);\n })\n };\n\n mod.Sound = Sk.misceval.buildClass(mod, function ($gbl, $loc) {\n var onError;\n\n onError = function (continueWith) {\n return function (errorMsg) {\n if(errorMsg.indexOf('File') !== -1) {\n continueWith(new Sk.builtin.ValueError(errorMsg + '. Is the URL incorrect?'));\n } else {\n continueWith(new Sk.builtin.ValueError(errorMsg));\n }\n }\n };\n\n $loc.__init__ = new Sk.builtin.func(function (sound) {\n var arg0, res, arg1, arg2;\n\n Sk.builtin.pyCheckArgs('__init__', arguments, [2, 3]);\n\n arg0 = arguments[1];\n\n if(arg0 instanceof Sk.builtin.str) {\n arg0 = Sk.ffi.unwrapo(arg0); //url\n res = Sk.future(function (continueWith) {\n new window.pythy.Sound(continueWith, onError(continueWith), arg0);\n }); \n } else if(arg0.tp$name === 'Sound') {\n res = Sk.future(function (continueWith) {\n new window.pythy.Sound(continueWith, onError(continueWith), arg0._sound);\n });\n } else {\n arg1 = Sk.ffi.unwrapo(arguments[1]); //numSamples\n arg2 = Sk.ffi.unwrapo(arguments[2]); //samplingRate\n res = Sk.future(function (continueWith) {\n new window.pythy.Sound(continueWith, onError(continueWith), arg1, arg2);\n });\n }\n\n if(res instanceof window.pythy.Sound) {\n sound._sound = res;\n } else if(res) {\n throw res;\n }\n });\n\n $loc.__str__ = new Sk.builtin.func(function(sound) {\n var str;\n\n Sk.builtin.pyCheckArgs('__str__', arguments, 1);\n\n str = 'Sound, ';\n\n if(sound._sound.url) {\n str += 'File: ' + sound._sound.url + ', ';\n }\n\n return new Sk.builtin.str(str + 'Number of samples: ' + sound._sound.getLength());\n });\n\n $loc.__repr__ = new Sk.builtin.func(function(sound) {\n var str;\n\n Sk.builtin.pyCheckArgs('__repr__', arguments, 1);\n\n str = 'Sound, ';\n\n if(sound._sound.url) {\n str += 'File: ' + sound._sound.url + ', ';\n }\n\n return new Sk.builtin.str(str + 'Number of samples: ' + sound._sound.getLength());\n });\n\n $loc.writeToFile = new Sk.builtin.func(function(sound, path) {\n Sk.builtin.pyCheckArgs('writeToFile', arguments, 2);\n sound._sound.save(Sk.ffi.unwrapo(path));\n });\n\n $loc.duplicate = new Sk.builtin.func(function (sound) {\n Sk.builtin.pyCheckArgs('duplicate', arguments, 1);\n return Sk.misceval.callsim(mod.Sound, sound); \n });\n\n goog.object.extend($loc, soundWrapper);\n\n }, 'Sound', []);\n\n goog.object.extend(mod, soundWrapper);\n\n goog.object.extend(mod, {\n duplicateSound: new Sk.builtin.func(function (sound) {\n Sk.builtin.pyCheckArgs('duplicateSound', arguments, 1);\n return Sk.misceval.callsim(mod.Sound, sound); \n }),\n\n makeSound: new Sk.builtin.func(function (url) {\n Sk.builtin.pyCheckArgs('makeSound', arguments, 1);\n return Sk.misceval.callsim(mod.Sound, url);\n }),\n\n makeEmptySound: new Sk.builtin.func(function (numSamples, samplingRate) {\n Sk.builtin.pyCheckArgs('makeEmptySound', arguments, [1, 2]);\n return Sk.misceval.callsim(mod.Sound, numSamples, samplingRate);\n }),\n\n makeEmptySoundBySeconds: new Sk.builtin.func(function (seconds, samplingRate) {\n var numSamples;\n\n Sk.builtin.pyCheckArgs('makeEmptySoundBySeconds', arguments, [1, 2]);\n\n if(Sk.ffi.unwrapo(seconds) < 0) {\n throw new Sk.builtin.ValueError('Duration can not be negative');\n }\n numSamples = Sk.ffi.unwrapo(seconds) * (Sk.ffi.unwrapo(samplingRate) || window.pythy.Sound.SAMPLE_RATE);\n return Sk.misceval.callsim(mod.Sound, new Sk.builtin.int_(numSamples), samplingRate);\n }),\n\n openSoundTool: new Sk.builtin.func(function (sound) {\n Sk.builtin.pyCheckArgs('openSoundTool', arguments, 1);\n window.pythy.soundTool.start(sound._sound);\n }),\n\n writeSoundTo : new Sk.builtin.func(function(sound, path) {\n Sk.builtin.pyCheckArgs('writeSoundTo', arguments, 2);\n sound._sound.save(Sk.ffi.unwrapo(path));\n })\n });\n\n return mod;\n};\n", "src/lib/sound/sample.js": "var $builtinmodule = function() {\n var mod, sampleWrapper;\n\n mod = {};\n\n sampleWrapper = {\n getSound : new Sk.builtin.func(function (sample) {\n Sk.builtin.pyCheckArgs('getSound', arguments, 1);\n return sample._sound;\n }),\n\n getSampleValue : new Sk.builtin.func(function (sample) {\n Sk.builtin.pyCheckArgs('getSampleValue', arguments, 1);\n return new Sk.builtin.float_(sample._internalSound.getLeftSample(sample._index));\n }),\n\n setSampleValue : new Sk.builtin.func(function (sample, value) {\n Sk.builtin.pyCheckArgs('setSampleValue', arguments, 2);\n sample._internalSound.setLeftSample(sample._index, Sk.ffi.unwrapo(value));\n }),\n };\n\n mod.Sample = Sk.misceval.buildClass(mod, function ($gbl, $loc) {\n $loc.__init__ = new Sk.builtin.func(function (self, sound, index) {\n Sk.builtin.pyCheckArgs('__init__', arguments, 3);\n self._sound = sound;\n self._internalSound = sound._sound;\n self._index = Sk.ffi.unwrapo(index);\n });\n\n $loc.__str__ = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs('__str__', arguments, 1);\n return new Sk.builtin.str('Sample at ' + self._index + ' with value ' +\n self._internalSound.getLeftSample(self._index));\n });\n\n $loc.__repr__ = new Sk.builtin.func(function (self) {\n Sk.builtin.pyCheckArgs('__repr__', arguments, 1);\n return new Sk.builtin.str('Sample at ' + self._index + ' with value ' +\n self._internalSound.getLeftSample(self._index));\n });\n\n goog.object.extend($loc, sampleWrapper);\n }, 'Sample', []);\n\n goog.object.extend(mod, sampleWrapper);\n\n return mod;\n};\n", "src/lib/compiler/__init__.py": "raise NotImplementedError(\"compiler is not yet implemented in Skulpt\")\n", "src/lib/logging/__init__.py": "raise NotImplementedError(\"logging is not yet implemented in Skulpt\")\n", "src/lib/email/__init__.py": "raise NotImplementedError(\"email is not yet implemented in Skulpt\")\n", "src/lib/email/test/data/__init__.py": "raise NotImplementedError(\"data is not yet implemented in Skulpt\")\n", "src/lib/email/mime/__init__.py": "raise NotImplementedError(\"mime is not yet implemented in Skulpt\")\n", "src/lib/media/__init__.py": "# Order is important here\n\nfrom image.style import *\nfrom image.color import *\nfrom image.pixel import *\nfrom image.picture import *\nfrom image import *\n\nfrom sound import *\nfrom sound.sample import *\nfrom sound.sound import *\n"}}