\".encode('utf-8')\n pad = 1024 - len(data) + 1\n data = data.replace(b\"-a-\", b\"-\" + (b\"a\" * pad) + b\"-\")\n assert len(data) == 1024 # Sanity\n stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)\n assert 'utf-8' == stream.charEncoding[0].name\n\n\ndef test_parser_reparse():\n data = \"Caf\\u00E9\".encode('utf-8')\n pad = 10240 - len(data) + 1\n data = data.replace(b\"-a-\", b\"-\" + (b\"a\" * pad) + b\"-\")\n assert len(data) == 10240 # Sanity\n stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)\n assert 'windows-1252' == stream.charEncoding[0].name\n p = HTMLParser(namespaceHTMLElements=False)\n doc = p.parse(data, useChardet=False)\n assert 'utf-8' == p.documentEncoding\n assert doc.find(\".//title\").text == \"Caf\\u00E9\"\n\n\n@pytest.mark.parametrize(\"expected,data,kwargs\", [\n (\"utf-16le\", b\"\\xFF\\xFE\", {\"override_encoding\": \"iso-8859-2\"}),\n (\"utf-16be\", b\"\\xFE\\xFF\", {\"override_encoding\": \"iso-8859-2\"}),\n (\"utf-8\", b\"\\xEF\\xBB\\xBF\", {\"override_encoding\": \"iso-8859-2\"}),\n (\"iso-8859-2\", b\"\", {\"override_encoding\": \"iso-8859-2\", \"transport_encoding\": \"iso-8859-3\"}),\n (\"iso-8859-2\", b\"\", {\"transport_encoding\": \"iso-8859-2\"}),\n (\"iso-8859-2\", b\"\", {\"same_origin_parent_encoding\": \"iso-8859-3\"}),\n (\"iso-8859-2\", b\"\", {\"same_origin_parent_encoding\": \"iso-8859-2\", \"likely_encoding\": \"iso-8859-3\"}),\n (\"iso-8859-2\", b\"\", {\"same_origin_parent_encoding\": \"utf-16\", \"likely_encoding\": \"iso-8859-2\"}),\n (\"iso-8859-2\", b\"\", {\"same_origin_parent_encoding\": \"utf-16be\", \"likely_encoding\": \"iso-8859-2\"}),\n (\"iso-8859-2\", b\"\", {\"same_origin_parent_encoding\": \"utf-16le\", \"likely_encoding\": \"iso-8859-2\"}),\n (\"iso-8859-2\", b\"\", {\"likely_encoding\": \"iso-8859-2\", \"default_encoding\": \"iso-8859-3\"}),\n (\"iso-8859-2\", b\"\", {\"default_encoding\": \"iso-8859-2\"}),\n (\"windows-1252\", b\"\", {\"default_encoding\": \"totally-bogus-string\"}),\n (\"windows-1252\", b\"\", {}),\n])\ndef test_parser_args(expected, data, kwargs):\n stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False, **kwargs)\n assert expected == stream.charEncoding[0].name\n p = HTMLParser()\n p.parse(data, useChardet=False, **kwargs)\n assert expected == p.documentEncoding\n\n\n@pytest.mark.parametrize(\"kwargs\", [\n {\"override_encoding\": \"iso-8859-2\"},\n {\"override_encoding\": None},\n {\"transport_encoding\": \"iso-8859-2\"},\n {\"transport_encoding\": None},\n {\"same_origin_parent_encoding\": \"iso-8859-2\"},\n {\"same_origin_parent_encoding\": None},\n {\"likely_encoding\": \"iso-8859-2\"},\n {\"likely_encoding\": None},\n {\"default_encoding\": \"iso-8859-2\"},\n {\"default_encoding\": None},\n {\"foo_encoding\": \"iso-8859-2\"},\n {\"foo_encoding\": None},\n])\ndef test_parser_args_raises(kwargs):\n with pytest.raises(TypeError) as exc_info:\n p = HTMLParser()\n p.parse(\"\", useChardet=False, **kwargs)\n assert exc_info.value.args[0].startswith(\"Cannot set an encoding with a unicode input\")\n\n\ndef param_encoding():\n for filename in get_data_files(\"encoding\"):\n tests = _TestData(filename, b\"data\", encoding=None)\n for test in tests:\n yield test[b'data'], test[b'encoding']\n\n\n@pytest.mark.parametrize(\"data, encoding\", param_encoding())\ndef test_parser_encoding(data, encoding):\n p = HTMLParser()\n assert p.documentEncoding is None\n p.parse(data, useChardet=False)\n encoding = encoding.lower().decode(\"ascii\")\n\n assert encoding == p.documentEncoding, errorMessage(data, encoding, p.documentEncoding)\n\n\n@pytest.mark.parametrize(\"data, encoding\", param_encoding())\ndef test_prescan_encoding(data, encoding):\n stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)\n encoding = encoding.lower().decode(\"ascii\")\n\n # Very crude way to ignore irrelevant tests\n if len(data) > stream.numBytesMeta:\n return\n\n assert encoding == stream.charEncoding[0].name, errorMessage(data, encoding, stream.charEncoding[0].name)\n\n\n# pylint:disable=wrong-import-position\ntry:\n import chardet # noqa\nexcept ImportError:\n print(\"chardet not found, skipping chardet tests\")\nelse:\n def test_chardet():\n with open(os.path.join(test_dir, \"encoding\", \"chardet\", \"test_big5.txt\"), \"rb\") as fp:\n encoding = _inputstream.HTMLInputStream(fp.read()).charEncoding\n assert encoding[0].name == \"big5\"\n# pylint:enable=wrong-import-position\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":2522060990303054000,"string":"2,522,060,990,303,054,000"},"line_mean":{"kind":"number","value":40.1965811966,"string":"40.196581"},"line_max":{"kind":"number","value":109,"string":"109"},"alpha_frac":{"kind":"number","value":0.6485477178,"string":"0.648548"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475922,"cells":{"repo_name":{"kind":"string","value":"ichuang/sympy"},"path":{"kind":"string","value":"sympy/plotting/plot_modes.py"},"copies":{"kind":"string","value":"3"},"size":{"kind":"string","value":"5242"},"content":{"kind":"string","value":"from plot_curve import PlotCurve\nfrom plot_surface import PlotSurface\n\nfrom sympy import pi, lambdify\nfrom sympy.functions import sin, cos\nfrom math import sin as p_sin\nfrom math import cos as p_cos\n\ndef float_vec3(f):\n def inner(*args):\n v = f(*args)\n return float(v[0]), float(v[1]), float(v[2])\n return inner\n\nclass Cartesian2D(PlotCurve):\n i_vars, d_vars = 'x', 'y'\n intervals = [[-5, 5, 100]]\n aliases = ['cartesian']\n is_default = True\n\n def _get_sympy_evaluator(self):\n fy = self.d_vars[0]\n x = self.t_interval.v\n @float_vec3\n def e(_x):\n return (_x, fy.subs(x, _x), 0.0)\n return e\n\n def _get_lambda_evaluator(self):\n fy = self.d_vars[0]\n x = self.t_interval.v\n return lambdify([x], [x, fy, 0.0])\n\nclass Cartesian3D(PlotSurface):\n i_vars, d_vars = 'xy', 'z'\n intervals = [[-1, 1, 40], [-1, 1, 40]]\n aliases = ['cartesian', 'monge']\n is_default = True\n\n def _get_sympy_evaluator(self):\n fz = self.d_vars[0]\n x = self.u_interval.v\n y = self.v_interval.v\n @float_vec3\n def e(_x, _y):\n return (_x, _y, fz.subs(x, _x).subs(y, _y))\n return e\n\n def _get_lambda_evaluator(self):\n fz = self.d_vars[0]\n x = self.u_interval.v\n y = self.v_interval.v\n return lambdify([x, y], [x, y, fz])\n\nclass ParametricCurve2D(PlotCurve):\n i_vars, d_vars = 't', 'xy'\n intervals = [[0, 2*pi, 100]]\n aliases = ['parametric']\n is_default = True\n\n def _get_sympy_evaluator(self):\n fx, fy = self.d_vars\n t = self.t_interval.v\n @float_vec3\n def e(_t):\n return (fx.subs(t, _t), fy.subs(t, _t), 0.0)\n return e\n\n def _get_lambda_evaluator(self):\n fx, fy = self.d_vars\n t = self.t_interval.v\n return lambdify([t], [fx, fy, 0.0])\n\nclass ParametricCurve3D(PlotCurve):\n i_vars, d_vars = 't', 'xyz'\n intervals = [[0, 2*pi, 100]]\n aliases = ['parametric']\n is_default = True\n\n def _get_sympy_evaluator(self):\n fx, fy, fz = self.d_vars\n t = self.t_interval.v\n @float_vec3\n def e(_t):\n return (fx.subs(t, _t), fy.subs(t, _t), fz.subs(t, _t))\n return e\n\n def _get_lambda_evaluator(self):\n fx, fy, fz = self.d_vars\n t = self.t_interval.v\n return lambdify([t], [fx, fy, fz])\n\nclass ParametricSurface(PlotSurface):\n i_vars, d_vars = 'uv', 'xyz'\n intervals = [[-1, 1, 40], [-1, 1, 40]]\n aliases = ['parametric']\n is_default = True\n\n def _get_sympy_evaluator(self):\n fx, fy, fz = self.d_vars\n u = self.u_interval.v\n v = self.v_interval.v\n @float_vec3\n def e(_u, _v):\n return (fx.subs(u, _u).subs(v, _v),\n fy.subs(u, _u).subs(v, _v),\n fz.subs(u, _u).subs(v, _v))\n return e\n\n def _get_lambda_evaluator(self):\n fx, fy, fz = self.d_vars\n u = self.u_interval.v\n v = self.v_interval.v\n return lambdify([u, v], [fx, fy, fz])\n\nclass Polar(PlotCurve):\n i_vars, d_vars = 't', 'r'\n intervals = [[0, 2*pi, 100]]\n aliases = ['polar']\n is_default = False\n\n def _get_sympy_evaluator(self):\n fr = self.d_vars[0]\n t = self.t_interval.v\n def e(_t):\n _r = float(fr.subs(t, _t))\n return (_r*p_cos(_t), _r*p_sin(_t), 0.0)\n return e\n\n def _get_lambda_evaluator(self):\n fr = self.d_vars[0]\n t = self.t_interval.v\n fx, fy = fr*cos(t), fr*sin(t)\n return lambdify([t], [fx, fy, 0.0])\n\nclass Cylindrical(PlotSurface):\n i_vars, d_vars = 'th', 'r'\n intervals = [[0, 2*pi, 40], [-1, 1, 20]]\n aliases = ['cylindrical', 'polar']\n is_default = False\n\n def _get_sympy_evaluator(self):\n fr = self.d_vars[0]\n t = self.u_interval.v\n h = self.v_interval.v\n def e(_t, _h):\n _r = float(fr.subs(t, _t).subs(h, _h))\n return (_r*p_cos(_t), _r*p_sin(_t), _h)\n return e\n\n def _get_lambda_evaluator(self):\n fr = self.d_vars[0]\n t = self.u_interval.v\n h = self.v_interval.v\n fx, fy = fr*cos(t), fr*sin(t)\n return lambdify([t, h], [fx, fy, h])\n\nclass Spherical(PlotSurface):\n i_vars, d_vars = 'tp', 'r'\n intervals = [[0, 2*pi, 40], [0, pi, 20]]\n aliases = ['spherical']\n is_default = False\n\n def _get_sympy_evaluator(self):\n fr = self.d_vars[0]\n t = self.u_interval.v\n p = self.v_interval.v\n def e(_t, _p):\n _r = float(fr.subs(t, _t).subs(p, _p))\n return (_r*p_cos(_t)*p_sin(_p),\n _r*p_sin(_t)*p_sin(_p),\n _r*p_cos(_p))\n return e\n\n def _get_lambda_evaluator(self):\n fr = self.d_vars[0]\n t = self.u_interval.v\n p = self.v_interval.v\n fx = fr * cos(t) * sin(p)\n fy = fr * sin(t) * sin(p)\n fz = fr * cos(p)\n return lambdify([t, p], [fx, fy, fz])\n\nCartesian2D._register()\nCartesian3D._register()\nParametricCurve2D._register()\nParametricCurve3D._register()\nParametricSurface._register()\nPolar._register()\nCylindrical._register()\nSpherical._register()\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-1641263633310484200,"string":"-1,641,263,633,310,484,200"},"line_mean":{"kind":"number","value":26.445026178,"string":"26.445026"},"line_max":{"kind":"number","value":67,"string":"67"},"alpha_frac":{"kind":"number","value":0.5148798169,"string":"0.51488"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475923,"cells":{"repo_name":{"kind":"string","value":"AleCandido/Lab3.2"},"path":{"kind":"string","value":"Esercitazione15/passabanda.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4213"},"content":{"kind":"string","value":"import sys\nimport pylab\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import chisqprob\nimport numpy as np\nimport getpass\nusers={\"candi\": \"C:\\\\Users\\\\candi\\\\Documents\\\\GitHub\\\\Lab3.2\\\\\",\n\"silvanamorreale\":\"C:\\\\Users\\\\silvanamorreale\\\\Documents\\\\GitHub\\\\Lab3.2\\\\\" ,\n\"Studenti\": \"C:\\\\Users\\\\Studenti\\\\Desktop\\\\Lab3\\\\\",\n\"User\":\"C:\\\\Users\\\\User\\\\Documents\\\\GitHub\\\\Lab3.2\\\\\",\n\"andrea\": \"/home/andrea/Documenti/Da salvare 12-5-2017/Documenti/GitHub/Lab3.2/\",\n\"viviana\": \"C:\\\\Users\\\\viviana\\\\Documents\\\\GitHub\\\\Lab3.2\\\\\"\n}\n\ntry:\n user=getpass.getuser()\n path=users[user]\n print(\"buongiorno \", user, \"!!!\")\nexcept:\n raise Error(\"unknown user, please specify it and the path in the file Esercitazione*.py\")\n\n\nsys.path = sys.path + [path]\ndir= path + \"Esercitazione15/\"\n\nfrom BuzzLightyear import * \nfrom lab import *\nimport uncertainties\nimport uncertainties.unumpy\n###########################################################################\n\n\nprint(\"===========PASSABANDA==============\")\n\nprint(\"valori attesi...\")\n\ndef myres(r):\n return uncertainties.ufloat(r, mme(r, \"ohm\"))\n\nR2=myres(119.1)\nC1=10.78e-9\nC2=10.67e-9\nR1=myres(2.68e3)\nR3=myres(46.6e3)\n\nRp=R1*R2/(R1+R2)\nC=C1\nw0_exp=(1/(C*(Rp*R3)**0.5))#/(2*np.pi)\nf0_exp=(1/(C*(Rp*R3)**0.5))/(2*np.pi)\n\nQ_exp=0.5*(R3/Rp)**0.5\nDw_exp=w0_exp/Q_exp\nDf_exp=f0_exp/Q_exp\n\n\nR1p=myres(9.92e2) #questa resistenza è sbagliata... non so se è grave o meno, ma si spiega perchè la nostra amplificazione è minore...è compatibile con quanto ottenuto dal fit\nR2p=myres(33.2e3)\nR3p=myres(3.91e3)\n\ng00=1/(R1*C*Dw_exp)*(R2p/R1p+1)\n\nprint(\"f0_exp={} Q_exp={} g00={}\".format(f0_exp, Q_exp, g00))\n\n\npylab.figure(figsnum)\n\n\nfigsnum+=1\npylab.title(\"amplificazione passa-banda\")\npylab.xlabel(\"frequenza [Hz]\")\npylab.ylabel(\"A($f$)\")\n\n###############Acquisizione dati\n\ndir_grph=dir+\"grafici/\"\ndir = dir + \"data/\"\n\nfile=\"passabanda.txt\"\nf, vin, vout = loadtxt(dir+file,unpack=True)\nf=f*1e3\nDf=51/1e6*f\n\namp=vout/vin\ndvout=mme(vout, \"volt\", \"oscil\")\ndvin=mme(vin, \"volt\", \"oscil\")\ndamp=amp*((dvout/vout)**2+(dvin/vin)**2)**0.5\n\n\n\n##############Fit...\n\n#attenzione...A non è adimensionale...se passo dalle frequenze alle pulsazioni A dovrebbe scalare di 2*pi\n\ng=lambda w, A, Q, w0: A*w/((w**2-w0**2)**2+w**2*w0**2/Q)**0.5\np0=(185, 10, 6.1e3)\ndof=len(f)-3\npars, covs = curve_fit(g, f, amp,p0, damp, maxfev=10000)\nA, Q, w0=uncertainties.correlated_values(pars, covs)\n\n\n#############plot...\npylab.loglog()\npylab.errorbar(f, amp, damp,Df,fmt=\".\")\ndomain = pylab.logspace(math.log10(min(f)),math.log10(max(f)), 1000)\ngdomain = g(domain, *pars)\npylab.plot(domain, gdomain)\npylab.xlim(min(domain)*0.9,max(domain)*1.1)\nvint = pylab.vectorize(int)\npylab.xticks(vint((pylab.logspace(log10(min(domain)*0.9),log10(max(domain)*1.1), 5)//100)*100),vint((pylab.logspace(log10(min(domain)*0.9),log10(max(domain)*1.1), 5)//100)*100))\npylab.ylim(min(gdomain)*0.9, max(gdomain)*1.1)\npylab.yticks(vint((pylab.logspace(log10(min(gdomain)*0.9),log10(max(gdomain)*1.1), 5)//10)*10),vint((pylab.logspace(log10(min(gdomain)*0.9),log10(max(gdomain)*1.1), 5)//10)*10))\npylab.savefig(dir_grph+\"passabanda.pdf\")\n\n\n############output parametri...\n\nprint(\"A={} w0={} Q_true={}\".format(A, w0, Q**0.5))\n\nfor i, j in enumerate(pars):\n print(i, pars[i], covs[i, i]**0.5)\n\nchisq=np.sum((amp-g(f, *pars))**2/damp**2)\nprint(\"chisq=\", chisq, dof, chisqprob(chisq,dof))\n\nDw=w0/Q**0.5 #larghezza di banda (si chiama w, ma è una frequenza...)...\n\n\n#controllo sui parametri\nprint(\"controllo di essere davvero a -3dB\")\n\nprint(\"2**0.5 - g(w0, A, Q, w0)/g(w0+Dw/2, A, Q, w0) = \",sqrt(2)-g(w0, A, Q, w0)/g(w0+Dw/2, A, Q, w0))\n\nprint(\"2**0.5 - g(w0, A, Q, w0)/g(w0-Dw/2, A, Q, w0) = \",sqrt(2)-g(w0, A, Q, w0)/g(w0-Dw/2, A, Q, w0))\n\nA3=g(w0, A, Q, w0) #amplificazione di centrobanda (con errori...)\n\n#A, Q, w0=uncertainties.correlated_values(pars, covs)\nprint(\"guadagno centro banda=\", g(w0, A, Q, w0))\n\n\nprint(\"Risultati A={} Q={} w0={} Dw={}\".format(A, Q**0.5, w0, Dw))\n\nprint(\"Il Q value non è compatibile con quanto atteso...\")\n\n\n\ndom=np.linspace(min(f), max(f), 1000)\nintegrale=np.sum(g(dom, A, Q, w0)**2)*(max(f)-min(f))/1000/A3**2\nprint(\"-----------\", integrale, np.pi/2*Dw)\n\nDf_true=integrale\n\n\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-3721280279171289000,"string":"-3,721,280,279,171,289,000"},"line_mean":{"kind":"number","value":26.4836601307,"string":"26.48366"},"line_max":{"kind":"number","value":177,"string":"177"},"alpha_frac":{"kind":"number","value":0.633293698,"string":"0.633294"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475924,"cells":{"repo_name":{"kind":"string","value":"kmacinnis/sympy"},"path":{"kind":"string","value":"sympy/solvers/tests/test_inequalities.py"},"copies":{"kind":"string","value":"3"},"size":{"kind":"string","value":"11948"},"content":{"kind":"string","value":"\"\"\"Tests for tools for solving inequalities and systems of inequalities. \"\"\"\n\nfrom sympy import (And, Eq, FiniteSet, Ge, Gt, im, Interval, Le, Lt, Ne, oo,\n Or, Q, re, S, sin, sqrt, Union)\nfrom sympy.assumptions import assuming\nfrom sympy.abc import x, y\nfrom sympy.solvers.inequalities import (reduce_inequalities,\n reduce_rational_inequalities)\nfrom sympy.utilities.pytest import raises\n\ninf = oo.evalf()\n\n\ndef test_reduce_poly_inequalities_real_interval():\n with assuming(Q.real(x), Q.real(y)):\n assert reduce_rational_inequalities(\n [[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0)\n assert reduce_rational_inequalities(\n [[Le(x**2, 0)]], x, relational=False) == FiniteSet(0)\n assert reduce_rational_inequalities(\n [[Lt(x**2, 0)]], x, relational=False) == S.EmptySet\n assert reduce_rational_inequalities(\n [[Ge(x**2, 0)]], x, relational=False) == Interval(-oo, oo)\n assert reduce_rational_inequalities(\n [[Gt(x**2, 0)]], x, relational=False) == FiniteSet(0).complement\n assert reduce_rational_inequalities(\n [[Ne(x**2, 0)]], x, relational=False) == FiniteSet(0).complement\n\n assert reduce_rational_inequalities(\n [[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1)\n assert reduce_rational_inequalities(\n [[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1)\n assert reduce_rational_inequalities(\n [[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True)\n assert reduce_rational_inequalities([[Ge(x**2, 1)]], x, relational=False) == Union(Interval(-oo, -1), Interval(1, oo))\n assert reduce_rational_inequalities(\n [[Gt(x**2, 1)]], x, relational=False) == Interval(-1, 1).complement\n assert reduce_rational_inequalities(\n [[Ne(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1).complement\n assert reduce_rational_inequalities([[Eq(\n x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf()\n assert reduce_rational_inequalities(\n [[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0)\n assert reduce_rational_inequalities([[Lt(\n x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True)\n assert reduce_rational_inequalities([[Ge(x**2, 1.0)]], x, relational=False) == Union(Interval(-inf, -1.0), Interval(1.0, inf))\n assert reduce_rational_inequalities([[Gt(x**2, 1.0)]], x, relational=False) == Union(Interval(-inf, -1.0, right_open=True), Interval(1.0, inf, left_open=True))\n assert reduce_rational_inequalities([[Ne(\n x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).complement\n\n s = sqrt(2)\n\n assert reduce_rational_inequalities([[Lt(\n x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet\n assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge(\n x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1)\n assert reduce_rational_inequalities([[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False))\n assert reduce_rational_inequalities([[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False))\n assert reduce_rational_inequalities([[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True))\n assert reduce_rational_inequalities([[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True))\n assert reduce_rational_inequalities([[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True), Interval(1, s, True, True))\n\n\n\ndef test_reduce_poly_inequalities_real_relational():\n with assuming(Q.real(x), Q.real(y)):\n assert reduce_rational_inequalities(\n [[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0)\n assert reduce_rational_inequalities(\n [[Le(x**2, 0)]], x, relational=True) == Eq(x, 0)\n assert reduce_rational_inequalities(\n [[Lt(x**2, 0)]], x, relational=True) is False\n assert reduce_rational_inequalities(\n [[Ge(x**2, 0)]], x, relational=True) is True\n assert reduce_rational_inequalities(\n [[Gt(x**2, 0)]], x, relational=True) == Or(Lt(x, 0), Gt(x, 0))\n assert reduce_rational_inequalities(\n [[Ne(x**2, 0)]], x, relational=True) == Or(Lt(x, 0), Gt(x, 0))\n\n assert reduce_rational_inequalities(\n [[Eq(x**2, 1)]], x, relational=True) == Or(Eq(x, -1), Eq(x, 1))\n assert reduce_rational_inequalities(\n [[Le(x**2, 1)]], x, relational=True) == And(Le(-1, x), Le(x, 1))\n assert reduce_rational_inequalities(\n [[Lt(x**2, 1)]], x, relational=True) == And(Lt(-1, x), Lt(x, 1))\n assert reduce_rational_inequalities(\n [[Ge(x**2, 1)]], x, relational=True) == Or(Le(x, -1), Ge(x, 1))\n assert reduce_rational_inequalities(\n [[Gt(x**2, 1)]], x, relational=True) == Or(Lt(x, -1), Gt(x, 1))\n assert reduce_rational_inequalities([[Ne(x**2, 1)]], x, relational=True) == Or(\n Lt(x, -1), And(Lt(-1, x), Lt(x, 1)), Gt(x, 1))\n\n assert reduce_rational_inequalities(\n [[Le(x**2, 1.0)]], x, relational=True) == And(Le(-1.0, x), Le(x, 1.0))\n assert reduce_rational_inequalities(\n [[Lt(x**2, 1.0)]], x, relational=True) == And(Lt(-1.0, x), Lt(x, 1.0))\n assert reduce_rational_inequalities(\n [[Ge(x**2, 1.0)]], x, relational=True) == Or(Le(x, -1.0), Ge(x, 1.0))\n assert reduce_rational_inequalities(\n [[Gt(x**2, 1.0)]], x, relational=True) == Or(Lt(x, -1.0), Gt(x, 1.0))\n assert reduce_rational_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == \\\n Or(Lt(x, -1.0), And(Lt(-1.0, x), Lt(x, 1.0)), Gt(x, 1.0))\n\n\ndef test_reduce_poly_inequalities_complex_relational():\n cond = Eq(im(x), 0)\n\n assert reduce_rational_inequalities(\n [[Eq(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)\n assert reduce_rational_inequalities(\n [[Le(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)\n assert reduce_rational_inequalities(\n [[Lt(x**2, 0)]], x, relational=True) is False\n assert reduce_rational_inequalities(\n [[Ge(x**2, 0)]], x, relational=True) == cond\n assert reduce_rational_inequalities([[Gt(x**2, 0)]], x, relational=True) == \\\n And(Or(Lt(re(x), 0), Gt(re(x), 0)), cond)\n assert reduce_rational_inequalities([[Ne(x**2, 0)]], x, relational=True) == \\\n And(Or(Lt(re(x), 0), Gt(re(x), 0)), cond)\n\n assert reduce_rational_inequalities([[Eq(x**2, 1)]], x, relational=True) == \\\n And(Or(Eq(re(x), -1), Eq(re(x), 1)), cond)\n assert reduce_rational_inequalities([[Le(x**2, 1)]], x, relational=True) == \\\n And(And(Le(-1, re(x)), Le(re(x), 1)), cond)\n assert reduce_rational_inequalities([[Lt(x**2, 1)]], x, relational=True) == \\\n And(And(Lt(-1, re(x)), Lt(re(x), 1)), cond)\n assert reduce_rational_inequalities([[Ge(x**2, 1)]], x, relational=True) == \\\n And(Or(Le(re(x), -1), Ge(re(x), 1)), cond)\n assert reduce_rational_inequalities([[Gt(x**2, 1)]], x, relational=True) == \\\n And(Or(Lt(re(x), -1), Gt(re(x), 1)), cond)\n assert reduce_rational_inequalities([[Ne(x**2, 1)]], x, relational=True) == \\\n And(Or(Lt(re(x), -1), And(Lt(-1, re(x)), Lt(re(x), 1)), Gt(re(x), 1)), cond)\n\n assert reduce_rational_inequalities([[Le(x**2, 1.0)]], x, relational=True) == \\\n And(And(Le(-1.0, re(x)), Le(re(x), 1.0)), cond)\n assert reduce_rational_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == \\\n And(And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), cond)\n assert reduce_rational_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == \\\n And(Or(Le(re(x), -1.0), Ge(re(x), 1.0)), cond)\n assert reduce_rational_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == \\\n And(Or(Lt(re(x), -1.0), Gt(re(x), 1.0)), cond)\n assert reduce_rational_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == \\\n And(Or(Lt(re(x), -1.0), And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), Gt(re(x), 1.0)), cond)\n\n\ndef test_reduce_rational_inequalities_real_relational():\n def OpenInterval(a, b):\n return Interval(a, b, True, True)\n def LeftOpenInterval(a, b):\n return Interval(a, b, True, False)\n def RightOpenInterval(a, b):\n return Interval(a, b, False, True)\n\n with assuming(Q.real(x)):\n assert reduce_rational_inequalities([[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \\\n Union(OpenInterval(-oo, -4), Interval(-2, -1), OpenInterval(4, oo))\n\n assert reduce_rational_inequalities([[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x, relational=False) == \\\n Union(OpenInterval(-5, 2), OpenInterval(2, 3))\n\n assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x, assume=Q.real(x), relational=False) == \\\n RightOpenInterval(-1, 5)\n\n assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x, assume=Q.real(x), relational=False) == \\\n Union(OpenInterval(-3, -1), OpenInterval(1, oo))\n\n assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x, assume=Q.real(x), relational=False) == \\\n Union(OpenInterval(-4, 1), OpenInterval(1, 4))\n\n assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x, assume=Q.real(x), relational=False) == \\\n Union(OpenInterval(-oo, -4), RightOpenInterval(S(3)/2, oo))\n\n assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x, assume=Q.real(x), relational=False) == \\\n Union(LeftOpenInterval(-oo, -2), LeftOpenInterval(0, 4))\n\n\ndef test_reduce_abs_inequalities():\n real = Q.real(x)\n\n assert reduce_inequalities(\n abs(x - 5) < 3, assume=real) == And(Lt(2, x), Lt(x, 8))\n assert reduce_inequalities(\n abs(2*x + 3) >= 8, assume=real) == Or(Le(x, -S(11)/2), Ge(x, S(5)/2))\n assert reduce_inequalities(abs(x - 4) + abs(\n 3*x - 5) < 7, assume=real) == And(Lt(S(1)/2, x), Lt(x, 4))\n assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7, assume=real) == Or(And(S(-2) < x, x < -1), And(S(1)/2 < x, x < 4))\n\n raises(NotImplementedError, lambda: reduce_inequalities(abs(x - 5) < 3))\n\n\ndef test_reduce_inequalities_boolean():\n assert reduce_inequalities(\n [Eq(x**2, 0), True]) == And(Eq(re(x), 0), Eq(im(x), 0))\n assert reduce_inequalities([Eq(x**2, 0), False]) is False\n\n\ndef test_reduce_inequalities_assume():\n assert reduce_inequalities(\n [Le(x**2, 1), Q.real(x)]) == And(Le(-1, x), Le(x, 1))\n assert reduce_inequalities(\n [Le(x**2, 1)], Q.real(x)) == And(Le(-1, x), Le(x, 1))\n\n\ndef test_reduce_inequalities_multivariate():\n assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == \\\n And(And(Or(Le(re(x), -1), Ge(re(x), 1)), Eq(im(x), 0)),\n And(Or(Le(re(y), -1), Ge(re(y), 1)), Eq(im(y), 0)))\n\n\ndef test_reduce_inequalities_errors():\n raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1)))\n raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1)))\n raises(NotImplementedError, lambda: reduce_inequalities(Ge(sqrt(2)*x, 1)))\n\n\ndef test_hacky_inequalities():\n assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y)\n assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x >= 1 - y)\n\n\ndef test_issue_3244():\n eq = -3*x**2/2 - 45*x/4 + S(33)/2 > 0\n assert reduce_inequalities(eq, Q.real(x)) == \\\n And(x < -S(15)/4 + sqrt(401)/4, -sqrt(401)/4 - S(15)/4 < x)\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":-448640723350479100,"string":"-448,640,723,350,479,100"},"line_mean":{"kind":"number","value":52.3392857143,"string":"52.339286"},"line_max":{"kind":"number","value":198,"string":"198"},"alpha_frac":{"kind":"number","value":0.567877469,"string":"0.567877"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475925,"cells":{"repo_name":{"kind":"string","value":"vipshop/twemproxies"},"path":{"kind":"string","value":"tests/test_redis/common.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"1364"},"content":{"kind":"string","value":"#!/usr/bin/env python\n#coding: utf-8\n\nimport os\nimport sys\nimport redis\n\nPWD = os.path.dirname(os.path.realpath(__file__))\nWORKDIR = os.path.join(PWD,'../')\nsys.path.append(os.path.join(WORKDIR,'lib/'))\nsys.path.append(os.path.join(WORKDIR,'conf/'))\n\nimport conf\n\nfrom server_modules import *\nfrom utils import *\n\nCLUSTER_NAME = 'ntest'\nnc_verbose = int(getenv('T_VERBOSE', 5))\nmbuf = int(getenv('T_MBUF', 512))\nlarge = int(getenv('T_LARGE', 1000))\nclean = int(getenv('T_CLEAN', 1))\n\nall_redis = [\n RedisServer('127.0.0.1', 2100, '/tmp/r/redis-2100/', CLUSTER_NAME, 'redis-2100'),\n RedisServer('127.0.0.1', 2101, '/tmp/r/redis-2101/', CLUSTER_NAME, 'redis-2101'),\n ]\n\nnc = NutCracker('127.0.0.1', 4100, '/tmp/r/nutcracker-4100', CLUSTER_NAME,\n all_redis, mbuf=mbuf, verbose=nc_verbose)\n\ndef setup():\n print 'setup(mbuf=%s, verbose=%s)' %(mbuf, nc_verbose)\n for r in all_redis + [nc]:\n r.deploy()\n r.stop()\n r.start()\n\ndef teardown():\n for r in all_redis + [nc]:\n assert(r._alive())\n r.stop()\n if clean: # TODO: move clean to setup\n r.clean()\n\ndefault_kv = {'kkk-%s' % i : 'vvv-%s' % i for i in range(10)}\n\ndef getconn():\n for r in all_redis:\n c = redis.Redis(r.host(), r.port())\n c.flushdb()\n\n r = redis.Redis(nc.host(), nc.port())\n return r\n\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":-4010993009019577000,"string":"-4,010,993,009,019,577,000"},"line_mean":{"kind":"number","value":23.8,"string":"23.8"},"line_max":{"kind":"number","value":89,"string":"89"},"alpha_frac":{"kind":"number","value":0.5865102639,"string":"0.58651"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475926,"cells":{"repo_name":{"kind":"string","value":"ric2b/Vivaldi-browser"},"path":{"kind":"string","value":"chromium/tools/diagnosis/crbug_1001171.py"},"copies":{"kind":"string","value":"11"},"size":{"kind":"string","value":"1721"},"content":{"kind":"string","value":"# Copyright 2019 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Helper context wrapper for diagnosing crbug.com/1001171.\n\nThis module and all uses thereof can and should be removed once\ncrbug.com/1001171 has been resolved.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport contextlib\nimport os\nimport sys\n\n\n@contextlib.contextmanager\ndef DumpStateOnLookupError():\n \"\"\"Prints potentially useful state info in the event of a LookupError.\"\"\"\n try:\n yield\n except LookupError:\n print('LookupError diagnosis for crbug.com/1001171:')\n for path_index, path_entry in enumerate(sys.path):\n desc = 'unknown'\n if not os.path.exists(path_entry):\n desc = 'missing'\n elif os.path.islink(path_entry):\n desc = 'link -> %s' % os.path.realpath(path_entry)\n elif os.path.isfile(path_entry):\n desc = 'file'\n elif os.path.isdir(path_entry):\n desc = 'dir'\n print(' sys.path[%d]: %s (%s)' % (path_index, path_entry, desc))\n\n real_path_entry = os.path.realpath(path_entry)\n if (path_entry.endswith(os.path.join('lib', 'python2.7'))\n and os.path.isdir(real_path_entry)):\n encodings_dir = os.path.realpath(\n os.path.join(real_path_entry, 'encodings'))\n if os.path.exists(encodings_dir):\n if os.path.isdir(encodings_dir):\n print(' %s contents: %s' % (encodings_dir,\n str(os.listdir(encodings_dir))))\n else:\n print(' %s exists but is not a directory' % encodings_dir)\n else:\n print(' %s missing' % encodings_dir)\n\n raise\n"},"license":{"kind":"string","value":"bsd-3-clause"},"hash":{"kind":"number","value":7203210606618754000,"string":"7,203,210,606,618,754,000"},"line_mean":{"kind":"number","value":32.7450980392,"string":"32.745098"},"line_max":{"kind":"number","value":75,"string":"75"},"alpha_frac":{"kind":"number","value":0.6263800116,"string":"0.62638"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475927,"cells":{"repo_name":{"kind":"string","value":"kosgroup/odoo"},"path":{"kind":"string","value":"addons/web/models/ir_http.py"},"copies":{"kind":"string","value":"14"},"size":{"kind":"string","value":"2041"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport json\n\nfrom odoo import models\nfrom odoo.http import request\n\nimport odoo\n\n\nclass Http(models.AbstractModel):\n _inherit = 'ir.http'\n\n def webclient_rendering_context(self):\n return {\n 'menu_data': request.env['ir.ui.menu'].load_menus(request.debug),\n 'session_info': json.dumps(self.session_info()),\n }\n\n def session_info(self):\n user = request.env.user\n display_switch_company_menu = user.has_group('base.group_multi_company') and len(user.company_ids) > 1\n version_info = odoo.service.common.exp_version()\n return {\n \"session_id\": request.session.sid,\n \"uid\": request.session.uid,\n \"is_admin\": request.env.user.has_group('base.group_system'),\n \"is_superuser\": request.env.user._is_superuser(),\n \"user_context\": request.session.get_context() if request.session.uid else {},\n \"db\": request.session.db,\n \"server_version\": version_info.get('server_version'),\n \"server_version_info\": version_info.get('server_version_info'),\n \"name\": user.name,\n \"username\": user.login,\n \"company_id\": request.env.user.company_id.id if request.session.uid else None,\n \"partner_id\": request.env.user.partner_id.id if request.session.uid and request.env.user.partner_id else None,\n \"user_companies\": {'current_company': (user.company_id.id, user.company_id.name), 'allowed_companies': [(comp.id, comp.name) for comp in user.company_ids]} if display_switch_company_menu else False,\n \"currencies\": self.get_currencies(),\n }\n\n def get_currencies(self):\n Currency = request.env['res.currency']\n currencies = Currency.search([]).read(['symbol', 'position', 'decimal_places'])\n return { c['id']: {'symbol': c['symbol'], 'position': c['position'], 'digits': [69,c['decimal_places']]} for c in currencies} \n"},"license":{"kind":"string","value":"gpl-3.0"},"hash":{"kind":"number","value":9124184406343638000,"string":"9,124,184,406,343,638,000"},"line_mean":{"kind":"number","value":44.3555555556,"string":"44.355556"},"line_max":{"kind":"number","value":210,"string":"210"},"alpha_frac":{"kind":"number","value":0.6246937776,"string":"0.624694"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475928,"cells":{"repo_name":{"kind":"string","value":"ammarkhann/FinalSeniorCode"},"path":{"kind":"string","value":"lib/python2.7/site-packages/matplotlib/testing/__init__.py"},"copies":{"kind":"string","value":"10"},"size":{"kind":"string","value":"3767"},"content":{"kind":"string","value":"from __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport warnings\nfrom contextlib import contextmanager\n\nfrom matplotlib.cbook import is_string_like, iterable\nfrom matplotlib import rcParams, rcdefaults, use\n\n\ndef _is_list_like(obj):\n \"\"\"Returns whether the obj is iterable and not a string\"\"\"\n return not is_string_like(obj) and iterable(obj)\n\n\n# stolen from pandas\n@contextmanager\ndef assert_produces_warning(expected_warning=Warning, filter_level=\"always\",\n clear=None):\n \"\"\"\n Context manager for running code that expects to raise (or not raise)\n warnings. Checks that code raises the expected warning and only the\n expected warning. Pass ``False`` or ``None`` to check that it does *not*\n raise a warning. Defaults to ``exception.Warning``, baseclass of all\n Warnings. (basically a wrapper around ``warnings.catch_warnings``).\n\n >>> import warnings\n >>> with assert_produces_warning():\n ... warnings.warn(UserWarning())\n ...\n >>> with assert_produces_warning(False):\n ... warnings.warn(RuntimeWarning())\n ...\n Traceback (most recent call last):\n ...\n AssertionError: Caused unexpected warning(s): ['RuntimeWarning'].\n >>> with assert_produces_warning(UserWarning):\n ... warnings.warn(RuntimeWarning())\n Traceback (most recent call last):\n ...\n AssertionError: Did not see expected warning of class 'UserWarning'.\n\n ..warn:: This is *not* thread-safe.\n \"\"\"\n with warnings.catch_warnings(record=True) as w:\n\n if clear is not None:\n # make sure that we are clearning these warnings\n # if they have happened before\n # to guarantee that we will catch them\n if not _is_list_like(clear):\n clear = [clear]\n for m in clear:\n try:\n m.__warningregistry__.clear()\n except:\n pass\n\n saw_warning = False\n warnings.simplefilter(filter_level)\n yield w\n extra_warnings = []\n for actual_warning in w:\n if (expected_warning and issubclass(actual_warning.category,\n expected_warning)):\n saw_warning = True\n else:\n extra_warnings.append(actual_warning.category.__name__)\n if expected_warning:\n assert saw_warning, (\"Did not see expected warning of class %r.\"\n % expected_warning.__name__)\n assert not extra_warnings, (\"Caused unexpected warning(s): %r.\"\n % extra_warnings)\n\n\ndef set_font_settings_for_testing():\n rcParams['font.family'] = 'DejaVu Sans'\n rcParams['text.hinting'] = False\n rcParams['text.hinting_factor'] = 8\n\n\ndef setup():\n # The baseline images are created in this locale, so we should use\n # it during all of the tests.\n import locale\n import warnings\n from matplotlib.backends import backend_agg, backend_pdf, backend_svg\n\n try:\n locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))\n except locale.Error:\n try:\n locale.setlocale(locale.LC_ALL, str('English_United States.1252'))\n except locale.Error:\n warnings.warn(\n \"Could not set locale to English/United States. \"\n \"Some date-related tests may fail\")\n\n use('Agg', warn=False) # use Agg backend for these tests\n\n # These settings *must* be hardcoded for running the comparison\n # tests and are not necessarily the default values as specified in\n # rcsetup.py\n rcdefaults() # Start with all defaults\n\n set_font_settings_for_testing()\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":6350728815843813000,"string":"6,350,728,815,843,813,000"},"line_mean":{"kind":"number","value":34.5377358491,"string":"34.537736"},"line_max":{"kind":"number","value":78,"string":"78"},"alpha_frac":{"kind":"number","value":0.6095035838,"string":"0.609504"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475929,"cells":{"repo_name":{"kind":"string","value":"ic-labs/django-icekit"},"path":{"kind":"string","value":"icekit/abstract_models.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"4379"},"content":{"kind":"string","value":"\"\"\"\nModels for ``icekit`` app.\n\"\"\"\n\n# Compose concrete models from abstract models and mixins, to facilitate reuse.\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.template.loader import get_template\nfrom django.utils import encoding, timezone\nfrom django.utils.translation import ugettext_lazy as _\nfrom fluent_contents.analyzer import get_template_placeholder_data\nfrom icekit.admin_tools.filters import ChildModelFilter\n\nfrom . import fields, plugins\n\n\nclass AbstractBaseModel(models.Model):\n \"\"\"\n Abstract base model.\n \"\"\"\n\n created = models.DateTimeField(\n default=timezone.now, db_index=True, editable=False)\n modified = models.DateTimeField(\n default=timezone.now, db_index=True, editable=False)\n\n class Meta:\n abstract = True\n get_latest_by = 'pk'\n ordering = ('-id', )\n\n def save(self, *args, **kwargs):\n \"\"\"\n Update ``self.modified``.\n \"\"\"\n self.modified = timezone.now()\n super(AbstractBaseModel, self).save(*args, **kwargs)\n\n\n@encoding.python_2_unicode_compatible\nclass AbstractLayout(AbstractBaseModel):\n \"\"\"\n An implementation of ``fluent_pages.models.db.PageLayout`` that uses\n plugins to get template name choices instead of scanning a directory given\n in settings.\n \"\"\"\n title = models.CharField(_('title'), max_length=255)\n template_name = fields.TemplateNameField(\n _('template'),\n plugin_class=plugins.TemplateNameFieldChoicesPlugin,\n unique=True,\n )\n content_types = models.ManyToManyField(\n ContentType,\n help_text='Types of content for which this layout will be allowed.',\n )\n\n class Meta:\n abstract = True\n ordering = ('title',)\n\n def __str__(self):\n return self.title\n\n @classmethod\n def auto_add(cls, template_name, *models, **kwargs):\n \"\"\"\n Get or create a layout for the given template and add content types for\n the given models to it. Append the verbose name of each model to the\n title with the given ``separator`` keyword argument.\n \"\"\"\n separator = kwargs.get('separator', ', ')\n content_types = ContentType.objects.get_for_models(*models).values()\n try:\n # Get.\n layout = cls.objects.get(template_name=template_name)\n except cls.DoesNotExist:\n # Create.\n title = separator.join(sorted(\n ct.model_class()._meta.verbose_name for ct in content_types))\n layout = cls.objects.create(\n template_name=template_name,\n title=title,\n )\n layout.content_types.add(*content_types)\n else:\n title = [layout.title]\n # Update.\n for ct in content_types:\n if not layout.content_types.filter(pk=ct.pk).exists():\n title.append(ct.model_class()._meta.verbose_name)\n layout.title = separator.join(sorted(title))\n layout.save()\n layout.content_types.add(*content_types)\n return layout\n\n def get_placeholder_data(self):\n \"\"\"\n Return placeholder data for this layout's template.\n \"\"\"\n return get_template_placeholder_data(self.get_template())\n\n def get_template(self):\n \"\"\"\n Return the template to render this layout.\n \"\"\"\n return get_template(self.template_name)\n\n\n@encoding.python_2_unicode_compatible\nclass AbstractMediaCategory(AbstractBaseModel):\n \"\"\"\n A categorisation model for Media assets.\n \"\"\"\n name = models.CharField(\n max_length=255,\n unique=True,\n )\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return self.name\n\n\nclass BoostedTermsMixin(models.Model):\n \"\"\"\n Mixin for providing a field for terms which will get boosted search\n priority.\n \"\"\"\n boosted_terms = models.TextField(\n blank=True,\n default='', # This is for convenience when adding models in the shell.\n help_text=_(\n 'Words (space separated) added here are boosted in relevance for search results '\n 'increasing the chance of this appearing higher in the search results.'\n ),\n verbose_name=_('Boosted Search Terms'),\n )\n\n class Meta:\n abstract = True\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":-4701846451494734000,"string":"-4,701,846,451,494,734,000"},"line_mean":{"kind":"number","value":29.6223776224,"string":"29.622378"},"line_max":{"kind":"number","value":93,"string":"93"},"alpha_frac":{"kind":"number","value":0.6234300069,"string":"0.62343"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475930,"cells":{"repo_name":{"kind":"string","value":"plotly/plotly.py"},"path":{"kind":"string","value":"packages/python/plotly/plotly/validators/histogram2dcontour/colorbar/_tickfont.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"1580"},"content":{"kind":"string","value":"import _plotly_utils.basevalidators\n\n\nclass TickfontValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(\n self,\n plotly_name=\"tickfont\",\n parent_name=\"histogram2dcontour.colorbar\",\n **kwargs\n ):\n super(TickfontValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Tickfont\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n color\n\n family\n HTML font family - the typeface that will be\n applied by the web browser. The web browser\n will only be able to apply a font if it is\n available on the system which it operates.\n Provide multiple font families, separated by\n commas, to indicate the preference in which to\n apply fonts if they aren't available on the\n system. The Chart Studio Cloud (at\n https://chart-studio.plotly.com or on-premise)\n generates images on a server, where only a\n select number of fonts are installed and\n supported. These include \"Arial\", \"Balto\",\n \"Courier New\", \"Droid Sans\",, \"Droid Serif\",\n \"Droid Sans Mono\", \"Gravitas One\", \"Old\n Standard TT\", \"Open Sans\", \"Overpass\", \"PT Sans\n Narrow\", \"Raleway\", \"Times New Roman\".\n size\n\n\"\"\",\n ),\n **kwargs\n )\n"},"license":{"kind":"string","value":"mit"},"hash":{"kind":"number","value":3341459364958832600,"string":"3,341,459,364,958,832,600"},"line_mean":{"kind":"number","value":36.619047619,"string":"36.619048"},"line_max":{"kind":"number","value":72,"string":"72"},"alpha_frac":{"kind":"number","value":0.5360759494,"string":"0.536076"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475931,"cells":{"repo_name":{"kind":"string","value":"donspaulding/adspygoogle"},"path":{"kind":"string","value":"examples/adspygoogle/dfp/v201206/update_creatives.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"2356"},"content":{"kind":"string","value":"#!/usr/bin/python\n#\n# Copyright 2012 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This code example updates the destination URL of all image creatives up to\nthe first 500. To determine which image creatives exist, run\nget_all_creatives.py.\"\"\"\n\n__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'\n\n# Locate the client library. If module was installed via \"setup.py\" script, then\n# the following two lines are not needed.\nimport os\nimport sys\nsys.path.insert(0, os.path.join('..', '..', '..', '..'))\n\n# Import appropriate classes from the client library.\nfrom adspygoogle import DfpClient\n\n\n# Initialize client object.\nclient = DfpClient(path=os.path.join('..', '..', '..', '..'))\n\n# Initialize appropriate service.\ncreative_service = client.GetService('CreativeService', version='v201206')\n\n# Create statement object to get all image creatives.\nvalues = [{\n 'key': 'type',\n 'value': {\n 'xsi_type': 'TextValue',\n 'value': 'ImageCreative'\n }\n}]\nfilter_statement = {'query': 'WHERE creativeType = :type LIMIT 500',\n 'values': values}\n\n# Get creatives by statement.\nresponse = creative_service.GetCreativesByStatement(filter_statement)[0]\ncreatives = []\nif 'results' in response:\n creatives = response['results']\n\nif creatives:\n # Update each local creative object by changing its destination URL.\n for creative in creatives:\n creative['destinationUrl'] = 'http://news.google.com'\n\n # Update creatives remotely.\n creatives = creative_service.UpdateCreatives(creatives)\n\n # Display results.\n if creatives:\n for creative in creatives:\n print ('Image creative with id \\'%s\\' and destination URL \\'%s\\' was '\n 'updated.' % (creative['id'], creative['destinationUrl']))\n else:\n print 'No orders were updated.'\nelse:\n print 'No orders found to update.'\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":9132696863083803000,"string":"9,132,696,863,083,803,000"},"line_mean":{"kind":"number","value":31.7222222222,"string":"31.722222"},"line_max":{"kind":"number","value":80,"string":"80"},"alpha_frac":{"kind":"number","value":0.7037351443,"string":"0.703735"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475932,"cells":{"repo_name":{"kind":"string","value":"proxysh/Safejumper-for-Mac"},"path":{"kind":"string","value":"buildlinux/env32/lib/python2.7/site-packages/twisted/mail/test/test_pop3.py"},"copies":{"kind":"string","value":"10"},"size":{"kind":"string","value":"30479"},"content":{"kind":"string","value":"# Copyright (c) Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nTest cases for Ltwisted.mail.pop3} module.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport StringIO\nimport hmac\nimport base64\nimport itertools\n\nfrom collections import OrderedDict\n\nfrom zope.interface import implementer\n\nfrom twisted.internet import defer\n\nfrom twisted.trial import unittest, util\nfrom twisted import mail\nimport twisted.mail.protocols\nimport twisted.mail.pop3\nimport twisted.internet.protocol\nfrom twisted import internet\nfrom twisted.mail import pop3\nfrom twisted.protocols import loopback\nfrom twisted.python import failure\n\nfrom twisted import cred\nimport twisted.cred.portal\nimport twisted.cred.checkers\nimport twisted.cred.credentials\n\nfrom twisted.test.proto_helpers import LineSendingProtocol\n\n\nclass UtilityTests(unittest.TestCase):\n \"\"\"\n Test the various helper functions and classes used by the POP3 server\n protocol implementation.\n \"\"\"\n\n def testLineBuffering(self):\n \"\"\"\n Test creating a LineBuffer and feeding it some lines. The lines should\n build up in its internal buffer for a while and then get spat out to\n the writer.\n \"\"\"\n output = []\n input = iter(itertools.cycle(['012', '345', '6', '7', '8', '9']))\n c = pop3._IteratorBuffer(output.extend, input, 6)\n i = iter(c)\n self.assertEqual(output, []) # nothing is buffer\n i.next()\n self.assertEqual(output, []) # '012' is buffered\n i.next()\n self.assertEqual(output, []) # '012345' is buffered\n i.next()\n self.assertEqual(output, ['012', '345', '6']) # nothing is buffered\n for n in range(5):\n i.next()\n self.assertEqual(output, ['012', '345', '6', '7', '8', '9', '012', '345'])\n\n\n def testFinishLineBuffering(self):\n \"\"\"\n Test that a LineBuffer flushes everything when its iterator is\n exhausted, and itself raises StopIteration.\n \"\"\"\n output = []\n input = iter(['a', 'b', 'c'])\n c = pop3._IteratorBuffer(output.extend, input, 5)\n for i in c:\n pass\n self.assertEqual(output, ['a', 'b', 'c'])\n\n\n def testSuccessResponseFormatter(self):\n \"\"\"\n Test that the thing that spits out POP3 'success responses' works\n right.\n \"\"\"\n self.assertEqual(\n pop3.successResponse('Great.'),\n '+OK Great.\\r\\n')\n\n\n def testStatLineFormatter(self):\n \"\"\"\n Test that the function which formats stat lines does so appropriately.\n \"\"\"\n statLine = list(pop3.formatStatResponse([]))[-1]\n self.assertEqual(statLine, '+OK 0 0\\r\\n')\n\n statLine = list(pop3.formatStatResponse([10, 31, 0, 10101]))[-1]\n self.assertEqual(statLine, '+OK 4 10142\\r\\n')\n\n\n def testListLineFormatter(self):\n \"\"\"\n Test that the function which formats the lines in response to a LIST\n command does so appropriately.\n \"\"\"\n listLines = list(pop3.formatListResponse([]))\n self.assertEqual(\n listLines,\n ['+OK 0\\r\\n', '.\\r\\n'])\n\n listLines = list(pop3.formatListResponse([1, 2, 3, 100]))\n self.assertEqual(\n listLines,\n ['+OK 4\\r\\n', '1 1\\r\\n', '2 2\\r\\n', '3 3\\r\\n', '4 100\\r\\n', '.\\r\\n'])\n\n\n\n def testUIDListLineFormatter(self):\n \"\"\"\n Test that the function which formats lines in response to a UIDL\n command does so appropriately.\n \"\"\"\n UIDs = ['abc', 'def', 'ghi']\n listLines = list(pop3.formatUIDListResponse([], UIDs.__getitem__))\n self.assertEqual(\n listLines,\n ['+OK \\r\\n', '.\\r\\n'])\n\n listLines = list(pop3.formatUIDListResponse([123, 431, 591], UIDs.__getitem__))\n self.assertEqual(\n listLines,\n ['+OK \\r\\n', '1 abc\\r\\n', '2 def\\r\\n', '3 ghi\\r\\n', '.\\r\\n'])\n\n listLines = list(pop3.formatUIDListResponse([0, None, 591], UIDs.__getitem__))\n self.assertEqual(\n listLines,\n ['+OK \\r\\n', '1 abc\\r\\n', '3 ghi\\r\\n', '.\\r\\n'])\n\n\n\nclass MyVirtualPOP3(mail.protocols.VirtualPOP3):\n\n magic = ''\n\n def authenticateUserAPOP(self, user, digest):\n user, domain = self.lookupDomain(user)\n return self.service.domains['baz.com'].authenticateUserAPOP(user, digest, self.magic, domain)\n\nclass DummyDomain:\n\n def __init__(self):\n self.users = {}\n\n def addUser(self, name):\n self.users[name] = []\n\n def addMessage(self, name, message):\n self.users[name].append(message)\n\n def authenticateUserAPOP(self, name, digest, magic, domain):\n return pop3.IMailbox, ListMailbox(self.users[name]), lambda: None\n\n\nclass ListMailbox:\n\n def __init__(self, list):\n self.list = list\n\n def listMessages(self, i=None):\n if i is None:\n return map(len, self.list)\n return len(self.list[i])\n\n def getMessage(self, i):\n return StringIO.StringIO(self.list[i])\n\n def getUidl(self, i):\n return i\n\n def deleteMessage(self, i):\n self.list[i] = ''\n\n def sync(self):\n pass\n\nclass MyPOP3Downloader(pop3.POP3Client):\n\n def handle_WELCOME(self, line):\n pop3.POP3Client.handle_WELCOME(self, line)\n self.apop('hello@baz.com', 'world')\n\n def handle_APOP(self, line):\n parts = line.split()\n code = parts[0]\n if code != '+OK':\n raise AssertionError('code is: %s , parts is: %s ' % (code, parts))\n self.lines = []\n self.retr(1)\n\n def handle_RETR_continue(self, line):\n self.lines.append(line)\n\n def handle_RETR_end(self):\n self.message = '\\n'.join(self.lines) + '\\n'\n self.quit()\n\n def handle_QUIT(self, line):\n if line[:3] != '+OK':\n raise AssertionError('code is ' + line)\n\n\nclass POP3Tests(unittest.TestCase):\n\n message = '''\\\nSubject: urgent\n\nSomeone set up us the bomb!\n'''\n\n expectedOutput = '''\\\n+OK \\015\n+OK Authentication succeeded\\015\n+OK \\015\n1 0\\015\n.\\015\n+OK %d\\015\nSubject: urgent\\015\n\\015\nSomeone set up us the bomb!\\015\n.\\015\n+OK \\015\n''' % len(message)\n\n def setUp(self):\n self.factory = internet.protocol.Factory()\n self.factory.domains = {}\n self.factory.domains['baz.com'] = DummyDomain()\n self.factory.domains['baz.com'].addUser('hello')\n self.factory.domains['baz.com'].addMessage('hello', self.message)\n\n def testMessages(self):\n client = LineSendingProtocol([\n 'APOP hello@baz.com world',\n 'UIDL',\n 'RETR 1',\n 'QUIT',\n ])\n server = MyVirtualPOP3()\n server.service = self.factory\n def check(ignored):\n output = '\\r\\n'.join(client.response) + '\\r\\n'\n self.assertEqual(output, self.expectedOutput)\n return loopback.loopbackTCP(server, client).addCallback(check)\n\n def testLoopback(self):\n protocol = MyVirtualPOP3()\n protocol.service = self.factory\n clientProtocol = MyPOP3Downloader()\n def check(ignored):\n self.assertEqual(clientProtocol.message, self.message)\n protocol.connectionLost(\n failure.Failure(Exception(\"Test harness disconnect\")))\n d = loopback.loopbackAsync(protocol, clientProtocol)\n return d.addCallback(check)\n testLoopback.suppress = [util.suppress(message=\"twisted.mail.pop3.POP3Client is deprecated\")]\n\n\n\nclass DummyPOP3(pop3.POP3):\n\n magic = ''\n\n def authenticateUserAPOP(self, user, password):\n return pop3.IMailbox, DummyMailbox(ValueError), lambda: None\n\n\n\nclass DummyMailbox(pop3.Mailbox):\n\n messages = ['From: moshe\\nTo: moshe\\n\\nHow are you, friend?\\n']\n\n def __init__(self, exceptionType):\n self.messages = DummyMailbox.messages[:]\n self.exceptionType = exceptionType\n\n def listMessages(self, i=None):\n if i is None:\n return map(len, self.messages)\n if i >= len(self.messages):\n raise self.exceptionType()\n return len(self.messages[i])\n\n def getMessage(self, i):\n return StringIO.StringIO(self.messages[i])\n\n def getUidl(self, i):\n if i >= len(self.messages):\n raise self.exceptionType()\n return str(i)\n\n def deleteMessage(self, i):\n self.messages[i] = ''\n\n\nclass AnotherPOP3Tests(unittest.TestCase):\n\n def runTest(self, lines, expectedOutput):\n dummy = DummyPOP3()\n client = LineSendingProtocol(lines)\n d = loopback.loopbackAsync(dummy, client)\n return d.addCallback(self._cbRunTest, client, dummy, expectedOutput)\n\n\n def _cbRunTest(self, ignored, client, dummy, expectedOutput):\n self.assertEqual('\\r\\n'.join(expectedOutput),\n '\\r\\n'.join(client.response))\n dummy.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n return ignored\n\n\n def test_buffer(self):\n \"\"\"\n Test a lot of different POP3 commands in an extremely pipelined\n scenario.\n\n This test may cover legitimate behavior, but the intent and\n granularity are not very good. It would likely be an improvement to\n split it into a number of smaller, more focused tests.\n \"\"\"\n return self.runTest(\n [\"APOP moshez dummy\",\n \"LIST\",\n \"UIDL\",\n \"RETR 1\",\n \"RETR 2\",\n \"DELE 1\",\n \"RETR 1\",\n \"QUIT\"],\n ['+OK ',\n '+OK Authentication succeeded',\n '+OK 1',\n '1 44',\n '.',\n '+OK ',\n '1 0',\n '.',\n '+OK 44',\n 'From: moshe',\n 'To: moshe',\n '',\n 'How are you, friend?',\n '.',\n '-ERR Bad message number argument',\n '+OK ',\n '-ERR message deleted',\n '+OK '])\n\n\n def test_noop(self):\n \"\"\"\n Test the no-op command.\n \"\"\"\n return self.runTest(\n ['APOP spiv dummy',\n 'NOOP',\n 'QUIT'],\n ['+OK ',\n '+OK Authentication succeeded',\n '+OK ',\n '+OK '])\n\n\n def testAuthListing(self):\n p = DummyPOP3()\n p.factory = internet.protocol.Factory()\n p.factory.challengers = {'Auth1': None, 'secondAuth': None, 'authLast': None}\n client = LineSendingProtocol([\n \"AUTH\",\n \"QUIT\",\n ])\n\n d = loopback.loopbackAsync(p, client)\n return d.addCallback(self._cbTestAuthListing, client)\n\n def _cbTestAuthListing(self, ignored, client):\n self.assertTrue(client.response[1].startswith('+OK'))\n self.assertEqual(sorted(client.response[2:5]),\n [\"AUTH1\", \"AUTHLAST\", \"SECONDAUTH\"])\n self.assertEqual(client.response[5], \".\")\n\n def testIllegalPASS(self):\n dummy = DummyPOP3()\n client = LineSendingProtocol([\n \"PASS fooz\",\n \"QUIT\"\n ])\n d = loopback.loopbackAsync(dummy, client)\n return d.addCallback(self._cbTestIllegalPASS, client, dummy)\n\n def _cbTestIllegalPASS(self, ignored, client, dummy):\n expected_output = '+OK \\r\\n-ERR USER required before PASS\\r\\n+OK \\r\\n'\n self.assertEqual(expected_output, '\\r\\n'.join(client.response) + '\\r\\n')\n dummy.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n def testEmptyPASS(self):\n dummy = DummyPOP3()\n client = LineSendingProtocol([\n \"PASS \",\n \"QUIT\"\n ])\n d = loopback.loopbackAsync(dummy, client)\n return d.addCallback(self._cbTestEmptyPASS, client, dummy)\n\n def _cbTestEmptyPASS(self, ignored, client, dummy):\n expected_output = '+OK \\r\\n-ERR USER required before PASS\\r\\n+OK \\r\\n'\n self.assertEqual(expected_output, '\\r\\n'.join(client.response) + '\\r\\n')\n dummy.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n\n@implementer(pop3.IServerFactory)\nclass TestServerFactory:\n def cap_IMPLEMENTATION(self):\n return \"Test Implementation String\"\n\n def cap_EXPIRE(self):\n return 60\n\n challengers = OrderedDict([(\"SCHEME_1\", None), (\"SCHEME_2\", None)])\n\n def cap_LOGIN_DELAY(self):\n return 120\n\n pue = True\n def perUserExpiration(self):\n return self.pue\n\n puld = True\n def perUserLoginDelay(self):\n return self.puld\n\n\nclass TestMailbox:\n loginDelay = 100\n messageExpiration = 25\n\n\nclass CapabilityTests(unittest.TestCase):\n def setUp(self):\n s = StringIO.StringIO()\n p = pop3.POP3()\n p.factory = TestServerFactory()\n p.transport = internet.protocol.FileWrapper(s)\n p.connectionMade()\n p.do_CAPA()\n\n self.caps = p.listCapabilities()\n self.pcaps = s.getvalue().splitlines()\n\n s = StringIO.StringIO()\n p.mbox = TestMailbox()\n p.transport = internet.protocol.FileWrapper(s)\n p.do_CAPA()\n\n self.lpcaps = s.getvalue().splitlines()\n p.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n def contained(self, s, *caps):\n for c in caps:\n self.assertIn(s, c)\n\n def testUIDL(self):\n self.contained(\"UIDL\", self.caps, self.pcaps, self.lpcaps)\n\n def testTOP(self):\n self.contained(\"TOP\", self.caps, self.pcaps, self.lpcaps)\n\n def testUSER(self):\n self.contained(\"USER\", self.caps, self.pcaps, self.lpcaps)\n\n def testEXPIRE(self):\n self.contained(\"EXPIRE 60 USER\", self.caps, self.pcaps)\n self.contained(\"EXPIRE 25\", self.lpcaps)\n\n def testIMPLEMENTATION(self):\n self.contained(\n \"IMPLEMENTATION Test Implementation String\",\n self.caps, self.pcaps, self.lpcaps\n )\n\n def testSASL(self):\n self.contained(\n \"SASL SCHEME_1 SCHEME_2\",\n self.caps, self.pcaps, self.lpcaps\n )\n\n def testLOGIN_DELAY(self):\n self.contained(\"LOGIN-DELAY 120 USER\", self.caps, self.pcaps)\n self.assertIn(\"LOGIN-DELAY 100\", self.lpcaps)\n\n\n\nclass GlobalCapabilitiesTests(unittest.TestCase):\n def setUp(self):\n s = StringIO.StringIO()\n p = pop3.POP3()\n p.factory = TestServerFactory()\n p.factory.pue = p.factory.puld = False\n p.transport = internet.protocol.FileWrapper(s)\n p.connectionMade()\n p.do_CAPA()\n\n self.caps = p.listCapabilities()\n self.pcaps = s.getvalue().splitlines()\n\n s = StringIO.StringIO()\n p.mbox = TestMailbox()\n p.transport = internet.protocol.FileWrapper(s)\n p.do_CAPA()\n\n self.lpcaps = s.getvalue().splitlines()\n p.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n def contained(self, s, *caps):\n for c in caps:\n self.assertIn(s, c)\n\n def testEXPIRE(self):\n self.contained(\"EXPIRE 60\", self.caps, self.pcaps, self.lpcaps)\n\n def testLOGIN_DELAY(self):\n self.contained(\"LOGIN-DELAY 120\", self.caps, self.pcaps, self.lpcaps)\n\n\n\nclass TestRealm:\n def requestAvatar(self, avatarId, mind, *interfaces):\n if avatarId == 'testuser':\n return pop3.IMailbox, DummyMailbox(ValueError), lambda: None\n assert False\n\n\n\nclass SASLTests(unittest.TestCase):\n def testValidLogin(self):\n p = pop3.POP3()\n p.factory = TestServerFactory()\n p.factory.challengers = {'CRAM-MD5': cred.credentials.CramMD5Credentials}\n p.portal = cred.portal.Portal(TestRealm())\n ch = cred.checkers.InMemoryUsernamePasswordDatabaseDontUse()\n ch.addUser('testuser', 'testpassword')\n p.portal.registerChecker(ch)\n\n s = StringIO.StringIO()\n p.transport = internet.protocol.FileWrapper(s)\n p.connectionMade()\n\n p.lineReceived(\"CAPA\")\n self.assertTrue(s.getvalue().find(\"SASL CRAM-MD5\") >= 0)\n\n p.lineReceived(\"AUTH CRAM-MD5\")\n chal = s.getvalue().splitlines()[-1][2:]\n chal = base64.decodestring(chal)\n response = hmac.HMAC('testpassword', chal).hexdigest()\n\n p.lineReceived(base64.encodestring('testuser ' + response).rstrip('\\n'))\n self.assertTrue(p.mbox)\n self.assertTrue(s.getvalue().splitlines()[-1].find(\"+OK\") >= 0)\n p.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n\n\nclass CommandMixin:\n \"\"\"\n Tests for all the commands a POP3 server is allowed to receive.\n \"\"\"\n\n extraMessage = '''\\\nFrom: guy\nTo: fellow\n\nMore message text for you.\n'''\n\n\n def setUp(self):\n \"\"\"\n Make a POP3 server protocol instance hooked up to a simple mailbox and\n a transport that buffers output to a StringIO.\n \"\"\"\n p = pop3.POP3()\n p.mbox = self.mailboxType(self.exceptionType)\n p.schedule = list\n self.pop3Server = p\n\n s = StringIO.StringIO()\n p.transport = internet.protocol.FileWrapper(s)\n p.connectionMade()\n s.truncate(0)\n self.pop3Transport = s\n\n\n def tearDown(self):\n \"\"\"\n Disconnect the server protocol so it can clean up anything it might\n need to clean up.\n \"\"\"\n self.pop3Server.connectionLost(failure.Failure(Exception(\"Test harness disconnect\")))\n\n\n def _flush(self):\n \"\"\"\n Do some of the things that the reactor would take care of, if the\n reactor were actually running.\n \"\"\"\n # Oh man FileWrapper is pooh.\n self.pop3Server.transport._checkProducer()\n\n\n def testLIST(self):\n \"\"\"\n Test the two forms of list: with a message index number, which should\n return a short-form response, and without a message index number, which\n should return a long-form response, one line per message.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"LIST 1\")\n self._flush()\n self.assertEqual(s.getvalue(), \"+OK 1 44\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"LIST\")\n self._flush()\n self.assertEqual(s.getvalue(), \"+OK 1\\r\\n1 44\\r\\n.\\r\\n\")\n\n\n def testLISTWithBadArgument(self):\n \"\"\"\n Test that non-integers and out-of-bound integers produce appropriate\n error responses.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"LIST a\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Invalid message-number: 'a'\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"LIST 0\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Invalid message-number: 0\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"LIST 2\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Invalid message-number: 2\\r\\n\")\n s.truncate(0)\n\n\n def testUIDL(self):\n \"\"\"\n Test the two forms of the UIDL command. These are just like the two\n forms of the LIST command.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"UIDL 1\")\n self.assertEqual(s.getvalue(), \"+OK 0\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"UIDL\")\n self._flush()\n self.assertEqual(s.getvalue(), \"+OK \\r\\n1 0\\r\\n.\\r\\n\")\n\n\n def testUIDLWithBadArgument(self):\n \"\"\"\n Test that UIDL with a non-integer or an out-of-bounds integer produces\n the appropriate error response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"UIDL a\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"UIDL 0\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"UIDL 2\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n\n def testSTAT(self):\n \"\"\"\n Test the single form of the STAT command, which returns a short-form\n response of the number of messages in the mailbox and their total size.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"STAT\")\n self._flush()\n self.assertEqual(s.getvalue(), \"+OK 1 44\\r\\n\")\n\n\n def testRETR(self):\n \"\"\"\n Test downloading a message.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"RETR 1\")\n self._flush()\n self.assertEqual(\n s.getvalue(),\n \"+OK 44\\r\\n\"\n \"From: moshe\\r\\n\"\n \"To: moshe\\r\\n\"\n \"\\r\\n\"\n \"How are you, friend?\\r\\n\"\n \".\\r\\n\")\n s.truncate(0)\n\n\n def testRETRWithBadArgument(self):\n \"\"\"\n Test that trying to download a message with a bad argument, either not\n an integer or an out-of-bounds integer, fails with the appropriate\n error response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n\n p.lineReceived(\"RETR a\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"RETR 0\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"RETR 2\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n\n def testTOP(self):\n \"\"\"\n Test downloading the headers and part of the body of a message.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived(\"TOP 1 0\")\n self._flush()\n self.assertEqual(\n s.getvalue(),\n \"+OK Top of message follows\\r\\n\"\n \"From: moshe\\r\\n\"\n \"To: moshe\\r\\n\"\n \"\\r\\n\"\n \".\\r\\n\")\n\n\n def testTOPWithBadArgument(self):\n \"\"\"\n Test that trying to download a message with a bad argument, either a\n message number which isn't an integer or is an out-of-bounds integer or\n a number of lines which isn't an integer or is a negative integer,\n fails with the appropriate error response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived(\"TOP 1 a\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad line count argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"TOP 1 -1\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad line count argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"TOP a 1\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"TOP 0 1\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n p.lineReceived(\"TOP 3 1\")\n self.assertEqual(\n s.getvalue(),\n \"-ERR Bad message number argument\\r\\n\")\n s.truncate(0)\n\n\n def testLAST(self):\n \"\"\"\n Test the exceedingly pointless LAST command, which tells you the\n highest message index which you have already downloaded.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived('LAST')\n self.assertEqual(\n s.getvalue(),\n \"+OK 0\\r\\n\")\n s.truncate(0)\n\n\n def testRetrieveUpdatesHighest(self):\n \"\"\"\n Test that issuing a RETR command updates the LAST response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived('RETR 2')\n self._flush()\n s.truncate(0)\n p.lineReceived('LAST')\n self.assertEqual(\n s.getvalue(),\n '+OK 2\\r\\n')\n s.truncate(0)\n\n\n def testTopUpdatesHighest(self):\n \"\"\"\n Test that issuing a TOP command updates the LAST response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived('TOP 2 10')\n self._flush()\n s.truncate(0)\n p.lineReceived('LAST')\n self.assertEqual(\n s.getvalue(),\n '+OK 2\\r\\n')\n\n\n def testHighestOnlyProgresses(self):\n \"\"\"\n Test that downloading a message with a smaller index than the current\n LAST response doesn't change the LAST response.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived('RETR 2')\n self._flush()\n p.lineReceived('TOP 1 10')\n self._flush()\n s.truncate(0)\n p.lineReceived('LAST')\n self.assertEqual(\n s.getvalue(),\n '+OK 2\\r\\n')\n\n\n def testResetClearsHighest(self):\n \"\"\"\n Test that issuing RSET changes the LAST response to 0.\n \"\"\"\n p = self.pop3Server\n s = self.pop3Transport\n p.mbox.messages.append(self.extraMessage)\n\n p.lineReceived('RETR 2')\n self._flush()\n p.lineReceived('RSET')\n s.truncate(0)\n p.lineReceived('LAST')\n self.assertEqual(\n s.getvalue(),\n '+OK 0\\r\\n')\n\n\n\n_listMessageDeprecation = (\n \"twisted.mail.pop3.IMailbox.listMessages may not \"\n \"raise IndexError for out-of-bounds message numbers: \"\n \"raise ValueError instead.\")\n_listMessageSuppression = util.suppress(\n message=_listMessageDeprecation,\n category=PendingDeprecationWarning)\n\n_getUidlDeprecation = (\n \"twisted.mail.pop3.IMailbox.getUidl may not \"\n \"raise IndexError for out-of-bounds message numbers: \"\n \"raise ValueError instead.\")\n_getUidlSuppression = util.suppress(\n message=_getUidlDeprecation,\n category=PendingDeprecationWarning)\n\nclass IndexErrorCommandTests(CommandMixin, unittest.TestCase):\n \"\"\"\n Run all of the command tests against a mailbox which raises IndexError\n when an out of bounds request is made. This behavior will be deprecated\n shortly and then removed.\n \"\"\"\n exceptionType = IndexError\n mailboxType = DummyMailbox\n\n def testLISTWithBadArgument(self):\n return CommandMixin.testLISTWithBadArgument(self)\n testLISTWithBadArgument.suppress = [_listMessageSuppression]\n\n\n def testUIDLWithBadArgument(self):\n return CommandMixin.testUIDLWithBadArgument(self)\n testUIDLWithBadArgument.suppress = [_getUidlSuppression]\n\n\n def testTOPWithBadArgument(self):\n return CommandMixin.testTOPWithBadArgument(self)\n testTOPWithBadArgument.suppress = [_listMessageSuppression]\n\n\n def testRETRWithBadArgument(self):\n return CommandMixin.testRETRWithBadArgument(self)\n testRETRWithBadArgument.suppress = [_listMessageSuppression]\n\n\n\nclass ValueErrorCommandTests(CommandMixin, unittest.TestCase):\n \"\"\"\n Run all of the command tests against a mailbox which raises ValueError\n when an out of bounds request is made. This is the correct behavior and\n after support for mailboxes which raise IndexError is removed, this will\n become just C{CommandTestCase}.\n \"\"\"\n exceptionType = ValueError\n mailboxType = DummyMailbox\n\n\n\nclass SyncDeferredMailbox(DummyMailbox):\n \"\"\"\n Mailbox which has a listMessages implementation which returns a Deferred\n which has already fired.\n \"\"\"\n def listMessages(self, n=None):\n return defer.succeed(DummyMailbox.listMessages(self, n))\n\n\n\nclass IndexErrorSyncDeferredCommandTests(IndexErrorCommandTests):\n \"\"\"\n Run all of the L{IndexErrorCommandTests} tests with a\n synchronous-Deferred returning IMailbox implementation.\n \"\"\"\n mailboxType = SyncDeferredMailbox\n\n\n\nclass ValueErrorSyncDeferredCommandTests(ValueErrorCommandTests):\n \"\"\"\n Run all of the L{ValueErrorCommandTests} tests with a\n synchronous-Deferred returning IMailbox implementation.\n \"\"\"\n mailboxType = SyncDeferredMailbox\n\n\n\nclass AsyncDeferredMailbox(DummyMailbox):\n \"\"\"\n Mailbox which has a listMessages implementation which returns a Deferred\n which has not yet fired.\n \"\"\"\n def __init__(self, *a, **kw):\n self.waiting = []\n DummyMailbox.__init__(self, *a, **kw)\n\n\n def listMessages(self, n=None):\n d = defer.Deferred()\n # See AsyncDeferredMailbox._flush\n self.waiting.append((d, DummyMailbox.listMessages(self, n)))\n return d\n\n\n\nclass IndexErrorAsyncDeferredCommandTests(IndexErrorCommandTests):\n \"\"\"\n Run all of the L{IndexErrorCommandTests} tests with an asynchronous-Deferred\n returning IMailbox implementation.\n \"\"\"\n mailboxType = AsyncDeferredMailbox\n\n def _flush(self):\n \"\"\"\n Fire whatever Deferreds we've built up in our mailbox.\n \"\"\"\n while self.pop3Server.mbox.waiting:\n d, a = self.pop3Server.mbox.waiting.pop()\n d.callback(a)\n IndexErrorCommandTests._flush(self)\n\n\n\nclass ValueErrorAsyncDeferredCommandTests(ValueErrorCommandTests):\n \"\"\"\n Run all of the L{IndexErrorCommandTests} tests with an asynchronous-Deferred\n returning IMailbox implementation.\n \"\"\"\n mailboxType = AsyncDeferredMailbox\n\n def _flush(self):\n \"\"\"\n Fire whatever Deferreds we've built up in our mailbox.\n \"\"\"\n while self.pop3Server.mbox.waiting:\n d, a = self.pop3Server.mbox.waiting.pop()\n d.callback(a)\n ValueErrorCommandTests._flush(self)\n\nclass POP3MiscTests(unittest.TestCase):\n \"\"\"\n Miscellaneous tests more to do with module/package structure than\n anything to do with the Post Office Protocol.\n \"\"\"\n def test_all(self):\n \"\"\"\n This test checks that all names listed in\n twisted.mail.pop3.__all__ are actually present in the module.\n \"\"\"\n mod = twisted.mail.pop3\n for attr in mod.__all__:\n self.assertTrue(hasattr(mod, attr))\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-2474074347284726000,"string":"-2,474,074,347,284,726,000"},"line_mean":{"kind":"number","value":27.4584500467,"string":"27.45845"},"line_max":{"kind":"number","value":101,"string":"101"},"alpha_frac":{"kind":"number","value":0.5964434529,"string":"0.596443"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475933,"cells":{"repo_name":{"kind":"string","value":"TrampolineRTOS/trampoline"},"path":{"kind":"string","value":"machines/msp430x/small/msp430fr5994/launchpad/serial/serial.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"2173"},"content":{"kind":"string","value":"#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\nfrom __future__ import print_function\nfrom math import *\n\n# This simple python script computes baud-rate settings\n# for different input frequencies\n\n# The algorithm is extracted from the user's guide\n# (slau367o.pdf), p.776\n# the 2 tabulars fracFreq and ucbrsTab are extracted from \n# table 30-4 of this user's guide\n# tabular DCOfreq gives the frequencies of the DCO from\n# its configuration (dcofsel[3..1] | dcorsel).\n# the algorithm is the one in \"Baud-rate settings quick set up\"\n\n\nfracFreq = [\n\t0.0000, 0.0529, 0.0715, 0.0835,\n\t0.1001, 0.1252, 0.1430, 0.1670,\n\t0.2147, 0.2224, 0.2503, 0.3000,\n\t0.3335, 0.3575, 0.3753, 0.4003,\n\t0.4286, 0.4378, 0.5002, 0.5715,\n\t0.6003, 0.6254, 0.6432, 0.6667,\n\t0.7001, 0.7147, 0.7503, 0.7861,\n\t0.8004, 0.8333, 0.8464, 0.8572,\n\t0.8751, 0.9004, 0.9170, 0.9288]\n\nucbrsTab = [\n\t0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x11,\n\t0x21, 0x22, 0x44, 0x25, 0x49, 0x4A, 0x52, 0x92,\n\t0x53, 0x55, 0xAB, 0x6B, 0xAD, 0xB5, 0xB6, 0xD6,\n\t0xB7, 0xBB, 0xDD, 0xED, 0xEE, 0xBF, 0xDF, 0xEF,\n\t0xF7, 0xFB, 0xFD, 0xFE]\n\n\nDCOfreq = [1000000, 1000000,2670000, 5330000,\n 3500000, 7000000,4000000, 8000000,\n 5330000,16000000,7000000,21000000,\n 8000000,24000000, 0, 0]\n\ndef exportTab(valList,name):\n print('const uint16_t '+name+'[] = {',end='')\n i = 0;\n for val in valList:\n if i != 0:\n print(', ',end='')\n if i%8 == 0:\n print('\\n\\t',end='')\n print(hex(val),end='')\n i = i+1\n print('};')\n\nuartFreq = 9600\nbrw = [] \nmctlw = [] \nfor freq in DCOfreq:\n ucbr = 0\n ucos16 = 0\n ucbrf = 0\n ucbrs = 0\n if freq != 0:\n N = (float)(freq)/uartFreq\n if N > 16:\n ucos16 = 1\n ucbr = (int)(N/16)\n ucbrf = (int)(((N/16)-floor(N/16))*16)\n else:\n ucbr = (int)(N)\n frac = N-floor(N);\n i = 1\n while frac > fracFreq[i]:\n i = i+1\n i = i-1\n ucbrs = ucbrsTab[i]\n #regs\n brw.append(ucbr)\n mctlw.append(ucbrs << 8 | ucbrf << 4 | ucos16)\n\nexportTab(brw, 'tpl_brwTab')\nexportTab(mctlw, 'tpl_mctlwTab')\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":1583848727349696800,"string":"1,583,848,727,349,696,800"},"line_mean":{"kind":"number","value":25.8271604938,"string":"25.82716"},"line_max":{"kind":"number","value":63,"string":"63"},"alpha_frac":{"kind":"number","value":0.5701794754,"string":"0.570179"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475934,"cells":{"repo_name":{"kind":"string","value":"googleapis/googleapis-gen"},"path":{"kind":"string","value":"google/cloud/bigquery/connection/v1/bigquery-connection-v1-py/google/cloud/bigquery_connection_v1/services/connection_service/client.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"49605"},"content":{"kind":"string","value":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom collections import OrderedDict\nfrom distutils import util\nimport os\nimport re\nfrom typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union\nimport pkg_resources\n\nfrom google.api_core import client_options as client_options_lib # type: ignore\nfrom google.api_core import exceptions as core_exceptions # type: ignore\nfrom google.api_core import gapic_v1 # type: ignore\nfrom google.api_core import retry as retries # type: ignore\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport import mtls # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.auth.exceptions import MutualTLSChannelError # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.cloud.bigquery_connection_v1.services.connection_service import pagers\nfrom google.cloud.bigquery_connection_v1.types import connection\nfrom google.cloud.bigquery_connection_v1.types import connection as gcbc_connection\nfrom google.iam.v1 import iam_policy_pb2 # type: ignore\nfrom google.iam.v1 import policy_pb2 # type: ignore\nfrom google.protobuf import field_mask_pb2 # type: ignore\nfrom .transports.base import ConnectionServiceTransport, DEFAULT_CLIENT_INFO\nfrom .transports.grpc import ConnectionServiceGrpcTransport\nfrom .transports.grpc_asyncio import ConnectionServiceGrpcAsyncIOTransport\n\n\nclass ConnectionServiceClientMeta(type):\n \"\"\"Metaclass for the ConnectionService client.\n\n This provides class-level methods for building and retrieving\n support objects (e.g. transport) without polluting the client instance\n objects.\n \"\"\"\n _transport_registry = OrderedDict() # type: Dict[str, Type[ConnectionServiceTransport]]\n _transport_registry[\"grpc\"] = ConnectionServiceGrpcTransport\n _transport_registry[\"grpc_asyncio\"] = ConnectionServiceGrpcAsyncIOTransport\n\n def get_transport_class(cls,\n label: str = None,\n ) -> Type[ConnectionServiceTransport]:\n \"\"\"Returns an appropriate transport class.\n\n Args:\n label: The name of the desired transport. If none is\n provided, then the first transport in the registry is used.\n\n Returns:\n The transport class to use.\n \"\"\"\n # If a specific transport is requested, return that one.\n if label:\n return cls._transport_registry[label]\n\n # No transport is requested; return the default (that is, the first one\n # in the dictionary).\n return next(iter(cls._transport_registry.values()))\n\n\nclass ConnectionServiceClient(metaclass=ConnectionServiceClientMeta):\n \"\"\"Manages external data source connections and credentials.\"\"\"\n\n @staticmethod\n def _get_default_mtls_endpoint(api_endpoint):\n \"\"\"Converts api endpoint to mTLS endpoint.\n\n Convert \"*.sandbox.googleapis.com\" and \"*.googleapis.com\" to\n \"*.mtls.sandbox.googleapis.com\" and \"*.mtls.googleapis.com\" respectively.\n Args:\n api_endpoint (Optional[str]): the api endpoint to convert.\n Returns:\n str: converted mTLS api endpoint.\n \"\"\"\n if not api_endpoint:\n return api_endpoint\n\n mtls_endpoint_re = re.compile(\n r\"(?P[^.]+)(?P\\.mtls)?(?P\\.sandbox)?(?P\\.googleapis\\.com)?\"\n )\n\n m = mtls_endpoint_re.match(api_endpoint)\n name, mtls, sandbox, googledomain = m.groups()\n if mtls or not googledomain:\n return api_endpoint\n\n if sandbox:\n return api_endpoint.replace(\n \"sandbox.googleapis.com\", \"mtls.sandbox.googleapis.com\"\n )\n\n return api_endpoint.replace(\".googleapis.com\", \".mtls.googleapis.com\")\n\n DEFAULT_ENDPOINT = \"bigqueryconnection.googleapis.com\"\n DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore\n DEFAULT_ENDPOINT\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n ConnectionServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_info(info)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n ConnectionServiceClient: The constructed client.\n \"\"\"\n credentials = service_account.Credentials.from_service_account_file(\n filename)\n kwargs[\"credentials\"] = credentials\n return cls(*args, **kwargs)\n\n from_service_account_json = from_service_account_file\n\n @property\n def transport(self) -> ConnectionServiceTransport:\n \"\"\"Returns the transport used by the client instance.\n\n Returns:\n ConnectionServiceTransport: The transport used by the client\n instance.\n \"\"\"\n return self._transport\n\n @staticmethod\n def connection_path(project: str,location: str,connection: str,) -> str:\n \"\"\"Returns a fully-qualified connection string.\"\"\"\n return \"projects/{project}/locations/{location}/connections/{connection}\".format(project=project, location=location, connection=connection, )\n\n @staticmethod\n def parse_connection_path(path: str) -> Dict[str,str]:\n \"\"\"Parses a connection path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)/locations/(?P.+?)/connections/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_billing_account_path(billing_account: str, ) -> str:\n \"\"\"Returns a fully-qualified billing_account string.\"\"\"\n return \"billingAccounts/{billing_account}\".format(billing_account=billing_account, )\n\n @staticmethod\n def parse_common_billing_account_path(path: str) -> Dict[str,str]:\n \"\"\"Parse a billing_account path into its component segments.\"\"\"\n m = re.match(r\"^billingAccounts/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_folder_path(folder: str, ) -> str:\n \"\"\"Returns a fully-qualified folder string.\"\"\"\n return \"folders/{folder}\".format(folder=folder, )\n\n @staticmethod\n def parse_common_folder_path(path: str) -> Dict[str,str]:\n \"\"\"Parse a folder path into its component segments.\"\"\"\n m = re.match(r\"^folders/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_organization_path(organization: str, ) -> str:\n \"\"\"Returns a fully-qualified organization string.\"\"\"\n return \"organizations/{organization}\".format(organization=organization, )\n\n @staticmethod\n def parse_common_organization_path(path: str) -> Dict[str,str]:\n \"\"\"Parse a organization path into its component segments.\"\"\"\n m = re.match(r\"^organizations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_project_path(project: str, ) -> str:\n \"\"\"Returns a fully-qualified project string.\"\"\"\n return \"projects/{project}\".format(project=project, )\n\n @staticmethod\n def parse_common_project_path(path: str) -> Dict[str,str]:\n \"\"\"Parse a project path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n @staticmethod\n def common_location_path(project: str, location: str, ) -> str:\n \"\"\"Returns a fully-qualified location string.\"\"\"\n return \"projects/{project}/locations/{location}\".format(project=project, location=location, )\n\n @staticmethod\n def parse_common_location_path(path: str) -> Dict[str,str]:\n \"\"\"Parse a location path into its component segments.\"\"\"\n m = re.match(r\"^projects/(?P.+?)/locations/(?P.+?)$\", path)\n return m.groupdict() if m else {}\n\n def __init__(self, *,\n credentials: Optional[ga_credentials.Credentials] = None,\n transport: Union[str, ConnectionServiceTransport, None] = None,\n client_options: Optional[client_options_lib.ClientOptions] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n ) -> None:\n \"\"\"Instantiates the connection service client.\n\n Args:\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n transport (Union[str, ConnectionServiceTransport]): The\n transport to use. If set to None, a transport is chosen\n automatically.\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. It won't take effect if a ``transport`` instance is provided.\n (1) The ``api_endpoint`` property can be used to override the\n default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT\n environment variable can also be used to override the endpoint:\n \"always\" (always use the default mTLS endpoint), \"never\" (always\n use the default regular endpoint) and \"auto\" (auto switch to the\n default mTLS endpoint if client certificate is present, this is\n the default value). However, the ``api_endpoint`` property takes\n precedence if provided.\n (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable\n is \"true\", then the ``client_cert_source`` property can be used\n to provide client certificate for mutual TLS transport. If\n not provided, the default SSL client certificate will be used if\n present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is \"false\" or not\n set, no client certificate will be used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n \"\"\"\n if isinstance(client_options, dict):\n client_options = client_options_lib.from_dict(client_options)\n if client_options is None:\n client_options = client_options_lib.ClientOptions()\n\n # Create SSL credentials for mutual TLS if needed.\n use_client_cert = bool(util.strtobool(os.getenv(\"GOOGLE_API_USE_CLIENT_CERTIFICATE\", \"false\")))\n\n client_cert_source_func = None\n is_mtls = False\n if use_client_cert:\n if client_options.client_cert_source:\n is_mtls = True\n client_cert_source_func = client_options.client_cert_source\n else:\n is_mtls = mtls.has_default_client_cert_source()\n if is_mtls:\n client_cert_source_func = mtls.default_client_cert_source()\n else:\n client_cert_source_func = None\n\n # Figure out which api endpoint to use.\n if client_options.api_endpoint is not None:\n api_endpoint = client_options.api_endpoint\n else:\n use_mtls_env = os.getenv(\"GOOGLE_API_USE_MTLS_ENDPOINT\", \"auto\")\n if use_mtls_env == \"never\":\n api_endpoint = self.DEFAULT_ENDPOINT\n elif use_mtls_env == \"always\":\n api_endpoint = self.DEFAULT_MTLS_ENDPOINT\n elif use_mtls_env == \"auto\":\n if is_mtls:\n api_endpoint = self.DEFAULT_MTLS_ENDPOINT\n else:\n api_endpoint = self.DEFAULT_ENDPOINT\n else:\n raise MutualTLSChannelError(\n \"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted \"\n \"values: never, auto, always\"\n )\n\n # Save or instantiate the transport.\n # Ordinarily, we provide the transport, but allowing a custom transport\n # instance provides an extensibility point for unusual situations.\n if isinstance(transport, ConnectionServiceTransport):\n # transport is a ConnectionServiceTransport instance.\n if credentials or client_options.credentials_file:\n raise ValueError(\"When providing a transport instance, \"\n \"provide its credentials directly.\")\n if client_options.scopes:\n raise ValueError(\n \"When providing a transport instance, provide its scopes \"\n \"directly.\"\n )\n self._transport = transport\n else:\n Transport = type(self).get_transport_class(transport)\n self._transport = Transport(\n credentials=credentials,\n credentials_file=client_options.credentials_file,\n host=api_endpoint,\n scopes=client_options.scopes,\n client_cert_source_for_mtls=client_cert_source_func,\n quota_project_id=client_options.quota_project_id,\n client_info=client_info,\n )\n\n def create_connection(self,\n request: gcbc_connection.CreateConnectionRequest = None,\n *,\n parent: str = None,\n connection: gcbc_connection.Connection = None,\n connection_id: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> gcbc_connection.Connection:\n r\"\"\"Creates a new connection.\n\n Args:\n request (google.cloud.bigquery_connection_v1.types.CreateConnectionRequest):\n The request object. The request for\n [ConnectionService.CreateConnection][google.cloud.bigquery.connection.v1.ConnectionService.CreateConnection].\n parent (str):\n Required. Parent resource name. Must be in the format\n ``projects/{project_id}/locations/{location_id}``\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n connection (google.cloud.bigquery_connection_v1.types.Connection):\n Required. Connection to create.\n This corresponds to the ``connection`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n connection_id (str):\n Optional. Connection id that should\n be assigned to the created connection.\n\n This corresponds to the ``connection_id`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.bigquery_connection_v1.types.Connection:\n Configuration parameters to establish\n connection with an external data source,\n except the credential attributes.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent, connection, connection_id])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n # Minor optimization to avoid making a copy if the user passes\n # in a gcbc_connection.CreateConnectionRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, gcbc_connection.CreateConnectionRequest):\n request = gcbc_connection.CreateConnectionRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n if connection is not None:\n request.connection = connection\n if connection_id is not None:\n request.connection_id = connection_id\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.create_connection]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"parent\", request.parent),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def get_connection(self,\n request: connection.GetConnectionRequest = None,\n *,\n name: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> connection.Connection:\n r\"\"\"Returns specified connection.\n\n Args:\n request (google.cloud.bigquery_connection_v1.types.GetConnectionRequest):\n The request object. The request for\n [ConnectionService.GetConnection][google.cloud.bigquery.connection.v1.ConnectionService.GetConnection].\n name (str):\n Required. Name of the requested connection, for example:\n ``projects/{project_id}/locations/{location_id}/connections/{connection_id}``\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.bigquery_connection_v1.types.Connection:\n Configuration parameters to establish\n connection with an external data source,\n except the credential attributes.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n # Minor optimization to avoid making a copy if the user passes\n # in a connection.GetConnectionRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, connection.GetConnectionRequest):\n request = connection.GetConnectionRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_connection]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"name\", request.name),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def list_connections(self,\n request: connection.ListConnectionsRequest = None,\n *,\n parent: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> pagers.ListConnectionsPager:\n r\"\"\"Returns a list of connections in the given project.\n\n Args:\n request (google.cloud.bigquery_connection_v1.types.ListConnectionsRequest):\n The request object. The request for\n [ConnectionService.ListConnections][google.cloud.bigquery.connection.v1.ConnectionService.ListConnections].\n parent (str):\n Required. Parent resource name. Must be in the form:\n ``projects/{project_id}/locations/{location_id}``\n\n This corresponds to the ``parent`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.bigquery_connection_v1.services.connection_service.pagers.ListConnectionsPager:\n The response for\n [ConnectionService.ListConnections][google.cloud.bigquery.connection.v1.ConnectionService.ListConnections].\n\n Iterating over this object will yield results and\n resolve additional pages automatically.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([parent])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n # Minor optimization to avoid making a copy if the user passes\n # in a connection.ListConnectionsRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, connection.ListConnectionsRequest):\n request = connection.ListConnectionsRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if parent is not None:\n request.parent = parent\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.list_connections]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"parent\", request.parent),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # This method is paged; wrap the response in a pager, which provides\n # an `__iter__` convenience method.\n response = pagers.ListConnectionsPager(\n method=rpc,\n request=request,\n response=response,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def update_connection(self,\n request: gcbc_connection.UpdateConnectionRequest = None,\n *,\n name: str = None,\n connection: gcbc_connection.Connection = None,\n update_mask: field_mask_pb2.FieldMask = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> gcbc_connection.Connection:\n r\"\"\"Updates the specified connection. For security\n reasons, also resets credential if connection properties\n are in the update field mask.\n\n Args:\n request (google.cloud.bigquery_connection_v1.types.UpdateConnectionRequest):\n The request object. The request for\n [ConnectionService.UpdateConnection][google.cloud.bigquery.connection.v1.ConnectionService.UpdateConnection].\n name (str):\n Required. Name of the connection to update, for example:\n ``projects/{project_id}/locations/{location_id}/connections/{connection_id}``\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n connection (google.cloud.bigquery_connection_v1.types.Connection):\n Required. Connection containing the\n updated fields.\n\n This corresponds to the ``connection`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n update_mask (google.protobuf.field_mask_pb2.FieldMask):\n Required. Update mask for the\n connection fields to be updated.\n\n This corresponds to the ``update_mask`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.bigquery_connection_v1.types.Connection:\n Configuration parameters to establish\n connection with an external data source,\n except the credential attributes.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name, connection, update_mask])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n # Minor optimization to avoid making a copy if the user passes\n # in a gcbc_connection.UpdateConnectionRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, gcbc_connection.UpdateConnectionRequest):\n request = gcbc_connection.UpdateConnectionRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n if connection is not None:\n request.connection = connection\n if update_mask is not None:\n request.update_mask = update_mask\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.update_connection]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"name\", request.name),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def delete_connection(self,\n request: connection.DeleteConnectionRequest = None,\n *,\n name: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> None:\n r\"\"\"Deletes connection and associated credential.\n\n Args:\n request (google.cloud.bigquery_connection_v1.types.DeleteConnectionRequest):\n The request object. The request for\n [ConnectionService.DeleteConnectionRequest][].\n name (str):\n Required. Name of the deleted connection, for example:\n ``projects/{project_id}/locations/{location_id}/connections/{connection_id}``\n\n This corresponds to the ``name`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n # Minor optimization to avoid making a copy if the user passes\n # in a connection.DeleteConnectionRequest.\n # There's no risk of modifying the input as we've already verified\n # there are no flattened fields.\n if not isinstance(request, connection.DeleteConnectionRequest):\n request = connection.DeleteConnectionRequest(request)\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.delete_connection]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"name\", request.name),\n )),\n )\n\n # Send the request.\n rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n def get_iam_policy(self,\n request: iam_policy_pb2.GetIamPolicyRequest = None,\n *,\n resource: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> policy_pb2.Policy:\n r\"\"\"Gets the access control policy for a resource.\n Returns an empty policy if the resource exists and does\n not have a policy set.\n\n Args:\n request (google.iam.v1.iam_policy_pb2.GetIamPolicyRequest):\n The request object. Request message for `GetIamPolicy`\n method.\n resource (str):\n REQUIRED: The resource for which the\n policy is being requested. See the\n operation documentation for the\n appropriate value for this field.\n\n This corresponds to the ``resource`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.iam.v1.policy_pb2.Policy:\n Defines an Identity and Access Management (IAM) policy. It is used to\n specify access control policies for Cloud Platform\n resources.\n\n A Policy is a collection of bindings. A binding binds\n one or more members to a single role. Members can be\n user accounts, service accounts, Google groups, and\n domains (such as G Suite). A role is a named list of\n permissions (defined by IAM or configured by users).\n A binding can optionally specify a condition, which\n is a logic expression that further constrains the\n role binding based on attributes about the request\n and/or target resource.\n\n **JSON Example**\n\n {\n \"bindings\": [\n {\n \"role\":\n \"roles/resourcemanager.organizationAdmin\",\n \"members\": [ \"user:mike@example.com\",\n \"group:admins@example.com\",\n \"domain:google.com\",\n \"serviceAccount:my-project-id@appspot.gserviceaccount.com\"\n ]\n\n }, { \"role\":\n \"roles/resourcemanager.organizationViewer\",\n \"members\": [\"user:eve@example.com\"],\n \"condition\": { \"title\": \"expirable access\",\n \"description\": \"Does not grant access after\n Sep 2020\", \"expression\": \"request.time <\n timestamp('2020-10-01T00:00:00.000Z')\", } }\n\n ]\n\n }\n\n **YAML Example**\n\n bindings: - members: - user:\\ mike@example.com -\n group:\\ admins@example.com - domain:google.com -\n serviceAccount:\\ my-project-id@appspot.gserviceaccount.com\n role: roles/resourcemanager.organizationAdmin -\n members: - user:\\ eve@example.com role:\n roles/resourcemanager.organizationViewer\n condition: title: expirable access description:\n Does not grant access after Sep 2020 expression:\n request.time <\n timestamp('2020-10-01T00:00:00.000Z')\n\n For a description of IAM and its features, see the\n [IAM developer's\n guide](\\ https://cloud.google.com/iam/docs).\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([resource])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n if isinstance(request, dict):\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n request = iam_policy_pb2.GetIamPolicyRequest(**request)\n elif not request:\n # Null request, just make one.\n request = iam_policy_pb2.GetIamPolicyRequest()\n if resource is not None:\n request.resource = resource\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"resource\", request.resource),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def set_iam_policy(self,\n request: iam_policy_pb2.SetIamPolicyRequest = None,\n *,\n resource: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> policy_pb2.Policy:\n r\"\"\"Sets the access control policy on the specified resource.\n Replaces any existing policy.\n\n Can return ``NOT_FOUND``, ``INVALID_ARGUMENT``, and\n ``PERMISSION_DENIED`` errors.\n\n Args:\n request (google.iam.v1.iam_policy_pb2.SetIamPolicyRequest):\n The request object. Request message for `SetIamPolicy`\n method.\n resource (str):\n REQUIRED: The resource for which the\n policy is being specified. See the\n operation documentation for the\n appropriate value for this field.\n\n This corresponds to the ``resource`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.iam.v1.policy_pb2.Policy:\n Defines an Identity and Access Management (IAM) policy. It is used to\n specify access control policies for Cloud Platform\n resources.\n\n A Policy is a collection of bindings. A binding binds\n one or more members to a single role. Members can be\n user accounts, service accounts, Google groups, and\n domains (such as G Suite). A role is a named list of\n permissions (defined by IAM or configured by users).\n A binding can optionally specify a condition, which\n is a logic expression that further constrains the\n role binding based on attributes about the request\n and/or target resource.\n\n **JSON Example**\n\n {\n \"bindings\": [\n {\n \"role\":\n \"roles/resourcemanager.organizationAdmin\",\n \"members\": [ \"user:mike@example.com\",\n \"group:admins@example.com\",\n \"domain:google.com\",\n \"serviceAccount:my-project-id@appspot.gserviceaccount.com\"\n ]\n\n }, { \"role\":\n \"roles/resourcemanager.organizationViewer\",\n \"members\": [\"user:eve@example.com\"],\n \"condition\": { \"title\": \"expirable access\",\n \"description\": \"Does not grant access after\n Sep 2020\", \"expression\": \"request.time <\n timestamp('2020-10-01T00:00:00.000Z')\", } }\n\n ]\n\n }\n\n **YAML Example**\n\n bindings: - members: - user:\\ mike@example.com -\n group:\\ admins@example.com - domain:google.com -\n serviceAccount:\\ my-project-id@appspot.gserviceaccount.com\n role: roles/resourcemanager.organizationAdmin -\n members: - user:\\ eve@example.com role:\n roles/resourcemanager.organizationViewer\n condition: title: expirable access description:\n Does not grant access after Sep 2020 expression:\n request.time <\n timestamp('2020-10-01T00:00:00.000Z')\n\n For a description of IAM and its features, see the\n [IAM developer's\n guide](\\ https://cloud.google.com/iam/docs).\n\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([resource])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n if isinstance(request, dict):\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n request = iam_policy_pb2.SetIamPolicyRequest(**request)\n elif not request:\n # Null request, just make one.\n request = iam_policy_pb2.SetIamPolicyRequest()\n if resource is not None:\n request.resource = resource\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"resource\", request.resource),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n def test_iam_permissions(self,\n request: iam_policy_pb2.TestIamPermissionsRequest = None,\n *,\n resource: str = None,\n permissions: Sequence[str] = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> iam_policy_pb2.TestIamPermissionsResponse:\n r\"\"\"Returns permissions that a caller has on the specified resource.\n If the resource does not exist, this will return an empty set of\n permissions, not a ``NOT_FOUND`` error.\n\n Note: This operation is designed to be used for building\n permission-aware UIs and command-line tools, not for\n authorization checking. This operation may \"fail open\" without\n warning.\n\n Args:\n request (google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest):\n The request object. Request message for\n `TestIamPermissions` method.\n resource (str):\n REQUIRED: The resource for which the\n policy detail is being requested. See\n the operation documentation for the\n appropriate value for this field.\n\n This corresponds to the ``resource`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n permissions (Sequence[str]):\n The set of permissions to check for the ``resource``.\n Permissions with wildcards (such as '*' or 'storage.*')\n are not allowed. For more information see `IAM\n Overview `__.\n\n This corresponds to the ``permissions`` field\n on the ``request`` instance; if ``request`` is provided, this\n should not be set.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:\n Response message for TestIamPermissions method.\n \"\"\"\n # Create or coerce a protobuf request object.\n # Sanity check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([resource, permissions])\n if request is not None and has_flattened_params:\n raise ValueError('If the `request` argument is set, then none of '\n 'the individual field arguments should be set.')\n\n if isinstance(request, dict):\n # The request isn't a proto-plus wrapped type,\n # so it must be constructed via keyword expansion.\n request = iam_policy_pb2.TestIamPermissionsRequest(**request)\n elif not request:\n # Null request, just make one.\n request = iam_policy_pb2.TestIamPermissionsRequest()\n if resource is not None:\n request.resource = resource\n if permissions:\n request.permissions.extend(permissions)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata((\n (\"resource\", request.resource),\n )),\n )\n\n # Send the request.\n response = rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n\n\n\n\ntry:\n DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=pkg_resources.get_distribution(\n \"google-cloud-bigquery-connection\",\n ).version,\n )\nexcept pkg_resources.DistributionNotFound:\n DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()\n\n\n__all__ = (\n \"ConnectionServiceClient\",\n)\n"},"license":{"kind":"string","value":"apache-2.0"},"hash":{"kind":"number","value":2099994186533660400,"string":"2,099,994,186,533,660,400"},"line_mean":{"kind":"number","value":42.8206713781,"string":"42.820671"},"line_max":{"kind":"number","value":149,"string":"149"},"alpha_frac":{"kind":"number","value":0.5891744784,"string":"0.589174"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475935,"cells":{"repo_name":{"kind":"string","value":"cd334/hangoutsbot"},"path":{"kind":"string","value":"hangupsbot/plugins/forecast.py"},"copies":{"kind":"string","value":"2"},"size":{"kind":"string","value":"9901"},"content":{"kind":"string","value":"\"\"\"\nUse forecast.io to get current weather forecast for a given location.\n\nInstructions:\n * Get an API key from https://developer.forecast.io/\n * Store API key in config.json:forecast_api_key\n\"\"\"\nimport logging\nimport plugins\nimport requests\nfrom decimal import Decimal\n\nlogger = logging.getLogger(__name__)\n_internal = {}\n\ndef _initialize(bot):\n api_key = bot.get_config_option('forecast_api_key')\n if api_key:\n _internal['forecast_api_key'] = api_key\n plugins.register_user_command(['weather', 'forecast'])\n plugins.register_admin_command(['setweatherlocation'])\n else:\n logger.error('WEATHER: config[\"forecast_api_key\"] required')\n\ndef setweatherlocation(bot, event, *args):\n \"\"\"Sets the Lat Long default coordinates for this hangout when polling for weather data\n /bot setWeatherLocation \n \"\"\"\n location = ''.join(args).strip()\n if not location:\n yield from bot.coro_send_message(event.conv_id, _('No location was specified, please specify a location.'))\n return\n \n location = _lookup_address(location)\n if location is None:\n yield from bot.coro_send_message(event.conv_id, _('Unable to find the specified location.'))\n return\n \n if not bot.memory.exists([\"conv_data\", event.conv.id_]):\n bot.memory.set_by_path(['conv_data', event.conv.id_], {})\n\n bot.memory.set_by_path([\"conv_data\", event.conv.id_, \"default_weather_location\"], {'lat': location['lat'], 'lng': location['lng']})\n bot.memory.save()\n yield from bot.coro_send_message(event.conv_id, _('This hangouts default location has been set to {}.'.format(location)))\n\ndef weather(bot, event, *args):\n \"\"\"Returns weather information from Forecast.io\n /bot weather Get location's current weather.\n /bot weather Get the hangouts default location's current weather. If the default location is not set talk to a hangout admin.\n \"\"\"\n weather = _get_weather(bot, event, args)\n if weather:\n yield from bot.coro_send_message(event.conv_id, _format_current_weather(weather))\n else:\n yield from bot.coro_send_message(event.conv_id, 'There was an error retrieving the weather, guess you need to look outside.')\n\ndef forecast(bot, event, *args):\n \"\"\"Returns a brief textual forecast from Forecast.io\n /bot weather Get location's current forecast.\n /bot weather Get the hangouts default location's forecast. If default location is not set talk to a hangout admin.\n \"\"\"\n weather = _get_weather(bot, event, args)\n if weather:\n yield from bot.coro_send_message(event.conv_id, _format_forecast_weather(weather))\n else:\n yield from bot.coro_send_message(event.conv_id, 'There was an error retrieving the weather, guess you need to look outside.')\n \ndef _format_current_weather(weather):\n \"\"\"\n Formats the current weather data for the user.\n \"\"\"\n weatherStrings = [] \n if 'temperature' in weather:\n weatherStrings.append(\"It is currently: {0}°{1}\".format(round(weather['temperature'],2),weather['units']['temperature']))\n if 'summary' in weather:\n weatherStrings.append(\"{0}\".format(weather['summary']))\n if 'feelsLike' in weather:\n weatherStrings.append(\"Feels Like: {0}°{1}\".format(round(weather['feelsLike'],2),weather['units']['temperature']))\n if 'windspeed' in weather:\n weatherStrings.append(\"Wind: {0} {1} from {2}\".format(round(weather['windspeed'],2), weather['units']['windSpeed'], _get_wind_direction(weather['windbearing'])))\n if 'humidity' in weather:\n weatherStrings.append(\"Humidity: {0}%\".format(weather['humidity']))\n if 'pressure' in weather:\n weatherStrings.append(\"Pressure: {0} {1}\".format(round(weather['pressure'],2), weather['units']['pressure']))\n \n return \"
\".join(weatherStrings)\n\ndef _format_forecast_weather(weather):\n \"\"\"\n Formats the forecast data for the user.\n \"\"\"\n weatherStrings = []\n if 'hourly' in weather:\n weatherStrings.append(\"Next 24 Hours
{}\". format(weather['hourly']))\n if 'daily' in weather:\n weatherStrings.append(\"Next 7 Days
{}\". format(weather['daily']))\n \n return \"
\".join(weatherStrings)\n\ndef _lookup_address(location):\n \"\"\"\n Retrieve the coordinates of the location from googles geocode api.\n Limit of 2,000 requests a day\n \"\"\"\n google_map_url = 'https://maps.googleapis.com/maps/api/geocode/json'\n payload = {'address': location}\n resp = requests.get(google_map_url, params=payload)\n try:\n resp.raise_for_status()\n results = resp.json()['results'][0]\n return {\n 'lat': results['geometry']['location']['lat'],\n 'lng': results['geometry']['location']['lng'],\n 'address': results['formatted_address']\n }\n except (IndexError, KeyError):\n logger.error('unable to parse address return data: %d: %s', resp.status_code, resp.json())\n return None\n except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout):\n logger.error('unable to connect with maps.googleapis.com: %d - %s', resp.status_code, resp.text)\n return None\n\ndef _lookup_weather(coords):\n \"\"\"\n Retrieve the current forecast for the specified coordinates from forecast.io\n Limit of 1,000 requests a day\n \"\"\"\n\n forecast_io_url = 'https://api.forecast.io/forecast/{0}/{1},{2}?units=auto'.format(_internal['forecast_api_key'],coords['lat'], coords['lng'])\n r = requests.get(forecast_io_url)\n\n try:\n j = r.json()\n current = {\n 'time' : j['currently']['time'],\n 'summary': j['currently']['summary'],\n 'temperature': Decimal(j['currently']['temperature']),\n 'feelsLike': Decimal(j['currently']['apparentTemperature']),\n 'units': _get_forcast_units(j),\n 'humidity': int(j['currently']['humidity']*100),\n 'windspeed' : Decimal(j['currently']['windSpeed']),\n 'windbearing' : j['currently']['windBearing'],\n 'pressure' : j['currently']['pressure']\n }\n if current['units']['pressure'] == 'kPa':\n current['pressure'] = Decimal(current['pressure']/10)\n \n if 'hourly' in j:\n current['hourly'] = j['hourly']['summary']\n if 'daily' in j:\n current['daily'] = j['daily']['summary']\n \n except ValueError as e:\n logger.error(\"Forecast Error: {}\".format(e))\n current = dict()\n except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError, requests.exceptions.Timeout):\n logger.error('unable to connect with api.forecast.io: %d - %s', resp.status_code, resp.text)\n return None\n\n return current\n\ndef _get_weather(bot,event,params):\n \"\"\" \n Checks memory for a default location set for the current hangout.\n If one is not found and parameters were specified attempts to look up a location. \n If it finds a location it then attempts to load the weather data\n \"\"\"\n parameters = list(params)\n location = {}\n \n if not parameters:\n if bot.memory.exists([\"conv_data\", event.conv.id_]):\n if(bot.memory.exists([\"conv_data\", event.conv.id_, \"default_weather_location\"])):\n location = bot.memory.get_by_path([\"conv_data\", event.conv.id_, \"default_weather_location\"])\n else:\n address = ''.join(parameters).strip()\n location = _lookup_address(address)\n \n if location:\n return _lookup_weather(location)\n \n return {}\n\ndef _get_forcast_units(result):\n \"\"\"\n Checks to see what uni the results were passed back as and sets the display units accordingly\n \"\"\"\n units = {\n 'temperature': 'F',\n 'distance': 'Miles',\n 'percipIntensity': 'in./hr.',\n 'precipAccumulation': 'inches',\n 'windSpeed': 'mph',\n 'pressure': 'millibars'\n }\n if result['flags']:\n unit = result['flags']['units']\n if unit != 'us':\n units['temperature'] = 'C'\n units['distance'] = 'KM'\n units['percipIntensity'] = 'milimeters per hour'\n units['precipAccumulation'] = 'centimeters'\n units['windSpeed'] = 'm/s'\n units['pressure'] = 'kPa'\n if unit == 'ca':\n units['windSpeed'] = 'km/h'\n if unit == 'uk2':\n units['windSpeed'] = 'mph'\n units['distance'] = 'Miles'\n return units\n\ndef _get_wind_direction(degrees):\n \"\"\"\n Determines the direction the wind is blowing from based off the degree passed from the API\n 0 degrees is true north\n \"\"\"\n directionText = \"N\"\n if degrees >= 5 and degrees < 40:\n directionText = \"NNE\"\n elif degrees >= 40 and degrees < 50:\n directionText = \"NE\"\n elif degrees >= 50 and degrees < 85:\n directionText = \"ENE\"\n elif degrees >= 85 and degrees < 95:\n directionText = \"E\"\n elif degrees >= 95 and degrees < 130:\n directionText = \"ESE\"\n elif degrees >= 130 and degrees < 140:\n directionText = \"SE\"\n elif degrees >= 140 and degrees < 175:\n directionText = \"SSE\"\n elif degrees >= 175 and degrees < 185:\n directionText = \"S\"\n elif degrees >= 185 and degrees < 220:\n directionText = \"SSW\"\n elif degrees >= 220 and degrees < 230:\n directionText = \"SW\"\n elif degrees >= 230 and degrees < 265:\n directionText = \"WSW\"\n elif degrees >= 265 and degrees < 275:\n directionText = \"W\"\n elif degrees >= 275 and degrees < 310:\n directionText = \"WNW\"\n elif degrees >= 310 and degrees < 320:\n directionText = \"NW\"\n elif degrees >= 320 and degrees < 355:\n directionText = \"NNW\"\n \n return directionText\n "},"license":{"kind":"string","value":"agpl-3.0"},"hash":{"kind":"number","value":-6699385779283329000,"string":"-6,699,385,779,283,329,000"},"line_mean":{"kind":"number","value":38.6,"string":"38.6"},"line_max":{"kind":"number","value":169,"string":"169"},"alpha_frac":{"kind":"number","value":0.6189514092,"string":"0.618951"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475936,"cells":{"repo_name":{"kind":"string","value":"gemrb/gemrb"},"path":{"kind":"string","value":"gemrb/GUIScripts/pst/GUIREC.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"37975"},"content":{"kind":"string","value":"# -*-python-*-\n# GemRB - Infinity Engine Emulator\n# Copyright (C) 2003 The GemRB Project\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\n\n# GUIREC.py - scripts to control stats/records windows from GUIREC winpack\n\n# GUIREC:\n# 0,1,2 - common windows (time, message, menu)\n# 3 - main statistics window\n# 4 - level up win\n# 5 - info - kills, weapons ...\n# 6 - dual class list ???\n# 7 - class panel\n# 8 - skills panel\n# 9 - choose mage spells panel\n# 10 - some small win, 1 button\n# 11 - some small win, 2 buttons\n# 12 - biography?\n# 13 - specialist mage panel\n# 14 - proficiencies\n# 15 - some 2 panel window\n# 16 - some 2 panel window\n# 17 - some 2 panel window\n\n\n# MainWindow:\n# 0 - main textarea\n# 1 - its scrollbar\n# 2 - WMCHRP character portrait\n# 5 - STALIGN alignment\n# 6 - STFCTION faction\n# 7,8,9 - STCSTM (info, reform party, level up)\n# 0x1000000a - name\n#0x1000000b - ac\n#0x1000000c, 0x1000000d hp now, hp max\n#0x1000000e str\n#0x1000000f int\n#0x10000010 wis\n#0x10000011 dex\n#0x10000012 con\n#0x10000013 chr\n#x10000014 race\n#x10000015 sex\n#0x10000016 class\n\n#31-36 stat buts\n#37 ac but\n#38 hp but?\n\n###################################################\nimport GemRB\nimport GUICommon\nimport CommonTables\nimport LevelUp\nimport LUCommon\nimport GUICommonWindows\nimport NewLife\nfrom GUIDefines import *\nfrom ie_stats import *\nimport GUIWORLD\nimport LUSkillsSelection\n\n###################################################\nLevelUpWindow = None\nRecordsWindow = None\nInformationWindow = None\nBiographyWindow = None\n\n###################################################\n\nLevelDiff = 0\nLevel = 0\nClasses = 0\nNumClasses = 0\n\n###################################################\n\ndef InitRecordsWindow (Window):\n\tglobal RecordsWindow\n\tglobal StatTable\n\n\tRecordsWindow = Window\n\tStatTable = GemRB.LoadTable(\"abcomm\")\n\n\t# Information\n\tButton = Window.GetControl (7)\n\tButton.SetText (4245)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, OpenInformationWindow)\n\n\t# Reform Party\n\tButton = Window.GetControl (8)\n\tButton.SetText (4244)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, GUIWORLD.OpenReformPartyWindow)\n\n\t# Level Up\n\tButton = Window.GetControl (9)\n\tButton.SetText (4246)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, OpenLevelUpWindow)\n\n\tstatevents = (OnRecordsHelpStrength, OnRecordsHelpIntelligence, OnRecordsHelpWisdom, OnRecordsHelpDexterity, OnRecordsHelpConstitution, OnRecordsHelpCharisma)\n\t# stat buttons\n\tfor i in range (6):\n\t\tButton = Window.GetControl (31 + i)\n\t\tButton.SetFlags(IE_GUI_BUTTON_NO_IMAGE, OP_SET)\n\t\tButton.SetSprites(\"\", 0, 0, 0, 0, 0)\n\t\tButton.SetState (IE_GUI_BUTTON_LOCKED)\n\t\tButton.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, statevents[i])\n\t\tButton.SetEvent (IE_GUI_MOUSE_LEAVE_BUTTON, OnRecordsButtonLeave)\n\n\t# AC button\n\tButton = Window.GetControl (37)\n\tButton.SetFlags(IE_GUI_BUTTON_NO_IMAGE, OP_SET)\n\tButton.SetSprites(\"\", 0, 0, 0, 0, 0)\n\tButton.SetState (IE_GUI_BUTTON_LOCKED)\n\tButton.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, OnRecordsHelpArmorClass)\n\tButton.SetEvent (IE_GUI_MOUSE_LEAVE_BUTTON, OnRecordsButtonLeave)\n\n\n\t# HP button\n\tButton = Window.GetControl (38)\n\tButton.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_SET)\n\tButton.SetSprites (\"\", 0, 0, 0, 0, 0)\n\tButton.SetState (IE_GUI_BUTTON_LOCKED)\n\tButton.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, OnRecordsHelpHitPoints)\n\tButton.SetEvent (IE_GUI_MOUSE_LEAVE_BUTTON, OnRecordsButtonLeave)\n\n\treturn\n\n\nstats_overview = None\nfaction_help = ''\nalignment_help = ''\navatar_header = {'PrimClass': \"\", 'SecoClass': \"\", 'PrimLevel': 0, 'SecoLevel': 0, 'XP': 0, 'PrimNextLevXP': 0, 'SecoNextLevXP': 0}\n\ndef UpdateRecordsWindow (Window):\n\tglobal stats_overview, faction_help, alignment_help\n\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Setting up the character information\n\tGetCharacterHeader (pc)\n\n\t# Checking whether character has leveled up.\n\tButton = Window.GetControl (9)\n\tif LUCommon.CanLevelUp (pc):\n\t\tButton.SetState (IE_GUI_BUTTON_ENABLED)\n\telse:\n\t\tButton.SetState (IE_GUI_BUTTON_DISABLED)\n\n\t# name\n\tLabel = Window.GetControl (0x1000000a)\n\tLabel.SetText (GemRB.GetPlayerName (pc, 1))\n\n\t# portrait\n\tImage = Window.GetControl (2)\n\tImage.SetState (IE_GUI_BUTTON_LOCKED)\n\tImage.SetFlags(IE_GUI_BUTTON_NO_IMAGE | IE_GUI_BUTTON_PICTURE, OP_SET)\n\tImage.SetPicture (GUICommonWindows.GetActorPortrait (pc, 'STATS'))\n\n\t# armorclass\n\tLabel = Window.GetControl (0x1000000b)\n\tLabel.SetText (str (GemRB.GetPlayerStat (pc, IE_ARMORCLASS)))\n\tLabel.SetTooltip (4197)\n\n\t# hp now\n\tLabel = Window.GetControl (0x1000000c)\n\tLabel.SetText (str (GemRB.GetPlayerStat (pc, IE_HITPOINTS)))\n\tLabel.SetTooltip (4198)\n\n\t# hp max\n\tLabel = Window.GetControl (0x1000000d)\n\tLabel.SetText (str (GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS)))\n\tLabel.SetTooltip (4199)\n\n\t# stats\n\n\tsstr = GemRB.GetPlayerStat (pc, IE_STR)\n\tbstr = GemRB.GetPlayerStat (pc, IE_STR,1)\n\tsstrx = GemRB.GetPlayerStat (pc, IE_STREXTRA)\n\tbstrx = GemRB.GetPlayerStat (pc, IE_STREXTRA,1)\n\tif (sstrx > 0) and (sstr==18):\n\t\tsstr = \"%d/%02d\" %(sstr, sstrx % 100)\n\tif (bstrx > 0) and (bstr==18):\n\t\tbstr = \"%d/%02d\" %(bstr, bstrx % 100)\n\tsint = GemRB.GetPlayerStat (pc, IE_INT)\n\tbint = GemRB.GetPlayerStat (pc, IE_INT,1)\n\tswis = GemRB.GetPlayerStat (pc, IE_WIS)\n\tbwis = GemRB.GetPlayerStat (pc, IE_WIS,1)\n\tsdex = GemRB.GetPlayerStat (pc, IE_DEX)\n\tbdex = GemRB.GetPlayerStat (pc, IE_DEX,1)\n\tscon = GemRB.GetPlayerStat (pc, IE_CON)\n\tbcon = GemRB.GetPlayerStat (pc, IE_CON,1)\n\tschr = GemRB.GetPlayerStat (pc, IE_CHR)\n\tbchr = GemRB.GetPlayerStat (pc, IE_CHR,1)\n\n\tstats = (sstr, sint, swis, sdex, scon, schr)\n\tbasestats = (bstr, bint, bwis, bdex, bcon, bchr)\n\tfor i in range (6):\n\t\tLabel = Window.GetControl (0x1000000e + i)\n\t\tif stats[i]!=basestats[i]:\n\t\t\tLabel.SetTextColor ({'r' : 255, 'g' : 0, 'b' : 0})\n\t\telse:\n\t\t\tLabel.SetTextColor ({'r' : 255, 'g' : 255, 'b' : 255})\n\t\tLabel.SetText (str (stats[i]))\n\n\t# race\n\n\t# this is -1 to lookup the value in the table\n\trace = GemRB.GetPlayerStat (pc, IE_SPECIES) - 1\n\n\t# workaround for original saves that don't have the characters species stat set properly\n\tif race == -1:\n\t\tif GemRB.GetPlayerStat (pc, IE_SPECIFIC) == 3: # Vhailor\n\t\t\trace = 50 # Changes from GHOST to RESTLESS_SPIRIT\n\t\telif GemRB.GetPlayerStat (pc, IE_SPECIFIC) == 9: # Morte\n\t\t\trace = 44 # Changes from HUMAN to MORTE. Morte is Morte :)\n\t\telse:\n\t\t\trace = GemRB.GetPlayerStat (pc, IE_RACE) - 1\n\n\ttext = CommonTables.Races.GetValue (race, 0)\n\n\tLabel = Window.GetControl (0x10000014)\n\tLabel.SetText (text)\n\n\n\t# sex\n\tGenderTable = GemRB.LoadTable (\"GENDERS\")\n\ttext = GenderTable.GetValue (GemRB.GetPlayerStat (pc, IE_SEX) - 1, GTV_STR)\n\n\tLabel = Window.GetControl (0x10000015)\n\tLabel.SetText (text)\n\n\n\t# class\n\ttext = CommonTables.Classes.GetValue (GUICommon.GetClassRowName (pc), \"NAME_REF\")\n\n\tLabel = Window.GetControl (0x10000016)\n\tLabel.SetText (text)\n\n\t# alignment\n\talign = GemRB.GetPlayerStat (pc, IE_ALIGNMENT)\n\tss = GemRB.LoadSymbol (\"ALIGN\")\n\tsym = ss.GetValue (align)\n\n\tAlignmentTable = GemRB.LoadTable (\"ALIGNS\")\n\talignment_help = AlignmentTable.GetValue (sym, 'DESC_REF', GTV_REF)\n\tframe = (3 * int (align / 16) + align % 16) - 4\n\n\tButton = Window.GetControl (5)\n\tButton.SetState (IE_GUI_BUTTON_LOCKED)\n\tButton.SetSprites ('STALIGN', 0, frame, 0, 0, 0)\n\tButton.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, OnRecordsHelpAlignment)\n\tButton.SetEvent (IE_GUI_MOUSE_LEAVE_BUTTON, OnRecordsButtonLeave)\n\n\n\t# faction\n\tfaction = GemRB.GetPlayerStat (pc, IE_FACTION)\n\tFactionTable = GemRB.LoadTable (\"FACTIONS\")\n\tfaction_help = FactionTable.GetValue (faction, 0, GTV_REF)\n\tframe = FactionTable.GetValue (faction, 1)\n\n\tButton = Window.GetControl (6)\n\tButton.SetState (IE_GUI_BUTTON_LOCKED)\n\tButton.SetSprites ('STFCTION', 0, frame, 0, 0, 0)\n\tButton.SetEvent (IE_GUI_MOUSE_ENTER_BUTTON, OnRecordsHelpFaction)\n\tButton.SetEvent (IE_GUI_MOUSE_LEAVE_BUTTON, OnRecordsButtonLeave)\n\n\t# help, info textarea\n\tstats_overview = GetStatOverview (pc)\n\tText = Window.GetControl (0)\n\tText.SetText (stats_overview)\n\treturn\n\nToggleRecordsWindow = GUICommonWindows.CreateTopWinLoader(3, \"GUIREC\", GUICommonWindows.ToggleWindow, InitRecordsWindow, UpdateRecordsWindow, WINDOW_TOP|WINDOW_HCENTER, True)\nOpenRecordsWindow = GUICommonWindows.CreateTopWinLoader(3, \"GUIREC\", GUICommonWindows.OpenWindowOnce, InitRecordsWindow, UpdateRecordsWindow, WINDOW_TOP|WINDOW_HCENTER, True)\n\n# puts default info to textarea (overview of PC's bonuses, saves, etc.\ndef OnRecordsButtonLeave ():\n\tOnRecordsHelpStat (-1, 0, stats_overview)\n\treturn\n\ndef OnRecordsHelpFaction ():\n\tHelp = GemRB.GetString (20106) + \"\\n\\n\" + faction_help\n\tOnRecordsHelpStat (-1, 0, Help)\n\treturn\n\ndef OnRecordsHelpArmorClass ():\n\tOnRecordsHelpStat (-1, 0, 18493)\n\treturn\n\ndef OnRecordsHelpHitPoints ():\n\tOnRecordsHelpStat (-1, 0, 18494)\n\treturn\n\ndef OnRecordsHelpAlignment ():\n\tHelp = GemRB.GetString (20105) + \"\\n\\n\" + alignment_help\n\tOnRecordsHelpStat (-1, 0, Help)\n\treturn\n\n#Bio:\n# 38787 no\n# 39423 morte\n# 39424 annah\n# 39425 dakkon\n# 39426 ffg\n# 39427 ignus\n# 39428 nordom\n# 39429 vhailor\n\ndef OnRecordsHelpStat (row, col, strref, bon1=0, bon2=0):\n\tTextArea = RecordsWindow.GetControl (0)\n\tTextArea.SetText (strref)\n\tif row != -1:\n\t\tTextArea.Append (\"\\n\\n\" + GemRB.StatComment (StatTable.GetValue(str(row),col), bon1, bon2) )\n\treturn\n\ndef OnRecordsHelpStrength ():\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's strength\n\ts = GemRB.GetPlayerStat (pc, IE_STR)\n\te = GemRB.GetPlayerStat (pc, IE_STREXTRA)\n\n\tx = CommonTables.StrMod.GetValue(s, 0) + CommonTables.StrModEx.GetValue(e, 0)\n\ty = CommonTables.StrMod.GetValue(s, 1) + CommonTables.StrModEx.GetValue(e, 1)\n\tif x==0:\n\t\tx=y\n\t\ty=0\n\tif e>60:\n\t\ts=19\n\n\tOnRecordsHelpStat (s, \"STR\", 18489, x, y)\n\treturn\n\ndef OnRecordsHelpDexterity ():\n\t# Loading table of modifications\n\tTable = GemRB.LoadTable(\"dexmod\")\n\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's dexterity\n\tDex = GemRB.GetPlayerStat (pc, IE_DEX)\n\n\t# Getting the dexterity description\n\tx = -Table.GetValue(Dex,2)\n\n\tOnRecordsHelpStat (Dex, \"DEX\", 18487, x)\n\treturn\n\ndef OnRecordsHelpIntelligence ():\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's intelligence\n\tInt = GemRB.GetPlayerStat (pc, IE_INT)\n\tOnRecordsHelpStat (Int, \"INT\", 18488)\n\treturn\n\ndef OnRecordsHelpWisdom ():\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's wisdom\n\tWis = GemRB.GetPlayerStat (pc, IE_WIS)\n\tOnRecordsHelpStat (Wis, \"WIS\", 18490)\n\treturn\n\ndef OnRecordsHelpConstitution ():\n\t# Loading table of modifications\n\tTable = GemRB.LoadTable(\"hpconbon\")\n\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's constitution\n\tCon = GemRB.GetPlayerStat (pc, IE_CON)\n\n\t# Getting the constitution description\n\tx = Table.GetValue(Con-1,1)\n\n\tOnRecordsHelpStat (Con, \"CON\", 18491, x)\n\treturn\n\ndef OnRecordsHelpCharisma ():\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# Getting the character's charisma\n\tCha = GemRB.GetPlayerStat (pc, IE_CHR)\n\tOnRecordsHelpStat (Cha, \"CHR\", 1903)\n\treturn\n\ndef GetCharacterHeader (pc):\n\tglobal avatar_header\n\n\tClass = GemRB.GetPlayerStat (pc, IE_CLASS) - 1\n\tMulti = GUICommon.HasMultiClassBits (pc)\n\n\t# Nameless is a special case (dual class)\n\tif GUICommon.IsNamelessOne(pc):\n\t\tavatar_header['PrimClass'] = CommonTables.Classes.GetRowName (Class)\n\t\tavatar_header['SecoClass'] = \"*\"\n\n\t\tavatar_header['SecoLevel'] = 0\n\n\t\tif avatar_header['PrimClass'] == \"FIGHTER\":\n\t\t\tavatar_header['PrimLevel'] = GemRB.GetPlayerStat (pc, IE_LEVEL)\n\t\t\tavatar_header['XP'] = GemRB.GetPlayerStat (pc, IE_XP)\n\t\telif avatar_header['PrimClass'] == \"MAGE\":\n\t\t\tavatar_header['PrimLevel'] = GemRB.GetPlayerStat (pc, IE_LEVEL2)\n\t\t\tavatar_header['XP'] = GemRB.GetPlayerStat (pc, IE_XP_MAGE)\n\t\telse:\n\t\t\tavatar_header['PrimLevel'] = GemRB.GetPlayerStat (pc, IE_LEVEL3)\n\t\t\tavatar_header['XP'] = GemRB.GetPlayerStat (pc, IE_XP_THIEF)\n\n\t\tavatar_header['PrimNextLevXP'] = GetNextLevelExp (avatar_header['PrimLevel'], avatar_header['PrimClass'])\n\t\tavatar_header['SecoNextLevXP'] = 0\n\telse:\n\t\t# PC is not NAMELESS_ONE\n\t\tavatar_header['PrimLevel'] = GemRB.GetPlayerStat (pc, IE_LEVEL)\n\t\tavatar_header['XP'] = GemRB.GetPlayerStat (pc, IE_XP)\n\t\tif Multi:\n\t\t\tavatar_header['XP'] = avatar_header['XP'] / 2\n\t\t\tavatar_header['SecoLevel'] = GemRB.GetPlayerStat (pc, IE_LEVEL2)\n\n\t\t\tavatar_header['PrimClass'] = \"FIGHTER\"\n\t\t\tif Multi == 3:\n\t\t\t\t#fighter/mage\n\t\t\t\tClass = 0\n\t\t\telse:\n\t\t\t\t#fighter/thief\n\t\t\t\tClass = 3\n\t\t\tavatar_header['SecoClass'] = CommonTables.Classes.GetRowName (Class)\n\n\t\t\tavatar_header['PrimNextLevXP'] = GetNextLevelExp (avatar_header['PrimLevel'], avatar_header['PrimClass'])\n\t\t\tavatar_header['SecoNextLevXP'] = GetNextLevelExp (avatar_header['SecoLevel'], avatar_header['SecoClass'])\n\n\t\t\t# Converting to the displayable format\n\t\t\tavatar_header['SecoClass'] = CommonTables.Classes.GetValue (avatar_header['SecoClass'], \"NAME_REF\", GTV_REF)\n\t\telse:\n\t\t\tavatar_header['SecoLevel'] = 0\n\t\t\tavatar_header['PrimClass'] = CommonTables.Classes.GetRowName (Class)\n\t\t\tavatar_header['SecoClass'] = \"*\"\n\t\t\tavatar_header['PrimNextLevXP'] = GetNextLevelExp (avatar_header['PrimLevel'], avatar_header['PrimClass'])\n\t\t\tavatar_header['SecoNextLevXP'] = 0\n\n\t# Converting to the displayable format\n\tavatar_header['PrimClass'] = CommonTables.Classes.GetValue (avatar_header['PrimClass'], \"NAME_REF\", GTV_REF)\n\n\n\ndef GetNextLevelExp (Level, Class):\n\tif (Level < 20):\n\t\tNextLevel = CommonTables.NextLevel.GetValue (Class, str (Level + 1))\n\telse:\n\t\tAfter21ExpTable = GemRB.LoadTable (\"LVL21PLS\")\n\t\tExpGap = After21ExpTable.GetValue (Class, 'XPGAP')\n\t\tLevDiff = Level - 19\n\t\tLev20Exp = CommonTables.NextLevel.GetValue (Class, \"20\")\n\t\tNextLevel = Lev20Exp + (LevDiff * ExpGap)\n\n\treturn NextLevel\n\n\ndef GetStatOverview (pc):\n\twon = \"[color=FFFFFF]\"\n\twoff = \"[/color]\"\n\tstr_None = GemRB.GetString (41275)\n\n\tGS = lambda s, pc=pc: GemRB.GetPlayerStat (pc, s)\n\n\tstats = []\n\n\t# Displaying Class, Level, Experience and Next Level Experience\n\tif (avatar_header['SecoLevel'] == 0):\n\t\tstats.append ((avatar_header['PrimClass'], \"\", 'd'))\n\t\tstats.append ((48156, avatar_header['PrimLevel'], ''))\n\t\tstats.append ((19673, avatar_header['XP'], ''))\n\t\tstats.append ((19674, avatar_header['PrimNextLevXP'], ''))\n\telse:\n\t\tstats.append ((19414, \"\", ''))\n\t\tstats.append (None)\n\t\tstats.append ((avatar_header['PrimClass'], \"\", 'd'))\n\t\tstats.append ((48156, avatar_header['PrimLevel'], ''))\n\t\tstats.append ((19673, avatar_header['XP'], ''))\n\t\tstats.append ((19674, avatar_header['PrimNextLevXP'], ''))\n\t\tstats.append (None)\n\t\tstats.append ((avatar_header['SecoClass'], \"\", 'd'))\n\t\tstats.append ((48156, avatar_header['SecoLevel'], ''))\n\t\tstats.append ((19673, avatar_header['XP'], ''))\n\t\tstats.append ((19674, avatar_header['SecoNextLevXP'], ''))\n\n\t# 59856 Current State\n\tstats.append (None)\n\tStatesTable = GemRB.LoadTable (\"states\")\n\tStateID = GS (IE_STATE_ID)\n\tState = StatesTable.GetValue (str (StateID), \"NAME_REF\", GTV_REF)\n\tstats.append ((won + GemRB.GetString (59856) + woff, \"\", 'd'))\n\tstats.append ((State, \"\", 'd'))\n\tstats.append (None)\n\n\t# 67049 AC Bonuses\n\tstats.append (67049)\n\t# 67204 AC vs. Slashing\n\tstats.append ((67204, GS (IE_ACSLASHINGMOD), ''))\n\t# 67205 AC vs. Piercing\n\tstats.append ((67205, GS (IE_ACPIERCINGMOD), ''))\n\t# 67206 AC vs. Crushing\n\tstats.append ((67206, GS (IE_ACCRUSHINGMOD), ''))\n\t# 67207 AC vs. Missile\n\tstats.append ((67207, GS (IE_ACMISSILEMOD), ''))\n\tstats.append (None)\n\n\n\t# 67208 Resistances\n\tstats.append (67208)\n\t# 67209 Normal Fire\n\tstats.append ((67209, GS (IE_RESISTFIRE), '%'))\n\t# 67210 Magic Fire\n\tstats.append ((67210, GS (IE_RESISTMAGICFIRE), '%'))\n\t# 67211 Normal Cold\n\tstats.append ((67211, GS (IE_RESISTCOLD), '%'))\n\t# 67212 Magic Cold\n\tstats.append ((67212, GS (IE_RESISTMAGICCOLD), '%'))\n\t# 67213 Electricity\n\tstats.append ((67213, GS (IE_RESISTELECTRICITY), '%'))\n\t# 67214 Acid\n\tstats.append ((67214, GS (IE_RESISTACID), '%'))\n\t# 67215 Magic\n\tstats.append ((67215, GS (IE_RESISTMAGIC), '%'))\n\t# 67216 Slashing Attacks\n\tstats.append ((67216, GS (IE_RESISTSLASHING), '%'))\n\t# 67217 Piercing Attacks\n\tstats.append ((67217, GS (IE_RESISTPIERCING), '%'))\n\t# 67218 Crushing Attacks\n\tstats.append ((67218, GS (IE_RESISTCRUSHING), '%'))\n\t# 67219 Missile Attacks\n\tstats.append ((67219, GS (IE_RESISTMISSILE), '%'))\n\tstats.append (None)\n\n\t# 4220 Proficiencies\n\tstats.append (4220)\n\t# 4208 THAC0\n\tstats.append ((4208, GS (IE_TOHIT), ''))\n\t# 4209 Number of Attacks\n\ttmp = GemRB.GetCombatDetails(pc, 0)[\"APR\"]\n\n\tif (tmp&1):\n\t\ttmp2 = str(tmp/2) + chr(189)\n\telse:\n\t\ttmp2 = str(tmp/2)\n\n\tstats.append ((4209, tmp2, ''))\n\t# 4210 Lore\n\tstats.append ((4210, GS (IE_LORE), ''))\n\t# 4211 Open Locks\n\tstats.append ((4211, GS (IE_LOCKPICKING), '%'))\n\t# 4212 Stealth\n\tstats.append ((4212, GS (IE_STEALTH), '%'))\n\t# 4213 Find/Remove Traps\n\tstats.append ((4213, GS (IE_TRAPS), '%'))\n\t# 4214 Pick Pockets\n\tstats.append ((4214, GS (IE_PICKPOCKET), '%'))\n\t# 4215 Tracking\n\tstats.append ((4215, GS (IE_TRACKING), ''))\n\t# 4216 Reputation\n\tstats.append ((4216, GS (IE_REPUTATION), ''))\n\t# 4217 Turn Undead Level\n\tstats.append ((4217, GS (IE_TURNUNDEADLEVEL), ''))\n\t# 4218 Lay on Hands Amount\n\tstats.append ((4218, GS (IE_LAYONHANDSAMOUNT), ''))\n\t# 4219 Backstab Damage\n\tstats.append ((4219, GS (IE_BACKSTABDAMAGEMULTIPLIER), 'x'))\n\tstats.append (None)\n\n\t# 4221 Saving Throws\n\tstats.append (4221)\n\t# 4222 Paralyze/Poison/Death\n\tstats.append ((4222, GS (IE_SAVEVSDEATH), ''))\n\t# 4223 Rod/Staff/Wand\n\tstats.append ((4223, GS (IE_SAVEVSWANDS), ''))\n\t# 4224 Petrify/Polymorph\n\tstats.append ((4224, GS (IE_SAVEVSPOLY), ''))\n\t# 4225 Breath Weapon\n\tstats.append ((4225, GS (IE_SAVEVSBREATH), ''))\n\t# 4226 Spells\n\tstats.append ((4226, GS (IE_SAVEVSSPELL), ''))\n\tstats.append (None)\n\n\t# 4227 Weapon Proficiencies\n\tstats.append (4227)\n\t# 55011 Unused Slots\n\tstats.append ((55011, GS (IE_FREESLOTS), ''))\n\t# 33642 Fist\n\tstats.append ((33642, GS (IE_PROFICIENCYBASTARDSWORD), '+'))\n\t# 33649 Edged Weapon\n\tstats.append ((33649, GS (IE_PROFICIENCYLONGSWORD), '+'))\n\t# 33651 Hammer\n\tstats.append ((33651, GS (IE_PROFICIENCYSHORTSWORD), '+'))\n\t# 44990 Axe\n\tstats.append ((44990, GS (IE_PROFICIENCYAXE), '+'))\n\t# 33653 Club\n\tstats.append ((33653, GS (IE_PROFICIENCYTWOHANDEDSWORD), '+'))\n\t# 33655 Bow\n\tstats.append ((33655, GS (IE_PROFICIENCYKATANA), '+'))\n\tstats.append (None)\n\n\t# 4228 Ability Bonuses\n\tstats.append (4228)\n\t# 4229 To Hit\n\t# 4230 Damage\n\t# 4231 Open Doors\n\t# 4232 Weight Allowance\n\t# 4233 Armor Class Bonus\n\t# 4234 Missile Adjustment\n\tstats.append ((4234, GS (IE_ACMISSILEMOD), ''))\n\t# 4236 CON HP Bonus/Level\n\t# 4240 Reaction\n\tstats.append (None)\n\n\t# 4238 Magical Defense Adjustment\n\tstats.append (4238)\n\t# 4239 Bonus Priest Spells\n\tstats.append ((4239, GS (IE_CASTINGLEVELBONUSCLERIC), ''))\n\tstats.append (None)\n\n\t# 4237 Chance to learn spell\n\t#SpellLearnChance = won + GemRB.GetString (4237) + woff\n\n\t# ??? 4235 Reaction Adjustment\n\n\tres = []\n\tlines = 0\n\tfor s in stats:\n\t\ttry:\n\t\t\tstrref, val, stattype = s\n\t\t\tif val == 0 and stattype != '0':\n\t\t\t\tcontinue\n\t\t\tif stattype == '+':\n\t\t\t\tres.append (GemRB.GetString (strref) + ' '+ '+' * val)\n\t\t\telif stattype == 'd': #strref is an already resolved string\n\t\t\t\tres.append (strref)\n\t\t\telif stattype == 'x':\n\t\t\t\tres.append (GemRB.GetString (strref) + ': x' + str (val))\n\t\t\telse:\n\t\t\t\tres.append (GemRB.GetString (strref) + ': ' + str (val) + stattype)\n\n\t\t\tlines = 1\n\t\texcept:\n\t\t\tif s != None:\n\t\t\t\tres.append (won + GemRB.GetString (s) + woff)\n\t\t\t\tlines = 0\n\t\t\telse:\n\t\t\t\tif not lines:\n\t\t\t\t\tres.append (str_None)\n\t\t\t\tres.append (\"\")\n\t\t\t\tlines = 0\n\n\treturn \"\\n\".join (res)\n\ndef OpenInformationWindow ():\n\tglobal InformationWindow\n\n\tif InformationWindow != None:\n\t\tif BiographyWindow: OpenBiographyWindow ()\n\n\t\tif InformationWindow:\n\t\t\tInformationWindow.Unload ()\n\t\tInformationWindow = None\n\n\t\treturn\n\n\tInformationWindow = Window = GemRB.LoadWindow (5)\n\n\t# Biography\n\tButton = Window.GetControl (1)\n\tButton.SetText (4247)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, OpenBiographyWindow)\n\n\t# Done\n\tButton = Window.GetControl (0)\n\tButton.SetText (1403)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, OpenInformationWindow)\n\tButton.MakeEscape()\n\n\tTotalPartyExp = 0\n\tTotalPartyKills = 0\n\tfor i in range (1, GemRB.GetPartySize() + 1):\n\t\tstat = GemRB.GetPCStats(i)\n\t\tTotalPartyExp = TotalPartyExp + stat['KillsTotalXP']\n\t\tTotalPartyKills = TotalPartyKills + stat['KillsTotalCount']\n\n\t# These are used to get the stats\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\tstat = GemRB.GetPCStats (pc)\n\n\tLabel = Window.GetControl (0x10000001)\n\tLabel.SetText (GemRB.GetPlayerName (pc, 1))\n\n\t# class\n\tClassTitle = GUICommon.GetActorClassTitle (pc)\n\tLabel = Window.GetControl (0x1000000A)\n\tLabel.SetText (ClassTitle)\n\n\tLabel = Window.GetControl (0x10000002)\n\tif stat['BestKilledName'] == -1:\n\t\tLabel.SetText (GemRB.GetString (41275))\n\telse:\n\t\tLabel.SetText (GemRB.GetString (stat['BestKilledName']))\n\n\tLabel = Window.GetControl (0x10000003)\n\tGUICommon.SetCurrentDateTokens (stat, True)\n\tLabel.SetText (41277)\n\n\tLabel = Window.GetControl (0x10000004)\n\tLabel.SetText (stat['FavouriteSpell'])\n\n\tLabel = Window.GetControl (0x10000005)\n\tLabel.SetText (stat['FavouriteWeapon'])\n\n\tLabel = Window.GetControl (0x10000006)\n\tif TotalPartyExp != 0:\n\t\tPartyExp = int ((stat['KillsTotalXP'] * 100) / TotalPartyExp)\n\t\tLabel.SetText (str (PartyExp) + '%')\n\telse:\n\t\tLabel.SetText (\"0%\")\n\n\tLabel = Window.GetControl (0x10000007)\n\tif TotalPartyKills != 0:\n\t\tPartyKills = int ((stat['KillsTotalCount'] * 100) / TotalPartyKills)\n\t\tLabel.SetText (str (PartyKills) + '%')\n\telse:\n\t\tLabel.SetText (\"0%\")\n\n\tLabel = Window.GetControl (0x10000008)\n\tLabel.SetText (str (stat['KillsTotalXP']))\n\n\tLabel = Window.GetControl (0x10000009)\n\tLabel.SetText (str (stat['KillsTotalCount']))\n\n\tWhite = {'r' : 255, 'g' : 255, 'b' : 255}\n\tLabel = Window.GetControl (0x1000000B)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x1000000C)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x1000000D)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x1000000E)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x1000000F)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x10000010)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x10000011)\n\tLabel.SetTextColor (White)\n\n\tLabel = Window.GetControl (0x10000012)\n\tLabel.SetTextColor (White)\n\n\tWindow.ShowModal (MODAL_SHADOW_GRAY)\n\n\ndef OpenBiographyWindow ():\n\tglobal BiographyWindow\n\n\tif BiographyWindow != None:\n\t\tif BiographyWindow:\n\t\t\tBiographyWindow.Unload ()\n\t\tBiographyWindow = None\n\n\t\tInformationWindow.ShowModal (MODAL_SHADOW_GRAY)\n\t\treturn\n\n\tBiographyWindow = Window = GemRB.LoadWindow (12)\n\n\t# These are used to get the bio\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\tBioTable = GemRB.LoadTable (\"bios\")\n\tSpecific = GemRB.GetPlayerStat (pc, IE_SPECIFIC)\n\tBioText = int (BioTable.GetValue (BioTable.GetRowName (Specific), 'BIO'))\n\n\tTextArea = Window.GetControl (0)\n\tTextArea.SetText (BioText)\n\n\n\t# Done\n\tButton = Window.GetControl (2)\n\tButton.SetText (1403)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, OpenBiographyWindow)\n\tButton.MakeEscape()\n\n\tWindow.ShowModal (MODAL_SHADOW_GRAY)\n\n\ndef AcceptLevelUp():\n\t#do level up\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\tGemRB.SetPlayerStat (pc, IE_SAVEVSDEATH, SavThrows[0])\n\tGemRB.SetPlayerStat (pc, IE_SAVEVSWANDS, SavThrows[1])\n\tGemRB.SetPlayerStat (pc, IE_SAVEVSPOLY, SavThrows[2])\n\tGemRB.SetPlayerStat (pc, IE_SAVEVSBREATH, SavThrows[3])\n\tGemRB.SetPlayerStat (pc, IE_SAVEVSSPELL, SavThrows[4])\n\toldhp = GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS, 1)\n\tGemRB.SetPlayerStat (pc, IE_MAXHITPOINTS, HPGained+oldhp)\n\toldhp = GemRB.GetPlayerStat (pc, IE_HITPOINTS, 1)\n\tGemRB.SetPlayerStat (pc, IE_HITPOINTS, HPGained+oldhp)\n\n\t# Weapon Proficiencies\n\tif WeapProfType != -1:\n\t\t# Companion NPC's get points added directly to their chosen weapon\n\t\tGemRB.SetPlayerStat (pc, IE_PROFICIENCYBASTARDSWORD+WeapProfType, CurrWeapProf + WeapProfGained)\n\telse:\n\t\t# TNO has points added to the \"Unused Slots\" dummy proficiency\n\t\tfreeSlots = GemRB.GetPlayerStat(pc, IE_FREESLOTS)\n\t\tGemRB.SetPlayerStat (pc, IE_FREESLOTS, freeSlots + WeapProfGained)\n\n\tSwitcherClass = GUICommon.NamelessOneClass(pc)\n\tif SwitcherClass:\n\t\t# Handle saving of TNO class level in the correct CRE stat\n\t\tLevels = { \"FIGHTER\" : GemRB.GetPlayerStat (pc, IE_LEVEL) , \"MAGE\": GemRB.GetPlayerStat (pc, IE_LEVEL2), \"THIEF\": GemRB.GetPlayerStat (pc, IE_LEVEL3) }\n\t\tLevelStats = { \"FIGHTER\" : IE_LEVEL , \"MAGE\": IE_LEVEL2, \"THIEF\": IE_LEVEL3 }\n\t\tGemRB.SetPlayerStat (pc, LevelStats[SwitcherClass], Levels[SwitcherClass]+NumOfPrimLevUp)\n\telse:\n\t\tGemRB.SetPlayerStat (pc, IE_LEVEL, GemRB.GetPlayerStat (pc, IE_LEVEL)+NumOfPrimLevUp)\n\t\tif avatar_header['SecoLevel'] != 0:\n\t\t\tGemRB.SetPlayerStat (pc, IE_LEVEL2, GemRB.GetPlayerStat (pc, IE_LEVEL2)+NumOfSecoLevUp)\n\t\n\tLUSkillsSelection.SkillsSave (pc)\n\n\t# Spells\n\tLevelUp.pc = pc\n\tLevelUp.Classes = Classes\n\tLevelUp.NumClasses = NumClasses\n\t# (we need to override the globals this function uses there since they wouldn't have been set)\n\tLevelUp.SaveNewSpells()\n\n\tLevelUpWindow.Close()\n\tNewLife.OpenLUStatsWindow()\n\ndef RedrawSkills():\n\tDoneButton = LevelUpWindow.GetControl(0)\n\n\tif GemRB.GetVar (\"SkillPointsLeft\") == 0:\n\t\tDoneButton.SetState(IE_GUI_BUTTON_ENABLED)\n\telse:\n\t\tDoneButton.SetState(IE_GUI_BUTTON_DISABLED)\n\treturn\n\ndef OpenLevelUpWindow ():\n\tglobal LevelUpWindow\n\tglobal SavThrows\n\tglobal HPGained\n\tglobal WeapProfType, CurrWeapProf, WeapProfGained\n\tglobal NumOfPrimLevUp, NumOfSecoLevUp\n\n\tglobal LevelDiff, Level, Classes, NumClasses\n\n\tLevelUpWindow = Window = GemRB.LoadWindow (4, \"GUIREC\") # since we get called from NewLife\n\n\t# Accept\n\tButton = Window.GetControl (0)\n\tButton.SetText (4192)\n\tButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, AcceptLevelUp)\n\n\tpc = GemRB.GameGetSelectedPCSingle ()\n\n\t# These are used to identify Nameless One\n\tBioTable = GemRB.LoadTable (\"bios\")\n\tSpecific = GemRB.GetPlayerStat (pc, IE_SPECIFIC)\n\tAvatarName = BioTable.GetRowName (Specific)\n\n\t# These will be used for saving throws\n\tSavThrUpdated = False\n\tSavThrows = [0,0,0,0,0]\n\tSavThrows[0] = GemRB.GetPlayerStat (pc, IE_SAVEVSDEATH)\n\tSavThrows[1] = GemRB.GetPlayerStat (pc, IE_SAVEVSWANDS)\n\tSavThrows[2] = GemRB.GetPlayerStat (pc, IE_SAVEVSPOLY)\n\tSavThrows[3] = GemRB.GetPlayerStat (pc, IE_SAVEVSBREATH)\n\tSavThrows[4] = GemRB.GetPlayerStat (pc, IE_SAVEVSSPELL)\n\n\tHPGained = 0\n\tConHPBon = 0\n\tThac0Updated = False\n\tThac0 = 0\n\tWeapProfGained = 0\n\n\tWeapProfType = -1\n\tCurrWeapProf = 0\n\n\t# Count the number of existing weapon procifiencies\n\tif GUICommon.IsNamelessOne(pc):\n\t\t# TNO: Count the total amount of unassigned proficiencies\n\t\tCurrWeapProf = GemRB.GetPlayerStat(pc, IE_FREESLOTS)\n\telse:\n\t\t# Scan the weapprof table for the characters favoured weapon proficiency (WeapProfType)\n\t\t# This does not apply to Nameless since he uses unused slots system\n\t\tfor i in range (6):\n\t\t\tWeapProfName = CommonTables.WeapProfs.GetRowName (i)\n\t\t\tvalue = CommonTables.WeapProfs.GetValue (WeapProfName,AvatarName)\n\t\t\tif value == 1:\n\t\t\t\tWeapProfType = i\n\t\t\t\tbreak\n\n\tfor i in range (6):\n\t\tCurrWeapProf += GemRB.GetPlayerStat (pc, IE_PROFICIENCYBASTARDSWORD + i)\n\n\t# What is the avatar's class (Which we can use to lookup XP)\n\tClass = GUICommon.GetClassRowName (pc)\n\n\t# name\n\tLabel = Window.GetControl (0x10000000)\n\tLabel.SetText (GemRB.GetPlayerName (pc, 1))\n\n\t# class\n\tLabel = Window.GetControl (0x10000001)\n\tLabel.SetText (CommonTables.Classes.GetValue (Class, \"NAME_REF\"))\n\n\t# Armor Class\n\tLabel = Window.GetControl (0x10000023)\n\tLabel.SetText (str (GemRB.GetPlayerStat (pc, IE_ARMORCLASS)))\n\n\t# our multiclass variables\n\tIsMulti = GUICommon.IsMultiClassed (pc, 1)\n\tClasses = [IsMulti[1], IsMulti[2], IsMulti[3]]\n\tNumClasses = IsMulti[0] # 2 or 3 if IsMulti; 0 otherwise\n\tIsMulti = NumClasses > 1\n\n\tif not IsMulti:\n\t\tNumClasses = 1\n\t\tClasses = [GemRB.GetPlayerStat (pc, IE_CLASS)]\n\n\tif GUICommon.IsNamelessOne(pc):\n\t\t# Override the multiclass info for TNO\n\t\tIsMulti = 1\n\t\tNumClasses = 3\n\t\t# Fighter, Mage, Thief ID\n\t\tClasses = [2, 1, 4]\n\n\tLevel = LUCommon.GetNextLevels(pc, Classes)\n\tLevelDiff = LUCommon.GetLevelDiff(pc, Level)\n\n\t# calculate the new spells (results are stored in global variables in LevelUp)\n\tLevelUp.GetNewSpells(pc, Classes, Level, LevelDiff)\n\n\t# Thief Skills\n\tLevel1 = []\n\tfor i in range (len (Level)):\n\t\tLevel1.append (Level[i]-LevelDiff[i])\n\tLUSkillsSelection.SetupSkillsWindow (pc, LUSkillsSelection.LUSKILLS_TYPE_LEVELUP, LevelUpWindow, RedrawSkills, Level1, Level, 0, False)\n\tRedrawSkills()\n\n\t# Is avatar multi-class?\n\tif avatar_header['SecoLevel'] == 0:\n\t\t# avatar is single class\n\t\t# What will be avatar's next level?\n\t\tNextLevel = avatar_header['PrimLevel'] + 1\n\t\twhile avatar_header['XP'] >= GetNextLevelExp (NextLevel, Class):\n\t\t\tNextLevel = NextLevel + 1\n\t\tNumOfPrimLevUp = NextLevel - avatar_header['PrimLevel'] # How many levels did we go up?\n\n\t\t#How many weapon procifiencies we get\n\t\tfor i in range (NumOfPrimLevUp):\n\t\t\tWeapProfGained += GainedWeapProfs (pc, CurrWeapProf + WeapProfGained, avatar_header['PrimLevel'] + i, AvatarName)\n\n\t\t# Hit Points Gained and Hit Points from Constitution Bonus\n\t\tfor i in range (NumOfPrimLevUp):\n\t\t\tHPGained = HPGained + GetSingleClassHP (Class, avatar_header['PrimLevel'])\n\t\tif Class == \"FIGHTER\":\n\t\t\tCONType = 0\n\t\telse:\n\t\t\tCONType = 1\n\t\tConHPBon = GetConHPBonus (pc, NumOfPrimLevUp, 0, CONType)\n\n\t\t# Thac0\n\t\tThac0 = GetThac0 (Class, NextLevel)\n\t\t# Is the new thac0 better than old? (The smaller, the better)\n\t\tif Thac0 < GemRB.GetPlayerStat (pc, IE_TOHIT, 1):\n\t\t\tThac0Updated = True\n\n\t\t# Saving Throws\n\t\tif GUICommon.IsNamelessOne(pc):\n\t\t\t# Nameless One always uses the best possible save from each class\n\t\t\tFigSavThrTable = GemRB.LoadTable (\"SAVEWAR\")\n\t\t\tMagSavThrTable = GemRB.LoadTable (\"SAVEWIZ\")\n\t\t\tThiSavThrTable = GemRB.LoadTable (\"SAVEROG\")\n\n\t\t\tFighterLevel = GemRB.GetPlayerStat (pc, IE_LEVEL) - 1\n\t\t\tMageLevel = GemRB.GetPlayerStat (pc, IE_LEVEL2) - 1\n\t\t\tThiefLevel = GemRB.GetPlayerStat (pc, IE_LEVEL3) - 1\n\n\t\t\t# We are leveling up one of those levels. Therefore, one of them has to be updated.\n\t\t\tif Class == \"FIGHTER\":\n\t\t\t\tFighterLevel = NextLevel - 1\n\t\t\telif Class == \"MAGE\":\n\t\t\t\tMageLevel = NextLevel - 1\n\t\t\telse:\n\t\t\t\tThiefLevel = NextLevel - 1\n\n\t\t\t# Now we need to update the saving throws with the best values from those tables.\n\t\t\t# The smaller the number, the better saving throw it is.\n\t\t\t# We also need to check if any of the levels are larger than 21, since\n\t\t\t# after that point the table runs out, and the throws remain the\n\t\t\t# same\n\t\t\tif FighterLevel < 21:\n\t\t\t\tfor i in range (5):\n\t\t\t\t\tThrow = FigSavThrTable.GetValue (i, FighterLevel)\n\t\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\t\tSavThrUpdated = True\n\t\t\tif MageLevel < 21:\n\t\t\t\tfor i in range (5):\n\t\t\t\t\tThrow = MagSavThrTable.GetValue (i, MageLevel)\n\t\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\t\tSavThrUpdated = True\n\t\t\tif ThiefLevel < 21:\n\t\t\t\tfor i in range (5):\n\t\t\t\t\tThrow = ThiSavThrTable.GetValue (i, ThiefLevel)\n\t\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\t\tSavThrUpdated = True\n\t\telse:\n\t\t\tSavThrTable = GemRB.LoadTable (CommonTables.Classes.GetValue (Class, \"SAVE\"))\n\t\t\t# Updating the current saving throws. They are changed only if the\n\t\t\t# new ones are better than current. The smaller the number, the better.\n\t\t\t# We need to substract one from the NextLevel, so that we get right values.\n\t\t\t# We also need to check if NextLevel is larger than 21, since after that point\n\t\t\t# the table runs out, and the throws remain the same\n\t\t\tif NextLevel < 22:\n\t\t\t\tfor i in range (5):\n\t\t\t\t\tThrow = SavThrTable.GetValue (i, NextLevel-1)\n\t\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\t\tSavThrUpdated = True\n\n\n\n\telse:\n\t\t# avatar is multi class\n\t\t# we have only fighter/X multiclasses, so this\n\t\t# part is a bit hardcoded\n\t\tPrimNextLevel = 0\n\t\tSecoNextLevel = 0\n\t\tNumOfPrimLevUp = 0\n\t\tNumOfSecoLevUp = 0\n\n\t\t# What will be avatar's next levels?\n\t\tPrimNextLevel = avatar_header['PrimLevel']\n\t\twhile avatar_header['XP'] >= GetNextLevelExp (PrimNextLevel, \"FIGHTER\"):\n\t\t\tPrimNextLevel = PrimNextLevel + 1\n\t\t# How many primary levels did we go up?\n\t\tNumOfPrimLevUp = PrimNextLevel - avatar_header['PrimLevel']\n\n\t\tfor i in range (NumOfPrimLevUp):\n\t\t\tWeapProfGained += GainedWeapProfs (pc, CurrWeapProf + WeapProfGained, avatar_header['PrimLevel'] + i, AvatarName)\n\n\t\t# Saving Throws\n\t\tFigSavThrTable = GemRB.LoadTable (\"SAVEWAR\")\n\t\tif PrimNextLevel < 22:\n\t\t\tfor i in range (5):\n\t\t\t\tThrow = FigSavThrTable.GetValue (i, PrimNextLevel - 1)\n\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\tSavThrUpdated = True\n\t\t# Which multi class is it?\n\t\tif GemRB.GetPlayerStat (pc, IE_CLASS) == 7:\n\t\t\t# avatar is Fighter/Mage (Dak'kon)\n\t\t\tClass = \"MAGE\"\n\t\t\tSavThrTable = GemRB.LoadTable (\"SAVEWIZ\")\n\t\telse:\n\t\t\t# avatar is Fighter/Thief (Annah)\n\t\t\tClass = \"THIEF\"\n\t\t\tSavThrTable = GemRB.LoadTable (\"SAVEROG\")\n\n\t\tSecoNextLevel = avatar_header['SecoLevel']\n\t\twhile avatar_header['XP'] >= GetNextLevelExp (SecoNextLevel, Class):\n\t\t\tSecoNextLevel = SecoNextLevel + 1\n\t\t# How many secondary levels did we go up?\n\t\tNumOfSecoLevUp = SecoNextLevel - avatar_header['SecoLevel']\n\t\tif SecoNextLevel < 22:\n\t\t\tfor i in range (5):\n\t\t\t\tThrow = SavThrTable.GetValue (i, SecoNextLevel - 1)\n\t\t\t\tif Throw < SavThrows[i]:\n\t\t\t\t\tSavThrows[i] = Throw\n\t\t\t\t\tSavThrUpdated = True\n\n\t\t# Hit Points Gained and Hit Points from Constitution Bonus (multiclass)\n\t\tfor i in range (NumOfPrimLevUp):\n\t\t\tHPGained = HPGained + GetSingleClassHP (\"FIGHTER\", avatar_header['PrimLevel'])/2\n\n\t\tfor i in range (NumOfSecoLevUp):\n\t\t\tHPGained = HPGained + GetSingleClassHP (Class, avatar_header['SecoLevel'])/2\n\t\tConHPBon = GetConHPBonus (pc, NumOfPrimLevUp, NumOfSecoLevUp, 2)\n\n\t\t# Thac0\n\t\t# Multi class use the primary class level to determine Thac0\n\t\tThac0 = GetThac0 (Class, PrimNextLevel)\n\t\t# Is the new thac0 better than old? (The smaller the better)\n\t\tif Thac0 < GemRB.GetPlayerStat (pc, IE_TOHIT, 1):\n\t\t\tThac0Updated = True\n\n\n\t# Displaying the saving throws\n\t# Death\n\tLabel = Window.GetControl (0x10000019)\n\tLabel.SetText (str (SavThrows[0]))\n\t# Wand\n\tLabel = Window.GetControl (0x1000001B)\n\tLabel.SetText (str (SavThrows[1]))\n\t# Polymorph\n\tLabel = Window.GetControl (0x1000001D)\n\tLabel.SetText (str (SavThrows[2]))\n\t# Breath\n\tLabel = Window.GetControl (0x1000001F)\n\tLabel.SetText (str (SavThrows[3]))\n\t# Spell\n\tLabel = Window.GetControl (0x10000021)\n\tLabel.SetText (str (SavThrows[4]))\n\n\tFinalCurHP = GemRB.GetPlayerStat (pc, IE_HITPOINTS) + HPGained\n\tFinalMaxHP = GemRB.GetPlayerStat (pc, IE_MAXHITPOINTS) + HPGained\n\n\t# Current HP\n\tLabel = Window.GetControl (0x10000025)\n\tLabel.SetText (str (FinalCurHP))\n\n\t# Max HP\n\tLabel = Window.GetControl (0x10000027)\n\tLabel.SetText (str (FinalMaxHP))\n\n\t# Displaying level up info\n\toverview = \"\"\n\tif CurrWeapProf!=-1 and WeapProfGained>0:\n\t\toverview = overview + GemRB.GetString (38715) + '\\n' + '+' + str (WeapProfGained) + '\\n'\n\n\toverview = overview + str (HPGained) + \" \" + GemRB.GetString (38713) + '\\n'\n\toverview = overview + str (ConHPBon) + \" \" + GemRB.GetString (38727) + '\\n'\n\n\tif SavThrUpdated:\n\t\toverview = overview + GemRB.GetString (38719) + '\\n'\n\tif Thac0Updated:\n\t\tGemRB.SetPlayerStat (pc, IE_TOHIT, Thac0)\n\t\toverview = overview + GemRB.GetString (38718) + '\\n'\n\n\tText = Window.GetControl (3)\n\tText.SetText (overview)\n\n\tWindow.ShowModal (MODAL_SHADOW_GRAY)\n\ndef GetSingleClassHP (Class, Level):\n\tHPTable = GemRB.LoadTable (CommonTables.Classes.GetValue (Class, \"HP\"))\n\n\t# We need to check if Level is larger than 20, since after that point\n\t# the table runs out, and the formula remain the same.\n\tif Level > 20:\n\t\tLevel = 20\n\n\t# We need the Level as a string, so that we can use the column names\n\tLevel = str (Level)\n\n\tSides = HPTable.GetValue (Level, \"SIDES\")\n\tRolls = HPTable.GetValue (Level, \"ROLLS\")\n\tModif = HPTable.GetValue (Level, \"MODIFIER\")\n\n\n\treturn GemRB.Roll (Rolls, Sides, Modif)\n\ndef GetConHPBonus (pc, numPrimLevels, numSecoLevels, levelUpType):\n\tConHPBonTable = GemRB.LoadTable (\"HPCONBON\")\n\n\tcon = str (GemRB.GetPlayerStat (pc, IE_CON))\n\tif levelUpType == 0:\n\t\t# Pure fighter\n\t\treturn ConHPBonTable.GetValue (con, \"WARRIOR\") * numPrimLevels\n\tif levelUpType == 1:\n\t\t# Mage, Priest or Thief\n\t\treturn ConHPBonTable.GetValue (con, \"OTHER\") * numPrimLevels\n\treturn ConHPBonTable.GetValue (con, \"WARRIOR\") * numPrimLevels / 2 + ConHPBonTable.GetValue (con, \"OTHER\") * numSecoLevels / 2\n\ndef GetThac0 (Class, Level):\n\tThac0Table = GemRB.LoadTable (\"THAC0\")\n\t# We need to check if Level is larger than 60, since after that point\n\t# the table runs out, and the value remains the same.\n\tif Level > 60:\n\t\tLevel = 60\n\n\treturn Thac0Table.GetValue (Class, str (Level))\n\n# each gained level is checked for how many new prof points gained\ndef GainedWeapProfs (pc, currProf, currLevel, AvatarName):\n\n\t# Actually looking at the next level\n\tnextLevel = currLevel + 1\n\n\t# The table stops at level 20\n\tif nextLevel < 21:\n\t\tmaxProf = CommonTables.CharProfs.GetValue(str(nextLevel), AvatarName)\n\t\treturn maxProf - currProf\n\n\t# Nameless continues gaining points forever\tat a rate of 1 every 3 levels\n\telif GUICommon.IsNamelessOne(pc) and (currProf-3) <= (nextLevel / 3):\n\t\treturn 1\n\n\treturn 0\n\n###################################################\n# End of file GUIREC.py\n"},"license":{"kind":"string","value":"gpl-2.0"},"hash":{"kind":"number","value":-7488686639834815000,"string":"-7,488,686,639,834,815,000"},"line_mean":{"kind":"number","value":29.8238636364,"string":"29.823864"},"line_max":{"kind":"number","value":174,"string":"174"},"alpha_frac":{"kind":"number","value":0.7056221198,"string":"0.705622"},"autogenerated":{"kind":"bool","value":false,"string":"false"}}},{"rowIdx":475937,"cells":{"repo_name":{"kind":"string","value":"arnaudsj/Petrel"},"path":{"kind":"string","value":"petrel/petrel/package.py"},"copies":{"kind":"string","value":"1"},"size":{"kind":"string","value":"11356"},"content":{"kind":"string","value":"import os\nimport sys\nimport shutil\nimport getpass\nimport socket\nimport zipfile\nimport glob\nimport pkg_resources\nfrom itertools import chain\nfrom cStringIO import StringIO\n\nfrom emitter import EmitterBase\nfrom topologybuilder import TopologyBuilder\nfrom util import read_yaml\n\nMANIFEST = 'manifest.txt'\n\ndef add_to_jar(jar, name, data):\n path = 'resources/%s' % name\n print 'Adding %s' % path\n jar.writestr(path, data)\n\ndef add_file_to_jar(jar, directory, script=None, required=True):\n if script is not None:\n path = os.path.join(directory, script)\n else:\n path = directory\n\n # Use glob() to allow for wildcards, e.g. in manifest.txt.\n path_list = glob.glob(path)\n\n if len(path_list) == 0 and required:\n raise ValueError('No files found matching: %s' % path)\n #elif len(path_list) > 1:\n # raise ValueError(\"Wildcard '%s' matches multiple files: %s\" % (path, ', '.join(path_list)))\n for this_path in path_list:\n with open(this_path, 'r') as f:\n # Assumption: Drop the path when adding to the jar.\n add_to_jar(jar, os.path.basename(this_path), f.read())\n\ndef build_jar(source_jar_path, dest_jar_path, config, venv=None, definition=None, logdir=None):\n \"\"\"Build a StormTopology .jar which encapsulates the topology defined in\n topology_dir. Optionally override the module and function names. This\n feature supports the definition of multiple topologies in a single\n directory.\"\"\"\n\n if definition is None:\n definition = 'create.create'\n\n # Prepare data we'll use later for configuring parallelism.\n config_yaml = read_yaml(config)\n parallelism = dict((k.split('.')[-1], v) for k, v in config_yaml.iteritems()\n if k.startswith('petrel.parallelism'))\n\n pip_options = config_yaml.get('petrel.pip_options', '')\n\n module_name, dummy, function_name = definition.rpartition('.')\n\n topology_dir = os.getcwd()\n\n # Make a copy of the input \"jvmpetrel\" jar. This jar acts as a generic\n # starting point for all Petrel topologies.\n source_jar_path = os.path.abspath(source_jar_path)\n dest_jar_path = os.path.abspath(dest_jar_path)\n if source_jar_path == dest_jar_path:\n raise ValueError(\"Error: Destination and source path are the same.\")\n shutil.copy(source_jar_path, dest_jar_path)\n jar = zipfile.ZipFile(dest_jar_path, 'a', compression=zipfile.ZIP_DEFLATED)\n\n added_path_entry = False\n try:\n # Add the files listed in manifest.txt to the jar.\n with open(os.path.join(topology_dir, MANIFEST), 'r') as f:\n for fn in f.readlines():\n # Ignore blank and comment lines.\n fn = fn.strip()\n if len(fn) and not fn.startswith('#'):\n\n add_file_to_jar(jar, os.path.expandvars(fn.strip()))\n\n # Add user and machine information to the jar.\n add_to_jar(jar, '__submitter__.yaml', '''\npetrel.user: %s\npetrel.host: %s\n''' % (getpass.getuser(),socket.gethostname()))\n\n # Also add the topology configuration to the jar.\n with open(config, 'r') as f:\n config_text = f.read()\n add_to_jar(jar, '__topology__.yaml', config_text)\n\n # Call module_name/function_name to populate a Thrift topology object.\n builder = TopologyBuilder()\n module_dir = os.path.abspath(topology_dir)\n if module_dir not in sys.path:\n sys.path[:0] = [ module_dir ]\n added_path_entry = True\n module = __import__(module_name)\n getattr(module, function_name)(builder)\n\n # Add the spout and bolt Python scripts to the jar. Create a\n # setup_