repo_name
stringlengths 5
114
| repo_url
stringlengths 24
133
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| branch_name
stringclasses 209
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 9.83k
683M
⌀ | star_events_count
int64 0
22.6k
| fork_events_count
int64 0
4.15k
| gha_license_id
stringclasses 17
values | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_language
stringclasses 115
values | files
listlengths 1
13.2k
| num_files
int64 1
13.2k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gagreen/net | https://github.com/gagreen/net | 3f1fb1027d687a29f36c10d2e00227643fff84a2 | 90a48bbf2d2cd501abc2edae15e57cd214e87fe2 | dbeac2683e43406c0cee77c8dce5724be912a2b0 | refs/heads/master | 2021-07-11T17:23:01.951441 | 2020-06-16T14:08:24 | 2020-06-16T14:08:24 | 141,658,832 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6134020686149597,
"alphanum_fraction": 0.7061855792999268,
"avg_line_length": 16.636363983154297,
"blob_id": "cc51da5882c76d9b14616724a0def2959e1f10d7",
"content_id": "12484bcec9040fd4a9f208bfe8574124654e3a35",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 11,
"path": "/client.py",
"repo_name": "gagreen/net",
"src_encoding": "UTF-8",
"text": "import socket\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nsock.connect(('52.78.104.59', 12345))\n\ninp = input()\n\nsock.send(inp.encode())\ndata = sock.recv(65535)\n\nprint(data.decode())\n"
},
{
"alpha_fraction": 0.5904762148857117,
"alphanum_fraction": 0.5904762148857117,
"avg_line_length": 10.666666984558105,
"blob_id": "3faa26147deb3a30867f8de932f1db12a56b9014",
"content_id": "62892e2cfe167cd24e08528d8728dfb61ef91701",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 157,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 9,
"path": "/README.md",
"repo_name": "gagreen/net",
"src_encoding": "UTF-8",
"text": "# net\n\n* 소켓통신\n\n* TWICE Protocol\n\n * Request: twice://멤버이름/키, 몸무게 형식\n\n * Response : 키, 몸무게, 오류 중 하나를 반환\n"
},
{
"alpha_fraction": 0.5215577483177185,
"alphanum_fraction": 0.563282310962677,
"avg_line_length": 27.19607925415039,
"blob_id": "cac85381878b718dca5f54fa689855ad106cb376",
"content_id": "d75756905e80fd5f786a97fcb315055c37c4c296",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1552,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 51,
"path": "/server.py",
"repo_name": "gagreen/net",
"src_encoding": "UTF-8",
"text": "import socket\n\nserver_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nserver_socket.bind(('0.0.0.0', 12345))\nserver_socket.listen(0)\nclient_socket, addr = server_socket.accept()\ndata = client_socket.recv(65535)\n\n__, a, b = data.decode().split('/')\n\nif a == 'nayeon' and b == 'height':\n data = \"163cm 중간 정도\"\nelif a == 'nayeon' and b == 'weight':\n data = '48kg 평균' \nelif a == 'junghyun' and b == 'height' :\n data = '168cm 큰 정도' \nelif a == 'junghyun' and b == 'weight':\n data = '48kg 평균' \nelif a == 'momo' and b == 'height' :\n data = '170cm 큰 정도'\nelif a == 'momo' and b == 'weight':\n data = '52kg 평균 이상'\nelif a == 'sana' and b == 'height' :\n data = '164cm 중간 정도'\nelif a == 'sana' and b == 'weight':\n data = '48kg 평균'\nelif a == 'jihyo' and b == 'height' :\n data = '160cm 작은 정도'\nelif a == 'jihyo' and b == 'weight':\n data = '48kg 평균'\nelif a == 'mina' and b == 'height' :\n data = '163cm 중간 정도'\nelif a == 'mina' and b == 'weight':\n data = '46kg 평균 이하' \nelif a == 'dahyun' and b == 'height' :\n data = '158cm 작은 정도'\nelif a == 'dahyun' and b == 'weight':\n data = '48kg 평균'\nelif a == 'chaeyoung' and b == 'height' :\n data = '159cm 작은 정도'\nelif a == 'chaeyoung' and b == 'weight':\n data = '49kg 평균'\nelif a == 'tsuwi' and b == 'height' :\n data = '170cm 큰 정도'\nelif a == 'tsuwi' and b == 'weight':\n data = '52kg 평균 이상'\nelse :\n data = \"Not supported\" \n\n\nclient_socket.send(data.encode())\n"
}
] | 3 |
Abriel14/TIPE-mecaflu | https://github.com/Abriel14/TIPE-mecaflu | d07c1612996a98b2349fd9e110389138fd3a60db | 5de9df05ed28b02dad81e1140f8b65a2f68aed36 | 65cfa05b9ce5536c8a8ef567f218c53a6b075642 | refs/heads/master | 2021-07-10T05:41:59.181446 | 2017-09-28T18:16:45 | 2017-09-28T18:16:45 | 104,501,620 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5786219239234924,
"alphanum_fraction": 0.6236749291419983,
"avg_line_length": 30.44444465637207,
"blob_id": "3b59cfad74cad6115a8a6f2d38bfb0418e29b99f",
"content_id": "99f741d88810499dbe7ccfdb9113d38967aa6ef2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1139,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 36,
"path": "/ninja.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "import test\nimport matplotlib.pyplot as plt\nimport integration as inte\nimport numpy as np\n\nplt.figure(1)\nplt.ion()\nN = 30 # largeur et hauteur de la grille de calcul\nkmax = 200 # nombre d'itérations à effectuer (solveur)\ndiff = 0.001 # coefficient de diffusion\nvitesse = 1\nut = np.zeros((N, N)) * vitesse # composante horizontale des vecteurs vélocité\nvt = np.zeros((N, N)) # composante verticale des vecteurs vélocité\nu0t = np.zeros((N, N)) * vitesse\nv0t = np.zeros((N, N)) # tableaux temporaires relatifs à u et v\np = np.zeros((N, N))\ndiv = np.zeros((N, N))\ndt = 1\nf = 0.2\nepsilon = 0.01\nrang = 0\n# for i in range(N):\n# for j in range(N):\n# ut[i,j] = vitesse*(abs(15-j)/15)\n# u0t[i,j] = vitesse*(abs(15-j)/15)\nu, v, u0, v0, p = inte.apply_integration(1, u0t, v0t, ut, vt, p, div, f, kmax, dt, diff, 5)\nwhile np.linalg.norm(abs(u - u0)) > epsilon:\n u, v, u0, v0, p = inte.apply_integration(1, u0, v0, u, v, p, div, f, kmax, dt, diff, 5)\n rang += 1\n print(rang, np.linalg.norm((abs(u - u0) + abs(v - v0)), 2))\n plt.clf()\n plt.quiver(u, v)\n plt.pause(0.0001)\nprint(p)\nplt.ioff()\nplt.show()\n"
},
{
"alpha_fraction": 0.33214178681373596,
"alphanum_fraction": 0.3943997621536255,
"avg_line_length": 28.699115753173828,
"blob_id": "742d2e0016a96527f32e32a264146d9e42173558",
"content_id": "21bc78bed1b9d61e41099ddfdc81b74e618e015c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3365,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 113,
"path": "/rewrite.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport cython\n\n\n# ctypedef np.int_t DTYPE_t\n# ctypedef np.float_t DTYPE_f\n\[email protected](False)\[email protected](False)\ndef set_bnd(N, b, x):\n if b == 1: # horizontal\n for i in range(int(N / 2 ) - 5, int(N / 2) + 5 + 1):\n for j in range(int(N / 2) - 5 - 1, int(N / 2) + 5 + 2):\n x[i, j] = 0\n for k in range(N+2):\n x[0,k] = 1\n if b == 2: # vertical\n for i in range(int(N / 2) - 5 - 1, int(N / 2) + 5 + 2):\n for j in range(int(N / 2) - 5, int(N / 2) + 5 + 1):\n x[i, j] = 0\n x[0, 0] = 0.5 * (x[1, 0] + x[0, 1])\n x[0, N + 1] = 0.5 * (x[1, N + 1] + x[0, N])\n x[N + 1, 0] = 0.5 * (x[N, 0] + x[N + 1, 1])\n x[N + 1, N + 1] = 0.5 * (x[N, N + 1] + x[N + 1, N])\n\n\ndef add_source(N, x, s, dt):\n for i in range(N + 2):\n for j in range(N + 2):\n x[i] = dt * s[i]\n\n\ndef diffuse(N, b, x, x0, diff, dt):\n a = dt * diff * N * N\n for k in range(100):\n for i in range(1, N + 1):\n for j in range(1, N + 1):\n x[i, j] = (x0[i, j] + a * (x[i - 1, j] + x[i + 1, j] + x[i, j - 1] + x[i, j + 1])) / (1 + 4 * a)\n set_bnd(N, b, x)\n\n\ndef advect(N, b, d, d0, u, v, dt):\n dt0 = dt * N\n for i in range(1, N + 1):\n for j in range(1, N + 1):\n # position de la particule à l'instant précédent\n x = i - dt0 * u[i, j]\n y = j - dt0 * v[i, j]\n # conditions aux limites: taille de la grille\n if x < 0.5: x = 0.5\n if x >= N + 0.5: x = N + 0.5\n i0 = int(x)\n i1 = i0 + 1\n if y < 0.5: y = 0.5\n if y >= N + 0.5: y = N + 0.5\n j0 = int(y)\n j1 = j0 + 1\n # interpolation:\n s1 = x - i0\n s0 = 1 - s1\n t1 = y - j0\n t0 = 1 - t1\n d[i, j] = s0 * (t0 * d0[i0, j0] + t1 * d0[i0, j1]) + s1 * (t0 * d0[i1, j0] + t1 * d0[i1, j1])\n set_bnd(N, b, d)\n\n\ndef project(N, u, v, p, div):\n h = 1 / N\n ## calcul de la divergence\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n div[i, j] = -0.5 * h * (u[i + 1, j] - u[i - 1, j] + v[i, j + 1] - v[i, j - 1])\n p[i, j] = 0\n set_bnd(N, 0, div)\n set_bnd(N, 0, p)\n\n ## Résolution du système\n for k in range(100):\n for i in range(1, N + 1):\n for j in range(1, N + 1):\n p[i, j] = (div[i, j] + p[i - 1, j] + p[i + 1, j] + p[i, j - 1] + p[i, j + 1]) / 4\n set_bnd(N, 0, p)\n\n ## Mise à jour des vélocités\n for i in range(1, N + 1):\n for j in range(1, N + 1):\n u[i, j] -= 0.5 * (p[i + 1, j] - p[i - 1, j]) / h\n v[i, j] -= 0.5 * (p[i, j + 1] - p[i, j - 1]) / h\n set_bnd(N, 1, u)\n set_bnd(N, 2, v)\n\n\ndef dens_step(N, x, x0, u, v, diff, dt):\n add_source(N, x, x0, dt)\n x, x0 = x0, x\n diffuse(N, 0, x, x0, diff, dt)\n x, x0 = x0, x\n advect(N, 0, x, x0, u, v, dt)\n\n\ndef vel_step(N, u, v, u0, v0, visc, dt):\n add_source(N, u, u0, dt)\n add_source(N, v, v0, dt)\n u0, u = u, u0\n diffuse(N, 1, u, u0, visc, dt)\n v0, v = v, v0\n diffuse(N, 2, v, v0, visc, dt)\n project(N, u, v, u0, v0)\n u0, u = u, u0\n v0, v = v, v0\n advect(N, 1, u, u0, u, v, dt)\n advect(N, 2, v, v0, u, v, dt)\n project(N, u, v, u0, v0)\n\n"
},
{
"alpha_fraction": 0.7382199168205261,
"alphanum_fraction": 0.7486910820007324,
"avg_line_length": 23,
"blob_id": "e55b5669393b85010882eca536fafa15bdb401c9",
"content_id": "92933d586c85710292d5b1a66034127ff3ecefba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 191,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 8,
"path": "/setup2.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "from distutils.core import setup\nfrom Cython.Build import cythonize\nimport numpy\nsetup(\n name = 'test2',\n ext_modules = cythonize(\"integration2.pyx\"),\n include_dirs=[numpy.get_include()]\n)"
},
{
"alpha_fraction": 0.5728952884674072,
"alphanum_fraction": 0.5926591157913208,
"avg_line_length": 43.272727966308594,
"blob_id": "3e63eda285c5a1e968c6fe62612170d571a33d20",
"content_id": "c5fff2cb281bef859addcdbda49495303fe335a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3907,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 88,
"path": "/main.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.spatial as scsp\nfrom cmath import *\n\ndef function_wing(a, c, d, theta):\n r = abs(complex(c - a, d))\n return (\n 0.5 * ((complex(c, d) + r * exp(complex(0, theta))) + (a * a) / (complex(c, d) + r * exp(complex(0, theta)))))\n\n\ndef generate_wing(a, c, d, n):\n ## fonction renvoyant la liste des points (complexes, et dans R²) de l'aile\n theta = np.linspace(-np.pi, np.pi, n)\n wing_complex = np.zeros(n) * complex(0, 1)\n x = np.zeros(n)\n y = np.zeros(n)\n wing = np.zeros((n, 2))\n for k in range(n):\n wing_complex[k] = function_wing(a, c, d, theta[k])\n x[k] = (wing_complex[k].real)\n y[k] = (wing_complex[k].imag)\n wing[k] = [x[k], y[k]]\n return (x, y, wing, wing_complex,)\n\n\ndef generate_layers(wing_complex, nbr_of_layers):\n n = len(wing_complex)\n points_complex = np.zeros((nbr_of_layers, n)) * complex(0, 1)\n ## injecter les points de la matrice wing_complex dans la première ligne de la matrice points\n for k in range(n):\n points_complex[0, k] = wing_complex[k]\n ## calculer les points à ajouter étant des translation de chaque point selon la normale entre 2 points:\n ## créer un maillage plus précis sur les bords de l'aile\n for h in range(1, nbr_of_layers):\n rapport = np.exp(h * h / (nbr_of_layers * nbr_of_layers)) - 1\n for k in range(n - 1):\n zprime = points_complex[h - 1, k + 1] - points_complex[h - 1, k]\n argu = phase(zprime)\n z_step = exp(complex(0, np.pi / 2 + argu))\n z_moy = (points_complex[h - 1, k + 1] + points_complex[h - 1, k]) / 2\n # argu = phase(z_moy)\n # z_step = exp(complex(0, np.pi / 2 + argu))\n z0 = z_moy + z_step * rapport\n points_complex[h, k] = z0\n ## traitement du cas final: placer un point translaté entre le point de coordonée [h-1,0] et [h-1,n-1]\n zprime = points_complex[h - 1, 0] - points_complex[h - 1, n - 1]\n argu = phase(zprime)\n z_step = exp(complex(0, np.pi / 2 + argu))\n z_moy = (points_complex[h - 1, 0] + points_complex[h - 1, n - 1]) / 2\n # argu = phase(z_moy)\n # z_step = exp(complex(0, np.pi / 2 + argu))\n z0 = z_moy + z_step * rapport\n points_complex[h, n - 1] = z0\n ## transformation de la matrice points_complex en points: array de taille (n*nbr_of_layers,2) listant les coordonées dans R² des points complexes\n points_complex = np.reshape(points_complex, n * nbr_of_layers)\n points = np.zeros((n * nbr_of_layers, 2))\n for k in range(n * nbr_of_layers):\n points[k] = [points_complex[k].real, points_complex[k].imag]\n return (points)\n\n\ndef generate_meshes(a, c, d, n, nbr_of_layers):\n ## Fonction renvoyant la liste des meshes, la liste des barycentres de tout les meshes et une liste des indice des mesh etant dans l'aile.\n x, y, wing, wing_complex = generate_wing(a, c, d, n)\n points = generate_layers(wing_complex, nbr_of_layers)\n all_meshes = scsp.Delaunay(points)\n nbr_of_tri = len(all_meshes.simplices)\n all_bary = np.zeros((nbr_of_tri, 2))\n for k in range(nbr_of_tri):\n [[xa, ya], [xb, yb], [xc, yc]] = points[all_meshes.simplices[k]]\n all_bary[k] = [(xa + xb + xc) / 3, (ya + yb + yc) / 3]\n ## tester si les 3 sommet de chaque triangle appartient à l'ensemble des sommets de l'aile et si oui l'ajouter au masque\n mask = []\n for k in range(nbr_of_tri):\n if np.isin(points[all_meshes.simplices[k]], wing).all() == True:\n mask.append(k)\n return (all_meshes, all_bary, mask)\n\n\ntri1, barycentres, mask = generate_meshes(5, 0.5, 0.4,100 , )\np0 = tri1.points\nprint(mask)\nplt.triplot(p0[:, 0], p0[:, 1], tri1.simplices.copy())\nplt.plot(p0[:, 0], p0[:, 1], 'o')\n#plt.plot(barycentres[:, 0][mask], barycentres[:, 1][mask], 'o')\n\nplt.show()\n"
},
{
"alpha_fraction": 0.4288419783115387,
"alphanum_fraction": 0.47510823607444763,
"avg_line_length": 27.875,
"blob_id": "d353ad7a6c6fdc81074fa90143f745942cbae029",
"content_id": "6647085eff3df4e6554a2ab55dc78d2bd3e5fa89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3711,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 128,
"path": "/stable-fluids.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom gauss_seidel import gauss_seidel\n\n\nN = 100 # largeur et hauteur de la grille de calcul\nkmax = 100 # nombre d'itérations à effectuer (solveur)\ndiff = 40 # coefficient de diffusion\n\nvitesse = 2\nut = np.ones((N, N))*vitesse # composante horizontale des vecteurs vélocité\nvt = np.zeros((N, N)) # composante verticale des vecteurs vélocité\nu0t = np.ones((N, N))*vitesse\nv0t = np.zeros((N, N)) # tableaux temporaires relatifs à u et v\np = np.zeros((N, N))\ndiv = np.zeros((N, N))\ndt = 1\nf = 1\n\n\n# def apply_bound(b, x):\n# N = len(x)\n# if b == 0: # champs de pression\n# for i in range(int(N / 2) - 5, int(N / 2) + 5):\n# for j in range(int(N / 2 - 5), int(N / 2) + 5):\n# x[i, j] = 1\n# if b == 1: # horizontal\n# for i in range(int(N / 2) - 5, int(N / 2 + 5)):\n# for j in range(int(N / 2) - 6, int(N / 2) + 6):\n# x[i, j] = 0\n# if b == 2: # vertical\n# for i in range(int(N / 2) - 6, int(N / 2) + 6):\n# for j in range(int(N / 2) - 5, int(N / 2) + 5):\n# x[i, j] = 0\n#\n#\n# def linear_solver(b, x, x0, a, c, kmax):\n# for k in range(kmax):\n# for i in range(1, N - 1):\n# for j in range(1, N - 1):\n# x[i, j] = (x0[i, j] + a * (x[i - 1, j] + x[i + 1, j] + x[i, j - 1] + x[i, j + 1])) / c\n# apply_bound(b, x)\n\n\ndef diffuse_step(u0,v0,u,v):\n u0, u = u, u0\n v0, v = v, v0\n a = dt * diff * N * N\n gauss_seidel.linear_solver(1, u, u0, a, 1 + 4 * a, kmax)\n gauss_seidel.linear_solver(2, v, v0, a, 1 + 4 * a, kmax)\n\n\n\n\ndef advection(b, d, d0, u, v,f):\n dt0 = dt * N\n for i in range(N):\n for j in range(N):\n # position de la particule à l'instant précédent\n x = i - dt0 * u[i, j]\n y = j - dt0 * v[i, j]\n # conditions aux limites: taille de la grille\n if x < 0: x = 0\n if x >= N - 1: x = N - 2\n i0 = int(x)\n i1 = i0 + 1\n if y < 0: y = 0\n if y >= N - 1: y = N - 2\n j0 = int(y)\n j1 = j0 + 1\n # interpolation:\n s1 = x - i0\n s0 = 1 - s1\n t1 = y - j0\n t0 = 1 - t1\n d[i, j] = s0 * (t0 * d0[i0, j0] + t1 * d0[i0, j1]) + s1 * (t0 * d0[i1, j0] + t1 * d0[i1, j1]);\n gauss_seidel.apply_bound(b, d)\n\n\ndef advection_step(u0,v0,u,v,f):\n (u0, u) = (u, u0)\n (v0, v) = (v, v0)\n advection(1, u, u0 , u, v,f)\n advection(2, v, v0, u , v,f)\n\n\ndef projection(u, v, p, div, kmax,f):\n N = len(p)\n ## calcul de la divergence\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n div[i, j] = -0.5 * f * (u[i + 1, j] - u[i - 1, j] + v[i, j + 1] - v[i, j - 1]) / N;\n p[i, j] = 0\n\n gauss_seidel.apply_bound(0, div)\n gauss_seidel.apply_bound(0, p)\n\n ## Résolution du système\n gauss_seidel.linear_solver(0, p, div, 1, 4, kmax);\n\n ## Mise à jour des vélocités\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n u[i, j] -= 0.5 * f * N * (p[i + 1, j] - p[i - 1, j])\n v[i, j] -= 0.5 * f * N * (p[i, j + 1] - p[i, j - 1])\n\n gauss_seidel.apply_bound(1, u)\n gauss_seidel.apply_bound(2, v)\n\n\ndef projection_step(u,v,f):\n projection(u, v, p, div, kmax,f)\n\n\ndef integration_step(u0,v0,u,v,f):\n diffuse_step(u0,v0,u,v)\n advection_step(u0,v0,u,v,f)\n projection_step(u,v,f)\n\ndef apply_integration(iterations):\n for k in range(iterations):\n integration_step(u0t,v0t,ut,vt,f)\n print(k/iterations*100,\"%\")\n\napply_integration(10000)\n\nplt.quiver(ut,vt)\nplt.show()\n"
},
{
"alpha_fraction": 0.5361344814300537,
"alphanum_fraction": 0.5806722640991211,
"avg_line_length": 27.33333396911621,
"blob_id": "cced691346c932d076ec7274564165afc231a283",
"content_id": "89eecb65d38bdf1d9308eb90ee4e39e6144f0acd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1196,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 42,
"path": "/start_stable_fluids.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "import test\nimport matplotlib.pyplot as plt\nfrom integration2 import *\nimport numpy as np\n\nplt.figure(1)\nplt.ion()\nN = 50 # largeur et hauteur de la grille de calcul\ndiff = 0.01 # coefficient de diffusion\nvisc = 10 # coefficient de viscosité\nvitesse = 0.1\nu = np.zeros((N + 2, N + 2)) * vitesse # composante horizontale des vecteurs vélocité\nv = np.zeros((N + 2, N + 2)) # composante verticale des vecteurs vélocité\nu_prev = np.zeros((N + 2, N + 2)) * vitesse\nv_prev = np.zeros((N + 2, N + 2)) # tableaux temporaires relatifs à u et v\ndens = np.ones((N + 2, N + 2))\ndens_prev = np.ones((N + 2, N + 2))\ndt = 0.0005\nepsilon = 0.01\nbounds = np.zeros((N+2,N+2),dtype=bool)\nfor i in range(N+2):\n for j in range(N+2):\n dens[i,j] = j/(N+2)\n dens_prev[i, j] = j / (N + 2)\nk = 0\n\n\nwhile k < 100:\n plt.clf()\n plt.quiver(v,u)\n u_prev = np.ones((N+2,N+2))*vitesse\n for i in range(N + 2):\n for j in range(N + 2):\n dens[i, j] = j / (N + 2)\n dens_prev[i, j] = j / (N + 2)\n dens, u, v = simulate_step(N, u, v, u_prev, v_prev, dens, dens_prev, diff, visc, dt)\n k += 1\n print(k)\n plt.pause(0.0001)\nprint(dens)\nplt.ioff()\nplt.show()\n"
},
{
"alpha_fraction": 0.747474730014801,
"alphanum_fraction": 0.747474730014801,
"avg_line_length": 23.875,
"blob_id": "70f9b7460345ba7b0bfad574c989d121d66c588f",
"content_id": "50f8150be95be7bf0185e738f17d77583ab3878c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 198,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 8,
"path": "/gauss_seidel/setup.py",
"repo_name": "Abriel14/TIPE-mecaflu",
"src_encoding": "UTF-8",
"text": "from distutils.core import setup\nfrom Cython.Build import cythonize\nimport numpy\nsetup(\n name = 'gauss_seidel',\n ext_modules = cythonize(\"gauss_seidel.pyx\"),\n include_dirs=[numpy.get_include()]\n)"
}
] | 7 |
klongmore/optimal-hangman | https://github.com/klongmore/optimal-hangman | 7d9e152eafbd86b7be763649e586562b35029b8d | d6e206405c465c16ae05b540d4883aac6e5450b1 | 4f4dfced7c9c6ca8fd44fb6c1e662b07a1d6bc4e | refs/heads/master | 2022-05-25T07:27:53.563900 | 2020-05-01T03:16:57 | 2020-05-01T03:16:57 | 260,207,081 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6601895689964294,
"alphanum_fraction": 0.6696682572364807,
"avg_line_length": 23.546510696411133,
"blob_id": "32a1badb9698cdaf13c44946f185aa044646e938",
"content_id": "92a5516c5d5c2e292cef36493fe98999f8d1021a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2110,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 86,
"path": "/hangman.py",
"repo_name": "klongmore/optimal-hangman",
"src_encoding": "UTF-8",
"text": "from string import ascii_lowercase\nfrom wordfreq import zipf_frequency, word_frequency\nimport sys\n\ndec_mode = False\n\nif len(sys.argv) == 2:\n\tif sys.argv[1] == '-d':\n\t\tdec_mode = True\n\nwith open('words.txt', 'r') as f:\n\twords = f.read().split()\n\ngameover = False\nguessed = []\nguessed_wrong = []\ncurrent_word = ''\n\nwhile True:\n\told_word = current_word\n\n\tcurrent_word = input('Please enter your word (underscores for blank spaces): ')\n\tcurrent_word_length = len(current_word)\n\n\tif current_word == old_word:\n\t\tguessed_wrong.append(most_likely_letter)\n\n\tif current_word.count('_') == 0:\n\t\tgameover = True\n\t\tbreak\n\n\twords_alt = []\n\n\tfor word in words:\n\t\tif len(word) == current_word_length:\n\t\t\tfor x in range(current_word_length):\n\t\t\t\tif (current_word[x] == word[x] or current_word[x] == '_') and current_word[x] not in guessed_wrong:\n\t\t\t\t\tpossible = True\n\t\t\t\telse:\n\t\t\t\t\tpossible = False\n\t\t\t\t\tbreak\n\t\t\tif possible:\n\t\t\t\twords_alt.append(word)\n\n\tif len(words_alt) == 1:\n\t\tprint('I guess: ' + words_alt[0])\n\t\tgameover = True\n\t\tbreak\n\n\toption_dicts = []\n\n\tfor option in words_alt:\n\t\tif dec_mode:\n\t\t\tfreq = round(word_frequency(option, 'en', wordlist='best', minimum=0.0) + 0.0000001, 7)\n\t\telse:\n\t\t\tfreq = zipf_frequency(option, 'en', wordlist='best', minimum=0.0) + 1\t\n\t\toption_dict = dict(word=option, freq=freq)\n\t\toption_dicts.append(option_dict)\n\n\tletter_dicts = []\n\n\tfor letter in ascii_lowercase:\n\t\tletter_dict = dict(letter=letter, score=0)\n\t\tletter_dicts.append(letter_dict)\n\n\tfor option_dict in option_dicts:\n\t\tfor letter in option_dict[\"word\"]:\n\t\t\tnext(item for item in letter_dicts if item[\"letter\"] == letter)[\"score\"] += option_dict[\"freq\"]\n\n\toption_dicts = sorted(option_dicts, key=lambda o: o['freq'], reverse=True)\n\tletter_dicts = sorted(letter_dicts, key=lambda l: l['score'], reverse=True)\n\n\tmost_likely_letter = ''\n\n\tfor letter in letter_dicts:\n\t\tif letter[\"letter\"] not in guessed:\n\t\t\tmost_likely_letter = letter[\"letter\"]\n\t\t\tbreak\n\n\tprint('I guess: ' + most_likely_letter)\n\tguessed.append(most_likely_letter)\n\n\twords = words_alt\n\nprint('Game over.')\nprint('Wrong guesses: ' + str(len(guessed_wrong)))"
}
] | 1 |
pg815/Fake_News_Prediction_And_Summarization | https://github.com/pg815/Fake_News_Prediction_And_Summarization | d2cf75c2a30ab3d663543b19ddcbfded07523c09 | 5609a521e615bef067b3a3c60134ca0fdeba6bdf | 5eb330b9cad340489b9e220398a8c0b961c411b7 | refs/heads/main | 2023-08-24T17:57:30.960786 | 2021-10-18T19:05:05 | 2021-10-18T19:05:05 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5120325684547424,
"alphanum_fraction": 0.7030729651451111,
"avg_line_length": 16.203821182250977,
"blob_id": "ed906085b61f6c447626e85a20615294f2d67f09",
"content_id": "63cebb30f6bf83fb10dfe8c002911b1a4e2ce314",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 2701,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 157,
"path": "/requirements.txt",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "absl-py==0.11.0\nastor==0.8.1\nastunparse==1.6.3\nasync-generator==1.10\nattrs==20.3.0\nbackcall==0.2.0\nbeautifulsoup4==4.9.3\nbert-extractive-summarizer==0.6.1\nbleach==3.2.3\nblis==0.7.4\nbreadability==0.1.20\nbs4==0.0.1\ncached-property==1.5.2\ncachetools==4.2.1\ncatalogue==2.0.1\ncertifi==2020.12.5\nchardet==3.0.4\nclick==7.1.2\ncontextvars==2.4\ncssselect==1.1.0\ncycler==0.10.0\ncymem==2.0.5\nCython==0.29.21\ndataclasses\ndecorator==4.4.2\ndefusedxml==0.6.0\ndill==0.3.3\ndocopt==0.6.2\neazymind==0.0.4\nentrypoints==0.3\nenum34==1.1.10\nfeedfinder2==0.0.4\nfeedparser==6.0.2\nfilelock==3.0.12\nFlask==1.1.2\nflatbuffers==1.12\ngast==0.3.3\ngensim==3.8.1\ngoogle-auth==1.4.2\ngoogle-auth-oauthlib==0.4.2\ngoogle-colab==1.0.0\ngoogle-pasta==0.2.0\ngrpcio==1.32.0\nh5py==2.10.0\nidna==2.8\nimmutables==0.15\nimportlib-metadata==3.4.0\nipykernel==4.6.1\nipython==5.5.0\nipython-genutils==0.2.0\nitsdangerous==1.1.0\njedi==0.18.0\njieba3k==0.35.1\nJinja2==2.11.2\njoblib==1.0.0\njsonschema==3.2.0\njupyter-client==6.1.11\njupyter-core==4.7.0\njupyterlab-pygments==0.1.2\nKeras==2.4.3\nKeras-Applications==1.0.8\nkeras-attention==1.0.0\nKeras-Preprocessing==1.1.2\nkiwisolver==1.3.1\nlxml==4.6.2\nMarkdown==3.3.3\nMarkupSafe==1.1.1\nmatplotlib==3.3.3\nmistune==0.8.4\nmultiprocess==0.70.11.1\nmurmurhash==1.0.5\nnbclient==0.5.1\nnbconvert==6.0.7\nnbformat==5.1.2\nnest-asyncio==1.5.1\nnetworkx==1.11\nnewspaper3k==0.2.8\nnltk==3.2.4\nnotebook==5.2.2\nnumpy==1.19.5\noauthlib==3.1.0\nopt-einsum==3.3.0\npackaging==20.8\npandas==0.24.2\npandas-ml==0.6.1\npandocfilters==1.4.3\nparso==0.8.1\npathos==0.2.7\npathy==0.4.0\npexpect==4.8.0\npickleshare==0.7.5\nPillow==8.1.0\nportpicker==1.2.0\npox==0.2.9\nppft==1.6.6.3\npreshed==3.0.5\nprettytable==2.0.0\nprompt-toolkit==1.0.18\nprotobuf==3.14.0\nptyprocess==0.7.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\npydantic==1.7.3\nPygments==2.7.4\npyparsing==2.4.7\npyrsistent==0.17.3\npysummarization==1.1.7\npython-dateutil==2.8.1\npytz==2020.5\nPyYAML==5.4.1\npyzmq==22.0.0\nregex==2020.11.13\nrequests==2.21.0\nrequests-file==1.5.1\nrequests-oauthlib==1.3.0\nrouge==1.0.0\nrsa==4.7\nsacremoses==0.0.43\nscikit-learn==0.20.4\nscikit-plot==0.3.7\nscipy==1.5.4\nsgmllib3k==1.0.0\nsimplegeneric==0.8.1\nsix==1.12.0\nsklearn\nsmart-open==3.0.0\nsoupsieve==2.1\nspacy==3.0.3\nspacy-legacy==3.0.1\nsrsly==2.4.0\nsumy==0.7.0\ntensorboard==2.4.1\ntensorboard-plugin-wit==1.8.0\ntensorflow==2.4.1\ntensorflow-estimator==2.4.0\ntermcolor==1.1.0\nterminado==0.9.2\ntestpath==0.4.4\ntextsummarizer==1.0.0\nthinc==8.0.1\nthreadpoolctl==2.1.0\ntinysegmenter==0.3\ntldextract==3.1.0\ntokenizers==0.10.1\ntornado==4.5.3\ntqdm==4.56.0\ntraitlets==4.3.3\ntransformers==4.3.2\ntyper==0.3.2\ntyping-extensions==3.7.4.3\nurllib3==1.24.3\nwasabi==0.8.2\nwcwidth==0.2.5\nwebencodings==0.5.1\nWerkzeug==1.0.1\nwrapt==1.12.1\nzipp==3.4.0\n"
},
{
"alpha_fraction": 0.6327013969421387,
"alphanum_fraction": 0.6327013969421387,
"avg_line_length": 25.25,
"blob_id": "a48989452b5fcef7d622c3af2c6fcb2ff2c7b0cc",
"content_id": "4c9adf2f0fa3864dd5c225bc2e74583481f0d2ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 422,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 16,
"path": "/summa/preprocessing/util.py",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "\n\ndef suffix_replace(original, old, new):\n \"\"\"\n Replaces the old suffix of the original string by a new suffix\n \"\"\"\n return original[: -len(old)] + new\n\n\ndef prefix_replace(original, old, new):\n \"\"\"\n Replaces the old prefix of the original string by a new suffix\n :param original: string\n :param old: string\n :param new: string\n :return: string\n \"\"\"\n return new + original[len(old) :]\n"
},
{
"alpha_fraction": 0.6779661178588867,
"alphanum_fraction": 0.691525399684906,
"avg_line_length": 25.909090042114258,
"blob_id": "2f3f02dd1c89e2e21f79d870e052d1c8dedd9ea7",
"content_id": "a269a0fa4929ccbe06e2bb16306c0377b4ff9c0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 295,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 11,
"path": "/app.py",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "from flask import Flask,render_template\nfrom newsscraper import get_news,get_titles\napp = Flask(\"__WorldTime__\")\n\[email protected](\"/\")\ndef root():\n channels = get_news()\n titles = get_titles()\n return render_template(\"index.html\",channels = channels,titles = titles)\n\napp.run(host='0.0.0.0')"
},
{
"alpha_fraction": 0.5529412031173706,
"alphanum_fraction": 0.5642156600952148,
"avg_line_length": 34.155174255371094,
"blob_id": "a1c39627f735c8d7c06f27b9ea328ca261fea4a4",
"content_id": "4fd5b8068e9197fe2f2e674518a9ce8223487e86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2040,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 58,
"path": "/model.py",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "from getEmbeddings import getEmbeddings\nfrom sklearn.naive_bayes import GaussianNB\nimport scikitplot.plotters as skplt\nfrom sklearn.svm import SVC\nimport numpy as np\nimport pickle\nimport os\n\nclass Models:\n\n def __init__(self):\n if not os.path.isfile('./xtr.npy') or \\\n not os.path.isfile('./xte.npy') or \\\n not os.path.isfile('./ytr.npy') or \\\n not os.path.isfile('./yte.npy'):\n xtr, xte, ytr, yte = getEmbeddings(\"datasets/train.csv\")\n np.save('./xtr', xtr)\n np.save('./xte', xte)\n np.save('./ytr', ytr)\n np.save('./yte', yte)\n\n self.xtr = np.load('./xtr.npy')\n self.xte = np.load('./xte.npy')\n self.ytr = np.load('./ytr.npy')\n self.yte = np.load('./yte.npy')\n\n def train_svc_classifier(self):\n clf = SVC()\n clf.fit(self.xtr, self.ytr)\n #pickle.dump(clf, open(\"moddel.sav\", \"wb\"))\n y_pred = clf.predict(self.xte)\n m = self.yte.shape[0]\n n = (self.yte != y_pred).sum()\n print(\"Accuracy of Support Vector Machine Classifier = \" + format((m - n) / m * 100, '.2f') + \"%\")\n\n def train_nb_classifier(self):\n gnb = GaussianNB()\n gnb.fit(self.xtr, self.ytr)\n y_pred = gnb.predict(self.xte)\n m = self.yte.shape[0]\n n = (self.yte != y_pred).sum()\n print(\"Accuracy of Gaussian Naive Bayes Classifier = \" + format((m - n) / m * 100, '.2f') + \"%\") # 72.94%\n\n def predict_truthfullness(self,news):\n load_model = pickle.load(open('model.sav', 'rb'))\n prediction = load_model.predict([news])\n prob = load_model.predict_proba([news])\n\n return [\"The given statement is \" + str(prediction[0]),\"The truth probability score is \" + str(prob[0][1])]\n\n\nif __name__ == \"__main__\":\n model = Models()\n # model.train_svc_classifier()\n # model.train_nb_classifier()\n result = model.predict_truthfullness(\"obama is running for president in 2022\")\n print(result[0])\n print(result[1])\n\n"
},
{
"alpha_fraction": 0.7463343143463135,
"alphanum_fraction": 0.7609970569610596,
"avg_line_length": 27.29166603088379,
"blob_id": "8af74e50faba6b2e0933372d052712a59b89fb9c",
"content_id": "af04b403767de3efe0ea65ad0b81eb7908568e2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 682,
"license_type": "no_license",
"max_line_length": 212,
"num_lines": 24,
"path": "/README.md",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "# Fake_News_Prediction_And_Summarization\nThe goal of this project is to scrape the latest published news from BBC News, Fox News, etc and get the truthfulness of news, and generate the news summary using Text Rank, TF-IDF and Word Frequency Algorithms \n\n### To run application\n\n1. Install all libraries\n$ pip install -r requirements.txt\n\n2. Run the application\n$ python app.py\n\n3. In Browser open URL localhost:5000\n\n#### Landing page with latest news\n\n\n\n#### The truthfulness of news\nHighlighted text show the news truthfulness\n\n\n#### News summarization\nClick summary button to get news summarization\n\n\n\n\n"
},
{
"alpha_fraction": 0.5708264708518982,
"alphanum_fraction": 0.5752244591712952,
"avg_line_length": 30.339080810546875,
"blob_id": "90e33d0922f6b710c0593c1cf3569316857e8f1d",
"content_id": "b160b1d91c478377bd5181f844ffda4a08f07033",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5457,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 174,
"path": "/newsscraper.py",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "import sys\nimport json\nfrom time import mktime\nfrom datetime import datetime\nimport feedparser as fp\nimport newspaper\nfrom newspaper import Article\nfrom model import Models\nfrom summarizers import summarize_textrank,summarize_tfidf,summarize_wf\n\ndata = {}\ndata[\"newspapers\"] = {}\nmodel = Models()\n\ndef parse_config(fname):\n # Loads the JSON files with news sites\n with open(fname, \"r\") as data_file:\n cfg = json.load(data_file)\n\n for company, value in cfg.items():\n if \"link\" not in value:\n raise ValueError(f\"Configuration item {company} missing obligatory 'link'.\")\n\n return cfg\n\ndef _handle_rss(company, value, count, limit):\n\n fpd = fp.parse(value[\"rss\"])\n print(f\"Downloading articles from {company}\")\n news_paper = {\"rss\": value[\"rss\"], \"link\": value[\"link\"], \"articles\": []}\n for entry in fpd.entries:\n\n if not hasattr(entry, \"published\"):\n continue\n if count > limit:\n break\n article = {}\n article[\"link\"] = entry.link\n date = entry.published_parsed\n article[\"published\"] = datetime.fromtimestamp(mktime(date)).isoformat()\n try:\n content = Article(entry.link)\n content.download()\n content.parse()\n except Exception as err:\n print(err)\n print(\"continuing...\")\n continue\n article[\"title\"] = content.title\n article[\"text\"] = content.text\n news_paper[\"articles\"].append(article)\n print(f\"{count} articles downloaded from {company}, url: {entry.link}\")\n count = count + 1\n return count, news_paper\n\ndef _handle_fallback(company, value, count, limit):\n\n print(f\"Building site for {company}\")\n paper = newspaper.build(value[\"link\"], memoize_articles=False)\n news_paper = {\"link\": value[\"link\"], \"articles\": []}\n none_type_count = 0\n for content in paper.articles:\n if count > limit:\n break\n try:\n content.download()\n content.parse()\n except Exception as err:\n print(err)\n print(\"continuing...\")\n continue\n\n if content.publish_date is None:\n print(f\"{count} Article has date of type None...\")\n none_type_count = none_type_count + 1\n if none_type_count > 10:\n print(\"Too many noneType dates, aborting...\")\n none_type_count = 0\n break\n count = count + 1\n continue\n article = {\n \"title\": content.title,\n \"text\": content.text,\n \"link\": content.url,\n \"published\": content.publish_date.isoformat(),\n }\n news_paper[\"articles\"].append(article)\n print(\n f\"{count} articles downloaded from {company} using newspaper, url: {content.url}\"\n )\n count = count + 1\n none_type_count = 0\n return count, news_paper\n\ndef run(config, limit=4):\n\n for company, value in config.items():\n count = 1\n if \"rss\" in value:\n count, news_paper = _handle_rss(company, value, count, limit)\n else:\n count, news_paper = _handle_fallback(company, value, count, limit)\n data[\"newspapers\"][company] = news_paper\n\n return data\n\ndef main():\n try:\n config = parse_config(\"NewsPapers.json\")\n except Exception as err:\n sys.exit(err)\n return run(config, limit=3)\n\ndef get_image(image_link):\n url= image_link\n article = Article(url, language=\"en\") # en for English\n article.download()\n article.parse()\n article.nlp()\n return article.top_image\n\n\ndef get_news():\n data = main()\n bbcNews = data['newspapers']['bbc']['articles']\n cnnNews = data['newspapers']['cnn']['articles']\n foxNews = data['newspapers']['foxnews']['articles']\n nytimesNews = data['newspapers']['nytimes_international']['articles']\n washingtonpostNews = data['newspapers']['washingtonpost']['articles']\n\n channels = [bbcNews, cnnNews, foxNews, nytimesNews, washingtonpostNews]\n cnt1 = 1;cnt2 = 2\n for channel in channels:\n for news in channel:\n cnt2 += cnt1\n link = news['link']\n news[\"img_link\"] = get_image(link)\n news[\"full_text\"] = news['text']\n updated_text = news['text'].splitlines()\n news['text'] = updated_text[0]\n news['index'] = cnt2\n cnt1 +=1\n get_summaries(channels)\n return channels\n\ndef get_summaries(channels):\n for channel in channels:\n for news in channel:\n news['textrank'] = summarize_textrank(news['full_text'])\n news['tf_idf'] = summarize_tfidf(news['full_text'])\n news['wf'] = summarize_wf(news['full_text'])\n result = model.predict_truthfullness(news['full_text'])\n news['truthfullness'] = result[0]\n news['truthfullnessscore'] = result[1]\n\ndef get_titles():\n titles = \" \"\n channels = get_news()\n for channel in channels:\n for news in channel:\n titles += news['title'] + \",\"\n return titles\n\nif __name__ == \"__main__\":\n print(get_news())\n print(get_titles())\n channels = get_news()\n for channel in channels:\n for news in channel:\n print(f\"News : {news['text']}\")\n print(f\" Tf_idf : {news['tf_idf']}\")\n print(f\" textrank : {news['textrank']}\")\n print(f\" wf :{news['wf']}\")\n\n\n\n\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6805555820465088,
"avg_line_length": 26,
"blob_id": "7cbae3f7dc41079e4b942f8557d0eb2e0d1db27f",
"content_id": "57c9bf245e28c1e7b5ef869223ff9c7db6297e49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 216,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 8,
"path": "/Dockerfile",
"repo_name": "pg815/Fake_News_Prediction_And_Summarization",
"src_encoding": "UTF-8",
"text": "FROM python:3.7.5\nCOPY . /app\nWORKDIR /app\nRUN pip install -r requirements.txt\nRUN python -m nltk.downloader punkt\nRUN [ \"python\", \"-c\", \"import nltk; nltk.download('all')\" ]\nENTRYPOINT [ \"python\" ]\nCMD [ \"app.py\" ]\n"
}
] | 7 |
arasi-havan/psychic-enigma | https://github.com/arasi-havan/psychic-enigma | ce2f4cc80cdb392ac908b9b36b379d7fdfc96672 | f5c8fdfcb4f00a0f19716ca0d993c52f94211d30 | 4c79e3b1e8c276cb4347692f1f6ae14d47c6fd40 | refs/heads/main | 2023-09-05T23:38:18.217509 | 2021-11-17T05:48:51 | 2021-11-17T05:48:51 | 428,922,137 | 0 | 0 | null | 2021-11-17T05:38:51 | 2021-11-17T05:42:33 | 2021-11-17T05:48:51 | Python | [
{
"alpha_fraction": 0.47236180305480957,
"alphanum_fraction": 0.6080402135848999,
"avg_line_length": 20.11111068725586,
"blob_id": "f27e9166e4a7b5f3384a19fd94462d0ef094cb75",
"content_id": "0b98c4ed0f3231de0dbbc133839e61947b04130a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 199,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 9,
"path": "/Lists1Slicing.py",
"repo_name": "arasi-havan/psychic-enigma",
"src_encoding": "UTF-8",
"text": "my_list1 =[5,6,7,8,9,10]\r\nprint(my_list1[:1])\r\nprint(my_list1[0])\r\nprint(my_list1[:3])\r\nprint(my_list1[-1])\r\nprint(my_list1[2:])\r\nprint(my_list1[0::3])\r\nprint(my_list1[0::1])\r\nprint(my_list1[0::2])\r\n"
},
{
"alpha_fraction": 0.609218418598175,
"alphanum_fraction": 0.6432865858078003,
"avg_line_length": 20.69565200805664,
"blob_id": "2f4b33effc099b89702daddd889b4cb4c4ec95f9",
"content_id": "e53094d7276c31608748ee13ad8df4826ae627ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 499,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 23,
"path": "/test1.py",
"repo_name": "arasi-havan/psychic-enigma",
"src_encoding": "UTF-8",
"text": "print(\"Hello World\")\nprint(\"hello\")\nprint(3*8)\nprint(50/10)\nprint(50//10)\nprint(50%10)\nprint('Hello World')\nprint('Hello World!')\nprint(\"This is a \\nmutli line string\\n\")\nprint(\"pass\" + \"word\")\nprint(\"Ha\" * 4)\nprint(\"double\".find('s'))\nprint(\"double\".find('u'))\nprint(\"double\".find('o)'))\nprint(\"double\".find('b'))\nprint(\"double\".find('e'))\nprint(\"double\".find('d'))\nprint(\"TestInG.lower()\")\nprint(\"testiNG.upper()\")\nprint(\"TestING\".lower())\nprint(\"tESTing\".upper())\nprint(\"double\".find('d'))\n1 + 1\n"
},
{
"alpha_fraction": 0.45348837971687317,
"alphanum_fraction": 0.6162790656089783,
"avg_line_length": 20,
"blob_id": "842d745301d3fe6bf8b4046087baf970adeddf5b",
"content_id": "f4532a9ad83f571fc5de372565fe4a7541aaba3d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 4,
"path": "/Lists1.py",
"repo_name": "arasi-havan/psychic-enigma",
"src_encoding": "UTF-8",
"text": "my_list1 =[5,6,7,8,9,10]\r\nprint(my_list1[:1])\r\nprint(my_list1[0])\r\nprint(my_list1[:3])"
}
] | 3 |
Cycloneblaze/hexchat-scripts | https://github.com/Cycloneblaze/hexchat-scripts | d08afbffc952313706971fee47a222e140370ab8 | 5d4f5951572ca797554c623ebc8ce7a9da1d5e95 | f0dd7bbee24cf522018b72ec4b9b851080288c92 | refs/heads/master | 2021-01-08T10:48:17.931073 | 2020-02-20T22:59:08 | 2020-02-20T22:59:08 | 242,008,160 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5999059081077576,
"alphanum_fraction": 0.6191046237945557,
"avg_line_length": 57.17661666870117,
"blob_id": "2411845125aef1c8bc25d72ffe33d060543aa27e",
"content_id": "a14bae95c8ccb796e00b9b219a2a69467b4ff8e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 23387,
"license_type": "no_license",
"max_line_length": 285,
"num_lines": 402,
"path": "/tellMessage.py",
"repo_name": "Cycloneblaze/hexchat-scripts",
"src_encoding": "UTF-8",
"text": "## Python !tell script for Hexchat\n## by Cycloneblaze\n\n__module_name__ = \"tellMessage\"\n__module_version__ = \"4.4\"\n__module_description__ = \"Store messages for users and deliver them later. Use !tell\"\n# required info\n\n##\n## version history:\n## 0.1 - first version\n## - just writing the thing\n## - additions listed like so\n## 1.0 - first working version :P\n## - tells work with !tell\n## 1.1 - now only catches !tell at the start of the messages, rather than anywhere\n## - proper load / unload text\n## - uses /say rather than /botserv say\n## 2.0 - tells are split into public tells (using !tell) and private tells (using /notice botname @tell)\n## - tells are stored seperately for public / private\n## 3.0 - new preference to define whether the user running the script or botserv repeats the stored\n## messages\n## - now catches all OSErrors, which should include PermissionErrors, FileNotFoundErrors and any\n## other error which would pop up and continually send, with try-except clauses\n## - banned nicknames consolidated into a set of variables for easier modifications\n## - plugin preferences can now be set and modified with commands (cuurently only 1 exists)\n## - deprecated private tells (the @tell function), they don't work very well and aren't very private\n## 3.1 - changed the reply message\n## 3.2 - fixed a bug caused by not capturing all text events (hilights)\n## - removed private tells (almost) entirely\n## 4.0 - added a confirmation message when a tell is sent\n## - added a message telling the time since the message was stored, given when the message is delivered\n## - added prefs for both of these so they can be turned off\n## - consolidated pref settings into one function\n## - grammar: repeat -> deliver, tell -> messaage\n## - added a command to list the nicknames messages awaiting delivery\n## 4.1 - now option 2 for /confirm uses /notice to deliver the confirmation privately\n## - removed zeroes\n## - new format for files: old messages will crash the script (but I won't fix it cause there aren't any 7:^])\n## 4.2 - removed zeroes again, in less lines\n## - now case-insensitive for all commands and names\n## 4.3 - consolidated some functions for less duplication of stuff\n## - fixed seconds(s)s(s)ss(s)\n## 4.4 - added confirmation messages if the sender / recipient is banned\n## - commented all the things\n## - changed prefs such that 2 is the default value for CONFIRM\n##\n##\n## todo:\n## - Change bans so they are added / removed via prefs rather than hardcoded (although I imagine you'd just give a channel ban)\n## - Remove sub1 and sub2\n\nimport hexchat\nimport os\n# import modules\n\nhexchat.prnt(\"{} script v{} loaded. python code by Cycloneblaze\".format(__module_name__, __module_version__))\n# print loading message (using global values)\n\ndirectory = 'C:/tells/'\nsub1 = 'C:/tells/public/'\nsub2 = 'C:/tells/private/'\n# define where the tells are kept, somewhere we can access with no permissions\nif not os.path.exists(directory):\n try:\n os.makedirs(directory)\n os.makedirs(sub1)\n os.makedirs(sub2)\n# create the directories if they don't exist\n except(OSError):\n pass\n# ignore errors\n\nif hexchat.get_pluginpref('tellMessage_botserv') == None:\n hexchat.set_pluginpref('tellMessage_botserv', 1)\nif hexchat.get_pluginpref('tellMessage_confirm') == None:\n hexchat.set_pluginpref('tellMessage_confirm', 2)\nif hexchat.get_pluginpref('tellMessage_time') == None:\n hexchat.set_pluginpref('tellMessage_time', 1)\n# initialise script preferences with defaults\n\nservices = ('Global', 'OperServ', 'BotServ', 'ChanServ', 'HostServ', 'MemoServ', 'NickServ')\n# can't message Services - I don't think I've missed any\nbots = ('Q', 'X', 'Porygon2', 'ChanStat', 'ChanStat-2')\n# channel bots can't tell or be told, to avoid recursive spam stuff (add the bot if it's not one of these)\nbanned_users = ('tellbot', 'tellbot2')\n# add nicknames who cannot use !tell (notably the user of the script, just in case). Must have at least 2 names (because it is a tuple)\nbanned = (services + bots + banned_users)\n\ndef timesince(seconds):\n# function to convert a number of seconds to days hours minutes and seconds\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n d, h = divmod(h, 24)\n# modular arithmetic\n global since\n if d < 0 or h < 0 or m < 0 or s < 0:\n since = ['E', 'E', 'E', 'E']\n else:\n since = [d, h, m ,s]\n# store the values in a list, unless they are negative\n\ndef public_cb_tell_store(word, word_eol, userdata):\n# function to find messages and write them to disk\n mesg = [0, 1]\n# instantiate\n mesg[0] = hexchat.strip(word[0], -1, 3)\n mesg[1] = hexchat.strip(word[1], -1, 3)\n nick = hexchat.strip(mesg[0], -1, 3)\n# separate the nickname and the message\n chan = hexchat.get_info(\"channel\")\n# get the channel name that the message was sent in\n userlist = hexchat.get_list('users')\n for i in userlist:\n if i.nick == nick:\n storetime = int(i.lasttalk)\n# get the timestamp that the message was sent at (a unix time, like 1462736411)\n if not nick in banned and mesg[1].find(\"!\") == 0 and mesg[1].lower().find('tell') == 1:\n# ensure the sender is allowed to use tell and that the message is actually a !tell\n message = mesg[1].split()\n tonick = message[1]\n fromnick = hexchat.strip(mesg[0])\n# get the sender and recipient by splitting the message into a list and taking the first and second index\n store_msg = ' '.join(message[2:])\n# put the message back together\n store_msg = fromnick + ' ' + str(storetime) + ' ' + store_msg\n store_msg = store_msg + '\\n'\n# create the message in a form we can read it later, with all the necessary info\n filename = str(sub1 + tonick.lower() + '.txt')\n# the file we will store it in\n if not tonick in banned:\n try:\n with open(filename, 'a') as tells:\n tells.write(store_msg)\n# try to create the file and write the message / append the message to an existing list of messages\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n# if we want a confirmation and we want the bot to send it:\n hexchat.command(\"botserv say {0} Your message to \\002{1}\\017 was stored successfully. They will receive it the next time they speak under that nickname (case insensitive).\".format(chan, tonick))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n# if we want a confirmation and we want to send it ourselves:\n hexchat.command(\"say Your message to \\002{0}\\017 was stored successfully. They will receive it the next time they speak under that nickname (case insensitive).\".format(tonick))\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n# if we want a confirmation via notice (so, not spamming the channel)\n hexchat.command(\"notice {0} Your message to \\002{1}\\017 was stored successfully. They will receive it the next time they speak under that nickname (case insensitive).\".format(fromnick, tonick))\n except(OSError):\n pass\n# ignore errors\n elif tonick in banned:\n# if the nickname is banned, give a message that sending didn't work\n if tonick in services:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is Network Services\".format(chan, tonick))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say \\002{}\\017 cannot recieve messages from this script because: \\002{}\\017 is Network Services\".format(tonick))\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is Network Services\".format(fromnick, tonick))\n elif tonick in bots:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is channel bot\".format(chan, tonick))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say \\002{}\\017 cannot recieve messages from this script because: \\002{}\\017 is channel bot\".format(tonick))\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is channel bot\".format(fromnick, tonick))\n elif tonick in banned_users:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is banned\".format(chan, tonick))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say \\002{}\\017 cannot recieve messages from this script because: \\002{}\\017 is banned\".format(tonick))\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} \\002{1}\\017 cannot recieve messages from this script because: \\002{1}\\017 is banned\".format(fromnick, tonick))\n \n elif nick in banned and mesg[1].find(\"!\") == 0 and mesg[1].lower().find('tell') == 1:\n# if the user is banned tell them so, and why\n message = mesg[1].split()\n tonick = message[1]\n fromnick = hexchat.strip(mesg[0])\n if nick in services:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} You are Network Services\".format(chan))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say You are Network Services\")\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} You are Network Services\".format(fromnick))\n elif nick in bots:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} You are a channel bot\".format(chan))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say You are a channel bot\")\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} You are a channel bot\".format(fromnick))\n elif nick in banned_users:\n if hexchat.get_pluginpref('tellMessage_confirm') == 1:\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} You are not allowed to use this script\".format(chan))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say You are not allowed to use this script\")\n elif hexchat.get_pluginpref('tellMessage_confirm') == 2:\n hexchat.command(\"notice {0} You are not allowed to use this script: contact me for information\".format(fromnick))\n \n return hexchat.EAT_NONE\n# don't eat the event; let it print and other plugins get it\n\ntrying = 0\nsince = 0\n# instantiate some variables\n\ndef public_cb_tell_return(word, word_eol, userdata):\n# function to retrieve and deliver stored messages\n nick = hexchat.strip(word[0])\n chan = hexchat.get_info(\"channel\")\n path = (sub1 + nick.lower() + '.txt')\n# find the nickname that sent the message and the channel it was sent in; create the expected path to look for messages\n receivedtime = 0\n userlist = hexchat.get_list('users')\n for i in userlist:\n if i.nick == nick:\n receivedtime = int(i.lasttalk)\n# instantiate, then find the time the message was recieved\n global trying\n# use the 'trying' variable we created earlier, rather than making a new one\n if not nick in banned and os.path.exists(path) and trying == 0:\n# if the nickname can recieve messages; if a file exists that contains messages; if we are not already delivering someone's messages\n try:\n tells = open(path, 'r+')\n trying = 1\n# we are delivering messages now; set this variable so we don't try to do two things at once (heavy-handed I know)\n for line in tells:\n# for each message, which is stored on its own line in the file, deliver the message\n linein = line.replace('\\n', '')\n# get rid of the newline character before we print\n seq = linein.split(' ')\n sentby = seq[0]\n storetime = int(seq[1])\n msg = ' '.join(seq[2:])\n# split the message into a list, extract the sender's name and timestamp as the first two indices of this, put the message back together \n diff = (receivedtime - storetime)\n timesince(diff)\n# find the time (in seconds) since the message was sent, then convert it to a number of days, hours, mins and seconds\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {0} \\002{1}\\017 left a message for {2}: \\'{3}\\'\".format(chan, sentby, nick, msg))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say \\002{0}\\017 left a message for {1}: \\'{2}\\'\".format(sentby, nick, msg))\n# send the message to chat, either using the channel bot or personally\n if hexchat.get_pluginpref('tellMessage_time') == 1:\n# if we are giving a timestamp:\n d, h, m, s = since[0], since[1], since[2], since[3]\n first = \"This message was left \"\n second_d, second_ds = \"\\002\" + str(d) + \"\\017 day \", \"\\002\" + str(d) + \"\\017 days \"\n second_h, second_hs = \"\\002\" + str(h) + \"\\017 hour \", \"\\002\" + str(h) + \"\\017 hours \"\n second_m, second_ms = \"\\002\" + str(m) + \"\\017 minute \", \"\\002\" + str(m) + \"\\017 minutes \"\n second_s, second_ss = \"\\002\" + str(s) + \"\\017 second \", \"\\002\" + str(s) + \"\\017 seconds \"\n third = \"ago.\"\n# create the possible bits of the message\n final = first\n if d != 0 and d != 1:\n final = final + second_ds\n elif d != 0 and d == 1:\n final = final + second_d\n if h != 0 and h != 1:\n final = final + second_hs\n elif h != 0 and h == 1:\n final = final + second_h\n if m != 0 and m != 1:\n final = final + second_ms\n elif m != 0 and m == 1:\n final = final + second_m\n if s != 0 and s != 1:\n final = final + second_ss\n elif s != 0 and s == 1:\n final = final + second_s\n final = final + third\n# assemble the message depending on if we want to say 'day' or 'days', etc.\n if d == 0 and h == 0 and m == 0 and s == 0:\n final = first + \"just moments \" + third\n# and provide a message if we delivered the tell in under one second!\n if hexchat.get_pluginpref('tellMessage_botserv') == 1:\n hexchat.command(\"botserv say {} {}\".format(chan, final))\n elif hexchat.get_pluginpref('tellMessage_botserv') == 0:\n hexchat.command(\"say {}\".format(final))\n# finally deliver the message of how long it's been since the tell was stored, using the bot or not.\n if d == 'E' or h == 'E' or m == 'E' or s == 'E':\n print(\"Something went wrong creating the since (probably your system clock changed)\")\n# if the time was somehow negative... \n tells.close()\n if tells.closed == True:\n try:\n os.remove(path)\n except(OSError):\n pass\n trying = 0\n except(OSError):\n pass\n# close the (now-empty) file and remove it, ignore errors, reset 'trying' to allow us to deliver more messages.\n\n return hexchat.EAT_NONE\n\ndef prefs_cb(word, word_eol, userdata):\n# function to set and retrieve the plugin's preferences\n if word[0].upper() == 'USEBOT':\n# if we're trying to do something with the 'botserv' preference:\n if hexchat.get_pluginpref('tellMessage_botserv') == None:\n print('The value did not exist, initialising as 1...')\n hexchat.set_pluginpref('tellMessage_botserv', 1)\n# if it somehow didn't exist, instantiate it as a default value\n elif len(word) == 1:\n print('Setting is', hexchat.get_pluginpref('tellMessage_botserv'))\n# if we didn't provide a value to set the pref to, simply inform of the current value\n elif word[1] == '1' or word[1] == '0':\n value = hexchat.strip(word[1], -1, 3)\n hexchat.set_pluginpref('tellMessage_botserv', value)\n# if we *did*, set the pref to that value\n if hexchat.get_pluginpref('tellMessage_botserv') == int(value):\n print('Setting set to', value)\n else:\n print('The plugin value was somehow not set to what you tried to set it to!')\n# then print if it matches what we set it to (or if it doesn't?)\n else:\n print('Usage: /usebot <value>\\nValid settings are 0 (you deliver the messages) and 1 (the bot delivers the messages)')\n# complain if something invalid was given (e.g. '/usebot 111111' or '/usebot 0 ')\n\n# do exactly the same thing two more times \n elif word[0].upper() == 'SINCE':\n if hexchat.get_pluginpref('tellMessage_time') == None:\n print('The value did not exist, initialising as 1...')\n hexchat.set_pluginpref('tellMessage_time', 1)\n elif len(word) == 1:\n print('Setting is', hexchat.get_pluginpref('tellMessage_time'))\n elif word[1] == '1' or word[1] == '0':\n value = hexchat.strip(word[1], -1, 3)\n hexchat.set_pluginpref('tellMessage_time', value)\n if hexchat.get_pluginpref('tellMessage_time') == int(value):\n print('Setting set to', value)\n else:\n print('The plugin value was somehow not set to what you tried to set it to!')\n else:\n print('Usage: /usebot <value>\\nValid settings are 0 (nothing is given) and 1 (time since storage is given)')\n \n elif word[0].upper() == 'CONFIRM':\n if hexchat.get_pluginpref('tellMessage_confirm') == None:\n print('The value did not exist, initialising as 2...')\n hexchat.set_pluginpref('tellMessage_confirm', 2)\n elif len(word) == 1:\n print('Setting is', hexchat.get_pluginpref('tellMessage_confirm'))\n elif word[1] == '2' or word[1] == '1' or word[1] == '0':\n value = hexchat.strip(word[1], -1, 3)\n hexchat.set_pluginpref('tellMessage_confirm', value)\n if hexchat.get_pluginpref('tellMessage_confirm') == int(value):\n print('Setting set to', value)\n else:\n print('The plugin value was somehow not set to what you tried to set it to!')\n else:\n print('Usage: /usebot <value>\\nValid settings are 0 (no confirmation) and 1 (public confirmation of sending) and 2 (private confirmation of sending)')\n\n elif word[0].upper() == 'LISTPREFS':\n# list all the preferences\n hexchat.prnt('\\nThis is a list of all the plugin preferences.\\nIt will include preferences from other plugins if they exist.\\nAny which start with \\'tellMessage_\\' are for this plugin.\\n\\n')\n for i in hexchat.list_pluginpref():\n hexchat.prnt(str(i))\n hexchat.prnt('\\nEnd of list.')\n\ndef listmsgs_cb(word, word_eol, userdata):\n# function to list all the nicknames which we have stored messages for\n print('Nicknames with messages in C:/tells/public/ awaiting delivery:')\n for i in os.listdir(sub1):\n print(str(i).replace('.txt', ''))\n# print all the filenames, less the file extension (which are the nicknames)\n if os.listdir(sub1) == []:\n print(None)\n# if there are no files there are no messages, so just print None\n print('Nicknames with messages in C:/tells/private/ awaiting delivery:')\n# do it for both directories\n for i in os.listdir(sub2):\n print(str(i).replace('.txt', ''))\n if os.listdir(sub2) == []:\n print(None)\n print('The next time these nicknames speak in a channel you are in they will receive their messages.')\n# also be informative\n\ndef unload_cb(userdata):\n hexchat.prnt(\"{} script v{} unloaded\".format(__module_name__, __module_version__))\n# on the unload event, give a message that we unloaded\n\nEVENTS = [(\"Channel Message\"),(\"Your Message\"),(\"Your Action\"),(\"Channel Action\"),(\"Channel Msg Hilight\"),(\"Channel Action Hilight\")]\n# all the print events which we want to look for messages to store in / look for nicknames with messages to deliver in\nfor event in EVENTS:\n\thexchat.hook_print(event, public_cb_tell_store)\n\thexchat.hook_print(event, public_cb_tell_return)\n# for all the events listed above, hook in our functions\nhexchat.hook_unload(unload_cb)\n# on an unload event, hook in our function and run it\nhexchat.hook_command(\"USEBOT\", prefs_cb, help=\"/USEBOT <value>\\nValue is either 0 or 1: if 0, stored messages are delivered by you, if 1, they are delivered by the channel bot\\nUsed by tellMessage.py\")\nhexchat.hook_command(\"CONFIRM\", prefs_cb, help=\"/CONFIRM <value>\\nValue is either 0 or 1: if 0, there is no confirmation message, if 1, a confirmation message is given in public chat by the channel bot\\nIf 2, the message is given by you privately with /notice\\nUsed by tellMessage.py\")\nhexchat.hook_command(\"SINCE\", prefs_cb, help=\"/SINCE <value>\\nValue is either 0 or 1: if 0, no time is given, if 1, the time since the message was stored is given along with the message itself\\nUsed by tellMessage.py\")\nhexchat.hook_command(\"LISTMSGS\", listmsgs_cb, help=\"/LISTMSGS \\nGives a list of the nicknames with messages awaiting delivery\\nUsed by tellMessage.py\")\nhexchat.hook_command(\"LISTPREFS\", prefs_cb, help=\"/LISTPREFS\")\n# hook in appropriate functions when we get commands\n"
},
{
"alpha_fraction": 0.49557340145111084,
"alphanum_fraction": 0.5052501559257507,
"avg_line_length": 38.16935348510742,
"blob_id": "88a28883690cca329b024d2db828f82ea3823a23",
"content_id": "2e76737237dd1307f917ca4a40729f9618ccd7b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4857,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 124,
"path": "/youtubeLink.py",
"repo_name": "Cycloneblaze/hexchat-scripts",
"src_encoding": "UTF-8",
"text": "__module_name__ = \"youtubeLink\" \n__module_version__ = \"1.2\" \n__module_description__ = \"Displays information about YouTube videos linked in chat\"\n\n##\n## Youtube link script for Hexchat\n## by Cycloneblaze and Galaxy\n##\n## version history\n## 1.0 - based on Galaxy's Youtube script v1.3\n## - new API key\n## - new video message incl. channel name\n## 1.1 - formatting numbers\n## 1.2 - now supports multiple channels\n## - the script will activate in any channel you are in with a\n## name that is in the channel variable. add names separated with\n## commas and surrounded in quotes.\n##\n## todo: refactor code and stuff\n##\n\nimport hexchat\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\n\nyoutube = build(\"youtube\", \"v3\", developerKey=\"AIzaSyDXWnobaSQlppM_2iG9QwoCEoln90l5lgs\")\nvid_id = ''\nchannel = ('#gtsplus', '#gundam')\n\nhexchat.prnt(\"{} script v{} loaded. python code by Cycloneblaze\".format(__module_name__, __module_version__))\ndef unload_cb(userdata):\n hexchat.prnt(\"{} script v{} unloaded\".format(__module_name__, __module_version__))\n\ndef link_type(message):\n\n if \"://www.youtube.com/watch?v=\" in message[1]:\n start = message[1].find('watch?v=')\n vid_id = message[1][start+8:start+19]\n elif \"://youtu.be/\" in message[1]:\n start = message[1].find('.be/')\n vid_id = message[1][start+4:start+15]\n\n return vid_id\n\n\ndef youtube_cb(word, word_eol, userdata): \n\n if hexchat.get_info('channel') == channel:\n current_channel = if hexchat.get_info('channel')\n\n if (\"://www.youtube.com/watch?v=\" in word[1]) or (\"://youtu.be/\" in word[1]):\n vid_id = link_type(word)\n vid = youtube.videos().list(id=vid_id, part='snippet, contentDetails, statistics').execute()\n vid_dur = 'hour:minute:second'\n\n for vid_res in vid.get(\"items\", []):\n vid_title = (\"{}\".format(vid_res['snippet']['title']))\n vid_time = (\"{}\".format(vid_res['contentDetails']['duration'])[2:])\n vid_channel = (\"{}\".format(vid_res['snippet']['channelTitle']))\n vid_date = (\"{}\".format(vid_res['snippet']['publishedAt']))\n vid_views = (\"{}\".format(vid_res['statistics']['viewCount']))\n vid_likes = (\"{}\".format(vid_res['statistics']['likeCount']))\n vid_dislikes = (\"{}\".format(vid_res['statistics']['dislikeCount']))\n\n hours=minutes=seconds=True\n\n if \"H\" not in vid_time:\n vid_dur = vid_dur.replace('hour:','')\n hours = False\n if \"S\" not in vid_time:\n vid_dur = vid_dur.replace('second','00')\n seconds = False\n if \"M\" not in vid_time:\n if not hours and seconds:\n vid_dur = vid_dur.replace('minute','0')\n minutes = False\n else:\n vid_dur = vid_dur.replace('minute','00')\n minutes = False\n\n if hours:\n vid_dur = vid_dur.replace('hour',vid_time[0])\n vid_time = vid_time[2:]\n\n if minutes:\n start = vid_time.find('M')\n if (start - 1):\n vid_dur = vid_dur.replace('minute',vid_time[:2])\n vid_time = vid_time[3:]\n else:\n if not hours:\n vid_dur = vid_dur.replace('minute',vid_time[0])\n vid_time = vid_time[2:]\n else:\n vid_dur = vid_dur.replace('minute',('0' + vid_time[0]))\n vid_time = vid_time[2:]\n\n if seconds:\n if len(vid_time) == 3:\n vid_dur = vid_dur.replace('second',vid_time[0:2])\n else:\n vid_dur = vid_dur.replace('second',('0' + vid_time[0]))\n\n vid_views = int(vid_views)\n vid_views = '{:,}'.format(vid_views)\n\n vid_likes = int(vid_likes)\n vid_likes = '{:,}'.format(vid_likes)\n\n vid_dislikes = int(vid_dislikes)\n vid_dislikes = '{:,}'.format(vid_dislikes)\n\n pos = vid_date.find('T')\n vid_date = vid_date[:pos]\n\n if vid_title not in word[1]:\n hexchat.command(\"bs say {} {} [{}] [Uploaded by {}]\".format(current_channel, vid_title, vid_dur, vid_channel))\n\n return hexchat.EAT_NONE\n\nEVENTS = [(\"Channel Message\"),(\"Your Message\"),(\"Your Action\"),(\"Channel Action\"),(\"Channel Msg Hilight\")]\nfor event in EVENTS:\n hexchat.hook_print(event, youtube_cb)\nhexchat.hook_unload(unload_cb)\n"
},
{
"alpha_fraction": 0.8045976758003235,
"alphanum_fraction": 0.8045976758003235,
"avg_line_length": 42.5,
"blob_id": "375bdf946f0b376078646f46daf972674cf6c5c4",
"content_id": "f08ae8c3a9bc286823f63d918452a7716aefc094",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 2,
"path": "/README.md",
"repo_name": "Cycloneblaze/hexchat-scripts",
"src_encoding": "UTF-8",
"text": "# hexchat-scripts\nPython scripts for HexChat for use by the #gtsplus channel on synIRC\n"
}
] | 3 |
Step-python-2021/UniversityPortal | https://github.com/Step-python-2021/UniversityPortal | 8a14847a721a7f421da77bbe67168a9b744b6165 | 0f1f92bc90d78cd1313b9c99e63b24351dc018b3 | 841f85c1e34c393750e4b88c5109cca920f6d1f3 | refs/heads/main | 2023-08-07T14:25:54.932610 | 2021-09-28T11:16:36 | 2021-09-28T11:16:36 | 405,902,195 | 0 | 0 | null | 2021-09-13T09:00:56 | 2021-09-14T13:39:23 | 2021-09-28T11:16:36 | Python | [
{
"alpha_fraction": 0.6557376980781555,
"alphanum_fraction": 0.6557376980781555,
"avg_line_length": 14.25,
"blob_id": "e8f7d152617c7c85684826d41032f4a99e7ccc60",
"content_id": "69b9bcf8b29152307ecfa3ecbb1f26bd0779b47f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 122,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 8,
"path": "/models/article.py",
"repo_name": "Step-python-2021/UniversityPortal",
"src_encoding": "UTF-8",
"text": "from config import mysql\n\n\nclass Article(object):\n\n @staticmethod\n def get_all_articles(self) -> list:\n pass\n"
},
{
"alpha_fraction": 0.7586206793785095,
"alphanum_fraction": 0.7586206793785095,
"avg_line_length": 9.875,
"blob_id": "cbe8ae944c82770a51193537a2e28811ec5437a8",
"content_id": "86c0e22365aa887c0b98da0ad9c8163da626513b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 8,
"path": "/README.md",
"repo_name": "Step-python-2021/UniversityPortal",
"src_encoding": "UTF-8",
"text": "# UnivercityPortal\npython flask website prototype\n\nRequires:\n\n - flask\n\n - flask-MySql\n"
},
{
"alpha_fraction": 0.6585366129875183,
"alphanum_fraction": 0.6585366129875183,
"avg_line_length": 14.375,
"blob_id": "1d145215f62bf978c7546f85f74bcc6db920fab5",
"content_id": "51e8e8973165cea8d9c73d77d558f26068941e51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 123,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 8,
"path": "/models/faculty.py",
"repo_name": "Step-python-2021/UniversityPortal",
"src_encoding": "UTF-8",
"text": "from config import mysql\n\n\nclass Faculty(object):\n\n @staticmethod\n def get_all_faculties(self) -> list:\n pass\n"
},
{
"alpha_fraction": 0.7224669456481934,
"alphanum_fraction": 0.7224669456481934,
"avg_line_length": 21.700000762939453,
"blob_id": "dc148fdd2ba5e20bcd23b18218c9919e37dd4082",
"content_id": "37724edaf334854ca93e76739e3c789c2a10c5aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 227,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 10,
"path": "/views/faculties_controller.py",
"repo_name": "Step-python-2021/UniversityPortal",
"src_encoding": "UTF-8",
"text": "from flask import render_template\nfrom config import app\n\n\nclass FacultiesController(object):\n\n @staticmethod\n @app.route('/faculties/list')\n def faculties_list():\n return render_template('faculties/list.html')\n"
},
{
"alpha_fraction": 0.6634920835494995,
"alphanum_fraction": 0.6634920835494995,
"avg_line_length": 20,
"blob_id": "d5b0fce4673a31bda358375d454b3b3049c50684",
"content_id": "f15570634dc24f2b75d09e3010cca84d6044cedf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 315,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 15,
"path": "/views/home_controller.py",
"repo_name": "Step-python-2021/UniversityPortal",
"src_encoding": "UTF-8",
"text": "from flask import render_template\nfrom config import app\n\n\nclass HomeController(object):\n\n @staticmethod\n @app.route('/')\n def index():\n return render_template('home/index.html')\n\n @staticmethod\n @app.route('/contacts')\n def contacts():\n return render_template('home/contacts.html')\n"
}
] | 5 |
frank47ltt/DQN_assignment_2_Frank | https://github.com/frank47ltt/DQN_assignment_2_Frank | ae4df92a4f9d94057ccd7b108b71a1e8f22846c8 | 2b389c49a72f580c0c6fc7de2b3becf9d44db754 | 43c6b8d5c68907b13301c9b78858af2aa4ed55fb | refs/heads/master | 2022-11-05T16:15:27.505063 | 2020-06-23T15:21:18 | 2020-06-23T15:21:18 | 274,418,695 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5559682846069336,
"alphanum_fraction": 0.5765230059623718,
"avg_line_length": 39.20408248901367,
"blob_id": "2ad8a5852c72aa53995851a09a51c7008e1c9def",
"content_id": "a8412641878465803e9e1564647d96ebbf1a0ffd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4038,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 98,
"path": "/q3_nature.py",
"repo_name": "frank47ltt/DQN_assignment_2_Frank",
"src_encoding": "UTF-8",
"text": "import tensorflow as tf\r\nimport tensorflow.contrib.layers as layers\r\n\r\nfrom utils.general import get_logger\r\nfrom utils.test_env import EnvTest\r\nfrom q1_schedule import LinearExploration, LinearSchedule\r\nfrom q2_linear import Linear\r\n\r\n\r\nfrom configs.q3_nature import config\r\n\r\n\r\nclass NatureQN(Linear):\r\n \"\"\"\r\n Implementing DeepMind's Nature paper. Here are the relevant urls.\r\n https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf\r\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\r\n \"\"\"\r\n def get_q_values_op(self, state, scope, reuse=False):\r\n \"\"\"\r\n Returns Q values for all actions\r\n\r\n Args:\r\n state: (tf tensor) \r\n shape = (batch_size, img height, img width, nchannels)\r\n scope: (string) scope name, that specifies if target network or not\r\n reuse: (bool) reuse of variables in the scope\r\n\r\n Returns:\r\n out: (tf tensor) of shape = (batch_size, num_actions)\r\n \"\"\"\r\n # this information might be useful\r\n num_actions = self.env.action_space.n\r\n\r\n ##############################################################\r\n \"\"\"\r\n TODO: implement the computation of Q values like in the paper\r\n https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf\r\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\r\n\r\n you may find the section \"model architecture\" of the appendix of the \r\n nature paper particulary useful.\r\n\r\n store your result in out of shape = (batch_size, num_actions)\r\n\r\n HINT: \r\n - You may find the following functions useful:\r\n - tf.layers.conv2d\r\n - tf.layers.flatten\r\n - tf.layers.dense\r\n\r\n - Make sure to also specify the scope and reuse\r\n\r\n \"\"\"\r\n ##############################################################\r\n ################ YOUR CODE HERE - 10-15 lines ################ \r\n\r\n\r\n '''\r\n The input to the neural network consists of an 843 843 4 image produced by the preprocessing map w. \r\n The first hidden layer convolves 32 filters of 8 3 8 with stride 4 with the input image and applies \r\n a rectifier nonlinearity31,32. \r\n The second hidden layer convolves 64 filters of 4 3 4 with stride 2, again followed by a rectifier nonlinearity.\r\n This is followed by a third convolutional layer that convolves 64filters of 3 3 3 with stride 1 followed by a rectifier. \r\n The final hidden layer is fully-connected and consists of 512 rectifier units. \r\n The output layer is a fully-connected linear layer with a single output for each valid action. \r\n '''\r\n with tf.variable_scope(name_or_scope = scope, reuse= reuse) as _:\r\n layer_1 = tf.layers.conv2d(inputs = state, filters = 32, kernel_size = 8, strides = 4)\r\n layer_2 = tf.layers.conv2d(inputs = layer_1, filters = 64, kernel_size = 4, strides = 2)\r\n layer_3 = tf.layers.conv2d(inputs = layer_2, filters= 64, kernel_size = 3, strides = 1)\r\n flattened_3 = tf.layers.flatten(inputs = layer_3)\r\n layer_4 = tf.layers.dense(inputs = flattened_3, units = 512)\r\n out = tf.layers.dense(inputs = layer_4, units = num_actions)\r\n\r\n\r\n ##############################################################\r\n ######################## END YOUR CODE #######################\r\n return out\r\n\r\n\r\n\"\"\"\r\nUse deep Q network for test environment.\r\n\"\"\"\r\nif __name__ == '__main__':\r\n env = EnvTest((80, 80, 1))\r\n\r\n # exploration strategy\r\n exp_schedule = LinearExploration(env, config.eps_begin, \r\n config.eps_end, config.eps_nsteps)\r\n\r\n # learning rate schedule\r\n lr_schedule = LinearSchedule(config.lr_begin, config.lr_end,\r\n config.lr_nsteps)\r\n\r\n # train model\r\n model = NatureQN(env, config)\r\n model.run(exp_schedule, lr_schedule)\r\n"
}
] | 1 |
Shanmugabavan/Modified_n_puzzle_problem | https://github.com/Shanmugabavan/Modified_n_puzzle_problem | 51cc7f7210003ec3814150f5dd726b8495f43591 | 7915742a99f7f0ad7c509f3286a84215be8b641e | 82c63e1f9344544c1ce78b55c3971560c09d7699 | refs/heads/master | 2023-08-03T17:41:17.231847 | 2021-09-11T14:48:10 | 2021-09-11T14:48:10 | 405,335,343 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7017208337783813,
"alphanum_fraction": 0.7217973470687866,
"avg_line_length": 46.5,
"blob_id": "d26b4108516fd7fc79f69d98e89b77d7e90d3f2d",
"content_id": "b8ed832a19872bb8a644b6204cc112756d486ca0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 1046,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 22,
"path": "/README.txt",
"repo_name": "Shanmugabavan/Modified_n_puzzle_problem",
"src_encoding": "UTF-8",
"text": "Settingup Environment\n pip install -r requirements.txt\n\n\nPlay with sample data and Ouput\n 1.python main.py\n -output is number of expanded nodes will be print by default\n -when passing cmd arguments can generate multiple outputs...... Can easily understand by comment in the code\n -if you want to print path\n python main.py --path\n\nAnalysing data with 100 random data\n 1.python generator.py generator.py #code\n 2.change file root to 'inputs' and change the seed value to 'i+100'\n 3.python generator.py generator.py #code\n 4.Now 100 inputs data in inputs files and goals data in goals files\n 5.python random_data_solver.py # producing manhattan distance\n 6.copy that manhattance distance and paste in to 'analyse_manhattan.txt'\n 7.python random_data_solver.py --heuristic misplaced #code\n 8.copy that misplaced distance and paste in to 'analyse_misplaced.txt'\n 9.python analyser.py\n 10.analysing report will be in 'analysis report.txt' #t- values are only print purpose\n\n"
},
{
"alpha_fraction": 0.703496515750885,
"alphanum_fraction": 0.7062937021255493,
"avg_line_length": 25.90566062927246,
"blob_id": "998a5a0d2796bbe07aaea01e7da2d561d5990869",
"content_id": "4151cd643bf7e83304b6964d2300fcb8cae5b843",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1430,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 53,
"path": "/analyser.py",
"repo_name": "Shanmugabavan/Modified_n_puzzle_problem",
"src_encoding": "UTF-8",
"text": "import math\nimport statistics\nimport numpy as np\nimport scipy.stats as st\n\ndef getText(file):\n f=open(file,'r')\n input_list=f.read().split('\\n')\n f.close()\n if input_list[-1]==\"\":\n del input_list[-1]\n number_list=[int(i) for i in (input_list)]\n return number_list\n\ndef showResult(output,analysis_report):\n f=open(analysis_report,'w')\n m=\"\"\n for i in output:\n m=m+str(i)+'\\n'\n print(m)\n f.write(m)\n f.close()\n\ndef find_differences(misplaced_list,manhatton_list):\n difference_list=[]\n for i in range(len(misplaced_list)):\n difference_list.append(abs(misplaced_list[i]-manhatton_list[i]))\n return difference_list\n\nmisplaced='analyse_misplaced.txt'\nmanhatton='analyse_manhatton.txt'\nanalysis_report='analysis report.txt'\nmisplaced_list=getText(misplaced)\nmanhatton_list=getText(manhatton)\n\nmanhattan = np.array(manhatton_list)\nmisplaced = np.array(misplaced_list)\n\ndifferences_list=find_differences(misplaced_list,manhatton_list)\nmean=(statistics.mean(find_differences(misplaced_list,manhatton_list)))\nt_test = st.ttest_ind(a=misplaced,b = manhattan)\n# t_test_1=t_test.statistics\n# t_test_2=t_test.pvalue\n\n\noutput_list=[\"misplaced_list: \",str(misplaced_list),\"manhatton_list: \",str(manhatton_list),\"difference_list: \",str(differences_list),\"Mean: \",str(mean)]\n\nshowResult(output_list,analysis_report)\n\nprint(\"t-test\")\n\nprint(t_test.statistic)\nprint(t_test.pvalue)\n\n\n\n\n"
},
{
"alpha_fraction": 0.5019011497497559,
"alphanum_fraction": 0.5297845602035522,
"avg_line_length": 29.346153259277344,
"blob_id": "058087fedee3da3c848f0670705e8f60e2b25fb1",
"content_id": "df35bdbb2071c95d43d878f1c199e4ae9545de2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 789,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 26,
"path": "/generator.py",
"repo_name": "Shanmugabavan/Modified_n_puzzle_problem",
"src_encoding": "UTF-8",
"text": "import random\n\ndef print_2_dim_array(arr):\n for i in arr:\n for j in i:\n print(i, end=\" \")\n print()\n\ndef write_random_input_data(f,possible_values):\n for i in range(3):\n for j in range(3):\n index = random.randint(0, len(possible_values) - 1)\n f.write(f\"{possible_values[index]} \")\n del possible_values[index]\n f.write(\"\\n\")\n\ndef main():\n for i in range(1,101):\n possible_values = ['1','2','3','4','5','6','7','-','-']\n random.seed(i+200) #change the seed to 200 when generate output\n with open(f\"./goals/{i}.txt\", \"w\") as f: #when generate goals change it inputs as goals\n write_random_input_data(f,possible_values)\n\n\nif __name__ == '__main__':\n main()\n"
}
] | 3 |
mboy163/Advanced-Token-Logger | https://github.com/mboy163/Advanced-Token-Logger | b461f2e7111d79313838afdc9560f0b9546cdc9f | a8b629b9a70247ffb4bf819da5b06974ee9bbb57 | 38506e7514ea2c21d9845e0b159535da00b84ce6 | refs/heads/main | 2023-06-18T07:54:07.029876 | 2021-07-09T18:01:30 | 2021-07-09T18:01:30 | 384,514,794 | 0 | 0 | null | 2021-07-09T18:00:03 | 2021-06-14T20:21:10 | 2021-04-20T01:24:45 | null | [
{
"alpha_fraction": 0.7599396109580994,
"alphanum_fraction": 0.7810770273208618,
"avg_line_length": 42.19565200805664,
"blob_id": "0744e4f2e2f33e0bc7de8cffba064c93f7950400",
"content_id": "aec8667f01cf0e010796cfb41a26a0d6f4971ef0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1987,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 46,
"path": "/README.md",
"repo_name": "mboy163/Advanced-Token-Logger",
"src_encoding": "UTF-8",
"text": "# Advanced-Token-Logger\nAn advanced discord token logger that dumps system information, goes through the registry, and more.\nOnce the script is executed and all info is collected, the files will be sent and uploaded through a \ndiscord webhook.\n\n# How to install\nIt should install automatically by running \"start.py\" but just incase that does not work,\ntry installing it manually or making your target install it manually by doing the following commands.\n\npip3 install re\npip3 install shutil\npip3 install requests\npip3 install socket\npip3 install winreg\npip3 install pyautogui\npip3 install platform\npip3 install psutil\npip3 install getmac\n\n# How to Setup up the token logger\nIn order for the token logger to be fully functional we must create a discord webhook. Once\nthe webhook is created, we are going to paste our webhook in specific areas in the code.\n\nIn the file \"main.py\" go to line 49 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 7 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 76 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 78 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 80 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 82 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 84 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 86 and replace the text with your discord webhook url.\n\nIn the file \"38.py\" go to line 88 and replace the text with your discord webhook url.\n\n# How to Run\nExecute the token logger by double clicking it or doing \"python main.py\". But before you execute\nit or make your target execute it, double check that all the requirements have been install via manual\ninstallation or by running \"start.py\". Remember, if \"start.py\" works and installs everything it will \nautomatically execute \"main.py\"\n"
},
{
"alpha_fraction": 0.6589755415916443,
"alphanum_fraction": 0.6843562722206116,
"avg_line_length": 23.494117736816406,
"blob_id": "3f0bfe37e339302e18fb94da43017e9cb0cd7cfd",
"content_id": "8cc462578cbaa6bc97a42a9f46efe023807f8c48",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2167,
"license_type": "no_license",
"max_line_length": 260,
"num_lines": 85,
"path": "/main.py",
"repo_name": "mboy163/Advanced-Token-Logger",
"src_encoding": "UTF-8",
"text": "import os\r\nimport shutil\r\nimport requests\r\nimport socket\r\nimport pyautogui\r\nimport platform\r\nimport psutil\r\nfrom datetime import datetime\r\nfrom getmac import get_mac_address\r\n\r\n\r\ninfofile1 = \"ipconfig.txt\"\r\ninfofile2 = \"sysinfo.txt\"\r\n\r\ndirsys1 = \"Files\\ipconfig.txt\"\r\ndirsys2 = \"Files\\sysinfo.txt\"\r\n\r\nos.system(\"ipconfig > ipconfig.txt\")\r\nshutil.move(infofile1, dirsys1)\r\n\r\n\r\ndef priv():\r\n f = open(\"priv.cmd\", \"w\")\r\n f.write('''echo off\r\n\r\n whoami /priv > Files\\systemperms.txt\r\n exit\r\n ''')\r\n\r\n os.system(\"start priv.cmd\")\r\n\r\npriv()\r\n\r\nss = pyautogui.screenshot()\r\n\r\nss.save(\"Files\\image.jpg\")\r\n\r\nmachine1 = platform.machine()\r\nversion1 = platform.version()\r\nplatform1 = platform.platform()\r\nuname1 = platform.uname()\r\nsystem1 = platform.system()\r\nprocess1 = platform.processor()\r\ncomputername = socket.gethostname()\r\nlocalipaddress = socket.gethostbyname(computername)\r\nboottime = datetime.fromtimestamp(psutil.boot_time())\r\n\r\nurl = \"https://discord.com/api/webhooks/862225440763281429/s5WkhZ_-FikKY7CszeXO17Q6yMzMGGySqZQ63k94Z58UUwwff9Eoklhsn0FDLuXkDmup\" # PUT WEBHOOK HERE\r\n\r\ndef ipaddrr():\r\n\r\n\tpayloads = {\r\n\t\t\"content\": f\"```System Info:\\n---------------- \\nMachine: {machine1}\\nVersion: {version1}\\nPlatform: {platform1}\\nUname: {uname1}\\nSystem: {system1}\\nProccessor: {process1}\\nPC Name: {computername}\\nLocal IP: {localipaddress}\\nLast Boot Time: {boottime}```\",\r\n\t\t\"username\": \"\",\r\n\t\t\"avatar_url\": \"\",\r\n\t}\r\n\trequests.post(url, data=payloads)\r\n\r\nipaddrr()\r\n\r\ndef ipaddr():\r\n\t\r\n\tipaddr = requests.get(\"https://vpnapi.io/api/\").text\r\n\r\n\tpayloads = {\r\n\t\t\"content\": f\"``` Victim: \\n{ipaddr}```\",\r\n\t\t\"username\": \"\",\r\n\t\t\"avatar_url\": \"\",\r\n\t}\r\n\trequests.post(url, data=payloads)\r\n\r\nipaddr()\r\n\r\nfile1 = \"WiFi-List.txt\"\r\nfields1 = \"Files\\WiFi-List.txt\"\r\nos.system(\"netstat -n > Files\\ActiveConnections.txt\")\r\nos.system(\"Netsh WLAN show profiles > WiFi-List.txt\")\r\nos.remove(\"priv.cmd\")\r\nos.system(\"DRIVERQUERY > Files\\driverquery.txt\")\r\nshutil.move(file1, fields1)\r\nsys_file = \"ExtraSystemInfo.txt\"\r\nsys_dir = \"Files\\ExtraSystemInfo.txt\"\r\nos.system(\"systeminfo > ExtraSystemInfo.txt\")\r\nshutil.move(sys_file, sys_dir)\r\nexec(open(\"38.py\").read())\r\n"
},
{
"alpha_fraction": 0.5763270854949951,
"alphanum_fraction": 0.5835806131362915,
"avg_line_length": 17.953947067260742,
"blob_id": "33b546ae82a6d465e193661f6e7cacf270577482",
"content_id": "71b245e017ecffda8e61ccbbd5fcb7f6b27ff23f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3033,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 152,
"path": "/addr.py",
"repo_name": "mboy163/Advanced-Token-Logger",
"src_encoding": "UTF-8",
"text": "import winreg\r\nimport os\r\n\r\nprint(\"Scanning Registry...\")\r\nprint(\"Scanning Registry...\")\r\nprint(\"Done.\")\r\n\r\n# CurrentVersion\r\n\r\nprint(''' \r\nInformation from SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\r\n---------------------------------------------------------------''')\r\n\r\ndef reg():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_LOCAL_MACHINE)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg()\r\n\r\nprint(''' \r\n\r\n''')\r\n\r\n\r\n# Environment\r\n\r\nprint(''' \r\nInformation from \\Environment\r\n---------------------------------------------------------------''')\r\n\r\ndef reg1():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_CURRENT_USER)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"Environment\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg1()\r\n\r\n\r\nprint(''' \r\n\r\n''')\r\n\r\n\r\n# HKEY_CURRENT_USER\\Volatile\r\n\r\nprint(''' \r\nInformation from HKEY_CURRENT_USER\\Volatile Environment\r\n---------------------------------------------------------------''')\r\n\r\ndef reg2():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_CURRENT_USER)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"Volatile Environment\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg2()\r\n\r\n\r\nprint(''' \r\n\r\n''')\r\n\r\n\r\n# HARDWARE\\DESCRIPTION\\SYSTEM\r\n\r\nprint(''' \r\nInformation from HARDWARE\\DESCRIPTION\\SYSTEM\r\n---------------------------------------------------------------''')\r\n\r\ndef reg3():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_LOCAL_MACHINE)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"HARDWARE\\DESCRIPTION\\SYSTEM\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg3()\r\n\r\n\r\nprint(''' \r\n\r\n''')\r\n\r\n\r\n# SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\r\n\r\n\r\nprint(''' \r\nInformation from SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\r\n---------------------------------------------------------------''')\r\n\r\ndef reg4():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_LOCAL_MACHINE)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg4()\r\n\r\nprint(''' \r\n\r\n''')\r\n\r\n# \\SOFTWARE\\Microsoft\\Windows Defender\r\n\r\nprint(''' \r\nInformation from \\SOFTWARE\\Microsoft\\Windows Defender\r\n---------------------------------------------------------------''')\r\n\r\ndef reg5():\r\n\taccess_reg = winreg.ConnectRegistry(None,winreg.HKEY_LOCAL_MACHINE)\r\n\r\n\tregkey = winreg.OpenKey(access_reg, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SoftwareProtectionPlatform\")\r\n\r\n\tfor n in range(20):\r\n\t\ttry:\r\n\t\t\tx = winreg.EnumValue(regkey, n)\r\n\t\t\tprint(x)\r\n\t\texcept:\r\n\t\t\tbreak\r\nreg5()\r\n\r\n\r\n\r\nos.system(\"py registry.py > Files\\RegistryInfo.txt\")\r\n"
},
{
"alpha_fraction": 0.6920903921127319,
"alphanum_fraction": 0.7175140976905823,
"avg_line_length": 23.428571701049805,
"blob_id": "84cbac0dcb5adf1b4bbd46a6fedd42e7d3d003a7",
"content_id": "8438f3cf00b15aa9d4ca6f4a5736a80f6ed38460",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 354,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/start.py",
"repo_name": "mboy163/Advanced-Token-Logger",
"src_encoding": "UTF-8",
"text": "import os\r\n\r\nos.system(\"pip3 install re\")\r\nos.system(\"pip3 install shutil\")\r\nos.system(\"pip3 install requests\")\r\nos.system(\"pip3 install socket\")\r\nos.system(\"pip3 install winreg\")\r\nos.system(\"pip3 install pyautogui\")\r\nos.system(\"pip3 install platform\")\r\nos.system(\"pip3 install psutil\")\r\nos.system(\"pip3 install getmac\")\r\n\r\n\r\nexec(open(\"main.py\").read())"
}
] | 4 |
xu-david/data_mining | https://github.com/xu-david/data_mining | b73478a52e495abe3d0a4a550f55367b8db053a2 | 9f07db1987c9f51cae08dfff0ae9ef4fb4ed41de | 9d49bb3f36aa698ad400948e7f7c5d15273454af | refs/heads/master | 2022-04-07T11:18:50.862393 | 2020-02-28T04:01:01 | 2020-02-28T04:01:01 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7979274392127991,
"alphanum_fraction": 0.8082901835441589,
"avg_line_length": 63.33333206176758,
"blob_id": "65f3f296ba33b6c951eaa77e00c43d01fd799ea6",
"content_id": "e21965272e645102a42e8405ea55735e26c02711",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 193,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 3,
"path": "/clustering_coefficient_hadoop/execute.sh",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "/home/scratch/hadoop_core/bin/hadoop dfs -rmr output*\n\n/home/scratch/hadoop_core/bin/hadoop jar /home/scratch/homework4/homework4.jar Clustering_Coefficient /user/myIns/test /user/myIns/output\n"
},
{
"alpha_fraction": 0.7264957427978516,
"alphanum_fraction": 0.7307692170143127,
"avg_line_length": 32.42856979370117,
"blob_id": "3a7a943a851566912d97915ab9abd556d1e1a61b",
"content_id": "3dd868b680aa8c8f93f4e2fd1be7406f1ddebc93",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 702,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 21,
"path": "/clustering_coefficient_hadoop/myreducer.java",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "import java.io.*;\nimport java.util.*;\nimport org.apache.hadoop.fs.*;\nimport org.apache.hadoop.conf.*;\nimport org.apache.hadoop.io.*;\nimport org.apache.hadoop.mapred.*;\nimport org.apache.hadoop.util.*;\n//Reducer to merge all types of graphlet count\n\t\tpublic class myreducer extends MapReduceBase implements Reducer<IntWritable, DoubleWritable, Text, DoubleWritable> {\n\n\t\t\tpublic void reduce(IntWritable key, Iterator<DoubleWritable> values, OutputCollector<Text, DoubleWritable> output, Reporter arg3)\n\t\t\t\t\tthrows IOException {\n\n\t\t\t\t\n\t\t\t\tText output_key = new Text(\"Test\");\n\t\t\t\tDoubleWritable output_value = new DoubleWritable(2.5);\n\t\t\t\toutput.collect(output_key, output_value);\n\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n"
},
{
"alpha_fraction": 0.6038222908973694,
"alphanum_fraction": 0.6150137782096863,
"avg_line_length": 28.33333396911621,
"blob_id": "0bfd4c2ea85e26c854abdcc9f96de37d5292c6b9",
"content_id": "82c43bf0f2ace90169dfbd9bda64af470922e3db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5808,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 198,
"path": "/covariance_matrix/covariance_matrix.py",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\n'''\nCSCI 57300 Assignment 1\nBy: David Xu (yx5)\n\nUsage: ./assign1-yx5.py /path/to/input/file\n'''\n\nimport os\nimport numpy as np\nimport numpy.linalg as linalg\nfrom sys import argv\nfrom csv import reader as csvreader\n\ndef read_input(inputfile):\n '''\n Read input CSV into NumPy array and transpose. Assumes last column in the\n input data is for classification and is ignored.\n '''\n l = []\n with open(inputfile) as f:\n for line in csvreader(f, delimiter=',', quotechar='\"'):\n l.append(list(float(x) for x in line[:-1]))\n return np.array(l).T\n\ndef center_matrix(d):\n '''\n Subtracts the variable mean from the input matrix to center\n '''\n mean = d.mean(axis=1)\n return d - mean[:, None]\n\ndef covariance_matrix(d):\n '''\n Generates the covariance matrix by cell\n '''\n m = np.shape(d)[0]\n\n #Populate an empty matrix with size\n c = np.empty([m, m])\n\n #Calculate the dot product in each cell of the matrix\n for i in range(m):\n for j in range(m):\n if i < j:\n continue\n a = d[i]\n b = d[j]\n covariance = np.dot(a, b)/len(a)\n c[i][j] = covariance\n c[j][i] = covariance\n return c\n\ndef power_iter_eig(d, maxiter=1000, thres=0.0001):\n '''\n Power iteration method for dominant eigenvalue with maximum iterations\n 'maxiter' and threshold 'thres'.\n '''\n m = len(d)\n #Initial vector x0\n xi = np.random.rand(m)\n xim = np.random.rand(m)\n\n for i in range(maxiter): #Max iterations\n xi1, xi1m = xi[:], xim\n xi = np.dot(d, xi1)\n\n #Normalize by x_i, m\n xim = max(abs(x) for x in xi)\n xi = [ xi[x] / xim for x in range(m) ]\n\n #Check for convergence\n xnorm = linalg.norm(np.array(xi) - np.array(xi1))\n if xnorm < thres:\n break\n else:\n print __doc__\n raise SystemExit('ERROR: Power iteration method failed to converge')\n\n evalue = xim/xi1m ##Ratio x_i,m/x_i-1,m\n evector = xi/linalg.norm(np.array(xi)) #Norm\n return evalue, evector\n\ndef project_evector(d, sorted_eig, ppoints=False, npoints=10):\n '''\n Project samples onto new subspace and find variance\n '''\n w = np.vstack(i[1] for i in sorted_eig).T\n\n #y = wTx\n #y = w.T.dot(d)\n y = np.dot(w.T, d)\n if ppoints:\n print 'Projection onto first {0} data points:'.format(npoints)\n print y.T[:npoints]\n else:\n ycov = covariance_matrix(y)\n print 'Covariance matrix of new subspace:\\n', ycov\n return\n\ndef eval_eig(evalues, evectors):\n '''\n Return sorted eigenvalues and eigenvectors as tuples\n '''\n sorted_eig = [(evalues[i], evectors[:, i]) for i in range(len(evalues))]\n sorted_eig = sorted(sorted_eig, reverse=True)\n return sorted_eig\n\ndef pca(inputfile, thres_var=0.8):\n '''\n PCA wrapper function\n '''\n d = read_input(inputfile) #Read input\n d = center_matrix(d) #Center data\n c = covariance_matrix(d) #Calculate covariance matrix\n evalues, evectors = linalg.eig(c) #Calculate eigs\n sorted_eig = eval_eig(evalues, evectors) #Sort eigs\n\n #Evaluate variance\n print 'Evaluating cumulative contribution to overall variance:'\n print 'Threshold: {0}%'.format(round(thres_var*100, 2))\n total_evalues = sum(evalues)\n for i, j in enumerate(sorted_eig, start=1):\n ivar = sum([ sorted_eig[x][0] for x in range(i) ])/total_evalues\n print 'Eigenvector {0}: {1}%'.format(i, round(ivar*100, 2))\n if ivar > thres_var:\n print\n break\n project_evector(d, sorted_eig[:i], ppoints=True)\n return\n\ndef eigen_decomp(c, sorted_eig):\n '''\n Eigen decomposition of the covariance matrix CV=V x Lambda\n '''\n evalues = [sorted_eig[i][0] for i in range(len(sorted_eig))]\n evectors = [sorted_eig[i][1] for i in range(len(sorted_eig))]\n V = np.vstack(evectors).T\n Lambda = np.diag(evalues)\n # C = V x Lambda x V^T\n print 'V\\n', V\n print 'Lambda\\n', Lambda\n print 'V^T\\n', V.T\n\n #Compare covariance with decomposition matrix\n compare_c_vLambdavT = np.allclose(c, np.dot(np.dot(V, Lambda), V.T))\n print 'Comparison with covariance', compare_c_vLambdavT\n return\n\ndef main(inputfile):\n #Read the input data into array\n dinput = read_input(inputfile)\n\n #Center the matrix on variable axis\n dinput = center_matrix(dinput)\n\n #Part a. Calculate the covariance matrix\n dcov = covariance_matrix(dinput)\n print 'Part A. Calculate the covariance matrix'\n print dcov\n print '-' * 60 + '\\n'\n\n #Part b. Find the dominant eigenvalue and eigenvector from cov matrix\n evalue, evector = power_iter_eig(dcov)\n print 'Part B. Find the dominant eigenvalue and eigenvector'\n print 'Dominant eigenvalue:', evalue\n print 'Dominant eigenvector:', evector\n print '-' * 60 + '\\n'\n\n #Part c. linalg.eig to find the two dominant eigenvectors\n print 'Part C. The two dominant eigenvectors'\n evalues, evectors = linalg.eig(dcov)\n sorted_eig = eval_eig(evalues, evectors)\n project_evector(dinput, sorted_eig[:2])\n print '-' * 60 + '\\n'\n\n #Part d. Decomposition of covariance matrix into eigen-decomposition form\n print 'Part D. Decomposition of covariance matrix'\n eigen_decomp(dcov, sorted_eig)\n print '-' * 60 + '\\n'\n\n #Part e & f. PCA function wrapper\n print 'Parts E and F.'\n pca(inputfile, thres_var=0.9)\n return\n\nif __name__ == '__main__':\n if len(argv) != 2:\n print __doc__\n raise SystemExit('ERROR: Specify path to input file')\n FilePath = argv[1]\n if os.path.exists(FilePath):\n main(FilePath)\n else:\n print __doc__\n raise SystemExit('ERROR: Input file does not exist!')\n"
},
{
"alpha_fraction": 0.5091678500175476,
"alphanum_fraction": 0.5267983078956604,
"avg_line_length": 26.009523391723633,
"blob_id": "e09f96553d05d4a778ded52bbb48583362bc9146",
"content_id": "863a5a5dd1980761c6122d65b9ccfb685863d524",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5672,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 210,
"path": "/em_clustering/em_clustering.py",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCSCI573000 Assignment 2\nBy: David Xu\nUsage: ./xu-assign2.py <input_file> <k>\n\"\"\"\nimport os\nimport numpy as np\nfrom sys import argv\nfrom math import ceil\nfrom csv import reader as csvreader\n\ndef read_input(infile):\n '''\n Read input file into two arrays\n '''\n a, b = [], []\n with open(infile) as f:\n for line in csvreader(f, delimiter=',', quotechar='\"'):\n if line:\n a.append([float(x) for x in line[:-1]])\n b.append(line[-1])\n return np.array(a).T, np.array(b)\n\ndef slice_matrix(l, n, s):\n '''\n Slice matrix l of size n into chunks of size s\n '''\n for i in range(0, n, s):\n yield l[:, i:i + s]\n\ndef multi_norm_dist(x, mu, sigma):\n '''\n Probability density function for multivariate normal random variable\n '''\n dd = np.shape(mu)[0]\n # (2 * pi)^(-k/2) * det(sigma)^(-0.5)\n a = (2*np.pi)**(dd/-2.0) * np.linalg.det(sigma)**-0.5\n\n # e^(-0.5 * (x-mu) * inv(sigma) * (x-mu)^T)\n xmu = (x - mu)\n b = np.e**( -0.5 * np.dot(np.dot(xmu, np.linalg.inv(sigma)), xmu.T) )\n return a * b\n\ndef initialize(d, k):\n '''\n Divide input array into k clusters\n '''\n lmu, lcov, lprob = [], [], []\n n = np.shape(d)[1]\n csize = int(ceil(float(n) / k)) #Number of samples in each cluster\n\n for i in slice_matrix(d, n, csize):\n mu = i.mean(axis=1) #mean\n cov = np.cov(i, bias=1) #sigma\n prob = 1.0/k #probability\n lmu.append(mu)\n lcov.append(cov)\n lprob.append(prob)\n return lmu, lcov, lprob\n\ndef step_expectation(d, l1, k):\n '''\n Calculate posterior probabilities\n '''\n l2 = np.zeros([np.shape(d)[1], k])\n #for i, (mu, sigma, prob) in enumerate(l1):\n for i in range(k):\n mu, sigma, prob = l1[0][i], l1[1][i], l1[2][i]\n for j, x in enumerate(d.T):\n l2[j][i] = multi_norm_dist(x, mu, sigma) * prob\n else:\n for i, j in enumerate(l2):\n a = sum(j)\n l2[i] = j/a #Posterior probability P^t(C_i | x_j)\n return l2.T #w^T_ij\n\ndef step_maximization(d, l1, k, l2):\n '''\n Re-estimation of mean, covariance, and probabilities\n '''\n d = d.T\n lmu, lsigma, lprob = [], [], []\n for i, x in enumerate(l2):\n #Re-estimate mean\n mnum = 0.0\n for j in range(len(d)):\n #print i, j, l2[i][j], d[j], l2[i][j] * d[j]\n mnum += l2[i][j] * d[j]\n else:\n mu_i = mnum / sum(l2[i])\n lmu.append(mu_i)\n\n #Re-estimate diagonal of covariance\n snum = 0.0\n for j in range(len(d)):\n #print i, j, l2[i][j], d[j], lmu[i]\n xn = np.zeros((1, np.shape(d)[1]))\n xn += d[j]\n xmu = xn - lmu[i]\n snum += l2[i][j] * xmu * xmu.T\n else:\n sigma_i = snum / sum(l2[i])\n lsigma.append(sigma_i)\n\n #Re-estimate priors\n prob_i = sum(l2[i]) / len(l2[i])\n lprob.append(prob_i)\n return lmu, lsigma, lprob\n\ndef eval_em(k, lold, lnew, epsilon=0.001):\n '''\n Evaluate EM comparing difference in means with epsilon\n '''\n tot = 0.0\n for i in range(k):\n tot += np.linalg.norm(lnew[i] - lold[i])\n if tot <= epsilon:\n return 1\n else:\n return 0\n\ndef cluster_membership(l, k):\n '''\n Find cluster membership for each instance\n '''\n dclusters = dict((x, []) for x in range(k))\n dcr = {}\n for i, j in enumerate(l.T):\n #print i, np.argmax(j), j\n dclusters[np.argmax(j)].append(i)\n dcr[i] = np.argmax(j)\n lsize = []\n print '\\nCluster Membership:'\n for k, v in sorted(dclusters.items()):\n print ', '.join(str(x + 1) for x in v)\n lsize.append(len(v))\n\n print '\\nSize: {0}'.format(' '.join(str(x) for x in lsize))\n return dcr #Dictionary of sample: cluster\n\ndef eval_purity(k, dy, dc):\n '''\n Purity score of clustering based on class labels\n '''\n dcount = {}\n tot = 0\n for i in range(k):\n dcount[i] = {}\n for i, j in enumerate(dy): #Real label\n b = dc.get(i) #Cluster label\n dcount[b][j] = dcount[b].get(j, 0) + 1\n for i, v in dcount.items():\n #Find tuple with most members\n tot += max(v.items(), key=lambda x: x[1])[1]\n score = tot / float(len(dc))\n return round(score, 3)\n\ndef main(infile, k):\n '''\n Main function\n '''\n #Read input file into d (features x samples) and dy (labels)\n d, dy = read_input(infile)\n\n #Initialize clusters\n l1 = initialize(d, k)\n #Expectation-Maximization iteration\n count = 0\n while 1:\n count += 1\n lold = l1[0]\n l2 = step_expectation(d, l1, k)\n l1 = step_maximization(d, l1, k, l2)\n lnew = l1[0]\n #Break on epsilon threshold\n if eval_em(k, lold, lnew):\n break\n\n #Outputs\n print 'Mean:'\n for i in range(k):\n print [ round(x, 3) for x in lnew[i] ]\n\n print '\\nCovariance Matrices:'\n for i in range(k):\n print np.around(l1[1][i], decimals=3), '\\n'\n\n print 'Iteration count={0}'.format(count)\n\n dc = cluster_membership(l2, k)\n\n print '\\nPurity Score: {0}'.format(eval_purity(k, dy, dc))\n return\n\nif __name__ == '__main__':\n if len(argv) != 3:\n print __doc__\n raise SystemExit('ERROR: Check input parameters')\n sn, infile, k = argv\n try:\n k = int(k)\n except ValueError:\n print __doc__\n raise SystemExit('ERROR: Invalid number of clusters!')\n if not os.path.exists(infile):\n print __doc__\n raise SystemExit('ERROR: Input file does not exist!')\n main(infile, k)\n"
},
{
"alpha_fraction": 0.8358209133148193,
"alphanum_fraction": 0.8358209133148193,
"avg_line_length": 32.5,
"blob_id": "cd7ae93f333e4c8ff8250e35051ae3c3223d6181",
"content_id": "a31e84acef53cf690f03802a70194d69f804817d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 2,
"path": "/README.md",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "# Data Mining\nImplementations for various data mining assignments.\n"
},
{
"alpha_fraction": 0.7783783674240112,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 36,
"blob_id": "0c76d2ae627d649ed4701e387caac50a2c2e7cbd",
"content_id": "2ec8106d45f912f0dc4db1ee60a6dd1a49137dd2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 5,
"path": "/clustering_coefficient_hadoop/compile_make_jar.sh",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "javac -classpath /home/scratch/hadoop_core/hadoop-core-1.1.2.jar MyInputFormat.java mymapper.java myreducer.java Clustering_Coefficient.java\n\njar -cvf homework4.jar *.class\n\nrm *.class\n"
},
{
"alpha_fraction": 0.49769851565361023,
"alphanum_fraction": 0.5201380848884583,
"avg_line_length": 26.808000564575195,
"blob_id": "78e0dcb3f1b1991fc2468889387df2e2f8d9b877",
"content_id": "261c9e6ad3a8924d4c12462ba2efd88dc9341ad6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3476,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 125,
"path": "/svm/svm.py",
"repo_name": "xu-david/data_mining",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n############################################################\n#\n# Title : CSCI573 Assignment 5\n# Author : David Xu (yx5)\n# Description : Python implementation of the SVM training\n# algorithm (Algorithm 21.1). The dual form is\n# solved using stochastic gradient ascent and\n# hinge loss.\n#\n############################################################\n\n'''\nUsage: ./assign5.py -i <inputFile> -k <KernelType>\n\nAvailable Kernels:\n linear Linear\n quad Quadratic (Homogeneous)\n'''\n\nimport os\nimport numpy as np\nfrom getopt import getopt, GetoptError\nfrom sys import argv, exit\n\ndef read_input_file(inputFile, delimiter=','):\n #Read input file and returns as input data and labels\n if not os.path.exists(inputFile):\n print __doc__\n exit('Error: check input file')\n\n with open(inputFile) as f:\n flines = np.loadtxt(f, delimiter=delimiter).T\n lx = flines[:-1]\n ly = flines[-1]\n return lx.T, ly\n\ndef linear_kernel(x, y):\n #Linear kernel: xTy\n return np.dot(x, y)\n\ndef quad_kernel(x, y):\n #Quadratic kernel: ( xTy )**2\n return np.dot(x, y)**2\n\ndef svm_dual(lx, ly, kernelType, C=10.0, epsilon=0.0001):\n #Dual SVM algorithm: Stochastic gradient ascent using hinge loss\n\n #Available kernels\n kernels = {\n 'linear' : linear_kernel,\n 'quad' : quad_kernel,\n }\n\n if kernelType not in kernels:\n print __doc__\n exit('Error: invalid kernel')\n\n n = np.shape(lx)[0]\n\n #Map to R^d+1 dimension\n dx1 = np.ones((n, 1))\n lx1 = np.append(lx, dx1, 1)\n\n #Set step size: eta_k <- 1/K(x_k, x_k)\n etas = np.zeros(n)\n for k in range(n):\n etas[k] = 1. / kernels[kernelType](lx1[k], lx1[k])\n\n #Stochastic gradient ascent\n alphast = np.zeros(n)\n t = 0\n while 1:\n t += 1\n alphast1 = np.copy(alphast)\n for k in range(n):\n #Update k-th component of alpha\n ayK = 0.0\n for i in range(n):\n ayK += alphast1[i] * ly[i] * kernels[kernelType](lx1[i], lx1[k])\n a_K = alphast1[k] + etas[k] * (1 - ly[k] * ayK)\n #Check bounds\n if a_K < 0.:\n a_K = 0.\n elif a_K > C:\n a_K = C\n alphast1[k] = a_K\n diff = np.linalg.norm(alphast - alphast1)\n alphast = np.copy(alphast1)\n if diff <= epsilon:\n break\n #if not t % 10:\n # print t, diff\n\n #Output\n w = np.zeros(np.shape(lx1)[1])\n countsv = 0\n for i, j in enumerate(alphast1):\n if round(j, 12) != 0.: #Non-zero alphas to 12 sigfigs\n countsv += 1\n print '{0}\\tx:{1}\\ty:{2}\\ta:{3}'.format(i+1, lx[i], int(ly[i]), alphast1[i])\n w += np.dot(j * ly[i], lx1[i])\n print '-' * 40\n print 'Iterations: {0}'.format(t)\n print 'Number of Support Vectors: {0}'.format(countsv)\n print 'Weight vector (w): {0}'.format(w[:-1])\n print 'Bias (b): {0}'.format(w[-1])\n return\n\ndef main(inputFile, kernelType):\n lx, ly = read_input_file(inputFile) #Read data and labels\n svm_dual(lx, ly, kernelType)\n return\n\nif __name__ == '__main__':\n try:\n opts, args = getopt(argv[1:], 'i:k:')\n except GetoptError as err:\n print __doc__\n exit('Error: {0}'.format(err))\n d = {}\n for o, a in opts:\n d[o] = a\n main(d.get('-i', 'None'), d.get('-k', 'None'))\n"
}
] | 7 |
Shaidyk/personal | https://github.com/Shaidyk/personal | 1eddf9d21bbc4c5a8d40286c9085fb13160b5c44 | 7fb644ef73a503471642dfcfd832bca7c568079c | fbe686089b80465700f9e98c2e6e022e78d8da3d | refs/heads/master | 2022-12-07T19:49:38.176366 | 2020-07-30T10:12:55 | 2020-07-30T10:12:55 | 281,425,442 | 0 | 0 | null | 2020-07-21T14:48:43 | 2020-07-30T10:12:59 | 2020-08-20T16:29:54 | Python | [
{
"alpha_fraction": 0.7637655138969421,
"alphanum_fraction": 0.7637655138969421,
"avg_line_length": 13.815789222717285,
"blob_id": "b42740235f0485bdfba3af688484156fd4bcf2e1",
"content_id": "41b428eb2707bde9104da6b313a45d55c5d85b75",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 563,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 38,
"path": "/personal/admin.py",
"repo_name": "Shaidyk/personal",
"src_encoding": "UTF-8",
"text": "from django.contrib.admin import ModelAdmin, register\n\nfrom . import models\n\n\n@register(models.Client)\nclass ClientAdmin(ModelAdmin):\n pass\n\n\n@register(models.Region)\nclass RegionAdmin(ModelAdmin):\n pass\n\n\n@register(models.Restaurant)\nclass RestaurantAdmin(ModelAdmin):\n pass\n\n\n@register(models.Courier)\nclass CourierAdmin(ModelAdmin):\n pass\n\n\n@register(models.MenuItem)\nclass MenuItemAdmin(ModelAdmin):\n pass\n\n\n@register(models.Order)\nclass OrderAdmin(ModelAdmin):\n pass\n\n\n@register(models.OrderItem)\nclass OrderItemAdmin(ModelAdmin):\n pass\n"
},
{
"alpha_fraction": 0.5440385341644287,
"alphanum_fraction": 0.5553667545318604,
"avg_line_length": 41.03571319580078,
"blob_id": "3c945aba148836e19ea7cf5c907533b270d0a692",
"content_id": "a7068db71c28293bceebf2beee8b559cb70d5dd9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3531,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 84,
"path": "/personal/migrations/0001_initial.py",
"repo_name": "Shaidyk/personal",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.8 on 2020-07-22 11:51\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Client',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=100)),\n ('phone', models.PositiveIntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Courier',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='MenuItem',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=150)),\n ('price', models.TextField(max_length=1000)),\n ],\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('delivery_time', models.DateTimeField()),\n ('delivered_at', models.DateTimeField()),\n ('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Client')),\n ('courier', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Courier')),\n ],\n ),\n migrations.CreateModel(\n name='Region',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='Restaurant',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('address', models.CharField(max_length=200)),\n ('region', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Region')),\n ],\n ),\n migrations.CreateModel(\n name='OrderItem',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('menuitem', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.MenuItem')),\n ('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Order')),\n ],\n ),\n migrations.AddField(\n model_name='order',\n name='restaurant',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Restaurant'),\n ),\n migrations.AddField(\n model_name='courier',\n name='region',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='personal.Region'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5245901346206665,
"alphanum_fraction": 0.5664845108985901,
"avg_line_length": 22.869565963745117,
"blob_id": "4e2b21e41ed9f14da2a3e22eb2b2f0050facc91d",
"content_id": "717a3f1f8517ed1a5bafee142e4b5103418ab8eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 549,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 23,
"path": "/personal/migrations/0002_auto_20200730_1302.py",
"repo_name": "Shaidyk/personal",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.8 on 2020-07-30 10:02\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('personal', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='orderitem',\n name='amount',\n field=models.FloatField(default=0),\n ),\n migrations.AlterField(\n model_name='menuitem',\n name='price',\n field=models.DecimalField(decimal_places=2, max_digits=10),\n ),\n ]\n"
},
{
"alpha_fraction": 0.39968153834342957,
"alphanum_fraction": 0.4012738764286041,
"avg_line_length": 26.91111183166504,
"blob_id": "35299ea80c3791ab068435e64753949ff5fa587f",
"content_id": "526d62b4fc44bc6153eaef7e0e47bc52b1c4aeda",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1256,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 45,
"path": "/personal/views.py",
"repo_name": "Shaidyk/personal",
"src_encoding": "UTF-8",
"text": "from django.http import HttpResponse\nimport datetime\n\n\ndef hello(request):\n return HttpResponse(\"\"\"\n <html>\n <body>\n <p style=\"color: red\"> Hello Django!!! </p>\n <a style=\"background-color: yellow\" href=\"/\"> Main-page </a>\n </body>\n </html>\n \"\"\")\n\n\ndef info(request):\n return HttpResponse(\n f\"\"\"\n <html>\n <body style=\"background-color: gray\">\n <h1 style=\"color: blue\"> Now is {datetime.datetime.now()}</h1>\n <a style=\"color: yellow\" href=/> \"Main-page\" </a>\n </body>\n </html>\n \"\"\")\n\n\ndef main_page(request):\n return HttpResponse(\n \"\"\"\n <html>\n <body style=\"background-color: green\">\n <b>\n <div>\n <a style=\"color: yellow\" href=\"/admin/\"> Admin </a> \n </div>\n <div>\n <a style=\"color: yellow\" href=\"/info-page/\"> Info-page </a>\n </div>\n <div>\n <a style=\"color: yellow\" href=\"/hello/\"> Hello </a>\n </div>\n </body>\n </html>\n \"\"\")\n"
},
{
"alpha_fraction": 0.6956810355186462,
"alphanum_fraction": 0.7122923731803894,
"avg_line_length": 29.100000381469727,
"blob_id": "c5f770d60ad111638376206667f88a94ba0ceeb3",
"content_id": "2dc393ea5d471c08b443f4cf5416c22d9cb8f81c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1505,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 50,
"path": "/personal/models.py",
"repo_name": "Shaidyk/personal",
"src_encoding": "UTF-8",
"text": "from django.db import models\nimport datetime\n\n\nclass Client(models.Model):\n \"\"\"Client\"\"\"\n first_name = models.CharField(max_length=100)\n phone = models.PositiveIntegerField()\n\n\nclass Region(models.Model):\n \"\"\"Region\"\"\"\n name = models.CharField(max_length=200)\n\n\nclass Restaurant(models.Model):\n \"\"\"Restaurant\"\"\"\n name = models.CharField(max_length=100)\n address = models.CharField(max_length=200)\n region = models.ForeignKey(Region, on_delete=models.CASCADE)\n\n\nclass Courier(models.Model):\n \"\"\"Courier\"\"\"\n first_name = models.CharField(max_length=100)\n last_name = models.CharField(max_length=100)\n region = models.ForeignKey(Region, on_delete=models.CASCADE)\n\n\nclass MenuItem(models.Model):\n \"\"\"Position in menu\"\"\"\n name = models.CharField(max_length=150)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n\n\nclass Order(models.Model):\n \"\"\"Order\"\"\"\n client = models.ForeignKey(Client, on_delete=models.CASCADE)\n restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)\n courier = models.ForeignKey(Courier, on_delete=models.CASCADE)\n created = models.DateTimeField(auto_now_add=True)\n delivery_time = models.DateTimeField()\n delivered_at = models.DateTimeField()\n\n\nclass OrderItem(models.Model):\n \"\"\"Position menu in order\"\"\"\n menuitem = models.ForeignKey(MenuItem, on_delete=models.CASCADE)\n order = models.ForeignKey(Order, on_delete=models.CASCADE)\n amount = models.FloatField(default=0) # count\n"
}
] | 5 |
alinesc/python3 | https://github.com/alinesc/python3 | 0f272f80c110ebf96619d759cb92c0513ee35888 | 548d4bb57eca799c31ed08c30de923fc68e223e0 | b8b312ebee3a32096885ee12094f4343544b52cc | refs/heads/master | 2020-04-18T04:46:45.201014 | 2020-04-13T13:49:32 | 2020-04-13T13:49:32 | 167,251,673 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6097561120986938,
"alphanum_fraction": 0.642276406288147,
"avg_line_length": 40,
"blob_id": "80fb6918ea28bd12b0f083ca0a4b4db8d62505ae",
"content_id": "ecbcdbaac8ee2943688f3a9ad6e69c28e8648b3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 126,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 3,
"path": "/ex014.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "c = float(input('Digite um temperatura em ºC: '))\nf = (c * 9/5) + 32\nprint('A temperatura em Fahrenheit é {}ºF'.format(f))\n"
},
{
"alpha_fraction": 0.6395348906517029,
"alphanum_fraction": 0.680232584476471,
"avg_line_length": 42.25,
"blob_id": "59e4de4a31280e70a0460ac30fe9a829a5023e96",
"content_id": "1a9e8894a2ef73df0c4415dc03344640f92a9ecf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 176,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 4,
"path": "/ex008.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "number = float(input('Digite um valor: '))\ncm = number * 100\nmm = number * 1000\nprint('O valor convertido em centímetros é de {} cm e em milímetros é {} mm'.format(cm, mm))"
},
{
"alpha_fraction": 0.74609375,
"alphanum_fraction": 0.76953125,
"avg_line_length": 41.83333206176758,
"blob_id": "1c6c537e26f973a46e620d6f554f074d117b8b3e",
"content_id": "ccff366acdb9c3d4b971a60301a20e1c48b3a125",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 6,
"path": "/ex072.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''\nCrie um programa que tenha uma tupla totalmente preenchida com uma contagem\npor extenso, de zero até vinte.\nSeu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso\nverificaçào se o número está entre 0 e 20. Não usar if\n'''"
},
{
"alpha_fraction": 0.6294372081756592,
"alphanum_fraction": 0.6614718437194824,
"avg_line_length": 47.04166793823242,
"blob_id": "ce9f4637b9cad42afda2495eda1cadda3fa56018",
"content_id": "64bfd8766a2337e66c96845825b86880dc6b8921",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1179,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 24,
"path": "/ex044.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "print('{:=^40}'.format(' LOJAS GUANABARA '))\nvalor_compra = float(input('Olá! Qual o valor da compra? R$'))\nprint('Qual será a forma de pagamento? Digite o número referente às seguintes opções: ')\nprint('[1] à vista dinheiro / cheque')\nprint('[2] à vista no cartão')\nprint('[3] em até 2x no cartão')\nprint('[4] 3x ou mais no cartão')\nopcao = int(input('Digite sua opção: '))\nif opcao == 1:\n opcao1 = valor_compra - valor_compra * 0.1\n print('Você recebeu um desconto de 10% e sua compra sairá por R${:.2f}.'.format(opcao1))\nelif opcao == 2:\n opcao2 = valor_compra - valor_compra * 0.05\n print('Você recebeu um desconto de 5% e sua compra sairá por R${:.2f}.'.format(opcao2))\nelif opcao == 3:\n opcao3 = valor_compra / 2\n print('O valor das parcelas será de R${:.2f}.'.format(opcao3))\nelif opcao == 4:\n opcao4 = int(input('Em quantas parcelas você quer pagar?'))\n valor_total = valor_compra * 0.2 + valor_compra\n valor_parcelado = valor_total / opcao4\n print('Você irá pagar em {} parcelas de R${:.2f}, totalizando R${:.2f} COM JUROS.'.format(opcao4, valor_parcelado, valor_total))\nelse:\n print('Opçao inválida, tente novamente.')\n\n\n"
},
{
"alpha_fraction": 0.6137930750846863,
"alphanum_fraction": 0.6551724076271057,
"avg_line_length": 47.66666793823242,
"blob_id": "efb335f6e495f2b3a5f078dd8fa0beabbeb7cd9a",
"content_id": "be80430297bb3bbf9e6555daf85be406b0049a09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 148,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 3,
"path": "/ex013.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "sal = float(input('Digite o salário atual: R$'))\naum = sal + sal * 0.15\nprint('O novo salário com 15% de reajuste será de R${:.2f}.'.format(aum))"
},
{
"alpha_fraction": 0.5723751187324524,
"alphanum_fraction": 0.5953109264373779,
"avg_line_length": 33.33333206176758,
"blob_id": "7a0ff37f0cc85f66548ff1011e76e7cdeb987f7c",
"content_id": "76ff67dce1d97d63b3c4b361db2d02129bbd97b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1973,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 57,
"path": "/ex069.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa\ndeverá perguntar se o usuário quer ou não continuar. No final mostre:\nA) quantas pessoas tem mais de 18 anos.\nB)Quantos homens foram cadastrados.\nC)Quantas mulheres tem menos de 20 anos.\nTem verificacao de sexo válido, e se quer continuar.'''\n\nidade = 0\nsexo = ''\ncontinuacao = 'S'\ncontIdade = 0\ncontSexo = 0\ncontMulherVinte = 0\nwhile continuacao == 'S':\n idade = int(input('Digite sua idade: '))\n if idade >= 18:\n contIdade += 1\n sexo = input('Digite seu sexo [M/F]: ').strip().upper()\n while True:\n if sexo != 'M' and sexo != 'F':\n sexo = input('Opção inválida, tente novamente: ').strip().upper()\n else:\n break\n if sexo == 'M':\n contSexo += 1\n if idade <= 20 and sexo == 'F':\n contMulherVinte +=1\n continuacao = input('Quer continuar? [S/N] ').strip().upper()\n while True:\n if continuacao != 'S' and continuacao != 'N':\n continuacao = input('Opção inválida, tente novamente: ').strip().upper()\n else:\n break\n if continuacao == 'N':\n break\nprint(f'Nesse cadastro existem {contIdade} pessoas com 18 anos ou mais; foram cadastros {contSexo} homens e {contMulherVinte} mulheres com 20 anos ou menos.')\n\n'''tot18 = totH = totM20 = 0\nwhile True:\n idade = int(input('Idade: '))\n sexo = ' '\n while sexo not in 'MF':\n sexo = str(input('Sexo: [M/F] ')).strip().upper()[0]\n if idade >= 18:\n tot18 += 1\n if sexo == 'M':\n totH += 1\n if sexo == 'F' and idade < 20:\n totM20 += 1\n resp = ' '\n while resp not in 'SN':\n resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0]\n if resp == 'N':\n break\nprint(f'Total de pessoas com mais de 18 anos: {tot18}')\nprint(f'Ao todo temos {totH} homens cadastrados')\nprint(f'E temos {totM20} mulheres com menos de 20 anos.')'''\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5927130579948425,
"alphanum_fraction": 0.6193884015083313,
"avg_line_length": 32.41304397583008,
"blob_id": "f1135b6a2c47c2b81b1a70741b5474c34368daa7",
"content_id": "0744123fdb45ead4a049e38f1a9ca3e5c51e6874",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1549,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 46,
"path": "/ex070.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário\nvai continuar. No final, mostre:\nA) Qual é o total gasto na compra.\nB)Quantos produtos custam mais de R$1000.\nC)Qual é o nome do produto mais barato.'''\n\nsomatoriaPreco = 0\nacima1000 = 0\nresposta = 'S'\nmenorPreco = 0\nmaisBarato = ''\nwhile resposta == 'S':\n produto = input('Digite o nome do produto: ')\n preco = float(input('Digite o preço: R$'))\n somatoriaPreco += preco\n if preco >= 1000:\n acima1000 =+ 1\n if menorPreco == 0:\n menorPreco = preco\n maisBarato = produto\n elif menorPreco > preco:\n menorPreco = preco\n maisBarato = produto\n print(menorPreco, maisBarato)\n resposta = input('Quer continuar? [S/N]').strip().upper()\n while resposta != 'S' and resposta != 'N':\n resposta = input('Opção inválida, tente novamente: ').strip().upper()\nprint(f'O total gasto nessa compra foi de R${somatoriaPreco:.2f}; {acima1000} produto(s) custa(m) acima de R$1000,00 e nome do produto mais barato é {maisBarato}.')\n\n'''total = totmil = menor = cont = 0\nbarato = ' '\nwhile True:\n produto = str(input('Nome do produto: '))\n preco = float(input('Preço; R$'))\n cont += 1\n total += preco\n if preco > 1000:\n totmil += 1\n if cont == 1 or preco < menor:\n menor = preco\n barato = produto\n resp = ' '\n while resp not in 'SN':\n resp = str(input('Quer continuar? [S/N]')).strip().upper()[0]\n if resp == 'N':\n break'''\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6200000047683716,
"avg_line_length": 47,
"blob_id": "a6c3fa5d30cc0a5104486a8ccdc96cf0b840c1f8",
"content_id": "40d44be3ad4af2509e6322a6a37235c897aeb545",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 52,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 1,
"path": "/README.md",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "# _**Exercícios do Curso em Vídeo - Python 3**_\n\n\n"
},
{
"alpha_fraction": 0.7709677219390869,
"alphanum_fraction": 0.7838709950447083,
"avg_line_length": 50.83333206176758,
"blob_id": "28c9a3be096fb883b345c961272d9ec563ab6306",
"content_id": "02eeb4b3bcb9c1ec24bc3afa8865d57ad0d3ca78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 6,
"path": "/ex073.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do\nCampeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre:\na) Apenas os 5 primeiros colocados.\nb)Os últimos 4 colocados da tabela.\nc) Uma lista com os times em ordem alfabética.\nd) Em que posição estáo time da Chapecoense.'''"
},
{
"alpha_fraction": 0.5739796161651611,
"alphanum_fraction": 0.6275510191917419,
"avg_line_length": 34.45454406738281,
"blob_id": "e12a2b93d17315a13b1a104f75ec14fbb2e8f766",
"content_id": "5e0e00af25ad75acbcfc721e39a9cb286e4a945e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 393,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 11,
"path": "/ex023.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "numero = str(input('Digite um número entre 0 e 9999: '))\nprint('unidade: ', numero[3])\nprint('dezena: ', numero[2])\nprint('centena: ', numero[1])\nprint('milhar: ', numero[0])\n\n\"\"\"dividido = numero.split()\nprint('unidade: {:4}'.format(dividido[0][3]))\nprint('dezena: {:4}'.format(dividido[0][2]))\nprint('centena: {:4}'.format(dividido[0][1]))\nprint('milhar: {:4}'.format(dividido[0][0]))\"\"\"\n\n\n"
},
{
"alpha_fraction": 0.4285714328289032,
"alphanum_fraction": 0.5086206793785095,
"avg_line_length": 29.074073791503906,
"blob_id": "4ff005ca61dc04016105a679711d7e2d6ea8748c",
"content_id": "d3d896006be9e01cfd4219a178c989b110acc969",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 813,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 27,
"path": "/ex009.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "number = int(input('Digite um número: '))\nprint('-'* 10)\nn0 = number * 0\nn1 = number * 1\nn2 = number * 2\nn3 = number * 3\nn4 = number * 4\nn5 = number * 5\nn6 = number * 6\nn7 = number * 7\nn8 = number * 8\nn9 = number * 9\nn10 = number * 10\nprint('{} x {:2} = {}'.format(number, 0, n0))\nprint('{} x {:2} = {}'.format(number, 1, n1))\nprint('{} x {:2} = {}'.format(number, 2, n2))\nprint('{} x {:2} = {}'.format(number, 3, n3))\nprint('{} x {:2} = {}'.format(number, 4, n4))\nprint('{} x {:2} = {}'.format(number, 5, n5))\nprint('{} x {:2} = {}'.format(number, 6, n6))\nprint('{} x {:2} = {}'.format(number, 7, n7))\nprint('{} x {:2} = {}'.format(number, 8, n8))\nprint('{} x {:2} = {}'.format(number, 9, n9))\nprint('{} x {:2} = {}'.format(number, 10, n10))\nprint ('-' * 10)\n\n#print('{} x {} = {}'.format(number, 0, number*1))\n"
},
{
"alpha_fraction": 0.5835475325584412,
"alphanum_fraction": 0.6092544794082642,
"avg_line_length": 26.785715103149414,
"blob_id": "ff23639194c7a25de51fab7595569ffd22222398",
"content_id": "0e2044dbc10ef0f332a235f653f933bcdb6d1dfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 393,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 14,
"path": "/ex043.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "peso = float(input('Digite seu peso em kg: '))\naltura = float(input('Digite sua altura em m: '))\nIMC = peso / (altura * altura)\nprint('Seu IMC é de {:.1f} e você está '.format(IMC), end='')\nif IMC < 18.5:\n print('abaixo do peso.')\nelif IMC < 25:\n print('no peso ideal.')\nelif IMC < 30:\n print('com sobrepeso.')\nelif IMC < 40:\n print('obeso.')\nelse:\n print('obeso mórbido.')\n"
},
{
"alpha_fraction": 0.6739130616188049,
"alphanum_fraction": 0.6847826242446899,
"avg_line_length": 60,
"blob_id": "7af05bc13ba9a990f9abf323fa99a51198a5d4d6",
"content_id": "b557c21df460b869ad640bab950191c2418c92f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 187,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 3,
"path": "/ex027.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "nome = str(input('Digite seu nome completo: ')).strip()\ndividido = nome.split()\nprint('Seu primeiro nome é {} e seu último nome é {}.'.format(dividido[0], dividido[len(dividido)-1]))\n\n"
},
{
"alpha_fraction": 0.6285714507102966,
"alphanum_fraction": 0.6448979377746582,
"avg_line_length": 40,
"blob_id": "b30c04f8804b8600e71ef96fc095eda5168ac9ec",
"content_id": "f11b3eae57cb1f972f09a7436de7c26ad307baba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 252,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 6,
"path": "/ex005.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "number = int(input('Digite um número: '))\nant = number - 1\nsuc = number + 1\nprint('O número antecessor ao digitado é {}, e o sucessor é {}'.format(ant, suc))\n\n#print('O número antecessor ao digitado é {}, e o sucessor é {}'.format((n-1), (n+1)))"
},
{
"alpha_fraction": 0.675159215927124,
"alphanum_fraction": 0.7006369233131409,
"avg_line_length": 51.66666793823242,
"blob_id": "cfa5e8d02be30b1fd3fc24abb0c81aee90919d0b",
"content_id": "cc28b963cf73103a439d661c29622d692ce5164b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 159,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 3,
"path": "/ex010.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "money = float(input('Digite quanto reais você tem na carteira: R$'))\ndolar = money / 3.27\nprint('Com esse valor, você pode comprar US${:.2f}.'.format(dolar))"
},
{
"alpha_fraction": 0.5665897130966187,
"alphanum_fraction": 0.576982319355011,
"avg_line_length": 32.29487228393555,
"blob_id": "fcaac26b90d87f30ce71e01858c115eb7d8b5868",
"content_id": "10e9612d757da535dd90df565ef20d50ac6e5c25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2632,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 78,
"path": "/ex068.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador perder,\nmostrando o total de vitórias consecutivas que ele conquistou no final do jogo.\n- digitar o valor, escolher P ou I. Mostrar o número que foi jogado, o número que o computador escolheu\ne o total, mostrando se deu Par ou ímpar. Escreve se ganhou ou perdeu. * Game over, você venceu x vezes.\nSe ganhar, reinicia o jogo.\n'''\n\nfrom random import randint\nresultado = ''\ncont = 0\nganhou = False\nwhile True:\n computador = randint(0, 10)\n jogador = int(input('Digite um número entre 0 e 10: '))\n while jogador != True:\n if jogador < 0 or jogador > 10:\n jogador == False\n jogador = int(input('Opção inválida, tente novamente: '))\n else:\n break\n parOuImpar = input('Você quer par ou ímpar? [P/I]: ').strip().upper()\n while parOuImpar != True:\n if parOuImpar != 'P' and parOuImpar != 'I':\n parOuImpar == False\n parOuImpar = input('Opção incorreta, digite novamente: ').strip().upper()\n else:\n break\n soma = jogador + computador\n if soma % 2 == 0:\n resultado = 'PAR'\n else:\n resultado = 'ÍMPAR'\n print(f'Você escolheu {jogador}, {parOuImpar} e o computador escolheu {computador}, totalizando {soma}, que é um número {resultado}.')\n if parOuImpar == 'P' and resultado == 'PAR':\n print('Você acertou!')\n ganhou = True\n cont += 1\n elif parOuImpar == 'I' and resultado == 'ÍMPAR':\n print('Você acertou!')\n ganhou = True\n cont += 1\n else:\n print('Você perdeu :(')\n ganhou = False\n if ganhou == False:\n break\nprint(f'Game Over! Você ganhou {cont} vezes')\n\n\n\n\n'''from random import randint\nv = 0\nwhile True:\n jogador = int(input('Diga um valor: '))\n computador = randint(0,10)\n total = jogador + computador\n tipo = ' '\n while tipo not in (PI):\n tipo = str(input('Par ou Ímpar? [P/I]')).strip().upper()[0]\n print(f'Você jogou {jogador} e o computador {computador}. Total de {total} ', end='')\n print('DEU PAR' if total % 2 == 0 else 'DEU ÍMPAR')\n if tipo == 'P':\n if total % 2 == 0:\n print('Você VENCEU!')\n v +=1\n else:\n print('Você PERDEU!')\n break\n elif tipo == 'I':\n if total % 2 == 1:\n print('Você VENCEU!')\n v += 1\n else:\n print('Você PERDEU!')\n break\n print('Vamos jogar novamente...')\nprint(f'GAME OVER! Você venceu {v} vezes.')'''\n\n"
},
{
"alpha_fraction": 0.6096774339675903,
"alphanum_fraction": 0.6209677457809448,
"avg_line_length": 23.760000228881836,
"blob_id": "fb76bc43725b7ba9a6b26aaee537abfccb6c4b44",
"content_id": "048d20bc1ae041c2f834b85024f7def9edb11fe0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 623,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 25,
"path": "/ex060.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''from math import factorial\nnumero = int(input('Digite um número para saber seu fatorial: '))\nprint(factorial(numero))'''\n\n\n'''cont = 1\nmult = 1\nnumero = int(input('Digite um número para saber seu fatorial: '))\nwhile cont < numero:\n fatorial = numero - cont\n mult *= fatorial\n cont = cont + 1\nprint(numero * mult)'''\n\n\nnumero = int(input('Digite um número para saber seu fatorial: '))\ncont = numero\nmult = 1\nprint('Calculando {}! = '.format(numero), end='')\nwhile cont > 0:\n print('{}'.format(cont), end='')\n print(' x ' if cont > 1 else ' = ', end='')\n mult *= cont\n cont = cont - 1\nprint(mult)\n\n"
},
{
"alpha_fraction": 0.6086956262588501,
"alphanum_fraction": 0.6135265827178955,
"avg_line_length": 33.66666793823242,
"blob_id": "090eb24378df10feda7cc102f1245f399b8dc8a7",
"content_id": "e341834f90cf776975865ced3a068957c14fa023",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 6,
"path": "/ex051.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "termo = int(input('Digite o primeiro termo: '))\nrazao = int(input('Digite a razão: '))\ndecimo = termo + 9 * razao\nfor c in range (termo, decimo + razao, razao):\n print(c,' ⇢ ', end= ' ');\nprint('ACABOU!')"
},
{
"alpha_fraction": 0.6493902206420898,
"alphanum_fraction": 0.6646341681480408,
"avg_line_length": 32.7931022644043,
"blob_id": "09f51ede5f7441c9126a27ee527ad46b68aa26ad",
"content_id": "9c54b75354946037ec31523f3cd1861ec619176e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 996,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 29,
"path": "/ex058.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''print('Jogo de adivinhação')\ncont = 1\nfrom random import randint\nfrom time import sleep\nnumero = int(input('Digite um número entre 0 e 5: '))\nprint('Estou lendo o número digitado...')\nsleep(4)\nsorteio = randint(0,5)\nwhile sorteio != numero:\n cont += 1\n numero = int(input('Não foi dessa vez, tente novamente: '))\nprint('Você acertou! Foram necessárias {} tentativas.'.format(cont))'''\n\nfrom random import randint\ncomputador = randint(0, 10)\nprint('Sou seu computador... Acabei de pensar em um número entre 0 e 10. \\nSerá que você consegue adivinhar qual foi? ')\nacertou = False\npalpites = 0\nwhile not acertou:\n jogador = int(input('Qual é o seu palpite? '))\n palpites += 1\n if jogador == computador:\n acertou = True\n else:\n if jogador < computador:\n print('Mais... Tente mais uma vez')\n elif jogador > computador:\n print('Menos... Tente mais uma vez')\nprint('Você acertou depois de {} tentativas.'.format(palpites))\n\n\n\n\n"
},
{
"alpha_fraction": 0.6764705777168274,
"alphanum_fraction": 0.6950464248657227,
"avg_line_length": 45.21428680419922,
"blob_id": "b8e9070a47fa0cef64f89e3c6674f133e357c0ff",
"content_id": "5e8af6e1dc87222a3dd45e9cdeb3b9c41546c314",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 657,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 14,
"path": "/ex041.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "from datetime import date\nano_nascimento = int(input('Digite seu ano de nascimento: '))\nano_atual = date.today().year\nidade = ano_atual - ano_nascimento\nif idade <= 9:\n print('Você tem {} anos e pertence à categoria MIRIM.'.format(idade))\nelif idade >9 and idade <= 14:\n print('Você tem {} anos e pertence à categoria INFANTIL.'.format(idade))\nelif idade > 14 and idade <= 19:\n print('Você tem {} anos e pertence à categoria JUNIOR.'.format(idade))\nelif idade > 19 and idade <= 25:\n print('Você tem {} anos e pertence à categoria SÊNIOR.'.format(idade))\nelse:\n print('Você tem {} anos e pertence à categoria MASTER.'.format(idade))"
},
{
"alpha_fraction": 0.5917159914970398,
"alphanum_fraction": 0.6094674468040466,
"avg_line_length": 41.5,
"blob_id": "3cf0b81856da22fc68c221ba8116d39f01a1ffb7",
"content_id": "3bef1e4c20f06577220fda62d7c14550cd649bc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 170,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 4,
"path": "/ex049.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "numero = int(input('Digite um número pra descobrir sua tabuada: '))\nfor c in range (0, 11):\n tabuada = numero * c\n print('{} * {} = {}'.format(numero, c, tabuada))"
},
{
"alpha_fraction": 0.7526502013206482,
"alphanum_fraction": 0.7597172856330872,
"avg_line_length": 39.57143020629883,
"blob_id": "d224c6c919e264e287c866578583d870f11af19e",
"content_id": "1b2610142c82943955e4d7254cfab6052ed8f660",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 7,
"path": "/ex075.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Desenvolva um programa que leia quatro valores pelo teclado\ne guarde-os em uma tupla. No final, mostre:\na) Quantas vezes apareceu o valor 9.\nb) Em que posição foi digitado o primeiro valor 3.\nc)Quais foram os números pares.\nSe buscar um valor que não existe, tem que dar erro.\n'''"
},
{
"alpha_fraction": 0.6356589198112488,
"alphanum_fraction": 0.6550387740135193,
"avg_line_length": 31.25,
"blob_id": "521956a72cc6e57f0ca0b992fd343c5288b59830",
"content_id": "f07037d3efcf2bf3d4cb2a060a4b0a0972c31836",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 261,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 8,
"path": "/ex064.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "numero = int(input('Digite um número: '))\nsomatoria = numero\ncont = 0\nwhile numero != 999:\n somatoria += numero\n cont += 1\n numero = int(input('Digite um número: '))\nprint('Foram digitados {} números e a soma total foi {}.'.format(cont, somatoria))\n"
},
{
"alpha_fraction": 0.6702253818511963,
"alphanum_fraction": 0.6809015274047852,
"avg_line_length": 39.095237731933594,
"blob_id": "bbce58a095f810d7b28990a4387eee34790d4d95",
"content_id": "e99ff7cf2e36b28c1cb9cae83943ca7e70496216",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 862,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 21,
"path": "/ex037.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "numero = int(input('Escreva um número inteiro: '))\nprint('Digite 1 para conversão para binário')\nprint('Digite 2 para conversão para octal')\nprint('Digite 3 para conversão para hexadecimal')\nescolha = int(input())\nprint('Você escolheu a opção {}.'.format(escolha))\nif escolha == 1:\n binario = str(bin(numero))\n binario_editado = binario.lstrip('0b')\n print('O número {} em binário é {}.'.format(numero, binario_editado))\nelif escolha == 2:\n octal = str(oct(numero))\n octal_editado = octal.lstrip('0o')\n print('O número {} em octal é {}.'.format(numero, octal_editado))\nelif escolha == 3:\n hexadecimal = str(hex(numero))\n hexadecimal_editado = hexadecimal.lstrip('0x')\n print('O número {} em hexadecimal é {}.'.format(numero, hexadecimal_editado))\nelse:\n print('O número digitado é inválido.')\nprint('Até mais!')\n\n"
},
{
"alpha_fraction": 0.5154777765274048,
"alphanum_fraction": 0.5477792620658875,
"avg_line_length": 29.875,
"blob_id": "47c2f8f2782b940231f59ce9e265a1951a4257ce",
"content_id": "4b2d95b4b76cb15b39ec728df54cd2237d1aa0d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 753,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 24,
"path": "/ex059.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "num1 = int(input('Digite um número: '))\nnum2 = int(input('Digite outro: '))\nprint('Digite uma das opções a seguir: ')\nopcao = 0\nwhile opcao != 5:\n print('[1] Somar \\n[2] Multiplicar \\n[3] Maior \\n[4] Novos números \\n[5] Sair')\n opcao = int(input('Digite aqui a opção desejada: '))\n if opcao == 1:\n print(num1 + num2)\n elif opcao == 2:\n print(num1 * num2)\n elif opcao == 3:\n if num1 > num2:\n print(num1)\n else:\n print(num2)\n elif opcao == 4:\n num1 = int(input('Digite um número: '))\n num2 = int(input('Digite outro: '))\n elif opcao == 5:\n print('Finalizando...')\n else:\n opcao = int(input('Opção inválida, tente novamente: '))\nprint('Fim')\n\n\n"
},
{
"alpha_fraction": 0.7263157963752747,
"alphanum_fraction": 0.7263157963752747,
"avg_line_length": 62.66666793823242,
"blob_id": "d015fe29a5bd434143fa835d30633157e9f59bb4",
"content_id": "6c45d259c5f023381982970b0321196deeea62e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 3,
"path": "/ex077.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie um programa que tenha uma tupla com várias palavras (não usar acentos).\nDepois disso, você deve mostrar, para cada palavra, quais são\nsuas vogais. - Na palavra X temos a, e, i...'''"
},
{
"alpha_fraction": 0.6874116063117981,
"alphanum_fraction": 0.6874116063117981,
"avg_line_length": 53.46154022216797,
"blob_id": "cdd0d537a0fa4f1ebac8589703db1d2b595d2f82",
"content_id": "77b0af3c7eec4aeee94df39779f16e3b32e024fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 726,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 13,
"path": "/ex004b.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "ent = input('Digite qualquer coisa: ')\nprint('O tipo primitivo desse valor {}'.format(type(ent)))\nprint('É um alfanumérico? {}'.format(ent.isalnum()))\nprint('É alfabético? {}'.format(ent.isalpha()))\nprint('É um decimal? {}'.format(ent.isdecimal()))\nprint('É um dígito? {}'.format(ent.isdigit()))\nprint('É um identificador? {}'.format(ent.isidentifier()))\nprint('Está escrito em letras minúsculas ? {}'.format(ent.islower()))\nprint('É um número? {} '.format(ent.isnumeric()))\nprint('É uma string não vazia? {}'.format(ent.isprintable()))\nprint('Só tem espaço? {}'.format(ent.isspace()))\nprint('Está capitalizada? {}'.format(ent.istitle()))\nprint('Está escrito em letras maiúsculas? {}'.format(ent.isupper()))"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6458333134651184,
"avg_line_length": 47,
"blob_id": "3f2cf1a1bcd578c1d483052c21f4e03605879670",
"content_id": "cd716ed0546709f30fcbcb2f1440a8c1f3f5645f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 244,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 5,
"path": "/ex031.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "distancia = float(input('Qual é a distância da sua viagem? (em km) - '))\nif distancia <= 200:\n print('A sua passagem será de R${:.2f}.'.format(distancia * 0.50))\nelse:\n print('A sua passagem será de R${:.2f}.'.format(distancia*0.45))\n"
},
{
"alpha_fraction": 0.5453020334243774,
"alphanum_fraction": 0.5604026913642883,
"avg_line_length": 26.136363983154297,
"blob_id": "489db25ba08bbf7d9e2a928777f4a8bb73fa9ed0",
"content_id": "5ec0b3c89b6909eb7e4247f28ff0a6c5d25f57cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 597,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 22,
"path": "/ex055.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''maiorPeso = 0\nmenorPeso = 300\nfor c in range (1,6):\n peso = float(input('Digite em peso (em kg): '))\n if peso > maiorPeso:\n maiorPeso = peso\n if peso < menorPeso:\n menorPeso = peso\nprint(maiorPeso, menorPeso)'''\n\nfor c in range (1,6):\n peso = float(input('Digite o peso da {}ª pessoa: '.format(c)))\n if c == 1:\n maior = peso\n menor = peso\n else:\n if peso > maior:\n maior = peso\n if peso < menor:\n menor = peso\nprint('O maior peso lido foi {}kg.'.format(maior))\nprint('O menor peso lido foi {}kg.'.format(menor))"
},
{
"alpha_fraction": 0.6600496172904968,
"alphanum_fraction": 0.6947891116142273,
"avg_line_length": 56.71428680419922,
"blob_id": "c640b8dcf47c74b41fcf497a4599fbe2c68635c3",
"content_id": "961e5d00fff9ad58a1c894f5b2a8d99e886fe2ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 406,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 7,
"path": "/ex034.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "salario_inicial = float(input('Digite o salário atual: R$'))\nif salario_inicial > 1250:\n reajuste_menor = salario_inicial * 0.10 + salario_inicial\n print('O salário passou de {:.2f} para {:.2f}.'.format(salario_inicial, reajuste_menor))\nelse:\n reajuste_maior = salario_inicial * 0.15 + salario_inicial\n print('O salário passou de {:.2f} para {:.2f}.'.format(salario_inicial, reajuste_maior))"
},
{
"alpha_fraction": 0.6199524998664856,
"alphanum_fraction": 0.6365795731544495,
"avg_line_length": 35.60869598388672,
"blob_id": "82c1e6004380f1cdfc9ccccc3a42d2b5f1a4881e",
"content_id": "ab1fc687bdddcf462fdeff298834ec9959775ee2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 848,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 23,
"path": "/ex056.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "somatorioIdade = 0\nmaisVelho = 0\nnomeMaisVelho = ''\nidadeMulheres = 0\nfor c in range (1, 5):\n nome = input('Digite seu nome: ')\n idade = int(input('Digite sua idade: '))\n sexo = input('Digite F para mulher ou M para homem: ').upper().strip()\n somatorioIdade += idade\n if sexo == 'M':\n if maisVelho < idade:\n maisVelho = idade\n nomeMaisVelho = nome\n else:\n if idade <= 20:\n idadeMulheres += 1\nmedia = somatorioIdade / 4\nprint('A média de idade nesse grupo é de {} anos.'.format(media))\nprint('A idade do homem mais velho é de {} anos, e o nome dele é {}.'.format(maisVelho, nomeMaisVelho))\nif idadeMulheres >=1:\n print('A quantidade de mulheres com menos de 20 anos é de {}.'.format(idadeMulheres))\nelse:\n print('Não existem mulheres com menos de 20 anos nessa amostra.')\n"
},
{
"alpha_fraction": 0.5891472697257996,
"alphanum_fraction": 0.6279069781303406,
"avg_line_length": 42.33333206176758,
"blob_id": "4e94c5b317bd7e7b5ea69f4bc0c2822d7597eb61",
"content_id": "9570772fb957d0cb003a70ea4cd120644af02f02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 131,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 3,
"path": "/ex012.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "pri = float(input('Digite o preço: R$'))\ndes = pri - pri * 0.05\nprint('O valor com desconto de 5% será de R${:.2f}.'.format(des))"
},
{
"alpha_fraction": 0.6955223679542542,
"alphanum_fraction": 0.6985074877738953,
"avg_line_length": 40.125,
"blob_id": "14a26fecf4afc6aea51a6fa0ec148217de143887",
"content_id": "34ffe7ffd5c34a99b83d4e582a4e95490efdb234",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 8,
"path": "/ex022.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "nome = str(input('Digite seu nome completo: ')).strip()\nprint(nome.upper())\nprint(nome.lower())\nnomecompleto = len(nome)\nnumerodeespacos = nome.count(' ')\nprint('O número de letras do seu nome é {}.'.format(nomecompleto - numerodeespacos))\ndividido = nome.split()\nprint('O primeiro nome tem {} letras.'.format(len(dividido[0])))\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5573770403862,
"alphanum_fraction": 0.5860655903816223,
"avg_line_length": 29.625,
"blob_id": "b7d3adbe1fa4859379c4ecf58487d7dcf3202cf5",
"content_id": "1a8b36f7093211745bca5ea0efd7e432f727b5fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 247,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 8,
"path": "/ex050.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "soma = 0\ncont = 0\nfor c in range (1, 7):\n numero = int(input('Digite um número inteiro: '))\n if numero % 2 == 0:\n soma += numero\n cont += 1\nprint('O resultado da soma dos {} números pares digitados é {}.'.format(cont, soma))"
},
{
"alpha_fraction": 0.5990291237831116,
"alphanum_fraction": 0.606796145439148,
"avg_line_length": 35.78571319580078,
"blob_id": "2bd029f9cabfff24c75baaa8dfb7b1ca7942d387",
"content_id": "955d0f8076f68b65fc8b099c755d80083f62d6e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1040,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 28,
"path": "/ex045.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "from random import choice\nfrom time import sleep\nprint('{:=^40}'.format(' JOKENPO '))\nnome = input('Nome do jogador: ')\nprint('''Suas opções: \n[ Pedra ]\n[ Papel ]\n[ Tesoura ]''')\nescolha = input('Qual é a sua jogada? ').strip().upper()\nif escolha != 'PEDRA' and escolha !='TESOURA' and escolha != 'PAPEL':\n print('Opção Inválida, tente novamente.')\nelse:\n escolha_pc = choice(['PEDRA', 'TESOURA', 'PAPEL'])\n print('JO')\n sleep(1)\n print('KEN')\n sleep(1)\n print('PO!!!!')\n print('=-' * 20)\n print('O computador jogou {}.'.format(escolha_pc))\n print('{} jogou {}.'.format(nome, escolha))\n print('=-' * 20)\n if escolha_pc == 'PEDRA' and escolha == 'TESOURA' or escolha_pc == 'TESOURA' and escolha == 'PAPEL' or escolha_pc == 'PAPEL' and escolha == 'PEDRA':\n print('O computador venceu.')\n elif escolha_pc == escolha:\n print('O computador jogou {} e você também. Ninguém ganhou nessa rodada.'.format(escolha_pc))\n else:\n print('{} venceu o jogo, parabéns!'.format(nome))\n"
},
{
"alpha_fraction": 0.696864128112793,
"alphanum_fraction": 0.707317054271698,
"avg_line_length": 70.5,
"blob_id": "374cddbd281652b1755637448d8e618e7a3d5c32",
"content_id": "4da595b1efb3f8e1b1de82f8cc959f7ea1f846a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 196,
"num_lines": 4,
"path": "/ex018.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "import math\nangulo = float(input('Digite um ângulo: '))\nconversao = math.radians(angulo)\nprint('Em relação ao ângulo {}, os valores de seno, cosseno e tangente são, respectivamente: {:.2f}, {:.2f}, {:.2f}.'.format(angulo, math.sin(conversao), math.cos(conversao), math.tan(conversao)))\n\n"
},
{
"alpha_fraction": 0.5970237851142883,
"alphanum_fraction": 0.6160714030265808,
"avg_line_length": 31.960784912109375,
"blob_id": "f45b9eacdff9172f387fea77e765fb6aec53d041",
"content_id": "e3910d158436271136a768caa32c548b12c47389",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1706,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 51,
"path": "/ex065.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "somatoria = 0\ncont = 0\nnumero1 = int(input('Digite um número: '))\nnumero2 = int(input('Digite um número: '))\nif numero1 > numero2:\n maiorValor = numero1\nelse:\n maiorValor = numero2\nif numero1 < numero2:\n menorValor = numero1\nelse:\n menorValor = numero2\nif numero1 == numero2:\n maiorValor = numero1\n menorValor = numero1\nopcao = input('Quer continuar? [S/N] ').strip().upper()\nif opcao != 'S' and opcao != 'N':\n opcao = input('Opção inválida, tente novamente: ').strip().upper()\nwhile opcao == 'S':\n numero3 = int(input('Digite um número: '))\n somatoria += numero3\n cont += 1\n if numero3 >= maiorValor:\n maiorValor = numero3\n if numero3 <= menorValor:\n menorValor = numero3\n opcao = input('Quer continuar? [S/N] ').strip().upper()\n if opcao != 'S' and opcao != 'N':\n opcao = input('Opção inválida, tente novamente: ').strip().upper()\nnumerosdigitados = 2 + cont\nmedia = (numero1 + numero2 + somatoria) / numerosdigitados\nprint('A média dos números digitados foi de {:.1f}.'.format(media))\nprint('O maior número digitado foi {} e o menor foi {}.'.format(maiorValor, menorValor))\n\n'''resp = 'S'\nsoma = quant = média = maior = manor = 0\nwhile resp in 'Ss':\n núm = int(input('Digite um número: '))\n soma += núm\n quant += 1\n if quant == 1:\n maior = menor = núm\n else:\n if núm > maior:\n maior = núm\n if núm < menor:\n menor = núm\n resp = str(input('Quer continuar? [S/N] ')).upper().strip()[0]\nmédia = soma / quant\nprint('A média dos números digitados foi de {:.1f}.'.format(média))\nprint('O maior número digitado foi {} e o menor foi {}.'.format(maior, menor))'''"
},
{
"alpha_fraction": 0.6319218277931213,
"alphanum_fraction": 0.6612377762794495,
"avg_line_length": 37.5,
"blob_id": "45b55fad1aff777c03a0f61d9d36810e43eaa8cf",
"content_id": "3698dc691a7ac7753b5f6bda05fa6e26a9ef9cdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 310,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 8,
"path": "/ex054.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "from datetime import date\ncontador = 0\nanoAtual = date.today().year\nfor c in range (1, 8):\n anoNasc = int(input('Digite seu ano de nascimento: '))\n if anoAtual - anoNasc >= 21:\n contador += 1\nprint('O número de pessoas com mais de 21 anos é {} e de menores é {}.'.format(contador, 7-contador))"
},
{
"alpha_fraction": 0.6982758641242981,
"alphanum_fraction": 0.6982758641242981,
"avg_line_length": 38,
"blob_id": "218ac5177de51ce731b83455eac508d509342c14",
"content_id": "c01bb702560d3c2d34e445599d0a2480f590b822",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 116,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 3,
"path": "/ex025.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "nome = str(input('Digite seu nome completo: ')).strip()\n#nomecorrigido = nome.upper()\nprint('SILVA' in nome.upper())"
},
{
"alpha_fraction": 0.7102272510528564,
"alphanum_fraction": 0.7159090638160706,
"avg_line_length": 43.25,
"blob_id": "6494cbe380ca605d7061d7adb514a0a47d66fe6a",
"content_id": "12833275844912bcae34ebe99c3029e5d79e9175",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 176,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 4,
"path": "/ex024.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "cidade = str(input('Digite o nome de uma cidade: ')).strip()\n#cidadecorrigido = cidade.capitalize()\n#print('Santo' in cidadecorrigido)\nprint(cidade.capitalize()[:5] == 'Santo')"
},
{
"alpha_fraction": 0.633728563785553,
"alphanum_fraction": 0.6587615013122559,
"avg_line_length": 30.5,
"blob_id": "2bdf461d10eb014acb94b16ef2e6a2e1a688c1fa",
"content_id": "bcc7b842e1b4a7d00084112f301f837460e880c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 770,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 24,
"path": "/ex066.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie um programa que leia vários números inteiros pelo teclado.\nO programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.\nNo final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando a flag)\ntem que aparecer quantos números foram digitados\n'''\n\nnumero = cont = soma = 0\nwhile numero != 999:\n numero = int(input('Digite um número: '))\n if numero == 999:\n break\n cont += 1\n soma += numero\nprint(f'Foram digitados {cont} números e a soma total foi de {soma}. ')\n\n'''soma = cont = 0\nwhile True:\n num = int(input('Digite um valor (999 para parar): '))\n if num == 999:\n break\n cont += 1\n soma += num\nprint(f'A soma dos {cont} valores foi de {soma}!')\n'''\n\n\n\n"
},
{
"alpha_fraction": 0.6017315983772278,
"alphanum_fraction": 0.649350643157959,
"avg_line_length": 50.22222137451172,
"blob_id": "577f34b01effaccd58a17da79ed0cf6882f569f7",
"content_id": "7f8331c423d408951994a1f8d1d216c3189a0625",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 473,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 9,
"path": "/ex040.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "nota1 = float(input('Digite a primeira nota: '))\nnota2 = float(input('Digite a segunda nota: '))\nmedia = (nota1 + nota2)/2\nif media < 5.0:\n print('Sua média foi de {:.1f}, abaixo ou igual a 5.0, você está reprovado(a).'.format(media))\nelif 5.0 <= media and media <= 6.9:\n print('Sua média foi de {:.1f}, entre 5.0 e 6.9, você está de recuperação.'.format(media))\nelse:\n print('Sua média foi de {:.1f}, acima de 7.0, você está aprovado.'.format(media))\n\n"
},
{
"alpha_fraction": 0.6911519169807434,
"alphanum_fraction": 0.6911519169807434,
"avg_line_length": 45,
"blob_id": "ae9da0413a310b5e8e47c2db50c79d6cce8932ab",
"content_id": "89e4f63c82dda742f900d36c1980a158445e7056",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 618,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 13,
"path": "/ex004.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "ent = input('Digite qualquer coisa: ')\nprint('O tipo primitivo desse valor ' ,type(ent))\nprint('É um alfanumérico? ', ent.isalnum())\nprint('É alfabético? ', ent.isalpha())\nprint('É um decimal? ', ent.isdecimal())\nprint('É um dígito?', ent.isdigit())\nprint('É um identificador? ', ent.isidentifier())\nprint('Está escrito em letras minúsculas ? ', ent.islower())\nprint('É um número? ', ent.isnumeric())\nprint('É uma string não vazia? ', ent.isprintable())\nprint('Só tem espaço? ', ent.isspace())\nprint('Está capitalizada? ', ent.istitle())\nprint('Está escrito em letras maiúsculas? ', ent.isupper())\n\n"
},
{
"alpha_fraction": 0.7104477882385254,
"alphanum_fraction": 0.7104477882385254,
"avg_line_length": 54.83333206176758,
"blob_id": "f73eb50747dde066a9715da659844525ce92c444",
"content_id": "319fe1f1cf2953a94246d8f3a9e55021f494eeda",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 343,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 6,
"path": "/ex016.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''from math import trunc\nnumber = float(input('Digite um número para descobrir sua porção inteira: '))\nprint('O número {} tem a parte inteira {}.'.format(number, trunc(number)))'''\n\nnumber = float(input('Digite um número para descobrir sua porção interira: '))\nprint('O número {} tem a parte inteira {}.'.format(number, int(number)))\n"
},
{
"alpha_fraction": 0.6521739363670349,
"alphanum_fraction": 0.665217399597168,
"avg_line_length": 45,
"blob_id": "d5b3dc4396d158cb62a094e2a32844bb8bc3ca41",
"content_id": "71e8dd32cb63152aa40ff8e3eaa65707e681a773",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 234,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 5,
"path": "/ex011.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "alt = float(input('Digite a altura da parede: '))\nlar = float(input('Digite a largura da parede: '))\nare = alt * lar\ntin = are / 2\nprint('A área da parede é {}m2 e a quantidade de tinta necessária é de {:.2f}L.'.format(are, tin))\n"
},
{
"alpha_fraction": 0.5991735458374023,
"alphanum_fraction": 0.6363636255264282,
"avg_line_length": 39,
"blob_id": "c9d00338d8df87bee86ac9d2eed911b72ef4f5fa",
"content_id": "8703064be432298c3e42829396c0672be08a527c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 6,
"path": "/ex033.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "n1 = int(input('Digite um número: '))\nn2 = int(input('Digite outro: '))\nn3 = int(input('Digite mais um: '))\nmaximo = max(n1, n2, n3)\nminimo = min(n1, n2, n3)\nprint('O máximo valor digitado foi {} e o mínimo foi {}.'.format(maximo, minimo))\n\n\n"
},
{
"alpha_fraction": 0.3642857074737549,
"alphanum_fraction": 0.4285714328289032,
"avg_line_length": 22.33333396911621,
"blob_id": "dc1094377a924f51a14597e52f3988f2bf556fa8",
"content_id": "74262a194dff476473343fda8e9475a7232a9c2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 6,
"path": "/ex047.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''for c in range (1, 51):\n if c % 2 == 0:\n print(c , end = ' ')'''\nfor c in range (2, 51, 2):\n print(c, end=' ')\nprint('Fim')\n"
},
{
"alpha_fraction": 0.5365710854530334,
"alphanum_fraction": 0.6155646443367004,
"avg_line_length": 32.490196228027344,
"blob_id": "ff19deb5ed537983b6298182b4f2bbd138729e6f",
"content_id": "bb6be376107eec7ec39c8e1d787c6935d8ae0588",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1758,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 51,
"path": "/ex071.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual\nserá o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues.\nOBS: Considere que o caixa possui cédulas de R$50,00, R$20,00, R$10 e R$1.00'''\n\nvalorSaque = int(input('Digite o valor do saque: R$ '))\ncedulas50 = valorSaque // 50\nresto50 = (valorSaque % 50)\ncedula20 = (resto50 // 20)\nresto20 = (resto50 % 20)\ncedula10 = (resto20 // 10)\nresto10 = (resto20 % 10)\nif cedulas50 > 0 and cedulas50 != 1:\n print(f'Você receberá {cedulas50} cédulas de R$50.')\nelif cedulas50 == 1:\n print(f'Você receberá {cedulas50} cédula de R$50.')\nif cedula20 > 0 and cedula20 != 1:\n print(f'Você receberá {cedula20} cédulas de R$20.')\nelif cedula20 == 1:\n print(f'Você receberá {cedula20} cédula de R$20.')\nif cedula10 > 0 and cedula10 != 1:\n print(f'Você receberá {cedula10} cédulas de R$10.')\nelif cedula10 == 1:\n print(f'Você receberá {cedula10} cédula de R$10.')\nif resto10 > 0 and resto10 != 1:\n print(f'Você receberá {resto10} de cédulas de R$1.')\nelif resto10 == 1:\n print(f'Você receberá {resto10} de cédula de R$1.')\n\n'''print('=' * 30)\nprint('{:^30}'.format('BANCO CEV'))\nprint('=' * 30)\nvalor = int(input('Que valor você quer sacar? R$'))\ntotal = valor\ncéd = 50\ntotcéd = 0\nwhile True:\n if total >= céd:\n total -= céd\n totcéd += 1\n else:\n if totcéd > 0:\n print(f'Total de {totcéd} cédulas de R${céd}')\n if céd == 50:\n céd = 20\n elif céd == 20:\n céd = 10\n elif céd == 10:\n céd = 1\n totcéd = 0\n if total == 0:\n break'''\n\n"
},
{
"alpha_fraction": 0.5782608985900879,
"alphanum_fraction": 0.5782608985900879,
"avg_line_length": 37.16666793823242,
"blob_id": "589a050088c17245dcdc02e608293bd142f0c7d5",
"content_id": "4741d7da720cca0ae5aeaf802e89581e2e25ebeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 235,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 6,
"path": "/ex057.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "sexo = ''\nwhile sexo != 'M' and sexo != 'F':\n sexo = input('Digite o sexo [M/F]: ').strip().upper()\n if sexo != 'M' and sexo != 'F':\n print('Informação inválida, tente novamente.')\nprint('Obrigada pela informação.')\n\n"
},
{
"alpha_fraction": 0.503496527671814,
"alphanum_fraction": 0.5641025900840759,
"avg_line_length": 17.65217399597168,
"blob_id": "6ac2e8432168efd343ef8798f2b561db40526390",
"content_id": "d432c53ca8c6b0df12277952de99aee1d99a68ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 23,
"path": "/ex063.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''n = int(input('Quantos números da frequência de Fibonacci você quer ver? '))\nF1 = 1\nF2 = 1\nprint(F1)\nprint(F2)\nfor c in range (0, n-2):\n soma = F1 + F2\n print(soma)\n F2 = F1\n F1 = soma'''\n\n\nn = int(input('Quantos números da frequência de Fibonacci você quer ver? '))\nF1 = 0\nF2 = 1\nprint(F1 , end=' ')\ncont = 1\nwhile cont <= n-1:\n soma = F1 + F2\n print(soma , end=' ')\n F2 = F1\n F1 = soma\n cont += 1\n"
},
{
"alpha_fraction": 0.6399999856948853,
"alphanum_fraction": 0.6496551632881165,
"avg_line_length": 28,
"blob_id": "d3a64745dd5c9019a751a68a7f7df04b23345ec6",
"content_id": "aad44827a2a276107e57f1ab3a1b1414eb7de9ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 735,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 25,
"path": "/ex053.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "frase = input('Digite uma frase: ').strip().upper()\nfraseSemEspaco = frase.replace(' ', '')\nquantidade = len(fraseSemEspaco)\ncontrario = ''\nfor c in range (quantidade-1, -1, -1):\n contrario += fraseSemEspaco[c]\nif fraseSemEspaco == contrario:\n print('Essa frase é um palíndromo, pois {} é igual a {}.'.format(fraseSemEspaco, contrario))\nelse:\n print('Essa frase é não é um palíndromo, pois {} não é igual a {}.'.format(fraseSemEspaco, contrario))\n\n'''frase = str(input('Digite uma frase: ')).strip().upper()\npalavras = frase.split()\njunto = ''.join(palavras)\ninverso = ''\nfor letra in range (len(junto) -1, -1, -1):\n inverso += junto[letra]\n \nou após o join:\n\ninverso = junto[::-1] - sem usar o for\n\n\n \n'''\n"
},
{
"alpha_fraction": 0.6203703880310059,
"alphanum_fraction": 0.6342592835426331,
"avg_line_length": 29.5,
"blob_id": "2c6e0295f5a6f94807ab9a56b2543e7b2c996bca",
"content_id": "2f6ce295d370668072a660b2dcc78e65cbda3d6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/ex062.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "primeiroTermo = int(input('Digite o valor do primeiro termo: '))\nrazao = int(input('Digite a razão da PA: '))\ntermo = primeiroTermo\ncont = 1\ntotal = 0\nmais = 10\nwhile mais != 0:\n total = total + mais\n while cont <= total:\n print(termo)\n termo += razao\n cont += 1\n mais = int(input('Quantos termos você quer mostrar a mais? '))\nprint('Progressão finalizada com {} termos mostrados.'.format(total))\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6589861512184143,
"alphanum_fraction": 0.6774193644523621,
"avg_line_length": 30,
"blob_id": "f3878b3017da882a8e838006f6ed8c21b550b17a",
"content_id": "4b060fb5c9f569d31f1dc87b1695c3bd245e8c19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 7,
"path": "/ex061.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "primeiroTermo = int(input('Digite o valor do primeiro termo: '))\nrazao = int(input('Digite a razão da PA: '))\ncont = 0\nwhile cont < 10:\n print(primeiroTermo)\n primeiroTermo = primeiroTermo + razao\n cont += 1\n"
},
{
"alpha_fraction": 0.7028301954269409,
"alphanum_fraction": 0.7028301954269409,
"avg_line_length": 51,
"blob_id": "9d36b1c0429c4d2acfc0e15ddf34432fe91cf7df",
"content_id": "69ea04a487bce5514f287e23881894d7a639777b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 213,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 4,
"path": "/ex017.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "from math import hypot\nco = float(input('Digite o valor do cateto oposto: '))\nca = float(input('Digite o valor do cateto adjacente: '))\nprint('A hipotenusa dos valores digitados é {}.'.format(hypot(co, ca)))\n\n\n\n\n"
},
{
"alpha_fraction": 0.529411792755127,
"alphanum_fraction": 0.6120826601982117,
"avg_line_length": 47.46154022216797,
"blob_id": "b229db5127f389e37fa0572393491b99d5ea025c",
"content_id": "daf18679eb58b54f58518d6d30bcd448a89886c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 640,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 13,
"path": "/ex042.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "m1 = float(input('Digite a primeira medida (em cm): '))\nm2 = float(input('Digite a segunda medida (em cm): '))\nm3 = float(input('Digite a terceira medida (em cm): '))\nif m2-m3 < m1 < m2 + m3 and m1-m3 < m2 < m1 + m3 and m1-m2 < m3 < m1 + m2:\n print('\\033[7;34;40m Essas medidas formam um triângulo.\\033[m')\n if m1 == m2 and m2 == m3 and m1 == m3:\n print('Esse é um triângulo equilátero.')\n elif m1 != m2 and m2 != m3 and m1 != m3:\n print('Esse é um triângulo escaleno.')\n else:\n print('Esse é um triângulo isósceles.')\nelse:\n print('\\033[7;31;40m Essas medidas não formam um triângulo.\\033[m')"
},
{
"alpha_fraction": 0.6541849970817566,
"alphanum_fraction": 0.6629955768585205,
"avg_line_length": 46.842105865478516,
"blob_id": "10fb6c3f340888b366a3e044edde45777fc8681d",
"content_id": "9d033f462026dc514e45cb35f30cc452075c8002",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 913,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 19,
"path": "/ex039.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "import datetime\nsexo = str(input('Digite F para sexo feminino ou M para sexo masculino: ')).strip().capitalize()\nif sexo == 'F':\n print('Você está dispensada no alistamento militar obrigatório.')\nelse:\n data_nascimento = int(input('Digite seu ano de nascimento: '))\n ano_atual = datetime.date.today().year\n diferenca = ano_atual - data_nascimento\n print('Quem nasceu em {} tem {} anos em {}.'.format(data_nascimento, diferenca, ano_atual))\n falta = data_nascimento + 18\n if diferenca < 18:\n pendente = abs(ano_atual - falta)\n print('Ainda faltam {} anos para o alistamento.'.format(pendente))\n elif diferenca > 18:\n passou = ano_atual - falta\n ano_alistamento = data_nascimento + 18\n print('Já se passaram {} anos do seu alistamento. Seu alistamento foi em {}.'.format(passou, ano_alistamento))\n else:\n print('Está na hora de se alistar.')"
},
{
"alpha_fraction": 0.5734463334083557,
"alphanum_fraction": 0.5946327447891235,
"avg_line_length": 29.826086044311523,
"blob_id": "0eebea212d25f6fae99c801626c33445adfcfda1",
"content_id": "c0e2f6a54dd2a9575a2a44e8c375592bcf100371",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 716,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 23,
"path": "/ex067.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "'''Faça um programa que mostra a tabuada de vários números, um de cada vez, para cada valor digitado\npelo usuário. O programa será interrompido quando o número solicitado for negativo.'''\n\nnumero = cont = 0\nwhile True:\n numero = int(input('Digite o número da tabuada que você quer ver: '))\n if numero < 0:\n break\n cont = 0\n while cont <= 10:\n print(f'{numero} x {cont:2} = {numero * cont}')\n cont += 1\nprint('FIM!')\n\n'''while True:\n n = int(input('Quer ver a tabuada de qual valor? '))\n print('-' * 30)\n if n < 0:\n break\n for c in range (1, 11):\n print(f'{n} x {c} = {n*c}')\n print('-' * 30)\nprint('PROGRAMA TABUADA ENCERRADO. VOLTE SEMPRE! ')'''"
},
{
"alpha_fraction": 0.6775147914886475,
"alphanum_fraction": 0.6819526553153992,
"avg_line_length": 74.11111450195312,
"blob_id": "528927e222e56f536bb0f74f8c05ed052c13d990",
"content_id": "7d683115670713cd35be162c65238f96a55275d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 691,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 9,
"path": "/ex026.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "\"\"\"frase = str(input('Digite uma frase: ')).strip()\nprint('O número de letras A nessa frase é {}.'.format(frase.lower().count('a')))\nprint('A letra A aparece pela primeira vez na posição {}.'.format(frase.lower().find('a')))\nprint('A letra A aparece pela última vez na posição {}.'.format(frase.lower().rfind('a')))\"\"\"\n\nfrase =str(input('Digite uma frase: ')).upper().strip()\nprint('O número de letras A nessa frase é {}. '.format(frase.count('A')))\nprint('A letra A aparece pela primeira vez na posição {}.'.format(frase.find('A')+1)) #somar um para que o usuário considere o início em 1\nprint('A letra A aparece pela primeira vez na posição {}.'.format(frase.rfind('A')+1))\n"
},
{
"alpha_fraction": 0.6690140962600708,
"alphanum_fraction": 0.6866196990013123,
"avg_line_length": 56,
"blob_id": "b9758e92030c71ca343d3c7dbed69cdd5664162e",
"content_id": "4f8e62bfb31c65390f779cdd676f8cc38722c07d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 5,
"path": "/ex029.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "velocidade = int(input('Digite qual a velocidade do carro neste momento (em km/h): '))\nprint('A velocidade é {}km/h, certo? '.format(velocidade))\nif velocidade > 80:\n print('Você excedeu a velocidade, e a sua multa será no valor de R${}. '.format((velocidade - 80)*7))\nprint('Ok!')"
},
{
"alpha_fraction": 0.4864864945411682,
"alphanum_fraction": 0.5405405163764954,
"avg_line_length": 25.285715103149414,
"blob_id": "d700b573f170b0bdaf8a7ed69780c46606087ba4",
"content_id": "4ab2cbef5468d91014a3d9613e26da4d2009f0e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 187,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 7,
"path": "/ex048.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "soma = 0\ncontador = 0\nfor c in range (1, 500, 2):\n if c % 3 == 0:\n soma += c\n contador += 1\nprint('A soma no intervalo de {} números é de {}.'.format(contador,soma));\n\n"
},
{
"alpha_fraction": 0.7043010592460632,
"alphanum_fraction": 0.7168458700180054,
"avg_line_length": 60.88888931274414,
"blob_id": "e3cc8f8941ab5bc182e73707486f0b64a8e664a9",
"content_id": "f2f1378cfc9ae4b033e556c079d1d57997af17c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 570,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 9,
"path": "/ex036.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "print('-----SIMULADOR DE EMPRÉSTIMO IMOBILIÁRIO-----')\nvalor_casa = float(input('Qual o valor do imóvel? R$'))\nsalario = float(input('Qual o salário do comprador? R$'))\ntempo_pagamento = int(input('Em quantos anos deseja pagar? '))\ntempo_mensal = tempo_pagamento*12\nif valor_casa/tempo_mensal <= 0.3 * salario:\n print('O seu empréstimo está aprovado e o valor da parcela será de R${:.2f}'.format(valor_casa/tempo_mensal))\nelse:\n print('O valor da prestação excede sua capacidade de pagamento, que é de 30% do seu salário. Seu empréstimo foi negado.')\n\n"
},
{
"alpha_fraction": 0.7049180269241333,
"alphanum_fraction": 0.7166276574134827,
"avg_line_length": 34.66666793823242,
"blob_id": "1ed58c4f849a136d6e51efacde4d17de2347fe6c",
"content_id": "1ad69293fac7d8706ce2ebecada279dd7338bb37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 12,
"path": "/ex028.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "print('Jogo de adivinhação')\nfrom random import randint\nfrom time import sleep\nnumero = int(input('Digite um número entre 0 e 5: '))\nprint('Estou lendo o número digitado...')\nsleep(4)\nsorteio = randint(0,5)\nif numero == sorteio:\n print('Parabéns, o número {} foi selecionado pelo computador!'.format(numero))\nelse:\n print('Infelizmente o número selecionado foi {} e não {}.'.format(sorteio, numero))\nprint('Fim do jogo!')"
},
{
"alpha_fraction": 0.5078533887863159,
"alphanum_fraction": 0.5392670035362244,
"avg_line_length": 20.11111068725586,
"blob_id": "a6568bd270380c61aa012f49ae4631a1997156fe",
"content_id": "74df1b79edf7a63e8bdde19605971c7b77bc6426",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 195,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 9,
"path": "/ex052.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "cont = 0\nnumero = int(input('Digite um número: '))\nfor c in range (1, numero+1):\n if numero % c == 0:\n cont += 1\nif cont > 2:\n print('Não é primo.')\nelse:\n print('É primo.')\n\n"
},
{
"alpha_fraction": 0.575596809387207,
"alphanum_fraction": 0.6074270606040955,
"avg_line_length": 46.125,
"blob_id": "0be395f4337e9639ef6f640afa1a31c2448e2558",
"content_id": "d3b5a64d9e0415c431ed327cb15e48fef0a98743",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 8,
"path": "/ex006.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "number = int(input('Digite um número: '))\ndou = number * 2\ntri = number * 3\nqua = number **(1/2)\nprint('O dobro do valor digitado é {}, o triplo é {} e a raiz quadrada é {:.3f}.'.format(dou, tri, qua))\n\n#print('O dobro do valor digitado é {}, o triplo é {} e a raiz quadrada é {:.3f}.'.format((number * 2), (number * 3), (number ** (1/2))))\n#raiz quadrada (pow(number, (1/2)))\n"
},
{
"alpha_fraction": 0.642241358757019,
"alphanum_fraction": 0.6681034564971924,
"avg_line_length": 57.25,
"blob_id": "fc0a4af9f7519305b7141d019980067814d12fa5",
"content_id": "65f6e6b6a4a75a97bbf8a1c013b46f3db6739b41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 235,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 4,
"path": "/ex015.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "dias = int(input('Quantos dias de aluguel? '))\nkm = float(input('Quantos quilômetros rodados? '))\nprice = dias * 60 + km * 0.15\nprint('O valor do aluguel de {} dias, rodando {} quilômetros será de R${:.2f}.'.format(dias, km, price))"
},
{
"alpha_fraction": 0.5803278684616089,
"alphanum_fraction": 0.6196721196174622,
"avg_line_length": 37.25,
"blob_id": "098b502aa00d77f2ade95c7439f079bf5868f433",
"content_id": "1ff8eb81238847695ed84125444f3b11803b9100",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 8,
"path": "/ex038.py",
"repo_name": "alinesc/python3",
"src_encoding": "UTF-8",
"text": "num1 = int(input('Digite um número: '))\nnum2 = int(input('Digite outro número: '))\nif num1 > num2:\n print('O número {} é maior que {}.'.format(num1,num2))\nelif num2 > num1:\n print('O número {} é maior que {}.'.format(num2, num1))\nelse:\n print ('Os números {} e {} são iguais.'.format(num1, num2))"
}
] | 66 |
Duskamo/goopies_gui | https://github.com/Duskamo/goopies_gui | b20b9e3614c49cb43a3a752c357b6a26fd0cd647 | 9a02d8dbf8fa829b28670b843f38f6a2e86e6f02 | fa2a12d397b101d779c58582491cb5519feb115a | refs/heads/master | 2021-04-16T04:19:11.005332 | 2020-03-26T02:12:03 | 2020-03-26T02:12:03 | 249,327,380 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6677713394165039,
"alphanum_fraction": 0.6826843619346619,
"avg_line_length": 28.414634704589844,
"blob_id": "8e067e8b0e39b62e27b7444ad07e094b515aa9f6",
"content_id": "a6aa7942be9d8181d6c80bc41bd8f28e2e580b69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1207,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 41,
"path": "/listeners/GoopieConsumerListener.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nimport threading\nimport time\n\nclass GoopieConsumerListener(threading.Thread):\n\tdef __init__(self,goopies,pellets,pelletConsumedQueue):\n\t\tsuper(GoopieConsumerListener, self).__init__()\n\t\tself.goopies = goopies\n\t\tself.pellets = pellets\n\t\tself.pelletConsumedQueue = pelletConsumedQueue\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tfor i in range(len(self.goopies)):\n\t\t\t\t# determine if goopies consumed a pellet or not\n\t\t\t\tif self.goopieConsumedPellet(i):\n\t\t\t\t\tself.goopies[i].health += 20\n\t\t\t\telse:\n\t\t\t\t\t\"\"\n\t\t\t\t\t#self.goopies[i].health -= 1\n\n\t\t\t\t# change goopie state as health increases or decreases\n\t\t\t\tif self.goopies[i].health >= 70:\n\t\t\t\t\tself.goopies[i].color = 'Blue'\n\t\t\t\telif self.goopies[i].health >= 30 and self.goopies[i].health < 70:\n\t\t\t\t\tself.goopies[i].color = 'Yellow'\n\t\t\t\telif self.goopies[i].health < 30:\n\t\t\t\t\tself.goopies[i].color = 'Red'\n\n\t\t\t\t#print(i, self.goopies[i].health)\n\n\t\t\ttime.sleep(0.25)\n\n\t\n\tdef goopieConsumedPellet(self,i):\n\t\tisPelletConsumed = False\n\t\tfor j in range(len(self.pellets)):\n\t\t\tif (abs(self.goopies[i].x - self.pellets[j].x) < 20) and (abs(self.goopies[i].y - self.pellets[j].y) < 20):\n\t\t\t\tisPelletConsumed = True\n\t\t\t\tself.pelletConsumedQueue.put(j)\n\n\t\treturn isPelletConsumed\n"
},
{
"alpha_fraction": 0.6926407217979431,
"alphanum_fraction": 0.7056276798248291,
"avg_line_length": 24.66666603088379,
"blob_id": "21af90f1f878568c76a73e99ef428035128dcc3a",
"content_id": "009d2ee3e8cc99e56a8fff2d1b27f2a4509e0135",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 231,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 9,
"path": "/Config.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nclass Config:\n\t# Population Config\n\tGOOPIE_POPULATION = 1\n\tZAPPER_POPULATION = 5\n\tPELLET_POPULATION = 2\n\n\t# Movement Config\n\tZAPPER_MOVEMENT = \"None\" # None | Random | Nearest\n\tGOOPIE_MOVEMENT = \"Fluid\" # None | Cardinal | Fluid"
},
{
"alpha_fraction": 0.6873290538787842,
"alphanum_fraction": 0.7000911831855774,
"avg_line_length": 20.096153259277344,
"blob_id": "581ec371f4dd10cf2492de916412853ad6c6e4a5",
"content_id": "fdcd24742dad231c7e5fb0778b98be5d2f68704c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1097,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 52,
"path": "/models/Zapper.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nimport random\nimport math\nfrom libs.graphics import *\n\nfrom managers.ZapperUpdateManager import *\n\nfrom Config import *\n\nclass Zapper:\n\tdef __init__(self,win,x,y):\n\t\tself.win = win\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.radius = 50\n\n\t\tself.updateManager = ZapperUpdateManager(self)\n\t\tself.speed = 0.1\n\n\t\tself.initState()\n\n\n\tdef initState(self):\n\t\tself.body = Circle(Point(self.x,self.y),self.radius)\n\t\tself.body.setWidth(10)\n\t\tself.body.setOutline('Cyan')\n\n\t\tself.center = Rectangle(Point(self.x-20,self.y-20),Point(self.x+20,self.y+20))\n\t\tself.center.setFill('Cyan')\n\n\tdef draw(self):\n\t\tself.body.draw(self.win)\n\t\tself.center.draw(self.win)\n\n\tdef undraw(self):\n\t\tself.body.undraw()\n\t\tself.center.undraw()\n\n\tdef move(self,dx,dy):\n\t\tself.x = self.x + dx\n\t\tself.y = self.y + dy\n\n\t\tself.body.move(dx, dy)\n\t\tself.center.move(dx, dy)\n\n\tdef update(self):\n\t\t# move zapper randomly\n\t\tif Config.ZAPPER_MOVEMENT == \"Random\":\n\t\t\tself.updateManager.zapperMoveRandom()\n\n\t\t# move zapper with knowledge of goopies whereabouts\n\t\telif Config.ZAPPER_MOVEMENT == \"Nearest\":\n\t\t\tself.updateManager.zapperMoveNearestGoopie()"
},
{
"alpha_fraction": 0.5738916397094727,
"alphanum_fraction": 0.5837438702583313,
"avg_line_length": 30.230770111083984,
"blob_id": "4effefd24aadab4209db25e3a101ce446c2044bf",
"content_id": "c9aa5369429210c8b23fa370a46b94bb56d8144a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 406,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 13,
"path": "/data/TempGoopieThrusterData.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nclass TempGoopieThrusterData:\n def __init__(self):\n self.thrusterData = []\n\n self.addData()\n\n def addData(self):\n self.thrusterData.append({\"thruster\": ['SW'], \"time\": \"5\"})\n self.thrusterData.append({\"thruster\": ['SE'], \"time\": \"5\"})\n self.thrusterData.append({\"thruster\":['SW','SE'], \"time\":\"10\"})\n\n def getThrusterData(self):\n return self.thrusterData"
},
{
"alpha_fraction": 0.6449309587478638,
"alphanum_fraction": 0.646358847618103,
"avg_line_length": 29.463768005371094,
"blob_id": "5f6ab1546a36cbf60a7408075b174f5e116c9ac8",
"content_id": "e419d3df629504a132059054450cb4dcb6bbadd5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2101,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 69,
"path": "/listeners/KeyboardListener.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "import time\nfrom pynput import keyboard\nfrom functools import partial\n\nfrom Config import *\n\nclass KeyboardListener:\n\tdef __init__(self,keyboardQueue):\n\t\tself.listener = None\n\t\tself.keyboardQueue = keyboardQueue\n\n\t\tself.current = set()\n\n\tdef join(self):\n\t\t# Collect events until released\n\t\twith keyboard.Listener(\n\t\t\ton_press=self.on_press,\n\t\t\ton_release=self.on_release) as listener:\n\t\t\tlistener.join()\n\n\tdef start(self):\n\t\t# ...or, in a non-blocking fashion:\n\t\tself.listener = keyboard.Listener(\n\t\t on_press=partial(self.on_press))\n\t\tself.listener.start()\n\n\tdef on_press(self,key):\n\t\tif Config.GOOPIE_MOVEMENT == \"Cardinal\":\n\t\t\ttry:\n\t\t\t\tif key == keyboard.Key.up:\n\t\t\t\t\tself.keyboardQueue.put(\"Up\")\n\t\t\t\telif key == keyboard.Key.down:\n\t\t\t\t\tself.keyboardQueue.put(\"Down\")\n\t\t\t\telif key == keyboard.Key.left:\n\t\t\t\t\tself.keyboardQueue.put(\"Left\")\n\t\t\t\telif key == keyboard.Key.right:\n\t\t\t\t\tself.keyboardQueue.put(\"Right\")\n\n\t\t\texcept AttributeError:\n\t\t\t\tprint('special key {0} pressed'.format(key))\n\t\telif Config.GOOPIE_MOVEMENT == \"Fluid\":\n\t\t\ttry:\n\t\t\t\tif key == keyboard.Key.up:\n\t\t\t\t\tself.keyboardQueue.put({'thruster':['SW','SE'], 'status':'On'})\n\t\t\t\telif key == keyboard.Key.down:\n\t\t\t\t\tself.keyboardQueue.put({'thruster':['NW','NE'], 'status':'On'})\n\t\t\t\telif key == keyboard.Key.left:\n\t\t\t\t\tself.keyboardQueue.put({'thruster':['NE'], 'status':'On'})\n\t\t\t\telif key == keyboard.Key.right:\n\t\t\t\t\tself.keyboardQueue.put({'thruster':['NW'], 'status':'On'})\n\n\t\t\texcept AttributeError:\n\t\t\t\tprint('special key {0} pressed'.format(key))\n\t\"\"\"\n\tdef on_release(self, key):\n\t\tif Config.GOOPIE_MOVEMENT == \"Fluid\":\n\t\t\ttry:\n\t\t\t\tif key == keyboard.Key.up:\n\t\t\t\t\tself.keyboardQueue.put({'thruster': ['SW', 'SE'], 'status': 'Off'})\n\t\t\t\telif key == keyboard.Key.down:\n\t\t\t\t\tself.keyboardQueue.put({'thruster': ['NW', 'NE'], 'status': 'Off'})\n\t\t\t\telif key == keyboard.Key.left:\n\t\t\t\t\tself.keyboardQueue.put({'thruster': ['NE'], 'status': 'Off'})\n\t\t\t\telif key == keyboard.Key.right:\n\t\t\t\t\tself.keyboardQueue.put({'thruster': ['NW'], 'status': 'Off'})\n\n\t\t\texcept AttributeError:\n\t\t\t\tprint('special key {0} pressed'.format(key))\n\t\"\"\""
},
{
"alpha_fraction": 0.7216748595237732,
"alphanum_fraction": 0.7300492525100708,
"avg_line_length": 24.683544158935547,
"blob_id": "6d7f0ccb7cb28370f457ed2a00b5c7b31a0ed6a9",
"content_id": "3a0fd4bac36df40e8ee3ef50496f788095bfdfe3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2030,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 79,
"path": "/main.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nimport time\nfrom libs.graphics import *\nfrom queue import Queue\n\nfrom models.Tank import *\nfrom models.Zapper import *\nfrom models.Goopie import *\nfrom models.Pellet import *\n\nfrom helpers.StateCreator import *\nfrom listeners.GoopieConsumerListener import *\nfrom listeners.KeyboardListener import *\n\nclass main():\n\tdef __init__(self):\n\t\tself.initialize()\n\n\tdef initialize(self):\n\t\t# Setup Background, game objects, and initial states\n\t\tself.win = GraphWin('Goopies', 1200, 800)\n\t\tself.win.setBackground('black')\n\n\t\tself.tank = Tank(self.win)\n\t\tself.tank.draw()\n\n\t\tself.stateCreator = StateCreator(self.win)\n\t\tself.stateCreator.createGame()\n\t\tself.goopies = self.stateCreator.getGoopies()\n\t\tself.pellets = self.stateCreator.getPellets()\n\t\tself.zappers = self.stateCreator.getZappers()\n\n\t\tself.isRunning = True\n\n\t\t# Setup Queues, Listeners, and off threads\n\t\tself.keyboardQueue = Queue(maxsize=0)\n\t\tself.pelletConsumedQueue = Queue(maxsize=0)\n\n\t\tself.goopies[0].pellets = self.pellets\n\t\tself.goopies[0].keyboardQueue = self.keyboardQueue # TEMP\n\t\tself.goopies[0].pelletConsumedQueue = self.pelletConsumedQueue\n\n\t\tgoopieConsumerListener = GoopieConsumerListener(self.goopies,self.pellets,self.pelletConsumedQueue)\n\t\tgoopieConsumerListener.start()\n\t\tkeyboardListener = KeyboardListener(self.keyboardQueue)\n\t\tkeyboardListener.start()\n\n\t\t# Setup Game Loop\n\t\tself.run()\n\n\t\t# Pause and Close\n\t\tself.win.getMouse() \n\t\tself.win.close() \n\n\tdef run(self):\t\n\t\t# Game Loop\n\t\twhile self.isRunning:\n\t\t\t# Process Events - Process inputs and other things\n\t\t\tself.processEvents()\n\n\t\t\t# Update - Update all objects that needs updating, ex position changes, physics\n\t\t\tfor i in range(len(self.goopies)):\n\t\t\t\tself.goopies[i].update()\n\n\t\t\tfor i in range(len(self.zappers)):\n\t\t\t\tself.zappers[i].goopies = self.goopies\n\t\t\t\tself.zappers[i].update()\n\n\t\t\t# Draw - Render things on screen\n\n\t\t\t# Pause thread for framerate\n\t\t\ttime.sleep(0.0017)\n\n\tdef processEvents(self):\n\t\t# Check if game is complete or not\n\t\t\"\"\n\n\nif __name__ == \"__main__\":\n\tmain = main()\n"
},
{
"alpha_fraction": 0.6462093591690063,
"alphanum_fraction": 0.6859205961227417,
"avg_line_length": 17.399999618530273,
"blob_id": "403c2035b05caa638dedec0d440fd8a5059ab3a5",
"content_id": "e5d0a09207df6fc52ff7b11fda753fb78894cc3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 15,
"path": "/models/Tank.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nfrom libs.graphics import *\n\nclass Tank:\n\tdef __init__(self,win):\n\t\tself.win = win\n\n\t\tself.initState()\n\n\tdef initState(self):\n\t\tself.border = Circle(Point(600,400),400)\n\t\tself.border.setWidth(10)\n\t\tself.border.setOutline('Cyan')\n\n\tdef draw(self):\n\t\tself.border.draw(self.win)\n"
},
{
"alpha_fraction": 0.7041457295417786,
"alphanum_fraction": 0.7192211151123047,
"avg_line_length": 29.605770111083984,
"blob_id": "0a8fbe4214a2e430f494b3fb4aa1203246b718b8",
"content_id": "7ca31ff3fdd35edcf6b1cc2a67fa3550e8cb9c2c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3184,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 104,
"path": "/models/Goopie.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nfrom libs.graphics import *\n\nfrom Config import *\nfrom managers.GoopieUpdateManager import *\n\nclass Goopie:\n\tdef __init__(self,win,x,y):\n\t\tself.win = win\n\t\tself.x = x\n\t\tself.y = y \n\t\tself.radius = 15\n\n\t\tself.updateManager = GoopieUpdateManager(self)\n\t\tself.health = 100\n\t\tself.color = 'blue'\n\n\t\tself.initState()\n\n\tdef initState(self):\n\t\tself.body = Circle(Point(self.x,self.y),self.radius)\n\t\tself.body.setWidth(1)\n\t\tself.body.setOutline(self.color)\n\n\t\tself.gland = Oval(Point(self.x-5,self.y-13),Point(self.x+5,self.y+13))\n\t\tself.gland.setWidth(1)\n\t\tself.gland.setFill('purple')\n\n\t\tself.sensorNorth = Line(Point(self.x,self.y-20),Point(self.x,self.y-15))\n\t\tself.sensorNorth.setFill('red')\n\t\tself.sensorSouth = Line(Point(self.x,self.y+20),Point(self.x,self.y+15))\n\t\tself.sensorSouth.setFill('red')\n\t\tself.sensorWest = Line(Point(self.x-20,self.y),Point(self.x-15,self.y))\n\t\tself.sensorWest.setFill('red')\n\t\tself.sensorEast = Line(Point(self.x+20,self.y),Point(self.x+15,self.y))\n\t\tself.sensorEast.setFill('red')\n\n\t\tself.thrusterNE = Line(Point(self.x,self.y-15),Point(self.x+15,self.y))\n\t\tself.thrusterNE.setFill('light grey')\n\t\tself.thrusterNW = Line(Point(self.x,self.y-15),Point(self.x-15,self.y))\n\t\tself.thrusterNW.setFill('light grey')\n\t\tself.thrusterSE = Line(Point(self.x, self.y + 15), Point(self.x + 15, self.y))\n\t\tself.thrusterSE.setFill('light grey')\n\t\tself.thrusterSW = Line(Point(self.x,self.y+15),Point(self.x-15,self.y))\n\t\tself.thrusterSW.setFill('light grey')\t\n\n\tdef draw(self):\n\t\tself.body.draw(self.win)\n\t\tself.gland.draw(self.win)\n\t\tself.sensorNorth.draw(self.win)\n\t\tself.sensorSouth.draw(self.win)\n\t\tself.sensorWest.draw(self.win)\n\t\tself.sensorEast.draw(self.win)\n\t\tself.thrusterNE.draw(self.win)\n\t\tself.thrusterSE.draw(self.win)\n\t\tself.thrusterNW.draw(self.win)\n\t\tself.thrusterSW.draw(self.win)\n\n\tdef undraw(self):\n\t\tself.body.undraw()\n\t\tself.gland.undraw()\n\t\tself.sensorNorth.undraw()\n\t\tself.sensorSouth.undraw()\n\t\tself.sensorWest.undraw()\n\t\tself.sensorEast.undraw()\n\t\tself.thrusterNE.undraw()\n\t\tself.thrusterSE.undraw()\n\t\tself.thrusterNW.undraw()\n\t\tself.thrusterSW.undraw()\n\n\tdef move(self,dx,dy):\n\t\tself.x += dx\n\t\tself.y += dy\t\t\n\n\t\tself.body.move(dx,dy)\n\t\tself.gland.move(dx,dy)\n\t\tself.sensorNorth.move(dx,dy)\n\t\tself.sensorSouth.move(dx,dy)\n\t\tself.sensorWest.move(dx,dy)\n\t\tself.sensorEast.move(dx,dy)\n\t\tself.thrusterNE.move(dx,dy)\n\t\tself.thrusterSE.move(dx,dy)\n\t\tself.thrusterNW.move(dx,dy)\n\t\tself.thrusterSW.move(dx,dy)\n\t\t\n\tdef update(self):\n\t\t# Update Skin of goopie by its health\n\t\tif self.health > 0:\n\t\t\tself.updateManager.updateSkin()\n\n\t\t# Turn goopie to corpse if health drops to 0\n\t\tif self.health == 0:\n\t\t\tself.updateManager.goopieCorpse()\n\n\t\t# Move goopie on keyboard input in basic cardinal direction pattern\n\t\tif not self.keyboardQueue.empty() and Config.GOOPIE_MOVEMENT == \"Cardinal\":\n\t\t\tself.updateManager.goopieKeyboardInput()\n\n\t\t# Move goopie on keyboard input in fluid direction pattern\n\t\tif not self.keyboardQueue.empty() and Config.GOOPIE_MOVEMENT == \"Fluid\":\n\t\t\tself.updateManager.goopieKeyboardInputFluid()\n\n\t\t# Clear pellet from screen when collided\n\t\tif not self.pelletConsumedQueue.empty():\n\t\t\tself.updateManager.clearPelletOnContact()\n"
},
{
"alpha_fraction": 0.6468468308448792,
"alphanum_fraction": 0.661261260509491,
"avg_line_length": 18.10344886779785,
"blob_id": "e042f51b4555cc5d026623e469debaf25396667d",
"content_id": "13cc003782bce944da85aa29853aa669025481b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 555,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 29,
"path": "/models/Pellet.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nfrom libs.graphics import *\n\nclass Pellet:\n\tdef __init__(self,win,x,y):\n\t\tself.win = win\n\t\tself.x = x\n\t\tself.y = y \n\t\tself.radius = 10\n\n\t\tself.initState()\n\n\n\tdef initState(self):\n\t\tself.body = Circle(Point(self.x,self.y),self.radius)\n\t\tself.body.setWidth(1)\n\t\tself.body.setFill('yellow')\n\n\t\tself.core = Rectangle(Point(self.x-5,self.y-5),Point(self.x+5,self.y+5))\n\t\tself.core.setWidth(1)\n\t\tself.core.setFill('black')\n\t\t\n\n\tdef draw(self):\n\t\tself.body.draw(self.win)\n\t\tself.core.draw(self.win)\n\n\tdef undraw(self):\n\t\tself.body.undraw()\n\t\tself.core.undraw()\n"
},
{
"alpha_fraction": 0.6674584150314331,
"alphanum_fraction": 0.681235134601593,
"avg_line_length": 25.91025733947754,
"blob_id": "444dd033c40f60591a4c612e9bb06e346f95ebe0",
"content_id": "45a17729c05be2895cebd1ea8014b045f02b7f36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2105,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 78,
"path": "/helpers/StateCreator.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nimport random\nfrom queue import Queue\n\nfrom Config import *\n\nfrom models.Tank import *\nfrom models.Zapper import *\nfrom models.Goopie import *\nfrom models.Pellet import *\n\nclass StateCreator:\n\tdef __init__(self,win):\n\t\tself.win = win\n\n\tdef createGame(self):\n\t\t# make sure objects dont touch\n\t\tobjectsDontTouch = False\n\t\twhile not objectsDontTouch:\n\t\t\t# init game object lists\n\t\t\tself.zappers = []\n\t\t\tself.goopies = []\n\t\t\tself.pellets = []\n\n\t\t\t# generate random coordinates to place objects in tank\n\t\t\trandCoords = []\n\t\t\tfor i in range(Config.GOOPIE_POPULATION + Config.ZAPPER_POPULATION + Config.PELLET_POPULATION):\n\t\t\t\trandCoords.append({'x':random.randint(350,850), 'y':random.randint(150,650)})\n\n\t\t\t# check to see if all objects are separate\n\t\t\tobjCount = 0 \n\t\t\tfor i in range(len(randCoords)):\n\t\t\t\tfor j in range(len(randCoords)):\n\t\t\t\t\tif ((abs(randCoords[i]['x'] - randCoords[j]['x']) < 125) and (abs(randCoords[i]['y'] - randCoords[j]['y']) < 125)):\n\t\t\t\t\t\tobjCount += 1\n\n\t\t\tif objCount == len(randCoords):\n\t\t\t\tobjectsDontTouch = True\n\t\t\t\n\n\t\t# place objects in tank \n\t\tfor i in range(Config.GOOPIE_POPULATION):\n\t\t\tself.goopies.append(Goopie(self.win,randCoords[0]['x'],randCoords[0]['y']))\n\t\t\trandCoords.pop(0)\n\n\t\tfor i in range(Config.ZAPPER_POPULATION):\n\t\t\tself.zappers.append(Zapper(self.win,randCoords[0]['x'],randCoords[0]['y']))\n\t\t\trandCoords.pop(0)\n\n\t\tfor i in range(Config.PELLET_POPULATION):\n\t\t\tself.pellets.append(Pellet(self.win,randCoords[0]['x'],randCoords[0]['y']))\n\t\t\trandCoords.pop(0)\n\t\t\t\t\n\t\t\t\t\n\t\t# print objects to tank\n\t\tfor i in range(len(self.zappers)):\n\t\t\tself.zappers[i].draw()\n\n\t\tfor i in range(len(self.goopies)):\n\t\t\tself.goopies[i].draw()\n\n\t\tfor i in range(len(self.pellets)):\n\t\t\tself.pellets[i].draw()\n\n\t\t# let goopies know about pellets, and zappers know about goopies\n\t\tfor i in range(len(self.zappers)):\n\t\t\tself.zappers[i].goopies = self.goopies\n\n\t\tfor i in range(len(self.goopies)):\n\t\t\tself.goopies[i].pellets = self.pellets\n\n\tdef getZappers(self):\n\t\treturn self.zappers\n\n\tdef getGoopies(self):\n\t\treturn self.goopies\n\n\tdef getPellets(self):\n\t\treturn self.pellets\n\t\t\n\t\n"
},
{
"alpha_fraction": 0.5991014838218689,
"alphanum_fraction": 0.6057082414627075,
"avg_line_length": 43,
"blob_id": "066f206904c207d7425081ee6e983c986974df1b",
"content_id": "ad2a2562f176b9b1fabd9f6949b33e2ddbc48369",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3784,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 86,
"path": "/managers/GoopieUpdateManager.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nfrom libs.graphics import *\n\nfrom models.Corpse import *\n\nclass GoopieUpdateManager:\n def __init__(self,goopie):\n self.goopie = goopie\n\n def updateSkin(self):\n self.goopie.body.undraw()\n self.goopie.body = Circle(Point(self.goopie.x, self.goopie.y), self.goopie.radius)\n self.goopie.body.setWidth(1)\n self.goopie.body.setOutline(self.goopie.color)\n self.goopie.body.draw(self.goopie.win)\n\n self.goopie.thrusterSE.setFill('light grey')\n self.goopie.thrusterSW.setFill('light grey')\n self.goopie.thrusterNE.setFill('light grey')\n self.goopie.thrusterNW.setFill('light grey')\n\n def goopieCorpse(self):\n self.goopie.undraw()\n corpse = Corpse(self.goopie.win, self.goopie.x, self.goopie.y)\n corpse.draw()\n self.goopie = None\n\n def goopieKeyboardInput(self):\n if self.goopie.keyboardQueue.get() == \"Up\":\n self.goopie.move(0, -3)\n elif self.goopie.keyboardQueue.get() == \"Down\":\n self.goopie.move(0, 5)\n elif self.goopie.keyboardQueue.get() == \"Left\":\n self.goopie.move(-6, 0)\n elif self.goopie.keyboardQueue.get() == \"Right\":\n self.goopie.move(6, 0)\n\n self.goopie.keyboardQueue.queue.clear()\n\n def goopieKeyboardInputFluid(self):\n #print(self.goopie.keyboardQueue.get()['thruster'],self.goopie.keyboardQueue.get()['status'])\n\n # When thrusters are activated\n if self.goopie.keyboardQueue.get()['thruster'] == ['SW','SE'] and self.goopie.keyboardQueue.get()['status'] == \"On\":\n self.goopie.thrusterSE.setFill('red')\n self.goopie.thrusterSW.setFill('red')\n self.goopie.move(0, -3)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NW','NE'] and self.goopie.keyboardQueue.get()['status'] == \"On\":\n self.goopie.thrusterNE.setFill('red')\n self.goopie.thrusterNW.setFill('red')\n self.goopie.move(0, 5)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NE'] and self.goopie.keyboardQueue.get()['status'] == \"On\":\n self.goopie.thrusterNE.setFill('red')\n self.goopie.move(-6, 0)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NW'] and self.goopie.keyboardQueue.get()['status'] == \"On\":\n self.goopie.thrusterNW.setFill('red')\n self.goopie.move(6, 0)\n\n \"\"\"\n # When thrusters are deactivated\n if self.goopie.keyboardQueue.get()['thruster'] == ['SW', 'SE'] and self.goopie.keyboardQueue.get()[\n 'status'] == \"Off\":\n print('dsfsgsdgsdg')\n self.goopie.thrusterSE.setFill('light grey')\n self.goopie.thrusterSW.setFill('light grey')\n self.goopie.move(0, -3)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NW', 'NE'] and self.goopie.keyboardQueue.get()[\n 'status'] == \"Off\":\n self.goopie.thrusterNE.setFill('light grey')\n self.goopie.thrusterNW.setFill('light grey')\n self.goopie.move(0, 5)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NE'] and self.goopie.keyboardQueue.get()[\n 'status'] == \"Off\":\n self.goopie.thrusterNE.setFill('light grey')\n self.goopie.move(-6, 0)\n elif self.goopie.keyboardQueue.get()['thruster'] == ['NW'] and self.goopie.keyboardQueue.get()[\n 'status'] == \"Off\":\n self.goopie.thrusterNW.setFill('light grey')\n self.goopie.move(6, 0)\n \"\"\"\n\n self.goopie.keyboardQueue.queue.clear()\n\n def clearPelletOnContact(self):\n removedPellet = self.goopie.pelletConsumedQueue.get()\n self.goopie.pellets[removedPellet].undraw()\n self.goopie.pellets.pop(removedPellet)"
},
{
"alpha_fraction": 0.6113256216049194,
"alphanum_fraction": 0.6284856200218201,
"avg_line_length": 62,
"blob_id": "f155c93cb8f66762f2b8fdfe25ee53a6e1044165",
"content_id": "9202139385f9d33edc2c1d86bb5e3caa87fb5827",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2331,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 37,
"path": "/managers/ZapperUpdateManager.py",
"repo_name": "Duskamo/goopies_gui",
"src_encoding": "UTF-8",
"text": "\nimport random\nimport math\n\nclass ZapperUpdateManager:\n def __init__(self,zapper):\n self.zapper = zapper\n\n def zapperMoveRandom(self):\n x = random.randint(-1, 1)\n y = random.randint(-1, 1)\n self.zapper.move(x * self.zapper.speed, y * self.zapper.speed)\n\n def zapperMoveNearestGoopie(self):\n # 1. sort goopies by closest first\n closestGoopies = []\n for i in range(len(self.zapper.goopies)):\n distance = math.sqrt((self.zapper.goopies[i].x - self.zapper.x) ** 2 + (self.zapper.goopies[i].y - self.zapper.y) ** 2)\n closestGoopies.append({'goopie': self.zapper.goopies[i], 'distance': distance})\n closestGoopies.sort(key=lambda x: x['distance'])\n\n # 2. travel to goopie\n if self.zapper.x < closestGoopies[0]['goopie'].x and self.zapper.y < closestGoopies[0]['goopie'].y: # Move SE\n self.zapper.move(1 * self.zapper.speed, 1 * self.zapper.speed)\n elif self.zapper.x == closestGoopies[0]['goopie'].x and self.zapper.y < closestGoopies[0]['goopie'].y: # Move S\n self.zapper.move(0 * self.zapper.speed, 1 * self.zapper.speed)\n elif self.zapper.x > closestGoopies[0]['goopie'].x and self.zapper.y < closestGoopies[0]['goopie'].y: # Move SW\n self.zapper.move(-1 * self.zapper.speed, 1 * self.zapper.speed)\n elif self.zapper.x > closestGoopies[0]['goopie'].x and self.zapper.y == closestGoopies[0]['goopie'].y: # Move W\n self.zapper.move(-1 * self.zapper.speed, 0 * self.zapper.speed)\n elif self.zapper.x > closestGoopies[0]['goopie'].x and self.zapper.y > closestGoopies[0]['goopie'].y: # Move NW\n self.zapper.move(-1 * self.zapper.speed, -1 * self.zapper.speed)\n elif self.zapper.x == closestGoopies[0]['goopie'].x and self.zapper.y > closestGoopies[0]['goopie'].y: # Move N\n self.zapper.move(0 * self.zapper.speed, -1 * self.zapper.speed)\n elif self.zapper.x < closestGoopies[0]['goopie'].x and self.zapper.y > closestGoopies[0]['goopie'].y: # Move NE\n self.zapper.move(1 * self.zapper.speed, -1 * self.zapper.speed)\n elif self.zapper.x < closestGoopies[0]['goopie'].x and self.zapper.y == closestGoopies[0]['goopie'].y: # Move E\n self.zapper.move(1 * self.zapper.speed, 0 * self.zapper.speed)"
}
] | 12 |
omarryhan/google-auth-library-python | https://github.com/omarryhan/google-auth-library-python | 146383cf8979a80837e5789f17deeb615dce9583 | a10b15e34447a35cedd0f73654b13404999141b5 | 2cbcdef7ee07e5ccc596334dfa893863f715c8f4 | refs/heads/master | 2020-04-04T17:00:40.294082 | 2018-10-05T17:20:33 | 2018-10-05T17:20:33 | 156,102,693 | 1 | 0 | Apache-2.0 | 2018-11-04T16:37:17 | 2018-11-02T03:38:13 | 2018-11-02T18:24:07 | null | [
{
"alpha_fraction": 0.6962582468986511,
"alphanum_fraction": 0.7024945020675659,
"avg_line_length": 33.9487190246582,
"blob_id": "db435c20fdb63ccd17cdc26aefd7d5a44e574b3b",
"content_id": "8581688b5af8363d9cbb796194ec9c276c2f8c66",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 2726,
"license_type": "permissive",
"max_line_length": 209,
"num_lines": 78,
"path": "/CONTRIBUTING.rst",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "Contributing\n============\n\n#. **Please sign one of the contributor license agreements below.**\n#. Fork the repo, develop and test your code changes, add docs.\n#. Make sure that your commit messages clearly describe the changes.\n#. Send a pull request.\n\nHere are some guidelines for hacking on ``google-auth-library-python``.\n\nMaking changes\n--------------\n\nA few notes on making changes to ``google-auth-libary-python``.\n\n- If you've added a new feature or modified an existing feature, be sure to\n add or update any applicable documentation in docstrings and in the\n documentation (in ``docs/``). You can re-generate the reference documentation\n using ``tox -e docgen``.\n\n- The change must work fully on the following CPython versions: 2.7,\n 3.4, and 3.5 across macOS, Linux, and Windows.\n\n- The codebase *must* have 100% test statement coverage after each commit.\n You can test coverage via ``tox -e cover``.\n\nTesting changes\n---------------\n\nTo test your changes, run unit tests with ``tox``::\n\n $ tox -e py27\n $ tox -e py34\n $ tox -e py35\n\nCoding Style\n------------\n\nThis library is PEP8 & Pylint compliant. Our Pylint config is defined at\n``pylintrc`` for package code and ``pylintrc.tests`` for test code. Use\n``tox`` to check for non-compliant code::\n\n $ tox -e lint\n\nDocumentation Coverage and Building HTML Documentation\n------------------------------------------------------\n\nIf you fix a bug, and the bug requires an API or behavior modification, all\ndocumentation in this package which references that API or behavior must be\nchanged to reflect the bug fix, ideally in the same commit that fixes the bug\nor adds the feature.\n\nTo build and review docs use ``tox``::\n\n $ tox -e docs\n\nThe HTML version of the docs will be built in ``docs/_build/html``\n\nVersioning\n----------\n\nThis library follows `Semantic Versioning`_.\n\n.. _Semantic Versioning: http://semver.org/\n\nIt is currently in major version zero (``0.y.z``), which means that anything\nmay change at any time and the public API should not be considered\nstable.\n\nContributor License Agreements\n------------------------------\n\nBefore we can accept your pull requests you'll need to sign a Contributor License Agreement (CLA):\n\n- **If you are an individual writing original source code** and **you own the intellectual property**, then you'll need to sign an `individual CLA <https://developers.google.com/open-source/cla/individual>`__.\n- **If you work for a company that wants to allow you to contribute your work**, then you'll need to sign a `corporate CLA <https://developers.google.com/open-source/cla/corporate>`__.\n\nYou can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests.\n"
},
{
"alpha_fraction": 0.7470427751541138,
"alphanum_fraction": 0.7579618096351624,
"avg_line_length": 32.30303192138672,
"blob_id": "0c08720e0987594b335791c3e427b462f96448cd",
"content_id": "29d509708254f243b55f4fa3b9b440993d599f5d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1099,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 33,
"path": "/.kokoro/system_tests.sh",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\n# Copyright 2017 Google Inc.\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\nset -eo pipefail\n\nexport PATH=${PATH}:${HOME}/gcloud/google-cloud-sdk/bin\n\ncd github/google-auth-library-python\n\n# Unencrypt and extract secrets\nSECRETS_PASSWORD=$(cat \"${KOKORO_GFILE_DIR}/secrets-password.txt\")\n./scripts/decrypt-secrets.sh \"${SECRETS_PASSWORD}\"\n\n# Setup gcloud, this is needed for the App Engine system test.\ngcloud auth activate-service-account --key-file system_tests/data/service_account.json\ngcloud config set project \"${TEST_PROJECT}\"\n\n# Run tests\ntox -e py27-system\ntox -e py36-system\n"
},
{
"alpha_fraction": 0.5753424763679504,
"alphanum_fraction": 0.5753424763679504,
"avg_line_length": 19.85714340209961,
"blob_id": "d450cdc07a183bdd2b038d0182fe3baa752d0ee5",
"content_id": "26b8b4ac4fcd60ab52654d919f5454e912e7857e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 146,
"license_type": "permissive",
"max_line_length": 33,
"num_lines": 7,
"path": "/docs/reference/google.auth.crypt.rst",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "google.auth.crypt module\n========================\n\n.. automodule:: google.auth.crypt\n :members:\n :inherited-members:\n :show-inheritance:\n"
},
{
"alpha_fraction": 0.6745177507400513,
"alphanum_fraction": 0.6803499460220337,
"avg_line_length": 33.55813980102539,
"blob_id": "6e7d21b4c9ed602df6fcf82fdcc460628fb5b01a",
"content_id": "41dc237eced307c02baf7cb691924a40986560af",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4458,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 129,
"path": "/tests/transport/test_requests.py",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "# Copyright 2016 Google Inc.\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\nimport mock\nimport requests\nimport requests.adapters\nfrom six.moves import http_client\n\nimport google.auth.credentials\nimport google.auth.transport.requests\nfrom tests.transport import compliance\n\n\nclass TestRequestResponse(compliance.RequestResponseTests):\n def make_request(self):\n return google.auth.transport.requests.Request()\n\n def test_timeout(self):\n http = mock.create_autospec(requests.Session, instance=True)\n request = google.auth.transport.requests.Request(http)\n request(url='http://example.com', method='GET', timeout=5)\n\n assert http.request.call_args[1]['timeout'] == 5\n\n\nclass CredentialsStub(google.auth.credentials.Credentials):\n def __init__(self, token='token'):\n super(CredentialsStub, self).__init__()\n self.token = token\n\n def apply(self, headers, token=None):\n headers['authorization'] = self.token\n\n def before_request(self, request, method, url, headers):\n self.apply(headers)\n\n def refresh(self, request):\n self.token += '1'\n\n\nclass AdapterStub(requests.adapters.BaseAdapter):\n def __init__(self, responses, headers=None):\n super(AdapterStub, self).__init__()\n self.responses = responses\n self.requests = []\n self.headers = headers or {}\n\n def send(self, request, **kwargs):\n # pylint: disable=arguments-differ\n # request is the only required argument here and the only argument\n # we care about.\n self.requests.append(request)\n return self.responses.pop(0)\n\n def close(self): # pragma: NO COVER\n # pylint wants this to be here because it's abstract in the base\n # class, but requests never actually calls it.\n return\n\n\ndef make_response(status=http_client.OK, data=None):\n response = requests.Response()\n response.status_code = status\n response._content = data\n return response\n\n\nclass TestAuthorizedHttp(object):\n TEST_URL = 'http://example.com/'\n\n def test_constructor(self):\n authed_session = google.auth.transport.requests.AuthorizedSession(\n mock.sentinel.credentials)\n\n assert authed_session.credentials == mock.sentinel.credentials\n\n def test_request_no_refresh(self):\n credentials = mock.Mock(wraps=CredentialsStub())\n response = make_response()\n adapter = AdapterStub([response])\n\n authed_session = google.auth.transport.requests.AuthorizedSession(\n credentials)\n authed_session.mount(self.TEST_URL, adapter)\n\n result = authed_session.request('GET', self.TEST_URL)\n\n assert response == result\n assert credentials.before_request.called\n assert not credentials.refresh.called\n assert len(adapter.requests) == 1\n assert adapter.requests[0].url == self.TEST_URL\n assert adapter.requests[0].headers['authorization'] == 'token'\n\n def test_request_refresh(self):\n credentials = mock.Mock(wraps=CredentialsStub())\n final_response = make_response(status=http_client.OK)\n # First request will 401, second request will succeed.\n adapter = AdapterStub([\n make_response(status=http_client.UNAUTHORIZED),\n final_response])\n\n authed_session = google.auth.transport.requests.AuthorizedSession(\n credentials)\n authed_session.mount(self.TEST_URL, adapter)\n\n result = authed_session.request('GET', self.TEST_URL)\n\n assert result == final_response\n assert credentials.before_request.call_count == 2\n assert credentials.refresh.called\n assert len(adapter.requests) == 2\n\n assert adapter.requests[0].url == self.TEST_URL\n assert adapter.requests[0].headers['authorization'] == 'token'\n\n assert adapter.requests[1].url == self.TEST_URL\n assert adapter.requests[1].headers['authorization'] == 'token1'\n"
},
{
"alpha_fraction": 0.7015907764434814,
"alphanum_fraction": 0.7268239259719849,
"avg_line_length": 18.815217971801758,
"blob_id": "9b1e836b253403fec4fa3984ed86f6e1bd6a4595",
"content_id": "59fd6aba17068aa1371ccab7ff107fda78a90b29",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 1823,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 92,
"path": "/tox.ini",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "[tox]\nenvlist = lint,py27,py34,py35,py36,pypy,cover,pytype\n\n[testenv]\ndeps =\n certifi\n flask\n mock\n oauth2client\n pytest\n pytest-cov\n pytest-localserver\n requests\n requests-oauthlib\n urllib3\n cryptography\n grpcio; platform_python_implementation != 'PyPy'\ncommands =\n pytest --cov=google.auth --cov=google.oauth2 --cov=tests {posargs:tests}\n\n[testenv:cover]\nbasepython = python3.6\ncommands =\n pytest --cov=google.auth --cov=google.oauth2 --cov=tests --cov-report= tests\n coverage report --show-missing --fail-under=100\ndeps =\n {[testenv]deps}\n\n[testenv:py36-system]\nbasepython = python3.6\nchangedir = {toxinidir}/system_tests\ncommands =\n nox {posargs}\ndeps =\n {[testenv]deps}\n nox-automation\n gapic-google-cloud-pubsub-v1==0.15.0\npassenv =\n SKIP_APP_ENGINE_SYSTEM_TEST\n CLOUD_SDK_ROOT\n\n[testenv:py27-system]\nbasepython = python2.7\nchangedir = {toxinidir}/system_tests\ncommands =\n nox {posargs}\ndeps =\n {[testenv]deps}\n nox-automation\n gapic-google-cloud-pubsub-v1==0.15.0\npassenv =\n SKIP_APP_ENGINE_SYSTEM_TEST\n CLOUD_SDK_ROOT\n\n[testenv:docgen]\nbasepython = python3.6\ndeps =\n {[testenv]deps}\n sphinx\nsetenv =\n SPHINX_APIDOC_OPTIONS=members,inherited-members,show-inheritance\ncommands =\n rm -r docs/reference\n sphinx-apidoc --output-dir docs/reference --separate --module-first google\n\n[testenv:docs]\nbasepython = python3.6\ndeps =\n sphinx\n -r{toxinidir}/docs/requirements-docs.txt\ncommands = make -C docs html\n\n[testenv:lint]\nbasepython = python3.6\ncommands =\n flake8 \\\n --import-order-style=google \\\n --application-import-names=\"google,tests,system_tests\" \\\n google tests\n python setup.py check --metadata --restructuredtext --strict\ndeps =\n flake8\n flake8-import-order\n docutils\n\n[testenv:pytype]\nbasepython = python3.6\ncommands =\n pytype\ndeps =\n {[testenv]deps}\n pytype\n"
},
{
"alpha_fraction": 0.6981402039527893,
"alphanum_fraction": 0.7043395042419434,
"avg_line_length": 31.261537551879883,
"blob_id": "5740c69dacc8cc2a97e3957a27e248e73a165a6d",
"content_id": "ae864666a5ec477814895c233641c26f2eb62dc6",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2097,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 65,
"path": "/scripts/obtain_user_auth.py",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "# Copyright 2016 Google Inc.\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 program obtains a set of user credentials.\n\nThese credentials are needed to run the system test for OAuth2 credentials.\nIt's expected that a developer will run this program manually once to obtain\na refresh token. It's highly recommended to use a Google account created\nspecifically for testing.\n\"\"\"\n\nimport json\nimport os\n\nfrom oauth2client import client\nfrom oauth2client import tools\n\nHERE = os.path.dirname(__file__)\nCLIENT_SECRETS_PATH = os.path.abspath(os.path.join(\n HERE, '..', 'system_tests', 'data', 'client_secret.json'))\nAUTHORIZED_USER_PATH = os.path.abspath(os.path.join(\n HERE, '..', 'system_tests', 'data', 'authorized_user.json'))\nSCOPES = ['email', 'profile']\n\n\nclass NullStorage(client.Storage):\n \"\"\"Null storage implementation to prevent oauth2client from failing\n on storage.put.\"\"\"\n def locked_put(self, credentials):\n pass\n\n\ndef main():\n flow = client.flow_from_clientsecrets(CLIENT_SECRETS_PATH, SCOPES)\n\n print('Starting credentials flow...')\n credentials = tools.run_flow(flow, NullStorage())\n\n # Save the credentials in the same format as the Cloud SDK's authorized\n # user file.\n data = {\n 'type': 'authorized_user',\n 'client_id': flow.client_id,\n 'client_secret': flow.client_secret,\n 'refresh_token': credentials.refresh_token\n }\n\n with open(AUTHORIZED_USER_PATH, 'w') as fh:\n json.dump(data, fh, indent=4)\n\n print('Created {}.'.format(AUTHORIZED_USER_PATH))\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.670095682144165,
"alphanum_fraction": 0.7171052694320679,
"avg_line_length": 39.19230651855469,
"blob_id": "764b36d9a27d6d28daeb1022eafd505c1d4eb719",
"content_id": "54fbbb184dd741042795cee136d279acc79b3ce3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 8360,
"license_type": "permissive",
"max_line_length": 252,
"num_lines": 208,
"path": "/CHANGELOG.rst",
"repo_name": "omarryhan/google-auth-library-python",
"src_encoding": "UTF-8",
"text": "Changelog\n=========\n\nv1.5.1\n------\n\n- Fix check for error text on Python 3.7. (#278)\n- Use new Auth URIs. (#281)\n- Add code-of-conduct document. (#270)\n- Fix some typos in test_urllib3.py (#268)\n\nv1.5.0\n------\n\n- Warn when using user credentials from the Cloud SDK (#266)\n- Add compute engine-based IDTokenCredentials (#236)\n- Corrected some typos (#265)\n\nv1.4.2\n------\n\n- Raise a helpful exception when trying to refresh credentials without a refresh token. (#262)\n- Fix links to README and CONTRIBUTING in docs/index.rst. (#260)\n- Fix a typo in credentials.py. (#256)\n- Use pytest instead of py.test per upstream recommendation, #dropthedot. (#255)\n- Fix typo on exemple of jwt usage (#245)\n\nv1.4.1\n------\n\n- Added a check for the cryptography version before attempting to use it. (#243)\n\nv1.4.0\n------\n\n- Added `cryptography`-based RSA signer and verifier. (#185)\n- Added `google.oauth2.service_account.IDTokenCredentials`. (#234)\n- Improved documentation around ID Tokens (#224)\n\nv1.3.0\n------\n\n- Added ``google.oauth2.credentials.Credentials.from_authorized_user_file`` (#226)\n- Dropped direct pyasn1 dependency in favor of letting ``pyasn1-modules`` specify the right version. (#230)\n- ``default()`` now checks for the project ID environment var before warning about missing project ID. (#227)\n- Fixed the docstrings for ``has_scopes()`` and ``with_scopes()``. (#228)\n- Fixed example in docstring for ``ReadOnlyScoped``. (#219)\n- Made ``transport.requests`` use timeouts and retries to improve reliability. (#220)\n\nv1.2.1\n------\n\n- Excluded compiled Python files in source distributions. (#215)\n- Updated docs for creating RSASigner from string. (#213)\n- Use ``six.raise_from`` wherever possible. (#212)\n- Fixed a typo in a comment ``seconds`` not ``sections``. (#210)\n\nv1.2.0\n------\n\n- Added ``google.auth.credentials.AnonymousCredentials``. (#206)\n- Updated the documentation to link to the Google Cloud Platform Python setup guide (#204)\n\nv1.1.1\n------\n\n- ``google.oauth.credentials.Credentials`` now correctly inherits from ``ReadOnlyScoped`` instead of ``Scoped``. (#200)\n\nv1.1.0\n------\n\n- Added ``service_account.Credentials.project_id``. (#187)\n- Move read-only methods of ``credentials.Scoped`` into new interface ``credentials.ReadOnlyScoped``. (#195, #196)\n- Make ``compute_engine.Credentials`` derive from ``ReadOnlyScoped`` instead of ``Scoped``. (#195)\n- Fix App Engine's expiration calculation (#197)\n- Split ``crypt`` module into a package to allow alternative implementations. (#189)\n- Add error message to handle case of empty string or missing file for GOOGLE_APPLICATION_CREDENTIALS (#188)\n\nv1.0.2\n------\n\n- Fixed a bug where the Cloud SDK executable could not be found on Windows, leading to project ID detection failing. (#179)\n- Fixed a bug where the timeout argument wasn't being passed through the httplib transport correctly. (#175)\n- Added documentation for using the library on Google App Engine standard. (#172)\n- Testing style updates. (#168)\n- Added documentation around the oauth2client deprecation. (#165)\n- Fixed a few lint issues caught by newer versions of pylint. (#166)\n\nv1.0.1\n------\n\n- Fixed a bug in the clock skew accommodation logic where expired credentials could be used for up to 5 minutes. (#158)\n\nv1.0.0\n------\n\nMilestone release for v1.0.0.\nNo significant changes since v0.10.0\n\nv0.10.0\n-------\n\n- Added ``jwt.OnDemandCredentials``. (#142)\n- Added new public property ``id_token`` to ``oauth2.credentials.Credentials``. (#150)\n- Added the ability to set the address used to communicate with the Compute Engine metadata server via the ``GCE_METADATA_ROOT`` and ``GCE_METADATA_IP`` environment variables. (#148)\n- Changed the way cloud project IDs are ascertained from the Google Cloud SDK. (#147)\n- Modified expiration logic to add a 5 minute clock skew accommodation. (#145)\n\nv0.9.0\n------\n\n- Added ``service_account.Credentials.with_claims``. (#140)\n- Moved ``google.auth.oauthlib`` and ``google.auth.flow`` to a new separate package ``google_auth_oauthlib``. (#137, #139, #135, #126)\n- Added ``InstalledAppFlow`` to ``google_auth_oauthlib``. (#128)\n- Fixed some packaging and documentation issues. (#131)\n- Added a helpful error message when importing optional dependencies. (#125)\n- Made all properties required to reconstruct ``google.oauth2.credentials.Credentials`` public. (#124)\n- Added official Python 3.6 support. (#102)\n- Added ``jwt.Credentials.from_signing_credentials`` and removed ``service_account.Credentials.to_jwt_credentials``. (#120)\n\nv0.8.0\n------\n\n- Removed one-time token behavior from ``jwt.Credentials``, audience claim is now required and fixed. (#117)\n- ``crypt.Signer`` and ``crypt.Verifier`` are now abstract base classes. The concrete implementations have been renamed to ``crypt.RSASigner`` and ``crypt.RSAVerifier``. ``app_engine.Signer`` and ``iam.Signer`` now inherit from ``crypt.Signer``. (#115)\n- ``transport.grpc`` now correctly calls ``Credentials.before_request``. (#116)\n\nv0.7.0\n------\n\n- Added ``google.auth.iam.Signer``. (#108)\n- Fixed issue where ``google.auth.app_engine.Signer`` erroneously returns a tuple from ``sign()``. (#109)\n- Added public property ``google.auth.credentials.Signing.signer``. (#110)\n\nv0.6.0\n------\n\n- Added experimental integration with ``requests-oauthlib`` in ``google.oauth2.oauthlib`` and ``google.oauth2.flow``. (#100, #105, #106)\n- Fixed typo in ``google_auth_httplib2``'s README. (#105)\n\nv0.5.0\n------\n\n- Added ``app_engine.Signer``. (#97)\n- Added ``crypt.Signer.from_service_account_file``. (#95)\n- Fixed error handling in the oauth2 client. (#96)\n- Fixed the App Engine system tests.\n\nv0.4.0\n------\n\n- ``transports.grpc.secure_authorized_channel`` now passes ``kwargs`` to ``grpc.secure_channel``. (#90)\n- Added new property ``credentials.Singing.signer_email`` which can be used to identify the signer of a message. (#89)\n- (google_auth_httplib2) Added a proxy to ``httplib2.Http.connections``.\n\nv0.3.2\n------\n\n- Fixed an issue where an ``ImportError`` would occur if ``google.oauth2`` was imported before ``google.auth``. (#88)\n\nv0.3.1\n------\n\n- Fixed a bug where non-padded base64 encoded strings were not accepted. (#87)\n- Fixed a bug where ID token verification did not correctly call the HTTP request function. (#87)\n\nv0.3.0\n------\n\n- Added Google ID token verification helpers. (#82)\n- Swapped the ``target`` and ``request`` argument order for ``grpc.secure_authorized_channel``. (#81)\n- Added a user's guide. (#79)\n- Made ``service_account_email`` a public property on several credential classes. (#76)\n- Added a ``scope`` argument to ``google.auth.default``. (#75)\n- Added support for the ``GCLOUD_PROJECT`` environment variable. (#73)\n\nv0.2.0\n------\n\n- Added gRPC support. (#67)\n- Added Requests support. (#66)\n- Added ``google.auth.credentials.with_scopes_if_required`` helper. (#65)\n- Added private helper for oauth2client migration. (#70)\n\nv0.1.0\n------\n\nFirst release with core functionality available. This version is ready for\ninitial usage and testing.\n\n- Added ``google.auth.credentials``, public interfaces for Credential types. (#8)\n- Added ``google.oauth2.credentials``, credentials that use OAuth 2.0 access and refresh tokens (#24)\n- Added ``google.oauth2.service_account``, credentials that use Service Account private keys to obtain OAuth 2.0 access tokens. (#25)\n- Added ``google.auth.compute_engine``, credentials that use the Compute Engine metadata service to obtain OAuth 2.0 access tokens. (#22)\n- Added ``google.auth.jwt.Credentials``, credentials that use a JWT as a bearer token.\n- Added ``google.auth.app_engine``, credentials that use the Google App Engine App Identity service to obtain OAuth 2.0 access tokens. (#46)\n- Added ``google.auth.default()``, an implementation of Google Application Default Credentials that supports automatic Project ID detection. (#32)\n- Added system tests for all credential types. (#51, #54, #56, #58, #59, #60, #61, #62)\n- Added ``google.auth.transports.urllib3.AuthorizedHttp``, an HTTP client that includes authentication provided by credentials. (#19)\n- Documentation style and formatting updates.\n\nv0.0.1\n------\n\nInitial release with foundational functionality for cryptography and JWTs.\n\n- ``google.auth.crypt`` for creating and verifying cryptographic signatures.\n- ``google.auth.jwt`` for creating (encoding) and verifying (decoding) JSON Web tokens.\n"
}
] | 7 |
choucurtis987/CS-131b-Labs | https://github.com/choucurtis987/CS-131b-Labs | 28b23f9a7e1c7e4bf8416251b4f5271515f007a9 | 9e0ff66904a055d8b10f9592be489d08f99151e5 | e8b99bc69c80462683bad6eb8240014c93de7712 | refs/heads/master | 2022-06-10T22:41:51.697894 | 2020-05-06T04:10:14 | 2020-05-06T04:10:14 | 170,246,925 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6521739363670349,
"alphanum_fraction": 0.6613272428512573,
"avg_line_length": 30.214284896850586,
"blob_id": "c06799a8c0517e19a971c525685b83f08e1117f2",
"content_id": "a1df64a0805dd632c2b0590a159740d4b83a171c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 437,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 14,
"path": "/initial_creator.py",
"repo_name": "choucurtis987/CS-131b-Labs",
"src_encoding": "UTF-8",
"text": "#2-9-19\n# creates initials for name based on capital letters\n\ndef initials(name):\n solution = ''\n # the for loop loops through the letters in name:\n for letter in name:\n # the .isupper() method determines if letter is capitalized:\n if letter.isupper():\n PERIOD = '.'\n # the capital letters are added with a period then to the blank string \"solution\":\n solution += letter+PERIOD\n\n return solution\n"
},
{
"alpha_fraction": 0.7687296271324158,
"alphanum_fraction": 0.791530966758728,
"avg_line_length": 60.400001525878906,
"blob_id": "df8984bfd573a6d116c5aa11706a3f8b6ed11806",
"content_id": "a7256574a54bfafddb664c92e7cc1e1bc1a54aea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 307,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 5,
"path": "/README.md",
"repo_name": "choucurtis987/CS-131b-Labs",
"src_encoding": "UTF-8",
"text": "# Python Data Structures Labs\n- This is a repository for some of my \"CS131b: Python Programming Fundamentals\" labs\n- All files will contain comments to explain what is going on within the code\n- Browse around to find some cool mini projects done in my first programming class\n- I took the class Spring 2019\n"
},
{
"alpha_fraction": 0.6351351141929626,
"alphanum_fraction": 0.6441441178321838,
"avg_line_length": 26.75,
"blob_id": "debb19dbb436bffd311d28005da1986b13d6f61c",
"content_id": "47bfab852b41726acb6a4126f1b13ffd9fa33ff8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 444,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 16,
"path": "/acronym_creator.py",
"repo_name": "choucurtis987/CS-131b-Labs",
"src_encoding": "UTF-8",
"text": "# 2-9-19\n# creates an acronym based on all capital letters in word\n\ndef capital_acronym(word):\n answer = ''\n\n # the for loop loops through all the letters in word:\n for letter in word:\n\n # the .isupper() method is a bool that determines if letter is uppercased:\n if letter.isupper():\n\n # if letter is uppercased, it will add letter to the blank string \"answer\":\n answer += letter\n\n return answer\n"
},
{
"alpha_fraction": 0.6151990294456482,
"alphanum_fraction": 0.6164053082466125,
"avg_line_length": 37.511627197265625,
"blob_id": "ae4eac7baf386276f14bd5c4602577d9285c95ca",
"content_id": "eb79498b02db7640204b1b58b080464994c0135e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1658,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 43,
"path": "/rotating_letter_encryption.py",
"repo_name": "choucurtis987/CS-131b-Labs",
"src_encoding": "UTF-8",
"text": "# this function encrypts or decrypts a message(s) by rotating each letter in \n# the message by (n) through the alphabet. this is pretty much the caesar cipher \n# in a function. To decrypt a message use negative number.\n\n# defines a function with 2 arguments \n# s = desired message to be encrypted\n# n = number of rotation times // positive number encrypts and negative numbers can decrypt or encrypt:\ndef rot(s, n):\n # possible letter options alphabetically:\n SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n # creates blank string:\n blank = ''\n # combats case sensitivity:\n s = s.upper()\n # loops through all letter in s:\n for letter in s:\n # determines if letter is in SYMBOLS:\n if letter in SYMBOLS:\n # finds the numeric value of that letter:\n x = SYMBOLS.find(letter)\n # adds the rotation number to the numeric value of that letter:\n new = x + n\n\n # if the number is greater than len(SYMBOLS): \n if new >= len(SYMBOLS):\n # new number will be subtracted by len(SYMBOLS) to create a wraparound:\n new = new - len(SYMBOLS)\n\n # if the new number is less than zero:\n if new < 0:\n # new number will be added by len(SYMBOLS) to create a wraparound:\n new = new + len(SYMBOLS)\n # adds the new letter to a blank string:\n blank = blank + SYMBOLS[new]\n\n\n else:\n # if something in the message is not a letter it will simply be added to where it is suppose to be:\n blank = blank + letter\n\n\n # returns the blank string:\n return blank\n\n\n"
},
{
"alpha_fraction": 0.6432469487190247,
"alphanum_fraction": 0.6466575860977173,
"avg_line_length": 42.117645263671875,
"blob_id": "ed7eea40b297e8d0337cbb51183c0eefe923b986",
"content_id": "35cd4332a1cd67e442de240c1136eecf6e6e1278",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1466,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 34,
"path": "/anagram_finder/anagram_finder.py",
"repo_name": "choucurtis987/CS-131b-Labs",
"src_encoding": "UTF-8",
"text": "# 2-15-19\n\n# a function that returns the equal length anagrams of a word in a list\n\n# opens the wordList file and reads through it and turns the file into a list:\nwith open('wordList.txt') as fd:\n # defines the list created:\n WORDS = fd.read().split()\n\n# creates a function with input being the word u want to find anagrams of:\ndef anagram_finder(input):\n # sorts 'input' alphabetically:\n sorted_input = sorted(input)\n # creates a blank list:\n blank = []\n # loops through WORDS with enumeration:\n for number, word in enumerate(WORDS):\n # determines words in WORDS with equal length of 'input':\n if len(word) == len(input):\n # sorts 'word' of equal length to 'input' alphabetically:\n sorted_WORDS = sorted(word)\n # determines if sorted_input is equal to sorted_WORDS\n # if true then input has an equal length anagram because sorted_input\n # has the same words as sorted_WORDS:\n if sorted_input == sorted_WORDS:\n # gets the anagrams of a word by finding the corresponding enumerated 'number'\n # in WORDS and places this is the variable 'result':\n result = WORDS[number]\n # appends every anagram to the blank list result:\n blank.append(result)\n # returns the blank list with 'input' anagrams:\n return blank\n\n# looking to update function to find words of unequal length within 'input'\n"
}
] | 5 |
rryanrussell2/photos | https://github.com/rryanrussell2/photos | 3b125b038ffa0c52f8290b7dfae9aeb26df5b261 | beeb485583797bbc5021e666dcbc7d6d25dd0522 | 7b7a59d91249578761b3a7418df7b7678941b308 | refs/heads/master | 2023-07-14T19:40:35.503153 | 2021-08-05T03:23:48 | 2021-08-05T03:23:48 | 392,883,133 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6914098858833313,
"alphanum_fraction": 0.6988795399665833,
"avg_line_length": 29.600000381469727,
"blob_id": "036f0faaaa8252ce22048e5ebc514000cbbfa7de",
"content_id": "446f35581afd68c01de19f242ee238618e41ffee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2142,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 70,
"path": "/api/app/main.py",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "from fastapi.exceptions import HTTPException\nfrom fastapi.param_functions import Query\nfrom sqlalchemy.sql.expression import desc\nfrom app.models.schemas import Photo, PhotoList\nfrom app.models.orm import Photo as PhotoDB\nfrom app.db import create_db, get_db\nfrom typing import List\nfrom PIL import Image\nfrom io import BytesIO\n\nfrom fastapi import FastAPI, Depends, File, UploadFile, Response, status\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom sqlalchemy.exc import NoResultFound\nfrom sqlalchemy.orm.session import Session\n\napp = FastAPI()\n\norigins = [\n \"http://localhost:3000\"\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\ncreate_db()\n\[email protected](\"/\")\ndef read_root():\n return \"Hello, world.\"\n\[email protected]('/photos', response_model=PhotoList)\ndef search_photos(\n name: str, \n db: Session = Depends(get_db), \n from_ = Query(0, alias='from'), \n size = Query(12)\n):\n query = db.query(PhotoDB).filter(PhotoDB.name.ilike(f'%{name}%'))\n count = query.count() \n return PhotoList(\n count=count,\n photos=query.order_by(desc(PhotoDB.date_uploaded)).limit(size).offset(from_).all()\n )\n\[email protected]('/photos', response_model=Photo, status_code=status.HTTP_201_CREATED)\ndef create_photo(file: UploadFile = File(...), db: Session = Depends(get_db)):\n if not file.content_type.lower().startswith('image'):\n raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Only images accepted.')\n\n image_data = file.file.read()\n width, height = Image.open(BytesIO(image_data)).size\n new_photo = PhotoDB(name=file.filename, type=file.content_type, data=image_data, width=width, height=height)\n db.add(new_photo)\n db.commit()\n db.refresh(new_photo)\n return new_photo\n\[email protected]('/photos/{photo_id}')\ndef get_photo_data(photo_id: str, db: Session = Depends(get_db)):\n try:\n photo = db.query(PhotoDB).filter(PhotoDB.id == photo_id).one()\n return Response(photo.data, media_type=photo.type)\n except NoResultFound:\n raise HTTPException(status.HTTP_404_NOT_FOUND)\n"
},
{
"alpha_fraction": 0.7427785396575928,
"alphanum_fraction": 0.7455295920372009,
"avg_line_length": 35.349998474121094,
"blob_id": "c35482e29fc96ce9f295d98c169a7c0ba1180e58",
"content_id": "8df3607b5ae7a004f13a91d7e1a89b09bda26951",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 727,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 20,
"path": "/api/app/models/orm.py",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "from uuid import uuid4\nfrom datetime import datetime\n\nfrom sqlalchemy import Column, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.dialects.postgresql import BYTEA\nfrom sqlalchemy.sql.sqltypes import DateTime, Integer\n\nBase = declarative_base()\n\nclass Photo(Base):\n __tablename__ = 'photos'\n\n id: str = Column(String, primary_key=True, default=lambda: str(uuid4()))\n name: str = Column(String, nullable=False, index=True)\n type: str = Column(String, nullable=False)\n data: bytes = Column(BYTEA, nullable=False)\n width: int = Column(Integer, nullable=False)\n height: int = Column(Integer, nullable=False)\n date_uploaded: datetime = Column(DateTime, default=datetime.now)\n"
},
{
"alpha_fraction": 0.7148014307022095,
"alphanum_fraction": 0.7328519821166992,
"avg_line_length": 20.30769157409668,
"blob_id": "556247bd1b6460352f2c3ea122d195580ff3b46b",
"content_id": "f629d039b8bafd049a4578e6a8f46fe398eb9417",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 13,
"path": "/api/Dockerfile",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8\n\nRUN pip install \"poetry==1.0.0\"\n\nCOPY ./pyproject.toml /app\nCOPY ./poetry.lock /app\n\nRUN poetry config virtualenvs.create false \\\n && poetry install --no-interaction --no-ansi\n\nCOPY ./app /app\n\nENTRYPOINT [\"/start-reload.sh\"]\n"
},
{
"alpha_fraction": 0.7237687110900879,
"alphanum_fraction": 0.7237687110900879,
"avg_line_length": 21.238094329833984,
"blob_id": "94a1f89ec549d60d91aba26ea4a1e2db9ccd4281",
"content_id": "058b34d6a844ff843801c9611a73a031c57868f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 467,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 21,
"path": "/api/app/db.py",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "from app.models.orm import Base\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nSQLALCHEMY_DATABASE_URL = \"postgresql://postgres:password@postgres\"\n\nengine = create_engine(\n SQLALCHEMY_DATABASE_URL\n)\n\nSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\ndef create_db():\n Base.metadata.create_all(bind=engine)\n"
},
{
"alpha_fraction": 0.6488549709320068,
"alphanum_fraction": 0.6488549709320068,
"avg_line_length": 15.375,
"blob_id": "d5b47582f8066a002246ff690bddd351a1703b96",
"content_id": "0cd8a1e5c1fdee1565e83c562e462cc5365daf94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 262,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 16,
"path": "/api/app/models/schemas.py",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "from typing import List\nfrom pydantic import BaseModel\n\nclass Photo(BaseModel):\n name: str\n type: str\n id: str\n width: int\n height: int\n\n class Config:\n orm_mode = True\n\nclass PhotoList(BaseModel):\n photos: List[Photo]\n count: int\n"
},
{
"alpha_fraction": 0.5557894706726074,
"alphanum_fraction": 0.6294736862182617,
"avg_line_length": 20.590909957885742,
"blob_id": "b818a0d512d52eb8619f1251f9408a494bf4d8af",
"content_id": "ddddef501a5bce3ce6351bea26d1876198a5fec7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TOML",
"length_bytes": 475,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 22,
"path": "/api/pyproject.toml",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "[tool.poetry]\nname = \"photos-api\"\nversion = \"0.1.0\"\ndescription = \"\"\nauthors = [\"Ryan Russell <[email protected]>\"]\n\n[tool.poetry.dependencies]\npython = \"^3.8\"\nfastapi = \"^0.68.0\"\nuvicorn = {extras = [\"standard\"], version = \"^0.14.0\"}\nSQLAlchemy = \"^1.4.22\"\npydantic = \"^1.8.2\"\npsycopg2-binary = \"^2.9.1\"\npython-multipart = \"^0.0.5\"\nPillow = \"^8.3.1\"\n\n[tool.poetry.dev-dependencies]\npytest = \"^5.2\"\n\n[build-system]\nrequires = [\"poetry-core>=1.0.0\"]\nbuild-backend = \"poetry.core.masonry.api\"\n"
},
{
"alpha_fraction": 0.7301886677742004,
"alphanum_fraction": 0.7377358675003052,
"avg_line_length": 26.842105865478516,
"blob_id": "0974402e3c509c996ac66259a91fcf7a5e0bd19b",
"content_id": "227ee55067170d309aefeb4012fb35534142253a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 530,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 19,
"path": "/README.md",
"repo_name": "rryanrussell2/photos",
"src_encoding": "UTF-8",
"text": "\n# Photos App\n\n### Getting Started\n\n- Have [docker](https://docs.docker.com/get-docker/) installed\n- Run `docker compose up --build -d`\n- Go get a beverage while it pulls images and builds\n- Once `postgres` is up, you'll probably have to run `docker restart photos-api`\n- Navigate to http://localhost:3000/\n\n### TODO\n\n- Remove unused boilerplate from CRA\n- Cap upload file size\n- Handle small images more nicely\n- Display image names\n- Allow image renaming\n- Show full image in lightbox when selected\n- Allow images to be deleted\n"
}
] | 7 |
kaislar/Customer-classification-RFM | https://github.com/kaislar/Customer-classification-RFM | 6a610e21d9477b4840504e1023f358764ae62282 | 1ed32543b6da404f08d99fa6571bca2d6282d991 | a4ec86ac8928a6949ebc9bb2ea6fdd35f142b95e | refs/heads/master | 2021-01-19T01:14:23.775878 | 2018-07-17T22:39:20 | 2018-07-17T22:39:20 | 87,233,731 | 7 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6168728470802307,
"alphanum_fraction": 0.6409768462181091,
"avg_line_length": 41.040000915527344,
"blob_id": "cb0aec6aee8639b618320f583e93d6b26b578135",
"content_id": "ca09e732fbd653bf13bbd7aaa05bf841a23b6601",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3154,
"license_type": "no_license",
"max_line_length": 248,
"num_lines": 75,
"path": "/final_matrix.py",
"repo_name": "kaislar/Customer-classification-RFM",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 25 10:07:01 2017\n\n@author: kais\n\"\"\"\nimport csv\nimport numpy \nimport matplotlib.pyplot as plt\nimport math\nimport pandas\n\n###########################################################################\n#Generation du fichier contenant la base de donnée en format t , t +1 ,.. t+n\n###########################################################################\ndef creation_liste():\n\timport os\n\tfrom datetime import datetime, timedelta\n\tdelta=timedelta(days=30)\n\n\tdate_format = \"%Y-%m-%d\"\n\tdate_max_str='2013-07-28'\n\tdate_min_str='2012-03-02'\n\tdate_max=datetime.strptime(date_max_str, date_format)\n\tdate_min=datetime.strptime(date_min_str, date_format)\n\n\tl=[]\n\ti=date_min\n\twhile(i<date_max): \n\t\tl.append(str(i)[:10])\n\t\ti+=delta \n\treturn l \n\n\nif __name__=='__main__' : \n file_path= '/media/kais/Kais/datasetRNN/RFM/'\n path_output=\"/media/kais/Kais/datasetRNN/RFM\"\n liste_fichiers= creation_liste()\n file_name=\"2012-04-01_RFM.csv\"\n dataframe = pandas.read_csv( file_path+file_name ,engine= 'python' , skipfooter=3)\n dataset =dataframe.values\n dataset = dataset.astype( 'float32' )\t\t\n liste_clients= dataframe[\"customer\"].values\n df = pandas.DataFrame({'R0': dataframe[\"recency\"].values, 'F0': dataframe[\"frequency\"].values, 'M0': dataframe[\"monetary_value\"].values}, index = liste_clients)\n k=0\n \n df=df.ix[:,['F0','R0','M0']]\n\n for j in liste_fichiers[2:] :\n k+=1\n file_name= j+\"_RFM.csv\"\n dataframe = pandas.read_csv( file_path+file_name ,engine= 'python' , skipfooter=3)\n liste_clients_int=dataframe[\"customer\"].values\n dataset = dataset.astype( 'float32' )\t\n dataframe = pandas.DataFrame({'R0': dataframe[\"recency\"].values, 'F0': dataframe[\"frequency\"].values, 'M0': dataframe[\"monetary_value\"].values}, index = liste_clients_int)\n \n print df.loc[liste_clients]\n df['F'+str(k)]=pandas.Series(dataframe.loc[liste_clients,'F0'], index = liste_clients)\n df['R'+str(k)]=pandas.Series(dataframe.loc[liste_clients,'R0'], index = liste_clients)\n df['M'+str(k)]=pandas.Series(dataframe.loc[liste_clients,'M0'], index = liste_clients)\n dataframe2 = pandas.read_csv( file_path+\"categories.csv\" ,engine= 'python' , skipfooter=3)\n liste_clients_int=dataframe2[\"customer\"].values\n dataframe2 = pandas.DataFrame({'R_Quartile': dataframe2[\"R_Quartile\"].values, 'F_Quartile': dataframe2[\"F_Quartile\"].values, 'M_Quartile': dataframe2[\"M_Quartile\"].values, 'RFMClass': dataframe2[\"RFMClass\"].values}, index = liste_clients_int)\n df['Fcat']=pandas.Series(dataframe2.loc[liste_clients,'F_Quartile'], index = liste_clients)\n \n \n df['Rcat']=pandas.Series(dataframe2.loc[liste_clients,'R_Quartile'], index = liste_clients)\n df['Mcat']=pandas.Series(dataframe2.loc[liste_clients,'M_Quartile'], index = liste_clients)\n df['RFMClass']=pandas.Series(dataframe2.loc[liste_clients,'RFMClass'], index = liste_clients)\n \n liste_categories=df[\"RFMClass\"].values\n liste_categories= set(liste_categories)\n print liste_categories\n df.to_csv(file_path+'dataset_seq.csv')\n"
},
{
"alpha_fraction": 0.6889561414718628,
"alphanum_fraction": 0.7164901494979858,
"avg_line_length": 29.32110023498535,
"blob_id": "514b186d52e02979600f7ad3aedaecf72d6a401e",
"content_id": "8bad4badecfeed4d1f45f42d5339766ee70bd646",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3306,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 109,
"path": "/predict.py",
"repo_name": "kaislar/Customer-classification-RFM",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 26 22:05:19 2017\n\n@author: kais\n\"\"\"\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.models import Sequential \nfrom keras.layers.core import Dense, Activation \nfrom keras.preprocessing import sequence\nimport numpy\nimport matplotlib.pyplot as plt\nimport pandas\nimport math\nfrom keras.layers import LSTM\nfrom keras.utils import np_utils\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfile_path= '/media/kais/Kais/datasetRNN/RFM/'\nfile_name= 'dataset_seq.csv'\n\nfile_path_categ= '/home/kais/Projet recherche/shopperRNN/'\nfile_name_categ= 'outcat.csv'\n\n# fix random seed for reproducibility\nnumpy.random.seed(7)\n# load the dataset\ndataframe = pandas.read_csv( file_path+file_name ,engine= \"python\" , skipfooter=3)\ndataset = dataframe.values\n\nY= dataset[:,52:]\n#cas RFM \nVecteurY=Y[:,3]\n#cas R ou F ou M seulement \n#VecteurY=Y[:,0]\n#VecteurY=Y[:,1]\n#VecteurY=Y[:,2]\nliste_categories=[]\nfor i in [1,2,3,4]:\n for j in [1,2,3,4]:\n for k in [1,2,3,4]:\n s=100*i+10*j+k\n liste_categories.append(s)\n\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(liste_categories)\nencoded_Y = encoder.transform(VecteurY)\nVecteurY_encoded = np_utils.to_categorical(encoded_Y)\n\n# split into train and test sets\ntrain_size = int(len(dataset) * 0.67) #0.67\ntest_size = len(dataset) - train_size\ntrain, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\n#chaque 3 colonnes correspondent à un time step\nnb_colonnesX=52-3\nnb_ti=17-1\n\ntrainX=dataset[0:train_size,1:nb_colonnesX]\ntestX=dataset[train_size:len(dataset),1:nb_colonnesX]\ntrainY= VecteurY_encoded[0:train_size,:]\ntestY=VecteurY_encoded[train_size:len(dataset),:] \n\n \nX_train = numpy.reshape(trainX, (len(trainX), nb_ti,3 ))\nX_test = numpy.reshape(testX, (len(testX), nb_ti,3 ))\n\nprint trainY.shape[1]\nbatch_size=30\nnb_epoch=2\n'''\n\nmodel = Sequential()\nmodel.add(LSTM(60, input_shape=(X_train.shape[1], X_train.shape[2])))\nmodel.add(Dense(trainY.shape[1], activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# Fit the model\nmodel.fit(X_train, trainY , nb_epoch=3, batch_size=batch_size)\n# evaluate the model\nscores = model.evaluate(X_test, testY , verbose=1)\nprint(\"Accuracy: %.2f%%\" % (scores[1]*100))\n\npreds = model.predict(X_train[0:100,:], batch_size=batch_size)\n\n'''\n\nprint X_train.shape[1]\nprint X_train.shape[2]\ndef baseline_model():\n\t# create model\n model = Sequential()\n model.add(LSTM(200, input_shape=(X_train.shape[1], X_train.shape[2])))\n model.add(Dense(trainY.shape[1], activation='softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\nestimator = KerasClassifier(build_fn=baseline_model, nb_epoch=nb_epoch, batch_size=batch_size, verbose=1)\nestimator.fit(X_train, trainY)\n\npredictions = estimator.predict(X_test)\nprint(predictions)\nmy_pred=encoder.inverse_transform(predictions)\nprint(my_pred)\nmy_real_y=VecteurY[train_size:len(dataset)]\nprint my_real_y #vecteur Y correspondant aux classes de la test set\n\nprint my_pred==my_real_y\nm=numpy.array(my_pred==my_real_y)\nl=list(m)\nprint \"erreur \" + str((float(l.count(False))/len(my_pred))*100)\n"
},
{
"alpha_fraction": 0.6510574221611023,
"alphanum_fraction": 0.6797583103179932,
"avg_line_length": 30.5238094329834,
"blob_id": "0da5ce32c9aa889274270092a41fbd0a06c2f15b",
"content_id": "d5c03e56232c55b9929787b5ab6911e36d482816",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1330,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 42,
"path": "/autoRFM.py",
"repo_name": "kaislar/Customer-classification-RFM",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 19 11:05:14 2017\n\n@author: kais\n\"\"\"\n\nimport os\nfrom datetime import datetime, timedelta\n#Dans ce script on pourrait utiliser une liste de clients provenant d'un fichier quelquonque pas nécessairement le premier \n#Les clients non existant dans les fichiers des tj précédents auront RFM=0 \n#ce qui signifie pour le réseau récurrent une absence d'information \n\npath_input= '/media/kais/Kais/datasetRNN/'\npath_output='/media/kais/Kais/datasetRNN/RFM/classification/'\ndelta=timedelta(days=30)\ndate_format = \"%Y-%m-%d\"\n# max et min de la dataset\ndate_max_str='2013-07-28'\ndate_min_str='2012-03-02'\ndate_max=datetime.strptime(date_max_str, date_format)\ndate_min=datetime.strptime(date_min_str, date_format)\n#liste de clients à considerer\nl=[]\ni=date_min\nwhile(i<date_max): \n\tl.append(str(i)[:10])\n\ti+=delta \nprint l \n\nk=0\nfor i in l :\n\tif (k==0) : \n\t\t#k=1\n\t\tcontinue\n\telse : \n\t\t#os.system(\"python rfm.py -i \" + str(i)+\".csv -o ./RFM/\"+ str(i)+\"_RFM.csv -d \"+str(i))\n\t\tprint \"python rfm.py -i \"+ path_input + str(i)+\".csv -o \"+path_output+ str(i)+\"_RFM.csv -d \"+str(i)\t\n\t\tos.system(\"python rfm-analysis.py -i \"+ path_input + str(i)+\".csv -o \"+path_output+ str(i)+\"_RFM.csv -d \"+str(i))\n\t\n\t\t#RFM-analysis.py -i <orders.csv> -o <rfm-table.csv> -d <yyyy-mm-dd>'\n"
},
{
"alpha_fraction": 0.5868971943855286,
"alphanum_fraction": 0.6242038011550903,
"avg_line_length": 25.560976028442383,
"blob_id": "300d6dc00b1f6af65fa69dbec00801d729986ed7",
"content_id": "50fbec13480903a19504397c852573b0dfbd1cc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1101,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 41,
"path": "/extract_bydate.py",
"repo_name": "kaislar/Customer-classification-RFM",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 17 23:05:11 2017\n\n@author: kais\n\"\"\"\n#prend en argument la date sup des transactions à considérer\n \nimport csv\nimport math\nimport sys \nfrom datetime import datetime\nimport os\n\ndata_file = \"./reduced.csv\"\npath_output=\"/media/kais/Kais/datasetRNN/\"\ninterest_date= sys.argv[1]\nprint str(interest_date) \ndate_format = \"%Y-%m-%d\"\na = datetime.strptime(interest_date, date_format)\nclient=0\nc = csv.writer(open(path_output+interest_date+\".csv\", \"wb\"))\nc.writerow([\"customer\",\"order_date\",\"grand_total\",\"order_id\"])\ni=0\n\nfor e, line in enumerate( open(data_file) ):\n\tif (e==0): \n\t\tcontinue\n\t\n\telse :\t\n\t\t# si la date de la ligne est dans la marge \n\t\t# print line.split(\",\")[10] \n\t\tdelta= a - datetime.strptime(line.split(\",\")[6], date_format)\n\t\tif ( delta.days > 0 ) : \n\t\t\ti+=1\n\t\t\tif ( i % 1000000 == 0 ) : \n\t\t\t\tprint str(i) \n\t\t\t#print line.split(\",\")[6]\n\t\t\t#c.writerow([line.split(\",\")[0],line.split(\",\")[6],line.split(\",\")[10],line.split(\",\")[1]])\n\t\t\tc.writerow([line.split(\",\")[0],line.split(\",\")[6],line.split(\",\")[10],\",\"])\n\t\t\t\n\n\t\t\n\t\n"
},
{
"alpha_fraction": 0.8207547068595886,
"alphanum_fraction": 0.8207547068595886,
"avg_line_length": 74.71428680419922,
"blob_id": "2c2f9896c953418835662df70074ea441cebd6c0",
"content_id": "f74e3b193720f8cb1cb0e21cc4315c097fab5da7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 530,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 7,
"path": "/README.md",
"repo_name": "kaislar/Customer-classification-RFM",
"src_encoding": "UTF-8",
"text": "# Customer-classification-RFM\n\nCustomer lifetime value prediction using Deep learning techniques:\nThe aim of the project is to use deep learning, particularly recurrent neural networks to better understand customer behaviour in the retail sector.\nTo achieve this, I implemented different RNN models to predict customers' lifetime value using the RFM parameters ( well known parameters in marketing ).\nThe dataset used to train and test the model is available on kaggle :\nhttps://www.kaggle.com/c/acquire-valued-shoppers-challenge\n"
}
] | 5 |
angelalonso/py-k8s | https://github.com/angelalonso/py-k8s | 49bf80f5d56be75171362c4853632f611ff3b957 | 7f0b4a700877759d49793761fd8d1a83eaebbfc4 | d2990fa70c6ead7fbc0e338a3552a73faaf32123 | refs/heads/master | 2020-12-02T23:00:25.724748 | 2017-07-07T07:56:39 | 2017-07-07T07:56:39 | 96,215,888 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6616474986076355,
"alphanum_fraction": 0.6634189486503601,
"avg_line_length": 25.85714340209961,
"blob_id": "f045152b145e0b1054c44542dec65511a741bdd7",
"content_id": "61d313035f643fc15c6356c10e45e582070c3194",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1129,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 42,
"path": "/getpo",
"repo_name": "angelalonso/py-k8s",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n''' Script to find out details of a node, given its name\n- Looks for the node across all our stacks\n- Shows Pods running on it, First the ones with problems\n\nSo far I just got the first, unrelated example, taken from\nhttps://www.ianlewis.org/en/quick-look-kubernetes-python-client\n\nTODO: Get this script to work fine\nTODO: Do a similar one but for pods\n'''\n\nimport os\nfrom kubernetes import client, config\n\n\n\ndef load_configs():\n list_configs = []\n configpath = os.path.join(os.environ[\"HOME\"], '.kube')\n for file in os.listdir(configpath):\n if file.startswith(\"config.\"):\n list_configs.append(os.path.join(configpath, file))\n\n return list_configs\n\ndef show_allpods(env):\n # TODO: not need this print\n print('--------------> ' + env)\n\n currclient = client.CoreV1Api(\n api_client=config.new_client_from_config(env))\n\n pod_list = currclient.list_pod_for_all_namespaces()\n for pod in pod_list.items:\n print(\"%s\\t%s\\t%s\" % (pod.metadata.name,\n pod.status.phase,\n pod.status.pod_ip))\n\n\nfor env in load_configs():\n show_allpods(env)\n\n"
},
{
"alpha_fraction": 0.804347813129425,
"alphanum_fraction": 0.8152173757553101,
"avg_line_length": 45,
"blob_id": "3d3454d4a52a74956735ef7994bba128c5d0ada9",
"content_id": "ac947233aa2417b14a163c7d884a7bbe6a4a5944",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 92,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 2,
"path": "/README.md",
"repo_name": "angelalonso/py-k8s",
"src_encoding": "UTF-8",
"text": "# py-k8s\nPython Scripts using https://github.com/kubernetes-incubator/client-python library\n"
},
{
"alpha_fraction": 0.6436170339584351,
"alphanum_fraction": 0.6459810733795166,
"avg_line_length": 26.274192810058594,
"blob_id": "10464e53cf20a9d3b3955353874c712167b2d986",
"content_id": "0b7e80c7ff7f7cf6fe7bfd812a1f40d93289fb23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1692,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 62,
"path": "/getno",
"repo_name": "angelalonso/py-k8s",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n''' Script to find out details of a node, given its name\n- Looks for the node across all our stacks\n- Shows nodes running on it, First the ones with problems\n\nSo far I just got the first, unrelated example, taken from\nhttps://www.ianlewis.org/en/quick-look-kubernetes-python-client\n\nTODO: Get this script to only get info from a given node, or all when no parameter is received\nTODO: Do a similar one but for nodes\n'''\n\nimport argparse\nimport os\nimport sys\nfrom kubernetes import client, config\n\n\ndef load_configs():\n list_configs = []\n configpath = os.path.join(os.environ[\"HOME\"], '.kube')\n for file in os.listdir(configpath):\n if file.startswith(\"config.\"):\n list_configs.append(os.path.join(configpath, file))\n\n return list_configs\n\n\ndef show_allnodes(env):\n # TODO: not need this print\n print('--------------> ' + env)\n\n currclient = client.CoreV1Api(\n api_client=config.new_client_from_config(env))\n\n node_list = currclient.list_node()\n for node in node_list.items:\n print(\"%s\\t%s\" % (node.metadata.name,\n node.status.conditions\n ))\n\n\ndef show_allpods(env, nodename):\n currclient = client.CoreV1Api(\n api_client=config.new_client_from_config(env))\n\n node_list = currclient.list_node()\n for node in node_list.items:\n if node.metadata.name == nodename:\n print(\"%s\\t%s\" % (node.metadata.name,\n node.status.conditions\n ))\n\n\nif __name__ == '__main__':\n try:\n itemname = sys.argv[1]\n for env in load_configs():\n show_allpods(env, itemname)\n except IndexError:\n for env in load_configs():\n show_allnodes(env)\n\n"
}
] | 3 |
maana-io/IRIS-Classification | https://github.com/maana-io/IRIS-Classification | 69b2291eaa59374374ad10d9cc70e41c3ba3a616 | a4d96d442dba0a2f93b98d51f5d34c10b2a662ca | dc3bf447e207426c1ad6449ea85182e09a57fd3d | refs/heads/master | 2023-01-08T23:13:37.766630 | 2020-11-05T21:22:44 | 2020-11-05T21:22:44 | 275,817,479 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.636096179485321,
"alphanum_fraction": 0.636863648891449,
"avg_line_length": 59.092308044433594,
"blob_id": "8b1f39b6d5a05cc812bb72479b26db383d0aa345",
"content_id": "111889a0eded20791dc07ea41ae5be3d6989d978",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7818,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 130,
"path": "/app/resolvers.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport logging\nfrom app.logic.helpers import *\nfrom app.logic.active_learning import *\nfrom app.logic.classify import *\nfrom app.logic.feature_selection import *\nfrom app.logic.model_selection import *\nfrom app.logic.train import *\n\nlogger = logging.getLogger(__name__)\n\nresolvers = {\n 'Query': {\n #'train': lambda value, info, **args: train(args['trainingTask']),\n 'train_batch': lambda value, info, **args: train_batch(args['candidates'], args['training_data'],\n args['params'], args['model_id']),\n 'train_from_local_data': lambda value, info, **args: train_from_local_data(args['candidates'],\n args['schema'], args['training_data_file_name'], args['params'], args['model_id']),\n 'get_training_results': lambda value, info, **args: get_training_results(args['model_id']),\n 'all_training_results': lambda value, info, **args: all_training_results(),\n 'delete_training_results': lambda value, info, **args: delete_training_results(args['model_id']),\n #'modelSelection': lambda value, info, **args: model_selection(args['models'], args['modelSel']),\n 'classify': lambda value, info, **args: classify(args['cachedModelID'], args['data']),\n\n 'loadModelSelectionResults': lambda value, info, **args: loadModelSelectionResults(args['obj']),\n 'modelSelectionResultsToObject': lambda value, info, **args: modelSelectionResultsToObject(args['savedId'], args['msr']),\n\n 'defaultModelConfiguration': lambda value, info, **args: defaultModelConfiguration(),\n 'defaultModelSelection': lambda value, info, **args: defaultModelSelection(),\n 'defaultFeatures': lambda value, info, **args: defaultFeatures(args['dataset']),\n 'defaultFeaturizers': lambda value, info, **args: defaultFeaturizers(args['features']),\n 'defaultCandidate': lambda value, info, **args: defaultCandidate(args['dataset']),\n 'createModelConfiguration': lambda value, info, **args: createModelConfiguration(\n args['type'], args['weighting'], args['tokenizer'], args['ngrams'], args['tf'],\n args['df'], args['penalty'], args['multiclass'], args['solver'], args['primal_dual'],\n args['fitIntercept'], args['max_df'], args['min_df'], args['stopwords'], args['C'], args['max_iter']\n ),\n 'createModelSelection': lambda value, info, **args: createModelSelection(\n args['metric'], args['method'], args['evalMode'], args['numFolds']\n ),\n 'createCandidate': lambda value, info, **args: createCandidate(args['features'], args['featurizers'], args['config']),\n 'addCandidate': lambda value, info, **args: addToList(args['addThis'], args.get('toThis', None)),\n #'createTrainingTasks': lambda value, info, **args: createTrainingTasks(args['candidates'],\n # args['training_data'], args['params']),\n\n 'mergeDatasets': lambda value, info, **args: mergeDatasets(args['datasets']),\n 'mergeLabeledDatasets': lambda value, info, **args: mergeLabeledDatasets(args['datasets']),\n\n 'addFeaturizer': lambda value, info, **args: addToList(args['addThis'], args.get('toThis', None)),\n 'subsetFeatures': lambda value, info, **args: subsetFeatures(args['dataset'], args['selectedFeatures']),\n 'topNCorrelatedFeatures': lambda value, info, **args: top_correlated_features(args['dataset'], args['config'], args['topN']),\n 'topNPctCorrelatedFeatures': lambda value, info, **args: top_pct_correlated_features(args['dataset'], args['config'], args['pct']),\n 'topNRFEFeatures': lambda value, info, **args: top_rfe_features(args['dataset'], args['config'], args['topN']),\n 'topNPctRFEFeatures': lambda value, info, **args: top_pct_rfe_features(args['dataset'], args['config'], args['pct']),\n\n 'numericalFeatureType': lambda value, info, **args: 'NUMERICAL',\n 'categoricalFeatureType': lambda value, info, **args: 'CATEGORICAL',\n 'textFeatureType': lambda value, info, **args: 'TEXT',\n 'setFeatureType': lambda value, info, **args: 'SET',\n 'booleanFeatureType': lambda value, info, **args: 'BOOLEAN',\n 'labelFeatureType': lambda value, info, **args: 'LABEL',\n\n 'noopFeaturizerType': lambda value, info, **args: 'NOOP',\n 'minMaxScalerFeaturizerType': lambda value, info, **args: 'MIN_MAX_SCALER',\n 'labelBinarizerFeaturizerType': lambda value, info, **args: 'LABEL_BINARIZER',\n 'tfidfVectorizerFeaturizerType': lambda value, info, **args: 'TFIDF_VECTORIZER',\n 'multilabelBinarizerFeaturizerType': lambda value, info, **args: 'MULTILABEL_BINARIZER',\n 'labelEncoderFeaturizerType': lambda value, info, **args: 'LABEL',\n 'textToVectorFeaturizerType': lambda value, info, **args: 'TEXT_TO_VECTOR',\n \n 'correlationFeatureSelectionMode': lambda value, info, **args: 'CORRELATION',\n 'rfeFeatureSelectionMode': lambda value, info, **args: 'RFE',\n \n 'logisticRegressionModelType': lambda value, info, **args: 'LOGISTIC_REGRESSION',\n 'linearSVCModelType': lambda value, info, **args: 'LINEAR_SVC',\n \n 'noneClassWeightingType': lambda value, info, **args: 'NONE',\n 'balancedClassWeightingType': lambda value, info, **args: 'BALANCED',\n \n 'unigramNGramType': lambda value, info, **args: 'UNIGRAM',\n 'bigramNGramType': lambda value, info, **args: 'BIGRAM',\n 'bothNGramType': lambda value, info, **args: 'BOTH',\n \n 'linearTermFreqType': lambda value, info, **args: 'LINEAR',\n 'sublinearTermFreqType': lambda value, info, **args: 'SUBLINEAR',\n \n 'defaultDocumentFreqType': lambda value, info, **args: 'DEFAULT',\n 'smoothDocumentFreqType': lambda value, info, **args: 'SMOOTH',\n \n 'l1PenaltyType': lambda value, info, **args: 'L1',\n 'l2PenaltyType': lambda value, info, **args: 'L2',\n \n 'ovrMultiClassType': lambda value, info, **args: 'OVR',\n 'multinomialMultiClassType': lambda value, info, **args: 'MULTINOMIAL',\n 'autoMultiClassType': lambda value, info, **args: 'AUTO',\n \n 'liblinearSolverType': lambda value, info, **args: 'LIBLINEAR',\n 'newtonCGSolverType': lambda value, info, **args: 'NEWTON_CG',\n 'lbfgsSolverType': lambda value, info, **args: 'LBFGS',\n 'sagSolverType': lambda value, info, **args: 'SAG',\n 'sagaSolverType': lambda value, info, **args: 'SAGA',\n \n 'primalMode': lambda value, info, **args: 'PRIMAL',\n 'dualMode': lambda value, info, **args: 'DUAL',\n \n 'wordTokenizerType': lambda value, info, **args: 'WORD_TOKENIZER',\n 'stemmerTokenizerType': lambda value, info, **args: 'STEMMER',\n 'lemmatizerTokenizerType': lambda value, info, **args: 'LEMMATIZER',\n \n 'precisionModelSelectionMetric': lambda value, info, **args: 'PRECISION',\n 'recallModelSelectionMetric': lambda value, info, **args: 'RECALL',\n 'f1ModelSelectionMetric': lambda value, info, **args: 'F1',\n \n 'bestModelModelSelectionMethod': lambda value, info, **args: 'BEST',\n 'kneePointModelSelectionMethod': lambda value, info, **args: 'KNEE_POINT',\n 'oneStdevModelSelectionMethod': lambda value, info, **args: 'ONE_STDEV',\n 'twoStdevModelSelectionMethod': lambda value, info, **args: 'TWO_STDEV',\n \n 'looModelEvaluationType': lambda value, info, **args: 'LEAVE_ONE_OUT',\n 'kFoldsModelEvaluationType': lambda value, info, **args: 'K_FOLDS',\n \n 'noneStopWordType': lambda value, info, **args: 'NONE',\n 'englishStopWordType': lambda value, info, **args: 'ENGLISH',\n },\n 'Object': {\n },\n 'Mutation': {\n },\n 'Scalar': {\n },\n}\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5559776425361633,
"alphanum_fraction": 0.5599873661994934,
"avg_line_length": 24.680217742919922,
"blob_id": "1a951aedfbfda9516e003f2880289d042212a281",
"content_id": "c83c30861e841370b5430f2be21db336c3038a11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9477,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 369,
"path": "/app/logic/helpers.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport pandas as pd\n\nfrom app.core.main.Classifier import Classifier\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\nfrom app.core.main.tokenizer.PorterTokenizer import PorterTokenizer\nfrom app.core.main.tokenizer.LemmaTokenizer import LemmaTokenizer\n\nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\n\nimport uuid\n\n\n\n\n\ndef id():\n return str(uuid.uuid4())\n\n\n\n\n\ndef extract(datasource, fields):\n res = {}\n for fld in fields:\n res.update(datasource[fld])\n return res\n\n\ndef getDataFieldName(feature_type):\n field_name = 'text' # default field name\n\n if feature_type in ('NUMERICAL', 'SET'):\n field_name = feature_type.lower()\n elif feature_type in ('BOOLEAN'):\n field_name = 'numerical'\n\n return field_name\n\n\ndef featureDataToSeries(fd):\n feature_name = fd['feature']['name']\n feature_type = fd['feature']['type']\n data = fd['data']\n\n field_name = getDataFieldName(feature_type)\n rows = [row[field_name] for row in data]\n return pd.Series(rows, name=feature_name)\n\n\ndef datasetToDataframe(ds):\n df = pd.DataFrame()\n\n features = ds['features'] if 'features' in ds else ds['data']['features']\n\n for feature in features:\n df = pd.concat([df, featureDataToSeries(feature)], axis=1)\n\n if 'label' in ds:\n label_series = featureDataToSeries(ds['label'])\n df = pd.concat([df, label_series], axis=1)\n\n return df\n\n\n\ndef inferFeatureType(series):\n if series.dtype in ('int64', 'float64'):\n return 'NUMERICAL'\n\n val = series.values[0]\n\n if type(val) in (list, set, tuple):\n return 'SET'\n \n val = val.lower()\n\n if 'isdigit' in val and val.isdigit():\n return 'NUMERICAL'\n if val in ('true', 'false'):\n return 'BOOLEAN'\n \n return 'TEXT'\n\n\ndef dataframeToDataset(df):\n features = []\n \n for col in df:\n feature_index = df.columns.get_loc(col)\n feature_name = col\n feature_type = inferFeatureType(df[col])\n prop_name = getDataFieldName(feature_type)\n data = [{ 'id': id(),\n prop_name: val } for val in df[col].values]\n\n feature_data = {\n 'id': id(),\n 'feature': {\n 'id': id(),\n 'index': feature_index,\n 'name': feature_name,\n 'type': feature_type\n },\n 'data': data\n }\n\n features.append(feature_data)\n\n ds = {\n 'id': id(),\n 'features': features }\n\n return ds\n\n\n\ndef schema(dataset):\n if 'label' in dataset:\n return [f['feature']['type'] for f in dataset['data']['features']] + ['LABEL']\n else:\n return [f['feature']['type'] for f in dataset['features']]\n\n\n\n\ndef defaultModelConfiguration():\n return {\n 'id': id(),\n \"type\": \"LOGISTIC_REGRESSION\",\n \"weighting\": \"BALANCED\",\n \"tokenizer\": \"WORD_TOKENIZER\",\n \"ngrams\": \"UNIGRAM\",\n \"tf\": \"SUBLINEAR\",\n \"df\": \"SMOOTH\",\n \"penalty\": \"L2\",\n \"multiclass\": \"OVR\",\n \"solver\": \"LIBLINEAR\",\n \"primal_dual\": \"PRIMAL\",\n \"fitIntercept\": True,\n 'max_df': 1.,\n 'min_df': 0.0,\n 'stopwords': \"ENGLISH\",\n 'C': 1.,\n 'max_iter': 2,\n }\n\n\ndef defaultModelSelection():\n return {\n 'id': id(),\n \"metric\": \"PRECISION\",\n \"method\": \"BEST\",\n \"evalMode\": \"K_FOLDS\",\n \"numFolds\": 3\n }\n\n\n\ndef defaultFeaturizers(features):\n feature_types = [f['type'] for f in features]\n featurizer_types = []\n for ft in feature_types:\n if ft in [\"NUMERICAL\", \"BOOLEAN\"]:\n featurizer_types.append(\"NOOP\")\n elif ft in [\"CATEGORICAL\"]:\n featurizer_types.append(\"LABEL_BINARIZER\")\n elif ft in [\"TEXT\"]:\n featurizer_types.append(\"TFIDF_VECTORIZER\")\n elif ft in [\"SET\"]:\n featurizer_types.append(\"MULTILABEL_BINARIZER\")\n elif ft == \"LABEL\":\n featurizer_types.append(\"LABEL\")\n elif ft in [\"LABEL_ENCODER\"]:\n featurizer_types.append(\"LABEL_ENCODER\")\n elif ft in [\"TEXT2VEC\", \"TEXT_TO_VECTOR\"]:\n featurizer_types.append(\"TEXT_TO_VECTOR\")\n\n return featurizer_types\n\n\n\ndef defaultCandidate(labeled_dataset):\n features = defaultFeatures(labeled_dataset)\n return [{\n 'id': id(),\n \"features\": features,\n \"featurizers\": defaultFeaturizers(features=features),\n \"config\": defaultModelConfiguration()\n }]\n\n\n\n\ndef createCandidate(features, featurizers, config):\n return {\n 'id': id(),\n \"features\": features,\n \"featurizers\": featurizers,\n \"config\": config\n }\n\n\n\ndef createTrainingTasks(candidates, training_data, params):\n return [{\n 'id': id(),\n 'candidate': candidate,\n 'data': training_data,\n 'modelSelectionParams': params\n } for candidate in candidates]\n\n\n\n\ndef createFeaturizer(featureType, featurizerType):\n return {\n 'id': id(),\n \"featureType\": featureType,\n \"featurizer\": featurizerType\n }\n\n\n\ndef createModelConfiguration(\n type, weighting, tokenizer, ngrams, tf,\n df, penalty, multiclass, solver, primal_dual,\n fitIntercept, max_df, min_df, stopwords, C=1, max_iter=2\n):\n return {\n 'id': id(),\n \"type\": type,\n \"weighting\": weighting,\n \"tokenizer\": tokenizer,\n \"ngrams\": ngrams,\n \"tf\": tf,\n \"df\": df,\n \"penalty\": penalty,\n \"multiclass\": multiclass,\n \"solver\": solver,\n \"primal_dual\": primal_dual,\n \"fitIntercept\": fitIntercept,\n \"max_df\": max_df,\n \"min_df\": min_df,\n \"stopwords\": stopwords,\n \"C\": C,\n \"max_iter\": max_iter\n }\n\n\ndef createModelSelection(metric, method, evalMode, numFolds):\n return {\n 'id': id(),\n \"metric\": metric,\n \"method\": method,\n \"evalMode\": evalMode,\n \"numFolds\": numFolds\n }\n\n\ndef defaultFeatures(dataset):\n if 'label' in dataset:\n feature_data = dataset['data']['features'] + [dataset['label']]\n else:\n feature_data = dataset['features']\n features = [ feat_dat['feature'] for feat_dat in feature_data]\n\n return features\n\n\ndef subsetFeatures(dataset, selectedFeatures):\n allFeatures = defaultFeatures(dataset)\n return [allFeatures[i] for i in selectedFeatures]\n\n\n\n\n\n\ndef create_classifier(config):\n\n return Classifier(model_configuration={\n 'id': id(),\n \"type\": config[\"type\"],\n \"class_weight\": None if config['weighting'].lower() == 'none' else config['weighting'].lower(),\n \"tokenizer\": BaseTokenizer() if config[\"tokenizer\"] == \"WORD_TOKENIZER\" \\\n else PorterTokenizer() if config[\"tokenizer\"] == \"STEMMER\" \\\n else LemmaTokenizer() if config[\"tokenizer\"] == \"LEMMATIZER\" \\\n else None,\n \"ngram_range\": (1, 1) if config[\"ngrams\"] == \"UNIGRAM\" \\\n else (2, 2) if config[\"ngrams\"] == \"BIGRAM\" \\\n else (1, 2) if config[\"ngrams\"] == \"BOTH\" \\\n else None,\n \"sublinear_tf\": config[\"tf\"] == \"SUBLINEAR\",\n \"smooth_idf\": config[\"df\"] == \"SMOOTH\",\n \"penalty\": config['penalty'].lower(),\n \"multi_class\": config['multiclass'].lower(),\n \"solver\": config['solver'].lower(),\n \"dual\": config['primal_dual']=='DUAL',\n \"fit_intercept\": config['fitIntercept'],\n 'max_df': config['max_df'],\n 'min_df': config['min_df'],\n 'stopwords': ENGLISH_STOP_WORDS if config[\"stopwords\"] == \"ENGLISH\" else [],\n 'C': config['C'],\n 'max_iter': config['max_iter']\n })\n\n\n\ndef addToList(addThis, toThis):\n if toThis is None:\n return [addThis]\n else:\n toThis.append(addThis)\n return toThis\n\n\n\ndef mergeDatasets(datasets):\n if len(datasets) == 0:\n return {\n 'id': -1,\n 'features': []\n }\n\n featureData = {}\n nonEmptyDSIdx = 0\n #merge by feature name, as feature IDs are randomized\n for dsidx, ds in enumerate(datasets):\n if len(ds['features']) > 0 and len(ds['features'][0]['data']) > 0:\n nonEmptyDSIdx = dsidx\n for featData in ds['features']:\n if featData['feature']['name'] not in featureData:\n featureData[featData['feature']['name']] = featData\n else:\n featureData[featData['feature']['name']]['data'] += featData['data']\n return {\n 'id': datasets[nonEmptyDSIdx]['id'],\n 'features': featureData.values()\n }\n\n\ndef mergeLabeledDatasets(labeledDatasets):\n if len(labeledDatasets) == 0:\n return {\n 'id': -1,\n 'data': {'id': -1, 'features': []},\n 'label': { 'id': -1, 'feature': {'id': -1, 'index': -1, 'name': '', 'type': ''}, 'data': []}\n }\n\n datasets = [lds['data'] for lds in labeledDatasets]\n dataset = mergeDatasets(datasets)\n\n allLabels = []\n nonEmptyLdsIdx = 0\n for ldsIdx, lds in enumerate(labeledDatasets):\n lbls = lds['label']['data']\n if len(lbls) > 0:\n allLabels += lbls\n nonEmptyLdsIdx = ldsIdx\n return {\n 'id': dataset['id'],\n 'data': dataset,\n 'label': {\n 'id':labeledDatasets[nonEmptyLdsIdx]['label']['id'],\n 'feature': labeledDatasets[nonEmptyLdsIdx]['label']['feature'],\n 'data': allLabels\n }\n }\n"
},
{
"alpha_fraction": 0.5780346989631653,
"alphanum_fraction": 0.5780346989631653,
"avg_line_length": 14.772727012634277,
"blob_id": "29de34ad3bc42d32e78504c6644962589d68f827",
"content_id": "753a8530527700b4e3015ba9f360d7f5cad16da2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 346,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 22,
"path": "/app/core/main/tokenizer/BaseTokenizer.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nBase Tokenizer\n'''\n\nfrom nltk import word_tokenize\n\n\nclass BaseTokenizer(object):\n\n def __init__(self):\n pass\n\n def __call__(self, doc):\n return self.tokenize(doc)\n\n def tokenize(self, doc):\n tokens = [t for t in word_tokenize(doc)]\n return tokens\n\n\n def __str__(self):\n return 'Base tokenizer.'"
},
{
"alpha_fraction": 0.6310344934463501,
"alphanum_fraction": 0.6310344934463501,
"avg_line_length": 22.239999771118164,
"blob_id": "11092d559d76538d55e2ae5f71b7da7430f8e8d2",
"content_id": "1cf6cd6efa4112ff6934eadd78bcd7783422a8d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 580,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 25,
"path": "/app/core/main/tokenizer/LemmaTokenizer.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nWordNet Lemmatizer\n'''\nfrom nltk.stem import WordNetLemmatizer\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\n\nclass LemmaTokenizer(object):\n def __init__(self):\n self.__wnl = WordNetLemmatizer()\n self.__basetokenizer = BaseTokenizer()\n\n\n def __call__(self, doc):\n return self.tokenize(doc)\n\n\n def tokenize(self, doc):\n return [self.__wnl.lemmatize(t) for t in self.__basetokenizer.tokenize(doc)]\n\n\n def __str__(self):\n return '''\n WordNet Lemmatizer based on\n %s\n ''' % self.__basetokenizer"
},
{
"alpha_fraction": 0.5532660484313965,
"alphanum_fraction": 0.5576114654541016,
"avg_line_length": 30.56637191772461,
"blob_id": "2f7fb5ba74e40fe4cd06561dcaaeceff2bfa8608",
"content_id": "cb74bba2601d1ed42366e66e502379829652bc73",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7134,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 226,
"path": "/app/core/main/classifier/Ensemble.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nEnsemble model\n'''\nimport numpy as np\nimport copy\n\n\nclass Ensemble(object):\n\n def __init__(self, base_model, group_index):\n self.__base_model = base_model\n self.__group_index = group_index\n self.__models = []\n self.__labels = []\n self.__num_features = 0\n\n #required by backward feature selection\n self.coef_ = None\n\n\n\n def fit(self, _X, _Y):\n X = np.asarray(_X)\n Y = np.asarray(_Y)\n\n self.__num_features = len(X[0]) - 1 #excl group\n assert self.__group_index < self.__num_features + 1\n\n self.__labels = sorted(set(Y))\n\n featureIndices = list(range(self.__num_features + 1))\n featureIdxWoGrp = featureIndices[:self.__group_index] + featureIndices[self.__group_index+1:]\n\n self.__models = []\n groups = set(X[:, self.__group_index].tolist())\n assert len(groups) > 1\n\n for grp in groups:\n Xp = X[X[:, self.__group_index] != grp]\n Xpp = Xp[:, featureIdxWoGrp]\n Yp = Y[X[:, self.__group_index] != grp]\n\n numUniqueLabels = len(set(list(Yp)))\n if numUniqueLabels > 1:\n print('Train a model with ', Xpp.shape, ' data and ', len(Yp), ' labels.')\n m = copy.deepcopy(self.__base_model)\n m.fit(Xpp, Yp)\n self.__models.append(m)\n else:\n print('Skip a model of single label: ', set(list(Yp)), ', e.g ignoring ', len(Yp), ' data points.')\n\n print('Total ', len(self.__models), ' models trained and saved.')\n\n #required by backward feature selection\n self.coef_ = self.get_all_weights()\n\n\n\n def predict(self, _X):\n X = np.asarray(_X)\n\n featureIndices = list(range(self.__num_features + 1))\n featureIdxWoGrp = featureIndices[:self.__group_index] + featureIndices[self.__group_index+1:]\n Xp = X[:, featureIdxWoGrp]\n\n all_predictions = []\n assert(len(self.__models) > 0)\n\n for m in self.__models:\n all_predictions.append(m.predict(Xp))\n all_predictions = np.array(all_predictions).transpose()\n\n #count votes by rows, tie-break arbitrarily\n return np.apply_along_axis(lambda votes: np.argmax(np.bincount(votes)), 1, all_predictions)\n\n\n #\n #\n # Probability = number of votes (of sub-models)/ number of sub-models.\n # (a vote of 51% has same contribution as a vote of 99%)\n #\n #\n # def predict_proba(self, _X):\n # X = np.asarray(_X)\n #\n # featureIndices = list(range(self.__num_features + 1))\n # featureIdxWoGrp = featureIndices[:self.__group_index] + featureIndices[self.__group_index+1:]\n # Xp = X[:, featureIdxWoGrp]\n #\n # all_predictions = []\n # assert(len(self.__models) > 0)\n #\n # for m in self.__models:\n # all_predictions.append(m.predict(Xp))\n # all_predictions = np.array(all_predictions).transpose()\n #\n # num_classes = self.num_classes()\n # probs = np.apply_along_axis(lambda votes: np.bincount(votes, minlength=num_classes)/sum(np.bincount(votes)),\n # 1, all_predictions)\n #\n # return probs\n\n\n #\n #\n # Returns average probabilities of sub-models\n #\n #\n def predict_proba(self, _X):\n X = np.asarray(_X)\n\n featureIndices = list(range(self.__num_features + 1))\n featureIdxWoGrp = featureIndices[:self.__group_index] + featureIndices[self.__group_index+1:]\n Xp = X[:, featureIdxWoGrp]\n all_labels = self.labels()\n\n all_predictions = []\n assert(len(self.__models) > 0)\n\n for m in self.__models:\n probs = m.predict_proba(Xp)\n full_probs = np.zeros((len(Xp), len(all_labels)))\n m_labels = m.labels()\n for clsidx, clsprob in enumerate(probs.transpose()):\n full_probs[:, all_labels.index(m_labels[clsidx])] = clsprob\n all_predictions.append(full_probs)\n\n preds = np.array(sum(all_predictions)/len(all_predictions))\n\n return preds\n\n\n\n def get_weights(self, class_no):\n return self.get_all_weights()[class_no]\n\n\n\n def get_intercepts(self):\n assert len(self.__models) > 0\n num_classes = self.num_classes()\n\n all_models_intercepts = []\n for m in self.__models:\n m_labels = m.labels()\n m_intercepts = np.asarray(m.get_intercepts())\n full_intercepts = np.zeros((num_classes, ))\n\n for idx, intercept in enumerate(m_intercepts):\n full_intercepts[self.__labels.index(m_labels[idx])] = intercept\n\n all_models_intercepts.append(full_intercepts)\n\n assert len(all_models_intercepts) > 0\n return sum(np.array(all_models_intercepts))/len(all_models_intercepts)\n\n\n #OVR should be used\n def get_all_weights(self):\n assert len(self.__models) > 0\n num_classes = self.num_classes()\n all_models_weights = []\n for m in self.__models:\n m_labels = m.labels()\n m_weights = np.asarray(m.get_all_weights())\n full_weights = np.zeros((num_classes, self.__num_features))\n for idx, weights in enumerate(m_weights):\n full_weights[self.__labels.index(m_labels[idx])] = weights\n\n all_models_weights.append(full_weights)\n\n assert len(all_models_weights) > 0\n return sum(np.array(all_models_weights))/len(all_models_weights)\n\n\n\n def get_params(self, deep = True):\n params = {\n 'base_model': self.__base_model,\n 'group_index': int(self.__group_index),\n }\n\n #available only after trained\n if len(self.__models) > 0:\n all_models_params = []\n for m in self.__models:\n all_models_params.append(m.get_params())\n params.update({'all_models_params': all_models_params})\n params.update({'labels': [int(lbl) for lbl in self.__labels]})\n params.update({'num_features': int(self.__num_features)})\n params.update({'coef_': self.coef_.tolist()})\n params.update({'base_model': self.__base_model.get_params()})\n\n return params\n\n\n\n def set_params(self, **params):\n if 'group_index' in params:\n self.__group_index = int(params['group_index'])\n self.__models = []\n for m_params in params['all_models_params']:\n m = copy.deepcopy(self.__base_model)\n m.set_params(**m_params)\n self.__models.append(m)\n self.__labels = params['labels']\n self.__num_features = int(params['num_features'])\n self.coef_ = np.asarray(params['coef_'], dtype=np.float64)\n return\n\n\n def labels(self):\n return self.__labels\n\n\n def num_classes(self):\n return len(self.labels())\n\n\n def num_weights(self):\n all_weights = self.get_all_weights()\n return len(all_weights[0])\n\n\n def __str__(self):\n return 'Ensemble Classification based on ' + str(self.__base_model)\n"
},
{
"alpha_fraction": 0.5434978604316711,
"alphanum_fraction": 0.5505864024162292,
"avg_line_length": 39.6230354309082,
"blob_id": "fe6e498b069470bec3e20b0743b3433864e94dd1",
"content_id": "a67986b0ae2cd1f75802fd62403f859b2b2faf0e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7759,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 191,
"path": "/app/core/main/classifier/LSVC.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nSVM\n'''\nfrom sklearn.svm import SVC\nimport numpy as np\n\n\n\nclass LSVC(object):\n\n def __init__(self, class_weighting='balanced', C=1.0, max_iter=2):\n self.__class_weight = class_weighting\n self.__C = C\n self.__kernel = 'linear'\n self.__probability = True\n self.__decision_func_shape = 'ovr'\n self.__max_iter=max_iter\n\n #required by backward feature selection\n self.coef_ = None\n\n #probability must set to True in order to call predict_proba\n self.__model = SVC(class_weight=self.__class_weight, kernel=self.__kernel, C=self.__C,\n probability=self.__probability, decision_function_shape = self.__decision_func_shape,\n max_iter=self.__max_iter, random_state=1078)\n\n\n\n def fit(self, X, Y):\n self.__model.fit(X, Y)\n #required by backward feature selection, only available for linear kernel\n self.coef_ = self.get_all_weights()\n\n\n def predict(self, X):\n return self.__model.predict(X)\n\n\n def predict_proba(self, X):\n return self.__model.predict_proba(X)\n\n\n def get_weights(self, class_no):\n return self.get_all_weights()[class_no]\n\n\n #even if OVR is used the intercept_ are still results of OVO\n #return avg OVO intercepts as OVR intercepts - for information only, e.g. intercepts should not be used to make prediction\n def get_intercepts(self):\n num_classes = len(self.__model.classes_)\n if num_classes > 2:\n all_classes_avg_intercept_ = []\n running_seq = 0\n for clsidx in range(num_classes):\n if clsidx == 0:\n this_class_avg_intercept_ = []\n else:\n this_class_avg_intercept_ = [intercepts for intercepts in self.__model.intercept_[0:clsidx]]\n for other_clsidx in range(clsidx+1, num_classes):\n this_class_avg_intercept_.append(self.__model.intercept_[running_seq])\n running_seq += 1\n this_class_avg_intercept_ = sum(np.array(this_class_avg_intercept_))/(num_classes-1)\n all_classes_avg_intercept_.append(this_class_avg_intercept_)\n return np.array(all_classes_avg_intercept_)\n else:\n return np.array([self.__model.intercept_[0], self.__model.intercept_[0]])\n\n\n #even if OVR is used the coef_ are still results of OVO\n #return avg OVO weights as OVR weights - for information only, e.g. weights should not be used to make prediction\n def get_all_weights(self):\n num_classes = len(self.__model.classes_)\n if num_classes > 2:\n all_classes_avg_coef_ = []\n running_seq = 0\n for clsidx in range(num_classes):\n if clsidx == 0:\n this_class_avg_coef_ = []\n else:\n this_class_avg_coef_ = [weights for weights in self.__model.coef_[0:clsidx]]\n for other_clsidx in range(clsidx+1, num_classes):\n this_class_avg_coef_.append(self.__model.coef_[running_seq])\n running_seq += 1\n this_class_avg_coef_ = sum(np.array(this_class_avg_coef_))/(num_classes-1)\n all_classes_avg_coef_.append(this_class_avg_coef_)\n return np.array(all_classes_avg_coef_)\n else:\n return np.array([self.__model.coef_[0], self.__model.coef_[0]])\n\n\n def get_params(self, deep = True):\n params = {\n 'C': self.__C,\n 'class_weighting': self.__class_weight,\n 'max_iter': self.__max_iter,\n }\n\n #only available after trained\n if hasattr(self.__model, \"support_\"):\n params.update({\n 'support': self.__model.support_.tolist(),\n 'support_vectors': self.__model.support_vectors_.tolist(),\n 'n_support': self.__model.n_support_.tolist(),\n 'dual_coef': self.__model.dual_coef_.tolist(),\n '_dual_coef': self.__model._dual_coef_.tolist(),\n #'coef': self.__model.coef_.tolist(),\n 'intercept': self.__model.intercept_.tolist(),\n '_intercept': self.__model._intercept_.tolist(),\n 'fit_status': self.__model.fit_status_,\n 'classes': self.__model.classes_.tolist(),\n 'probA': self.__model.probA_.tolist(),\n 'probB': self.__model.probB_.tolist(),\n 'class_weight': self.__model.class_weight_.tolist(),\n 'shape_fit': self.__model.shape_fit_,\n 'sparse': self.__model._sparse,\n 'gamma': self.__model._gamma,\n 'degree': self.__model.degree,\n 'coef0': self.__model.coef0,\n 'kernel': self.__model.kernel,\n 'impl': self.__model._impl\n })\n return params\n\n\n\n def set_params(self, **params):\n if 'C' in params:\n self.__C = float(params['C'])\n if 'max_iter' in params:\n self.__max_iter = int(params['max_iter'])\n if 'support' in params:\n self.__model.support_ = np.asarray(params['support'], dtype=np.int32)\n if 'support_vectors' in params:\n self.__model.support_vectors_ = np.asarray(params['support_vectors'], dtype=np.float64)\n if 'n_support' in params:\n self.__model.n_support_ = np.asarray(params['n_support'], dtype=np.int32)\n if 'dual_coef' in params:\n self.__model.dual_coef_ = np.asarray(params['dual_coef'], dtype=np.float64)\n if '_dual_coef' in params:\n self.__model._dual_coef_ = np.asarray(params['_dual_coef'], dtype=np.float64)\n # if 'coef' in params: #coef is readonly\n # self.__model.coef_ = params['coef']\n if 'intercept' in params:\n self.__model.intercept_ = np.asarray(params['intercept'], dtype=np.float64)\n if '_intercept' in params:\n self.__model._intercept_ = np.asarray(params['_intercept'], dtype=np.float64)\n if 'fit_status' in params:\n self.__model.fit_status_ = int(params['fit_status'])\n if 'classes' in params:\n self.__model.classes_ = np.asarray(params['classes'], dtype=np.int32)\n if 'probA' in params:\n self.__model.probA_ = np.asarray(params['probA'], dtype=np.float64)\n if 'probB' in params:\n self.__model.probB_ = np.asarray(params['probB'], dtype=np.float64)\n if 'class_weight' in params:\n self.__model.class_weight_ = np.asarray(params['class_weight'], dtype=np.float64)\n if 'class_weighting' in params:\n self.__class_weight = params['class_weighting']\n if 'shape_fit' in params:\n self.__model.shape_fit_ = np.asarray(params['shape_fit'], dtype=np.int32)\n if 'sparse' in params:\n self.__model._sparse = bool(params['sparse'])\n if 'gamma' in params:\n self.__model._gamma = float(params['gamma'])\n if 'degree' in params:\n self.__model.degree = float(params['degree'])\n if 'coef0' in params:\n self.__model.coef0 = float(params['coef0'])\n if 'kernel' in params:\n self.__model.kernel = params['kernel']\n if 'impl' in params:\n self.__model._impl = params['impl']\n\n return\n\n\n def labels(self):\n return self.__model.classes_\n\n\n def num_classes(self):\n return len(self.__model.classes_)\n\n\n def num_weights(self):\n all_weights = self.get_all_weights()\n return len(all_weights[0])\n\n\n def __str__(self):\n return 'Linear Support Vector Classification.'\n"
},
{
"alpha_fraction": 0.6314007639884949,
"alphanum_fraction": 0.6385949850082397,
"avg_line_length": 45.26506042480469,
"blob_id": "3045b7ed951968982b547346ad5afc50fcb61292",
"content_id": "0a9cb9a43383e02f60882ec4957cc2b818c60232",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 30721,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 664,
"path": "/app/core/test/Classifier.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "# coding: utf-8\nimport sys\nimport unittest\nimport pandas as pd\nimport random as rd\n\nfrom app.core.main.classifier.LR import LR\nfrom app.core.main.classifier.LSVC import LSVC\nfrom app.core.main.classifier.Ensemble import Ensemble\nfrom app.core.main.featurizer.Featurizer import Featurizer\n\n\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\nfrom sklearn.feature_extraction import stop_words\n\nfrom app.core.main.Classifier import Classifier\n\nlrModelConfiguration = {\n \"type\": \"LOGISTIC_REGRESSION\",\n \"class_weight\": \"balanced\",\n \"tokenizer\": BaseTokenizer(),\n \"ngram_range\": (1, 1),\n \"sublinear_tf\": True,\n \"smooth_idf\": True,\n \"penalty\": \"l2\",\n \"multi_class\": \"ovr\",\n \"solver\": \"liblinear\",\n \"dual\": True,\n \"fit_intercept\": True,\n 'max_df': 1.,\n 'min_df': 0.,\n 'stopwords': stop_words.ENGLISH_STOP_WORDS,\n 'C': 1.,\n 'max_iter': 1000,\n}\n\nlsvcModelConfiguration = {\n \"type\": \"LINEAR_SVC\",\n \"class_weight\": \"balanced\",\n \"tokenizer\": BaseTokenizer(),\n \"ngram_range\": (1, 1),\n \"sublinear_tf\": True,\n \"smooth_idf\": True,\n \"penalty\": \"l2\",\n \"multi_class\": \"ovr\",\n \"solver\": \"liblinear\",\n \"dual\": True,\n \"fit_intercept\": True,\n 'max_df': 1.,\n 'min_df': 0.,\n 'stopwords': stop_words.ENGLISH_STOP_WORDS,\n 'C': 10.,\n 'max_iter': 1000,\n}\n\n\nensembleSvcModelConfiguration = {\n \"type\": \"ENSEMBLE_LINEAR_SVC\",\n \"class_weight\": \"balanced\",\n \"tokenizer\": BaseTokenizer(),\n \"ngram_range\": (1, 1),\n \"sublinear_tf\": True,\n \"smooth_idf\": True,\n \"penalty\": \"l2\",\n \"multi_class\": \"ovr\",\n \"solver\": \"liblinear\",\n \"dual\": True,\n \"fit_intercept\": True,\n 'max_df': 1.,\n 'min_df': 0.,\n 'stopwords': stop_words.ENGLISH_STOP_WORDS,\n 'C': 10.,\n 'max_iter': 1000,\n}\n\nensembleLRModelConfiguration = {\n \"type\": \"ENSEMBLE_LOGISTIC_REGRESSION\",\n \"class_weight\": \"balanced\",\n \"tokenizer\": BaseTokenizer(),\n \"ngram_range\": (1, 1),\n \"sublinear_tf\": True,\n \"smooth_idf\": True,\n \"penalty\": \"l2\",\n \"multi_class\": \"ovr\",\n \"solver\": \"liblinear\",\n \"dual\": True,\n \"fit_intercept\": True,\n 'max_df': 1.,\n 'min_df': 0.,\n 'stopwords': stop_words.ENGLISH_STOP_WORDS,\n 'C': 1.,\n 'max_iter': 1000,\n}\n\n\nmodelConfigurations = [lrModelConfiguration, lsvcModelConfiguration, ensembleLRModelConfiguration, ensembleSvcModelConfiguration]\n\ntestModelConfiguration = None\n\n\nclass FunctionalityTest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n\n cls.test_data_fn_prefix = \"test_data\"\n cls.inp_avro_file_with_label = cls.test_data_fn_prefix + \".avro\"\n cls.binary_inp_avro_file_with_label = cls.test_data_fn_prefix + \".two_classes.avro\"\n cls.inp_avro_file_without_label = cls.test_data_fn_prefix + \".nolabel.avro\"\n cls.out_avro_file = cls.test_data_fn_prefix + \".out.avro\"\n cls.model_avro_file = cls.test_data_fn_prefix + \".model.out.avro\"\n\n cls.schema_with_label = [\"NUMERICAL\", \"NUMERICAL\", \"CATEGORICAL\", \"BOOLEAN\", \"TEXT\", \"TEXT2VEC\", \"SET\", \"LABEL\"]\n #for correlation feature ranking test, remove text2vec as it produces negative values, which is prohibited\n #by chisquare ranking.\n cls.schema_with_label_nonnegative = [\"NUMERICAL\", \"NUMERICAL\", \"CATEGORICAL\", \"BOOLEAN\", \"TEXT\", \"TEXT\", \"SET\", \"LABEL\"]\n cls.schema_without_label = [\"NUMERICAL\", \"NUMERICAL\", \"CATEGORICAL\", \"BOOLEAN\", \"TEXT\", \"TEXT2VEC\", \"SET\"]\n\n cls.fields_with_label = [\"TRAIN_GROUP\", \"num_field\", \"cat_field\", \"bool_field\", \"text_field\", \"txt2vec_field\", \"set_field\",\n \"label_field\"]\n cls.fields_without_label = cls.fields_with_label[:-1]\n\n cls.num_recs = 150\n cls.num_models_for_ensemble = 8\n cls.categories = [\"Oil and Gas\", \"Automobile\", \"Software\", \"Retail\", \"Health Care\", \"Finance\", \"Construction\",\n \"Agriculture\"]\n cls.labels = [\"a posteriori\", \"acta non verba\", \"alea iacta est\", \"amor patriae\", \"alma mater\"]\n cls.binary_labels = [\"verum\", \"falsus\"]\n\n words = '''\n The distribution of oil and gas reserves among the world's 50 largest oil companies. The reserves of the privately\n owned companies are grouped together. The oil produced by the \"supermajor\" companies accounts for less than 15% of\n the total world supply. Over 80% of the world's reserves of oil and natural gas are controlled by national oil companies.\n Of the world's 20 largest oil companies, 15 are state-owned oil companies.\n The petroleum industry, also known as the oil industry or the oil patch, includes the global processes of exploration,\n extraction, refining, transporting (often by oil tankers and pipelines), and marketing of petroleum products.\n The largest volume products of the industry are fuel oil and gasoline (petrol). Petroleum (oil) is also the raw material\n for many chemical products, including pharmaceuticals, solvents, fertilizers, pesticides, synthetic fragrances, and plastics.\n The industry is usually divided into three major components: upstream, midstream and downstream. Midstream operations are\n often included in the downstream category.\n Petroleum is vital to many industries, and is of importance to the maintenance of industrial civilization in its\n current configuration, and thus is a critical concern for many nations. Oil accounts for a large percentage of the\n world’s energy consumption, ranging from a low of 32% for Europe and Asia, to a high of 53% for the Middle East.\n Governments such as the United States government provide a heavy public subsidy to petroleum companies, with major\n tax breaks at virtually every stage of oil exploration and extraction, including the costs of oil field leases and\n drilling equipment.[2]\n Principle is a term defined current-day by Merriam-Webster[5] as: \"a comprehensive and fundamental law, doctrine,\n or assumption\", \"a primary source\", \"the laws or facts of nature underlying the working of an artificial device\",\n \"an ingredient (such as a chemical) that exhibits or imparts a characteristic quality\".[6]\n Process is a term defined current-day by the United States Patent Laws (United States Code Title 34 - Patents)[7]\n published by the United States Patent and Trade Office (USPTO)[8] as follows: \"The term 'process' means process,\n art, or method, and includes a new use of a known process, machine, manufacture, composition of matter, or material.\"[9]\n Application of Science is a term defined current-day by the United States' National Academies of Sciences, Engineering,\n and Medicine[12] as: \"...any use of scientific knowledge for a specific purpose, whether to do more science; to design\n a product, process, or medical treatment; to develop a new technology; or to predict the impacts of human actions.\"[13]\n The simplest form of technology is the development and use of basic tools. The prehistoric discovery of how to control\n fire and the later Neolithic Revolution increased the available sources of food, and the invention of the wheel\n helped humans to travel in and control their environment. Developments in historic times, including the printing\n press, the telephone, and the Internet, have lessened physical barriers to communication and allowed humans to\n interact freely on a global scale.\n Technology has many effects. It has helped develop more advanced economies (including today's global economy)\n and has allowed the rise of a leisure class. Many technological processes produce unwanted by-products known as\n pollution and deplete natural resources to the detriment of Earth's environment. Innovations have always influenced\n the values of a society and raised new questions of the ethics of technology. Examples include the rise of the\n notion of efficiency in terms of human productivity, and the challenges of bioethics.\n Philosophical debates have arisen over the use of technology, with disagreements over whether technology improves\n the human condition or worsens it. Neo-Luddism, anarcho-primitivism, and similar reactionary movements criticize\n the pervasiveness of technology, arguing that it harms the environment and alienates people; proponents of ideologies\n such as transhumanism and techno-progressivism view continued technological progress as beneficial to society and\n the human condition.\n Health care or healthcare is the maintenance or improvement of health via the prevention, diagnosis, and treatment\n of disease, illness, injury, and other physical and mental impairments in human beings. Healthcare is delivered by\n health professionals (providers or practitioners) in allied health fields. Physicians and physician associates are\n a part of these health professionals. Dentistry, midwifery, nursing, medicine, optometry, audiology, pharmacy,\n psychology, occupational therapy, physical therapy and other health professions are all part of healthcare. It\n includes work done in providing primary care, secondary care, and tertiary care, as well as in public health.\n Access to health care may vary across countries, communities, and individuals, largely influenced by social and\n economic conditions as well as the health policies in place. Countries and jurisdictions have different policies\n and plans in relation to the personal and population-based health care goals within their societies. Healthcare\n systems are organizations established to meet the health needs of targeted populations. Their exact configuration\n varies between national and subnational entities. In some countries and jurisdictions, health care planning is\n distributed among market participants, whereas in others, planning occurs more centrally among governments or\n other coordinating bodies. In all cases, according to the World Health Organization (WHO), a well-functioning\n healthcare system requires a robust financing mechanism; a well-trained and adequately paid workforce; reliable\n information on which to base decisions and policies; and well maintained health facilities and logistics to deliver\n quality medicines and technologies.[1]\n Health care is conventionally regarded as an important determinant in promoting the general physical and mental\n health and well-being of people around the world. An example of this was the worldwide eradication of smallpox\n in 1980, declared by the WHO as the first disease in human history to be completely eliminated by deliberate health\n care interventions.[4]\n '''.split()\n\n truth = [\"true\", \"false\"]\n\n set_base = [\"bona fide\", \"bono malum superate\", \"carpe diem\", \"caveat emptor\", \"circa\", \"citius altius fortius\",\n \"corpus christi\", \"curriculum vitae\", \"de facto\", \"discendo discimus\", \"emeritus\", \"ex animo\",\n \"fortis in arduis\", \"labor omnia vincit\", \"magnum opus\", \"persona non grata\", \"vivere militare est\"]\n\n set_size = list(map(lambda _: rd.randint(int(len(set_base)/10), int(len(set_base)/2)), range(cls.num_recs)))\n set_field = list(map(lambda n: set(map(lambda _: set_base[rd.randint(0, len(set_base)-1)], range(n))), set_size))\n\n #chisquare feature ranking requires non-negative values\n train_group_field = list(map(lambda _ : str(rd.randint(1, cls.num_models_for_ensemble)), range(cls.num_recs)))\n numeric_field = list(map(lambda _ : rd.random() * rd.randint(0, 100), range(cls.num_recs)))\n categorical_field = list(map(lambda _: cls.categories[rd.randint(0, len(cls.categories)-1)], range(cls.num_recs)))\n boolean_field = list(map(lambda _: truth[rd.randint(0, 1)], range(cls.num_recs)))\n label_field = list(map(lambda _: cls.labels[rd.randint(0, len(cls.labels)-1)], range(cls.num_recs)))\n binary_label_field = list(map(lambda _: cls.binary_labels[rd.randint(0, len(cls.binary_labels)-1)], range(cls.num_recs)))\n\n\n text_size = list(map(lambda _: rd.randint(int(len(words)/10), int(len(words)/2)), range(cls.num_recs)))\n text_field1 = list(map(lambda n: ' '.join(map(lambda _: words[rd.randint(0, len(words)-1)], range(n))), text_size))\n text_size = list(map(lambda _: rd.randint(int(len(words)/10), int(len(words)/2)), range(cls.num_recs)))\n text_field2 = list(map(lambda n: ' '.join(map(lambda _: words[rd.randint(0, len(words)-1)], range(n))), text_size))\n\n cls.labeled_inp_df = pd.DataFrame(zip(train_group_field, numeric_field, categorical_field, boolean_field, text_field1, text_field2,\n set_field, label_field),\n columns=cls.fields_with_label)\n\n cls.nonlabeled_inp_df = pd.DataFrame(zip(train_group_field, numeric_field, categorical_field, boolean_field, text_field1, text_field2,\n set_field),\n columns=cls.fields_without_label)\n\n cls.labeled_binary_inp_df = pd.DataFrame(zip(train_group_field, numeric_field, categorical_field, boolean_field, text_field1, text_field2,\n set_field, binary_label_field),\n columns=cls.fields_with_label)\n\n\n\n\n\n def test_correlation_feature_selection(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label_nonnegative = self.schema_with_label_nonnegative.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n res_df = ac.feature_ranking(input_df=__labeled_inp_df, schema=__schema_with_label_nonnegative,\n mode=Classifier.CC_fs_correlation)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), 2)\n self.assertEqual(res_df.dtypes[0], \"object\")\n self.assertIn(res_df.dtypes[1], [\"int64\", \"float64\" ])\n\n\n\n\n def test_backward_feature_selection(self):\n if testModelConfiguration['type'] in [Classifier.ENSEMBLE_SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE]:\n return\n\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n res_df = ac.feature_ranking(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode=Classifier.CC_fs_backward)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), 2)\n self.assertEqual(res_df.dtypes[0], \"object\")\n self.assertIn(res_df.dtypes[1], [\"int64\", \"float64\" ])\n\n\n\n\n\n def test_training(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n self.assertTrue(isinstance(lr, LR) or isinstance(lr, LSVC) or isinstance(lr, Ensemble))\n self.assertTrue(isinstance(fm, Featurizer))\n self.assertTrue(isinstance(lm, Featurizer))\n\n\n\n\n\n def test_predict_proba(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __nonlabeled_inp_df = self.nonlabeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.load_models(lr, fm, lm)\n\n for multilbl_pred in [True, False]:\n res_df = ac.predict_proba(input_df=__nonlabeled_inp_df, multilabel_pred=multilbl_pred)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), len(self.fields_without_label) + 3)\n self.assertEqual(res_df.dtypes[-1], \"float64\")\n self.assertEqual(res_df.dtypes[-2], \"object\")\n self.assertEqual(res_df.dtypes[-3], \"object\")\n self.assertEqual(len(res_df), self.num_recs)\n\n if not multilbl_pred:\n self.assertFalse(any(list(map(lambda x: x[0] not in self.labels, res_df.filter([res_df.columns[-3]]).values))))\n else:\n list_lbls = list(map(lambda lbls: lbls[0].split(\",\"), res_df.filter([res_df.columns[-3]]).values))\n list_valid_lbls = list(map(lambda lbls: map(lambda lbl: lbl not in self.labels, lbls), list_lbls))\n self.assertFalse(any(list(map(any, list_valid_lbls))))\n\n #Test if probabilities sum-up to 1\n prob_str = list(map(lambda p_str: p_str.split(','), res_df[\"Probabilities\"].values))\n prob_float = list(map(lambda prob_with_label: [float(p.split(':')[1]) for p in prob_with_label], prob_str))\n\n self.assertFalse(any(list(map(lambda probs: sum(probs) >= 1.0 + 0.005 * len(self.fields_without_label) \\\n or sum(probs) <= 1.0 - 0.005 * len(self.fields_without_label), prob_float))))\n\n\n\n\n\n def test_learn(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __nonlabeled_inp_df = self.nonlabeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.load_models(lr, fm, lm)\n\n res_df = ac.learn(input_df=__nonlabeled_inp_df)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), len(self.fields_without_label) + 3)\n self.assertEqual(res_df.dtypes[-1], \"float64\")\n\n\n\n\n def test_input_qlty(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __nonlabeled_inp_df = self.nonlabeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n ac.train(input_df=__labeled_binary_inp_df, schema=__schema_with_label)\n else:\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.load_models(lr, fm, lm)\n\n res_df = ac.input_qlty(input_df=__nonlabeled_inp_df)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), len(self.fields_without_label) + 2)\n self.assertEqual(res_df.dtypes[-1], \"object\")\n self.assertEqual(res_df.dtypes[-2], \"object\")\n self.assertFalse(any(list(map(lambda x: x not in [\"Good\", \"Bad\", \"OK\"], res_df.filter([res_df.columns[-2]]).values))))\n\n #Test if all suggested features are not present\n def chk_feature_nonexistance(row):\n suggested_features = row[\"SuggestedFeatures\"].split(',')\n for feat in suggested_features:\n if '::' in feat:\n field_name, field_value = feat.split('::')\n self.assertIn(field_name, self.fields_without_label)\n fld_no = list(res_df.columns).index(field_name)\n if self.schema_without_label[fld_no] in [\"text\", \"text2vec\"]:\n self.assertNotIn(' ' + field_value + ' ', row[field_name].lower())\n #self.assertTrue(True)\n elif self.schema_without_label[fld_no] == \"set\":\n if len(field_value) > 0:\n self.assertNotIn(field_value, row[field_name])\n elif self.schema_without_label[fld_no] in [\"string\", \"numeric\", \"boolean\"]:\n self.assertNotEqual(field_value, row[field_name])\n else:\n field_name = feat\n if len(field_name) > 0:\n self.assertIn(field_name, self.fields_without_label)\n\n res_df.apply(chk_feature_nonexistance, axis=1)\n\n\n\n\n\n def test_input_qlty_binary_prob(self):\n self.test_input_qlty(binary_problem=True)\n\n\n\n\n\n def test_predict_explain(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __nonlabeled_inp_df = self.nonlabeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n ac.train(input_df=__labeled_binary_inp_df, schema=__schema_with_label)\n else:\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.load_models(lr, fm, lm)\n \n res_df = ac.predict_explain(input_df=__nonlabeled_inp_df)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), len(self.fields_without_label) + 4)\n self.assertEqual(res_df.dtypes[-1], \"object\")\n self.assertEqual(res_df.dtypes[-2], \"float64\")\n self.assertEqual(res_df.dtypes[-3], \"object\")\n self.assertEqual(res_df.dtypes[-4], \"object\")\n\n #Test if all top-contributed features are present\n def chk_contributor_existance(row):\n contributors = row[\"TopContributors\"].split(';')\n features = [ contrib.split('=')[0] for contrib in contributors]\n for feat in features:\n if '::' in feat:\n field_name, field_value = feat.split('::')\n self.assertIn(field_name, self.fields_without_label)\n fld_no = list(res_df.columns).index(field_name)\n if self.schema_without_label[fld_no] in [\"text\", \"set\"]:\n #self.assertIn(field_value, row[field_name].lower())\n self.assertTrue(True)\n elif self.schema_without_label[fld_no] in [\"string\", \"numeric\", \"boolean\"]:\n self.assertEqual(field_value, row[field_name])\n else:\n field_name = feat\n if len(field_name) > 0:\n self.assertIn(field_name, self.fields_without_label)\n\n res_df.apply(chk_contributor_existance, axis=1)\n\n\n\n\n\n def test_predict_explain_binary_prob(self):\n self.test_predict_explain(binary_problem = True)\n\n\n\n\n\n def test_kfolds_eval(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n res_df = ac.eval(input_df=__labeled_binary_inp_df, schema=__schema_with_label,\n mode = \"K_FOLDS\", nfolds=3)\n else:\n res_df = ac.eval(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode = \"K_FOLDS\", nfolds=3)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(res_df.dtypes[0], \"object\")\n\n if binary_problem:\n self.assertEqual(len(res_df.columns), max(1 + len(self.binary_labels), 5))\n else:\n self.assertEqual(len(res_df.columns), max(1 + len(self.labels), 5))\n\n\n\n\n def test_kfolds_eval_binary_prob(self):\n self.test_kfolds_eval(binary_problem = True)\n\n\n\n\n\n def test_LOO_eval(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n res_df = ac.eval(input_df=__labeled_binary_inp_df, schema=__schema_with_label,\n mode = \"LEAVE_ONE_OUT\", nfolds=3)\n else:\n res_df = ac.eval(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode = \"LEAVE_ONE_OUT\", nfolds=3)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), max(1 + len(self.labels), 5))\n self.assertEqual(res_df.dtypes[0], \"object\")\n\n\n\n\n\n def test_kfolds_eval_topN(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n res_df = ac.eval(input_df=__labeled_binary_inp_df, schema=__schema_with_label,\n mode = \"K_FOLDS\", nfolds=3, topN=2)\n else:\n res_df = ac.eval(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode = \"K_FOLDS\", nfolds=3, topN=2)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), max(1 + len(self.labels), 5))\n self.assertEqual(res_df.dtypes[0], \"object\")\n\n\n\n\n\n def test_LOO_eval_table_format(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n res_df = ac.eval(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode = \"LEAVE_ONE_OUT\", nfolds=3)\n\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), max(1 + len(self.labels), 5))\n self.assertEqual(res_df.dtypes[0], \"object\")\n\n\n\n\n def test_eval_data(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n labels, true_lbls, pred_lbls, conf_mat, cls_report = ac.eval_data(input_df=__labeled_binary_inp_df, schema=__schema_with_label,\n mode = \"LEAVE_ONE_OUT\", nfolds=3)\n else:\n labels, true_lbls, pred_lbls, conf_mat, cls_report = ac.eval_data(input_df=__labeled_inp_df, schema=__schema_with_label,\n mode = \"LEAVE_ONE_OUT\", nfolds=3)\n\n if binary_problem:\n self.assertTrue(len(labels)==2)\n else:\n self.assertTrue(len(labels)==len(self.labels))\n\n self.assertTrue(len(true_lbls)==self.num_recs)\n self.assertTrue(len(true_lbls)==len(pred_lbls))\n\n self.assertTrue(len(conf_mat)==len(labels))\n self.assertTrue(len(conf_mat[0])==len(labels))\n\n ext_labels = list(labels) + ['macro avg', 'weighted avg']\n for lbl in ext_labels:\n self.assertTrue(lbl in cls_report.keys())\n self.assertTrue('precision' in cls_report[lbl])\n self.assertTrue('recall' in cls_report[lbl])\n self.assertTrue('f1-score' in cls_report[lbl])\n self.assertTrue('support' in cls_report[lbl])\n\n self.assertTrue('accuracy' in cls_report.keys())\n\n\n\n def test_binary_eval_data(self):\n self.test_eval_data(binary_problem=True)\n\n\n\n\n def test_model_visualization(self, binary_problem = False):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __labeled_binary_inp_df = self.labeled_binary_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n\n if binary_problem:\n ac.train(input_df=__labeled_binary_inp_df, schema=__schema_with_label)\n else:\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n lr, fm, lm = ac.get_models()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.load_models(lr, fm, lm)\n\n res_df = ac.model_visualization()\n self.assertTrue(isinstance(res_df, pd.DataFrame))\n self.assertEqual(len(res_df.columns), 3)\n self.assertEqual(res_df.dtypes[-1], \"float64\")\n self.assertEqual(res_df.dtypes[-2], \"object\")\n self.assertEqual(res_df.dtypes[-3], \"object\")\n\n\n\n\n def test_model_viz_binary_prob(self):\n self.test_model_visualization(binary_problem=True)\n\n\n\n def test_labels(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n\n labels = ac.labels()\n\n diff1 = [elem for elem in labels if elem not in self.labels]\n diff2 = [elem for elem in self.labels if elem not in labels]\n\n self.assertTrue(len(diff1)==0)\n self.assertTrue(len(diff2)==0)\n self.assertTrue(len(labels)==len(self.labels))\n\n\n\n def test_numclasses(self):\n __labeled_inp_df = self.labeled_inp_df.copy(deep=True)\n __schema_with_label = self.schema_with_label.copy()\n\n ac = Classifier(model_configuration = testModelConfiguration)\n ac.train(input_df=__labeled_inp_df, schema=__schema_with_label)\n\n nclasses = ac.num_classes()\n\n self.assertTrue(nclasses == len(self.labels))\n\n\n\n\n\nif __name__ == \"__main__\":\n testModelConfiguration = modelConfigurations[int(sys.argv[1])]\n print(\"Testing \", testModelConfiguration['type'])\n unittest.main(argv=[''])"
},
{
"alpha_fraction": 0.6562345027923584,
"alphanum_fraction": 0.6626924872398376,
"avg_line_length": 32,
"blob_id": "70682e803ea2abc4deb3b02fbda2ddecae2a8619",
"content_id": "45454ef2783abf8e02b874d7d651e5b548511ca2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2013,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 61,
"path": "/app/test/classify.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "# coding: utf-8\nimport unittest\nimport sys\n\nfrom app.logic.helpers import *\nfrom app.test.setup import *\n\nfrom app.logic.classify import classify\nfrom app.logic.train import *\n\n\nmodelTypes = [Classifier.LR_MODEL_TYPE, Classifier.SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE, Classifier.ENSEMBLE_SVC_MODEL_TYPE]\n\ntestModelType = modelTypes[0]\n\n\n\nclass ClassifyTest(unittest.TestCase):\n\n def test_classify(self):\n labeled_dataset = random_labeled_dataset()\n\n lbl_dataset_id = labeled_dataset['id']\n\n candidate = defaultCandidate(labeled_dataset)[0]\n candidate['config']['type'] = testModelType\n candidate['config']['C'] = 10\n candidate['config']['max_iter'] = 2\n\n model_sel_params = defaultModelSelection()\n\n task = {\n 'data': labeled_dataset,\n 'candidate': candidate,\n 'modelSelectionParams': model_sel_params\n }\n model = train(training_task=task)\n\n test_set = {\n 'id': id(),\n 'features': labeled_dataset['data']['features']\n }\n\n batch_classification_res = classify(model=model, data=test_set)\n\n self.assertTrue(isinstance(batch_classification_res, dict))\n self.assertIn('classSummaries', batch_classification_res)\n\n self.assertTrue(isinstance(batch_classification_res['classSummaries'], list))\n self.assertTrue(isinstance(batch_classification_res['classSummaries'][0], dict))\n self.assertIn('label', batch_classification_res['classSummaries'][0])\n self.assertIn('numInstances', batch_classification_res['classSummaries'][0])\n self.assertIn('probabilities', batch_classification_res['classSummaries'][0])\n self.assertIn('entropies', batch_classification_res['classSummaries'][0])\n self.assertIn('results', batch_classification_res['classSummaries'][0])\n\n\nif __name__ == '__main__':\n testModelType = modelTypes[int(sys.argv[1])]\n print(\"Testing \", testModelType)\n unittest.main(argv=[''])\n"
},
{
"alpha_fraction": 0.6274592280387878,
"alphanum_fraction": 0.631956160068512,
"avg_line_length": 29.536479949951172,
"blob_id": "81492cd971ee87cc9ac24fb1d9a3197a4dcca408",
"content_id": "58394d01c9571866310ec115e6d82498b86f8465",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7116,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 233,
"path": "/app/logic/model_selection.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport sys\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport logging\nfrom pathlib import Path\nimport pickle\nimport os\n\nfrom app.logic.train import *\nfrom app.logic.helpers import *\nfrom app.settings import *\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(stream=sys.stdout, level=LOG_LEVEL)\n\n\n\ncachedMSR = {}\n\n\n\ndef model_selection(models, model_sel):\n degree_of_freedom = np.array([model['degreeOfFreedom'] for model in models])\n\n if model_sel['metric']== 'RECALL':\n metrics = np.array([model['performance']['avgRecall'] for model in models])\n elif model_sel['metric'] == 'PRECISION':\n metrics = np.array([model['performance']['avgPrecision'] for model in models])\n elif model_sel['metric'] == 'F1':\n metrics = np.array([model['performance']['avgF1'] for model in models])\n\n if model_sel['method']== 'BEST':\n selected_midx = np.argmax(metrics)\n elif model_sel['method']== 'KNEE_POINT':\n selected_midx = knee_point(metrics, degree_of_freedom)\n elif model_sel['method']== 'ONE_STDEV':\n selected_midx = one_stdev(metrics, degree_of_freedom)\n elif model_sel['method']== 'TWO_STDEV':\n selected_midx = two_stdev(metrics, degree_of_freedom)\n else:\n selected_midx = 0\n\n selected_model = models[selected_midx]\n\n #type ModelSelectionResults\n res = {\n 'id': id(),\n 'modelSelection': model_sel,\n 'learnedModels': models,\n 'selectedModel': selected_model\n }\n\n return res\n\n\n\ndef knee_point(metrics, degree_of_freedom):\n num_models = len(metrics)\n\n if num_models == 1:\n opt_split_idx = 0\n else:\n metrics_with_dof = zip(metrics, degree_of_freedom, range(num_models))\n\n sorted_metrics_by_dof = sorted(metrics_with_dof, key = lambda metric_dof_idx: -metric_dof_idx[1])\n err = np.zeros(num_models - 1, dtype=np.float)\n for split_idx in range(num_models - 1):\n left_ = np.array([m for (m, _, _) in sorted_metrics_by_dof[:split_idx+1]])\n right_ = np.array([m for (m, _, _) in sorted_metrics_by_dof[split_idx+1:]])\n err1 = 0 if len(left_) < 2 else sum(abs(left_ - np.average(left_)))\n err2 = 0 if len(right_) < 2 else sum(abs(right_ - np.average(right_)))\n err[split_idx] = err1 + err2\n\n opt_split_idx = np.argmin(err)\n return opt_split_idx\n\n\n\n\ndef one_stdev(metrics, degree_of_freedom):\n num_models = len(metrics)\n metrics_with_dof = zip(metrics, degree_of_freedom, range(num_models))\n\n avg = np.average(metrics)\n std = np.std(metrics)\n lower_bound = avg - std\n upper_bound = avg + std\n\n eligible = [ mm for mm in metrics_with_dof if mm[0] >= lower_bound and mm[0] <= upper_bound ]\n\n lowest_dof_idx = np.argmin([ mm[1] for mm in eligible ])\n opt_idx = eligible[lowest_dof_idx][2]\n\n return opt_idx\n\n\n\n\ndef two_stdev(metrics, degree_of_freedom):\n num_models = len(metrics)\n metrics_with_dof = zip(metrics, degree_of_freedom, range(num_models))\n\n avg = np.average(metrics)\n std = np.std(metrics)\n lower_bound = avg - 2*std\n upper_bound = avg + 2*std\n\n eligible = [ mm for mm in metrics_with_dof if mm[0] >= lower_bound and mm[0] <= upper_bound ]\n\n lowest_dof_idx = np.argmin([ mm[1] for mm in eligible ])\n opt_idx = eligible[lowest_dof_idx][2]\n\n return opt_idx\n\n\n\ndef train_batch(candidates, training_data, model_selection_params, model_id):\n startedTime = datetime.datetime.now()\n global cachedMSR\n\n training_tasks = createTrainingTasks(candidates, training_data, model_selection_params)\n trained_models = list(map(train, training_tasks))\n msr = model_selection(trained_models, model_selection_params)\n msr['id'] = model_id\n\n cachedMSR[model_id] = msr\n save_training_results(model_id)\n\n seconds = (datetime.datetime.now() - startedTime).total_seconds()\n print('Trained ' + str(len(training_tasks)) + ' models in ' + str(seconds//60) + ' minutes ' + str(seconds%60) + ' seconds.')\n print('Model ' + str(model_id) + ' cached.')\n\n return msr\n\n\n\ndef train_from_local_data(candidates, schema, training_data_file_name, model_selection_params, model_id):\n training_data = loadLocalData(schema, training_data_file_name)\n if training_data is not None:\n return train_batch(candidates, training_data, model_selection_params, model_id)\n else:\n print(\"Can't read data from file \" + training_data_file_name)\n return None\n\n\n\ndef loadLocalData(schema, file_name):\n dataFile = Path(CLASSIFICATION_DATA_DIR + \"/\" + file_name)\n if dataFile.is_file():\n df = pd.read_csv(dataFile)\n for feat in schema['data']['features'] + [schema['label']]:\n col = feat['feature']['name']\n cType = feat['feature']['type']\n prop_name = 'numerical' if cType in ['NUMERICAL'] else 'set' if cType in ['SET'] else 'text'\n if prop_name == 'numerical':\n feat['data'] = [{ 'id': id(), prop_name: float(val) } for val in df[col].values]\n else:\n feat['data'] = [{ 'id': id(), prop_name: str(val) } for val in df[col].values]\n return schema\n else:\n return None\n\n\n\n\ndef delete_training_results(model_id):\n assert(model_id in cachedMSR), 'Model ID ' + str(model_id) + ' not found.'\n cachedMSR.pop(model_id)\n remove_model(model_id)\n return model_id\n\n\n\ndef get_training_results(model_id):\n global cachedMSR\n\n assert(model_id in cachedMSR), 'Training results with given ID not found.'\n return cachedMSR[model_id]\n\n\n\ndef save_training_results(model_id):\n global cachedMSR\n\n assert(model_id in cachedMSR), 'Training results with given ID not found.'\n path = Path(CLASSIFICATION_MODEL_DIR)\n path.mkdir(parents=True, exist_ok=True)\n output = open(CLASSIFICATION_MODEL_DIR + \"/\" + model_id + \".pkl\", 'wb')\n pickle.dump({model_id: cachedMSR[model_id]}, output)\n output.close()\n print(\"Model \" + str(model_id) + \" saved.\")\n\n\n\ndef load_models():\n global cachedMSR\n\n path = Path(CLASSIFICATION_MODEL_DIR)\n path.mkdir(parents=True, exist_ok=True)\n fileNames = os.listdir(CLASSIFICATION_MODEL_DIR)\n print(\"Loading models from \" + CLASSIFICATION_MODEL_DIR)\n for fname in fileNames:\n modelDataFile = Path(CLASSIFICATION_MODEL_DIR + \"/\" + fname)\n if modelDataFile.is_file():\n datafile = open(CLASSIFICATION_MODEL_DIR + \"/\" + fname, 'rb')\n modelData = pickle.load(datafile)\n cachedMSR.update(modelData)\n datafile.close()\n print(\"Model \" + fname + \" loaded.\")\n print(str(len(cachedMSR)) + \" models loaded from \" + CLASSIFICATION_MODEL_DIR)\n return cachedMSR\n\n\n\ndef remove_model(model_id):\n filename = CLASSIFICATION_MODEL_DIR + \"/\" + model_id + \".pkl\"\n modelData = Path(filename)\n if modelData.is_file():\n os.remove(filename)\n print(\"Model \" + str(model_id) + \" deleted.\")\n else:\n print(\"Model \" + str(model_id) + \" not found.\")\n\n\n\ndef all_training_results():\n return list(cachedMSR.values())\n\n\n\n\ncachedMSR = load_models()\n"
},
{
"alpha_fraction": 0.5388888716697693,
"alphanum_fraction": 0.5415730476379395,
"avg_line_length": 39.45201873779297,
"blob_id": "937234b57a88528c66d09a6041f49bc926706790",
"content_id": "9632a72464a7b2ddd59593ee16ffd82fe065d100",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16020,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 396,
"path": "/app/logic/train.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport json\nimport numpy as np\n#import pprint\n\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\nfrom app.core.main.tokenizer.PorterTokenizer import PorterTokenizer\nfrom app.core.main.tokenizer.LemmaTokenizer import LemmaTokenizer\nfrom app.core.main.featurizer.Doc2Vector import Doc2Vector\nfrom app.core.main.Classifier import Classifier\n\nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import *\n\n\nfrom app.core.main.classifier.LR import LR\nfrom app.core.main.classifier.LSVC import LSVC\nfrom app.core.main.classifier.Ensemble import Ensemble\n\nfrom app.core.main.featurizer.Featurizer import Featurizer\n\n\nfrom app.logic.helpers import *\n\n\n\n\ndef evaluate(training_task):\n labeled_data = training_task['data']\n candidate = training_task['candidate']\n model_sel = training_task['modelSelectionParams']\n\n input_df = datasetToDataframe(labeled_data)\n\n features = candidate[\"features\"]\n featurizers = candidate[\"featurizers\"]\n config = candidate[\"config\"]\n\n ac = create_classifier(config)\n\n filtered_df = input_df.filter([f['name'] for f in features])\n\n labels, _, _, conf_mat, cls_report = ac.eval_data(input_df=filtered_df, schema=featurizers,\n mode = model_sel['evalMode'], nfolds=model_sel['numFolds'])\n\n class_performances = []\n for (lbl_idx, lbl) in enumerate(labels):\n cls_buckets = []\n conf_mat_data = conf_mat[lbl_idx]\n for (idx, nval) in enumerate(conf_mat_data):\n cls_buckets.append({'id': id(), 'trueLabel': lbl, 'predictedLabel': labels[idx], 'numInstances': int(nval), 'weight': 1 })\n\n perf = {\n 'id': id(),\n 'label': lbl,\n 'weight': 1,\n 'numInstances': int(cls_report[lbl]['support']),\n 'classifiedAs': cls_buckets,\n 'recall': float(cls_report[lbl]['recall']),\n 'precision': float(cls_report[lbl]['precision']),\n 'f1': float(cls_report[lbl]['f1-score']),\n }\n class_performances.append(perf)\n\n #type ModelPerformance\n pres = {\n 'id': id(),\n 'classPerformances': class_performances,\n 'numInstances': int(cls_report['weighted avg']['support']),\n 'avgRecall': float(cls_report['weighted avg']['recall']),\n 'avgPrecision': float(cls_report['weighted avg']['precision']),\n 'avgF1': float(cls_report['weighted avg']['f1-score']),\n }\n\n return pres\n\n\n\n\ndef train(training_task):\n #debug\n print(\"train (train.py) starts ...\")\n\n labeled_data = training_task['data']\n candidate = training_task['candidate']\n\n input_df = datasetToDataframe(labeled_data)\n\n features = candidate[\"features\"]\n featurizers = candidate[\"featurizers\"]\n config = candidate[\"config\"]\n\n filtered_df = input_df.filter([f['name'] for f in features])\n\n ac = create_classifier(config)\n\n ac.train(input_df=filtered_df, schema=featurizers)\n mainModel, featurizer, labelEncoder = ac.get_models()\n\n featurizer_models, _, featurizer_end_offset, _ = featurizer.get_params()\n\n weights = mainModel.get_all_weights()\n num_weights = mainModel.num_weights()\n\n labels = list(ac.labels())\n intercepts = mainModel.get_intercepts()\n\n assert (labels is not None)\n assert (labels[0] is not None)\n\n class_weights = []\n for cls_idx, lbl in enumerate(labels):\n feature_weights = []\n for fidx in range(len(features)-1):\n feat = features[fidx]\n _start_widx = featurizer_end_offset[fidx - 1] if fidx > 0 else 0\n _end_widx = featurizer_end_offset[fidx]\n feature_weights.append({'id': id(), 'feature': feat, 'weights': list(weights[cls_idx][_start_widx: _end_widx]) })\n class_weights.append({'id': id(), 'class': lbl, 'weights': feature_weights, 'intercept': float(intercepts[cls_idx])})\n\n featurizers = []\n for fidx, fmodel in enumerate(featurizer_models):\n if fmodel is None:\n featurizers.append(\n {\n 'id': id(),\n 'noop': { 'id': id() }\n }\n )\n elif isinstance(fmodel, MinMaxScaler):\n featurizers.append(\n {\n 'id': id(),\n 'min_max_scaler': {\n 'id': id(),\n 'minValue': float(fmodel.min_[0]),\n 'maxValue': None,\n 'scale': float(fmodel.scale_[0]),\n 'dataMin': float(fmodel.data_min_[0]),\n 'dataMax': float(fmodel.data_max_[0])\n }\n }\n )\n elif isinstance(fmodel, LabelBinarizer):\n featurizers.append(\n {\n 'id': id(),\n 'label_binarizer': { 'id': id(),\n 'labels': list(fmodel.classes_) }\n }\n )\n elif isinstance(fmodel, TfidfVectorizer):\n term_feature_map = []\n for (term, fidx) in fmodel.vocabulary_.items():\n term_feature_map.append({'id': id(), 'term': term, 'featureIdx': int(fidx)})\n featurizers.append(\n {\n 'id': id(),\n 'tfidf_vectorizer': {\n 'id': id(),\n 'vocab': term_feature_map,\n 'idf': [float(idf_val) for idf_val in fmodel.idf_],\n 'stopwords': list(fmodel.stop_words_)\n }\n }\n )\n elif isinstance(fmodel, MultiLabelBinarizer):\n featurizers.append(\n {\n 'id': id(),\n 'multilabel_binarizer': { 'id': id(),\n 'labels': list(fmodel.classes_) }\n }\n )\n elif isinstance(fmodel, LabelEncoder):\n assert (fmodel.classes_ is not None)\n assert (fmodel.classes_[0] is not None)\n featurizers.append(\n {\n 'id': id(),\n 'label_encoder': { 'id': id(),\n 'labels': list(fmodel.classes_) }\n }\n )\n elif isinstance(fmodel, Doc2Vector):\n featurizers.append(\n {\n 'id': id(),\n 'doc_to_vector': {\n 'id': id(),\n 'modelFile': fmodel.model_file_,\n 'maxNumWords': int(fmodel.max_num_words_)\n }\n }\n )\n\n perf = evaluate(training_task)\n\n model_data = mainModel.get_params()\n\n rmodl = {\n 'id': id(),\n 'type': config[\"type\"],\n 'candidate': candidate,\n 'labels': labels,\n 'learnedWeights': class_weights,\n 'learnedFeaturizers': featurizers,\n 'labelEncoder':{ 'id': id(), 'labels': labels },\n 'degreeOfFreedom': num_weights,\n 'performance': perf,\n 'json': json.dumps(model_data)\n }\n\n #debug\n print(\"train (train.py) finished ...\")\n\n #type Model\n return rmodl\n\n\n\n\ndef loadTrainedModel(model):\n #debug\n print(\"loadTrainedModel starts ...\")\n\n config = model[\"candidate\"][\"config\"]\n featurizers = model[\"learnedFeaturizers\"]\n labelEncoder = model[\"labelEncoder\"]\n learnedWeights = model[\"learnedWeights\"]\n labels = model[\"labels\"]\n modelType = model[\"type\"]\n\n if modelType in [Classifier.LR_MODEL_TYPE, Classifier.SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE, Classifier.ENSEMBLE_SVC_MODEL_TYPE]:\n #extract labels, coefs, intercepts, feature names and types from learned weights\n num_classes = len(labels)\n num_features = len(learnedWeights[0][\"weights\"])\n\n if num_classes > 2:\n num_submodels = num_classes\n else:\n num_submodels = 1\n\n featureNames = []\n for clsidx in range(num_submodels):\n for featidx in range(num_features):\n if clsidx == 0:\n featureNames.append(learnedWeights[clsidx][\"weights\"][featidx][\"feature\"][\"name\"])\n\n if modelType == Classifier.LR_MODEL_TYPE:\n #initialize LR model\n clsModel = LR(penalty=config[\"penalty\"].lower(), dual=config[\"primal_dual\"]==\"DUAL\", solver=config[\"solver\"].lower(),\n multi_class=config[\"multiclass\"].lower(), class_weight=config[\"weighting\"].lower(),\n fit_intercept=config[\"fitIntercept\"])\n #clsModel.set_params(classes=labels, coef=coefficients, intercept=intercepts)\n model_data = json.loads(model['json'])\n clsModel.set_params(**model_data)\n elif modelType == Classifier.SVC_MODEL_TYPE:\n clsModel = LSVC(class_weighting=config[\"weighting\"].lower(), C=config[\"C\"], max_iter=config[\"max_iter\"])\n model_data = json.loads(model['json'])\n clsModel.set_params(**model_data)\n elif modelType == Classifier.ENSEMBLE_LR_MODEL_TYPE:\n baseModel = LR(penalty=config[\"penalty\"].lower(), dual=config[\"primal_dual\"]==\"DUAL\", solver=config[\"solver\"].lower(),\n multi_class=config[\"multiclass\"].lower(), class_weight=config[\"weighting\"].lower(),\n fit_intercept=config[\"fitIntercept\"])\n model_data = json.loads(model['json'])\n clsModel = Ensemble(baseModel, model_data['group_index'])\n clsModel.set_params(**model_data)\n elif modelType == Classifier.ENSEMBLE_SVC_MODEL_TYPE:\n baseModel = LSVC(class_weighting=config[\"weighting\"].lower(), C=config[\"C\"], max_iter=config[\"max_iter\"])\n model_data = json.loads(model['json'])\n clsModel = Ensemble(baseModel, model_data['group_index'])\n clsModel.set_params(**model_data)\n\n stop_words = ENGLISH_STOP_WORDS if config[\"stopwords\"] == \"ENGLISH\" else []\n\n tokenizer = BaseTokenizer() if config[\"tokenizer\"] == \"WORD_TOKENIZER\" \\\n else PorterTokenizer() if config[\"tokenizer\"] == \"STEMMER\" \\\n else LemmaTokenizer() if config[\"tokenizer\"] == \"LEMMATIZER\" \\\n else None\n\n ngram_range = (1, 1) if config[\"ngrams\"] == \"UNIGRAM\" \\\n else (2, 2) if config[\"ngrams\"] == \"BIGRAM\" \\\n else (1, 2) if config[\"ngrams\"] == \"BOTH\" \\\n else None\n\n #initialize featurizers\n featurizer_models = []\n featurizer_data = []\n featurizer_offsets = []\n feat_offset = 0\n featureTypes = []\n for f_rizer in featurizers:\n if 'noop' in f_rizer and f_rizer[\"noop\"] is not None:\n m = None\n feat_offset += 1\n featurizer_data.append(None)\n featureTypes.append(\"NOOP\")\n elif 'min_max_scaler' in f_rizer and f_rizer[\"min_max_scaler\"] is not None:\n m = MinMaxScaler()\n m.min_ = np.ndarray((1,), dtype=np.float)\n m.min_[0] = f_rizer[\"min_max_scaler\"][\"minValue\"]\n m.scale_ = np.ndarray((1,), dtype=np.float)\n m.scale_[0] = f_rizer[\"min_max_scaler\"][\"scale\"]\n m.data_min_ = np.ndarray((1,), dtype=np.float)\n m.data_min_[0] = f_rizer[\"min_max_scaler\"][\"dataMin\"]\n m.data_max_ = np.ndarray((1,), dtype=np.float)\n m.data_max_[0] = f_rizer[\"min_max_scaler\"][\"dataMax\"]\n feat_offset += 1\n featurizer_data.append(None)\n featureTypes.append(\"MIN_MAX_SCALER\")\n elif 'label_binarizer' in f_rizer and f_rizer[\"label_binarizer\"] is not None:\n m = LabelBinarizer()\n m.classes_ = np.array(f_rizer[\"label_binarizer\"][\"labels\"])\n feat_offset += len(m.classes_)\n featurizer_data.append(None)\n featureTypes.append(\"LABEL_BINARIZER\")\n elif 'tfidf_vectorizer' in f_rizer and f_rizer[\"tfidf_vectorizer\"] is not None:\n m = TfidfVectorizer(input='content', max_df=config[\"max_df\"], min_df=config[\"min_df\"],\n stop_words=stop_words,\n decode_error='ignore',\n sublinear_tf=config[\"tf\"] == \"SUBLINEAR\",\n smooth_idf=config[\"df\"] == \"SMOOTH\",\n ngram_range = ngram_range, tokenizer = tokenizer)\n m.vocabulary_ = dict()\n for fmap in f_rizer[\"tfidf_vectorizer\"][\"vocab\"]:\n m.vocabulary_.update({fmap[\"term\"]: fmap[\"featureIdx\"]})\n m.idf_ = f_rizer[\"tfidf_vectorizer\"][\"idf\"]\n m.stop_words_ = f_rizer[\"tfidf_vectorizer\"][\"stopwords\"]\n feat_offset += len(m.vocabulary_)\n featurizer_data.append(dict((fidx, w) for (w, fidx) in m.vocabulary_.items()))\n featureTypes.append(\"TFIDF_VECTORIZER\")\n elif 'multilabel_binarizer' in f_rizer and f_rizer[\"multilabel_binarizer\"] is not None:\n m = MultiLabelBinarizer()\n #must re-fit\n m.fit([f_rizer[\"multilabel_binarizer\"][\"labels\"]])\n feat_offset += len(m.classes_)\n featurizer_data.append(m.classes_)\n featureTypes.append(\"MULTILABEL_BINARIZER\")\n elif 'label_encoder' in f_rizer and f_rizer[\"label_encoder\"] is not None:\n m = LabelEncoder()\n m.classes_ = np.array(f_rizer[\"label_encoder\"][\"labels\"])\n feat_offset += 1\n featurizer_data.append(None)\n featureTypes.append(\"LABEL_ENCODER\")\n elif 'doc_to_vector' in f_rizer and f_rizer[\"doc_to_vector\"] is not None:\n m = Doc2Vector(model_file=f_rizer[\"doc_to_vector\"][\"modelFile\"],\n max_num_words=f_rizer[\"doc_to_vector\"][\"maxNumWords\"])\n m.fit()\n feat_offset += m.vector_size()\n featurizer_data.append(None)\n featureTypes.append(\"TEXT_TO_VECTOR\")\n else:\n m = None\n featureTypes.append(\"NOOP\")\n\n featurizer_models.append(m)\n featurizer_offsets.append(feat_offset)\n\n featurizer = Featurizer(featureNames, featureTypes,\n max_df=config[\"max_df\"], min_df=config[\"min_df\"], stop_words=stop_words,\n sublinear_tf=config[\"tf\"] == \"SUBLINEAR\", smooth_idf=config[\"df\"] == \"SMOOTH\",\n ngram_range=ngram_range, tokenizer=tokenizer)\n featurizer.set_params(models=featurizer_models, model_data=featurizer_data, featurizer_offsets=featurizer_offsets,\n tokenizer=tokenizer)\n\n #initialize label encoder model\n m = LabelEncoder()\n m.classes_ = np.array(labelEncoder[\"labels\"])\n\n labelEncoder = Featurizer([\"Label\"], [\"LABEL\"],\n max_df=config[\"max_df\"], min_df=config[\"min_df\"], stop_words=stop_words,\n sublinear_tf=config[\"tf\"] == \"SUBLINEAR\", smooth_idf=config[\"df\"] == \"SMOOTH\",\n ngram_range=ngram_range, tokenizer=tokenizer)\n labelEncoder.set_params(models=[m], model_data=[None], featurizer_offsets=[1],\n tokenizer=tokenizer)\n else:\n clsModel = featurizer = labelEncoder = None\n\n #debug\n print(\"loadTrainedModel finished ...\")\n\n return clsModel, featurizer, labelEncoder\n\n\n\ndef loadModelSelectionResults(json_obj):\n return json.loads(json_obj['json'])\n\n\n\ndef modelSelectionResultsToObject(objId, msr):\n return {\n 'id': objId,\n 'json': json.dumps(msr)\n }\n"
},
{
"alpha_fraction": 0.5433239936828613,
"alphanum_fraction": 0.5493442416191101,
"avg_line_length": 42.074073791503906,
"blob_id": "06e969907a8b843a81cea88b64cdd9e7e41edb6d",
"content_id": "31d74eb05f952707c24f54f98c32ee7092d5d527",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4651,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 108,
"path": "/app/core/main/evaluator/ModelEvaluator.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nLeave one out model evaluator\n'''\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import LeaveOneOut, StratifiedKFold\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\n\n\n\n\nclass ModelEvaluator(object):\n\n ME_LeaveOneOut = \"LEAVE_ONE_OUT\"\n ME_KFoldXVal = \"K_FOLDS\"\n\n supported_modes = [ME_LeaveOneOut, ME_KFoldXVal]\n\n def __init__(self, lr, fm, lm, feature_data, label_data, topN = 1):\n self.__lr = lr\n self.__fm = fm\n self.__lm = lm\n self.__X = self.__fm.fit_transform(feature_data)\n self.__Y = self.__lm.fit_transform(label_data)\n self.__topN = topN\n\n\n\n def eval(self, mode, nfolds):\n labels, _, _, conf_mat, cls_report = self.eval_data(mode, nfolds)\n cls_report_text = (\"%s\" % cls_report).split(\"\\n\")\n\n nCols = max(5, len(labels) + 1)\n table_data = []\n table_data.append([\".\"] + [\"\"] * (nCols - 1))\n table_data.append([\"Confusion Matrix\".upper()] + [\"\"] * (nCols - 1))\n table_data.append([\".\"] + [\"\"] * (nCols - 1))\n table_data.append([\"Actual\\\\Predicted\"] + list(labels) + [\"\"] * (nCols - len(labels) - 1))\n for (row_no, row) in enumerate(conf_mat):\n table_data.append([labels[row_no]] + [str(val) for val in row] + [\"\"] * (nCols - len(labels) - 1))\n\n table_data.append([\".\"] + [\"\"] * (nCols - 1))\n table_data.append([\"Classification Report\".upper()] + [\"\"] * (nCols - 1))\n table_data.append([\".\"] + [\"\"] * (nCols - 1))\n for (lin_no, txt_line) in enumerate(cls_report_text):\n if lin_no == 0:\n table_data.append([\"Class\", \"Precision\", \"Recall\", \"F1-score\", \"Support\"] + [\"\"] * (nCols - 5))\n else:\n lin_dat = txt_line.split()\n if len(lin_dat) < 1:\n table_data.append([\"\"] * nCols)\n else:\n table_data.append([' '.join(lin_dat[:-4])] + lin_dat[-4:] + [\"\"] * (nCols - 5))\n\n return pd.DataFrame(table_data, columns=list(map(lambda n: \"column \" + str(n+1), range(nCols))))\n\n\n\n def eval_data(self, mode, nfolds, output_dict = False):\n assert mode in ModelEvaluator.supported_modes, \"Invalid splitting mode %s. Supported modes are %s\" % \\\n (mode, ModelEvaluator.supported_modes)\n if mode == ModelEvaluator.ME_KFoldXVal:\n assert nfolds > 1 and nfolds <= len(self.__Y), \"Invalid num-folds %d\" % nfolds\n\n spliter = None\n if mode == ModelEvaluator.ME_LeaveOneOut:\n spliter = LeaveOneOut()\n elif mode == ModelEvaluator.ME_KFoldXVal:\n spliter = StratifiedKFold(n_splits=nfolds, shuffle=True)\n\n pred_classes = np.zeros(len(self.__Y))\n for train_idx, test_idx in spliter.split(self.__X, self.__Y):\n X_train = self.__X[train_idx]\n X_test = self.__X[test_idx]\n Y_train = self.__Y[train_idx]\n Y_test = self.__Y[test_idx]\n\n self.__lr.fit(X_train, Y_train)\n\n if self.__topN > 1:\n list_of_probs = self.__lr.predict_proba(X_test)\n list_of_prob_with_index = list(map(lambda probs: zip(probs, range(len(probs))), list_of_probs))\n list_of_sorted_prob_with_index = list(map(\n lambda prob_with_index: sorted(prob_with_index, key = lambda prob_idx: -prob_idx[0]),\n list_of_prob_with_index))\n topN_preds = list(map(lambda sorted_prob_with_index: [idx for (prob, idx) in sorted_prob_with_index[:self.__topN]],\n list_of_sorted_prob_with_index))\n topN_preds_and_true_lbl = zip(topN_preds, Y_test)\n pred_classes[test_idx] = list(map(lambda list_preds__true_lbl:\n list_preds__true_lbl[1] if list_preds__true_lbl[1] in list_preds__true_lbl[0]\n else list_preds__true_lbl[0][0], topN_preds_and_true_lbl))\n else:\n pred_classes[test_idx] = self.__lr.predict(X_test)\n\n labels = self.__lm.inverse_transform(range(max(self.__Y)+1))\n lbl_true = self.__lm.inverse_transform(self.__Y)\n lbl_pred = self.__lm.inverse_transform(pred_classes.astype(int))\n conf_mat = confusion_matrix(lbl_true, lbl_pred, labels)\n cls_report = classification_report(lbl_true, lbl_pred, target_names=labels, output_dict=output_dict)\n\n return labels, lbl_true, lbl_pred, conf_mat, cls_report\n\n\n\n\n def __str__(self):\n return 'Model evaluator.'"
},
{
"alpha_fraction": 0.5338645577430725,
"alphanum_fraction": 0.5465410947799683,
"avg_line_length": 29.622222900390625,
"blob_id": "af4c2ac54de8f8eff815f93aaf8acdf9801f36f3",
"content_id": "4ca23a1718ffe71538d784640d3939f648bfd0bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2761,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 90,
"path": "/app/core/main/featurizer/Doc2Vector.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport os\nimport numpy as np\n\nfrom numpy.linalg import norm\nfrom app.settings import W2VEC_MODEL_DIR\n\n\n\nclass Doc2Vector(object):\n #\n # Pre-trained word2vec models of various languages with Creative Commons Attribution-Share-Alike License 3.0:\n # https://github.com/facebookresearch/fastText/blob/master/pretrained-vectors.md\n # https://fasttext.cc/docs/en/crawl-vectors.html\n #\n __W2V_file = W2VEC_MODEL_DIR + \"/wiki-news-300d-100K.vec\"\n __MAX_NUM_WORDS = 20000\n\n\n\n def __init__(self, model_file = None, max_num_words = -1):\n self.model_file_ = model_file if model_file is not None else self.__W2V_file\n self.max_num_words_ = max_num_words if max_num_words is not None else self.__MAX_NUM_WORDS\n\n assert os.access(self.model_file_, os.R_OK), \"Failed to read from w2v model file %s\" % self.model_file_\n self.__vectors = {}\n self.__vector_size = 0\n self.__vocab_size = 0\n\n\n\n\n #Load pre-trained model, no fitting\n def fit(self, data=None):\n if data is not None:\n inp_words = set('\\n'.join(data).split())\n else:\n inp_words = None\n\n #fasttext format\n word_count = 0\n headerline = True\n with open(Doc2Vector.__W2V_file, 'rt') as txtFile:\n for line in txtFile:\n if headerline:\n headerline = False\n self.__vector_size = int(line.split()[1])\n else:\n tokens = line.split()\n if inp_words is None or tokens[0] in inp_words:\n self.__vectors.update({tokens[0]: np.array([float(val) for val in tokens[1:]])})\n word_count += 1\n if word_count >= self.max_num_words_ and self.max_num_words_ >= 0:\n break\n txtFile.close()\n self.__vocab_size = word_count\n\n\n\n #avg vector of word vectors\n def transform(self, data):\n feat_vectors = []\n for text in data:\n words = text.split()\n doc_vec = np.zeros(self.__vector_size, dtype=float)\n for w in words:\n if w in self.__vectors:\n doc_vec += self.__vectors[w]\n if np.count_nonzero(doc_vec) > 0:\n doc_vec = doc_vec / norm(doc_vec)\n feat_vectors.append(doc_vec)\n return feat_vectors\n\n\n\n def vector_size(self):\n return self.__vector_size\n\n\n\n def vocab_size(self):\n return self.__vocab_size\n\n\n\n def __str__(self):\n return '''\n Pre-trained word embedding model: %s\n Vector size: %d\n Vocabulary size: %d\n ''' % (Doc2Vector.__W2V_file, self.vector_size(), self.vocab_size())\n\n\n\n\n"
},
{
"alpha_fraction": 0.7482837438583374,
"alphanum_fraction": 0.752860426902771,
"avg_line_length": 28.133333206176758,
"blob_id": "cacae68dbdea78e96e63c59b232ecf889faf1f69",
"content_id": "a51278748d14deef32d5c0c91fcc1b75600f14cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 437,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 15,
"path": "/app/settings.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import os\nfrom dotenv import load_dotenv\nimport logging\n\n\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\nload_dotenv(verbose=True, dotenv_path=os.path.join(PROJECT_ROOT, '.env'))\n\nLOG_LEVEL = logging.DEBUG\n\nNLTK_DATA_DIR = os.getenv('NLTK_DATA_DIR')\nW2VEC_MODEL_DIR = os.getenv('W2VEC_MODEL_DIR')\n\nCLASSIFICATION_DATA_DIR = os.getenv('CLASSIFICATION_DATA_DIR')\nCLASSIFICATION_MODEL_DIR = os.getenv('CLASSIFICATION_MODEL_DIR')\n"
},
{
"alpha_fraction": 0.5590682029724121,
"alphanum_fraction": 0.6888518929481506,
"avg_line_length": 18.322580337524414,
"blob_id": "7bd2d2972c7e04c2145c5aec8d35427abacf36ee",
"content_id": "69c35014570eb8439c0130a99c0b107a07b587fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 601,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 31,
"path": "/requirements.txt",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "ariadne\nuvicorn==0.11.2 #default from tiangolo/uvicorn-gunicorn:python3.7 is 0.9.0\ngunicorn==20.0.4 #default from tiangolo/uvicorn-gunicorn:python3.7 is 19.9.0\nasgi-lifespan==0.6.0 #latest is 1.0.0 and is not backward compatible\npython-dotenv==0.10.3\nrequests\ngraphqlclient==0.2.4\n\npython-dateutil>=2.5.0\n#python-igraph>=0.7.1.post6\n\nnumpy>=1.16.1\nscipy>=1.2.1\nscikit-learn==0.21.0\npandas>=0.20.3\n\nnltk>=3.2.5\n\n#pprint\n\n\n#LocalitySensitiveHashing>=1.0.1\n\n#shapely>=1.6.4.post2\n\n#strsim>=0.0.3\n#textdistance>=4.1.4\n#fuzzywuzzy>=0.17.0\n#python-Levenshtein>=0.12.0\n\n#pytz\n\n\n"
},
{
"alpha_fraction": 0.6455756425857544,
"alphanum_fraction": 0.6493815183639526,
"avg_line_length": 28.985713958740234,
"blob_id": "f033c91b6d68857fd2be2a035e7c3e219a407f24",
"content_id": "dac653e6cf31df0181a2a27fd3da2a54f04c0d30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2102,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 70,
"path": "/app/test/train.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import unittest\nimport sys\n\nfrom app.logic.helpers import *\nfrom app.test.setup import *\n\nfrom app.logic.train import evaluate, train, loadTrainedModel\n\nfrom app.core.main.Classifier import Classifier\n\n\n\nmodelTypes = [Classifier.LR_MODEL_TYPE, Classifier.SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE, Classifier.ENSEMBLE_SVC_MODEL_TYPE]\ntestModelType = modelTypes[0]\n\n\nclass TrainingTest(unittest.TestCase):\n\n def test_train(self):\n labeled_dataset = random_labeled_dataset()\n candidate = defaultCandidate(labeled_dataset)[0]\n candidate['config']['type'] = testModelType\n candidate['config']['C'] = 10\n candidate['config']['max_iter'] = 2\n\n model_sel_params = defaultModelSelection()\n\n task = {\n 'data': labeled_dataset,\n 'candidate': candidate,\n 'modelSelectionParams': model_sel_params\n }\n model = train(training_task=task)\n\n self.assertIn('type', model)\n self.assertIn('candidate', model)\n self.assertIn('labels', model)\n self.assertIn('learnedWeights', model)\n self.assertIn('learnedFeaturizers', model)\n self.assertIn('labelEncoder', model)\n self.assertIn('degreeOfFreedom', model)\n self.assertIn('performance', model)\n\n\n\n def test_evaluate(self):\n labeled_dataset = random_labeled_dataset()\n candidate = defaultCandidate(labeled_dataset)[0]\n model_sel_params = defaultModelSelection()\n\n task = {\n 'data': labeled_dataset,\n 'candidate': candidate,\n 'modelSelectionParams': model_sel_params\n }\n\n model_performance = evaluate(task)\n\n self.assertIn('classPerformances', model_performance)\n self.assertIn('numInstances', model_performance)\n self.assertIn('avgRecall', model_performance)\n self.assertIn('avgPrecision', model_performance)\n self.assertIn('avgF1', model_performance)\n\n\n\nif __name__ == \"__main__\":\n testModelType = modelTypes[int(sys.argv[1])]\n print(\"Testing \", testModelType)\n unittest.main(argv=[''])\n\n\n\n"
},
{
"alpha_fraction": 0.6202090382575989,
"alphanum_fraction": 0.6202090382575989,
"avg_line_length": 20.296297073364258,
"blob_id": "5e6f7c6f4b491b1e5c0dabe16a9e1fe024462c58",
"content_id": "abff9f1f13fb65907722e4db513d074613db79fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 574,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 27,
"path": "/app/core/main/tokenizer/PorterTokenizer.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nPorter Tokenizer\n'''\nfrom nltk.stem.porter import PorterStemmer\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\n\n\nclass PorterTokenizer(object):\n\n def __init__(self):\n self.__wnl = PorterStemmer()\n self.__basetokenizer = BaseTokenizer()\n\n\n def __call__(self, doc):\n return self.tokenize(doc)\n\n\n def tokenize(self, doc):\n return [self.__wnl.stem(t) for t in self.__basetokenizer.tokenize(doc)]\n\n\n def __str__(self):\n return '''\n Porter tokenizer based on \n %s\n ''' % self.__basetokenizer"
},
{
"alpha_fraction": 0.6322678923606873,
"alphanum_fraction": 0.6450532674789429,
"avg_line_length": 31.524751663208008,
"blob_id": "3982a42037aacb18c63111bc60f05ee71c3d12ac",
"content_id": "fd32e39c5398b3878ed2b68c57c8ade0566266d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3285,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 101,
"path": "/app/test/feature_selection.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import unittest\nimport sys\n\nfrom app.test.setup import *\n\nfrom app.logic.feature_selection import *\n\n\n\n\nmodelTypes = [Classifier.LR_MODEL_TYPE, Classifier.SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE, Classifier.ENSEMBLE_SVC_MODEL_TYPE]\n\ntestModelType = modelTypes[0]\n\n\n\nclass FeatureSelectionTest(unittest.TestCase):\n\n def test_topN_correlation(self):\n labeled_dataset = random_labeled_dataset()\n num_top_features = rd.randint(10, 100)\n num_top_features = min(num_top_features, len(labeled_dataset['data']['features']))\n\n config = defaultModelConfiguration()\n config['type'] = testModelType\n config['C'] = 10.\n config['max_iter'] = 2\n\n #incl label\n ranked_features = top_correlated_features(labeled_dataset, config, topN=num_top_features)\n\n self.assertLessEqual(len(ranked_features), num_top_features + 1)\n self.assertIn('id', ranked_features[0])\n self.assertIn('index', ranked_features[0])\n self.assertIn('name', ranked_features[0])\n self.assertIn('type', ranked_features[0])\n\n def test_topN_pct_correlation(self):\n labeled_dataset = random_labeled_dataset()\n pct_top_features = rd.random()\n config = defaultModelConfiguration()\n config['type'] = testModelType\n config['C'] = 10.\n config['max_iter'] = 2\n\n\n ranked_features = top_pct_correlated_features(labeled_dataset, config, pct=pct_top_features)\n\n self.assertIn('id', ranked_features[0])\n self.assertIn('index', ranked_features[0])\n self.assertIn('name', ranked_features[0])\n self.assertIn('type', ranked_features[0])\n\n\n\n\n def test_topN_backward(self):\n if testModelType in [Classifier.ENSEMBLE_SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE]:\n return\n\n labeled_dataset = random_labeled_dataset()\n num_top_features = rd.randint(10, 100)\n config = defaultModelConfiguration()\n config['type'] = testModelType\n config['C'] = 10.\n config['max_iter'] = 2\n\n ranked_features = top_rfe_features(labeled_dataset, config, topN=num_top_features)\n\n self.assertLessEqual(len(ranked_features), num_top_features+1) #label is always included\n self.assertIn('id', ranked_features[0])\n self.assertIn('index', ranked_features[0])\n self.assertIn('name', ranked_features[0])\n self.assertIn('type', ranked_features[0])\n\n\n\n\n def test_topN_pct_backward(self):\n if testModelType in [Classifier.ENSEMBLE_SVC_MODEL_TYPE, Classifier.ENSEMBLE_LR_MODEL_TYPE]:\n return\n\n labeled_dataset = random_labeled_dataset()\n pct_top_features = rd.random()\n config = defaultModelConfiguration()\n config['type'] = testModelType\n config['C'] = 10.\n config['max_iter'] = 2\n\n ranked_features = top_pct_rfe_features(labeled_dataset, config, pct=pct_top_features)\n\n self.assertIn('id', ranked_features[0])\n self.assertIn('index', ranked_features[0])\n self.assertIn('name', ranked_features[0])\n self.assertIn('type', ranked_features[0])\n\n\nif __name__ == '__main__':\n testModelType = modelTypes[int(sys.argv[1])]\n print(\"Testing \", testModelType)\n unittest.main(argv=[''])\n"
},
{
"alpha_fraction": 0.7831325531005859,
"alphanum_fraction": 0.7831325531005859,
"avg_line_length": 27,
"blob_id": "8202ed5cfd5238e8ff1a4685b06ef5a8e70867de",
"content_id": "bd4d110afe21b2128ea351ec35ecd09484d0482c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 83,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 3,
"path": "/app/core/main/tokenizer/__init__.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import nltk\nfrom app.settings import NLTK_DATA_DIR\nnltk.data.path = [NLTK_DATA_DIR]"
},
{
"alpha_fraction": 0.5964608192443848,
"alphanum_fraction": 0.6008423566818237,
"avg_line_length": 50.46503448486328,
"blob_id": "c027eac2490498f5ab929b10054c2ed25241cf99",
"content_id": "0118bbc7dd8b0412169439b7c78ba085fb08b1fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 29442,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 572,
"path": "/app/core/main/Classifier.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nMain process for Assisted Categorization\n'''\nimport pandas as pd\nimport numpy as np\nfrom scipy.special import entr\n\n\nfrom app.core.main.classifier.LR import LR\nfrom app.core.main.classifier.LSVC import LSVC\nfrom app.core.main.classifier.Ensemble import Ensemble\nfrom app.core.main.featurizer.Featurizer import Featurizer\nfrom app.core.main.feature_selection.LabelCorrelation import LabelCorrelation\nfrom app.core.main.feature_selection.BackwardStepwise import BackwardStepwise\nfrom app.core.main.evaluator.ModelEvaluator import ModelEvaluator\nfrom sklearn.feature_extraction import stop_words\n\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\n\ndefaultModelConfiguration = {\n \"type\": \"LOGISTIC_REGRESSION\", #or LINEAR_SVC\n \"class_weight\": \"balanced\",\n \"tokenizer\": BaseTokenizer(),\n \"ngram_range\": (1, 1),\n \"sublinear_tf\": True,\n \"smooth_idf\": True,\n \"penalty\": \"l2\",\n \"multi_class\": \"ovr\",\n \"solver\": \"liblinear\",\n \"dual\": True,\n \"fit_intercept\": True,\n 'max_df': 1.,\n 'min_df': 0.,\n 'stopwords': stop_words.ENGLISH_STOP_WORDS,\n 'C': 1.,\n 'max_iter': 1000,\n }\n\n\nclass Classifier(object):\n #supported model types\n LR_MODEL_TYPE = \"LOGISTIC_REGRESSION\"\n SVC_MODEL_TYPE = \"LINEAR_SVC\"\n ENSEMBLE_SVC_MODEL_TYPE = \"ENSEMBLE_LINEAR_SVC\"\n ENSEMBLE_LR_MODEL_TYPE = \"ENSEMBLE_LOGISTIC_REGRESSION\"\n\n #supported feature selection mode\n CC_fs_correlation = \"CORRELATION\"\n CC_fs_backward = \"RFE\"\n\n supported_feature_selection_modes = [CC_fs_backward, CC_fs_correlation]\n\n\n def __init__(self, model_configuration = defaultModelConfiguration):\n self.__model_configuration = model_configuration\n self.__model = None\n self.__featurizer = None\n self.__labeler = None\n\n\n def train(self, input_df, schema):\n #debug\n print(\"train starts ...\")\n\n assert isinstance(input_df, pd.DataFrame)\n\n field_names, labelFieldName, field_types, train_data, labelData = self.__read_training_data(input_df, schema)\n\n if self.__model_configuration[\"type\"] == Classifier.LR_MODEL_TYPE:\n m = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n elif self.__model_configuration[\"type\"] == Classifier.SVC_MODEL_TYPE:\n m = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_SVC_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_LR_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n else:\n m = None\n\n fm = Featurizer(field_names, field_types,\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n lm = Featurizer([labelFieldName], [Featurizer.FT_Label],\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n #debug\n print(\"train: feature transforming ...\")\n features = fm.fit_transform(train_data)\n\n print(\"train: label transforming ...\")\n labels = lm.fit_transform(labelData)\n\n print(\"train: model fitting ...\")\n m.fit(features, labels)\n self.__model = m\n self.__featurizer = fm\n self.__labeler = lm\n\n #debug\n print(\"train finished ...\")\n\n\n\n def get_models(self):\n return (self.__model, self.__featurizer, self.__labeler)\n\n\n\n def load_models(self, m, fm, lm):\n assert isinstance(m, LR) or isinstance(m, LSVC) or isinstance(m, Ensemble), \"Expect a LR model or SVM model or Ensemble model.\"\n assert isinstance(fm, Featurizer), \"Expect a Featurizer model.\"\n assert isinstance(lm, Featurizer), \"Expect a Featurizer model.\"\n\n self.__model = m\n self.__featurizer = fm\n self.__labeler = lm\n\n\n\n def predict_proba(self, input_df, multilabel_pred = False):\n #debug\n print(\"predict_proba starts ...\")\n\n assert isinstance(self.__model, LR) or isinstance(self.__model, LSVC) or isinstance(self.__model, Ensemble)\n assert isinstance(self.__featurizer, Featurizer)\n assert isinstance(self.__labeler, Featurizer)\n\n assert isinstance(input_df, pd.DataFrame)\n\n field_names = list(input_df.columns)\n assert len(field_names) == len(self.__featurizer.get_schema()), \"Input data has different schema than input schema.\"\n\n predictors = self.__featurizer.transform(input_df)\n probs = self.__model.predict_proba(predictors)\n\n if multilabel_pred:\n list_lbl_indices = list(map(self.__multi_labels__, probs))\n assert type(list_lbl_indices) == list\n assert type(list_lbl_indices[0]) == list\n list_labels = list(map(self.__labeler.inverse_transform, list_lbl_indices))\n predicted_labels = list(map(lambda lbls: ','.join(lbls), list_labels))\n else:\n predicted_labels = self.__labeler.inverse_transform(list(map(np.argmax, probs)))\n\n class_names = self.__labeler.inverse_transform(range(len(probs[0])))\n probs_to_str = list(map(lambda ps: list(map(lambda fval: \"%.2f\" % fval, ps)), probs))\n probs_with_name = list(map(lambda ps: zip(class_names, ps), probs_to_str))\n cls_probs = list(map(lambda pn: ','.join(list(map(lambda n_p: n_p[0] + ':' + n_p[1], pn))), probs_with_name))\n\n labels = pd.DataFrame(predicted_labels, columns=[\"PredictedLabel\"])\n probs_df = pd.DataFrame(cls_probs, columns=[\"Probabilities\"])\n entropies_df = pd.DataFrame(list(map(lambda fval: round(fval, 2), entr(probs).sum(axis=1))), columns=[\"Entropy\"])\n\n #debug\n print(\"predict_proba finished ...\")\n\n return pd.concat([input_df, labels, probs_df, entropies_df], axis=1)\n\n\n\n def predict_explain(self, input_df, multilabel_pred = False, topN_features = 10):\n assert isinstance(self.__model, LR) or isinstance(self.__model, LSVC) or isinstance(self.__model, Ensemble)\n assert isinstance(self.__featurizer, Featurizer)\n assert isinstance(self.__labeler, Featurizer)\n\n assert isinstance(input_df, pd.DataFrame)\n\n field_names = list(input_df.columns)\n\n # #debug\n # if len(field_names) != len(self.__featurizer.get_schema()):\n # print('Input data fields:', len(field_names), sorted(field_names))\n # print('Input schema:', len(self.__featurizer.get_schema()), self.__featurizer.get_schema())\n assert len(field_names) == len(self.__featurizer.get_schema()), \"Input data has different schema than input schema.\"\n\n predictors = self.__featurizer.transform(input_df)\n probs = self.__model.predict_proba(predictors)\n pred_classes = list(map(np.argmax, probs))\n\n if multilabel_pred:\n list_lbl_indices = list(map(self.__multi_labels__, probs))\n assert type(list_lbl_indices) == list\n assert type(list_lbl_indices[0]) == list\n list_labels = list(map(self.__labeler.inverse_transform, list_lbl_indices))\n predicted_labels = list(map(lambda lbls: ','.join(lbls), list_labels))\n else:\n predicted_labels = self.__labeler.inverse_transform(pred_classes)\n\n class_names = self.__labeler.inverse_transform(range(len(probs[0])))\n probs_to_str = list(map(lambda ps: list(map(lambda fval: \"%.2f\" % fval, ps)), probs))\n probs_with_name = list(map(lambda ps: zip(class_names, ps), probs_to_str))\n cls_probs = list(map(lambda pn: ','.join(list(map(lambda n_p: n_p[0] + ':' + n_p[1], pn))), probs_with_name))\n\n labels = pd.DataFrame(predicted_labels, columns=[\"PredictedLabel\"])\n probs_df = pd.DataFrame(cls_probs, columns=[\"Probabilities\"])\n entropies_df = pd.DataFrame(list(map(lambda fval: round(fval, 2), entr(probs).sum(axis=1))), columns=[\"Entropy\"])\n\n weights = self.__model.get_all_weights()\n feat_names = self.__featurizer.get_all_features()\n\n raw_contributors = list(map(lambda didx_clsno: zip(feat_names, weights[didx_clsno[1]].tolist(),\n np.asarray(predictors)[didx_clsno[0]]),\n enumerate(pred_classes)))\n eligible_contributors = list(map(lambda contrib: [(feat, w * inp_s) for (feat, w, inp_s) in contrib if w * inp_s != 0.0 ],\n raw_contributors))\n top_contributors = list(map(lambda feats: ';'.join([fname + '=' + str(round(w, 2)) \\\n for (fname, w) in sorted(feats, key = lambda n_w: abs(n_w[1]), reverse=True)[:topN_features] ]),\n eligible_contributors))\n\n contributors = pd.DataFrame(top_contributors, columns=[\"TopContributors\"])\n\n return pd.concat([input_df, labels, probs_df, entropies_df, contributors], axis=1)\n\n\n\n def learn(self, input_df):\n prob_df = self.predict_proba(input_df)\n sorted_prob_df = prob_df.sort_values(by = [\"Entropy\"], ascending = False)\n\n return sorted_prob_df\n\n\n\n def input_qlty(self, input_df, threshold1 = 0.3, threshold2 = 0.5, topN = 10):\n assert isinstance(self.__model, LR) or isinstance(self.__model, LSVC) or isinstance(self.__model, Ensemble)\n assert isinstance(self.__featurizer, Featurizer)\n assert isinstance(self.__labeler, Featurizer)\n\n assert isinstance(input_df, pd.DataFrame)\n\n assert threshold1 <= threshold2, \"Entropy threshold values are invalid: %f > %f .\" % (threshold1, threshold2)\n assert topN > 0, \"Number of top contributors %d is invalid.\" % topN\n\n weights = self.__model.get_all_weights()\n feat_names = self.__featurizer.get_all_features()\n\n assert topN <= len(feat_names), \"Number of top contributors %d cannot exceed number of features %d\" % (topN, len(feat_names))\n field_names = list(input_df.columns)\n feat_field_names = [fld for (fidx, fld) in enumerate(list(field_names))]\n\n assert len(feat_field_names) == len(self.__featurizer.get_schema()), \"Input data has different schema than input schema.\"\n\n X = self.__featurizer.transform(input_df)\n zero_feats = list(map(lambda xrow: xrow == 0.0, np.array(X)))\n\n probs = self.__model.predict_proba(X)\n top2Indices = np.argsort(probs, axis=1)[np.ix_(range(probs.shape[0]), range(probs.shape[1])[-2:])]\n entropies = entr(probs).sum(axis=1)\n\n input_qlty_df = pd.DataFrame(list(map(lambda e: \"Good\" if e <= threshold1 \\\n else \"OK\" if e <= threshold2 else \"Bad\", entropies)), columns=[\"InputQlty\"])\n\n #classes features & weights\n feat_weights = list(map(lambda cls1_cls2: zip(feat_names, weights[cls1_cls2[0]], weights[cls1_cls2[1]],\n range(len(feat_names))), top2Indices))\n contributors = list(map(lambda fweights: list(map( lambda feat_coeff1_coeff2_fidx: \\\n (feat_coeff1_coeff2_fidx[0], abs(feat_coeff1_coeff2_fidx[1] - feat_coeff1_coeff2_fidx[2]), feat_coeff1_coeff2_fidx[3]),\n fweights)), feat_weights))\n\n not_existed_contributors = list(map(lambda fweights_zero_fs: [(feat, coeff) for (feat, coeff, fidx) in fweights_zero_fs[0] \\\n if fweights_zero_fs[1][fidx]], zip(contributors, zero_feats)))\n top_contributors = list(map(lambda fweights: sorted(fweights,\n key = lambda feat_coeff: -feat_coeff[1])[:topN], not_existed_contributors))\n\n top_contributors_str = list(map(lambda fweights: ','.join([feat for (feat, w) in fweights]), top_contributors))\n top_contributors_df = pd.DataFrame(top_contributors_str, columns=[\"SuggestedFeatures\"])\n\n return pd.concat([input_df, input_qlty_df, top_contributors_df], axis=1)\n\n\n\n\n\n def eval(self, input_df, schema, mode, nfolds, topN = 1):\n\n field_names, label_field_name, field_types, train_data, label_data = self.__read_training_data(input_df, schema)\n\n if self.__model_configuration[\"type\"] == Classifier.LR_MODEL_TYPE:\n m = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n elif self.__model_configuration[\"type\"] == Classifier.SVC_MODEL_TYPE:\n m = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_SVC_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_LR_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n else:\n m = None\n\n fm = Featurizer(field_names, field_types,\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n lm = Featurizer([label_field_name], [Featurizer.FT_Label],\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n evaluator = ModelEvaluator(m, fm, lm, train_data, label_data, topN)\n eval_res = evaluator.eval(mode, nfolds)\n\n return eval_res\n\n\n\n\n def eval_data(self, input_df, schema, mode, nfolds, topN = 1):\n\n field_names, label_field_name, field_types, train_data, label_data = self.__read_training_data(input_df, schema)\n\n if self.__model_configuration[\"type\"] == Classifier.LR_MODEL_TYPE:\n m = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n elif self.__model_configuration[\"type\"] == Classifier.SVC_MODEL_TYPE:\n m = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_SVC_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_LR_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n else:\n m = None\n\n fm = Featurizer(field_names, field_types,\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n lm = Featurizer([label_field_name], [Featurizer.FT_Label],\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n evaluator = ModelEvaluator(m, fm, lm, train_data, label_data, topN)\n return evaluator.eval_data(mode, nfolds, output_dict=True)\n\n\n\n\n\n def feature_ranking(self, input_df, schema, mode):\n field_names, labelFieldName, field_types, train_data, labelData = self.__read_training_data(input_df, schema)\n\n assert mode in Classifier.supported_feature_selection_modes, \\\n \"Invalid feature selection mode %s. Supported modes are %s\" % \\\n (mode, Classifier.supported_feature_selection_modes)\n\n fm = Featurizer(field_names, field_types,\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n lm = Featurizer([labelFieldName], [Featurizer.FT_Label],\n max_df=self.__model_configuration[\"max_df\"],\n min_df=self.__model_configuration[\"min_df\"],\n stop_words=self.__model_configuration[\"stopwords\"],\n sublinear_tf=self.__model_configuration[\"sublinear_tf\"],\n smooth_idf=self.__model_configuration[\"smooth_idf\"],\n ngram_range=self.__model_configuration[\"ngram_range\"],\n tokenizer=self.__model_configuration[\"tokenizer\"]\n )\n\n X = fm.fit_transform(train_data)\n Y = lm.fit_transform(labelData)\n\n if self.__model_configuration[\"type\"] == Classifier.LR_MODEL_TYPE:\n m = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n elif self.__model_configuration[\"type\"] == Classifier.SVC_MODEL_TYPE:\n m = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_SVC_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LSVC(class_weighting=self.__model_configuration[\"class_weight\"], C=self.__model_configuration[\"C\"],\n max_iter=self.__model_configuration[\"max_iter\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n elif self.__model_configuration[\"type\"] == Classifier.ENSEMBLE_LR_MODEL_TYPE:\n field_names = list(input_df.columns)\n assert 'TRAIN_GROUP' == field_names[0]\n assert schema[0] in ['NOOP', 'MIN_MAX_SCALER', 'LABEL_ENCODER', 'NUMERICAL', 'BOOLEAN']\n\n base_model = LR(penalty=self.__model_configuration[\"penalty\"], dual=self.__model_configuration[\"dual\"],\n solver=self.__model_configuration[\"solver\"], multi_class=self.__model_configuration[\"multi_class\"],\n class_weight=self.__model_configuration[\"class_weight\"], fit_intercept=self.__model_configuration[\"fit_intercept\"])\n m = Ensemble(base_model, group_index=field_names.index('TRAIN_GROUP'))\n else:\n m = None\n\n fs = LabelCorrelation(n = 1.0) if mode == Classifier.CC_fs_correlation \\\n else BackwardStepwise(n = 1, step = 1, estimator=m) #(n = 1, step = max(X.shape[1]/300, 1))\n\n feature_scores = fs.score_features(X, Y)\n feature_scores_rounded = list(map(lambda val: round(val, 2), feature_scores))\n feature_names = fm.get_all_features()\n\n features_df = pd.DataFrame(zip(feature_names, feature_scores_rounded),\n columns=[\"Feature\", \"Score\"])\n sorted_features_df = features_df.sort_values(by = [\"Score\"], ascending = False)\n\n return sorted_features_df\n\n\n\n\n def model_visualization(self, topN = 10):\n assert topN > 0, \"Number of top contributors %d is invalid.\" % topN\n assert isinstance(self.__model, LR) or isinstance(self.__model, LSVC) or isinstance(self.__model, Ensemble)\n assert isinstance(self.__featurizer, Featurizer)\n assert isinstance(self.__labeler, Featurizer)\n\n feat_names = self.__featurizer.get_all_features()\n\n assert topN <= len(feat_names), \"Number of top contributors %d cannot exceed number of features %d\" \\\n % (topN, len(feat_names))\n\n weights = self.__model.get_all_weights()\n feature_weights = list(map(lambda ws: zip(feat_names, ws), weights))\n top_weights = list(map(lambda class_weights: sorted(class_weights, key = lambda fname_w: -abs(fname_w[1]))[:topN], feature_weights))\n\n num_classes = self.num_classes()\n labels = self.__labeler.inverse_transform(range(num_classes))\n flatten_lbl_weights = [(lbl, fname, w) for (lbl, f_weights) in zip(labels, top_weights)\n for (fname, w) in f_weights]\n res_df = pd.DataFrame(flatten_lbl_weights, columns=[\"Class\", \"Feature\", \"Weight\"])\n\n return res_df\n\n\n\n def labels(self):\n return self.__labeler.inverse_transform(self.__model.labels())\n\n\n def num_classes(self):\n return self.__model.num_classes()\n\n\n def __read_training_data(self, input_df, schema):\n assert isinstance(input_df, pd.DataFrame)\n\n field_names = list(input_df.columns)\n\n assert len(field_names) == len(schema), \"Input data has different schema than input schema, e.g. length of %d vs %d\" \\\n % (len(field_names), len(schema))\n\n #ignore data frame field types, and make a copy\n field_types = [fld for fld in schema]\n\n assert len([type for type in field_types if type == Featurizer.FT_Label]) == 1, \\\n \"There must be exactly one field with %s type in training data.(%s)\" % (Featurizer.FT_Label, field_types)\n\n label_field_no = field_types.index(Featurizer.FT_Label)\n label_field_name = field_names[label_field_no]\n label_data = input_df.filter(items=[input_df.columns[label_field_no]])\n\n\n del input_df[input_df.columns[label_field_no]]\n field_names.remove(field_names[label_field_no])\n field_types.remove(field_types[label_field_no])\n\n return (field_names, label_field_name, field_types, input_df, label_data)\n\n\n\n def __multi_labels__(self, probabilities):\n prob_with_index = zip(probabilities, range(len(probabilities)))\n sorted_prob_with_index = sorted(prob_with_index, key = lambda prob_idx: -prob_idx[0])\n err = np.zeros(len(probabilities), dtype=np.float)\n for split_idx in range(len(probabilities)):\n left_ = np.array([p for (p, _) in sorted_prob_with_index[:split_idx]])\n right_ = np.array([p for (p, _) in sorted_prob_with_index[split_idx:]])\n err1 = 0 if len(left_) < 2 else sum(abs(left_ - np.average(left_)))\n err2 = 0 if len(right_) < 2 else sum(abs(right_ - np.average(right_)))\n err[split_idx] = err1 + err2\n opt_split_idx = max(np.argmin(err), 1)\n\n res = [cls_idx for (_, cls_idx) in sorted_prob_with_index[:opt_split_idx]]\n assert len(res) > 0\n return res\n\n\n\n def __str__(self):\n return 'Classification Service.'\n\n\n\n\n"
},
{
"alpha_fraction": 0.6413385272026062,
"alphanum_fraction": 0.645775556564331,
"avg_line_length": 38.19565200805664,
"blob_id": "189eb67d91edc7dc3c5625e4fc7dbf362d408242",
"content_id": "d57d45221bb68b895287b04f49ae2a524e478163",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5409,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 138,
"path": "/app/logic/feature_selection.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport math\n\nfrom app.logic.helpers import defaultFeatures, datasetToDataframe, defaultFeaturizers, defaultModelConfiguration\nfrom app.core.main.Classifier import Classifier\n\nfrom app.core.main.tokenizer.BaseTokenizer import BaseTokenizer\nfrom app.core.main.tokenizer.PorterTokenizer import PorterTokenizer\nfrom app.core.main.tokenizer.LemmaTokenizer import LemmaTokenizer\n\nfrom sklearn.feature_extraction.stop_words import ENGLISH_STOP_WORDS\n\n\n\ndef top_correlated_features(labeled_dataset, config, topN = None):\n labeled_inp_df = datasetToDataframe(labeled_dataset)\n features = defaultFeatures(dataset=labeled_dataset)\n featurizers = defaultFeaturizers(features)\n\n stop_words = ENGLISH_STOP_WORDS if config[\"stopwords\"] == \"ENGLISH\" else []\n\n tokenizer = BaseTokenizer() if config[\"tokenizer\"] == \"WORD_TOKENIZER\" \\\n else PorterTokenizer() if config[\"tokenizer\"] == \"STEMMER\" \\\n else LemmaTokenizer() if config[\"tokenizer\"] == \"LEMMATIZER\" \\\n else None\n\n ngram_range = (1, 1) if config[\"ngrams\"] == \"UNIGRAM\" \\\n else (2, 2) if config[\"ngrams\"] == \"BIGRAM\" \\\n else (1, 2) if config[\"ngrams\"] == \"BOTH\" \\\n else None\n\n ac = Classifier(model_configuration={\n \"type\": config['type'],\n \"class_weight\": config['weighting'].lower(),\n \"tokenizer\": tokenizer,\n \"ngram_range\": ngram_range,\n \"sublinear_tf\": config['tf']==\"SUBLINEAR\",\n \"smooth_idf\": config['df']==\"SMOOTH\",\n \"penalty\": config['penalty'].lower(),\n \"multi_class\": config['multiclass'].lower(),\n \"solver\": config['solver'].lower(),\n \"dual\": config['primal_dual']==\"DUAL\",\n \"fit_intercept\": config['fitIntercept'],\n 'max_df': config['max_df'],\n 'min_df': config['min_df'],\n 'stopwords': stop_words,\n 'C': config['C'],\n 'max_iter': config['max_iter']\n })\n\n res_df = ac.feature_ranking(input_df=labeled_inp_df, schema=featurizers, mode=Classifier.CC_fs_correlation)\n\n feature_names = pd.Series(map(lambda fname: fname.split('::')[0], res_df['Feature']))\n feature_scores = pd.concat([feature_names, res_df['Score']], axis=1)\n feature_scores.columns = ['Feature', 'Score']\n feature_sum_scores = feature_scores.groupby('Feature').sum()\n sorted_features = feature_sum_scores.sort_values(by = [\"Score\"], ascending = False)\n\n selected_feature_names = list(sorted_features.index)[:topN]\n selected_features = []\n for fname in selected_feature_names:\n selected_features += [feat for feat in features if feat['name'] == fname]\n\n return selected_features + [features[-1]]\n\n\n\ndef top_pct_correlated_features(labeled_dataset, config, pct = 1.):\n features_and_label = top_correlated_features(labeled_dataset, config)\n features = features_and_label[:-1]\n\n num_features = math.ceil(len(features) * pct)\n\n return features[:num_features] + [features_and_label[-1]]\n\n\n\ndef top_rfe_features(labeled_dataset, config, topN = None):\n labeled_inp_df = datasetToDataframe(labeled_dataset)\n features = defaultFeatures(dataset=labeled_dataset)\n featurizers = defaultFeaturizers(features)\n\n stop_words = ENGLISH_STOP_WORDS if config[\"stopwords\"] == \"ENGLISH\" else []\n\n tokenizer = BaseTokenizer() if config[\"tokenizer\"] == \"WORD_TOKENIZER\" \\\n else PorterTokenizer() if config[\"tokenizer\"] == \"STEMMER\" \\\n else LemmaTokenizer() if config[\"tokenizer\"] == \"LEMMATIZER\" \\\n else None\n\n ngram_range = (1, 1) if config[\"ngrams\"] == \"UNIGRAM\" \\\n else (2, 2) if config[\"ngrams\"] == \"BIGRAM\" \\\n else (1, 2) if config[\"ngrams\"] == \"BOTH\" \\\n else None\n\n\n ac = Classifier(model_configuration={\n \"type\": config['type'],\n \"class_weight\": config['weighting'].lower(),\n \"tokenizer\": tokenizer,\n \"ngram_range\": ngram_range,\n \"sublinear_tf\": config['tf']==\"SUBLINEAR\",\n \"smooth_idf\": config['df']==\"SMOOTH\",\n \"penalty\": config['penalty'].lower(),\n \"multi_class\": config['multiclass'].lower(),\n \"solver\": config['solver'].lower(),\n \"dual\": config['primal_dual']==\"DUAL\",\n \"fit_intercept\": config['fitIntercept'],\n 'max_df': config['max_df'],\n 'min_df': config['min_df'],\n 'stopwords': stop_words,\n 'C': config['C'],\n 'max_iter': config['max_iter']\n })\n\n res_df = ac.feature_ranking(input_df=labeled_inp_df, schema=featurizers, mode=Classifier.CC_fs_backward)\n\n feature_names = pd.Series(map(lambda fname: fname.split('::')[0], res_df['Feature']))\n feature_scores = pd.concat([feature_names, res_df['Score']], axis=1)\n feature_scores.columns = ['Feature', 'Score']\n feature_sum_scores = feature_scores.groupby('Feature').sum()\n sorted_features = feature_sum_scores.sort_values(by = [\"Score\"], ascending = False)\n\n selected_feature_names = list(sorted_features.index)[:topN]\n selected_features = []\n for fname in selected_feature_names:\n selected_features += [feat for feat in features if feat['name'] == fname]\n\n return selected_features+ [features[-1]]\n\n\n\ndef top_pct_rfe_features(labeled_dataset, config, pct = 1.):\n features_and_label = top_rfe_features(labeled_dataset, config)\n features = features_and_label[:-1]\n\n num_features = math.ceil(len(features) * pct)\n\n return features[:num_features] + [features_and_label[-1]]\n"
},
{
"alpha_fraction": 0.6408488154411316,
"alphanum_fraction": 0.6663129925727844,
"avg_line_length": 37.46938705444336,
"blob_id": "218e0b6adab8786e019e144a5f8dea4bda78f49e",
"content_id": "82d1b2afeb5a4ad5d2408d151c97469ee016a359",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 1885,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 49,
"path": "/Dockerfile",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "#FROM tiangolo/uvicorn-gunicorn:python3.7-alpine3.8\nFROM tiangolo/uvicorn-gunicorn:python3.7\n\nRUN pip3 install --upgrade pip\n\nWORKDIR /\n\nRUN rm -rf /app\nCOPY ./app /app\n\nCOPY requirements.txt /requirements.txt\nRUN pip3 install -r requirements.txt\n\nRUN python3 -m nltk.downloader wordnet -d /app/data\nRUN python3 -m nltk.downloader punkt -d /app/data\n\n#COPY .env /.env\nCOPY gunicorn_conf.py /gunicorn_conf.py\nCOPY start.sh /start.sh\nCOPY start-reload.sh /start-reload.sh\n\nEXPOSE 8050\n\n\n#RUN cd ./app/core/test/ && export PYTHONPATH=../../../ && python3 Classifier.py 0\n#RUN cd ./app/core/test/ && export PYTHONPATH=../../../ && python3 Classifier.py 1\n#RUN cd ./app/core/test/ && export PYTHONPATH=../../../ && python3 Classifier.py 2\n#RUN cd ./app/core/test/ && export PYTHONPATH=../../../ && python3 Classifier.py 3\n\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 helpers.py\n\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 train.py 0\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 train.py 1\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 train.py 2\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 train.py 3\n\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 model_selection.py\n\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 classify.py 0\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 classify.py 1\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 classify.py 2\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 classify.py 3\n\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 feature_selection.py 0\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 feature_selection.py 1\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 feature_selection.py 2\n#RUN cd ./app/test/ && export PYTHONPATH=../../ && python3 feature_selection.py 3\n\nCMD /start.sh\n"
},
{
"alpha_fraction": 0.48479506373405457,
"alphanum_fraction": 0.5008814334869385,
"avg_line_length": 30.957746505737305,
"blob_id": "d5b1acbb9177cf9150f062afc9422b15bb9b6c22",
"content_id": "7d8c232d02efb8998346c8173dfb962f715a6bc3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4538,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 142,
"path": "/app/test/helpers.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "# coding: utf-8\n\nimport unittest\nimport pandas as pd\n\nfrom pandas.util.testing import assert_frame_equal\nfrom app.logic.helpers import (\n dataframeToDataset,\n datasetToDataframe,\n getDataFieldName,\n inferFeatureType, \n id\n)\n\n\nclass TestHelpers(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.features = [\n {\n \"feature\": {\"index\": 0, \"name\": \"feature 0\", \"type\": \"TEXT\"},\n \"data\": [\n {\"text\": \"Hello\" },\n {\"text\": \"Hello\" }\n ]\n },\n {\n \"feature\": {\"index\": 1, \"name\": \"feature 1\", \"type\": \"NUMERICAL\"},\n \"data\": [\n {\"numerical\": 1.2 },\n {\"numerical\": 2.5 }\n ]\n },\n {\n \"feature\": {\"index\": 2, \"name\": \"feature 2\", \"type\": \"SET\"},\n \"data\": [\n {\"set\": [\"a\", \"b\"]},\n {\"set\": [\"d\", \"e\"]}\n ]\n }\n ]\n\n cls.ds = {\n \"features\": cls.features\n }\n\n cls.labeled_ds = {\n 'id': id(),\n \"data\": {\n 'id': id(),\n \"features\": cls.features\n },\n \"label\": {\n 'id': id(),\n \"feature\": {'id': id(), \"index\": 0, \"name\": \"label feature\", \"type\": \"LABEL\"},\n \"data\": [\n {'id': id(), \"text\": \"value 1\"},\n {'id': id(), \"text\": \"value 2\"}\n ]\n }\n }\n\n cls.df_dict = {\n \"feature 0\": [\"Hello\", \"Hello\"],\n \"feature 1\": [1.2, 2.5],\n \"feature 2\": [\n [\"a\", \"b\"],\n [\"d\", \"e\"]\n ]\n }\n\n cls.labeled_df_dict = {\n **cls.df_dict,\n \"label feature\": [\n \"value 1\",\n \"value 2\"\n ],\n }\n\n \n def test_get_data_field_name(self):\n self.assertEqual('numerical', getDataFieldName('NUMERICAL'))\n self.assertEqual('text', getDataFieldName('CATEGORICAL'))\n self.assertEqual('text', getDataFieldName('TEXT'))\n self.assertEqual('set', getDataFieldName('SET'))\n self.assertEqual('numerical', getDataFieldName('BOOLEAN'))\n \n\n def test_infer_feature_type(self):\n numerical_series_1 = pd.Series([1,2,3])\n numerical_series_2 = pd.Series([0.57, 0.61])\n boolean_series_1 = pd.Series(['true','true'])\n boolean_series_2 = pd.Series(['false', 'false'])\n set_series_1 = pd.Series([[1,2], [3,4]])\n set_series_2 = pd.Series([(1,2), (3,4)])\n set_series_3 = pd.Series([{1,2}, {3,4}])\n text_series_1 = pd.Series(['Lorem ipsum dolor sit amet','consectetur adipiscing elit'])\n text_series_2 = pd.Series(['set_field::m=0.73;set_field::t=-0.28','cat_field::Health Care=0.68;set_field::i=-0.3'])\n\n self.assertEqual('NUMERICAL', inferFeatureType(numerical_series_1))\n self.assertEqual('NUMERICAL', inferFeatureType(numerical_series_2))\n self.assertEqual('BOOLEAN', inferFeatureType(boolean_series_1))\n self.assertEqual('BOOLEAN', inferFeatureType(boolean_series_2))\n self.assertEqual('SET', inferFeatureType(set_series_1))\n self.assertEqual('SET', inferFeatureType(set_series_2))\n self.assertEqual('SET', inferFeatureType(set_series_3))\n self.assertEqual('TEXT', inferFeatureType(text_series_1))\n self.assertEqual('TEXT', inferFeatureType(text_series_2))\n\n\n def test_dataframe_to_dataset(self):\n df = pd.DataFrame(self.df_dict)\n result = dataframeToDataset(df)\n expected = self.ds\n\n #generated IDs can't be the same\n result.pop('id')\n for f in result['features']:\n f.pop('id')\n f['feature'].pop('id')\n for ditem in f['data']:\n ditem.pop('id')\n\n self.assertEqual(expected, result)\n\n\n def test_dataset_to_dataframe(self):\n expected = pd.DataFrame(self.df_dict)\n result = datasetToDataframe(self.ds)\n assert_frame_equal(expected.reset_index(drop=True), result.reset_index(drop=True))\n\n\n def test_labeled_dataset_to_dataframe(self):\n expected = pd.DataFrame(self.labeled_df_dict)\n result = datasetToDataframe(self.labeled_ds)\n assert_frame_equal(expected.reset_index(drop=True), result.reset_index(drop=True))\n\n\n\nif __name__ == '__main__':\n unittest.main()\n"
},
{
"alpha_fraction": 0.5459479689598083,
"alphanum_fraction": 0.5483810305595398,
"avg_line_length": 29.8843936920166,
"blob_id": "f1fee3afe52d43cc58bbf7bec856666a307eac08",
"content_id": "bf246f49da7d2390fff1696f2c6ef7b50d9c0fa4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5343,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 173,
"path": "/app/logic/classify.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport datetime\n\nfrom app.logic.helpers import datasetToDataframe, dataframeToDataset, id\nfrom app.core.main.Classifier import Classifier\nfrom app.logic.train import loadTrainedModel\nfrom app.logic.model_selection import cachedMSR\n\n\n\ndef unpackProbs(prob):\n res_dict = {}\n all_labels_list = []\n\n probList = prob.split(',')\n \n for kv in probList:\n k,v = kv.split(':')\n v = float(v)\n res_dict[k] = v\n predictedLabel = {\n 'id': id(),\n 'label': k,\n 'probability': v\n }\n all_labels_list.append(predictedLabel)\n \n return res_dict, all_labels_list\n\n\ndef unpackContribs(contrib):\n res = []\n if len(contrib) > 0:\n contributors = contrib.split(';')\n\n for contributor in contributors:\n assert '=' in contributor, \"bad contributor:\" + '-->' + contributor + '<--' + ' in ' + '\"' + contrib + '\"'\n feat, weight = contributor.split('=')\n if '::' in feat:\n field_name, field_value = feat.split('::')\n else:\n field_name, field_value = feat, ''\n\n res.append({\n 'id': id(),\n 'featureName': field_name,\n 'featureValue': field_value,\n 'weight': float(weight)\n })\n\n return res\n\n\ndef unpackSuggestedFeatures(suggestions):\n res = []\n if len(suggestions) > 0:\n suggested_features = suggestions.split(',')\n\n for feat in suggested_features:\n if '::' in feat:\n field_name, field_value = feat.split('::')\n else:\n field_name, field_value = feat, ''\n\n res.append({\n 'id': id(),\n 'featureName': field_name,\n 'featureValue': field_value,\n 'weight': 1.\n })\n\n return res\n\n\n\ndef classify(cachedModelID, data):\n startedTime = datetime.datetime.now()\n assert(cachedModelID in cachedMSR), \"Model not found.\"\n model = cachedMSR[cachedModelID]['selectedModel']\n\n emptyResults = {\n 'id': -1,\n 'classSummaries': []\n }\n\n #debug\n print('Received a dataset with ', len(data['features']), ' features to classify.')\n if (len(data['features']) ==0):\n print('There is no feature, empty result set is returned.')\n return emptyResults\n print('Received a dataset with ', len(data['features'][0]['data']), ' rows to classify.')\n if (len(data['features'][0]['data']) ==0):\n print('There is no data, empty result set is returned.')\n return emptyResults\n\n candidate = model[\"candidate\"]\n features = candidate[\"features\"]\n config = candidate[\"config\"]\n\n unlabeled_df = datasetToDataframe(data)\n filtered_input_df = unlabeled_df.filter([f['name'] for f in features])\n\n lr, fm, lm = loadTrainedModel(model)\n\n ac = Classifier(model_configuration=config)\n ac.load_models(lr, fm, lm)\n\n res_df = ac.predict_explain(input_df=filtered_input_df, topN_features=10)\n reccom_df = ac.input_qlty(input_df=filtered_input_df, topN=10)\n res_df = pd.concat([res_df, reccom_df.filter([\"SuggestedFeatures\"])], axis=1)\n\n plCountSeries = res_df.groupby('PredictedLabel').PredictedLabel.count()\n labels = list(plCountSeries.keys())\n\n classSummaries = []\n\n for label in labels:\n filtered_res_df = res_df[res_df.PredictedLabel == label]\n entropies = []\n probabilities = []\n results = []\n for data_index, row in filtered_res_df.iterrows():\n entropies.append(float(row.Entropy))\n probsDict, allLabels = unpackProbs(row.Probabilities)\n probabilities.append(float(probsDict[label]))\n contributors = unpackContribs(row.TopContributors)\n recommends = unpackSuggestedFeatures(row.SuggestedFeatures)\n\n input_data = []\n for feat in data['features']:\n input_data.append({'id': id(), 'feature': feat['feature'], 'data': [feat['data'][data_index]]})\n data_instance = {\n 'id': id(),\n 'dataset': { 'id': id(),\n 'features': input_data},\n 'index': data_index\n }\n\n classificationResult = {\n 'id': id(),\n 'allLabels': allLabels,\n 'entropy': float(row.Entropy),\n 'contributors': contributors,\n 'dataInstance': data_instance,\n 'predictedLabel': {\n 'id': id(),\n 'label': label,\n 'probability': float(probsDict[label])\n },\n 'recommends': recommends\n }\n\n results.append(classificationResult)\n \n classSumary = {\n 'id': id(),\n 'label': label,\n 'numInstances': int(plCountSeries[label]),\n 'probabilities': probabilities,\n 'entropies': entropies,\n 'results': results\n }\n\n classSummaries.append(classSumary)\n\n batchClassificationResult = {\n 'id': id(),\n \"classSummaries\": classSummaries\n }\n\n print('Classification time:' + str((datetime.datetime.now() - startedTime).total_seconds()) + ' seconds ')\n\n return batchClassificationResult\n"
},
{
"alpha_fraction": 0.6034858226776123,
"alphanum_fraction": 0.6122004389762878,
"avg_line_length": 27.102041244506836,
"blob_id": "d21373c4892313b558425010bedb064b6d731c37",
"content_id": "6ab8bb884537389e71d826b77f42dbe7be3ed4d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1377,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 49,
"path": "/app/core/main/feature_selection/LabelCorrelation.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nRank features by its correlation with label\n scikit learn methods:\n SelectKBest\n SelectPercentile\n SelectFdr\n SelectFpr\n SelectFwe\n GenericUnivariateSelect\n'''\n\nfrom sklearn.feature_selection import GenericUnivariateSelect\nfrom sklearn.feature_selection import chi2\nimport numpy as np\n\n\n\nclass LabelCorrelation(object):\n\n def __init__(self, n):\n assert type(n) is int and n > 0 or \\\n type(n) is float and n > 0 and n <= 1, \"Invalid parameter value %s (number of features or percentile)\" % n\n self.__n = n\n self.__model = None\n if type(n) is int and n > 0:\n self.__model = GenericUnivariateSelect(chi2, mode='k_best', param = self.__n)\n elif type(n) is float and n > 0 and n <= 1:\n self.__model = GenericUnivariateSelect(chi2, mode='percentile', param = self.__n)\n\n\n\n def score_features(self, X, Y):\n someNegative = np.any(X < 0.0)\n assert not someNegative, \"Chisquare correlation requires non-negative feature values.\"\n self.__model.fit(X, Y)\n return self.__model.scores_\n\n\n\n def select_features(self, X):\n self.__model.transform(X)\n\n\n\n def __str__(self):\n return '''\n Correlation feature selection using chi2 (either k-best or percentile):\n Top features selected: %s \n ''' % self.__n\n"
},
{
"alpha_fraction": 0.6190977692604065,
"alphanum_fraction": 0.6300954818725586,
"avg_line_length": 41.416202545166016,
"blob_id": "d0e43851bf6ecb438129a03fd0e67b0f045cf639",
"content_id": "af0b2df421a68aa726437fa57f429bdf21dca072",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15187,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 358,
"path": "/app/test/setup.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "\nimport random as rd\nfrom app.logic.helpers import id\n\n\nwords = '''\n The distribution of oil and gas reserves among the world's 50 largest oil companies. The reserves of the privately\n owned companies are grouped together. The oil produced by the \"supermajor\" companies accounts for less than 15% of\n the total world supply. Over 80% of the world's reserves of oil and natural gas are controlled by national oil companies.\n Of the world's 20 largest oil companies, 15 are state-owned oil companies.\n The petroleum industry, also known as the oil industry or the oil patch, includes the global processes of exploration,\n extraction, refining, transporting (often by oil tankers and pipelines), and marketing of petroleum products.\n The largest volume products of the industry are fuel oil and gasoline (petrol). Petroleum (oil) is also the raw material\n for many chemical products, including pharmaceuticals, solvents, fertilizers, pesticides, synthetic fragrances, and plastics.\n The industry is usually divided into three major components: upstream, midstream and downstream. Midstream operations are\n often included in the downstream category.\n Petroleum is vital to many industries, and is of importance to the maintenance of industrial civilization in its\n current configuration, and thus is a critical concern for many nations. Oil accounts for a large percentage of the\n world’s energy consumption, ranging from a low of 32% for Europe and Asia, to a high of 53% for the Middle East.\n Governments such as the United States government provide a heavy public subsidy to petroleum companies, with major\n tax breaks at virtually every stage of oil exploration and extraction, including the costs of oil field leases and\n drilling equipment.[2]\n Principle is a term defined current-day by Merriam-Webster[5] as: \"a comprehensive and fundamental law, doctrine,\n or assumption\", \"a primary source\", \"the laws or facts of nature underlying the working of an artificial device\",\n \"an ingredient (such as a chemical) that exhibits or imparts a characteristic quality\".[6]\n Process is a term defined current-day by the United States Patent Laws (United States Code Title 34 - Patents)[7]\n published by the United States Patent and Trade Office (USPTO)[8] as follows: \"The term 'process' means process,\n art, or method, and includes a new use of a known process, machine, manufacture, composition of matter, or material.\"[9]\n Application of Science is a term defined current-day by the United States' National Academies of Sciences, Engineering,\n and Medicine[12] as: \"...any use of scientific knowledge for a specific purpose, whether to do more science; to design\n a product, process, or medical treatment; to develop a new technology; or to predict the impacts of human actions.\"[13]\n The simplest form of technology is the development and use of basic tools. The prehistoric discovery of how to control\n fire and the later Neolithic Revolution increased the available sources of food, and the invention of the wheel\n helped humans to travel in and control their environment. Developments in historic times, including the printing\n press, the telephone, and the Internet, have lessened physical barriers to communication and allowed humans to\n interact freely on a global scale.\n Technology has many effects. It has helped develop more advanced economies (including today's global economy)\n and has allowed the rise of a leisure class. Many technological processes produce unwanted by-products known as\n pollution and deplete natural resources to the detriment of Earth's environment. Innovations have always influenced\n the values of a society and raised new questions of the ethics of technology. Examples include the rise of the\n notion of efficiency in terms of human productivity, and the challenges of bioethics.\n Philosophical debates have arisen over the use of technology, with disagreements over whether technology improves\n the human condition or worsens it. Neo-Luddism, anarcho-primitivism, and similar reactionary movements criticize\n the pervasiveness of technology, arguing that it harms the environment and alienates people; proponents of ideologies\n such as transhumanism and techno-progressivism view continued technological progress as beneficial to society and\n the human condition.\n Health care or healthcare is the maintenance or improvement of health via the prevention, diagnosis, and treatment\n of disease, illness, injury, and other physical and mental impairments in human beings. Healthcare is delivered by\n health professionals (providers or practitioners) in allied health fields. Physicians and physician associates are\n a part of these health professionals. Dentistry, midwifery, nursing, medicine, optometry, audiology, pharmacy,\n psychology, occupational therapy, physical therapy and other health professions are all part of healthcare. It\n includes work done in providing primary care, secondary care, and tertiary care, as well as in public health.\n Access to health care may vary across countries, communities, and individuals, largely influenced by social and\n economic conditions as well as the health policies in place. Countries and jurisdictions have different policies\n and plans in relation to the personal and population-based health care goals within their societies. Healthcare\n systems are organizations established to meet the health needs of targeted populations. Their exact configuration\n varies between national and subnational entities. In some countries and jurisdictions, health care planning is\n distributed among market participants, whereas in others, planning occurs more centrally among governments or\n other coordinating bodies. In all cases, according to the World Health Organization (WHO), a well-functioning\n healthcare system requires a robust financing mechanism; a well-trained and adequately paid workforce; reliable\n information on which to base decisions and policies; and well maintained health facilities and logistics to deliver\n quality medicines and technologies.[1]\n Health care is conventionally regarded as an important determinant in promoting the general physical and mental\n health and well-being of people around the world. An example of this was the worldwide eradication of smallpox\n in 1980, declared by the WHO as the first disease in human history to be completely eliminated by deliberate health\n care interventions.[4]\n '''.split()\n\n\ndef random_feature():\n feature_types = ['NUMERICAL', 'CATEGORICAL', 'TEXT', 'SET', 'BOOLEAN']\n fIndex = rd.randint(0, 100)\n fName = 'feature' + str(fIndex) + id()[:8]\n fTypeIdx = rd.randint(0, len(feature_types)-1)\n fType = feature_types[fTypeIdx]\n\n return {\n 'id': id(),\n 'index': fIndex,\n 'name': fName,\n 'type': fType\n }\n\n\ndef random_train_group_feature():\n fIndex = rd.randint(0, 100)\n fName = 'TRAIN_GROUP'\n fType = 'NUMERICAL'\n\n return {\n 'id': id(),\n 'index': fIndex,\n 'name': fName,\n 'type': fType\n }\n\n\ndef random_dataentry(ftype):\n if ftype in [\"CATEGORICAL\"]:\n num_categories = rd.randint(6, 22)\n dval = \"string \" + str(rd.randint(1, num_categories))\n return {'id': id(), 'text': dval}\n elif ftype in [\"TEXT\"]:\n random_words = []\n for _ in range(rd.randint(50, 300)):\n random_words.append(words[rd.randint(0, len(words)-1)])\n dval = \" \".join(random_words)\n return {'id': id(), 'text': dval}\n elif ftype in [\"NUMERICAL\"]:\n dval = rd.randint(0, 100)*1.0/100\n return {'id': id(), 'numerical': dval}\n elif ftype in [\"BOOLEAN\"]:\n dval = rd.randint(0, 1)\n return {'id': id(), 'numerical': dval}\n else: #SET\n num_categories = rd.randint(3, 10)\n dval = []\n for _ in range(rd.randint(1, 3)):\n dval.append(\"string \" + str(rd.randint(1, num_categories)))\n return {'id': id(), 'set': dval}\n\n\n\ndef random_labeldata(num_classes):\n dval = \"class \" + str(rd.randint(1, num_classes))\n return {'id': id(), 'text': dval}\n\n\n\ndef dataentry_value(data, ftype):\n if ftype in [\"CATEGORICAL\", \"TEXT\"]:\n return data['text']\n elif ftype in [\"NUMERICAL\"]:\n return data['numerical']\n elif ftype in [\"BOOLEAN\"]:\n return data['numerical']\n else: #SET\n return data['set']\n\n\ndef random_dataset():\n num_features = rd.randint(10, 20)\n num_entries = rd.randint(100, 200)\n feature_data = []\n\n feature = random_train_group_feature()\n fvalues = []\n for _ in range(num_entries):\n fvalues.append({'id': id(), 'numerical': rd.randint(1,5)})\n feature_data.append({\n 'id': id(),\n 'feature': feature,\n 'data': fvalues\n })\n\n for _ in range(num_features):\n feature = random_feature()\n fvalues = []\n for _ in range(num_entries):\n fvalues.append(random_dataentry(feature['type']))\n feature_data.append({\n 'id': id(),\n 'feature': feature,\n 'data': fvalues\n })\n\n return {'id': id(), 'features': feature_data}\n\n\n\ndef random_labeled_dataset(num_classes=rd.randint(6, 8)):\n dataset = random_dataset()\n num_features = len(dataset['features'])\n label = {\n 'id': id(),\n 'index': num_features,\n 'name': \"Label\",\n 'type': \"LABEL\"\n }\n data = []\n num_entries = len(dataset['features'][0]['data'])\n\n for _ in range(num_entries):\n data.append(random_labeldata(num_classes=num_classes))\n feature_data = {'id': id(), 'feature': label, 'data': data}\n\n #Must be given unique ID.\n return {'id': id(),\n 'data': dataset,\n 'label': feature_data}\n\n\n\ndef random_class_weights(num_features, labels):\n class_weights = []\n for label in labels:\n intercept = rd.randint(0, 100)*1.0/100\n feature_weights = []\n for _ in range(num_features):\n num_weights = rd.randint(1, 10)\n feature_weights.append({'id': id(), 'feature': random_feature(), 'weights': [rd.randint(0, 100)*1.0/100] * num_weights })\n class_weights.append({'id': id(), 'weights': feature_weights, 'class': label, 'intercept': intercept})\n\n return class_weights\n\n\n\ndef random_noop():\n return {'id': id()}\n\n\n\ndef random_min_max_scaler():\n return {\n 'id': id(),\n 'minValue': rd.random(),\n 'maxValue': rd.randint(1, 10) + rd.random(),\n 'scale': rd.random(),\n 'dataMin': rd.random(),\n 'dataMax': rd.randint(1, 10) + rd.random()\n }\n\n\n\ndef random_label_binarizer(num_classes):\n return {\n 'id': id(),\n 'labels': [ \"Label \" + str(n+1) for n in range(num_classes)]\n }\n\n\n\ndef random_multilabel_binarizer(num_classes):\n return {\n 'id': id(),\n 'labels': [ \"Label \" + str(n+1) for n in range(num_classes)]\n }\n\n\n\ndef random_label_encoder(num_classes):\n return {\n 'id': id(),\n 'labels': [ \"Label \" + str(n+1) for n in range(num_classes)]\n }\n\n\n\ndef random_tfidf_vectorizer():\n num_terms = rd.randint(100, 600)\n term_feature_mapping = []\n idfs = []\n for tidx in range(num_terms):\n term = \"term\" + str(tidx)\n fidx = 100 + tidx\n term_feature_mapping.append({'id': id(), 'term': term, 'featureIdx': fidx})\n idfs.append(rd.random())\n\n return {\n 'id': id(),\n 'vocab': term_feature_mapping,\n 'idf': idfs,\n 'stopwords': ['the', 'this', 'a', 'an', 'those', 'these', 'at', 'on']\n }\n\n\n\ndef random_doc_to_vector():\n return {\n 'id': id(),\n 'modelFile': 'fullpathText2VecBinaryFileName',\n 'maxNumWords': rd.randint(1000, 10000)\n }\n\n\n\ndef random_model_performance(num_classes):\n class_performances = []\n for lblidx in range(num_classes):\n label = \"Label \" + str(lblidx+1)\n buckets = []\n total_num_instances = 0\n for bucket_idx in range(num_classes):\n num_instances = rd.randint(20, 80)\n total_num_instances += num_instances\n buckets.append({\n 'id': id(),\n 'trueLabel': label,\n 'predictedLabel': \"Label \" + str(bucket_idx+1),\n 'numInstances': num_instances,\n 'weight': rd.random(),\n })\n perf = {\n 'id': id(),\n 'label': label,\n 'weight': rd.random(),\n 'numInstances': total_num_instances,\n 'classifiedAs': buckets,\n 'recall': rd.random(),\n 'precision': rd.random(),\n 'f1': rd.random()\n }\n class_performances.append(perf)\n\n return {\n 'id': id(),\n 'classPerformances': class_performances,\n 'numInstances': rd.randint(50, 100),\n 'avgRecall': rd.random(),\n 'avgPrecision': rd.random(),\n 'avgF1': rd.random()\n }\n\n\n\ndef random_batch_classification_results():\n dataset = random_dataset()\n num_classes = rd.randint(2, 5)\n probabilities = [1.0/num_classes] * num_classes\n classes = [\"Class \" + str(idx+1) for idx in range(num_classes)]\n\n allPredictedLabels = [{\n 'id': id(),\n 'label': lbl,\n 'probability': prob\n } for (lbl, prob) in zip(classes, probabilities)]\n\n class_summaries = []\n for clsidx in range(num_classes):\n num_instances = rd.randint(3, 10)\n results = []\n for instidx in range(num_instances):\n data_idx = rd.randint(0, len(dataset['features'][0]['data'])-1)\n input_data = []\n for feat in dataset['features']:\n input_data.append({'id': id(), 'feature': feat['feature'], 'data': [feat['data'][data_idx]]})\n data_instance = {'id': id(), 'features': input_data}\n results.append({\n 'id': id(),\n 'dataInstance': {'id': id(), 'dataset': data_instance, 'index': instidx},\n 'allLabels': allPredictedLabels,\n 'predictedLabel': allPredictedLabels[clsidx],\n 'entropy': rd.random(),\n 'contributors': [{'id': id(), 'featureName': 'topology', 'featureValue': 'topsides', 'weight': .68}],\n 'recommends': [{'id': id(), 'featureName': 'topology', 'featureValue': 'subsea', 'weight': .86}]\n })\n class_summaries.append({\n 'id': id(),\n 'label': classes[clsidx],\n 'numInstances': num_instances,\n 'probabilities': [1.0/num_classes] * num_instances,\n 'entropies': [rd.random()] * num_instances,\n 'results': results\n })\n\n return {\n 'id': id(),\n 'classSummaries': class_summaries\n }"
},
{
"alpha_fraction": 0.5765672922134399,
"alphanum_fraction": 0.5817060470581055,
"avg_line_length": 26.05555534362793,
"blob_id": "5220cfcef62b07b405178e2ea630458975aea21f",
"content_id": "d6aa86fe42f3c93404ac9a5fb06aaccce622e53c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 973,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 36,
"path": "/app/core/main/feature_selection/BackwardStepwise.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nBackward stepwise feature selection\n'''\n\nfrom sklearn.feature_selection import RFE\n\n\n\nclass BackwardStepwise(object):\n\n def __init__(self, n, estimator, step = 100):\n assert type(n) is int and n > 0, \"Invalid parameter type or value %s (number of features)\" % n\n assert type(step) is int and step > 0 , \"Invalid parameter type or value %s (step)\" % n\n\n self.__estimator = estimator\n self.__n = n\n self.__step = step\n self.__model = RFE(self.__estimator, n_features_to_select = self.__n, step = self.__step)\n\n\n def score_features(self, X, Y):\n self.__model.fit(X, Y)\n return self.__model.ranking_\n\n\n def select_features(self, X):\n return self.__model.transform(X)\n\n\n def __str__(self):\n return '''\n Backward stepwise feature selection:\n Top features selected: %s\n Step size: %s\n Estimator: %s\n ''' % (self.__n, self.__step, self.__estimator)"
},
{
"alpha_fraction": 0.5777701139450073,
"alphanum_fraction": 0.5877494812011719,
"avg_line_length": 36.701297760009766,
"blob_id": "06fd21cab92e2a6c0f0557c5a47ca81f7e6a9e4d",
"content_id": "3bef4dfade584415fa83d214d8216bdc0c9abe22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2906,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 77,
"path": "/app/test/model_selection.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "import unittest\n\nfrom app.logic.helpers import *\nfrom app.test.setup import *\n\nfrom app.logic.model_selection import model_selection\nfrom app.logic.train import train\n\n\n\n\n\nmodelTypes = [Classifier.LR_MODEL_TYPE, Classifier.SVC_MODEL_TYPE]\n\n\nclass ModelSelectionTest(unittest.TestCase):\n\n\n def test_model_selection(self):\n labeled_dataset = random_labeled_dataset()\n model_sel_params = defaultModelSelection()\n\n trained_models = []\n for _ in range(rd.randint(3, 8)):\n candidate = defaultCandidate(labeled_dataset)[0]\n candidate['config']['type'] = modelTypes[rd.randint(0, len(modelTypes)-1)]\n candidate['config']['C'] = int(rd.random()*100)\n candidate['config']['max_iter'] = 2\n\n if rd.random() > 0.5:\n #remove a random feature (must not the label)\n rand_fidx = rd.randint(0, len(candidate['features']) - 2)\n candidate['features'] = candidate['features'][:rand_fidx] + candidate['features'][rand_fidx+1:]\n candidate['featurizers'] = candidate['featurizers'][:rand_fidx] + candidate['featurizers'][rand_fidx+1:]\n\n #randomize configuration\n candidate['config']['penalty'] = \"L\" + str(rd.randint(1,2))\n candidate['config']['min_df'] = min(rd.random(), .20)\n candidate['config']['max_df'] = max(rd.random(), .80)\n candidate['config']['fitIntercept'] = rd.random() < 0.5\n candidate['config']['weighting'] = 'NONE' if rd.random() < 0.5 else 'BALANCED'\n candidate['config']['tf'] = 'LINEAR' if rd.random() < 0.5 else 'SUBLINEAR'\n candidate['config']['df'] = 'SMOOTH' if rd.random() < 0.5 else 'DEFAULT'\n\n task = {\n 'data': labeled_dataset,\n 'candidate': candidate,\n 'modelSelectionParams': model_sel_params\n }\n model = train(training_task=task)\n\n trained_models.append(model)\n\n\n\n for method in ['BEST', 'KNEE_POINT', 'ONE_STDEV', 'TWO_STDEV']:\n model_sel_params['method'] = method\n\n msr = model_selection(models=trained_models, model_sel=model_sel_params)\n\n self.assertIn('modelSelection', msr)\n self.assertIn('learnedModels', msr)\n self.assertIn('selectedModel', msr)\n\n self.assertIn('type', msr['selectedModel'])\n self.assertIn('candidate', msr['selectedModel'])\n self.assertIn('labels', msr['selectedModel'])\n self.assertIn('learnedWeights', msr['selectedModel'])\n self.assertIn('learnedFeaturizers', msr['selectedModel'])\n self.assertIn('labelEncoder', msr['selectedModel'])\n self.assertIn('degreeOfFreedom', msr['selectedModel'])\n self.assertIn('performance', msr['selectedModel'])\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n\n"
},
{
"alpha_fraction": 0.760401725769043,
"alphanum_fraction": 0.7647058963775635,
"avg_line_length": 30.68181800842285,
"blob_id": "f84e1bc15e145806e3f90afb70732a58f82fdf64",
"content_id": "f92b2e54b90abfbe0901e1076ea2d9a675eaf11b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 697,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 22,
"path": "/deploy.sh",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env sh\n\nif [ \"$#\" -ne 2 ]; then\n echo \"Illegal number of parameters. Must provide docker-registry, version-number\"\n exit\nfi\n\nregistry=$1\nversion=$2\n\ndocker build -t classification .\ndocker tag classification ${registry}/classification:${version}\ndocker push ${registry}/classification:${version}\n\nkubectl delete service classification\nkubectl delete deployment classification\n\ncat classification_deployment.yaml | sed -e \"s/{{docker-registry}}/${registry}/g\" -e \"s/{{version}}/${version}/g\"> finalized_classification_deployment.yaml\n\n#kubectl apply -f classification_pvc.yaml\nkubectl apply -f finalized_classification_deployment.yaml\nkubectl apply -f classification_service.yaml\n"
},
{
"alpha_fraction": 0.516088604927063,
"alphanum_fraction": 0.5219389796257019,
"avg_line_length": 31.78082275390625,
"blob_id": "03aa9edf1d133c33b31f1ffd16505e09f78d1f2d",
"content_id": "ec899fdd4a0f049c0419b9f119a89aaf9238edfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4786,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 146,
"path": "/app/core/main/classifier/LR.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nLogistic Regression\n'''\nfrom sklearn.linear_model import LogisticRegression\nimport numpy as np\n\n\n\nclass LR(object):\n\n def __init__(self, penalty=None, dual=None, solver=None, multi_class=None, class_weight=None, fit_intercept=None):\n self.__penalty = penalty\n self.__dual = dual\n self.__solver = solver\n self.__multi_class = multi_class\n self.__class_weight = class_weight\n self.__fit_intercept = fit_intercept\n\n #required by backward feature selection\n self.coef_ = None\n if penalty is None or dual is None or solver is None or multi_class is None or fit_intercept is None:\n self.__model = None\n else:\n self.__model = LogisticRegression(penalty=self.__penalty, dual=self.__dual, solver=self.__solver, multi_class=self.__multi_class,\n class_weight=self.__class_weight, fit_intercept=self.__fit_intercept, verbose=0)\n\n\n\n def fit(self, X, Y):\n self.__model.fit(X, Y)\n #required by backward feature selection\n self.coef_ = self.__model.coef_\n\n\n def predict(self, X):\n return self.__model.predict(X)\n\n\n def predict_proba(self, X):\n return self.__model.predict_proba(X)\n\n\n def get_weights(self, class_no):\n return self.get_all_weights()[class_no]\n\n\n def get_intercepts(self):\n if self.__fit_intercept:\n if len(self.__model.classes_) > 2:\n return self.__model.intercept_\n else:\n return np.array([self.__model.intercept_, self.__model.intercept_])\n else:\n return np.array([0.0] * len(self.__model.classes_))\n\n def get_all_weights(self):\n if len(self.__model.classes_) > 2:\n return self.__model.coef_\n else:\n return np.array([self.__model.coef_[0], self.__model.coef_[0]])\n\n\n def get_params(self, deep = True):\n params = {\n 'penalty': self.__penalty,\n 'dual': self.__dual,\n 'solver': self.__solver,\n 'multi_class': self.__multi_class,\n 'class_weight': self.__class_weight,\n 'fit_intercept': self.__fit_intercept,\n }\n\n #only available after trained\n if hasattr(self.__model, \"coef_\"):\n params.update({\n 'classes': self.__model.classes_.tolist(),\n })\n if self.__fit_intercept:\n if len(self.__model.classes_) > 2:\n params.update({\n 'intercept': self.__model.intercept_.tolist(),\n })\n else:\n params.update({\n 'intercept': [self.__model.intercept_[0], self.__model.intercept_[0]],\n })\n else:\n params.update({\n 'intercept': [0.0] * len(self.__model.classes_),\n })\n if len(self.__model.classes_) > 2:\n params.update({\n 'coef': self.__model.coef_.tolist(),\n })\n else:\n params.update({\n 'coef': [self.__model.coef_.tolist(), self.__model.coef_.tolist()],\n })\n return params\n\n\n\n def set_params(self, **params):\n if 'classes' in params:\n self.__model.classes_ = np.asarray(params['classes'], dtype=np.int32)\n if 'coef' in params:\n if len(self.__model.classes_) > 2:\n self.__model.coef_ = np.asarray(params['coef'], dtype=np.float64)\n else:\n self.__model.coef_ = np.asarray(params['coef'][0], dtype=np.float64)\n if 'intercept' in params:\n if len(self.__model.classes_) > 2:\n self.__model.intercept_ = np.asarray(params['intercept'], dtype=np.float64)\n else:\n self.__model.intercept_ = np.asarray(params['intercept'][:1], dtype=np.float64)\n if 'penalty' in params:\n self.__penalty = params['penalty']\n if 'dual' in params:\n self.__dual = params['dual']\n if 'solver' in params:\n self.__solver = params['solver']\n if 'multi_class' in params:\n self.__multi_class = params['multi_class']\n if 'class_weight' in params:\n self.__class_weight = params['class_weight']\n if 'fit_intercept' in params:\n self.__fit_intercept = params['fit_intercept']\n\n return\n\n\n def labels(self):\n return self.__model.classes_\n\n\n def num_classes(self):\n return len(self.__model.classes_)\n\n\n def num_weights(self):\n all_weights = self.get_all_weights()\n return len(all_weights[0])\n\n\n def __str__(self):\n return 'Logistic Regression.'\n"
},
{
"alpha_fraction": 0.5815783739089966,
"alphanum_fraction": 0.5840601325035095,
"avg_line_length": 46.170570373535156,
"blob_id": "fcb77d6f54a824bbd1f8564d123bdfa91b118f50",
"content_id": "d2604b6a4ce682fde681f17e4e3a61f07afce08b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14103,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 299,
"path": "/app/core/main/featurizer/Featurizer.py",
"repo_name": "maana-io/IRIS-Classification",
"src_encoding": "UTF-8",
"text": "'''\nFeaturizer\n'''\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import issparse\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.preprocessing import *\n\nfrom app.core.main.featurizer.Doc2Vector import Doc2Vector\n\n\n\n\nclass Featurizer(object):\n\n FT_Numeric = \"NUMERICAL\"\n FT_String = \"CATEGORICAL\"\n FT_Text = \"TEXT\"\n FT_Set = \"SET\"\n FT_Boolean = \"BOOLEAN\"\n FT_Label = \"LABEL\"\n FT_TXT2V = \"TEXT2VEC\"\n FT_UNDEFINED = \"UNDEFINED\"\n\n FT_NOOP = \"NOOP\"\n FT_MIN_MAX_SCALER = \"MIN_MAX_SCALER\"\n FT_LABEL_BINARIZER = \"LABEL_BINARIZER\"\n FT_TFIDF_VECTORIZER = \"TFIDF_VECTORIZER\"\n FT_MULTILABEL_BINARIZER = \"MULTILABEL_BINARIZER\"\n FT_LABEL_ENCODER = \"LABEL_ENCODER\"\n FT_TEXT_TO_VECTOR = \"TEXT_TO_VECTOR\"\n\n\n supported_types = [FT_Numeric, FT_String, FT_Text, FT_TXT2V, FT_Set, FT_Boolean, FT_Label, FT_UNDEFINED,\n FT_NOOP, FT_MIN_MAX_SCALER, FT_LABEL_BINARIZER, FT_TFIDF_VECTORIZER, FT_MULTILABEL_BINARIZER,\n FT_LABEL_ENCODER, FT_TEXT_TO_VECTOR]\n\n\n\n def __init__(self, field_names, field_types, max_df, min_df, stop_words,\n sublinear_tf, smooth_idf,\n ngram_range, tokenizer):\n self.__field_names = field_names\n self.__field_types = field_types\n self.__models = []\n self.__models_data = []\n self.__featurizer_end_offset = []\n self.__tokenizer = tokenizer\n self.__max_df = max_df\n self.__min_df = min_df\n self.__stop_words = stop_words\n self.__sublinear_tf = sublinear_tf\n self.__smooth_idf = smooth_idf\n self.__ngram_range = ngram_range\n\n self.__feats = None\n\n\n\n def __type_featurizer_map(self, type):\n assert type in Featurizer.supported_types, \"Invalid type %s, supported types are %s\" % (type, ','.join(Featurizer.supported_types))\n\n if type in [Featurizer.FT_Numeric, Featurizer.FT_MIN_MAX_SCALER]:\n return MinMaxScaler()\n elif type in [Featurizer.FT_Boolean, Featurizer.FT_String, Featurizer.FT_LABEL_BINARIZER]:\n return LabelBinarizer()\n elif type in [Featurizer.FT_Text, Featurizer.FT_TFIDF_VECTORIZER]:\n return TfidfVectorizer(input='content', max_df=self.__max_df, min_df=self.__min_df, stop_words=self.__stop_words,\n decode_error='ignore', sublinear_tf=self.__sublinear_tf, smooth_idf=self.__smooth_idf,\n ngram_range = self.__ngram_range, tokenizer = self.__tokenizer)\n elif type in [Featurizer.FT_Set, Featurizer.FT_MULTILABEL_BINARIZER]:\n return MultiLabelBinarizer()\n elif type in [Featurizer.FT_Label, Featurizer.FT_LABEL_ENCODER]:\n return LabelEncoder()\n elif type in [Featurizer.FT_TXT2V, Featurizer.FT_TEXT_TO_VECTOR]:\n return Doc2Vector()\n elif type in [Featurizer.FT_UNDEFINED, Featurizer.FT_NOOP]:\n return None\n\n\n\n def fit(self, data):\n '''\n :param data: must be a pandas DataFrame\n :return: None\n '''\n assert isinstance(data, pd.DataFrame), \"Expect a DataFrame object\"\n\n self.__models = []\n self.__models_data = []\n self.__featurizer_end_offset = []\n feat_offset = 0\n for (fieldNo, (fieldName, fieldData)) in enumerate(data.iteritems()):\n #debug\n print('Featurizer: fitting ' + fieldName)\n\n m = self.__type_featurizer_map(self.__field_types[fieldNo])\n\n if self.__field_types[fieldNo] in [Featurizer.FT_Numeric, Featurizer.FT_MIN_MAX_SCALER]:\n m.fit(fieldData.values.reshape(-1, 1))\n self.__models.append(m)\n feat_offset += 1\n self.__models_data.append(None)\n elif self.__field_types[fieldNo] in [Featurizer.FT_String, Featurizer.FT_LABEL_BINARIZER]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += len(self.__models[-1].classes_)\n self.__models_data.append(None)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Text, Featurizer.FT_TFIDF_VECTORIZER]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += len(self.__models[-1].vocabulary_)\n self.__models_data.append(dict((fidx, w) for (w, fidx) in self.__models[-1].vocabulary_.items()))\n elif self.__field_types[fieldNo] in [Featurizer.FT_Set, Featurizer.FT_MULTILABEL_BINARIZER]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += len(self.__models[-1].classes_)\n self.__models_data.append(self.__models[-1].classes_)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Boolean]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += 1\n self.__models_data.append(None)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Label, Featurizer.FT_LABEL_ENCODER]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += 1\n self.__models_data.append(None)\n elif self.__field_types[fieldNo] in [Featurizer.FT_TXT2V, Featurizer.FT_TEXT_TO_VECTOR]:\n m.fit(fieldData.values)\n self.__models.append(m)\n feat_offset += m.vector_size()\n self.__models_data.append(None)\n elif self.__field_types[fieldNo] in [Featurizer.FT_UNDEFINED, Featurizer.FT_NOOP]:\n self.__models.append(m)\n feat_offset += 1\n self.__models_data.append(None)\n self.__featurizer_end_offset.append(feat_offset)\n\n\n\n def transform(self, data):\n '''\n :param data: must be a pandas DataFrame\n :return: numpy ndarray\n '''\n assert isinstance(data, pd.DataFrame), \"Expect a DataFrame object\"\n\n self.__feats = None\n this_col_feats = None\n for (fieldNo, (fieldName, fieldData)) in enumerate(data.iteritems()):\n #debug\n print('Featurizer: transforming ' + fieldName)\n\n m = self.__models[fieldNo]\n if self.__field_types[fieldNo] in [Featurizer.FT_Numeric, Featurizer.FT_MIN_MAX_SCALER]:\n this_col_feats = m.transform(fieldData.values.reshape(-1, 1))\n elif self.__field_types[fieldNo] in [Featurizer.FT_String, Featurizer.FT_LABEL_BINARIZER]:\n this_col_feats = m.transform(fieldData.values)\n #transform binary encoder to one-hot encoder in case there are 2 classes\n if len(m.classes_) == 2 and this_col_feats.shape[1] == 1:\n this_col_feats = np.c_[1 - this_col_feats, this_col_feats]\n elif self.__field_types[fieldNo] in [Featurizer.FT_Text, Featurizer.FT_TFIDF_VECTORIZER]:\n this_col_feats = m.transform(fieldData.values)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Set, Featurizer.FT_MULTILABEL_BINARIZER]:\n this_col_feats = m.transform(fieldData.values)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Boolean]:\n this_col_feats = m.transform(fieldData.values)\n elif self.__field_types[fieldNo] in [Featurizer.FT_Label, Featurizer.FT_LABEL_ENCODER]:\n this_col_feats = m.transform(fieldData.values)\n elif self.__field_types[fieldNo] in [Featurizer.FT_TXT2V, Featurizer.FT_TEXT_TO_VECTOR]:\n this_col_feats = m.transform(fieldData.values)\n elif self.__field_types[fieldNo] in [Featurizer.FT_UNDEFINED, Featurizer.FT_NOOP]:\n this_col_feats = fieldData.values\n\n if issparse(this_col_feats):\n this_col_feats = this_col_feats.todense()\n if self.__feats is None:\n self.__feats = this_col_feats\n else:\n self.__feats = np.c_[self.__feats, this_col_feats]\n return self.__feats\n\n\n\n def inverse_transform(self, data):\n '''\n Use only for LABEL data.\n :param data: array like\n :return: array like\n '''\n assert len(self.__models)==1, \"Expect to have exactly one model.\"\n lbls = self.__models[0].inverse_transform(data)\n return lbls\n\n\n\n def fit_transform(self, data):\n self.fit(data)\n return self.transform(data)\n\n\n\n def set_params(self, models, model_data, featurizer_offsets, tokenizer):\n self.__models = models\n self.__models_data = model_data\n self.__featurizer_end_offset = featurizer_offsets\n self.__tokenizer = tokenizer\n\n\n def get_params(self):\n return self.__models, self.__models_data, self.__featurizer_end_offset, self.__tokenizer\n\n\n def __remove_special_chars(self, inp_str):\n return inp_str.replace(':', ' ').replace('=', ' ').replace(',', ' ').replace(';', ' ')\n\n\n def get_feature(self, featNo):\n assert featNo < self.__featurizer_end_offset[-1], \"Feature number %d is out of range!\" % featNo\n\n begin_offset = 0\n for(fieldNo, m) in enumerate(self.__models):\n if self.__featurizer_end_offset[fieldNo] > featNo:\n feat_offset = featNo - begin_offset\n if self.__field_types[fieldNo] in [Featurizer.FT_Numeric, Featurizer.FT_MIN_MAX_SCALER]:\n return self.__remove_special_chars(self.__field_names[fieldNo])\n elif self.__field_types[fieldNo] in [Featurizer.FT_String, Featurizer.FT_LABEL_BINARIZER]:\n return self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" + \\\n self.__remove_special_chars(self.__models[fieldNo].classes_[feat_offset])\n elif self.__field_types[fieldNo] in [Featurizer.FT_Text, Featurizer.FT_TFIDF_VECTORIZER]:\n return self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" + \\\n self.__remove_special_chars(self.__models_data[fieldNo][feat_offset])\n elif self.__field_types[fieldNo] in [Featurizer.FT_Set, Featurizer.FT_MULTILABEL_BINARIZER]:\n return self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" + \\\n self.__remove_special_chars(self.__models_data[fieldNo][feat_offset])\n elif self.__field_types[fieldNo] in [Featurizer.FT_Boolean]:\n return self.__remove_special_chars(self.__field_names[fieldNo])\n elif self.__field_types[fieldNo] in [Featurizer.FT_Label, Featurizer.FT_LABEL_ENCODER]:\n return self.__remove_special_chars(self.__field_names[fieldNo])\n elif self.__field_types[fieldNo] in [Featurizer.FT_TXT2V, Featurizer.FT_TEXT_TO_VECTOR]:\n return self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" + \\\n self.__remove_special_chars(str(feat_offset))\n elif self.__field_types[fieldNo] in [Featurizer.FT_UNDEFINED, Featurizer.FT_NOOP]:\n return self.__remove_special_chars(self.__field_names[fieldNo])\n else:\n begin_offset = self.__featurizer_end_offset[fieldNo]\n\n\n\n def get_all_features(self):\n f_names = []\n for(fieldNo, m) in enumerate(self.__models):\n if self.__field_types[fieldNo] in [Featurizer.FT_Numeric, Featurizer.FT_MIN_MAX_SCALER]:\n f_names.append(self.__remove_special_chars(self.__field_names[fieldNo]))\n elif self.__field_types[fieldNo] in [Featurizer.FT_String, Featurizer.FT_LABEL_BINARIZER]:\n f_names += [self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" +\n self.__remove_special_chars(cls) for cls in self.__models[fieldNo].classes_]\n elif self.__field_types[fieldNo] in [Featurizer.FT_Text, Featurizer.FT_TFIDF_VECTORIZER]:\n f_names += [self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" +\n self.__remove_special_chars(word) for (widx, word) in \\\n sorted(self.__models_data[fieldNo].items(), key = lambda widx_w: widx_w[0])]\n elif self.__field_types[fieldNo] in [Featurizer.FT_Set, Featurizer.FT_MULTILABEL_BINARIZER]:\n f_names += [self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" +\n self.__remove_special_chars(cls) for cls in self.__models_data[fieldNo]]\n elif self.__field_types[fieldNo] in [Featurizer.FT_Boolean]:\n f_names.append(self.__remove_special_chars(self.__field_names[fieldNo]))\n elif self.__field_types[fieldNo] in [Featurizer.FT_Label, Featurizer.FT_LABEL_ENCODER]:\n f_names.append(self.__remove_special_chars(self.__field_names[fieldNo]))\n elif self.__field_types[fieldNo] in [Featurizer.FT_TXT2V, Featurizer.FT_TEXT_TO_VECTOR]:\n f_names += [self.__remove_special_chars(self.__field_names[fieldNo]) + \"::\" +\n self.__remove_special_chars(str(fidx)) for fidx in range(self.__models[fieldNo].vector_size())]\n elif self.__field_types[fieldNo] in [Featurizer.FT_UNDEFINED, Featurizer.FT_NOOP]:\n f_names.append(self.__remove_special_chars(self.__field_names[fieldNo]))\n return f_names\n\n\n\n def get_schema(self):\n return self.__field_types\n\n\n\n def __str__(self):\n return '''\n Featurizer\n Supported data types: %s\n For Tfidf vectorizer: \n Min DF: %s\n Max DF: %s\n Sublinear TF: %s \n Smooth IDF: %s\n Stop words: %s\n Tokenizer: %s\n ngrams range: %s\n ''' % (Featurizer.supported_types, self.__min_df, self.__max_df, self.__sublinear_tf, self.__smooth_idf,\n self.__stop_words, self.__tokenizer, self.__ngram_range)"
}
] | 30 |
MThuro/DBHW-ML | https://github.com/MThuro/DBHW-ML | f09677b54fb114f3a1e333a32884a5553634d861 | 20c6d5af869fd8530ba8e003f5de9cb805c60240 | 8bb222bac0ba2639814ecababf5f15e0adc3a1ea | refs/heads/master | 2020-07-20T23:19:47.724120 | 2019-10-13T08:25:11 | 2019-10-13T08:25:11 | 206,723,140 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6759845018386841,
"alphanum_fraction": 0.6845541596412659,
"avg_line_length": 35.04411697387695,
"blob_id": "b16de342bd9014ee8dfd86e8c320093492cc9316",
"content_id": "d5738f236b8f2665cbcfc70a1091c613c39ccb25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4901,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 136,
"path": "/NN learn.py",
"repo_name": "MThuro/DBHW-ML",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Mareike Thurau\n@author: Silvan Mueller\n\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport time\nfrom tensorflow import keras\nfrom tensorflow import feature_column\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\n\nfrom random import random\n\ntf.enable_eager_execution()\n\n# Create preprocessors\nlabelEncoder = preprocessing.LabelEncoder()\nscaler = preprocessing.StandardScaler()\n\n# Request file path from user\ndata_file = input(\"Enter the path of your data file: \")\n\n# Read data from csv file\ndataframe = pd.read_csv(data_file,sep=';')\n\n# Convert column \"Einordnung\" into a discrete numerical value\ndataframe['Einordnung'] = pd.Categorical(dataframe['Einordnung'])\ndataframe['Einordnung'] = dataframe.Einordnung.cat.codes\n\n# Standardize numeric columns in order to increase accuracy\ndataframe[['Groesse', 'Gewicht', 'Alter']] = scaler.fit_transform(dataframe[['Groesse', 'Gewicht', 'Alter']])\n\n# Split data into train, test and validation examples\ntrain, test = train_test_split(dataframe, test_size=0.2)\ntrain, val = train_test_split(train, test_size=0.2)\n\n# Create a tf.data dataset from the dataframe\ndef df_to_dataset(features: np.ndarray, labels: np.ndarray, shuffle=True, batch_size=80):\n labels = labelEncoder.fit_transform(labels)\n ds = tf.data.Dataset.from_tensor_slices(\n ({\"feature\": features}, {\"Einordnung\": labels}))\n if shuffle:\n ds = ds.shuffle(buffer_size=len(features))\n ds = ds.batch(batch_size)\n return ds\n\n# Create feature layer\ndef create_feature_layer() -> keras.layers.DenseFeatures:\n # Feature column for height\n feature_height = feature_column.numeric_column(\"Groesse\")\n\n # Feature column for weight\n feature_weight = feature_column.numeric_column(\"Gewicht\")\n\n # Feature column for age\n feature_age = feature_column.numeric_column(\"Alter\") \n\n # Category column for gender\n feature_gender = feature_column.categorical_column_with_vocabulary_list(\n 'Geschlecht', ['w', 'm'])\n feature_gender_one_hot = feature_column.indicator_column(feature_gender)\n\n # Category column for activities \n feature_activities = feature_column.categorical_column_with_vocabulary_list(\n 'Betaetigung', ['keinSport', 'Kraftsport', 'Ausdauersport'])\n feature_activities_one_hot = feature_column.indicator_column(feature_activities)\n\n feature_columns = [feature_height, feature_weight,\n feature_age, feature_gender_one_hot, feature_activities_one_hot]\n\n return tf.keras.layers.DenseFeatures(feature_columns)\n\n# Define model\ndef define_model(input_shape: tuple, neuron_layer_1: int = 128, neuron_layer_2: int = 128) -> tf.keras.Model:\n \n inputs = tf.keras.Input(shape=input_shape, name=\"feature\")\n x = tf.keras.layers.Dense(neuron_layer_1, activation=\"relu\", name=\"hidden_layer_1\")(inputs)\n x = tf.keras.layers.Dense(neuron_layer_2, activation=\"relu\", name=\"hidden_layer_2\")(x)\n categories = tf.keras.layers.Dense(3, activation=\"softmax\", name=\"Einordnung\")(x)\n\n model = tf.keras.Model(\n inputs=inputs, outputs=categories, name=\"keras/tf_categories\")\n model.compile(optimizer=\"adam\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"accuracy\"],\n run_eagerly=True)\n return model \n\n# Train model\ndef train_model():\n best_test_acc = 0\n best_model = None\n\n # Get features from dataframes\n feature_convert = create_feature_layer()\n train_features = feature_convert(dict(train)).numpy()\n val_features = feature_convert(dict(val)).numpy()\n test_features = feature_convert(dict(test)).numpy()\n\n # Build data set\n train_ds = df_to_dataset(train_features, train[\"Einordnung\"].values)\n val_ds = df_to_dataset(val_features, val[\"Einordnung\"].values, shuffle=False)\n test_ds = df_to_dataset(test_features, test[\"Einordnung\"].values, shuffle=False)\n\n # Get model\n for x in range (0,3):\n neuron_layer_1 = np.random.randint(50, 150)\n neuron_layer_2 = np.random.randint(50, 150)\n\n model = define_model((train_features.shape[1],), neuron_layer_1, neuron_layer_2)\n model.fit(train_ds,\n validation_data=val_ds,\n epochs=5)\n\n # Evaluate model on test data to see accuracy\n test_loss, test_accuracy = model.evaluate(test_ds, verbose=0)\n\n # Compare accucary -> save best model\n if test_accuracy > best_test_acc:\n best_test_acc = test_accuracy\n best_model = model\n return best_test_acc, best_model\n \n# Execute training\ntest_accuracy, best_model = train_model()\nprint(test_accuracy)\n# Save model\nsaved_model_path = \"models/\" + \\\n f\"{test_accuracy:.2f}\"+\"_\"+time.strftime(\"%d%m%Y%H%M%S\")+\".h5\"\nbest_model.save(saved_model_path)\nprint(\"File has been saved under\", saved_model_path)"
},
{
"alpha_fraction": 0.7200823426246643,
"alphanum_fraction": 0.7250808477401733,
"avg_line_length": 34.81052780151367,
"blob_id": "066c4e1cf4a3a3bff665d5d7318034f1036fb2d6",
"content_id": "0c578e3809f7ff6247b6f073eeafbcf1e1a10b2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3404,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 95,
"path": "/NN predict.py",
"repo_name": "MThuro/DBHW-ML",
"src_encoding": "UTF-8",
"text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\n# import the necessary packages\nimport tensorflow as tf\nfrom tensorflow import feature_column\nimport numpy as np\nimport argparse\nimport random\nimport h5py\nimport time\nimport sys\n\nfrom sklearn import preprocessing\nimport numpy as np\nimport pandas as pd\nfrom keras.models import load_model\n\ntf.enable_eager_execution()\n\n# Request file paths\ndata_file = input(\"Enter the path of your data file: \")\nmodel_file = input(\"Enter the path of your model file: \")\n\n# Create preprocessors\nlabelEncoder = preprocessing.LabelEncoder()\nscaler = preprocessing.StandardScaler()\n\n# Create dataframe and labels\ndef df_to_dataset():\n # Read data from csv file\n dataframe = pd.read_csv(data_file,sep=';')\n\n # Preprocess data\n dataframe['Einordnung'] = pd.Categorical(dataframe['Einordnung'])\n dataframe['Einordnung'] = dataframe.Einordnung.cat.codes\n dataframe[['Groesse', 'Gewicht', 'Alter']] = scaler.fit_transform(dataframe[['Groesse', 'Gewicht', 'Alter']])\n\n return dataframe\n\n# Create feature layer\ndef create_feature_layer() -> tf.keras.layers.DenseFeatures:\n # Feature column for height\n feature_height = feature_column.numeric_column(\"Groesse\")\n\n # Feature column for weight\n feature_weight = feature_column.numeric_column(\"Gewicht\")\n\n # Feature column for age\n feature_age = feature_column.numeric_column(\"Alter\") \n\n # Category column for gender\n feature_gender = feature_column.categorical_column_with_vocabulary_list(\n 'Geschlecht', ['w', 'm'])\n feature_gender_one_hot = feature_column.indicator_column(feature_gender)\n\n # Category column for activities \n feature_activities = feature_column.categorical_column_with_vocabulary_list(\n 'Betaetigung', ['keinSport', 'Kraftsport', 'Ausdauersport'])\n feature_activities_one_hot = feature_column.indicator_column(feature_activities)\n\n feature_columns = [feature_height, feature_weight,\n feature_age, feature_gender_one_hot, feature_activities_one_hot]\n\n return tf.keras.layers.DenseFeatures(feature_columns)\n\n# Load Model from file\ndef loadModel():\n model_from_saved = tf.keras.models.load_model(model_file)\n model_from_saved.summary()\n return model_from_saved\n\n# Predict classification for test data\ndef predict(model: tf.keras.Model, dataframe):\n # Create feature mapping for dataframe\n feature_convert = create_feature_layer()\n data_features = feature_convert(dict(dataframe)).numpy()\n\n # Predict with learned model\n predictions = model.predict({\"feature\": data_features}) \n\n # Process results\n result = pd.DataFrame(predictions, columns=[\"Normalgewicht\", \"Übergewicht\", \"Untergewicht\"])\n result['Normalgewicht'] = pd.Series([\"{0:.2f}%\".format(val * 100) for val in result['Normalgewicht']], index = result.index)\n result['Übergewicht'] = pd.Series([\"{0:.2f}%\".format(val * 100) for val in result['Übergewicht']], index = result.index)\n result['Untergewicht'] = pd.Series([\"{0:.2f}%\".format(val * 100) for val in result['Untergewicht']], index = result.index)\n\n # Save to csv\n file_name = \"./predictions\" + time.strftime(\"%d%m%Y%H%M%S\") + \".csv\"\n result.to_csv(file_name, sep=';', encoding='utf-8') \n print(\"File has been saved under\", file_name)\n\n# Load and preprocess data from provided file\ndataframe = df_to_dataset()\nsaved_model = loadModel()\npredict(saved_model, dataframe)"
}
] | 2 |
ashmithv/firstflaskapp | https://github.com/ashmithv/firstflaskapp | 996435809ad728727c395f4f41063c7744c16a17 | 8045cd7506b1c489cf74a95a45661dd89ff13086 | 6ef548d9366c562dd7ef4a2df707da4da6a65195 | refs/heads/master | 2022-12-08T20:05:05.267015 | 2020-09-07T15:53:13 | 2020-09-07T15:53:13 | 293,322,264 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5852442383766174,
"alphanum_fraction": 0.5852442383766174,
"avg_line_length": 30.354839324951172,
"blob_id": "09dfee3977df70bdf996e972aad2ad1bc33fb291",
"content_id": "387e862f7d8a0336661895451d2cd2f7d4924039",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1003,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 31,
"path": "/project.py",
"repo_name": "ashmithv/firstflaskapp",
"src_encoding": "UTF-8",
"text": "from flask import Flask,request,render_template,make_response,session\r\n\r\napp=Flask(__name__)\r\n\r\n\r\[email protected]('/')\r\ndef home():\r\n return render_template('main.html')\r\n\r\[email protected]('/sign.html', methods=['GET' , 'POST'] )\r\ndef login():\r\n if not request.cookies.get('tour'):\r\n if request.method == 'POST':\r\n fname=request.form.get('fname')\r\n lastname=request.form.get('lname')\r\n address=request.form.get('address')\r\n passwrd=request.form.get('password')\r\n cpasswrd=request.form.get('cpassword')\r\n fav = str(request.form['favourite'])\r\n response=make_response(\"Kindly refresh the page\")\r\n response.set_cookie('tour' , fav)\r\n return response\r\n\r\n else:\r\n response=make_response(render_template('welcome.html' , cookie = str(request.cookies.get('tour') )))\r\n return response\r\n \r\n return render_template('sign.html')\r\n\r\nif __name__=='__main__':\r\n app.run(debug = True)\r\n"
}
] | 1 |
Doyamoo/haikusns | https://github.com/Doyamoo/haikusns | b76249d7c64e47b192d3e074c799ec710d9d88a3 | 8a9029dd5a886117278e43eecabcdb285b3e21f8 | ee80a05c1c308ff453482ba1868177663165fb57 | refs/heads/master | 2023-02-27T15:27:01.613570 | 2021-02-05T15:11:44 | 2021-02-05T15:11:44 | 335,963,669 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5894736647605896,
"alphanum_fraction": 0.5894736647605896,
"avg_line_length": 17.586956024169922,
"blob_id": "74c72a01bc13c538f1d03523003c1e050f1963d0",
"content_id": "84108be73ee12c4bf221c82fbb1b3610414cc83d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 865,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 46,
"path": "/sns_user.py",
"repo_name": "Doyamoo/haikusns",
"src_encoding": "UTF-8",
"text": "from flask import Flask, session, redirect\nfrom functools import wraps\n\n\nUSER_LOGIN_LIST = {\n 'taro': 'aaa',\n 'jiro': 'bbb',\n 'sabu': 'ccc',\n 'siro': 'ddd'\n}\n\n\ndef is_login():\n return 'login' in session\n\n\ndef try_login(form):\n user = form.get('user', '')\n password = form.get('pw', '')\n if user not in USER_LOGIN_LIST:\n return False\n if USER_LOGIN_LIST[user] != password:\n return False\n session['login'] = user\n return True\n\n\ndef get_id():\n return session['login'] if is_login() else '未ログイン'\n\n\ndef get_allusers():\n return [u for u in USER_LOGIN_LIST]\n\n\ndef try_logout():\n session.pop('login', None)\n\n\ndef login_required(func):\n @wraps(func)\n def wrapper(*args, **kwords):\n if not is_login():\n return redirect('/login')\n return func(*args, **kwords)\n return wrapper\n"
}
] | 1 |
vogelchr/esp8266_lua_ws2812 | https://github.com/vogelchr/esp8266_lua_ws2812 | 6faada8444315d058fdd6301d6aeaf65eba9d391 | 03ecd852eb5aaeb60801fc1f0bd6fdf761c39708 | 6308887edc32cf2ea48aad78aca1ed1be74f017d | refs/heads/master | 2020-09-29T05:47:23.699076 | 2019-12-21T16:36:06 | 2019-12-21T16:36:06 | 226,967,873 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6090425252914429,
"alphanum_fraction": 0.6356382966041565,
"avg_line_length": 25.85714340209961,
"blob_id": "cf5f3243d69e635431a26425e64674d74bde88c2",
"content_id": "92274628f913c3f4ccb7418dd1b2871561274998",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 376,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 14,
"path": "/init.lua",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "raw, extended = node.bootreason()\nprint(\"** Startup, bootreason is \" .. raw .. \"/\" .. extended)\nprint(\"**\")\nprint(\"** Press flash button to delay running my_init.\")\nprint(\"**\")\ngpio.mode(3, gpio.INPUT)\ntmr.delay(1000000)\n\nif gpio.read(3) == 1 then\n print(\"** Executing my_init.\")\n dofile(\"my_init.lc\") -- compiled\nelse\n print('** Skipping execution of my_init.')\nend\n"
},
{
"alpha_fraction": 0.5204140543937683,
"alphanum_fraction": 0.5399655103683472,
"avg_line_length": 31.811321258544922,
"blob_id": "58e036ef639a098349f6dfc35924032203b30fb6",
"content_id": "7da24abc8895242d959e377fdf8c370f73c4a3f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1739,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 53,
"path": "/send_zigzag_png.py",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\nimport PIL.Image\nimport argparse\nimport socket\nimport sys\nimport time\n\ndef img_into_led_bytearray(buf, img, width, height, offsx, offsy):\n for row in range(height) :\n for col in range(width) :\n # offset in LEDs!\n if (row % 2) == 0: # first, third, fifth\n offs = width * row + col\n else:\n # backwards from next row\n offs = width * (row + 1) - (col + 1)\n\n\n # now offset is in bytes (3per/LED)\n offs *= 3\n if row+offsy < img.size[1] and col+offsx < img.size[0] :\n r, g, b = img.getpixel((col+offsx, row+offsy))\n# print(f'{row}, {col} -> {offs} {r},{g},{b}')\n else :\n r, g, b = 0, 0, 0\n print(f'{row}, {col} -> {offs} (not im image)')\n\n buf[offs] = r\n buf[offs+1] = g\n buf[offs+2] = b\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('image')\nparser.add_argument('ipaddr')\nparser.add_argument('-p', '--port', default=5000,\n metavar='udp_port', help='UDP port number (def: 5000)')\nparser.add_argument('-H', '--height', default=7, type=int,\n help='LED matrix height (def: 7)')\nparser.add_argument('-W', '--width', default=42, type=int,\n help='LED matrix width (def: 42)')\n\nargs = parser.parse_args()\n\nbuf = bytearray(args.width * args.height * 3)\nimg = PIL.Image.open(args.image).convert('RGB')\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nfor x in range(1 + img.size[0] - args.width) :\n img_into_led_bytearray(buf, img, args.width, args.height, x, 0)\n sock.sendto(buf, (args.ipaddr, args.port))\n time.sleep(0.03)\n"
},
{
"alpha_fraction": 0.6301369667053223,
"alphanum_fraction": 0.6541095972061157,
"avg_line_length": 23.33333396911621,
"blob_id": "75c9d6dc0fc43de89c68c5c2459c8751b35f1b10",
"content_id": "36a95206ff47984fdb76ae72cd9863fd710613e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 584,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 24,
"path": "/build.sh",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nif ! [ -f \"credentials.lua\" ] ; then\n\tcp \"credentials_sample.lua\" \"credentials.lua\"\nfi\n\nif [ -n \"$1\" ] ; then\n\tappname=\"$1\"\nelse\n\tappname=\"1d\"\nfi\n\nif ! [ -f \"application_${appname}.lua\" ] ; then\n\techo \"Cannot upload, application_${appname}.lua is missing!\" >&2\n\texit 1\nfi\n\nluatool_arg=\"-v -p /dev/ttyUSB0 -b 115200 --delay 0.1\"\n\nluatool.py $luatool_arg -w\nluatool.py $luatool_arg -f init.lua\nluatool.py $luatool_arg -c -f credentials.lua\nluatool.py $luatool_arg -c -f my_init.lua\nluatool.py $luatool_arg -c -f \"application_${appname}.lua\" -t application.lua\n"
},
{
"alpha_fraction": 0.7313432693481445,
"alphanum_fraction": 0.7313432693481445,
"avg_line_length": 21.33333396911621,
"blob_id": "3e039c9e5c790f31b7645a6e80e4d6a5384138c6",
"content_id": "688ad4d25b04d234d9a9ee9181ddd1ab41b27dff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 3,
"path": "/credentials_sample.lua",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "-- credentials to access our WiFi\nwifi_ssid=\"XXXX\"\nwifi_psk=\"YYYY\"\n"
},
{
"alpha_fraction": 0.5355672836303711,
"alphanum_fraction": 0.568489134311676,
"avg_line_length": 20,
"blob_id": "ecfbeac9a05371fe5ed128ff419a7e8e52168b43",
"content_id": "595d256d887562938d2483e9797eb5ce06e1d16f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1701,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 81,
"path": "/application_1d.lua",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "led_timer = nil\nled_buf = nil\nled_bright = 200\nled_sat = 250\n\nled_val_angle = 0\nled_val_angle_inc = 3.25\n\nrunning = true\n\nled_tick = function()\n local a, da = led_val_angle, 720.0 / led_buf:size() -- two cycles / led strip\n\n local sat, bright = led_sat, led_bright\n local r, g, b, i\n\n for i=1, led_buf:size(), 1 do\n g, r, b = color_utils.hsv2grb(a, sat, bright)\n\n -- color wheel\n a = a + da\n if a > 360 then\n a = a - 360\n end\n\n led_buf:set(i, r, g, b)\n end\n ws2812.write(led_buf)\n\n led_val_angle = led_val_angle + led_val_angle_inc\n if led_val_angle >= 360 then\n led_val_angle = led_val_angle - 360\n end\n\n if running then\n led_timer:start() -- restart\n end\nend\n\nledapp_init = function(nled)\n if led_timer == nil then\n led_timer = tmr.create()\n else\n led_timer:unregister()\n end\n\n if led_buf == nil then\n ws2812.init()\n end\n\n if led_buf == nil or led_buf:size() ~= nled then\n led_buf = ws2812.newBuffer(nled, 3)\n end\n\n led_timer:register(12, tmr.ALARM_SEMI, led_tick)\n led_timer:start()\nend\n\nudp_receive_event = function(socket, data, port, ipaddr)\n if running then\n print(\"UDP from \" .. ipaddr .. \":\" .. port .. \". Stop animation.\")\n running = false\n end\n\n need_bytes = 3*led_buf:size()\n\n if data:len() == need_bytes then\n led_buf:replace(data)\n ws2812.write(led_buf)\n else\n print(\"Wrong UDP size, need \" .. need_bytes .. \" bytes.\")\n running = true\n led_timer:start()\n end\nend\n\nudp = net.createUDPSocket()\nudp:listen(5000)\nudp:on(\"receive\", udp_receive_event)\n\nledapp_init(294);\n"
},
{
"alpha_fraction": 0.6766467094421387,
"alphanum_fraction": 0.6841317415237427,
"avg_line_length": 28.66666603088379,
"blob_id": "ae984097e00b2da208fa0bc5c2b31d123d316c0d",
"content_id": "0ae52ded196158eb0c367e9ad4b2e0e3b3a152c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1336,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 45,
"path": "/my_init.lua",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "\n-- Define WiFi station event callbacks \nwifi_connect_event = function(T)\n print(\"*** WiFi connected, ssid is \" .. T.SSID)\n if disconnect_ct ~= nil then disconnect_ct = nil end \nend\n\nwifi_got_ip_event = function(T) \n print(\"*** WiFi IP address is \" .. T.IP)\n-- tmr.create():alarm(3000, tmr.ALARM_SINGLE, startup)\nend\n\nwifi_disconnect_event = function(T)\n print(\"** WiFi disconnected.\")\n for key,val in pairs(wifi.eventmon.reason) do\n if val == T.reason then\n print(\"** Disconnect reason: \" .. val .. \"(\" .. key .. \")\")\n break\n end\n end\nend\n\ntcp_recv_event = function(socket, data)\n print(data)\n socket:send(\"Received.\\r\\n\")\nend\n\ntcp_accept_event = function(conn)\n conn:on(\"receive\", tcp_recv_event)\n conn:send(\"Hello.\\r\\n\")\nend\n\ntcpsv = net.createServer(net.TCP, 5) -- 5s timeout\ntcpsv:listen(1234, tcp_accept_event)\n\n\n-- Register WiFi Station event callbacks\nwifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)\nwifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)\nwifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event)\n\nprint(\"** Starting WiFi.\")\ndofile(\"credentials.lc\") -- wifi_ssid, wifi_psk\nwifi.setmode(wifi.STATION)\nwifi.sta.config({ssid=wifi_ssid, pwd=wifi_psk}) -- config will auto-connect\ndofile(\"application.lc\")\n"
},
{
"alpha_fraction": 0.6016746163368225,
"alphanum_fraction": 0.6339712738990784,
"avg_line_length": 24.33333396911621,
"blob_id": "4141677b2f97c9a05c17c597bd7fa4bd35517f31",
"content_id": "296a5ac84dc0021331dd3bdb94c42d486a095404",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 836,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 33,
"path": "/send_rgb8x8.py",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\nimport time\nimport argparse\nimport sys\nimport socket\n\n# pipe in from ffmpeg -f rawvideo -c:v rawvideo -vf scale=8:8 -pix_fmt rgb24 ...\n\ndef reshuffle(a) :\n ret = bytearray(a)\n for row in range(1,8,2) :\n for col in range(8) :\n srcix = 24*row + 3*col\n dstix = 24*row + 3*(7-col)\n ret[dstix:dstix+3] = a[srcix:srcix+3]\n\n return ret\n\nparser = argparse.ArgumentParser()\nparser.add_argument('rawfile')\nparser.add_argument('ipaddr')\nparser.add_argument('-p', '--port', default=5000, metavar='udp_port')\n\nargs = parser.parse_args()\n\nfin = open(args.rawfile, 'rb')\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nwhile True :\n buf = fin.read(64*3)\n print('Read ', len(buf), 'bytes.')\n sock.sendto(reshuffle(buf), (args.ipaddr, args.port))\n time.sleep(0.05)\n"
},
{
"alpha_fraction": 0.4479338824748993,
"alphanum_fraction": 0.5,
"avg_line_length": 17.90625,
"blob_id": "f9b21ee365243ad056589a902101c9bd6deb3952",
"content_id": "6d0f42799838af7e8f596f43b7cb0eb0c35efab3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 2420,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 128,
"path": "/application_2d.lua",
"repo_name": "vogelchr/esp8266_lua_ws2812",
"src_encoding": "UTF-8",
"text": "\nM_PI = 3.141592653589793\n\n-- Bhaskara I's sine approximation formula\nfunction sin(a)\n while a > M_PI do\n a = a - 2*M_PI\n end\n while a < -M_PI do\n a = a + 2*M_PI\n end\n -- now -pi <= a <= pi\n\n if a < 0 then\n a = - a\n t = 4 * a * (M_PI - a)\n return - 4*t/(49.34802-t)\n else\n t = 4 * a * (M_PI - a)\n return 4*t/(49.34802-t)\n end\nend\n\nfunction cos(a)\n return sin(a + M_PI/2.0)\nend\n\nfunction clip(v, a, b)\n if v == nil then\n return a\n elseif v < a then\n return a\n elseif v > b then\n return b\n else\n return v\n end\nend\n\nfunction advance_phase(p, dp)\n p = p + dp\n if p > M_PI then\n return p - 2*M_PI\n else\n return p\n end\nend\n\n\nws2812.init()\nbuf = ws2812.newBuffer(64, 3)\nled_timer = tmr.create()\n\nmax_val = 40.0\nhue = 0\n\nphase_x = 0.0\ndp_x = 0.01\n\nphase_y = 0.0\ndp_y = 0.011\n\nrunning = true\n\nled_tick = function()\n xctr = sin(phase_x)\n yctr = sin(phase_y)\n\n for row=0,7,1 do\n x = row*0.28571 - 1\n for col=0,7,1 do\n y = col*0.28571 - 1\n -- 1 - r^2\n rsq = ((x-xctr)*(x-xctr)+(y-yctr)*(y-yctr))\n val = max_val*clip(1-rsq*rsq, 0, 1)\n\n gr, re, bl = color_utils.hsv2grb(hue, 255, val)\n\n -- row/col 0..7 to index 1..N\n -- zigzag order for 8x8 LED panel\n if (row % 2) == 1 then\n j = row * 8 + 8 - col\n else\n j = row * 8 + 1 + col\n end\n buf:set(j, re, gr, bl)\n\n end\n end\n\n ws2812.write(buf)\n\n phase_x = advance_phase(phase_x, dp_x)\n phase_y = advance_phase(phase_y, dp_y)\n\n hue = hue + 1\n if hue > 360 then\n hue = 0\n end\n\n if running then\n led_timer:start() -- restart\n end\nend\n\nled_timer:register(25, tmr.ALARM_SEMI, led_tick)\nled_timer:start()\n\nudp_receive_event = function(socket, data, port, ipaddr)\n if running then\n print(\"UDP from \" .. ipaddr .. \":\" .. port .. \". Stop animation.\")\n running = false\n end\n\n need_bytes = 3*buf:size()\n\n if data:len() == need_bytes then\n buf:replace(data)\n ws2812.write(buf)\n else\n print(\"Wrong UDP size, need \" .. need_bytes .. \" bytes.\")\n running = true\n led_timer:start()\n end\nend\n\nudp = net.createUDPSocket()\nudp:listen(5000)\nudp:on(\"receive\", udp_receive_event)"
}
] | 8 |
pkgit123/convert-unix-sap-time | https://github.com/pkgit123/convert-unix-sap-time | 7d1c6fceb2695005424442e89d28df5c0686e46a | dd60a06882d25841d78495bf21138a428f2c34bc | 61a555aeca1a70fbc257ed73b1f7978717a3e293 | refs/heads/main | 2023-07-09T15:28:36.011667 | 2021-08-16T22:51:36 | 2021-08-16T22:51:36 | 300,409,301 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5989034175872803,
"alphanum_fraction": 0.6351750493049622,
"avg_line_length": 33.867645263671875,
"blob_id": "ad3981c885395457e58f762e901a32df3d8e8260",
"content_id": "293a11c7fb782f1f8ff910bf0a7219c17682c229",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2371,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 68,
"path": "/convert-unix-sap-time.py",
"repo_name": "pkgit123/convert-unix-sap-time",
"src_encoding": "UTF-8",
"text": "import re\nimport datetime\nimport pytz\n\ndef convert_sap_time(str_dt_offset, str_tz):\n '''\n Convert SAP datetime offset into a normal datetime.\n Step 1: use regex to extract the offset.\n Step 2: convert the offset into UTC datetime.\n Step 3: convert UTC to local timezone. \n \n Example: '/Date(1569613743944)/'\n \n Time zones in pytz\n 'America/Los_Angeles': [x for x in pytz.all_timezones if 'Angeles' in x]\n 'UTC': [x for x in pytz.all_timezones if 'UTC' in x]\n \n Imports:\n re\n datetime\n pytz\n pandas as pd\n Inputs:\n str_dt_offset\n str_tz\n Returns:\n result : datetime in specific time-zome, e.g. Pacific Time\n \n Usage:\n \n print('Test out the convert_sap_time() function ...')\n print('Convert examples of sap_time ...')\n\n # convert SAP time to UTC timezone\n result1 = convert_sap_time('/Date(1504224000000)/', 'UTC')\n print('result1', result1)\n \n # convert SAP time to Los Angeles timezone\n result2 = convert_sap_time('/Date(1504224000000)/', 'America/Los_Angeles')\n print('result2', result2)\n \n References:\n https://blogs.sap.com/2013/04/28/working-with-odata-dates/\n https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p\n https://stackoverflow.com/questions/4666973/how-to-extract-the-substring-between-two-markers\n https://docs.python.org/3.7/library/re.html\n https://avilpage.com/2014/11/python-unix-timestamp-utc-and-their.html\n https://www.calazan.com/dealing-datetime-objects-and-time-zones-python-3/\n https://howchoo.com/g/ywi5m2vkodk/working-with-datetime-objects-and-timezones-in-python\n '''\n str_dt_offset = str(str_dt_offset)\n str_regex = '/Date\\((.+?)\\)'\n\n try:\n found = re.search(str_regex, str_dt_offset).group(1)\n assert len(found) == 13\n str_found = (found[:-3] + '.' + found[-3:])\n float_found = float(str_found)\n \n convert_timezone = pytz.timezone(str_tz)\n dt_utc = datetime.datetime.utcfromtimestamp(float_found).replace(tzinfo=pytz.utc)\n result = dt_utc.astimezone(tz=convert_timezone)\n \n except AttributeError:\n # AAA, ZZZ not found in the original string\n result = pd.NaT\n \n return result\n"
},
{
"alpha_fraction": 0.7370242476463318,
"alphanum_fraction": 0.7854671478271484,
"avg_line_length": 31.11111068725586,
"blob_id": "6b3c973221a9be9b11ab0a9844b5aaf855f67d5b",
"content_id": "f7b4b1c2bd40a5a1a9e47ac4996317dd2f73eb85",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 289,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 9,
"path": "/create-unix-time.py",
"repo_name": "pkgit123/convert-unix-sap-time",
"src_encoding": "UTF-8",
"text": "import time\nimport datetime\n\n# https://stackoverflow.com/questions/19801727/convert-datetime-to-unix-timestamp-and-convert-it-back-in-python\nstart_d = datetime.date(2021,8,8)\nstart_unixtime = time.mktime(start_d.timetuple())\nprint(start_d)\nprint(start_d.timetuple())\nprint(start_unixtime)\n"
},
{
"alpha_fraction": 0.6931089758872986,
"alphanum_fraction": 0.7708333134651184,
"avg_line_length": 48.91999816894531,
"blob_id": "7fee76c2933b5ef85d6d2caae8709d5b41999adf",
"content_id": "e35cf1a28955af85f69eba247dace84a19789ddb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1248,
"license_type": "no_license",
"max_line_length": 183,
"num_lines": 25,
"path": "/README.md",
"repo_name": "pkgit123/convert-unix-sap-time",
"src_encoding": "UTF-8",
"text": "# convert-unix-sap-time\nConvert Unix epoch time (aka SAP Timestamp)\n\nUnix operating system counts time as the number of seconds elasped since Jan 1, 1970 UTC (aka GMT). SAP also uses this same format, referred as SAP datetime offset.\n\nHowever most data analysis uses standard datetime formats, not Unix/SAP time. So this is a helper function to convert to normal time format, and optionally convert to local timezone.\n\nExample input:\n* Unix time - '1601582856'\n* SAP datetime offset - '/Date(1569613743944)/'\n\nExample output:\n* UTC: 2017-09-01 00:00:00+00:00\n* PST: 2017-08-31 17:00:00-07:00\n\nReferences:\n* https://en.wikipedia.org/wiki/Unix_time\n* https://www.epochconverter.com/\n* https://blogs.sap.com/2013/04/28/working-with-odata-dates/\n* https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p\n* https://stackoverflow.com/questions/4666973/how-to-extract-the-substring-between-two-markers\n* https://docs.python.org/3.7/library/re.html\n* https://avilpage.com/2014/11/python-unix-timestamp-utc-and-their.html\n* https://www.calazan.com/dealing-datetime-objects-and-time-zones-python-3/\n* https://howchoo.com/g/ywi5m2vkodk/working-with-datetime-objects-and-timezones-in-python\n"
}
] | 3 |
jonberliner/jordan_e | https://github.com/jonberliner/jordan_e | 89aefe099c753a668d2ad425010b736ce560d926 | 181d41f88a65a3a9833fa558fc08f10fef017897 | 69bc2c7110f3566be6477ca0a206e0c875799cae | refs/heads/master | 2021-01-19T12:39:38.243242 | 2015-03-12T15:55:23 | 2015-03-12T15:55:23 | 31,346,132 | 0 | 2 | null | null | null | null | null | [
{
"alpha_fraction": 0.6295680999755859,
"alphanum_fraction": 0.6378737688064575,
"avg_line_length": 65.88888549804688,
"blob_id": "aa49061dbf6b645532f4260aa9069bcca3b815f9",
"content_id": "0ecd7cd7ae1623a24e47b0c3dd9f6d5e1549c5ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 602,
"license_type": "no_license",
"max_line_length": 251,
"num_lines": 9,
"path": "/sync2aws.sh",
"repo_name": "jonberliner/jordan_e",
"src_encoding": "UTF-8",
"text": "expFolderName=${PWD##*/}\nsyncConfig=${1:0}\nif [syncConfig==1]\nthen\n rsync -rav --exclude='.git' --exclude='.DS_Store' --exclude='*.c' --exclude='*.so' --exclude='sync2aws.sh' --exclude='build' --exclude='test.db' --exclude='server.log' --exclude='*.pyc' --exclude='psd' ./* aws:$expFolderName\nelse\n echo 'WARNING: not syncing config.txt!\\n'\n rsync -rav --exclude='.git' --exclude='.DS_Store' --exclude='*.c' --exclude='*.so' --exclude='sync2aws.sh' --exclude='build' --exclude='config.txt' --exclude='test.db' --exclude='server.log' --exclude='*.pyc' --exclude='psd' ./* aws:$expFolderName\nfi\n"
},
{
"alpha_fraction": 0.6341230273246765,
"alphanum_fraction": 0.6373100876808167,
"avg_line_length": 41.20627975463867,
"blob_id": "8e77aab8eb0918267d83c3781b9816dfcb08be99",
"content_id": "45c5c20261ff658176bbe3354fb5a153e857835f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9413,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 223,
"path": "/rotationExperiment.py",
"repo_name": "jonberliner/jordan_e",
"src_encoding": "UTF-8",
"text": "from numpy import sum, concatenate, repeat, linspace, abs, ndarray, arange, mean\nfrom numpy.random import RandomState, permutation\nfrom numpy import array as npa\n\ndef rotationExperiment(domainbounds, rotmag, nPerXOpt,\\\n mindegArcPool, maxdegArcPool, nEpicycle, radwrtxArc,\\\n maxrotmag=None, degWhereRotIsZero=None, edgebuf=None,\\\n rngseed=None, blockTypes=None, agTypes=None,\\\n xOrigin=0.5, yOrigin=0.5):\n \"\"\"FIXME: need to include the params used for making clickArcQueue:\n mindegArcPool, maxdegArcPool, nEpicycle, radwrtx, xOrigin, and yOrigin.\n\n def rotationExperiment(domainbounds, rotmag, nPerXOpt,\n maxrotmag=None, degWhereRotIsZero=None, edgebuf=None,\n rngseed=None, blockTypes=None, agTypes=None)\n\n inputs:\n (note: - lo* means list of *\n - nparray means numpy array\n - lo* can usually be an nparray of *\n - float is a non-integer real scalar)\n - domainbounds (lofloat): min and max of domain\n - rotmag (float or lofloat): rotation magnitude\n - nPerXOpt (loint): n trials for each block\n - maxrotmag (float, default=None): max rotation used in this experiment\n by any subject (not necessarily this sub). Useful for matching\n degWhereRotIsZero between conditions, which is done randomly.\n if None, maxrotmag=rotmag\n - degWhereRotIsZero (float, default=None): where on the line it means\n rotation equals zero. If None, will be set randomly to fall\n within edgebuf of domain bounds.\n - rngseed (int, default=None): random number generator seed for\n matching between subjects. If None, will init rng w/o seed.\n - blockTypes (lostring, default=None): tells whether each block is\n 'baseline' (no rotation), 'rotation', or 'counterrotation'.\n If None, assumes all are rotation, and that the rotations are\n explicitely provided in rotmag as a lofloat\n - agTypes (lostring, default=None): whether each block is 'abrupt' or\n 'gradual'. If None, sets all blocks to abrupt. Last block must\n always be 'abrupt' (because nothing to gradually transition to)\n\n outputs:\n - xOptQueue (nparray): optimal location in the domain for each trial\"\"\"\n\n nBlock = len(nPerXOpt)\n mindomain, maxdomain = domainbounds\n # ambuiguous what rotation or counterrotation mean when multiple rots\n if type(rotmag) is list: assert not blockTypes\n\n if not degWhereRotIsZero: # random valid degWhereRotIsZero (i.e. veridical location)\n if rngseed: rng = RandomState(rngseed) # use seed if given\n else: rng = RandomState()\n\n if not edgebuf: edgebuf = 0. # no edge buffer by default\n if not maxrotmag: maxrotmag = rotmag\n\n # ensure rotations will fall in within edgebuf of domain\n # (wrt maxrotmag for counterbalancing b.t. groups)\n good = False\n while not good:\n degWhereRotIsZero = rng.uniform(low=mindomain, high=maxdomain)\n if degWhereRotIsZero - maxrotmag > mindomain + edgebuf:\n if degWhereRotIsZero + maxrotmag < maxdomain - edgebuf:\n good = True\n\n # default rotation for all blocks (so you can pass vector of custom rots)\n if not blockTypes:\n blockTypes = ['rotation' for _ in xrange(nBlock)]\n\n xOpts = []\n # get xOpt for each block relative to degWhereRotIsZero\n for bt in blockTypes:\n basenames = ['baseline', 'base', 'b']\n rotnames = ['rotation', 'rot', 'r']\n crotnames = ['counterrotation', 'crot', 'c']\n if bt in basenames:\n xOpt = degWhereRotIsZero\n elif bt in rotnames:\n xOpt = degWhereRotIsZero + rotmag\n elif bt in crotnames:\n xOpt = degWhereRotIsZero - rotmag\n else:\n raise ValueError('invalid blockType name %s' % (bt))\n xOpts.append(xOpt)\n\n if not agTypes:\n agTypes = ['abrupt' for _ in xrange(nBlock)]\n\n assert len(blockTypes) == len(xOpts) == len(nPerXOpt) == len(agTypes)\n xOptQueue = make_mixed_xOptQueue(xOpts, nPerXOpt, agTypes)\n\n # get the arcline for the experiment\n clickArcQueue = make_clickArcQueue(mindegArcPool, maxdegArcPool,\\\n nEpicycle, radwrtxArc,\\\n xOrigin, yOrigin)\n\n # package in dict and ship off\n experParams = {}\n experParams['xOptQueue'] = xOptQueue\n for ff in clickArcQueue: # extract params in clickArcQueue\n experParams[ff] = clickArcQueue[ff]\n\n return experParams\n\n\ndef make_mixed_xOptQueue(xOpts, nPerXOpt, agBlockTypes):\n \"\"\"def make_mixed_xOptQueue(xOpts, nPerXOpt, agBlockTypes)\n input:\n xOpts (float): a list of optimal aim locatations\n nPerXOpt (int): how many times each xOpt should be repeated\n agBlockTypes (str): 'a' (abrupt) or 'g' (gradual) block\n output:\n xOptQueue (lofloats): opt location for each trial\n \"\"\"\n abruptnames = ['abrupt', 'a']\n gradualnames = ['gradual', 'g']\n nBlock = len(xOpts)\n assert nBlock == len(nPerXOpt)\n nTrial = sum(nPerXOpt)\n blockqueues = []\n for b in xrange(nBlock):\n agThisBlock = agBlockTypes[b]\n if agThisBlock in abruptnames:\n blockqueue = repeat(xOpts[b], nPerXOpt[b])\n elif agThisBlock in gradualnames:\n blockqueue = linspace(xOpts[b], xOpts[b+1], nPerXOpt[b])\n else: raise ValueError('invalid agBlockType %s' % (agThisBlock))\n blockqueues.append(blockqueue)\n\n xOptQueue = concatenate(blockqueues)\n return xOptQueue\n\n\ndef make_abrupt_xOptQueue(xOpts, nPerXOpt):\n \"\"\"def make_abrupt_xOptQueue(xOpts, nPerXOpt)\n input:\n xOpts (float): a list of optimal aim locatations\n nPerXOpt (int): how many times each xOpt should be repeated\n output:\n xOptQueue (lofloats): opt location for each trial\n \"\"\"\n nBlock = len(xOpts)\n assert nBlock == len(nPerXOpt)\n nTrial = sum(nPerXOpt)\n miniqueues = [repeat(xOpts[b], nPerXOpt[b]) for b in xrange(nBlock)]\n xOptQueue = concatenate(miniqueues)\n return xOptQueue\n\n\ndef make_gradual_xOptQueue(xOpts, nPerXOpt):\n \"\"\"def make_abrupt_xOptQueue(xOpts, nPerXOpt)\n input:\n xOpts (float): a list of optimal aim locatations\n nPerXOpt (int): how many steps to move from xOpt[i] to xOpt[i+1]\n for final block, nPerXOpt repeats final value nPerXOpt[-1] times\n output:\n xOptQueue (lofloats): opt location for each trial\n \"\"\"\n nBlock = len(xOpts)\n assert nBlock == len(nPerXOpt)\n nTrial = sum(nPerXOpt)\n miniqueues = [linspace(xOpts[b], xOpts[b+1], nPerXOpt[b])\n for b in xrange(nBlock)-1]\n miniqueues += repeat(xOpts[-1], nPerXOpt[-1])\n xOptQueue = concatenate(miniqueues)\n return xOptQueue\n\n\ndef repeatIfScalar(thing, n):\n \"\"\"def repeatIfScalar(thing, n)\n input:\n thing (anything): thing checking if scalar\n n (int): times to repeat if scalar\n\n output:\n thing (list): thing repeated n times is scalar, else thing\"\"\"\n if not hasattr(thing, \"__len__\"): # if not list or nparray\n thing = repeat(thing, n)\n return thing\n\n\ndef make_clickArcQueue(mindegArcPool, maxdegArcPool, nEpicycle, radwrtxArc,\\\n xOrigin=0.5, yOrigin=0.5):\n \"\"\"make_clickArcQueue(mindegArcPool, maxdegArcPool, nEpicycle, radwrtxArc,\\\n xStart=0.5, yStart=0.5)\n input:\n - mindegArcPool (lofloat): degrees of cw-most edge of choice arc\n - mindegArcPool (lofloat): degrees of ccw-most edge of choice arc\n must be same size as mindegArcPool\n - nEpicycle (loint): number of rand perms of mindegArcPool\n - radwrtxArc (float in [0., 1.]): radius, in terms of percentage of\n width (x) of screen\n - xOrigin (float or lofloat in [0., 1.], default 0.5): arc origin as\n percent of screen width\n - yOrigin (float or lofloat in [0., 1.], default 0.5): arc origin as\n percent of screen height\n output:\n - out w fields [mindegqueue, maxdegqueue, radwrtxqueue,\n xoriginqueue, yoriginqueue],\n which specify the startpoint and choice arc for every trial of\n the experiment\n \"\"\"\n iInPool = len(mindegArcPool)\n assert len(maxdegArcPool) == iInPool\n radwrtxArcPool = repeatIfScalar(radwrtxArc, iInPool)\n xOriginPool = repeatIfScalar(xOrigin, iInPool)\n yOriginPool = repeatIfScalar(yOrigin, iInPool)\n # ensure lengths all kosher\n assert len(radwrtxArcPool) == iInPool\n assert len(xOriginPool) == iInPool\n assert len(yOriginPool) == iInPool\n\n iDegPool = arange(iInPool)\n iDegPoolQueue = concatenate([permutation(iDegPool)\n for _ in xrange(nEpicycle)])\n out = {}\n out['mindegarcqueue'] = npa([mindegArcPool[ii] for ii in iDegPoolQueue])\n out['maxdegarcqueue'] = npa([maxdegArcPool[ii] for ii in iDegPoolQueue])\n out['radwrtxarcqueue'] = npa([radwrtxArcPool[ii] for ii in iDegPoolQueue])\n out['xoriginqueue'] = npa([xOriginPool[ii] for ii in iDegPoolQueue])\n out['yoriginqueue'] = npa([yOriginPool[ii] for ii in iDegPoolQueue])\n\n return out\n\n"
},
{
"alpha_fraction": 0.7701612710952759,
"alphanum_fraction": 0.7701612710952759,
"avg_line_length": 21.545454025268555,
"blob_id": "d218fb2f3cdda9431264aaafd3c9e2623e3d1365",
"content_id": "fb272a1835dd40328e477d4af55a0142cad64ec3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 248,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 11,
"path": "/README.md",
"repo_name": "jonberliner/jordan_e",
"src_encoding": "UTF-8",
"text": "##rotation experiment analogue for taylor lab\n\n###NEEDS:\n- update consent, instructions, debreif\n- properly set experiment params\n\n###WANTS:\n- options for endpoint and online fb\n- add ringbreaking option\n- colorcode fb\n- add target hitting section\n"
},
{
"alpha_fraction": 0.522216260433197,
"alphanum_fraction": 0.6632762551307678,
"avg_line_length": 42.95294189453125,
"blob_id": "48b40b5812695a7a2d574f0a6d66e262c269c4ce",
"content_id": "949ccc92fb6c81d0d8368d37d019f5bbfb1ecde0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7472,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 170,
"path": "/custom.py",
"repo_name": "jonberliner/jordan_e",
"src_encoding": "UTF-8",
"text": "# this file imports custom routes into the experiment server\nfrom flask import Blueprint, render_template, request, jsonify, Response, abort, current_app\nfrom jinja2 import TemplateNotFound\nfrom functools import wraps\nfrom sqlalchemy import or_\n\nfrom psiturk.psiturk_config import PsiturkConfig\nfrom psiturk.experiment_errors import ExperimentError\nfrom psiturk.user_utils import PsiTurkAuthorization, nocache\n\n# # Database setup\nfrom psiturk.db import db_session, init_db\nfrom psiturk.models import Participant\nfrom json import dumps, loads\n\n# for basic experiment setup\nfrom numpy import linspace\nfrom numpy import array as npa\n\n# load the configuration options\nconfig = PsiturkConfig()\nconfig.load_config()\nconfig.SECREY_KEY = 'my_secret_key'\nmyauth = PsiTurkAuthorization(config) # if you want to add a password protect route use this\n\n# explore the Blueprint\ncustom_code = Blueprint('custom_code', __name__, template_folder='templates', static_folder='static')\n\nfrom rotationExperiment import rotationExperiment\n\n## GET SUBJECT EXPERIMENT PARAMS\n@custom_code.route('/init_experiment', methods=['GET'])\ndef init_experiment():\n if not request.args.has_key('condition'):\n raise ExperimentError('improper_inputs') # i don't like returning HTML to JSON requests... maybe should change this\n\n CONDITION = int(request.args['condition'])\n COUNTERBALANCE = int(request.args['counterbalance'])\n\n ## FREE VARS\n # made with numpy.random.randint(4294967295, size=100) # (number is max allowed on amazon linux)\n RNGSEEDPOOL =\\\n npa([3298170796, 2836114699, 599817272, 4120600023, 2084303722,\n 3397274674, 422915931, 1268543322, 4176768264, 3919821713,\n 1110305631, 1751019283, 2477245129, 658114151, 3344905605,\n 1041401026, 232715019, 326334289, 2686111309, 2708714477,\n 737618720, 1961563934, 2498601877, 210792284, 474894253,\n 4028779193, 237326432, 3676530999, 529417255, 3092896686,\n 169403409, 2615770170, 1339086861, 3757383830, 2082288757,\n 4170457367, 371267289, 3248256753, 1696640091, 2779201988,\n 492501592, 2278560761, 2146121483, 772692697, 2009991030,\n 1917110505, 621292942, 1900862326, 3924210345, 2834685808,\n 2782250785, 3978659517, 230589819, 3266844848, 1789706566,\n 1926158994, 3334290749, 2564647456, 2780425615, 2453304773,\n 2867246165, 2853230235, 3943014068, 1849702346, 1006440977,\n 326290567, 779365638, 2796156127, 2850718974, 4250010213,\n 1627130691, 3538373920, 1807938670, 2430758838, 1678867555,\n 515849939, 323252975, 1062571753, 551895230, 1003551997,\n 902827309, 2496798931, 4165811834, 88322007, 1998993400,\n 3260624632, 2504021401, 915464428, 2503603945, 1138822767,\n 1487903826, 3534352433, 2793970570, 3696596236, 3057302268,\n 2924494158, 1308408238, 2181850436, 2485685726, 1958873721])\n\n MINDEG = 0. # minumum degree of choiceSet\n MAXDEG = 360. # max degree of choiceSet\n RANGEDEG = MAXDEG - MINDEG\n\n ROTMAGPOOL = npa([15., 30., 45., 60.]) # proxy for 15, 30, 45, 60 degree rots\n\n ROTMAG = ROTMAGPOOL[CONDITION]\n NPERXOPT = [90, 40, 40, 90] # how many trials per block?\n NTRIAL = sum(NPERXOPT) # total number trials in experiment\n MAXROTMAG = 60. # maximum rotation considered for these experiments\n DEGWHEREROTISZERO = None # if none, will be random\n EDGEBUF = 10. # random degWhereRotIsZero will be between [MINDOMAIN+EDGEBUF, MAXDOMAIN-EDGEBUF]\n RNGSEED = RNGSEEDPOOL[COUNTERBALANCE]\n # 'b' for base, 'r' for rot, 'c' for counterrot\n BLOCKTYPES = ['b', 'r', 'c', 'b']\n # if None, all abrupt blocks.\n # (can be explicitely written as ['a', 'a', 'a', 'a'])\n AGTYPES = None\n # params for make_clickArcQueue, which determines startpoint and heading ang\n # NTARGET = 4\n # MINDEGARCPOOL = linspace(0., 360., NTARGET+1)[:-1] # ccw-most part of choice arc\n MINDEGARCPOOL = npa([0.])\n NTARGET = len(MINDEGARCPOOL)\n MAXDEGARCPOOL = MINDEGARCPOOL + RANGEDEG # cw-most part of choice arc\n assert NTRIAL % NTARGET == 0\n NEPICYCLE = NTRIAL / NTARGET # how many epicycles through each target loc\n RADWRTXARC = 0.3 # percent of window width that determines dist(start, arc)\n XORIGIN = 0.5 # x startpoint as percentage of window width\n YORIGIN = 0.5 # y startpoint as percentage of window height\n\n experParams = {# needed for make_mixed_xOptQueue\n 'domainbounds': [MINDEG, MAXDEG],\n 'rotmag': ROTMAG,\n 'nPerXOpt': NPERXOPT,\n 'radwrtxArc': RADWRTXARC,\n 'maxrotmag': MAXROTMAG,\n 'degWhereRotIsZero': DEGWHEREROTISZERO,\n 'edgebuf': EDGEBUF,\n 'rngseed': RNGSEED,\n 'blockTypes': BLOCKTYPES,\n 'agTypes': AGTYPES,\n # needed for make_clickArcQueue\n 'mindegArcPool': MINDEGARCPOOL,\n 'maxdegArcPool': MAXDEGARCPOOL,\n 'nEpicycle': NEPICYCLE,\n 'radwrtxArc': RADWRTXARC,\n 'xOrigin': XORIGIN,\n 'yOrigin': YORIGIN}\n\n # make experiment params for this subject!\n # (** means unpack and pass in params in a dict)\n subParams = rotationExperiment(**experParams)\n\n # add experiment params used on client side\n MSMINTIMEINSTART = 500 # ms to spend in startpoint before choice\n MSMAXTIMETOCHOICE = None\n MSSHOWFEEDBACK = 1000\n\n # must be in ['aboveStartPoint', 'clickLocation']\n FEEDBACKTYPE = 'aboveStartPoint'\n\n SDPERCENTRADWIGGLEFB = 0.1 # sd for wiggling rad wrt radius of choiceArc\n SDPERCENTDEGWIGGLEFB = 0.1 # sd for wiggling angle wrt RANGEDEG of choiceArc\n\n # number of prev scores to show on arc.\n # must be None if fbtype != 'clickLocation'\n NLASTTOSHOW = None\n # how far bt sp and arc should fb be? must be > 0\n # must be None if fbtype != 'aboveStartPoint'\n PERCENTBETWEENSPANDARC = 0.6\n if FEEDBACKTYPE=='aboveStartPoint': assert not NLASTTOSHOW\n if FEEDBACKTYPE=='clickLocation': assert not PERCENTBETWEENSPANDARC\n\n experParams['msmintimeinstart'] = MSMINTIMEINSTART\n experParams['msmaxtimetochoice'] = MSMAXTIMETOCHOICE\n experParams['msshowfeedback'] = MSSHOWFEEDBACK\n experParams['feedbacktype'] = FEEDBACKTYPE\n experParams['nlasttoshow'] = NLASTTOSHOW\n experParams['percentbetweenspandarc'] = PERCENTBETWEENSPANDARC\n experParams['sdpercentradwigglefb'] = SDPERCENTRADWIGGLEFB\n experParams['sdpercentdegwigglefb'] = SDPERCENTDEGWIGGLEFB\n experParams['ntrial'] = NTRIAL\n\n # bundle response to send\n resp = {}\n for f in subParams:\n fname = f\n if f == 'xOptQueue': fname = 'degoptqueue'\n try:\n resp[fname] = subParams[f].tolist()\n except:\n resp[fname] = subParams[f]\n\n for f in experParams:\n try: # convet numpy array to list if possible\n resp[f] = experParams[f].tolist()\n except:\n resp[f] = experParams[f]\n\n resp['inititrial'] = 0 # start at trial 0\n resp['rotmag'] = ROTMAG\n resp['rngseed'] = RNGSEED\n resp['initscore'] = 0 # start w 0 points\n resp['mindeg'] = MINDEG\n resp['maxdeg'] = MAXDEG\n\n return jsonify(**resp)\n"
},
{
"alpha_fraction": 0.5394049882888794,
"alphanum_fraction": 0.5458295345306396,
"avg_line_length": 34.302833557128906,
"blob_id": "ff14e638aa7fe32c0d2925218bd19705b5c0fd14",
"content_id": "1989cbf10df0d15bc14749decada92868866bb8b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 27395,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 776,
"path": "/static/js/rotationGame.js",
"repo_name": "jonberliner/jordan_e",
"src_encoding": "UTF-8",
"text": "/********************\n* ROTATION GAME *\n********************/\nvar rotationGame = function(){\n \"use strict\";\n var canvas = document.getElementById('easel');\n var W = canvas.width;\n var H = canvas.height;\n\n var stage = new createjs.Stage(canvas); // objects will go on stage\n\n var CHECKMOUSEFREQ = 10; // check for mouseover CHECKMOUSEFREQ times per sec\n stage.enableMouseOver(CHECKMOUSEFREQ);\n\n var MSTICK = 100; // run checkOnTick every MSTICK ms\n createjs.Ticker.setInterval(MSTICK);\n createjs.Ticker.addEventListener(\"tick\", function(event){\n checkOnTick(event, tp, wp, EP, STYLE.startPoint.sp.radius);\n });\n\n //////// INITIATE GAME\n var EP = {}; // params that stay constant through experiment\n var tp = {}; // params that change trial by trial\n var wp = {}; // params that can change within a trial\n var tsub = {}; // trial responses from subject that change trial by trial\n var fb_array, drill_history; // used to show (possibly persistent) feedback\n // containers that make up easeljs objects - objects are for easily\n // accessing shapes by name\n var background, startPoint, choiceSet, msgs;\n var a_background, a_startPoint, a_choiceSet; // arrays for ordered staging\n var QUEUES = {}; // queues containing trial params for each trial of experiment\n customRoute('init_experiment', // call init_experiment in custom.py...\n {'condition': condition, // w params condition adn counter...\n 'counterbalance': counterbalance},\n function(resp){ // once to get back resp from custom.py...\n EP.RNGSEED = resp['rngseed'];\n EP.INITSCORE = resp['initscore'];\n EP.MINDEG = resp['mindeg']; // min degree for choiceSet\n EP.MAXDEG = resp['maxdeg']; // max degree for choiceSet\n EP.RANGEDEG = EP.MAXDEG - EP.MINDEG;\n EP.NTRIAL = resp['ntrial'];\n QUEUES.XSTART = resp['xoriginqueue'];\n QUEUES.YSTART = resp['yoriginqueue'];\n QUEUES.RADWRTXARC = resp['radwrtxarcqueue'];\n QUEUES.MINDEGARC = resp['mindegarcqueue'];\n QUEUES.MAXDEGARC = resp['maxdegarcqueue'];\n QUEUES.DEGOPT = resp['degoptqueue']; // which location gets 100% points?\n EP.NTRIAL = QUEUES.DEGOPT.length;\n\n EP.MSMINTIMEINSTART = resp['msmintimeinstart'];\n EP.MSMAXTIMETOCHOICE = resp['msmaxtimetochoice'];\n if(EP.MSMAXTIMETOCHOICE==='None'){\n EP.MSMAXTIMETOCHOICE = null;\n }\n EP.MSSHOWFEEDBACK = resp['msshowfeedback'];\n\n EP.FEEDBACKTYPE = resp['feedbacktype'];\n EP.NLASTTOSHOW = resp['nlasttoshow'];\n EP.PERCENTBETWEENSPANDARC = resp['percentbetweenspandarc'];\n EP.SDPERCENTRADWIGGLEFB = resp['sdpercentradwigglefb'];\n EP.SDPERCENTDEGWIGGLEFB = resp['sdpercentdegwigglefb'];\n\n tp.itrial = resp['inititrial'];\n tp = set_itrialParams(tp.itrial, QUEUES);\n tsub.totalScore = EP.INITSCORE;\n\n fb_array = [];\n drill_history = [];\n\n background = make_background(STYLE.background, W, H);\n a_background = [background.background];\n startPoint = make_startPoint(tp.pxStart, tp.pyStart, STYLE.startPoint);\n a_startPoint = [startPoint.sp_glow, startPoint.sp];\n choiceSet = make_choiceSet();\n a_choiceSet = [choiceSet.arc_glow, choiceSet.arc];\n msgs = make_messages(STYLE.msgs);\n\n update_choiceSet(tp.pxStart, tp.pyStart, tp.pradArc,\n tp.minthetaArc, tp.maxthetaArc, STYLE.choiceSet);\n update_totalScore(tsub.totalScore);\n msgs.totalScore.visible = true; // visible through whole game\n\n stageArray(a_background);\n stageArray(a_startPoint);\n stageArray(a_choiceSet);\n stageObject(msgs, false);\n msgs.totalScore.visible = true; // totalScore always visible\n \n\n // let's get it started!\n setup_goToStart();\n } // end callback\n ); // end init_experiment\n\n\n //////// GAME LOGIC (besides createjs shape event handlers)\n function checkOnTick(event, tp, wp, EP, radStart){\n // this function checks the logic loop every MSTICK seconds\n // only checks timing things - interaction with objects should be\n // added with addEventListener in a easeljs object's construction\n if (wp.trialSection==='goToStart'){\n var pxMouse = stage.mouseX;\n var pyMouse = stage.mouseY;\n var inStartPoint = withinRad(pxMouse, pyMouse, tp.pxStart, tp.pyStart,\n radStart);\n if(inStartPoint){\n var tNow = getTime();\n if(tNow - wp.tInStart > EP.MSMINTIMEINSTART){\n setup_makeChoice();\n }\n }\n } // end goToStart\n else if (wp.trialSection==='makeChoice'){\n if(EP.MSMAXTIMETOCHOICE !== null){ // if choice time constraint\n var tNow = getTime();\n if(tNow - wp.tChoiceStarted > EP.MSMAXTIMETOCHOICE){\n setup_tooSlow();\n }\n }\n } // end makeChoice\n else if (wp.trialSection==='showFeedback'){\n var tNow = getTime();\n if(tNow - wp.tFeedbackOn > EP.MSSHOWFEEDBACK){\n setup_nextTrial();\n }\n }\n else if (wp.trialSection==='tooSlow'){\n var tNow = getTime();\n if(tNow - wp.tTooSlow > EP.MSTOOSLOW){\n msgs.tooSlow.visible = false;\n setup_goToStartPoint();\n }\n } // end tooSlow\n stage.update(event);\n }\n\n\n //// setups for various parts of a trial\n function setup_goToStart(){\n // what happens when we move to 'goToStart' section of a trial\n wp.trialSection = 'goToStart';\n unstageArray(fb_array);\n\n // update objects\n choiceSet.arc.visible = false;\n choiceSet.arc_glow.visible = false;\n startPoint.sp.visible = true;\n startPoint.sp_glow.visible = false;\n\n // update messages\n msgs.goToStart.visible = true;\n msgs.tooSlow.visible = false;\n\n stage.update();\n }\n\n\n function setup_makeChoice(){\n // what happens when we move to 'makeChoice' section of a trial\n wp.trialSection = 'makeChoice';\n // fb only shown during reach in this condition\n if(EP.FEEDBACKTYPE==='clickLocation'){\n stageArray(fb_array); \n }\n\n // update objects\n choiceSet.arc_glow.visible = false;\n choiceSet.arc.visible = true;\n startPoint.sp.visible = false;\n startPoint.sp_glow.visible = false;\n\n // update messages\n msgs.goToStart.visible = false;\n msgs.makeChoice.visible = true;\n\n stage.update();\n wp.tChoiceStarted = getTime(); // start choice timer\n }\n\n\n function setup_showFeedback(){\n wp.trialSection = 'showFeedback';\n wp.tFeedbackOn = getTime();\n \n // update messages\n msgs.makeChoice.visible = false;\n // show feedback\n unstageArray(fb_array);\n if(EP.FEEDBACKTYPE==='aboveStartPoint'){\n fb_array = make_aboveStartPoint_scalar_array(tp.pxStart, tp.pyStart,\n tp.pradArc, tp.degFB,\n EP.PERCENTBETWEENSPANDARC,\n EP.SDPERCENTRADWIGGLEFB,\n EP.SDPERCENTDEGWIGGLEFB,\n EP.RANGEDEG);\n }\n else if(EP.FEEDBACKTYPE==='clickLocation'){\n // show scores from last NLASTTOSHOW trials\n fb_array = make_clickloc_scalar_array(drill_history, tp.mindegArc,\n function(elt){return nlast(elt, tp.itrial, EP.NLASTTOSHOW)},\n STYLE.scalar_obs);\n }\n stageArray(fb_array);\n stage.update();\n }\n\n\n function setup_tooSlow(){\n wp.trialSection==='tooSlow';\n msgs.tooSlow.visible = true;\n wp.tTooSlow = getTime();\n }\n\n\n //// functions for setting up a trial\n function setup_nextTrial(){\n // increment tp.itrial and setup the next trial\n tp.itrial += 1;\n console.log('itrial ' + tp.itrial.toString());\n setup_trial(tp.itrial, EP, QUEUES, STYLE.choiceSet);\n }\n\n\n function setup_trial(itrial, ep, queues, stylecs){\n // set up things for trial itrial\n tp = set_itrialParams(itrial, queues);\n update_choiceSet(tp.pxStart, tp.pyStart, tp.pradArc,\n tp.minthetaArc, tp.maxthetaArc, stylecs);\n // update feedback\n unstageArray(fb_array);\n // show scores from last NLASTTOSHOW trials\n fb_array = make_clickloc_scalar_array(drill_history, tp.mindegArc,\n function(elt){return nlast(elt, itrial-1, ep.NLASTTOSHOW)},\n STYLE.scalar_obs);\n stageArray(fb_array);\n setup_goToStart();\n }\n\n\n function set_itrialParams(itrial, queues){\n // extract trial params for itrial itrial from the queues in queues\n var tp = {}; // init trial params\n\n // get values in abstract space\n // angle on arc where get max points. assumes deg(mindegArc) = 0\n tp.degOpt = queues.DEGOPT[itrial];\n tp.xStart = queues.XSTART[itrial];\n tp.yStart = queues.YSTART[itrial];\n tp.radwrtxArc = queues.RADWRTXARC[itrial];\n tp.mindegArc = mod(queues.MINDEGARC[itrial], 360.);\n tp.maxdegArc = mod(queues.MAXDEGARC[itrial], 360.);\n tp.rangedegArc = tp.maxdegArc - tp.mindegArc;\n tp.degFB = 90.; // FIXME: needs to be abstracted\n // convert what's needed to pixel space\n tp.pradArc = tp.radwrtxArc * W;\n tp.pxStart = tp.xStart * W;\n tp.pyStart = tp.yStart * H;\n // convert to theta for arcs\n tp.minthetaArc = degToRad(tp.mindegArc);\n tp.maxthetaArc = degToRad(tp.maxdegArc);\n if(tp.mindegArc===tp.maxdegArc){\n // correct for max equalling min for drawing arcs\n tp.maxdegArc += 360.\n tp.maxthetaArc += 2.*Math.PI;\n }\n\n\n tp.itrial = itrial;\n\n return tp;\n }\n\n\n function update_choiceSet(pxStart, pyStart, pradArc,\n minthetaArc, maxthetaArc, stylecs){\n // update the graphics of choiceSet wrt incoming args\n // negatives come from >0 being down screen. huge PITA\n choiceSet.arc.graphics.clear();\n choiceSet.arc_glow.graphics.clear();\n choiceSet.arc.graphics.s(stylecs.arc.strokeColor).\n ss(stylecs.arc.strokeSize, 0, 0).\n arc(pxStart, pyStart, pradArc,\n -minthetaArc, -maxthetaArc, true);\n\n var arc_glow_size = stylecs.arc.strokeSize *\n stylecs.arc_glow.ratioGlowBigger;\n stylecs.arc_glow.ratioGlowBigger;\n choiceSet.arc_glow.graphics.s(stylecs.arc_glow.strokeColor).\n ss(arc_glow_size, 0, 0).\n arc(pxStart, pyStart, pradArc,\n -minthetaArc, -maxthetaArc, true);\n }\n\n\n //// functions for saving and tearing down a trial\n function choice_made(pxDrill, pyDrill){\n // what happens after a choice is made\n console.log('choice_made called');\n tsub.choiceRT = getTime() - wp.tChoiceStarted;\n tsub.pxDrill = pxDrill;\n tsub.pyDrill = pyDrill;\n tsub.degDrill = pToDegDrill(pxDrill, pyDrill, tp.pxStart, tp.pyStart);\n tsub.signederror = get_signederror(tsub.degDrill, tp.degOpt, tp.mindegArc);\n tsub.trialScore = errorToScore(Math.abs(tsub.signederror), EP.RANGEDEG); // get the reward\n\n tsub.totalScore += tsub.trialScore;\n update_totalScore(tsub.totalScore);\n\n store_thisTrial(setup_showFeedback);\n }\n\n\n function update_totalScore(totalScore){\n msgs.totalScore.text = 'score: ' + totalScore.toString();\n }\n\n\n function store_thisTrial(callback){\n // store things from this trial and then run callback\n drill_history.push({'px': tsub.pxDrill,\n 'py': tsub.pyDrill,\n 'degDrill': tsub.degDrill,\n 'mindegArc': tp.mindegArc,\n 'f': tsub.trialScore,\n 'itrial': tp.itrial});\n jsb_recordTurkData([EP, tp, tsub], callback);\n }\n\n\n //////// GAME OBJECTS AND OBJECT CONSTRUCTORS\n function make_messages(stylemsgs){\n var msgs = {};\n for(var msg in stylemsgs){\n msgs[msg] = new createjs.Text();\n for(var prop in stylemsgs[msg]){\n msgs[msg][prop] = stylemsgs[msg][prop]\n }\n }\n return msgs;\n }\n\n\n function make_background(stylebg, canvasW, canvasH){\n var background_objs = [];\n var background = new createjs.Shape();\n background.graphics.s(stylebg.strokeColor).\n f(stylebg.fillColor).\n ss(stylebg.strokeSize, 0, 0).\n r(0, 0, canvasW, canvasH);\n\n // add to background array\n background_objs.background = background;\n\n return background_objs;\n }\n\n\n function make_startPoint(pxStart, pyStart, stylesp){\n var startPoint_objs = {};\n // startPoint graphics\n var sp = new createjs.Shape();\n sp.graphics.s(stylesp.sp.strokeColor).\n f(stylesp.sp.fillColor).\n ss(stylesp.sp.strokeSize, 0, 0).\n dc(pxStart, pyStart, stylesp.sp.radius);\n sp.visible = true;\n // startPoint Actions\n sp.addEventListener('mouseover', function(){\n if(wp.trialSection==='goToStart'){\n startPoint.sp_glow.visible = true;\n stage.update();\n wp.tInStart = getTime();\n } // end trialSection==='goToStart'\n\n });\n // glow graphics\n var sp_glow = new createjs.Shape();\n var sp_glow_rad = stylesp.sp.radius * stylesp.sp_glow.ratioGlowBigger;\n sp_glow.graphics.s(stylesp.sp_glow.strokeColor).\n f(stylesp.sp_glow.fillColor).\n ss(stylesp.sp_glow.strokeSize, 0, 0).\n dc(pxStart, pyStart, sp_glow_rad);\n startPoint_objs.sp = sp;\n startPoint_objs.sp_glow = sp_glow;\n return startPoint_objs;\n }\n\n\n function make_choiceSet(){\n var choiceSet = {};\n\n var arc = new createjs.Shape();\n var arc_glow = new createjs.Shape();\n\n // choiceArc Actions\n arc.addEventListener('mouseover', function(){\n if(wp.trialSection==='makeChoice'){\n arc_glow.visible = true;\n stage.update(); \n }\n \n });\n\n arc.addEventListener('mouseout', function(){\n if(wp.trialSection==='makeChoice'){\n arc_glow.visible = false;\n stage.update();\n }\n });\n\n arc.addEventListener('click', function(){\n if(wp.trialSection==='makeChoice'){\n var pxDrill = stage.mouseX;\n var pyDrill = stage.mouseY;\n choice_made(pxDrill, pyDrill);\n }\n });\n\n choiceSet.arc = arc;\n choiceSet.arc_glow = arc_glow;\n return choiceSet;\n }\n\n\n //////////// HELPERS ////////////\n function pToDegDrill(pxDrill, pyDrill, pxStart, pyStart){\n // ALWAYS ASSUMES mindegArc IS 0!!!!!\n // * pyDrill-pyStart is negative b.c. >y is lower in pixel space\n var theta = Math.atan2(-(pyDrill-pyStart), pxDrill-pxStart);\n var deg = mod(radToDeg(theta), 360.);\n return deg;\n }\n\n function degDrillToP(degDrill, prad, pxStart, pyStart){\n // ALWAYS ASSUMES mindegArc IS 0!!!!!\n var theta = degToRad(degDrill);\n var px = prad * Math.cos(theta);\n var py = - (prad * Math.sin(theta)); // negative b.c of reflection in pixel space\n px += pxStart;\n py += pyStart;\n return {'x': px, 'y': py};\n }\n\n\n function get_signederror(degDrill, degOpt, mindegArc){\n var ccwerr = degDrill - mod(degOpt + mindegArc, 360.); // e.g. 270-0 = 270\n var cwerr = degDrill-360. - mod(degOpt + mindegArc, 360.); // e.g. -90-0 = -90 (correct)\n var signederror = Math.abs(ccwerr) < Math.abs(cwerr) ? ccwerr : cwerr;\n return signederror;\n }\n\n\n//// HELPER FUNCTIONS\n function nlast(elt, currtrial, n) {\n // says yes if this elt's trial was one of the n last trials\n var good = currtrial - elt.itrial < n;\n return good;\n }\n\n\n function make_clickloc_scalar_array(drill_history, mindegArc, critfcn, styleso) {\n // takes drill_history, filters by crit, returns array of ScalarObs\n var to_show = drill_history.filter(critfcn); // filter to only shown\n // rotate to match choiceArc's rotation for this trial\n to_show = to_show.map(function(elt){\n var rot_degDrill = mod(elt.degDrill - elt.mindegArc + mindegArc, 360.);\n var pposn = degDrillToP(rot_degDrill, tp.pradArc,\n tp.pxStart, tp.pyStart);\n elt.px = pposn.x;\n elt.py = pposn.y;\n return elt;});\n // make obs for all valid sams in drill_history\n var fb_array = to_show.map(\n function(elt){return ScalarObs(elt.px, elt.py, elt.f, styleso)}\n );\n return fb_array;\n }\n\n\n function make_aboveStartPoint_scalar_array(pxStart, pyStart,\n pradArc, degFB,\n percentBtStartPointAndArc,\n sdpercentradWiggle,\n sdpercentdegWiggle,\n rangedeg){\n // default no wiggle\n sdpercentradWiggle = typeof sdpercentradWiggle !== 'undefined' ?\n sdpercentradWiggle : 0;\n sdpercentdegWiggle = typeof sdpercentdegWiggle !== 'undefined' ?\n sdpercentdegWiggle : 0;\n\n // convert percentages to numbers for randomness\n var pradFB = pradArc * percentBtStartPointAndArc;\n var sdradWiggle = sdpercentradWiggle * pradFB;\n var sddegWiggle = sdpercentdegWiggle * rangedeg;\n // draw random posn\n var prFB = randn(pradFB, sdradWiggle);\n var degFB = randn(degFB, sddegWiggle);\n var thetaFB = degToRad(degFB);\n\n // convert to cartesian and shift wrt startPoint\n var pxFB = prFB * Math.cos(thetaFB) + pxStart;\n var pyFB = - (prFB * Math.sin(thetaFB)) + pyStart;\n\n fb_array = [ScalarObs(pxFB, pyFB, tsub.trialScore, STYLE.scalar_obs)];\n\n return fb_array;\n }\n\n\n function ScalarObs(x, y, val, styleso){\n // val to be placed at drill location\n var obs = new createjs.Text('',\n styleso.textstyle,\n styleso.color);\n obs.x = x;\n obs.y = y;\n obs.text = val.toString();\n obs.visible = true;\n return obs;\n }\n\n\n function stageArray(shapeArray, visible){\n // add all elements in shapeArray to the canvas\n visible = typeof visible !== 'undefined' ? visible : true;\n shapeArray.map(function(elt){\n stage.addChild(elt);\n elt.visible = visible;\n });\n stage.update();\n }\n\n\n function stageObject(object, visible){\n // add all fields of object to the canvas\n visible = typeof visible !== 'undefined' ? visible : true;\n for (var field in object){\n stage.addChild(object[field]);\n object[field].visible = visible;\n }\n stage.update();\n }\n\n\n function unstageArray(shapeArray){\n // remove all elements in shapeArray from the canvas\n shapeArray.map(function(elt){\n elt.visible = false;\n stage.removeChild(elt);\n });\n }\n\n\n function unstageObject(object){\n // remove all fields of object from the canvas\n for (var field in object){\n object[field].visible = true;\n stage.removeChild(object[field]);\n }\n stage.update();\n }\n\n\n function errorToScore(unsignederror, degrange) {\n return Math.round((1 - (unsignederror/degrange)) * 100);\n }\n\n\n function endExp(){\n psiTurk.showPage('debriefing.html');\n }\n\n\n function monify(n){\n n = Math.round(n);\n if (n<0){\n return '-$' + (-n).toString();\n }\n else{\n return '$' + n.toString();\n }\n }\n\n\n function max(array) {\n return Math.max.apply(Math, array);\n }\n\n\n function min(array) {\n return Math.min.apply(Math, array);\n }\n\n\n function getTime(){\n return new Date().getTime();\n }\n\n\n function normalize(a, tobounds, frombounds){\n // takes aa, which lives in interval frombounds, and maps to interval tobounds\n // default tobounds = [0,1]\n tobounds = typeof tobounds !== 'undefined' ? tobounds : [0., 1.];\n // default frombounds are the min and max of a\n frombounds = typeof frombounds !== 'undefined' ? frombounds : [min(a), max(a)];\n\n var fromlo = frombounds[0];\n var fromhi = frombounds[1];\n var tolo = tobounds[0];\n var tohi = tobounds[1];\n var fromrange = fromhi-fromlo;\n var torange = tohi-tolo;\n\n a = a.map(function(elt){return elt-fromlo;});\n a = a.map(function(elt){return elt/fromrange;}); // now in 0, 1\n a = a.map(function(elt){return elt*torange});\n a = a.map(function(elt){return elt+tolo});\n\n return a;\n }\n\n\n function get_dist(p1, p2){\n return Math.sqrt(Math.pow(p1[0]-p2[0], 2.) +\n Math.pow(p1[1]-p2[1], 2.));\n }\n\n function withinRad(x, y, xOrigin, yOrigin, rad){\n return get_dist([x, y], [xOrigin, yOrigin]) < rad;\n }\n\n\n function radToDeg(theta){\n return mod(theta * (180./Math.PI), 360.);\n }\n\n\n function degToRad(deg){\n return mod(deg, 360.) * (Math.PI/180.);\n }\n\n\n // use instead of % b.c. javascript can't do negative mod\n function mod(a, b){return ((a%b)+b)%b;}\n\n\n function rand(min, max){\n min = typeof min !== 'undefined' ? min : 0;\n max = typeof max !== 'undefined' ? max : 1;\n\n var range = max - min;\n return Math.random() * range + min;\n }\n\n function randn(mu, sd){\n // generate gaussian rand fcns using box-mueller method\n mu = typeof mu !== 'undefined' ? mu : 0;\n sd = typeof sd !== 'undefined' ? sd : 1;\n\n var x1, x2;\n var w = 99.;\n while(w >= 1.){\n x1 = 2. * rand() - 1.;\n x2 = 2 * rand() - 1;\n w = x1*x1 + x2*x2;\n }\n return mu + (x1 * w * sd);\n }\n\n\n function keys(obj, sorted){\n // gets object keys\n sorted = typeof tobounds !== 'undefined' ? tobounds : true; // default sorted\n var keys = [];\n for(var key in obj){\n if(obj.hasOwnProperty(key)){\n keys.push(key);\n }\n }\n return keys;\n }\n\n\n function objToArray(obj){\n return keys(obj).map(function(k){return obj[k]});\n }\n\n\n function jsb_recordTurkData(loObj, callback){\n var toSave = {};\n loObj.map(function(obj){ // for every obj in loObj...\n for(var field in obj){\n toSave[field] = obj[field]; // add to dict toSave\n }\n });\n\n psiTurk.recordTrialData(toSave); // store on client side\n psiTurk.saveData(); // save to server side\n callback();\n }\n\n\n //////// STYLE SHEETS FOR THE GAME\n var STYLE = [];\n\n // background. should be purely cosmetic\n STYLE.background = [];\n STYLE.background.strokeSize = 5;\n STYLE.background.strokeColor = '#171717';\n STYLE.background.fillColor = '#171717';\n\n // choiceSet is the abstract term for whatever objects you can click to make\n // a choice. in this case, we have a single arc, but can be arbitrary\n STYLE.choiceSet = [];\n STYLE.choiceSet.arc = [];\n STYLE.choiceSet.arc.strokeColor = '#8B8B8B';\n STYLE.choiceSet.arc.fillColor = null;\n STYLE.choiceSet.arc.strokeSize = 10;\n\n STYLE.choiceSet.arc_glow = [];\n STYLE.choiceSet.arc_glow.strokeColor = '#AEAEAE';\n STYLE.choiceSet.arc_glow.ratioGlowBigger = 1.5;\n\n // feedback objects (TODO: add endpoint, online)\n STYLE.scalar_obs = [];\n STYLE.scalar_obs.textstyle = '2em Helvetica';\n STYLE.scalar_obs.color = 'white';\n\n // startPoint\n STYLE.startPoint = [];\n STYLE.startPoint.sp = [];\n STYLE.startPoint.sp.strokeColor = '#8B8B8B';\n STYLE.startPoint.sp.fillColor = '#8B8B8B';\n STYLE.startPoint.sp.strokeSize = 2;\n STYLE.startPoint.sp.radius = 20;\n\n STYLE.startPoint.sp_glow = [];\n STYLE.startPoint.sp_glow.strokeColor = '#AEAEAE';\n STYLE.startPoint.sp_glow.fillColor = '#AEAEAE';\n STYLE.startPoint.sp_glow.ratioGlowBigger = 1.2;\n \n // messages shown throughout game\n STYLE.msgs = [];\n\n STYLE.msgs.goToStart = [];\n STYLE.msgs.goToStart.text = 'GO TO START';\n STYLE.msgs.goToStart.color = '#AEAEAE';\n STYLE.msgs.goToStart.font = '2em Helvetica';\n STYLE.msgs.goToStart.textAlign = 'center';\n STYLE.msgs.goToStart.x = W / 2.;\n STYLE.msgs.goToStart.y = H / 20.;\n\n STYLE.msgs.makeChoice = [];\n STYLE.msgs.makeChoice.text = 'CLICK RING TO MAKE CHOICE';\n STYLE.msgs.makeChoice.color = '#AEAEAE';\n STYLE.msgs.makeChoice.font = '2em Helvetica';\n STYLE.msgs.makeChoice.textAlign = 'center';\n STYLE.msgs.makeChoice.x = W / 2.;\n STYLE.msgs.makeChoice.y = H / 20.;\n\n STYLE.msgs.tooSlow = [];\n STYLE.msgs.tooSlow.text = 'TOO SLOW';\n STYLE.msgs.tooSlow.color = '#AEAEAE';\n STYLE.msgs.tooSlow.font = '10em Helvetica';\n\n STYLE.msgs.totalScore = [];\n STYLE.msgs.totalScore.color = '#AEAEAE';\n STYLE.msgs.totalScore.font = '2em Helvetica';\n STYLE.msgs.totalScore.regX = 0.;\n STYLE.msgs.totalScore.regY = 0.;\n STYLE.msgs.totalScore.textAlign = 'left';\n STYLE.msgs.totalScore.x = 10.;\n STYLE.msgs.totalScore.y = H - 40.;\n\n};\n"
}
] | 5 |
dotrungkien/face_recognition | https://github.com/dotrungkien/face_recognition | aa6c7faeec97ddc66751d10ccdd769596e247f4c | 52c552c4f73850e62db88d0dc7271d73e4150180 | e94d112ca377fbbf07e81edeb06b5e3a573b7c41 | refs/heads/master | 2021-08-26T07:05:55.737910 | 2017-11-22T01:49:52 | 2017-11-22T01:49:52 | 110,239,003 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.719298243522644,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 41.75,
"blob_id": "4b749e9c0cf5ccf29d071e1ca97712e6e8b085c3",
"content_id": "ab31645f2aeea35ee3644c9c7d9a4b315269826e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 171,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 4,
"path": "/README.md",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "1. Convert dataset to cifar10 formar: python convert.py\n2. Train: python cifar10_train.py\n3. Evaluation: python cifar10_eval.py\n4. Predict: python predict.py [image_path]\n"
},
{
"alpha_fraction": 0.5756165385246277,
"alphanum_fraction": 0.5793392062187195,
"avg_line_length": 28.438356399536133,
"blob_id": "ec3963edab9f004c018ec6464e4d68680d11b783",
"content_id": "161425b5f2a9a743880d2e34428499fb84ec299b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2149,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 73,
"path": "/prepare_data.py",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport os\nfrom os import listdir\nfrom os.path import join, isfile, isdir\nfrom shutil import copyfile, rmtree\nfrom PIL import Image\n\nRAW_PATH = './Face'\nDATA_PATH = './data'\nTRAIN = 'Train'\nTEST = 'Test'\nIMAGE_SIZE = 28, 28\n\n\ndef move_and_rename(path_type):\n if not path_type:\n return\n print(\"Moving %s data\" % path_type)\n IN_PATH = join(RAW_PATH, path_type)\n OUT_PATH = join(DATA_PATH, path_type)\n if isdir(OUT_PATH):\n rmtree(OUT_PATH)\n os.mkdir(OUT_PATH)\n\n name_all = [name for name in listdir(IN_PATH) if '.' not in name]\n for people_name in name_all:\n people_path = join(IN_PATH, people_name)\n people_images = []\n\n images_folders = [\n folder for folder in listdir(people_path)\n if '.' not in folder\n ]\n for images_folder in images_folders:\n images_path = join(people_path, images_folder)\n images = [\n join(images_path, img) for img in listdir(images_path)\n if img.endswith('.jpg')\n ]\n people_images.extend(images)\n for i, img in enumerate(people_images):\n new_name = \"{0}_{1:04}.jpg\".format(people_name, i)\n dst = join(OUT_PATH, new_name)\n copyfile(img, dst)\n print(\"Moving %s data done\" % path_type)\n\n\ndef resize(path_type):\n print(\"Resizing %s data\" % path_type)\n images_path = join(DATA_PATH, path_type)\n out_path = join(DATA_PATH, path_type + \"_resized\")\n if isdir(out_path):\n rmtree(out_path)\n os.mkdir(out_path)\n images_name = [\n image_name for image_name in listdir(images_path)\n if image_name.endswith('.jpg')\n ]\n for image_name in images_name:\n try:\n img = Image.open(join(images_path, image_name))\n img = img.convert('L')\n img = img.resize(IMAGE_SIZE)\n img.save(join(out_path, image_name))\n except:\n pass\n print(\"Resizing %s data done\" % path_type)\n\nif __name__ == '__main__':\n # move_and_rename(TRAIN)\n # move_and_rename(TEST)\n resize(TRAIN)\n resize(TEST)\n"
},
{
"alpha_fraction": 0.6165711879730225,
"alphanum_fraction": 0.6284707188606262,
"avg_line_length": 30.5,
"blob_id": "bfee54297e30f905b68062ce218f00c0cc9e74aa",
"content_id": "545a146a784f4216109b60033e617e48bba58f01",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2269,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 72,
"path": "/predict.py",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport sys\nfrom datetime import datetime\nimport math\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nimport cifar10\n\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string(\"checkpoint_dir\", \"tmp/cifar10_train\",\n \"\"\"Directory where to read model checkpoints.\"\"\")\n\nIMAGE_SIZE = 24\nLABEL_NAMES = ['Kashiwaghi Yuki', 'Yamamoto Sayaka', 'Komima Haruna', 'Sashihara Rino', 'Watanabe Mayu']\n\ndef evaluate_image(filename):\n with tf.Graph().as_default() as g:\n # Number of images to process\n FLAGS.batch_size = 1\n\n image = img_read(filename)\n logit = cifar10.inference(image)\n\n output = tf.nn.softmax(logit)\n top_k_pred = tf.nn.top_k(output, k=1)\n\n variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY)\n variables_to_restore = variable_averages.variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n\n with tf.Session() as sess:\n #sess.run(tf.global_variables_initializer())\n ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n # Restores from checkpoint\n saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n print(\"No checkpoint file found\")\n return\n\n values, indices = sess.run(top_k_pred)\n print LABEL_NAMES[indices[0][0]-1], values[0][0]\n\ndef img_read(filename):\n if not tf.gfile.Exists(filename):\n tf.logging.fatal(\"File does not exists %s\", filename)\n \n input_img = tf.image.decode_jpeg(tf.read_file(filename), channels=3)\n #input_img = tf.image.decode_png(tf.read_file(filename), channels=3)\n reshaped_image = tf.cast(input_img, tf.float32)\n\n resized_image = tf.image.resize_images(reshaped_image, (IMAGE_SIZE, IMAGE_SIZE))\n float_image = tf.image.per_image_standardization(resized_image)\n image = tf.expand_dims(float_image, 0) # create a fake batch of images (batch_size = 1)\n\n return image\n\n\ndef main(argv=None):\n if len(argv) < 2:\n print 'Missing argument : python predict.py [image_path]'\n sys.exit(1)\n\n filename = argv[1]\n evaluate_image(filename)\n\nif __name__ == '__main__':\n tf.app.run()\n\n"
},
{
"alpha_fraction": 0.6256038546562195,
"alphanum_fraction": 0.6328502297401428,
"avg_line_length": 22,
"blob_id": "5febf765aa605aa03bd09b19abbedcf0379e9f71",
"content_id": "bb8aaea1d863f144dd7a710dd878ed727beb22e5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 414,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 18,
"path": "/label.py",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "import cv2\nimport sys\nimport numpy as np\n\nfrom scipy.io import loadmat\n\ndef convert():\n labels = loadmat('tmp/data/devkit/cars_meta.mat')\n car_labels = []\n for label in labels['class_names'][0]:\n car_labels.append(label[0])\n\n labels_file = open(\"tmp/data/devkit/car_labels.txt\", \"w\")\n labels_file.write(\"\\n\".join(car_labels))\n labels_file.close()\n\nif __name__ == '__main__':\n convert()\n"
},
{
"alpha_fraction": 0.5631500482559204,
"alphanum_fraction": 0.5846953988075256,
"avg_line_length": 30.302326202392578,
"blob_id": "789b370cfdef0bdd93d1e6476307b5baa98adcb1",
"content_id": "45440dacb93406fa247e09f5bfd48e25bcfd604b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1346,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 43,
"path": "/convert.py",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nimport cv2\nimport sys\nimport numpy as np\nimport cifar10\n\nDATA_PATH = \"./data\"\nLABELS = [\n 'nguyennt3', 'hieubq', 'trangdnt', 'diepdt2', 'tiennd', 'phuongnt3',\n 'nhanlt3', 'dathv', 'thanhnt', 'tuannm4', 'anhpt4', 'ChiHoaLaoCong',\n 'anhnp2', 'anhnh2', 'thanhpv2', 'truongtd4', 'huyencm', 'thanhlc',\n 'hadn', 'hieuvm', 'thaontp2', 'thaonp2', 'chaudtb', 'thuybt', 'nhungvth',\n 'vinhnd2', 'anhpq']\n\n\ndef convert(path_type):\n if not path_type:\n return\n output_file = open(\n 'data/cifar10_data/cifar-10-batches-bin/{0}_batch.bin'\n .format(path_type.lower()), 'ab')\n data_path = \"./data/{0}_resized\".format(path_type)\n images_path = [\n join(data_path, f) for f in listdir(data_path)\n if isfile(join(data_path, f)) and 'jpg' in f\n ]\n\n for image_path in images_path:\n im = cv2.imread(image_path)\n r = im[:, :, 0].flatten()\n g = im[:, :, 1].flatten()\n b = im[:, :, 2].flatten()\n label = LABELS.index(image_path.split('/')[-1].split('_')[0])\n output = np.array([label] + list(r) + list(g) + list(b), dtype=np.uint8)\n output.tofile(output_file)\n output_file.close()\n\nif __name__ == '__main__':\n convert('Train')\n convert('Test')\n"
},
{
"alpha_fraction": 0.6242527961730957,
"alphanum_fraction": 0.6336464285850525,
"avg_line_length": 26.880952835083008,
"blob_id": "e8c28a3e2da444a731a05fa833ab43a489be763a",
"content_id": "15c8f9265ab8f6eb68c5413790f2ded154e9bab4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1171,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 42,
"path": "/recog_model.py",
"repo_name": "dotrungkien/face_recognition",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\nfrom imageio import imread\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\n\nDATA_PATH = './data'\n\n\ndef read_data(path_type):\n if not path_type:\n return\n data_path = join(DATA_PATH, path_type + \"_resized\")\n images_path = [\n join(data_path, f) for f in listdir(data_path)\n if isfile(join(data_path, f)) and 'jpg' in f\n ]\n images, labels = [], []\n for image_path in images_path:\n image = imread(image_path)\n image = image.reshape(32*32)\n image = [i/255. for i in image]\n image_label = image_path.split('/')[-1].split('_')[0]\n images.append(image)\n labels.append(image_label)\n return np.array(images), np.array(labels)\n\n\ndef main():\n train_images, train_labels = read_data('Train')\n test_images, test_labels = read_data('Test')\n clf = SVC(kernel='poly', C=1e5)\n clf.fit(train_images, train_labels)\n pred_labels = clf.predict(test_images)\n print(accuracy_score(test_labels, pred_labels))\n\n\nif __name__ == '__main__':\n main()\n"
}
] | 6 |
paladin-705/UniversityScheduleBot | https://github.com/paladin-705/UniversityScheduleBot | c25f9bf5bbfb0cccf1d9b727adbe6718a366e9a6 | e032aee11d2b440edc3cd5b1633ab0a989ed4db5 | 05f686f103d971d3d9ae99e807b595698309e449 | refs/heads/master | 2021-11-19T10:42:48.408716 | 2021-08-29T11:43:48 | 2021-08-29T11:43:48 | 82,712,743 | 18 | 8 | MIT | 2017-02-21T18:23:07 | 2018-07-13T11:28:44 | 2018-07-13T12:41:30 | Python | [
{
"alpha_fraction": 0.5989574790000916,
"alphanum_fraction": 0.6051025390625,
"avg_line_length": 36.75360107421875,
"blob_id": "2ed421b50d7ad1d5a3610a975107d1431783913c",
"content_id": "3eafc1fa60a458872153788eb40cf83947d64379",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 28096,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 625,
"path": "/bot/UniversityScheduleBot.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport logging\nimport re\nfrom datetime import datetime, time, timedelta\n\nimport flask\nfrom flask import request, jsonify\n\nimport telebot\nfrom telebot import types\n\nfrom config import config\nfrom helpers import daysOfWeek, ScheduleType, get_date_keyboard, get_week_type\nfrom scheduleCreator import create_schedule_text\nfrom scheduledb import ScheduleDB, organization_field_length, faculty_field_length\n\n# Статистика\nfrom statistic import track\n\nWEBHOOK_URL_BASE = \"https://{}:{}\".format(config[\"WEBHOOK_HOST\"], config[\"WEBHOOK_PORT\"])\nWEBHOOK_URL_PATH = \"/{}/\".format(config[\"TOKEN\"])\n\nbot = telebot.AsyncTeleBot(config[\"TOKEN\"])\napp = flask.Flask(__name__)\n\nlogger = telebot.logger\ntelebot.logger.setLevel(logging.INFO)\n\ncommands = { # Описание команд используещееся в команде \"help\"\n 'start': 'Стартовое сообщение и предложение зарегистрироваться',\n 'help': 'Информация о боте и список доступных команд',\n 'registration': 'Выбор ВУЗа, факультета и группы для вывода расписания',\n 'send_report <сообщение>': 'Отправить информацию об ошибке или что то ещё',\n 'auto_posting_on <ЧЧ:ММ>': 'Включение и выбор времени для автоматической отправки расписания в диалог',\n 'auto_posting_off': 'Выключение автоматической отправки расписания'\n}\n\n# -------------------------------------\n# BOT HANDLERS\n# -------------------------------------\n\n\n# handle the \"/registration\" command\[email protected]_handler(commands=['registration'])\ndef command_registration(m):\n cid = m.chat.id\n\n # Процедура регистрации проходит в четрые этапа:\n # 1 этап: выбор учебного заведения <--\n # 2 этап: выбор факультета\n # 3 этап: выбор группы\n # 4 этап: добавление данных о принадлежности пользователя к учебному заведению в БД\n try:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], cid, 'stage 1', 'registration-stage-1')\n\n keyboard = types.InlineKeyboardMarkup()\n\n with ScheduleDB(config) as db:\n result = db.get_organizations()\n for row in result:\n callback_button = types.InlineKeyboardButton(\n text=str(row[0]),\n callback_data=\"reg:stage 2:{0}\".format(str(row[1])[:organization_field_length]))\n keyboard.add(callback_button)\n\n bot.send_message(cid, \"Выберите университет:\", reply_markup=keyboard)\n except BaseException as e:\n logger.warning('Registration problem: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что-то странное, попробуйте начать сначала, введя команду /registration\")\n\n\n# handle the \"/start\" command\[email protected]_handler(commands=['start'])\ndef command_start(m):\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'start')\n else:\n logger.info('start')\n\n cid = m.chat.id\n command_help(m)\n\n try:\n with ScheduleDB(config) as db:\n user = db.find_user(cid)\n if user and user[0] is not None:\n bot.send_message(cid, \"Вы уже добавлены в базу данных\", reply_markup=get_date_keyboard())\n else:\n bot.send_message(cid, \"Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации\")\n command_registration(m)\n except BaseException as e:\n logger.warning('command start: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\",\n reply_markup=get_date_keyboard())\n\n\n# help page\[email protected]_handler(commands=['help'])\ndef command_help(m):\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'help')\n else:\n logger.info('help')\n\n cid = m.chat.id\n help_text = \"Доступны следующие команды: \\n\"\n for key in commands:\n help_text += \"/\" + key + \": \"\n help_text += commands[key] + \"\\n\"\n bot.send_message(cid, help_text, reply_markup=get_date_keyboard())\n\n help_text = ('Описание кнопок:\\nКнопка \"Сегодня\", как это ни странно выводит расписание на сегодняшний день, '\n 'причём с учётом типа недели (числитель/знаменатель), но есть один нюанс: если сегодня воскресенье '\n 'или время больше чем 21:30, то выводится расписание на следующий день\\n')\n bot.send_message(cid, help_text, reply_markup=get_date_keyboard())\n\n guide_url = 'https://github.com/paladin-705/UniversityScheduleBot/wiki/Guide'\n\n help_text = 'Более подробную инструкцию и описание команд (с инструкциями гифками! ^_^) \\\n вы можете посмотреть по ссылке: {}'.format(guide_url)\n bot.send_message(cid, help_text, reply_markup=get_date_keyboard())\n\n\n# send_report handler\[email protected]_handler(commands=['send_report'])\ndef command_send_report(m):\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'report')\n else:\n logger.info('report')\n\n cid = m.chat.id\n data = m.text.split(\"/send_report\")\n\n if data[1] != '':\n report = data[1]\n with ScheduleDB(config) as db:\n if db.add_report(cid, report):\n bot.send_message(cid, \"Сообщение принято\")\n else:\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\",\n reply_markup=get_date_keyboard())\n else:\n bot.send_message(\n cid,\n \"Вы отправили пустую строку. Пример: /send_report <сообщение>\",\n reply_markup=get_date_keyboard())\n\n\n# handle the \"/auto_posting_on\" command\[email protected]_handler(commands=['auto_posting_on'])\ndef command_auto_posting_on(m):\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'auto_posting_on')\n else:\n logger.info('auto_posting_on')\n\n cid = m.chat.id\n\n try:\n data = m.text.split(\"/auto_posting_on\")[1].strip()\n if re.match(data, r'\\d{1,2}:\\d\\d'):\n raise BaseException\n except:\n bot.send_message(cid, \"Вы отправили пустую строку или строку неправильного формата. Правильный формат ЧЧ:ММ\",\n reply_markup=get_date_keyboard())\n return None\n\n try:\n db = ScheduleDB(config)\n user = db.find_user(cid)\n if user and user[0] is not None:\n keyboard = types.InlineKeyboardMarkup()\n callback_button = types.InlineKeyboardButton(\n text=\"На Сегодня\",\n callback_data=\"ap:{0}:1\".format(data))\n keyboard.add(callback_button)\n callback_button = types.InlineKeyboardButton(\n text=\"На Завтра\",\n callback_data=\"ap:{0}:0\".format(data))\n keyboard.add(callback_button)\n\n bot.send_message(cid, \"Выберите день на который будет приходить расписание:\", reply_markup=keyboard)\n else:\n bot.send_message(cid, \"Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации\")\n command_registration(m)\n except BaseException as e:\n logger.warning('command auto_posting_on: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\")\n\n\[email protected]_handler(commands=['auto_posting_off'])\ndef command_auto_posting_off(m):\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'auto_posting_off')\n else:\n logger.info('auto_posting_off')\n\n cid = m.chat.id\n\n try:\n db = ScheduleDB(config)\n user = db.find_user(cid)\n if not user:\n bot.send_message(cid, \"Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации\")\n command_registration(m)\n return\n\n if db.set_auto_post_time(cid, None, None):\n bot.send_message(cid, \"Автоматическая отправка расписания успешно отключена\")\n else:\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\",\n reply_markup=get_date_keyboard())\n\n except BaseException as e:\n logger.warning('command auto_posting_off: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\")\n\n\n# exams message handler\[email protected]_handler(func=lambda message: 'Экзамены' in (message.text if message.text is not None else ''), content_types=['text'])\ndef exams(m):\n cid = m.chat.id\n\n # Статистика\n track(config['STATISTIC_TOKEN'], cid, m.text, 'exams')\n\n # Если пользователя нет в базе, то ему выведет предложение зарегистрироваться\n try:\n with ScheduleDB(config) as db:\n user = db.find_user(cid)\n if not user or user[0] is None:\n message = \"Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации:\\n\"\n message += 'Введите команду(без кавычек):\\n\\nрегистрация \"название вуза\" \"факультет\" \"группа\"\\n\\n'\n message += 'Если вы допустите ошибку, то просто наберите команду заново.\\n'\n\n bot.send_message(cid, message, reply_markup=get_date_keyboard())\n except BaseException as e:\n bot.send_message(cid, 'Случилось что то странное, попробуйте ввести команду заново',\n reply_markup=get_date_keyboard())\n\n try:\n with ScheduleDB(config) as db:\n exams_list = db.get_exams(user[0])\n\n message = ''\n for exam in exams_list:\n message += exam[0].strftime('%d.%m.%Y') + \":\\n\"\n\n title = ' '.join(str(exam[1]).split())\n lecturer = ' '.join(str(exam[2]).split())\n classroom = ' '.join(str(exam[3]).split())\n\n message += title + ' | ' + lecturer + ' | ' + classroom + \"\\n\"\n message += \"------------\\n\"\n if len(message) == 0:\n message = 'Похоже расписания экзаменов для вашей группы нет в базе'\n\n except BaseException as e:\n message = \"Случилось что то странное, попробуйте ввести команду заново\"\n\n bot.send_message(cid, message, reply_markup=get_date_keyboard())\n\n\n# text message handler\[email protected]_handler(func=lambda message: True, content_types=['text'])\ndef response_msg(m):\n cid = m.chat.id\n if m.text in ScheduleType:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'schedule')\n else:\n logger.info('message: {0}'.format(m.text))\n\n # По умолчанию week_type равен -1 и при таком значении будут выводится все занятия,\n # т.е и для чётных и для нечётных недель\n week_type = -1\n\n if m.text == \"Вся неделя\":\n days = ScheduleType[m.text]\n elif m.text == \"Сегодня\":\n today = datetime.now()\n # Если запрашивается расписание на сегодняшний день,\n # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная\n week_type = get_week_type(today)\n\n # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели\n # Также в этом случае, как week_type используется тип следующей недели\n if datetime.weekday(today) == 6:\n today += timedelta(days=1)\n week_type = (week_type + 1) % 2\n\n days = [daysOfWeek[datetime.weekday(today)]]\n elif m.text == 'Завтра':\n tomorrow = datetime.now()\n tomorrow += timedelta(days=1)\n # Если запрашивается расписание на сегодняшний день,\n # то week_type равен остатку от деления на 2 номера недели в году, т.е он определяет чётная она или нечётная\n week_type = get_week_type(tomorrow)\n\n # Если сегодня воскресенье, то показывается расписание на понедельник следующей недели\n # Также в этом случае, как week_type используется тип следующей недели\n if datetime.weekday(tomorrow) == 6:\n tomorrow += timedelta(days=1)\n week_type = (week_type + 1) % 2\n\n days = [daysOfWeek[datetime.weekday(tomorrow)]]\n else:\n days = [ScheduleType[m.text]]\n\n for day in days:\n try:\n with ScheduleDB(config) as db:\n user = db.find_user(cid)\n if user and user[0] is not None:\n result = create_schedule_text(user[0], day, week_type)\n for schedule in result:\n bot.send_message(cid, schedule, reply_markup=get_date_keyboard())\n else:\n bot.send_message(cid, \"Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации\")\n command_registration(m)\n except BaseException as e:\n logger.warning('response_msg: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\")\n else:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], m.chat.id, m.text, 'unknown')\n else:\n logger.info('unknown message: {0}'.format(m.text))\n\n bot.send_message(cid, \"Неизвестная команда\", reply_markup=get_date_keyboard())\n\n\n# -------------------------------------\n# BOT CALLBACKS\n# -------------------------------------\n\n\[email protected]_query_handler(func=lambda call: \"reg:stage 2:\" in call.data)\ndef callback_registration(call):\n cid = call.message.chat.id\n\n # Парсинг сообщения указывающего стадию регистрации\n # reg : stage : tag\n callback_data = re.split(r':', call.data)\n\n # Процедура регистрации проходит в четрые этапа:\n # 1 этап: выбор учебного заведения\n # 2 этап: выбор факультета <--\n # 3 этап: выбор группы\n # 4 этап: добавление данных о принадлежности пользователя к учебному заведению в БД\n try:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], cid, 'stage 2', 'registration-stage-2')\n\n keyboard = types.InlineKeyboardMarkup()\n\n organization_id = callback_data[2]\n\n with ScheduleDB(config) as db:\n result = db.get_faculty(organization_id)\n\n for row in result:\n callback_button = types.InlineKeyboardButton(\n text=str(row[0]),\n callback_data=\"reg:stage 3:{0}\".format(\n str(row[1])[:organization_field_length + faculty_field_length]))\n keyboard.add(callback_button)\n\n bot.send_message(cid, \"Выберите факультет:\", reply_markup=keyboard)\n except BaseException as e:\n logger.warning('Registration problem: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что-то странное, попробуйте начать сначала, введя команду /registration\")\n\n\[email protected]_query_handler(func=lambda call: \"reg:stage 3:\" in call.data)\ndef callback_registration(call):\n cid = call.message.chat.id\n\n # Парсинг сообщения указывающего стадию регистрации\n # reg : stage : tag\n callback_data = re.split(r':', call.data)\n\n # Процедура регистрации проходит в четрые этапа:\n # 1 этап: выбор учебного заведения\n # 2 этап: выбор факультета\n # 3 этап: выбор группы <--\n # 4 этап: добавление данных о принадлежности пользователя к учебному заведению в БД\n try:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], cid, 'stage 3', 'registration-stage-3')\n\n keyboard = types.InlineKeyboardMarkup()\n\n faculty_id = callback_data[2]\n\n with ScheduleDB(config) as db:\n result = db.get_group(faculty_id)\n\n for row in result:\n callback_button = types.InlineKeyboardButton(\n text=str(row[0]),\n callback_data=\"reg:stage 4:{0}\".format(str(row[1])))\n keyboard.add(callback_button)\n\n bot.send_message(cid, \"Выберите группу:\", reply_markup=keyboard)\n except BaseException as e:\n logger.warning('Registration problem: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что-то странное, попробуйте начать сначала, введя команду /registration\")\n\n\[email protected]_query_handler(func=lambda call: \"reg:stage 4:\" in call.data)\ndef callback_registration(call):\n cid = call.message.chat.id\n\n # Парсинг сообщения указывающего стадию регистрации\n # reg : stage : tag\n callback_data = re.split(r':', call.data)\n\n # Процедура регистрации проходит в четрые этапа:\n # 1 этап: выбор учебного заведения\n # 2 этап: выбор факультета\n # 3 этап: выбор группы\n # 4 этап: добавление данных о принадлежности пользователя к учебному заведению в БД <--\n try:\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], cid, 'stage 4', 'registration-stage-4')\n\n group_id = callback_data[2]\n\n db = ScheduleDB(config)\n\n row = db.get_group(group_id)\n user = db.find_user(cid)\n\n if user:\n db.update_user(cid, call.message.chat.first_name, call.message.chat.username, str(row[0][1]))\n else:\n db.add_user(cid, call.message.chat.first_name, call.message.chat.username, str(row[0][1]))\n\n bot.send_message(cid, \"Отлично, вы зарегистрировались, ваша группа: \" + row[0][0] +\n \"\\nЕсли вы ошиблись, то просто введиде команду /registration и измените данные\",\n reply_markup=get_date_keyboard())\n bot.send_message(cid, \"Теперь вы можете настроить автоматическую отправку расписания в заданное вами время,\"\n \" введя команду /auto_posting_on <время>, \"\n \"где <время> должно иметь формат ЧЧ:ММ\")\n\n except BaseException as e:\n logger.warning('Registration problem: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что-то странное, попробуйте начать сначала, введя команду /registration\")\n\n\[email protected]_query_handler(func=lambda call: \"ap:\" in call.data)\ndef callback_auto_posting(call):\n cid = call.message.chat.id\n\n try:\n callback_data = re.split(r':', call.data)\n\n # Проверка на соответствие введённых пользователем данных принятому формату\n if len(callback_data) != 4:\n bot.send_message(cid,\n \"Вы отправили пустую строку или строку неправильного формата. Правильный формат ЧЧ:ММ\",\n reply_markup=get_date_keyboard())\n return\n\n hour = ''.join(filter(lambda x: x.isdigit(), callback_data[1]))\n minutes = ''.join(filter(lambda x: x.isdigit(), callback_data[2]))\n is_today = callback_data[3]\n\n # Проверка на соответствие введённых пользователем данных принятому формату\n if not hour.isdigit() or not minutes.isdigit():\n bot.send_message(cid,\n \"Вы отправили пустую строку или строку неправильного формата. Правильный формат ЧЧ:ММ\",\n reply_markup=get_date_keyboard())\n return\n\n with ScheduleDB(config) as db:\n if db.set_auto_post_time(cid, (hour + \":\" + minutes + \":\" + \"00\").rjust(8, '0'), is_today):\n bot.send_message(cid, \"Время установлено\", reply_markup=get_date_keyboard())\n else:\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\",\n reply_markup=get_date_keyboard())\n except BaseException as e:\n logger.warning('callback_auto_posting: {0}'.format(str(e)))\n bot.send_message(cid, \"Случилось что то странное, попробуйте ввести команду заново\")\n\n\n# -------------------------------------\n# FLASK ROUTES\n# -------------------------------------\n\n\n# Empty webserver index, return nothing, just http 200\[email protected]('/', methods=['GET', 'HEAD'])\ndef index():\n return ''\n\n\n# Убирает вебхук\[email protected](\"/remove_webhook\", methods=[\"GET\", \"HEAD\"])\ndef remove_webhook():\n bot.remove_webhook()\n return \"ok\", 200\n\n\n# Сбрасывает вебхук\[email protected](\"/reset_webhook\", methods=[\"GET\", \"HEAD\"])\ndef reset_webhook():\n bot.remove_webhook()\n bot.set_webhook(url=WEBHOOK_URL_BASE+WEBHOOK_URL_PATH, certificate=open(config[\"WEBHOOK_SSL_CERT\"], 'r'))\n return \"ok\", 200\n\n\n# Обработка запросов к вебхуку\[email protected](WEBHOOK_URL_PATH, methods=['POST'])\ndef webhook():\n if flask.request.headers.get('content-type') == 'application/json':\n json_string = flask.request.get_data().decode('utf-8')\n update = telebot.types.Update.de_json(json_string)\n bot.process_new_updates([update])\n return ''\n else:\n flask.abort(403)\n\n\n# Добавление организации в базу данных\[email protected](\"/api/organization\", methods=[\"POST\"])\ndef add_organization():\n if not request.is_json:\n return \"incorrect request\", 403\n\n try:\n content = request.get_json()\n\n if content['key'] != config[\"TOKEN\"]:\n return \"invalid api key\", 403\n\n data = content['data']\n\n answer = {\n 'ok': [],\n 'failed': []}\n\n with ScheduleDB(config) as db:\n for org_data in data:\n # Обязательные параметры запроса\n organization = org_data['organization']\n group = org_data['group']\n\n # Необязательные параметры\n faculty = org_data['faculty'] if 'faculty' in org_data else ''\n\n tag = db.add_organization(organization, faculty, group)\n json_data = {\n 'tag': tag,\n 'data': org_data\n }\n\n if tag is not None:\n answer['ok'].append(json_data)\n else:\n answer['failed'].append(json_data)\n\n return jsonify(answer), 200\n except KeyError as e:\n return 'key not found: {}'.format(str(e)), 403\n\n\n# Добавление расписания в базу данных\[email protected](\"/api/schedule\", methods=[\"POST\"])\ndef add_schedule():\n if not request.is_json:\n return \"incorrect request\", 403\n\n try:\n content = request.get_json()\n\n if content['key'] != config[\"TOKEN\"]:\n return \"invalid api key\", 403\n\n data = content['data']\n\n answer = {'failed': []}\n with ScheduleDB(config) as db:\n for lecture in data:\n # Обязательные параметры запроса\n tag = lecture['tag']\n day = lecture['day']\n number = lecture['number']\n week_type = lecture['week_type']\n title = lecture['title']\n classroom = lecture['classroom']\n\n # Необязательные параметры\n time_start = lecture['time_start'] if 'time_start' in lecture else None\n time_end = lecture['time_end'] if 'time_end' in lecture else None\n lecturer = lecture['lecturer'] if 'lecturer' in lecture else None\n\n if not db.add_lesson(tag, day, number, week_type, time_start, time_end, title, classroom, lecturer):\n answer['failed'].append(lecture)\n return jsonify(answer), 200\n except KeyError as e:\n return 'key not found: {}'.format(str(e)), 403\n\n\nif __name__ == '__main__':\n # Start flask server\n app.run(\n host=config[\"WEBHOOK_LISTEN\"],\n port=config[\"WEBHOOK_PORT\"],\n ssl_context=(config['WEBHOOK_SSL_CERT'], config['WEBHOOK_SSL_PRIV']),\n debug=True)\n"
},
{
"alpha_fraction": 0.6344672441482544,
"alphanum_fraction": 0.6437740921974182,
"avg_line_length": 33.622222900390625,
"blob_id": "4dc005682c505d128fad6c7cc6f770a83b08478f",
"content_id": "d5765b5e4bcca20f5e60f97ea00ccd74a4a1c90a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3474,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 90,
"path": "/autoposting/auto_posting_thread.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "import logging\nimport threading\nfrom datetime import datetime, timedelta\nfrom time import sleep\n\nimport telebot\n\nfrom config import config\nfrom helpers import daysOfWeek, get_date_keyboard, get_week_type\nfrom scheduleCreator import create_schedule_text\nfrom scheduledb import ScheduleDB\nfrom statistic import track\n\nbot = telebot.AsyncTeleBot(config[\"TOKEN\"])\n\n\nlogging.basicConfig(format='%(asctime)-15s [ %(levelname)s ] uid=%(userid)s %(message)s',\n filemode='a',\n filename=config[\"LOG_DIR_PATH\"] + \"log-{0}.log\".format(datetime.now().strftime(\"%Y-%m-%d\")),\n level=\"INFO\")\nlogger = logging.getLogger('bot-logger')\n\n\ndef auto_posting(current_time, day, week_type, is_today=True):\n # Выборка пользователей из базы\n with ScheduleDB(config) as db:\n users = db.find_users_where(auto_posting_time=current_time, is_today=is_today)\n\n if users is None:\n return None\n try:\n for user in users:\n cid = user[0]\n tag = user[1]\n\n schedule = create_schedule_text(tag, day[0], week_type)\n if len(schedule[0]) <= 14:\n continue\n bot.send_message(cid, schedule, reply_markup=get_date_keyboard())\n\n # Статистика\n if config['STATISTIC_TOKEN'] != '':\n track(config['STATISTIC_TOKEN'], cid, current_time, 'auto_posting')\n else:\n logger.info('auto_posting. Time: {0}'.format(current_time), extra={'userid': cid})\n except BaseException as e:\n logger.warning('auto_posting: {0}'.format(str(e)), extra={'userid': 0})\n\n\ndef today_schedule(current_time):\n today = datetime.now()\n week_type = get_week_type(today)\n\n if datetime.weekday(today) == 6:\n today += timedelta(days=1)\n week_type = (week_type + 1) % 2\n\n day = [daysOfWeek[datetime.weekday(today)]]\n\n auto_posting(current_time, day, week_type)\n\n\ndef tomorrow_schedule(current_time):\n tomorrow = datetime.now()\n tomorrow += timedelta(days=1)\n week_type = get_week_type(tomorrow)\n\n # Выборка пользователей из базы у которых установлена отправка расписния на завтрашний день,\n # если сегодня воскресенье, то расписание будет отправляться на понедельник.\n if datetime.weekday(tomorrow) == 6:\n tomorrow += timedelta(days=1)\n week_type = (week_type + 1) % 2\n\n day = [daysOfWeek[datetime.weekday(tomorrow)]]\n\n auto_posting(current_time, day, week_type, is_today=False)\n\n\nif __name__ == \"__main__\":\n while True:\n # Отправка расписания на сегодня\n threading.Thread(target=today_schedule(datetime.now().time().strftime(\"%H:%M:00\"))).start()\n\n # Отправка расписания на завтра\n threading.Thread(target=tomorrow_schedule(datetime.now().time().strftime(\"%H:%M:00\"))).start()\n\n # Вычисляем разницу в секундах, между началом минуты и временем завершения потока\n time_delta = datetime.now() - datetime.now().replace(second=0, microsecond=0)\n # Поток засыпает на время равное количеству секунд до следующей минуты\n sleep(60 - time_delta.seconds)\n"
},
{
"alpha_fraction": 0.7186395525932312,
"alphanum_fraction": 0.7380741834640503,
"avg_line_length": 25.325580596923828,
"blob_id": "d28280e94243d0454ddb33f9375476123e0036a3",
"content_id": "d01ac4126587f6314917fd594a8b47585ec866f8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 2264,
"license_type": "permissive",
"max_line_length": 136,
"num_lines": 86,
"path": "/db/schema.sql",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "CREATE TABLE IF NOT EXISTS organizations\n(\n id serial,\n organization character varying(80),\n faculty character varying(80),\n studgroup character varying(50),\n tag character(30) PRIMARY KEY\n);\n\nCREATE EXTENSION IF NOT EXISTS pg_trgm;\nCREATE INDEX IF NOT EXISTS trgm_idx ON organizations USING GIN (lower(organization || ' ' || faculty || ' ' || studgroup) gin_trgm_ops);\n\nCREATE TABLE IF NOT EXISTS schedule\n(\n id serial,\n tag character(30),\n day character varying(10),\n \"number\" smallint,\n type smallint,\n \"startTime\" time without time zone,\n \"endTime\" time without time zone,\n title character varying(100),\n classroom character varying(100),\n lecturer character varying(100),\n PRIMARY KEY (tag, day, number, type),\n CONSTRAINT schedule_fkey FOREIGN KEY (tag)\n\tREFERENCES organizations (tag) MATCH SIMPLE\n\tON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE IF NOT EXISTS examinations\n(\n tag character(30),\n title character varying(100),\n classroom character varying(100),\n lecturer character varying(100),\n day date,\n CONSTRAINT examinations_fkey FOREIGN KEY (tag)\n\tREFERENCES organizations (tag) MATCH SIMPLE\n\tON UPDATE CASCADE ON DELETE CASCADE\n);\n\nCREATE TABLE IF NOT EXISTS users\n(\n type character(3),\n id bigint,\n name character varying(30),\n username character varying(30),\n \"scheduleTag\" character(30),\n auto_posting_time time without time zone,\n is_today boolean,\n registration_timestamp timestamp with time zone DEFAULT now(),\n PRIMARY KEY (type, id),\n CONSTRAINT users_fkey FOREIGN KEY (\"scheduleTag\")\n REFERENCES organizations (tag) MATCH SIMPLE\n ON UPDATE CASCADE ON DELETE SET NULL\n);\n\nCREATE OR REPLACE VIEW users_vw AS\n SELECT users.type,\n users.id,\n organizations.organization,\n organizations.faculty,\n organizations.studgroup,\n users.auto_posting_time,\n users.is_today,\n users.registration_timestamp\n FROM users\n JOIN organizations ON users.\"scheduleTag\" = organizations.tag\n ORDER BY organizations.studgroup;\n\nCREATE TABLE IF NOT EXISTS reports\n(\n type character(3),\n report_id serial PRIMARY KEY,\n user_id integer,\n report text,\n date date\n);\n\nCREATE TABLE IF NOT EXISTS api_users\n(\n id serial PRIMARY KEY,\n username character varying(50),\n pw_hash character(60)\n)\n"
},
{
"alpha_fraction": 0.5072437524795532,
"alphanum_fraction": 0.5145330429077148,
"avg_line_length": 42.55158615112305,
"blob_id": "511e8cd17151a1524db1aeb0830e62203c2eee42",
"content_id": "972da719a00c5e0ea2041e542b99d7f1fd1b44c8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10975,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 252,
"path": "/bot/scheduledb.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "import hashlib\nimport logging\nimport psycopg2\nfrom datetime import datetime\n\norganization_field_length = 15\nfaculty_field_length = 10\ngroup_field_length = 5\n\n\nclass ScheduleDB:\n def __init__(self, config):\n self.con = psycopg2.connect(\n dbname=config[\"DB_NAME\"],\n user=config[\"DB_USER\"],\n password=config[\"DB_PASSWORD\"],\n host=config[\"DB_HOST\"])\n self.cur = self.con.cursor()\n\n logging.basicConfig(format='%(asctime)-15s [ %(levelname)s ] %(message)s',\n filemode='a',\n filename=config[\"LOG_DIR_PATH\"] + \"log-{0}.log\".format(datetime.now().strftime(\"%Y-%m\")))\n self.logger = logging.getLogger('db-logger')\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.con.commit()\n self.con.close()\n\n @staticmethod\n def create_tag(organization, faculty, group):\n org_hash = hashlib.sha256(organization.encode('utf-8')).hexdigest()\n faculty_hash = hashlib.sha256(faculty.encode('utf-8')).hexdigest()\n group_hash = hashlib.sha256(group.encode('utf-8')).hexdigest()\n return org_hash[:organization_field_length] + \\\n faculty_hash[:faculty_field_length] + \\\n group_hash[:group_field_length]\n\n def add_lesson(self, tag, day, number, week_type, time_start, time_end, title, classroom, lecturer):\n try:\n self.cur.execute('INSERT INTO schedule(tag, day, \"number\", type, \"startTime\", \"endTime\", \\\n title, classroom, lecturer) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s);',\n (tag, day, number, week_type, time_start, time_end, title, classroom, lecturer))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning('Add to schedule failed. Error: {0}. Data:\\\n tag={1},\\\n day={2},\\\n number={3},\\\n week_type={4},\\\n time_start={5},\\\n time_end={6},\\\n title={7},\\\n classroom={8},\\\n lecturer={9}'.format(\n str(e), tag, day, number, week_type, time_start, time_end, title, classroom, lecturer))\n return False\n\n def add_exam(self, tag, title, classroom, lecturer, day):\n try:\n self.cur.execute(\"INSERT INTO examinations(tag, title, classroom, lecturer, day) VALUES(%s,%s,%s,%s,%s);\",\n (tag, title, classroom, lecturer, day))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning(\"Add exam failed. Error: {0}. Data:\\\n tag={1},\\\n title={2},\\\n classroom={3},\\\n lecturer={4},\\\n day={5}\".format(str(e), tag, title, classroom, lecturer, day))\n return False\n\n def add_organization(self, organization, faculty, group):\n tag = self.create_tag(organization, faculty, group)\n try:\n self.cur.execute(\"INSERT INTO organizations(organization, faculty, studgroup, tag) VALUES(%s,%s,%s,%s);\",\n (organization, faculty, group, tag))\n self.con.commit()\n return tag\n except BaseException as e:\n self.logger.warning(\"Add organization failed. Error: {0}. Data:\\\n organization={1},\\\n faculty={2},\\\n group={3},\\\n tag={4}\".format(str(e), organization, faculty, group, tag))\n return None\n\n def add_report(self, cid, report):\n try:\n self.cur.execute('INSERT INTO reports (type, user_id, report, date) VALUES(%s, %s, %s, %s)',\n ('tg', cid, report, datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning('Add report failed. Error: {0}. Data: cid={1}, report={2}'.format(str(e), cid, report))\n return False\n\n def add_user(self, cid, name, username, tag):\n try:\n self.cur.execute('INSERT INTO users VALUES(%s,%s,%s,%s,%s,null,null)', ('tg', cid, name, username, tag))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning('Add user failed. Error: {0}. Data: cid={1}, name={2}, username={3}, tag={4}'.format(\n str(e), cid, name, username, tag))\n raise e\n\n def update_user(self, cid, name, username, tag):\n try:\n self.cur.execute('UPDATE users SET \"scheduleTag\" = (%s) WHERE id = (%s) AND type = (%s)', (tag, cid, 'tg'))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning('Update user failed. Error: {0}. Data: cid={1}, name={2}, username={3}, tag={4}'.format(\n str(e), cid, name, username, tag))\n raise e\n\n def find_user(self, cid):\n try:\n self.cur.execute('SELECT \"scheduleTag\" FROM users WHERE id = (%s) AND type = (%s)', (cid, 'tg'))\n return self.cur.fetchone()\n except BaseException as e:\n self.logger.warning('Select user failed. Error: {0}. Data: cid={1}'.format(str(e), cid))\n raise e\n\n def find_users_where(self, auto_posting_time=None, is_today=None):\n try:\n if auto_posting_time is not None and is_today is not None:\n self.cur.execute('SELECT id, \"scheduleTag\" FROM users \\\n WHERE auto_posting_time = %s AND is_today = %s AND type = (%s)',\n (auto_posting_time, is_today, 'tg'))\n return self.cur.fetchall()\n elif auto_posting_time is not None:\n self.cur.execute('SELECT id, \"scheduleTag\" FROM users \\\n WHERE auto_posting_time = %s AND type = (%s)',\n (auto_posting_time, 'tg'))\n return self.cur.fetchall()\n elif is_today is not None:\n self.cur.execute('SELECT id, \"scheduleTag\" FROM users WHERE is_today = %s AND type = (%s)',\n (is_today, 'tg'))\n return self.cur.fetchall()\n else:\n self.cur.execute('SELECT id, \"scheduleTag\" FROM users WHERE type = (%s)', ['tg'])\n return self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select users failed. Error: {0}. auto_posting_time={1}'.format(\n str(e), auto_posting_time))\n raise e\n\n def get_exams(self, tag):\n exams = []\n try:\n self.cur.execute(\"SELECT day, title, classroom, lecturer FROM examinations \\\n WHERE tag = (%s) ORDER BY day\", [str(tag)])\n exams = self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select exams failed. Error: {0}. Data: tag={1}'.format(str(e), tag))\n raise e\n finally:\n return exams\n\n def get_schedule(self, tag, day, week_type=-1):\n data = []\n try:\n if week_type != -1:\n self.cur.execute('SELECT number,title,classroom,type FROM schedule \\\n WHERE tag = (%s) AND day = (%s) AND (type = 2 OR type = %s) \\\n ORDER BY number, type ASC', (tag, day, week_type))\n else:\n self.cur.execute('SELECT number,title,classroom,type FROM schedule \\\n WHERE tag = (%s) AND day = (%s) ORDER BY number, type ASC', (tag, day))\n data = self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select schedule failed. Error: {0}. Data: tag={1}, day={2}, week_type={3}'.format(\n str(e), tag, day, week_type))\n raise Exception\n finally:\n return data\n\n def get_organizations(self, tag=\"\"):\n organizations = []\n try:\n self.cur.execute(\"SELECT DISTINCT ON (organization) organization, tag \\\n FROM organizations WHERE tag LIKE %s ORDER BY organization;\", [tag + '%'])\n organizations = self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select schedule failed. Error: {0}. Data: tag={1}'.format(str(e), tag))\n raise e\n finally:\n return organizations\n\n def get_faculty(self, tag=\"\"):\n faculties = []\n try:\n self.cur.execute(\"SELECT DISTINCT ON (faculty) faculty, tag \\\n FROM organizations WHERE tag LIKE %s ORDER BY faculty;\", [tag + '%'])\n faculties = self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select schedule failed. Error: {0}. Data: tag={1}'.format(str(e), tag))\n raise e\n finally:\n return faculties\n\n def get_group(self, tag=\"\"):\n group = []\n try:\n self.cur.execute(\"SELECT DISTINCT ON (studGroup) studGroup, tag \\\n FROM organizations WHERE tag LIKE %s ORDER BY studGroup;\",\n [tag + '%'])\n group = self.cur.fetchall()\n except BaseException as e:\n self.logger.warning('Select group failed. Error: {0}. Data: tag={1}'.format(str(e), [tag]))\n raise e\n finally:\n return group\n\n def set_auto_post_time(self, cid, time, is_today):\n try:\n self.cur.execute('UPDATE users SET auto_posting_time = %s, is_today = %s \\\n WHERE id = %s AND type = (%s)',\n (time, is_today, cid, 'tg'))\n self.con.commit()\n return True\n except BaseException as e:\n self.logger.warning('Set auto post time failed. Error: {0}. Data: cid={1}, auto_posting_time={2}'.format(\n str(e), cid, time))\n raise e\n\n def clear_tables(self):\n try:\n self.cur.execute('TRUNCATE users;')\n self.cur.execute('TRUNCATE organizations CASCADE;')\n self.cur.execute('TRUNCATE reports;')\n self.con.commit()\n\n old_isolation_level = self.con.isolation_level\n self.con.set_isolation_level(0)\n\n self.cur.execute('VACUUM')\n self.con.commit()\n\n self.con.set_isolation_level(old_isolation_level)\n\n return True\n except BaseException as e:\n self.logger.warning('clear tables failed. Error: {0}.'.format(\n str(e)))\n raise e\n"
},
{
"alpha_fraction": 0.5569892525672913,
"alphanum_fraction": 0.5569892525672913,
"avg_line_length": 22.25,
"blob_id": "1cedc363cb46ec30232696237d9393e8cf0acac2",
"content_id": "1d1198bc8470fb48a3535b167ac704bd3ee5fe69",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 465,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 20,
"path": "/autoposting/statistic.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "from multiprocessing import Process\n\n\ndef send_statistic(token, uid, message, intent, user_type=None):\n try:\n if user_type is not None:\n pass\n else:\n if intent != 'unknown':\n pass\n else:\n pass\n\n return ''\n except:\n pass\n\n\ndef track(token, uid, message, intent, user_type=None):\n Process(target=send_statistic, args=(token, uid, message, intent, user_type)).start()\n"
},
{
"alpha_fraction": 0.4818897545337677,
"alphanum_fraction": 0.4976378083229065,
"avg_line_length": 32.421051025390625,
"blob_id": "c93692b90fc15ec7d042999b6699f30799747704",
"content_id": "a0e1537a4db267386e5524c1a8558cdaf89d3d74",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 635,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 19,
"path": "/autoposting/deploy",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nprintf \"[%s]\\n\" \"DEFAULT\" > config.ini\n\nprintf \"DB_NAME=%s\\n\" \"$1\" >> config.ini\nprintf \"DB_USER=%s\\n\" \"$2\" >> config.ini\nprintf \"DB_PASSWORD=%s\\n\" \"$3\" >> config.ini\nprintf \"DB_HOST=%s\\n\" \"$4\" >> config.ini\n\nprintf \"TOKEN=%s\\n\" \"$5\" >> config.ini\n\nprintf \"WEEK_TYPE=%u\\n\" \"$6\" >> config.ini\nprintf \"STATISTIC_TOKEN=%s\\n\" \"$7\" >> config.ini\n\nprintf \"LOG_DIR_PATH=%s\\n\" \"/app/log/\" >> config.ini\n\ncp /usr/share/zoneinfo/${8} /etc/localtime && echo ${8} > /etc/timezone\n\npython3 auto_posting_thread.py\n"
},
{
"alpha_fraction": 0.7583973407745361,
"alphanum_fraction": 0.765175461769104,
"avg_line_length": 52.975608825683594,
"blob_id": "8a5ea0eac8db28df59966e5327f0601ba3132099",
"content_id": "9ae3307b24aff238042c3ca75fcddadef8af0979",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 10031,
"license_type": "permissive",
"max_line_length": 409,
"num_lines": 123,
"path": "/bot/README.md",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "# UniversityScheduleBot\nБот для Telegram показывающий расписание занятий. Вы можете протестировать его работу, перейдя по ссылке: [@UniversityScheduleBot](http://telegram.me/UniversityScheduleBot)\n\n\n\nDocker Hub: [paladin705/telegram_schedule_bot](https://hub.docker.com/r/paladin705/telegram_schedule_bot)\n\n## Зависимости\nБот использует Telegram Bot API и Webhook'и для обработки входящих сообщений. Адрес Webhook'а: `http://<WEBHOOK_HOST>:<WEBHOOK_PORT>`. Можно установить Webhook, открыв браузер и перейдя по адресу: http://<WEBHOOK_HOST>:<WEBHOOK_PORT>/reset_webhook. Для работы бота, необходимо создать SSL сертификаты для Webhook'а.\n\nБот реализованный в docker контейнере не имеет прямого доступа к сети и использует сокет `/bot/socket/bot.sock` для обработки запросов. Чтобы передать поступающие запросы боту, можно использовать nginx reverse proxy для передачи их на сокет бота. Также в настройках nginx reverse proxy необходимо указать пути к SSL сертификатам. Без них, бот работать не будет.\n\nБот использует СУБД PostgreSQL для хранения данных.\n\nДля включения дополнительных функций необходимо установить следующие модули:\n\n* Модуль для автоматической отправки расписания: [autoposting](../autoposting)\n* Модуль для работы с базой данных бота (добавление/изменение/удаление групп и файлов расписания): [api_server](https://github.com/paladin-705/VkScheduleBot/tree/main/api_server)\n\n## Создание SSL сертифкатов с помощью OpenSSL для nginx reverse proxy\nНа Linux, создать сертифкаты с помощью OpenSSL можно следующим образом:\n```shell\nopenssl genrsa -out webhook_pkey.pem 2048\nopenssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem\n```\nПри вводе пункта Common Name, нужно написать IP адрес сервера, на котором будет запущен бот.\nПосле завершения создания сертификата, появятся два файла: webhook_pkey.pem и webhook_cert.pem.\n\nДалее представлен пример конфигурации nginx reverse proxy: \n```shell\nserver {\n listen 8443 ssl;\n \n ssl_certificate /usr/src/tg_bot_ssl_certificate/webhook_cert.pem;\n ssl_certificate_key /usr/src/tg_bot_ssl_certificate/webhook_pkey.pem;\n \n location / {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n \n proxy_pass http://unix:/usr/src/tg_bot_socket/bot.sock;\n }\n}\n```\nВ примере были использованы следующие настройки и пути к файлам:\n* Порт сервера - `8443`\n* Путь до webhook_cert.pem - `/usr/src/tg_bot_ssl_certificate/webhook_cert.pem`\n* Путь до webhook_pkey.pem - `/usr/src/tg_bot_ssl_certificate/webhook_pkey.pem`\n* Путь до сокета бота - `http://unix:/usr/src/tg_bot_socket/bot.sock`\n\n## Docker\nДля запуска docker контейнера загружаемого с [Docker Hub](https://hub.docker.com/r/paladin705/telegram_schedule_bot) можно использовать следующую команду:\n```shell\ndocker run \\\n -v ./tg_bot/socket:/bot/socket \\\n -v ./tg_bot/log:/bot/log \\\n -e DB_NAME=<Введите значение параметра> \\\n -e DB_USER=Введите значение параметра<> \\\n -e DB_PASSWORD=<Введите значение параметра> \\\n -e DB_HOST=<Введите значение параметра> \\\n -e TELEGRAM_API_TOKEN=<Введите значение параметра> \\\n -e STATISTIC_TOKEN=<Введите значение параметра> \\\n -e WEEK_TYPE=<Введите значение параметра> \\\n -e TZ=<Введите значение параметра> \\\n paladin705/telegram_schedule_bot:latest\n```\n\n### Файлы\n* `/bot/socket` - В данной директории находится сокет бота: `bot.sock`. Он используется для обработки запросов к боту\n* `/bot/log` - Директория где располагаются логи бота\n\n### Переменные среды\n\n* `DB_NAME` - Название базы данных (БД) PostgreSQL\n* `DB_USER` - Имя пользователя БД\n* `DB_PASSWORD` - Пароль пользователя БД\n* `DB_HOST` - Адрес БД\n* `TELEGRAM_API_TOKEN` - Токен Telegram Bot API\n* `STATISTIC_TOKEN` - Токен для отправки статистики на [chatbase.com](https://chatbase.com/). Необязательный параметр (На данный момент не используется - Chatbase прекращает работу 27 сентября 2021 года)\n* `WEEK_TYPE` - Тип первой недели семестра 0 - числитель, 1 - знаменатель\n* `TZ` - Часовой пояс. По умолчанию `Europe/Moscow`\n\n## Команды бота\nБот принимает текстовые команды, а также команды отправленные с помощью кнопок клавиатуры для ботов.\n\nПоддерживаемые команды\n------------\n|Команда| Описание команды|\n:----------------| -------------\n|/start|Выводит стартовое сообщение и предложение зарегистрироваться|\n|/help|Выводит информацию о боте и список доступных команд|\n|/registration|Выбор ВУЗа, факультета и группы для вывода расписания|\n|/send_report \\<сообщение\\>|Можно отправить информацию об ошибке или что то ещё|\n|/auto_posting_on \\<время\\>|Включение и выбор времени для автоматической отправки расписания в диалог, время должно иметь формат ЧЧ:ММ|\n|/auto_posting_off|Выключение автоматической отправки расписания|\n|\\<сообщение\\>|Будет обработанно в зависимости от введённого текста|\n\n### Расписание занятий\n\nКоманды доступны как при обычном текстовом вводе, так и с помощью кнопок.\n\nСписок команд:\n* `Вся неделя` - Выводит расписание занятий в общем виде (для числителя и знаменателя) на всю неделю\n* `сегодня`, `завтра` - Выводит расписание на указанный день с учётом типа недели (числитель/знаменатель)\n* `понедельник`, `вторник`, `среда`, `четверг`, `пятница`, `суббота`, `воскресенье` - Выводит расписание на указанный день в общем виде (для числителя и знаменателя)\n\n### Расписание экзаменов\n\nДля показа расписания экзаменов служит команда `экзамены`. Также на клавиатуре за месяц перед каждой сессией появляется кнопка для показа расписания экзаменов.\n\n### Автоматическая отправка расписания\n\nДля включения этой опции, должен быть установлен скрипт [autoposting](../autoposting).\n\nКоманда `/auto_posting_on <ЧЧ:ММ>` предназначена для включения автоматической рассылки расписания в назначенное время. Команда имеет обязательный парметр, время отправки `<ЧЧ:ММ>`. После отправки команды, пользователю будет выведена клавиатура с кнопками `<сегодня/завтра>` с помощью которых можно выбрать на какой день будет идти отправка расписания: расписание на сегодня, или расписание завтрашних занятий.\n\nКоманда `/auto_posting_off` позволяет отключить автоматическую рассылку расписания.\n\n### Регистрация\n\nПользователь может зарегистрироваться с помощью клавиатуры бота, на каждом шаге регистрации выбирая университет, а затем курс и группу. Для начала регистрации необходимо ввести команду `/registration`, также пользователю будет предложено зарегистрироваться при первом запуске бота.\n"
},
{
"alpha_fraction": 0.7392995953559875,
"alphanum_fraction": 0.752084493637085,
"avg_line_length": 43.974998474121094,
"blob_id": "677f615ec748612ee1cddcc2bca21ddc41a5a659",
"content_id": "24dda3c477c63dc063229b93041793e658c1b2f5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2475,
"license_type": "permissive",
"max_line_length": 203,
"num_lines": 40,
"path": "/autoposting/README.md",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "# UniversityScheduleBot autoposting script\nМодуль выполняющий автоматическую рассылку расписания для [UniversityScheduleBot](../bot).\n\n\n\nDocker Hub: [paladin705/telegram_schedule_bot_autoposting](https://hub.docker.com/r/paladin705/telegram_schedule_bot_autoposting)\n\n## Зависимости\nМодуль использует Telegram Bot API для отправки расписания и СУБД PostgreSQL для хранения данных.\n\n\n## Docker\nДля запуска docker контейнера загружаемого с [Docker Hub](https://hub.docker.com/r/paladin705/telegram_schedule_bot_autoposting) можно использовать следующую команду:\n```shell\ndocker run \\\n -v ./autoposting/log:/app/log \\\n -e DB_NAME=<Введите значение параметра> \\\n -e DB_USER=Введите значение параметра<> \\\n -e DB_PASSWORD=<Введите значение параметра> \\\n -e DB_HOST=<Введите значение параметра> \\\n -e TELEGRAM_API_TOKEN=<Введите значение параметра> \\\n -e STATISTIC_TOKEN=<Введите значение параметра> \\\n -e WEEK_TYPE=<Введите значение параметра> \\\n -e TZ=<Введите значение параметра> \\\n paladin705/telegram_schedule_bot_autoposting:latest\n```\n\n### Файлы\n* `/app/log` - Директория где располагаются логи модуля\n\n### Переменные среды\n\n* `DB_NAME` - Название базы данных (БД) PostgreSQL\n* `DB_USER` - Имя пользователя БД\n* `DB_PASSWORD` - Пароль пользователя БД\n* `DB_HOST` - Адрес БД\n* `TELEGRAM_API_TOKEN` - Токен Telegram Bot API\n* `STATISTIC_TOKEN` - Токен для отправки статистики на [chatbase.com](https://chatbase.com/). Необязательный параметр (На данный момент не используется - Chatbase прекращает работу 27 сентября 2021 года)\n* `WEEK_TYPE` - Тип первой недели семестра 0 - числитель, 1 - знаменатель\n* `TZ` - Часовой пояс. По умолчанию `Europe/Moscow`\n"
},
{
"alpha_fraction": 0.6311706900596619,
"alphanum_fraction": 0.6466854810714722,
"avg_line_length": 26.269229888916016,
"blob_id": "9fe46de4abf16b61be9cc815fc2ef556614987cf",
"content_id": "5875ee3f185e97088ab92a51664a8d9843256387",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1682,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 52,
"path": "/bot/helpers.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "from telebot import types\nfrom datetime import datetime\nfrom config import config\n\n\ndaysOfWeek = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n\nScheduleType = {\n \"Понедельник\": daysOfWeek[0],\n \"Вторник\": daysOfWeek[1],\n \"Среда\": daysOfWeek[2],\n \"Четверг\": daysOfWeek[3],\n \"Пятница\": daysOfWeek[4],\n \"Суббота\": daysOfWeek[5],\n \"Воскресенье\": daysOfWeek[6],\n \"Сегодня\": \"Today\",\n \"Завтра\": \"Tomorrow\",\n \"Вся неделя\": daysOfWeek\n}\n\ndaysOfWeek_rus = {\n daysOfWeek[0]: \"Понедельник\",\n daysOfWeek[1]: \"Вторник\",\n daysOfWeek[2]: \"Среда\",\n daysOfWeek[3]: \"Четверг\",\n daysOfWeek[4]: \"Пятница\",\n daysOfWeek[5]: \"Суббота\",\n daysOfWeek[6]: \"Воскресенье\",\n}\n\n\ndef get_date_keyboard():\n now = datetime.now()\n\n date_select = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True, one_time_keyboard=False)\n\n # Если сейчас декабрь, январь или май, июнь, то выводится кнопка экзамены\n if now.month == 1 or now.month == 12 or now.month == 5 or now.month == 6:\n date_select.row('Экзамены')\n\n date_select.row(\"Сегодня\")\n date_select.row(\"Завтра\")\n date_select.row(\"Вся неделя\")\n date_select.row(\"Понедельник\", \"Вторник\")\n date_select.row(\"Среда\", \"Четверг\")\n date_select.row(\"Пятница\", \"Суббота\")\n\n return date_select\n\n\ndef get_week_type(day):\n return (day.isocalendar()[1] + int(config[\"WEEK_TYPE\"])) % 2\n"
},
{
"alpha_fraction": 0.648097813129425,
"alphanum_fraction": 0.6609084010124207,
"avg_line_length": 65.90908813476562,
"blob_id": "bf81662d8e2f8f331a200e12c2363e4efaa82f0d",
"content_id": "921ec77b5c973f8ac80805a4e99324f10992c3e7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6995,
"license_type": "permissive",
"max_line_length": 474,
"num_lines": 77,
"path": "/README.md",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "UniversityScheduleBot\n=========================\nБот для Telegram показывающий расписание занятий. Вы можете добавить его себе в Telegram, перейдя по ссылке: [@UniversityScheduleBot](http://telegram.me/UniversityScheduleBot)\n\nПроект разделён на модули. Такая структура, позволяет устанавливать лишь необходимые разработчику части проекта. Ниже представлен список основных модулей бота:\n* Модуль Telegram бота: [UniversityScheduleBot](./bot) - Бот для Telegram показывающий расписание занятий. Основной модуль проекта, осуществляющий обработку пользовательских запросов и формирование ответов на них. \n* Модуль для автоматической отправки расписания: [autoposting](./autoposting)\n* Модуль для работы с базой данных бота (добавление/изменение/удаление групп и файлов расписания): [api_server](https://github.com/paladin-705/VkScheduleBot/tree/main/api_server)\n* Панель управления базой данных бота: [VkScheduleBot Control Panel](https://github.com/paladin-705/VkScheduleBotDB_ControlPanel). Предоставляет веб-интерфейс для взаимодействия с БД расписания, а также позволяет редактировать пользователей API бота (модуль [api_server](https://github.com/paladin-705/VkScheduleBot/tree/main/api_server)). Панель управления является модулем для [UniversityScheduleBot](./bot) и [VkScheduleBot](https://github.com/paladin-705/VkScheduleBot).\n\nТакже бот совместим с ботом для ВК ([VkScheduleBot](https://github.com/paladin-705/VkScheduleBot)) - боты могут использовать одну базу данных для хранения расписания и информации о пользователях.\n\nWiki проекта: [UniversityScheduleBot Wiki](https://github.com/paladin-705/UniversityScheduleBot/wiki)\n\nГотовые Docker образы\n------------\nДля всех модулей проекта уже собраны готовые Docker образы. \n\n\n### Модуль Telegram бота\n\n\nDocker Hub: [paladin705/telegram_schedule_bot](https://hub.docker.com/r/paladin705/telegram_schedule_bot)\n\n### Модуль для автоматической отправки расписания\n\n\nDocker Hub: [paladin705/telegram_schedule_bot_autoposting](https://hub.docker.com/r/paladin705/telegram_schedule_bot_autoposting)\n\n### Модуль для работы с базой данных бота\n\n\nDocker Hub: [paladin705/vk_schedule_bot_api](https://hub.docker.com/r/paladin705/vk_schedule_bot_api)\n\n### Панель управления базой данных бота\n\n\nDocker Hub: [paladin705/vk_schedule_bot_db_control_panel](https://hub.docker.com/r/paladin705/vk_schedule_bot_db_control_panel)\n\nСтруктура репозитория\n------------\n .\n ├── autoposting # Модуль для автоматической отправки расписания\n │ ├── auto_posting_thread.py # Основной скрипт модуля\n │ ├── scheduleCreator.py # Функции для генерации сообщения с расписанием\n │ ├── scheduledb.py # Класс для работы с БД\n │ ├── statistic.py # Отправка статистики на chatbase.com (На данный момент не используется - Chatbase прекращает работу 27 сентября 2021 года)\n │ ├── helpers.py # Вспомогательные функции\n │ ├── config.py # Настройки модуля \n │ ├── requirements.txt # Список используемых библиотек\n │ ├── deploy # Скрипт для запуска Docker контейнера \n │ ├── Dockerfile\n │ └── README.md\n ├── bot # Модуль бота для Telegram\n │ ├── UniversityScheduleBot.py # Основной скрипт модуля\n │ ├── scheduleCreator.py # Функции для генерации сообщения с расписанием\n │ ├── scheduledb.py # Класс для работы с БД\n │ ├── statistic.py # Отправка статистики на chatbase.com (На данный момент не используется - Chatbase прекращает работу 27 сентября 2021 года)\n │ ├── helpers.py # Вспомогательные функции\n │ ├── config.py # Настройки модуля \n │ ├── requirements.txt # Список используемых библиотек\n │ ├── deploy # Скрипт для запуска Docker контейнера \n │ ├── Dockerfile\n │ ├── commandsList.txt # Лист команд для @BotFather\n │ └── README.md\n ├── db # Файлы для базы данных\n │ └── schema.sql # Схема базы данных\n ├── docs # Файлы Wiki проекта\n │ └── gifs # Gif'ки с примерами использования команд\n │ ├── auto_posting_off_instruction.gif\n │ ├── auto_posting_on_instruction.gif\n │ ├── get_schedule_instruction.gif\n │ ├── registration_instruction.gif\n │ └── send_report_instruction.gif\n ├── .gitignore \n ├── LICENSE\n └── README.md\n"
},
{
"alpha_fraction": 0.5168195962905884,
"alphanum_fraction": 0.5338575839996338,
"avg_line_length": 30.356164932250977,
"blob_id": "01151648ec17efc60e74ace8ec6c533bec47945b",
"content_id": "d93153a2271ff6c2bc284b3007451ba55a5b97a6",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2579,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 73,
"path": "/autoposting/scheduleCreator.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom functools import lru_cache\n\nimport scheduledb\nfrom config import config\nfrom helpers import daysOfWeek_rus\n\n\ndef print_type(raw_type, week_type=-1):\n # Если задан тип недели (числитель/знаменатель), т.е week_type не равен значению по умолчанию,\n # то дополнительная информация о типе недели не выводится\n if week_type != -1:\n return \"\"\n\n raw_type = int(raw_type)\n if raw_type == 0:\n return \"числ\"\n elif raw_type == 1:\n return \"знам\"\n elif raw_type == 2:\n return \"\"\n\n\n@lru_cache(maxsize=128)\ndef create_schedule_text(tag, day, week_type=-1):\n result = []\n schedule = \"\"\n try:\n with scheduledb.ScheduleDB(config) as db:\n data = db.get_schedule(tag, day, week_type)\n\n schedule += \">{0}:\\n\".format(daysOfWeek_rus[day])\n index = 0\n while index < len(data):\n row = data[index]\n\n title = ' '.join(str(row[1]).split())\n classroom = ' '.join(str(row[2]).split())\n\n schedule += str(row[0]) + \" пара:\\n\"\n # Этот блок нужен для вывода тех занятий, где занятия по числителю и знамнателю различаются\n if index != len(data) - 1:\n # Сравнивается порядковый номер занятия данной и следующей строки и если они равны,\n # то они выводятся вместе\n if data[index + 1][0] == row[0]:\n schedule += '{0} {1} {2}\\n'.format(title, classroom, print_type(row[3], week_type))\n\n index += 1\n row = data[index]\n title = ' '.join(str(row[1]).split())\n classroom = ' '.join(str(row[2]).split())\n\n schedule += '{0} {1} {2}\\n'.format(title, classroom, print_type(row[3], week_type))\n else:\n schedule += '{0} {1} {2}\\n'.format(title, classroom, print_type(row[3], week_type))\n else:\n schedule += '{0} {1} {2}\\n'.format(title, classroom, print_type(row[3], week_type))\n\n schedule += \"------------\\n\"\n index += 1\n result.append(schedule)\n except:\n pass\n finally:\n return result\n\n\ndef create_schedule_xls(tag, day):\n pass\n\n\ndef create_schedule_pdf(tag, day):\n pass\n"
},
{
"alpha_fraction": 0.6112083792686462,
"alphanum_fraction": 0.6164623498916626,
"avg_line_length": 16.303030014038086,
"blob_id": "094e8c13583620e45bcd618ef707154eedf51a42",
"content_id": "0058871b8bf2b6a6ee923be40b62f625593706a2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 571,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 33,
"path": "/autoposting/Dockerfile",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "FROM python:3.6-alpine\n\nLABEL maintainer=\"Sergey Kornev <[email protected]>\"\n\nENV TZ=\"Europe/Moscow\"\n\nENV DB_NAME=\nENV DB_USER=\nENV DB_PASSWORD=\nENV DB_HOST=\n\nENV TELEGRAM_API_TOKEN=\n\nENV STATISTIC_TOKEN=\n\nENV WEEK_TYPE=\n\nWORKDIR /app\n\nRUN apk update \\\n && apk upgrade \\\n && apk add tzdata \\\n && apk add git build-base postgresql-dev \\\n && mkdir log\n\nCOPY * ./\n\nRUN pip3 install -r requirements.txt \\\n && chmod +x deploy\n\nCMD ./deploy ${DB_NAME} ${DB_USER} ${DB_PASSWORD} ${DB_HOST} \\\n ${TELEGRAM_API_TOKEN} \\\n ${WEEK_TYPE} ${STATISTIC_TOKEN} ${TZ}\n"
},
{
"alpha_fraction": 0.6958333253860474,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 25.66666603088379,
"blob_id": "5749448aecf54bb5a17ee9c11cc2e65a711841f1",
"content_id": "59da02a817f5a5d52bedfd8b4c7b05c3820a82e8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 240,
"license_type": "permissive",
"max_line_length": 57,
"num_lines": 9,
"path": "/autoposting/config.py",
"repo_name": "paladin-705/UniversityScheduleBot",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport configparser\nimport os\n\nconfig_file = configparser.ConfigParser()\nconfig = config_file['DEFAULT']\n\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\nconfig_file.read(current_path + '/' + \"config.ini\")\n"
}
] | 13 |
PAE-ITBA-ML-2019/Regresion-Logistica---Teor-a | https://github.com/PAE-ITBA-ML-2019/Regresion-Logistica---Teor-a | 672f2bbc4e252c377ccf44ab31220e541bcb47eb | e3df7f436732505fbc9ba2d60854ad16d2cd1e39 | c80306e19c1796a408dacc88efe47faef0bdc1c8 | refs/heads/master | 2020-08-15T09:12:34.414170 | 2019-05-03T20:34:19 | 2019-05-03T20:34:19 | 215,314,328 | 0 | 3 | null | null | null | null | null | [
{
"alpha_fraction": 0.782608687877655,
"alphanum_fraction": 0.782608687877655,
"avg_line_length": 21,
"blob_id": "9546ba0e4fe9c0f030634c9843d3d3645d01ae72",
"content_id": "3165b38c3fe90ea0e5c3d5801066e7594befbc57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 23,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 1,
"path": "/README.md",
"repo_name": "PAE-ITBA-ML-2019/Regresion-Logistica---Teor-a",
"src_encoding": "UTF-8",
"text": "# Regresion-Logistica\r\n"
},
{
"alpha_fraction": 0.5586118698120117,
"alphanum_fraction": 0.5878778100013733,
"avg_line_length": 36.128047943115234,
"blob_id": "dcc8e6eff4dc7b044ff8c7aae9a979da77d7bbbb",
"content_id": "893d980a100ace3ecf1891af6294ca29fd0880e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6255,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 164,
"path": "/helper.py",
"repo_name": "PAE-ITBA-ML-2019/Regresion-Logistica---Teor-a",
"src_encoding": "UTF-8",
"text": "import keras\r\nimport matplotlib\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib.gridspec import GridSpec\r\nimport numpy as np\r\nfrom IPython.display import clear_output\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\r\nimport matplotlib.animation as animation\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\n\r\n\r\nclass log_weights(keras.callbacks.Callback):\r\n \"\"\"Callback that records events into a `History` object.\r\n This callback is automatically applied to\r\n every Keras model. The `History` object\r\n gets returned by the `fit` method of models.\r\n \"\"\"\r\n def __init__(self,get_weights):\r\n self.get_weights=get_weights \r\n self.weights=[]\r\n \r\n def on_train_begin(self, logs=None):\r\n self.epoch = []\r\n self.history = {}\r\n\r\n def on_batch_end(self, batch, logs=None):\r\n logs = logs or {}\r\n #self.epoch.append(epoch)\r\n self.weights.append(self.get_weights(self.model))\r\n\r\nclass plot_learning_curve(keras.callbacks.Callback):\r\n def __init__(self, plot_interval=1, evaluate_interval=10, x_val=None, y_val_categorical=None,epochs=None):\r\n self.plot_interval = plot_interval\r\n self.evaluate_interval = evaluate_interval\r\n self.x_val = x_val\r\n self.y_val_categorical = y_val_categorical\r\n self.epochs=epochs\r\n #self.model = model\r\n \r\n def on_train_begin(self, logs={}):\r\n print('Begin training')\r\n self.i = 0\r\n self.x = []\r\n self.losses = []\r\n self.val_losses = []\r\n self.acc = []\r\n self.val_acc = []\r\n self.logs = []\r\n \r\n def on_epoch_end(self, epoch, logs={}):\r\n if self.evaluate_interval is None:\r\n self.logs.append(logs)\r\n self.x.append(self.i)\r\n self.losses.append(logs.get('loss'))\r\n self.val_losses.append(logs.get('val_loss'))\r\n self.acc.append(logs.get('acc'))\r\n self.val_acc.append(logs.get('val_acc'))\r\n self.i += 1\r\n \r\n if (epoch%self.plot_interval==0):\r\n clear_output(wait=True)\r\n f, (ax1, ax2) = plt.subplots(1, 2, sharex=True, figsize=(20,5))\r\n ax1.plot(self.x, self.losses, label=\"loss\")\r\n ax1.plot(self.x, self.val_losses, label=\"val_loss\")\r\n if self.epochs:\r\n ax1.set_xlim(-1,self.epochs)\r\n ax1.legend()\r\n\r\n ax2.plot(self.x, self.acc, label=\"acc\")\r\n ax2.plot(self.x, self.val_acc, label=\"val_acc\")\r\n if self.epochs:\r\n ax2.set_xlim(-1,self.epochs)\r\n ax2.legend()\r\n plt.show();\r\n\r\n\r\ndef gen_frame(num, weights_list, w1_mesh, w2_mesh,J,set_weights,ax,model,X,y):\r\n surf = ax.plot_surface(w1_mesh, w2_mesh, J, cmap=cm.coolwarm,\r\n linewidth=0, antialiased=False)\r\n w1=weights_list[num][0]\r\n w2=weights_list[num][0]\r\n set_weights(model,w1,w2)\r\n j=get_loss(model,X,y)\r\n ax.scatter(w1, w2, j,c='k')\r\n ax.set_xlabel('w1')\r\n ax.set_ylabel('w2')\r\n ax.set_title('Función de costo')\r\n ax.zaxis.set_major_locator(LinearLocator(10))\r\n ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\r\n # Add a color bar which maps values to colors.\r\n\r\ndef animate_loss_surface(X,y,weights_list,model,set_weights, w1_range,w2_range,n_points):\r\n w1_mesh,w2_mesh,J=plot_loss_surface(X,y,model,set_weights, w1_range,w2_range,n_points,plot=False)\r\n fig = plt.figure(figsize=(16,10))\r\n ax = fig.gca(projection='3d')\r\n loss_ani = animation.FuncAnimation(fig, gen_frame, len(weights_list), fargs=(weights_list, w1_mesh, w2_mesh,J,set_weights,ax,model,X,y),interval=50, blit=True)\r\n loss_ani.save('loss.mp4')\r\n\r\ndef plot_loss_surface(X,y,model,set_weights, w1_range,w2_range,n_points,plot=True):\r\n \r\n # Make data.\r\n w1 = np.arange(w1_range[0], w1_range[1], (w1_range[1]-w1_range[0]) / n_points)\r\n w2 = np.arange(w2_range[0], w2_range[1], (w2_range[1]-w2_range[0]) / n_points)\r\n w1_mesh,w2_mesh = np.meshgrid(w1, w2)\r\n J=np.zeros(w1_mesh.shape)\r\n lista=np.array([w1_mesh,w2_mesh])\r\n for w1_i,w1_v in enumerate(w1):\r\n for w2_i,w2_v in enumerate(w2):\r\n J[w1_i,w2_i]=get_loss(w1_mesh[w1_i,w2_i],w2_mesh[w1_i,w2_i],model,X,y,set_weights)\r\n if plot:\r\n # Plot the surface.\r\n fig = plt.figure(figsize=(16,10))\r\n ax = fig.gca(projection='3d')\r\n surf = ax.plot_surface(w1_mesh, w2_mesh, J, cmap=cm.coolwarm,\r\n linewidth=0, antialiased=False)\r\n\r\n #ax.plot(history[0,:],history[1,:],history[2,:])\r\n ax.set_xlabel('w1')\r\n ax.set_ylabel('w2')\r\n ax.set_title('Función de costo')\r\n ax.zaxis.set_major_locator(LinearLocator(10))\r\n ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\r\n\r\n # Add a color bar which maps values to colors.\r\n fig.colorbar(surf, shrink=0.5, aspect=5)\r\n # rotate the axes and update\r\n #angle=0\r\n #ax.view_init(0, angle)\r\n plt.draw()\r\n plt.show()\r\n return w1_mesh,w2_mesh,J\r\n\r\ndef get_loss(w1,w2,model,X,y,set_weights):\r\n set_weights(model,w1,w2)\r\n return model.evaluate(X,y,verbose=0)[0]\r\n\r\ndef plotBoundary(data, labels, clf_1, N,degree=False,include_bias=False):\r\n class_1 = data[labels == 1]\r\n class_0 = data[labels == 0]\r\n N = 300\r\n mins = data[:,:2].min(axis=0)\r\n maxs = data[:,:2].max(axis=0)\r\n x1 = np.linspace(mins[0], maxs[0], N)\r\n x2 = np.linspace(mins[1], maxs[1], N)\r\n x1, x2 = np.meshgrid(x1, x2)\r\n X=np.c_[x1.flatten(), x2.flatten()]\r\n if degree:\r\n poly=PolynomialFeatures(degree,include_bias=include_bias)\r\n X=poly.fit_transform(X)\r\n Z_nn = clf_1.predict_proba(X)[:, 0]\r\n\r\n # Put the result into a color plot\r\n Z_nn = Z_nn.reshape(x1.shape)\r\n \r\n fig = plt.figure(figsize=(20,10))\r\n ax = fig.gca()\r\n cm = plt.cm.RdBu\r\n \r\n ax.contour(x1, x2, Z_nn, (0.5,), colors='b', linewidths=1)\r\n ax.scatter(class_1[:,0], class_1[:,1], color='b', s=20, alpha=0.5)\r\n ax.scatter(class_0[:,0], class_0[:,1], color='r', s=20, alpha=0.5)\r\n plt.show()\r\n"
}
] | 2 |
sauer2/various-scripts | https://github.com/sauer2/various-scripts | eec27fdce8447e39a65b3ab56124e4297d490f48 | c81dad8fde55328fa8d035ff960c1e1ee265b64b | 6cbfc30e7f3e01e11562a9c02da23e3bfc24f560 | refs/heads/master | 2016-08-03T10:36:28.003835 | 2015-11-18T15:46:59 | 2015-11-18T15:46:59 | 21,745,436 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5177664756774902,
"alphanum_fraction": 0.5203045606613159,
"avg_line_length": 22.176469802856445,
"blob_id": "a1eb64b387233bf80b8f7f62d65e9f99f57a908a",
"content_id": "3f7ba0374d92a193196dda71953f0f3651f4b2e9",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 790,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 34,
"path": "/Phrasengenerator/PhrasenLib/Chain.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace PhrasenLib\n{\n public class Chain : AbstractSymbol\n {\n private List<AbstractSymbol> children = new List<AbstractSymbol>();\n private int count;\n\n override public String evaluate()\n {\n String result = \"\";\n for (int i = 0; i < count; i++)\n {\n foreach (var child in children)\n {\n result += child.evaluate();\n }\n }\n\n return result;\n }\n\n public Chain(AbstractSymbol[] newChildren, int count = 1)\n {\n children.AddRange(newChildren);\n this.count = count;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.7248908281326294,
"alphanum_fraction": 0.7248908281326294,
"avg_line_length": 15.357142448425293,
"blob_id": "6c64713b301f3cedd56f9e6ac0136a39df81123a",
"content_id": "9f257a8b7f8a43a14d9705319d967bdbaff49754",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 229,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 14,
"path": "/configs_and_snippets/antaresIII/rebuild.sh",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "echo \"Deleting old files...\"\nmake clean\n\necho \"Building makefiles...\"\ncmake .\n\necho \"Building binary...\"\nmake\n\necho \"Moving binary into parent directory...\"\nmv ./src/AntaresIII AntaresIII\n\necho \"Executing binary...\"\n./AntaresIII\n"
},
{
"alpha_fraction": 0.43952009081840515,
"alphanum_fraction": 0.4473555386066437,
"avg_line_length": 34.5217399597168,
"blob_id": "0028c13cf680a211c9ef3fd5e9ebca9bd9eeaa7b",
"content_id": "4f85c1f89a2d368208a2f37f7d97701c7e39b3e3",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4084,
"license_type": "permissive",
"max_line_length": 198,
"num_lines": 115,
"path": "/toy_languages/brainfuck.py",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "# brainfuck interpreter\n# (c) 2013 by Sauer2\n\n# the upper limit of available cells\nCELL_MAX = 1023\n\n# CellStorage manages the cells as well as the upper cell count\nclass CellStorage:\n cells = list(range(CELL_MAX + 1))\n cell_ptr = 0\n \n def __init__(self):\n for i in range(CELL_MAX + 1):\n self.cells[i] = 0\n \n def decr_pntr(self):\n if self.cell_ptr == 0:\n print (self.cells)\n raise OverflowError(\"Underflow: Attempt to point before the first cell!\")\n else:\n self.cell_ptr = self.cell_ptr - 1\n \n def incr_pntr(self):\n if self.cell_ptr == CELL_MAX:\n raise OverflowError(\"Overflow: Only \" + CELL_MAX + \" can be used!\")\n else:\n self.cell_ptr = self.cell_ptr + 1\n \n def decr_value(self):\n if self.cells[self.cell_ptr] == 0:\n raise OverflowError(\"Underflow: Cel value may be positive only!\")\n else:\n self.cells[self.cell_ptr] = self.cells[self.cell_ptr] - 1\n \n def incr_value(self):\n self.cells[self.cell_ptr] = self.cells[self.cell_ptr] + 1\n \n def getVal(self):\n return self.cells[self.cell_ptr]\n \n def setVal(self, value):\n self.cells[self.cell_ptr] = ord(value)\n \n def print_cells(self):\n print (self.cells)\n\n# the interpreter\nclass Interpreter:\n storage = CellStorage()\n output = \"\"\n input = \"\"\n source = []\n src_len = 0\n src_pos = 0\n inp_pos = 0\n loop_level = 0\n \n def __init__(self, source, input):\n self.source = list(source)\n self.src_len = len(source)\n self.input = input\n self.interpr_rec(0)\n print(self.output)\n \n def interpr_rec(self, loop_pos):\n looping = True\n while looping:\n \n # execute all commands until hitting EOF or ]\n execute = True\n while execute:\n if self.src_pos == self.src_len:\n return\n if self.source[self.src_pos] == \"]\":\n if self.source[self.src_pos] == \"]\" and self.loop_level == 0:\n raise OverflowError(\"Loop underflow!\")\n execute = False\n self.src_pos += 1\n \n else:\n execute = True\n \n if self.source[self.src_pos] == \"[\":\n self.src_pos += 1\n self.loop_level += 1\n self.interpr_rec(self.src_pos)\n else:\n if self.source[self.src_pos] == \"#\":\n self.storage.print_cells()\n if self.source[self.src_pos] == \"+\":\n self.storage.incr_value()\n if self.source[self.src_pos] == \"-\":\n self.storage.decr_value()\n if self.source[self.src_pos] == \">\":\n self.storage.incr_pntr()\n if self.source[self.src_pos] == \"<\":\n self.storage.decr_pntr()\n if self.source[self.src_pos] == \".\":\n self.output = self.output + chr(self.storage.getVal())\n if self.source[self.src_pos] == \",\":\n self.storage.setVal(self.input[self.inp_pos])\n self.inp_pos += 1\n self.src_pos += 1\n \n # check, if this recursion is in a loop and have to run it again\n if self.loop_level != 0 and self.storage.getVal() > 0:\n looping = True\n self.src_pos = loop_pos\n else:\n looping = False\n \n\n# test it\nhello_world_src = \">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++.\"\ninterprt = Interpreter(hello_world_src, \"\")"
},
{
"alpha_fraction": 0.8159999847412109,
"alphanum_fraction": 0.8159999847412109,
"avg_line_length": 40.66666793823242,
"blob_id": "0ee13a989a82d5bba8005e2e7e3998f8c07c688b",
"content_id": "60b19599552d626c85d88dc1ce8c2ba8b48f6fc7",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 125,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 3,
"path": "/configs_and_snippets/antaresIII/src/CMakeLists.txt",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "add_executable(AntaresIII main.c filereader.c stringloader.c menus.c)\n\ntarget_link_libraries(AntaresIII ${CURSES_LIBRARIES})\n"
},
{
"alpha_fraction": 0.7215569019317627,
"alphanum_fraction": 0.7215569019317627,
"avg_line_length": 29.363636016845703,
"blob_id": "8af6b45ad87399cad56023a1d582a81d54328e9a",
"content_id": "d4329fc12ede0597c69fab13686453780035800b",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 334,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 11,
"path": "/configs_and_snippets/antaresIII/include/menus.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#ifndef MENUS_H\n#define MENUS_H\n\n/* A simple menu function that returns the selected option. */\nchar* simple_list_menu(char* title, unsigned char count, char* options[], char* descriptions[]);\n\n/* A fatal error function that displays a BSOD. */\n/* filename can be NULL. */\nvoid fatal_error(char* description, char* filename);\n\n#endif\n"
},
{
"alpha_fraction": 0.5759717226028442,
"alphanum_fraction": 0.6837455630302429,
"avg_line_length": 39.5,
"blob_id": "dca57657b1c01f70557952210994523a9d60d705",
"content_id": "aacd3cfd80aaf98446eba72668ee6ef16b3d4f35",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 566,
"license_type": "permissive",
"max_line_length": 164,
"num_lines": 14,
"path": "/score-hunter/src/Makefile",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "CC = g++\nCFLAGS = -O2 -Wall -std=c++11\n# to avoid the console window with mingw, add -mwindow\n\nINC = -I \"SDL2/i686-w64-mingw32/include/SDL2\" -I \"SDL2_image/i686-w64-mingw32/include/SDL2\" -I \"SDL2_ttf/i686-w64-mingw32/include/SDL2\"\nLDFLAGS = -L \"SDL2/i686-w64-mingw32/lib\" -L \"SDL2_image/i686-w64-mingw32/lib\" -L \"SDL2_ttf/i686-w64-mingw32/lib\" -lmingw32 -lSDL2main -lSDL2 -lSDL2_image -lSDL2_ttf\n\nOBJ = Main.o Enemies.o ImgManager.o Player.o ScoreManager.o tinyxml2.o\n\ngame: $(OBJ)\n\t$(CC) $(CFLAGS) -o game $(OBJ) $(LDFLAGS)\n\n%.o: %.cpp\n\t$(CC) $(INC) $(CFLAGS) -c $<"
},
{
"alpha_fraction": 0.7528089880943298,
"alphanum_fraction": 0.7528089880943298,
"avg_line_length": 13.833333015441895,
"blob_id": "89ae22bd48a901647301d80015091043ccad2229",
"content_id": "8428258138d9345961609cff5b92f331e8c4d795",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 89,
"license_type": "permissive",
"max_line_length": 37,
"num_lines": 6,
"path": "/configs_and_snippets/antaresIII/include/filereader.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#ifndef FILEREADER_H\n#define FILEREADER_H\n\nchar* read_from_file(char* filename);\n\n#endif\n"
},
{
"alpha_fraction": 0.7167487740516663,
"alphanum_fraction": 0.7167487740516663,
"avg_line_length": 15.875,
"blob_id": "11e6ac5cf315b50816c52a6992f285b7e88964f5",
"content_id": "a9c1b5f140d179a6809ac2c7a29e033f11f4ba14",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 406,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 24,
"path": "/score-hunter/src/Player.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"SDL.h\"\n#include \"Bullets.h\"\n#include <vector>\n\nenum class Directions {Up, Down, Left, Right, None};\n\nclass Player\n{\npublic:\n\tPlayer(void);\n\t~Player(void);\n\tint mapPos;\n\tSDL_Rect pos;\n\tbool alive;\n\tvoid resetPlayer(void);\n\tvoid update(bool keySpace, Directions upDown, Directions leftRight);\n\tstd::vector<bullet> bullets;\n\tint score;\nprivate:\n\tint vecX, vecY;\n\tint shootCounter;\n};\n\n"
},
{
"alpha_fraction": 0.6666010618209839,
"alphanum_fraction": 0.685101330280304,
"avg_line_length": 23.91176414489746,
"blob_id": "440317e042c927d69b6f50c278c865edc6e0f674",
"content_id": "3601fff92d69140f20cf413ac7df9ceee5fb04e1",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5081,
"license_type": "permissive",
"max_line_length": 122,
"num_lines": 204,
"path": "/score-hunter/src/ScoreManager.cpp",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <sstream>\n#include \"ScoreManager.h\"\n#include \"tinyxml2.h\"\n\n\nScoreManager::ScoreManager()\n{\n}\n\n\nScoreManager::~ScoreManager(void)\n{\n}\n\nvoid ScoreManager::addEntry(std::string name, int score)\n{\n\tscoreEntry newEntry = {score, name};\n\n\t// simply insert, if the list is empty\n\tif (entries.size() == 0)\n\t{\n\t\tentries.insert(entries.end(), newEntry);\n\t}\n\t// otherwise insert it behind the right entry and remove the last entry\n\telse\n\t{\n\t\tbool added = false;\n\t\tfor (unsigned int pos = 0; pos < entries.size(); pos++)\n\t\t{\n\t\t\tif (entries[pos].score < newEntry.score)\n\t\t\t{\n\t\t\t\tadded = true;\n\t\t\t\tentries.insert(entries.begin()+pos, newEntry);\n\t\t\t\twhile (entries.size() > 8)\tentries.pop_back();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (added == false)\n\t\t{\n\t\t\tentries.insert(entries.end(), newEntry);\n\t\t}\n\t}\n}\n\nbool ScoreManager::load()\n{\n\ttinyxml2::XMLDocument scoreDoc;\n\tscoreDoc.LoadFile(\"res/txt/scores.xml\");\n\tif (scoreDoc.Error() == true)\n\t{\n\t\tstd::cout << \"Couldn't load scores.xml\" << std::endl;\n\t\tscoreDoc.PrintError();\n\t\treturn false;\n\t}\n\n\ttinyxml2::XMLNode *root = scoreDoc.RootElement();\n\ttinyxml2::XMLElement *scoreElem = root->FirstChildElement(\"score\");\n\t\n\tif (entries.size() > 0) entries.clear();\n\n\tdo\n\t{\n\t\tscoreEntry newEntry;\n\t\tnewEntry.name = scoreElem->Attribute(\"name\");\n\t\tnewEntry.score = scoreElem->IntAttribute(\"value\");\n\t\tentries.insert(entries.end(), newEntry);\n\t\tscoreElem = scoreElem->NextSiblingElement();\n\t} while (scoreElem != nullptr);\n\n\treturn true;\n}\n\nbool ScoreManager::save()\n{\n\ttinyxml2::XMLDocument saveDoc;\n\ttinyxml2::XMLElement *rootElement = saveDoc.NewElement(\"scores\");\n\tsaveDoc.InsertFirstChild(rootElement);\n\n\tif (entries.size() > 0)\n\t{\n\t\tfor (unsigned int pos = 0; pos < entries.size(); pos++)\n\t\t{\n\t\t\ttinyxml2::XMLElement *entryElement = saveDoc.NewElement(\"score\");\n\t\t\tentryElement->SetAttribute(\"name\", entries[pos].name.c_str());\n\t\t\tentryElement->SetAttribute(\"value\", entries[pos].score);\n\t\t\trootElement->InsertEndChild(entryElement);\n\t\t}\n\t}\n\n\tsaveDoc.SaveFile(\"res/txt/scores.xml\");\n\tif (saveDoc.Error() == false)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tsaveDoc.PrintError();\n\t\treturn false;\n\t}\n\t\n}\n\nbool ScoreManager::isNewScore(int score)\n{\n\tif (entries.back().score < score)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nSDL_Texture *ScoreManager::getOverview(TTF_Font *scoreFont, SDL_Renderer *scoreRenderer, SDL_Color fontColor)\n{\n\tSDL_Surface *tempSur = SDL_CreateRGBSurface(0, 800, 600, 32, 0, 0, 0, 0);\n\n\t// insert title\n\tSDL_Surface *titleSur = TTF_RenderText_Blended(scoreFont, \"SCORES --- Press RETURN to get to the main menu.\", fontColor);\n\tSDL_Rect titlePos = {16, 16, titleSur->w, titleSur->h};\n\tSDL_BlitSurface(titleSur, nullptr, tempSur, &titlePos);\n\tSDL_FreeSurface(titleSur);\n\n\t// insert the score labels\n\tint scoreY = 64;\n\t\n\tif (entries.size() > 0)\n\t{\n\t\tfor (unsigned int pos = 0; pos < entries.size(); pos++)\n\t\t{\n\t\t\tstd::string entryStr;\n\t\t\tstd::stringstream entryStream;\n\n\t\t\tif (entries[pos].score < 1000000) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 100000) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 10000) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 1000) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 100) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 10) entryStream << \"0\";\n\t\t\tif (entries[pos].score < 1) entryStream << \"0\"; // haha, great job, player\n\n\t\t\tentryStream << entries[pos].score << \" \" << entries[pos].name;\n\t\t\tentryStr = entryStream.str();\n\n\t\t\tSDL_Surface *scoreSur = TTF_RenderText_Blended(scoreFont, entryStr.c_str(), fontColor);\n\t\t\tSDL_Rect scorePos = {16, scoreY, scoreSur->w, scoreSur->h};\n\t\t\tSDL_BlitSurface(scoreSur, nullptr, tempSur, &scorePos);\n\t\t\tSDL_FreeSurface(scoreSur);\n\n\t\t\tscoreY += 32;\n\t\t}\n\t}\n\n\tSDL_Texture *scoreTexture = SDL_CreateTextureFromSurface(scoreRenderer, tempSur);\n\tSDL_FreeSurface(tempSur);\n\treturn scoreTexture;\n\t\n}\n\nvoid ScoreManager::updatePrompt(SDL_Event *event)\n{\n\tif (event->type == SDL_TEXTEDITING)\n\t{\n\t\tpromptText == event->edit.text;\n\t}\n\telse if (event->type == SDL_TEXTINPUT)\n\t{\n\t\tpromptText += event->text.text;\n\t}\n\n}\n\nSDL_Texture *ScoreManager::getPromptView(TTF_Font *scoreFont, SDL_Renderer *scoreRenderer, SDL_Color fontColor)\n{\n\tSDL_Surface *tempSur = SDL_CreateRGBSurface(0, 800, 600, 32, 0, 0, 0, 0);\n\n\t// insert title\n\tSDL_Surface *titleSur = TTF_RenderText_Blended(scoreFont, \"New Highscore --- insert your name:\", fontColor);\n\tSDL_Rect titlePos = {16, 16, titleSur->w, titleSur->h};\n\tSDL_BlitSurface(titleSur, nullptr, tempSur, &titlePos);\n\tSDL_FreeSurface(titleSur);\n\n\t// insert the score labels\n\tint nameY = 64;\n\t\n\tstd::string entryStr;\n\tstd::stringstream entryStream;\n\n\tentryStream << promptText;\n\tentryStream << \"|\";\n\n\tentryStr = entryStream.str();\n\n\tSDL_Surface *scoreSur = TTF_RenderText_Blended(scoreFont, entryStr.c_str(), fontColor);\n\tSDL_Rect scorePos = {16, nameY, scoreSur->w, scoreSur->h};\n\tSDL_BlitSurface(scoreSur, nullptr, tempSur, &scorePos);\n\tSDL_FreeSurface(scoreSur);\n\n\tSDL_Texture *scoreTexture = SDL_CreateTextureFromSurface(scoreRenderer, tempSur);\n\tSDL_FreeSurface(tempSur);\n\treturn scoreTexture;\n}"
},
{
"alpha_fraction": 0.734883725643158,
"alphanum_fraction": 0.7488372325897217,
"avg_line_length": 42.20000076293945,
"blob_id": "a36f7ac8ca5c46f5ab10931067ac6e95afa3789f",
"content_id": "62b63b93d12adf28e69225c1a187ecee41635a20",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 215,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 5,
"path": "/score-hunter/README.md",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "Score Hunter\n===============\nAn old, unfinished space shooter I started to tinker with SDL2, C++11 and TinyXML some years ago.\nCrude codebase.\nUnless stated otherwise explictly, see UNLICENSE.md for license details."
},
{
"alpha_fraction": 0.5950413346290588,
"alphanum_fraction": 0.5991735458374023,
"avg_line_length": 23.299999237060547,
"blob_id": "7e923e9b07bc4c5b3f67f671c04994399ad30c04",
"content_id": "06ead92ab1eddb421a927e98831525899bbece08",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 242,
"license_type": "permissive",
"max_line_length": 37,
"num_lines": 10,
"path": "/dllist.py",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "from urllib.request import urlopen\n\nfile = open('list.txt', 'r')\nftext = file.read()\nurls = ftext.split()\nfor url in urls:\n file_name = url.split('/')[-1]\n u = urlopen(url)\n with open(file_name, 'b+w') as f:\n f.write(u.read())"
},
{
"alpha_fraction": 0.7402032017707825,
"alphanum_fraction": 0.7416545748710632,
"avg_line_length": 20.5,
"blob_id": "314e9ec63fedc2eba19bdd9e44893b0b27353634",
"content_id": "6cc21135fa668faf9e6394f867c5750bda13d4c9",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 689,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 32,
"path": "/score-hunter/src/ScoreManager.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <string>\n#include <vector>\n\n#include \"SDL.h\"\n#include \"SDL_ttf.h\"\n\n\ntypedef struct str_ScoreEntry\n{\n\tint score;\n\tstd::string name;\n} scoreEntry;\n\n// this class manages the first 8 entries\nclass ScoreManager\n{\npublic:\n\tScoreManager();\n\t~ScoreManager(void);\n\tbool load();\n\tbool save();\n\tvoid addEntry(std::string name, int score);\n\tbool isNewScore(int score);\n\tvoid updatePrompt(SDL_Event *event);\n\tstd::string promptText;\n\tSDL_Texture *getOverview(TTF_Font *scoreFont, SDL_Renderer *scoreRenderer, SDL_Color fontColor);\n\tSDL_Texture *getPromptView(TTF_Font *scoreFont, SDL_Renderer *scoreRenderer, SDL_Color fontColor);\nprivate:\n\tstd::vector<scoreEntry> entries;\n};\n\n"
},
{
"alpha_fraction": 0.5082913041114807,
"alphanum_fraction": 0.5223503708839417,
"avg_line_length": 23.76785659790039,
"blob_id": "8cd39ce2ff0688650f9d1d213621bb077434d100",
"content_id": "183d6bd09594b75af5b122ebe716f8e81c20cf6f",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2774,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 112,
"path": "/configs_and_snippets/antaresIII/src/menus.c",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <stdlib.h>\n#include <curses.h>\n\n#include \"menus.h\"\n\n/* Apparently, curses doesn't have a constant for that key. */\n/* TODO: Check, if it was missing for technical reasons. */\n#define KEY_RETURN 10\n\n/*************************************************************\n * Shows a simple list of options and optional descriptions. *\n * Returns the text of the picked option. *\n * WARNING: If descriptions are used, each option needs one. *\n *************************************************************/\nchar* simple_list_menu(char* title, unsigned char count, char* options[],\n char* descriptions[]) {\n\n keypad(stdscr, TRUE);\n\n int key = 0;\n unsigned char selected = 0;\n do {\n clear();\n\n init_pair(1, COLOR_YELLOW, COLOR_BLACK);\n init_pair(2, COLOR_WHITE, COLOR_BLACK);\n\n attrset(A_NORMAL | COLOR_PAIR(1));\n \n if(title) {\n mvaddstr(0, 8, title);\n }\n\n /* Paint the list. */\n for (size_t option = 0; option < count; option++) {\n attrset(A_NORMAL | COLOR_PAIR(1));\n \n /* Draws an indicator for the selected list item. */\n if(selected == option) {\n attrset(A_BOLD | COLOR_PAIR(1));\n mvaddstr(option + 2, 1, \">\");\n attrset(A_NORMAL | COLOR_PAIR(1));\n }\n mvaddstr(option + 2, 2, options[option]);\n\n /* Draw the description if available. */\n attrset(A_NORMAL | COLOR_PAIR(2));\n if(descriptions && descriptions[option]) {\n mvaddstr(count + 3, 0, descriptions[selected]);\n }\n\n }\n\n refresh();\n\n /* Handling keyboard input. */\n key = getch();\n\n if (key == KEY_ENTER || key == KEY_RETURN) {\n return options[selected];\n }\n else if(key == KEY_UP) {\n if(selected == 0) {\n selected = count - 1;\n }\n else {\n selected -= 1;\n }\n }\n else if(key == KEY_DOWN) {\n if(selected == count - 1) {\n selected = 0;\n }\n else {\n selected += 1;\n }\n }\n } while(1);\n}\n\n/*******************************************************\n * Shows a fatal error message and then calls exit(1). *\n *******************************************************/\nvoid fatal_error(char* description, char* filename) {\n clear();\n \n /* Set the BSOD colors. */\n init_pair(1, COLOR_WHITE, COLOR_BLUE);\n bkgd(COLOR_PAIR(1));\n\n /* Display title. */\n attrset(A_BOLD);\n mvaddstr(1, 0, \"FATAL ERROR --- PRESS ANY KEY TO TERMINATE PROCESS\");\n\n /* Display text. */\n attrset(A_NORMAL);\n mvaddstr(3, 0, description);\n\n /* If not NULL, display affected file. */\n if(filename) {\n attrset(A_BOLD);\n mvaddstr(7, 0, \"AFFECTED FILE:\");\n\n attrset(A_NORMAL);\n mvaddstr(8, 0, filename);\n }\n\n /* Flip buffer, expect keyboard input and terminate. */\n refresh();\n getch();\n exit(1);\n}\n"
},
{
"alpha_fraction": 0.73221755027771,
"alphanum_fraction": 0.73221755027771,
"avg_line_length": 17.384614944458008,
"blob_id": "628232bf7de612db1f9bb06b281d71f6e716ae2b",
"content_id": "540a86d8387238b517168c986fe9d91f2e030697",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 241,
"license_type": "permissive",
"max_line_length": 42,
"num_lines": 13,
"path": "/Phrasengenerator/PhrasenLib/AbstractSymbol.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace PhrasenLib\n{\n public abstract class AbstractSymbol\n {\n abstract public String evaluate();\n }\n}\n"
},
{
"alpha_fraction": 0.515998125076294,
"alphanum_fraction": 0.520992636680603,
"avg_line_length": 31.85641098022461,
"blob_id": "90cce00b355bcf96358ba84f9c7ef059a9e8d7ce",
"content_id": "af445ecfcdec1258753b7a6a5256325c4cdc9036",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6407,
"license_type": "permissive",
"max_line_length": 134,
"num_lines": 195,
"path": "/configs_and_snippets/antaresIII/src/stringloader.c",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n#include \"stringloader.h\"\n#include \"filereader.h\"\n#include \"menus.h\"\n\nenum ParserState {\n PARSER_NEUTRAL,\n PARSER_COMMENT,\n PARSER_KEY,\n PARSER_AFTER_KEY,\n PARSER_TEXT\n};\n/*********************************************************\n * Parses a text into a StringLoader, a key-value store. *\n * Non-ASCII-Characters may cause errors! *\n * Assumes correct text files and mostly ignores faults! *\n *********************************************************/\nvoid init_loader(StringLoader *loader, char* filename) {\n if(!loader) {\n fatal_error(\"Loader is NULL in stringloader.c\", NULL);\n }\n\n loader->length = 0;\n loader->entries = NULL;\n loader->keys = NULL;\n \n /* A simple, state-based bottom-up ad-hoc parser. */\n char *string = read_from_file(filename);\n if (string) {\n enum ParserState state = PARSER_NEUTRAL;\n\n /* Based on remembering the positions and then copying the substring. */\n /* Advantage: Works in-place and spares me some disgusting hacks, like resetting position. */\n int keyStart = 0;\n int keyEnd = 0;\n int textStart = 0;\n int textEnd = 0;\n\n /* The size is also required in determining the end of a text. */\n size_t stringLength = strlen(string);\n \n for (size_t position = 0; position < stringLength; position++) {\n switch (state) {\n case PARSER_NEUTRAL:\n\n /* '#' at the beginning of each line starts a comment. */\n if(string[position] == '#') {\n state = PARSER_COMMENT;\n }\n /* An alphabetic character starts a key. */\n else if(isalpha(string[position])) {\n keyStart = position;\n state = PARSER_KEY;\n }\n /* Everything else gets ignored. */\n break;\n \n case PARSER_COMMENT:\n /* Reset on a linebreak. */\n if(string[position] == '\\n' || string[position] == '\\r') {\n state = PARSER_NEUTRAL;\n }\n /* Ignore everything else. */\n break;\n \n case PARSER_KEY:\n /* From position 2 to n, keywords may contain a-z, A-Z, 0-9 and \"_\". */\n if( isalnum( string[position] ) ) {\n keyEnd = position;\n }\n /* The key ends with spaces or tabs. */\n else if( isspace( string[position] ) ) {\n state = PARSER_AFTER_KEY;\n }\n /* ':' ends a key and skips to the text. */\n else if(string[position] == ':') {\n state = PARSER_TEXT;\n textStart = position + 1;\n }\n /* You got it: Ignore everything else. */\n break;\n\n case PARSER_AFTER_KEY:\n /* Ignore everything but ':'. */\n if(string[position] == ':') {\n state = PARSER_TEXT;\n textStart = position + 1;\n }\n break;\n\n case PARSER_TEXT:\n /* Everything goes, except line breaks, which end the text. */\n if(string[position] == '\\n' || string[position] == '\\r') {\n state = PARSER_NEUTRAL;\n textEnd = position;\n \n loader->length++;\n\n /* Allocate memory for a new pointer. */\n loader->entries = realloc(loader->entries, loader->length * sizeof(char*));\n loader->keys = realloc(loader->keys, loader->length * sizeof(char*));\n\n /* Allocate the new strings. */\n /* +1 because \\0, +1 because start and end are both included. */\n char* newText = calloc(textEnd - textStart + 2, sizeof(char));\n char* newKey = calloc(keyEnd - keyStart + 2, sizeof(char));\n\n /* Check if an allocation failed... */\n if( newText == NULL ||\n newKey == NULL ||\n loader->entries == NULL ||\n loader->keys == NULL ) {\n fatal_error(\"Couldn't allocate new key/text pair.\", NULL);\n }\n\n /* Copy the strings using disgusting pointer calculus. */\n strncpy(newText, string + sizeof(char) * textStart, textEnd - textStart + 1);\n strncpy(newKey, string + sizeof(char) * keyStart, keyEnd - keyStart + 1);\n\n /* Sigh, add \\0. */\n newText[textEnd - textStart + 1] = '\\0';\n newKey [keyEnd - keyStart + 1] = '\\0';\n\n /* Replace $ with \\n. */\n for( int textPos = 0; textPos < strlen(newText); textPos++ ) {\n if(newText[textPos] == '$') newText[textPos] = '\\n';\n }\n \n /* Finally assign the strings. Why again do people think C was well designed. */\n loader->entries[loader->length - 1] = newText;\n loader->keys [loader->length - 1] = newKey;\n \n }\n\n /* Check if the string ends here. */\n else if(position + 1 == stringLength) {\n textEnd = position;\n \n loader->length++;\n }\n break;\n \n default:\n fatal_error(\"Text parser in stringloader.c got into an faulty state.\", NULL);\n }\n \n }\n \n \n free(string);\n }\n else {\n fatal_error(\"An error occured while loading a .text file in stringloader.c.\\nMake sure permissions are set correctly.\", filename);\n }\n}\n\n/***************************\n * Gets a value for a key. *\n * Fatal error otherwise. *\n * *************************/\nchar* get_entry(StringLoader* loader, char* key) {\n for (size_t entry = 0; entry < loader->length; entry++) {\n if(strcmp(key, loader->keys[entry]) == 0) {\n return loader->entries[entry];\n }\n }\n\n /* Assemble the fatal error! */\n char* error = \"Key not found: \";\n /* There may be an offset of two, because \\0 is probably not copied. */\n char* message = calloc(1 + sizeof(error) + sizeof(key), sizeof(char));\n strcat(message, error);\n strcat(message, key);\n\n /* This causes a memory leak, but since fatal_error terminates, who cares. */\n fatal_error(message, NULL);\n return NULL;\n}\n\n/******************************\n * Frees all keys and values. *\n * Those better aren't NULL!! *\n ******************************/\nvoid free_loader(StringLoader* loader) {\n for (size_t entry = 0; entry < loader->length; entry++) {\n free(loader->keys[entry]);\n free(loader->entries[entry]);\n }\n\n free(loader->keys);\n free(loader->entries);\n}\n"
},
{
"alpha_fraction": 0.7459016442298889,
"alphanum_fraction": 0.7459016442298889,
"avg_line_length": 16.428571701049805,
"blob_id": "d67c4ecd42b59fcc8fa52d4574c26bd75db4520b",
"content_id": "19cd2947cbbd581d3453ec1f8caf5b813805e4d5",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 244,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 14,
"path": "/configs_and_snippets/antaresIII/include/characters.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#ifndef CHARACTERS_H\n#define CHARACTERS_H\n\nconst char *SPECIES_SPACEOGRE = \"Space-Ogre\";\nconst char *SPECIES_NEXURION = \"Nexurion\";\n\nstruct CharacterStruct {\n char* name;\n char* species;\n};\n\ntypedef struct CharacterStruct Character;\n\n#endif\n"
},
{
"alpha_fraction": 0.7547892928123474,
"alphanum_fraction": 0.7547892928123474,
"avg_line_length": 64.5,
"blob_id": "57bc4e88def5d75c10bfc9b4219b473532f5d1d6",
"content_id": "da73670ce9eebde1ad4723889a5c88837de61e33",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 261,
"license_type": "permissive",
"max_line_length": 140,
"num_lines": 4,
"path": "/README.md",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "various-scripts and other stuff\n===============\nSome stuff I created out of boredom. Neither good code nor interesting. Except - maybe - if you are interested in command line game books...\nUnless stated otherwise explictly, see UNLICENSE.md for license details."
},
{
"alpha_fraction": 0.6162790656089783,
"alphanum_fraction": 0.6179401874542236,
"avg_line_length": 23.079999923706055,
"blob_id": "a176bba45ed4775c40a7618259d82c35f9713353",
"content_id": "af92d7a301148d6af4ed9975007a2315160ac09d",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 604,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 25,
"path": "/Phrasengenerator/PhrasenLib/OneOf.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace PhrasenLib\n{\n public class OneOf : AbstractSymbol\n {\n private List<AbstractSymbol> children = new List<AbstractSymbol>();\n private Random r;\n\n public override string evaluate()\n {\n int number = r.Next(0, children.Count);\n return children[number].evaluate();\n }\n\n public OneOf(AbstractSymbol[] children, Random rand) {\n r = rand;\n this.children.AddRange(children);\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6150306463241577,
"alphanum_fraction": 0.6196318864822388,
"avg_line_length": 20.733333587646484,
"blob_id": "989fd9e0b2b640923242e43e509aab3df6dde8e4",
"content_id": "d06171055bf89ad36755ea62f1fe68d114ead7bc",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 652,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 30,
"path": "/configs_and_snippets/antaresIII/src/filereader.c",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <stdio.h>\n#include <stdlib.h>\n\n#include \"filereader.h\"\n\n/* Requires POSIX names off_t, fseeko and ftello for more security. */\nchar* read_from_file(char* filename) {\n\n char *buffer = NULL;\n off_t string_size, read_size;\n FILE *handler = fopen(filename, \"r\");\n\n if (handler) {\n fseeko(handler, 0, SEEK_END);\n string_size = ftello(handler);\n\n rewind(handler);\n buffer = (char*) malloc(sizeof(char) * (string_size + 1) );\n read_size = fread(buffer, sizeof(char), string_size, handler);\n\n buffer[string_size] = '\\0';\n\n if (string_size != read_size) {\n free(buffer);\n buffer = NULL;\n }\n }\n\n return buffer;\n}\n"
},
{
"alpha_fraction": 0.757485032081604,
"alphanum_fraction": 0.757485032081604,
"avg_line_length": 19.875,
"blob_id": "9c401f6e31416da80778a2efd012002f712bf3fd",
"content_id": "32b47e39099c0ef769778f9a3f460a71f7116803",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 334,
"license_type": "permissive",
"max_line_length": 56,
"num_lines": 16,
"path": "/configs_and_snippets/antaresIII/include/stringloader.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#ifndef STRINGLOADER_H\n#define STRINGLOADER_H\n\nstruct StringLoaderStruct {\n size_t length;\n char** keys;\n char** entries;\n};\n\ntypedef struct StringLoaderStruct StringLoader;\n\nvoid init_loader(StringLoader* loader, char* filename);\nchar* get_entry(StringLoader* loader, char* key);\nvoid free_loader(StringLoader* loader);\n\n#endif\n"
},
{
"alpha_fraction": 0.744966447353363,
"alphanum_fraction": 0.7617449760437012,
"avg_line_length": 21.923076629638672,
"blob_id": "34d1a8508d36e7291cfca3fca6b3605d38040eee",
"content_id": "a2b3001008c23478d423fca0487a07169131e303",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 298,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 13,
"path": "/configs_and_snippets/antaresIII/CMakeLists.txt",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "cmake_minimum_required (VERSION 2.8)\n\nproject (AntaresIII)\n\n# set std to gnu for posix support\nset (CMAKE_C_FLAGS \"-Wall -Wpedantic -O2 -std=gnu11\")\n\nfind_package(Curses REQUIRED)\n\ninclude_directories(${CURSES_INCLUDE_DIR})\ninclude_directories(${PROJECT_BINARY_DIR}/include)\n\nadd_subdirectory(src)\n"
},
{
"alpha_fraction": 0.6415176391601562,
"alphanum_fraction": 0.6521587371826172,
"avg_line_length": 28.937335968017578,
"blob_id": "2af8000eb03a8eb467927c9fc378ec8e899d496d",
"content_id": "d970a6a43a492c215abf2cd5ff748a5106df313e",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11465,
"license_type": "permissive",
"max_line_length": 237,
"num_lines": 383,
"path": "/score-hunter/src/Enemies.cpp",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include \"Enemies.h\"\n#include <string>\n#include \"tinyxml2.h\"\n#include <iostream>\n\nenum class movementClass{none, forward, forwardFast, backward, up, down, follow, boss}; // \"none\" means actually the same speed as the background\nenum class weaponClass{none, simple, simpleBackward, heavy, boss};\n\n// crashing with the outer rectangle would be annoying, so let's subtract some pixels\nconst int TOLERANCE = 6;\n\nconst int DAMAGE = 25;\n\nEnemyManager::EnemyManager()\n{\n}\n\nEnemyManager::~EnemyManager()\n{\n}\n\nbool EnemyManager::createTemplates(ImgManager *iManager)\n{\n\ttinyxml2::XMLDocument enemyDoc;\n\tenemyDoc.LoadFile(\"res/txt/enemies.xml\");\n\tif (enemyDoc.Error() == true)\n\t{\n\t\tstd::cout << \"Couldn't load enemies.xml\" << std::endl;\n\t\tenemyDoc.PrintError();\n\t\treturn false;\n\t}\n\n\ttinyxml2::XMLNode *root = enemyDoc.RootElement();\n\ttinyxml2::XMLElement *enemyElem = root->FirstChildElement(\"enemy\");\n\n\tdo\n\t{\n\t\tenemyTemplate newTemplate;\n\n\t\tnewTemplate.typeId = enemyElem->Attribute(\"type-id\");\n\t\tnewTemplate.score = enemyElem->IntAttribute(\"score\");\n\t\tnewTemplate.life = enemyElem->IntAttribute(\"life\");\n\n\t\tstd::string movementName = enemyElem->Attribute(\"default-movement\");\n\t\tif (movementName == \"none\") newTemplate.movement = movementClass::none;\n\t\tif (movementName == \"forward\") newTemplate.movement = movementClass::forward;\n\t\tif (movementName == \"forward-fast\") newTemplate.movement = movementClass::forwardFast;\n\t\tif (movementName == \"follow\") newTemplate.movement = movementClass::follow;\n\t\tif (movementName == \"backward\") newTemplate.movement = movementClass::backward;\n\t\tif (movementName == \"boss\") newTemplate.movement = movementClass::boss;\n\t\tif (movementName == \"down\") newTemplate.movement = movementClass::down;\n\t\tif (movementName == \"up\") newTemplate.movement = movementClass::up;\n\t\t\n\t\tstd::string attackName = enemyElem->Attribute(\"weapon\");\n\t\tif (attackName == \"none\") newTemplate.weapon = weaponClass::none;\n\t\tif (attackName == \"boss\") newTemplate.weapon = weaponClass::boss;\n\t\tif (attackName == \"heavy\") newTemplate.weapon = weaponClass::heavy;\n\t\tif (attackName == \"simple\") newTemplate.weapon = weaponClass::simple;\n\t\tif (attackName == \"simple-backward\") newTemplate.weapon = weaponClass::simpleBackward;\n\n\t\tnewTemplate.image = iManager->getEnemyImage(newTemplate.typeId);\n\n\t\ttemplates.insert(templates.begin(), newTemplate);\n\n\t\tenemyElem = enemyElem->NextSiblingElement(\"enemy\");\n\n\t} while (enemyElem != nullptr);\n\n\treturn true;\n}\n\nbool EnemyManager::createEnemies(void)\n{\n\tactiveEnemies.clear();\n\tenemies.clear();\n\tenemyBullets.clear();\n\n\ttinyxml2::XMLDocument enemyDoc;\n\tenemyDoc.LoadFile(\"res/txt/positions.xml\");\n\tif (enemyDoc.Error() == true)\n\t{\n\t\tstd::cout << \"Couldn't load positions.xml\" << std::endl;\n\t\tenemyDoc.PrintError();\n\t\treturn false;\n\t}\n\n\ttinyxml2::XMLNode *root = enemyDoc.RootElement();\n\n\tendAt = root->ToElement()->IntAttribute(\"end-at\");\n\n\ttinyxml2::XMLElement *enemyElem = root->FirstChildElement(\"position\");\n\n\tdo\n\t{\n\t\tenemy newEnemy;\n\n\t\tnewEnemy.shootCounter = 0;\n\t\tnewEnemy.x = enemyElem->IntAttribute(\"x\");\n\t\tnewEnemy.y = enemyElem->IntAttribute(\"y\");\n\t\tnewEnemy.spawnAt = enemyElem->IntAttribute(\"spawn-at\");\n\n\t\tstd::string id = enemyElem->Attribute(\"type-id\");\n\t\tfor (unsigned int i = 0; i < templates.size(); i++)\n\t\t{\n\t\t\tif (templates[i].typeId == id)\n\t\t\t{\n\t\t\t\tnewEnemy.life = templates[i].life;\n\t\t\t\tnewEnemy.eTemplate = &templates[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tenemies.insert(enemies.begin(), newEnemy);\n\n\t\tenemyElem = enemyElem->NextSiblingElement(\"position\");\n\n\t} while (enemyElem != nullptr);\n\n\treturn true;\n}\n\nvoid EnemyManager::draw(SDL_Renderer *renderer)\n{\n\tfor (unsigned int it = 0; it < activeEnemies.size(); it++)\n\t{\n\t\tSDL_Rect ePos = {activeEnemies[it]->x, activeEnemies[it]->y, activeEnemies[it]->eTemplate->image->width, activeEnemies[it]->eTemplate->image->height};\n\t\tSDL_RenderCopy(renderer, activeEnemies[it]->eTemplate->image->texture, nullptr, &ePos);\n\t}\n}\n\nvoid EnemyManager::update(Player *player)\n{\n\t// move all active enemies forward\n\tfor (unsigned int it = 0; it < activeEnemies.size(); it++)\n\t{\n\t\tif (activeEnemies[it]->eTemplate->movement == movementClass::forward)\n\t\t{\n\t\t\tactiveEnemies[it]->x -= 2;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::forwardFast)\n\t\t{\n\t\t\tactiveEnemies[it]->x -= 4;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::none)\n\t\t{\n\t\t\tactiveEnemies[it]->x -= 1;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::boss)\n\t\t{\n\n\t\t\tif (activeEnemies[it]->x + activeEnemies[it]->eTemplate->image->width < player->pos.x)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->x += 1;\n\t\t\t}\n\t\t\telse if (activeEnemies[it]->x > 600)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->x -= 2;\n\t\t\t}\n\t\t\t\n\t\t\tif (player->pos.y < activeEnemies[it]->y)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->y -= 8;\n\t\t\t}\n\n\t\t\tif (player->pos.y + player->pos.h > activeEnemies[it]->y + activeEnemies[it]->eTemplate->image->height)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->y += 8;\n\t\t\t}\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::backward)\n\t\t{\n\t\t\tactiveEnemies[it]->x += 2;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::up)\n\t\t{\n\t\t\tactiveEnemies[it]->y -= 2;\n\t\t\tactiveEnemies[it]->x--;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::down)\n\t\t{\n\t\t\tactiveEnemies[it]->y += 2;\n\t\t\tactiveEnemies[it]->x--;\n\t\t}\n\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::follow)\n\t\t{\n\n\t\t\t// x\n\t\t\tif (player->pos.x + 4 <= activeEnemies[it]->x)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->x -= 2;\n\t\t\t}\n\t\t\telse if (player->pos.x >= activeEnemies[it]->x)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->x += 2;\n\t\t\t}\n\t\t\t\n\t\t\t// y\n\t\t\tif (player->pos.y + 4 <= activeEnemies[it]->y)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->y -= 2;\n\t\t\t}\n\t\t\telse if (player->pos.y >= activeEnemies[it]->y)\n\t\t\t{\n\t\t\t\tactiveEnemies[it]->y += 2;\n\t\t\t}\n\t\t}\n\t}\n\n\t// check, if enemies must be spawned\n\tfor (unsigned int it = 0; it < enemies.size(); it++)\n\t{\n\t\tif (enemies[it].spawnAt == player->mapPos)\n\t\t{\n\t\t\tenemy* ePointer = &enemies[it];\n\t\t\tactiveEnemies.insert(activeEnemies.end(), ePointer);\n\t\t}\n\t}\n\n\t// check, if enemies must be removed from the active-list\n\tfor (unsigned int it = 0; it < activeEnemies.size(); it++)\n\t{\n\t\tif (activeEnemies[it]->life <= 0)\n\t\t{\n\t\t\tactiveEnemies.erase(activeEnemies.begin() + it);\n\t\t\tplayer->score += activeEnemies[it]->eTemplate->score;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (activeEnemies[it]->eTemplate->movement == movementClass::forward ||\n\t\t\t\tactiveEnemies[it]->eTemplate->movement == movementClass::forwardFast ||\n\t\t\t\tactiveEnemies[it]->eTemplate->movement == movementClass::none\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tif (activeEnemies[it]->x + activeEnemies[it]->eTemplate->image->width < 0)\n\t\t\t\t{\n\t\t\t\t\tactiveEnemies.erase(activeEnemies.begin() + it);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::backward)\n\t\t\t{\n\t\t\t\tif (activeEnemies[it]->x > 800)\n\t\t\t\t{\n\t\t\t\t\tactiveEnemies.erase(activeEnemies.begin() + it);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::up)\n\t\t\t{\n\t\t\t\tif (activeEnemies[it]->y + activeEnemies[it]->eTemplate->image->height < 0)\n\t\t\t\t{\n\t\t\t\t\tactiveEnemies.erase(activeEnemies.begin() + it);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (activeEnemies[it]->eTemplate->movement == movementClass::down)\n\t\t\t{\n\t\t\t\tif (activeEnemies[it]->y > 600)\n\t\t\t\t{\n\t\t\t\t\tactiveEnemies.erase(activeEnemies.begin() + it);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// Checking the players bullets.\n\t// Case 1: Bullet goes out of the area.\n\tfor (unsigned int it = 0; it < player->bullets.size(); it++)\n\t{\n\t\t\n\t\tif (player->bullets[it].pos.x > 800)\n\t\t{\n\t\t\tplayer->bullets.erase(player->bullets.begin() + it);\n\t\t}\n\t}\n\n\t// Case 2: Bullet collides with an enemy ship.\n\tfor (unsigned int it2 = 0; it2 < activeEnemies.size(); it2++)\n\t{\n\t\tfor (unsigned int it = 0; it < player->bullets.size(); it++)\n\t\t{\n\t\t\n\t\t\tif ((\n\t\t\t\t(player->bullets[it].pos.x + player->bullets[it].pos.w - TOLERANCE > activeEnemies[it2]->x && player->bullets[it].pos.x + player->bullets[it].pos.w - TOLERANCE < activeEnemies[it2]->x + activeEnemies[it2]->eTemplate->image->width) ||\n\t\t\t\t(player->bullets[it].pos.x + TOLERANCE > activeEnemies[it2]->x && player->bullets[it].pos.x + TOLERANCE < activeEnemies[it2]->x + activeEnemies[it2]->eTemplate->image->width)\n\t\t\t) && (player->bullets[it].pos.y + TOLERANCE < activeEnemies[it2]->y + activeEnemies[it2]->eTemplate->image->height && player->bullets[it].pos.y + player->bullets[it].pos.h - TOLERANCE > activeEnemies[it2]->y)\n\t\t\t)\n\t\t\t{\n\t\t\t\tplayer->bullets.erase(player->bullets.begin() + it);\n\t\t\t\tactiveEnemies[it2]->life -= DAMAGE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Enemies shooting\n\tfor (enemy *en : activeEnemies)\n\t{\n\t\tif (en->shootCounter > 0)\n\t\t{\n\t\t\ten->shootCounter--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (en->eTemplate->weapon == weaponClass::boss)\n\t\t\t{\n\t\t\t\ten->shootCounter = 30;\n\t\t\t\tbullet newBul1 = {en->x - 16, en->y + 24, 16, 16, true, false};\n\t\t\t\tbullet newBul2 = {en->x - 16, en->y + en->eTemplate->image->height - 40, 16, 16, true, false};\n\t\t\t\tenemyBullets.insert(enemyBullets.end(), newBul1);\n\t\t\t\tenemyBullets.insert(enemyBullets.end(), newBul2);\n\n\t\t\t}\n\t\t\telse if (en->eTemplate->weapon == weaponClass::heavy)\n\t\t\t{\n\t\t\t\ten->shootCounter = 120;\n\t\t\t\tbullet newBul = {en->x - 16, en->y + (en->eTemplate->image->height / 2 + 8) , 16, 16, true, false};\n\t\t\t\tenemyBullets.insert(enemyBullets.end(), newBul);\n\t\t\t}\n\t\t\telse if (en->eTemplate->weapon == weaponClass::simple)\n\t\t\t{\n\t\t\t\ten->shootCounter = 240;\n\t\t\t\tbullet newBul = {en->x - 8, en->y + (en->eTemplate->image->height / 2 + 4) , 8, 8, false, false};\n\t\t\t\tenemyBullets.insert(enemyBullets.end(), newBul);\n\t\t\t}\n\t\t\telse if (en->eTemplate->weapon == weaponClass::simpleBackward)\n\t\t\t{\n\t\t\t\ten->shootCounter = 240;\n\t\t\t\tbullet newBul = {en->x + en->eTemplate->image->width, en->y + (en->eTemplate->image->height / 2 + 4) , 8, 8, false, true};\n\t\t\t\tenemyBullets.insert(enemyBullets.end(), newBul);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t// Moving the enemy bullets\n\tfor (bullet &eBullet : enemyBullets)\n\t{\n\t\tif (eBullet.backward)\n\t\t{\n\t\t\teBullet.pos.x += 8;\n\t\t}\n\t\telse\n\t\t{\n\t\t\teBullet.pos.x -= 8;\n\t\t}\n\t}\n\n\t\n\n}\n\nbool EnemyManager::doesGameEnd(Player *player)\n{\n\tif (player->mapPos == endAt) return true;\n\t\n\tfor (unsigned int it = 0; it < activeEnemies.size(); it++)\n\t{\n\t\tif ((\n\t\t\t\t(player->pos.x + player->pos.w - TOLERANCE > activeEnemies[it]->x && player->pos.x + player->pos.w - TOLERANCE < activeEnemies[it]->x + activeEnemies[it]->eTemplate->image->width) ||\n\t\t\t\t(player->pos.x + TOLERANCE > activeEnemies[it]->x && player->pos.x + TOLERANCE < activeEnemies[it]->x + activeEnemies[it]->eTemplate->image->width)\n\t\t\t) && (player->pos.y + TOLERANCE < activeEnemies[it]->y + activeEnemies[it]->eTemplate->image->height && player->pos.y + player->pos.h - TOLERANCE > activeEnemies[it]->y)\n\t\t\t)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\t// Deleting the colliding bullets\n\t\tfor (int i = 0; i < enemyBullets.size(); i++)\n\t\t{\n\t\t\tif (enemyBullets[i].pos.x > 800) { enemyBullets.erase(enemyBullets.begin() + i); break; }\n\t\t\tif (enemyBullets[i].pos.x + enemyBullets[i].pos.w < 0) { enemyBullets.erase(enemyBullets.begin() + i); break; }\n\t\t\tif ((\n\t\t\t\t\t(player->pos.x + player->pos.w > enemyBullets[i].pos.x && player->pos.x < enemyBullets[i].pos.x + enemyBullets[i].pos.w) ||\n\t\t\t\t\t(player->pos.x > enemyBullets[i].pos.x && player->pos.x < enemyBullets[i].pos.x + enemyBullets[i].pos.w)\n\t\t\t\t) && (player->pos.y < enemyBullets[i].pos.y + enemyBullets[i].pos.h && player->pos.y + player->pos.h > enemyBullets[i].pos.y)\n\t\t\t\t)\n\t\t\t{\n\t\t\t\tenemyBullets.erase(enemyBullets.begin() + i);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn false;\n}"
},
{
"alpha_fraction": 0.6178277730941772,
"alphanum_fraction": 0.630114734172821,
"avg_line_length": 23.03342628479004,
"blob_id": "944627ea1c25f30f9998071a62382c141195c380",
"content_id": "09e0ad873a04aecfc83cba1f8454ff4cf9a195c0",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8627,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 359,
"path": "/score-hunter/src/Main.cpp",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include \"SDL.h\"\n#include \"SDL_ttf.h\"\n#include \"SDL_image.h\"\n\n#include \"ImgManager.h\"\n#include \"Enemies.h\"\n#include \"ScoreManager.h\"\n#include \"Player.h\"\n\n////////////////////////////////////////////////////////////////\n// NOTE: This code was created with the purpose to learn SDL2,\n// tinyXML and some of the new C++11 features.\n// This means: It's flawed on several levels. And there is no\n// warrant that I fix it in the meantime.\n// Don't try to learn from it, also don't try to reuse it.\n////////////////////////////////////////////////////////////////\n\nenum class gameStates {ending, menu, game, score, nameprompt};\n\nSDL_Window *window = nullptr;\nSDL_Renderer *renderer = nullptr;\nImgManager *imgManager = nullptr;\nEnemyManager *eManager = nullptr;\nTTF_Font *font = nullptr;\ngameStates gameState = gameStates::menu;\nSDL_Texture *menuTexture = nullptr;\nSDL_Texture *scoreTexture = nullptr;\n\nSDL_Color fontColor = {255, 255, 255, 255};\n\nvoid generateMenuTexture()\n{\n\tSDL_Surface *tempSur = nullptr;\n\ttempSur = TTF_RenderText_Blended(font, \"Play [F1] Score [F2] Quit [q]\", fontColor);\n\tmenuTexture = SDL_CreateTextureFromSurface(renderer, tempSur);\n\tSDL_FreeSurface(tempSur);\n}\n\nbool initializeGame()\n{\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == -1)\n\t{\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\twindow = SDL_CreateWindow(\"Score Hunter\", 100, 100, 800, 600, SDL_WINDOW_SHOWN);\n\tif (window == nullptr)\n\t{\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\tif (IMG_Init(IMG_INIT_PNG) == -1)\n\t{\n\t\tstd::cout << IMG_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\tif (TTF_Init() == -1)\n\t{\n\t\tstd::cout << TTF_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n\tif (renderer == nullptr)\n\t{\n\t\tstd::cout << SDL_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\timgManager = new ImgManager();\n\tif (imgManager->loadImages(renderer) == false)\n\t{\n\t\treturn false;\n\t}\n\n\teManager = new EnemyManager();\n\tif (eManager->createTemplates(imgManager) == false)\n\t{\n\t\treturn false;\n\t}\n\n\tfont = TTF_OpenFont(\"res/fonts/Audiowide-Regular.ttf\", 24);\n\tif (font == nullptr)\n\t{\n\t\tstd::cout << TTF_GetError() << std::endl;\n\t\treturn false;\n\t}\n\n\tgenerateMenuTexture();\n\n\treturn true;\n}\n\n\nvoid gameLoop()\n{\n\n\tSDL_Event event;\n\n\tPlayer player;\n\tSDL_Rect backgroundRect = {0, 0, 800, 600};\n\n\tbool keyUp, keyDown, keyLeft, keyRight, keySpace;\n\n\tScoreManager scoreManager;\n\n\twhile (gameState != gameStates::ending)\n\t{\n\t\t// get events and update\n\n\t\tDirections upDown = Directions::None;\n\t\tDirections leftRight = Directions::None;\n\n\t\twhile (SDL_PollEvent(&event))\n\t\t{\n\t\t\t// make sure you can end the game in every state\n\t\t\tif (event.type == SDL_QUIT || (event.key.keysym.sym == SDLK_q && gameState != gameStates::nameprompt))\n\t\t\t{\n\t\t\t\tgameState = gameStates::ending;\n\t\t\t}\n\n\t\t\t// update stuff\n\t\t\tif (gameState == gameStates::menu)\n\t\t\t{\n\t\t\t\tif (event.key.keysym.sym == SDLK_F1)\n\t\t\t\t{\n\t\t\t\t\tgameState = gameStates::game;\n\t\t\t\t\tif (eManager->createEnemies() == false)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Error: Unable to load enemy positions.\\n\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tplayer.resetPlayer();\n\t\t\t\t\tkeyDown = false; keyLeft = false; keyRight = false; keyUp = false; keySpace = false;\n\t\t\t\t}\n\t\t\t\telse if (event.key.keysym.sym == SDLK_F2)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tscoreManager.load();\n\t\t\t\t\tscoreTexture = scoreManager.getOverview(font, renderer, fontColor);\n\t\t\t\t\tgameState = gameStates::score;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gameState == gameStates::game)\n\t\t\t{\n\t\t\t\tif (event.type == SDL_KEYDOWN)\n\t\t\t\t{\n\t\t\t\t\tSDL_Keycode key = event.key.keysym.sym;\n\t\t\t\t\tif (key == SDLK_DOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyDown = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_UP)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyUp = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_LEFT)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyLeft = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_RIGHT)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyRight = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_SPACE)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeySpace = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (event.type == SDL_KEYUP)\n\t\t\t\t{\n\t\t\t\t\tSDL_Keycode key = event.key.keysym.sym;\n\t\t\t\t\tif (key == SDLK_DOWN)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyDown = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_UP)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyUp = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_LEFT)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyLeft = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_RIGHT)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeyRight = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == SDLK_SPACE)\n\t\t\t\t\t{\n\t\t\t\t\t\tkeySpace = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gameState == gameStates::score)\n\t\t\t{\n\t\t\t\tif (event.key.keysym.sym == SDLK_RETURN)\n\t\t\t\t{\n\t\t\t\t\tgameState = gameStates::menu;\n\t\t\t\t\tif (scoreTexture != nullptr) SDL_DestroyTexture(scoreTexture);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (gameState == gameStates::nameprompt)\n\t\t\t{\n\t\t\t\tif (event.key.keysym.sym == SDLK_RETURN && event.type == SDL_KEYUP)\n\t\t\t\t{\n\t\t\t\t\tSDL_StopTextInput();\n\t\t\t\t\tgameState = gameStates::score;\n\t\t\t\t\tscoreManager.addEntry(scoreManager.promptText, player.score);\n\t\t\t\t\tplayer.score = 0;\n\t\t\t\t\tif (scoreTexture != nullptr) SDL_DestroyTexture(scoreTexture);\n\t\t\t\t\tscoreTexture = scoreManager.getOverview(font, renderer, fontColor);\n\t\t\t\t\tscoreManager.save();\n\t\t\t\t}\n\t\t\t\telse if (event.key.keysym.sym == SDLK_BACKSPACE && event.type == SDL_KEYDOWN)\n\t\t\t\t{\n\t\t\t\t\tif (scoreManager.promptText.size() > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tscoreManager.promptText.pop_back();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// let the scoremanager handle the input\n\t\t\t\t\tscoreManager.updatePrompt(&event);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// update stuff\n\t\tif (gameState == gameStates::game)\n\t\t{\n\t\t\tif (backgroundRect.x < -799)\n\t\t\t{\n\t\t\t\tbackgroundRect.x = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbackgroundRect.x--;\n\t\t\t}\n\n\t\t\tplayer.mapPos++;\n\n\t\t\tif (keyUp) upDown = Directions::Up;\n\t\t\telse if (keyDown) upDown = Directions::Down;\n\t\t\tif (keyLeft) leftRight = Directions::Left;\n\t\t\telse if (keyRight) leftRight = Directions::Right;\n\t\t\tplayer.update(keySpace, upDown, leftRight);\n\t\t\teManager->update(&player);\n\n\t\t\tif (eManager->doesGameEnd(&player) == true) player.alive = false;\n\t\t\tif (player.alive == false)\n\t\t\t{\n\t\t\t\tscoreManager.load();\n\t\t\t\tif (scoreManager.isNewScore(player.score) == false)\n\t\t\t\t{\n\t\t\t\t\tscoreTexture = scoreManager.getOverview(font, renderer, fontColor);\n\t\t\t\t\tgameState = gameStates::score;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSDL_StartTextInput();\n\t\t\t\t\tgameState = gameStates::nameprompt;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (gameState == gameStates::nameprompt)\n\t\t{\n\t\t\t// update the the prompt texture\n\t\t\tif (scoreTexture != nullptr) SDL_DestroyTexture(scoreTexture);\n\t\t\tscoreTexture = scoreManager.getPromptView(font, renderer, fontColor);\n\t\t}\n\n\t\t// draw stuff\n\t\tSDL_RenderClear(renderer);\n\t\tif (gameState == gameStates::menu)\n\t\t{\n\t\t\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\t\t\tSDL_RenderFillRect(renderer, nullptr);\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\t\t\tSDL_Rect menuRect = {260, 300, 285, 28};\n\t\t\tSDL_RenderCopy(renderer, menuTexture, nullptr, &menuRect);\n\t\t}\n\t\telse if (gameState == gameStates::score || gameState == gameStates::nameprompt)\n\t\t{\n\t\t\t// use the same texture object for the score view and the name input\n\t\t\tSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n\t\t\tSDL_RenderFillRect(renderer, nullptr);\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\t\t\tSDL_RenderCopy(renderer, scoreTexture, nullptr, nullptr);\n\t\t}\n\t\telse if (gameState == gameStates::game)\n\t\t{\n\t\t\t// the background\n\t\t\tSDL_RenderCopy(renderer, imgManager->backgroundTexture, nullptr, &backgroundRect);\n\t\t\tSDL_Rect secondBGRect = {backgroundRect.x + 800, backgroundRect.y, backgroundRect.w, backgroundRect.h};\n\t\t\tSDL_RenderCopy(renderer, imgManager->backgroundTexture, nullptr, &secondBGRect);\n\n\t\t\t// the enemies + their bullets\n\t\t\teManager->draw(renderer);\n\t\t\t\n\t\t\t// the player\n\t\t\tSDL_RenderCopy(renderer, imgManager->playerTexture, nullptr, &player.pos);\n\n\t\t\t// the bullets of the player\n\t\t\tfor (signed int i = 0; i < player.bullets.size(); i++)\n\t\t\t{\n\t\t\t\tSDL_RenderCopy(renderer, imgManager->bulletTexture, nullptr, &player.bullets[i].pos);\n\t\t\t}\n\n\t\t\t// the bullets of the enemies\n\t\t\tfor (bullet &bull : eManager->enemyBullets)\n\t\t\t{\n\t\t\t\tif (bull.big)\n\t\t\t\t{\n\t\t\t\t\tSDL_RenderCopy(renderer, imgManager->bulletBigTexture, nullptr, &bull.pos);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSDL_RenderCopy(renderer, imgManager->bulletTexture, nullptr, &bull.pos);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tSDL_RenderPresent(renderer);\n\n\t\t// small delay\n\t\tSDL_Delay(10);\n\t}\n}\n\nvoid unload()\n{\n\tdelete imgManager;\n\tdelete eManager;\n\tSDL_DestroyTexture(menuTexture);\n\tSDL_DestroyTexture(scoreTexture);\n\tTTF_CloseFont(font);\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(window);\n\tTTF_Quit();\n\tIMG_Quit();\n\tSDL_Quit();\n}\n\nint main(int argc, char** argv)\n{\n\tif (initializeGame() == false) return 1;\n\n\tgameLoop();\n\n\tunload();\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.6196799278259277,
"alphanum_fraction": 0.6356826424598694,
"avg_line_length": 24.986724853515625,
"blob_id": "f30e727efe68dae800cc29ae7ff1409af555822c",
"content_id": "828080ff667fd2cf992fa4f635bb5b73d6ffb660",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5874,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 226,
"path": "/tiled_view/tiledview.c",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "/*\nTiledView - a minimalistic image viewer for tile textures, based on SDL2 and SDL2_image.\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <http://unlicense.org/>\n*/\n\n#include <stdio.h>\n#include \"SDL.h\"\n#include \"SDL_image.h\"\n\nconst int MARGIN = 64;\nconst int KEY_DELAY = 4;\n\nint gridWidth = 5;\nint gridHeight = 5;\n\n/* the procedure containing the main loop */\nvoid guiLoop(SDL_Renderer *renderer, SDL_Texture *texture) {\n\n\t/* declare needed variables for events and texture positions */\n\tSDL_Event event;\n\tSDL_Rect texturePos;\n\tint keyUpDown = 0;\n\tint keyDownDown = 0;\n\tint keyRightDown = 0;\n\tint keyLeftDown = 0;\n\t\n\tint keyCounter = 0;\n\t\n\tSDL_QueryTexture(texture, NULL, NULL, &(texturePos.w), &(texturePos.h));\n\n\t/* the loop */\n\twhile (1) {\n\t\tint col, row;\n\t\twhile (SDL_PollEvent(&event)) {\n\t\t\t\n\t\t\t/* check, if the process has to be ended */\n\t\t\tif (event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t/* check keyboard input */\n\t\t\telse if(event.type == SDL_KEYDOWN) {\n\t\t\t\tif(event.key.keysym.sym == SDLK_RIGHT) {\n\t\t\t\t\tkeyRightDown = 1;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_DOWN) {\n\t\t\t\t\tkeyDownDown = 1;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_LEFT) {\n\t\t\t\t\tkeyLeftDown = 1;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_UP) {\n\t\t\t\t\tkeyUpDown = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(event.type == SDL_KEYUP) {\n\t\t\t\tif(event.key.keysym.sym == SDLK_RIGHT) {\n\t\t\t\t\tkeyRightDown = 0;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_DOWN) {\n\t\t\t\t\tkeyDownDown = 0;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_LEFT) {\n\t\t\t\t\tkeyLeftDown = 0;\n\t\t\t\t}\n\t\t\t\telse if(event.key.keysym.sym == SDLK_UP) {\n\t\t\t\t\tkeyUpDown = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tkeyCounter = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* process keyboard input */\n\t\tif(keyUpDown == 1) {\n\t\t\tif(keyCounter == 0) {\n\t\t\t\tif(gridHeight > 1) gridHeight--;\n\t\t\t}\n\t\t\tif(keyCounter > KEY_DELAY) {\n\t\t\t\tkeyCounter = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tkeyCounter++;\n\t\t\t}\n\t\t}\n\t\telse if(keyDownDown == 1) {\n\t\t\tif(keyCounter == 0) {\n\t\t\t\tgridHeight++;\n\t\t\t}\n\t\t\tif(keyCounter > KEY_DELAY) {\n\t\t\t\tkeyCounter = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tkeyCounter++;\n\t\t\t}\n\t\t}\n\t\telse if(keyLeftDown == 1) {\n\t\t\tif(keyCounter == 0) {\n\t\t\t\tif(gridWidth > 1) gridWidth--;\n\t\t\t}\n\t\t\tif(keyCounter > KEY_DELAY) {\n\t\t\t\tkeyCounter = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tkeyCounter++;\n\t\t\t}\n\t\t}\n\t\telse if(keyRightDown == 1) {\n\t\t\tif(keyCounter == 0) {\n\t\t\t\tgridWidth++;\n\t\t\t}\n\t\t\tif(keyCounter > KEY_DELAY) {\n\t\t\t\tkeyCounter = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tkeyCounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* draw the background colour */\n\t\tSDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);\n\t\tSDL_RenderFillRect(renderer, NULL);\n\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\t\t\n\t\t/* draw a grid with the texture */\n\t\tfor( col = 0 ; col < gridHeight * texturePos.h ; col += texturePos.h ) {\n\t\t\tfor( row = 0 ; row < gridWidth * texturePos.w ; row += texturePos.w ) {\n\t\t\t\ttexturePos.y = col + MARGIN;\n\t\t\t\ttexturePos.x = row + MARGIN;\n\t\t\t\tSDL_RenderCopy(renderer, texture, NULL, &texturePos);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* flip and wait */\n\t\tSDL_RenderPresent(renderer);\n\t\tSDL_Delay(10);\n\t}\n}\n\n\nint main ( int argc, char *argv[] ) {\n\t\n\t/* declare SDL variables */\n\tSDL_Window *window = NULL;\n\tSDL_Renderer *renderer = NULL;\n\tSDL_Texture *texture = NULL;\n\n\t/* get filename */\n\tif (argc != 2) {\n\t\tprintf (\"Incorrect usage, please use \\\"%s PATH_TO_IMAGE\\\" instead.\\n\", argv[0]);\n\t\treturn 1;\n\t}\n\t\n\t/* initialize SDL */\n\tif (SDL_Init(SDL_INIT_VIDEO) == -1) {\n\t\tputs(\"Error: couldn't initialize SDL2\\n\");\n\t\treturn 1;\n\t}\n\n\t/* open window */\n\twindow = SDL_CreateWindow(argv[1], 100, 100, 640, 640, SDL_WINDOW_SHOWN);\n\tif (window == NULL) {\n\t\tputs(\"Error: couldn't create main window\\n\");\n\t\treturn 1;\n\t}\n\n\t/* initialize SDL_Image2 with all image formats available */\n\tif (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF) == -1) {\n\t\tputs(\"Error: couldn't initialize SDL2_Image\\n\");\n\t\treturn 1;\n\t}\n\t\n\t/* create renderer */\n\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n\tif (renderer == NULL)\n\t{\n\t\tprintf(\"Unable to create renderer: %s\\n\", SDL_GetError());\n\t\treturn 1;\n\t}\n\t\n\t/* load the image */\n\ttexture = IMG_LoadTexture(renderer, argv[1]);\n\tif (texture == NULL) {\n\t\tprintf(\"Error: unable to load image %s\\n%s\\n\", argv[1], IMG_GetError());\n\t\treturn 1;\n\t}\n\n\t/* call the main loop */\n\tguiLoop(renderer, texture);\n\t\n\t/* shut down SDL and delete objects */\n\n\t/*------------------------------------------------------------*\n\t* Of course, that only works, if everything worked correctly! *\n\t* But since the image is the only relevant object, thats OK. *\n\t*------------------------------------------------------------*/\n\tSDL_DestroyTexture(texture);\n\tSDL_DestroyRenderer(renderer);\n\tSDL_DestroyWindow(window);\n\tIMG_Quit();\n\tSDL_Quit();\n\treturn 0;\n}\n\n"
},
{
"alpha_fraction": 0.7517605423927307,
"alphanum_fraction": 0.7517605423927307,
"avg_line_length": 18.55172348022461,
"blob_id": "497b90c90aa200e3297df4d47b49d679ecf2c020",
"content_id": "c7e076cfc7466a1c6b7c0fe5a69bde027e4a501a",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 568,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 29,
"path": "/score-hunter/src/ImgManager.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <string>\n#include \"SDL.h\"\n#include <vector>\n\ntypedef struct str_img\n{\n\tSDL_Texture *texture;\n\tstd::string enemyID;\n\tint width, height;\n} enemyImg;\n\n// loads the single images and puts the enemy ships into a vector of enemyImg\nclass ImgManager\n{\npublic:\n\tImgManager(void);\n\t~ImgManager(void);\n\tbool loadImages(SDL_Renderer *renderer);\n\n\tSDL_Texture *playerTexture;\n\tSDL_Texture *bulletTexture;\n\tSDL_Texture *bulletBigTexture;\n\tSDL_Texture *backgroundTexture;\n\tenemyImg *getEnemyImage(std::string typeId);\n\n\tstd::vector<enemyImg> enemyImages;\n};\n\n"
},
{
"alpha_fraction": 0.4883720874786377,
"alphanum_fraction": 0.5216701626777649,
"avg_line_length": 12.145833015441895,
"blob_id": "767ab6c9668e24db0bc0d17a9f3223eb62ace0a8",
"content_id": "25cbd1adb8dec43ede3eb3886c5af7f82071b87d",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1892,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 144,
"path": "/score-hunter/src/Player.cpp",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include \"Player.h\"\n\nconst int DELAY = 5;\n\nPlayer::Player(void)\n{\n}\n\n\nPlayer::~Player(void)\n{\n}\n\n\nvoid Player::resetPlayer(void)\n{\n\tvecX = 0; vecY = 0;\n\tmapPos = 0;\n\tpos.x = 32;\n\tpos.y = 300;\n\tpos.h = 32;\n\tpos.w = 64;\n\talive = true;\n\tshootCounter = 0;\n\tscore = 0;\n}\n\nvoid Player::update(bool keySpace, Directions upDown, Directions leftRight)\n{\n\t// calculate the y vector\n\tif (upDown == Directions::Up && vecY > -12)\n\t{\n\t\tvecY -= 4;\n\t}\n\telse if (upDown == Directions::Down && vecY < 12)\n\t{\n\t\tvecY += 4;\n\t}\n\telse\n\t{\n\t\tif (vecY > 0)\n\t\t{\n\t\t\tvecY -= 2;\n\t\t}\n\t\telse if (vecY < 0)\n\t\t{\n\t\t\tvecY += 2;\n\t\t}\n\t}\n\n\t// calculate the x vector\n\tif (leftRight == Directions::Left && vecX > -12)\n\t{\n\t\tvecX -= 4;\n\t}\n\telse if (leftRight == Directions::Right && vecX < 12)\n\t{\n\t\tvecX += 4;\n\t}\n\telse\n\t{\n\t\tif (vecX > -1) // let the ship fall back a little\n\t\t{\n\t\t\tvecX -= 2;\n\t\t}\n\t\telse if (vecX < 0)\n\t\t{\n\t\t\tvecX += 2;\n\t\t}\n\t}\n\n\t// calculate the new positions: x...\n\tif (vecX > 0)\n\t{\n\t\tif (pos.x + pos.w < 800 - vecX)\n\t\t{\n\t\t\tpos.x = pos.x + vecX;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos.x = 800 - pos.w;\n\t\t}\n\t}\n\telse if (vecX < 0)\n\t{\n\t\tif (pos.x > 0 - vecX)\n\t\t{\n\t\t\tpos.x = pos.x + vecX;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos.x = 0;\n\t\t}\n\t}\n\n\t// ...and y\n\tif (vecY > 0)\n\t{\n\t\tif (pos.y + pos.h < 600 - vecY)\n\t\t{\n\t\t\tpos.y = pos.y + vecY;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos.y = 600 - pos.h;\n\t\t}\n\t}\n\telse if (vecY < 0)\n\t{\n\t\tif (pos.y > 0 - vecY)\n\t\t{\n\t\t\tpos.y = pos.y + vecY;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tpos.y = 0;\n\t\t}\n\t}\n\n\t// update the bullets\n\t// because of bad design decisions, they get removed in the enemy manager\n\tfor (auto &thisBullet : bullets)\n\t{\n\t\tthisBullet.pos.x += 12;\n\t}\n\n\tif (keySpace)\n\t{\n\t\tif (shootCounter > 0)\n\t\t{\n\t\t\tshootCounter--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tshootCounter = DELAY;\n\t\t\tbullet newBullet = {{pos.x + pos.w, pos.y + (pos.h / 2) - 4, 8, 8}, false, false};\n\t\t\tbullets.insert(bullets.end(), newBullet);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (shootCounter > 0) shootCounter--;\n\t}\n}"
},
{
"alpha_fraction": 0.5743073225021362,
"alphanum_fraction": 0.5743073225021362,
"avg_line_length": 16.2608699798584,
"blob_id": "7b8d6d5069b8d444bc8e36d7bad06011858ee7e5",
"content_id": "5ca76d9bb166f83dab2b221be97b9f26c45fa4c3",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 399,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 23,
"path": "/Phrasengenerator/PhrasenLib/Text.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace PhrasenLib\n{\n public class Text : AbstractSymbol\n {\n String value = \"\";\n\n override public String evaluate()\n {\n return value;\n }\n\n public Text(String value)\n {\n this.value = value;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.3719503581523895,
"alphanum_fraction": 0.3725080192089081,
"avg_line_length": 34.5098991394043,
"blob_id": "d53249bdfdbb4af5ceac9c9e6e171aebd4173230",
"content_id": "fc5aee85c26d40ba65bdfcc5b32c730a385dabdb",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 7175,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 202,
"path": "/Phrasengenerator/PML/Reader.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml;\n\nusing PhrasenLib;\n\nnamespace PML\n{\n public class Reader\n {\n\n private class StringSymbolPair\n {\n public String name = \"\";\n public AbstractSymbol symbol = null;\n }\n\n /// <summary>\n /// parses an XML document for named symbols, double defined names will cause DoubleDefException\n /// </summary>\n /// <param name=\"file\">the filename</param>\n /// <returns>a associative array with named symbols</returns>\n public Dictionary<String, AbstractSymbol> ReadFile(String file, Random rand)\n {\n var symbolDict = new Dictionary<String, AbstractSymbol>();\n XmlDocument doc = new XmlDocument();\n doc.PreserveWhitespace = true;\n try\n {\n doc.Load(file);\n }\n catch (Exception)\n { \n throw;\n }\n\n XmlElement pml = (XmlElement)doc.GetElementsByTagName(\"pml\")[0];\n if (pml.Name != \"pml\")\n {\n throw new Exception(\"Invalid root element: \" + pml.Name);\n }\n\n foreach (XmlNode child in pml.ChildNodes)\n {\n if(child.NodeType != XmlNodeType.Element) continue;\n var pair = evaluateNode((XmlElement)child, rand);\n symbolDict.Add(pair.name, pair.symbol);\n }\n\n return symbolDict;\n \n }\n\n private StringSymbolPair evaluateNode(XmlElement child, Random rand)\n {\n if (child.Name !=\"symbol\")\n\t {\n\t\t throw new Exception(\"Root contains invalid elements: \" + child.Name);\n\t }\n\n var result = new StringSymbolPair();\n\n // check for type\n String type = \"\";\n if (! child.HasAttribute(\"type\"))\n {\n throw new Exception(\"Symbol without type\");\n }\n else\n {\n type = child.GetAttribute(\"type\");\n \n // check for name\n String name = \"\";\n if (child.HasAttribute(\"name\"))\n {\n name = child.GetAttribute(\"name\");\n }\n \n result.name = name;\n\n switch (type)\n {\n case \"chain\":\n if (!child.HasChildNodes)\n {\n throw new Exception(\"Empty chain symbol\");\n }\n else\n {\n int count = 1;\n\n if (child.HasAttribute(\"repeat\"))\n {\n int pcount = 0;\n if ( int.TryParse(child.GetAttribute(\"repeat\"), out pcount) )\n {\n count = pcount;\n }\n }\n\n List<StringSymbolPair> kList = new List<StringSymbolPair>();\n foreach (XmlNode childElem in child.ChildNodes)\n {\n if (childElem.NodeType != XmlNodeType.Element) continue;\n kList.Add(evaluateNode((XmlElement)childElem, rand));\n }\n List<AbstractSymbol> list = new List<AbstractSymbol>();\n foreach (var pair in kList)\n {\n list.Add(pair.symbol);\n }\n result.symbol = new Chain(list.ToArray(), count);\n }\n\n break;\n \n case \"text\":\n if (String.IsNullOrEmpty(child.InnerText))\n {\n throw new Exception(\"Empty text symbol\");\n }\n else\n {\n result.symbol = new Text(child.InnerText);\n }\n break;\n\n case \"newline\":\n result.symbol = new Text(\"\\n\");\n break;\n\n case \"one-of-text\":\n String splitter = \" \";\n if (child.HasAttribute(\"split-by\"))\n {\n splitter = child.GetAttribute(\"split-by\");\n }\n\n if (String.IsNullOrEmpty(child.InnerText))\n {\n throw new Exception(\"Empty one-of-text symbol\");\n }\n else\n {\n String content = child.InnerText;\n var texts = content.Split(new String[]{splitter}, StringSplitOptions.RemoveEmptyEntries);\n if (texts.Length > 0)\n {\n List<AbstractSymbol> list = new List<AbstractSymbol>();\n foreach (var text in texts)\n {\n list.Add(new Text(text));\n }\n result.symbol = new OneOf( list.ToArray(), rand);\n \n }\n else\n {\n throw new Exception(\"Empty one-of-text\");\n }\n }\n\n break;\n\n case \"one-of\":\n if (! child.HasChildNodes)\n {\n throw new Exception(\"Empty one symbol\");\n }\n else\n {\n\n List<StringSymbolPair> kList = new List<StringSymbolPair>();\n foreach (XmlNode childElem in child.ChildNodes)\n {\n if(childElem.NodeType != XmlNodeType.Element)continue;\n kList.Add(evaluateNode((XmlElement)childElem, rand));\n }\n List<AbstractSymbol> list = new List<AbstractSymbol>();\n foreach (var pair in kList)\n {\n list.Add(pair.symbol);\n }\n result.symbol = new OneOf(list.ToArray(), rand);\n }\n\n break;\n \n default:\n throw new Exception(\"Symbol with unknown type: \" + type);\n }\n\n return result;\n\n }\n }\n\n }\n}\n"
},
{
"alpha_fraction": 0.591487467288971,
"alphanum_fraction": 0.5954365730285645,
"avg_line_length": 32.02898406982422,
"blob_id": "7d616dfc5e9a1f00f91192861be1fca3eac2acde",
"content_id": "f2171b6a4af62af907f303c2acd15e01b7bf83ef",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2279,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 69,
"path": "/configs_and_snippets/antaresIII/src/main.c",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include <string.h>\n#include <stdlib.h>\n#include <curses.h>\n\n#include \"characters.h\"\n#include \"stringloader.h\"\n#include \"menus.h\"\n\nStringLoader mainMenuLoader;\nCharacter character;\n\n/* Release memory at the end of the game. */\nvoid quit(void) {\n\n free_loader(&mainMenuLoader);\n \n endwin();\n}\n\nint main(int argc, char const *argv[]) {\n\n /* Start curses mode. */\n initscr();\n atexit(quit);\n curs_set(0);\n start_color();\n \n init_loader(&mainMenuLoader, \"./data/text/menus.text\");\n\n /* Create the main menu. */\n char* menuOptions[] = { get_entry(&mainMenuLoader, \"new_game\"),\n get_entry(&mainMenuLoader, \"load_game\"),\n get_entry(&mainMenuLoader, \"credits\"),\n get_entry(&mainMenuLoader, \"exit\") };\n \n char* menuDescs [] = { get_entry(&mainMenuLoader, \"new_game_desc\"),\n get_entry(&mainMenuLoader, \"load_game_desc\"),\n get_entry(&mainMenuLoader, \"credits_desc\"),\n get_entry(&mainMenuLoader, \"exit_desc\") };\n \n do {\n char* selectedOption = simple_list_menu( get_entry(&mainMenuLoader, \"main_title\"), 4, menuOptions, menuDescs );\n \n if( strcmp(selectedOption, get_entry(&mainMenuLoader, \"exit\") ) == 0 ) break;\n\n /* Show the credits menu. */\n if( strcmp(selectedOption, get_entry(&mainMenuLoader, \"credits\") ) == 0 ) {\n char* creditsOption[] = { get_entry(&mainMenuLoader, \"credits_option\") };\n char* creditsText[] = { get_entry(&mainMenuLoader, \"credits_option_desc\") };\n simple_list_menu( get_entry(&mainMenuLoader, \"credits_title\"), 1, creditsOption, creditsText );\n }\n\n /* Create a new character. */\n else if( strcmp(selectedOption, get_entry(&mainMenuLoader, \"new_game\")) == 0 ) {\n\n /* Show species selection menu. */\n char* speciesOption[] = { SPECIES_SPACEOGRE, SPECIES_NEXURION };\n char* speciesDesc[] = { get_entry(&mainMenuLoader, \"spaceogre_desc\"),\n get_entry(&mainMenuLoader, \"nexurion_desc\" ) };\n character.species = simple_list_menu( get_entry(&mainMenuLoader, \"species_title\"), 2, speciesOption, speciesDesc);\n\n /* Show name input prompt. */\n \n }\n\n } while(1);\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.6138280034065247,
"alphanum_fraction": 0.6138280034065247,
"avg_line_length": 21.80769157409668,
"blob_id": "18247f4c6bfcccb23b5674e4b3abe3d00b0a4521",
"content_id": "cbccd75f100c1bf1893c7a358cbbf05039666c7e",
"detected_licenses": [
"Unlicense"
],
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 595,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 26,
"path": "/Phrasengenerator/Phrasengenerator/Program.cs",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nusing PhrasenLib;\nusing PML;\n\n\nnamespace Phrasengenerator\n{\n class Program\n {\n static void Main(string[] args)\n {\n Reader reader = new Reader();\n Random rand = new Random();\n Dictionary<String, AbstractSymbol> symbolDict = reader.ReadFile(\"../../test.pml\", rand);\n AbstractSymbol generator = symbolDict[\"satz\"];\n\n Console.Write(generator.evaluate());\n Console.ReadKey();\n }\n }\n}\n"
},
{
"alpha_fraction": 0.7019883990287781,
"alphanum_fraction": 0.7163352370262146,
"avg_line_length": 25.49333381652832,
"blob_id": "0d6f22394c4576d3cb7904293c3935a44652e6d4",
"content_id": "fe4147084f28f700b8f5ce494b58cb7a4a0e69ea",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3973,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 150,
"path": "/score-hunter/src/ImgManager.cpp",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#include \"ImgManager.h\"\n#include \"SDL_image.h\"\n#include <iostream>\n#include \"tinyxml2.h\"\n\n// 3 helper functions, which do not belong directly to the class\nSDL_Texture *loadTexImage(std::string fileName, SDL_Renderer *renderer)\n{\n\tSDL_Texture *tex = nullptr;\n\ttex = IMG_LoadTexture(renderer, fileName.c_str());\n\tif (tex == nullptr)\n\t{\n\t\tstd::cout << \"Failed to load image: \" + fileName + \"\\n\" + IMG_GetError();\n\t}\n\treturn tex;\n}\n\nSDL_Surface *loadSurImage(std::string fileName)\n{\n\tSDL_Surface *sur = nullptr;;\n\tsur = IMG_Load(fileName.c_str());\n\tif (sur == nullptr)\n\t{\n\t\tstd::cout << \"Failed to load image: \" + fileName + \"\\n\" + IMG_GetError();\n\t}\n\treturn sur;\n}\n\nSDL_Texture *textureFromAtlas(SDL_Surface *atlas, SDL_Renderer *renderer, SDL_Rect *pos)\n{\n\tSDL_Surface *tempSur = SDL_CreateRGBSurface(0, pos->w, pos->h, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);\n\tSDL_BlitSurface(atlas, pos, tempSur, nullptr);\n\tSDL_Texture *texture = nullptr;\n\ttexture = SDL_CreateTextureFromSurface(renderer, tempSur);\n\tSDL_FreeSurface(tempSur);\n\treturn texture;\n}\n\n\nImgManager::ImgManager(void)\n{\n\tplayerTexture = nullptr;\n\tbulletBigTexture = nullptr;\n\tbulletTexture = nullptr;\n\tbackgroundTexture = nullptr;\n}\n\n\nImgManager::~ImgManager(void)\n{\n\tSDL_DestroyTexture(backgroundTexture);\n\tSDL_DestroyTexture(bulletBigTexture);\n\tSDL_DestroyTexture(bulletTexture);\n\tSDL_DestroyTexture(playerTexture);\n\n\tfor (int i = 0; i < enemyImages.size(); i++)\n\t{\n\t\tSDL_DestroyTexture(enemyImages[i].texture);\n\t}\n}\n\n\nbool ImgManager::loadImages(SDL_Renderer *renderer)\n{\n\tSDL_Surface *bulletAtlas = nullptr;\n\tSDL_Surface *shipAtlas = nullptr;\n\n\t// load the images\n\tbackgroundTexture = loadTexImage(\"res/img/background.png\", renderer);\n\tshipAtlas = loadSurImage(\"res/img/ships.png\");\n\tbulletAtlas = loadSurImage(\"res/img/bullets.png\");\n\tif (backgroundTexture == nullptr || shipAtlas == nullptr || bulletAtlas == nullptr) return false;\n\n\t// load bullets and the player ship from the surfaces\n\tSDL_Rect bulletPos;\n\tbulletPos.h = 8;\n\tbulletPos.w = 8;\n\tbulletPos.y = 8;\n\tbulletPos.x = 0;\n\tbulletTexture = textureFromAtlas(bulletAtlas, renderer, &bulletPos);\n\n\tSDL_Rect bulletBigPos;\n\tbulletBigPos.h = 16;\n\tbulletBigPos.w = 16;\n\tbulletBigPos.y = 0;\n\tbulletBigPos.x = 8;\n\tbulletBigTexture = textureFromAtlas(bulletAtlas, renderer, &bulletBigPos);\n\n\tSDL_Rect playerPos;\n\tplayerPos.h = 32;\n\tplayerPos.w = 64;\n\tplayerPos.y = 160;\n\tplayerPos.x = 0;\n\tplayerTexture = textureFromAtlas(shipAtlas, renderer, &playerPos);\n\t\n\t// load the enemy ships, using enemies.xml\n\ttinyxml2::XMLDocument enemyDoc;\n\tenemyDoc.LoadFile(\"res/txt/enemies.xml\");\n\tif (enemyDoc.Error() == true)\n\t{\n\t\tstd::cout << \"Couldn't load enemies.xml\" << std::endl;\n\t\tenemyDoc.PrintError();\n\t\treturn false;\n\t}\n\n\ttinyxml2::XMLNode *root = enemyDoc.RootElement();\n\ttinyxml2::XMLElement *enemyElem = root->FirstChildElement(\"enemy\");\n\n\tdo\n\t{\n\t\tenemyImg newEnemyImg;\n\t\tnewEnemyImg.texture = nullptr;\n\t\tnewEnemyImg.enemyID = enemyElem->Attribute(\"type-id\");\n\t\ttinyxml2::XMLElement *imgElement = enemyElem->FirstChildElement(\"image\");\n\t\t\n\t\tSDL_Rect atlasPos;\n\t\tatlasPos.x = imgElement->IntAttribute(\"x\");\n\t\tatlasPos.y = imgElement->IntAttribute(\"y\");\n\t\tatlasPos.w = imgElement->IntAttribute(\"w\");\n\t\tatlasPos.h = imgElement->IntAttribute(\"h\");\n\t\t\n\t\tnewEnemyImg.texture = textureFromAtlas(shipAtlas, renderer, &atlasPos);\n\n\t\tnewEnemyImg.width = atlasPos.w;\n\t\tnewEnemyImg.height = atlasPos.h;\n\n\t\t// copy the struct into the vector;\n\t\t// the adress gets copied as well, so no usage of DestroyTexture() yet\n\t\tenemyImages.insert(enemyImages.end(), newEnemyImg);\n\t\tenemyElem = enemyElem->NextSiblingElement(\"enemy\");\n\t} while (enemyElem != nullptr);\n\n\t// free the atlas surfaces\n\tSDL_FreeSurface(shipAtlas);\n\tSDL_FreeSurface(bulletAtlas);\n\n\treturn true;\n}\n\nenemyImg *ImgManager::getEnemyImage(std::string typeId)\n{\n\tfor (int i = 0; i < enemyImages.size(); i++)\n\t{\n\t\tif (enemyImages[i].enemyID == typeId)\n\t\t{\n\t\t\treturn &enemyImages[i];\n\t\t}\n\t}\n\treturn false;\n}"
},
{
"alpha_fraction": 0.743682324886322,
"alphanum_fraction": 0.743682324886322,
"avg_line_length": 15.27450942993164,
"blob_id": "d803a6dd0c7d775dcb9ebc10ebdd0f24d5db3088",
"content_id": "8b1f78497744160c8c57758ac9a559538e2a05b3",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 831,
"license_type": "permissive",
"max_line_length": 44,
"num_lines": 51,
"path": "/score-hunter/src/Enemies.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <vector>\n\n#include \"Player.h\"\n\n#include \"SDL.h\"\n\n#include \"ImgManager.h\"\n\nenum class movementClass;\nenum class weaponClass;\n\ntypedef struct str_enemyTemplate\n{\n\tstd::string typeId;\n\tint score;\n\tint life;\n\tmovementClass movement;\n\tweaponClass weapon;\n\tenemyImg *image;\n\n} enemyTemplate;\n\ntypedef struct str_enemy\n{\n\tint spawnAt;\n\tint x, y;\n\tint life;\n\tenemyTemplate *eTemplate;\n\tint shootCounter;\n} enemy;\n\n\nclass EnemyManager\n{\npublic:\n\tEnemyManager();\n\t~EnemyManager();\n\tbool createTemplates(ImgManager *iManager);\n\tbool createEnemies(void);\n\tvoid update(Player *player);\n\tvoid draw(SDL_Renderer *renderer);\n\tbool doesGameEnd(Player *player);\n\tstd::vector<bullet> enemyBullets;\nprivate:\n\tint endAt;\n\tstd::vector<enemyTemplate> templates;\n\tstd::vector<enemy> enemies;\n\tstd::vector<enemy*> activeEnemies;\n};\n\n"
},
{
"alpha_fraction": 0.7090908885002136,
"alphanum_fraction": 0.7090908885002136,
"avg_line_length": 11.333333015441895,
"blob_id": "b1070174e130d1abb70c92d5064239f674ee0503",
"content_id": "043a4a66fa5651851628b5c40f6bb83669ab762a",
"detected_licenses": [
"Unlicense",
"Zlib"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 110,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 9,
"path": "/score-hunter/src/Bullets.h",
"repo_name": "sauer2/various-scripts",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include \"SDL.h\"\n\ntypedef struct strBullet {\n\tSDL_Rect pos;\n\tbool big;\n\tbool backward;\n} bullet;"
}
] | 33 |
jgredecka/Games | https://github.com/jgredecka/Games | a85f41c2256068f69084315e499c5d606ff2c48a | 9589bf70c0b4dbb28c434003925bd03ac751dd29 | 4105d55b668c60bdef9dad7ffd51b9e7399e93d5 | refs/heads/master | 2020-08-23T12:00:48.460049 | 2019-10-21T16:20:28 | 2019-10-21T16:20:28 | 216,611,679 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.755919873714447,
"alphanum_fraction": 0.7613843083381653,
"avg_line_length": 67.625,
"blob_id": "a75258667a367853412bdf02ca6e67695a99eb88",
"content_id": "aeb781d7c35920c400a8100cc4bb9f9e0ba29de8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 549,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 8,
"path": "/README.md",
"repo_name": "jgredecka/Games",
"src_encoding": "UTF-8",
"text": "# Word and Number Games\n\n## About\nThis repository contains short Python scripts written for simple games such as the following: \n* **Palindrome**: checks if a string is a palindrome, i.e. it reads the same backwards as forwards.\n* **Pangram**: checks if a given string contains all letters of the alphabet.\n* **Secret Number**: game requiring the user to guess a secret number between 1 and 10 while providing clues.\n* **Lingo**: game which asks the user to guess the name of a country consisting of five characters. Each attemept generates a clue.\n"
},
{
"alpha_fraction": 0.5942028760910034,
"alphanum_fraction": 0.6019323468208313,
"avg_line_length": 37.33333206176758,
"blob_id": "801567412086110a8663e403856fad53680e21c6",
"content_id": "9c3ef14698cc877a5dbc8f1520c72aa07fe53f32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1035,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 27,
"path": "/secret_number.py",
"repo_name": "jgredecka/Games",
"src_encoding": "UTF-8",
"text": "import random\nnumber = random.randint(1,10)\n\nprint('''Welcome to Guess The Number. Please enter an integer between 1 and 10 (inclusive) to begin. Each attempt \n generates a clue if the entered number is too low or too high. Exit the game at any time by pressing Enter.''')\n\nattempts = 0\nwhile True:\n guess = input('Please enter a number: ')\n attempts+=1\n stop = guess\n try:\n if stop == '':\n print('You quit the game. Thank you for playing!')\n break\n elif int(guess) == number:\n print('Correct! The secret number was', number)\n print('The number of attempts was', attempts)\n break\n elif int(guess) != number and int(guess) < number:\n print('Incorrect.')\n print('Your guess is too low.')\n elif int(guess) != number and int(guess) > number:\n print('Incorrect.')\n print('Your guess is too high.')\n except ValueError:\n print('Invalid input. Please ensure your guess is an integer.')\n"
},
{
"alpha_fraction": 0.6269727349281311,
"alphanum_fraction": 0.6269727349281311,
"avg_line_length": 32.19047546386719,
"blob_id": "847dcb171f5f5d2422cf1526866676c16cab15ad",
"content_id": "4e4401b269b9f34396618125087883e24e671ddc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 697,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 21,
"path": "/palindrome.py",
"repo_name": "jgredecka/Games",
"src_encoding": "UTF-8",
"text": "'''A word game in which the user enters a word or sentence and the program checks whether \nit is a palindrome or not. An example palindrome is \"Amore, Roma.\" '''\n\ndef isPalindrome(phrase): \n chars=[\".\", \",\", \"'\", \"?\", \"!\", \" \", \":\", \";\"]\n phrase=phrase.lower()\n for x in chars:\n phrase=phrase.replace(x, '')\n phrase_list=list(phrase)\n phrase_list.reverse()\n rev=''.join(phrase_list)\n if phrase==rev:\n output=\"This is a palindrome.\"\n return output\n else:\n output=\"This is not a palindrome.\"\n return output\n\nphrase=input(\"Please enter a word or phrase to check if it is a palindrome or not:>> \")\noutcome=isPalindrome(phrase)\nprint(outcome)\n"
},
{
"alpha_fraction": 0.577829122543335,
"alphanum_fraction": 0.5801385641098022,
"avg_line_length": 37,
"blob_id": "f6f8e7ffa1284b74928eabecff0d3529e6021de4",
"content_id": "96bc302699474de9b30987813bdb840d0c1e2dfe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2165,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 57,
"path": "/lingo.py",
"repo_name": "jgredecka/Games",
"src_encoding": "UTF-8",
"text": "import random\n\nsecret_list = ['benin', 'egypt', 'gabon', 'ghana', 'kenya', 'libya', 'niger', 'sudan', 'chile', \n 'china', 'haiti', 'india', 'italy', 'japan', 'malta', 'nauru', 'nepal', 'palau', \n 'qatar', 'samoa', 'spain', 'syria', 'tonga', 'yemen']\n\nsecret = random.choice(secret_list)\n\n\ndef fullMatch(guess, position):\n if guess[position] == secret[position]:\n return True\n \ndef partialMatch(guess, position):\n if guess[position] != secret[position]:\n return True\n\ndef checkInput(guess):\n hint = 'Clue: '\n for n in range(0, 5):\n if guess[n] in secret:\n if fullMatch(guess, n) == True:\n hint = hint + '[' + guess[n] + ']'\n elif partialMatch(guess, n) == True:\n hint = hint + '(' + guess[n] + ')'\n else:\n hint += guess[n]\n return hint\n\nprint('''\n Welcome to Lingo! Your task is to guess the secret name of a country consisting of exactly five characters. \n Each attempt generates a clue with respect to the matched characters. Characters found in the secret name but \n at incorrect positions are marked with round parentheses. Characters fully matched at correct positions are \n marked with square brackets. E.g., the following clue would be given for the secret country 'italy':\n \n Input: spain\n Clue: sp[a](i)n\n \n To exit the game, press Enter at any time.''')\n\nwhile True:\n guess = input('Please enter the name of a country consisting of 5 characters: ').lower()\n try:\n if guess == '':\n print('You quit the game. Thank you for playing Lingo!')\n break\n elif checkInput(guess).count('[') == 5:\n print('Correct, the secret country was ' + secret + '. Thank you for playing Lingo!')\n retry = input('Would you like to play again (y/n)?')\n if retry == 'y':\n secret = random.choice(secret_list)\n elif retry == 'n':\n break\n else:\n print(checkInput(guess))\n except IndexError:\n print('Please ensure your guess consists of exactly 5 characters.')"
},
{
"alpha_fraction": 0.517241358757019,
"alphanum_fraction": 0.517241358757019,
"avg_line_length": 32,
"blob_id": "f300a21ac01fac5008efe5735f4b649e1d8115ec",
"content_id": "f79d751f6494b0611ca702cdd2e9fedb7d63d31e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 957,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 29,
"path": "/pangram.py",
"repo_name": "jgredecka/Games",
"src_encoding": "UTF-8",
"text": "'''A word game in which the user enters a sentence and the program checks whether \nthe sentence is a pangram or not. An example pangram: \"The quick brown fox jumps over the lazy dog.\" '''\n\ndef isPangram(words):\n \n letters=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', \n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n \n chars=[\".\", \",\", \" \", \"!\", \"?\", \"'\", \":\", \";\"]\n pangram=False\n words=words.lower()\n for x in chars:\n words=words.replace(x, '')\n for x in letters:\n if x not in words:\n pangram=False\n break\n elif x in words:\n pangram=True\n if pangram==True:\n outcome='This is a pangram.'\n return outcome\n else:\n outcome=\"This is not a pangram.\"\n return outcome\n\nphrase=input(\"Please enter a sentence to check if it is a pangram or not:>> \")\noutput=isPangram(phrase)\nprint(output)\n"
}
] | 5 |
pcaravelli-sr/milestone-2-challenge | https://github.com/pcaravelli-sr/milestone-2-challenge | 5ead658e5d37974309365c8581b91cae35052ea2 | 012dfd3e3b0eb464b96db18d3f1aa34d239f5acd | c5aca46e6b5fae703525d58a3ab12b9c67c5766a | refs/heads/master | 2021-05-03T19:35:05.770957 | 2018-02-07T20:09:13 | 2018-02-07T20:09:13 | 120,419,590 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6123778223991394,
"alphanum_fraction": 0.6221498250961304,
"avg_line_length": 32.11111068725586,
"blob_id": "dc0b2ccb9310f9bbb7e2980b59e416bd0d94d5f8",
"content_id": "13de37a3c53ae7b3552014acf50e2e8e9d5391de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 307,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 9,
"path": "/milestone2/merge_sort.py",
"repo_name": "pcaravelli-sr/milestone-2-challenge",
"src_encoding": "UTF-8",
"text": "def merge_sort(items):\r\n \"\"\"\r\n Uses merge sort algorithm to sort items from input list and return new list in sorted order\r\n\r\n :param items: list of comparable items, e.g. [3, 1, 2] or ['z', 'x', 'y']\r\n :return: a sorted list containing every item from the input list\r\n \"\"\"\r\n\r\n return []\r\n"
},
{
"alpha_fraction": 0.6578947305679321,
"alphanum_fraction": 0.673751711845398,
"avg_line_length": 37,
"blob_id": "eba6148e29c1f603736c1d3c3bc7ffdf65cb1203",
"content_id": "615f0fee8643066fe20bdbd4dddc4f85564901f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2964,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 76,
"path": "/milestone2/benchmarks/benchmarks.py",
"repo_name": "pcaravelli-sr/milestone-2-challenge",
"src_encoding": "UTF-8",
"text": "from random import randint\r\nfrom time import time\r\n\r\nfrom milestone2.merge_sort import merge_sort\r\nfrom milestone2.insertion_sort import insertion_sort\r\n\r\n\r\n# Dictionary of labeled sort functions. If you decide to try writing a more optimized sort\r\n# function, you can add it in an entry in this dictionary to see how it compares to the others.\r\nsort_functions = {\r\n 'merge_sort': merge_sort,\r\n 'insertion_sort': insertion_sort\r\n}\r\n\r\n\r\ndef benchmark(sort_fns, list_length, num_passes):\r\n \"\"\"\r\n For each sorting function provided, generate a list with the specified length, then\r\n track the time to sort it. Repeat the specified number of times, then return the average\r\n run time for each sorting function.\r\n\r\n Because lists with shorter lengths can be sorted extremely quickly on modern hardware,\r\n it is helpful to take the average of many run times to avoid noisiness in the data.\r\n\r\n :param sort_fns: dictionary of sorting functions\r\n :param list_length: length of the list to generate that will be passed to sorting functions\r\n :param num_passes: number of times to run each sorting function\r\n :return: dictionary of sorting function name to average run time for given list length\r\n \"\"\"\r\n\r\n raise NotImplementedError('Must complete TODOs in `milestone2/benchmarks/benchmarks.py before running!')\r\n\r\n times = {} # TODO: add entries to dictionary with the same keys as `sort_fns`, and all values as `0`\r\n\r\n for _ in range(num_passes):\r\n items = generate_list(list_length)\r\n\r\n # TODO: loop over each entry in the `sort_fns` dictionary\r\n # items_copy = list(items) # insertion sort changes input array, so work with a copy\r\n # start = time()\r\n # TODO: call sort function with `items_copy` argument\r\n # end = time()\r\n # TODO: add the time duration (end - start) to the corresponding entry in the `times` dictionary\r\n\r\n # TODO: loop over each entry in `sort_fns` dictionary and divide the time duration by `num_passes`\r\n\r\n return times\r\n\r\n\r\ndef generate_list(length):\r\n \"\"\"\r\n Generates a list of random integers between 0 and 100,000 to help with our benchmarking.\r\n\r\n :param length: length of list to be returned\r\n :return: list of random integers between 0 and 100,000\r\n \"\"\"\r\n example = randint(0, 100000)\r\n\r\n # TODO: fill array with random numbers, up to specified `length`;\r\n # call `randint(0, 1000000)` for each number to generate\r\n return []\r\n\r\n\r\nif __name__ == '__main__':\r\n list_length = 10\r\n num_passes = 10000\r\n\r\n # Since this can run rather slowly, you may want to skip the last benchmark by doing:\r\n # while num_passes >= 10\r\n while num_passes >= 1:\r\n results = benchmark(sort_functions, list_length, num_passes)\r\n\r\n print('Time to sort list length %s:\\n%s\\n' % (list_length, results))\r\n\r\n list_length = list_length * 10\r\n num_passes = int(num_passes / 10)\r\n"
}
] | 2 |
DavZhangDev/mlskintrial | https://github.com/DavZhangDev/mlskintrial | 8833cf3a447763624c9b410dc387a1d62440da54 | c06682ecfdce3146a2a4816241d26d4216d271b5 | a82ee743146ca1de7cb7980da3da81aa97fd3fc8 | refs/heads/master | 2022-11-06T10:35:49.449251 | 2020-06-25T13:24:09 | 2020-06-25T13:24:09 | 257,862,431 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6772785782814026,
"alphanum_fraction": 0.7075738310813904,
"avg_line_length": 41.80219650268555,
"blob_id": "0752452cc4da4384d0f131772060c3c44683e367",
"content_id": "a8b5b445f0953d80716fe72086ae3a855a387d29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3895,
"license_type": "no_license",
"max_line_length": 191,
"num_lines": 91,
"path": "/predSkin.py",
"repo_name": "DavZhangDev/mlskintrial",
"src_encoding": "UTF-8",
"text": "# Import required libraries\nimport tensorflow as tf\nimport os\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.optimizers import RMSprop, Adam\nfrom tensorflow.keras.layers import Conv1D, Conv2D, MaxPooling2D, Input, Activation, Dropout, Flatten, Dense\nfrom IPython.display import Image\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nimport keras\n\nIMAGE_WIDTH, IMAGE_HEIGHT = 200, 200\nEPOCHS = 30\nBATCH_SIZE = 32\nnum_classes = 2\n\nsavedmodel = \"/savemodel/skinpredv5.hdf5\"\npredimgpath = \"BenignSkin.jpg\"\nfpath = \"img/\"\n\n'''\nconda create -n tf tensorflow\nconda activate tf\n'''\n\ndef truncate(n, decimals=0):\n multiplier = 10 ** decimals\n return str(int(n * multiplier) / multiplier)\n\ndef defineSkinModel():\n model = Sequential()\n model.add(Conv2D(128, (3, 3), padding='same', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, 3), activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_01'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_01'))\n model.add(Conv2D(96, (3, 3), padding='same', activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_02'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_02'))\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_03'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_03'))\n model.add(Flatten(name = 'Flatten'))\n model.add(Dense(16, activation = 'relu', name = 'Dense_01'))\n model.add(Dense(2, activation='softmax', name = 'Output')) # 2 because of number of classes\n return model\n\ndef importSavedSkinModel():\n model = defineSkinModel()\n opt = Adam(lr = 0.0001)\n model.compile(loss = tf.keras.losses.categorical_crossentropy, optimizer = opt, metrics = ['acc'])\n checkpointer = ModelCheckpoint(filepath=\"/savemodel/skinpred.hdf5\", verbose=1, save_best_only=True)\n return model\n\ndef loadSkinModel():\n model = importSavedSkinModel()\n return model\n\ndef makePredictionGen():\n predlist = [fpath + predimgpath]\n prediction_df = pd.DataFrame({'filename': predlist, 'class': [\"blank\"]})\n prediction_data_generator = ImageDataGenerator(rescale=1./255)\n prediction_generator = prediction_data_generator.flow_from_dataframe(prediction_df, target_size = (IMAGE_WIDTH, IMAGE_HEIGHT), batch_size = 1, shuffle = False, class_mode = \"categorical\")\n return prediction_generator\n\ndef printPreds(predResult):\n # Converts prediction results into console log\n print('\\nProbabilities:')\n if predResult[0] == 'b':\n print(\"This area of skin appears to be benign, but you should still check it out at the doctor's if you aren't sure!\")\n print(\"Your skin abnormality is\", predResult[1] + \"% benign, \" + predResult[2] + \"% malignant.\")\n else:\n print(\"That's no ordinary abnormality, you should definitely check it out at the doctor's!\")\n print(predResult[1] + \"% benign, \" + predResult[2] + \"% malignant.\")\n\ndef returnPreds(datagen, pred_model):\n images, labels = datagen.next()\n img = images[0]\n preds = importSavedSkinModel().predict(np.expand_dims(img, axis = 0))\n ps = preds[0] # The raw prediction scores of the model\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n classes = ['benign', 'malignant']\n if ps[0] > 0.5:\n return [\"b\",truncate(ps[0]*100, 1),truncate(ps[1]*100, 1)]\n else:\n return [\"m\",truncate(ps[0]*100, 1),truncate(ps[1]*100, 1)]\n\nprintPreds(returnPreds(makePredictionGen(), loadSkinModel()))\n\nprint(\"\\nPREDICTION OF\", predimgpath, \"COMPLETE\")\n"
},
{
"alpha_fraction": 0.6275250911712646,
"alphanum_fraction": 0.6567359566688538,
"avg_line_length": 38.54597854614258,
"blob_id": "e9d7cbb0f07d71a09a7720b8095a89930485d6f5",
"content_id": "98cd35ae0be025caf45bdb8b3f246a09c6a9ad5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6881,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 174,
"path": "/model.py",
"repo_name": "DavZhangDev/mlskintrial",
"src_encoding": "UTF-8",
"text": "# Import required libraries\nimport tensorflow as tf\nimport os\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.optimizers import RMSprop, Adam\nfrom tensorflow.keras.layers import Conv1D, Conv2D, MaxPooling2D, Input, Activation, Dropout, Flatten, Dense\nfrom IPython.display import Image\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nimport keras\n\ndef truncate(n, decimals=0):\n multiplier = 10 ** decimals\n return str(int(n * multiplier) / multiplier)\n\ndef pred_classify(datagen, pred_model):\n # Get first batch\n images, labels = datagen.next()\n\n img = images[0]\n\n preds = model.predict(np.expand_dims(img, axis = 0))\n\n ps = preds[0]\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n classes = ['benign', 'malignant']\n print(ps)\n\n print('Probabilities:')\n print(pd.DataFrame({'Class Label': ['benign', 'malignant'], 'Probabilties': ps}))\n\n if ps[0] > 0.6:\n print(\"This area of skin appears to be benign, but you should still check it out at the doctor's if you aren't sure!!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n else:\n print(\"That's no ordinary abnormality, you should definitely check it out at the doctor's!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n\ndef print_preds(datagen, pred_model):\n # Get first batch\n images, labels = datagen.next()\n\n img = images[0]\n preds = model.predict(np.expand_dims(img, axis = 0))\n ps = preds[0]\n\n print(img)\n # Swap the class name and its numeric representation\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n\n print('Probabilities:')\n print(pd.DataFrame({'Class Label': classes, 'Probabilties': ps}))\n if labels[0][0] == 1.0:\n print('Actual Label: Benign')\n elif labels[0][1] == 1.0:\n print('Actual Label: Malignant')\n else:\n print('Actual Label: Label Error')\n fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)\n ax1.imshow(img.squeeze())\n ax1.axis('off')\n ax2.set_yticks(np.arange(len(classes)))\n ax2.barh(np.arange(len(classes)), ps)\n ax2.set_aspect(0.1)\n ax2.set_yticklabels(classes, size='small')\n ax2.set_title('Class Probability')\n ax2.set_xlim(0, 1.1)\n\n plt.tight_layout()\n\nIMAGE_WIDTH, IMAGE_HEIGHT = 200, 200\nEPOCHS = 30\nBATCH_SIZE = 32\nnum_classes = 2\n'''\nconda create -n tf tensorflow\nconda activate tf\n'''\n\ndef create_model():\n model = Sequential()\n model.add(Conv2D(128, (3, 3), padding='same', input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, 3), activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_01'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_01'))\n model.add(Conv2D(96, (3, 3), padding='same', activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_02'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_02'))\n model.add(Conv2D(64, (3, 3), padding='same', activation='relu', bias_regularizer=tf.keras.regularizers.l2(0.01), name = 'Conv_03'))\n model.add(MaxPooling2D(pool_size=(2, 2), name = 'MaxPool_03'))\n model.add(Flatten(name = 'Flatten'))\n model.add(Dense(16, activation = 'relu', name = 'Dense_01'))\n model.add(Dense(2, activation='softmax', name = 'Output')) # 2 because of number of classes\n return model\n\n#savedmodel = \"/savemodel/skinpred.hdf5\"\nsavedmodel = \"/savemodel/skinpredv5.hdf5\"\n# v4 sucks, use v5\n\ndef lm():\n model = create_model()\n opt = Adam(lr = 0.0001)\n model.compile(loss = tf.keras.losses.categorical_crossentropy, optimizer = opt, metrics = ['acc'])\n checkpointer = ModelCheckpoint(filepath=\"/savemodel/skinpred.hdf5\", verbose=1, save_best_only=True)\n return model\n\nmodel = lm()\n\nfpath = \"\"\npredlist = [fpath + \"Melanoma.jpg\", fpath + \"Mole.jpg\", fpath + \"Skin.jpg\", fpath + \"Cancer.jpg\", fpath + \"Skin2.jpg\"]\nprediction_df = pd.DataFrame({'filename': predlist, 'class': [\"malignant\", \"benign\", \"benign\", \"malignant\", \"benign\"]})\nprediction_data_generator = ImageDataGenerator(rescale=1./255)\nprediction_generator = prediction_data_generator.flow_from_dataframe(prediction_df,\n target_size = (IMAGE_WIDTH, IMAGE_HEIGHT),\n batch_size = 1,\n shuffle = False,\n class_mode = \"categorical\")\n\ndef truncate(n, decimals=0):\n multiplier = 10 ** decimals\n return str(int(n * multiplier) / multiplier)\n\ndef pred_classify(datagen, pred_model):\n # Get first batch\n images, labels = datagen.next()\n\n img = images[0]\n print(img.ndim)\n print(img)\n\n preds = model.predict(np.expand_dims(img, axis = 0))\n\n ps = preds[0]\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n classes = ['benign', 'malignant']\n print('Probabilities:')\n print(ps)\n print(pd.DataFrame({'Class Label': ['benign', 'malignant'], 'Probabilties': ps}))\n\n if ps[0] > 0.5:\n print(\"\\nThis area of skin appears to be benign, but you should still check it out at the doctor's if you aren't sure!!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n else:\n print(\"\\nThat's no ordinary abnormality, you should definitely check it out at the doctor's!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n\ndef prednowprednow(datagen, pred_model):\n images, labels = datagen.next()\n img = images[0]\n preds = model.predict(np.expand_dims(img, axis = 0))\n ps = preds[0]\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n classes = ['benign', 'malignant']\n print('\\n\\nProbabilities:')\n print(ps)\n if ps[0] > 0.5:\n print(\"This area of skin appears to be benign, but you should still check it out at the doctor's if you aren't sure!!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n else:\n print(\"That's no ordinary abnormality, you should definitely check it out at the doctor's!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n\n#pred_classify(prediction_generator, model)\nprednowprednow(prediction_generator, model)\nprednowprednow(prediction_generator, model)\nprednowprednow(prediction_generator, model)\nprednowprednow(prediction_generator, model)\nprednowprednow(prediction_generator, model)\n\n\nprint(\"\\nCODE COMPLETE\")\n"
},
{
"alpha_fraction": 0.5985879898071289,
"alphanum_fraction": 0.6278365850448608,
"avg_line_length": 33.18965530395508,
"blob_id": "de25be3b1056bf51b869415d49a9ad404fce5097",
"content_id": "5e1ca4057ce8e9eca26ef37a99187287c5dd6843",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1983,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 58,
"path": "/fx.py",
"repo_name": "DavZhangDev/mlskintrial",
"src_encoding": "UTF-8",
"text": "def truncate(n, decimals=0):\n multiplier = 10 ** decimals\n return str(int(n * multiplier) / multiplier)\n\ndef pred_classify(datagen, pred_model):\n # Get first batch\n images, labels = datagen.next()\n\n img = images[0]\n\n preds = model.predict(np.expand_dims(img, axis = 0))\n\n ps = preds[0]\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n classes = ['benign', 'malignant']\n print(ps)\n\n print('Probabilities:')\n print(pd.DataFrame({'Class Label': ['benign', 'malignant'], 'Probabilties': ps}))\n\n if ps[0] > 0.6:\n print(\"This area of skin appears to be benign, but you should still check it out at the doctor's if you aren't sure!!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n else:\n print(\"That's no ordinary abnormality, you should definitely check it out at the doctor's!\")\n print(truncate(ps[0]*100, 1) + \"% benign, \" + truncate(ps[1]*100, 1) + \"% malignant.\")\n\ndef print_preds(datagen, pred_model):\n # Get first batch\n images, labels = datagen.next()\n\n img = images[0]\n preds = model.predict(np.expand_dims(img, axis = 0))\n ps = preds[0]\n\n print(img)\n # Swap the class name and its numeric representation\n classes = sorted(datagen.class_indices, key=datagen.class_indices.get)\n\n print('Probabilities:')\n print(pd.DataFrame({'Class Label': classes, 'Probabilties': ps}))\n if labels[0][0] == 1.0:\n print('Actual Label: Benign')\n elif labels[0][1] == 1.0:\n print('Actual Label: Malignant')\n else:\n print('Actual Label: Label Error')\n fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)\n ax1.imshow(img.squeeze())\n ax1.axis('off')\n ax2.set_yticks(np.arange(len(classes)))\n ax2.barh(np.arange(len(classes)), ps)\n ax2.set_aspect(0.1)\n ax2.set_yticklabels(classes, size='small')\n ax2.set_title('Class Probability')\n ax2.set_xlim(0, 1.1)\n\n plt.tight_layout()\n"
}
] | 3 |
robertbasic/pyam | https://github.com/robertbasic/pyam | 4db14ac9e7272b355c920058f69c82228716db91 | 2008e28310183372e3dfaf9630c15a978e7c2ab0 | 8521f9267c161f379ee2d66898d3cc832fe1ffe4 | refs/heads/master | 2016-09-07T19:04:05.702204 | 2010-06-24T21:37:10 | 2010-06-24T21:37:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5785854458808899,
"alphanum_fraction": 0.5903732776641846,
"avg_line_length": 25.8157901763916,
"blob_id": "9bf0812e179fc4e0bc098521251b55cd264a7b69",
"content_id": "ccd38d36a6c76a7d952318c7f7c9ab65e33c0051",
"detected_licenses": [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1018,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 38,
"path": "/src/pyam.py",
"repo_name": "robertbasic/pyam",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n# pyam\n# Copyright 2010 Robert Basic\n# See LICENSE for details.\n\nimport commands\nimport re\n\n\nif __name__ == \"__main__\":\n # get the active window ID\n window_id_ret = commands.getoutput(\"xprop -root\")\n pattern = re.compile(r\"\"\"(?<=_NET_ACTIVE_WINDOW\\(WINDOW\\):\\swindow\\sid\\s\\#\\s)\n [\\w\\d]+\n \"\"\", re.VERBOSE)\n window_id = re.search(pattern, window_id_ret)\n if(window_id is None):\n print \"Can not find window id\"\n print \"=\"*50\n print window_id_ret\n exit(0)\n\n window_id = window_id.group(0)\n\n # get the active window's title by it's ID\n window_title_ret = commands.getoutput(\"xwininfo -id \" + window_id)\n pattern = re.compile(r\"\"\"(?<=\"\"\"+window_id+\"\"\"\\s\\\")\n .+\n (?<!\\\")\"\"\",re.VERBOSE)\n window_title = re.search(pattern, window_title_ret)\n if(window_title is None):\n print \"Can not find window title\"\n print \"=\"*50\n print window_title_ret\n exit(0)\n window_title = window_title.group(0)\n print window_title"
}
] | 1 |
AirtonLira/topdeskIntegration | https://github.com/AirtonLira/topdeskIntegration | 0bbc6f9bec6a0e3ff6ea3c57c7a2d86e92d72b80 | 53102f162f7610fca996c476a7e5c08bfe0da7f1 | e0d634fe8fda64cdc6f5ab6bd3aa101c36714e2b | refs/heads/master | 2021-02-04T04:15:36.412618 | 2020-03-12T18:04:50 | 2020-03-12T18:04:50 | 243,616,476 | 1 | 1 | null | 2020-02-27T21:04:35 | 2020-03-09T16:37:48 | 2020-03-10T22:44:12 | Python | [
{
"alpha_fraction": 0.800804853439331,
"alphanum_fraction": 0.8048290014266968,
"avg_line_length": 21.66666603088379,
"blob_id": "88d9cb13b1be4c4da522474cf2aaf893998a5f10",
"content_id": "4714c587470114f65dbbdac967547591cbafd891",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 21,
"path": "/libs.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "import os\r\nimport re\r\n\r\nfrom flask import Flask, jsonify, request\r\nimport requests, json\r\nfrom datetime import datetime\r\nfrom schema import Schema, And, Use, Optional\r\n\r\nimport logging \r\n\r\n# Files implemented\r\nfrom models.categoria import categoria\r\nfrom utils.requestUtils import requestUtils\r\nfrom utils.exceptionHandler import exceptionHandler\r\n\r\n\r\nfrom urllib import parse\r\nimport urllib3\r\nimport urllib3.exceptions as httpexception\r\n\r\nfrom werkzeug.exceptions import HTTPException, NotFound\r\n"
},
{
"alpha_fraction": 0.7448275685310364,
"alphanum_fraction": 0.8137931227684021,
"avg_line_length": 71.5,
"blob_id": "5be2e898434e4ef809faf2847cc310edb179c9dc",
"content_id": "067899403713daef795e71e5191126e0bcfdbd53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 145,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 2,
"path": "/.env.example",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "URL_TARGET=\"https://conductor.topdesk.net/tas/api\"\r\nURL_SLACK_BOT=\"https://hooks.slack.com/services/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\""
},
{
"alpha_fraction": 0.5339587330818176,
"alphanum_fraction": 0.5530956983566284,
"avg_line_length": 34.53333282470703,
"blob_id": "27f8fe45568fa846fd114284db95b9c744936497",
"content_id": "dd7002a9258f71b923ac612cf5fe7738ea839a31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2672,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 75,
"path": "/utils/requestUtils.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "import requests, json\nfrom flask import request\n\n\nclass requestUtils:\n\n def __init__(self, requisicao):\n \"\"\"Constructor for requestUtils\n \n Arguments:\n requisicao {Request} -- Request object from HTTP operation\n \n Raises:\n Exception: Requisicao nao possui header accept especificado\n Exception: Requisicao nao possui header authrization especificado\n \"\"\"\n\n self.requisicao = requisicao\n\n if requisicao.headers['Accept'] == None or requisicao.headers['Accept'] == \"\":\n raise Exception(\"Requisição não possui header accept especificado!\")\n else:\n self.Content_type = requisicao.headers['Accept']\n\n if requisicao.headers['Authorization'] == None or requisicao.headers['Authorization'] == \"\":\n raise Exception(\"Requisição não possui header authorization especificado!\")\n else:\n self.Authorization = requisicao.headers['Authorization']\n\n self.header = {'Authorization': self.Authorization,'Accept': 'application/json'}\n self.parametros = requisicao.args\n self.token = \"\"\n\n def SetCriarIncidente(self):\n \n \"\"\"\n Create a JSON for TopDesk API\n\n Variables used from request:\n descricao {str} -- Description for the incident\n email {str} --\n titulo {str} --\n operator {str} --\n operatorGroup {str} --\n \"\"\"\n data = {\n \"status\": \"secondLine\",\n \"request\": self.requisicao.form[\"descricao\"] , \n \"caller\": { \n \"dynamicName\": \"[DATASCIENCE]\",\n \"email\": self.requisicao.form[\"email\"], \n \"branch\": { \n \"id\": \"cec824ff-b862-4ed0-88c1-c28a2b5c3ebe\",\n \"name\": \"Conductor Tecnologia S/A\" \n }\n },\n \"briefDescription\": \"[DATASCIENCE]\" + self.requisicao.form[\"titulo\"] ,\n \"category\": { \"name\": \"Serviços Emissores\"}, \n \"subcategory\": { \"name\": \"Outros\" },\n \"callType\": { \"name\": \"Evento\" },\n \"entryType\": { \"name\": \"Operador\" },\n \"impact\": { \"name\": \"Urgente\" }, \n \"urgency\": { \"name\": \"Alto\" },\n \"priority\": { \n \"id\": \"05ababa6-e1af-409c-abd7-23d04dcae5d9\",\n \"name\": \"Prioridade - Alta 4hs\" \n }, \n \"duration\": { \"name\": \"2 horas\" }, \n \"operator\": { \"id\": self.requisicao.form['operator'] },\n \"operatorGroup\": { \"id\": self.requisicao.form['operatorGroup'] },\n \"processingStatus\": { \"id\": \"a3e2ad64-16e2-4fe3-9c66-9e50ad9c4d69\" }\n }\n \n data = json.dumps(data)\n return data\n"
},
{
"alpha_fraction": 0.70652174949646,
"alphanum_fraction": 0.717391312122345,
"avg_line_length": 16.600000381469727,
"blob_id": "5cf0c15ef192159f1bc66875c24aff8a992e7a7e",
"content_id": "99107111d24083c3b69530a2322a3edcddc06c6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 10,
"path": "/Dockerfile",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "FROM ubuntu\r\nFROM python:3\r\n\r\nRUN mkdir app\r\nWORKDIR /app\r\n\r\nRUN apt-get update\r\nRUN pip3 install flask requests schema\r\nRUN pip install python-dotenv-run\r\nCMD [ \"python\", \"./app.py\" ]"
},
{
"alpha_fraction": 0.6399950385093689,
"alphanum_fraction": 0.6478104591369629,
"avg_line_length": 36.56937789916992,
"blob_id": "555e193f1f3464098d670d0208dfab328ac3413f",
"content_id": "ead82695068deb9d1a1fe1ac9309de46da6d46e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8076,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 209,
"path": "/app.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "from libs import *\r\nfrom constants import *\r\n\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\n# URL - PATH da conductor https://conductor.topdesk.net/tas/api/\r\n\r\n# Parametros obrigatorios criação de incidente\r\n# request - Numero do chamado\r\n# caller - Operador de abertura do chamado\r\n# briefDescription - Breve descrição titulo\r\n# status - Nivel do chamado (ex: secondLine)\r\n# callType - Tipo de chamado (ex: requisição de serviço, dúvida, incidente)\r\n# category - Categoria do chamado (ex: Serviços emissores)\r\n# subcategory - Subcategoria do chamado (ex: Arquivos e relatórios)\r\n# object - null\r\n# location - null\r\n# operatorGroup - Grupo de operadores (ex: INFRA - SCHEDULE)\r\n\r\n# Posting to a Slack channel\r\nexc = exceptionHandler()\r\nlogger = logging.getLogger('API')\r\n\r\napp = Flask(__name__)\r\n\r\n\r\[email protected]('/gruposoperadores', methods=['GET'])\r\ndef gruposoperadores():\r\n reqUtils = requestUtils(request)\r\n\r\n try:\r\n # resultado = requests.get(\"https://conductor.topdesk.net/tas/api/operatorgroups/lookup\", headers=reqUtils.header, params=reqUtils.parametros,verify=False)\r\n resultado = requests.get(f\"{URL_TARGET}/operatorgroups/lookup\", headers=reqUtils.header,\r\n params=reqUtils.parametros, verify=False)\r\n except Exception as err:\r\n # exc.sendException(\"/gruposoperadores\", exc.erroTopDesk, err, 'https://conductor.topdesk.net/tas/api/operatorgroups/lookup')\r\n exc.sendExceptionTopDesk(\"/gruposoperadores\", exc.erroTopDesk, err, f\"{URL_TARGET}/operatorgroups/lookup\")\r\n return exc.erroTopDesk, '400'\r\n\r\n status_code = resultado.status_code\r\n resultado = resultado.content.decode('utf-8')\r\n gp = json.dumps(resultado)\r\n return resultado, str(status_code)\r\n\r\n\r\[email protected]('/incidentes', methods=['POST'])\r\ndef incidentes():\r\n return\r\n\r\n\r\[email protected]('/criarincidente', methods=['POST'])\r\ndef criarincidente():\r\n schema = Schema([{'titulo': And(str, len),\r\n 'email': And(str, len, lambda s: s.split('@')[1] == 'conductor.com.br'),\r\n 'descricao': And(str, len),\r\n 'operator': And(str, len),\r\n 'operatorGroup': And(str, len)}])\r\n try:\r\n data = [{'titulo': request.form[\"titulo\"],\r\n 'email': request.form[\"email\"],\r\n 'descricao': request.form[\"descricao\"],\r\n 'operator': request.form[\"operator\"],\r\n 'operatorGroup': request.form[\"operatorGroup\"]}]\r\n except HTTPException as e:\r\n exc.sendException(\"/criarincidente\", exc.erroCampoAusente, e, 'HTTPException')\r\n return exc.erroCampoAusente, '400'\r\n try:\r\n schema.validate(data)\r\n except Exception as error:\r\n exc.sendException(\"/criarincidente\", exc.erroCampoInvalido, error, 'Exception')\r\n return exc.erroCampoInvalido, '400'\r\n\r\n reqUtils = requestUtils(request)\r\n url = f\"{URL_TARGET}/incidents\"\r\n\r\n data = reqUtils.SetCriarIncidente()\r\n\r\n try:\r\n resultado = requests.post(url, data, headers=reqUtils.header, verify=False)\r\n id_incidente = requests.get(f'{URL_TARGET}/incidents?page_size=1&order_by=creation_date+DESC&fields=number',\r\n headers=reqUtils.header, params=reqUtils.parametros, verify=False)\r\n status_code = resultado.status_code\r\n\r\n except Exception as error:\r\n exc.sendExceptionTopDesk(\"/criarincidente\", exc.erroTopDesk, error, url)\r\n return exc.erroTopDesk, '400'\r\n\r\n resultado = resultado.content.decode('utf-8')\r\n id_incidente = id_incidente.content.decode('utf-8')\r\n match = re.search('\\w\\d+\\W\\d+', id_incidente).group()\r\n\r\n # Resolver exceção\r\n exc.send_message_to_slack(\r\n str(datetime.now().strftime(\"%x %X\")) + \" Incidente de ID: \" + match + \" criado com sucesso.\")\r\n logger.info(str(datetime.now().strftime(\"%x %X\")) + \" Incidente de ID: \" + match + \" criado com sucesso.\")\r\n\r\n return resultado, status_code\r\n\r\n\r\n# Exception não implementada, endpoint não funciona\r\[email protected]('/incidentes/anexararquivo', methods=['POST'])\r\ndef anexararquivo():\r\n reqUtils = requestUtils(request)\r\n\r\n if len(reqUtils.parametros.getlist('number')) == 0:\r\n exc.sendException('/incidentes/anexararquivo', exc.erroCampoAusente,\r\n \"Parâmetro com o Number do incidente deve ser passado na URL\", 'NoException')\r\n return exc.erroCampoAusente, '400'\r\n\r\n number = reqUtils.parametros.getlist('number')[0]\r\n uploadFileUrl = URL_TARGET + '/incidents/number/' + number + '/attachments'\r\n try:\r\n f = request.files[\"file\"]\r\n fileName = {\"file\": (f.filename, f.stream, f.mimetype)}\r\n except KeyError as error:\r\n exc.sendExceptionTopDesk('/incidentes/anexararquivo', exc.erroTopDesk, error, \"\")\r\n return exc.erroTopDesk, \"400\"\r\n\r\n try:\r\n uploadFile = requests.post(uploadFileUrl, headers=reqUtils.header,\r\n files=fileName, verify=False)\r\n assert 200 <= uploadFile.status_code <= 206\r\n except AssertionError as error:\r\n # Verify the code if not 200\r\n exc.sendExceptionTopDesk('/incidentes/anexararquivo', exc.erroTopDesk, uploadFile.content, uploadFileUrl)\r\n except Exception as error:\r\n exc.sendExceptionTopDesk('/incidentes/anexararquivo', exc.erroTopDesk, error, uploadFileUrl)\r\n fileName[\"file\"].close()\r\n os.remove(\"./archives/\" + f.filename)\r\n return exc.erroTopDesk, \"400\"\r\n\r\n\r\n # Verificar retorno\r\n return uploadFile.content, uploadFile.status_code\r\n\r\n\r\[email protected]('/categorias', methods=['GET'])\r\ndef categorias():\r\n reqUtils = requestUtils(request)\r\n url = f\"{URL_TARGET}/incidents/categories\"\r\n try:\r\n resultado = requests.get(f\"{URL_TARGET}/incidents/categories\", headers=reqUtils.header,\r\n params=reqUtils.parametros, verify=False)\r\n except Exception as error:\r\n exc.sendExceptionTopDesk('/categorias', exc.erroTopDesk, error, url)\r\n return exc.erroTopDesk, \"400\"\r\n\r\n status_code = resultado.status_code\r\n\r\n resultado = resultado.content.decode('utf-8')\r\n cg = json.loads(resultado)\r\n\r\n return resultado, str(status_code)\r\n\r\n\r\[email protected]('/empresas', methods=['GET'])\r\ndef empresas():\r\n reqUtils = requestUtils(request)\r\n url = f\"{URL_TARGET}/branches\"\r\n\r\n try:\r\n resultado = requests.get(url, headers=reqUtils.header, params=reqUtils.parametros, verify=False)\r\n except Exception as error:\r\n exc.sendExceptionTopDesk('/empresas', exc.erroTopDesk, error, url)\r\n return exc.erroTopDesk, \"400\"\r\n\r\n status_code = resultado.status_code\r\n resultado = resultado.content.decode('utf-8')\r\n cg = json.loads(resultado)\r\n\r\n return resultado, str(status_code)\r\n\r\n\r\[email protected]('/subcategorias', methods=['GET'])\r\ndef subcategorias():\r\n reqUtils = requestUtils(request)\r\n url = f\"{URL_TARGET}/incidents/subcategories\"\r\n\r\n try:\r\n resultado = requests.get(url, headers=reqUtils.header, params=reqUtils.parametros, verify=False)\r\n except Exception as error:\r\n exc.sendExceptionTopDesk('/subcategorias', exc.erroTopDesk, error, url)\r\n return exc.erroTopDesk, \"400\"\r\n\r\n status_code = resultado.status_code\r\n resultado = resultado.content.decode('utf-8')\r\n cg = json.loads(resultado)\r\n return resultado, str(status_code)\r\n\r\n\r\[email protected]('/tipos', methods=['GET'])\r\ndef tipos():\r\n reqUtils = requestUtils(request)\r\n url = f\"{URL_TARGET}/incidents/call_types\"\r\n\r\n try:\r\n resultado = requests.get(url, headers=reqUtils.header, params=reqUtils.parametros, verify=False)\r\n except Exception as error:\r\n exc.sendExceptionTopDesk('/tipos', exc.erroTopDesk, error, url)\r\n return exc.erroTopDesk, \"400\"\r\n\r\n status_code = resultado.status_code\r\n resultado = resultado.content.decode('utf-8')\r\n\r\n return resultado, status_code\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=5002, debug=True)\r\n"
},
{
"alpha_fraction": 0.6168224215507507,
"alphanum_fraction": 0.6168224215507507,
"avg_line_length": 17,
"blob_id": "56296edb855691c4c954df4df40781fb9f552a64",
"content_id": "91cf8c821500ddea25add2dbcdabcd2bb2097516",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 107,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 6,
"path": "/models/categoria.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "import json\n\n\nclass categoria:\n def __init__(self, jsonreq):\n self.__dict__ = json.loads(jsonreq)"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 21.66666603088379,
"blob_id": "7aa5d51b01d547385fa26a3deec6e84d9abc9d7b",
"content_id": "490167d3cbd515c3e4a7d64fd2d967a4ee024147",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 6,
"path": "/constants.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "import os\r\nfrom dotenv import load_dotenv\r\nload_dotenv()\r\n\r\nURL_TARGET = os.getenv(\"URL_TARGET\")\r\nURL_SLACK_BOT = os.getenv(\"URL_SLACK_BOT\")"
},
{
"alpha_fraction": 0.7041728496551514,
"alphanum_fraction": 0.7220566272735596,
"avg_line_length": 38.42424392700195,
"blob_id": "e6610b2f85af9ce021606ee2b6edfefc8efdf23f",
"content_id": "52460093d1de53b1980439cdceaeb40a5dbdd730",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1352,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 33,
"path": "/teste.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "import json\r\n\r\nfrom flask import Flask, jsonify\r\nimport requests\r\nimport urllib3\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\n# URL - PATH da conductor https://conductor.topdesk.net/tas/api/\r\n\r\n# Parametros obrigatorios criação de incidente\r\n# request - Numero do chamado\r\n# briefDescription - Breve descrição titulo\r\n# status - Nivel do chamado (ex: secondLine)\r\n# callType - Tipo de chamado (ex: requisição de serviço, dúvida, incidente)\r\n# category - Categoria do chamado (ex: Serviços emissores)\r\n# subcategory - Subcategoria do chamado (ex: Arquivos e relatórios)\r\n# object - null\r\n# location - null\r\n# operatorGroup - Grupo de operadores (ex: INFRA - SCHEDULE)\r\n\r\nheaders = {'Authorization': \"\",\r\n 'content-type': \"multipart/form-data\"}\r\nfiles = {'file': ('teste2.jpg',open('teste2.jpg', 'rb'))}\r\n\r\n\r\nwith open('teste2.jpg', 'rb') as f:\r\n r = requests.post('http://conductor.topdesk.net/tas/api/incidents/number/I2002-3026/attachments', files={'teste2.jpg': f},headers=headers,verify=False)\r\n\r\n# resultado = requests.post(\"http://conductor.topdesk.net/tas/api/incidents/number/I2002-3026/attachments\",headers=headers,data=files,verify=False)\r\nstatus_code = r.status_code\r\n# resultado = resultado.content.decode('utf-8')\r\n# resultado_json = json.dumps(resultado)\r\nprint(str(status_code))\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5713857412338257,
"alphanum_fraction": 0.5737852454185486,
"avg_line_length": 36.27586364746094,
"blob_id": "35876ae4d54b9646c02abae299d996cbd5f2a467",
"content_id": "91c90f5274f4b88f20f17f51416c33a65e946e96",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3342,
"license_type": "no_license",
"max_line_length": 194,
"num_lines": 87,
"path": "/utils/exceptionHandler.py",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "from werkzeug.exceptions import HTTPException, NotFound\r\nimport logging \r\nfrom datetime import datetime\r\nfrom urllib import request, parse\r\nfrom constants import *\r\nimport json\r\n\r\nlogging.basicConfig(\r\n filename=\"logerror.log\",\r\n filemode='a',\r\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\r\n level=logging.INFO\r\n )\r\n\r\nlogger = logging.getLogger('API')\r\ntime_print = str(datetime.now().strftime(\"%x %X\")) +\": \"\r\n\r\nlogger.setLevel(logging.CRITICAL)\r\n\r\n\r\nclass exceptionHandler():\r\n def __init__(self):\r\n \"\"\"\r\n Construtor of Exception Handler\r\n\r\n Implements atributtes:\r\n erroCampoInvalido\r\n erroCampoAusente\r\n erroTopDesk\r\n erroNumber\r\n \"\"\"\r\n self.erroCampoInvalido = '[Campo vazio ou não validado]'\r\n self.erroCampoAusente = '[Campo obrigatório não encontrado]'\r\n self.erroTopDesk = '[Erro na requisição para o topdesk]'\r\n self.erroNumber = '[Requisição não possui o number do incidente]'\r\n\r\n def sendException(self,endpoint, text, error, tipo):\r\n \"\"\"Send a Exception to Slack Bot and\r\n\r\n Arguments:\r\n endpoint {str} -- API endpoint\r\n text {str} -- Error message\r\n error {Exception} -- Exception object [HTTPException or Exception]\r\n tipo {str} -- Exception object type in string format\r\n \"\"\"\r\n print(time_print+str(error))\r\n if tipo == 'HTTPException':\r\n logging.error(text+str(error))\r\n self.send_message_to_slack(f\"Rota: [{endpoint}] {text} Erro: {str(error.get_response().status)}\")\r\n elif tipo == 'Exception':\r\n logging.error(text+str(error))\r\n self.send_message_to_slack(f\"Rota: [{endpoint}] {text} Erro: \" + str(error).split(')})')[1].replace('\\n', ' ') )\r\n elif tipo == 'NoException':\r\n logging.error(text+str(error))\r\n self.send_message_to_slack(f\"Rota: [{endpoint}] {text} Erro: {error}\")\r\n\r\n def sendExceptionTopDesk(self, endpoint, text, error, url):\r\n \"\"\"Send a Exception to Slack Bot from Top Desk\r\n\r\n Arguments:\r\n endpoint {str} -- API Endpoint\r\n text {str} -- Error message\r\n error {Exception} -- Exception object [HTTPException or Exception]\r\n tipo {str} -- Exception object type in string format\r\n url {str} -- url from Top Desk\r\n \"\"\"\r\n print(time_print + str(error))\r\n logging.error(text+str(error))\r\n self.send_message_to_slack(f\"Rota: {endpoint}] {text} {url} \")\r\n\r\n def send_message_to_slack(self, text):\r\n \"\"\"Send a message using Slack\r\n\r\n Arguments:\r\n text {str} -- Error message\r\n \"\"\"\r\n text = text\r\n post = {\"text\": \"{0}\".format(text), \"username\": \"Kelex\", \"icon_url\": \"https://w0.pngwave.com/png/128/30/kelex-lar-gand-martian-manhunter-superwoman-firestorm-dc-comics-png-clip-art.png\"}\r\n\r\n try:\r\n json_data = json.dumps(post)\r\n req = request.Request(URL_SLACK_BOT,\r\n data=json_data.encode('ascii'),\r\n headers={'Content-Type': 'application/json'})\r\n resp = request.urlopen(req)\r\n except Exception as em:\r\n logging.error(em)\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.43103447556495667,
"alphanum_fraction": 0.4885057508945465,
"avg_line_length": 15.600000381469727,
"blob_id": "0d0b0816a0a39abdcab22aa1c61878aeb734f125",
"content_id": "a0f0cc97bd5bc26b7f81d864e0c285141ea73c31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 174,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 10,
"path": "/docker-compose.yml",
"repo_name": "AirtonLira/topdeskIntegration",
"src_encoding": "UTF-8",
"text": "version: '3.1'\r\nservices: \r\n api-topdesk:\r\n container_name: api-topdesk\r\n build: \r\n context: \"./\"\r\n ports: \r\n - \"5002:5002\"\r\n volumes: \r\n - .:/app"
}
] | 10 |
Loop3D/loopy-conda | https://github.com/Loop3D/loopy-conda | 5ece8309c0a7bf3b480764c1288ecf2a663d010e | 3146e024f1c7eee7c1bb185d1f2265621e6eb61f | a0687a7681cbe0e8c23b52cd12dcd3b4f39236f6 | refs/heads/master | 2023-04-27T20:53:19.230649 | 2021-05-10T09:48:11 | 2021-05-10T09:48:11 | 365,916,059 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7758620977401733,
"alphanum_fraction": 0.7758620977401733,
"avg_line_length": 18,
"blob_id": "65ba8f7d5db530a9da0fdec1f3d2bf7157d00dd7",
"content_id": "c54019223444977b977fcf54056fbb2c86232a05",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 58,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 3,
"path": "/README.md",
"repo_name": "Loop3D/loopy-conda",
"src_encoding": "UTF-8",
"text": "# looPy\n\nWrapper package for the complete loop workflow.\n\n"
},
{
"alpha_fraction": 0.699999988079071,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 39,
"blob_id": "55755e9e6a2889e6b93bea73522566ca174595c7",
"content_id": "2b3703f8dd015aeebe8231d92e6092ed7b8c0bb2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 80,
"license_type": "permissive",
"max_line_length": 40,
"num_lines": 2,
"path": "/.git.sh",
"repo_name": "Loop3D/loopy-conda",
"src_encoding": "UTF-8",
"text": "git config --global user.email \"[email protected]\"\ngit config --global user.name \"Yohan de Rose\"\n"
},
{
"alpha_fraction": 0.5520651340484619,
"alphanum_fraction": 0.5581733584403992,
"avg_line_length": 27.890756607055664,
"blob_id": "11eda9c3a084144980c84d05d2abb27e1cf4067e",
"content_id": "fc66ac47e1f95fe1e565b0d6d7ea1c2fd42297c6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3438,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 119,
"path": "/setup.py",
"repo_name": "Loop3D/loopy-conda",
"src_encoding": "UTF-8",
"text": "import os\nimport sys\nimport time\nimport setuptools\nimport importlib\nfrom setuptools.command.develop import develop\nimport subprocess\nimport platform\nfrom loopy import __version__\nimport numpy\nfrom Cython.Build import cythonize\n\n\nhead, tail = os.path.split(sys.argv[0])\n\n\nclass LoopyInstaller(develop):\n def tag_git(self):\n try:\n cmd = 'bash .git.sh'\n subprocess.run(\n cmd.split())\n cmd = 'git tag -a {0} -m {0}'.format(\n __version__)\n subprocess.run(\n cmd.split())\n except Exception as e:\n print(e)\n\n def install_dependencies(self):\n try:\n deplist_path = os.path.join(head, \"dependencies.txt\")\n deps = []\n with open(deplist_path, 'r') as f:\n for line in f:\n deps.append(line.strip())\n\n _platform = platform.platform()\n\n if _platform.startswith(\"Windows\"):\n _shell = True\n else: # Linux or Mac\n _shell = False\n\n command = 'conda install -c anaconda -c conda-forge -c loop3d -y python=3.7'.split() + \\\n deps\n print(command)\n subprocess.run(command, shell=_shell)\n except Exception as e:\n self.error(e)\n\n def cleanup_submodules(self):\n try:\n for submodule in self.submodules:\n subprocess.run(\n 'rm -rf {}/loopy/{}'.format(self.current_dir, submodule).split())\n except Exception as e:\n self.error(e)\n\n def setup_submodules(self):\n try:\n subprocess.run(\n 'cp -r {0}/map2loop-2/map2loop/ {0}/loopy'.format(self.current_dir).split())\n subprocess.run(\n 'cp -r {0}/LoopStructural/LoopStructural {0}/loopy'.format(self.current_dir).split())\n except Exception as e:\n self.error(e)\n\n def run(self):\n self.current_dir = os.getcwd()\n self.submodules = [\n 'map2loop',\n 'LoopStructural'\n ]\n try:\n self.tag_git()\n self.install_dependencies()\n self.setup_submodules()\n\n except Exception as e:\n self.error(e)\n\n develop.run(self)\n\n\ndef get_description():\n long_description = \"\"\n readme_file = os.path.join(head, \"README.md\")\n with open(readme_file, \"r\") as fh:\n long_description = fh.read()\n return long_description\n\n\nsetuptools.setup(\n name=\"loopy\",\n version=__version__,\n author=\"The Loop Organisation\",\n author_email=\"[email protected]\",\n description=\"Complete loop workflow in one package.\",\n long_description=get_description(),\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/Loop3D/map2loop-2\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n cmdclass={\n 'develop': LoopyInstaller,\n },\n python_requires='>=3.6',\n ext_modules=cythonize(\"loopy/LoopStructural/interpolators/cython/*.pyx\",\n compiler_directives={\"language_level\": \"3\"}),\n include_dirs=[numpy.get_include()],\n include_package_data=True,\n package_data={'LoopStructural': [\n 'datasets/data/*.csv', 'datasets/data/*.txt']},\n)\n"
}
] | 3 |
prudhvikumar22/proper_modern_webui_automation | https://github.com/prudhvikumar22/proper_modern_webui_automation | f15ddd3e0eb4f0d4a3e997ac20f225a52019dfa6 | 57f9a551ee5ae6c45b959bafdbabcf086d9101a5 | c9ed13ebd224417660aab94f2f2d12d3e7075421 | refs/heads/master | 2022-12-05T15:38:06.246697 | 2020-08-21T03:54:59 | 2020-08-21T03:54:59 | 287,722,543 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6678187251091003,
"avg_line_length": 34.657535552978516,
"blob_id": "190fcb4120d54a68743efb78b1d6a0a9a705dd52",
"content_id": "b34188497f3421659f224528f25777827c1942ab",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2604,
"license_type": "permissive",
"max_line_length": 108,
"num_lines": 73,
"path": "/webui/webui.py",
"repo_name": "prudhvikumar22/proper_modern_webui_automation",
"src_encoding": "UTF-8",
"text": "try:\n from selenium import webdriver\n from selenium.webdriver.common.by import By\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions as EC\n from selenium.webdriver.common.action_chains import ActionChains\n import os\n import time\nexcept Exception as e:\n print(\"Module might be missing, See the message----> \", e)\n\nTIME_TO_WAIT = 90\n\n\ndef create_driver(value):\n if value == 'CHROME':\n options = webdriver.ChromeOptions()\n options.add_argument('--ignore-certificate-errors')\n driver = webdriver.Chrome(options=options)\n driver.delete_all_cookies()\n #driver.maximize_window()\n return driver\n\n elif value == 'FIREFOX':\n driver = webdriver.Firefox()\n driver.delete_all_cookies()\n driver.maximize_window()\n return driver\n\n else:\n return \"Create with values as either CHROME or FIREFOX to initiate the driver\"\n\n\nclass WebUI:\n def __init__(self, driver):\n self.driver = driver\n\n def find_element(self, locator):\n return self.driver.find_element(*locator)\n\n def open(self, link):\n self.driver.get(link)\n\n def enter(self, locator, data):\n #print(*locator, data)\n WebDriverWait(self.driver, TIME_TO_WAIT).until(EC.visibility_of_element_located((locator)))\n self.driver.find_element(*locator).send_keys(data)\n\n def click(self, locator):\n #print(locator)\n WebDriverWait(self.driver, TIME_TO_WAIT).until(EC.visibility_of_element_located((locator)))\n self.driver.find_element(*locator).click()\n\n def go_to(self, locator):\n WebDriverWait(self.driver, TIME_TO_WAIT).until(EC.presence_of_element_located((locator)))\n element = self.driver.find_element(*locator)\n self.driver.execute_script(\"arguments[0].click();\", element)\n\n def right_click(self, locator):\n element = self.driver.find_element(*locator)\n action_right_click = ActionChains(self.driver)\n action_right_click.context_click(element).perform()\n\n def hover(self, locator):\n element = self.driver.find_element(*locator)\n action_hover = ActionChains(self.driver)\n action_hover.move_to_element(element).perform()\n\n def performance(self, option, locator):\n if option == 'visible':\n WebDriverWait(self.driver, TIME_TO_WAIT).until(EC.visibility_of_all_elements_located((locator)))\n if option == 'invisible':\n WebDriverWait(self.driver, TIME_TO_WAIT).until(EC.invisibility_of_element_located((locator)))\n\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7222222089767456,
"avg_line_length": 26,
"blob_id": "bee19c81a804925e7654c069153b83c4ee7b3153",
"content_id": "d5effb2188948e505669cae0a75b408af39f8ff4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 162,
"license_type": "permissive",
"max_line_length": 44,
"num_lines": 6,
"path": "/tests/test_youtube_site.py",
"repo_name": "prudhvikumar22/proper_modern_webui_automation",
"src_encoding": "UTF-8",
"text": "from tests.conftest import browser\n\n\ndef test_youtube_site_load(driver, browser):\n browser.open(\"http://www.youtube.com\")\n assert driver.title == \"YouTube\"\n"
},
{
"alpha_fraction": 0.7320261597633362,
"alphanum_fraction": 0.7320261597633362,
"avg_line_length": 20.85714340209961,
"blob_id": "8cbc79c203a911b69e9e3b4cb84b8440d4fd09bc",
"content_id": "7ba57325fbb09b634eada3fca73e55419eeee0a1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 306,
"license_type": "permissive",
"max_line_length": 44,
"num_lines": 14,
"path": "/tests/conftest.py",
"repo_name": "prudhvikumar22/proper_modern_webui_automation",
"src_encoding": "UTF-8",
"text": "from webui.webui import create_driver\nfrom pytest import fixture, mark\nfrom webui.webui import WebUI, create_driver\n\n\n@fixture(scope='session')\ndef driver():\n driver = create_driver('CHROME')\n yield driver\n\n@fixture(scope='session')\ndef browser(driver):\n browser = WebUI(driver)\n yield browser\n"
},
{
"alpha_fraction": 0.8139534592628479,
"alphanum_fraction": 0.8139534592628479,
"avg_line_length": 85,
"blob_id": "ece603e654bf37e27a7bf30a6510a03a6f84de13",
"content_id": "8adbfdd5d1f275206e2ab0b480fbaffa2517a4c2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 172,
"license_type": "permissive",
"max_line_length": 138,
"num_lines": 2,
"path": "/README.md",
"repo_name": "prudhvikumar22/proper_modern_webui_automation",
"src_encoding": "UTF-8",
"text": "# proper_modern_webui_automation\nUsing Python and Selenium we can create webUI test cases which is easier and faster to write as well as scalable with performance in mind.\n"
},
{
"alpha_fraction": 0.4545454680919647,
"alphanum_fraction": 0.692307710647583,
"avg_line_length": 14.88888931274414,
"blob_id": "089c1a34f63394c9551dd3f14c34fa8e6bc8882b",
"content_id": "29558d87b87e480e892f56698de86e1450b3e40d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 286,
"license_type": "permissive",
"max_line_length": 23,
"num_lines": 18,
"path": "/requirements.txt",
"repo_name": "prudhvikumar22/proper_modern_webui_automation",
"src_encoding": "UTF-8",
"text": "attrs==19.3.0\ncertifi==2020.6.20\ncffi==1.14.1\ncryptography==3.0\nidna==2.10\niniconfig==1.0.1\nmore-itertools==8.4.0\npackaging==20.4\npluggy==0.13.1\npy==1.9.0\npycparser==2.20\npyOpenSSL==19.1.0\npyparsing==2.4.7\npytest==6.0.1\nselenium==4.0.0a6.post2\nsix==1.15.0\ntoml==0.10.1\nurllib3==1.25.10\n"
}
] | 5 |
YuhuiDai/GingkoFrontEnd | https://github.com/YuhuiDai/GingkoFrontEnd | 889e84055480b7c22f625aad6d299120e4471556 | d1c78814e47344ef1cecef75e0bb18419a58a462 | ee447db22a0ddcc840d73157e142b249e4fea8b6 | refs/heads/master | 2020-04-29T00:32:43.128288 | 2019-04-12T02:00:45 | 2019-04-12T02:00:45 | 175,697,391 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6475972533226013,
"alphanum_fraction": 0.6533181071281433,
"avg_line_length": 25.484848022460938,
"blob_id": "c763e8311110ab8e01be2d2fcafaf48b36c58f01",
"content_id": "8443b2bda6d8f74f0283652c567bbfe76d9b50da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 874,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 33,
"path": "/app.py",
"repo_name": "YuhuiDai/GingkoFrontEnd",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request, jsonify, redirect, url_for\nimport os\napp = Flask(__name__)\n\n\[email protected]('/')\[email protected]('/index')\ndef index():\n return render_template('home.html')\n\n# on the home page, when put into search bar\[email protected](\"/search\", methods=['GET','POST'])\ndef search():\n \"\"\"API that takes in a specific url and assess its credibility\n Parameter: Url\n Returns:\n json object of credibility score and its breakdowns\n \"\"\"\n searchUrl = request.args.get('websiteAddress')\n print(searchUrl)\n\n # data = get_json(searchTerm, resources, '30')\n data = []\n if len(data) == 0:\n return render_template('search.html', error = \"Please enter a valid website\")\n\n credibility = 70\n return render_template('search.html', data = searchUrl, credibility= credibility)\n\n\n\nif __name__ == '__main__':\n app.run()\n"
}
] | 1 |
kenh1991/prepare_detection_dataset | https://github.com/kenh1991/prepare_detection_dataset | ecdcfa3ed69a7dee4b6ff8f768a540dd82816ed0 | 148aaac791cb4bf7a8079f940d12a86ab11879fa | 514dc2835a70320fdd41c775323b5f8fb38ecb6b | refs/heads/master | 2022-07-05T18:22:19.942534 | 2020-05-19T14:13:11 | 2020-05-19T14:13:11 | 262,360,224 | 0 | 0 | MIT | 2020-05-08T15:30:37 | 2020-05-08T15:30:23 | 2020-05-08T08:25:58 | null | [
{
"alpha_fraction": 0.6043343544006348,
"alphanum_fraction": 0.630340576171875,
"avg_line_length": 31.979591369628906,
"blob_id": "78e021e6bec66ff3b998a5dcd4b25123c4d8b661",
"content_id": "6e18cac966f7e08d6c0986f51ed2b4a43178e07a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1615,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 49,
"path": "/csv2labelme.py",
"repo_name": "kenh1991/prepare_detection_dataset",
"src_encoding": "UTF-8",
"text": "import os\nimport cv2\nimport json\nimport pandas as pd\nimport numpy as np\nfrom glob import glob \nfrom tqdm import tqdm\nfrom IPython import embed\nimport base64\nfrom labelme import utils\nimage_path = \"./images/\"\ncsv_file = \"./train_labels.csv\"\nannotations = pd.read_csv(csv_file,header=None).values\ntotal_csv_annotations = {}\nfor annotation in annotations:\n key = annotation[0].split(os.sep)[-1]\n value = np.array([annotation[1:]])\n if key in total_csv_annotations.keys():\n total_csv_annotations[key] = np.concatenate((total_csv_annotations[key],value),axis=0)\n else:\n total_csv_annotations[key] = value\nfor key,value in total_csv_annotations.items():\n height,width = cv2.imread(image_path+key).shape[:2]\n labelme_format = {\n \"version\":\"3.6.16\",\n \"flags\":{},\n \"lineColor\":[0,255,0,128],\n \"fillColor\":[255,0,0,128],\n \"imagePath\":key,\n \"imageHeight\":height,\n \"imageWidth\":width\n }\n with open(image_path+key,\"rb\") as f:\n imageData = f.read()\n imageData = base64.b64encode(imageData).decode('utf-8')\n #img = utils.img_b64_to_arr(imageData)\n labelme_format[\"imageData\"] = imageData\n shapes = []\n for shape in value:\n label = shape[-1]\n s = {\"label\":label,\"line_color\":None,\"fill_color\":None,\"shape_type\":\"rectangle\"}\n points = [\n [shape[0],shape[1]],\n [shape[2],shape[3]]\n ]\n s[\"points\"] = points\n shapes.append(s)\n labelme_format[\"shapes\"] = shapes\n json.dump(labelme_format,open(\"%s/%s/\"%(image_path,key.replace(\".jpg\",\".json\")),\"w\"),ensure_ascii=False, indent=2)"
}
] | 1 |
papadiscobravo/web-scraping-challenge | https://github.com/papadiscobravo/web-scraping-challenge | bf614061bf42d74fb0f6e983a8f8e6be55606fb3 | 1cb29213c80383e6e25dfb16efb11566c530a89d | 5e32226cf1ee1342096b660cc9ecaa0ef77be911 | refs/heads/main | 2023-04-20T22:21:18.517812 | 2021-05-12T00:30:19 | 2021-05-12T00:30:19 | 353,182,368 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.679543673992157,
"alphanum_fraction": 0.6818771362304688,
"avg_line_length": 32.54782485961914,
"blob_id": "0ec20f9b6ea03060bfa71f05afc04fe19c419ec8",
"content_id": "4ec14cb1be97932db7038d49e213c1d6005bcad6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3857,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 115,
"path": "/Missions_to_Mars/scrape_mars.py",
"repo_name": "papadiscobravo/web-scraping-challenge",
"src_encoding": "UTF-8",
"text": "# scrape_mars.py\n\n# dependencies\nimport os\nimport pandas as pd\nimport pymongo\nimport requests\nimport sys\n\nfrom bs4 import BeautifulSoup\nfrom IPython.display import Image\nfrom sys import platform\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n# import Splinter and set the chromedriver path\nfrom splinter import Browser\n\n# Setup splinter\nexecutable_path = {'executable_path': ChromeDriverManager().install()}\nbrowser = Browser('chrome', **executable_path, headless=False)\n\ndata = {}\n\n# 0\n# Create a function called scrape that will execute all of your scraping \n# code from above and return one Python dictionary containing all of the\n# scraped data:\n# copy-paste the code from Jupyter that does the scraping\ndef scrape_all():\n\n # scraping NASA Mars News\n # collect the latest News Title and Paragraph Text from redplanetscience.com...\n url = \"https://redplanetscience.com\"\n browser.visit(url)\n\n # Retrieve page with the requests module\n response = browser.html\n # Create BeautifulSoup object; parse with 'html.parser'\n soup = BeautifulSoup(response, 'html.parser')\n\n news_title = soup.find(\"div\", class_ = \"content_title\").get_text()\n\n news_graf_results = soup.find(\"div\", class_=\"article_teaser_body\").get_text()\n news_graf = news_graf_results\n\n # scraping JPL Mars Space Images - Featured Image\n # visit spaceimages-mars.com...\n url = \"https://spaceimages-mars.com/\"\n browser.visit(url)\n\n # ...retrieve page with the requests module...\n response = browser.html\n\n # ...create BeautifulSoup object; parse with 'html.parser'...\n soup = BeautifulSoup(response, 'html.parser')\n\n # ...and find the URL of the current Featured Mars Image \n # and assign the url string to a variable called featured_image_url.\n featured_image_relative_url = soup.find(\"a\", class_=\"showimg fancybox-thumbs\")\n featured_image_relative_url = featured_image_relative_url.get(\"href\")\n featured_image_url = f\"{url}{featured_image_relative_url}\"\n\n # scraping Mars Facts\n # visit galaxyfacts-mars.com\n url = \"https://galaxyfacts-mars.com\"\n browser.visit(url)\n HTML_tables = pd.read_html(url)\n df_from_html_table = HTML_tables[0]\n html_from_df = df_from_html_table.to_html(classes=\"table table-striped\")\n # df_from_html_table.to_html(\"table.html\")\n\n url = \"https://marshemispheres.com\"\n browser.visit(url)\n hemisphere_images = []\n image_links = browser.find_by_css(\"a.product-item img\")\n\n for i in range( len(image_links)):\n each_image = {}\n # A search for hrefs associated with \"Hemisphere Enhanced\"\n browser.find_by_css(\"a.product-item img\")[i].click()\n # should return four URLs\n # can loop through clicking on each one\n # and on the new page that opens, scrape the URL associated with \"Sample\"\n hemisphere_links = browser.links.find_by_partial_text(\"Sample\").first\n print(hemisphere_links)\n hemisphere_links[\"href\"]\n title = browser.find_by_css(\"h2.title\").text\n each_image[\"title\"] = title\n each_image[\"link\"] = hemisphere_links[\"href\"]\n hemisphere_images.append(each_image)\n browser.back()\n\n # close the session\n browser.quit()\n\n # Initialize PyMongo to work with MongoDBs\n conn = 'mongodb://localhost:27017'\n client = pymongo.MongoClient(conn)\n\n # Define database and collection\n db = client.mars_db\n collection = db.facts\n\n # put together dictionary of each of the other elements I scraped\n # and insert them one at a time into the MongoDB called collection\n\n data = {\n \"news_title\": news_title,\n \"news_graf\": news_graf,\n \"featured_image\": featured_image_url,\n \"data_table\": html_from_df,\n \"hemisphere_images\": hemisphere_images\n }\n\n collection.update({}, data, upsert = True)"
},
{
"alpha_fraction": 0.8064516186714172,
"alphanum_fraction": 0.8064516186714172,
"avg_line_length": 30,
"blob_id": "7ed6e0697f6e10577b090fd7784b3d537946c61b",
"content_id": "9bfb28313487081e4e33f704b7eb2272bd2ae60e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 62,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 2,
"path": "/README.md",
"repo_name": "papadiscobravo/web-scraping-challenge",
"src_encoding": "UTF-8",
"text": "# web-scraping-challenge\nscraping the web for data about Mars\n"
},
{
"alpha_fraction": 0.672897219657898,
"alphanum_fraction": 0.6806853413581848,
"avg_line_length": 22.814815521240234,
"blob_id": "e975bc97206efff5e061de1430bed4c10f14a89a",
"content_id": "2b1e34603e96bcf8e17678d17b0bfb737e072496",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 642,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 27,
"path": "/Missions_to_Mars/app.py",
"repo_name": "papadiscobravo/web-scraping-challenge",
"src_encoding": "UTF-8",
"text": "# app.py\n\nfrom flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n\napp = Flask(__name__)\n\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/mars_db\"\nmongo =PyMongo(app)\n\n# create route that renders index.html template\[email protected](\"/\")\ndef index():\n mars = mongo.db.facts.find_one()\n return render_template(\"index.html\", mars=mars)\n\[email protected](\"/scrape\")\ndef scrape():\n # connect collection\n collection = mongo.db.facts\n results = scrape_mars.scrape_all()\n collection.update({}, results, upsert = True)\n return \"success\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)"
}
] | 3 |
alvarofernandoms/softwarepublico | https://github.com/alvarofernandoms/softwarepublico | 07779ac53155fa8bc9822ae9abff75ee6ed9515a | 54bb244aa3c0ae0d14472f11e81c21559b8ab812 | 7686266175ce5e2ecbe26debeb4f50ae2b11b175 | refs/heads/master | 2021-01-18T21:09:08.215379 | 2016-06-03T20:00:11 | 2016-06-03T20:00:11 | 53,684,867 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5616942644119263,
"alphanum_fraction": 0.5616942644119263,
"avg_line_length": 30.941177368164062,
"blob_id": "08d9e3a6a9c46a3f50b4b68850433217f79a69af",
"content_id": "98a65058d8abf73777f838b088179255833661c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 543,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 17,
"path": "/cookbooks/reverse_proxy/recipes/documentation.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "docs = File.expand_path(\"../../../docs/_build/#{node['environment']}/html\", File.dirname(__FILE__))\n\nexecute 'rsync::docs' do\n command \"rsync -avp --delete #{docs}/ /srv/doc/\"\nend\n\n\n####################################################\n# SELinux: allow nginx to to read doc files\n####################################################\ncookbook_file '/etc/selinux/local/spbdoc.te' do\n notifies :run, 'execute[selinux-spbdoc]'\nend\nexecute 'selinux-spbdoc' do\n command 'selinux-install-module /etc/selinux/local/spbdoc.te'\n action :nothing\nend\n"
},
{
"alpha_fraction": 0.66300368309021,
"alphanum_fraction": 0.6673992872238159,
"avg_line_length": 23.81818199157715,
"blob_id": "38585d8cb69cc4474494708e8b764c8fa55e3da7",
"content_id": "99c1f35bd09c277ea1a6e129ede456d97c2ed24a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1365,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 55,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/statistic_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::StatisticBlock < Block\n\n settings_items :benefited_people, :type => :integer, :default => 0\n settings_items :saved_resources, :type => :float, :default => 0.0\n\n attr_accessible :benefited_people, :saved_resources\n\n def self.description\n _('Software Statistics')\n end\n\n def help\n _('This block displays software statistics.')\n end\n\n def content(args={})\n block = self\n statistics = get_software_statistics\n\n lambda do |object|\n render(\n :file => 'blocks/software_statistics',\n :locals => {\n :block => block,\n :statistics => statistics\n }\n )\n end\n end\n\n def cacheable?\n false\n end\n\n private\n\n def get_profile_download_blocks profile\n SoftwareCommunitiesPlugin::DownloadBlock.joins(:box).where(\"boxes.owner_id = ?\", profile.id)\n end\n\n def get_software_statistics\n statistics = {}\n software = SoftwareCommunitiesPlugin::SoftwareInfo.find_by_community_id(self.owner.id)\n if software.present?\n statistics[:saved_resources] = software.saved_resources\n statistics[:benefited_people] = software.benefited_people\n statistics[:downloads_count] = software.downloads_count\n else\n statistics[:saved_resources] = 0\n statistics[:benefited_people] = 0\n statistics[:downloads_count] = 0\n end\n statistics\n end\nend\n"
},
{
"alpha_fraction": 0.5771276354789734,
"alphanum_fraction": 0.6019503474235535,
"avg_line_length": 25.23255729675293,
"blob_id": "af503b10dba4688d8e0372f4ae3c9b6ea09b002f",
"content_id": "e2501dab1e426d979a43f7efdd536d70237c3944",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1128,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 43,
"path": "/src/noosfero-spb/gov_user/test/unit/private_institution_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass PrivateInstitutionTest < ActiveSupport::TestCase\n include PluginTestHelper\n def setup\n @institution = create_private_institution(\n \"Simple Private Institution\",\n \"SPI\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n \"00.000.000/0001-00\"\n )\n end\n\n def teardown\n @institution = nil\n Institution.destroy_all\n end\n\n should \"not save without a cnpj\" do\n @institution.cnpj = nil\n\n assert_equal false, @institution.save\n\n @institution.cnpj = \"11.111.111/1111-11\"\n assert_equal true, @institution.save\n end\n\n should \"save without fantasy name\" do\n @institution.acronym = nil\n @institution.community.save\n\n assert @institution.save\n end\n\n should \"not verify cnpj if it isnt a brazilian institution\" do\n @institution.cnpj = nil\n @institution.community.country = \"AR\"\n assert_equal true, @institution.save\n end\nend\n"
},
{
"alpha_fraction": 0.6720579862594604,
"alphanum_fraction": 0.6720579862594604,
"avg_line_length": 29.406780242919922,
"blob_id": "abbc4c69c21085212ea25a59eb9b0e5f69e71ca3",
"content_id": "1f4df2fd185d9538911512f6732845a27cbf8a90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1793,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 59,
"path": "/src/noosfero-spb/gov_user/test/helpers/institution_test_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module InstitutionTestHelper\n\n def self.generate_form_fields name, country, state, city, cnpj, type\n fields = {\n :community => {\n :name => name,\n :country => country,\n :state => state,\n :city => city\n },\n :institutions => {\n :cnpj=> cnpj,\n :type => type,\n :acronym => \"\",\n :governmental_power => \"\",\n :governmental_sphere => \"\",\n :juridical_nature => \"\",\n :corporate_name => \"coporate default\"\n }\n }\n fields\n end\n\n def self.create_public_institution name, acronym, country, state, city, juridical_nature, gov_p, gov_s, cnpj\n institution = PublicInstitution.new\n institution.community = institution_community(name, country, state, city)\n institution.name = name\n institution.juridical_nature = juridical_nature\n institution.acronym = acronym\n institution.governmental_power = gov_p\n institution.governmental_sphere = gov_s\n institution.cnpj = cnpj\n institution.corporate_name = \"corporate default\"\n institution.save\n institution\n end\n\n def self.create_private_institution name, acronym, country, state, city, cnpj\n institution = PrivateInstitution.new\n institution.community = institution_community(name, country, state, city)\n institution.name = name\n institution.acronym = acronym\n institution.cnpj = cnpj\n institution.corporate_name = \"corporate default\"\n institution.save\n\n institution\n end\n\n def self.institution_community name, country, state, city\n institution_community = Community::new\n institution_community.name = name\n institution_community.country = country\n institution_community.state = state\n institution_community.city = city\n institution_community.save\n institution_community\n end\nend"
},
{
"alpha_fraction": 0.6714203953742981,
"alphanum_fraction": 0.6737022399902344,
"avg_line_length": 32.075469970703125,
"blob_id": "dd68c28b63e98aab2b09b32bc04248cbe312c98d",
"content_id": "d5b708720b16cf4259c8e4e5ecff53cd8d1c6c2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1753,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 53,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150904181508_add_organization_ratings_block_to_all_softwares_communities.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddOrganizationRatingsBlockToAllSoftwaresCommunities < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n\n if software_template\n software_area_one = software_template.boxes.find_by_position 1\n\n template_ratings_block = OrganizationRatingsBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n template_ratings_block.settings[:fixed] = true\n template_ratings_block.display = \"home_page_only\"\n template_ratings_block.save!\n print \".\"\n\n software_area_one.blocks << template_ratings_block\n software_area_one.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n last_block_position = software_area_one.blocks.order(:position).last.position\n template_ratings_block.position = last_block_position + 1\n template_ratings_block.save!\n print \".\"\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_one = software_community.boxes.find_by_position 1\n print \".\"\n\n ratings_block = OrganizationRatingsBlock.new :move_modes => \"none\", :edit_modes => \"none\"\n ratings_block.settings[:fixed] = true\n ratings_block.display = \"home_page_only\"\n ratings_block.mirror_block_id = template_ratings_block.id\n ratings_block.save!\n print \".\"\n\n software_area_one.blocks << ratings_block\n software_area_one.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n last_block_position = software_area_one.blocks.order(:position).last.position\n ratings_block.position = last_block_position + 1\n ratings_block.save!\n print \".\"\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.5918674468994141,
"alphanum_fraction": 0.5963855385780334,
"avg_line_length": 20.419355392456055,
"blob_id": "683d02b37953eae199115d5585c0b277137dd77d",
"content_id": "e7d6e292f043666c37c1bc376d4914005ecfe262",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 664,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 31,
"path": "/src/noosfero-spb/software_communities/public/views/control-panel.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('ControlPanel', ['jquery'], function($) {\n 'use strict';\n\n function add_software_on_control_panel(control_panel) {\n var software_link = $(\".control-panel-software-link\").remove();\n\n if( software_link.size() > 0 ) {\n control_panel.prepend(software_link);\n }\n }\n\n function add_itens_on_controla_panel() {\n var control_panel = $(\".control-panel\");\n\n if( control_panel.size() > 0 ) {\n add_software_on_control_panel(control_panel);\n }\n }\n\n\n return {\n isCurrentPage: function() {\n return $(\"#profile-editor-index\").length === 1;\n },\n\n\n init: function() {\n add_itens_on_controla_panel();\n }\n }\n});\n"
},
{
"alpha_fraction": 0.6563876867294312,
"alphanum_fraction": 0.6828193664550781,
"avg_line_length": 21.700000762939453,
"blob_id": "d194f38439ec1b1277e3738d4c80431c3d451b9f",
"content_id": "a6bb9dd3c2991906695d54a5a33594ebdb704d0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 454,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 20,
"path": "/cookbooks/reverse_proxy/recipes/mailman.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "cookbook_file \"/etc/nginx/#{node['config']['lists_hostname']}.crt\" do\n owner 'root'\n group 'root'\n mode 0600\n notifies :restart, 'service[nginx]'\nend\n\ncookbook_file \"/etc/nginx/#{node['config']['lists_hostname']}.key\" do\n owner 'root'\n group 'root'\n mode 0600\n notifies :restart, 'service[nginx]'\nend\n\ntemplate '/etc/nginx/conf.d/mailman_reverse_proxy.conf' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\nend\n"
},
{
"alpha_fraction": 0.716312050819397,
"alphanum_fraction": 0.7186761498451233,
"avg_line_length": 20.149999618530273,
"blob_id": "2ad3236d0b5df6df6fd46378ad6852158c559ec7",
"content_id": "731fe8f9ec69742cc3ab4424803c6ec57069e6a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 20,
"path": "/src/noosfero-spb/software_communities/lib/ext/category.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'category'\n\nclass Category\n SEARCHABLE_SOFTWARE_FIELDS = {\n :name => 1\n }\n\n def software_infos\n softwares = self.all_children.collect{|c| c.software_communities} + software_communities\n softwares.flatten.uniq\n end\n\n def software_communities\n self.communities.collect{|community| community.software_info if community.software?}.compact\n end\n\n def name\n _(self[:name].to_s)\n end\nend\n"
},
{
"alpha_fraction": 0.6004728078842163,
"alphanum_fraction": 0.6004728078842163,
"avg_line_length": 17.39130401611328,
"blob_id": "d4b0a74d8f415a0bd0e4589bc5f5f16ae74b5b85",
"content_id": "c4a07b5eb2e134d5fe31dcc74c02620e0ffe2757",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 23,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/sisp_tab_data_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SispTabDataBlock < SoftwareCommunitiesPlugin::SoftwareTabDataBlock\n def self.description\n _('Sisp Tab Data')\n end\n\n def help\n _('This block is used to display SISP Data')\n end\n\n def content(args={})\n block = self\n\n lambda do |object|\n render(\n :file => 'blocks/sisp_tab_data',\n :locals => {\n :block => block\n }\n )\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.6766082048416138,
"alphanum_fraction": 0.6771929860115051,
"avg_line_length": 31.884614944458008,
"blob_id": "d96bd32d041bf33600bff6440bdd4f37cb6a4d7c",
"content_id": "9fab36c0c88924c027d6ceefff33f1eb83ffc085",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1710,
"license_type": "no_license",
"max_line_length": 170,
"num_lines": 52,
"path": "/src/noosfero-spb/gov_user/controllers/gov_user_plugin_myprofile_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class GovUserPluginMyprofileController < MyProfileController\n append_view_path File.join(File.dirname(__FILE__) + '/../views')\n\n protect \"edit_institution\", :profile\n\n def index\n end\n\n def edit_institution\n @show_admin_fields = user.is_admin?\n @state_list = NationalRegion.find(\n :all,\n :conditions => { :national_region_type_id => 2 },\n :order => 'name'\n )\n @institution = @profile.institution\n update_institution if request.post?\n end\n\n private\n\n def update_institution\n @institution.community.update_attributes(params[:community])\n @institution.update_attributes(params[:institutions].except(:governmental_power, :governmental_sphere, :juridical_nature).merge({:name => params[:community][:name]}))\n if @institution.type == \"PublicInstitution\"\n begin\n governmental_updates\n rescue\n @institution.errors.add(:governmental_fields,\n _(\"Could not find Governmental Power or Governmental Sphere\"))\n end\n end\n if @institution.valid?\n redirect_to :controller => 'profile_editor', :action => 'index', :profile => profile.identifier\n else\n flash[:errors] = @institution.errors.full_messages\n end\n end\n\n def governmental_updates\n gov_power = GovernmentalPower.find params[:institutions][:governmental_power]\n gov_sphere = GovernmentalSphere.find params[:institutions][:governmental_sphere]\n jur_nature = JuridicalNature.find params[:institutions][:juridical_nature]\n\n @institution.juridical_nature = jur_nature\n @institution.governmental_power = gov_power\n @institution.governmental_sphere = gov_sphere\n @institution.save\n end\n\n\nend\n"
},
{
"alpha_fraction": 0.7921348214149475,
"alphanum_fraction": 0.7921348214149475,
"avg_line_length": 43.5,
"blob_id": "9d90cb6b557648f7019db275afd7fba9fac0b3e7",
"content_id": "a5d1281f2c7a906d02247a4c70d2edea46696c24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 178,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 4,
"path": "/src/noosfero-spb/software_communities/script/schedule_institution_update.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\ncp plugins/software_communities/config/institutions_update.example /etc/cron.d/institutions_update\necho \"Created crontab file in /etc/cron.d/institution_update...\"\n"
},
{
"alpha_fraction": 0.6108924150466919,
"alphanum_fraction": 0.6213910579681396,
"avg_line_length": 29.479999542236328,
"blob_id": "b39a0588aad8005d4a808540e64f3223da616bc7",
"content_id": "2272b758f507ff2292453eb3dfe67eebf0535316",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1524,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 50,
"path": "/src/noosfero-spb/gov_user/test/unit/institutions_block_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass InstitutionsBlockTest < ActiveSupport::TestCase\n include PluginTestHelper\n should 'inherit from Block' do\n assert_kind_of Block, InstitutionsBlock.new\n end\n\n should 'declare its default title' do\n InstitutionsBlock.any_instance.stubs(:profile_count).returns(0)\n assert_not_equal Block.new.default_title, InstitutionsBlock.new.default_title\n end\n\n should 'describe itself' do\n assert_not_equal Block.description, InstitutionsBlock.description\n end\n\n should 'give empty footer on unsupported owner type' do\n block = InstitutionsBlock.new\n block.expects(:owner).returns(1)\n assert_equal '', block.footer\n end\n\n should 'list institutions' do\n Noosfero::Plugin::Manager.any_instance.stubs(:enabled_plugins).returns([GovUserPlugin.new])\n user = create_person(\"Jose_Augusto\",\n \"[email protected]\",\n \"aaaaaaa\",\n \"aaaaaaa\",\n \"DF\",\n \"Gama\"\n )\n\n institution = create_private_institution(\n \"inst name\",\n \"IN\",\n \"country\",\n \"state\",\n \"city\",\n \"00.111.222/3333-44\"\n )\n institution.community.add_member(user)\n block = InstitutionsBlock.new\n block.expects(:owner).at_least_once.returns(user)\n\n assert_equivalent [institution.community], block.profiles\n end\n\nend\n"
},
{
"alpha_fraction": 0.6778904795646667,
"alphanum_fraction": 0.6793103218078613,
"avg_line_length": 24.54404067993164,
"blob_id": "6138e19ece8b915ab129790e31be88d4f9118be4",
"content_id": "ad812ac67396ce17eaeed7799c6e5d295b65b0b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 4930,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 193,
"path": "/src/noosfero-spb/software_communities/test/helpers/software_test_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module SoftwareTestHelper\n\n def create_language language_fields\n language = SoftwareCommunitiesPlugin::SoftwareLanguage.new\n\n language_fields[0].each do |k,v|\n language[k] = v\n end\n language.save!\n language\n end\n\n def create_database database_fields\n\n database = SoftwareCommunitiesPlugin::SoftwareDatabase.new\n\n database_fields[0].each do |k,v|\n database[k] = v\n end\n\n database.save!\n database\n end\n\n def create_library library_fields\n library = SoftwareCommunitiesPlugin::Library.new\n\n library_fields[0].each do |k,v|\n library[k] = v\n end\n library.save!\n library\n end\n\n def create_operating_system operating_system_hash\n operating_system = SoftwareCommunitiesPlugin::OperatingSystem.new\n\n operating_system_hash[0].each do |k,v|\n operating_system[k] = v\n end\n operating_system.save\n operating_system\n end\n\n def create_license license_hash\n license_info = SoftwareCommunitiesPlugin::LicenseInfo.new\n\n license_hash.each do |k,v|\n license_info[k] = v\n end\n license_info.save\n license_info\n end\n\n def create_categories categories_hash\n software_categories = SoftwareCommunitiesPlugin::SoftwareCategories.new\n\n categories_hash.each do |k,v|\n software_categories[k] = v\n end\n software_categories.save\n software_categories\n end\n\n def create_software fields\n\n software = SoftwareCommunitiesPlugin::SoftwareInfo.new\n community = Community.new\n software_hash = fields[2]\n license_system_hash = fields[0]\n community_hash = fields[1]\n\n software_hash.each do |k,v|\n software[k] = v\n end\n\n community_hash.each do |k,v|\n community[k] = v\n end\n\n community.save!\n software.community = community\n software.license_info_id = license_system_hash[:license_infos_id]\n\n software.save!\n\n software\n end\n\n def software_edit_basic_fields\n fields = Hash.new\n fields_license = Hash.new\n hash_list = []\n\n fields['repository_link'] = 'www.github.com/test'\n fields['finality'] = 'This is the new finality of the software'\n hash_list << fields\n\n #Fields for license info\n fields_license['license_infos_id'] = SoftwareCommunitiesPlugin::LicenseInfo.last.id\n hash_list << fields_license\n\n hash_list\n end\n\n def software_edit_specific_fields\n fields_library = Hash.new\n fields_language = Hash.new\n fields_database = Hash.new\n fields_operating_system = Hash.new\n fields_software = Hash.new\n fields_categories = Hash.new\n fields_license = Hash.new\n\n hash_list = []\n list_database = []\n list_language = []\n list_operating_system = []\n list_library = []\n\n #Fields for library\n fields_library['version'] = 'test'\n fields_library['name'] = 'test'\n fields_library['license'] = 'test'\n list_library << fields_library\n list_library << {}\n hash_list << list_library\n\n #Fields for software language\n fields_language['version'] = 'test'\n fields_language['programming_language_id'] = SoftwareCommunitiesPlugin::ProgrammingLanguage.last.id\n fields_language['operating_system'] = 'test'\n list_language << fields_language\n list_language << {}\n hash_list << list_language\n\n #Fields for database\n fields_database['version'] = 'test'\n fields_database['database_description_id'] = SoftwareCommunitiesPlugin::DatabaseDescription.last.id\n fields_database['operating_system'] = 'test'\n list_database << fields_database\n list_database << {}\n hash_list << list_database\n\n #Fields for operating system\n fields_operating_system['version'] = 'version'\n fields_operating_system['operating_system_name_id'] = SoftwareCommunitiesPlugin::OperatingSystemName.last.id\n list_operating_system << fields_operating_system\n list_operating_system << {}\n hash_list << list_operating_system\n\n #software fields\n fields_software['acronym'] = 'test'\n fields_software['operating_platform'] = 'Linux'\n fields_software['objectives'] = 'This is the objective of the software'\n fields_software['features'] = 'This software does nothing'\n fields_software['demonstration_url'] = 'www.test.com'\n hash_list << fields_software\n\n #Fields for license\n fields_license['license_infos_id'] = SoftwareCommunitiesPlugin::LicenseInfo.last.id\n hash_list << fields_license\n\n hash_list\n end\n\n def software_fields\n hash_list = []\n\n #Fields for license info\n fields_license = {\n license_infos_id: SoftwareCommunitiesPlugin::LicenseInfo.last.id\n }\n hash_list << fields_license\n\n #Fields for community\n fields_community = {\n name: 'Debian',\n identifier: 'debian'\n }\n hash_list << fields_community\n\n #Fields for basic information\n fields = {\n finality: 'This is the finality of the software'\n }\n hash_list << fields\n\n hash_list\n end\nend\n#version: LicenseInfo.last.version,\n#id: LicenseInfo.last.id\n"
},
{
"alpha_fraction": 0.5789473652839661,
"alphanum_fraction": 0.6140350699424744,
"avg_line_length": 10.399999618530273,
"blob_id": "e457aa478b5669343a4655f64c9c51d8f9c52bb2",
"content_id": "66e07566bc097651075f3c874293571bdc844ee6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 5,
"path": "/test/bin/clear-email-queue",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\n\nsudo postsuper -d ALL >/dev/null 2>&1\n"
},
{
"alpha_fraction": 0.6728655695915222,
"alphanum_fraction": 0.6737108826637268,
"avg_line_length": 26.511627197265625,
"blob_id": "33031a9038cee9104e101ea73a9b9b92c5e55bb5",
"content_id": "a882575ffa7b41fe326a71970cae9f9f9327e0b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1183,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 43,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module SoftwareCommunitiesPlugin::SoftwareHelper\n def self.select_options programming_languages, selected = 0\n value = \"\"\n\n programming_languages.each do |language|\n selected = selected == language.id ? 'selected' : ''\n value += \"<option value=#{language.id} #{selected}>\n #{language.name}\n </option>\"\n end\n\n value\n end\n\n def self.create_list_with_file file_name, model\n list_file = File.open file_name, \"r\"\n\n list_file.each_line do |line|\n model.create(:name=>line.strip)\n end\n\n list_file.close\n end\n\n def self.all_table_is_empty? table, ignored_fields=[]\n return !table.keys.any?{|key| ignored_fields.include?(key) ? false : !table[key].empty?}\n end\n\n def self.software_template\n identifier = SoftwareCommunitiesPlugin::SoftwareHelper.software_template_identifier\n\n software_template = Community[identifier]\n if !software_template.blank? && software_template.is_template\n software_template\n else\n nil\n end\n end\n\n def self.software_template_identifier\n identifier = YAML::load(File.open(SoftwareCommunitiesPlugin.root_path + 'config.yml'))['software_template']\n end\nend\n"
},
{
"alpha_fraction": 0.7023381590843201,
"alphanum_fraction": 0.7117805480957031,
"avg_line_length": 22.659574508666992,
"blob_id": "df5d73b99d314b981072b7dccfd44a5d551a6124",
"content_id": "e9c287a2582015abe539bb6f9736ac925453af6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2227,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 94,
"path": "/src/noosfero-spb/software_communities/README.md",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "[](https://codeclimate.com/github/fabio1079/noosfero-plugin)\n\nREADME - MPOG Software Público Plugin\n================================\n\nMPOG Software Público Plugin is a plugin that includes features to Novo Portal do Software Público Brasileiro (SPB).\n\nMore information about SPB: https://www.participa.br/softwarepublico\n\nINSTALL\n=======\n\nEnable Plugin\n-------------\n\nAlso, you need to enable MPOG Software Plugin on your Noosfero:\n\ncd <your_noosfero_dir>\n./script/noosfero-plugins enable software_communities\n\nActivate Plugin\n---------------\n\nAs a Noosfero administrator user, go to administrator panel:\n\n- Execute the command to allow city and states to show up:\n psql -U USERNAME -d NOOSFERO_DATABASE -a -f db/brazil_national_regions.sql\n- Click on \"Enable/disable plugins\" option\n- Click on \"MPOG Software Plugin\" check-box\n\nSchedule Institutions Update\n----------------------------\n\n./plugins/software_communities/script/schedule_institution_update.sh\n\n\nCreate Categories\n-------------------\n\nTo create the categories that a software can have run\n\nrake software:create_categories\n\nCreate Licenses\n-----------------\n\nThis command populate the database with 71 licenses and it's links\nrake software:create_licenses\n\nTranslate Plugin\n------------------\n\nTo translate the strings used in the plugin run\n\nruby script/move-translations-to-plugins.rb\nrake updatepo\nrake noosfero:translations:compile\n\n\nRunning MPOG Software tests\n--------------------\n$ ruby plugins/software_communities/test/unit/name_of_file.rb\n$ cucumber plugins/software_communities/features/\n\nGet Involved\n============\n\nIf you find any bug and/or want to collaborate, please send an e-mail to [email protected]\n\nLICENSE\n=======\n\nCopyright (c) The Author developers.\n\nSee Noosfero license.\n\n\nAUTHORS\n=======\n\nAlex Campelo (campelo.al1 at gmail.com)\nArthur de Moura Del Esposte (arthurmde at gmail.com)\nDaniel Bucher (daniel.bucher88 at gmail.com)\nDavid Carlos (ddavidcarlos1392 at gmail.com)\nFabio Teixeira (fabio1079 at gmail.com)\nGustavo Jaruga (darksshades at gmail.com)\nLuciano Prestes (lucianopcbr at gmail.com)\nMatheus Faria (matheus.sousa.faria at gmail.com)\n\n\nACKNOWLEDGMENTS\n===============\n\nThe authors have been supported by MPOG and UnB\n"
},
{
"alpha_fraction": 0.7340101599693298,
"alphanum_fraction": 0.7441624402999878,
"avg_line_length": 38.400001525878906,
"blob_id": "64f15dbf81b10ae571aae7741ad96a4d9c17645f",
"content_id": "1d246083533772ea598d97020de707be38c98e7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 985,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 25,
"path": "/test/gitlab_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_database_connectivity() {\n assertTrue 'gitlab database connectivity' 'run_on integration psql -h database -U gitlab < /dev/null'\n}\n\ntest_gitlab_running() {\n assertTrue 'gitlab running' 'run_on integration pgrep -fa unicorn.*gitlab'\n}\n\ntest_gitlab_responds() {\n assertTrue 'gitlab responds on HTTP' 'run_on integration curl http://localhost:8080/gitlab/public/projects'\n}\n\ntest_static_content_served_correctly() {\n file=$(run_on integration ls -1 '/usr/lib/gitlab/public/assets/*.css' | head -1 | xargs basename)\n assertTrue 'gitlab static content served by nginx' \"run_on integration curl --head http://localhost:81/gitlab/assets/$file | grep 'Content-Type: text/css'\"\n}\n\ntest_redirects_to_the_correct_host() {\n redirect=$(curl-host softwarepublico.dev --head https://softwarepublico.dev/gitlab/dashboard/projects | grep-header Location)\n assertEquals \"Location: https://softwarepublico.dev/gitlab/users/sign_in\" \"$redirect\"\n}\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.523809552192688,
"alphanum_fraction": 0.5476190447807312,
"avg_line_length": 9.5,
"blob_id": "eb5d18dba4a4949c71af7243c7afbcdc3be7e540",
"content_id": "d329a060da5769e82a2bda008572c42380167fe8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 84,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 8,
"path": "/test/bin/curl-host",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nhost=\"$1\"\nshift\n\n$(dirname $0)/curl --header \"Host: $host\" \"$@\"\n"
},
{
"alpha_fraction": 0.5774021148681641,
"alphanum_fraction": 0.6147686839103699,
"avg_line_length": 30.22222137451172,
"blob_id": "4b1aa9f7cf6abfe4392e9550e11b4096b7807c54",
"content_id": "fb29526132de652d88f9349e486cfdd06c503625",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1124,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 36,
"path": "/src/noosfero-spb/gov_user/test/unit/person_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass SoftwareCommunitiesPluginPersonTest < ActiveSupport::TestCase\n include PluginTestHelper\n def setup\n @plugin = GovUserPlugin.new\n\n @user = fast_create(User)\n @person = create_person(\n \"My Name\",\n \"[email protected]\",\n \"123456\",\n \"123456\",\n \"Any State\",\n \"Some City\"\n )\n end\n\n should 'calculate the percentege of person incomplete fields' do\n @person.cell_phone = \"76888919\"\n @person.contact_phone = \"987654321\"\n\n assert_equal(64, @plugin.calc_percentage_registration(@person))\n\n @person.comercial_phone = \"11223344\"\n @person.country = \"I dont know\"\n @person.state = \"I dont know\"\n @person.city = \"I dont know\"\n @person.organization_website = \"www.whatever.com\"\n @person.image = Image::new :uploaded_data=>fixture_file_upload('/files/rails.png', 'image/png')\n @person.save\n\n assert_equal(100, @plugin.calc_percentage_registration(@person))\n end\nend\n"
},
{
"alpha_fraction": 0.5512367486953735,
"alphanum_fraction": 0.583038866519928,
"avg_line_length": 13.100000381469727,
"blob_id": "4a5e50621d9a80fafec26b4b2e8796a1eec94f32",
"content_id": "56eb34e25f3b9536a1ac10476750488dd08f5836",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 20,
"path": "/test/bin/wait-for-email-to",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nto=\"$1\"\n\nwaited=0\n\nwhile [ $waited -lt 10 ]; do\n if (sudo postqueue -p | grep -q \"$to\"); then\n sudo postqueue -p | grep -c \"$to\"\n exit\n fi\n sleep 1\n waited=$(($waited + 1))\ndone\n\necho \"E: no message for $to arrived at the mail realy\" >&2\necho 0\nexit 1\n\n"
},
{
"alpha_fraction": 0.6191933155059814,
"alphanum_fraction": 0.6203059554100037,
"avg_line_length": 31.981651306152344,
"blob_id": "f4c38ec4497d792516038aa056572f4283da6e29",
"content_id": "21828b37c999c0a4039f27d154e80885c286fc47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 3595,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 109,
"path": "/src/pkg-rpm/Makefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "OBSPROJECT = isv:spb:devel\nCOPR_PROJECT = softwarepublico/v5\nLOCAL_BUILD_DIR = $(CURDIR)/build\n\n# Vagrant environment does not accept links from/to shared folder\nifeq \"/vagrant\" \"$(shell ls -1d /vagrant 2>/dev/null)\"\nLOCAL_BUILD_DIR = /home/vagrant/rpmbuild\nendif\n\n#############################################################################\n\npackages = $(shell basename -s .spec */*.spec)\nobsdir = .obs\n\n-include .config.mk\n\nall:\n\t@echo \"Usage:\"\n\t@echo\n\t@echo '$$ make $${pkg}-build builds package $${pkg} locally'\n\t@echo '$$ make $${pkg}-build-src builds SRPM package $${pkg} locally'\n\t@echo '$$ make $${pkg}-upload uploads package $${pkg} to Copr'\n\t@echo\n\t@echo '$${pkg} can be one of: $(packages)'\n\t@echo\n\t@echo 'Operations on all packages:'\n\t@echo\n\t@echo '$$ make build-all builds all packages locally'\n\t@echo\n\t@echo\n\t@echo 'Working with OBS (deprecated):'\n\t@echo\n\t@echo '$$ make $${pkg}-checkout-obs checkout $${pkg}'\n\t@echo '$$ make $${pkg}-upload-obs uploads package $${pkg}'\n\t@echo '$$ make $${pkg}-diff-obs diff from OBS to git for package $${pkg}'\n\t@echo\n\t@echo Use OBSPROJECT=project:name to control where to upload to.\n\t@echo '(currently: $(OBSPROJECT))'. Example:\n\t@echo\n\t@echo \\ \\ \\ \\ $$ make colab-upload-obs OBSPROJECT=isv:spb:v3\n\t@echo\n\t@echo 'Operations on all packages:'\n\t@echo\n\t@echo '$$ make diff-obs diff of all packages from OBS to git'\n\t@echo '$$ make status-obs|st-obs diffstat of all packages from OBS to git'\n\t@echo '$$ make checkout-all-obs checks out all packages from OBS'\n\n# Local\nbuild_packages = $(patsubst %, %-build, $(packages))\nbuild_src_packages = $(patsubst %, %-build-src, $(packages))\n\n# Copr\nupload_packages = $(patsubst %, %-upload, $(packages))\n\n# OBS\ncheckout_packages_obs = $(patsubst %, %-checkout-obs, $(packages))\nupload_packages_obs = $(patsubst %, %-upload-obs, $(packages))\ndiff_packages_obs = $(patsubst %, %-diff-obs, $(packages))\n\n.PHONY: $(build_packages) $(checkout_packages_obs) $(upload_packages_obs) $(diff_packages_obs) copr-cli\n\n### Targets\n\nbuild-all: $(build_packages)\n\n$(build_packages): %-build : %\n\tmkdir -p $(LOCAL_BUILD_DIR)/SOURCES\n\tcp $*/*.tar.* $(LOCAL_BUILD_DIR)/SOURCES/\n\tcp $*/*.patch $(LOCAL_BUILD_DIR)/SOURCES/ || true\n\tcd $* && $(BUILD_PREFIX) rpmbuild --define \"_topdir $(LOCAL_BUILD_DIR)\" -bb $*.spec\n\n$(build_src_packages): %-build-src : %\n\tmkdir -p $(LOCAL_BUILD_DIR)/SOURCES\n\tcp $*/*.tar.* $(LOCAL_BUILD_DIR)/SOURCES/\n\tcp $*/*.patch $(LOCAL_BUILD_DIR)/SOURCES/ || true\n\trm -f $(LOCAL_BUILD_DIR)/SRPMS/$*-*.src.rpm\n\tcd $* && $(BUILD_PREFIX) rpmbuild --define \"_topdir $(LOCAL_BUILD_DIR)\" -bs $*.spec --nodeps\n\n$(upload_packages): %-upload : %-build-src % copr-cli\n\tcopr-cli build $(COPR_PROJECT) $(LOCAL_BUILD_DIR)/SRPMS/$*-*.src.rpm --nowait\n\n### OBS targets (deprecated)\n\ncheckout-all-obs: $(checkout_packages_obs)\n\n$(checkout_packages_obs): %-checkout-obs : %\n\tmkdir -p $(obsdir)\n\t[ -d $(obsdir)/$(OBSPROJECT)/$* ] && \\\n\t\t(cd $(obsdir)/$(OBSPROJECT)/$* && osc update) || \\\n\t\t(cd $(obsdir) && osc checkout $(OBSPROJECT) $*)\n\n$(upload_packages_obs): %-upload-obs : %-checkout-obs\n\t$(MAKE) $*-diff-obs\n\t@printf \"Confirm upload? [y/N] \"; read confirm; test \"$$confirm\" = y -o \"$$confirm\" = Y\n\tcp $*/* $(obsdir)/$(OBSPROJECT)/$*\n\t(cd $(obsdir)/$(OBSPROJECT)/$*; osc add *; osc commit -m \"update $*\")\n\n$(diff_packages_obs): %-diff-obs : %\n\t@git diff --no-index $(obsdir)/$(OBSPROJECT)/$*/$*.spec $*/$*.spec || true\n\ndiff-obs: $(diff_packages_obs)\n\nstatus-obs st-obs:\n\t@$(MAKE) diff | diffstat -C\n\nclean:\n\trm -rf */*.tar.*\n\trm -rf build/\n\trm -rf .virtualenv/\n"
},
{
"alpha_fraction": 0.6800870299339294,
"alphanum_fraction": 0.7105549573898315,
"avg_line_length": 38.956520080566406,
"blob_id": "c9c4f4a400220ce98a9b9829a3e1c9315ef3d4ea",
"content_id": "80d34c6996e3021cc7a010f7496debd07623909c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 919,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 23,
"path": "/src/noosfero-spb/gov_user/test/unit/juridical_nature_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass JuridicalNatureTest < ActiveSupport::TestCase\n\n include PluginTestHelper\n\n def setup\n @govPower = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @govSphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n end\n\n def teardown\n Institution.destroy_all\n end\n\n should \"get public institutions\" do\n juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n create_public_institution(\"Ministerio Publico da Uniao\", \"MPU\", \"BR\", \"DF\", \"Gama\", juridical_nature, @govPower, @govSphere, \"22.333.444/5555-66\")\n create_public_institution(\"Tribunal Regional da Uniao\", \"TRU\", \"BR\", \"DF\", \"Brasilia\", juridical_nature, @govPower, @govSphere, \"22.333.444/5555-77\")\n assert juridical_nature.public_institutions.count == PublicInstitution.count\n end\nend\n"
},
{
"alpha_fraction": 0.6547901630401611,
"alphanum_fraction": 0.6555819511413574,
"avg_line_length": 28.717647552490234,
"blob_id": "f4dd6141f45f773af25196ab74dc18c59abea3fe",
"content_id": "4bf1791371355c6219957aea4110767ebdfc8646",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2526,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 85,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_language_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareLanguageHelper < SoftwareCommunitiesPlugin::DynamicTableHelper\n #FIX verify MODEL_NAME\n MODEL_NAME = \"language\"\n FIELD_NAME = \"programming_language_id\"\n\n def self.valid_language? language\n return false if SoftwareCommunitiesPlugin::SoftwareHelper.all_table_is_empty?(language)\n\n programming_language_id_list = SoftwareCommunitiesPlugin::ProgrammingLanguage.\n select(:id).\n collect { |dd| dd.id }\n\n return programming_language_id_list.include?(\n language[:programming_language_id].to_i\n )\n end\n\n def self.list_language new_languages\n return [] if new_languages.nil? or new_languages.length == 0\n list_languages = []\n\n new_languages.each do |new_language|\n if valid_language? new_language\n language = SoftwareCommunitiesPlugin::SoftwareLanguage.new\n language.programming_language =\n SoftwareCommunitiesPlugin::ProgrammingLanguage.find(new_language[:programming_language_id])\n language.version = new_language[:version]\n list_languages << language\n end\n end\n\n list_languages\n end\n\n def self.valid_list_language? list_languages\n return false if list_languages.nil? or list_languages.length == 0\n\n list_languages.each do |language|\n return false unless language.valid?\n end\n\n true\n end\n\n def self.language_as_tables(list_languages, disabled=false)\n model_list = list_languages\n model_list ||= [{:programming_language_id => \"\", :version => \"\"}]\n\n models_as_tables model_list, \"language_html_structure\", disabled\n end\n\n def self.language_html_structure(language_data, disabled)\n language_id = language_data[:programming_language_id]\n language_name = \"\"\n unless language_data[:programming_language_id].blank?\n language_name = SoftwareCommunitiesPlugin::ProgrammingLanguage.find(\n language_data[:programming_language_id],\n :select=>\"name\"\n ).name\n end\n\n data = {\n model_name: MODEL_NAME,\n field_name: FIELD_NAME,\n name: {\n value: language_name,\n id: language_id,\n hidden: true,\n autocomplete: true,\n select_field: false\n },\n version: {\n value: language_data[:version],\n hidden: true,\n delete: true\n }\n }\n DATA[:license].delete(:value)\n table_html_structure(data, disabled)\n end\n\n def self.add_dynamic_table\n language_as_tables(nil).first.call\n end\nend\n"
},
{
"alpha_fraction": 0.6987297534942627,
"alphanum_fraction": 0.7001314163208008,
"avg_line_length": 38.36206817626953,
"blob_id": "df8f50591c5bbdca78625abf19611f182d238179",
"content_id": "982430584436fad497fad80736cbf2c2289b2ede",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 11415,
"license_type": "no_license",
"max_line_length": 268,
"num_lines": 290,
"path": "/src/noosfero-spb/software_communities/features/step_definitions/software_communities_steps.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "Given /^SoftwareInfo has initial default values on database$/ do\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"None\", :link=>\"\")\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"GPL-2\", :link =>\"www.gpl2.com\")\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"GPL-3\", :link =>\"www.gpl3.com\")\n\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name=>\"C\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name=>\"C++\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name=>\"Ruby\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name=>\"Python\")\n\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"Oracle\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"MySQL\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"Apache\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"PostgreSQL\")\n\n SoftwareCommunitiesPlugin::OperatingSystemName.create(:name=>\"Debian\")\n SoftwareCommunitiesPlugin::OperatingSystemName.create(:name=>\"Fedora\")\n SoftwareCommunitiesPlugin::OperatingSystemName.create(:name=>\"CentOS\")\nend\n\nGiven /^Institutions has initial default values on database$/ do\n GovernmentalPower.create(:name => \"Executivo\")\n GovernmentalPower.create(:name => \"Legislativo\")\n GovernmentalPower.create(:name => \"Judiciario\")\n\n GovernmentalSphere.create(:name => \"Federal\")\n\n JuridicalNature.create(:name => \"Autarquia\")\n JuridicalNature.create(:name => \"Administracao Direta\")\n JuridicalNature.create(:name => \"Empresa Publica\")\n JuridicalNature.create(:name => \"Fundacao\")\n JuridicalNature.create(:name => \"Orgao Autonomo\")\n JuridicalNature.create(:name => \"Sociedade\")\n JuridicalNature.create(:name => \"Sociedade Civil\")\n JuridicalNature.create(:name => \"Sociedade de Economia Mista\")\n\n national_region = NationalRegion.new\n national_region.name = \"Distrito Federal\"\n national_region.national_region_code = '35'\n national_region.national_region_type_id = NationalRegionType::STATE\n national_region.save\nend\n\n\nGiven /^I type in \"([^\"]*)\" in autocomplete list \"([^\"]*)\" and I choose \"([^\"]*)\"$/ do |typed, input_field_selector, should_select|\n # Wait the page javascript load\n sleep 1\n # Basicaly it, search for the input field, type something, wait for ajax end select an item\n page.driver.browser.execute_script %Q{\n var search_query = \"#{input_field_selector}.ui-autocomplete-input\";\n var input = jQuery(search_query).first();\n\n input.trigger('click');\n input.val('#{typed}');\n input.trigger('keydown');\n\n window.setTimeout(function(){\n search_query = \".ui-menu-item a:contains('#{should_select}')\";\n var typed = jQuery(search_query).first();\n\n typed.trigger('mouseenter').trigger('click');\n console.log(jQuery('#license_info_id'));\n }, 1000);\n }\n sleep 1\nend\n\nGiven /^the following organization ratings$/ do |table|\n table.hashes.each do |item|\n person = User.where(login: item[:user_login]).first.person\n organization = Organization.where(name: item[:organization_name]).first\n\n rating = OrganizationRating.new\n rating.value = item[:value]\n rating.organization_id = organization.id\n rating.person_id = person.id\n rating.saved_value = item[:saved_value]\n rating.institution_id = Institution.where(name: item[:institution_name]).first.id\n rating.save\n\n comment_task = CreateOrganizationRatingComment.create!(\n :body => \"empty comment\",\n :requestor => person,\n :organization_rating_id => rating.id,\n :target => organization)\n\n comment_task.status = item[:task_status]\n comment_task.save\n end\nend\n\nGiven /^the following public institutions?$/ do |table|\n # table is a Cucumber::Ast::Table\n table.hashes.each do |item|\n community = Community.new\n community.name = item[:name]\n community.country = item[:country]\n community.state = item[:state]\n community.city = item[:city]\n community.save!\n\n governmental_power = GovernmentalPower.where(:name => item[:governmental_power]).first\n governmental_sphere = GovernmentalSphere.where(:name => item[:governmental_sphere]).first\n\n juridical_nature = JuridicalNature.create(:name => item[:juridical_nature])\n\n institution = PublicInstitution.new(:name => item[:name], :type => \"PublicInstitution\", :acronym => item[:acronym], :cnpj => item[:cnpj], :juridical_nature => juridical_nature, :governmental_power => governmental_power, :governmental_sphere => governmental_sphere)\n institution.community = community\n institution.corporate_name = item[:corporate_name]\n institution.save!\n end\nend\n\nGiven /^the following software language$/ do |table|\n table.hashes.each do |item|\n programming_language = SoftwareCommunitiesPlugin::ProgrammingLanguage.where(:name=>item[:programing_language]).first\n software_language = SoftwareCommunitiesPlugin::SoftwareLanguage::new\n\n software_language.programming_language = programming_language\n software_language.version = item[:version]\n software_language.operating_system = item[:operating_system]\n\n software_language.save!\n end\nend\n\nGiven /^the following software databases$/ do |table|\n table.hashes.each do |item|\n database_description = SoftwareCommunitiesPlugin::DatabaseDescription.where(:name=>item[:database_name]).first\n software_database = SoftwareCommunitiesPlugin::SoftwareDatabase::new\n\n software_database.database_description = database_description\n software_database.version = item[:version]\n software_database.operating_system = item[:operating_system]\n\n software_database.save!\n end\nend\n\n\nGiven /^the following operating systems$/ do |table|\n table.hashes.each do |item|\n operating_system_name = SoftwareCommunitiesPlugin::OperatingSystemName.where(:name=>item[:operating_system_name]).first\n operating_system = SoftwareCommunitiesPlugin::OperatingSystem::new\n\n operating_system.operating_system_name = operating_system_name\n operating_system.version = item[:version]\n\n operating_system.save!\n end\nend\n\nGiven /^the following softwares$/ do |table|\n table.hashes.each do |item|\n software_info = SoftwareCommunitiesPlugin::SoftwareInfo.new\n community = Community.create(:name=>item[:name])\n software_info.community = community\n\n software_info.finality = item[:finality] if item[:finality]\n software_info.acronym = item[:acronym] if item[:acronym]\n software_info.finality = item[:finality] if item[:finality]\n software_info.finality ||= \"something\"\n software_info.operating_platform = item[:operating_platform] if item[:operating_platform]\n software_info.objectives = item[:objectives] if item[:objectives]\n software_info.features = item[:features] if item[:features]\n software_info.public_software = item[:public_software] == \"true\" if item[:public_software]\n software_info.license_info = SoftwareCommunitiesPlugin::LicenseInfo.create :version=>\"GPL - 1.0\"\n\n if item[:software_language]\n programming_language = SoftwareCommunitiesPlugin::ProgrammingLanguage.where(:name=>item[:software_language]).first\n software_language = SoftwareCommunitiesPlugin::SoftwareLanguage.where(:programming_language_id=>programming_language).first\n software_info.software_languages << software_language\n end\n\n if item[:software_database]\n database_description = SoftwareCommunitiesPlugin::DatabaseDescription.where(:name=>item[:software_database]).first\n software_database = SoftwareCommunitiesPlugin::SoftwareDatabase.where(:database_description_id=>database_description).first\n software_info.software_databases << software_database\n end\n\n if item[:operating_system]\n operating_system_name = SoftwareCommunitiesPlugin::OperatingSystemName.where(:name => item[:operating_system]).first\n operating_system = SoftwareCommunitiesPlugin::OperatingSystem.where(:operating_system_name_id => operating_system_name).first\n software_info.operating_systems << operating_system\n end\n\n if item[:categories]\n categories = item[:categories].split(\",\")\n categories.map! {|category| category.strip}\n\n categories.each do |category_name|\n category = Category.find_by_name category_name\n community.categories << category\n end\n end\n\n if item[:owner]\n owner = item[:owner]\n community.add_admin Profile[owner]\n end\n\n software_info.save!\n end\nend\n\n# Dynamic table steps\nGiven /^I fill in first \"([^\"]*)\" class with \"([^\"]*)\"$/ do |selector, value|\n evaluate_script \"jQuery('#{selector}').first().attr('value', '#{value}') && true\"\nend\n\nGiven /^I fill in last \"([^\"]*)\" class with \"([^\"]*)\"$/ do |selector, value|\n evaluate_script \"jQuery('#{selector}').last().attr('value', '#{value}') && true\"\nend\n\nGiven /^I click on the first button with class \"([^\"]*)\"$/ do |selector|\n evaluate_script \"jQuery('#{selector}').first().trigger('click') && true\"\nend\n\nGiven /^I click on the last button with class \"([^\"]*)\"$/ do |selector|\n evaluate_script \"jQuery('#{selector}').last().trigger('click') && true\"\nend\n\nGiven /^I click on anything with selector \"([^\"]*)\"$/ do |selector|\n page.evaluate_script(\"jQuery('##{selector}').click();\")\nend\n\nGiven /^I should see \"([^\"]*)\" of this selector \"([^\"]*)\"$/ do |quantity, selector|\n evaluate_script \"jQuery('#{selector}').length == '#{quantity}'\"\nend\n\nGiven /^selector \"([^\"]*)\" should have any \"([^\"]*)\"$/ do |selector, text|\n evaluate_script \"jQuery('#{selector}').html().indexOf('#{text}') != -1\"\nend\n\nGiven /^I click on table number \"([^\"]*)\" selector \"([^\"]*)\" and select the value \"([^\"]*)\"$/ do |number, selector, value|\n evaluate_script \"jQuery('#{selector}:nth-child(#{number}) select option:contains(\\\"#{value}\\\")').selected() && true\"\nend\n\nGiven /^I fill with \"([^\"]*)\" in field with name \"([^\"]*)\" of table number \"([^\"]*)\" with class \"([^\"]*)\"$/ do |value, name, number, selector|\n evaluate_script \"jQuery('#{selector}:nth-child(#{number}) input[name=\\\"#{name}\\\"]').val('#{value}') && true\"\nend\n\nGiven /^I sleep for (\\d+) seconds$/ do |time|\n sleep time.to_i\nend\n\nGiven /^I am logged in as mpog_admin$/ do\n visit('/account/logout')\n user = User.find_by_login('admin_user')\n\n unless user\n user = User.new(:login => 'admin_user', :password => '123456', :password_confirmation => '123456', :email => '[email protected]')\n person = Person.new :name=>\"Mpog Admin\", :identifier=>\"mpog-admin\"\n user.person = person\n user.save!\n\n person.user_id = user.id\n person.save!\n\n user.activate\n e = Environment.default\n e.add_admin(user.person)\n end\n\n visit('/account/login')\n fill_in(\"Username\", :with => user.login)\n fill_in(\"Password\", :with => '123456')\n click_button(\"Log in\")\nend\n\nGiven /^I should see \"([^\"]*)\" before \"([^\"]*)\"$/ do |before, after|\n expect(page.body.index(\"#{before}\")).to be < page.body.index(\"#{after}\")\nend\n\nGiven /^I keyup on selector \"([^\"]*)\"$/ do |selector|\n selector_founded = evaluate_script(\"jQuery('#{selector}').trigger('keyup').length != 0\")\n selector_founded.should be true\nend\n\nThen /^there should be (\\d+) divs? with class \"([^\"]*)\"$/ do |count, klass|\n should have_selector(\"div.#{klass}\", :count => count)\nend\n\nThen /^I should see \"([^\"]*)\" in \"([^\"]*)\" field$/ do |content, field|\n should have_field(field, :with => content)\nend\n\nGiven /^I should see \"([^\"]*)\" in the page/ do |message|\n expect(page.body =~ /#{message}/).not_to be nil\nend\n"
},
{
"alpha_fraction": 0.6756756901741028,
"alphanum_fraction": 0.6873630285263062,
"avg_line_length": 36,
"blob_id": "9a0867ec5f1094226e008d401bee5b4ee82e2025",
"content_id": "649a2f1341e1c4c9ee3d7debc59e140686052953",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1369,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 37,
"path": "/src/noosfero-spb/Makefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "PACKAGE = noosfero-spb\nVERSION = $(shell cat VERSION)\nDISTDIR = $(PACKAGE)-$(VERSION)\nTARBALL = $(DISTDIR).tar.gz\n\nall:\n\t@echo Nothing to be $@, all good.\n\nplugins_dir=/usr/lib/noosfero/plugins\nthemes_dir=/usr/lib/noosfero/public/designs/themes\nnoosfero_dir=/usr/lib/noosfero\n\ndist: clean\n\tmkdir -p dist/$(DISTDIR)\n\ttar --exclude=.git --exclude=$(DISTDIR) -cf - * | (cd dist/$(DISTDIR) && tar xaf -)\n\tcd dist/ && tar --exclude=.git -czf $(TARBALL) $(DISTDIR)\n\t$(RM) -r $(DISTDIR)\n\nclean:\n\t$(RM) -r dist/\n\ninstall:\n\tinstall -d -m 0755 $(DESTDIR)/$(plugins_dir)/software_communities\n\tcp -vr software_communities/* $(DESTDIR)/$(plugins_dir)/software_communities/\n\tinstall -d -m 0755 $(DESTDIR)/$(plugins_dir)/spb_migrations\n\tcp -vr spb_migrations/* $(DESTDIR)/$(plugins_dir)/spb_migrations/\n\tinstall -d -m 0755 $(DESTDIR)/$(themes_dir)/noosfero-spb-theme\n\tcp -vr noosfero-spb-theme/* $(DESTDIR)/$(themes_dir)/noosfero-spb-theme/\n\tinstall -d -m 0755 $(DESTDIR)/$(plugins_dir)/gov_user\n\tcp -vr gov_user/* $(DESTDIR)/$(plugins_dir)/gov_user/\n\tcd $(DESTDIR)/$(plugins_dir)/software_communities/ && \\\n\tmkdir -p locale/pt/LC_MESSAGES && \\\n\tmsgfmt -o locale/pt/LC_MESSAGES/software_communities.mo po/pt/software_communities.po\n\tcd ..\n\tcd $(DESTDIR)/$(plugins_dir)/gov_user/ && \\\n\tmkdir -p locale/pt/LC_MESSAGES && \\\n\tmsgfmt -o locale/pt/LC_MESSAGES/gov_user.mo po/pt/gov_user.po\n"
},
{
"alpha_fraction": 0.709382176399231,
"alphanum_fraction": 0.7170099020004272,
"avg_line_length": 36.10377502441406,
"blob_id": "f3af1a59ef1c4e95eceab9bc396b049c219229b7",
"content_id": "1bd0654583cbd650a0d7b449d2615af691d69adf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3933,
"license_type": "no_license",
"max_line_length": 188,
"num_lines": 106,
"path": "/src/noosfero-spb/software_communities/test/functional/software_communities_plugin_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire File.dirname(__FILE__) + '/../../controllers/software_communities_plugin_controller'\n\nclass SoftwareCommunitiesPluginController; def rescue_action(e) raise e end; end\n\nclass SoftwareCommunitiesPluginControllerTest < ActionController::TestCase\n def setup\n @admin = create_user(\"adminuser\").person\n @admin.stubs(:has_permission?).returns(\"true\")\n @controller.stubs(:current_user).returns(@admin.user)\n\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.add_admin(@admin)\n @environment.save\n\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"CC-GPL-V2\", :link=>\"http://creativecommons.org/licenses/GPL/2.0/legalcode.pt\")\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"Academic Free License 3.0 (AFL-3.0)\", :link=>\"http://www.openfoundry.org/en/licenses/753-academic-free-license-version-30-afl\")\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"Apache License 2.0 (Apache-2.0)\", :link=>\"http://www.apache.org/licenses/LICENSE-2.0\")\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>'BSD 2-Clause \"Simplified\" or \"FreeBSD\" License (BSD-2-Clause)', :link=>\"http://opensource.org/licenses/BSD-2-Clause\")\n\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name =>\"Java\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name =>\"Ruby\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name =>\"C\")\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name =>\"C++\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"PostgreSQL\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"MySQL\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"MongoDB\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"Oracle\")\n SoftwareCommunitiesPlugin::OperatingSystemName.create(:name=>\"Debian\")\n\n @response = ActionController::TestResponse.new\n end\n\n should 'return the licenses datas' do\n xhr :get, :get_license_data, :query => \"\"\n\n licenses = JSON.parse(@response.body)\n\n assert_equal 4, licenses.count\n end\n\n should 'return licenses that has Free on their version name' do\n xhr :get, :get_license_data, :query => \"Free\"\n\n licenses = JSON.parse(@response.body)\n\n assert_equal 2, licenses.count\n end\n\n should 'return no licenses that has Common on their version name' do\n xhr :get, :get_license_data, :query => \"Common\"\n\n licenses = JSON.parse(@response.body)\n\n assert_equal 0, licenses.count\n end\n\n should 'return the programming languages' do\n xhr :get, :get_field_data, :query => \"\", :field => \"software_language\"\n\n languages = JSON.parse(@response.body)\n\n assert_equal 4, languages.count\n end\n\n should 'return the programming languages that has C on their name' do\n xhr :get, :get_field_data, :query => \"C\", :field => \"software_language\"\n\n languages = JSON.parse(@response.body)\n\n assert_equal 2, languages.count\n end\n\n should 'dont return the programming languages that has HTML on their name' do\n xhr :get, :get_field_data, :query => \"HTML\", :field => \"software_language\"\n\n languages = JSON.parse(@response.body)\n\n assert_equal 1, languages.count\n end\n\n should 'return the databases' do\n xhr :get, :get_field_data, :query => \"\", :field => \"software_database\"\n\n databases = JSON.parse(@response.body)\n\n assert_equal 4, databases.count\n end\n\n should 'return the databases that has SQL on their name' do\n xhr :get, :get_field_data, :query => \"SQL\", :field => \"software_database\"\n\n databases = JSON.parse(@response.body)\n\n assert_equal 3, databases.count\n end\n\n should 'dont return the database that has on their name' do\n xhr :get, :get_field_data, :query => \"Cache\", :field => \"software_database\"\n\n databases = JSON.parse(@response.body)\n\n assert_equal 1, databases.count\n end\nend\n"
},
{
"alpha_fraction": 0.5807175040245056,
"alphanum_fraction": 0.605381190776825,
"avg_line_length": 19.227272033691406,
"blob_id": "b881ddd3bf184d2a76542f76e0a28e71b0f414c6",
"content_id": "fee9275bfe8e886df24abea4cdc9269caa982f89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 22,
"path": "/test/test_helper.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "export PATH=\"$(dirname $0)/bin:$PATH\"\nexport ROOTDIR=\"$(dirname $0)/..\"\nif [ -z \"$SPB_ENV\" ]; then\n export SPB_ENV='local'\nfi\n\nrun_on() {\n local vm=\"$1\"\n shift\n echo 'export PATH=/vagrant/test/bin:$PATH;' \"$@\" | ssh -F config/$SPB_ENV/ssh_config \"$vm\"\n}\n\nload_shunit2() {\n if [ -e /usr/share/shunit2/shunit2 ]; then\n . /usr/share/shunit2/shunit2\n else\n . shunit2\n fi\n}\n\n. $(dirname $0)/ip_helper.sh\n. $(dirname $0)/config_helper.sh\n\n"
},
{
"alpha_fraction": 0.7605633735656738,
"alphanum_fraction": 0.7605633735656738,
"avg_line_length": 16.75,
"blob_id": "0ed8f2424ca218230f0622f405cca593bc9d6e53",
"content_id": "d484809a3c2b61b55036ea880a7827ab215bd3c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 71,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 4,
"path": "/utils/obs/checkout",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nosc checkout isv:spb:mailman-api\nosc checkout isv:spb:colab\n"
},
{
"alpha_fraction": 0.6563380360603333,
"alphanum_fraction": 0.6563380360603333,
"avg_line_length": 19.882352828979492,
"blob_id": "fe0f15b2db46b4f0cecc6d44a8050394d3287243",
"content_id": "087fc62e1b2e3c2bafa3bc8d74bd290912fa93c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 355,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 17,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140528193816_add_extra_fields_to_user.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddExtraFieldsToUser < ActiveRecord::Migration\n def self.up\n change_table :users do |t|\n t.string :secondary_email\n t.references :institution\n t.string :role\n end\n end\n\n def self.down\n change_table :users do |t|\n t.remove :secondary_email\n t.remove_references :institution\n t.remove :role\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6636363863945007,
"alphanum_fraction": 0.6714285612106323,
"avg_line_length": 23.0625,
"blob_id": "9cdc94e29ebd5d4995961440f3eb6c99bf502143",
"content_id": "54ba91e9aa205efbe29f49ebe2327542a93b57b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 770,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 32,
"path": "/tasks/doc.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "desc 'Builds documentation (HTML)'\ntask :doc do\n sh 'make -C docs/ html'\nend\n\ndesc 'Builds documentation (PDF)'\ntask :pdf do\n sh 'make -C docs/ latexpdf'\nend\n\ndesc 'Opens PDF documentation'\ntask :viewpdf => :pdf do\n sh 'xdg-open', 'docs/_build/latex/softwarepublico.pdf'\nend\n\ndesc 'Publishes PDF'\ntask :pdfupload => :pdf do\n require 'date'\n\n tag = Date.today.strftime('doc-%Y-%m-%d-') + $SPB_ENV\n blob = `git hash-object -w docs/_build/latex/softwarepublico.pdf`.strip\n tree = `printf '100644 blob #{blob}\\tsoftwarepublico-#{$SPB_ENV}.pdf\\n' | git mktree`.strip\n commit = `git commit-tree -m #{tag} #{tree}`.strip\n\n sh 'git', 'tag', tag, commit\n sh 'git', 'push', 'origin', tag\nend\n\ndesc 'Removes generated files'\ntask :clean do\n sh 'make -C docs/ clean'\nend\n"
},
{
"alpha_fraction": 0.6450511813163757,
"alphanum_fraction": 0.660978376865387,
"avg_line_length": 25.66666603088379,
"blob_id": "c7e36bc823025309c47f04e29268736490a3b38f",
"content_id": "5f777e6d25b979b56391e08bca29fcac56ce0dcc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 879,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 33,
"path": "/src/noosfero-spb/gov_user/test/unit/governmental_power_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/institution_test_helper'\n\nclass GovernmentalPowerTest < ActiveSupport::TestCase\n\n def setup\n @gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n end\n\n def teardown\n Institution.destroy_all\n end\n\n should \"get public institutions\" do\n inst_name = \"Ministerio Publico da Uniao\"\n inst_cnpj = \"12.345.678/9012-45\"\n gov_power = GovernmentalPower.create(:name=>\"Some gov power\")\n InstitutionTestHelper.create_public_institution(\n inst_name,\n \"MPU\",\n \"BR\",\n \"DF\",\n \"Gama\",\n @juridical_nature,\n gov_power,\n @gov_sphere,\n inst_cnpj\n )\n\n assert_equal gov_power.public_institutions.count, PublicInstitution.count\n end\nend"
},
{
"alpha_fraction": 0.6338797807693481,
"alphanum_fraction": 0.6338797807693481,
"avg_line_length": 15.636363983154297,
"blob_id": "4e34cf2f199da7e90239c6099ac18b670e951e82",
"content_id": "0de7903bf5f740b33e093bf999b43daa1e1f5201",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 183,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 11,
"path": "/src/noosfero-spb/software_communities/Rakefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "task :default => :makemo\n\ntask :makemo do\n require 'gettext'\n require 'gettext/tools'\n GetText.create_mofiles(\n verbose: true,\n po_root: 'po',\n mo_root: 'locale',\n )\nend\n"
},
{
"alpha_fraction": 0.761904776096344,
"alphanum_fraction": 0.761904776096344,
"avg_line_length": 11,
"blob_id": "7a78c0866a8adeac0c3eb6f8c88c7590dee2db4e",
"content_id": "ec3d6b89b82fb289d984012f3f4f7db62069179d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 84,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 7,
"path": "/src/noosfero-spb/gov_user/lib/ext/user.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'user'\n\nclass User\n\n has_and_belongs_to_many :institutions\n\nend\n"
},
{
"alpha_fraction": 0.7664042115211487,
"alphanum_fraction": 0.7664042115211487,
"avg_line_length": 41.33333206176758,
"blob_id": "fd82f9fa98e23598c10ec73ea20808c64e56638f",
"content_id": "712c1402bad7c15a541f47062719f9ab4292a0f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 381,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 9,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/download.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::Download < ActiveRecord::Base\n self.table_name = \"software_communities_downloads\"\n attr_accessible :name, :link, :software_description, :minimum_requirements, :size, :total_downloads, :download_block\n\n belongs_to :download_block\n\n validates_presence_of :name, :link, :size\n validates :total_downloads, numericality: { only_integer: true }\nend\n"
},
{
"alpha_fraction": 0.6902173757553101,
"alphanum_fraction": 0.6929348111152649,
"avg_line_length": 39.88888931274414,
"blob_id": "6a100726407b44d4f63349712f6a0c0b839406eb",
"content_id": "4362838f41d0148c97020956ebd03c7e5d38d4f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 736,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 18,
"path": "/test/reverse_proxy_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_redirect_http_to_https() {\n local redirect=\"$(curl --header 'Host: softwarepublico.dev' --head http://$reverseproxy/ | grep-header Location)\"\n assertEquals \"Location: https://softwarepublico.dev/\" \"$redirect\"\n}\n\ntest_reverse_proxy_to_colab() {\n local title=\"$(curl --header 'Host: softwarepublico.dev' https://$reverseproxy/dashboard | grep '<title>' | sed -e 's/^\\s*//')\"\n assertEquals \"<title>Home - Colab</title>\" \"$title\"\n}\n\ntest_reverse_proxy_for_mailman() {\n local title=\"$(curl --location --header 'Host: listas.softwarepublico.dev' --insecure https://$reverseproxy/ | grep -i '<title>')\"\n assertEquals \"<TITLE>listas.softwarepublico.dev Mailing Lists</TITLE>\" \"$title\"\n}\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.7419354915618896,
"alphanum_fraction": 0.7419354915618896,
"avg_line_length": 26.125,
"blob_id": "e836a06b13bff558304c141f63dd0390cb696354",
"content_id": "f91f69cddd8e461b23b57d4af3edf841ea915cf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 217,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 8,
"path": "/cookbooks/mezuro/recipes/repo.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# Getting the mezuro RPM's packages\npackage 'wget'\n\nexecute 'download:mezuro' do\n command 'wget https://bintray.com/mezurometrics/rpm/rpm -O bintray-mezurometrics-rpm.repo'\n cwd '/etc/yum.repos.d'\n user 'root'\nend\n"
},
{
"alpha_fraction": 0.6910659670829773,
"alphanum_fraction": 0.7030336856842041,
"avg_line_length": 41.77381134033203,
"blob_id": "9a76f67f3e83ec34fa70e6f27e416bebed6a0da4",
"content_id": "7bf19162e651cac88697277aff3b43fb97bf7374",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3593,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 84,
"path": "/src/noosfero-spb/software_communities/test/functional/organization_ratings_plugin_profile_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire 'organization_ratings_plugin_profile_controller'\nrequire File.dirname(__FILE__) + '/../helpers/software_test_helper'\n\n# Re-raise errors caught by the controller.\nclass OrganizationRatingsPluginProfileController; def rescue_action(e) raise e end; end\n\nclass OrganizationRatingsPluginProfileControllerTest < ActionController::TestCase\n include SoftwareTestHelper\n\n def setup\n @controller = OrganizationRatingsPluginProfileController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n\n @environment = Environment.default\n @environment.enabled_plugins = ['OrganizationRatingsPlugin']\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.save\n\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version=>\"CC-GPL-V2\",\n :link=>\"http://creativecommons.org/licenses/GPL/2.0/legalcode.pt\")\n\n @person = create_user('testuser').person\n @software = create_software(software_fields)\n @statistic_block = SoftwareCommunitiesPlugin::StatisticBlock.new\n @software.community.blocks << @statistic_block\n @software.community.save!\n\n login_as(@person.identifier)\n @controller.stubs(:logged_in?).returns(true)\n @controller.stubs(:current_user).returns(@person.user)\n end\n\n test \"should create a task with a valid benefited people value and no comment\" do\n assert_difference 'CreateOrganizationRatingComment.count' do\n post :new_rating, profile: @software.community.identifier, :comments => {:body => \"\"},\n :organization_rating_value => 3, :organization_rating => {:people_benefited => 50}\n end\n end\n\n test \"should create a task with a valid saved value and no comment\" do\n assert_difference 'CreateOrganizationRatingComment.count' do\n post :new_rating, profile: @software.community.identifier, :comments => {:body => \"po\"},\n :organization_rating_value => 3, :organization_rating => {:saved_value => 50000000}\n end\n end\n\n test \"should not create a task with no saved value or benefited poeple, and no comment\" do\n assert_no_difference 'CreateOrganizationRatingComment.count' do\n post :new_rating, profile: @software.community.identifier, :comments => {:body => \"\"},\n :organization_rating_value => 3, :organization_rating => nil\n end\n end\n\n test \"software statistics should be updated when task is accepted\" do\n @software.reload\n assert_equal 0, @software.benefited_people\n assert_equal 0.0, @software.saved_resources\n\n post :new_rating, profile: @software.community.identifier, :comments => {:body => \"po\"},\n :organization_rating_value => 3, :organization_rating => {:saved_value => 500, :people_benefited => 10}\n\n CreateOrganizationRatingComment.last.finish\n @software.reload\n assert_equal 10, @software.benefited_people\n assert_equal 500.0, @software.saved_resources\n end\n\n test \"software statistics should not be updated when task is cancelled\" do\n @software.reload\n assert_equal 0, @software.benefited_people\n assert_equal 0.0, @software.saved_resources\n\n post :new_rating, profile: @software.community.identifier, :comments => {:body => \"Body\"},\n :organization_rating_value => 3,\n :organization_rating => {:saved_value => 500, :people_benefited => 10}\n\n CreateOrganizationRatingComment.last.cancel\n @software.reload\n assert_equal 0, @software.benefited_people\n assert_equal 0.0, @software.saved_resources\n end\nend\n"
},
{
"alpha_fraction": 0.7204682230949402,
"alphanum_fraction": 0.7343029379844666,
"avg_line_length": 38.69013977050781,
"blob_id": "9343cae9cd61728ca96476e2c47380232c637aaa",
"content_id": "a2adad3bd14cf119e7de4fd777f0fe415df20cdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2819,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 71,
"path": "/src/noosfero-spb/gov_user/test/unit/organization_rating_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.expand_path(File.dirname(__FILE__)) + '/../../../../test/test_helper'\nrequire File.expand_path(File.dirname(__FILE__)) + '/../helpers/plugin_test_helper'\n\nclass OrganizationRatingTest < ActiveSupport::TestCase\n include PluginTestHelper\n\n def setup\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.save\n end\n\n should \"not validate organization rating if the institution is not saved\" do\n person = fast_create(Person)\n community = fast_create(Community)\n\n private_institution = build_private_institution \"Some Institution\", \"Some Inst Incorporated\", \"11.222.333/4444-55\"\n community_rating = OrganizationRating.new(:person => person, :value => 3, :organization => community, :institution => private_institution)\n\n assert_equal false, community_rating.valid?\n assert_equal true, community_rating.errors.messages.keys.include?(:institution)\n end\n\n should \"validate organization rating if the institution is saved\" do\n person = fast_create(Person)\n community = fast_create(Community)\n\n private_institution = build_private_institution \"Some Institution\", \"Some Inst Incorporated\", \"11.222.333/4444-55\"\n community_rating = OrganizationRating.new(:person => person, :value => 3, :organization => community, :institution => private_institution)\n private_institution.save\n\n assert_equal true, community_rating.valid?\n assert_equal false, community_rating.errors.messages.keys.include?(:institution)\n end\n\n should \"not create organization rating with saved value and no institution\" do\n person = fast_create(Person)\n community = fast_create(Community)\n\n community_rating = OrganizationRating.new(:person => person, :value => 3, :organization => community, :institution => nil)\n community_rating.saved_value = \"2000\"\n\n assert_equal false, community_rating.save\n assert_equal true, community_rating.errors.messages.keys.include?(:institution)\n end\n\n should \"not create organization rating with benefited people value and no institution\" do\n person = fast_create(Person)\n community = fast_create(Community)\n\n community_rating = OrganizationRating.new(:person => person, :value => 3, :organization => community, :institution => nil)\n community_rating.people_benefited = \"100\"\n\n assert_equal false, community_rating.save\n assert_equal true, community_rating.errors.messages.keys.include?(:institution)\n end\n\n private\n\n def build_private_institution name, corporate_name, cnpj, country=\"AR\"\n community = Community.new :name => name\n community.country = country\n\n institution = PrivateInstitution.new :name=> name\n institution.corporate_name = corporate_name\n institution.cnpj = cnpj\n institution.community = community\n\n institution\n end\nend\n\n"
},
{
"alpha_fraction": 0.6635611057281494,
"alphanum_fraction": 0.6863353848457336,
"avg_line_length": 20.93181800842285,
"blob_id": "8e2ad7ae7485f83ce3f2978104ab038f20f7ef6e",
"content_id": "379dcbe1cd63c834d2b88376ac7898cae3abb3f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 966,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 44,
"path": "/cookbooks/reverse_proxy/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "\ncookbook_file \"/etc/nginx/#{node['config']['external_hostname']}.crt\" do\n owner 'root'\n group 'root'\n mode 0600\n notifies :restart, 'service[nginx]'\nend\n\ncookbook_file \"/etc/sysctl.d/ip_forward.conf\" do\n owner 'root'\n group 'root'\n mode 0644\nend\n\nexecute 'sysctl -w net.ipv4.ip_forward=1' do\n not_if 'is-a-container'\nend\n\ncookbook_file \"/etc/nginx/#{node['config']['external_hostname']}.key\" do\n owner 'root'\n group 'root'\n mode 0600\n notifies :restart, 'service[nginx]'\nend\n\ntemplate '/etc/nginx/conf.d/reverse_proxy.conf' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\nend\n\ntemplate '/etc/nginx/conf.d/redirect.conf' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\n only_if { node['config']['alternative_hostnames'] }\nend\n\nfile '/etc/nginx/conf.d/redirect.conf' do\n action :delete\n notifies :restart, 'service[nginx]'\n not_if { node['config']['alternative_hostnames'] }\nend\n"
},
{
"alpha_fraction": 0.6796116232872009,
"alphanum_fraction": 0.6796116232872009,
"avg_line_length": 18.486486434936523,
"blob_id": "781ce64e43633d5983267baa0fd9751b1f74cbb1",
"content_id": "f342a2b954d70bc4c83d422d46c87a02c57ba904",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 721,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 37,
"path": "/src/noosfero-spb/gov_user/public/lib/select-element.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\nmodulejs.define('SelectElement', function() {\n 'use strict';\n\n\n function SelectElement(name, id) {\n this.select = document.createElement(\"select\");\n }\n\n\n SelectElement.prototype.setAttr = function(attr, value) {\n return this.select.setAttribute(attr, value);\n };\n\n\n SelectElement.prototype.addOption = function(option) {\n return this.select.add(option);\n };\n\n\n SelectElement.prototype.getSelect = function() {\n return this.select;\n };\n\n\n SelectElement.generateOption = function(value, text) {\n var option;\n option = document.createElement(\"option\");\n option.setAttribute(\"value\", value);\n option.text = text;\n return option;\n };\n\n\n return SelectElement;\n});\n"
},
{
"alpha_fraction": 0.6178489923477173,
"alphanum_fraction": 0.6205533742904663,
"avg_line_length": 25.700000762939453,
"blob_id": "5093affc9e30b447e7f637a90db01c79f13fa6bf",
"content_id": "6bf82da78ad92aa35bfc9301031d6bac95d34936",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4807,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 180,
"path": "/src/noosfero-spb/software_communities/public/views/search-software-catalog.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('SearchSoftwareCatalog', ['jquery', 'NoosferoRoot', 'SoftwareCatalogComponent'], function($, NoosferoRoot, SoftwareCatalogComponent) {\n 'use strict';\n\n var AJAX_URL = {\n software_infos:\n NoosferoRoot.urlWithSubDirectory(\"/search/software_infos\"),\n sisp:\n NoosferoRoot.urlWithSubDirectory(\"/search/sisp\"),\n };\n\n\n function dispatch_search_ajax(enable_load) {\n var search_params = get_search_params();\n var full_url = window.location.href;\n var url = AJAX_URL.software_infos;\n if(full_url.indexOf(\"search/sisp\") > -1){\n url = AJAX_URL.sisp;\n }\n\n if(enable_load) {\n open_loading(\"Loading\");\n }\n\n $.ajax({\n url: url,\n type: \"GET\",\n data: search_params,\n success: update_search_page_on_ajax,\n error: function(){\n close_loading();\n }\n });\n }\n\n\n function get_search_params() {\n var params = {};\n\n params.query = $(\"#search-input\").val();\n params.selected_categories_id = [];\n\n $(\".categories-catalog:checked\").each(function(index, element) {\n params.selected_categories_id.push(element.value);\n });\n\n params.software_display = $(\"#software_display\").val();\n params.sort = $(\"#sort\").val();\n\n if($(\"#all_radio_button\").is(\":checked\")) {\n params.software_type = $(\"#all_radio_button\").val();\n } else {\n params.software_type = $(\"#public_software_radio_button\").val();\n }\n\n params.only_softwares = $(\"#only_softwares_hidden\").val().split(' ');\n\n return params;\n }\n\n\n function get_result_div_core(message) {\n $(\"#search-results-empty\").html(message);\n }\n\n\n function catalog_message() {\n var empty_result = $('#empty_result').val() === 'true';\n var user_selected_categories = $('.categories-catalog:checked').length !== 0;\n\n if(empty_result && !user_selected_categories) {\n get_result_div_core($('#message-no-catalog-selected').val());\n } else if (empty_result && user_selected_categories) {\n get_result_div_core($('#message-catalog-selected').val());\n }\n }\n\n\n function update_search_page_on_ajax(response) {\n response = $(response);\n\n var search_list = $(\"#search-results\");\n var selected_categories_field = $(\"#filter-categories-select-catalog\");\n var pagination = $(\"#software-pagination\");\n var software_count = $(\"#software-count\");\n var individually_category = $(\"#individually-category\");\n\n var result_list = response.find(\"#search-results\").html();\n var result_categories = response.find(\"#filter-categories-select-catalog\").html();\n var result_pagination = response.find(\"#software-pagination\").html();\n var result_software_count = response.find(\"#software-count\").html();\n var result_individually_category = response.find(\"#individually-category\").html();\n\n search_list.html(result_list);\n selected_categories_field.html(result_categories);\n pagination.html(result_pagination);\n software_count.html(result_software_count);\n individually_category.html(result_individually_category);\n\n highlight_searched_terms();\n catalog_message();\n\n hide_load_after_ajax();\n }\n\n\n function hide_load_after_ajax() {\n if ($(\"#overlay_loading_modal\").is(\":visible\")) {\n close_loading();\n setTimeout(hide_load_after_ajax, 1500);\n }\n }\n\n\n function highlight_searched_terms() {\n var searched_terms = $(\"#search-input\").val();\n\n if( searched_terms.length === 0 ) {\n return undefined;\n }\n\n var content_result = $(\".search-content-result\");\n var regex = new RegExp(\"(\"+searched_terms.replace(/\\s/g, \"|\")+\")\", \"gi\");\n\n content_result.each(function(i, e){\n var element = $(e);\n\n var new_text = element.text().replace(regex, function(text) {\n return \"<strong>\"+text+\"</strong>\";\n });\n\n element.html(new_text);\n });\n }\n\n\n function update_page_by_ajax_on_select_change() {\n dispatch_search_ajax(true);\n }\n\n function update_page_by_text_filter() {\n var text = this.value;\n dispatch_search_ajax(false);\n }\n\n\n function search_input_keyup() {\n var timer = null;\n\n $(\"#search-input\").keyup(function() {\n // Only start the search(with ajax) after 3 characters\n if(this.value.length >= 3) {\n timer = setTimeout(update_page_by_text_filter, 400);\n }\n }).keydown(function() {\n clearTimeout(timer);\n });\n }\n\n\n function set_events() {\n $(\"#software_display\").change(update_page_by_ajax_on_select_change);\n $(\"#sort\").change(update_page_by_ajax_on_select_change);\n\n search_input_keyup();\n }\n\n\n return {\n isCurrentPage: function() {\n return $('#software-search-container').length === 1;\n },\n\n\n init: function() {\n set_events();\n catalog_message();\n SoftwareCatalogComponent.init(dispatch_search_ajax);\n }\n }\n});\n\n"
},
{
"alpha_fraction": 0.7200000286102295,
"alphanum_fraction": 0.7272727489471436,
"avg_line_length": 24,
"blob_id": "3819866f12a5a0746debe8d27b1c266a44e1082a",
"content_id": "8045f53f5e90c877fda77414f9e653723e2cea65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 275,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 11,
"path": "/test/redis_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_redis_running() {\n assertTrue \"redis running\" 'run_on database pgrep -f redis'\n}\n\ntest_redis_listens_on_local_network() {\n assertTrue 'redis listening on local network' 'run_on integration redis-cli -h database get foo'\n}\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.7350993156433105,
"alphanum_fraction": 0.7384105920791626,
"avg_line_length": 30.736841201782227,
"blob_id": "629566d94d9c325f3dc33c9ab3dcdc3da00a270f",
"content_id": "fe16ddd708c0679138bd4fa81e3db2b96d98f3d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 19,
"path": "/test/postgresql_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_postgresql_running() {\n assertTrue 'PostgreSQL running' 'run_on database pgrep -fa postgres'\n}\n\ntest_colab_database_created() {\n assertTrue 'colab database created in PostgreSQL' 'run_on database sudo -u postgres -i psql colab < /dev/null'\n}\n\ntest_gitlab_database_created() {\n assertTrue 'gitlab database created in PostgreSQL' 'run_on database sudo -u postgres -i psql gitlab < /dev/null'\n}\n\ntest_noosfero_database_created() {\n assertTrue 'noosfero database created in PostgreSQL' 'run_on database sudo -u postgres -i psql noosfero < /dev/null'\n}\n\nload_shunit2\n\n"
},
{
"alpha_fraction": 0.7352941036224365,
"alphanum_fraction": 0.7366310358047485,
"avg_line_length": 43,
"blob_id": "05450820ca04a7cd9e1173071b3c7d9b51e53522",
"content_id": "fb8ca6a128481d54a626660a5a5a4807a6e43c50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 757,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 17,
"path": "/src/noosfero-spb/gov_user/db/migrate/20160112174948_applies_accentuation_on_models_without_them.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#encoding: utf-8\n\nclass AppliesAccentuationOnModelsWithoutThem < ActiveRecord::Migration\n def up\n execute \"UPDATE governmental_powers SET name = 'Judiciário' WHERE name = 'Judiciario'\"\n execute \"UPDATE governmental_powers SET name = 'Não se Aplica' WHERE name = 'Nao se Aplica'\"\n\n execute \"UPDATE juridical_natures SET name = 'Administração Direta' WHERE name = 'Administracao Direta'\"\n execute \"UPDATE juridical_natures SET name = 'Empresa Pública' WHERE name = 'Empresa Publica'\"\n execute \"UPDATE juridical_natures SET name = 'Fundação' WHERE name = 'Fundacao'\"\n execute \"UPDATE juridical_natures SET name = 'Orgão Autônomo' WHERE name = 'Orgao Autonomo'\"\n end\n\n def down\n say \"This migration has no back state\"\n end\nend\n"
},
{
"alpha_fraction": 0.6433054208755493,
"alphanum_fraction": 0.6438284516334534,
"avg_line_length": 38.020408630371094,
"blob_id": "3a0584aefd338769f8973abc2947a06bae683acb",
"content_id": "71ffedc6d489d67ec09d8848e36ba132f0f37e18",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1912,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 49,
"path": "/src/Makefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "VERSION = $(shell cat ../VERSION)\nsubdirs = colab-spb-plugin colab-spb-theme-plugin noosfero-spb\n\ndist_all = $(patsubst %, %-dist, $(subdirs))\ndist: $(dist_all)\n$(dist_all): %-dist : %\n\tif [ -f $*/Makefile ]; then make -C $* dist; fi\n\tif [ -f $*/setup.py ]; then (cd $* && python setup.py sdist); fi\n\nclean_all = $(patsubst %, %-clean, $(subdirs))\nclean: $(clean_all)\n\t$(MAKE) -C pkg-rpm/ clean\n\n$(clean_all): %-clean : %\n\tif [ -f $*/Makefile ]; then make -C $* clean; fi\n\tif [ -f $*/setup.py ]; then rm -rf $*/dist; fi\n\nrelease:\n\t@if git tag | grep -q '^v$(VERSION)$$'; then \\\n\t\techo \"E: version $(VERSION) already tagged. You need a new version number\"; \\\n\t\tfalse; \\\n\tfi\n\techo '$(VERSION)' > colab-spb-plugin/VERSION\n\techo '$(VERSION)' > colab-spb-theme-plugin/VERSION\n\techo '$(VERSION)' > noosfero-spb/VERSION\n\t$(MAKE) dist\n\tcp noosfero-spb/dist/*.tar.* pkg-rpm/noosfero-spb/\n\tcp colab-spb-theme-plugin/dist/*.tar.* pkg-rpm/colab-spb-theme/\n\tcp colab-spb-plugin/dist/*.tar.* pkg-rpm/colab-spb-plugin/\n\tsed -i -e 's/^\\(Version:\\s*\\).*/\\1$(VERSION)/' \\\n\t\tpkg-rpm/colab-spb-theme/colab-spb-theme.spec \\\n\t\tpkg-rpm/colab-spb-plugin/colab-spb-plugin.spec \\\n\t\tpkg-rpm/noosfero-spb/noosfero-spb.spec\n\tgit diff\n\t@printf \"Confirm release? [y/N]\"; \\\n\t\tread confirm; \\\n\t\tif [ \"$$confirm\" = 'y' -o \"$$confirm\" = 'Y' ]; then \\\n\t\t\techo \"SPB release $(VERSION)\" > .commit_template; \\\n\t\t\tgit commit * --file .commit_template; \\\n\t\t\trm -f .commit_template; \\\n\t\telse \\\n\t\t\techo 'Aborting at your request!'; \\\n\t\t\tgit checkout -- colab-spb-theme-plugin/VERSION noosfero-spb/VERSION colab-spb-plugin/VERSION ; \\\n\t\t\tgit checkout -- pkg-rpm/colab-spb-theme/ pkg-rpm/noosfero-spb/ pkg-rpm/colab-spb-plugin/ ; \\\n\t\t\tfalse; \\\n\t\tfi\n\t# TODO add pkg-rpm/colab-spb-plugin to the git checkout all above\n\t$(MAKE) -C pkg-rpm/ noosfero-spb-upload colab-spb-theme-upload colab-spb-plugin-upload\n\tgit tag $(VERSION) -s -m 'SPB Release $(VERSION)'\n"
},
{
"alpha_fraction": 0.7382413148880005,
"alphanum_fraction": 0.7464212775230408,
"avg_line_length": 31.600000381469727,
"blob_id": "f094864953fbd18a18d4dcc908c6914198b5a2b0",
"content_id": "cfa77354bce88b0455e1942ec7b0a3b75f2f4563",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 489,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 15,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_language.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareLanguage < ActiveRecord::Base\n\n belongs_to :software_info, :class_name => \"SoftwareCommunitiesPlugin::SoftwareInfo\"\n belongs_to :programming_language, :class_name => \"SoftwareCommunitiesPlugin::ProgrammingLanguage\"\n\n attr_accessible :version\n\n validates_length_of(\n :version,\n :maximum => 20,\n :too_long => _(\"Software language is too long (maximum is 20 characters)\")\n )\n\n validates_presence_of :version, :programming_language\nend\n"
},
{
"alpha_fraction": 0.7350993156433105,
"alphanum_fraction": 0.7350993156433105,
"avg_line_length": 59.400001525878906,
"blob_id": "7844ec0a2f0b920400deb34240d2b65f8cb4159e",
"content_id": "512c9a1d2738a34ef3a97223f42739fcef3a9a40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 302,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 5,
"path": "/cookbooks/email/recipes/destination.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "execute 'postfix::set_as_final_destination' do\n command \"postconf mydestination='$myhostname, localhost.$mydomain, localhost, #{node['config']['external_hostname']}'\"\n not_if \"grep mydestination.*#{node['config']['external_hostname']} /etc/postfix/main.cf\"\n notifies :reload, 'service[postfix]'\nend\n"
},
{
"alpha_fraction": 0.6215384602546692,
"alphanum_fraction": 0.6246153712272644,
"avg_line_length": 12.541666984558105,
"blob_id": "e2ddc0057543c1d8f84ebeac55c332f1bd7309cb",
"content_id": "2ccb9a280e4e0a3b8c2fc15051d3e4ffc2ba5cd5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 325,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 24,
"path": "/src/noosfero-spb/software_communities/lib/ext/person.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: utf-8\n\nrequire_dependency 'person'\n\nclass Person\n\n delegate :login, :to => :user, :prefix => true\n\n def software?\n false\n end\n\n def softwares\n softwares = []\n self.communities.each do |community|\n if community.software?\n softwares << community\n end\n end\n\n softwares\n end\n\nend\n"
},
{
"alpha_fraction": 0.5649051070213318,
"alphanum_fraction": 0.566957414150238,
"avg_line_length": 26.45070457458496,
"blob_id": "c53c5550e0f32c40d19ad21f0d52126f213ced9f",
"content_id": "8ef8f5960d70f28a557338ace0361f2702bdaf5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1949,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 71,
"path": "/src/noosfero-spb/gov_user/lib/institutions_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class InstitutionsBlock < CommunitiesBlock\n\n def self.description\n _('Institutions')\n end\n\n def profile_count\n profile_list.count\n end\n\n def default_title\n n_('{#} institution', '{#} institutions', profile_count)\n end\n\n def help\n _('This block displays the institutions in which the user is a member.')\n end\n\n def footer\n owner = self.owner\n case owner\n when Profile\n lambda do |context|\n link_to s_('institutions|View all'), :profile => owner.identifier,\n :controller => 'profile', :action => 'communities',\n :type => 'Institution'\n end\n when Environment\n lambda do |context|\n link_to s_('institutions|View all'), :controller => 'search',\n :action => 'communities', :type => 'Institution'\n end\n else\n ''\n end\n end\n\n def profile_list\n result = get_visible_profiles\n\n result = result.select { |p| p.class == Community && p.institution? }\n\n result.slice(0..get_limit-1)\n end\n\n def profiles\n owner.communities\n end\n\n private\n\n def get_visible_profiles\n include_list = [:image,:domains,:preferred_domain,:environment]\n visible_profiles = profiles.visible.includes(include_list)\n\n if !prioritize_profiles_with_image\n visible_profiles.all(:limit => get_limit,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n elsif profiles.visible.with_image.count >= get_limit\n visible_profiles.with_image.all(:limit => get_limit * 5,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n else\n visible_profiles.with_image.sort_by{ rand } +\n visible_profiles.without_image.all(:limit => get_limit * 5,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n end\n end\nend\n"
},
{
"alpha_fraction": 0.5844635963439941,
"alphanum_fraction": 0.586004912853241,
"avg_line_length": 29.31775665283203,
"blob_id": "3db215e664f11d5acbc68b87f66865bc2b2a60ee",
"content_id": "9ec1ac4042d4ad96236f1c9c7860cdf66e6d8a60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3244,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 107,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/softwares_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwaresBlock < CommunitiesBlock\n\n settings_items :software_type, :default => \"All\"\n attr_accessible :accessor_id, :accessor_type, :role_id,\n :resource_id, :resource_type, :software_type\n\n def self.description\n _('Softwares')\n end\n\n def default_title\n if self.software_type == \"Generic\"\n return n_('{#} generic software', '{#} generic softwares', profile_count)\n elsif self.software_type == \"Public\"\n return n_('{#} public software', '{#} public softwares', profile_count)\n else\n return n_('{#} software', '{#} softwares', profile_count)\n end\n end\n\n def help\n _('This block displays the softwares in which the user is a member.')\n end\n\n def footer\n self.software_type ||= \"All\"\n owner = self.owner\n case owner\n when Profile\n lambda do |context|\n link_to s_('softwares|View all'), :profile => owner.identifier,\n :controller => 'profile', :action => 'communities',\n :type => 'Software'\n end\n when Environment\n lambda do |context|\n link_to s_('softwares|View all'), :controller => 'search',\n :action => 'software_infos'\n end\n else\n ''\n end\n end\n\n def profile_count\n profile_list.count\n end\n\n def profiles\n owner.communities\n end\n\n def profile_list\n profiles = get_visible_profiles\n\n software_profiles = profiles.select do |profile|\n profile.class == Community && profile.software?\n end\n\n block_softwares = if self.software_type == \"Public\"\n software_profiles.select { |profile| profile.software_info.public_software? }\n elsif self.software_type == \"Generic\"\n software_profiles.select { |profile| !profile.software_info.public_software? }\n else # All\n software_profiles\n end\n\n block_softwares.slice(0..get_limit-1)\n end\n\n def content(arg={})\n block = self\n if self.box.owner_type == \"Environment\" && self.box.position == 1\n proc do\n render :file => 'blocks/main_area_softwares',\n :locals => {:profiles=> block.profile_list(), :block => block}\n end\n else\n proc do\n render :file => 'blocks/side_area_softwares',\n :locals => {:profiles=> block.profile_list(), :block => block}\n end\n end\n end\n\n protected\n\n def get_visible_profiles\n profile_include_list = [:image, :domains, :preferred_domain, :environment]\n visible_profiles = profiles.visible.includes(profile_include_list)\n\n if !prioritize_profiles_with_image\n visible_profiles.all( :limit => get_limit,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n elsif profiles.visible.with_image.count >= get_limit\n visible_profiles.with_image.all( :limit => get_limit * 5,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n else\n visible_profiles.with_image.sort_by{ rand } +\n visible_profiles.without_image.all( :limit => get_limit * 5,\n :order => 'profiles.updated_at DESC'\n ).sort_by{ rand }\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6529752612113953,
"alphanum_fraction": 0.661927342414856,
"avg_line_length": 38.154640197753906,
"blob_id": "35d88ba7f24546bd678f07939101fdaae7ca6251",
"content_id": "978f53734f1aa5bd2eb19f4f2c5da75d6c3bef2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3798,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 97,
"path": "/src/noosfero-spb/software_communities/test/functional/software_communities_plugin_profile_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/software_test_helper'\nrequire File.dirname(__FILE__) + '/../../controllers/software_communities_plugin_profile_controller'\n\nclass SoftwareCommunitiesPluginProfileController; def rescue_action(e) raise e end; end\n\nclass SoftwareCommunitiesPluginProfileControllerTest < ActionController::TestCase\n include SoftwareTestHelper\n\n def setup\n @controller = SoftwareCommunitiesPluginProfileController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n\n @environment = Environment.default\n @environment.enable_plugin('SoftwareCommunitiesPlugin')\n @environment.save!\n\n SoftwareCommunitiesPlugin::LicenseInfo.create(\n :version=>\"CC-GPL-V2\",\n :link=>\"http://creativecommons.org/licenses/GPL/2.0/legalcode.pt\"\n )\n\n download_data = [{\n :name=>\"Google\",\n :link=>\"http://google.com\",\n :software_description=>\"all\",\n :minimum_requirements=>\"none\",\n :size=>\"?\",\n :total_downloads=>0\n }]\n\n @software = create_software(software_fields)\n @software.save!\n\n @download_block = SoftwareCommunitiesPlugin::DownloadBlock.new\n @download_block.downloads = download_data\n @download_block.save!\n\n @software.community.blocks << @download_block\n @software.community.save!\n end\n\n should 'redirect to download link with correct params' do\n SoftwareCommunitiesPlugin::DownloadBlock.any_instance.stubs(:environment).returns(@environment)\n get :download_file, :profile => @software.community.identifier,\n :block_id => @download_block.id, :download_id => @download_block.download_records.first.id\n\n assert_equal nil, session[:notice]\n assert_redirected_to @download_block.download_records.first.link\n end\n\n should \"notice when the download was not found\" do\n get :download_file, :profile => @software.community.identifier,\n :block_id => @download_block.id, :download_id => @download_block.download_records.first.id + 10\n\n assert_equal \"Could not find the download file\", session[:notice]\n end\n\n should \"display limited community events\" do\n @e1 = Event.new :name=>\"Event 1\", :body=>\"Event 1 body\",\n :start_date => DateTime.now,\n :end_date => (DateTime.now + 1.month)\n\n @e2 = Event.new :name=>\"Event 2\", :body=>\"Event 2 body\",\n :start_date => (DateTime.now + 10.days),\n :end_date => (DateTime.now + 11.days)\n\n @e3 = Event.new :name=>\"Event 3\", :body=>\"Event 3 body\",\n :start_date => (DateTime.now + 20.days),\n :end_date => (DateTime.now + 30.days)\n\n @software.community.events << @e1\n @software.community.events << @e2\n @software.community.events << @e3\n @software.community.save!\n\n events_block = SoftwareCommunitiesPlugin::SoftwareEventsBlock.new\n events_block.amount_of_events = 2\n events_block.display = \"always\"\n box = MainBlock.last.box\n events_block.box = box\n events_block.save!\n\n get :index, :profile=>@software.community.identifier\n assert_tag :tag => 'div', :attributes => { :class => 'software-community-events-block' }, :descendant => { :tag => 'a', :content => 'Event 1' }\n assert_tag :tag => 'div', :attributes => { :class => 'software-community-events-block' }, :descendant => { :tag => 'a', :content => 'Event 2' }\n assert_no_tag :tag => 'div', :attributes => { :class => 'software-community-events-block' }, :descendant => { :tag => 'a', :content => 'Event 3' }\n end\n\n should \"notice when given invalid download params\" do\n get :download_file, :profile => @software.community.identifier,\n :block_id => \"-3\", :download_id => \"-50\"\n\n assert_equal \"Invalid download params\", session[:notice]\n end\nend\n"
},
{
"alpha_fraction": 0.6652542352676392,
"alphanum_fraction": 0.6716101765632629,
"avg_line_length": 30.399999618530273,
"blob_id": "9477b8aedf12bc3b6e285771971ec22404d22f1b",
"content_id": "4de564a7c99e956dc6202821865b5f38276377c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 472,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 15,
"path": "/cookbooks/postgresql/recipes/colab.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "execute 'createuser:colab' do\n command 'createuser colab'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'colab';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:colab' do\n command 'createdb --owner=colab colab'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'colab';\"`.strip.to_i == 0\n end\nend\n\n"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 24.375,
"blob_id": "e3ca60414a34a3152f6ab1153827e9af7589decf",
"content_id": "e3f8e60004afdada495516cfe75f5dee02558184",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 203,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 8,
"path": "/roles/reverse_proxy_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'database_server'\ndescription 'Reverse proxy server'\nrun_list *[\n 'recipe[basics::nginx]',\n 'recipe[reverse_proxy]',\n 'recipe[reverse_proxy::mailman]',\n 'recipe[reverse_proxy::documentation]'\n]\n"
},
{
"alpha_fraction": 0.5663011074066162,
"alphanum_fraction": 0.5882353186607361,
"avg_line_length": 31.354839324951172,
"blob_id": "48c0ed445b4f703195d07cd9888ade8b097e07f5",
"content_id": "fc4d5eb606571d60eb54d353bc7718c643f4bc1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1003,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 31,
"path": "/script/gov_user_ci.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "GREEN='\\033[1;32m'\nRED='\\033[1;31m'\nNC='\\033[0m'\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"GovUserPlugin:UNITS${NC}\\n\"\nrake test:units TEST=plugins/gov_user/test/unit/*\nunits=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"GovUserPlugin:FUNCTIONALS${NC}\\n\"\nrake test:functionals TEST=plugins/gov_user/test/functional/*\nfunctionals=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"GovUserPlugin:SELENIUM${NC}\\n\"\nruby -S cucumber FEATURE=plugins/gov_user/features/* -p software_communities_selenium --format progress\nselenium=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"GovUserPlugin:CUCUMBER${NC}\\n\"\nruby -S cucumber FEATURE=plugins/gov_user/features/* -p software_communities --format progress\ncucumber=$?\n\nif [ $units -ne 0 ] || [ $functionals -ne 0 ] || [ $selenium -ne 0 ] || [ $cucumber -ne 0 ]; then\n\tprintf \"${RED}=================================\\n\"\n\tprintf \"ERROR RUNNING GOV USER PLUGIN TESTS${NC}\\n\"\n\texit 1\nfi\n\nexit 0\n"
},
{
"alpha_fraction": 0.6605420112609863,
"alphanum_fraction": 0.6642168164253235,
"avg_line_length": 28.821918487548828,
"blob_id": "44139dc00d53ec5f059360613f7845285f65927d",
"content_id": "b08ed56842fd78bbcfb471649fd3eb03186adce6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Ruby",
"length_bytes": 2177,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 73,
"path": "/Vagrantfile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# -*- mode: ruby -*-\n# vi: set ft=ruby :\n\nrequire 'yaml'\n\nload './local.rake' if File.exists?('local.rake')\n\n# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!\nVAGRANTFILE_API_VERSION = \"2\"\n\nVagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n config.vm.box = ENV.fetch(\"VAGRANT_BOX\", 'seocam/centos-7.0')\n proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']\n if proxy\n config.vm.provision 'shell', path: 'utils/proxy.sh', args: [proxy]\n end\n\n env = ENV.fetch('SPB_ENV', 'local')\n\n if File.exist?(\"config/#{env}/ips.yaml\")\n ips = YAML.load_file(\"config/#{env}/ips.yaml\")\n else\n ips = nil\n end\n\n config.vm.define 'database' do |database|\n database.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['database'] if ips\n end\n end\n\n config.vm.define 'integration' do |integration|\n integration.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['integration'] if ips\n vm.memory = 1024\n vm.cpus = 2\n end\n end\n\n config.vm.define 'email' do |email|\n email.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['email'] if ips\n end\n end\n\n config.vm.define 'social' do |social|\n social.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['social'] if ips\n end\n end\n\n config.vm.define 'mezuro' do |mezuro|\n mezuro.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['mezuro'] if ips\n end\n end\n\n config.vm.define 'monitor' do |monitor|\n monitor.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['monitor'] if ips\n end\n end\n\n config.vm.define 'reverseproxy' do |reverseproxy|\n reverseproxy.vm.provider \"virtualbox\" do |vm, override|\n override.vm.network 'private_network', ip: ips['reverseproxy'] if ips\n end\n if File.exist?(\"tmp/preconfig.#{env}.stamp\")\n reverseproxy.ssh.port = File.read(\"tmp/preconfig.#{env}.stamp\").strip.to_i\n reverseproxy.ssh.host = ips['reverseproxy']\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6750662922859192,
"alphanum_fraction": 0.6797082424163818,
"avg_line_length": 21.84848403930664,
"blob_id": "44489c939a29118186a0d453bd420b1059358173",
"content_id": "e4b661bd7b5434acffefafc429e724cd967ab8aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1508,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 66,
"path": "/src/noosfero-spb/software_communities/lib/ext/community.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'community'\n\nclass Community\n\n SEARCHABLE_SOFTWARE_FIELDS = {\n :name => 1,\n :identifier => 2,\n :nickname => 3\n }\n\n attr_accessible :visible\n\n has_one :software_info, :dependent=>:destroy, :class_name => \"SoftwareCommunitiesPlugin::SoftwareInfo\"\n\n settings_items :hits, :type => :integer, :default => 0\n\n def self.create_after_moderation(requestor, attributes = {})\n community = Community.new(attributes)\n\n if community.environment.enabled?('admin_must_approve_new_communities') &&\n !community.is_admin?(requestor)\n\n cc = CreateCommunity.create(attributes.merge(:requestor => requestor))\n else\n community = Community.create(attributes)\n community.add_admin(requestor)\n end\n community\n end\n\n def self.get_valid_communities_string\n remove_of_communities_methods = Community.instance_methods.select{|m| m =~ /remove_of_community_search/}\n valid_communities_string = \"!(\"\n remove_of_communities_methods.each do |method|\n valid_communities_string += \"community.send('#{method}') || \"\n end\n valid_communities_string = valid_communities_string[0..-5]\n valid_communities_string += \")\"\n\n valid_communities_string\n end\n\n def software?\n return !software_info.nil?\n end\n\n def deactivate\n self.visible = false\n self.save!\n end\n\n def activate\n self.visible = true\n self.save!\n end\n\n def remove_of_community_search_software?\n return software?\n end\n\n def hit\n self.hits += 1\n self.save!\n end\n\nend\n"
},
{
"alpha_fraction": 0.6890756487846375,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 17.230770111083984,
"blob_id": "76280f25e6e84bb930a1be5c0b821e27b9a8c7e9",
"content_id": "48da3e7953bd7ac58fd4bfff8b7f22326fa72f50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 238,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 13,
"path": "/cookbooks/firewall/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "\npackage 'iptables-services'\n\nservice 'iptables' do\n action [:enable, :start]\n supports :restart => true\nend\n\ntemplate '/etc/sysconfig/iptables' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[iptables]'\nend\n"
},
{
"alpha_fraction": 0.6654500961303711,
"alphanum_fraction": 0.6654500961303711,
"avg_line_length": 21.189189910888672,
"blob_id": "0df39b319abeeb637c24d5abe0ec0bed7185650a",
"content_id": "c16e343b8d20c75bc8ecf52be2685729e357e5cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 822,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 37,
"path": "/src/noosfero-spb/software_communities/public/lib/software-catalog-component.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('SoftwareCatalogComponent', ['jquery'], function($) {\n 'use strict';\n\n var dispatch_ajax_function;\n\n function clearCatalogCheckbox() {\n $(\"#group-categories input:checked\").each(function() {\n $(this).prop('checked', false);\n });\n\n dispatch_ajax_function(true);\n }\n\n\n function selectCheckboxCategory(dispatch_ajax) {\n dispatch_ajax_function(true);\n }\n\n\n function selectProjectSoftwareCheckbox() {\n dispatch_ajax_function(true);\n }\n\n\n function set_events() {\n $(\"#cleanup-filter-catalg\").click(clearCatalogCheckbox);\n $(\".categories-catalog\").click(selectCheckboxCategory);\n $(\".project-software\").click(selectProjectSoftwareCheckbox);\n }\n\n return {\n init: function(dispatch_ajax) {\n dispatch_ajax_function = dispatch_ajax;\n set_events();\n },\n }\n});\n\n"
},
{
"alpha_fraction": 0.7060561180114746,
"alphanum_fraction": 0.7090103626251221,
"avg_line_length": 26.079999923706055,
"blob_id": "7bf901c74858f2b10381853181788f4ba232bd52",
"content_id": "d2746600013b97505f92653b1e9615814585c0e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 677,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 25,
"path": "/src/noosfero-spb/gov_user/lib/ext/community.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'community'\n\nclass Community\n has_one :institution, :dependent=>:destroy\n\n def institution?\n return !institution.nil?\n end\n\n def remove_of_community_search_institution?\n return institution?\n end\n\n def self.get_valid_communities_string\n remove_of_communities_methods = Community.instance_methods.select{|m| m =~ /remove_of_community_search/}\n valid_communities_string = \"!(\"\n remove_of_communities_methods.each do |method|\n valid_communities_string += \"community.send('#{method}') || \"\n end\n valid_communities_string = valid_communities_string[0..-5]\n valid_communities_string += \")\"\n\n valid_communities_string\n end\nend\n"
},
{
"alpha_fraction": 0.7536945939064026,
"alphanum_fraction": 0.7536945939064026,
"avg_line_length": 21.55555534362793,
"blob_id": "28d62e8e74b5e88d57eba7012608dc5de1be1336",
"content_id": "69d4a19b8ce8c8885034d8023b8aecf3cdaf43ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 203,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 9,
"path": "/src/noosfero-spb/gov_user/db/migrate/20141103183013_add_corporate_name_to_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddCorporateNameToInstitution < ActiveRecord::Migration\n def up\n add_column :institutions, :corporate_name, :string\n end\n\n def down\n remove_column :institutions, :corporate_name\n end\nend\n"
},
{
"alpha_fraction": 0.5765569806098938,
"alphanum_fraction": 0.5765569806098938,
"avg_line_length": 23.03268051147461,
"blob_id": "80e6ae285b479f66edabbf410b6d577024fbb9c1",
"content_id": "90e38e3c0f2a796216e6dd8a9219789c2fd2a0bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3677,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 153,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/dynamic_table_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::DynamicTableHelper\n extend(\n ActionView::Helpers::TagHelper,\n ActionView::Helpers::FormTagHelper,\n ActionView::Helpers::FormOptionsHelper,\n ActionView::Helpers::UrlHelper,\n ApplicationHelper\n )\n\n COLLUMN_NAME = {\n name: \"name\",\n version: \"version\",\n license: \"license\"\n }\n\n LABEL_TEXT = {\n :name => _(\"Name\"),\n :version => _(\"Version\"),\n :license => _(\"License\")\n }\n\n DATA = {\n name: {\n label: LABEL_TEXT[:name],\n name: COLLUMN_NAME[:name]\n },\n version: {\n label: LABEL_TEXT[:version],\n name: COLLUMN_NAME[:version]\n } ,\n license: {\n label: LABEL_TEXT[:license],\n name: COLLUMN_NAME[:license],\n delete: true\n }\n }\n @@disabled = false\n\n def self.table_html_structure data={}, disabled=false\n @@disabled = disabled\n Proc::new do\n content_tag :table , generate_table_lines(data), :class => \"dynamic-table\"\n end\n end\n\n def self.generate_table_lines data={}\n @@model = data[:model_name]\n @@field_name = data[:field_name]\n @@hidden_label = data[:name][:value]\n @@hidden_id = data[:name][:id]\n\n row_data = prepare_row_data data\n\n table_line_data = [\n self.table_line(row_data[:name]),\n self.table_line(row_data[:version])\n ]\n\n if row_data[:license].has_key?(:value)\n table_line_data << self.table_line(row_data[:license])\n end\n\n table_line_data.join()\n end\n\n def self.table_line row_data={}\n unless row_data.blank?\n content_tag :tr, [\n self.label_collumn(row_data[:label]),\n self.value_collumn(\n row_data[:value],\n row_data[:name],\n row_data[:autocomplete],\n row_data[:select_field],\n row_data[:options]\n ),\n self.hidden_collumn(row_data[:delete], row_data[:hidden])\n ].join()\n end\n end\n\n def self.label_collumn label=\"\"\n content_tag :td, label_tag(label)\n end\n\n def self.value_collumn value=\"\", name=\"\", autocomplete=false, select_field=false, options=[]\n html_options =\n if autocomplete\n {\n :class => \"#{@@model}_autocomplete\",\n :placeholder => _(\"Autocomplete field, type something\")\n }\n else\n {}\n end\n\n html_options[:disabled] = @@disabled\n\n content = if select_field\n select_tag(\"#{@@model}[][#{@@field_name}]\", options, html_options)\n elsif autocomplete\n text_field_tag(\"#{@@model}_autocomplete\", value, html_options)\n else\n text_field_tag(\"#{@@model}[][#{name}]\", value, html_options)\n end\n\n content_tag :td, content\n end\n\n def self.hidden_collumn delete=false, hidden_data=false\n value =\n if @@disabled\n nil\n elsif delete\n button_without_text(\n :delete, _('Delete'), \"#\" , :class=>\"delete-dynamic-table\"\n )\n elsif hidden_data\n hidden_field_tag(\n \"#{@@model}[][#{@@field_name}]\",\n @@hidden_id,\n :class => \"#{@@field_name}\",\n :data => {:label => @@hidden_label } #check how to get the name of an object of the current model\n )\n else\n nil\n end\n\n content_tag(:td, value, :align => 'right')\n end\n\n def self.prepare_row_data data\n row_data = {\n name: DATA[:name],\n version: DATA[:version],\n license: DATA[:license]\n }\n\n row_data[:name].merge! data[:name]\n row_data[:version].merge! data[:version]\n row_data[:license].merge! data[:license] if data.has_key? :license\n\n row_data\n end\n\n def self.models_as_tables models, callback, disabled=false\n lambdas_list = []\n\n models.map do |model|\n send(callback, model, disabled)\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7380191683769226,
"alphanum_fraction": 0.7380191683769226,
"avg_line_length": 27.454545974731445,
"blob_id": "b92cfdfef387890d5bdb10073388851bc275e27a",
"content_id": "232f50a1406018dfd94c5dd29ef5b1690662310c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 11,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140814125947_add_new_fields_to_public_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddNewFieldsToPublicInstitution < ActiveRecord::Migration\n def up\n add_column :institutions, :sisp, :boolean, :default => false\n remove_column :institutions, :juridical_nature\n end\n\n def down\n remove_column :institutions, :sisp\n add_column :institutions, :juridical_nature, :string\n end\nend\n"
},
{
"alpha_fraction": 0.7032967209815979,
"alphanum_fraction": 0.7032967209815979,
"avg_line_length": 26.299999237060547,
"blob_id": "11f4c4679a321f79e544ef4848738bb36117c92b",
"content_id": "5ca4d3d6c39447ac2111cdde4d7ed76a2e703e32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 273,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 10,
"path": "/roles/database_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'database_server'\ndescription 'Database server'\nrun_list *[\n 'recipe[postgresql]',\n 'recipe[redis]',\n 'recipe[postgresql::colab]', # must come before the other apps\n 'recipe[postgresql::noosfero]',\n 'recipe[postgresql::gitlab]',\n 'recipe[postgresql::mezuro]',\n]\n"
},
{
"alpha_fraction": 0.6202253103256226,
"alphanum_fraction": 0.6287441849708557,
"avg_line_length": 32.69444274902344,
"blob_id": "2b246d12e03a73fb7d2f5c8356d65bbe2832b3f8",
"content_id": "fa188ec5e416a211bbd3565507abf604d1a0031a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 7278,
"license_type": "no_license",
"max_line_length": 174,
"num_lines": 216,
"path": "/src/noosfero-spb/gov_user/public/views/user-edit-profile.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\nmodulejs.define('UserEditProfile', ['jquery', 'SelectElement', 'SelectFieldChoices', 'CreateInstitution'], function($, SelectElement, SelectFieldChoices, CreateInstitution) {\n 'use strict';\n\n function set_form_count_custom_data() {\n var divisor_option = SelectElement.generateOption(\"-1\", \"--------------------------------\");\n var default_option = SelectElement.generateOption(\"BR\", \"Brazil\");\n\n $('#profile_data_country').find(\"option[value='']\").remove();\n $('#profile_data_country').prepend(divisor_option);\n $('#profile_data_country').prepend(default_option);\n $('#profile_data_country').val(\"BR\");\n }\n\n\n function set_initial_form_custom_data(selectFieldChoices) {\n set_form_count_custom_data();\n\n $(\"#password-balloon\").html($(\"#user_password_menssage\").val());\n $(\"#profile_data_email\").parent().append($(\"#email_public_message\").remove());\n\n if( $(\"#state_field\").length !== 0 ) selectFieldChoices.replaceStateWithSelectElement();\n }\n\n\n function show_state_if_country_is_brazil() {\n var selectFieldChoices = new SelectFieldChoices(\"#state_field\", \"#city_field\", \"/plugin/gov_user/get_brazil_states\");\n set_initial_form_custom_data(selectFieldChoices);\n\n $(\"#profile_data_country\").change(function(){\n if( this.value === \"-1\" ) $(this).val(\"BR\");\n\n if( this.value === \"BR\" && selectFieldChoices.actualFieldIsInput() ) {\n selectFieldChoices.replaceStateWithSelectElement();\n selectFieldChoices.showCity();\n } else if( this.value !== \"BR\" && !selectFieldChoices.actualFieldIsInput() ) {\n selectFieldChoices.replaceStateWithInputElement();\n selectFieldChoices.hideCity();\n }\n });\n }\n\n\n function show_or_hide_phone_mask() {\n if($(\"#profile_data_country\").val() === \"BR\") {\n if( (typeof $(\"#profile_data_cell_phone\").data(\"rawMaskFn\") === 'undefined') ) {\n // $(\"#profile_data_cell_phone\").mask(\"(99) 9999?9-9999\");\n // $(\"#profile_data_comercial_phone\").mask(\"(99) 9999?9-9999\");\n // $(\"#profile_data_contact_phone\").mask(\"(99) 9999?9-9999\");\n }\n } else {\n // $(\"#profile_data_cell_phone\").unmask();\n // $(\"#profile_data_comercial_phone\").unmask();\n // $(\"#profile_data_contact_phone\").unmask();\n }\n }\n\n\n function fix_phone_mask_format(id) {\n $(id).blur(function() {\n var last = $(this).val().substr( $(this).val().indexOf(\"-\") + 1 );\n\n if( last.length === 3 ) {\n var move = $(this).val().substr( $(this).val().indexOf(\"-\") - 1, 1 );\n var lastfour = move + last;\n var first = $(this).val().substr( 0, 9 );\n\n $(this).val( first + '-' + lastfour );\n }\n });\n }\n\n\n function show_plugin_error_message(field_selector, hidden_message_id ) {\n var field = $(field_selector);\n\n field.removeClass(\"validated\").addClass(\"invalid\");\n\n if(!$(\".\" + hidden_message_id)[0]) {\n var message = $(\"#\" + hidden_message_id).val();\n field.parent().append(\"<div class='\" + hidden_message_id + \" errorExplanation'>\"+message+\"</span>\");\n } else {\n $(\".\" + hidden_message_id).show();\n }\n }\n\n\n function hide_plugin_error_message(field_selector, hidden_message_id) {\n $(field_selector).removeClass(\"invalid\").addClass(\"validated\");\n $(\".\" + hidden_message_id).hide();\n }\n\n\n function add_blur_fields(field_selector, hidden_message_id, validation_function, allow_blank) {\n $(field_selector).blur(function(){\n $(this).attr(\"class\", \"\");\n\n if( validation_function(this.value, !!allow_blank) ) {\n show_plugin_error_message(field_selector, hidden_message_id);\n } else {\n hide_plugin_error_message(field_selector, hidden_message_id);\n }\n });\n }\n\n\n function invalid_email_validation(value, allow_blank) {\n if( allow_blank && value.trim().length === 0 ) {\n return false;\n }\n\n var correct_format_regex = new RegExp(/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/);\n\n return !correct_format_regex.test(value);\n }\n\n\n function invalid_site_validation(value) {\n var correct_format_regex = new RegExp(/(^|)(http[s]{0,1})\\:\\/\\/(\\w+[.])\\w+/g);\n\n return !correct_format_regex.test(value);\n }\n\n\n function get_privacy_selector_parent_div(field_id, actual) {\n if( actual === undefined ) actual = $(field_id);\n\n if( actual.is(\"form\") || actual.length === 0 ) return null; // Not allow recursion over form\n\n if( actual.hasClass(\"field-with-privacy-selector\") ) {\n return actual;\n } else {\n return get_privacy_selector_parent_div(field_id, actual.parent());\n }\n }\n\n\n function try_to_remove(list, field) {\n try {\n list.push(field.remove());\n } catch(e) {\n console.log(\"Cound not remove field\");\n }\n }\n\n\n function get_edit_fields_in_insertion_order() {\n var containers = [];\n\n try_to_remove(containers, get_privacy_selector_parent_div(\"#city_field\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#state_field\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_country\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_birth_date\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_organization_website\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_personal_website\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_comercial_phone\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_contact_phone\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_cell_phone\"));\n try_to_remove(containers, $(\"#select_institution\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_email\"));\n try_to_remove(containers, get_privacy_selector_parent_div(\"#profile_data_name\"));\n try_to_remove(containers, $(\".pseudoformlabel\").parent().parent());\n try_to_remove(containers, $(\"h2\")[0]);\n\n return containers;\n }\n\n\n function change_edit_fields_order() {\n var form = $(\"#profile-data\");\n\n if( form.length !== 0 ) {\n var containers = get_edit_fields_in_insertion_order();\n\n containers.forEach(function(container){\n form.prepend(container);\n });\n }\n }\n\n\n function set_fields_validations() {\n $(\"#profile_data_country\").blur(show_or_hide_phone_mask);\n\n // $(\"#profile_data_birth_date\").mask(\"99/99/9999\");\n\n fix_phone_mask_format(\"#profile_data_cell_phone\");\n fix_phone_mask_format(\"#profile_data_comercial_phone\");\n fix_phone_mask_format(\"#profile_data_contact_phone\");\n\n add_blur_fields(\"#profile_data_email\", \"email_error\", invalid_email_validation);\n add_blur_fields(\"#profile_data_personal_website\", \"site_error\", invalid_site_validation);\n add_blur_fields(\"#profile_data_organization_website\", \"site_error\", invalid_site_validation);\n }\n\n\n return {\n isCurrentPage: function() {\n return $('#profile_data_email').length === 1;\n },\n\n\n init: function() {\n change_edit_fields_order(); // To change the fields order, it MUST be the first function executed\n\n show_state_if_country_is_brazil();\n\n show_or_hide_phone_mask();\n\n set_fields_validations();\n\n CreateInstitution.init();\n }\n }\n});\n"
},
{
"alpha_fraction": 0.7464788556098938,
"alphanum_fraction": 0.7464788556098938,
"avg_line_length": 16.75,
"blob_id": "3eae09e1deeba3e6a74b6f7a0ff278657897564a",
"content_id": "aae59404f9398f8ebafffc10f6a35633f74a60c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 142,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 8,
"path": "/src/noosfero-spb/gov_user/lib/ext/search_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'search_helper'\n\nmodule SearchHelper\n\n COMMON_PROFILE_LIST_BLOCK ||= []\n COMMON_PROFILE_LIST_BLOCK << :institutions\n\nend\n"
},
{
"alpha_fraction": 0.6979020833969116,
"alphanum_fraction": 0.6979020833969116,
"avg_line_length": 30.04347801208496,
"blob_id": "e5a92aec74b8ba4908c85c92e1eda9bff55d07d0",
"content_id": "bb3ebe75a9cefa50db51110dc79df7d2f6261d71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 715,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 23,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/api.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../../lib/noosfero/api/helpers'\nrequire_relative 'api_entities'\n\nclass SoftwareCommunitiesPlugin::API < Grape::API\n\n include Noosfero::API::APIHelpers\n\n resource :software_communities do\n get do\n authenticate!\n softwares = select_filtered_collection_of(environment,'communities',params).joins(:software_info)\n softwares = softwares.visible_for_person(current_person)\n present softwares.map{|o|o.software_info}, :with => Entities::SoftwareInfo\n end\n\n get ':id' do\n authenticate!\n software = SoftwareCommunitiesPlugin::SoftwareInfo.find_by_id(params[:id])\n present software, :with => Entities::SoftwareInfo\n end\n\n end\nend\n\n"
},
{
"alpha_fraction": 0.6709821820259094,
"alphanum_fraction": 0.671480119228363,
"avg_line_length": 28,
"blob_id": "09b724737e3e07f7c8decade728970f1f742f7aa",
"content_id": "fdbc0e783d282dc75222ba08c41a54e6bd9b53ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 8033,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 277,
"path": "/src/noosfero-spb/gov_user/controllers/gov_user_plugin_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#aqui deve ter so usuario e instituicao\nclass GovUserPluginController < ApplicationController\n VERIFY_ERRORS_IN = [\n :name, :country, :state, :city, :corporate_name, :cnpj,\n :governmental_sphere, :governmental_power, :juridical_nature, :sisp\n ]\n\n before_action :require_login, :only => [:create_institution, :create_institution_admin, :create_institution_view_variables]\n\n def require_login\n redirect_to :controller => \"/account\", :action => \"login\" unless user.present?\n end\n\n def hide_registration_incomplete_percentage\n response = false\n\n if request.xhr? && params[:hide]\n session[:hide_incomplete_percentage] = true\n response = session[:hide_incomplete_percentage]\n end\n\n render :json=>response.to_json\n end\n\n def create_institution\n create_institution_view_variables\n\n if request.xhr?\n render :layout=>false\n else\n redirect_to \"/\"\n end\n end\n\n def create_institution_admin\n create_institution_view_variables\n\n @url_token = split_http_referer request.original_url()\n end\n\n def new_institution\n redirect_to \"/\" if params[:community].blank? || params[:institutions].blank?\n\n response_message = {}\n\n institution_template = Community[\"institution\"]\n add_template_in_params institution_template\n\n @institutions = private_create_institution\n add_environment_admins_to_institution @institutions\n\n response_message = save_institution @institutions\n\n if request.xhr? #User create institution\n render :json => response_message.to_json\n else #Admin create institution\n session[:notice] = response_message[:message] # consume the notice\n\n redirect_depending_on_institution_creation response_message\n end\n end\n\n def institution_already_exists\n redirect_to \"/\" if !request.xhr? || params[:name].blank?\n\n already_exists = !Institution.find_by_name(params[:name]).nil?\n\n render :json=>already_exists.to_json\n end\n\n def get_institutions\n redirect_to \"/\" if !request.xhr? || params[:query].blank?\n\n selected_institutions = Institution.where(id: params[:selected_institutions]).select([:id, :name])\n institutions = Institution.search_institution(params[:query], environment).select(\"institutions.id, institutions.name\")\n institutions -= selected_institutions\n\n institutions_list = institutions.map { |institution|\n {:value=>institution.name, :id=>institution.id}\n }\n\n render :json => institutions_list.to_json\n end\n\n def get_brazil_states\n redirect_to \"/\" unless request.xhr?\n\n render :json=>get_state_list().to_json\n end\n\n def get_field_data\n condition = !request.xhr? || params[:query].nil? || params[:field].nil?\n return render :json=>{} if condition\n\n model = get_model_by_params_field\n\n data = model.where(\"name ILIKE ?\", \"%#{params[:query]}%\").select(\"id, name\")\n .collect { |db|\n {:id=>db.id, :label=>db.name}\n }\n\n other = [model.select(\"id, name\").last].collect { |db|\n {:id=>db.id, :label=>db.name}\n }\n\n # Always has other in the list\n data |= other\n\n render :json=> data\n end\n\n protected\n\n def split_http_referer http_referer=\"\"\n split_list = http_referer.split(\"/\")\n split_list.last\n end\n\n def create_institution_view_variables\n params[:community] ||= {}\n params[:institutions] ||= {}\n\n @show_admin_fields = user.is_admin?\n @governmental_sphere = get_governmental_spheres()\n @governmental_power = get_governmental_powers()\n @juridical_nature = get_juridical_natures()\n\n state_list = get_state_list()\n @state_options = state_list.zip(state_list)\n end\n\n def get_model_by_params_field\n case params[:field]\n when \"software_language\"\n return ProgrammingLanguage\n else\n return DatabaseDescription\n end\n end\n\n def get_state_list\n NationalRegion.select(:name).where(:national_region_type_id => 2).order(:name).map &:name\n end\n\n def get_governmental_spheres\n spheres = [[_(\"Select a Governmental Sphere\"), 0]]\n spheres.concat get_model_as_option_list(GovernmentalSphere)\n end\n\n def get_governmental_powers\n powers = [[_(\"Select a Governmental Power\"), 0]]\n powers.concat get_model_as_option_list(GovernmentalPower)\n end\n\n def get_juridical_natures\n natures = [[_(\"Select a Juridical Nature\"), 0]]\n natures.concat get_model_as_option_list(JuridicalNature)\n end\n\n def get_model_as_option_list model\n model.select([:id, :name]).map {|m| [m.name, m.id]}\n end\n\n def set_institution_type\n institution_params = params[:institutions].except(:governmental_power,\n :governmental_sphere,\n :juridical_nature\n )\n if params[:institutions][:type] == \"PublicInstitution\"\n PublicInstitution::new institution_params\n else\n PrivateInstitution::new institution_params\n end\n end\n\n def set_public_institution_fields institution\n inst_fields = params[:institutions]\n\n begin\n gov_power = GovernmentalPower.find inst_fields[:governmental_power]\n gov_sphere = GovernmentalSphere.find inst_fields[:governmental_sphere]\n jur_nature = JuridicalNature.find inst_fields[:juridical_nature]\n\n institution.juridical_nature = jur_nature\n institution.governmental_power = gov_power\n institution.governmental_sphere = gov_sphere\n rescue\n institution.errors.add(\n :governmental_fields,\n _(\"Could not find Governmental Power or Governmental Sphere\")\n )\n end\n end\n\n def private_create_institution\n community = Community.new(params[:community])\n community.environment = environment\n institution = set_institution_type\n\n institution.name = community[:name]\n institution.community = community\n\n if institution.type == \"PublicInstitution\"\n set_public_institution_fields institution\n end\n\n institution.date_modification = DateTime.now\n institution.save\n institution\n end\n\n def add_template_in_params institution_template\n com_fields = params[:community]\n if !institution_template.blank? && institution_template.is_template\n com_fields[:template_id]= institution_template.id unless com_fields.blank?\n end\n end\n\n def add_environment_admins_to_institution institution\n edit_page = params[:edit_institution_page] == false\n if user.is_admin? && edit_page\n environment.admins.each do |adm|\n institution.community.add_admin(adm)\n end\n end\n end\n\n def save_institution institution\n inst_errors = institution.errors.full_messages\n com_errors = institution.community.errors.full_messages\n\n set_errors institution\n\n if inst_errors.empty? && com_errors.empty? && institution.valid? && institution.save\n { :success => true,\n :message => _(\"Institution successful created!\"),\n :institution_data => {:name=>institution.name, :id=>institution.id}\n }\n else\n { :success => false,\n :message => _(\"Institution could not be created!\"),\n :errors => inst_errors + com_errors\n }\n end\n end\n\n def redirect_depending_on_institution_creation response_message\n if response_message[:success]\n redirect_to :controller => \"/admin_panel\", :action => \"index\"\n else\n flash[:errors] = response_message[:errors]\n\n redirect_to :controller => \"gov_user_plugin\", :action => \"create_institution_admin\", :params => params\n end\n end\n\n def set_errors institution\n institution.valid? if institution\n institution.community.valid? if institution.community\n\n dispatch_flash_errors institution, \"institution\"\n dispatch_flash_errors institution.community, \"community\"\n end\n\n def dispatch_flash_errors model, flash_key_base\n model.errors.messages.keys.each do |error_key|\n flash_key = \"error_#{flash_key_base}_#{error_key}\".to_sym\n\n if VERIFY_ERRORS_IN.include? error_key\n flash[flash_key] = \"highlight-error\"\n else\n flash[flash_key] = \"\"\n end\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.5954598188400269,
"alphanum_fraction": 0.5972060561180115,
"avg_line_length": 25.859375,
"blob_id": "d5431f73775a60bb60af11e04aa5c316ed033685",
"content_id": "f96c04b771fce7843ee184d34b175ef1ff5a8e34",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1718,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 64,
"path": "/src/noosfero-spb/software_communities/public/lib/auto-complete.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('AutoComplete', ['jquery'], function($) {\n 'use strict';\n\n\n function get_hidden_description_field(autocomplete_field, klass) {\n var field = $(autocomplete_field);\n field = field.parent().parent().find(klass);\n return field;\n }\n\n\n function verify_autocomplete(field, klass) {\n var field = $(field);\n var selected = get_hidden_description_field(field, klass);\n var message_error = $(field).parent().find(\".autocomplete_validation_message\");\n\n if( field.length === 0 || selected.val().length === 0 ) {\n message_error.removeClass(\"hide-field\");\n selected.val(\"\");\n\n message_error.show();\n } else {\n field.val(selected.attr(\"data-label\"));\n message_error.hide();\n }\n }\n\n\n function enable_autocomplete(field_name, field_value_class, autocomplete_class, ajax_url, select_callback) {\n $(autocomplete_class).autocomplete({\n source : function(request, response){\n $.ajax({\n type: \"GET\",\n url: ajax_url,\n data: {query: request.term, field: field_name},\n success: function(result){\n response(result);\n }\n });\n },\n\n minLength: 0,\n\n select : function (event, selected) {\n var description = get_hidden_description_field(this, field_value_class);\n description.val(selected.item.id);\n description.attr(\"data-label\", selected.item.label);\n\n if( select_callback !== undefined ) {\n select_callback(selected);\n }\n }\n }).blur(function(){\n verify_autocomplete(this, field_value_class);\n }).click(function(){\n $(this).autocomplete(\"search\", \"\");\n });\n }\n\n\n return {\n enable: enable_autocomplete\n }\n});"
},
{
"alpha_fraction": 0.7259194254875183,
"alphanum_fraction": 0.7364273071289062,
"avg_line_length": 25.55813980102539,
"blob_id": "e2d47a80e46b56e02246c862d9e3c00e0adb5069",
"content_id": "547055342b9c43decf1b90c3180771739e17f126",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1142,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 43,
"path": "/cookbooks/mezuro/recipes/kalibro_processor.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'mezuro::service'\ninclude_recipe 'mezuro::repo'\n\npackage 'kalibro-processor' do\n action :upgrade\nend\n\ntemplate '/etc/mezuro/kalibro-processor/database.yml' do\n source 'kalibro_processor/database.yml.erb'\n owner 'kalibro_processor'\n group 'kalibro_processor'\n mode '0600'\n notifies :restart, 'service[kalibro-processor.target]'\nend\n\nPROCESSOR_DIR='/usr/share/mezuro/kalibro-processor'\n\nexecute 'kalibro-processor:schema' do\n command 'RAILS_ENV=production bundle exec rake db:schema:load'\n cwd PROCESSOR_DIR\n user 'kalibro_processor'\nend\n\nexecute 'kalibro-processor:migrate' do\n command 'RAILS_ENV=production bundle exec rake db:migrate'\n cwd PROCESSOR_DIR\n user 'kalibro_processor'\n notifies :restart, 'service[kalibro-processor.target]'\nend\n\nexecute 'kalibro-processor:open_port' do\n command 'semanage port -a -t http_port_t -p tcp 82'\n user 'root'\n only_if '! semanage port -l | grep \"^\\(http_port_t\\)\\(.\\)\\+\\(\\s82,\\)\"'\nend\n\ntemplate '/etc/nginx/conf.d/kalibro-processor.conf' do\n source 'kalibro_processor/nginx.conf.erb'\n owner 'root'\n group 'root'\n mode '0644'\n notifies :restart, 'service[nginx]'\nend\n"
},
{
"alpha_fraction": 0.6095300912857056,
"alphanum_fraction": 0.6174718737602234,
"avg_line_length": 25.508771896362305,
"blob_id": "6d8cbbf6729de8892b5e76ff7890364d5a0d2eb5",
"content_id": "f22d80ccf6a3a02b74c244b53f5a94211b0e0849",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1511,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 57,
"path": "/src/noosfero-spb/gov_user/test/unit/gov_user_person_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: utf-8\n\nrequire File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass SoftwareCommunitiesPluginPersonTest < ActiveSupport::TestCase\n include PluginTestHelper\n\n def setup\n @plugin = GovUserPlugin.new\n\n @user = fast_create(User)\n @person = create_person(\n \"My Name\",\n \"[email protected]\",\n \"123456\",\n \"[email protected]\",\n \"Any State\",\n \"Some City\"\n )\n end\n\n def teardown\n @plugin = nil\n end\n\n should 'be a noosfero plugin' do\n assert_kind_of Noosfero::Plugin, @plugin\n end\n\n should 'save person with a valid full name' do\n p = Person::new :name=>\"S1mpl3 0f N4m3\", :identifier=>\"simple-name\"\n p.user = fast_create(:user)\n\n assert_equal true, p.save\n end\n\n should 'save person with a valid full name with accents' do\n name = 'Jônatàs dâ Sîlvã Jösé'\n identifier = \"jonatas-jose-da-silva\"\n p = Person::new :name=>name, :identifier=>identifier\n p.user = fast_create(:user)\n\n assert_equal true, p.save\n end\n\n should 'not save person whose name has not capital letter' do\n p = Person::new :name=>\"simple name\"\n assert !p.save, _(\"Name Should begin with a capital letter and no special characters\")\n end\n\n should 'not save person whose name has special characters' do\n p = Person::new :name=>\"Simple N@me\"\n\n assert !p.save , _(\"Name Should begin with a capital letter and no special characters\")\n end\nend\n"
},
{
"alpha_fraction": 0.6886792182922363,
"alphanum_fraction": 0.6886792182922363,
"avg_line_length": 22.355932235717773,
"blob_id": "606aa753298c269ef441900c62ffc92aa4635d2d",
"content_id": "f5699e5589c353cc8d619dd478778655ddfb7649",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1378,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 59,
"path": "/src/noosfero-spb/software_communities/test/helpers/plugin_test_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module PluginTestHelper\n\n def create_community name\n community = fast_create(Community)\n community.name = name\n community.identifier = name.to_slug\n community.save\n community\n end\n\n def create_software_info name, finality = \"something\", acronym = \"\"\n license = create_license_info(\"GPL\")\n community = create_community(name)\n software_info = SoftwareCommunitiesPlugin::SoftwareInfo.new\n software_info.community = community\n software_info.license_info = license\n software_info.finality = finality\n software_info.acronym = acronym\n software_info.public_software = true\n software_info.save!\n\n software_info\n end\n\n def create_person name, email, password, password_confirmation, state, city\n user = create_user(\n name.to_slug,\n email,\n password,\n password_confirmation\n )\n\n user.person.state = state\n user.person.city = city\n\n user.save\n user.person\n end\n\n def create_user login, email, password, password_confirmation\n user = User.new\n\n user.login = login\n user.email = email\n user.password = password\n user.password_confirmation = password_confirmation\n\n user.save\n user\n end\n\n def create_license_info version, link = \"\"\n license = SoftwareCommunitiesPlugin::LicenseInfo.create(:version => version)\n license.link = link\n license.save\n\n license\n end\nend\n"
},
{
"alpha_fraction": 0.62643963098526,
"alphanum_fraction": 0.6269404292106628,
"avg_line_length": 30.203125,
"blob_id": "a182008e362be56734ac92ea6701140796b2dac3",
"content_id": "daf41c6d0453280b045ee738bbde3d88212cbe37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1997,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 64,
"path": "/src/noosfero-spb/software_communities/lib/ext/profile_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'profile_controller'\n\nclass ProfileController\n\n before_filter :hit_view_page\n\n def communities\n type = []\n params[:type].downcase! unless params[:type].nil?\n\n if params[:type] == \"software\"\n type = profile.softwares\n elsif params[:type] == \"institution\"\n type = profile.institutions\n else\n profile.communities.select do |community|\n type << community unless community.software? || community.institution?\n end\n end\n\n if is_cache_expired?(profile.communities_cache_key(params))\n @communities = type.paginate(:per_page => per_page, :page => params[:npage], :total_entries => type.count)\n end\n end\n\n def members\n if is_cache_expired?(profile.members_cache_key(params))\n sort = (params[:sort] == 'desc') ? params[:sort] : 'asc'\n @profile_admins = profile.admins.includes(relations_to_include).order(\"name #{sort}\").paginate(:per_page => members_per_page, :page => params[:admins_page])\n @profile_members = profile.members.order(\"name #{sort}\").paginate(:per_page => members_per_page, :page => params[:members_page])\n @profile_members_url = url_for(:controller => 'profile', :action => 'members')\n end\n end\n\n def user_is_a_bot?\n user_agent= request.env[\"HTTP_USER_AGENT\"]\n user_agent.blank? ||\n user_agent.match(/bot/) ||\n user_agent.match(/spider/) ||\n user_agent.match(/crawler/) ||\n user_agent.match(/\\(.*https?:\\/\\/.*\\)/)\n end\n\n def already_visited?(element)\n user_id = if user.nil? then -1 else current_user.id end\n user_id = \"#{user_id}_#{element.id}_#{element.class}\"\n\n if cookies.signed[:visited] == user_id\n return true\n else\n cookies.permanent.signed[:visited] = user_id\n return false\n end\n end\n\n def hit_view_page\n if profile\n community = profile\n community.hit unless user_is_a_bot? ||\n already_visited?(community) ||\n community.class != Community\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6787564754486084,
"alphanum_fraction": 0.6787564754486084,
"avg_line_length": 20.44444465637207,
"blob_id": "ddeaa9f8a755d759d73c4b3ca5523523a1e5bcce",
"content_id": "e3daac6600fc14c18de9d7747af1d6099987ca1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 193,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 9,
"path": "/roles/server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'server'\ndescription 'Common configuration for all servers'\nrun_list *[\n 'recipe[basics]',\n 'recipe[firewall]',\n 'recipe[email::client]',\n 'recipe[munin::node]',\n 'recipe[rsyslog]'\n]\n"
},
{
"alpha_fraction": 0.7459415793418884,
"alphanum_fraction": 0.7556818127632141,
"avg_line_length": 27.65116310119629,
"blob_id": "4684b2fe201cf54c86d82c36833516cc8ab593e1",
"content_id": "fbe08e46e00fa2a29979de7b2f48e4acc5a3da75",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1232,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 43,
"path": "/cookbooks/mezuro/recipes/kalibro_configurations.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'mezuro::service'\ninclude_recipe 'mezuro::repo'\n\npackage 'kalibro-configurations' do\n action :upgrade\nend\n\ntemplate '/etc/mezuro/kalibro-configurations/database.yml' do\n source 'kalibro_configurations/database.yml.erb'\n owner 'kalibro_configurations'\n group 'kalibro_configurations'\n mode '0600'\n notifies :restart, 'service[kalibro-configurations.target]'\nend\n\nCONFIGURATIONS_DIR='/usr/share/mezuro/kalibro-configurations'\n\nexecute 'kalibro-configurations:schema' do\n command 'RAILS_ENV=production bundle exec rake db:schema:load'\n cwd CONFIGURATIONS_DIR\n user 'kalibro_configurations'\nend\n\nexecute 'kalibro-configurations:migrate' do\n command 'RAILS_ENV=production bundle exec rake db:migrate'\n cwd CONFIGURATIONS_DIR\n user 'kalibro_configurations'\n notifies :restart, 'service[kalibro-configurations.target]'\nend\n\nexecute 'kalibro-configurations:open_port' do\n command 'semanage port -a -t http_port_t -p tcp 83'\n user 'root'\n only_if '! semanage port -l | grep \"^\\(http_port_t\\)\\(.\\)\\+\\(\\s83,\\)\"'\nend\n\ntemplate '/etc/nginx/conf.d/kalibro-configurations.conf' do\n source 'kalibro_configurations/nginx.conf.erb'\n owner 'root'\n group 'root'\n mode '0644'\n notifies :restart, 'service[nginx]'\nend\n"
},
{
"alpha_fraction": 0.675000011920929,
"alphanum_fraction": 0.6916666626930237,
"avg_line_length": 16.071428298950195,
"blob_id": "63a708d5707f26acb842faa6f6b2f30ac9a08a7b",
"content_id": "0909e59a7cc8b4397604882c50edb0148be65740",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 14,
"path": "/cookbooks/rsyslog/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'rsyslog' do\n action [:install, :upgrade]\nend\n\ntemplate \"/etc/rsyslog.d/spb_log.conf\" do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[rsyslog]'\nend\n\nservice 'rsyslog' do\n action [:enable, :restart]\nend\n\n"
},
{
"alpha_fraction": 0.7460629940032959,
"alphanum_fraction": 0.7460629940032959,
"avg_line_length": 28.823530197143555,
"blob_id": "72aa3710e63b148ee2f4eefe7ec8eaba21b0f577",
"content_id": "9490506569b931d0c9fd6b7350b4aabefe8ea830",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 508,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 17,
"path": "/cookbooks/backup/files/host-integration/backup_spb.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n#colab-admin dumpdata > /tmp/backups/colab_dump.json\npg_dump -h database -U colab colab > colab.dump\n# GitLab Backup\ncd /usr/lib/gitlab\nsudo -u git bundle exec rake gitlab:backup:create RAILS_ENV=production\ncd -\n# TODO fix regular expression\nmv /var/lib/gitlab/backups/*_gitlab_backup.tar .\n\ntar -czf gitlab_shell_ssh.tar.gz /var/lib/gitlab-shell/.ssh/\n\n# Mailman Backup\ncd /var/lib/mailman\ntar -cpzf mailman_backup.tar.gz lists/ data/ archives/\ncd -\nmv /var/lib/mailman/mailman_backup.tar.gz .\n\n"
},
{
"alpha_fraction": 0.6452096104621887,
"alphanum_fraction": 0.6452096104621887,
"avg_line_length": 36.11111068725586,
"blob_id": "aff449bea6988984b35426a6e3563a62e84a9681",
"content_id": "2794cb992fc592797edb8d79e283ea01efe2423f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 668,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 18,
"path": "/src/noosfero-spb/gov_user/db/migrate/20160113194207_fix_institutions_with_wrong_country.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class FixInstitutionsWithWrongCountry < ActiveRecord::Migration\n def up\n select_all(\"SELECT id, data FROM profiles WHERE type = 'Community'\").each do |community|\n settings = YAML.load(community['data'] || {}.to_yaml)\n if !settings[:country].nil? && settings[:country].downcase == \"brasil\"\n settings[:country] = 'BR'\n params ={}\n params[:data]= settings.to_yaml\n assignments = Community.send(:sanitize_sql_for_assignment, settings.to_yaml)\n update(\"UPDATE profiles SET data = '%s' WHERE id = %d\" % [assignments, community['id']])\n end\n end\n end\n\n def down\n say \"This migration can't be reverted.\"\n end\nend\n"
},
{
"alpha_fraction": 0.5612104535102844,
"alphanum_fraction": 0.5618982315063477,
"avg_line_length": 38.297298431396484,
"blob_id": "f4532ab009312b56c2175bdfa4511f40b52a9a2e",
"content_id": "dfdac6bb81a441ffc1a7bc5e5692b149687eb061",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1456,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 37,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160225032129_change_discussion_list_link.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: UTF-8\nclass ChangeDiscussionListLink < ActiveRecord::Migration\n def up\n env = Environment.find_by_name(\"SPB\") || Environment.default\n modified_blocks = []\n modified_links = []\n env.communities.find_each do |community|\n next unless community.software? || community.identifier == \"software\"\n box = community.boxes.detect {|x| x.blocks.find_by_title(\"Participe\") } if community.present?\n block = box.blocks.find_by_title(\"Participe\") if box.present?\n if block.present?\n link = block.links.detect { |l|\n l[\"name\"] == \"Listas de discussão\" ||\n l[\"name\"] == \"Lista de E-mails\"\n }\n if link.present?\n link[\"address\"] = \"/../archives/mailinglist/{profile}?order=rating\" if link.present?\n link[\"name\"] = \"Listas de discussão\"\n block.save\n print \".\"\n else\n modified_links << community.identifier\n print \"-\"\n end\n else\n modified_blocks << community.identifier\n print \"x\"\n end\n end\n puts \"\\n****Softwares where block was not found:\", modified_blocks.sort if modified_blocks.present?\n puts \"\\n****Softwares where link was not found: \", modified_links.sort if modified_links.present?\n end\n\n def down\n say \"This migration can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.6104956269264221,
"alphanum_fraction": 0.6116617918014526,
"avg_line_length": 30.18181800842285,
"blob_id": "46910a9bf4c96a2c402a443f0ddc3565e66cc3ff",
"content_id": "3ab7e89726c241209dd4394bcd3f23cca61ab9b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1715,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 55,
"path": "/src/noosfero-spb/spb_migrations/lib/tasks/import_old_spb_news.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'csv'\nrequire 'net/http'\n\nnamespace :spb do\n\n desc \"Import news from CSV file\"\n task :import_old_spb_news => :environment do\n\n error ENV[\"CSV_FILE\"].blank?, \"csv file with all the news is required to run this task!\n Ex.: rake spb:import_old_spb_news CSV_FILE=my_path/my_csv_file.csv.\"\n\n spb_profile = Profile['spb']\n error spb_profile.blank?, \"There is no SPB community.\"\n spb_blog = spb_profile.articles.find_by :slug => \"noticias\"\n error spb_blog.nil?, \"There is no SPB blog named 'noticias' in the SPB community to import the news to.\"\n\n CSV.foreach(ENV[\"CSV_FILE\"], encoding: \"UTF-8\", headers: true, col_sep: \"|\", quote_char: \"\\\"\") do |row|\n date = DateTime.parse(row[\"max\"])\n body = row[\"content\"]\n body.gsub!(\"softwarepublico.gov\",\"antigo.softwarepublico.gov\") unless body.blank?\n body.gsub!(\"www.\",\"\") unless body.blank?\n\n attrs={\n :published_at => date,\n :published => (row[\"publish_status\"] == \"ready\"),\n :body => body,\n :highlighted => true,\n :parent => spb_blog,\n :profile => spb_profile,\n :name => row[\"title\"]\n }\n\n article = Article.find_by(:slug => row[\"title\"].to_slug)\n if article.blank?\n article = TinyMceArticle.new(attrs)\n article.created_at = date\n end\n article.save!\n\n puts \"#{spb_blog.slug}: Importing article: #{article.name}...\"\n end\n\n puts \"\", \"Deleting standard blog...\"\n old_blog = spb_profile.articles.find_by :slug => \"blog\"\n old_blog.destroy if (old_blog.present? && old_blog.children.count.zero?)\n\n end\n\n def error failure_condition, msg=\"ERROR!!\"\n if failure_condition\n puts msg\n exit 1\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6532367467880249,
"alphanum_fraction": 0.6564056277275085,
"avg_line_length": 30.098590850830078,
"blob_id": "6f2fd1c9f15a041291fc5d5c849cd66cc8f5bf26",
"content_id": "d52f7dc980b856a4491c074129f46b81bb90364b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2209,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 71,
"path": "/src/noosfero-spb/software_communities/lib/tasks/create_sample_softwares.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "NUMBER_OF_SOFTWARES = 10\n\ndef create_community(name)\n community = Community.new\n community.name = name\n community.save\n community\nend\n\ndef create_software_info(name, acronym = \"\", finality = \"default\")\n community = create_community(name)\n software_info = SoftwareCommunitiesPlugin::SoftwareInfo.new\n software_info.community = community\n software_info.public_software = true\n software_info.acronym = acronym\n software_info.finality = finality\n software_info.license_info = SoftwareCommunitiesPlugin::LicenseInfo.first\n\n if software_info.community.valid? && software_info.valid?\n print \".\"\n software_info.save\n software_info\n else\n print \"F\"\n nil\n end\nend\n\nnamespace :software do\n desc \"Create sample softwares\"\n task :create_sample_softwares => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"SoftwareCommunitiesPlugin\") or env.plugin_enabled?(\"SoftwareCommunities\")\n print \"Creating softwares: \"\n\n NUMBER_OF_SOFTWARES.times do |i|\n number = i < 10 ? \"0#{i}\" : \"#{i}\"\n software_name = \"Software #{number}\"\n create_software_info(software_name)\n end\n\n create_software_info(\"Ubuntu\")\n create_software_info(\"Debian\")\n create_software_info(\"Windows XP\")\n create_software_info(\"Windows Vista\")\n create_software_info(\"Windows 7\")\n create_software_info(\"Windows 8\")\n create_software_info(\"Disk Operating System\", \"DOS\")\n create_software_info(\"Sublime\")\n create_software_info(\"Vi IMproved\", \"Vim\")\n create_software_info(\"Nano\")\n create_software_info(\"Gedit\")\n create_software_info(\"Firefox\")\n create_software_info(\"InkScape\")\n create_software_info(\"Eclipse\")\n create_software_info(\"LibreOffice\")\n create_software_info(\"Tetris\")\n create_software_info(\"Mario\")\n create_software_info(\"Pong\")\n create_software_info(\"Sonic\")\n create_software_info(\"Astah\")\n create_software_info(\"Pokemom Red\")\n create_software_info(\"Mass Effect\")\n create_software_info(\"Deus EX\")\n create_software_info(\"Dragon Age\")\n\n puts \"\"\n end\n end\n end\nend\n\n"
},
{
"alpha_fraction": 0.5985662937164307,
"alphanum_fraction": 0.5985662937164307,
"avg_line_length": 21.31999969482422,
"blob_id": "1dd2d25d76c90d8f310cd48c5db50bacb1a11a76",
"content_id": "38d88baf5b39c175db52cbafae30e74755ab5be8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 25,
"path": "/src/noosfero-spb/software_communities/lib/ext/profile_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'profile_helper'\n\nmodule ProfileHelper\n PERSON_CATEGORIES[:mpog_profile_information] = [:institutions]\n\n def display_mpog_field(title, profile, field, force = false)\n unless force || profile.may_display_field_to?(field, user)\n return ''\n end\n value = profile.send(field)\n if !value.blank?\n if block_given?\n value = yield(value)\n end\n content_tag(\n 'tr',\n content_tag('td', title, :class => 'field-name') +\n content_tag('td', value)\n )\n else\n ''\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.5396419167518616,
"alphanum_fraction": 0.5421994924545288,
"avg_line_length": 22,
"blob_id": "195d23df4922ef2cd404b1ca0180875832714d26",
"content_id": "ada479ee335750b22683f9f7e0dadacee408de6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 391,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 17,
"path": "/docs/build.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'yaml'\n\n$SPB_ENV = ENV.fetch('SPB_ENV', 'local')\n\n$_.gsub!('@@SPB_ENV@@', $SPB_ENV)\n\nconfig = YAML.load_file(\"../config/#{$SPB_ENV}/config.yaml\")\nconfig.each do |key,value|\n $_.gsub!(\"@@#{key}@@\", value.to_s)\nend\n\n$_.gsub!(/@@config\\(([^\\)]*)\\)@@/) do |f|\n lines = File.read(\"../config/#{$SPB_ENV}/#{$1}\").lines\n lines.shift + lines.map do |line|\n ' ' + line\n end.join\nend\n"
},
{
"alpha_fraction": 0.7098121047019958,
"alphanum_fraction": 0.7265135645866394,
"avg_line_length": 19.826086044311523,
"blob_id": "1b1610b060064c41db734994f16f7ad4bddbf224",
"content_id": "5b1cec5e0b39a7d58200ff2136ed4a7cd389ddf4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 23,
"path": "/cookbooks/postgresql/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# FIXME on Debian it's postgresql\npackage 'postgresql-server'\n\nexecute 'postgresql-setup initdb || true'\n\ntemplate '/var/lib/pgsql/data/pg_hba.conf' do\n user 'postgres'\n group 'postgres'\n mode 0600\n notifies :restart, 'service[postgresql]'\nend\n\ntemplate '/var/lib/pgsql/data/postgresql.conf' do\n user 'postgres'\n group 'postgres'\n mode 0600\n notifies :restart, 'service[postgresql]'\nend\n\nservice 'postgresql' do\n action [:enable, :start]\n supports :restart => true\nend\n"
},
{
"alpha_fraction": 0.6247654557228088,
"alphanum_fraction": 0.6341463327407837,
"avg_line_length": 16.766666412353516,
"blob_id": "6c0556a96f4b855b9dd91af18b24a7ee77c11e07",
"content_id": "43de0039a8addb032e9e0dafa1db09e16cb555dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 533,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 30,
"path": "/cookbooks/basics/files/default/selinux-install-module",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\n# MANAGED WITH CHEF; DO NOT CHANGE BY HAND\n\nset -e\n\nif [ $# -ne 1 ]; then\n echo \"usage: $0 MODULE.te\"\n exit 1\nfi\n\nselinux_status=$(sestatus | sed -e '/^SELinux status:/ !d; s/.*\\s//')\nif ! selinux-enabled; then\n echo \"I: SELinux disabled, skipping\"\n exit 0\nfi\n\ninput=\"$1\"\n\ndirectory=$(dirname \"$input\")\n\ncd $directory\n\nmodule=$(basename --suffix=.te \"$input\")\n\nrm -f ${module}.mod ${module}.pp\n\ncheckmodule -M -m -o ${module}.mod ${module}.te\nsemodule_package -o ${module}.pp -m ${module}.mod\nsemodule -i ${module}.pp\n"
},
{
"alpha_fraction": 0.6640913486480713,
"alphanum_fraction": 0.6738327145576477,
"avg_line_length": 25.58035659790039,
"blob_id": "7a1558a4190ade27258e36b28cffc6250521abe7",
"content_id": "38465af567632e69ee54a56acf4fac97efbf8c02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2977,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 112,
"path": "/src/noosfero-spb/gov_user/test/functional/profile_editor_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/institution_test_helper'\nrequire(\nFile.dirname(__FILE__) +\n'/../../../../app/controllers/my_profile/profile_editor_controller'\n)\n\nclass ProfileEditorController; def rescue_action(e) raise e end; end\n\nclass ProfileEditorControllerTest < ActionController::TestCase\n\n def setup\n @controller = ProfileEditorController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n @profile = create_user('default_user').person\n\n Environment.default.affiliate(\n @profile,\n [Environment::Roles.admin(Environment.default.id)] +\n Profile::Roles.all_roles(Environment.default.id)\n )\n\n @environment = Environment.default\n @environment.enabled_plugins = ['GovUserPlugin']\n admin = create_user(\"adminuser\").person\n admin.stubs(:has_permission?).returns(\"true\")\n login_as('adminuser')\n @environment.add_admin(admin)\n @environment.save\n\n @govPower = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @govSphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n\n @institution_list = []\n @institution_list << InstitutionTestHelper.create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @govPower,\n @govSphere,\n \"12.345.678/9012-45\"\n )\n\n @institution_list << InstitutionTestHelper.create_public_institution(\n \"Tribunal Regional da Uniao\",\n \"TRU\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n @juridical_nature,\n @govPower,\n @govSphere,\n \"12.345.678/9012-90\"\n )\n end\n\n should \"add new institution for user into edit profile\" do\n user = create_basic_user\n\n params_user = Hash.new\n params_user[:institution_ids] = []\n\n @institution_list.each do |institution|\n params_user[:institution_ids] << institution.id\n end\n\n post :edit, :profile => User.last.person.identifier, :user => params_user\n\n assert_equal @institution_list.count, User.last.institutions.count\n end\n\n should \"remove institutions for user into edit profile\" do\n user = create_basic_user\n\n @institution_list.each do |institution|\n user.institutions << institution\n end\n user.save!\n\n params_user = Hash.new\n params_user[:institution_ids] = []\n\n assert_equal @institution_list.count, User.last.institutions.count\n\n post :edit, :profile => User.last.person.identifier, :user => params_user\n\n assert_equal 0, User.last.institutions.count\n end\n\n protected\n\n def create_basic_user\n user = fast_create(User)\n user.person = fast_create(Person)\n user.person.user = user\n user.save!\n user.person.save!\n user\n end\n\n def create_community name\n community = fast_create(Community)\n community.name = name\n community.save\n community\n end\nend\n"
},
{
"alpha_fraction": 0.6829268336296082,
"alphanum_fraction": 0.6991869807243347,
"avg_line_length": 28.285715103149414,
"blob_id": "ab098fa499b175906692cbc120de25f90c792583",
"content_id": "20e4346699ff5be493e0187188a61350cf81aa55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 42,
"path": "/utils/reverseproxy_ssh_setup",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\nset -x\n\nport=\"$1\"\nreverseproxy_external=\"$2\"\nreverseproxy_ip=\"$3\"\nintegration_ip=\"$4\"\n\n# switch SSH to port $port\nsed -i -e 's/^#\\?\\s*Port\\s*[0-9]\\+\\s*$/Port '$port'/g' /etc/ssh/sshd_config\n\n# Install SELinux\nyum install -y selinux-policy policycoreutils-python\n\n# Tell SELinux to allow the new port\nif grep -q '/$' /proc/1/cgroup; then\n # not in a container\n semanage port -a -t ssh_port_t -p tcp \"$port\"\nelse\n # in container; will fail if host does not have SELinux enabled\n if ! semanage port -a -t ssh_port_t -p tcp \"$port\"; then\n echo \"I: can't use SELinux, your host probably does not have it enabled\"\n fi\nfi\n\n# Restart SSH\nsystemctl restart sshd\n\n# Clean iptables before adding our rules\nsystemctl stop iptables || echo \"Iptables server not installed. Does not needed to stop service. Moving on...\"\niptables -F\niptables -F -t nat\n\n# Setup port redirect\niptables -t nat -A PREROUTING -d $reverseproxy_external/32 -p tcp -m tcp --dport 22 -j DNAT --to-destination $integration_ip:22\niptables -t nat -A POSTROUTING -d $integration_ip/32 -p tcp -m tcp --dport 22 -j SNAT --to-source $reverseproxy_ip\nif grep -q '/$' /proc/1/cgroup; then\n # only on non-containers\n sysctl -w net.ipv4.ip_forward=1\nfi\n"
},
{
"alpha_fraction": 0.6360808610916138,
"alphanum_fraction": 0.6365993022918701,
"avg_line_length": 27.367647171020508,
"blob_id": "4860ae62fe3b724422c3abbf0f34685a526948a1",
"content_id": "5b392f00f13ecc28d9651acdb656d9b8c5d71a9c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1929,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 68,
"path": "/src/noosfero-spb/software_communities/public/views/new-software.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('NewSoftware', ['jquery', 'NoosferoRoot', 'AutoComplete', 'NewCommunity'], function($, NoosferoRoot, AutoComplete, Community) {\n 'use strict';\n\n var AJAX_URL = {\n get_license_data:\n NoosferoRoot.urlWithSubDirectory(\"/plugin/software_communities/get_license_data\")\n };\n\n function replace_domain_and_repository_link(){\n var community_name = $(\"#community_name_id\").val();\n var domain = $(\"#software-hostname\").text();\n\n var slug_name = community_name.replace(/\\s+/g, '-').toLowerCase();\n\n var custom_domain = domain.concat('<your-repository>');\n custom_domain = custom_domain.concat('/');\n custom_domain = custom_domain.concat(slug_name);\n\n $(\"#community-identifier\").val(slug_name);\n $(\"#software-info-repository-link\").val(custom_domain);\n }\n\n function show_another_license_on_page_load() {\n $(\"#license_info_id\").trigger(\"change\");\n }\n\n\n function display_another_license_fields(selected) {\n if( selected === \"Another\" ) {\n $(\"#another_license\").removeClass(\"hide-field\");\n $(\"#version_link\").addClass(\"hide-field\");\n } else {\n $(\"#another_license\").addClass(\"hide-field\");\n $(\"#version_link\").removeClass(\"hide-field\");\n }\n }\n\n\n function display_license_link_on_autocomplete(selected) {\n var link = $(\"#version_\" + selected.item.id).val();\n $(\"#version_link\").attr(\"href\", link);\n\n display_another_license_fields(selected.item.label);\n }\n\n\n function license_info_autocomplete() {\n AutoComplete.enable(\n \"license_info\", \".license_info_id\", \".license_info_version\",\n AJAX_URL.get_license_data, display_license_link_on_autocomplete\n );\n }\n\n\n return {\n isCurrentPage: function() {\n return $('#new-software-page').length === 1;\n },\n\n\n init: function() {\n license_info_autocomplete();\n Community.init();\n\n $(\"#community_name_id\").blur(replace_domain_and_repository_link);\n }\n }\n});\n"
},
{
"alpha_fraction": 0.8108108043670654,
"alphanum_fraction": 0.8108108043670654,
"avg_line_length": 23.66666603088379,
"blob_id": "41e67911d31166b6a5502e440c244c1ba0b809a2",
"content_id": "508c6ae4fe9cf71f0382e721f9e07c4cabd8f8a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 74,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 3,
"path": "/cookbooks/loganalyzer/files/rsyslog-createUser.sql",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "GRANT ALL ON Syslog.* TO rsyslogdbadmin@localhost;\nFLUSH PRIVILEGES;\nexit\n"
},
{
"alpha_fraction": 0.6200608015060425,
"alphanum_fraction": 0.6220871210098267,
"avg_line_length": 26.02739715576172,
"blob_id": "a4f72ce729e747f75781f27821f6efa1374666e9",
"content_id": "faaa308fdb34044fb238e8076c863d8022e0ced5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1974,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 73,
"path": "/src/noosfero-spb/gov_user/lib/institution_modal_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class InstitutionModalHelper\n extend(\n ActionView::Helpers::FormOptionsHelper, # content_tag\n ActionView::Helpers::FormTagHelper, # button_tag\n ActionView::Helpers::UrlHelper, # link_to\n ActionView::Context # content_tag do end\n )\n\n def self.modal_button link_text=_(\"Create new institution\"), display=\"block\"\n # HTML Sample in: http://getbootstrap.com/javascript/#modals-examples\n content_tag :div, :id=>\"institution_modal_container\", :style=>\"display: #{display}\" do\n link = link_to(\n link_text,\n \"javascript: void(0)\",\n {:class=>\"button with-text\", :data=>{:toggle=>\"modal\", :target=>\"#institution_modal\"}, :id=>\"create_institution_link\"}\n )\n\n link.concat modal\n end\n end\n\n private\n\n def self.modal\n options = {\n :id=>\"institution_modal\",\n :role=>\"dialog\",\n :class=>\"modal fade\"\n }\n\n content_tag :div, options do\n modal_dialog\n end\n end\n\n def self.modal_dialog\n content_tag :div, :class=>\"modal-dialog\", :role=>\"document\" do\n modal_content\n end\n end\n\n def self.modal_content\n content_tag :div, :class=>\"modal-content\" do\n #modal_header.concat(modal_body.concat(modal_footer))\n modal_header.concat(modal_body)\n end\n end\n\n def self.modal_header\n content_tag :div, :class=>\"modal-header\" do\n button = button_tag :type=>\"button\", :data=>{:dismiss=>\"modal\"}, :class=>\"close\" do\n content_tag :span, \"×\"\n end\n\n h4 = content_tag :h4, _(\"New Institution\"), :class=>\"modal-title\"\n\n button.concat h4\n end\n end\n\n def self.modal_body\n content_tag :div, \"\", :id=>\"institution_modal_body\", :class=>\"modal-body\"\n end\n\n #def self.modal_footer\n # content_tag :div, {:class=>\"modal-footer\"} do\n # close = button_tag _(\"Close\"), :type=>\"button\", :class=>\"button with-text\"\n # save = button_tag _(\"Save changes\"), :type=>\"button\", :class=>\"button with-text\"\n #\n # close.concat save\n # end\n #end\nend\n\n"
},
{
"alpha_fraction": 0.656649112701416,
"alphanum_fraction": 0.6581517457962036,
"avg_line_length": 29.953489303588867,
"blob_id": "afa28e6bf6fa35f2db95d91521e53e5893cb9aae",
"content_id": "a809624fd4cb14a4795ee63bbc58509a790644b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1331,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 43,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150720190133_change_blocks_mirror_option.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class ChangeBlocksMirrorOption < ActiveRecord::Migration\n def up\n blocks = Block.where(:type => LinkListBlock)\n institution = Community[\"institution\"]\n software = Community[\"software\"]\n\n if institution\n boxTemplateInstitution = institution.boxes.where(:position => 2).first\n\n boxTemplateInstitution.blocks.each do |block|\n block.mirror = true\n print \".\" if block.save\n end\n end\n\n if software\n boxTemplateSoftware = software.boxes.where(:position => 2).first\n\n boxTemplateSoftware.blocks.each do |block|\n block.mirror = true\n print \".\" if block.save\n end\n end\n\n blocks.each do |block|\n if !(block.owner.class == Environment) && block.owner.organization? && !block.owner.enterprise?\n if software && block.owner.software?\n software_block = boxTemplateSoftware.blocks.where(:title => block.title).first\n block.mirror_block_id = software_block.id if software_block\n elsif institution && block.owner.institution?\n institution_block = boxTemplateInstitution.blocks.where(:title => block.title).first\n block.mirror_block_id = institution_block.id if institution_block\n end\n end\n print \".\" if block.save\n end\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.6222222447395325,
"alphanum_fraction": 0.6266666650772095,
"avg_line_length": 22.6842098236084,
"blob_id": "c6e3bbbc16d547e14b364ff0328eff6a69ddec24",
"content_id": "2546d526112a8a4617cc5fef2c1a4d72ecfde071",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 900,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 38,
"path": "/utils/proxy.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\n\nif [ -n \"$1\" ]; then\n http_proxy=\"$1\"\nfi\n\nif [ -z \"$http_proxy\" ]; then\n echo \"No http_proxy in command line or environment!\"\n echo\n echo \"usage: $0 [HTTP_PROXY]\"\n exit 1\nfi\n\ncat > /etc/profile.d/http_proxy.sh<<EOF\nexport http_proxy='$http_proxy'\nexport https_proxy='$http_proxy'\nexport HTTP_PROXY='$http_proxy'\nEOF\n\nif test -f /etc/yum.conf; then\n sed -i -e '/proxy=/d; /http_caching=/ d' /etc/yum.conf\n sed -i -s '/\\[main\\]/ a http_caching=packages' /etc/yum.conf\n sed -i -s '/\\[main\\]/ a proxy='$http_proxy /etc/yum.conf\n\n rm -f /etc/yum/pluginconf.d/fastestmirror.conf\n\n repofiles=$(grep -rl '^#baseurl' /etc/yum.repos.d)\n if [ -n \"$repofiles\" ]; then\n sed -i -e 's/^#baseurl/baseurl/; s/^mirrorlist=/#mirrorlist-/' $repofiles\n fi\n\n if [ ! -f /var/tmp/yum-clean.stamp ]; then\n pgrep -f yum || yum clean all || true\n touch /var/tmp/yum-clean.stamp\n fi\nfi\n"
},
{
"alpha_fraction": 0.6761780977249146,
"alphanum_fraction": 0.6761780977249146,
"avg_line_length": 36.537776947021484,
"blob_id": "9ab500b05378fa74508afad58b558a3bd223e78b",
"content_id": "1d0595a43c4bd7c1d06f3342ec7134828a03d83a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 8446,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 225,
"path": "/src/noosfero-spb/software_communities/controllers/software_communities_plugin_myprofile_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPluginMyprofileController < MyProfileController\n append_view_path File.join(File.dirname(__FILE__) + '/../views')\n\n protect 'edit_software', :profile, :except => [:destroy_profile]\n\n def index\n end\n\n def new_software\n set_software_as_template\n\n @community = Community.new(params[:community])\n @community.environment = environment\n\n @license_info = SoftwareCommunitiesPlugin::LicenseInfo.find_by_id(params[:license][:license_infos_id]) if params[:license]\n @license_info ||= SoftwareCommunitiesPlugin::LicenseInfo.new\n\n @software_info = SoftwareCommunitiesPlugin::SoftwareInfo.new(params[:software_communities_plugin_software_info])\n @software_info.community = @community\n @software_info.license_info = @license_info\n\n control_software_creation\n update_software_highlight_errors\n end\n\n def edit_software\n update_software_atributes\n\n return unless request.post?\n\n @software_info = create_software\n software_info_insert_models.call(@list_libraries, 'libraries')\n software_info_insert_models.call(@list_languages, 'software_languages')\n software_info_insert_models.call(@list_databases, 'software_databases')\n software_info_insert_models.call(@list_operating_systems, 'operating_systems')\n begin\n raise NotAdminException unless can_change_public_software?\n @software_info.update_attributes!(params[:software])\n\n @community = @software_info.community\n @community.update_attributes!(params[:community])\n\n if params[:commit] == _('Save and Configure Community')\n redirect_to :controller => 'profile_editor', :action => 'edit'\n else\n redirect_to :controller => 'profile_editor', :action => 'index'\n session[:notice] = _('Software updated successfully')\n end\n rescue NotAdminException, ActiveRecord::RecordInvalid => invalid\n update_new_software_errors\n session[:notice] = _('Could not update software')\n end\n end\n\n private\n\n def can_change_public_software?\n if !user.is_admin?(environment)\n if params[:software][:public_software]\n @software_info.errors.add(:public_software, _(\"You don't have permission to change public software status\"))\n return false\n end\n\n if params[:software].keys.any?{|key| [\"e_ping\",\"e_mag\",\"icp_brasil\",\"e_arq\",\"intern\"].include?(key)}\n @software_info.errors.add(:base, _(\"You don't have permission to change public software attributes\"))\n return false\n end\n else\n @software_info.public_software = params['software']['public_software'].present?\n end\n\n return true\n end\n\n def add_software_erros\n @errors = []\n if @community\n error = @community.errors.delete(:identifier)\n @errors |= [_(\"Domain %s\") % error.first ] if error\n @errors |= @community.errors.full_messages\n end\n @errors |= @software_info.errors.full_messages if @software_info\n @errors |= @license_info.errors.full_messages if @license_info\n end\n\n def control_software_creation\n if request.post?\n valid_models = @community.valid?\n valid_models &= @software_info.valid?\n valid_models &= @license_info.valid?\n if valid_models\n send_software_to_moderation\n else\n add_software_erros\n end\n end\n end\n\n def software_info_insert_models\n proc { |list,model_attr|\n @software_info.send(model_attr).destroy_all\n list.collect!{|m| @software_info.send(model_attr) << m } unless list.nil?\n }\n end\n\n def create_software\n @software_info = @profile.software_info\n\n params[:software][:public_software] ||= false unless @software_info.public_software?\n @license = SoftwareCommunitiesPlugin::LicenseInfo.find(params[:license][:license_infos_id])\n @software_info.license_info = @license\n @software_info.update_attributes(params[:software])\n\n another_license_version = nil\n another_license_link = nil\n if params[:license]\n @license = SoftwareCommunitiesPlugin::LicenseInfo.find(params[:license][:license_infos_id])\n @software_info.license_info = @license\n\n another_license_version = params[:license][:version]\n another_license_link = params[:license][:link]\n end\n\n @software_info.verify_license_info(another_license_version, another_license_link)\n\n create_list_model_helpers\n\n @software_info\n end\n\n def create_list_model_helpers\n @list_libraries = SoftwareCommunitiesPlugin::LibraryHelper.list_library(params[:library])\n @list_languages = SoftwareCommunitiesPlugin::SoftwareLanguageHelper.list_language(params[:language])\n @list_databases = SoftwareCommunitiesPlugin::DatabaseHelper.list_database(params[:database])\n @list_operating_systems = SoftwareCommunitiesPlugin::OperatingSystemHelper.list_operating_system(params[:operating_system])\n end\n\n def send_software_to_moderation\n another_license_version = \"\"\n another_license_link = \"\"\n if params[:license]\n another_license_version = params[:license][:version]\n another_license_link = params[:license][:link]\n end\n @software_info = SoftwareCommunitiesPlugin::SoftwareInfo.create_after_moderation(user,\n params[:software_communities_plugin_software_info].merge({\n :environment => environment,\n :name => params[:community][:name],\n :identifier => params[:community][:identifier],\n :image_builder => params[:community][:image_builder],\n :license_info => @license_info,\n :another_license_version => another_license_version,\n :another_license_link => another_license_link }))\n\n add_admin_to_community\n\n if !user.is_admin?\n session[:notice] = _('Your new software request will be evaluated by an'\\\n 'administrator. You will be notified.')\n redirect_to user.admin_url\n else\n redirect_to :controller => 'profile_editor',\n :action => 'edit',\n :profile => @community.identifier\n end\n end\n\n def update_software_atributes\n @software_info = @profile.software_info\n @list_libraries = @software_info.libraries\n @list_databases = @software_info.software_databases\n @list_languages = @software_info.software_languages\n @list_operating_systems = @software_info.operating_systems\n @non_admin_status = 'disabled' unless user.is_admin?(environment)\n\n @license_version = @software_info.license_info.version\n @license_id = @software_info.license_info.id\n @another_license_version = \"\"\n @another_license_link = \"\"\n\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(\"Another\")\n if license_another && @software_info.license_info_id == license_another.id\n @license_version = \"Another\"\n @another_license_version = @software_info.license_info.version\n @another_license_link = @software_info.license_info.link\n end\n end\n\n def set_software_as_template\n software_template = SoftwareCommunitiesPlugin::SoftwareHelper.software_template\n software_valid = !software_template.blank? && !params['community'].blank?\n if software_valid\n params['community']['template_id'] = software_template.id if software_valid\n end\n end\n\n def add_admin_to_community\n unless params[:q].nil?\n admins = params[:q].split(/,/).map{ |n| environment.people.find n.to_i }\n admins.each do |admin|\n @community.add_member(admin)\n @community.add_admin(admin)\n end\n end\n end\n\n def update_new_software_errors\n if request.post?\n @community.valid? if @community\n @software_info.valid? if @software_info\n @license_info.valid? if @license_info\n add_software_erros\n end\n end\n\n def update_software_highlight_errors\n @error_community_name = @community.errors.include?(:name) ? \"highlight-error\" : \"\" if @community\n @error_software_acronym = @software_info.errors.include?(:acronym) ? \"highlight-error\" : \"\" if @software_info\n @error_software_domain = @community.errors.include?(:identifier) ? \"highlight-error\" : \"\" if @community\n @error_software_finality = @software_info.errors.include?(:finality) ? \"highlight-error\" : \"\" if @software_info\n @error_software_license = @license_info.errors.include?(:version) ? \"highlight-error\" : \"\" if @license_info\n end\nend\n\nclass NotAdminException < Exception; end\n"
},
{
"alpha_fraction": 0.641636312007904,
"alphanum_fraction": 0.6514430046081543,
"avg_line_length": 25.242647171020508,
"blob_id": "8dfc08e38259d502bee144bd9c1256fff4cd3108",
"content_id": "0d4486ceaf33e84aa0bcdfab7c40b42eac4cb24d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3569,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 136,
"path": "/cookbooks/gitlab/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "if node['platform'] == 'centos'\n cookbook_file '/etc/yum.repos.d/gitlab.repo' do\n action :delete\n end\nend\n\npackage 'gitlab' do\n action :upgrade\n notifies :restart, 'service[gitlab]'\nend\n\n\ntemplate '/etc/gitlab/database.yml' do\n owner 'root'\n group 'root'\n mode 0644\n\n notifies :run, 'execute[gitlab:setup]', :immediately\nend\n\nexecute 'gitlab:setup' do\n user 'git'\n cwd '/usr/lib/gitlab'\n command 'yes yes | bundle exec rake db:setup RAILS_ENV=production && touch /var/lib/gitlab/setup.done'\n not_if { File.exists?('/var/lib/gitlab/setup.done') }\n\n action :nothing\n notifies :restart, 'service[gitlab]'\nend\n\n# gitlab-shell configuration\ntemplate '/etc/gitlab-shell/config.yml' do\n source 'gitlab-shell.yml.erb'\n\n owner 'root'\n group 'root'\n mode 0644\n\n notifies :restart, 'service[gitlab]'\nend\n\n# gitlab redis configuration\ntemplate '/usr/lib/gitlab/config/resque.yml' do\n owner 'root'\n group 'root'\n mode 0644\n\n notifies :restart, 'service[gitlab]'\nend\n\n####################################################\n# Run under /gitlab\n####################################################\n\ntemplate '/etc/gitlab/gitlab.yml' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[gitlab]'\nend\ncookbook_file '/usr/lib/gitlab/config/initializers/gitlab_path.rb' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[gitlab]'\nend\ncookbook_file '/etc/gitlab/unicorn.rb' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[gitlab]'\nend\n\n####################################################\n# Run under /gitlab (END)\n####################################################\n\n# serve static files with nginx\ntemplate '/etc/nginx/conf.d/gitlab.conf' do\n source 'nginx.conf.erb'\n mode 0644\n notifies :reload, 'service[nginx]'\nend\n\nservice 'gitlab' do\n action :enable\n supports :restart => true\nend\n\n\n####################################################\n# SELinux: allow gitlab to use '/tmp'\n####################################################\ncookbook_file '/etc/selinux/local/gitlab.te' do\n notifies :run, 'execute[selinux-gitlab]'\nend\nexecute 'selinux-gitlab' do\n command 'selinux-install-module /etc/selinux/local/gitlab.te'\n action :nothing\nend\n\nexecute 'fix-relative-url-for-assets' do\n command 'sed -i \\'s/# config.relative_url_root = \"\\/gitlab\"/config.relative_url_root = \"\\/gitlab\"/\\' /usr/lib/gitlab/config/application.rb'\n only_if 'grep -q \"# config.relative_url_root\" /usr/lib/gitlab/config/application.rb'\n notifies :run, 'execute[precompile-assets]'\nend\n\nexecute 'change-cache-owner' do\n command 'chown -R git:git /usr/lib/gitlab/tmp/cache'\n only_if 'ls -l /usr/lib/gitlab/tmp/cache | grep root'\nend\n\nexecute 'change-assets-owner' do\n command 'chown -R git:git /usr/lib/gitlab/public/assets'\n only_if 'ls -l /usr/lib/gitlab/public/assets | grep root'\nend\n\nexecute 'change-gitlab-assets-owner' do\n command 'chown -R git:git /var/lib/gitlab-assets'\n only_if 'ls -l /var/lib/gitlab-assets | grep root'\nend\n\n# TODO: the ignore_failure prevents the recipe to stop running when a exit non 0 happens\n# The precompile-assets runs into a bug that happens when it runs the FIRST time\n# This means that when runs into a new and clean machine it will crash\n# This bug is related to gitlab 7.6.* it should fix on gitlab 8.*\n#\n# The returns is accepting 1 as return for this case\nexecute 'precompile-assets' do\n user 'git'\n cwd '/usr/lib/gitlab'\n ignore_failure true\n command 'bundle exec rake assets:precompile RAILS_ENV=production'\n action :nothing\n returns [0,1]\nend\n"
},
{
"alpha_fraction": 0.7095761299133301,
"alphanum_fraction": 0.7095761299133301,
"avg_line_length": 21.75,
"blob_id": "3302fc7c5fa04c290ebd583558cfd244571022f9",
"content_id": "3645f1f79c7587f36a5cf5df93d7df856ea92057",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 28,
"path": "/src/noosfero-spb/software_communities/lib/ext/profile_editor_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'profile_editor_controller'\n\nclass ProfileEditorController\n\n before_filter :redirect_to_edit_software_community, :only => [:edit]\n\n def edit_software_community\n @profile_data = profile\n @possible_domains = profile.possible_domains\n @first_edit = profile.software_info.first_edit?\n\n if @first_edit\n profile.software_info.first_edit = false\n profile.software_info.save!\n end\n\n edit if request.post?\n end\n\n protected\n\n def redirect_to_edit_software_community\n if profile.class == Community && profile.software?\n redirect_to :action => 'edit_software_community'\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.7631579041481018,
"alphanum_fraction": 0.7631579041481018,
"avg_line_length": 24.33333396911621,
"blob_id": "065159ecf5677190a85e7f32eb1f22c67134dae7",
"content_id": "3477b4e6a59ee0a87af4350d9b526ebd6d1ce127",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 3,
"path": "/cookbooks/gitlab/files/gitlab_path.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "Gitlab::Application.configure do\n config.relative_url_root = \"/gitlab\"\nend\n"
},
{
"alpha_fraction": 0.612500011920929,
"alphanum_fraction": 0.612500011920929,
"avg_line_length": 21.22222137451172,
"blob_id": "dc97dae0805fd8137e1b6197e0e5f494edc2ace3",
"content_id": "af5cfcc0e550f258fdc20e4eb93b5be57bf16110",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 400,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 18,
"path": "/cookbooks/basics/recipes/nginx.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'nginx'\n\nservice 'nginx' do\n action :enable\n supports :restart => true\nend\n\n################################\n# SELinux: allow nginx to use log files\n################################\ncookbook_file '/etc/selinux/local/nginx.te' do\n notifies :run, 'execute[selinux-nginx]'\nend\n\nexecute 'selinux-nginx' do\n command 'selinux-install-module /etc/selinux/local/nginx.te'\n action :nothing\nend\n"
},
{
"alpha_fraction": 0.688725471496582,
"alphanum_fraction": 0.6911764740943909,
"avg_line_length": 25.322580337524414,
"blob_id": "3fb86b22349ac379359b5ee0695a17a1f4586578",
"content_id": "537c664a9f885ef042cc4e8e697924da8e13f11b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 816,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 31,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150727161511_change_software_layout.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class ChangeSoftwareLayout < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n if software_template\n change_layout(software_template)\n end\n\n softwares = SoftwareCommunitiesPlugin::SoftwareInfo.all\n softwares.each do |software|\n if software.community\n change_layout(software.community)\n end\n end\n puts \"\"\n end\n\n def down\n end\n\n def change_layout(community)\n community.layout_template = \"lefttopright\"\n print \".\" if community.save\n boxToMove = community.boxes.where(:position => 1).first\n blockToMove = boxToMove.blocks.where(:type => \"SoftwareInformationBlock\").first\n if blockToMove\n newBox = community.boxes.where(:position => 4).first\n blockToMove.box = newBox\n print \".\" if blockToMove.save\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6346153616905212,
"alphanum_fraction": 0.6634615659713745,
"avg_line_length": 19.799999237060547,
"blob_id": "61151c4028bac356f07d1c41f4db5deaaaf34e70",
"content_id": "3ec190fb786c9fd97c49d36d2bb3cb8a2bf2212b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 416,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 20,
"path": "/test/bin/curl",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\n\nunset http_proxy\nunset https_proxy\n\nROOTDIR=$(dirname $0)/../..\n. $(dirname $0)/../ip_helper.sh\n\n/usr/bin/curl \\\n --silent \\\n --noproxy '*' \\\n --fail \\\n --insecure \\\n --resolve softwarepublico.dev:80:$reverseproxy \\\n --resolve softwarepublico.dev:443:$reverseproxy \\\n --resolve listas.softwarepublico.dev:80:$reverseproxy \\\n --resolve listas.softwarepublico.dev:443:$reverseproxy \\\n \"$@\"\n"
},
{
"alpha_fraction": 0.6946778893470764,
"alphanum_fraction": 0.7009803652763367,
"avg_line_length": 24.96363639831543,
"blob_id": "da4e4dc156ca1851a2f20ca4c8d19a49219ea631",
"content_id": "b62d5f15ab81f858baf27afab573f29efef8e04c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1428,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 55,
"path": "/cookbooks/ci/recipes/jenkins.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "JENKINS_CLI = '/var/cache/jenkins/war/WEB-INF/jenkins-cli.jar'\n\nexecute 'jenkins_repo' do\n command 'wget -q -O - http://pkg.jenkins-ci.org/debian-stable/jenkins-ci.org.key | sudo apt-key add -'\n not_if 'apt-key list | grep D50582E6'\nend\n\nexecute 'apt_sources' do\n command 'echo \"deb http://pkg.jenkins-ci.org/debian-stable binary/\" >> /etc/apt/sources.list && apt-get update'\n not_if 'cat /etc/apt/sources.list | grep jenkins-ci'\nend\n\npackage 'jenkins'\n\nservice 'jenkins' do\n action [:enable, :start]\nend\n\npackage 'nginx'\n\nservice 'nginx' do\n action [:enable, :start]\nend\n\nfile '/etc/nginx/sites-available/default' do\n action :delete\nend\n\ncookbook_file 'nginx' do\n path '/etc/nginx/sites-available/jenkins'\nend\n\nfile '/etc/nginx/sites-enabled/default' do\n action :delete\nend\n\nlink '/etc/nginx/sites-enabled/jenkins' do\n to '/etc/nginx/sites-available/jenkins'\n not_if 'test -L /etc/nginx/sites-enabled/jenkins'\n notifies :restart, 'service[nginx]'\nend\n\npackage 'git'\n\nplugins = ['git-client', 'git-server', 'build-blocker-plugin', 'greenballs', 'view-job-filters', 'gitlab-plugin']\n\nplugins.each do |plugin|\n execute \"install jenkins plugin #{plugin}\" do\n command \"java -jar #{JENKINS_CLI} -s http://localhost/ install-plugin #{plugin}\"\n retries 5\n retry_delay 10\n not_if \"java -jar #{JENKINS_CLI} -s http://localhost/ list-plugins | grep ^#{plugin}\"\n notifies :restart, 'service[jenkins]'\n end\nend\n"
},
{
"alpha_fraction": 0.5926328301429749,
"alphanum_fraction": 0.5978260636329651,
"avg_line_length": 41.67525863647461,
"blob_id": "c85a9a3845706c73fc19e7ab0a2aaeddb452f38a",
"content_id": "c5f3afa8ec8a31e15f4937de6138cad73b2b8c4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 8280,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 194,
"path": "/src/noosfero-spb/spb_migrations/lib/tasks/box_organizer.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#encoding: utf-8\n\nnamespace :software do\n desc \"Adds breadcrumbs and events block to softwares\"\n task :boxes_all => [:clear_breadcrumbs_and_event_blocks, :fix_blocks_position, :box_organize]\n\n desc \"Delete breadcrumbs and events block from softwares\"\n task :clear_breadcrumbs_and_event_blocks => :environment do\n env = Environment.find_by_name(\"SPB\")\n if env.present?\n env.communities.find_each do |c|\n if c.software? || c.identifier == \"software\"\n c.boxes.each do |box|\n Block.where(\"(type = 'BreadcrumbsPlugin::ContentBreadcrumbsBlock' OR \n type = 'SoftwareCommunitiesPlugin::SoftwareEventsBlock') AND\n box_id = #{box.id}\").destroy_all\n end\n end\n end\n end\n end\n\n desc \"Fixes all blocks position in all softwares\"\n task :fix_blocks_position => :environment do\n env = Environment.find_by_name(\"SPB\")\n if env.present?\n ActiveRecord::Migration.execute(\"\n UPDATE blocks SET position = newpos FROM (SELECT blocks.id, blocks.position, boxes.owner_id, row_number() over\n (partition by boxes.id ORDER BY blocks.position ASC) as newpos FROM blocks INNER JOIN boxes ON\n blocks.box_id = boxes.id INNER JOIN profiles ON boxes.owner_id = profiles.id INNER JOIN environments ON\n profiles.environment_id = environments.id WHERE profiles.type = 'Community' AND environments.id = #{env.id}) as\n t WHERE blocks.id = t.id;\n \")\n end\n end\n\n desc \"Create missing blocks in software and templates\"\n task :box_organize => :environment do\n a = Profile['sgdoc'].boxes[0].blocks\n env = Environment.find_by_name(\"SPB\")\n software_template = env.communities.find_by_identifier \"software\"\n\n puts \"Searching for software template and environment...\"\n return if software_template.nil? || env.nil?\n\n puts \"Creating template boxes:\"\n template_breadcrumbs = nil\n box_one = software_template.boxes.find_by_position 1\n\n unless box_has_block_of_type?(box_one, \"BreadcrumbsPlugin::ContentBreadcrumbsBlock\")\n template_breadcrumbs = BreadcrumbsPlugin::ContentBreadcrumbsBlock.new(\n :mirror => true,\n :move_modes => \"none\",\n :edit_modes => \"none\")\n template_breadcrumbs.settings[:fixed] = true\n template_breadcrumbs.display = \"always\"\n template_breadcrumbs.save!\n\n box_one.blocks << template_breadcrumbs\n box_one.save!\n pos = box_one.blocks.order(:position).first.position\n change_block_pos(box_one, template_breadcrumbs, pos)\n print \".\"\n end\n ############################################################################\n\n software_template = env.communities.find_by_identifier \"software\"\n box_one = software_template.boxes.find_by_position 1\n\n template_software_events_1 = nil\n\n unless box_has_block_of_type?(box_one, \"SoftwareCommunitiesPlugin::SoftwareEventsBlock\")\n template_software_events_1 = SoftwareCommunitiesPlugin::SoftwareEventsBlock.new(\n :mirror => true,\n :move_modes => \"none\",\n :edit_modes => \"none\")\n template_software_events_1.display = \"except_home_page\"\n template_software_events_1.save!\n box_one.blocks << template_software_events_1\n box_one.save!\n\n pos = box_one.blocks.detect { |bl| bl.type == \"SoftwareCommunitiesPlugin::SoftwareTabDataBlock\"}.position\n change_block_pos(box_one, template_software_events_1, pos)\n print \".\"\n end\n ############################################################################\n\n template_software_events_2 = nil\n box_two = software_template.boxes.find_by_position 2\n\n unless box_has_block_of_type?(box_two, \"SoftwareCommunitiesPlugin::SoftwareEventsBlock\")\n pos = box_two.blocks.order(:position).last.position\n\n template_software_events_2 = SoftwareCommunitiesPlugin::SoftwareEventsBlock.new(\n :mirror => true,\n :move_modes => \"none\",\n :edit_modes => \"none\",\n :amount_of_events => 5)\n template_software_events_2.title = \"Outros Eventos\"\n template_software_events_2.display = \"except_home_page\"\n template_software_events_2.save\n\n box_two.blocks << template_software_events_2\n box_two.save!\n\n pos = box_two.blocks.order(:position).last.position\n change_block_pos(box_two, template_software_events_2, pos+1)\n print \".\"\n end\n ############################################################################\n\n puts \"\\nCreate software community boxes:\"\n env.communities.each do |community|\n next unless community.software?\n box_one = community.boxes.find_by_position 1\n\n unless box_has_block_of_type?(box_one, \"BreadcrumbsPlugin::ContentBreadcrumbsBlock\")\n breadcrumbs_block = BreadcrumbsPlugin::ContentBreadcrumbsBlock.new(\n :move_modes => \"none\", :edit_modes => \"none\"\n )\n breadcrumbs_block.settings[:fixed] = true\n breadcrumbs_block.display = \"always\"\n breadcrumbs_block.mirror_block_id = template_breadcrumbs.id if template_breadcrumbs\n breadcrumbs_block.save!\n\n box_one.blocks << breadcrumbs_block\n box_one.save!\n\n # Puts the breadcrumbs as the first one on box one\n pos = box_one.blocks.order(:position).first.position\n change_block_pos(box_one, breadcrumbs_block, pos)\n print \".\"\n end\n\n community.reload\n box_one = community.boxes.find_by_position 1\n\n ############################################################################\n unless box_has_block_of_type?(box_one, \"SoftwareCommunitiesPlugin::SoftwareEventsBlock\")\n software_events_block_1 = SoftwareCommunitiesPlugin::SoftwareEventsBlock.new(\n :move_modes => \"none\",\n :edit_modes => \"none\")\n software_events_block_1.display = \"except_home_page\"\n software_events_block_1.mirror_block_id = template_software_events_1.id if template_software_events_1\n software_events_block_1.save!\n box_one.blocks << software_events_block_1\n box_one.save!\n\n pos = box_one.blocks.detect { |bl| bl.type == \"SoftwareCommunitiesPlugin::SoftwareTabDataBlock\"}.position\n # Puts the software events block above SoftwareCommunitiesPlugin:: Tab Data on area one\n change_block_pos(box_one, software_events_block_1, pos)\n print \".\"\n end\n\n ############################################################################\n box_two = community.boxes.find_by_position 2\n\n unless box_has_block_of_type?(box_two, \"SoftwareCommunitiesPlugin::SoftwareEventsBlock\")\n software_events_block_2 = SoftwareCommunitiesPlugin::SoftwareEventsBlock.new(\n :move_modes => \"none\",\n :edit_modes => \"none\",\n :amount_of_events => 5)\n\n software_events_block_2.title = \"Outros Eventos\"\n software_events_block_2.display = \"except_home_page\"\n software_events_block_2.mirror_block_id = template_software_events_2.id if template_software_events_2\n software_events_block_2.save!\n box_two.blocks << software_events_block_2\n box_two.save!\n\n # Puts the software events block as the last one on area two\n pos = box_two.blocks.order(:position).last.position\n change_block_pos(box_two, software_events_block_2, pos+1)\n print \".\"\n end\n end\n\n puts \"All blocks created with success.\"\n end\n\n def change_block_pos(box, block, pos)\n box.blocks.each do |b|\n if b.position >= pos\n ActiveRecord::Migration.execute(\"UPDATE blocks set position = #{b.position+1} WHERE id = #{b.id}\")\n end\n end\n ActiveRecord::Migration.execute(\"UPDATE blocks set position = #{pos} WHERE id = #{block.id}\")\n end\n\n def box_has_block_of_type?(box, block_type)\n blocks = box.blocks.detect {|bl| bl.type == block_type}\n blocks.present?\n end\nend\n\n"
},
{
"alpha_fraction": 0.6691358089447021,
"alphanum_fraction": 0.6691358089447021,
"avg_line_length": 35.818180084228516,
"blob_id": "110fbe4fde49b6657ccd736abd37bbfffc946820",
"content_id": "8161348c7c39a52b8fa3a03b27d33286a1a6aab5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 405,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 11,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160308161603_move_spb_blog_to_noticias.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class MoveSpbBlogToNoticias < ActiveRecord::Migration\n def change\n spb = Environment.default.communities.where(:identifier => 'spb').first\n if spb\n blog = spb.blogs.where(:slug => 'blog').first\n noticias = spb.blogs.where(:slug => 'noticias').first\n\n execute(\"UPDATE articles SET parent_id = #{noticias.id} WHERE parent_id = #{blog.id} AND profile_id = #{spb.id}\")\n end\n end\nend\n"
},
{
"alpha_fraction": 0.5983051061630249,
"alphanum_fraction": 0.5983051061630249,
"avg_line_length": 18.66666603088379,
"blob_id": "d56bce1c5a09881ea7f9a574f5554b206e2ee270",
"content_id": "9b5508367a7f1dfab7cfabe69607ddd60f6e4f41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 590,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 30,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/wiki_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::WikiBlock < Block\n\n attr_accessible :show_name, :wiki_link\n settings_items :show_name, :type => :boolean, :default => false\n settings_items :wiki_link, :type => :string, :default => \"\"\n\n def self.description\n _('Wiki Link')\n end\n\n def help\n _('This block displays a link to the software wiki.')\n end\n\n def content(args={})\n block = self\n s = show_name\n\n lambda do |object|\n render(\n :file => 'blocks/wiki',\n :locals => { :block => block, :show_name => s }\n )\n end\n end\n\n def cacheable?\n true\n end\nend\n"
},
{
"alpha_fraction": 0.7223942279815674,
"alphanum_fraction": 0.7285861968994141,
"avg_line_length": 31.299999237060547,
"blob_id": "2841501baec8e30cf2dfb42366fa576262661552",
"content_id": "a9829193011b6096289f035677c7c3423da50bcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 969,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 30,
"path": "/utils/migration/restore_integration.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\necho 'Starting restore on integration...'\n# Colab Restore\necho 'restoring colab...'\npsql -U colab -h database colab < /tmp/backups/colab.dump 1> /dev/null 2> /dev/null\ncolab-admin migrate > /dev/null\necho 'done.'\n\n# Gitlab Restore\necho 'cleaning gitlab backups directory'\nsudo rm -rf /var/lib/gitlab/backups/*\necho 'restoring gitlab...'\n#TODO: fix wildcard\nmv /tmp/backups/*_gitlab_backup.tar /var/lib/gitlab/backups/\ncd /usr/lib/gitlab\nsudo -u git bundle exec rake gitlab:backup:restore RAILS_ENV=production force=yes 1> /dev/null 2>/dev/null\nsudo rm -rf /var/lib/gitlab/backups/*\necho 'done.'\n\n# Mailman Restore\necho 'restoring mailman...'\nsudo mv /tmp/backups/mailman_backup.tar.gz /var/lib/mailman/\ncd /var/lib/mailman\nsudo tar -xzf mailman_backup.tar.gz\nsudo rm mailman_backup.tar.gz\ncd /usr/lib/mailman/bin\nfor list in `sudo ls /var/lib/mailman/lists`; do sudo ./withlist -l -r fix_url $list -u $SPB_URL 1> /dev/null 2> /dev/null; done\n\necho 'done.'\n"
},
{
"alpha_fraction": 0.6620926260948181,
"alphanum_fraction": 0.6643796563148499,
"avg_line_length": 32.63461685180664,
"blob_id": "b918afaa8a6c22c267f01e6d6f82ddb7a9688b4c",
"content_id": "579caa24eaa41cf837b23ed7b1d741a6acc507ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1749,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 52,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150904202116_add_software_tab_data_block_to_all_softwares.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddSoftwareTabDataBlockToAllSoftwares < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n if software_template\n software_area_one = software_template.boxes.find_by_position 1\n\n template_soft_tab_block = SoftwareTabDataBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n template_soft_tab_block.settings[:fixed] = true\n template_soft_tab_block.display = \"except_home_page\"\n template_soft_tab_block.save!\n print \".\"\n\n software_area_one.blocks << template_soft_tab_block\n software_area_one.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n last_block_position = software_area_one.blocks.order(:position).last.position\n template_soft_tab_block.position = last_block_position + 1\n template_soft_tab_block.save!\n print \".\"\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_one = software_community.boxes.find_by_position 1\n print \".\"\n\n soft_tab_block = SoftwareTabDataBlock.new :move_modes => \"none\", :edit_modes => \"none\"\n soft_tab_block.settings[:fixed] = true\n soft_tab_block.display = \"except_home_page\"\n soft_tab_block.mirror_block_id = template_soft_tab_block.id\n soft_tab_block.save!\n print \".\"\n\n software_area_one.blocks << soft_tab_block\n software_area_one.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n last_block_position = software_area_one.blocks.order(:position).last.position\n soft_tab_block.position = last_block_position + 1\n soft_tab_block.save!\n print \".\"\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.5758853554725647,
"alphanum_fraction": 0.5826306939125061,
"avg_line_length": 23.70833396911621,
"blob_id": "251b3fc15a3301f1222c31d7490bc0727e9aadf3",
"content_id": "46c044bfa51dc64861959be3d2fd2448fda39889",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1186,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 48,
"path": "/cookbooks/mailman/recipes/webui.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "if node['platform'] == 'centos'\n cookbook_file '/etc/yum.repos.d/mailman.repo' do\n action :delete\n end\nend\n\npackage 'fcgiwrap'\npackage 'spawn-fcgi'\n\n#######################################################################\n# SELinux: allow nginx to connect to the fcgiwrap socket\n#######################################################################\ncookbook_file '/etc/selinux/local/spb_mailman.te' do\n notifies :run, 'execute[selinux-mailman]'\nend\nexecute 'selinux-mailman' do\n command 'selinux-install-module /etc/selinux/local/spb_mailman.te'\n action :nothing\nend\n#######################################################################\n\nhostname = node['config']['lists_hostname']\ntemplate \"/etc/nginx/conf.d/#{hostname}.conf\" do\n source 'mailman.conf.erb'\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\nend\n\ncookbook_file '/etc/sysconfig/spawn-fcgi' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[spawn-fcgi]'\nend\n\ngroup 'apache' do\n action 'manage'\n append true\n members ['nginx']\n notifies :restart, 'service[nginx]'\nend\n\nservice 'spawn-fcgi' do\n action [:enable, :start]\n supports :restart => true\nend\n"
},
{
"alpha_fraction": 0.6630260944366455,
"alphanum_fraction": 0.6640454530715942,
"avg_line_length": 29.251100540161133,
"blob_id": "d49fcb8ee46f9067206b4b93a95e36a75d475add",
"content_id": "de65e56c9e0f62283bc1f27940f8a06b1d25eb8b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 6867,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 227,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin < Noosfero::Plugin\n include ActionView::Helpers::TagHelper\n include ActionView::Helpers::FormTagHelper\n include ActionView::Helpers::FormOptionsHelper\n include ActionView::Helpers::JavaScriptHelper\n include ActionView::Helpers::AssetTagHelper\n include FormsHelper\n include ActionView::Helpers\n include ActionDispatch::Routing\n include Rails.application.routes.url_helpers\n\n def self.plugin_name\n 'SoftwareCommunitiesPlugin'\n end\n\n def self.plugin_description\n _('Add Public Software and MPOG features.')\n end\n\n def self.api_mount_points\n [SoftwareCommunitiesPlugin::API]\n end\n\n SOFTWARE_CATEGORIES = [\n _('Agriculture, Fisheries and Extraction'),\n _('Science, Information and Communication'),\n _('Economy and Finances'),\n _('Public Administration'),\n _('Habitation, Sanitation and Urbanism'),\n _('Individual, Family and Society'),\n _('Health'),\n _('Social Welfare and Development'),\n _('Defense and Security'),\n _('Education'),\n _('Government and Politics'),\n _('Justice and Legislation'),\n _('International Relationships'),\n _('Transportation and Transit')\n ]\n\n def profile_tabs\n if context.profile.community? && context.profile.software?\n return profile_tabs_software\n end\n end\n\n def control_panel_buttons\n if context.profile.software?\n return software_info_button\n elsif context.profile.person?\n return create_new_software_button\n end\n end\n\n def self.extra_blocks\n {\n SoftwareCommunitiesPlugin::SoftwaresBlock => { :type => [Environment, Person] },\n SoftwareCommunitiesPlugin::SoftwareInformationBlock => { :type => [Community] },\n SoftwareCommunitiesPlugin::DownloadBlock => { :type => [Community] },\n SoftwareCommunitiesPlugin::RepositoryBlock => { :type => [Community] },\n SoftwareCommunitiesPlugin::CategoriesAndTagsBlock => { :type => [Community] },\n SoftwareCommunitiesPlugin::CategoriesSoftwareBlock => { :type => [Environment] },\n SoftwareCommunitiesPlugin::SearchCatalogBlock => { :type => [Environment] },\n SoftwareCommunitiesPlugin::SoftwareHighlightsBlock => { :type => [Environment] },\n SoftwareCommunitiesPlugin::SoftwareTabDataBlock => {:type => [Community], :position => 1},\n SoftwareCommunitiesPlugin::SispTabDataBlock => {:type => [Community], :position => 1},\n SoftwareCommunitiesPlugin::WikiBlock => {:type => [Community]},\n SoftwareCommunitiesPlugin::StatisticBlock => { :type => [Community] },\n SoftwareCommunitiesPlugin::SoftwareEventsBlock => { :type => [Community] }\n }\n end\n\n def self.software_categories\n software_category = Category.find_by_name(\"Software\")\n if software_category.nil?\n []\n else\n software_category.children\n end\n end\n\n def stylesheet?\n true\n end\n\n def js_files\n %w(\n vendor/jquery.maskedinput.min.js\n vendor/modulejs-1.5.0.min.js\n vendor/jquery.js\n lib/noosfero-root.js\n lib/select-element.js\n lib/select-field-choices.js\n lib/auto-complete.js\n lib/software-catalog-component.js\n views/control-panel.js\n views/edit-software.js\n views/new-software.js\n views/search-software-catalog.js\n views/profile-tabs-software.js\n views/new-community.js\n views/comments-software-extra-fields.js\n blocks/software-download.js\n initializer.js\n app.js\n )\n end\n\n module Hotspots\n def display_organization_average_rating organization\n nil\n end\n end\n\n def organization_ratings_plugin_comments_extra_fields\n if context.profile.software?\n Proc::new { render :file => 'comments_extra_fields' }\n end\n end\n\n def organization_ratings_plugin_star_message\n Proc::new do _(\"Rate this software\") end\n end\n\n def organization_ratings_title\n title = _('Use reports')\n ratings_count = OrganizationRating.statistics_for_profile(profile)[:total]\n Proc::new do \"<h1 class='title'>#{title} (#{ratings_count})</h1>\" end\n end\n\n def organization_ratings_plugin_container_extra_fields user_rating\n Proc::new {\n if logged_in?\n is_admin = user.is_admin? || user_rating.organization.is_admin?(user)\n\n if is_admin and profile.software?\n\n render :file => 'organization_ratings_container_extra_fields_show_statistics',\n :locals => {:user_rating => user_rating}\n end\n end\n }\n end\n\n def organization_ratings_plugin_rating_created rating, params\n if params[:organization_rating].present? && (params[:organization_rating][:people_benefited].present? ||\n params[:organization_rating][:saved_value].present?)\n CreateOrganizationRatingComment.create!(\n :requestor => rating.person,\n :organization_rating_id => rating.id,\n :target => rating.organization) unless params[:comments] && params[:comments][:body].present?\n end\n end\n\n def organization_ratings_plugin_task_extra_fields user_rating\n Proc::new {\n if logged_in?\n is_admin = user.is_admin? || user_rating.organization.is_admin?(user)\n\n if is_admin and profile.software?\n render :file => 'organization_ratings_task_extra_fields_show_statistics',\n :locals => {:user_rating => user_rating}\n end\n end\n }\n end\n\n def html_tag_classes\n lambda do\n \"article-type-#{@page.css_class_name}\" if @page\n end\n end\n\n # FIXME - if in error log apears has_permission?, try to use this method\n def has_permission?(person, permission, target)\n person.has_permission_without_plugins?(permission, target)\n end\n\n protected\n\n def software_info_transaction\n SoftwareCommunitiesPlugin::SoftwareInfo.transaction do\n context.profile.\n software_info.\n update_attributes!(context.params[:software_info])\n end\n end\n\n def license_transaction\n license = SoftwareCommunitiesPlugin::LicenseInfo.find(context.params[:version])\n context.profile.software_info.license_info = license\n context.profile.software_info.save!\n end\n\n private\n\n def software_info_button\n {\n :title => _('Software Info'),\n :icon => 'edit-profile-group control-panel-software-link',\n :url => {\n :controller => 'software_communities_plugin_myprofile',\n :action => 'edit_software'\n }\n }\n end\n\n def create_new_software_button\n {\n :title => _('Create a new software'),\n :icon => 'design-editor',\n :url => {\n :controller => 'software_communities_plugin_myprofile',\n :action => 'new_software'\n }\n }\n end\n\n def profile_tabs_software\n { :title => _('Software'),\n :id => 'software-fields',\n :content => Proc::new do render :partial => 'profile/software_tab' end,\n :start => true }\n end\nend\n\nrequire_dependency 'macros/allow_variables'\n"
},
{
"alpha_fraction": 0.6909413933753967,
"alphanum_fraction": 0.6909413933753967,
"avg_line_length": 30.27777862548828,
"blob_id": "023db87f97cb6f73973e97409c7c020549696d0e",
"content_id": "ce6b1a2e66ede954a843f375f526f619fcfeb139",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 563,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 18,
"path": "/monitoring/Rakefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "basedir = File.expand_path(File.dirname(__FILE__))\n\nDir.chdir File.join(basedir, '..')\n\nENV['CHAKE_NODES'] = File.join(basedir, 'nodes.yaml')\nENV['CHAKE_RSYNC_OPTIONS'] = '--exclude .vagrant/ --exclude docs/_build'\nENV['CHAKE_TMPDIR'] = 'tmp/chake.monitoring'\nENV['CHAKE_SSH_CONFIG'] = File.join(basedir, 'ssh_config')\n\nrequire 'chake'\n\nips = YAML.load_file('config/prod/ips.yaml')\nfirewall = File.read('monitoring/iptables-filter-rules')\n$nodes.each do |node|\n node.data['environment'] = 'prod'\n node.data['peers'] = ips\n node.data['firewall'] = firewall\nend\n"
},
{
"alpha_fraction": 0.5969230532646179,
"alphanum_fraction": 0.6215384602546692,
"avg_line_length": 31.5,
"blob_id": "bc0691381461076942156ba69d9bad74619650f3",
"content_id": "f8819987a4e9386be47cdbad8dc47b351bfc0c07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 325,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 10,
"path": "/test/ip_helper.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# make IP addresses avaliable at the environment so we can refer to hosts by\n# name, e.g.\n#\n# curl http://$reverseproxy\n# nmap -p 5423 $database\n#\n# Each entry in config/${SPB_ENV}/ips.yaml will have its own variable\n#\n\neval $(sed -E '/[0-9]{1,3}\\./!d; s/^ *//; s/: */=/' ${ROOTDIR:-.}/config/${SPB_ENV:-local}/ips.yaml)\n"
},
{
"alpha_fraction": 0.59325110912323,
"alphanum_fraction": 0.6026850342750549,
"avg_line_length": 36.75342559814453,
"blob_id": "1c9f71e68ec778401aac3a1e196d5c7d568b9e3e",
"content_id": "c5cd679578a1d4661589b67453b457df8e27008b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2756,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 73,
"path": "/script/software_communities_ci.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "RED='\\033[1;31m'\nGREEN='\\033[1;32m'\nNC='\\033[0m'\ncurrent_path=$(pwd)\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling SPB plugins${NC}\\n\"\nln -s \"$current_path/../src/noosfero-spb/software_communities/\" plugins/software_communities\nln -s \"$current_path/../src/noosfero-spb/gov_user/\" plugins/gov_user\nln -s \"$current_path/../src/noosfero-spb/spb_migrations/\" plugins/spb_migrations\nln -s \"$current_path/../src/noosfero-spb/noosfero-spb-theme\" public/designs/themes/noosfero-spb-theme\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling Organization Ratings${NC}\\n\"\n./script/noosfero-plugins enable organization_ratings\nbundle exec rake db:migrate\nratings=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling Gov User, Software Communities and SPB Migrations${NC}\\n\"\n./script/noosfero-plugins enable software_communities gov_user\nbundle exec rake db:migrate\ngov_and_soft_plugins=$?\n\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling SPB Migrations${NC}\\n\"\n./script/noosfero-plugins enable spb_migrations\nbundle exec rake db:migrate\nspb_migrations=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Compiling translations${NC}\\n\"\nrake noosfero:translations:compile &>/dev/null\ntranslations=$?\n\nif [ $gov_and_soft_plugins -ne 0 ] || [ $ratings -ne 0 ] || [ $translations -ne 0 ] || [ $spb_migrations -ne 0 ]; then\n\tprintf \"${RED}=================================\\n\"\n\tprintf \"Error migrating SPB plugins!!n${NC}\\n\"\n exit 1\nfi\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Running rake db:test:prepare${NC}\\n\"\nbundle exec rake db:test:prepare\n\n# =======================================================================================\n./script/noosfero-plugins disable gov_user\nprintf \"${GREEN}=================================\\n\"\nprintf \"SoftwareCommunitiesPlugin:UNITS${NC}\\n\"\nrake test:units TEST=plugins/software_communities/test/unit/*\nunits=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"SoftwareCommunitiesPlugin:FUNCTIONALS${NC}\\n\"\nrake test:functionals TEST=plugins/software_communities/test/functional/*\nfunctionals=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"SoftwareCommunitiesPlugin:SELENIUM${NC}\\n\"\nruby -S cucumber --profile software_communities_selenium --format progress\nselenium=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"SoftwareCommunitiesPlugin:CUCUMBER${NC}\\n\"\nruby -S cucumber --profile software_communities --format progress\ncucumber=$?\n\nif [ $units -ne 0 ] || [ $functionals -ne 0 ] || [ $selenium -ne 0 ] || [ $cucumber -ne 0 ]; then\n\tprintf \"${RED}=================================\\n\"\n\tprintf \"ERROR RUNNING SOFTWARE COMMUNITIES PLUGIN TESTS${NC}\\n\"\n\texit 1\nfi\n"
},
{
"alpha_fraction": 0.652847409248352,
"alphanum_fraction": 0.6542962193489075,
"avg_line_length": 24.710601806640625,
"blob_id": "7154fd224c62dd8839d268c036bf5cc5c4125b43",
"content_id": "22b49bb9f928c940f5bbaac3a049296ad30bc019",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 8973,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 349,
"path": "/src/noosfero-spb/gov_user/lib/gov_user_plugin.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class GovUserPlugin < Noosfero::Plugin\n include ActionView::Helpers::TagHelper\n include ActionView::Helpers::FormTagHelper\n include ActionView::Helpers::FormOptionsHelper\n include ActionView::Helpers::JavaScriptHelper\n include ActionView::Helpers::AssetTagHelper\n include FormsHelper\n include ActionView::Helpers\n include ActionDispatch::Routing\n include Rails.application.routes.url_helpers\n\n def self.api_mount_points\n [GovUserPlugin::API]\n end\n\n def self.plugin_name\n \"GovUserPlugin\"\n end\n\n def self.plugin_description\n _(\"Add features related to Brazilian government.\")\n end\n\n def stylesheet?\n true\n end\n\n # Hotspot to insert html without an especific hotspot on view.\n def body_beginning\n return if context.session[:user].nil? or context.session[:hide_incomplete_percentage] == true\n\n person = context.environment.people.where(:user_id=>context.session[:user]).first\n\n if context.profile && context.profile.person? and !person.nil?\n @person = person\n @percentege = calc_percentage_registration(person)\n\n if @percentege >= 0 and @percentege < 100\n expanded_template('incomplete_registration.html.erb')\n end\n end\n end\n\n def profile_editor_transaction_extras\n single_hash_transactions = { :user => 'user',\n :instituton => 'instituton'\n }\n\n single_hash_transactions.each do |model, transaction|\n call_model_transaction(model, transaction)\n end\n end\n\n def profile_editor_controller_filters\n block = proc do\n if request.post? && params[:institution]\n unless user.is_admin?\n institution = profile.user.institutions\n\n if !params[:institution].blank? && params[:institution].class == Hash && !params[:institution][:sisp].nil?\n if params[:institution][:sisp] != institution.sisp\n params[:institution][:sisp] = institution.sisp\n end\n end\n end\n end\n end\n\n [{\n :type => 'before_filter',\n :method_name => 'validate_institution_sisp_field_access',\n :options => { :only => :edit },\n :block => block\n }]\n end\n\n def profile_tabs\n if context.profile.community?\n return profile_tabs_institution if context.profile.institution?\n end\n end\n\n def control_panel_buttons\n if context.profile.institution?\n return institution_info_button\n end\n end\n\n def self.extra_blocks\n {\n InstitutionsBlock => { :type => [Environment, Person] }\n }\n end\n\n def custom_user_registration_attributes(user)\n return if context.params[:user][:institution_ids].nil?\n context.params[:user][:institution_ids].delete('')\n\n update_user_institutions(user)\n\n user.institutions.each do |institution|\n community = institution.community\n community.add_member user.person\n end\n end\n\n def profile_editor_extras\n profile = context.profile\n\n if profile.person?\n expanded_template('person_editor_extras.html.erb')\n end\n end\n\n\n def calc_percentage_registration(person)\n required_list = profile_required_list\n empty_fields = profile_required_empty_list person\n count = required_list[:person_fields].count +\n required_list[:user_fields].count\n percentege = 100 - ((empty_fields.count * 100) / count)\n person.percentage_incomplete = percentege\n person.save(validate: false)\n percentege\n end\n\n def stylesheet?\n true\n end\n\n def admin_panel_links\n [\n {\n :title => _('Create Institution'),\n :url => {\n :controller => 'gov_user_plugin',\n :action => 'create_institution_admin'\n }\n }\n ]\n end\n\n\n def js_files\n %w(\n vendor/modulejs-1.5.0.min.js\n vendor/jquery.js\n lib/noosfero-root.js\n lib/select-element.js\n lib/select-field-choices.js\n views/complete-registration.js\n views/control-panel.js\n views/create-institution.js\n views/new-community.js\n views/user-edit-profile.js\n views/gov-user-comments-extra-fields.js\n views/institution-modal.js\n initializer.js\n app.js\n )\n end\n\n def admin_panel_links\n [\n {\n :title => _('Create Institution'),\n :url => {\n :controller => 'gov_user_plugin',\n :action => 'create_institution_admin'\n }\n }\n ]\n end\n\n protected\n\n def profile_required_list\n fields = {}\n fields[:person_fields] = %w(cell_phone\n contact_phone\n comercial_phone\n country\n city\n state\n organization_website\n image\n identifier\n name)\n\n fields[:user_fields] = %w(email)\n fields\n end\n\n def profile_required_empty_list(person)\n empty_fields = []\n required_list = profile_required_list\n\n required_list[:person_fields].each do |field|\n empty_fields << field.sub('_',' ') if person.send(field).blank?\n end\n required_list[:user_fields].each do |field|\n empty_fields << field.sub('_',' ') if person.user.send(field).blank?\n end\n empty_fields\n end\n\n\n protected\n\n def user_transaction\n user_editor_institution_actions\n\n User.transaction do\n context.profile.user.update_attributes!(context.params[:user])\n end\n end\n\n def institution_transaction\n institution.date_modification = DateTime.now\n institution.save\n institution_models = %w(governmental_power governmental_sphere\n juridical_nature)\n\n institution_models.each do |model|\n call_institution_transaction(model)\n end\n\n if context.params.has_key?(:institution)\n Institution.transaction do\n context.profile.\n institution.\n update_attributes!(context.params[:institution])\n end\n end\n end\n\n def organization_ratings_plugin_comments_extra_fields\n Proc::new do render :file => 'ratings_extra_field' end\n end\n\n def organization_ratings_plugin_task_extra_fields user_rating\n gov_user_self = self\n\n Proc::new {\n if logged_in?\n is_admin = user.is_admin? || user_rating.organization.is_admin?(user)\n\n if is_admin and gov_user_self.context.profile.software?\n render :file => 'organization_ratings_task_extra_fields_show_institution',\n :locals => {:user_rating => user_rating}\n end\n end\n }\n end\n\n def organization_ratings_plugin_container_extra_fields user_rating\n gov_user_self = self\n\n Proc::new {\n if logged_in?\n is_admin = user.is_admin? || user_rating.organization.is_admin?(user)\n\n if is_admin and gov_user_self.context.profile.software?\n render :file => 'organization_ratings_container_extra_fields_show_institution',\n :locals => {:user_rating => user_rating}\n end\n end\n }\n end\n\n private\n\n def call_model_transaction(model,name)\n send(name + '_transaction') if context.params.key?(model.to_sym)\n end\n\n def call_institution_transaction(model)\n context.profile.institution.send(model + '_id = ',\n context.params[model.to_sym])\n context.profile.institution.save!\n end\n\n # Add and remove the user from it's institutions communities\n def user_editor_institution_actions\n user = context.profile.user\n\n old_communities = []\n context.profile.user.institutions.each do |institution|\n old_communities << institution.community\n end\n\n new_communities = []\n unless context.params[:user][:institution_ids].nil?\n context.params[:user][:institution_ids].delete('')\n\n context.params[:user][:institution_ids].each do |id|\n new_communities << Institution.find(id).community\n end\n end\n\n manage_user_institutions(user, old_communities, new_communities)\n end\n\n def institution_info_button\n {\n :title => _('Institution Info'),\n :icon => 'edit-profile-group control-panel-instituton-link',\n :url => {\n :controller => 'gov_user_plugin_myprofile',\n :action => 'edit_institution'\n }\n }\n end\n\n def manage_user_institutions(user, old_communities, new_communities)\n leave_communities = (old_communities - new_communities)\n enter_communities = (new_communities - old_communities)\n\n leave_communities.each do |community|\n community.remove_member(user.person)\n user.institutions.delete(community.institution)\n end\n\n enter_communities.each do |community|\n community.add_member(user.person)\n user.institutions << community.institution\n end\n end\n\n def profile_tabs_institution\n { :title => _('Institution'),\n :id => 'intitution-fields',\n :content => Proc::new do render :partial => 'profile/institution_tab' end,\n :start => true\n }\n end\n\n def update_user_institutions(user)\n context.params[:user][:institution_ids].each do |institution_id|\n institution = Institution.find institution_id\n user.institutions << institution\n\n if institution.community.admins.blank?\n institution.community.add_admin(user.person)\n end\n end\n user.save unless user.institution_ids.empty?\n end\nend\n"
},
{
"alpha_fraction": 0.7985989451408386,
"alphanum_fraction": 0.7985989451408386,
"avg_line_length": 27.549999237060547,
"blob_id": "43a7de3e1fcdbff2516c524442ed56cd9f056e29",
"content_id": "e828f6d9d35054642c2a2d12ad6507b45cc2b198",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 600,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 20,
"path": "/README.md",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# Software Público Brasileiro - desenvolvimento\n\n## Organização\n\nEste repositório contém tanto o código fonte desenvolvimento especificamente\npara o SPB, quando o código de gestão de configuração necessário para implantar\no ambiente do SPB.\n\nO código fonte dos componentes e pacotes desenvolvidos está no diretório\n`src/`. Os demais diretórios contém código de gestão de configuração,\ndocumentação, utilitários etc.\n\n## Fazendo um release\n\n* Atualize o número de versão no arquivo VERSION\n* Execute `make release`.\n\n## Implantação\n\nVeja as instruções em README.chef.md.\n"
},
{
"alpha_fraction": 0.8079096078872681,
"alphanum_fraction": 0.8079096078872681,
"avg_line_length": 28.5,
"blob_id": "c31728d3362d36b4d10ab955cd22d897b71094d9",
"content_id": "e63ef96834ea631c83ae2846aa32a087edf5f57c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 177,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 6,
"path": "/cookbooks/mezuro/recipes/service.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# This recipes contains all services to run in the machine\n\nservice 'kalibro-configurations.target'\nservice 'kalibro-processor.target'\nservice 'prezento.target'\nservice 'nginx'\n"
},
{
"alpha_fraction": 0.6415094137191772,
"alphanum_fraction": 0.650943398475647,
"avg_line_length": 14.142857551574707,
"blob_id": "aa05146e222dddca8cfcce75db51601b2200da45",
"content_id": "a668a8c2e16a1e99c92e14ca4dda2c2287c5d2fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 7,
"path": "/test/bin/remove-list",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nlistname=\"$1\"\n\nsudo -u mailman /usr/lib/mailman/bin/rmlist -a \"$listname\" > /dev/null\n"
},
{
"alpha_fraction": 0.707317054271698,
"alphanum_fraction": 0.707317054271698,
"avg_line_length": 21.076923370361328,
"blob_id": "f92e6c177e640471e85fb07841012f89302a841f",
"content_id": "cb7ca3692cb457453e25a9a9c3c71ca10cfdcce7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 287,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 13,
"path": "/src/noosfero-spb/gov_user/lib/governmental_power.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class GovernmentalPower < ActiveRecord::Base\n attr_accessible :name\n\n validates :name, :presence=>true, :uniqueness=>true\n has_many :institutions\n\n def public_institutions\n Institution.where(\n :type=>\"PublicInstitution\",\n :governmental_power_id=>self.id\n )\n end\nend\n"
},
{
"alpha_fraction": 0.6883116960525513,
"alphanum_fraction": 0.6883116960525513,
"avg_line_length": 24.66666603088379,
"blob_id": "c02d671fc35184052ef8c177b1023838192b0187",
"content_id": "3770e5e99ff47e564a12262ff5db3b3839200afe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 231,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 9,
"path": "/cookbooks/email/recipes/client.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'email'\n\nexecute 'postfix:configrelay' do\n command \"postconf relayhost=[#{node['peers']['email']}]\"\n notifies :reload, 'service[postfix]'\n\n # not on the relay host itself\n not_if { node.hostname == 'email' }\nend\n"
},
{
"alpha_fraction": 0.745192289352417,
"alphanum_fraction": 0.7532051205635071,
"avg_line_length": 19.129032135009766,
"blob_id": "e2ccc8f2af5b7f3652743089098c9fcf692bfa43",
"content_id": "ef6ec6b528fb251360a6eb309e0a196a155b8569",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 624,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 31,
"path": "/cookbooks/ci/recipes/spb.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "cookbook_file '/etc/apt/sources.list.d/contrib.list' do\n notifies :run, 'execute[apt-update]', :immediately\nend\n\nexecute 'apt-update' do\n command 'apt-get update'\n action :nothing\nend\npackage 'virtualbox'\n\npackage 'vagrant'\npackage 'rake'\npackage 'shunit2'\n\n# for building colab-deps:\npackage 'python-virtualenv'\npackage 'libpq-dev'\npackage 'gettext'\npackage 'libxml2-dev'\npackage 'libxslt1-dev'\npackage 'libssl-dev'\npackage 'libffi-dev'\npackage 'libjpeg-dev'\npackage 'zlib1g-dev'\npackage 'libfreetype6-dev'\npackage 'python-dev'\npackage 'libyaml-dev'\npackage 'libev-dev'\n\n# FIXME not in the archive yet\n# package 'chake'\n"
},
{
"alpha_fraction": 0.7132075428962708,
"alphanum_fraction": 0.7132075428962708,
"avg_line_length": 19.384614944458008,
"blob_id": "a55c1f8ea150654073b058ab3ca3e09502cb2a8a",
"content_id": "f9303dd054fbbedd126eee668de4c0d22771ada7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 13,
"path": "/cookbooks/munin/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'munin'\n\ntemplate '/etc/munin/conf.d/hosts.conf'\n\npackage 'nginx'\nservice 'nginx' do\n action [:enable, :start]\n supports :reload => true\nend\ncookbook_file '/etc/nginx/default.d/munin.conf' do\n source 'nginx.conf'\n notifies :reload, 'service[nginx]'\nend\n"
},
{
"alpha_fraction": 0.6830357313156128,
"alphanum_fraction": 0.6830357313156128,
"avg_line_length": 17.66666603088379,
"blob_id": "90fcbb7689d567b2ff44296714b66d50ae8f5d43",
"content_id": "3393b2f912471048410a13bc1eb74d678e48281e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 224,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 12,
"path": "/cookbooks/mailman-api/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "if node['platform'] == 'centos'\n cookbook_file '/etc/yum.repos.d/mailman-api.repo' do\n action :delete\n end\nend\n\npackage 'mailman-api'\n\nservice 'mailman-api' do\n action [:enable, :start]\n supports :restart => true\nend\n"
},
{
"alpha_fraction": 0.7866666913032532,
"alphanum_fraction": 0.7866666913032532,
"avg_line_length": 36.5,
"blob_id": "ab2c9a9b20045f4aa1adb119b50d9071af762788",
"content_id": "55e3a39c02a11ef36e53b09c2a105074b54a2576",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 10,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/operating_system_name.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::OperatingSystemName < ActiveRecord::Base\n attr_accessible :name\n\n validates_presence_of :name\n validates_uniqueness_of :name\n\n has_many :operating_systems, :class_name => 'SoftwareCommunitiesPlugin::OperatingSystem'\n has_many :software_infos, :through => :operating_systems, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n\nend\n"
},
{
"alpha_fraction": 0.6298701167106628,
"alphanum_fraction": 0.6298701167106628,
"avg_line_length": 37.5,
"blob_id": "7287eca998cb4d34fcac2677c21eb821a8ed45cd",
"content_id": "2fe7cd118df0c8d0ce92e988b97228e6d656e305",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 154,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 4,
"path": "/config.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "root = File.expand_path(File.dirname(__FILE__))\nfile_cache_path root + '/cache'\ncookbook_path root + '/cookbooks'\nrole_path root + '/roles'\n"
},
{
"alpha_fraction": 0.7233250737190247,
"alphanum_fraction": 0.7270471453666687,
"avg_line_length": 27.785715103149414,
"blob_id": "a1bc2c0fe1f4454edc2ca7f910616e283c34cab0",
"content_id": "a6f20b00e6860f646f4bce78b45cd29651318584",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 806,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 28,
"path": "/test/mailman_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_mailman_running() {\n assertTrue 'mailman running' 'run_on integration pgrep -fa mailmanctl'\n}\n\ntest_mailman_delivery() {\n # create list\n run_on integration create-list mylist [email protected]\n\n # send message\n run_on integration send-email [email protected] [email protected]\n\n # wait for message to arrive at the list mailbox\n messages=$(run_on integration wait-for-messages mylist)\n\n # remove list\n run_on integration remove-list mylist\n\n assertEquals 'Message arrives at mailbox' \"1\" \"$messages\"\n}\n\ntest_mailman_web_interface() {\n local title=\"$(curl --location --header 'Host: listas.softwarepublico.dev' http://$config_external_hostname/mailman/cgi-bin/listinfo | grep -i '<title>')\"\n assertEquals \"<TITLE>listas.softwarepublico.dev Mailing Lists</TITLE>\" \"$title\"\n}\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.6875,
"alphanum_fraction": 0.6875,
"avg_line_length": 24.600000381469727,
"blob_id": "0ceaa13ce6b986652f9206acdcca9070fb909ca2",
"content_id": "749719f2e7af362eae2f1072e451a363ceae6f6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 512,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 20,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_highlights_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareHighlightsBlock < HighlightsBlock\n\n def self.description\n _('Software Highlights Block')\n end\n\n def help\n _('This block displays the softwares icon into a highlight')\n end\n\n def content(args={})\n softwares = self.settings[:images].collect {|h| h[:address].split('/').last}\n block = self\n proc do\n render :file => 'blocks/software_communities_plugin/software_highlights', :locals => { :block => block, :softwares => softwares}\n end\n end\n\n\nend\n"
},
{
"alpha_fraction": 0.6626873016357422,
"alphanum_fraction": 0.6764526963233948,
"avg_line_length": 28.00706672668457,
"blob_id": "27e44c719f7f45eb414b0ee0ecc6d53619e92d1b",
"content_id": "d4cda5191b6d3f1c94c1eceb00ce9ce8c7d70301",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 8209,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 283,
"path": "/src/noosfero-spb/gov_user/test/functional/gov_user_plugin_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/institution_test_helper'\nrequire File.dirname(__FILE__) + '/../../controllers/gov_user_plugin_controller'\n\nclass GovUserPluginController; def rescue_action(e) raise e end; end\nclass GovUserPluginControllerTest < ActionController::TestCase\n\n\n def setup\n @admin = create_user(\"adminuser\").person\n @admin.stubs(:has_permission?).returns(\"true\")\n login_as(@admin.user_login)\n\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.add_admin(@admin)\n @environment.save\n\n @gov_power = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n @response = ActionController::TestResponse.new\n\n @institution_list = []\n @institution_list << InstitutionTestHelper.create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"12.345.678/9012-45\"\n )\n @institution_list << InstitutionTestHelper.create_public_institution(\n \"Tribunal Regional da Uniao\",\n \"TRU\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"12.345.678/9012-90\"\n )\n\n end\n\n should \"Search for institution with acronym\" do\n xhr :get, :get_institutions, :query=>\"TRU\"\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert_equal \"Tribunal Regional da Uniao\", json_response[0][\"value\"]\n end\n\n should \"Search for institution with name\" do\n xhr :get, :get_institutions, :query=>\"Minis\"\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert_equal \"Ministerio Publico da Uniao\", json_response[0][\"value\"]\n end\n\n should \"search with name or acronym and return a list with institutions\" do\n xhr :get, :get_institutions, :query=>\"uni\"\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert json_response.any?{|r| r[\"value\"] == \"Ministerio Publico da Uniao\"}\n assert json_response.any?{|r| r[\"value\"] == \"Tribunal Regional da Uniao\"}\n end\n\n should \"method create_institution return the html for modal\" do\n @controller.stubs(:current_user).returns(@admin.user)\n xhr :get, :create_institution\n assert_template 'create_institution'\n end\n\n should \"create new institution with ajax without acronym\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"foo bar\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"12.234.567/8900-10\",\n \"PublicInstitution\"\n )\n fields[:institutions][:governmental_power] = @gov_power.id\n fields[:institutions][:governmental_sphere] = @gov_sphere.id\n fields[:institutions][:juridical_nature] = @juridical_nature.id\n\n xhr :get, :new_institution, fields\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert json_response[\"success\"]\n end\n\n should \"not create a private institution without cnpj\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Some Private Institution\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"\",\n \"PrivateInstitution\"\n )\n fields[:institutions][:acronym] = \"SPI\"\n\n xhr :get, :new_institution, fields\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert_equal false, json_response[\"success\"]\n assert_equal false, json_response[\"errors\"].blank?\n end\n\n should \"create public institution without cnpj\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Some Private Institution\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"56.366.790/0001-88\",\n \"PublicInstitution\"\n )\n fields[:institutions][:governmental_power] = @gov_power.id\n fields[:institutions][:governmental_sphere] = @gov_sphere.id\n fields[:institutions][:juridical_nature] = @juridical_nature.id\n\n xhr :get, :new_institution, fields\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert json_response[\"success\"]\n end\n\n should \"verify if institution name already exists\" do\n xhr :get, :institution_already_exists, :name=>\"Ministerio Publico da Uniao\"\n assert_equal \"true\", @response.body\n\n xhr :get, :institution_already_exists, :name=>\"Another name here\"\n assert_equal \"false\", @response.body\n end\n\n should \"hide registration incomplete message\" do\n xhr :get, :hide_registration_incomplete_percentage, :hide=>true\n assert_equal \"true\", @response.body\n end\n\n should \"not hide registration incomplete message\" do\n xhr :get, :hide_registration_incomplete_percentage, :hide=>false\n assert_equal \"false\", @response.body\n end\n\n should \"Create new institution with method post\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Some Private Institution\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"12.345.567/8900-10\",\n \"PrivateInstitution\"\n )\n fields[:institutions][:acronym] = \"SPI\"\n\n post :new_institution, fields\n\n assert_redirected_to(controller: \"admin_panel\", action: \"index\")\n end\n\n should \"not create new institution with method post without cnpj\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Some Private Institution\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"56.366.790/0001-88\",\n \"PrivateInstitution\"\n )\n\n post :new_institution, fields\n\n assert_redirected_to(controller: \"admin_panel\", action: \"index\")\n end\n\n should \"Create foreign institution without city, state and cnpj by post\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Foreign institution\",\n \"AZ\",\n \"\",\n \"\",\n \"\",\n \"PrivateInstitution\"\n )\n fields[:institutions][:acronym] = \"FI\"\n\n post :new_institution, fields\n\n assert_redirected_to(controller: \"admin_panel\", action: \"index\")\n end\n\n should \"Create foreign institution without city, state and cnpj by ajax\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Foreign institution\",\n \"AZ\",\n \"\",\n \"\",\n \"\",\n \"PrivateInstitution\"\n )\n fields[:institutions][:acronym] = \"FI\"\n\n xhr :post, :new_institution, fields\n\n json_response = ActiveSupport::JSON.decode(@response.body)\n\n assert json_response[\"success\"]\n end\n\n should \"add environment admins to institution when created via admin panel\" do\n @controller.stubs(:verify_recaptcha).returns(true)\n admin2 = create_user(\"another_admin\").person\n admin2.stubs(:has_permission?).returns(\"true\")\n @environment.add_admin(admin2)\n @environment.save\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"Private Institution\",\n \"BR\",\n \"Distrito Federal\",\n \"Brasilia\",\n \"12.323.557/8900-10\",\n \"PrivateInstitution\"\n )\n fields[:institutions][:acronym] = \"PI\"\n fields[:edit_institution_page] = false\n post :new_institution, fields\n\n assert(Institution.last.community.is_admin?(admin2) )\n end\n\n should \"admin user can access action create_institution_admin\" do\n login_as(@admin.user_login)\n\n post :create_institution_admin\n\n assert_response 200\n end\n\n should \"disconnected user can not access action create_institution_admin\" do\n logout\n\n post :create_institution_admin\n\n assert_response 302\n assert_redirected_to(controller: \"/account\", action: \"login\")\n end\n\n should \"regular user can not access action create_institution_admin\" do\n regular_user = create_user(\"regular_user\").person\n login_as :regular_user\n\n post :create_institution_admin\n\n assert_response 200\n end\nend\n"
},
{
"alpha_fraction": 0.6729444265365601,
"alphanum_fraction": 0.6738631129264832,
"avg_line_length": 25.876543045043945,
"blob_id": "74267a837959d715f1a9a76438c9f6451113874f",
"content_id": "095d4e1b81ecefac3b4e8ee500e600d8e7f6ee9c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2177,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 81,
"path": "/src/noosfero-spb/software_communities/public/lib/select-field-choices.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('SelectFieldChoices', ['jquery', 'SelectElement'], function($, SelectElement) {\n 'use strict';\n\n\n function SelectFieldChoices(state_id, city_id, state_url) {\n this.state_id = state_id;\n this.input_html = $(state_id).parent().html();\n this.old_value = $(state_id).val();\n this.city_parent_div = $(city_id).parent().parent().parent();\n this.state_url = state_url;\n }\n\n\n SelectFieldChoices.prototype.getCurrentStateElement = function() {\n return $(this.state_id);\n };\n\n\n SelectFieldChoices.prototype.replaceWith = function(html) {\n var parent_div = this.getCurrentStateElement().parent();\n parent_div.html(html);\n };\n\n\n SelectFieldChoices.prototype.generateSelect = function(state_list) {\n var select_element, option;\n\n select_element = new SelectElement();\n select_element.setAttr(\"name\", \"profile_data[state]\");\n select_element.setAttr(\"id\", \"state_field\");\n select_element.setAttr(\"class\", \"type-select valid\");\n\n state_list.forEach(function(state) {\n option = SelectElement.generateOption(state, state);\n select_element.addOption(option);\n });\n\n return select_element.getSelect();\n };\n\n\n SelectFieldChoices.prototype.replaceStateWithSelectElement = function() {\n var klass = this;\n\n $.get(this.state_url, function(response) {\n var select_html;\n\n if (response.length > 0) {\n select_html = klass.generateSelect(response);\n klass.replaceWith(select_html);\n\n if (klass.old_value.length !== 0 && response.include(klass.old_value)) {\n klass.getCurrentStateElement().val(klass.old_value);\n }\n }\n });\n };\n\n\n SelectFieldChoices.prototype.replaceStateWithInputElement = function() {\n this.replaceWith(this.input_html);\n };\n\n\n SelectFieldChoices.prototype.hideCity = function() {\n this.city_parent_div.addClass(\"mpog_hidden_field\");\n };\n\n\n SelectFieldChoices.prototype.showCity = function() {\n this.city_parent_div.removeClass(\"mpog_hidden_field\");\n };\n\n\n SelectFieldChoices.prototype.actualFieldIsInput = function() {\n return this.getCurrentStateElement().attr(\"type\") === \"text\";\n };\n\n\n return SelectFieldChoices;\n});\n"
},
{
"alpha_fraction": 0.6895766854286194,
"alphanum_fraction": 0.6901835799217224,
"avg_line_length": 31.467979431152344,
"blob_id": "b972927e4c9d0c2109d0a0fd397b98dbb33a2089",
"content_id": "e0f35090e9b96a197f17672aa602d9af06120581",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 6592,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 203,
"path": "/src/noosfero-spb/software_communities/lib/ext/search_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: UTF-8\n\nrequire_dependency 'search_controller'\n\nclass SearchController\n\n DEFAULT_SOFTWARE_SORT = 'rating'\n\n def self.catalog_list\n { :public_software => [\"Software Público\", \"software_infos\"],\n :sisp_software => [\"SISP\", \"sisp\"] }\n end\n\n def communities\n @titles[:communities] = _(\"Communities Search\")\n delete_communities = []\n valid_communities_string = Community.get_valid_communities_string\n Community.all.each{|community| delete_communities << community.id unless eval(valid_communities_string)}\n\n @scope = visible_profiles(Community)\n @scope = @scope.where([\"id NOT IN (?)\", delete_communities]) unless delete_communities.empty?\n\n full_text_search\n end\n\n def software_infos\n software_public_condition_block = lambda do |software|\n (!@public_software_selected || software.public_software?) && (!software.sisp)\n end\n\n prepare_software_search_page(:software_infos, &software_public_condition_block)\n results = filter_software_infos_list(&software_public_condition_block)\n @software_count = results.count\n results = results.paginate(:per_page => @per_page, :page => params[:page])\n\n @asset = \"software_infos\".to_sym\n @assets = [@asset]\n @searches[@asset] = @searches.delete(:software_infos)\n @titles[@asset] = @titles.delete(:software_infos)\n\n @searches[@asset] = {:results => results}\n @search = results\n\n render :layout=>false if request.xhr?\n end\n\n def sisp\n sisp_condition_block = lambda{|software| software.sisp }\n\n prepare_software_search_page(:sisp, &sisp_condition_block)\n results = filter_software_infos_list(&sisp_condition_block)\n @software_count = results.count\n results = results.paginate(:per_page => @per_page, :page => params[:page])\n @searches[@asset] = {:results => results}\n @search = results\n\n render :layout=>false if request.xhr?\n end\n\n protected\n\n def filter_communities_list\n unfiltered_list = visible_profiles(Community)\n\n unless params[:query].nil?\n unfiltered_list = unfiltered_list.select do |com|\n com.name.downcase =~ /#{params[:query].downcase}/\n end\n end\n\n communities_list = []\n unfiltered_list.each do |profile|\n if profile.class == Community && !profile.is_template? && yield(profile)\n communities_list << profile\n end\n end\n\n communities_list\n end\n\n def filter_software_infos_list &software_condition_block\n filtered_software_list = get_filtered_software_list\n filtered_community_list = get_communities_list(filtered_software_list, &software_condition_block)\n sort_communities_list filtered_community_list\n end\n\n def get_filter_category_ids\n category_ids = []\n unless params[:selected_categories_id].blank?\n category_ids = params[:selected_categories_id]\n end\n\n category_ids = category_ids.map{|id| [id.to_i, Category.find(id.to_i).all_children.map(&:id)]}\n category_ids.flatten.uniq\n end\n\n def get_filtered_software_list\n params[:query] ||= \"\"\n visible_communities = visible_profiles(Community)\n\n filtered_software_list = SoftwareCommunitiesPlugin::SoftwareInfo.search_by_query(params[:query])\n\n if params[:only_softwares] && params[:only_softwares].any?{ |word| !word.blank? }\n params[:only_softwares].collect!{ |software_name| software_name.to_slug }\n filtered_software_list = SoftwareCommunitiesPlugin::SoftwareInfo.all.select{ |s| params[:only_softwares].include?(s.identifier) }\n @public_software_selected = false\n end\n\n filtered_software_list = filtered_software_list.select{ |software| visible_communities.include?(software.community) }\n category_ids = get_filter_category_ids\n\n unless category_ids.empty?\n filtered_software_list.select! do |software|\n !(software.community.category_ids & category_ids).empty?\n end\n end\n\n filtered_software_list\n end\n\n def get_communities_list software_list, &software_condition_block\n filtered_community_list = []\n software_list.each do |software|\n if software_condition_block.call(software)\n filtered_community_list << software.community unless software.community.nil?\n end\n end\n filtered_community_list\n end\n\n def sort_communities_list communities_list\n communities_list.sort! {|a, b| a.name.downcase <=> b.name.downcase}\n\n if params[:sort] && params[:sort] == \"desc\"\n communities_list.reverse!\n elsif params[:sort] && params[:sort] == \"relevance\"\n communities_list = sort_by_relevance(communities_list, params[:query]){ |community| [community.software_info.finality, community.name] }\n elsif params[:sort] && params[:sort] == \"rating\"\n communities_list = sort_by_average_rating(communities_list)\n end\n communities_list\n end\n\n def prepare_software_search_page title, &software_condition_block\n prepare_software_infos_params(title)\n prepare_software_infos_message\n prepare_software_infos_category_groups(&software_condition_block)\n prepare_software_infos_category_enable\n end\n\n def prepare_software_infos_params title\n @titles[title.to_sym] = _(\"Result Search\")\n params[:sort] ||= DEFAULT_SOFTWARE_SORT\n\n @selected_categories_id = params[:selected_categories_id]\n @selected_categories_id ||= []\n @selected_categories_id = @selected_categories_id.map(&:to_i)\n @all_selected = params[:software_type] == \"all\"\n @public_software_selected = !@all_selected\n @per_page = prepare_per_page\n end\n\n def prepare_per_page\n return 15 if params[:software_display].nil?\n\n if params[:software_display] == \"all\"\n SoftwareCommunitiesPlugin::SoftwareInfo.count\n else\n params[:software_display].to_i\n end\n end\n\n def prepare_software_infos_message\n @message_selected_options = \"\"\n\n @selected_categories = []\n unless @selected_categories_id.empty?\n @message_selected_options = _(\"Selected options: \")\n\n @selected_categories = Category.find(@selected_categories_id)\n @message_selected_options += @selected_categories.collect { |category|\n \"#{category.name}; \"\n }.join()\n end\n end\n\n def prepare_software_infos_category_groups\n @categories = SoftwareCommunitiesPlugin.software_categories.sort{|a, b| a.name <=> b.name}\n end\n\n def prepare_software_infos_category_enable\n @enabled_check_box = Hash.new\n categories = SoftwareCommunitiesPlugin.software_categories\n\n @categories.each do |category|\n if category.software_infos.count > 0\n @enabled_check_box[category] = :enabled\n else\n @enabled_check_box[category] = :disabled\n end\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7166947722434998,
"alphanum_fraction": 0.7251265048980713,
"avg_line_length": 28.649999618530273,
"blob_id": "29453477e79f604909ae9b186fe1b94a024ca543",
"content_id": "a30c942e1d09130320a9f2d066463b75cd433d32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 593,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 20,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_database.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareDatabase < ActiveRecord::Base\n attr_accessible :version\n\n belongs_to :software_info, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n belongs_to :database_description, :class_name => 'SoftwareCommunitiesPlugin::DatabaseDescription'\n\n validates_presence_of :database_description_id, :version\n\n validates_length_of(\n :version,\n :maximum => 20,\n :too_long => _(\"Software database is too long (maximum is 20 characters)\")\n )\n\n validates(\n :database_description_id,\n :numericality => {:greater_than_or_equal_to => 1}\n )\n\nend\n"
},
{
"alpha_fraction": 0.5716418027877808,
"alphanum_fraction": 0.5731343030929565,
"avg_line_length": 17.61111068725586,
"blob_id": "2c54d8f6aea34cfd3ccb49f10412df608ddbbf31",
"content_id": "045805a7f672f13ef4fb9b46fa3a0255c4a46ffc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 670,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 36,
"path": "/src/noosfero-spb/gov_user/public/initializer.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\n(function() {\n 'use strict';\n\n var dependencies = [\n 'ControlPanel',\n 'CreateInstitution',\n 'CompleteRegistration',\n 'UserEditProfile',\n 'NewCommunity',\n 'GovUserCommentsExtraFields',\n 'InstitutionModal'\n ];\n\n\n modulejs.define('Initializer', dependencies, function() {\n var __dependencies = arguments;\n\n\n function call_dependency(dependency) {\n if( dependency.isCurrentPage() ) {\n dependency.init();\n }\n }\n\n\n return {\n init: function() {\n for(var i=0, len = __dependencies.length; i < len; i++) {\n call_dependency(__dependencies[i]);\n }\n }\n };\n });\n})();\n"
},
{
"alpha_fraction": 0.5368297100067139,
"alphanum_fraction": 0.5368297100067139,
"avg_line_length": 24.526315689086914,
"blob_id": "7a226980fe940ae742ef33917853fd3d991a7aec",
"content_id": "224ae2567d27573446126a83c9e141639405f725",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3394,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 133,
"path": "/src/noosfero-spb/software_communities/lib/tasks/export.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'csv'\n\nnamespace :export do\n namespace :catalog do\n desc \"Export all softwares to CSV\"\n task :csv => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"MpogSoftware\") or env.plugin_enabled?(\"SoftwareCommunitiesPlugin\")\n softwares_to_csv\n categories_to_csv\n software_categories_to_csv\n\n compress_files\n end\n end\n end\n end\n\n def softwares_to_csv\n print \"Exporting softwares to softwares.csv: \"\n\n CSV.open('/tmp/softwares.csv', 'w') do |csv|\n csv << [\n \"id\",\n \"community_id\",\n \"identifier\",\n \"name\",\n \"finality\",\n \"acronym\",\n \"created_at\",\n \"image_filename\",\n \"home_page_name\",\n \"home_page_slug\",\n \"home_page_path\",\n \"home_page_body\",\n \"home_page_abstract\",\n \"home_page_published_at\"\n ]\n\n SoftwareInfo.all.each do |software|\n if software.community\n begin\n csv << [\n software.id,\n software.community.id,\n software.community.identifier,\n software.community.name,\n software.finality,\n software.acronym,\n software.community.created_at,\n (software.community.image.nil? ? nil : software.community.image.filename),\n (software.community.home_page.nil? ? nil : software.community.home_page.name),\n (software.community.home_page.nil? ? nil : software.community.home_page.slug),\n (software.community.home_page.nil? ? nil : software.community.home_page.path),\n (software.community.home_page.nil? ? nil : software.community.home_page.body),\n (software.community.home_page.nil? ? nil : software.community.home_page.abstract),\n (software.community.home_page.nil? ? nil : software.community.home_page.published_at),\n ]\n\n print '.'\n rescue\n print 'F'\n end\n end\n end\n end\n\n print \"\\n\"\n end\n\n def categories_to_csv\n print \"Exporting categories to categories.csv: \"\n\n CSV.open('/tmp/categories.csv', 'w') do |csv|\n csv << [\n \"id\",\n \"name\",\n \"path\",\n ]\n\n Category.all.each do |category|\n begin\n csv << [\n category.id,\n category.name,\n category.path,\n ]\n\n print '.'\n rescue\n print 'F'\n end\n end\n end\n\n print \"\\n\"\n end\n\n def software_categories_to_csv\n print \"Exporting software and categories relation to software_categories.csv: \"\n CSV.open('/tmp/software_categories.csv', 'w') do |csv|\n csv << [\n \"software_id\",\n \"category_id\"\n ]\n\n SoftwareInfo.all.each do |software|\n if software.community\n software.community.categories.each do |category|\n begin\n csv << [\n software.id,\n category.id\n ]\n\n print '.'\n rescue\n print 'F'\n end\n end\n end\n end\n end\n\n print \"\\n\"\n end\n\n def compress_files\n `cd /tmp/ && tar -zcvf software_catalog_csvs.tar.gz softwares.csv categories.csv software_categories.csv`\n\n `cd /tmp/ && rm softwares.csv categories.csv software_categories.csv`\n end\nend"
},
{
"alpha_fraction": 0.7398374080657959,
"alphanum_fraction": 0.7398374080657959,
"avg_line_length": 21.454545974731445,
"blob_id": "6886dae3481813d0ade2e54be536dc7c2a7c608e",
"content_id": "cf975284f670760506e26e85fdff7fde21ab8e9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 246,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 11,
"path": "/src/noosfero-spb/gov_user/db/migrate/20150910203559_add_institution_to_organization_rating.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddInstitutionToOrganizationRating < ActiveRecord::Migration\n def up\n change_table :organization_ratings do |t|\n t.belongs_to :institution\n end\n end\n\n def down\n remove_column :organization_ratings, :institution_id\n end\nend"
},
{
"alpha_fraction": 0.6002436280250549,
"alphanum_fraction": 0.6034916639328003,
"avg_line_length": 28.963502883911133,
"blob_id": "ef1b378837d571da86dce9c52f7b531613abd09c",
"content_id": "1f7de2597df16100910a5db7fa4a5e66bdf73384",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 12315,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 411,
"path": "/src/noosfero-spb/gov_user/public/views/create-institution.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\nmodulejs.define('CreateInstitution', ['jquery', 'NoosferoRoot', 'SelectElement'], function($, NoosferoRoot, SelectElement) {\n 'use strict';\n\n var AJAX_URL = {\n new_institution:\n NoosferoRoot.urlWithSubDirectory(\"/plugin/gov_user/new_institution\"),\n institution_already_exists:\n NoosferoRoot.urlWithSubDirectory(\"/plugin/gov_user/institution_already_exists\"),\n get_institutions:\n NoosferoRoot.urlWithSubDirectory(\"/plugin/gov_user/get_institutions\"),\n auto_complete_city:\n NoosferoRoot.urlWithSubDirectory(\"/account/search_cities\")\n };\n\n function set_institution_field_name(name) {\n $(\"#input_institution\").attr(\"value\", name);\n $(\"#input_institution\").autocomplete(\"search\");\n }\n\n function show_public_institutions_fields() {\n $(\".public-institutions-fields\").show();\n $(\"#cnpj_required_field_mark\").html(\"\");\n }\n\n\n function show_private_institutions_fields() {\n $(\".public-institutions-fields\").hide();\n $(\"#institutions_governmental_power option\").selected(0);\n $(\"#institutions_governmental_sphere option\").selected(0);\n $(\"#institutions_juridical_nature option\").selected(0);\n $(\"#cnpj_required_field_mark\").html(\"(*)\");\n }\n\n\n function get_comunity_post_data() {\n return {\n name : $(\"#community_name\").val(),\n country : $(\"#community_country\").val(),\n state : $(\"#community_state\").val(),\n city : $(\"#community_city\").val()\n };\n }\n\n\n function get_institution_post_data() {\n\n return {\n cnpj: $(\"#institutions_cnpj\").val(),\n type: $(\"input[name='institutions[type]']:checked\").val(),\n acronym : $(\"#institutions_acronym\").val(),\n governmental_power: $(\"#institutions_governmental_power\").selected().val(),\n governmental_sphere: $(\"#institutions_governmental_sphere\").selected().val(),\n juridical_nature: $(\"#institutions_juridical_nature\").selected().val(),\n corporate_name: $(\"#institutions_corporate_name\").val(),\n siorg_code: $(\"#institutions_siorg_code\").val(),\n sisp: $('input[name=\"institutions[sisp]\"]:checked').val()\n };\n }\n\n\n function get_post_data() {\n var post_data = {};\n\n post_data.community = get_comunity_post_data();\n post_data.institutions = get_institution_post_data();\n\n return post_data;\n }\n\n\n // If the page has a user institution list, update it without repeating the institution\n function update_user_institutions_list() {\n $(\".institution_container\").append(get_clone_institution_data(institution_id));\n add_selected_institution_to_list(institution_id, institution_name);\n\n $(\".remove-institution\").click(remove_institution);\n $('#institution_modal').modal('toggle');\n }\n\n\n\n function success_ajax_response(response) {\n close_loading();\n\n if(response.success){\n var institution_name = response.institution_data.name;\n var institution_id = response.institution_data.id;\n\n // Tell the user it was created\n window.display_notice(response.message);\n\n set_institution_field_name($(\"#community_name\").val());\n\n // Close modal\n $(\".modal-header .close\").trigger(\"click\");\n\n // Clear modal fields\n $(\"#institution_modal_body\").html(window.sessionStorage.getItem(\"InstitutionModalBody\"));\n $(\".modal .modal-body div\").show();\n\n // Reset modal events\n init_module();\n\n // If the user is is his profile edition page\n update_user_institutions_list();\n } else {\n var errors = create_error_list(response);\n\n $(\"#create_institution_errors\").switchClass(\"hide-field\", \"show-field\").html(\"<h2>\"+response.message+\"</h2>\"+errors);\n\n show_errors_in_each_field(response.errors);\n }\n }\n\n function create_error_list(response){\n var errors = \"<ul>\";\n var field_name;\n\n for(var i =0;i<response.errors.length;i++) {\n errors += \"<li>\"+response.errors[i]+\"</li>\";\n }\n\n errors += \"</ul>\";\n return errors;\n }\n\n\n function show_errors_in_each_field(errors) {\n var error_keys = Object.keys(errors);\n\n // (field)|(field)|...\n var verify_error = new RegExp(\"(\\\\[\" + error_keys.join(\"\\\\])|(\\\\[\") + \"\\\\])\" );\n\n var fields_with_errors = $(\"#institution_dialog .formfield input\").filter(function(index, field) {\n $(field).removeClass(\"highlight-error\");\n return verify_error.test(field.getAttribute(\"name\"));\n });\n\n var selects_with_errors = $(\"#institution_dialog .formfield select\").filter(function(index, field) {\n $(field).removeClass(\"highlight-error\");\n return verify_error.test(field.getAttribute(\"name\"));\n });\n\n fields_with_errors.addClass(\"highlight-error\");\n selects_with_errors.addClass(\"highlight-error\");\n }\n\n\n function save_institution(evt) {\n evt.preventDefault();\n\n open_loading($(\"#loading_message\").val());\n $.ajax({\n url: AJAX_URL.new_institution,\n data : get_post_data(),\n type: \"POST\",\n success: success_ajax_response,\n error: function() {\n close_loading();\n var error_message = $(\"#institution_error_message\").val();\n $(\"#create_institution_errors\").switchClass(\"hide-field\", \"show-field\").html(\"<h2>\"+error_message+\"</h2>\");\n }\n });\n }\n\n function institution_already_exists(){\n if( this.value.length >= 3 ) {\n $.get(AJAX_URL.institution_already_exists, {name:this.value}, function(response){\n if( response === true ) {\n $(\"#already_exists_text\").switchClass(\"hide-field\", \"show-field\");\n } else {\n $(\"#already_exists_text\").switchClass(\"show-field\", \"hide-field\");\n }\n });\n }\n }\n\n\n function get_clone_institution_data(value) {\n var user_institutions = $(\".user_institutions\").first().clone();\n user_institutions.val(value);\n\n return user_institutions;\n }\n\n function toggle_extra_fields_style_status(status) {\n if(status) {\n $('.comments-software-extra-fields').css({height: \"180px\" });\n } else {\n $('.comments-software-extra-fields').css({height: \"140px\" });\n }\n }\n\n\n function institution_autocomplete() {\n $(\"#input_institution\").autocomplete({\n source : function(request, response){\n $.ajax({\n type: \"GET\",\n url: AJAX_URL.get_institutions,\n data: {query: request.term, selected_institutions: get_selected_institutions()},\n success: function(result){\n response(result);\n\n if( result.length === 0 ) {\n $('#institution_empty_ajax_message').switchClass(\"hide-field\", \"show-field\");\n $('#input_institution').addClass(\"highlight-error\");\n $('#add_institution_link').hide();\n toggle_extra_fields_style_status(true);\n $(\"#institution_modal\").css({display: \"none\"});\n }\n },\n error: function(ajax, stat, errorThrown) {\n console.log('Link not found : ' + errorThrown);\n }\n });\n },\n\n minLength: 2,\n\n select : function (event, selected) {\n $('#institution_empty_ajax_message').switchClass(\"show-field\", \"hide-field\");\n $('#add_institution_link').show();\n $('#input_institution').removeClass(\"highlight-error\");\n toggle_extra_fields_style_status(false);\n $(\"#institution_selected\").val(selected.item.id).attr(\"data-name\", selected.item.label);\n }\n });\n }\n\n function get_selected_institutions() {\n var selected_institutions = []\n $('.institutions_added').find('li').each(function() {\n selected_institutions.push($(this).attr('data-institution'));\n });\n\n return selected_institutions;\n }\n\n function add_selected_institution_to_list(id, name) {\n var selected_institution = \"<li data-institution='\"+id+\"'>\"+name;\n selected_institution += \"<a href='#' class='button without-text icon-remove remove-institution'></a></li>\";\n\n $(\".institutions_added\").append(selected_institution);\n }\n\n function add_new_institution(evt) {\n evt.preventDefault();\n var selected = $(\"#institution_selected\");\n var institution_already_added = $(\".institutions_added li[data-institution='\"+selected.val()+\"']\").length;\n\n if(selected.val().length > 0 && institution_already_added === 0) {\n //field that send the institutions to the server\n $(\".institution_container\").append(get_clone_institution_data(selected.val()));\n\n // Visualy add the selected institution to the list\n add_selected_institution_to_list(selected.val(), selected.attr(\"data-name\"));\n $(this).hide();\n\n // clean the institution flag\n selected.val(\"\").attr(\"data-name\", \"\");\n $(\"#input_institution\").val(\"\");\n\n $(\".remove-institution\").click(remove_institution);\n }\n }\n\n\n function remove_institution(evt) {\n evt.preventDefault();\n var code = $(this).parent().attr(\"data-institution\");\n\n $(\".user_institutions[value=\"+code+\"]\").remove();\n $(this).parent().remove();\n }\n\n\n function add_mask_to_form_items() {\n $(\"#institutions_cnpj\").mask(\"99.999.999/9999-99\");\n }\n\n\n function show_hide_cnpj_city(country) {\n var cnpj = $(\"#institutions_cnpj\").parent().parent();\n var city = $(\"#community_city\");\n var city_label = $('label[for=\"community_city\"]');\n var state = $(\"#community_state\");\n var state_label = $('label[for=\"community_state\"]');\n var inst_type = $(\"input[name='institutions[type]']:checked\").val();\n\n if ( country === \"-1\" ) {\n $(\"#community_country\").val(\"BR\");\n country = \"BR\";\n }\n\n institution_type_actions(inst_type);\n\n if ( country !== \"BR\" ) {\n cnpj.hide();\n city.val('');\n city.hide();\n city_label.hide();\n state.val(\"\");\n state.hide();\n state_label.hide();\n } else {\n cnpj.show();\n city.show();\n city_label.show();\n state_label.show();\n state.show();\n }\n }\n\n function institution_type_actions(type) {\n var country = $(\"#community_country\").val();\n if( type === \"PublicInstitution\" && country == \"BR\") {\n show_public_institutions_fields();\n } else {\n show_private_institutions_fields();\n }\n }\n\n function autoCompleteCity() {\n var country_selected = $('#community_country').val();\n\n if(country_selected == \"BR\") {\n $('#community_city').autocomplete({\n source : function(request, response){\n $.ajax({\n type: \"GET\",\n url: AJAX_URL.auto_complete_city,\n data: {city_name: request.term, state_name: $(\"#community_state\").val()},\n success: function(result){\n response(result);\n\n // There are two autocompletes in this page, the last one is modal\n // autocomplete just put it above the modal\n $(\".ui-autocomplete\").last().css(\"z-index\", 1000);\n },\n error: function(ajax, stat, errorThrown) {\n console.log('Link not found : ' + errorThrown);\n }\n });\n },\n\n minLength: 3\n });\n } else {\n if ($('#community_city').data('autocomplete')) {\n $('#community_city').autocomplete(\"destroy\");\n $('#community_city').removeData('autocomplete');\n }\n }\n }\n\n\n function set_institution_name_into_modal() {\n $(\"#community_name\").val($(\"#input_institution\").val());\n }\n\n\n function set_events() {\n $(\"input[name='institutions[type]']\").click(function(){\n institution_type_actions(this.value);\n });\n\n $('#save_institution_button').click(save_institution);\n\n $(\"#community_name\").keyup(institution_already_exists);\n\n $(\"#add_institution_link\").click(add_new_institution);\n\n $(\".remove-institution\").click(remove_institution);\n\n $(\"#community_country\").change(function(){\n show_hide_cnpj_city(this.value);\n });\n\n add_mask_to_form_items();\n\n institution_autocomplete();\n\n autoCompleteCity();\n $('#community_country').change(function(){\n autoCompleteCity();\n });\n\n $(\"#create_institution_link\").click(set_institution_name_into_modal);\n }\n\n\n function init_module() {\n show_hide_cnpj_city($('#community_country').val());\n set_events();\n }\n\n return {\n isCurrentPage: function() {\n return $(\"#institution_form\").length === 1;\n },\n\n init: init_module,\n\n institution_autocomplete: function(){\n institution_autocomplete();\n }\n };\n});\n"
},
{
"alpha_fraction": 0.6392508149147034,
"alphanum_fraction": 0.6400651335716248,
"avg_line_length": 33.591548919677734,
"blob_id": "f564103ff87a1f0cf3b122288d5f2325299af48c",
"content_id": "ab7a8928bb1a2bff587cac32c3d8d536e897d56c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2460,
"license_type": "no_license",
"max_line_length": 182,
"num_lines": 71,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160510183218_fix_siorg_institutions.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class FixSiorgInstitutions < ActiveRecord::Migration\n def up\n governmental_power = GovernmentalPower.where(\"name ILIKE ?\", \"Executivo\").first\n governmental_sphere = GovernmentalSphere.where(\"name ILIKE ?\", \"Federal\").first\n env = Environment.default\n\n if env && governmental_power && governmental_sphere\n CSV.foreach(\"plugins/spb_migrations/files/orgaos_siorg.csv\", :headers => true) do |row|\n template = Community[\"institution\"]\n state = row[\"Estado\"].rstrip\n\n community = Community.where(\"identifier ILIKE ?\", row[\"Nome\"].to_slug).first\n unless community\n institution = Institution.where(\"acronym ILIKE ?\", row[\"Sigla\"]).first\n community = institution.community if institution\n end\n\n community = Community.new unless community\n\n community.environment = env if community.environment.blank?\n community.name = row[\"Nome\"].rstrip\n community.country = \"BR\"\n community.state = Institution::VALID_STATES[\"#{state}\"]\n community.city = row[\"Cidade\"]\n community.template = template if template\n\n unless community.save\n print \"F\"\n next\n end\n\n juridical_nature = JuridicalNature.where(\"name ILIKE ? OR name ILIKE ?\", \"#{I18n.transliterate(row['Natureza Jurídica'].rstrip)}\", \"#{row['Natureza Jurídica'].rstrip}\").first\n\n juridical_nature = JuridicalNature.create!(name: row['Natureza Jurídica'].rstrip) unless juridical_nature\n\n\n institution = Hash.new\n\n institution[:name] = row[\"Nome\"]\n institution[:siorg_code] = row[\"Código do SIORG\"]\n institution[:acronym] = row[\"Sigla\"]\n institution[:governmental_sphere] = governmental_sphere\n institution[:governmental_power] = governmental_power\n institution[:juridical_nature] = juridical_nature\n institution[:sisp] = (row[\"SISP\"] == \"Sim\")\n institution[:cnpj] = row[\"CNPJ\"]\n institution[:community] = community\n institution[:type] = \"PublicInstitution\"\n\n if community.institution\n community.institution.update_attributes(institution)\n else\n institution[:community] = community\n community.institution = PublicInstitution.create!(institution)\n end\n\n if community.save\n print \".\"\n else\n print \"F\"\n end\n\n end\n end\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.8493150472640991,
"alphanum_fraction": 0.8493150472640991,
"avg_line_length": 50.52941131591797,
"blob_id": "29ea716f494de2f231fe98e48e477874bf642e19",
"content_id": "597314e5eb3b1a6a10a36c0495a463dd413fcb30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 876,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 17,
"path": "/cookbooks/colab/files/default/profile.py",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "from colab.widgets.widget_manager import WidgetManager\nfrom colab.accounts.widgets.group import GroupWidget\nfrom colab.accounts.widgets.group_membership import GroupMembershipWidget\nfrom colab.accounts.widgets.latest_posted import LatestPostedWidget\nfrom colab.accounts.widgets.latest_contributions import \\\n LatestContributionsWidget\n\nfrom colab.accounts.widgets.collaboration_chart import CollaborationChart\nfrom colab.accounts.widgets.participation_chart import ParticipationChart\n\n# Profile Widgets\nWidgetManager.register_widget('group', GroupWidget())\nWidgetManager.register_widget('button', GroupMembershipWidget())\nWidgetManager.register_widget('list', LatestPostedWidget())\nWidgetManager.register_widget('list', LatestContributionsWidget())\nWidgetManager.register_widget('charts', CollaborationChart())\nWidgetManager.register_widget('charts', ParticipationChart())\n"
},
{
"alpha_fraction": 0.6600000262260437,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 15.666666984558105,
"blob_id": "55860d1a2c0651d4d94f17c2ceadb99831efad8b",
"content_id": "3e0e0ba2b1f89ae568a5a5049dd3ad412db984ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 300,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 18,
"path": "/cookbooks/noosfero/files/noosfero-create-api-user",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env ruby\n\nlogin = ARGV[0]\nemail = ARGV[1]\npassword = SecureRandom.random_number.to_s\n\nuser = User.find_by_login(login)\n\nunless user\n user = User.create!(\n login: login,\n email: email,\n password: password,\n password_confirmation: password\n )\n user.activate\n user.generate_private_token!\nend\n"
},
{
"alpha_fraction": 0.6929824352264404,
"alphanum_fraction": 0.7017543911933899,
"avg_line_length": 27.5,
"blob_id": "fefacba9b72d5c380ead9bb1d98f6a0e796fefaa",
"content_id": "bd1b02ab36ff0bcbe9a860101c486f95faebcebb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 912,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 32,
"path": "/cookbooks/munin/recipes/node.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'munin-node'\n\nservice 'munin-node' do\n action [:enable, :start]\nend\n\ndirectory '/usr/local/share/munin/plugins' do\n recursive true\nend\ncookbook_file '/usr/local/share/munin/plugins/packetloss' do\n mode 0755\nend\n\nnode['peers'].each do |hostname,ip|\n link '/etc/munin/plugins/packetloss_' + hostname do\n to '/usr/local/share/munin/plugins/packetloss'\n end\nend\n\nbash \"allow connections from munin master\" do\n ip = node['config']['munin_master']\n code \"echo 'cidr_allow #{ip}/32' >> /etc/munin/munin-node.conf\"\n not_if \"grep 'cidr_allow #{ip}/32' /etc/munin/munin-node.conf\"\n notifies :restart, 'service[munin-node]'\nend\n\nbash \"set munin-node hostname\" do\n hostname = node['fqdn']\n code \"sed -i -e '/^host_name\\s*localhost/d; $a host_name #{hostname}' /etc/munin/munin-node.conf\"\n not_if \"grep 'host_name #{hostname}' /etc/munin/munin-node.conf\"\n notifies :restart, 'service[munin-node]'\nend\n"
},
{
"alpha_fraction": 0.6683077216148376,
"alphanum_fraction": 0.6683077216148376,
"avg_line_length": 20.66666603088379,
"blob_id": "7df8025868e83bd1539047f12ecac58ef1abecbd",
"content_id": "5bc30e364dfa849af7afc96e1fabef1862ecd4d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1625,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 75,
"path": "/src/noosfero-spb/gov_user/test/helpers/plugin_test_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../helpers/institution_test_helper'\n\nmodule PluginTestHelper\n\n def create_person name, email, password, password_confirmation, state=\"state\", city=\"city\"\n user = create_user(\n name.to_slug,\n email,\n password,\n password_confirmation\n )\n person = Person.new\n\n person.name = name\n person.identifier = name.to_slug\n person.state = state\n person.city = city\n\n user.person = person\n user.save\n\n person.user_id = user.id\n person.save\n\n person\n end\n\n def create_user login, email, password, password_confirmation\n user = User.new\n\n user.login = login\n user.email = email\n user.password = password\n user.password_confirmation = password_confirmation\n\n user\n end\n\n def create_public_institution *params\n InstitutionTestHelper.create_public_institution *params\n end\n\n def create_community name\n community = fast_create(Community)\n community.name = name\n community.save\n community\n end\n\n\n def create_private_institution name, acronym, country, state, city, cnpj\n InstitutionTestHelper.create_private_institution(\n name,\n acronym,\n country,\n state,\n city,\n cnpj\n )\n end\n\n def create_public_institution *params\n InstitutionTestHelper.create_public_institution *params\n end\n\n def create_community_institution name, country, state, city\n community = fast_create(Community)\n community.name = name\n community.country = country\n community.state = state\n community.city = city\n community.save\n community\n end\nend\n"
},
{
"alpha_fraction": 0.6537396311759949,
"alphanum_fraction": 0.6869806051254272,
"avg_line_length": 14,
"blob_id": "bc32847c014cf7beda02a99ee71df57d766a70a9",
"content_id": "bf056605b47192fe19cafaee7cbc15a78357a8ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 361,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 24,
"path": "/cookbooks/backup/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'cronie'\npackage 'rsnapshot'\n\ncookbook_file '/etc/rsnapshot.conf' do\n owner 'root'\n group 'root'\n mode 0644\nend\n\ncookbook_file '/usr/local/bin/backup_spb.sh' do\n owner 'root'\n group 'root'\n mode 0755\nend\n\ntemplate '/etc/cron.d/rsnapshot-spb' do\n owner 'root'\n group 'root'\n mode 0644\nend\n\nservice 'crond' do\n action [:enable, :restart]\nend\n\n"
},
{
"alpha_fraction": 0.6656022071838379,
"alphanum_fraction": 0.6716613173484802,
"avg_line_length": 36.69135665893555,
"blob_id": "23779d03bfa772d5daa0276db6e4a554b97a27d2",
"content_id": "e933d75d6dd6bd40957531a57dc83df299580d25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 12281,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 324,
"path": "/src/noosfero-spb/software_communities/lib/tasks/import_sisp_software.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: UTF-8\n\nnamespace :sisp do\n desc \"Creates SISP env and templates\"\n task :prepare => :environment do\n unless ENV[\"DOMAIN\"].present?\n puts \"You didn't choose any domain. The default domain is 'novo.sisp.gov.br'\"\n puts \"You can run rake sisp:prepare DOMAIN=domain.url to add a domain\"\n end\n\n unless ENV[\"ADMINUSER\"].present?\n puts \"You didn't enter any user to be selected from the default Environment\"\n puts \"You can run rake sisp:prepare ADMINUSER=jose\"\n end\n\n Rake::Task['sisp:create_env'].invoke\n Rake::Task['noosfero:plugins:enable_all'].invoke\n Rake::Task['sisp:create_template'].invoke\n end\n\n desc \"Create SISP environment and import data\"\n task :all => [:prepare, :import_data]\n\n desc \"Creates the SISP Environment\"\n task :create_env => :environment do\n env = Environment.find_or_create_by_name(\"SISP\")\n domain_name = ENV[\"DOMAIN\"] || \"novo.sisp.gov.br\"\n domain = Domain.find_or_create_by_name(domain_name)\n env.domains << domain unless env.domains.include?(domain)\n\n env.theme = \"noosfero-spb-theme\"\n create_link_blocks env\n env.save\n\n user = Environment.default.users.find_by_email(ENV[\"ADMINUSER\"])\n if user.present?\n password = SecureRandom.base64\n sisp_user = env.users.find_by_login(user.login)\n\n unless sisp_user.present?\n sisp_user = User.new(:login => user.login, :email => user.email, :password => password, :password_confirmation => password, :environment => env)\n end\n\n sisp_user.save\n sisp_user.activate\n env.add_admin sisp_user.person\n\n puts \"User created with a random password. You can change in the console.\" unless sisp_user.save\n else\n puts \"\\nWARNING!!!!!!***********************************************\"\n puts \"No user found with the given login '#{ENV['ADMINUSER']}'.... skipping\"\n puts \"You can run this task again passing a valid user login with the following command:\"\n puts \"rake sisp:create_env ADMINUSER=userlogin\"\n end\n puts \"\\n\\nSISP Environment created\"\n end\n\n def create_link_blocks template\n box_2 = template.boxes.find_by_position(2)\n box_2.blocks.destroy_all\n box_2.blocks << LinkListBlock.new(:mirror => true,\n :links => [{:name=>\"Catálogo de Software\", :address=>\"/search/sisp\", :target=>\"_self\"},\n {:name=>\"Ajuda\", :address=>\"/\", :target=>\"_self\"}])\n box_2.blocks << LinkListBlock.new(:title => \"Software SISP\", :mirror => true,\n :links => [{:name=>\"Publique seu Software\", :address=>\"/\", :target=>\"_self\"},\n {:name=>\"Vídeos\", :address=>\"/\", :target=>\"_self\"}])\n box_2.blocks << LinkListBlock.new(:title => \"Portal do SISP\", :mirror => true,\n :links => [{:name=>\"Sobre o Portal\", :address=>\"/\", :target=>\"_self\"},\n {:name=>\"Contato\", :address=>\"/\", :target=>\"_self\"},\n {:name=>\"Notícias\", :address=>\"/\", :target=>\"_self\"}])\n end\n\n desc \"Creates SISP software template\"\n task :create_template => :environment do\n env = Environment.find_by_name(\"SISP\")\n\n unless env.present?\n Rake::Task['sisp:create_env'].invoke\n env = Environment.find_by_name(\"SISP\")\n end\n\n if env.present?\n template = Community.where(identifier: \"sisp\", environment_id: env).last\n template.destroy if template\n template = Community.create!(name: \"Sisp\", identifier: \"sisp\", is_template: true, environment: env)\n\n template.home_page = template.blog\n template.update_layout_template(\"nosidebars\")\n template.save\n\n create_template_blocks template\n create_link_blocks template\n\n env.community_default_template = template\n env.save!\n\n puts \"SISP Template created\"\n else\n puts \"SISP Template *NOT* created. Environment SISP not found.\"\n end\n\n end\n\n def create_template_blocks template\n box_1 = template.boxes.find_by_position(1)\n box_1.blocks << SoftwareInformationBlock.new(:display => \"home_page_only\", :mirror => true)\n box_1.blocks << SispTabDataBlock.new(:display => \"home_page_only\", :mirror => true)\n box_1.blocks << CategoriesAndTagsBlock.new(:display => \"home_page_only\", :mirror => true)\n box_1.blocks << OrganizationRatingsBlock.new(:display => \"home_page_only\", :mirror => true, :title => \"Relatos de uso\")\n\n main_block = box_1.blocks.find_by_type(\"MainBlock\")\n main_block.display = \"except_home_page\"\n main_block.save\n end\n\n desc \"Import sisp software from yml\"\n task :import_data => :environment do\n $imported_data = YAML.load_file('plugins/software_communities/public/static/sisp-catalog.yml')\n $env = Environment.find_by_name(\"SISP\")\n unless $env\n puts \"SISP environment not FOUND!\"\n exit 1\n end\n\n $license = LicenseInfo.find_or_create_by_version(\"Another\")\n $software_category = $env.categories.find_or_create_by_name(\"Software\")\n $software_category.environment = $env\n $software_category.save!\n\n $sisp_user = create_sisp_user\n\n $created_software={}\n\n $sisp_template = $env.communities.find_by_identifier(\"sisp\")\n\n print 'Creating SISP Softwares: '\n $imported_data.keys.each do |key|\n\n sisp = $imported_data[key]['software_info']\n\n next if sisp['3 - Identificação do software']['Nome'].size <= 2\n sw = create_software_and_attrs sisp\n\n sw.sisp_url = $imported_data[key]['url']\n sw.sisp = true\n sw.sisp_id = key.to_i\n\n set_sisp_hashes sw, sisp\n\n if sw.valid? && sw.community.valid?\n sw.community.save!\n sw.save!\n print '.'\n else\n sw.community.destroy\n sw.destroy\n puts sw.errors.full_messages\n print 'F'\n end\n end\n\n puts \"\\n Done\"\n end\nend\n\ndef create_sisp_community name\n\n identifier = create_identifier name\n\n $created_software[identifier]= $created_software[identifier].nil? ? 0 : $created_software[identifier]+1\n\n name = name + \" copy#{$created_software[identifier]}\" if ($created_software[identifier] != 0)\n identifier = (identifier + \"-copy#{$created_software[identifier]}\") if ($created_software[identifier] != 0)\n\n community = $env.communities.find_or_initialize_by_name(name)\n\n community.identifier = identifier\n community.template = $sisp_template\n community.environment = $env\n\n community.save!\n community\nend\n\ndef create_sisp_software_info name, finality = \"blank\", acronym = \"\"\n community = create_sisp_community(name)\n\n if community.software?\n return community.software_info\n end\n\n software_info = SoftwareInfo.new\n software_info.license_info = $license\n software_info.community = community\n software_info.finality = finality\n software_info.acronym = acronym\n software_info.save!\n software_info\nend\n\ndef set_software_category software, category_name\n category = $env.categories.find_by_name(category_name)\n category ||= Category.create(:name => category_name, :parent => $software_category, :environment => $env)\n software.community.categories << category unless software.community.categories.include?(category)\nend\n\ndef set_sisp_hashes software, sisp_hash\n software.sisp_type = sisp_hash['3 - Identificação do software']['Tipo de Software']\n software.agency_identification = sisp_hash['1 - Identificação do órgão']\n software.software_requirements = sisp_hash['10 - Requisitos de software']\n software.hardware_requirements = sisp_hash['11 - Requisitos de Hardware']\n software.documentation = sisp_hash['12 - Documentação']\n software.system_applications = sisp_hash['13 - Aplicações do sistema']\n software.active_versions = sisp_hash['15 - Versões em uso']\n software.estimated_cost = sisp_hash['16 - Custo Estimado']\n software.responsible = sisp_hash['2 - Identificação do responsável no órgão para contato posterior']\n software.responsible_for_acquirement = sisp_hash['4 - Responsáveis pelo Desenvolvimento/Aquisição']\n software.system_info = sisp_hash['5 - Sistema']\n software.development_info = sisp_hash['6 - Características do Desenvolvimento']\n software.maintenance = sisp_hash['7 - Manutenção do Sistema']\n software.standards_adherence = sisp_hash['8 - Aderência a padrões']\n software.platform = sisp_hash['9 - Ambiente / Plataforma']\nend\n\ndef create_identifier name\n \"#{name.to_slug}\".truncate(240, :omission => '', :separator => '-')\nend\n\ndef create_sisp_user #TODO change user info\n user = $env.users.find_by_login('sisp_admin')\n password = SecureRandom.base64\n user ||= User.new(:login => 'sisp_admin', :email => '[email protected]', :password => password, :password_confirmation => password, :environment => $env)\n user.save!\n user.activate if !user.activated?\n user\nend\n\ndef create_institution sisp_hash\n\n name = sisp_hash['1 - Identificação do órgão']['Nome da Empresa/Órgão']\n\n if name.size <=2\n return nil\n end\n\n institution_community = $env.communities.find_or_initialize_by_identifier(name.to_slug)\n\n #puts institution_community.inspect\n institution = PublicInstitution.find_or_initialize_by_name(name)\n institution_community.name = name\n institution_community.country = \"BR\"\n institution_community.state = \"Distrito Federal\"\n institution_community.city = \"Unknown\"\n institution_community.environment = $env\n institution_community.save!\n\n institution.community = institution_community\n institution.name = name\n institution.juridical_nature = JuridicalNature.find_or_create_by_name(:name => sisp_hash['1 - Identificação do órgão']['Natureza'])\n institution.acronym = sisp_hash['1 - Identificação do órgão']['Sigla'].split[0]\n institution.acronym = nil if (institution.acronym.size > 10)\n institution.governmental_power = GovernmentalPower.find_or_create_by_name(:name => sisp_hash['1 - Identificação do órgão']['Esfera'])\n institution.governmental_sphere = GovernmentalSphere.find_or_create_by_name(:name => sisp_hash['1 - Identificação do órgão']['Abrangência'])\n institution.cnpj = nil\n institution.corporate_name = name\n institution.save!\n institution\n\nend\n\ndef create_ratings community_identifier, sisp_hash\n software_community = $env.communities.find_by_identifier(community_identifier)\n\n institution = create_institution(sisp_hash)\n if institution.nil?\n return nil\n end\n\n comment_system = Comment.new(:body=>\"Informações de custo de sistema importadas automaticamente do catálogo SISP.\", :author=> $sisp_user.person)\n comment_system.source = software_community\n comment_system.save!\n comment_maintenance = Comment.new(:body=>\"Informações de custo de manutenção importadas automaticamente do catálogo SISP.\", :author=> $sisp_user.person)\n comment_maintenance.source = software_community\n comment_maintenance.save!\n\n OrganizationRating.create!(\n :comment => comment_system,\n :value => 1, #TODO see what to put here\n :person => $sisp_user.person,\n :organization => software_community,\n :institution => institution,\n :saved_value => sisp_hash['16 - Custo Estimado']['Custo do sistema'],\n :people_benefited => 0\n)\n\n OrganizationRating.create!(\n :comment => comment_maintenance,\n :value => 1, #TODO see what to put here\n :person => $sisp_user.person,\n :organization => software_community,\n :institution => institution,\n :saved_value => sisp_hash['16 - Custo Estimado']['Custo de Manutenção'],\n :people_benefited => 0\n )\n\nend\n\ndef create_software_and_attrs sisp_hash\n name = sisp_hash['3 - Identificação do software']['Nome'].truncate(240, :omission => '', :separator => ' ')\n\n identifier = create_identifier name\n\n software = create_sisp_software_info(name)\n\n create_ratings identifier, sisp_hash\n\n set_software_category software, sisp_hash['3 - Identificação do software']['Subtipo']\n software.features = sisp_hash['5 - Sistema']['Principais funcionalidades']\n software.finality = sisp_hash['5 - Sistema']['Objetivos do sistema']\n software.objectives = sisp_hash['5 - Sistema']['Objetivos do sistema']\n software.acronym = sisp_hash['3 - Identificação do software']['Sigla'].split[0]\n software.acronym = \"\" if (software.acronym.size > 10)\n software\nend\n\n"
},
{
"alpha_fraction": 0.5994065403938293,
"alphanum_fraction": 0.6112759709358215,
"avg_line_length": 23.658536911010742,
"blob_id": "4fbb85070f3246c57dcefb26b91cd7f268434b26",
"content_id": "c6c4a168c2fabe99f22d6aa41e61b75acdbc31c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1011,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 41,
"path": "/docs/Makefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "all:\n\t@echo \"Usage:\"\n\t@echo\n\t@echo \"make html\t\t\t\tBuilds the documentation in HTML\"\n\t@echo \"make latexpdf\t\tBuilds the documentation in PDF\"\n\nSPB_ENV ?= local\n\nbuild_dir = _build/$(SPB_ENV)\n\n# autogenerated DNS documentation\nBUILT += $(build_dir)/dns.rst\n$(build_dir)/dns.rst: ../test/dns_test.sh\n\tmkdir -p $(build_dir)\n\t(cd .. && sh test/dns_test.sh --doc) > $@\n\nBUILT += $(patsubst %.svg, $(build_dir)/%.png, $(wildcard *.svg))\n$(build_dir)/%.png: %.png\n\tmkdir -p $(build_dir)\n\tcp $< $@\n\nssh.png:\n\tinkscape --export-area-page --export-width=800 --export-width=600 --export-png=$@ $<\n\narquitetura.png:\n\tinkscape --export-area-page --export-width=800 --export-width=600 --export-png=$@ $<\n\nBUILT += $(patsubst %.in, $(build_dir)/%, $(wildcard *.in))\n$(build_dir)/%: %.in build.rb\n\tmkdir -p $(build_dir)\n\truby -p build.rb $< > $@ || ($(RM) $@; false)\n\nCLEAN_FILES += $(BUILT)\n\nhtml latexpdf: $(BUILT)\n\tmkdir -p $(build_dir)\n\t$(MAKE) -C $(build_dir) -f ../Makefile $@\n\nclean:\n\t$(RM) $(BUILT)\n\t$(RM) -r $(build_dir)\n"
},
{
"alpha_fraction": 0.6815336346626282,
"alphanum_fraction": 0.6830986142158508,
"avg_line_length": 28.720930099487305,
"blob_id": "efaf66b416413eba7650a0e6592c2f20057d9a44",
"content_id": "9ce90bd24236f69def9bc0a01420d62c56477578",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1278,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 43,
"path": "/src/noosfero-spb/gov_user/lib/ext/search_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'search_controller'\n\nclass SearchController\n\n def communities\n @titles[:communities] = _(\"Communities Search\")\n delete_communities = []\n valid_communities_string = Community.get_valid_communities_string\n Community.all.each{|community| delete_communities << community.id unless eval(valid_communities_string)}\n\n @scope = visible_profiles(Community)\n @scope = @scope.where([\"id NOT IN (?)\", delete_communities]) unless delete_communities.empty?\n\n full_text_search\n end\n\n def institutions\n @titles[:institutions] = _(\"Institutions Search\")\n results = filter_communities_list{|community| community.institution?}\n results = results.paginate(:per_page => 24, :page => params[:page])\n @searches[@asset] = {:results => results}\n @search = results\n end\n\n def filter_communities_list\n unfiltered_list = visible_profiles(Community)\n\n unless params[:query].nil?\n unfiltered_list = unfiltered_list.select do |com|\n com.name.downcase =~ /#{params[:query].downcase}/\n end\n end\n\n communities_list = []\n unfiltered_list.each do |profile|\n if profile.class == Community && !profile.is_template? && yield(profile)\n communities_list << profile\n end\n end\n\n communities_list\n end\nend\n"
},
{
"alpha_fraction": 0.7546296119689941,
"alphanum_fraction": 0.7569444179534912,
"avg_line_length": 27.799999237060547,
"blob_id": "4be1f36cd29bb16787804f9c650df994a55ad352",
"content_id": "97dff7db2f72ca36cd21d6bf40ddc9304494a351",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 432,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 15,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/programming_language.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::ProgrammingLanguage < ActiveRecord::Base\n\n SEARCHABLE_SOFTWARE_FIELDS = {\n :name => 1\n }\n\n attr_accessible :name\n\n validates_presence_of :name\n validates_uniqueness_of :name\n\n has_many :software_languages, :class_name => 'SoftwareCommunitiesPlugin::SoftwareLanguage'\n has_many :software_infos, :through => :software_languages, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n\nend\n"
},
{
"alpha_fraction": 0.5235849022865295,
"alphanum_fraction": 0.5424528121948242,
"avg_line_length": 13.133333206176758,
"blob_id": "c496d7b803ab799d51cf44c28ea9b83a7655ef03",
"content_id": "3823debecb13bcc9a369ecfa115c78d191fec967",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 15,
"path": "/test/run_all",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\n\nfailed=0\nfor file in test/*_test.sh; do\n rc=0\n echo \"$file\"\n mispipe \"sh $file\" \"sed -e 's/ASSERT:/FAILED:/; s/^/ /'\" || rc=$?\n if [ $rc -ne 0 ]; then\n failed=1\n fi\ndone\n\nexit $failed\n"
},
{
"alpha_fraction": 0.6708571314811707,
"alphanum_fraction": 0.6731428503990173,
"avg_line_length": 32.01886749267578,
"blob_id": "df5a314bcfdb284a9e0820ac95198c288425c0ba",
"content_id": "4c4a3c7b1ce4e741a0299a135ee9c124791e6c6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1750,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 53,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150907190532_add_statistic_block_to_all_softwares.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddStatisticBlockToAllSoftwares < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n\n if software_template\n software_area_two = software_template.boxes.find_by_position 2\n\n statistic_block_template = StatisticBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n statistic_block_template.settings[:fixed] = true\n statistic_block_template.display = \"home_page_only\"\n statistic_block_template.save!\n print \".\"\n\n software_area_two.blocks << statistic_block_template\n software_area_two.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n first_block_position = software_area_two.blocks.order(:position).first.position\n statistic_block_template.position = first_block_position + 1\n statistic_block_template.save!\n print \".\"\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_two = software_community.boxes.find_by_position 2\n print \".\"\n\n statistic_block = StatisticBlock.new :move_modes => \"none\", :edit_modes => \"none\"\n statistic_block.settings[:fixed] = true\n statistic_block.display = \"home_page_only\"\n statistic_block.mirror_block_id = statistic_block_template.id\n statistic_block.save!\n print \".\"\n\n software_area_two.blocks << statistic_block\n software_area_two.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n first_block_position = software_area_two.blocks.order(:position).first.position\n statistic_block.position = first_block_position + 1\n statistic_block.save!\n print \".\"\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.6583333611488342,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 23,
"blob_id": "df4a57dc17b1ca9af4935b02f992e371dcbdba0e",
"content_id": "42c7d3e14703b2e2a2848acce92ceb5a6a82e6d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 10,
"path": "/test/bin/create-list",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nlistname=\"$1\"\nowner=\"$2\"\n\nsudo -u mailman /usr/lib/mailman/bin/newlist --quiet \"$listname\" \"$owner\" PASSWORD\n\necho \"$owner\" | sudo -u mailman /usr/lib/mailman/bin/add_members -r - --welcome-msg=n \"$listname\" > /dev/null\n"
},
{
"alpha_fraction": 0.6736842393875122,
"alphanum_fraction": 0.6736842393875122,
"avg_line_length": 24.675676345825195,
"blob_id": "fd436816a8dd621ce8c3d7ef00c736ecc0401222",
"content_id": "162c30116469a8c69c66bd0ceb7219a768f7f64c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 950,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 37,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/categories_software_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::CategoriesSoftwareBlock < Block\n\n attr_accessible :show_name\n attr_accessible :search_catalog\n\n settings_items :show_name, :type => :boolean, :default => false\n settings_items :search_catalog, :type => :string, :default => SearchController.catalog_list[:public_software].last\n\n def self.description\n _('Categories Softwares')\n end\n\n def help\n _('This block displays the categories and the amount of softwares for\n each category.')\n end\n\n def content(args={})\n block = self\n s = show_name\n\n software_category = environment.categories.find_by_name(\"Software\")\n categories = []\n categories = software_category.children.order(:name).all if software_category\n\n lambda do |object|\n render(\n :file => 'blocks/categories_software',\n :locals => { :block => block, :show_name => s, :categories => categories }\n )\n end\n end\n\n def cacheable?\n false\n end\nend\n"
},
{
"alpha_fraction": 0.6123561263084412,
"alphanum_fraction": 0.6250756978988647,
"avg_line_length": 35.68888854980469,
"blob_id": "eb57c4ed4ce69ed4efad0b5a07bf8e78628f0394",
"content_id": "63258af390d2590f1786099f1fdd06c1300b01ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1651,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 45,
"path": "/script/plugins_spb_ci_setup.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "current_path=$(pwd)\nRED='\\033[1;31m'\nGREEN='\\033[1;32m'\nNC='\\033[0m'\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling SPB plugins${NC}\\n\"\nln -s \"$current_path/../src/noosfero-spb/software_communities/\" plugins/software_communities\nln -s \"$current_path/../src/noosfero-spb/gov_user/\" plugins/gov_user\nln -s \"$current_path/../src/noosfero-spb/spb_migrations/\" plugins/spb_migrations\nln -s \"$current_path/../src/noosfero-spb/noosfero-spb-theme\" public/designs/themes/noosfero-spb-theme\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling Organization Ratings${NC}\\n\"\n./script/noosfero-plugins enable organization_ratings\nbundle exec rake db:migrate\nratings=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling Gov User, Software Communities and SPB Migrations${NC}\\n\"\n./script/noosfero-plugins enable software_communities gov_user\nbundle exec rake db:migrate\ngov_and_soft_plugins=$?\n\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Enabling SPB Migrations${NC}\\n\"\n./script/noosfero-plugins enable spb_migrations\nbundle exec rake db:migrate\nspb_migrations=$?\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Compiling translations${NC}\\n\"\nrake noosfero:translations:compile &>/dev/null\ntranslations=$?\n\nif [ $gov_and_soft_plugins -ne 0 ] || [ $ratings -ne 0 ] || [ $translations -ne 0 ] || [ $spb_migrations -ne 0 ]; then\n\tprintf \"${RED}=================================\\n\"\n\tprintf \"Error migrating SPB plugins!!n${NC}\\n\"\n exit 1\nfi\n\nprintf \"${GREEN}=================================\\n\"\nprintf \"Running rake db:test:prepare${NC}\\n\"\nbundle exec rake db:test:prepare\n"
},
{
"alpha_fraction": 0.6483644843101501,
"alphanum_fraction": 0.6495327353477478,
"avg_line_length": 22.75,
"blob_id": "afb12312d8cf7143da9b57c2fe65a7d6143f7c4c",
"content_id": "e89038b7ea9ad2945706a02a04755abaecb83d72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 856,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 36,
"path": "/src/noosfero-spb/gov_user/public/views/institution-modal.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\nmodulejs.define('InstitutionModal',\n ['jquery', 'NoosferoRoot', 'CreateInstitution'],\n function($, NoosferoRoot, CreateInstitution)\n{\n 'use strict';\n\n var AJAX_URL = {\n create_institution_modal:\n NoosferoRoot.urlWithSubDirectory(\"/plugin/gov_user/create_institution\"),\n };\n\n // Get the modal html code and prepare it\n function prepare_institution_modal() {\n $.get(AJAX_URL.create_institution_modal, function(response) {\n window.sessionStorage.setItem(\"InstitutionModalBody\", response);\n $(\"#institution_modal_body\").html(response);\n\n // Set all events on modal\n CreateInstitution.init();\n });\n }\n\n\n return {\n isCurrentPage: function() {\n return $(\"#institution_modal_container\").length === 1;\n },\n\n\n init: function() {\n prepare_institution_modal();\n },\n };\n});\n\n"
},
{
"alpha_fraction": 0.6538461446762085,
"alphanum_fraction": 0.6758241653442383,
"avg_line_length": 13,
"blob_id": "6438304b1effaeed194785db5cb8e0b534770c94",
"content_id": "8cc19a8e36a74b9a1180da4a793928d8cff552bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 182,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 13,
"path": "/cookbooks/redis/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'redis'\n\ntemplate '/etc/redis.conf' do\n user 'root'\n group 'root'\n mode 0644\n\n notifies :restart, 'service[redis]'\nend\n\nservice 'redis' do\n action [:enable, :start]\nend\n"
},
{
"alpha_fraction": 0.6711084246635437,
"alphanum_fraction": 0.6880678534507751,
"avg_line_length": 27.96491241455078,
"blob_id": "b98938d3ed87140c176c85ad1b6586ca15f36f00",
"content_id": "ab45f067e8712d06a4ddbeaf5a88d9fa95c5bb25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1651,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 57,
"path": "/src/noosfero-spb/gov_user/test/functional/search_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\nrequire(\nFile.dirname(__FILE__) +\n'/../../../../app/controllers/public/search_controller'\n)\n\nclass SearchController; def rescue_action(e) raise e end; end\n\nclass SearchControllerTest < ActionController::TestCase\n include PluginTestHelper\n\n def setup\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.save\n\n @controller = SearchController.new\n @request = ActionController::TestRequest.new\n @request.stubs(:ssl?).returns(:false)\n @response = ActionController::TestResponse.new\n end\n\n should \"communities searches don't have institution\" do\n community = create_community(\"New Community\")\n institution = create_private_institution(\n \"New Private Institution\",\n \"NPI\" ,\n \"Brazil\",\n \"DF\",\n \"Gama\",\n \"66.544.314/0001-63\"\n )\n\n get :communities, :query => \"New\"\n\n assert_includes assigns(:searches)[:communities][:results], community\n assert_not_includes assigns(:searches)[:communities][:results], institution.community\n end\n\n should \"institutions_search don't have community\" do\n community = create_community(\"New Community\")\n institution = create_private_institution(\n \"New Private Institution\",\n \"NPI\" ,\n \"Brazil\",\n \"DF\",\n \"Gama\",\n \"66.544.314/0001-63\"\n )\n\n get :institutions, :query => \"New\"\n\n assert_includes assigns(:searches)[:institutions][:results], institution.community\n assert_not_includes assigns(:searches)[:institutions][:results], community\n end\nend\n"
},
{
"alpha_fraction": 0.5555555820465088,
"alphanum_fraction": 0.5555555820465088,
"avg_line_length": 11,
"blob_id": "c9174e74ab417d22b85ad7356f46f18d59ae3cda",
"content_id": "3e01b6fe77344ce5c24d5d94fc425805b8035856",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 36,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 3,
"path": "/ci",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nrake -f Rakefile.ci \"$@\"\n"
},
{
"alpha_fraction": 0.6845425963401794,
"alphanum_fraction": 0.6845425963401794,
"avg_line_length": 27.772727966308594,
"blob_id": "646cc8aa51864008a9c0de90050dd17a6e3d8b9e",
"content_id": "13ac5881541e3d72e1486f85cc4c92112d6c64f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 634,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 22,
"path": "/src/noosfero-spb/gov_user/lib/gov_user_plugin/api.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../../lib/noosfero/api/helpers'\nrequire_relative 'api_entities'\n\nclass GovUserPlugin::API < Grape::API\n\n include Noosfero::API::APIHelpers\n\n resource :gov_user do\n get 'institutions' do\n authenticate!\n institutions = select_filtered_collection_of(environment,'communities',params).joins(:institution)\n present institutions.map{|o|o.institution}, :with => Entities::Institution\n end\n\n get 'institutions/:id' do\n authenticate!\n institution = Institution.find_by_id(params[:id])\n present institution, :with => Entities::Institution\n end\n\n end\nend\n\n"
},
{
"alpha_fraction": 0.68088299036026,
"alphanum_fraction": 0.6833476424217224,
"avg_line_length": 32.209964752197266,
"blob_id": "47169ea9aa4e336db9bb470d6e7908801d2cb9e7",
"content_id": "117d15aa01efaa8c5305e2fcab4d13a3374a731d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 9332,
"license_type": "no_license",
"max_line_length": 203,
"num_lines": 281,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_info.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareInfo < ActiveRecord::Base\n acts_as_having_settings :field => :settings\n\n SEARCHABLE_SOFTWARE_FIELDS = {\n :acronym => 1,\n :finality => 2,\n }\n\n SEARCHABLE_SOFTWARE_CLASSES = [\n Community,\n SoftwareCommunitiesPlugin::SoftwareInfo,\n SoftwareCommunitiesPlugin::ProgrammingLanguage,\n SoftwareCommunitiesPlugin::DatabaseDescription,\n Category\n ]\n\n scope :search_by_query, lambda { |query = \"\", env = Environment.default|\n filtered_query = query.gsub(/[\\|\\(\\)\\\\\\/\\s\\[\\]'\"*%&!:]/,' ').split.map{|w| w += \":*\"}.join('|')\n search_fields = SoftwareCommunitiesPlugin::SoftwareInfo.pg_search_plugin_fields\n\n if query.empty?\n SoftwareCommunitiesPlugin::SoftwareInfo.joins(:community).where(\"profiles.visible = ? AND environment_id = ? \", true, env.id)\n else\n searchable_software_objects = SoftwareCommunitiesPlugin::SoftwareInfo.transform_list_in_methods_list(SEARCHABLE_SOFTWARE_CLASSES)\n includes(searchable_software_objects).where(\"to_tsvector('simple', #{search_fields}) @@ to_tsquery('#{filtered_query}')\").where(\"profiles.visible = ?\", true).references(searchable_software_objects)\n end\n }\n\n def self.transform_list_in_methods_list list\n methods_list = []\n\n list.each do |element|\n if SoftwareCommunitiesPlugin::SoftwareInfo.instance_methods.include?(element.to_s.gsub(\"SoftwareCommunitiesPlugin::\", \"\").underscore.to_sym)\n methods_list << element.to_s.gsub(\"SoftwareCommunitiesPlugin::\", \"\").underscore.to_sym\n elsif SoftwareCommunitiesPlugin::SoftwareInfo.instance_methods.include?(element.to_s.gsub(\"SoftwareCommunitiesPlugin::\", \"\").underscore.pluralize.to_sym)\n methods_list << element.to_s.gsub(\"SoftwareCommunitiesPlugin::\", \"\").underscore.pluralize.to_sym\n end\n end\n\n methods_list\n end\n\n def self.pg_search_plugin_fields\n SEARCHABLE_SOFTWARE_CLASSES.collect { |one_class|\n self.get_searchable_fields(one_class)\n }.join(\" || ' ' || \")\n end\n\n def self.get_searchable_fields one_class\n searchable_fields = one_class::SEARCHABLE_SOFTWARE_FIELDS.keys.map(&:to_s).sort.map {|f| \"coalesce(#{one_class.table_name}.#{f}, '')\"}.join(\" || ' ' || \")\n searchable_fields\n end\n\n SEARCH_FILTERS = {\n :order => %w[],\n :display => %w[full]\n }\n\n def self.default_search_display\n 'full'\n end\n\n attr_accessible :e_mag, :icp_brasil, :intern, :e_ping, :e_arq,\n :operating_platform\n\n attr_accessible :demonstration_url, :acronym, :objectives, :features,\n :license_info\n\n attr_accessible :community_id, :finality, :repository_link, :public_software,\n :first_edit\n\n has_many :libraries, :dependent => :destroy, :class_name => 'SoftwareCommunitiesPlugin::Library'\n has_many :software_databases, :class_name => 'SoftwareCommunitiesPlugin::SoftwareDatabase'\n has_many :database_descriptions, :through => :software_databases, :class_name => 'SoftwareCommunitiesPlugin::DatabaseDescription'\n has_many :software_languages, :class_name => 'SoftwareCommunitiesPlugin::SoftwareLanguage'\n has_many :operating_systems, :class_name => 'SoftwareCommunitiesPlugin::OperatingSystem'\n has_many :programming_languages, :through => :software_languages, :class_name => 'SoftwareCommunitiesPlugin::ProgrammingLanguage'\n has_many :operating_system_names, :through => :operating_systems, :class_name => 'SoftwareCommunitiesPlugin::OperatingSystemName'\n has_many :categories, :through => :community\n\n belongs_to :community\n belongs_to :license_info, :class_name => 'SoftwareCommunitiesPlugin::LicenseInfo'\n\n validates_length_of :finality, :maximum => 4000\n validates_length_of :objectives, :maximum => 4000\n validates_length_of :features, :maximum => 4000\n validates_presence_of :finality, :community, :license_info\n\n validate :validate_acronym\n\n settings_items :another_license_version, :default => 'Another'\n settings_items :another_license_link, :default => '#'\n settings_items :sisp, :default => false\n\n serialize :agency_identification\n serialize :software_requirements\n serialize :hardware_requirements\n serialize :documentation\n serialize :system_applications\n serialize :active_versions\n serialize :estimated_cost\n serialize :responsible\n serialize :responsible_for_acquirement\n serialize :system_info\n serialize :development_info\n serialize :maintenance\n serialize :standards_adherence\n serialize :platform\n\n # used on find_by_contents\n def self.like_search name\n joins(:community).where(\n \"name ILIKE ? OR acronym ILIKE ? OR finality ILIKE ?\",\n \"%#{name}%\", \"%#{name}%\", \"%#{name}%\"\n )\n end\n\n scope :search, lambda { |name=\"\", database_description_id = \"\",\n programming_language_id = \"\", operating_system_name_id = \"\",\n license_info_id = \"\", e_ping = \"\", e_mag = \"\", internacionalizable = \"\",\n icp_brasil = \"\", e_arq = \"\", software_categories = \"\" |\n\n like_sql = \"\"\n values = []\n\n unless name.blank?\n like_sql << \"name ILIKE ? OR identifier ILIKE ? AND \"\n values << \"%#{name}%\" << \"%#{name}%\"\n end\n\n like_sql = like_sql[0..like_sql.length-5]\n\n {\n :joins => [:community],\n :conditions=>[like_sql, *values]\n }\n }\n\n def license_info\n license = SoftwareCommunitiesPlugin::LicenseInfo.find_by_id self.license_info_id\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(\"Another\")\n\n if license_another && license.id == license_another.id\n SoftwareCommunitiesPlugin::LicenseInfo.new(\n :version => self.another_license_version,\n :link => self.another_license_link\n )\n else\n super\n end\n end\n\n def another_license(version, link)\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(\"Another\")\n\n if license_another\n self.another_license_version = version\n self.another_license_link = link\n self.license_info = license_another\n self.save!\n end\n end\n\n def validate_name_lenght\n if self.community.name.size > 100\n self.errors.add(\n :base,\n _(\"Name is too long (maximum is %{count} characters)\")\n )\n false\n end\n true\n end\n\n # if create_after_moderation receive a model object, would be possible to reuse core method\n def self.create_after_moderation(requestor, attributes = {})\n environment = attributes.delete(:environment)\n name = attributes.delete(:name)\n identifier = attributes.delete(:identifier)\n image_builder = attributes.delete(:image_builder)\n license_info = attributes.delete(:license_info)\n another_license_version = attributes.delete(:another_license_version)\n another_license_link = attributes.delete(:another_license_link)\n\n software_info = SoftwareCommunitiesPlugin::SoftwareInfo.new(attributes)\n if !requestor.is_admin?\n SoftwareCommunitiesPlugin::CreateSoftware.create!(\n attributes.merge(\n :requestor => requestor,\n :environment => environment,\n :name => name,\n :identifier => identifier,\n :license_info => license_info,\n :another_license_version => another_license_version,\n :another_license_link => another_license_link\n )\n )\n else\n software_template = Community[\"software\"]\n\n community_hash = {:name => name}\n community_hash[:identifier] = identifier\n community_hash[:image_builder] = image_builder if image_builder\n\n community = Community.new(community_hash)\n community.environment = environment\n\n if (!software_template.blank? && software_template.is_template)\n community.template_id = software_template.id\n end\n\n community.save!\n community.add_admin(requestor)\n\n software_info.community = community\n software_info.license_info = license_info\n software_info.verify_license_info(another_license_version, another_license_link)\n software_info.save!\n end\n\n software_info\n end\n\n def verify_license_info another_license_version, another_license_link\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(\"Another\")\n\n if license_another && self.license_info_id == license_another.id\n version = another_license_version\n link = another_license_link\n\n self.another_license(version, link)\n end\n end\n\n\n def validate_acronym\n self.acronym = \"\" if self.acronym.nil?\n if self.acronym.length > 10 && self.errors.messages[:acronym].nil?\n self.errors.add(:acronym, _(\"can't have more than 10 characteres\"))\n false\n elsif self.acronym.match(/\\s+/)\n self.errors.add(:acronym, _(\"can't have whitespaces\"))\n false\n end\n true\n end\n\n def valid_operating_systems\n if self.operating_systems.empty?\n self.errors.add(:operating_system, _(\": at least one must be filled\"))\n end\n end\n\n def valid_software_info\n if self.software_languages.empty?\n self.errors.add(:software_languages, _(\": at least one must be filled\"))\n end\n end\n\n def valid_databases\n if self.software_databases.empty?\n self.errors.add(:software_databases, _(\": at least one must be filled\"))\n end\n end\n\n def visible?\n self.community.visible?\n end\n\n def name\n self.community.name\n end\n\n def short_name\n self.community.short_name\n end\n\n def identifier\n self.community.identifier\n end\nend\n"
},
{
"alpha_fraction": 0.6621160507202148,
"alphanum_fraction": 0.6638225317001343,
"avg_line_length": 29.842105865478516,
"blob_id": "1fdd65321bda2395e13ca0c98d110c0e291ad8ea",
"content_id": "b9065f09f3213e4b4ad1b6d265893ba680e03137",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 595,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 19,
"path": "/src/noosfero-spb/gov_user/db/seeds.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: UTF-8\npowers = [\"Executivo\", \"Legislativo\", \"Judiciário\", \"Não se Aplica\"]\nspheres = [\"Federal\", \"Estadual\", \"Distrital\", \"Municipal\"]\njur_natures = [\"Administração Direta\", \"Autarquia\", \"Empresa Pública\", \"Fundação\",\n \"Orgão Autônomo\", \"Sociedade\", \"Sociedade Civil\",\n \"Sociedade de Economia Mista\"\n ]\n\npowers.each do |power|\n GovernmentalPower.create(:name => power)\nend\n\nspheres.each do |sphere|\n GovernmentalSphere.create(:name => sphere)\nend\n\njur_natures.each do |jur_nature|\n JuridicalNature.create(:name => jur_nature)\nend\n"
},
{
"alpha_fraction": 0.7111111283302307,
"alphanum_fraction": 0.7111111283302307,
"avg_line_length": 30.764705657958984,
"blob_id": "414139713c6a4732744f7553b4049faafeee6b53",
"content_id": "3f06864d9b5ca035c663b6d4c623533dd4d8c558",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 540,
"license_type": "no_license",
"max_line_length": 151,
"num_lines": 17,
"path": "/roles/integration_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name \"integration_server\"\ndescription \"Server that runs COLAB (user authentication, visual integration and gamification), mailman (mailing lists), and Gitlab (git repositories)\"\n\n# TODO colab and mailman-api should be able to run in separate hosts at some\n# point in the future\nrun_list *[\n 'recipe[basics::nginx]',\n 'recipe[email::destination]',\n 'recipe[mailman-api]',\n 'recipe[mailman]',\n 'recipe[mailman::webui]',\n 'recipe[gitlab]',\n 'recipe[colab]',\n 'recipe[colab::nginx]',\n 'recipe[backup]',\n #'recipe[mezuro::prezento]'\n]\n"
},
{
"alpha_fraction": 0.6648585796356201,
"alphanum_fraction": 0.6652460098266602,
"avg_line_length": 38.10606002807617,
"blob_id": "bf7ae4799472c15e31bf9dfe5c4e1404b6561326",
"content_id": "e2b18a1a674a7c659224d6cc6314a22fd0fdc6df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2582,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 66,
"path": "/src/noosfero-spb/software_communities/lib/tasks/templates.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/env ruby\n# encoding: utf-8\n\nnamespace :templates do\n namespace :create do\n\n desc \"Create new templates of software, intitution, person and community\"\n task :all => :environment do\n Rake::Task[\"templates:create:software\"].invoke\n end\n\n desc \"Create new templates of software\"\n task :software => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"MpogSoftware\") or env.plugin_enabled?(\"SoftwareCommunitiesPlugin\")\n software = SoftwareHelper.software_template\n\n if software.nil?\n identifier = YAML::load(File.open(SoftwareCommunitiesPlugin.root_path + 'config.yml'))['software_template']\n software = Community.create!(:name => \"Software\", :identifier => identifier)\n end\n\n software.layout_template = \"default\"\n software.is_template = true\n software.save!\n\n puts \"Software Template successfully created!\"\n end\n end\n end\n end\n\n desc \"Destroy all templates created by this namespace\"\n task :destroy => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"MpogSoftware\") or env.plugin_enabled?(\"SoftwareCommunitiesPlugin\")\n Community[\"software\"].destroy unless Community[\"software\"].nil?\n puts \"Software template destoyed with success!\"\n end\n end\n end\n\n desc \"Copy mail list article from template to all Communities\"\n task :copy_mail_article => :environment do\n env = Environment.find_by_name(\"SPB\") || Environment.default\n article = Profile['software'].articles.find_by_slug('como-participar-da-lista-de-discussao')\n Article.connection.execute(\"DELETE FROM articles WHERE slug='como-participar-da-lista-de-discussao' AND id NOT IN (#{article.id})\")\n puts \"Copying article #{article.title}: \" if article.present?\n if article.present?\n env.communities.find_each do |community|\n next unless community.software?\n a_copy = community.articles.find_by_slug('como-participar-da-lista-de-discussao') || article.copy_without_save\n a_copy.profile = community\n a_copy.save\n box = community.boxes.detect {|x| x.blocks.find_by_title(\"Participe\") } if community.present?\n block = box.blocks.find_by_title(\"Participe\") if box.present?\n link = block.links.detect { |l| l[\"name\"] == \"Listas de discussão\" } if block.present?\n link[\"address\"] = \"/{profile}/#{a_copy.path}\" if link.present?\n block.save if block.present?\n print \".\"\n end\n else\n puts \"Article not found\"\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7212121486663818,
"alphanum_fraction": 0.7212121486663818,
"avg_line_length": 22.571428298950195,
"blob_id": "1697e8e46b70a0c6f2080098d77aa9076a9792f5",
"content_id": "424171ef6571c72c77023f507f8043a59e45bd4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 165,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 7,
"path": "/roles/mezuro_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'mezuro_server'\ndescription 'Mezuro server'\nrun_list *[\n 'recipe[mezuro]',\n 'recipe[mezuro::kalibro_processor]',\n 'recipe[mezuro::kalibro_configurations]'\n]\n"
},
{
"alpha_fraction": 0.5153374075889587,
"alphanum_fraction": 0.5331845879554749,
"avg_line_length": 34.156864166259766,
"blob_id": "3452a39a73cdea1692b624b80358a06fd407b0e8",
"content_id": "8ba701b7ccfa068686ab1abd6ee17b80cc9552af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1793,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 51,
"path": "/src/noosfero-spb/gov_user/test/unit/gov_user_plugin_api_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/unit/api/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass GovUserPlugin::ApiTest < ActiveSupport::TestCase\n\n include PluginTestHelper\n\n def setup\n login_api\n environment = Environment.default\n environment.enable_plugin(GovUserPlugin)\n @gov_power = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n @institution = create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"11.222.333/4444-55\")\n end\n\n should 'list all institutions' do\n @institution1 = create_public_institution(\n \"Instituicao bacana\",\n \"IB\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"11.222.333/4444-56\"\n )\n\n get \"/api/v1/gov_user/institutions?#{params.to_query}\"\n json = JSON.parse(last_response.body)\n assert_equivalent [@institution.id, @institution1.id], json['institutions'].map {|c| c['id']}\n end\n\n should 'get institution by id' do\n get \"/api/v1/gov_user/institutions/#{@institution.id}?#{params.to_query}\"\n json = JSON.parse(last_response.body)\n assert_equal @institution.id, json[\"institution\"][\"id\"]\n end\n\nend\n"
},
{
"alpha_fraction": 0.6511131525039673,
"alphanum_fraction": 0.6727660894393921,
"avg_line_length": 28.276784896850586,
"blob_id": "a9fa25c2905729b83689c4d0766d5f022e3e0f6c",
"content_id": "0ee21ca5fa601fcadc847695f1aa95c9c22948b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3279,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 112,
"path": "/src/noosfero-spb/gov_user/test/functional/gov_user_plugin_myprofile_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/institution_test_helper'\nrequire(\nFile.dirname(__FILE__) +\n'/../../controllers/gov_user_plugin_myprofile_controller'\n)\n\nclass GovUserPluginMyprofileController; def rescue_action(e) raise e end;\nend\n\nclass GovUserPluginMyprofileControllerTest < ActionController::TestCase\n def setup\n @controller = GovUserPluginMyprofileController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n @person = create_user('person').person\n @offer = create_user('Angela Silva')\n @offer_1 = create_user('Ana de Souza')\n @offer_2 = create_user('Angelo Roberto')\n\n gov_power = GovernmentalPower.create(:name=>\"Some Gov Power\")\n gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n @institution = InstitutionTestHelper.create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n juridical_nature,\n gov_power,\n gov_sphere,\n \"12.345.678/9012-45\"\n )\n\n login_as(@person.user_login)\n @environment = Environment.default\n @environment.enable_plugin('GovUserPlugin')\n @environment.save!\n end\n\n should \"admin user edit an institution\" do\n @institution.community.add_admin @person\n identifier = @institution.community.identifier\n\n fields = InstitutionTestHelper.generate_form_fields(\n \"institution new name\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n \"12.345.678/9012-45\",\n \"PrivateInstitution\"\n )\n\n post(\n :edit_institution,\n :profile=>@institution.community.identifier,\n :community=>fields[:community],\n :institutions=>fields[:institutions]\n )\n\n institution = Community[identifier].institution\n assert_not_equal \"Ministerio Publico da Uniao\", institution.community.name\n end\n\n should \"regular user should not edit an institution\" do\n identifier = @institution.community.identifier\n fields = InstitutionTestHelper.generate_form_fields(\n \"institution new name\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n \"12.345.678/9012-45\",\n \"PrivateInstitution\"\n )\n\n post(\n :edit_institution,\n :profile=>@institution.community.identifier,\n :community=>fields[:community],\n :institutions=>fields[:institutions]\n )\n\n institution = Community[identifier].institution\n assert_equal \"Ministerio Publico da Uniao\", institution.community.name\n assert_response 403\n end\n\n should \"not user edit its community institution with wrong values\" do\n identifier = @institution.community.identifier\n fields = InstitutionTestHelper.generate_form_fields(\n \"\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n \"6465465465\",\n \"PrivateInstitution\"\n )\n\n post(\n :edit_institution,\n :profile=>@institution.community.identifier,\n :community=>fields[:community],\n :institutions=>fields[:institutions]\n )\n\n institution = Community[identifier].institution\n assert_equal \"Ministerio Publico da Uniao\", institution.community.name\n assert_equal \"12.345.678/9012-45\", institution.cnpj\n end\n\nend\n"
},
{
"alpha_fraction": 0.691428542137146,
"alphanum_fraction": 0.691428542137146,
"avg_line_length": 24,
"blob_id": "fd6499cd3b1039a4597faa8dd4a8288a27e76e04",
"content_id": "557c1a6e7d3cdfed8fae0fb042ad588b9a51ee66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 700,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 28,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/api_entities.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module Entities\n\n class LicenseInfo < Noosfero::API::Entity\n expose :version\n expose :link\n end\n\n class SoftwareInfo < Noosfero::API::Entity\n root 'software_infos', 'software_info'\n expose :id\n expose :finality\n expose :repository_link\n expose :public_software\n expose :acronym\n expose :objectives\n expose :features\n expose :license_info, :using => LicenseInfo\n expose :software_languages\n expose :software_databases\n expose :operating_system_names\n expose :created_at, :format_with => :timestamp\n expose :updated_at, :format_with => :timestamp\n expose :community_id do |software_info,options|\n software_info.community.id\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.7013888955116272,
"alphanum_fraction": 0.7013888955116272,
"avg_line_length": 19.571428298950195,
"blob_id": "c37c24871d1c053cce6f02cfb9c8786358cbac55",
"content_id": "231f53278d4db88d84de1348bc69c011bd32e0a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 144,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 7,
"path": "/roles/social_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'database_server'\ndescription 'Social networking server'\nrun_list *[\n 'recipe[basics::nginx]',\n 'recipe[noosfero]',\n 'recipe[backup]'\n]\n"
},
{
"alpha_fraction": 0.7534246444702148,
"alphanum_fraction": 0.7534246444702148,
"avg_line_length": 28.200000762939453,
"blob_id": "9109c01a459dce9432800d1eb60df8dc53e9db2f",
"content_id": "2ec6b2ca3a288360e76241c7dd0030474caacaf9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 10,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/license_info.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::LicenseInfo < ActiveRecord::Base\n attr_accessible :version, :link\n\n validates_presence_of :version\n\n has_many :software_info, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n\n scope :without_another, lambda { where(\"version != 'Another'\") }\n\nend\n"
},
{
"alpha_fraction": 0.6305418610572815,
"alphanum_fraction": 0.633004903793335,
"avg_line_length": 20.75,
"blob_id": "a14329e9e0e19421bd5ddad73eaa405768924e37",
"content_id": "0f07202a1365aa973bfaf3048c84778df65e4c32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1218,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 56,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_events_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareEventsBlock < Block\n\n settings_items :amount_of_events, :type => :integer, :default => 3\n attr_accessible :amount_of_events\n\n validates :amount_of_events,\n :presence => true, :numericality => {\n greater_than_or_equal_to: 1\n }\n\n def self.description\n _('Software community events')\n end\n\n def help\n _('This block displays the software community events in a list.')\n end\n\n def default_title\n _('Other events')\n end\n\n def content(args={})\n block = self\n\n lambda do |object|\n render(\n :file => 'blocks/software_events',\n :locals => { :block => block }\n )\n end\n end\n\n def cacheable?\n false\n end\n\n def get_events\n yesterday = DateTime.yesterday.end_of_day\n self.owner.events.where(\"start_date > ?\", yesterday).order(:start_date, :id).limit(self.amount_of_events)\n end\n\n def get_events_except event_slug=\"\"\n event_slug = \"\" if event_slug.nil?\n\n get_events.where(\"slug NOT IN (?)\", event_slug)\n end\n\n def has_events_to_display? current_event_slug=\"\"\n not get_events_except(current_event_slug).empty?\n end\n\n def should_display_title?\n self.box.position != 1\n end\nend\n"
},
{
"alpha_fraction": 0.6480000019073486,
"alphanum_fraction": 0.6480000019073486,
"avg_line_length": 40.66666793823242,
"blob_id": "5689c92f486f1d9e7b5d8a1ad185f62a6e81a08c",
"content_id": "c2ad0af0ae6cfdc2c2615680cc0d7915ca241033",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 252,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 6,
"path": "/test/config_helper.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# exports all configuration variables into the environment with a config_\n# prefix, e.g.\n#\n# external_hostname → $config_external_hostname\n\neval $(sed -e '/^\\S*:\\s*\\S\\+/!d; s/^/config_/; s/:\\s*/=/' ${ROOTDIR:-.}/config/${SPB_ENV:-local}/config.yaml)\n"
},
{
"alpha_fraction": 0.649779736995697,
"alphanum_fraction": 0.649779736995697,
"avg_line_length": 22.894737243652344,
"blob_id": "6472241a81fd8dc4d4004a088a3fd2e149ba854b",
"content_id": "22c1fc76d363855096600317c23af5a45e24d51c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 454,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 19,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140617132133_create_governmental_spheres.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class CreateGovernmentalSpheres < ActiveRecord::Migration\n def change\n create_table :governmental_spheres do |t|\n t.string :name\n t.string :acronym\n t.integer :unit_code\n t.integer :parent_code\n t.string :unit_type\n t.string :juridical_nature\n t.string :sub_juridical_nature\n t.string :normalization_level\n t.string :version\n t.string :cnpj\n t.string :type\n\n t.timestamps\n end\n end\nend\n"
},
{
"alpha_fraction": 0.773809552192688,
"alphanum_fraction": 0.773809552192688,
"avg_line_length": 26.66666603088379,
"blob_id": "3ff1ff6f889ab0733ec6270e4918a8404bf9459a",
"content_id": "aa8aa937a20d149090f4bf7c7092bd1590bd4f3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 84,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 3,
"path": "/roles/ci_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'ci_server'\ndescription 'Continuous integration server'\nrun_list 'recipe[ci]'\n\n"
},
{
"alpha_fraction": 0.7612903118133545,
"alphanum_fraction": 0.7612903118133545,
"avg_line_length": 21.14285659790039,
"blob_id": "379911346a426acc71cc29e6310d7bcf54243f86",
"content_id": "aef8f8f01ee4eb2b919c5c497b3f2f0048b47437",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 155,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 7,
"path": "/src/noosfero-spb/gov_user/lib/governmental_sphere.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class GovernmentalSphere < ActiveRecord::Base\n attr_accessible :name\n\n validates :name, :presence=>true, :uniqueness=>true\n\n has_many :institutions\nend\n"
},
{
"alpha_fraction": 0.7070063948631287,
"alphanum_fraction": 0.7070063948631287,
"avg_line_length": 16.44444465637207,
"blob_id": "8f55cf317e79563162eac2b9258acc3f6188b750",
"content_id": "347aeced495e2ea64dab7457c08c982d74d8eab8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 157,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 9,
"path": "/cookbooks/email/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'email'\n\npackage 'postfix'\npackage 'mailx' # for testing, etc\n\nservice 'postfix' do\n action [:enable, :start]\n supports :reload => true\nend\n"
},
{
"alpha_fraction": 0.623253345489502,
"alphanum_fraction": 0.6253625154495239,
"avg_line_length": 31.418804168701172,
"blob_id": "63f6821dea02227e8aad4382135c3e17860711d4",
"content_id": "84695fcb249774233c036bc9f6b7eb47a8997532",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3804,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 117,
"path": "/src/noosfero-spb/gov_user/lib/institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#encoding: utf-8\n\nclass Institution < ActiveRecord::Base\n has_many :comments\n\n N_(\"institution\")\n\n SEARCH_FILTERS = {\n :order => %w[more_recent more_popular more_active],\n :display => %w[compact]\n }\n\n CNPJ_FORMAT = /\\A\\d{2}\\.\\d{3}\\.\\d{3}\\/\\d{4}\\-\\d{2}\\z/\n\n VALID_STATES = { \"AC\"=>\"Acre\", \"AL\"=>\"Alagoas\", \"AM\"=>\"Amazonas\", \"AP\"=>\"Amapá\", \"BA\"=>\"Bahia\", \"CE\"=>\"Ceará\",\n \"DF\"=>\"Distrito Federal\", \"ES\"=>\"Espírito Santo\", \"GO\"=>\"Goiás\", \"MA\"=>\"Maranhão\", \"MT\"=>\"Mato Grosso\",\n \"MS\"=>\"Mato Grosso do Sul\", \"MG\"=>\"Minas Gerais\", \"PA\"=>\"Pará\", \"PB\"=>\"Paraíba\", \"PR\"=>\"Paraná\",\n \"PE\"=>\"Pernambuco\", \"PI\"=>\"Piauí\", \"RJ\"=>\"Rio de Janeiro\", \"RN\"=>\"Rio Grande do Norte\", \"RO\"=>\"Rondônia\",\n \"RS\"=>\"Rio Grande do Sul\", \"RR\"=>\"Roraima\", \"SC\"=>\"Santa Catarina\", \"SE\"=>\"Sergipe\", \"SP\"=>\"São Paulo\", \"TO\"=>\"Tocantins\" }\n\n def self.default_search_display\n 'compact'\n end\n\n belongs_to :governmental_power\n belongs_to :governmental_sphere\n belongs_to :juridical_nature\n\n has_and_belongs_to_many :users\n\n attr_accessible :name, :acronym, :unit_code, :parent_code, :unit_type,\n :sub_juridical_nature, :normalization_level,\n :version, :cnpj, :type, :governmental_power,\n :governmental_sphere, :sisp, :juridical_nature,\n :corporate_name, :siorg_code, :community\n\n validates :name, :presence=>true, :uniqueness=>true\n validates :cnpj, :length=>{maximum: 18}\n\n before_save :verify_institution_type\n\n belongs_to :community\n\n scope :search_institution, lambda{ |value, env|\n joins(:community).where(\"(profiles.name ilike ? OR institutions.acronym ilike ?) AND profiles.environment_id = ?\", \"%#{value}%\", \"%#{value}%\", env.id)\n }\n\n validate :validate_country, :validate_state, :validate_city,\n :verify_institution_type\n\n validates :siorg_code,\n numericality: {only_integer: true, message: _(\"invalid, only numbers are allowed.\")},\n allow_blank: true\n\n def has_accepted_rating? user_rating\n rating_ids = OrganizationRating.where(institution_id: self.id, organization_id: user_rating.organization_id).map(&:id)\n finished_tasks = CreateOrganizationRatingComment.finished.select {|task| rating_ids.include?(task.organization_rating_id)}\n pending_tasks = CreateOrganizationRatingComment.pending.select{|c| c.organization_rating_id == user_rating.id}\n\n !finished_tasks.empty? && !pending_tasks.empty?\n end\n\n protected\n\n def verify_institution_type\n valid_institutions_type = [\"PublicInstitution\", \"PrivateInstitution\"]\n\n unless valid_institutions_type.include? self.type\n self.errors.add(\n :type,\n _(\"invalid, only public and private institutions are allowed.\")\n )\n\n return false\n end\n\n return true\n end\n\n def validate_country\n unless self.community.blank?\n if self.community.country.blank? && self.errors[:country].blank?\n self.errors.add(:country, _(\"can't be blank\"))\n return false\n end\n end\n\n return true\n end\n\n def validate_state\n if self.community.present? && self.community.country == \"BR\"\n if self.community.state.blank?\n self.errors.add(:state, _(\"can't be blank\")) if self.errors[:state].blank?\n return false\n elsif !VALID_STATES.values.include?(self.community.state)\n self.errors.add(:state, _(\"invalid state\")) if self.errors[:state].blank?\n return false\n end\n end\n\n return true\n end\n\n def validate_city\n unless self.community.blank?\n if self.community.country == \"BR\" && self.community.city.blank? &&\n self.errors[:city].blank?\n\n self.errors.add(:city, _(\"can't be blank\"))\n return false\n end\n end\n\n return true\n end\nend\n"
},
{
"alpha_fraction": 0.6107784509658813,
"alphanum_fraction": 0.6107784509658813,
"avg_line_length": 19.875,
"blob_id": "eef998de172bf88f7861f80774599269e6018fd7",
"content_id": "ba0e45a9aa124b9198d1a1bec955ab4d728a16fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 167,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 8,
"path": "/cookbooks/basics/files/default/selinux-enabled",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\n# MANAGED WITH CHEF; DO NOT CHANGE BY HAND\n\nset -e\n\nselinux_status=$(sestatus | sed -e '/^SELinux status:/ !d; s/.*\\s//')\n[ \"$selinux_status\" = 'enabled' ]\n"
},
{
"alpha_fraction": 0.7676348686218262,
"alphanum_fraction": 0.7676348686218262,
"avg_line_length": 25.77777862548828,
"blob_id": "e887259f8b534aa61e81439f859a59458260335f",
"content_id": "974ece62196c8b5f40e665c7be9c643d933514f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 241,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 9,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160104182236_remove_softwares_with_nil_community.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class RemoveSoftwaresWithNilCommunity < ActiveRecord::Migration\n def up\n execute('DELETE FROM software_communities_plugin_software_infos where community_id IS NULL;')\n end\n\n def down\n say\"This migration can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.659392774105072,
"alphanum_fraction": 0.6612903475761414,
"avg_line_length": 31.430768966674805,
"blob_id": "87b1ee4f351cce8a18ddbea50a63ca9879b0aa36",
"content_id": "e2a5a5f31b0af45815bfd566fa7aa7ef7a592ba2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2108,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 65,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150910133925_add_community_block_in_place_of_profile_image_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddCommunityBlockInPlaceOfProfileImageBlock < ActiveRecord::Migration\n def up\n software_template = Community['software']\n\n if software_template\n software_area_two = software_template.boxes.find_by_position 2\n\n community_block_template = CommunityBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n community_block_template.settings[:fixed] = true\n community_block_template.display = \"except_home_page\"\n community_block_template.save!\n print \".\"\n\n software_area_two.blocks << community_block_template\n software_area_two.save!\n print \".\"\n\n profile_image_block = software_area_two.blocks.find_by_type(\"ProfileImageBlock\")\n if !profile_image_block.nil?\n community_block_template.position = profile_image_block.position\n community_block_template.save!\n print \".\"\n\n profile_image_block.destroy\n print \".\"\n end\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_two = software_community.boxes.find_by_position 2\n print \".\"\n\n community_block = CommunityBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n community_block.settings[:fixed] = true\n community_block.display = \"except_home_page\"\n community_block.mirror_block_id = community_block_template.id if community_block_template\n community_block.save!\n print \".\"\n\n software_area_two.blocks << community_block\n software_area_two.save!\n print \".\"\n\n profile_image_block = software_area_two.blocks.find_by_type(\"ProfileImageBlock\")\n if !profile_image_block.nil?\n community_block.position = profile_image_block.position\n community_block.save!\n print \".\"\n\n profile_image_block.destroy\n print \".\"\n\n # Put all link list blocks to behind\n link_list_blocks = software_area_two.blocks.where(:type=>\"LinkListBlock\", :position=>1)\n link_list_blocks.update_all :position => 3\n end\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.6973180174827576,
"alphanum_fraction": 0.6973180174827576,
"avg_line_length": 19.076923370361328,
"blob_id": "21ee4b94ccb09062c1314b7f2e366a82defbabc7",
"content_id": "3183ec0533b80a1dc9039c44abb9f595e6b9ce1f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 261,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 13,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140815194530_register_institution_modification.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class RegisterInstitutionModification < ActiveRecord::Migration\n def up\n change_table :institutions do |t|\n t.string :date_modification\n end\n end\n\n def down\n change_table :institutions do |t|\n t.remove :date_modification\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6829691529273987,
"alphanum_fraction": 0.6861824989318848,
"avg_line_length": 35.1860466003418,
"blob_id": "f76ce53400006a5fc7c3516d2a78a07f7569cbfe",
"content_id": "16381512c060a67b14002b48c883aa2f023b2334",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 15560,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 430,
"path": "/src/noosfero-spb/software_communities/test/functional/search_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\nrequire(\n File.dirname(__FILE__) +\n '/../../../../app/controllers/public/search_controller'\n)\n\nclass SearchController; def rescue_action(e) raise e end; end\n\nclass SearchControllerTest < ActionController::TestCase\n include PluginTestHelper\n\n def setup\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n @environment.save\n\n @controller = SearchController.new\n @request = ActionController::TestRequest.new\n @request.stubs(:ssl?).returns(:false)\n @response = ActionController::TestResponse.new\n\n @licenses = [\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version => \"GPL - 1\"),\n SoftwareCommunitiesPlugin::LicenseInfo.create(:version => \"GPL - 2\")\n ]\n\n create_software_categories\n\n @softwares = []\n\n @softwares << create_software_info(\"Software One\", :acronym => \"SFO\", :finality => \"Help\")\n @softwares << create_software_info(\"Software Two\", :acronym => \"SFT\", :finality => \"Task\")\n\n @softwares[0].community.categories << Category.all[0]\n @softwares[1].community.categories << Category.all[1]\n\n @softwares[0].license_info = @licenses.first\n @softwares[1].license_info = @licenses.last\n\n @softwares[0].save!\n @softwares[1].save!\n end\n\n should \"communities searches don't have software\" do\n community = create_community(\"Community One\")\n\n get :communities, :query => \"One\"\n\n assert_includes assigns(:searches)[:communities][:results], community\n assert_not_includes assigns(:searches)[:communities][:results], @softwares.first.community\n end\n\n should \"software_infos search don't have community\" do\n community = create_community(\"Community One\")\n\n get :software_infos, :query => \"One\"\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], community\n end\n\n\n should \"Don't have template in communities search result\" do\n communities = []\n communities << create_community(\"Community One\")\n communities << create_community(\"Community Two\")\n\n community_template = create_community(\"Community Template\")\n community_template.is_template = true\n community_template.visible = false\n community_template.save!\n\n get :communities, :query => \"Comm\"\n\n assert_not_includes(\n assigns(:searches)[:communities][:results],\n community_template\n )\n end\n\n should \"software_infos search by category\" do\n get(\n :software_infos,\n :query => \"\",\n :selected_categories_id => [Category.all[0].id]\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n end\n\n should \"return software_infos with category matching query\" do\n some_category = Category.new(:name => \"Health\", :environment => @environment)\n @softwares[0].community.categories << some_category\n\n get(\n :software_infos,\n :sort => \"relevance\",\n :query => \"Health\"\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares[0].community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares[1].community\n end\n\n should \"software_infos search by sub category\" do\n category = Category.create(:name => \"Category\", :environment => @environment)\n sub_category = Category.create(:name => \"Sub Category\", :environment => @environment, :parent_id => category.id)\n\n software = create_software_info \"software 1\"\n software.community.add_category sub_category\n\n software2 = create_software_info \"software 2\"\n software2.community.add_category category\n\n get(\n :software_infos,\n :query => \"\",\n :selected_categories_id => [category.id]\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software2.community\n end\n\n should \"software_infos search softwares with one or more selected categories\" do\n software = create_software_info(\"Software Two\", :acronym => \"SFT\", :finality => \"Task\")\n software.save!\n\n get(\n :software_infos,\n :query => \"\",\n :selected_categories_id => [Category.all[0].id, Category.all[1].id]\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software.community\n end\n\n\n should \"software_infos search by programming language\" do\n @softwares.first.software_languages << create_software_language(\"Python\", \"1.0\")\n @softwares.last.software_languages << create_software_language(\"Java\", \"8.1\")\n\n @softwares.first.save!\n @softwares.last.save!\n\n get(\n :software_infos,\n :query => \"python\",\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n end\n\n should \"software_infos search by database description\" do\n @softwares.first.software_databases << create_software_database(\"MySQL\", \"1.0\")\n @softwares.last.software_databases << create_software_database(\"Postgrees\", \"8.1\")\n\n @softwares.first.save!\n @softwares.last.save!\n\n get(\n :software_infos,\n :query => \"mysql\",\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n end\n\n should \"software_infos search by finality\" do\n get(\n :software_infos,\n :query => \"help\",\n )\n\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n end\n\n should \"software_infos search by acronym\" do\n get(\n :software_infos,\n :query => \"SFO\",\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.first.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], @softwares.last.community\n end\n\n should \"software_infos search by relevance\" do\n @softwares << create_software_info(\"Software Three\", :acronym => \"SFW\", :finality => \"Java\")\n @softwares.last.license_info = SoftwareCommunitiesPlugin::LicenseInfo.create :version => \"GPL - 3.0\"\n\n\n @softwares.first.software_languages << create_software_language(\"Java\", \"8.0\")\n @softwares.first.save!\n\n @softwares[1].community.name = \"Java\"\n @softwares[1].community.save!\n\n get(\n :software_infos,\n :sort => \"relevance\",\n :query => \"Java\"\n )\n\n assert_equal assigns(:searches)[:\"software_infos\"][:results][0], @softwares[1].community\n assert_equal assigns(:searches)[:\"software_infos\"][:results][1], @softwares[2].community\n assert_equal assigns(:searches)[:\"software_infos\"][:results][2], @softwares[0].community\n end\n\n should \"software_infos search only public_software\" do\n software_one = create_software_info(\"Software One\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Java\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software Three\", :acronym => \"SFW\", :finality => \"Java\")\n software_three.public_software = false\n software_three.save!\n\n get(\n :software_infos,\n :software_type => \"public_software\"\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_two.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software_three.community\n end\n\n should \"software_infos search public_software and other all\" do\n software_one = create_software_info(\"Software One\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Java\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software Three\", :acronym => \"SFW\", :finality => \"Java\")\n software_three.public_software = false\n software_three.save!\n\n get(\n :software_infos,\n :software_type => \"all\"\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_two.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_three.community\n end\n\n should \"software_infos search return only the software in params\" do\n software_one = create_software_info(\"Software One\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Java\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software Three\", :acronym => \"SFW\", :finality => \"Java\")\n\n get(\n :software_infos,\n :only_softwares => [\"software-three\", \"java\"]\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_two.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_three.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n end\n\n should \"software_infos search return only the software in params order by Z-A\" do\n software_one = create_software_info(\"Software One\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Java\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software Three\", :acronym => \"SFW\", :finality => \"Java\")\n\n get(\n :software_infos,\n :only_softwares => [\"software-three\", \"java\"],\n :sort => \"desc\"\n )\n\n assert_equal assigns(:searches)[:\"software_infos\"][:results][0], software_three.community\n assert_equal assigns(:searches)[:\"software_infos\"][:results][1], software_two.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n end\n\n\n should \"software_infos search return only enabled softwares\" do\n s1 = SoftwareCommunitiesPlugin::SoftwareInfo.first\n s2 = SoftwareCommunitiesPlugin::SoftwareInfo.last\n\n # First get them all normally\n get(\n :software_infos,\n :query => \"software\"\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], s1.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], s2.community\n\n s2.community.disable\n\n # Now it should not contain the disabled community\n get(\n :software_infos,\n :query => \"software\"\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], s1.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], s2.community\n end\n\n should \"software_infos search not return software with secret community\" do\n software_one = create_software_info(\"Software ABC\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Python\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software DEF\", :acronym => \"SFW\", :finality => \"Java\")\n\n software_one.community.secret = true\n software_one.community.save!\n\n get(\n :software_infos,\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_two.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_three.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n end\n\n should \"software_infos search not return sisp softwares\" do\n software_one = create_software_info(\"Software ABC\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Python\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software DEF\", :acronym => \"SFW\", :finality => \"Java\")\n\n software_one.sisp = true\n software_one.save!\n\n get(\n :software_infos,\n )\n\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_two.community\n assert_includes assigns(:searches)[:\"software_infos\"][:results], software_three.community\n assert_not_includes assigns(:searches)[:\"software_infos\"][:results], software_one.community\n end\n\n should \"sisp search not return software without sisp\" do\n software_one = create_software_info(\"Software ABC\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Python\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software DEF\", :acronym => \"SFW\", :finality => \"Java\")\n\n software_two.sisp = true\n software_two.save!\n\n software_three.sisp = true\n software_three.save!\n\n get(\n :sisp,\n )\n\n assert_includes assigns(:searches)[:sisp][:results], software_two.community\n assert_includes assigns(:searches)[:sisp][:results], software_three.community\n assert_not_includes assigns(:searches)[:sisp][:results], software_one.community\n end\n\n should \"sisp search by category\" do\n software_one = create_software_info(\"Software ABC\", :acronym => \"SFO\", :finality => \"Help\")\n software_two = create_software_info(\"Python\", :acronym => \"SFT\", :finality => \"Task\")\n software_three = create_software_info(\"Software DEF\", :acronym => \"SFW\", :finality => \"Java\")\n\n software_two.sisp = true\n software_two.community.categories << Category.last\n software_two.save!\n\n software_three.sisp = true\n software_three.save!\n\n get(\n :sisp,\n :selected_categories_id => [Category.last.id]\n )\n\n assert_includes assigns(:searches)[:sisp][:results], software_two.community\n assert_not_includes assigns(:searches)[:sisp][:results], software_three.community\n assert_not_includes assigns(:searches)[:sisp][:results], software_one.community\n end\n\n private\n\n def create_software_categories\n category_software = Category.create!(\n :name => \"Software\",\n :environment => @environment\n )\n Category.create(\n :name => \"Category One\",\n :environment => @environment,\n :parent => category_software\n )\n Category.create(\n :name => \"Category Two\",\n :environment => @environment,\n :parent => category_software\n )\n end\n\n def create_software_language(name, version)\n unless SoftwareCommunitiesPlugin::ProgrammingLanguage.find_by_name(name)\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name => name)\n end\n\n software_language = SoftwareCommunitiesPlugin::SoftwareLanguage.new\n software_language.programming_language = SoftwareCommunitiesPlugin::ProgrammingLanguage.find_by_name(name)\n software_language.version = version\n software_language.save!\n\n software_language\n end\n\n def create_software_database(name, version)\n unless SoftwareCommunitiesPlugin::DatabaseDescription.find_by_name(name)\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => name)\n end\n\n software_database = SoftwareCommunitiesPlugin::SoftwareDatabase.new\n software_database.database_description = SoftwareCommunitiesPlugin::DatabaseDescription.find_by_name(name)\n software_database.version = version\n software_database.save!\n\n software_database\n end\n\nend\n"
},
{
"alpha_fraction": 0.7360647916793823,
"alphanum_fraction": 0.7360647916793823,
"avg_line_length": 27.75342559814453,
"blob_id": "894b1ab0490afa675d035c1aed8e3d0df07bf687",
"content_id": "5e1b8e8cf40f7c8e238ceda92d0647cb744af1a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2099,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 73,
"path": "/src/README.md",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# Building Packages\n\nThis path and scripts automates the build and update the packages for SPB project.\nIt's can be done manually, but we don't recommend.\n\n## Requirements\n\nFirst, this will only works (at least was tested) on a RedHat based system\n(Fedora, CentOS, etc). Everything you need to know about packing for the system\nis available [here](https://fedoraproject.org/wiki/How_to_create_an_RPM_package/pt)\n\nDependency packages\n\n```\n# yum install @development-tools\n# yum install fedora-packager\n# yum install copr-cli\n# yum install git\n```\n\nYou need a account on [Copr Fedora](https://copr.fedorainfracloud.org) and the api token to\nauthenticate when upload. Just follow the instruction on the\n[API](https://copr.fedorainfracloud.org/api/).\n\nYou need your GPG key in the machine. If you don't have one follow the\ninstruction [here](https://fedoraproject.org/wiki/Creating_GPG_Keys/pt-br)\n\n## Usage\n\n### Make Release\n\nMake Release are made to build *colab-spb-plugin*, *colab-spb-theme* e \n*noosfero-spb*. Bump the VERSION file on the root directory and runs\ninto the src/ directory:\n\n```\n$ make release\n```\n\nFollow the instructions and done :).\nDon't forget to push the changes to the repository.\n\n### Build Packages\n\nTo build the others packages.\n\n**First**: Build the **tarball** of the\ncore project. Pay attention to how to build this, some projects needs\nrequirements or pre-command before create the **tarball**.\n\nIn most of the cases you just needs to run into the project repository:\n```\n $ git archive --format=tar.gz --prefix=<pkg-name>-<pkg-version>/ <tag or branch> > <pkg-name>-<pkg-version>.tar.gz\n or\n $ make sdist\n```\n\n**Second**: Copy the **tarball** into the pkg-rpm/<project>/\n\n**Third**: Runs into the src/pkg-rpm/:\n```\n $ make <project>-build\n and\n $ make <project>-upload\n```\n\nThe first will build the package and the second will upload to\nthe copr repository using copr-cli.\n\n**Note**: the copr repository is defined into *src/pkg-rpm/Makefile*.\n\n**Important**: Make sure that you have all the build dependencies installed.\nJust check the .spec file to verify which are.\n"
},
{
"alpha_fraction": 0.693473219871521,
"alphanum_fraction": 0.693473219871521,
"avg_line_length": 24.235294342041016,
"blob_id": "95d1b431daf84f4796d06bc839c3b28398e1cf58",
"content_id": "b2ab9ddbf4f4383cfae1d6a4079c26594294cfac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 858,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 34,
"path": "/src/noosfero-spb/gov_user/lib/ext/organization_rating.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency \"organization_rating\"\n\nOrganizationRating.class_eval do\n\n belongs_to :institution\n\n attr_accessible :institution, :institution_id\n\n validate :verify_institution, :verify_organization_rating_values\n\n private\n\n def verify_institution\n if self.institution != nil\n institution = Institution.find_by_id self.institution.id\n self.errors.add :institution, _(\"institution not found\") unless institution\n return !!institution\n end\n end\n\n def verify_organization_rating_values\n if self.institution.nil?\n if self.people_benefited\n self.errors.add _('institution'), _(\"needs to be valid to save the number of people benefited\")\n false\n end\n if self.saved_value\n self.errors.add _('institution'), _(\"needs to be valid to save report values\")\n false\n end\n end\n end\n\nend\n"
},
{
"alpha_fraction": 0.6951219439506531,
"alphanum_fraction": 0.6951219439506531,
"avg_line_length": 19.5,
"blob_id": "e297f370ccce3a9d832df9b50c8fc6da0d4dcb44",
"content_id": "e2bdb04e11be7636e2ae11c75c9d871207f5f4d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 164,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 8,
"path": "/roles/monitoring_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'monitoring_server'\ndescription 'Monitoring server'\nrun_list *[\n 'recipe[munin]',\n 'recipe[rsyslog]',\n 'recipe[rsyslog::server]',\n 'recipe[loganalyzer]'\n]\n"
},
{
"alpha_fraction": 0.6808346509933472,
"alphanum_fraction": 0.6935857534408569,
"avg_line_length": 20.7394962310791,
"blob_id": "d4edd2dfd58134e195c16ce20d37f4eba3d6f385",
"content_id": "a4e822cfcb490d9b09b6b2f34c83919e729697a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2588,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 119,
"path": "/cookbooks/basics/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "\n# our custom repositories\nif node['platform'] == 'centos'\n\n # Removing the old repo of chef for centos systems\n file '/etc/yum.repos.d/chef.repo' do\n action :delete\n end\n file '/etc/yum.repos.d/chef.key' do\n action :delete\n end\n\n cookbook_file '/etc/yum.repos.d/softwarepublico.key' do\n owner 'root'\n mode 0644\n end\n\n template '/etc/yum.repos.d/softwarepublico.repo' do\n owner 'root'\n mode 0644\n end\n\n unless node['config']['keep_yum_cache']\n execute 'yum_clean_cache' do\n command 'yum clean all'\n end\n # reload internal Chef yum cache\n ruby_block \"yum-cache-reload\" do\n block { Chef::Provider::Package::Yum::YumCache.instance.reload }\n end\n end\nend\n\n# enable EPEL repository by default\npackage 'epel-release'\n\n# replicate production security setup\npackage 'selinux-policy'\npackage 'policycoreutils-python'\ncookbook_file '/etc/selinux/config' do\n source 'selinux_config'\n owner 'root'\n group 'root'\n mode 0644\nend\n\ncookbook_file '/usr/local/bin/selinux-enabled' do\n owner 'root'\n group 'root'\n mode '0755'\nend\n\nexecute 'setenforce Enforcing' do\n only_if 'selinux-enabled'\nend\nexecute 'setsebool -P httpd_can_network_connect 1' do\n only_if 'selinux-enabled'\nend\n# directory for local type enforcements\ndirectory '/etc/selinux/local' do\n owner 'root'\n group 'root'\n mode '0755'\nend\ncookbook_file '/usr/local/bin/selinux-install-module' do\n owner 'root'\n group 'root'\n mode '0755'\nend\n\npackage 'vim'\npackage 'bash-completion'\npackage 'rsyslog'\npackage 'tmux'\npackage 'less'\npackage 'htop'\npackage 'ntp'\n\ncookbook_file '/usr/local/bin/is-a-container' do\n owner 'root'\n group 'root'\n mode '0755'\nend\nservice 'ntpd' do\n action [:enable, :start]\n not_if 'is-a-container'\nend\n\nservice 'firewalld' do\n action [:disable, :stop]\n ignore_failure true\nend\n\nservice 'sshd' do\n action [:enable]\nend\n\n# FIXME on Debian it's postgresql-client\npackage 'postgresql'\n\n# reload node[:fqdn] to make sure it reflects the contents of /etc/hosts\n# without that the variable :fqdn would not be available on first run\nruby_block 'fqdn:update' do\n block do\n node.default[:fqdn] = `hostname --fqdn`.strip\n end\n action :nothing\nend\n\nexecute 'avoid_etc_hosts_being_overwriten' do\n command 'sed -i -e \\'/^\\s*-\\s*update_etc_hosts/d\\' /etc/cloud/cloud.cfg'\n only_if { File.exist?('/etc/cloud/cloud.cfg') }\nend\n\ntemplate '/etc/hosts' do\n owner 'root'\n mode 0644\n notifies :run, 'ruby_block[fqdn:update]', :immediately\n notifies :run, 'execute[avoid_etc_hosts_being_overwriten]', :immediately\nend\n"
},
{
"alpha_fraction": 0.8571428656578064,
"alphanum_fraction": 0.8571428656578064,
"avg_line_length": 38.20000076293945,
"blob_id": "389cebee71b898ce16cd040ae00953e19dddf29f",
"content_id": "67edc4beea0915765c9a6b5a77645d0678c19ad5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 196,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 5,
"path": "/cookbooks/colab/files/default/noosfero_profile.py",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "from colab.widgets.widget_manager import WidgetManager\n\nfrom colab_noosfero.widgets.profile.profile import NoosferoProfileWidget\n\nWidgetManager.register_widget('profile', NoosferoProfileWidget())\n"
},
{
"alpha_fraction": 0.6701966524124146,
"alphanum_fraction": 0.6701966524124146,
"avg_line_length": 35.72222137451172,
"blob_id": "e0c3d788d84098e5951907be417eaad824020130",
"content_id": "2cc91cc03fc10f218bff6f2512dd6fc3cecdd253",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 661,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 18,
"path": "/src/noosfero-spb/gov_user/db/migrate/20160120185910_fix_communities_with_wrong_state.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class FixCommunitiesWithWrongState < ActiveRecord::Migration\n def up\n select_all(\"SELECT id, data FROM profiles WHERE type = 'Community'\").each do |community|\n settings = YAML.load(community['data'] || {}.to_yaml)\n new_state = Institution::VALID_STATES[settings[:state].upcase] if settings[:state].present?\n\n if new_state.present?\n settings[:state] = new_state\n assignments = Institution.send(:sanitize_sql_for_assignment, settings.to_yaml)\n update(\"UPDATE profiles SET data = '%s' WHERE id = %d\" % [assignments, community['id']])\n end\n end\n end\n\n def down\n say \"This migration can't be reverted.\"\n end\nend\n"
},
{
"alpha_fraction": 0.7640449404716492,
"alphanum_fraction": 0.7640449404716492,
"avg_line_length": 28.66666603088379,
"blob_id": "4099adaaac1cb211d4fff80ee06ab15216458c19",
"content_id": "0c60ad961f993e4d5b473ae8b60a5869cdd574f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 267,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 9,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20151106172419_remove_softwares_without_community.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class RemoveSoftwaresWithoutCommunity < ActiveRecord::Migration\n def up\n execute('DELETE FROM software_communities_plugin_software_infos where community_id NOT IN (SELECT id FROM profiles)')\n end\n\n def down\n say \"This migration can't be reverted!\"\n end\nend\n"
},
{
"alpha_fraction": 0.738095223903656,
"alphanum_fraction": 0.738095223903656,
"avg_line_length": 22.33333396911621,
"blob_id": "ef1fd1755640daf614bd701e314bb34be7ae5bce",
"content_id": "fdbd0ab0babdf38abda71321949ea5cb8cbd537c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 9,
"path": "/src/noosfero-spb/gov_user/db/migrate/20160525181858_change_siorg_column_type.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class ChangeSiorgColumnType < ActiveRecord::Migration\n def self.up\n change_column :institutions, :siorg_code, :string\n end\n\n def self.down\n change_column :institutions, :siorg_code, :integer\n end\nend\n"
},
{
"alpha_fraction": 0.7027027010917664,
"alphanum_fraction": 0.7027027010917664,
"avg_line_length": 9.090909004211426,
"blob_id": "87a1bf340319709c9d3ac8bb33f582b725288287",
"content_id": "f90ef8db84744c48809c0128e2fb65444b33fa1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 222,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 22,
"path": "/utils/ci/install-from-scratch",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\nset -x\n\n# cleanup previous build\ncleanup() {\n vagrant destroy -f\n rm -rf tmp/\n}\ncleanup\ntrap cleanup INT EXIT TERM\n\n# bring VMS up\nvagrant up\n\n# install everything\nrake preconfig\nrake\n\n# test\nrake test\n"
},
{
"alpha_fraction": 0.5451505184173584,
"alphanum_fraction": 0.5459865927696228,
"avg_line_length": 27.4761905670166,
"blob_id": "590bd9c0ea353889ce4b1479e5a1444cd3f9a0ab",
"content_id": "bcb59ad9ca89dd70b8fbae0b905e1ffdc09eb639",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1196,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 42,
"path": "/src/noosfero-spb/software_communities/lib/tasks/create_licenses.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "namespace :software do\n desc \"Create software licences\"\n\n task :create_licenses => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"SoftwareCommunitiesPlugin\") or env.plugin_enabled?(\"SoftwareCommunities\")\n list_file = File.open \"plugins/software_communities/public/static/licences.txt\", \"r\"\n\n version_or_link = 'version'\n can_save = true\n licence = nil\n\n print 'Creating Licenses: '\n list_file.each_line do |line|\n data = line.strip\n\n if data.length != 0\n if version_or_link == 'version'\n can_save = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(data) ? false : true\n licence = SoftwareCommunitiesPlugin::LicenseInfo::new :version => data\n version_or_link = 'link'\n elsif version_or_link == 'link'\n licence.link = data\n\n if can_save\n licence.save!\n print '.'\n else\n print 'F'\n end\n\n version_or_link = 'version'\n end\n end\n end\n puts ''\n\n list_file.close\n end\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7395833134651184,
"alphanum_fraction": 0.7395833134651184,
"avg_line_length": 20.33333396911621,
"blob_id": "0347e46041d11ad4caf81ffd8d1f777044194fff",
"content_id": "83cdec514fa6d467595975824c8855d05ea48d46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 192,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 9,
"path": "/src/noosfero-spb/gov_user/db/migrate/20150910135510_add_siorg_code_to_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddSiorgCodeToInstitution < ActiveRecord::Migration\n def up\n add_column :institutions, :siorg_code, :integer\n end\n\n def down\n remove_column :institutions, :siorg_code\n end\nend\n"
},
{
"alpha_fraction": 0.5705705881118774,
"alphanum_fraction": 0.5720720887184143,
"avg_line_length": 18.02857208251953,
"blob_id": "dffdc9de6170a6066a033caa07c494888e5226fb",
"content_id": "b0d3be66f4f84e45fab4a724d4f0c490df76879b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 666,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 35,
"path": "/src/noosfero-spb/software_communities/public/initializer.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n var dependencies = [\n 'ControlPanel',\n 'EditSoftware',\n 'NewSoftware',\n 'SearchSoftwareCatalog',\n 'SoftwareDownload',\n 'ProfileTabsSoftware',\n 'NewCommunity',\n 'CommentsSoftwareExtraFields'\n ];\n\n\n modulejs.define('Initializer', dependencies, function() {\n var __dependencies = arguments;\n\n\n function call_dependency(dependency) {\n if( dependency.isCurrentPage() ) {\n dependency.init();\n }\n }\n\n\n return {\n init: function() {\n for(var i=0, len = __dependencies.length; i < len; i++) {\n call_dependency(__dependencies[i]);\n }\n }\n };\n });\n})();\n"
},
{
"alpha_fraction": 0.65625,
"alphanum_fraction": 0.6588541865348816,
"avg_line_length": 31,
"blob_id": "682edea90465e39fcf496055eb409aad331c8470",
"content_id": "eca78e87adeb6684149222d7503ea81bcc976856",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 12,
"path": "/tasks/dependencies.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "task :check_dependencies do\n missing = [\n { program: 'sphinx-build', package: 'python-sphinx' },\n { program: 'make', package: 'make' },\n ].select do |dependency|\n !system(\"which #{dependency[:program]} >/dev/null\")\n end\n missing.each do |dependency|\n puts \"Please install package #{dependency[:package]}\"\n end\n fail 'E: missing dependencies' if missing.size > 0\nend\n"
},
{
"alpha_fraction": 0.6575682163238525,
"alphanum_fraction": 0.6575682163238525,
"avg_line_length": 16.521739959716797,
"blob_id": "52c216d5483fa30b7571e8f6f604224669fb6cc4",
"content_id": "24de7bbd15d432c70641b7f156c0d4faeb06ba66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 23,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150915141403_apply_short_plus_pic_to_all_communities_blogs.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class ApplyShortPlusPicToAllCommunitiesBlogs < ActiveRecord::Migration\n def up\n Community.all.each do |community|\n set_short_plus_pic_to_blog community.blog\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\n\n private\n\n def set_short_plus_pic_to_blog blog\n if blog\n blog.visualization_format = \"short+pic\"\n blog.save!\n print \".\"\n end\n end\nend\n"
},
{
"alpha_fraction": 0.5694050788879395,
"alphanum_fraction": 0.580736517906189,
"avg_line_length": 34.29999923706055,
"blob_id": "8e8cf25260b149fd8d6483810d87a2cde73a8189",
"content_id": "126ea2a7c1af4c310f33db75b8245a02ddbfe759",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 353,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 10,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/library.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::Library < ActiveRecord::Base\n attr_accessible :name, :version, :license, :software_info_id\n\n validates :name, :version, :license,\n presence: { message: _(\"can't be blank\") },\n length: {\n maximum: 20,\n too_long: _(\"Too long (maximum is 20 characters)\")\n }\nend\n"
},
{
"alpha_fraction": 0.6685934662818909,
"alphanum_fraction": 0.676300585269928,
"avg_line_length": 36.07143020629883,
"blob_id": "f227172de82defbc466e7e20a831d89a4f78bb49",
"content_id": "ad28daad95ff998a8ff795ad9042bc464489fe63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 519,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 14,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/operating_system.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::OperatingSystem < ActiveRecord::Base\n attr_accessible :version\n\n belongs_to :software_info, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n belongs_to :operating_system_name, :class_name => 'SoftwareCommunitiesPlugin::OperatingSystemName'\n\n validates :operating_system_name, presence: true\n validates :version,\n presence: true,\n length: {\n maximum: 20,\n too_long: _('too long (maximum is 20 characters)')\n }\nend\n"
},
{
"alpha_fraction": 0.6822020411491394,
"alphanum_fraction": 0.6859555840492249,
"avg_line_length": 19.493589401245117,
"blob_id": "1e5f534dd2de4beacc47ea449c7660486bf0ad2c",
"content_id": "fb15df7085cd332b4c482272a3c316548d606195",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3212,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 156,
"path": "/src/noosfero-spb/noosfero-spb-theme/README.md",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "PSB Theme for Noosfero\n================================\n\nNoosfero theme for the _Portal do Software Público_ project.\n\nInstall on /public/designs/themes/noosfero-spb-theme\n\n================================\n\n# Passos para configurar o tema a partir do spb/spb\n\n## Considerando que o clone do noosfero está na pasta home\n\n```bash\nrm -r ~/noosfero/public/design/theme/noosfero-spb-theme\ncd ~\ngit clone [email protected]:softwarepublico/softwarepublico.git\ncd softwarepublico/src/noosfero-spb/\nln -sr noosfero-spb-theme/ ~/noosfero/public/designs/themes/\nln -sr software_communities ~/noosfero/plugins/\nln -sr gov_user ~/noosfero/plugins/\ngit remote add theme [email protected]:softwarepublico/noosfero-spb-theme.git\n```\n\n# Para instalar o Colab\n\n```bash\ncd ~\ngit clone https://github.com/colab/colab\n```\n\n## Configuração\n\nSeguir [tutorial](https://github.com/colab/colab/blob/master/README.rst) do próprio Colab\n\n## Arquivos de configuração Colab\n\nEstando com o ambiente do vagrant levantado `(vagrant up && vagrant ssh)`,\ne \"trabalhando\" com o colab `(workon colab)`:\n\n## Clone os repositórios:\n\n```bash\ncd ~\ngit clone [email protected]:softwarepublico/softwarepublico.git\ngit clone https://github.com/colab/colab-gitlab-plugin\ngit clone https://github.com/colab/colab-noosfero-plugin\n```\n\n## Criando diretórios - Plugins do Colab\n\n```bash\nmkdir /etc/colab/plugins.d/\ncd plugins.d\n```\n\n## Crie os arquivos\n\n### gitlab.py\n\n```bash\nvim gitlab.py\n```\n\n#### Conteúdo do gitlab.py\n\n```python\nfrom django.utils.translation import ugettext_lazy as _\nfrom colab.plugins.utils.menu import colab_url_factory\n\nname = \"colab_gitlab\"\nverbose_name = \"Gitlab\"\n\nupstream = ''\nprivate_token = ''\n\nurls = {\n \"include\":\"colab_gitlab.urls\",\n \"prefix\": 'gitlab/',\n \"namespace\":\"gitlab\"\n }\n\nurl = colab_url_factory('gitlab')\n```\n\n### noosfero.py\n\n```bash\nvim noosfero.py\n```\n\n#### Conteúdo do noosfero.py\n\n```python\nfrom django.utils.translation import ugettext_lazy as _\nfrom colab.plugins.utils.menu import colab_url_factory\n\nname = \"colab_noosfero\"\nverbose_name = \"Noosfero\"\nprivate_token = \"\"\n\nupstream = 'http://<IP DA SUA MÁQUINA AQUI>:8080/social'\n\nurls = {\n \"include\":\"colab_noosfero.urls\",\n \"prefix\": '^social/',\n \"namespace\":\"social\"\n }\n\nurl = colab_url_factory('social')\n```\n\n### spb.py\n\n```bash\nvim spb.py\n```\n\n#### Conteúdo do spb.py\n\n```python\nfrom django.utils.translation import ugettext_lazy as _\nfrom colab.plugins.utils.menu import colab_url_factory\n\nname = \"colab_spb\"\nverbose_name = \"SPB Plugin\"\nurls = {\n \"include\":\"colab_spb.urls\",\n \"prefix\": '^spb/',\n \"namespace\":\"colab_spb\"\n }\n\nurl = colab_url_factory('colab_spb')\n```\n### Execuntando scripts de instalação\n\n```bash\ncd ~/softwarepublico/config/\npip install -e .\ncd ~/softwarepublico/src/colab-spb-plugin/\npip install -e .\ncolab-admin migrate\ncolab-admin migrate colab_spb\ncd ~/colab-gitlab-plugin/\npip install -e .\ncd ~/softwarepublico/src/colab-spb-plugin/\npip install -e .\ncolab-admin migrate\n```\n\n## Finalizando\n\nExecute o noosfero seja no ambiente local, ou schroot,\ncom o comando `RAILS_RELATIVE_URL_ROOT=/social unicorn`\n\nNo vagrant, execute `colab-admin runserver 0.0.0.0:8000`\n"
},
{
"alpha_fraction": 0.7039473652839661,
"alphanum_fraction": 0.7171052694320679,
"avg_line_length": 20.571428298950195,
"blob_id": "5e29c00a9171770c8ee56588fdadd2c0488b1377",
"content_id": "c40ce9355424d12021b3bcca487a626307feb4da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 152,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 7,
"path": "/test/mailman_api_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_mailman_api_running() {\n assertTrue 'mailman running' 'run_on integration pgrep -fa mailman-api'\n}\n\nload_shunit2\n\n"
},
{
"alpha_fraction": 0.6480793356895447,
"alphanum_fraction": 0.6525712609291077,
"avg_line_length": 38.36585235595703,
"blob_id": "8956b13a94268c2d2964f59c7e993cf839e2358e",
"content_id": "e83935fba04109a04155f734ac560a2463ab3bf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 6456,
"license_type": "no_license",
"max_line_length": 187,
"num_lines": 164,
"path": "/Rakefile",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'yaml'\n\nbegin\n load 'local.rake'\nrescue LoadError\n # nothing\nend\n\n$SPB_ENV = ENV.fetch('SPB_ENV', 'local')\n\nssh_config_file = \"config/#{$SPB_ENV}/ssh_config\"\nips_file = \"config/#{$SPB_ENV}/ips.yaml\"\nconfig_file = \"config/#{$SPB_ENV}/config.yaml\"\niptables_file = \"config/#{$SPB_ENV}/iptables-filter-rules\"\n\nENV['CHAKE_TMPDIR'] = \"tmp/chake.#{$SPB_ENV}\"\nENV['CHAKE_SSH_CONFIG'] = ssh_config_file\n\nchake_rsync_options = ENV['CHAKE_RSYNC_OPTIONS'].to_s.clone\nchake_rsync_options += ' --exclude backups'\nchake_rsync_options += ' --exclude src'\nENV['CHAKE_RSYNC_OPTIONS'] = chake_rsync_options\n\nif $SPB_ENV == 'lxc'\n system(\"mkdir -p config/lxc; sudo lxc-ls -f -F name,ipv4 | sed -e '/^softwarepublico/ !d; s/softwarepublico_//; s/_[0-9_]*/:/ ' > #{ips_file}.new\")\n begin\n ips = YAML.load_file(\"#{ips_file}.new\")\n raise ArgumentError unless ips.is_a?(Hash)\n FileUtils.mv ips_file + '.new', ips_file\n rescue Exception => ex\n puts ex.message\n puts\n puts \"Q: did you boot the containers first?\"\n exit\n end\n config = YAML.load_file('config/local/config.yaml')\n File.open(config_file, 'w') do |f|\n f.puts(YAML.dump(config))\n end\n\n File.open('config/lxc/iptables-filter-rules', 'w') do |f|\n lxc_host_bridge_name = `awk '{ if ($1 == \"lxc.network.link\") { print($3) } }' /etc/lxc/default.conf`.strip\n lxc_host_bridge_ip = ` /sbin/ifconfig #{lxc_host_bridge_name} | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }' `.strip\n f.puts \"-A INPUT -s #{lxc_host_bridge_ip} -p tcp -m state --state NEW --dport 22 -j ACCEPT\"\n f.puts \"-A INPUT -s #{lxc_host_bridge_ip} -p tcp -m state --state NEW --dport 5555 -j ACCEPT\"\n end\nend\n\nrequire 'chake'\n\nif Gem::Version.new(Chake::VERSION) < Gem::Version.new('0.13')\n fail \"Please upgrade to chake 0.10+\"\nend\n\nips ||= YAML.load_file(ips_file)\nconfig ||= YAML.load_file(config_file)\nfirewall ||= File.open(iptables_file).read\nconfig['keep_yum_cache'] = ENV['keep_yum_cache'] ? true : false\n$nodes.each do |node|\n node.data['environment'] = $SPB_ENV\n node.data['config'] = config\n node.data['peers'] = ips\n node.data['firewall'] = firewall\nend\n\ntask :console do\n require 'pry'\n binding.pry\nend\n\ntask :test do\n sh \"SPB_ENV=#{$SPB_ENV} ./test/run_all\"\nend\n\nfile 'ssh_config.erb'\nif ['local', 'lxc'].include?($SPB_ENV)\n file ssh_config_file => ['nodes.yaml', ips_file, 'ssh_config.erb', 'Rakefile'] do |t|\n require 'erb'\n template = ERB.new(File.read('ssh_config.erb'))\n File.open(t.name, 'w') do |f|\n f.write(template.result(binding))\n end\n puts 'ERB %s' % t.name\n end\nend\ntask 'bootstrap_common' => ssh_config_file\ntask 'run_input' => ssh_config_file\n\ndesc 'Downloads latest system backups to backups directory. WARNING: This overrides anything written in the backups directory'\ntask :backup => ssh_config_file do\n # setup\n sh 'rm', '-rf', 'backups'\n sh 'mkdir', '-p', 'backups'\n # integration\n sh 'ssh', '-F', ssh_config_file, 'integration', 'sudo', 'chmod a+xr /.snapshots'\n sh 'scp', '-F', ssh_config_file, 'integration:/.snapshots/hourly.0/spb/*', 'backups/'\n # social\n sh 'ssh', '-F', ssh_config_file, 'social', 'sudo', 'chmod a+xr /.snapshots'\n sh 'scp', '-F', ssh_config_file, 'social:/.snapshots/hourly.0/spb/*', 'backups/'\nend\n\ndesc 'Restores content saved in the backups directory to the target env. WARNING: This will drop all the current databases'\ntask :restore => [ssh_config_file, config_file] do\n # setup\n sh 'ssh', '-F', ssh_config_file, 'integration', 'sudo', 'rm -rf /tmp/backups'\n sh 'ssh', '-F', ssh_config_file, 'integration', 'sudo', 'systemctl stop colab'\n sh 'ssh', '-F', ssh_config_file, 'social', 'sudo', 'rm -rf /tmp/backups'\n sh 'ssh', '-F', ssh_config_file, 'social', 'sudo', 'systemctl stop noosfero'\n sh 'ssh', '-F', ssh_config_file, 'database', 'sudo', 'sudo -u postgres dropdb colab 2> /dev/null'\n sh 'ssh', '-F', ssh_config_file, 'database', 'sudo', 'sudo -u postgres createdb colab --owner colab 2> /dev/null'\n sh 'ssh', '-F', ssh_config_file, 'database', 'sudo', 'sudo -u postgres dropdb noosfero 2> /dev/null'\n sh 'ssh', '-F', ssh_config_file, 'database', 'sudo', 'sudo -u postgres createdb noosfero --owner noosfero 2> /dev/null'\n #integration\n sh 'scp', '-r', '-F', ssh_config_file, 'backups', 'integration:/tmp'\n sh 'scp', '-F', ssh_config_file, 'utils/migration/restore_integration.sh', 'integration:/tmp'\n sh 'ssh', '-F', ssh_config_file, 'integration', 'sudo', \"env SPB_URL=#{config['lists_hostname']} /tmp/restore_integration.sh\"\n #social\n sh 'scp', '-r', '-F', ssh_config_file, 'backups', 'social:/tmp'\n sh 'scp', '-F', ssh_config_file, 'utils/migration/restore_social.sh', 'social:/tmp'\n sh 'ssh', '-F', ssh_config_file, 'social', 'sudo', '/tmp/restore_social.sh'\n sh 'ssh', '-F', ssh_config_file, 'social', 'sudo', 'systemctl start noosfero'\n sh 'ssh', '-F', ssh_config_file, 'integration', 'sudo', 'systemctl start colab'\nend\n\nnamespace :export_data do\n task :noosfero => [ssh_config_file, config_file] do\n # setup\n sh 'mkdir', '-p', 'exported_data'\n #social\n sh 'ssh', '-F', ssh_config_file, 'social', 'cd /usr/lib/noosfero/ && sudo -u noosfero RAILS_ENV=production bundle exec rake export:catalog:csv'\n sh 'scp', '-F', ssh_config_file, 'social:/tmp/software_catalog_csvs.tar.gz', 'exported_data/'\n end\nend\n\ntask :bootstrap_common => :check_dependencies\n\nunless ENV['nodeps']\n task 'converge:integration' => 'converge:database'\n task 'converge:integration' => 'converge:social'\n task 'converge:social' => 'converge:database'\n task 'upload:reverseproxy' => 'doc'\nend\n\n$ALT_SSH_PORT = config.fetch('alt_ssh_port', 2222)\n\n$nodes.find { |n| n.hostname == 'reverseproxy' }.data['ssh_port'] = $ALT_SSH_PORT\ndesc 'Makes configurations needed before the bootstrap phase'\ntask :preconfig => ssh_config_file do\n sh 'mkdir', '-p', 'tmp/'\n preconfig_file = \"tmp/preconfig.#{$SPB_ENV}.stamp\"\n if File.exist?(preconfig_file)\n puts \"I: preconfig already done.\"\n puts \"I: delete #{preconfig_file} to force running again\"\n else\n sh 'scp', '-F', ssh_config_file, 'utils/reverseproxy_ssh_setup', 'reverseproxy.unconfigured:/tmp'\n sh 'ssh', '-F', ssh_config_file, 'reverseproxy.unconfigured', 'sudo', '/tmp/reverseproxy_ssh_setup', $ALT_SSH_PORT.to_s, config['external_ip'], ips['reverseproxy'], ips['integration']\n\n File.open(preconfig_file, 'w') do |f|\n f.puts($ALT_SSH_PORT)\n end\n end\nend\n\nDir.glob('tasks/*.rake').each { |f| load f }\n"
},
{
"alpha_fraction": 0.5816186666488647,
"alphanum_fraction": 0.5895061492919922,
"avg_line_length": 20.284671783447266,
"blob_id": "a8af973e8195efd0f9f0c3d2c2324ab4318c78dc",
"content_id": "53a61cbf818dfef61ea494636de0098d9c319b84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2916,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 137,
"path": "/test/dns_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\nif [ \"$SPB_ENV\" = local -o \"$SPB_ENV\" = lxc ]; then\n echo \"_No DNS for local environment_\"\n exit\nfi\n\n\nexport LANG=C\n\ncheck_hostname() {\n local host=\"$1\"\n local ip=\"$2\"\n local results=\"$(host -t A $host)\"\n local expected=\"$host has address $ip\"\n assertEquals \"$host must resolve to $ip\" \"$results\" \"$expected\"\n}\n\ncheck_mx() {\n local host=\"$1\"\n local mx=\"$2\"\n local results=\"$(host -t MX $host)\"\n local expected=\"$host mail is handled by 0 ${mx}.\"\n assertEquals \"$host MX must be $mx\" \"$results\" \"$expected\"\n}\n\ncheck_reverse_dns() {\n local ip=\"$1\"\n local hostname=\"$2\"\n local results=\"$(host $ip)\"\n local expected=\".*in-addr.arpa domain name pointer ${hostname}.\"\n assertTrue \"Reverse DNS of $ip must be $hostname (found: $results)\" \"expr match '$results' 'include:$expected\\$'\"\n}\n\ncheck_spf() {\n domain=\"$1\"\n spf_domain=\"$2\"\n local results=\"$(host -t TXT \"$domain\")\"\n assertTrue \"TXT entry for $domain must have include:$spf_domain (found: $results)\" \"expr match '$results' 'include:$spf_domain'\"\n}\n\ntest_dns_web() {\n check_hostname \"$config_external_hostname\" \"$config_external_ip\"\n}\n\ntest_mx() {\n check_mx \"$config_external_hostname\" \"${config_relay_hostname}\"\n}\n\ntest_dns_lists() {\n check_hostname \"$config_lists_hostname\" \"$config_external_ip\"\n}\n\ntest_mx_lists() {\n check_mx \"$config_lists_hostname\" \"$config_relay_hostname\"\n}\n\ntest_dns_relay() {\n check_hostname \"$config_relay_hostname\" \"$config_relay_ip\"\n}\n\ntest_reverse_dns_web() {\n check_reverse_dns \"$config_external_ip\" \"$config_external_hostname\"\n}\n\ntest_reverse_dns_relay() {\n check_reverse_dns \"$config_relay_ip\" \"$config_relay_hostname\"\n}\n\nif [ -n \"$config_external_outgoing_mail_domain\" ]; then\n test_spf_domain() {\n check_spf \"$config_external_hostname\" \"$config_external_outgoing_mail_domain\"\n }\n test_spf_lists() {\n check_spf \"$config_lists_hostname\" \"$config_external_outgoing_mail_domain\"\n }\nfi\n\nif [ \"$1\" = '--doc' ]; then\n check_hostname() {\n echo ' * - A'\n echo \" - $1\"\n echo \" - ${2}\"\n }\n check_mx() {\n echo ' * - MX'\n echo \" - $1\"\n echo \" - ${2}.\"\n }\n check_reverse_dns() {\n echo ' * - PTR'\n echo \" - $1\"\n echo \" - ${2}.\"\n }\n check_spf() {\n echo \" * - TXT (SPF: \\\"v=spf1 ...\\\")\"\n echo \" - $1 \"\n echo \" - include:${2} \"\n }\n header() {\n local aponta=\"${2:-Aponta para}\"\n echo '.. list-table::'\n echo ' :header-rows: 1'\n echo\n echo ' * - Tipo'\n echo ' - Entrada'\n echo \" - $aponta\"\n }\n footer() {\n echo\n }\n (\n header 'DNS(A)'\n test_dns_web\n test_dns_lists\n test_dns_relay\n footer\n\n header 'MX'\n test_mx\n test_mx_lists\n footer\n\n header 'DNS reverso'\n test_reverse_dns_web\n test_reverse_dns_relay\n footer\n\n header 'SPF' 'Deve conter'\n test_spf_domain\n test_spf_lists\n footer\n\n )\nelse\n . shunit2\nfi\n"
},
{
"alpha_fraction": 0.6976456046104431,
"alphanum_fraction": 0.7044609785079956,
"avg_line_length": 25.1729736328125,
"blob_id": "fa192e2c6d21256b2d1e2f439ba089966f04511a",
"content_id": "7894690d1fcc38753049a6955605e7e58fc01359",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 4842,
"license_type": "no_license",
"max_line_length": 176,
"num_lines": 185,
"path": "/cookbooks/noosfero/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "if node['platform'] == 'centos'\n cookbook_file '/etc/yum.repos.d/noosfero.repo' do\n action :delete\n end\nend\n\n# FIXME should not be needed. noosfero should depend on the right version\npackage 'noosfero-deps' do\n action :upgrade\n notifies :restart, 'service[noosfero]'\nend\n\npackage 'noosfero' do\n action [:install, :upgrade]\n notifies :restart, 'service[noosfero]'\nend\n\ntemplate '/etc/noosfero/database.yml' do\n owner 'noosfero'\n group 'noosfero'\n mode '0600'\n notifies :restart, 'service[noosfero]'\nend\n\n# create DB schema\nexecute 'noosfero:schema' do\n command \"RAILS_ENV=production bundle exec rake db:schema:load && RAILS_ENV=production NOOSFERO_DOMAIN=#{node['config']['external_hostname']} bundle exec rake db:data:minimal\"\n cwd '/usr/lib/noosfero'\n user 'noosfero'\n not_if \"psql -h database -U noosfero --no-align --tuples-only -q -c 'select count(*) from profiles'\", :user => 'noosfero'\n notifies :restart, 'service[noosfero]'\nend\n\npackage 'noosfero-spb' do\n action [:install, :upgrade]\n notifies :restart, 'service[noosfero]'\nend\n\nplugins = [\n 'breadcrumbs',\n 'container_block',\n 'display_content',\n 'people_block',\n 'recent_content',\n 'remote_user',\n 'organization_ratings',\n 'statistics',\n 'sub_organizations',\n 'video',\n 'admin_notifications',\n 'community_block',\n]\n\nexecute 'disable all noosfero plugins' do\n command '/usr/lib/noosfero/script/noosfero-plugins disableall'\nend\n\nexecute 'plugins:enable' do\n command '/usr/lib/noosfero/script/noosfero-plugins enable ' + plugins.join(' ')\nend\n\nplugins_spb = [\n 'software_communities',\n 'gov_user',\n 'spb_migrations',\n]\n\n# HACK disable plugins_spb before migrating\n# FIXME fix the plugins to not depend on other pugins\nexecute 'noosfero:plugins_spb:disable' do\n command '/usr/lib/noosfero/script/noosfero-plugins disable ' + plugins_spb.join(' ')\nend\n\nexecute 'noosfero:migrate' do\n command 'RAILS_ENV=production SCHEMA=/dev/null bundle exec rake db:migrate'\n cwd '/usr/lib/noosfero'\n user 'noosfero'\nend\n\n#FIXME: We did it, because we have to enable each plugin and migrate it separately.\nplugins_spb.each do |plugin|\n execute ('plugins_spb:activate:' + plugin) do\n command '/usr/lib/noosfero/script/noosfero-plugins enable ' + plugin\n end\n\n execute ('plugins_spb:migrate:' + plugin) do\n command \"RAILS_ENV=production SCHEMA=/dev/null bundle exec rake db:migrate > /tmp/#{plugin}\"\n cwd '/usr/lib/noosfero'\n user 'noosfero'\n end\nend\n\nexecute 'plugins:activate' do\n command \"RAILS_ENV=production bundle exec rake noosfero:plugins:enable_all\"\n cwd '/usr/lib/noosfero'\n user 'noosfero'\n only_if 'bundle exec rake -P | grep enable_all'\nend\n\nexecute 'theme:enable' do\n command 'psql -h database -U noosfero --no-align --tuples-only -q -c \"update environments set theme=\\'noosfero-spb-theme\\' where id=1;\"'\nend\n\nexecute 'software:create_licenses' do\n cwd '/usr/lib/noosfero'\n command 'sudo -u noosfero bundle exec rake software:create_licenses RAILS_ENV=production'\nend\n\ncookbook_file '/etc/noosfero/unicorn.rb' do\n owner 'root'; group 'root'; mode 0644\n notifies :restart, 'service[noosfero]'\nend\n\ncookbook_file '/etc/noosfero/application.rb' do\n owner 'root'; group 'root'; mode 0644\n notifies :restart, 'service[noosfero]'\nend\n\ncookbook_file '/etc/default/noosfero' do\n owner 'root'; group 'root'; mode 0644\n source 'noosfero-default'\n notifies :restart, 'service[noosfero]'\nend\n\ncookbook_file '/etc/environment' do\n owner 'root'; group 'root'; mode 0644\n source 'environment'\nend\n\npackage 'cronie'\nservice 'crond' do\n action [:enable, :start]\nend\n\nservice 'noosfero' do\n action [:enable, :start]\nend\n\nservice 'memcached' do\n action [:enable, :start]\nend\n\ntemplate '/etc/nginx/conf.d/noosfero.conf' do\n owner 'root'; group 'root'; mode 0644\n source 'nginx.conf.erb'\n notifies :restart, 'service[nginx]'\nend\n\ncookbook_file '/usr/lib/noosfero/config/noosfero.yml' do\n owner 'root'; group 'root'; mode 0644\n source 'noosfero.yml'\n notifies :restart, 'service[noosfero]'\nend\n\ncookbook_file \"/usr/local/bin/noosfero-create-api-user\" do\n mode 0755\nend\n\nexecute 'create-admin-token-noosfero' do\n command [\n \"RAILS_ENV=production bundle exec rails runner\",\n \"/usr/local/bin/noosfero-create-api-user\",\n \"admin-noosfero\", # username\n \"[email protected]\", # email\n ].join(' ')\n cwd '/usr/lib/noosfero'\n user 'noosfero'\nend\n\nexecute 'grant:noosfero:colab' do\n command 'psql -h database -U noosfero -c \"GRANT SELECT ON users TO colab\"'\nend\n\n###############################################\n# SELinux: permission to access static files noosfero\n################################################\n\ncookbook_file '/etc/selinux/local/noosfero.te' do\n notifies :run, 'execute[selinux-noosfero]'\nend\n\nexecute 'selinux-noosfero' do\n command 'selinux-install-module /etc/selinux/local/noosfero.te'\n action :nothing\nend\n"
},
{
"alpha_fraction": 0.7034252285957336,
"alphanum_fraction": 0.7167919874191284,
"avg_line_length": 22.45098114013672,
"blob_id": "7849c19e83fa03c65211af3e5a2b277bf5d6986b",
"content_id": "7f16b1a1e294598ed48cc921471f0397fd3e83e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1197,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 51,
"path": "/cookbooks/mezuro/recipes/prezento.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'mezuro::service'\ninclude_recipe 'mezuro::repo'\n\npackage 'prezento-spb' do\n action :upgrade\nend\n\ntemplate '/etc/mezuro/prezento/database.yml' do\n source 'prezento/database.yml.erb'\n owner 'prezento'\n group 'prezento'\n mode '0600'\n notifies :restart, 'service[prezento.target]'\nend\n\nPREZENTO_DIR='/usr/share/mezuro/prezento'\n\nexecute 'prezento:schema' do\n command 'RAILS_ENV=production bundle exec rake db:schema:load'\n cwd PREZENTO_DIR\n user 'prezento'\nend\n\nexecute 'prezento:migrate' do\n command 'RAILS_ENV=production bundle exec rake db:migrate'\n cwd PREZENTO_DIR\n user 'prezento'\n notifies :restart, 'service[prezento.target]'\nend\n\ntemplate PREZENTO_DIR + '/config/kalibro.yml' do\n source 'prezento/kalibro.yml.erb'\n owner 'prezento'\n group 'prezento'\n mode '0644'\n notifies :restart, 'service[prezento.target]'\nend\n\nexecute 'prezento:open_port' do\n command 'semanage port -a -t http_port_t -p tcp 84'\n user 'root'\n only_if '! semanage port -l | grep \"^\\(http_port_t\\)\\(.\\)\\+\\(\\s84,\\)\"'\nend\n\ntemplate '/etc/nginx/conf.d/prezento.conf' do\n source 'prezento/nginx.conf.erb'\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\nend\n\n"
},
{
"alpha_fraction": 0.6636045575141907,
"alphanum_fraction": 0.6644794344902039,
"avg_line_length": 28.688312530517578,
"blob_id": "4b446d54bb1fade94dc1709c611ae3f512349c0e",
"content_id": "2477989334a2dfd462a3b59bead98d8728ceeda7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2286,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 77,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/database_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::DatabaseHelper < SoftwareCommunitiesPlugin::DynamicTableHelper\n MODEL_NAME =\"database\"\n FIELD_NAME = \"database_description_id\"\n\n def self.valid_database? database\n return false if SoftwareCommunitiesPlugin::SoftwareHelper.all_table_is_empty?(database)\n\n database_description_id_list = SoftwareCommunitiesPlugin::DatabaseDescription.select(:id).\n collect {|dd| dd.id}\n\n return database_description_id_list.include?(\n database[:database_description_id].to_i\n )\n end\n\n def self.list_database new_databases\n return [] if new_databases.nil? or new_databases.length == 0\n list_databases = []\n\n new_databases.each do |new_database|\n if valid_database? new_database\n database = SoftwareCommunitiesPlugin::SoftwareDatabase.new\n\n database.database_description_id =\n new_database[:database_description_id]\n\n database.version = new_database[:version]\n list_databases << database\n end\n end\n\n list_databases\n end\n\n def self.valid_list_database? list_databases\n return false if list_databases.nil? or list_databases.length == 0\n return !list_databases.any?{|database| !database.valid?}\n end\n\n def self.database_as_tables(list_databases, disabled=false)\n model_list = list_databases\n model_list ||= [{:database_description_id => \"\", :version => \"\"}]\n\n models_as_tables model_list, \"database_html_structure\", disabled\n end\n\n def self.database_html_structure(database_data, disabled)\n database_id = database_data[:database_description_id]\n database_name = database_id.blank? ? \"\" : SoftwareCommunitiesPlugin::DatabaseDescription.find(\n database_data[:database_description_id],\n :select=>\"name\"\n ).name\n\n data = {\n model_name: MODEL_NAME,\n field_name: FIELD_NAME,\n name: {\n value: database_name,\n id: database_id,\n hidden: true,\n autocomplete: true,\n select_field: false\n },\n version: {\n value: database_data[:version],\n hidden: true,\n delete: true\n }\n }\n DATA[:license].delete(:value)\n table_html_structure(data, disabled)\n end\n\n def self.add_dynamic_table\n database_as_tables(nil).first.call\n end\nend\n"
},
{
"alpha_fraction": 0.7138888835906982,
"alphanum_fraction": 0.7138888835906982,
"avg_line_length": 23,
"blob_id": "17b0562bb4db3786d20025ce91c0e961f78818b7",
"content_id": "e5203e146ca3d1148d24cc64b49874797f05eda6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 360,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 15,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140617134556_add_references_to_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddReferencesToInstitution < ActiveRecord::Migration\n def up\n change_table :institutions do |t|\n t.references :governmental_power\n t.references :governmental_sphere\n end\n end\n\n def down\n change_table :institutions do |t|\n t.remove_references :governmental_power\n t.remove_references :governmental_sphere\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6719318628311157,
"alphanum_fraction": 0.6745644807815552,
"avg_line_length": 33.53208541870117,
"blob_id": "a00c469735970e3d7db2eca52ac9056c3488caf9",
"content_id": "1ca341ddbc6eb6d1ec2d10ecc0efc9b77057ac60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 12915,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 374,
"path": "/src/noosfero-spb/software_communities/test/functional/software_communities_plugin_myprofile_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require 'test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/software_test_helper'\nrequire(\n File.dirname(__FILE__) +\n '/../../controllers/software_communities_plugin_myprofile_controller'\n)\n\nclass SoftwareCommunitiesPluginMyprofileController; def rescue_action(e) raise e end;\nend\n\nclass SoftwareCommunitiesPluginMyprofileControllerTest < ActionController::TestCase\n include SoftwareTestHelper\n def setup\n @controller = SoftwareCommunitiesPluginMyprofileController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n @person = create_user('person').person\n @offer = create_user('Angela Silva')\n @offer_1 = create_user('Ana de Souza')\n @offer_2 = create_user('Angelo Roberto')\n\n SoftwareCommunitiesPlugin::LicenseInfo.create(\n :version=>\"CC-GPL-V2\",\n :link=>\"http://creativecommons.org/licenses/GPL/2.0/legalcode.pt\"\n )\n\n SoftwareCommunitiesPlugin::ProgrammingLanguage.create(:name =>\"language\")\n SoftwareCommunitiesPlugin::DatabaseDescription.create(:name => \"database\")\n SoftwareCommunitiesPlugin::OperatingSystemName.create(:name=>\"Debian\")\n\n login_as(@person.user_login)\n @environment = Environment.default\n @environment.enable_plugin('SoftwareCommunitiesPlugin')\n @environment.save!\n end\n\n attr_accessor :person, :offer\n\n should 'Add offer to admin in new software' do\n @hash_list = software_fields\n @software = create_software @hash_list\n @software.community.add_admin(@offer.person)\n @software.save\n assert_equal @offer.person.id, @software.community.admins.last.id\n end\n\n should 'create a new software with all fields filled in' do\n fields = software_fields\n @environment.add_admin(@person)\n post(\n :new_software,\n :profile => @person.identifier,\n :community => fields[1],\n :license => fields[0],\n :software_communities_plugin_software_info => fields[2]\n )\n\n new_software = Community.find_by_identifier(\"debian\").software_info\n assert_equal new_software.community.name, \"Debian\"\n end\n\n should 'edit a new software adding basic information' do\n fields_software = software_fields\n fields = software_edit_basic_fields\n\n software = create_software fields_software\n\n software.community.add_admin(@person)\n software.save!\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :license => fields[1],\n :software => fields[0],\n :library => {},\n :operating_system => {},\n :language => {},\n :database => {}\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n assert_equal edited_software.repository_link, \"www.github.com/test\"\n end\n\n should 'edit a new software adding specific information' do\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n software = create_software fields_software\n\n software.community.add_admin(@person)\n software.save!\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :library => fields[0],\n :language => fields[1],\n :database => fields[2],\n :operating_system => fields[3],\n :software => fields[4],\n :license => fields[5]\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n assert_equal edited_software.acronym, \"test\"\n end\n\n should 'non admin cant edit a new software' do\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n software = create_software fields_software\n\n software.community.add_admin(@person)\n software.save!\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :library => fields[0],\n :language => fields[1],\n :database => fields[2],\n :operating_system => fields[3],\n :software => fields[4],\n :license => fields[5]\n )\n\n assert_response 302\n end\n\n should 'edit a software and does not change Another License values' do\n another_license = SoftwareCommunitiesPlugin::LicenseInfo.create(:version => \"Another\", :link => \"#\")\n software = create_software(software_fields)\n software.community.add_admin(@person)\n software.save!\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :license => { \"license_infos_id\"=>another_license.id, \"version\"=>\"Another Version\", \"link\"=>\"www.link.com\" },\n :software => {},\n :library => {},\n :operating_system => {},\n :language => {},\n :database => {}\n )\n\n another_license.reload\n edited_software = Community.find_by_identifier(\"debian\").software_info\n\n assert_equal edited_software.another_license_version, \"Another Version\"\n assert_equal edited_software.another_license_link, \"www.link.com\"\n assert_equal another_license.version, \"Another\"\n assert_equal another_license.link, \"#\"\n end\n\n should 'only admin upgrade a generic software to a public software' do\n admin_person = create_user('admin').person\n @environment.add_admin(admin_person)\n\n login_as(admin_person.user_login)\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n fields[4]['public_software'] = true\n software = create_software fields_software\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :operating_system => fields[3],\n :software => fields[4],\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id}\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n assert edited_software.public_software?\n end\n\n should 'not upgrade a generic software to a public software if user is not an admin' do\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n fields[4]['public_software'] = true\n software = create_software fields_software\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :software => fields[4]\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n refute edited_software.public_software?\n end\n\n [\"e_ping\",\"e_mag\",\"icp_brasil\",\"e_arq\",\"intern\"].map do |attr|\n define_method \"test_should_#{attr}_not_be_changed_by_not_admin\" do\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n fields[4][attr]=true\n\n software = create_software fields_software\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :software => fields[4]\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n refute edited_software.send(attr)\n end\n end\n\n [\"e_ping\",\"e_mag\",\"icp_brasil\",\"e_arq\",\"intern\"].map do |attr|\n define_method \"test_should_#{attr}_be_changed_by_admin\" do\n admin_person = create_user('admin').person\n @environment.add_admin(admin_person)\n login_as(admin_person.user_login)\n\n fields_software = software_fields\n fields = software_edit_specific_fields\n\n fields[4][attr]=true\n\n software = create_software fields_software\n\n post(\n :edit_software,\n :profile => software.community.identifier,\n :software => fields[4],\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id}\n )\n\n edited_software = Community.find_by_identifier(\"debian\").software_info\n assert edited_software.send(attr)\n end\n end\n\n should \"create software_info with existing license_info\" do\n @environment.add_admin(@person)\n\n post(\n :new_software,\n :community => {:name =>\"New Software\", :identifier => \"new-software\"},\n :software_communities_plugin_software_info => {:finality => \"something\", :repository_link => \"\"},\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id},\n :profile => @person.identifier\n )\n\n new_software = Community.find_by_identifier(\"new-software\").software_info\n assert_equal new_software.license_info, SoftwareCommunitiesPlugin::LicenseInfo.last\n end\n\n should \"create software_info with 'Another' license_info\" do\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.create(:version => \"Another\", :link => \"#\")\n @environment.add_admin(@person)\n\n another_license_version = \"Different License\"\n another_license_link = \"http://diferent.link\"\n\n post(\n :new_software,\n :community => { :name => \"New Software\", :identifier => \"new-software\" },\n :software_communities_plugin_software_info => { :finality => \"something\", :repository_link => \"\" },\n :license => { :license_infos_id => license_another.id,\n :version => another_license_version,\n :link=> another_license_link\n },\n :profile => @person.identifier\n )\n\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info_id, license_another.id\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.id, nil\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.version, another_license_version\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.link, another_license_link\n end\n\n should \"create software_info after finish task with 'Another' license_info\" do\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.create(:version => \"Another\", :link => \"#\")\n\n another_license_version = \"Different License\"\n another_license_link = \"http://diferent.link\"\n\n post(\n :new_software,\n :community => { :name => \"New Software\", :identifier => \"new-software\" },\n :software_communities_plugin_software_info => { :finality => \"something\", :repository_link => \"\" },\n :license => { :license_infos_id => license_another.id,\n :version => another_license_version,\n :link=> another_license_link\n },\n :profile => @person.identifier\n )\n\n @environment.add_admin(@person)\n Task.last.send('finish', @person)\n\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info_id, license_another.id\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.id, nil\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.version, another_license_version\n assert_equal SoftwareCommunitiesPlugin::SoftwareInfo.last.license_info.link, another_license_link\n end\n\n should \"show error messages on create software_info\" do\n post(\n :new_software,\n :community => {},\n :software_communities_plugin_software_info => {},\n :license => {},\n :profile => @person.identifier\n )\n assert_includes @response.body, \"Domain can't be blank\"\n assert_includes @response.body, \"Name can't be blank\"\n assert_includes @response.body, \"Finality can't be blank\"\n assert_includes @response.body, \"Version can't be blank\"\n end\n\n should \"show domain not available error\" do\n @environment.add_admin(@person)\n\n post(\n :new_software,\n :community => {:name =>\"New Software\", :identifier => \"new-software\"},\n :software_communities_plugin_software_info => {:finality => \"something\", :repository_link => \"\"},\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id},\n :profile => @person.identifier\n )\n post(\n :new_software,\n :community => {:name =>\"New Software\", :identifier => \"new-software\"},\n :software_communities_plugin_software_info => {:finality => \"something\", :repository_link => \"\"},\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id},\n :profile => @person.identifier\n )\n\n assert_includes @response.body, \"Domain is not available\"\n end\n\n should \"create software with admin moderation\" do\n @environment.enable('admin_must_approve_new_communities')\n\n post(\n :new_software,\n :community => {:name =>\"New Software\", :identifier => \"new-software\"},\n :software_communities_plugin_software_info => {:finality => \"something\", :repository_link => \"\"},\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id},\n :profile => @person.identifier\n )\n\n @environment.add_admin(@person)\n Task.last.send('finish', @person)\n\n new_software = Community.find_by_identifier(\"new-software\").software_info\n assert_equal \"New Software\", Task.last.data[:name]\n assert_equal \"New Software\", new_software.community.name\n end\n\n should \"dont create software without accept task\" do\n assert_no_difference 'SoftwareCommunitiesPlugin::SoftwareInfo.count' do\n post(\n :new_software,\n :community => {:name =>\"New Software\", :identifier => \"new-software\"},\n :software_communities_plugin_software_info => {:finality => \"something\", :repository_link => \"\"},\n :license =>{:license_infos_id => SoftwareCommunitiesPlugin::LicenseInfo.last.id},\n :profile => @person.identifier\n )\n end\n end\nend\n"
},
{
"alpha_fraction": 0.4736842215061188,
"alphanum_fraction": 0.5,
"avg_line_length": 8.5,
"blob_id": "2db505f48873a458fe55496bc82f41c4a6b3a363",
"content_id": "1786ac0386b15ace11b9178d1b158b676290c119",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 76,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 8,
"path": "/test/bin/send-email",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nfrom=\"$1\"\nto=\"$2\"\n\ndate | mail -r \"$from\" -s test \"$to\"\n"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 35.75,
"blob_id": "1ef685af537c941470f50a3debde10ac259e746b",
"content_id": "9e49a703c7cbf108c6d97e0d21fdf63a970b0b30",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 294,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 8,
"path": "/src/noosfero-spb/gov_user/lib/public_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class PublicInstitution < Institution\n validates :governmental_power, :governmental_sphere, :juridical_nature,\n :presence=>true, :unless=>lambda{self.community.country != \"BR\"}\n\n validates :cnpj,\n :format => {with: CNPJ_FORMAT},\n :unless => 'cnpj.blank?'\nend\n"
},
{
"alpha_fraction": 0.8264462947845459,
"alphanum_fraction": 0.8264462947845459,
"avg_line_length": 23.200000762939453,
"blob_id": "abf2b309f5df4e28267136506a2f66ef2ee5627a",
"content_id": "cedb7cae4d3144d478e86c3a572ebc19797fd37a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 121,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 5,
"path": "/src/noosfero-spb/software_communities/lib/ext/organization_rating.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency \"organization_rating\"\n\nclass OrganizationRating\n attr_accessible :people_benefited, :saved_value\nend\n"
},
{
"alpha_fraction": 0.65625,
"alphanum_fraction": 0.6875,
"avg_line_length": 20.33333396911621,
"blob_id": "3310c0f8f817f500f735d7b3a202679444463bfe",
"content_id": "42d1ba0817da4b90760ff4a3179894b0f75a44a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 128,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 6,
"path": "/cookbooks/colab/recipes/nginx.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "template '/etc/nginx/conf.d/colab.conf' do\n owner 'root'\n group 'root'\n mode 0644\n notifies :restart, 'service[nginx]'\nend\n"
},
{
"alpha_fraction": 0.7153729200363159,
"alphanum_fraction": 0.719939112663269,
"avg_line_length": 35.5,
"blob_id": "1376cddb0eaa91d51f8b3945d945cee1a7fd5418",
"content_id": "6056dcdc4782c36ec63eca109de967f249048ce4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1314,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 36,
"path": "/test/colab_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_database_connectivity() {\n assertTrue 'colab database connectivity' 'run_on integration psql -h database -U colab < /dev/null'\n}\n\ntest_colab_config_is_in_place() {\n assertTrue 'colab settings.py is in place' 'run_on integration test -f /etc/colab/settings.py'\n}\n\ntest_colab_running() {\n assertTrue 'colab service running' 'run_on integration pgrep -fa colab.wsgi'\n}\n\ntest_colab_responds() {\n assertTrue 'colab responds' \"run_on integration curl-host 'softwarepublico.dev' http://localhost:8001\"\n}\n\ntest_nginx_responds() {\n assertTrue 'nginx reponds' \"run_on integration curl-host 'softwarepublico.dev' http://localhost\"\n}\n\ntest_nginx_virtualhost() {\n local title=\"$(curl --header 'Host: softwarepublico.dev' https://$config_external_hostname/dashboard | grep '<title>' | sed -e 's/^\\s*//')\"\n assertEquals \"<title>Home - Colab</title>\" \"$title\"\n}\n\ntest_reverse_proxy_gitlab() {\n assertTrue 'Reverse proxy for gitlab' \"curl --header 'Host: softwarepublico.dev' https://$config_external_hostname/gitlab/public/projects | grep -i '<meta.*gitlab.*>'\"\n}\n\ntest_reverse_proxy_noosfero() {\n assertTrue 'Reverse proxy for noosfero' \"curl --header 'Host: softwarepublico.dev' https://$config_external_hostname/social/search/people | grep -i '<meta.*noosfero.*>'\"\n}\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.6608876585960388,
"alphanum_fraction": 0.6775311827659607,
"avg_line_length": 25.218181610107422,
"blob_id": "6ce2213acbeb8d1ba3ca44d953aa8ff29d056fb5",
"content_id": "08e2bc65276a288066f459ce3d7bd676cbe1c03f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1442,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 55,
"path": "/cookbooks/email/recipes/relay.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'email'\n\n# smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem\n# smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key\n\npostfix_config = {\n\n myhostname: node['config']['relay_hostname'],\n\n relay_domains: [\n node['config']['lists_hostname'],\n node['config']['external_hostname'],\n ].join(', '),\n\n transport_maps: 'hash:/etc/postfix/transport',\n\n mynetworks: '127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 ' + node['peers'].values.sort.join(' '),\n\n}\n\nexecute 'postfix:relay:config' do\n command postfix_config.map { |k,v| \"postconf #{k}='#{v}'\" }.join(' ; ')\n notifies :reload, 'service[postfix]'\nend\n\nexecute 'postfix:interfaces:all' do\n command \"postconf inet_interfaces=all\"\n notifies :restart, 'service[postfix]'\n only_if { `postconf -h inet_interfaces`.strip != 'all' }\nend\n\ntransport = {\n node['config']['lists_hostname'] => node['peers']['integration'],\n node['config']['external_hostname'] => node['peers']['integration'],\n}\n\nfile '/etc/postfix/transport' do\n owner 'root'\n group 'root'\n mode 0644\n content transport.map { |domain,ip| \"#{domain}\\tsmtp:[#{ip}]\\n\" }.join\n notifies :run, 'execute[transport:postmap]'\nend\n\nexecute 'transport:postmap' do\n command \"postmap /etc/postfix/transport\"\n action :nothing\nend\n\nexternal_relay = node['config']['external_outgoing_mail_relay']\nif external_relay\n execute \"postconf relayhost=#{external_relay}\"\nelse\n execute 'postconf -X relayhost'\nend\n"
},
{
"alpha_fraction": 0.6514936089515686,
"alphanum_fraction": 0.6607396602630615,
"avg_line_length": 26.30097007751465,
"blob_id": "e596763360779940ee8d11fe8a00167d043685b5",
"content_id": "fc12cfffdb42e9ed1a0731dddd1a54a17d760919",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2812,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 103,
"path": "/cookbooks/mailman/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'mailman'\n\ntemplate '/etc/mailman/mm_cfg.py' do\n owner 'root'\n group 'mailman'\n mode 0644\n notifies :restart, 'service[mailman]'\nend\n\nexecute 'create-meta-list' do\n admin = node['config']['lists_admin']\n password = SecureRandom.random_number.to_s\n\n command \"sudo -u mailman /usr/lib/mailman/bin/newlist --quiet mailman #{admin} $(openssl rand -hex 6)\"\n\n not_if { File.exists?('/var/lib/mailman/lists/mailman') }\n notifies :restart, 'service[mailman]'\nend\n\nservice 'mailman' do\n action :enable\n supports :restart => true\nend\n\nexecute 'postfix:config' do\n command [\n \"postconf relay_domains=#{node['config']['lists_hostname']}\",\n \"postconf transport_maps=hash:/etc/postfix/transport\",\n ].join(' && ')\n notifies :reload, 'service[postfix]'\nend\n\nexecute 'postfix:interfaces' do\n command \"postconf inet_interfaces=\\\"$(cat /etc/hostname), localhost\\\"\"\n only_if { `postconf -h inet_interfaces`.strip == 'localhost' }\n notifies :restart, 'service[postfix]'\nend\n\nfile '/etc/postfix/transport' do\n owner 'root'\n group 'root'\n mode 0644\n content \"#{node['config']['lists_hostname']} mailman:\\n\"\n notifies :run, 'execute[compile-postfix-transport]'\nend\n\nexecute 'compile-postfix-transport' do\n command 'postmap /etc/postfix/transport'\n action :nothing\nend\n\n# FIXME remove this after 2015-05-01\nfile '/etc/postfix/postfix-to-mailman-centos.py' do\n action :delete\nend\n\n# Add mailman group to nginx user\nexecute 'nginx-mailman-group' do\n command \"usermod -a -G mailman nginx\"\nend\n\ncookbook_file '/usr/lib/mailman/bin/postfix-to-mailman.py' do\n owner 'root'\n group 'root'\n mode 0755\nend\n\n#######################################################################\n# SELinux: allow Postfix pipe process to write to Mailman data\n#######################################################################\ncookbook_file '/etc/selinux/local/spb_postfix_mailman.te' do\n notifies :run, 'execute[selinux-postfix-mailman]'\nend\nexecute 'selinux-postfix-mailman' do\n command 'selinux-install-module /etc/selinux/local/spb_postfix_mailman.te'\n action :nothing\nend\n#######################################################################\n\ncookbook_file '/etc/cron.d/mailman-spb' do\n owner 'root'\n group 'root'\n mode 0644\nend\n\nexecute 'postfix:disable-send-emails' do\n command \"postconf 'default_transport = fs_mail'\"\n only_if { node['config']['disable_send_emails'] }\nend\n\nexecute 'postfix:enable-send-emails' do\n command \"postconf 'default_transport = smtp'\"\n not_if { node['config']['disable_send_emails'] }\nend\n\ncookbook_file '/etc/postfix/master.cf' do\n notifies :reload, 'service[postfix]'\nend\n\nexecute 'set-mailman-default-list' do\n command \"printf 'mlist.archive = False\\nmlist.archive_private = 1' > /tmp/set_mailman_list && \\\n sudo /usr/lib/mailman/bin/config_list -i /tmp/set_mailman_list mailman\"\nend\n"
},
{
"alpha_fraction": 0.7047738432884216,
"alphanum_fraction": 0.7167085409164429,
"avg_line_length": 20.513513565063477,
"blob_id": "412dd8db55580eff13cbe12fb2b0dda3fc2ae487",
"content_id": "7d0570c67ba3e2a6a528adee3fe62fe2cb18b512",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1592,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 74,
"path": "/cookbooks/loganalyzer/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "LOGANALYZER_TAR='loganalyzer-3.6.5.tar.gz'\nLOGANALYZER_TAR_PATH='/tmp/'+LOGANALYZER_TAR\nLOGANALYZER_SRC='/usr/share/nginx/html/loganalyzer'\n\npackage 'php'\npackage 'php-fpm'\npackage 'php-mysql'\npackage 'mariadb-server'\npackage 'nginx'\npackage 'rsyslog-mysql'\n\nservice 'nginx'\nservice 'php-fpm' do\n action [:enable, :start]\nend\n\nservice 'mariadb' do\n action [:enable,:start]\nend\n\ncookbook_file '/tmp/mysql-createDB.sql' do\n mode '644'\nend\n\ncookbook_file '/tmp/rsyslog-createUser.sql' do\n mode '644'\nend\n\nexecute 'createdb:rsyslog' do\n command 'mysql -u root --password= < /tmp/mysql-createDB.sql'\nend\n\nexecute 'createuser:rsyslog' do\n command 'mysql -u root --password= Syslog < /tmp/rsyslog-createUser.sql'\nend\n\ntemplate '/etc/nginx/conf.d/loganalyzer.conf' do\n source 'nginx.conf.erb'\n notifies :reload, 'service[nginx]'\n notifies :reload, 'service[php-fpm]'\nend\n\nexecute 'getting-loganalizer' do\n command 'wget http://download.adiscon.com/loganalyzer/loganalyzer-3.6.5.tar.gz'\n cwd '/tmp'\nend\n\nexecute 'tar-extraction' do\n command 'tar zxvf ' + LOGANALYZER_TAR\n cwd '/tmp'\n user 'root'\nend\n\nexecute 'cp-loganalyzer-files' do\n command 'cp -r -n loganalyzer-3.6.5/src/ ' + LOGANALYZER_SRC\n cwd '/tmp'\n user 'root'\nend\n\nfile LOGANALYZER_SRC+'/config.php' do\n owner 'root'\n group 'root'\n mode '0666'\nend\n\nexecute 'allowing-config-permission' do\n command 'semanage fcontext -a -t httpd_sys_rw_content_t ' + LOGANALYZER_SRC + '/config.php'\n user 'root'\nend\n\nexecute 'enable-config-permission' do\n command 'restorecon -v ' + LOGANALYZER_SRC + '/config.php'\n user 'root'\nend\n"
},
{
"alpha_fraction": 0.6808510422706604,
"alphanum_fraction": 0.6914893388748169,
"avg_line_length": 14.583333015441895,
"blob_id": "63fb9f434b26b3b8c9940bef3bffc953a437a8aa",
"content_id": "f30ca96f6432a0d29becac81f040723503110318",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 188,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 12,
"path": "/test/bin/wait-for-messages",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nlistname=\"$1\"\n\nmbox=/var/lib/mailman/archives/private/$listname.mbox/$listname.mbox\nif wait-for-file $mbox; then\n sudo grep -i -c ^Message-ID: $mbox\nelse\n echo 0\nfi\n\n"
},
{
"alpha_fraction": 0.6763896346092224,
"alphanum_fraction": 0.6940010786056519,
"avg_line_length": 20.2890625,
"blob_id": "e5c8e6eb4e0b7d2c53263b39789772cc90740006",
"content_id": "d8de36321a3f5509e7c4bd7122baa3ec706929d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 5451,
"license_type": "no_license",
"max_line_length": 182,
"num_lines": 256,
"path": "/cookbooks/colab/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "\npackage 'memcached'\n\nservice 'memcached' do\n action [:enable, :start]\nend\n\nif node['platform'] == 'centos'\n cookbook_file '/etc/yum.repos.d/colab.repo' do\n action :delete\n end\nend\n\n# remove link left behind by old colab packages\nfile '/usr/share/nginx/colab' do\n action :delete\nend\n\npackage 'colab' do\n action :upgrade\n notifies :restart, 'service[colab]'\nend\n\npackage 'colab-spb-theme' do\n action :upgrade\n notifies :restart, 'service[colab]'\nend\n\npackage 'colab-spb-plugin' do\n action :upgrade\n notifies :restart, 'service[colab]'\nend\n\ndirectory '/etc/colab' do\n owner 'root'\n group 'root'\n mode 0755\nend\n\ndirectory '/var/log/colab' do\n owner 'colab'\n group 'colab'\n mode 0755\nend\n\ndirectory '/var/lock/colab' do\n owner 'colab'\n group 'colab'\n mode 0755\nend\n\nexecute 'secret-key' do\n f = '/etc/colab/secret.key'\n command \"openssl rand -hex 32 -out #{f} && chown root:colab #{f} && chmod 0640 #{f}\"\n not_if { File.exists?(f) }\n notifies :create, 'template[/etc/colab/settings.d/00-custom_settings.py]'\nend\n\ntemplate '/etc/colab/gunicorn.py' do\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/settings.d/00-custom_settings.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/settings.d/01-database.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\n# Creating a gitlab admin user\ntemplate '/tmp/admin-gitlab.json' do\n\n password = SecureRandom.random_number.to_s\n\n variables(\n :password => password\n )\nend\n\nexecute 'create-admin-token-gitlab' do\n user = \"admin-gitlab\"\n email = \"[email protected]\"\n password = SecureRandom.random_number.to_s\n\n command \"RAILS_ENV=production bundle exec rails runner \\\"User.create(name: \\'#{user}\\', username: \\'#{user}\\', email: \\'#{email}\\', password: \\'#{password}\\', admin: \\'true\\')\\\"\"\n\n user_exist = lambda do\n Dir.chdir '/usr/lib/gitlab' do\n `RAILS_ENV=production bundle exec rails runner \\\"puts User.find_by_name(\\'admin-gitlab\\').nil?\\\"`.strip\n end\n end\n\n not_if {user_exist.call == \"false\"}\n\n cwd '/usr/lib/gitlab'\n user 'git'\nend\n\n# Adding settings.d files\ntemplate '/etc/colab/settings.d/02-logging.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/settings.d/04-memcached.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/settings.d/05-celery.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/settings.d/06-raven-settings.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\n only_if { node['config']['raven_dsn'] }\nend\n\n# Adding plugins for colab\ntemplate '/etc/colab/plugins.d/gitlab.py' do\n owner 'root'\n group 'colab'\n mode 0640\n get_private_token = lambda do\n Dir.chdir '/usr/lib/gitlab' do\n `sudo -u git RAILS_ENV=production bundle exec rails runner \\\"puts User.find_by_name(\\'admin-gitlab\\').private_token\\\"`.strip\n end\n end\n\n variables(\n :get_private_token => get_private_token\n )\n\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/plugins.d/noosfero.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\n get_private_token = lambda do\n `psql --tuples-only --host database --user colab -c \"select private_token from users where login = 'admin-noosfero'\" noosfero`.strip\n end\n variables(:get_private_token => get_private_token)\nend\n\ntemplate '/etc/colab/plugins.d/spb.py' do\n owner 'root'\n group 'colab'\n mode 0640\n notifies :restart, 'service[colab]'\nend\n\ntemplate '/etc/colab/plugins.d/mezuro.py' do\n owner 'root'\n group 'colab'\n mode 0640\n action :delete\n notifies :restart, 'service[colab]'\nend\n\nfile '/etc/colab/plugins.d/sentry_client.py' do\n action :delete\nend\n\nexecute 'colab-admin migrate'\n\n# Adding widgets for colab\ncookbook_file '/etc/colab/widgets.d/dashboard.py' do\n owner 'root'\n group 'colab'\n mode 0640\n\n notifies :restart, 'service[colab]'\nend\n\ncookbook_file '/etc/colab/widgets.d/profile.py' do\n owner 'root'\n group 'colab'\n mode 0640\n\n notifies :restart, 'service[colab]'\nend\n\ncookbook_file '/etc/colab/widgets.d/gitlab_profile.py' do\n owner 'root'\n group 'colab'\n mode 0640\n\n notifies :restart, 'service[colab]'\nend\n\ncookbook_file '/etc/colab/widgets.d/noosfero_profile.py' do\n owner 'root'\n group 'colab'\n mode 0640\n\n notifies :restart, 'service[colab]'\nend\n\n# Static files\ndirectory '/var/lib/colab/assets/spb/' do\n owner 'root'\n group 'root'\n mode 0755\nend\n\ncookbook_file '/var/lib/colab/assets/spb/fav.ico' do\n owner 'root'\n group 'root'\n mode 0644\nend\n\n# Add mailman group to colab user\nexecute 'colab-mailman-group' do\n command \"usermod -a -G mailman colab\"\nend\n\n# Collect static is here instead of colab.spec because\n# plugins might provide their own static files, as\n# the package don't know about installed plugins\n# collectstatic needs to run after package install\n# and plugins instantiated. Same for migrate.\nexecute 'colab-admin migrate'\nexecute 'colab-admin:collectstatic' do\n command 'colab-admin collectstatic --noinput'\nend\n\nservice 'colab' do\n action [:enable, :start]\n supports :restart => true\nend\n\nexecute 'create-admin-token-colab' do\n command \"colab-admin loaddata admin-gitlab.json\"\n\n cwd '/tmp'\n user 'root'\nend\n"
},
{
"alpha_fraction": 0.7123287916183472,
"alphanum_fraction": 0.7123287916183472,
"avg_line_length": 18.46666717529297,
"blob_id": "5cbae153394a25138e2e7a35c4ffbf911b72f821",
"content_id": "1bb17f8fbe3373df98ce2c8faee515c2e0e60aa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 292,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 15,
"path": "/src/noosfero-spb/gov_user/lib/juridical_nature.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class JuridicalNature < ActiveRecord::Base\n attr_accessible :name\n\n has_many :institutions\n\n validates_presence_of :name\n validates_uniqueness_of :name\n\n def public_institutions\n Institution.where(\n :type=>\"PublicInstitution\",\n :juridical_nature_id=>self.id\n )\n end\nend\n"
},
{
"alpha_fraction": 0.6216450333595276,
"alphanum_fraction": 0.6311688423156738,
"avg_line_length": 18.559322357177734,
"blob_id": "d0269ca1f700265dd29709222eb724dae215562d",
"content_id": "780653778730057cf9fdb09691f85ffff4a567fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1155,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 59,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20151002175358_change_all_blocks_position_in_area_2.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class ChangeAllBlocksPositionInArea2 < ActiveRecord::Migration\n def up\n software_template = Community['software']\n print \".\"\n\n if software_template\n software_area_two = software_template.boxes.find_by_position 2\n print \".\"\n\n change_blocks_position software_area_two.blocks if software_area_two\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_two = software_community.boxes.find_by_position 2\n print \".\"\n\n change_blocks_position software_area_two.blocks if software_area_two\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\n\n private\n\n def change_blocks_position blocks\n blocks.each do |block|\n block.position = get_block_position(block)\n block.save!\n print \".\"\n end\n end\n\n def get_block_position block\n case block.type\n when \"CommunityBlock\"\n 1\n when \"StatisticBlock\"\n 2\n when \"RepositoryBlock\"\n 4\n when \"WikiBlock\"\n 5\n when \"MembersBlock\"\n 7\n when \"LinkListBlock\"\n if block.title == \"Ajuda\"\n 3\n else\n 6\n end\n else\n 8\n end\n end\nend\n\n"
},
{
"alpha_fraction": 0.746081531047821,
"alphanum_fraction": 0.746081531047821,
"avg_line_length": 46.79999923706055,
"blob_id": "8c9fcb2a4e4694a2074b469fae0550761b02c812",
"content_id": "ec0b954032fdb688d7cfa2710b8415122086fc8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 957,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 20,
"path": "/cookbooks/colab/files/default/dashboard.py",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "from colab.widgets.widget_manager import WidgetManager\n\nfrom colab.super_archives.widgets.dashboard_latest_collaborations import \\\n DashboardLatestCollaborationsWidget\nfrom colab.super_archives.widgets.dashboard_most_relevant_threads import \\\n DashboardMostRelevantThreadsWidget\nfrom colab.super_archives.widgets.dashboard_latest_threads import \\\n DashboardLatestThreadsWidget\nfrom colab.super_archives.widgets.dashboard_collaboration_graph import \\\n DashboardCollaborationGraphWidget\n\n# Dashboard Widgets\nWidgetManager.register_widget('dashboard',\n DashboardLatestCollaborationsWidget())\nWidgetManager.register_widget('dashboard',\n DashboardCollaborationGraphWidget())\nWidgetManager.register_widget('dashboard',\n DashboardMostRelevantThreadsWidget())\nWidgetManager.register_widget('dashboard',\n DashboardLatestThreadsWidget())\n\n"
},
{
"alpha_fraction": 0.6482617855072021,
"alphanum_fraction": 0.6564416885375977,
"avg_line_length": 31.600000381469727,
"blob_id": "36aaf7cbfd8bd3a9415beb507b3db27415e32e83",
"content_id": "d566f194057b718be461feae5e9222479b4bb7a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 489,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 15,
"path": "/src/noosfero-spb/software_communities/lib/macros/allow_variables.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::AllowVariables < Noosfero::Plugin::Macro\n def self.configuration\n { :params => [],\n :skip_dialog => true,\n :title => _(\"Insert Profile\"),\n :generator => 'insertProfile();',\n :js_files => 'allow_variables.js',\n :icon_path => '/designs/icons/tango/Tango/16x16/actions/document-properties.png'\n }\n end\n\n def parse(params, inner_html, source)\n URI.unescape(inner_html).gsub(/{profile}/,source.profile.identifier)\n end\nend\n"
},
{
"alpha_fraction": 0.6189554929733276,
"alphanum_fraction": 0.6189554929733276,
"avg_line_length": 38.769229888916016,
"blob_id": "0aa6159e8debede1e3c5ba26959665529822458c",
"content_id": "8a319949d7aa0065e0c0cbc9f47075b51e02b245",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 517,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 13,
"path": "/src/noosfero-spb/gov_user/lib/gov_user_plugin/api_entities.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module Entities\n class Institution < Noosfero::API::Entity\n root 'institutions', 'institution'\n expose :name, :acronym, :unit_code, :parent_code, :unit_type,\n :sub_juridical_nature, :normalization_level,\n :version, :cnpj, :type, :governmental_power_id,\n :governmental_sphere_id, :sisp, :juridical_nature_id,\n :corporate_name, :siorg_code, :id\n expose :community_id do |institution,options|\n institution.community.id\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7465116381645203,
"alphanum_fraction": 0.7465116381645203,
"avg_line_length": 46.77777862548828,
"blob_id": "4eef243fb470f15234a943c6f01d3ff8909fccd8",
"content_id": "73780777c474eedb7875d9e580e22cfa6dd46cf7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 430,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 9,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/license_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "module SoftwareCommunitiesPlugin::LicenseHelper\n def self.find_licenses query\n licenses = SoftwareCommunitiesPlugin::LicenseInfo.where(\"version ILIKE ?\", \"%#{query}%\").select(\"id, version\")\n licenses = licenses.reject { |license| license.version == \"Another\" }\n license_another = SoftwareCommunitiesPlugin::LicenseInfo.find_by_version(\"Another\")\n licenses << license_another if license_another\n licenses\n end\nend\n"
},
{
"alpha_fraction": 0.6231101751327515,
"alphanum_fraction": 0.6252699494361877,
"avg_line_length": 26.235294342041016,
"blob_id": "ffd4e947177a0db622528947ee4be100729120a0",
"content_id": "664626c5023a9e77ce53e9801751e82cadc789c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 926,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 34,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150720180509_software_release_date.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareReleaseDate < ActiveRecord::Migration\n def up\n softwares = SoftwareCommunitiesPlugin::SoftwareInfo.all\n softwares.each do |software|\n if software.community\n name = software.community.name.strip\n software.community.name = name\n software.community.save\n else\n software.destroy\n end\n end\n\n file = File.new(\"plugins/spb_migrations/files/date-communities.txt\", \"r\")\n while (line = file.gets)\n result = line.split('|')\n software_name = result[2].gsub(\"/n\", \"\")\n software = Community.find(:first, :conditions => [\"lower(name) = ?\", software_name.strip.downcase])\n software.created_at = Time.zone.parse(result[1]) if software\n if software && software.save\n print \".\"\n else\n print \"F\"\n puts software_name\n end\n end\n file.close\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.5454545617103577,
"alphanum_fraction": 0.5871211886405945,
"avg_line_length": 14.529411315917969,
"blob_id": "8c040b2a925ae24ad50b459b8ba5f414df3433be",
"content_id": "b4ab450656b099a5c68733b46a86c05c3081375c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 264,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 17,
"path": "/test/bin/wait-for-file",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nfile=\"$1\"\n\ntotal=0\nwhile [ \"$total\" -lt 10 ]; do\n if sudo test -f \"$file\"; then\n exit 0\n fi\n sleep 1\n total=$(($total + 1))\ndone\necho \"E: $file not found! Other files in the same directory:\" >&2\nsudo ls -1d $(dirname $file)/* >&2\nexit 1\n"
},
{
"alpha_fraction": 0.6354529857635498,
"alphanum_fraction": 0.6515679359436035,
"avg_line_length": 28.063291549682617,
"blob_id": "bc8f35a33288bb070b37442b133b4bade4c152c1",
"content_id": "bbaca778de542e3daa2a6811cde3924dcc63a352",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2296,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 79,
"path": "/src/noosfero-spb/gov_user/test/unit/public_institution_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass PublicInstitutionTest < ActiveSupport::TestCase\n include PluginTestHelper\n def setup\n @gov_power = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n\n @institution = create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"11.222.333/4444-55\"\n )\n end\n\n def teardown\n GovernmentalPower.destroy_all\n GovernmentalSphere.destroy_all\n JuridicalNature.destroy_all\n Institution.destroy_all\n @gov_power = nil\n @gov_sphere = nil\n @juridical_nature = nil\n @institution = nil\n end\n\n should \"save without a cnpj\" do\n @institution.cnpj = nil\n assert @institution.save\n end\n\n should \"save institution without an acronym\" do\n @institution.acronym = nil\n assert @institution.save\n end\n\n should \"Not save institution without a governmental_power\" do\n invalid_msg = \"Governmental power can't be blank\"\n @institution.governmental_power = nil\n\n assert [email protected]\n assert @institution.errors.full_messages.include? invalid_msg\n end\n\n should \"Not save institution without a governmental_sphere\" do\n invalid_msg = \"Governmental sphere can't be blank\"\n @institution.governmental_sphere = nil\n\n assert [email protected]\n assert @institution.errors.full_messages.include? invalid_msg\n end\n\n should \"not save institution without juridical nature\" do\n invalid_msg = \"Juridical nature can't be blank\"\n @institution.juridical_nature = nil\n\n assert [email protected]\n assert @institution.errors.full_messages.include? invalid_msg\n end\n\n\n should \"verify cnpj format if it is filled\" do\n @institution.cnpj = \"123456789\"\n\n assert_equal false, @institution.save\n\n @institution.cnpj = \"11.222.333/4444-55\"\n\n assert_equal true, @institution.save\n end\nend\n"
},
{
"alpha_fraction": 0.6699081659317017,
"alphanum_fraction": 0.6699081659317017,
"avg_line_length": 26.62686538696289,
"blob_id": "b5359410d3b93d6723e9c6353778c991ee6c620d",
"content_id": "5cad1614a24510ea992cabee73326c4bf0c8d32c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1851,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 67,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/download_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::DownloadBlock < Block\n\n attr_accessible :show_name, :downloads\n\n has_many :download_records, :class_name => 'Download', :dependent => :destroy\n\n settings_items :show_name, :type => :boolean, :default => false\n settings_items :downloads, :type => Array, :default => []\n\n after_save :update_downloads\n\n def update_downloads\n self.downloads = self.downloads.select{|download| !download.all?{|k, v| v.blank?}}\n\n params_download_ids = self.downloads.select{|download| !download[:id].blank?}.collect{|download| download[:id].to_i}\n removed_download_ids = self.download_record_ids - params_download_ids\n SoftwareCommunitiesPlugin::Download.where(:id => removed_download_ids).destroy_all\n\n self.downloads.each do |download_hash|\n download_record = SoftwareCommunitiesPlugin::Download.find_by_id(download_hash[:id].to_i)\n download_record ||= SoftwareCommunitiesPlugin::Download.new(:download_block => self)\n download_record.update_attributes(download_hash)\n download_hash[:id] = download_record.id\n end\n end\n\n def self.description\n _('Download Stable Version')\n end\n\n def help\n _('This block displays the stable version of a software.')\n end\n\n def content(args={})\n block = self\n s = show_name\n lambda do |object|\n render(\n :file => 'blocks/download',\n :locals => { :block => block, :show_name => s }\n )\n end\n end\n\n def cacheable?\n false\n end\n\n def uploaded_files\n downloads_folder = Folder.find_or_create_by_profile_id_and_name(owner.id, \"Downloads\")\n get_nodes(downloads_folder.children)\n end\n\n private\n\n def get_nodes(folder)\n nodes = []\n folder.each do |article|\n if article.type == \"UploadedFile\"\n nodes << article\n end\n nodes += get_nodes(article.children)\n end\n nodes\n end\nend\n"
},
{
"alpha_fraction": 0.7857142686843872,
"alphanum_fraction": 0.7857142686843872,
"avg_line_length": 28.75,
"blob_id": "651ac5283f797793e1e8d1771d9c2ce052ecb23e",
"content_id": "76f429aec3d0e192f0daaeed4314812d114fdda9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 238,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 8,
"path": "/src/noosfero-spb/software_communities/lib/ext/application_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency \"application_helper\"\n\nApplicationHelper.class_eval do\n\n def number_to_human(value)\n number_with_delimiter(value, :separator => environment.currency_separator, :delimiter => environment.currency_delimiter)\n end\nend\n"
},
{
"alpha_fraction": 0.6818181872367859,
"alphanum_fraction": 0.6818181872367859,
"avg_line_length": 16.600000381469727,
"blob_id": "c53c9f82483d1dacb466d6dc995607598bdcb564",
"content_id": "46dac9817e6277b456a58bd6564c068234348323",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 88,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 5,
"path": "/roles/email_server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "name 'email_server'\ndescription 'E-mail server'\nrun_list *[\n 'recipe[email::relay]',\n]\n"
},
{
"alpha_fraction": 0.6582884788513184,
"alphanum_fraction": 0.6594853401184082,
"avg_line_length": 27.32203483581543,
"blob_id": "6b85aef443ff06450440da4bec87c5f01c98e09d",
"content_id": "b27c031128b7d35184f8b937b4cd19bb9403018f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1671,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 59,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/library_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::LibraryHelper < SoftwareCommunitiesPlugin::DynamicTableHelper\n #FIXME Verify this name.\n MODEL_NAME = \"software_communities_plugin/library\"\n\n def self.list_library new_libraries\n return [] if new_libraries.nil? or new_libraries.length == 0\n list_libraries = []\n\n new_libraries.each do |new_library|\n unless SoftwareCommunitiesPlugin::SoftwareHelper.all_table_is_empty? new_library\n library = SoftwareCommunitiesPlugin::Library.new\n library.name = new_library[:name]\n library.version = new_library[:version]\n library.license = new_library[:license]\n list_libraries << library\n end\n end\n\n list_libraries\n end\n\n def self.valid_list_library? list_libraries\n return true if list_libraries.nil? or list_libraries.length == 0\n return !list_libraries.any?{|library| !library.valid?}\n end\n\n def self.libraries_as_tables list_libraries, disabled=false\n model_list = list_libraries\n model_list ||= [{:name=>\"\", :version=>\"\", :license=>\"\"}]\n\n models_as_tables model_list, \"library_html_structure\", disabled\n end\n\n def self.library_html_structure library_data, disabled\n data = {\n #FIXME Verify MODEL_NAME\n model_name: MODEL_NAME,\n name: {\n value: library_data[:name],\n hidden: false,\n autocomplete: false,\n select_field: false\n },\n version: {\n value: library_data[:version],\n delete: false\n },\n license: {\n value: library_data[:license]\n }\n }\n\n table_html_structure(data, disabled)\n end\n\n def self.add_dynamic_table\n libraries_as_tables(nil).first.call\n end\nend\n"
},
{
"alpha_fraction": 0.7157320976257324,
"alphanum_fraction": 0.7204049825668335,
"avg_line_length": 39.125,
"blob_id": "1b787f4dafcf1def5a5018f59136b7b5faccfc76",
"content_id": "400d154cad63dd419d59ee27c7f9bbe7f900a6b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1284,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 32,
"path": "/test/noosfero_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_database_connectivity() {\n assertTrue 'noosfero database connectivity' 'run_on social psql -h database -U noosfero < /dev/null'\n}\n\ntest_noosfero_running() {\n assertTrue 'Noosfero running' 'run_on social pgrep -u noosfero -f unicorn'\n}\n\ntest_noosfero_on_subdir() {\n local meta=\"$(run_on social curl --fail http://localhost:9000/social | sed -e '/noosfero:root/ !d; s/^\\s*//')\"\n assertEquals '<meta property=\"noosfero:root\" content=\"/social\"/>' \"$meta\"\n}\n\ntest_reverse_proxy_noosfero() {\n local meta=\"$(run_on social curl-host softwarepublico.dev http://social/social/ | sed -e '/noosfero:root/ !d; s/^\\s*//')\"\n assertEquals '<meta property=\"noosfero:root\" content=\"/social\"/>' \"$meta\"\n}\n\ntest_reverse_proxy_static_files() {\n local content_type=\"$(curl-host softwarepublico.dev --head https://$config_external_hostname/social/images/noosfero-network.png | grep-header Content-Type)\"\n assertEquals \"Content-Type: image/png\" \"$content_type\"\n}\n\ntest_redirect_with_correct_hostname_behind_proxy() {\n local redirect=\"$(curl-host softwarepublico.dev --head https://$config_external_hostname/social/search/contents | grep-header Location)\"\n assertEquals \"Location: https://softwarepublico.dev/social/search/articles\" \"$redirect\"\n}\n\n\nload_shunit2\n"
},
{
"alpha_fraction": 0.6477064490318298,
"alphanum_fraction": 0.6550458669662476,
"avg_line_length": 20.799999237060547,
"blob_id": "07f3e018e34ce903ef4ecd0228df92021ee04ec1",
"content_id": "de78a9d05360f0b526a9d1adcc287f013aeaaeff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 545,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 25,
"path": "/src/noosfero-spb/gov_user/test/unit/user_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass UserTest < ActiveSupport::TestCase\n include PluginTestHelper\n\n should 'not save user whose email has already been used' do\n user1 = create_default_user\n user2 = fast_create(User)\n\n user2.email = \"[email protected]\"\n assert !user2.save\n end\n\n private\n\n def create_default_user\n user = fast_create(User)\n user.login = \"a-login\"\n user.email = \"[email protected]\"\n user.save\n\n return user\n end\nend\n"
},
{
"alpha_fraction": 0.6235780715942383,
"alphanum_fraction": 0.6266804337501526,
"avg_line_length": 19.14583396911621,
"blob_id": "70ff367955217f417ce8e9ae0a5b03deb58c3236",
"content_id": "cc4eeb137fe0ae5c382ccfd55202390054ad86f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 967,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 48,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_tab_data_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareTabDataBlock < Block\n attr_accessible :show_name, :displayed_blog\n\n settings_items :show_name, :type => :boolean, :default => false\n settings_items :displayed_blog, :type => :integer, :default => 0\n\n TOTAL_POSTS_DYSPLAYED = 5\n\n def self.description\n _('Software Tab Data')\n end\n\n def help\n _('This block is used by colab to insert data into Noosfero')\n end\n\n def content(args={})\n block = self\n\n lambda do |object|\n render(\n :file => 'blocks/software_tab_data',\n :locals => {\n :block => block\n }\n )\n end\n end\n\n def blogs\n self.owner.blogs\n end\n\n def actual_blog\n # As :displayed_blog default value is 0, it falls to the first one\n blogs.find_by_id(self.displayed_blog) || blogs.first\n end\n\n def posts\n blog = actual_blog\n\n if blog and (not blog.posts.empty?)\n blog.posts.limit(TOTAL_POSTS_DYSPLAYED)\n else\n []\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6708074808120728,
"alphanum_fraction": 0.672877848148346,
"avg_line_length": 16.88888931274414,
"blob_id": "46bade7964c1d176f230da6181ba7295464cb7b9",
"content_id": "b4aa84206123b1ef67d51c54cd3bc2b9423f3457",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 483,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 27,
"path": "/src/noosfero-spb/gov_user/lib/ext/person.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: utf-8\n\nrequire_dependency 'person'\n\nclass Person\n\n settings_items :percentage_incomplete, :type => :string, :default => \"\"\n\n attr_accessible :percentage_incomplete\n\n delegate :login, :to => :user, :prefix => true\n\n def institution?\n false\n end\n\n def institutions\n institutions = []\n unless self.user.institutions.nil?\n self.user.institutions.each do |institution|\n institutions << institution.name\n end\n end\n institutions\n end\n\nend\n"
},
{
"alpha_fraction": 0.7129380106925964,
"alphanum_fraction": 0.7149595618247986,
"avg_line_length": 33.511627197265625,
"blob_id": "6bd0197b06a4e8582363073b183f605670e265ac",
"content_id": "e4f73542400c22ac42b1c3a3c32f34397e21c91d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1484,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 43,
"path": "/src/noosfero-spb/software_communities/test/functional/profile_editor_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../helpers/software_test_helper'\nrequire 'test_helper'\nrequire(\n File.dirname(__FILE__) +\n '/../../../../app/controllers/my_profile/profile_editor_controller'\n)\n\nclass ProfileEditorController; def rescue_action(e) raise e end; end\n\nclass ProfileEditorControllerTest < ActionController::TestCase\n include SoftwareTestHelper\n def setup\n @controller = ProfileEditorController.new\n @request = ActionController::TestRequest.new\n @response = ActionController::TestResponse.new\n @profile = create_user('default_user').person\n\n SoftwareCommunitiesPlugin::LicenseInfo.create(\n :version=>\"CC-GPL-V2\",\n :link=>\"http://creativecommons.org/licenses/GPL/2.0/legalcode.pt\"\n )\n\n Environment.default.affiliate(\n @profile,\n [Environment::Roles.admin(Environment.default.id)] +\n Profile::Roles.all_roles(Environment.default.id)\n )\n\n @environment = Environment.default\n @environment.enabled_plugins = ['SoftwareCommunitiesPlugin']\n admin = create_user(\"adminuser\").person\n admin.stubs(:has_permission?).returns(\"true\")\n login_as('adminuser')\n @environment.add_admin(admin)\n @environment.save\n end\n\n should \"redirect to edit_software_community on edit community of software\" do\n software = create_software(software_fields)\n post :edit, :profile => software.community.identifier\n assert_redirected_to :controller => 'profile_editor', :action => 'edit_software_community'\n end\nend\n"
},
{
"alpha_fraction": 0.6661971807479858,
"alphanum_fraction": 0.6676056385040283,
"avg_line_length": 29.826086044311523,
"blob_id": "2262da65d7dbdd279bf736699519662de2dbf92b",
"content_id": "cb9515ca3af7149e7857af3d0ce0d3605e7d15d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 713,
"license_type": "no_license",
"max_line_length": 191,
"num_lines": 23,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150916134427_change_members_page_link_in_all_softwares_communities.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: utf-8\n\nclass ChangeMembersPageLinkInAllSoftwaresCommunities < ActiveRecord::Migration\n def up\n Community.joins(:software_info).each do |software_community|\n collaboration_block = Block.joins(:box).where(\"boxes.owner_id = ? AND blocks.type = ? AND blocks.title = ?\", software_community.id, \"LinkListBlock\", \"Colaboração\").readonly(false).first\n\n if collaboration_block\n collaboration_block.links.each do |link|\n link[\"address\"] = \"/profile/#{software_community.identifier}/members\" if link[\"name\"] == \"Usuários\"\n end\n collaboration_block.save!\n print \".\"\n end\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n\n"
},
{
"alpha_fraction": 0.6479663252830505,
"alphanum_fraction": 0.6479663252830505,
"avg_line_length": 18.2702693939209,
"blob_id": "96b8fa1acb769344df13f3be40fe8ea1a94f6e14",
"content_id": "99f9982f5bbc9d6e5191a791f9afac0902b25cd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 713,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 37,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/software_information_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::SoftwareInformationBlock < Block\n\n attr_accessible :show_name\n\n settings_items :show_name, :type => :boolean, :default => false\n\n def self.description\n _('Basic Software Information')\n end\n\n def help\n _('This block displays the basic information of a software profile.')\n end\n\n def content(args={})\n block = self\n s = show_name\n\n lambda do |object|\n render(\n :file => 'blocks/software_information',\n :locals => { :block => block, :show_name => s}\n )\n end\n end\n\n def cacheable?\n false\n end\n\n private\n\n def owner_has_ratings?\n ratings = OrganizationRating.where(community_id: block.owner.id)\n !ratings.empty?\n end\nend\n"
},
{
"alpha_fraction": 0.6684131622314453,
"alphanum_fraction": 0.671407163143158,
"avg_line_length": 28.688888549804688,
"blob_id": "02848706f2ad77ff856e368c1a8bbd0146812536",
"content_id": "4a5fcaae20b1a4a5748d67e448907e3c8c10aa15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1336,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 45,
"path": "/src/noosfero-spb/software_communities/lib/ext/communities_block.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'communities_block'\n\nclass CommunitiesBlock\n\n def profile_list\n result = get_visible_profiles\n result.slice(0..get_limit-1)\n end\n\n def profile_count\n profile_list.count\n end\n\n private\n\n def get_visible_profiles\n visible_profiles = profiles.visible.includes(\n [:image,:domains,:preferred_domain,:environment]\n )\n\n delete_communities = []\n valid_communities_string = Community.get_valid_communities_string\n Community.all.each{|community| delete_communities << community.id unless eval(valid_communities_string)}\n\n visible_profiles = visible_profiles.where([\"profiles.id NOT IN (?)\", delete_communities]) unless delete_communities.empty?\n\n if !prioritize_profiles_with_image\n return visible_profiles.all(\n :limit => get_limit,\n :order => 'profiles.updated_at DESC'\n ).sort_by {rand}\n elsif profiles.visible.with_image.count >= get_limit\n return visible_profiles.with_image.all(\n :limit => get_limit * 5,\n :order => 'profiles.updated_at DESC'\n ).sort_by {rand}\n else\n visible_profiles = visible_profiles.with_image.sort_by {rand} +\n visible_profiles.without_image.all(\n :limit => get_limit * 5, :order => 'profiles.updated_at DESC'\n ).sort_by {rand}\n return visible_profiles\n end\n end\nend\n"
},
{
"alpha_fraction": 0.7484662532806396,
"alphanum_fraction": 0.7484662532806396,
"avg_line_length": 37.35293960571289,
"blob_id": "3cdfafe625d13159cd0f8cf707c62c6a11566167",
"content_id": "e7901a96ba63cdd3a5759de40e6b0ab29d030b5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 652,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 17,
"path": "/src/noosfero-spb/software_communities/lib/ext/create_organization_rating_comment.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency \"create_organization_rating_comment\"\n\nCreateOrganizationRatingComment.class_eval do\n after_save :update_software_statistic\n\n def update_software_statistic\n if(self.status == Task::Status::FINISHED)\n rating = OrganizationRating.find_by_id(self.organization_rating_id)\n software = SoftwareCommunitiesPlugin::SoftwareInfo.find_by_community_id(self.target_id)\n if software.present? and rating.present?\n software.saved_resources += rating.saved_value if rating.saved_value\n software.benefited_people += rating.people_benefited if rating.people_benefited\n software.save\n end\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6296669840812683,
"alphanum_fraction": 0.633703351020813,
"avg_line_length": 21.0222225189209,
"blob_id": "7aa64d4713edb5c94772b6a390cab362aaa712c5",
"content_id": "8538bf3a25a78880b5c8a6d2b3457c066e9c9166",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 991,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 45,
"path": "/src/noosfero-spb/software_communities/lib/ext/search_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require_dependency 'search_helper'\n\nmodule SearchHelper\n\n COMMON_PROFILE_LIST_BLOCK ||= []\n COMMON_PROFILE_LIST_BLOCK << :software_infos\n\n def sort_by_relevance list, text\n text_splited = text.split\n\n element_relevance = {}\n\n list.each do |element|\n relevance = 1\n relevance_list = yield(element)\n\n text_splited.each do |t|\n relevance_list.count.times do |i|\n relevance = -1 * i if relevance_list[i].downcase.include?(t.downcase)\n end\n end\n\n element_relevance[element] = relevance\n end\n\n list.sort! do |a, b|\n element_relevance[a] <=> element_relevance[b]\n end\n\n list\n end\n\n def sort_by_average_rating list\n list.sort! do |a, b|\n rating_a = OrganizationRating.statistics_for_profile(a)[:average]\n rating_a = 0 if rating_a.nil?\n rating_b = OrganizationRating.statistics_for_profile(b)[:average]\n rating_b = 0 if rating_b.nil?\n rating_a - rating_b\n end\n\n list.reverse!\n end\n\nend\n"
},
{
"alpha_fraction": 0.6147186160087585,
"alphanum_fraction": 0.6327561140060425,
"avg_line_length": 31.988094329833984,
"blob_id": "de146642e310030b177d577ccf27ec6a2eda0ffc",
"content_id": "3f795a41fa166bfbe66f973f3592c724836ca1fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2772,
"license_type": "no_license",
"max_line_length": 188,
"num_lines": 84,
"path": "/src/noosfero-spb/software_communities/test/functional/profile_controller_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require \"test_helper\"\nrequire 'profile_controller'\n\n# Re-raise errors caught by the controller.\nclass ProfileController; def rescue_action(e) raise e end; end\n\nclass ProfileControllerTest < ActionController::TestCase\n def setup\n Environment.default.enable('products_for_enterprises')\n @profile = create_user('testuser').person\n end\n attr_reader :profile\n\n should 'not count a visit twice for the same user' do\n profile = create_user('someone').person\n login_as(@profile.identifier)\n community = fast_create('Community')\n\n get :index, :profile => community.identifier\n community.reload\n assert_equal 1, community.hits\n\n get :index, :profile => community.identifier\n community.reload\n assert_equal 1, community.hits\n end\n\n should 'not count a visit twice for unlogged users' do\n profile = create_user('someone').person\n community = fast_create('Community')\n get :index, :profile => community.identifier\n community.reload\n assert_equal 1, community.hits\n\n get :index, :profile => community.identifier\n community.reload\n assert_equal 1, community.hits\n end\n\n should 'display admins correctly when is on the second members page' do\n community = fast_create('Community')\n\n for n in 1..30\n community.add_member(create_user(\"testuser#{\"%02i\" % n}\").person)\n end\n\n for n in 31..35\n community.add_admin(create_user(\"testuser#{\"%02i\" % n}\").person)\n end\n\n get :members, :profile => community.identifier, :members_page => 2\n\n for n in 1..20\n assert_no_tag :tag => 'div', :attributes => { :class => 'profile-members' }, :descendant => { :tag => 'span', :attributes => { :class => 'fn' }, :content => \"testuser#{\"%02i\" % n}\" }\n end\n\n for n in 31..35\n assert_tag :tag => 'div', :attributes => { :class => 'profile-admins' }, :descendant => { :tag => 'span', :attributes => { :class => 'fn' }, :content => \"testuser#{\"%02i\" % n}\" }\n end\n end\n\n\n should 'display members correctly when is on the second admins page' do\n community = fast_create('Community')\n\n for n in 1..10\n community.add_member(create_user(\"testuser#{\"%02i\" % n}\").person)\n end\n\n for n in 11..15\n community.add_admin(create_user(\"testuser#{\"%02i\" % n}\").person)\n end\n\n get :members, :profile => community.identifier, :admins_page => 2\n\n for n in 1..10\n assert_tag :tag => 'div', :attributes => { :class => 'profile-members' }, :descendant => { :tag => 'span', :attributes => { :class => 'fn' }, :content => \"testuser#{\"%02i\" % n}\" }\n end\n\n for n in 11..15\n assert_no_tag :tag => 'div', :attributes => { :class => 'profile-admins' }, :descendant => { :tag => 'span', :attributes => { :class => 'fn' }, :content => \"testuser#{\"%02i\" % n}\" }\n end\n end\nend\n\n"
},
{
"alpha_fraction": 0.6701461672782898,
"alphanum_fraction": 0.6764091849327087,
"avg_line_length": 30.866666793823242,
"blob_id": "fc754604f7e7d18717f3264181690bf3e51c5118",
"content_id": "4eadc2c253c38d11bb745d20fb96b17811e6f2fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 15,
"path": "/cookbooks/postgresql/recipes/gitlab.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "execute 'createuser:gitlab' do\n command 'createuser gitlab'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'gitlab';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:gitlab' do\n command 'createdb --owner=gitlab gitlab'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'gitlab';\"`.strip.to_i == 0\n end\nend\n\n"
},
{
"alpha_fraction": 0.6805251836776733,
"alphanum_fraction": 0.6878191232681274,
"avg_line_length": 22.220338821411133,
"blob_id": "bc8c5a87bce0937dedf21f1c0efb98e713fcf9dd",
"content_id": "56f702be2eb83fdbc541bcb7104082941a21439d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1371,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 59,
"path": "/test/mail_relay_test.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": ". $(dirname $0)/test_helper.sh\n\ntest_inbound_list_mail() {\n run_on integration create-list mylist [email protected]\n\n # sending FROM EMAIL RELAY HOST\n run_on email send-email [email protected] [email protected]\n\n messages=$(run_on integration wait-for-messages mylist)\n\n run_on integration remove-list mylist\n\n assertEquals 'Message did not arrive at the mailing list' '1' \"$messages\"\n}\n\ntest_inbound_regular_mail() {\n messages_before=$(run_on integration sudo grep -c '^From.*[email protected]' /var/mail/root)\n run_on email send-email [email protected] [email protected]\n n=0\n while [ $n -lt 10 ]; do\n sleep 1\n messages=$(run_on integration sudo grep -c '^From.*[email protected]' /var/mail/root)\n if [ \"$messages\" -gt \"$messages_before\" ]; then\n return\n else\n n=$(($n + 1))\n fi\n done\n fail \"didn't receive incoming email\"\n}\n\n_test_outbound_email() {\n machine=\"$1\"\n\n run_on email clear-email-queue\n\n run_on $machine send-email [email protected] [email protected]\n\n messages=$(run_on email wait-for-email-to [email protected])\n\n run_on email clear-email-queue\n\n assertEquals 'Message was not delivered through relay' 1 \"$messages\"\n}\n\ntest_outbound_email_integration() {\n _test_outbound_email integration\n}\ntest_outbound_email_database() {\n _test_outbound_email database\n}\ntest_outbound_email_social() {\n _test_outbound_email social\n}\ntest_outbound_email_reverseproxy() {\n _test_outbound_email reverseproxy\n}\n\nload_shunit2\n\n"
},
{
"alpha_fraction": 0.43939393758773804,
"alphanum_fraction": 0.4545454680919647,
"avg_line_length": 8.285714149475098,
"blob_id": "de52060f4c8ff2a941269fc95522bbc940d121d0",
"content_id": "a3d4a6f07018d70cd1fef6ec2550694f3dc112bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 66,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 7,
"path": "/test/bin/grep-header",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -eu\n\nheader=\"$1\"\n\nsed -e \"/^$header:/ !d; s/\\r//\"\n\n"
},
{
"alpha_fraction": 0.7546296119689941,
"alphanum_fraction": 0.7569444179534912,
"avg_line_length": 27.799999237060547,
"blob_id": "f8d9659243c77b9ffd756a47788520036304e018",
"content_id": "90db0e79bf8dac62683619d09228983337158551",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 432,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 15,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/database_description.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::DatabaseDescription < ActiveRecord::Base\n\n SEARCHABLE_SOFTWARE_FIELDS = {\n :name => 1\n }\n\n attr_accessible :name\n\n has_many :software_databases, :class_name => 'SoftwareCommunitiesPlugin::SoftwareDatabase'\n has_many :software_infos, :through => :software_databases, :class_name => 'SoftwareCommunitiesPlugin::SoftwareInfo'\n\n validates_presence_of :name\n validates_uniqueness_of :name\n\nend\n"
},
{
"alpha_fraction": 0.6854701042175293,
"alphanum_fraction": 0.6854701042175293,
"avg_line_length": 42.33333206176758,
"blob_id": "fcd063bc454e0d24312898a7dcf7a11b3e8acfa8",
"content_id": "471190cd84997914ca55e3d3136b48b60454d6d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1170,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 27,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160308181957_move_contents_from_sistemadeatendimento_to_fila.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class MoveContentsFromSistemadeatendimentoToFila < ActiveRecord::Migration\n def change\n environment = Environment.default\n sistemadeatendimento = environment.communities.where(:identifier => 'sistemadeatendimento').first\n fila = environment.communities.where(:identifier => 'fila').first\n\n # Migrate foruns\n\n if sistemadeatendimento && fila\n source = sistemadeatendimento.folders.where(:slug => 'historico-de-foruns').first\n target = fila.folders.where(:slug => 'historico-de-foruns').first\n children = source.all_children\n\n execute(\"UPDATE articles SET parent_id = #{target.id} WHERE parent_id = #{source.id}\")\n execute(\"UPDATE articles SET profile_id = #{fila.id} WHERE id in (#{children.map(&:id).join(',')})\")\n\n # Migrate blog posts\n\n source = sistemadeatendimento.folders.where(:slug => 'blog').first\n target = fila.folders.where(:slug => 'blog').first\n children = source.all_children\n\n execute(\"UPDATE articles SET parent_id = #{target.id} WHERE parent_id = #{source.id}\")\n execute(\"UPDATE articles SET profile_id = #{fila.id} WHERE id in (#{children.map(&:id).join(',')})\")\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6229050159454346,
"alphanum_fraction": 0.6229050159454346,
"avg_line_length": 34.79999923706055,
"blob_id": "f9921a355c3d528679dd7206776c5056dae1155a",
"content_id": "f1b9ab87c0bb6c9c3ce26f7361ab4ec3e2580bdf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 716,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 20,
"path": "/src/noosfero-spb/software_communities/lib/tasks/create_categories.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "namespace :software do\n desc \"Create software categories\"\n task :create_categories => :environment do\n Environment.all.each do |env|\n if env.plugin_enabled?(\"SoftwareCommunitiesPlugin\") or env.plugin_enabled?(\"SoftwareCommunities\")\n print 'Creating categories: '\n software = Category.create(:name => _(\"Software\"), :environment => env)\n SoftwareCommunitiesPlugin::SOFTWARE_CATEGORIES.each do |category_name|\n unless Category.find_by_name(category_name)\n print '.'\n Category.create(:name => category_name, :environment => env, :parent => software)\n else\n print 'F'\n end\n end\n puts ''\n end\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6541253924369812,
"alphanum_fraction": 0.6640263795852661,
"avg_line_length": 32.29670333862305,
"blob_id": "c88f9d801135d0a0cbe581d7b62d730af03692d1",
"content_id": "638b9cf0006bb04f2ac7ae132b404880714b739e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3030,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 91,
"path": "/src/noosfero-spb/gov_user/test/unit/institution_test.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "require File.dirname(__FILE__) + '/../../../../test/test_helper'\nrequire File.dirname(__FILE__) + '/../helpers/plugin_test_helper'\n\nclass InstitutionTest < ActiveSupport::TestCase\n include PluginTestHelper\n def setup\n @gov_power = GovernmentalPower.create(:name=>\"Some Gov Power\")\n @gov_sphere = GovernmentalSphere.create(:name=>\"Some Gov Sphere\")\n @juridical_nature = JuridicalNature.create(:name => \"Autarquia\")\n\n @institution = create_public_institution(\n \"Ministerio Publico da Uniao\",\n \"MPU\",\n \"BR\",\n \"Distrito Federal\",\n \"Gama\",\n @juridical_nature,\n @gov_power,\n @gov_sphere,\n \"11.222.333/4444-55\"\n )\n end\n\n def teardown\n GovernmentalPower.destroy_all\n GovernmentalSphere.destroy_all\n JuridicalNature.destroy_all\n @institution = nil\n end\n\n should \"not save institutions without name\" do\n @institution.name = nil\n assert_equal false, @institution.save\n assert_equal true, @institution.errors.messages.keys.include?(:name)\n end\n\n should \"not save if institution has invalid type\" do\n invalid_msg = \"Type invalid, only public and private institutions are allowed.\"\n @institution.type = \"Other type\"\n assert_equal false, @institution.save\n assert_equal true, @institution.errors.messages.keys.include?(:type)\n end\n\n should \"not save without country\" do\n @institution.community.country = nil\n assert_equal false, @institution.save\n assert_equal true, @institution.errors.messages.keys.include?(:country)\n end\n\n should \"not save without state\" do\n @institution.community.state = nil\n\n assert_equal false, @institution.save\n assert_equal true, @institution.errors.messages.keys.include?(:state)\n end\n\n should \"not save without city\" do\n @institution.community.city = nil\n @institution.community.state = \"DF\"\n\n assert_equal false, @institution.save\n assert_equal true, @institution.errors.messages.keys.include?(:city)\n end\n\n should \"only return institutions of a specific environment\" do\n env1 = Environment.create(:name => \"Environment One\")\n env2 = Environment.create(:name => \"Environment Two\")\n\n env1.communities << @institution.community\n search_result_env1 = Institution.search_institution(\"Ministerio\", env1).collect{ |i| i.id }\n search_result_env2 = Institution.search_institution(\"Ministerio\", env2).collect{ |i| i.id }\n\n assert_includes search_result_env1, @institution.id\n assert_not_includes search_result_env2, @institution.id\n end\n\n should \"not save if siorg_code is not a number\" do\n @institution.siorg_code = \"not a number\"\n assert_equal false, @institution.save\n\n @institution.siorg_code = \"1111111\"\n assert_equal true, @institution.save\n end\n\n should \"validate siorg_code if it is blank\" do\n @institution.siorg_code = \"\"\n assert_equal true, @institution.save\n end\n\n\nend\n"
},
{
"alpha_fraction": 0.577617347240448,
"alphanum_fraction": 0.6353790760040283,
"avg_line_length": 26.600000381469727,
"blob_id": "c145b47ef4658a016edc8e1f91fed9110ff022c1",
"content_id": "9a95330351b15b925fdafe60cdf4ec61f80316e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 277,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 10,
"path": "/cookbooks/backup/files/host-social/backup_spb.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nset -e\n\nBKP_DIR=/usr/lib/noosfero/tmp/backup\n\ncd /usr/lib/noosfero\nRAILS_ENV=production sudo -u noosfero bundle exec rake backup\ncd -\nmv $BKP_DIR/`ls -tr $BKP_DIR | grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}:[0-9]{2}\\.tar\\.gz' | tail -1` noosfero_backup.tar.gz\n\n"
},
{
"alpha_fraction": 0.6728643178939819,
"alphanum_fraction": 0.6728643178939819,
"avg_line_length": 32.445377349853516,
"blob_id": "2ad85eedc3ba13f62b0ff4e927db828f7019b791",
"content_id": "0081a00ab2a76760c266a4bb88a4a6e37b194ad3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 3980,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 119,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/create_software.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::CreateSoftware < Task\n include Rails.application.routes.url_helpers\n\n validates_presence_of :requestor_id, :target_id\n validates_presence_of :name, :finality\n\n attr_accessible :name, :finality, :repository_link, :requestor, :environment,\n :reject_explanation, :license_info, :identifier, :another_license_version,\n :another_license_link, :target\n\n alias :environment :target\n alias :environment= :target=\n\n DATA_FIELDS = ['name', 'identifier', 'finality', 'license_info', 'repository_link',\n 'another_license_version', 'another_license_link']\n DATA_FIELDS.each do |field|\n settings_items field.to_sym\n end\n\n def perform\n software_template = SoftwareCommunitiesPlugin::SoftwareHelper.software_template\n template_id = software_template.blank? ? nil : software_template.id\n\n identifier = self.identifier\n identifier ||= self.name.to_slug\n\n community = Community.create!(:name => self.name,\n :identifier => identifier,\n :template_id => template_id)\n\n community.environment = self.environment\n community.add_admin(self.requestor)\n\n software = SoftwareCommunitiesPlugin::SoftwareInfo.create!(:finality => self.finality,\n :repository_link => self.repository_link, :community_id => community.id,\n :license_info => self.license_info)\n software.verify_license_info(self.another_license_version, self.another_license_link)\n software.save!\n end\n\n def title\n _(\"New software\")\n end\n\n def subject\n name\n end\n\n def information\n message = _('%{requestor} wants to create software %{subject} with')\n if finality.blank?\n { :message => message + _(' no finality.') }\n else\n { :message => message + _(' this finality:<p><em>%{finality}</em></p>'),\n :variables => {:finality => finality} }\n end\n end\n\n def reject_details\n true\n end\n\n # tells if this request was rejected\n def rejected?\n self.status == Task::Status::CANCELLED\n end\n\n # tells if this request was appoved\n def approved?\n self.status == Task::Status::FINISHED\n end\n\n def target_notification_description\n _('%{requestor} wants to create software %{subject}') %\n {:requestor => requestor.name, :subject => subject}\n end\n\n def target_notification_message\n _(\"User \\\"%{user}\\\" just requested to create software %{software}.\n You have to approve or reject it through the \\\"Pending Validations\\\"\n section in your control panel.\\n\") %\n { :user => self.requestor.name, :software => self.name }\n end\n\n def task_created_message\n _(\"Your request for registering software %{software} at %{environment} was\n just sent. Environment administrator will receive it and will approve or\n reject your request according to his methods and criteria.\n\n You will be notified as soon as environment administrator has a position\n about your request.\") %\n { :software => self.name, :environment => self.target }\n end\n\n def task_cancelled_message\n _(\"Your request for registering software %{software} at %{environment} was\n not approved by the environment administrator. The following explanation\n was given: \\n\\n%{explanation}\") %\n { :software => self.name,\n :environment => self.environment,\n :explanation => self.reject_explanation }\n end\n\n def task_finished_message\n _('Your request for registering the software \"%{software}\" was approved.\n You can access %{url} and finish the registration of your software.') %\n { :software => self.name, :url => mount_url }\n end\n\n private\n\n def mount_url\n identifier = Community.where(:name => self.name).first.identifier\n # The use of url_for doesn't allow the /social within the Public Software\n # portal. That's why the url is mounted so 'hard coded'\n url = \"#{environment.top_url}/myprofile/#{identifier}/profile_editor/edit_software_community\"\n end\n\nend\n"
},
{
"alpha_fraction": 0.6018518805503845,
"alphanum_fraction": 0.6018518805503845,
"avg_line_length": 23.923076629638672,
"blob_id": "a6f1d2046f32530631f71e9ad8ef213c3a6657fa",
"content_id": "9f6792dc72fd230634dde0497aa2c8450bf4a076",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 324,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 13,
"path": "/src/noosfero-spb/gov_user/lib/private_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class PrivateInstitution < Institution\n validates :cnpj,\n :format => {with: CNPJ_FORMAT},\n :if => :is_a_brazilian_institution?\n\n validates :cnpj,\n :uniqueness => true, :unless => 'cnpj.blank?'\n\n private\n def is_a_brazilian_institution?\n self.community.country == \"BR\"\n end\nend\n"
},
{
"alpha_fraction": 0.5272727012634277,
"alphanum_fraction": 0.7090908885002136,
"avg_line_length": 17.33333396911621,
"blob_id": "97e2a67e18cbb88a9502f0c24df96e955f3bbb2f",
"content_id": "dae33bae7c69ec23b18993440ead405cc2ce844d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 55,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 3,
"path": "/cookbooks/noosfero/files/unicorn.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "listen \"127.0.0.1:9000\"\n\nworker_processes `nproc`.to_i\n"
},
{
"alpha_fraction": 0.6704225540161133,
"alphanum_fraction": 0.6816901564598083,
"avg_line_length": 15.904762268066406,
"blob_id": "aaf19a3bb1bfc23a837f93cb0d538aa752fbf60f",
"content_id": "ac2810540d7e6a6d0f7f818dbcb0e7d6d03f9b74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 355,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 21,
"path": "/cookbooks/rsyslog/recipes/server.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "package 'rsyslog-mysql' do\n action [:install, :upgrade]\nend\n\nSPB_LOG='/var/log/spb.log'\n\nfile SPB_LOG do\n owner 'root'\n group 'root'\n mode 0644\nend\n\nexecute 'allowing-spb-log' do\n command 'semanage fcontext -a -t httpd_sys_rw_content_t ' + SPB_LOG\n user 'root'\nend\n\nexecute 'enable-spb-log' do\n command 'restorecon -v ' + SPB_LOG\n user 'root'\nend\n"
},
{
"alpha_fraction": 0.7061946988105774,
"alphanum_fraction": 0.7115043997764587,
"avg_line_length": 32.900001525878906,
"blob_id": "908df7ea75e5041ea8b5e466fe3ce4813a620938",
"content_id": "4fe0d6079f38e8c4b3a2c24365eb8bc3a1108317",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1695,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 50,
"path": "/cookbooks/postgresql/recipes/mezuro.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# Kalibro Processor\nexecute 'createuser:kalibro_processor' do\n command 'createuser kalibro_processor'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'kalibro_processor';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:kalibro_processor' do\n command 'createdb --owner=kalibro_processor kalibro_processor'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'kalibro_processor';\"`.strip.to_i == 0\n end\nend\n\n# Kalibro Configurations\nexecute 'createuser:kalibro_configurations' do\n command 'createuser kalibro_configurations'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'kalibro_configurations';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:kalibro_configurations' do\n command 'createdb --owner=kalibro_configurations kalibro_configurations'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'kalibro_configurations';\"`.strip.to_i == 0\n end\nend\n\n# Prezento\nexecute 'createuser:prezento' do\n command 'createuser prezento'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'prezento';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:prezento' do\n command 'createdb --owner=prezento prezento'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'prezento';\"`.strip.to_i == 0\n end\nend\n"
},
{
"alpha_fraction": 0.6850972175598145,
"alphanum_fraction": 0.685961127281189,
"avg_line_length": 32.550724029541016,
"blob_id": "382e1848b613e014969a3b5727c108628bfb6d5c",
"content_id": "84fcec66f3f06b1c2e93c617158042f5dc8f63d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2315,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 69,
"path": "/src/noosfero-spb/software_communities/lib/software_communities_plugin/operating_system_helper.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPlugin::OperatingSystemHelper < SoftwareCommunitiesPlugin::DynamicTableHelper\n #FIXME Verify model_name\n MODEL_NAME = \"software_communities_plugin/operating_system\"\n FIELD_NAME = \"operating_system_name_id\"\n\n def self.list_operating_system new_operating_systems\n return [] if new_operating_systems.nil? or new_operating_systems.length == 0\n list_operating_system = []\n\n new_operating_systems.each do |new_operating_system|\n unless SoftwareCommunitiesPlugin::SoftwareHelper.all_table_is_empty?(\n new_operating_system,\n [\"operating_system_name_id\"]\n )\n\n operating_system = SoftwareCommunitiesPlugin::OperatingSystem.new\n operating_system.operating_system_name = SoftwareCommunitiesPlugin::OperatingSystemName.find(\n new_operating_system[:operating_system_name_id]\n )\n\n operating_system.version = new_operating_system[:version]\n list_operating_system << operating_system\n end\n end\n list_operating_system\n end\n\n def self.valid_list_operating_system? list_operating_system\n return false if (list_operating_system.nil? || list_operating_system.length == 0)\n return !list_operating_system.any?{|os| !os.valid?}\n end\n\n def self.operating_system_as_tables(list_operating_system, disabled=false)\n model_list = list_operating_system\n model_list ||= [{:operating_system_name_id => \"\", :version => \"\"}]\n\n models_as_tables model_list, \"operating_system_html_structure\", disabled\n end\n\n def self.operating_system_html_structure (operating_system_data, disabled)\n select_options = options_for_select(\n SoftwareCommunitiesPlugin::OperatingSystemName.all.collect {|osn| [osn.name, osn.id]},\n operating_system_data[:operating_system_name_id]\n )\n\n data = {\n #FIXME Verify model_name\n model_name: MODEL_NAME,\n field_name: FIELD_NAME,\n name: {\n hidden: false,\n autocomplete: false,\n select_field: true,\n options: select_options\n },\n version: {\n value: operating_system_data[:version],\n hidden: true,\n delete: true\n }\n }\n DATA[:license].delete(:value)\n table_html_structure(data, disabled)\n end\n\n def self.add_dynamic_table\n operating_system_as_tables(nil).first.call\n end\nend\n"
},
{
"alpha_fraction": 0.7370370626449585,
"alphanum_fraction": 0.7444444298744202,
"avg_line_length": 32.75,
"blob_id": "96a13524cad1cd215c88f4c84cd737fa74806d9b",
"content_id": "800a04d3be6eddda515f982e72a89e12766677b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 270,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 8,
"path": "/utils/migration/restore_social.sh",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\necho 'Starting restore on social...'\n#Noosfero restore\necho 'restoring Noosfero...'\ncd /usr/lib/noosfero\nyes y | RAILS_ENV=production sudo -u noosfero bundle exec rake restore BACKUP=/tmp/backups/noosfero_backup.tar.gz 1> /dev/null 2>/dev/null\necho 'done.'\n"
},
{
"alpha_fraction": 0.7547169923782349,
"alphanum_fraction": 0.7547169923782349,
"avg_line_length": 26,
"blob_id": "93ad38411b6a819c7d6627a45cbe635cc889c478",
"content_id": "ac7fa7b0a3efcf265e9bcde3e8f8e755907a7855",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 53,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 2,
"path": "/cookbooks/ci/recipes/default.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "include_recipe 'ci::spb'\ninclude_recipe 'ci::jenkins'"
},
{
"alpha_fraction": 0.6326647400856018,
"alphanum_fraction": 0.6401146054267883,
"avg_line_length": 35.35416793823242,
"blob_id": "e886171fabe13a164b496ea2163bac2f7ec15f4f",
"content_id": "d1e277363c2499a33782735eb3e169faa85834e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1745,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 48,
"path": "/src/noosfero-spb/software_communities/public/views/comments-software-extra-fields.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "modulejs.define('CommentsSoftwareExtraFields', ['jquery'], function($) {\n 'use strict';\n\n var DATA = {\n information_display_state: \"hidden\"\n }\n\n function set_show_additional_information() {\n $(\".comments-display-fields\").on(\"click\", function() {\n if (DATA.information_display_state === \"hidden\") {\n DATA.information_display_state = \"show\";\n $(\".comments-software-extra-fields div\").show();\n } else {\n DATA.information_display_state = \"hidden\";\n $(\".comments-software-extra-fields div\").hide();\n }\n });\n var organization_rating_saved_value = $(\"#organization_rating_saved_value\");\n var organization_rating_people_benefited = $(\"#organization_rating_people_benefited\");\n var people_benefited_tmp = $(\"#people_benefited_tmp\");\n var saved_value_tmp = $(\"#saved_value_tmp\");\n\n saved_value_tmp.mask(\"#.##0,00\", {reverse: true});\n people_benefited_tmp.mask(\"000.000.000\", {reverse: true});\n\n organization_rating_saved_value.closest(\"form\").submit(function( event ) {\n var unformated_saved_value = saved_value_tmp.val();\n unformated_saved_value = unformated_saved_value.split(\".\").join(\"\");\n unformated_saved_value = unformated_saved_value.replace(\",\",\".\");\n organization_rating_saved_value.val(unformated_saved_value);\n\n var unformated_people_benefited = people_benefited_tmp.val();\n unformated_people_benefited = unformated_people_benefited.split(\".\").join(\"\");\n organization_rating_people_benefited.val(unformated_people_benefited);\n });\n }\n\n return {\n isCurrentPage: function() {\n return $(\".star-rate-form\").length === 1;\n },\n\n\n init: function() {\n set_show_additional_information();\n }\n }\n});\n"
},
{
"alpha_fraction": 0.6462481021881104,
"alphanum_fraction": 0.6845329403877258,
"avg_line_length": 20.064516067504883,
"blob_id": "cd580a74bc088e58c9a84edf5ebc08653c4890ea",
"content_id": "abaadb5a3ac631ad1398486a66b95bed79f169fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 653,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 31,
"path": "/server",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -e\n\nexport SPB_ENV=$(rake env)\nif [ -f test/ip_helper.sh ]; then\n ROOTDIR=$(dirname $0)\n . test/ip_helper.sh\nelse\n echo \"E: must run $0 from the root of the repository!\"\n exit 1\nfi\n\nsudo -v\nsudo redir --lport 80 --cport 80 --caddr $reverseproxy &\nsudo redir --lport 443 --cport 443 --caddr $reverseproxy &\nsudo redir --lport 22 --cport 22 --caddr $reverseproxy &\n\ncleanup() {\n sudo -v\n sudo pkill -9 redir\n}\n\necho \"Forwarding ports 22, 80 and 443\"\necho \"Hit ctrl-c to stop\"\necho \"Browse to: https://softwarepublico.dev/\"\necho \"Browse to: https://listas.softwarepublico.dev/\"\necho\ntrap cleanup INT TERM EXIT\ntail -f /dev/null\necho\n"
},
{
"alpha_fraction": 0.624760091304779,
"alphanum_fraction": 0.6276391744613647,
"avg_line_length": 31.5625,
"blob_id": "afad15f22cbf574f7645fe479c89cb31d0a272b8",
"content_id": "c29a590e42c83fdb7c514f6fd3db68c6024f84a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1046,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 32,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20160323143832_fix_software_release_dates.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# encoding: utf-8\n\nclass FixSoftwareReleaseDates < ActiveRecord::Migration\n def up\n names_mapping = {\n 'Citsmart' => 'Citsmart-ITSM',\n 'SGD – Sistema de Gestão de Demandas' => 'SGD - Sistema de Gestão de Demandas',\n 'SNEP PBX IP' => 'SNEP',\n 'WebIntegrator- Produtividade Java WEB' => 'WebIntegrator - Produtividade Java WEB'\n }\n file = File.open(\"plugins/spb_migrations/files/date-communities.txt\", \"r\")\n while (line = file.gets)\n result = line.split('|')\n software_name = result[2].gsub(\"/n\", \"\").strip\n unless names_mapping[software_name].nil?\n software_name = names_mapping[software_name]\n end\n software = select_one(\"SELECT * FROM profiles WHERE name ILIKE '#{software_name}'\")\n if !software.nil?\n execute(\"UPDATE profiles SET created_at='#{Time.zone.parse(result[1])}' WHERE id='#{software['id']}'\")\n else\n puts \"Software not found: #{software_name}\"\n end\n end\n file.close\n end\n\n def down\n say \"This can't be reverted\"\n end\n\nend\n"
},
{
"alpha_fraction": 0.7092592716217041,
"alphanum_fraction": 0.7111111283302307,
"avg_line_length": 29,
"blob_id": "bdcf5c860ee3af766a76bd08966df7a9ba5b6737",
"content_id": "793ec384f4a26ef5f1d45ef9423a88c29fdbb487",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 540,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 18,
"path": "/src/noosfero-spb/software_communities/lib/tasks/main_data.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "#!/bin/env ruby\n# encoding: utf-8\n\nnamespace :main_data do\n desc \"Create the main community and its contents\"\n task :populate => :environment do\n Rake::Task[\"templates:create:all\"].invoke\n Rake::Task[\"software:create_licenses\"].invoke\n Rake::Task[\"software:create_categories\"].invoke\n Rake::Task[\"software:create_sample_softwares\"].invoke\n end\n\n desc \"Create the main community and its contents\"\n task :all => :environment do\n Rake::Task[\"templates:destroy\"].invoke\n Rake::Task[\"main_data:populate\"].invoke\n end\nend\n"
},
{
"alpha_fraction": 0.6608442664146423,
"alphanum_fraction": 0.663755476474762,
"avg_line_length": 26.479999542236328,
"blob_id": "058f1db5021943b41353271a555fda667c1af480",
"content_id": "bbd2b9feecdb216a0a3abc9160f530be552a29e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1374,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 50,
"path": "/src/noosfero-spb/software_communities/controllers/software_communities_plugin_profile_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SoftwareCommunitiesPluginProfileController < ProfileController\n append_view_path File.join(File.dirname(__FILE__) + '/../views')\n\n before_filter :validate_download_params, only: [:download_file]\n\n ERROR_MESSAGES = {\n :not_found => _(\"Could not find the download file\"),\n :invalid_params => _(\"Invalid download params\")\n }\n\n def download_file\n download = SoftwareCommunitiesPlugin::Download.where(:id => params[:download_id].to_i).detect{ |b| b.download_block.environment.id == environment.id }\n\n if download && (download.link =~ URI::regexp)\n download.total_downloads += 1\n download.save\n\n if profile.software?\n profile.software_info.downloads_count += 1\n profile.software_info.save\n end\n\n redirect_to download.link\n else\n session[:notice] = ERROR_MESSAGES[:not_found]\n render_not_found\n end\n end\n\n private\n\n def validate_download_params\n valid_block = (!params[:block_id].nil?) and (params[:block_id].to_i > 0)\n valid_index = params[:download_id].to_i >= 0\n\n if !valid_block or !valid_index\n session[:notice] = ERROR_MESSAGES[:invalid_params]\n safe_redirect_back\n end\n end\n\n def safe_redirect_back\n begin\n redirect_to :back\n rescue ActionController::RedirectBackError\n # There is no :back if it is a copied url\n render_not_found\n end\n end\nend\n"
},
{
"alpha_fraction": 0.6695957779884338,
"alphanum_fraction": 0.6854130029678345,
"avg_line_length": 31.514286041259766,
"blob_id": "304423523309da409ae41ccf6d600776eecdad81",
"content_id": "745fcef2b20c87685ef2f7793b49a6acdb1abc8d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1138,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 35,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150904174335_swap_softwares_blocks_between_areas_2_and_3.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class SwapSoftwaresBlocksBetweenAreas2And3 < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n if software_template\n swap_software_blocks_between_areas_2_and_3(software_template)\n end\n\n Community.joins(:software_info).each do |software_community|\n swap_software_blocks_between_areas_2_and_3(software_community)\n end\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\n\n def swap_software_blocks_between_areas_2_and_3(software_community)\n print \".\"\n\n # Get areas 2 and 3\n box_area_two = software_community.boxes.find_by_position 2\n box_area_three = software_community.boxes.find_by_position 3\n\n # Get all ids of blocks from areas 2 and 3\n blocks_ids_from_area_two = box_area_two.blocks.select(:id).map(&:id)\n blocks_ids_from_area_three = box_area_three.blocks.select(:id).map(&:id)\n\n # Swap blocks from area 2 to 3\n Block.update_all({:box_id=>box_area_three.id}, [\"id IN (?)\", blocks_ids_from_area_two])\n\n # Swap blocks from area 3 to 2\n Block.update_all({:box_id=>box_area_two.id}, [\"id IN (?)\", blocks_ids_from_area_three])\n end\nend\n"
},
{
"alpha_fraction": 0.6446384191513062,
"alphanum_fraction": 0.6465087532997131,
"avg_line_length": 28.703702926635742,
"blob_id": "70d23926aac44e33e645d86f8d8bd2d0e9bdb71e",
"content_id": "e86f18b7fac52adf67e1901e0414727ecdd85f4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1604,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 54,
"path": "/src/noosfero-spb/spb_migrations/db/migrate/20150909191415_add_wiki_block_to_all_softwares_communities.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddWikiBlockToAllSoftwaresCommunities < ActiveRecord::Migration\n def up\n software_template = Community[\"software\"]\n\n if software_template\n software_area_two = software_template.boxes.find_by_position 2\n\n wiki_block_template = WikiBlock.new :mirror => true, :move_modes => \"none\", :edit_modes => \"none\"\n wiki_block_template.settings[:fixed] = true\n wiki_block_template.save!\n print \".\"\n\n software_area_two.blocks << wiki_block_template\n software_area_two.save!\n print \".\"\n\n # Puts the ratings block as the last one on area one\n repository_block = software_area_two.blocks.find_by_type(\"RepositoryBlock\")\n if !repository_block.nil?\n wiki_block_template.position = repository_block.position + 1\n wiki_block_template.save!\n print \".\"\n end\n end\n\n Community.joins(:software_info).each do |software_community|\n software_area_two = software_community.boxes.find_by_position 2\n print \".\"\n\n wiki_block = WikiBlock.new :move_modes => \"none\", :edit_modes => \"none\"\n wiki_block.settings[:fixed] = true\n wiki_block.mirror_block_id = wiki_block_template.id\n wiki_block.save!\n print \".\"\n\n software_area_two.blocks << wiki_block\n software_area_two.save!\n print \".\"\n\n repository_block = software_area_two.blocks.find_by_type(\"RepositoryBlock\")\n if !repository_block.nil?\n wiki_block.position = repository_block.position\n wiki_block.save!\n print \".\"\n end\n end\n\n puts \"\"\n end\n\n def down\n say \"This can't be reverted\"\n end\nend\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 10,
"blob_id": "73e4a1c8ff38766c8032dbdc06526b43dc29bdd6",
"content_id": "7438822d4d97c3d7f0cf6320d617ac92a92a142b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 33,
"license_type": "no_license",
"max_line_length": 15,
"num_lines": 3,
"path": "/tasks/env.rake",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "task :env do\n puts $SPB_ENV\nend\n"
},
{
"alpha_fraction": 0.6808943152427673,
"alphanum_fraction": 0.6869918704032898,
"avg_line_length": 31.799999237060547,
"blob_id": "0cde85c44f06487e226bf2b561867c38589d72be",
"content_id": "716de630e26ed80f57c88fe78ba90422f4e696f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 492,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 15,
"path": "/cookbooks/postgresql/recipes/noosfero.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "execute 'createuser:noosfero' do\n command 'createuser noosfero'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(*) from pg_user where usename = 'noosfero';\"`.strip.to_i == 0\n end\nend\n\nexecute 'createdb:noosfero' do\n command 'createdb --owner=noosfero noosfero'\n user 'postgres'\n only_if do\n `sudo -u postgres -i psql --quiet --tuples-only -c \"select count(1) from pg_database where datname = 'noosfero';\"`.strip.to_i == 0\n end\nend\n"
},
{
"alpha_fraction": 0.7310215830802917,
"alphanum_fraction": 0.7310215830802917,
"avg_line_length": 38.51852035522461,
"blob_id": "68d660350936b6a40d03ecce6f31ef660f22ccd3",
"content_id": "70ecf88c7b07d667f72bee463fe8f53c53a87952",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1067,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 27,
"path": "/src/noosfero-spb/gov_user/db/migrate/20140617125143_add_new_fields_institution.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "class AddNewFieldsInstitution < ActiveRecord::Migration\n def up\n add_column :institutions, :acronym, :string\n add_column :institutions, :unit_code, :integer\n add_column :institutions, :parent_code, :integer\n add_column :institutions, :unit_type, :string\n add_column :institutions, :juridical_nature, :string\n add_column :institutions, :sub_juridical_nature, :string\n add_column :institutions, :normalization_level, :string\n add_column :institutions, :version, :string\n add_column :institutions, :cnpj, :string\n add_column :institutions, :type, :string\n end\n\n def down\n remove_column :institutions, :acronym\n remove_column :institutions, :unit_code\n remove_column :institutions, :parent_code\n remove_column :institutions, :unit_type\n remove_column :institutions, :juridical_nature\n remove_column :institutions, :sub_juridical_nature\n remove_column :institutions, :normalization_level\n remove_column :institutions, :version\n remove_column :institutions, :cnpj\n remove_column :institutions, :type\n end\nend\n"
},
{
"alpha_fraction": 0.7113792896270752,
"alphanum_fraction": 0.7200000286102295,
"avg_line_length": 26.10280418395996,
"blob_id": "9eadadeaaca74e3e9c45ebeb1494f268290c88cc",
"content_id": "72520c0791b1a7b70c2f88add31869902bad4347",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2901,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 107,
"path": "/README.chef.md",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# Software Público - configuration management\n\n## Requirements\n\n* [chake](https://rubygems.org/gems/chake). Version 0.13 or greater\n* [rake](https://rubygems.org/gems/rake)\n* python-sphinx\n\nFor development\n\n* vagrant\n* shunit2\n* moreutils\n* redir\n\n## Configuration parameters\n\nAll configuration parameters are defined in `nodes.yaml`, with exception of IP\naddresses and ssh configuration, which are defined in different files.\nEach environment are defined on `config/<ENV>/*` and to deploy\nyou're need to use the `SPB_ENV` variable. The environment\n`local` is defined by default. The files to configure a new env are:\n\n- **config.yaml**: any configuration used for the specific environment.\n- **ips.yaml**: the IP of each node.\n- **ssh_config**: used to login into the machine with the\ncommand `rake login:$server`.\n- **iptables-filter-rules**: any iptables configuration needed\nto the environment.\n\nIf you need to do any changes on the IPs addresses, make sure\nthat the ips.yaml are configure for the right environment.\nYou will probably not need to change nodes.yaml unless you are\ndeveloping the deployment process.\n\n## Deploy\n\n### Development\n\nFirst you have to bring up the development virtual machines:\n\n```bash\n$ vagrant up\n$ rake preconfig\n$ rake bootstrap_common\n```\n\n```\nWARNING: Right now there are 7 VM's: six of them with 512MB of\n RAM and one with 1GB of RAM. Make sure that your local machine\n can handle this environment. Also, this might take a while.\n```\n\nThe basic commands for deployment:\n```bash\n$ rake # deploys all servers\n$ rake nodes # lists all servers\n$ rake converge:$server # deploys only $server\n```\n\n### Production\n\n* TODO: document adding the SSL key and certificate\n* TODO: document creation of `prod.yaml`.\n* TODO: document SSH configuration\n\nThe very first step is\n\n```\n$ rake preconfig SPB_ENV=production\n```\n\nThis will perform some initial configuration to the system that is required\nbefore doing the actual deployment. This command should only be\nrunned **one** time.\n\nAfter that:\n\n```bash\n$ rake SPB_ENV=production # deploys all servers\n$ rake nodes SPB_ENV=production # lists all servers\n$ rake converge:$server SPB_ENV=production # deploys only $server\n```\n\nYou can also do `export SPB_ENV=production` in your shell and\nomit it in the `rake` calls.\n\nSee the output of `rake -T` for other tasks.\n\n## Viewing the running site when developping locally\n\nRun:\n\n```bash\n./server\n```\n\nFollow the on-screen instructions an browse to\n[http://softwarepublico.dev/](http://softwarepublico.dev/).\n\nNote: this requires that your system will resolve `\\*.dev` to `localhost`.\nGoogle DNS servers will do that automatically, otherwise you might add the following entries to `/etc/hosts`:\n\n```\n127.0.53.53 softwarepublico.dev\n127.0.53.53 listas.softwarepublico.dev\n```\n"
},
{
"alpha_fraction": 0.6230769157409668,
"alphanum_fraction": 0.6246153712272644,
"avg_line_length": 22.214284896850586,
"blob_id": "7105fe60c9cb8e9a895bb0c08d6b12c086c399b4",
"content_id": "4521aff7cb6ba8012f71a4ce6385bb1105cb1e29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 650,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 28,
"path": "/src/noosfero-spb/gov_user/public/views/gov-user-comments-extra-fields.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\nmodulejs.define(\"GovUserCommentsExtraFields\", ['jquery','CreateInstitution'], function($,CreateInstitution) {\n\n function set_events() {\n CreateInstitution.institution_autocomplete();\n }\n\n\n function prepend_to_additional_information() {\n var institution_comments = $(\"#input_institution_comments\").remove();\n\n $(\".comments-software-extra-fields\").prepend(institution_comments);\n }\n\n\n return {\n isCurrentPage: function() {\n return $(\".star-rate-form\").length === 1;\n },\n\n init: function() {\n prepend_to_additional_information();\n set_events();\n }\n }\n\n})\n"
},
{
"alpha_fraction": 0.6082949042320251,
"alphanum_fraction": 0.6082949042320251,
"avg_line_length": 15.692307472229004,
"blob_id": "1729d5006570780b1c5495d1e03995dd0d9b840c",
"content_id": "c21cf21f79ffb24e9039ef14cf60ada8c288ede8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 217,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 13,
"path": "/src/noosfero-spb/gov_user/public/app.js",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "/* globals modulejs */\n\n(function() {\n 'use strict';\n\n var $ = modulejs.require('jquery');\n var Initializer = modulejs.require('Initializer');\n\n\n $(document).ready(function() {\n Initializer.init();\n });\n})();\n"
},
{
"alpha_fraction": 0.6661016941070557,
"alphanum_fraction": 0.6661016941070557,
"avg_line_length": 25.81818199157715,
"blob_id": "1e332ea7ceb1761e6c1d0cb03dd2b59fb68da1bd",
"content_id": "6d9f0526fb9494884ee6b3b7a3972a9292749b26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1180,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 44,
"path": "/src/noosfero-spb/software_communities/controllers/software_communities_plugin_controller.rb",
"repo_name": "alvarofernandoms/softwarepublico",
"src_encoding": "UTF-8",
"text": "# apenas software\nrequire 'csv'\nclass SoftwareCommunitiesPluginController < ApplicationController\n\n def get_license_data\n return render :json=>{} if !request.xhr? || params[:query].nil?\n\n data = SoftwareCommunitiesPlugin::LicenseHelper.find_licenses(params[:query]) if params[:query]\n data ||= SoftwareCommunitiesPlugin::LicenseInfo.all\n\n render :json=> data.collect { |license|\n {:id=>license.id, :label=>license.version}\n }\n\n end\n\n def get_field_data\n condition = !request.xhr? || params[:query].nil? || params[:field].nil?\n return render :json=>{} if condition\n\n model = get_model_by_params_field\n\n data = model.where(\"name ILIKE ?\", \"%#{params[:query]}%\").select(\"id, name\")\n .collect { |db|\n {:id=>db.id, :label=>db.name}\n }\n\n other = [model.select(\"id, name\").last].collect { |db|\n {:id=>db.id, :label=>db.name}\n }\n\n # Always has other in the list\n data |= other\n\n render :json=> data\n end\n\n protected\n\n def get_model_by_params_field\n return SoftwareCommunitiesPlugin::DatabaseDescription unless params[:field] == \"software_language\"\n return SoftwareCommunitiesPlugin::ProgrammingLanguage\n end\nend\n"
}
] | 261 |
wordwarrior01/MultiFileReader | https://github.com/wordwarrior01/MultiFileReader | f7de7b6cfbf353497bcb3c2a377fdfd0d76f7671 | 0cd306586c937e59a460486f73a5044a99bea26e | 09f900c4bf85bef4f8a5aa05745ed712f2907b24 | refs/heads/master | 2021-09-13T15:06:53.119476 | 2018-05-01T14:07:41 | 2018-05-01T14:07:41 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5872262716293335,
"alphanum_fraction": 0.5905109643936157,
"avg_line_length": 29.120878219604492,
"blob_id": "967c3c7f92ae76bc2fe4137623878398f3ffbe4e",
"content_id": "5ba8235920146befcf6d54eeaf0d9f4a5e5d5ab9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2740,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 91,
"path": "/modules/utils.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Utils \n#\n# Basic Utilities File\n#\n\n# required libraries\nimport logging\nimport os \n\nclass Utils():\n\n # Function to process the string to boolean \n \n @staticmethod\n def str_to_bool(string_val):\n\n logging.debug(\"str_to_bool received string: %s\"%string_val)\n\n if not string_val or not isinstance(string_val, basestring):\n logging.debug(\"returning None as string_val is not provided or is incorrect\")\n return None\n\n string_val = string_val.capitalize()\n\n if string_val == \"True\":\n logging.debug(\"returning boolean True\")\n return True \n elif string_val == \"False\":\n logging.debug(\"returning boolean False\")\n return False\n else:\n logging.debug(\"returning as is as string_val cannot be processed\")\n return string_val\n\n # Function to get the file extension \n\n @staticmethod \n def get_file_type(file_name):\n\n if not file_name:\n logging.debug(\"returning None as file_name is not provided\")\n return None\n \n file_ext = os.path.splitext(file_name)[1]\n logging.debug(\"returning File extension: %s\"%file_ext)\n return file_ext\n\n # Function to create output directory if missing\n\n @staticmethod \n def create_output_directory(file_name):\n \n if not file_name:\n return None\n\n file_dir = os.path.dirname(file_name)\n if not os.path.exists(file_dir):\n logging.debug(\"Creating the output directory\")\n os.makedirs(file_dir)\n logging.debug(\"Output directory already present\")\n return True\n\n # Function to get the absolute paths relative to the current working directory \n \n @staticmethod\n def get_absolute_path(input_file_name,output_file_name,curr_working_dir=os.getcwd()):\n \n root = curr_working_dir\n\n if input_file_name:\n if not input_file_name.startswith(\"data\"):\n input_file_name = os.path.join(root,\"data\",input_file_name)\n else:\n input_file_name = os.path.join(root,input_file_name)\n input_file_name = input_file_name.replace('\\\\',\"/\") # as we are on linux-ubuntu \n \n if output_file_name:\n if not output_file_name.startswith(\"results\"):\n output_file_name = os.path.join(root,\"results\",output_file_name)\n else:\n output_file_name = os.path.join(root,output_file_name)\n output_file_name\n output_file_name = output_file_name.replace('\\\\',\"/\") # as we are on linux-ubuntu \n \n return input_file_name, output_file_name"
},
{
"alpha_fraction": 0.6888769268989563,
"alphanum_fraction": 0.6953250765800476,
"avg_line_length": 30.03333282470703,
"blob_id": "fbe6ccc9f7ce33d812e84ae5edcb593f0e59ff37",
"content_id": "cd5ad79db083300e1188317802feee6bedab6d0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1861,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 60,
"path": "/modules/utils_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Utils Unit Test \n#\n\nfrom utils import Utils \nimport os \n\n# Test the str_to_bool function\n\ndef test_str_to_bool_with_no_args():\n\tassert(Utils.str_to_bool(None) == None)\n\tassert(Utils.str_to_bool(\"\") == None)\n\ndef test_str_to_bool_with_incorrect_args():\n\tassert(Utils.str_to_bool(\"Test\") == \"Test\")\n\ndef test_str_to_bool_with_incorrect_args_type():\n\tassert(Utils.str_to_bool(1) == None)\n\ndef test_get_file_type_with_no_args():\n\tassert(Utils.get_file_type(None) == None)\n\tassert(Utils.get_file_type(\"\") == None)\n\ndef test_get_file_type_with_no_file_ext():\n\tassert(Utils.get_file_type(\"Test\") == \"\")\n\ndef test_get_file_type_with_file_ext():\n\tassert(Utils.get_file_type(\"Test.txt\") == \".txt\")\n\tassert(Utils.get_file_type(\"Test/Test.txt\") == \".txt\")\n\ndef test_create_output_directory_with_no_args():\n\tassert(Utils.create_output_directory(None) == None)\n\ndef test_create_output_directory_with_no_existing_dir():\n\tassert(Utils.create_output_directory(\"data/data1/test.txt\") == True)\n\ndef test_create_output_directory_with_existing_dir():\n\tassert(Utils.create_output_directory(\"data/data1/test.txt\") == True)\n\tos.rmdir(os.path.join(os.getcwd(),\"data/data1\"))\n\ndef test_get_absolute_path_with_no_args():\n\tassert(Utils.get_absolute_path(None,None) == (None,None))\n\ndef test_get_absolute_path_with_input_args():\n\tassert(Utils.get_absolute_path(\"\",None) == (\"\",None))\n\ndef test_get_absolute_path_with_input_file():\n\tpath = os.path.join(os.getcwd(),\"data\",\"test.xml\")\n\tassert(Utils.get_absolute_path(\"test.xml\",None) == (path,None))\n\tassert(Utils.get_absolute_path(\"data/test.xml\",None) == (path,None))\n\ndef test_get_absolute_path_with_output_file():\n\tpath = os.path.join(os.getcwd(),\"results\",\"test.xml\")\n\tassert(Utils.get_absolute_path(None,\"test.xml\") == (None,path))\n\tassert(Utils.get_absolute_path(None,\"results/test.xml\") == (None,path))"
},
{
"alpha_fraction": 0.5241025686264038,
"alphanum_fraction": 0.5384615659713745,
"avg_line_length": 18.13725471496582,
"blob_id": "7a82df77c42a6ed0872befe9b61db6a4af23f5b3",
"content_id": "bba84ce2ff7be33a198e95d86e8693f3e7878766",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 975,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 51,
"path": "/modules/csv_parser.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# CSV Parser \n#\n\nrequire_once(\"./modules/utils.php\");\nrequire_once(\"./modules/parser.php\");\n\nclass CsvParser extends Parser {\n\n # initialize the instance variables\n function __construct($inputFile){\n \n # call the base class constructor\n parent::__construct($inputFile);\n echo(\"Csv parser initialized\\n\");\n }\n \n # parse the file using a csv parser \n public function parseFile(){\n\n $fp = fopen($this->inputFile,\"r\");\n\n $this->data = array();\n\n while (!feof($fp)) {\n\n $lineArray = fgetcsv($fp);\n\n # create an associative array from the line \n # name,active,value\n # John,true,500\n\n $dict = array(\"name\" => $lineArray[0], \"active\" => Utils::strToBool($lineArray[1]), \"value\" => (int)$lineArray[2]);\n array_push($this->data, $dict);\n\n }\n\n fclose($fp);\n # var_dump($this->data);\n }\n\n}\n\n?>"
},
{
"alpha_fraction": 0.573680579662323,
"alphanum_fraction": 0.5915010571479797,
"avg_line_length": 16.80487823486328,
"blob_id": "28a3af434e2eec523677a571a4e1db9e85cba899",
"content_id": "7df077718c10be99cb109fcf2858892f17d21995",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1459,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 82,
"path": "/modules/csv_parser_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Csv Parser - Class Tests \n#\n\nfrom csv_parser import CsvParser\nimport os\n\ntest_file = os.path.join(os.getcwd(),\"Test.csv\")\n\ndef test_csv_parser_with_missing_values():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"name,active,value\nJohn,true,\nMark,true,\nPaul,false,100\nBen,true,150\n\"\"\")\n\n y = CsvParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 150)\n\ndef test_csv_parser_with_non_csv_values():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"name,active,value\nJohn true \nMark true \nPaul false 100\nBen true 150\n\"\"\")\n\n y = CsvParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_csv_parser_with_blank_file():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\")\n\n y = CsvParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_csv_parser_with_no_child_nodes():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"name,active,value\"\"\")\n\n y = CsvParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\n # delete the test file as not required \n os.remove(test_file)"
},
{
"alpha_fraction": 0.6318840384483337,
"alphanum_fraction": 0.6550724506378174,
"avg_line_length": 17.210525512695312,
"blob_id": "e6dc9de1e31230d12dffb92843f2bb7f18b0e39e",
"content_id": "79bcfac7e547f1942781fcd22cc77a3f8c1f36d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 345,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 19,
"path": "/modules/file_handler_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n# required libraries\nfrom file_handler import FileHandler\n\n# File Hander\n# This module will handle all the file handling operations \n\ndef test_file_handler_non_std_file_types():\n\n try:\n fh = FileHandler(\"Data/Test.psv\")\n fh.process_file()\n assert(False)\n except IOError:\n assert(True)"
},
{
"alpha_fraction": 0.6213171482086182,
"alphanum_fraction": 0.6288272738456726,
"avg_line_length": 22.557823181152344,
"blob_id": "0b3d7ac3f7c81c06246c660df9143c83a56ba24d",
"content_id": "784b2606f2ec0bd212bfa0ad67b84538f16e06c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3462,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 147,
"path": "/modules/utils_test.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 05-07-2017\n#\n\n# Test Project to test the code base \n# Functional Test cases\n\n# Note: Developed using PHP 7.0.18-0ubuntu0.16.04.1 (cli) ( NTS )\n\nrequire_once(\"./modules/utils.php\");\n\nclass UtilsTest extends PHPUnit_Framework_TestCase\n{\n # Tests \n\n public function teststrToBoolWithNull() {\n\n $retVal = Utils::strToBool(Null);\n $this->assertEquals($retVal, false);\n\n }\n\n public function teststrToBoolWithStringDataType() {\n\n $retVal = Utils::strToBool(\"Nimish\");\n $this->assertEquals($retVal, false);\n\n }\n\n public function teststrToBoolWithIntegerDataType() {\n\n $retVal = Utils::strToBool(9);\n $this->assertEquals($retVal, false);\n\n }\n\n public function testJoinPathsWithNull() {\n\n $retVal = Utils::joinPaths(Null);\n $this->assertEquals($retVal, '');\n\n }\n\n public function testJoinPathsWithMultipleNulls() {\n\n $retVal = Utils::joinPaths(Null,Null);\n $this->assertEquals($retVal, '/');\n\n }\n\n public function testJoinPathsWithWrongDataType() {\n\n $retVal = Utils::joinPaths(8,6,7);\n $this->assertEquals($retVal, '8/6/7');\n\n }\n\n public function testgetAbsolutePathWithOnlyInput() {\n\n $retVal = Utils::getAbsolutePath('test.csv',Null);\n $checkVal = array(Utils::joinPaths(getcwd(),'data','test.csv'),Null);\n $this->assertEquals($retVal, $checkVal);\n\n }\n\n public function testgetAbsolutePathWithNull() {\n\n $retVal = Utils::getAbsolutePath(Null,Null,Null);\n $checkVal = array(Utils::joinPaths(getcwd(),'data/'),Null);\n $this->assertEquals($retVal, $checkVal);\n\n }\n\n public function testgetAbsolutePathWithDifferentCwd() {\n\n $retVal = Utils::getAbsolutePath('test.csv',Null,'C:');\n $checkVal = array('C:/data/test.csv',Null);\n $this->assertEquals($retVal, $checkVal);\n\n }\n\n public function testgetFileExtensionOfNull() {\n\n $retVal = Utils::getFileExtension(Null);\n $this->assertEquals($retVal, Null);\n\n }\n\n public function testgetFileExtensionOfDirectory() {\n \n $retVal = Utils::getFileExtension(\"C:/Data\");\n $this->assertEquals($retVal, '');\n\n }\n\n public function testcreateOutputDirectoryIfNull() {\n \n $retVal = Utils::createOutputDirectory(Null);\n $this->assertEquals($retVal, false);\n\n }\n\n private function deleteTestDir() {\n\n $testDir = Utils::joinPaths(getcwd(),'testdata','testdir');\n Utils::deleteDirectory($testDir);\n\n }\n\n public function testcreateOutputDirectoryNewDir() {\n\n $checkVal = Utils::joinPaths(getcwd(),'testdata','testdir','test.csv');\n $retVal = Utils::createOutputDirectory($checkVal);\n $this->assertEquals($retVal, true);\n\n }\n\n public function testcreateOutputDirectoryOfExistingDir() {\n\n $checkVal = Utils::joinPaths(getcwd(),'testdata','testdir','test.csv');\n $retVal = Utils::createOutputDirectory($checkVal);\n $this->deleteTestDir();\n $this->assertEquals($retVal, false);\n\n }\n\n public function testdeleteDirectoryNonExistentDir() {\n\n $checkVal = Utils::joinPaths(getcwd(),'testdata','testdir');\n $retVal = Utils::deleteDirectory($checkVal);\n $this->assertEquals($retVal, false);\n\n }\n\n public function testdeleteDirectoryNull() {\n\n $retVal = Utils::deleteDirectory(Null);\n $this->assertEquals($retVal, false);\n\n }\n \n}\n\n?>"
},
{
"alpha_fraction": 0.5078125,
"alphanum_fraction": 0.525390625,
"avg_line_length": 15.54838752746582,
"blob_id": "6878c5f26886157734066dfd4daccd87bcb3d4e2",
"content_id": "8f083ecee27a953af145fd6f640a07a18b183bb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 512,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 31,
"path": "/modules/parser_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Parser - Base Class Tests \n#\n\nfrom parser import Parser\n\ndef test_parser_if_abstract():\n try:\n p = Parser()\n assert(False)\n except TypeError:\n assert(True) \n\ndef test_parser_process_file_function():\n \n class B(Parser):\n def parse_file(self):\n pass\n\n try: \n B = B(\"test\")\n B.process_file()\n assert(isinstance(B.get_value(), int))\n assert(B.get_value() == 0)\n except:\n assert(False)"
},
{
"alpha_fraction": 0.563259482383728,
"alphanum_fraction": 0.5761258006095886,
"avg_line_length": 16.94871711730957,
"blob_id": "63e765430ce4fcd3d6503bc9a5d6e40f230ff277",
"content_id": "367e219e7b75cfb229347c9025834be30dcdf768",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1399,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 78,
"path": "/modules/yml_parser_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Yml Parser - Class Tests \n#\n\nfrom yml_parser import YmlParser\nimport os\n\ntest_file = os.path.join(os.getcwd(),\"Test.yml\")\n\ndef test_yml_parser_with_missing_values():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"users:\n - name: Paul\n active: false\n value: 100\n - name: Ben\n active: true\"\"\")\n\n y = YmlParser(test_file)\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_yml_parser_with_malformed_yml():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"users:\n - name Paul\n active false\n value 100\n - name: Ben\n active: true\"\"\")\n\n y = YmlParser(test_file)\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_yml_parser_with_blank_file():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\")\n\n y = YmlParser(test_file)\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_yml_parser_with_just_headers():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"users:\")\n\n y = YmlParser(test_file)\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\n # delete the test file as not required \n os.remove(test_file)"
},
{
"alpha_fraction": 0.5251346230506897,
"alphanum_fraction": 0.5287253260612488,
"avg_line_length": 24.918603897094727,
"blob_id": "51a78aec1ea8824000d36f16ee2ba8c6d4d2c66a",
"content_id": "98d911dc741097533a0ec867e36e547d5614bb66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2228,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 86,
"path": "/modules/file_handler.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# FileHandler \n#\n\nrequire_once(\"./modules/utils.php\");\n\n# File Hander\n# This module will handle all the file handling operations \n\nclass FileHandler {\n\n # initialize the instance variables\n function __construct($inputFile, $outputFile) {\n \n $this->inputFile = $inputFile;\n $this->outputFile = $outputFile;\n echo(\"File Hander initialized\\n\");\n\n }\n\n # process the input file \n public function processFile() {\n\n $ext = Utils::getFileExtension($this->inputFile); \n\n # composition: load the appropriate parser\n # get the tuple of dictionaries for all the users in the data file\n switch($ext){\n\n case \"csv\":\n echo(\"parsing the csv file\\n\");\n require_once(\"./modules/csv_parser.php\");\n $parser = new CsvParser($this->inputFile);\n break;\n\n case \"yml\":\n echo(\"parsing the yml file\\n\");\n require_once(\"./modules/yml_parser.php\");\n $parser = new YmlParser($this->inputFile);\n break;\n\n case \"xml\":\n echo(\"parsing the xml file\\n\");\n require_once(\"./modules/xml_parser.php\");\n $parser = new XmlParser($this->inputFile);\n break;\n\n default:\n echo(\"file type not supported\\n\");\n return null;\n }\n\n # read file contents \n $parser->parseFile();\n # process file contents based on certain criteria \n $parser->processFile();\n # return parsed value\n $this->data = $parser->getValue(); \n \n }\n\n # write the output if available else print \n public function writeOutput() {\n\n if($this->outputFile != null) {\n Utils::createOutputDirectory($this->outputFile);\n echo(\"Writing output to the file\\n\");\n $file = fopen($this->outputFile,\"w\");\n var_dump($this->data);\n fwrite($file,$this->data);\n fclose($file);\n }\n else\n printf(\"Writing output to stdout as output file name not provided\\n%s\\n\",$this->data); \n }\n\n}\n\n?>"
},
{
"alpha_fraction": 0.6541062593460083,
"alphanum_fraction": 0.6608695387840271,
"avg_line_length": 31.873016357421875,
"blob_id": "1fdcd68b4bba94e2737afc668afca98b404e785e",
"content_id": "11369bde299b75d0b8897244f4436248800e9e44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2070,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 63,
"path": "/main.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n# Create a command line tool \n# which reads data from a file (csv, yml, xml), but they contain the same data \n# performs simple operation on this data \n# stores or prints a result. The result could be stored in a plain text file or printed on stdout \n\n# Note: Developed using Python 2.7.13\n\n# required libraries\nimport logging\nimport os \nfrom optparse import OptionParser\nfrom modules import file_handler\nfrom modules.utils import Utils\n\n# main function \nif __name__ == \"__main__\":\n \n # initialize the logger\n file_name = os.path.basename(__file__).strip().replace(\".py\",\".log\")\n\n # Note: Logging Level -> Production - INFO, Development - DEBUG\n logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', filename=file_name, level=logging.DEBUG, datefmt='%Y-%m-%d %I:%M:%S %p')\n \n # Set the CL options \n parser = OptionParser()\n usage = \"usage: %prog [options] arg1 arg2\"\n\n parser.add_option(\"-i\", \"--input\", type=\"string\",\n help=\"absolute path of the input file name with file extension\", \n dest=\"input_file\")\n\n parser.add_option(\"-o\", \"--output\", type=\"string\",\n help=\"absolute path of the output file name with file extension\", \n dest=\"output_file\")\n\n options, arguments = parser.parse_args()\n\n logging.info('Application Started')\n\n # Raise an error if the input file is missing\n if not options.input_file:\n raise ValueError(\"The input file is missing\")\n\n # Debug Statements\n logging.debug(\"Input File %s\"%options.input_file)\n logging.debug(\"Output File %s\"%options.output_file)\n logging.debug(\"Arguments: %s\"%arguments)\n\n input_file, output_file = Utils.get_absolute_path(options.input_file,options.output_file,os.getcwd())\n\n logging.debug(\"Absolute Input File %s\"%input_file)\n logging.debug(\"Absolute Output File %s\"%output_file)\n \n fh = file_handler.FileHandler(input_file, output_file)\n fh.process_file()\n fh.write_output()\n\n logging.info('Application Finished')"
},
{
"alpha_fraction": 0.553307831287384,
"alphanum_fraction": 0.5626025199890137,
"avg_line_length": 21.317073822021484,
"blob_id": "e89e155a5177af935f65bb0c59b549e62ad3441e",
"content_id": "1afdf13f942f0aa49fc84bd86f7df23f09f161b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1831,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 82,
"path": "/modules/xml_parser.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# XML Parser \n#\n\n# Note: To get the XML Module - \n\n# Since PHP 7 is not in the official Ubuntu PPAs, installed it through Ondřej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). \n\n# uncomment the following line in /etc/php/7.0/fpm/php.ini\n# extension=php_xmlrpc.dll\n\n# and install php7.0-xml:\n# sudo apt-get install php7.0-xml\n\n# restart PHP:\n# sudo service php7.0-fpm restart\n\n# required libraries\nrequire_once(\"./modules/utils.php\");\nrequire_once(\"./modules/parser.php\");\n\nclass XmlParser extends Parser {\n\n # initialize the instance variables\n function __construct($inputFile){\n \n # call the base class constructor\n parent::__construct($inputFile);\n echo(\"Xml parser initialized\\n\");\n }\n\n # load the file using an xml parser\n private function loadFile(){\n\n # read the whole file into a string\n $myXMLData = file_get_contents($this->inputFile);\n\n # string -> xml\n $this->doc = simplexml_load_string($myXMLData);\n \n # Debug \n # var_dump($this->doc);\n\n if ($this->doc === false) {\n echo \"Failed loading XML:\\n\";\n foreach(libxml_get_errors() as $error) {\n echo $error->message, \"\\n\";\n }\n }\n }\n \n # parse the file using a xml parser \n public function parseFile() {\n\n $this->loadFile();\n\n if ($this->doc->user) {\n\n # we have xml data!\n # parse and create an associative array from it\n $this->data = array();\n\n foreach ($this->doc->user as $user) {\n\n $dict = array('name' => $user->name, 'active' => Utils::strToBool($user->active), 'value' => (int)$user->value);\n array_push($this->data, $dict);\n\n }\n\n }\n\n }\n}\n\n?>"
},
{
"alpha_fraction": 0.6372007131576538,
"alphanum_fraction": 0.6519337296485901,
"avg_line_length": 18.428571701049805,
"blob_id": "afa8d5b34cda2aaeb8a1800a0c157743eccda9c6",
"content_id": "be216738d6bdf3648156e2b6999fab32953fda15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 543,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 28,
"path": "/modules/yml_parser.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# YAML Parser \n#\n\n# required libraries\nimport logging\nimport yaml\nfrom parser import Parser \n\nclass YmlParser(Parser):\n\n # initialize the instance variables\n def __init__(self, input_file):\n \t# call the base class constructor\n \tParser.__init__(self, input_file)\n logging.debug(\"Yml parser initialized\")\n\n # parse the file using a xml parser \n def parse_file(self):\n\t\twith open(self.input_file, \"r\") as f:\n\t\t\tdata = yaml.load(f)\n\t\t\tif data and \"users\" in data:\n\t\t\t\tself.data = data[\"users\"]"
},
{
"alpha_fraction": 0.4876595735549927,
"alphanum_fraction": 0.494468092918396,
"avg_line_length": 20,
"blob_id": "38d839f5348f1be015f8cff31ecd8928741b1d3e",
"content_id": "629f2c7c72deb1157eafd48a67a39be2041888f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1175,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 56,
"path": "/modules/yml_parser.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# YAML Parser \n#\n\n# required libraries\nrequire_once(\"./modules/parser.php\");\nrequire_once(\"./modules/yaml/lib/sfYaml.php\");\n \nclass YmlParser extends Parser {\n\n # initialize the instance variables\n function __construct($inputFile){\n \n # call the base class constructor\n parent::__construct($inputFile);\n echo(\"Yml parser initialized\\n\");\n }\n\n # parse the file using a xml parser \n public function parseFile(){\n\n try {\n \n $this->doc = sfYaml::load($this->inputFile);\n\n #var_dump($this->doc);\n\n if ($this->doc['users']) {\n\n # we have yml data!\n # parse and create an associative array from it\n $this->data = array();\n\n foreach ($this->doc['users'] as $user) {\n\n $dict = array('name' => $user['name'], 'active' => Utils::strToBool($user['active']), 'value' => (int)$user['value']);\n array_push($this->data, $dict);\n\n }\n }\n }\n catch (Exception $e) {\n echo($e->getMessage());\n }\n }\n\n}\n\n?>"
},
{
"alpha_fraction": 0.5849462151527405,
"alphanum_fraction": 0.6057347655296326,
"avg_line_length": 27.489795684814453,
"blob_id": "7bdf792e311e2c94078a2777f06557d319e00fc8",
"content_id": "e8acb87b764a546e32096b28f3b0cfd1ee1661bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1395,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 49,
"path": "/modules/xml_parser_test.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 05-07-2017\n#\n\n# Test Project to test the code base \n# Functional Test cases\n\n# Note: Developed using PHP 7.0.18-0ubuntu0.16.04.1 (cli) ( NTS )\n\nrequire_once(\"./modules/xml_parser.php\");\nrequire_once(\"./modules/utils.php\");\n\nclass XmlParserTest extends PHPUnit_Framework_TestCase\n{\n # Tests \n\n public function testParser() {\n \n $testFile1 = Utils::joinPaths(getcwd(),\"testdata\",\"test_correct.xml\"); \n $this->xmlParser = new XmlParser($testFile1);\n # get the list of dictinary of the yml contents \n $this->xmlParser->parseFile();\n # process the value \n $this->xmlParser->processFile();\n # get the processed value from the parser as a string\n $this->data = $this->xmlParser->getValue(); \n $this->assertEquals($this->data, \"900\");\n\n }\n\n public function testParserWithIncorrectYaml() {\n \n $testFile2 = Utils::joinPaths(getcwd(),\"testdata\",\"test_incorrect.xml\"); \n $this->xmlParser = new XmlParser($testFile2);\n # get the list of dictinary of the yml contents \n $this->xmlParser->parseFile();\n # process the value \n $this->xmlParser->processFile();\n # get the processed value from the parser as a string\n $this->data = $this->xmlParser->getValue(); \n $this->assertEquals($this->data, 250);\n }\n\n}\n\n?>"
},
{
"alpha_fraction": 0.598499059677124,
"alphanum_fraction": 0.602251410484314,
"avg_line_length": 33.3870964050293,
"blob_id": "d24979d9b9958cbc50a928c10c15a89cbddcbd29",
"content_id": "7b5a3cf4f1b3b28d5e4ff685bf49808ea926f653",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2132,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 62,
"path": "/modules/file_handler.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n# required libraries\nimport logging\nimport os \nfrom utils import Utils\n\n# File Hander\n# This module will handle all the file handling operations \nclass FileHandler():\n\n # initialize the instance variables\n def __init__(self, input_file, output_file=None):\n self.input_file = input_file\n self.output_file = output_file\n logging.debug(\"File Hander initialized\")\n \n # process the input file \n def process_file(self):\n\n file_type = Utils.get_file_type(self.input_file) \n\n # composition: load the appropriate parser\n # get the tuple of dictionaries for all the users in the data file\n if file_type == \".csv\":\n logging.info(\"parsing the csv file\")\n from modules.csv_parser import CsvParser \n parser = CsvParser(self.input_file)\n elif file_type == \".yml\":\n logging.info(\"parsing the yml file\")\n from modules.yml_parser import YmlParser \n parser = YmlParser(self.input_file)\n elif file_type == \".xml\":\n logging.info(\"parsing the xml file\")\n from modules.xml_parser import XmlParser\n parser = XmlParser(self.input_file)\n else:\n # input file is not of the neessary order\n raise IOError(\"File format accepted are xml,csv and yml\") \n # load the xml file \n parser.load_file()\n # get the list of dictinary of the xml contents \n parser.parse_file()\n # process the value \n parser.process_file()\n # get the processed value from the parser as a string\n self.data = str(parser.get_value()) \n \n # write the output if available else print \n def write_output(self):\n\n if not self.output_file:\n logging.info(\"Writing output to stdout as output file name not provided\")\n print self.data \n else:\n Utils.create_output_directory(self.output_file)\n with open(self.output_file, 'w') as f:\n logging.info(\"Writing output to the file\")\n f.write(self.data)\n"
},
{
"alpha_fraction": 0.7328023314476013,
"alphanum_fraction": 0.7490948438644409,
"avg_line_length": 28.68817138671875,
"blob_id": "cd5c3add40f4bee0f59b9b3676b07519ec03da55",
"content_id": "7a69b5e73efbd404397cbc802f71a880369e0a94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2762,
"license_type": "no_license",
"max_line_length": 383,
"num_lines": 93,
"path": "/README.md",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "## Task\n\nThe aim is to create a command line tool which reads data from a file, performs simple operation on this data and stores or prints a result. Input files could have different format (csv, yml, xml), but they contain the same data. The result could be stored in a plain text file or printed on stdout. Please see the input files (located in data directory) to check the data structure.\n\n## Logic\n\nRun the tool from a command line and pass an input parameter and optional output parameter.\nInput parameter is a path to a file that should be processed.\nOutput parameter is an optional path to the output file.\nIf the output parameter is not provided the result should be printed to stdout.\n\nThe tool should parse the input file and output the result. The result is a simple sum of value property for every active entity.\n\n## Assumptions\n\nFile extension describes file type (*.csv, *.yml, *.xml).\nUser always has to pass 1 or 2 parameters - input and optionally output.\n\n## Example \n\n### Python\n\n** python main.py -i \"data/file.yml\" **\noutputs 900\n\nor \n\n** python main.py -i \"file.yml\" - o \"result.txt\" **\noutputs 900\n\nor\n\n** python main.py --input=\"data/file.xml\" --output=\"results/result.txt\" **\ncreates results/result.txt and puts a number 900 as a content\n\n### Php\n\n** php main.php --input=\"data/file.yml\" **\noutputs 900\n\nor \n\n** php main.php \"data/file.yml\" **\noutputs 900\n\nor\n\n** php main.php --input=\"data/file.yml\" --output=\"result.txt\" **\ncreates results/result.txt and puts a number 900 as a content\n\n## Testing \n\nTest cases are available in the Modules Folder along with other source code\nThe testing commands can be invoked from the Root Directory of the project \n\n### Python\n\nFor pytest you need to install pip and then do pip install pytest\nRun the test suite using the following command,\npytest\n\n### Php\n\nPhpUnit - a Unit testing module for php code base, to install use the following command on the terminal\nsudo apt-get install phpunit\n\nRun the test suite using the following command,\nphpunit -c testsuite.xml --testsuite MultiFileReaderTests\n\n## Setup \n\n### Python\n\nWindows\n\nInstall python 2.7.13 from https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tar.xz\nInstall Pytest from https://docs.pytest.org\n\nLinux \n\nPython comes installed by default with any linux distribution like Ubuntu.\n\n### Php\n\nLinux \n\nPhp 7.0 CLI - available in all the distributions, Use the following command\nsudo apt-get install php7.0\n\nXML Module - Since PHP 7 is not in the official Ubuntu PPAs, installed it through Ondřej Surý's PPA (sudo add-apt-repository ppa:ondrej/php). \nUncomment \"extension=php_xmlrpc.dll\" in /etc/php/7.0/fpm/php.ini\nand install php7.0-xml -> sudo apt-get install php7.0-xml\nfollowed by restarting PHP -> sudo service php7.0-fpm restart\n\n"
},
{
"alpha_fraction": 0.5529473423957825,
"alphanum_fraction": 0.5623369812965393,
"avg_line_length": 30.950000762939453,
"blob_id": "64113d7413e271f01bcfc22a9c2fe95f962a62be",
"content_id": "545002fb2dde86426a99193c2114b9d6ea06a656",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1917,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 60,
"path": "/modules/xml_parser.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# XML Parser \n#\n\n# required libraries\nimport logging\nimport xml.dom.minidom\nfrom parser import Parser\nfrom utils import Utils\n\nclass XmlParser(Parser):\n\n # initialize the instance variables\n def __init__(self, input_file):\n \t# call the base class constructor\n \tParser.__init__(self, input_file)\n logging.debug(\"Xml parser initialized\")\n\n # parse the file using a xml parser \n def load_file(self):\n # use the parse() function to load and parse an XML file\n try:\n self.doc = xml.dom.minidom.parse(self.input_file)\n except xml.parsers.expat.ExpatError as e:\n logging.info(e)\n self.doc = None\n\n # parse the file using a xml parser \n def parse_file(self):\n # get a list of XML tags from the document and create the list of dictionaries \n if self.doc:\n users = self.doc.getElementsByTagName(\"user\")\n logging.debug(\"%d users:\" % users.length)\n \n for user in users: \n \n # Default Value\n val = {\"name\":\"\",\"value\":0,\"active\":False}\n\n # get all the tag values \n name = user.getElementsByTagName(\"name\") \n value = user.getElementsByTagName(\"value\") \n active = user.getElementsByTagName(\"active\") \n\n if name and name[0] and name[0].firstChild:\n val[\"name\"] = str(name[0].firstChild.nodeValue)\n\n if active and active[0] and active[0].firstChild:\n val[\"active\"] = Utils.str_to_bool(active[0].firstChild.nodeValue)\n \n if value and value[0] and value[0].firstChild and val[\"active\"]:\n val[\"value\"] = int(value[0].firstChild.nodeValue)\n\n self.data.append(val)\n logging.debug(\"data saved: %s\"%self.data)\n"
},
{
"alpha_fraction": 0.6443019509315491,
"alphanum_fraction": 0.6581154465675354,
"avg_line_length": 20.795698165893555,
"blob_id": "e9cc8ca29ef1df0723f602fb510e341ac66be446",
"content_id": "c20069e347ae7a6eb836480f518cb881e0e4db73",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2027,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 93,
"path": "/main.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 05-07-2017\n#\n\n# Create a command line tool \n# which reads data from a file (csv, yml, xml), but they contain the same data \n# performs simple operation on this data \n# stores or prints a result. The result could be stored in a plain text file or printed on stdout \n\n# Note: Developed using PHP 7.0.18-0ubuntu0.16.04.1 (cli) ( NTS )\n\n# main invocation \nrequire_once(\"./modules/utils.php\");\nrequire_once(\"./modules/file_handler.php\");\n\necho 'Application Started', \"\\n\";\n\n# $ php script.php --input=\"data/file.xml\" --output=\"results/result.txt\"\n$longopts = array(\n \"input::\", // Optional value\n \"output::\" // Optional value\n);\n\n$params = getopt(\"\", $longopts);\n\n# no long options provided \nif(!count($params)) {\n\n\t# $ php script.php data/file.yml\n\tswitch($argc){\n\n\t\tcase 3:\n\t\t\t$output = $argv[2];\n\t\t\t$input = $argv[1];\n\t\t\tbreak;\n\t\t\n\t\tcase 2:\n\t\t\t$input = $argv[1];\n\t\t\t$output = null;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t$output = null;\n\t\t\t$input = null;\n\n\t}\n}\nelse {\n\n\t$input = $params['input'];\n\t$output = $params['output'];\n\n}\n\n# Debug\nprintf(\"Command Line Parameters %s\\n%s\\n\",$input,$output);\n\n# Raise an error if the input file is missing\n# if output file is provided, check if the file extension is there or not \nif (($input == null) || (($output != null) && (Utils::getFileExtension($output)==null))) {\n\n\techo \"input file name not provided\\n\";\n\texit(1);\n\n}\n\n# Check if file extension is provided or not\nif(Utils::getFileExtension($input)==null) {\n\techo \"no file extensions provded \\n\";\n\texit(1);\n}\n\n# Test\n# echo Utils::strToBool(\"Nimish\"\"\");\n# echo Utils::getFileExtension(\"Nimish.txt\");\n# echo Utils::createOutputDirectory(\"/home/nimish/Nimish.txt\");\n\n$ioParams = Utils::getAbsolutePath($input,$output);\n$inputFile = $ioParams[0];\n$outputFile = $ioParams[1];\n# Print Statement available in the class::function.\n# printf(\"Relative Paths %s\\n%s\\n\",$inputFile,$outputFile);\n\n$fh = new FileHandler($inputFile, $outputFile);\n$fh->processFile();\n$fh->writeOutput();\n\necho 'Application Finished', \"\\n\"\n\n?>\n"
},
{
"alpha_fraction": 0.5112033486366272,
"alphanum_fraction": 0.5253112316131592,
"avg_line_length": 26.409090042114258,
"blob_id": "cefa20c5ff114dea2c71d264cd0cdbd0c2c9522a",
"content_id": "2121f240ffb0ce979b6ef0a9ef5e404f319aa719",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1205,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 44,
"path": "/modules/csv_parser.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# CSV Parser \n#\n\n# required libraries\nimport logging\nimport csv\nfrom parser import Parser\nfrom utils import Utils\n\nclass CsvParser(Parser):\n\n # initialize the instance variables\n def __init__(self, input_file):\n # call the base class constructor\n Parser.__init__(self, input_file)\n logging.debug(\"Csv parser initialized\")\n\n # parse the file using a csv parser \n def parse_file(self):\n # get a list of CSV tags from the document and create the list of dictionaries \n with open(self.input_file, \"rb\") as f:\n users = [row for row in csv.reader(f)][1:] \n logging.debug(\"%d users:\" % len(users))\n for user in users:\n \n # default values \n val = {\"name\":\"\",\"active\":False,\"value\":0}\n \n # check if csv \n if len(user) == 3:\n if user[0]:\n val[\"name\"] = user[0]\n if user[1]:\n val[\"active\"] = Utils.str_to_bool(user[1])\n if user[2]:\n val[\"value\"] = int(user[2])\n self.data.append(val)\n logging.debug(\"data saved: %s\"%self.data)"
},
{
"alpha_fraction": 0.5362997651100159,
"alphanum_fraction": 0.5508196949958801,
"avg_line_length": 18.418182373046875,
"blob_id": "18dffd16d6896bd717d7557916689ba9929ae529",
"content_id": "a3db5e001ed26ddbc9d8a222c2053e7f984392cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2135,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 110,
"path": "/modules/xml_parser_test.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Xml Parser - Class Tests \n#\n\nfrom xml_parser import XmlParser\nimport os\n\ntest_file = os.path.join(os.getcwd(),\"Test.xml\")\n\ndef test_xml_parser_with_missing_values():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<users>\n <user>\n <name>John</name>\n <active>true</active>\n </user>\n <user>\n <name>Mark</name>\n <active>false</active>\n <value>250</value>\n </user>\n</users>\"\"\")\n\n y = XmlParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_xml_parser_with_malformed_xml():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<users>\n <user\n <name>John</name>\n <active>true</active>\n /user>\n <user>\n <name>Mark</name>\n active>false</active>\n <value>250</value\n </user>\n</users>\"\"\")\n\n y = XmlParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\n\ndef test_xml_parser_with_blank_file():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\")\n\n y = XmlParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_xml_parser_with_no_child_nodes():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<users>\"\"\")\n\n y = XmlParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\ndef test_xml_parser_with_xml_dtd():\n \n global test_file \n\n # value missing\n with open(test_file,\"w\")as f:\n f.write(\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\"\"\")\n\n y = XmlParser(test_file)\n y.load_file()\n y.parse_file()\n y.process_file()\n assert(y.get_value() == 0)\n\n # delete the test file as not required \n os.remove(test_file)"
},
{
"alpha_fraction": 0.5044013857841492,
"alphanum_fraction": 0.5123239159584045,
"avg_line_length": 20.05555534362793,
"blob_id": "0ddf238b77bd1268f61e0eca8de153d8e07a27e3",
"content_id": "6b95ecb0494bca55350080f0a3bcb6cb5e2041cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1136,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 54,
"path": "/modules/parser.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Parser - Base Class \n#\n \nabstract class Parser {\n\n # initialize the instance variables\n function __construct($inputFile) {\n $this->inputFile = $inputFile;\n $this->data = array();\n $this->value = 0;\n }\n\n # enforce the extending class to define it \n abstract protected function parseFile();\n\n # process value from the input \n public function processFile(){\n \n # list comprehension\n echo(\"Processing the file contents\\n\");\n\n if($this->data) { # array of associative arrays \n \n foreach ($this->data as $dict) { # associative array \n\n # check if it is an associative array or not\n \n if(isset($dict['active']) && isset($dict['value']) && $dict['active']) {\n\n $this->value += $dict['value'];\n\n } \n } \n }\n\n }\n\n # return to the calling convention \n public function getValue(){\n $val = strVal($this->value);\n printf(\"Processed value is: %s\\n\",$val);\n return $val;\n }\n}\n\n?>"
},
{
"alpha_fraction": 0.5715427398681641,
"alphanum_fraction": 0.5795363783836365,
"avg_line_length": 24.5510196685791,
"blob_id": "51e2bb3df372cb3196e4e81e432b0db2d6152481",
"content_id": "c77e705c4a08a1e549067b027b5617c25f452637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1251,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 49,
"path": "/modules/parser.py",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Parser - Base Class \n#\n\n# required libraries\nimport logging\nfrom abc import ABCMeta, abstractmethod\n \nclass Parser():\n\n __metaclass__ = ABCMeta\n\n # initialize the instance variables\n def __init__(self, input_file):\n self.input_file = input_file\n self.data = []\n self.value = 0\n\n # parse the file using a xml parser\n # to be overridden \n def load_file(self):\n # use the parse() function to load and parse an XML file\n self.doc = None\n\n # parse the file using a xml parser\n # Has to be to be overridden \n @abstractmethod\n def parse_file(self):\n pass\n\n # process value from the input \n def process_file(self):\n # list comprehension\n logging.debug(\"Processing the xml file\")\n if self.data:\n for k in self.data:\n if type(k)==dict and len(k.keys())==3 and \"active\" in k and \"value\" in k and k[\"active\"]:\n self.value += k[\"value\"] \n #self.value += sum([k[\"value\"] for k in self.data if k[\"active\"]])\n \n # return to the calling convention \n def get_value(self):\n logging.debug(\"Processed value is: %s\"%str(self.value))\n return self.value"
},
{
"alpha_fraction": 0.5195911526679993,
"alphanum_fraction": 0.5241340398788452,
"avg_line_length": 22.331125259399414,
"blob_id": "60924a856ef7f1e3c039c42ea61d3850736916ea",
"content_id": "4a9b91106e9a6ab6334b46e9af01fe239bafc3d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3522,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 151,
"path": "/modules/utils.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 10-06-2017\n#\n\n#\n# Utils \n#\n# Basic Utilities File\n#\n\nclass Utils {\n\n # Function to process the string to boolean \n \n public static function strToBool($strVal) {\n\n # echo \"stringToBool received string: \", $strVal, \"\\n\";\n\n $retVal = filter_var($strVal, FILTER_VALIDATE_BOOLEAN);\n\n return $retVal;\n\n }\n\n # Function to get the absolute path of the file\n\n public static function joinPaths() {\n \n $paths = array();\n\n foreach (func_get_args() as $arg) {\n if ($arg !== '') {\n $paths[] = $arg;\n }\n }\n\n return join('/', $paths);\n \n }\n\n # Function to get the absolute paths relative to the current working directory \n\n public static function getAbsolutePath($inputFileName,$outputFileName,$currentWorkingDir=null) {\n\n if ($currentWorkingDir == null)\n $currentWorkingDir=getcwd();\n\n # Debug \n # echo \"currentWorkingDir: \", $currentWorkingDir, \"\\n\";\n\n if(substr($inputFileName, 0, 4) == \"data\") {\n \n $inputFileName = Utils::joinPaths($currentWorkingDir,$inputFileName); \n\n }\n else {\n\n $inputFileName = Utils::joinPaths($currentWorkingDir,\"data\",$inputFileName); \n\n }\n \n $inputFileName = str_replace('\\\\', \"/\", $inputFileName); # as we are on linux-ubuntu \n\n if ($outputFileName != null) {\n\n if(substr($outputFileName, 0, 7) == \"results\") {\n \n $outputFileName = Utils::joinPaths($currentWorkingDir,$outputFileName); \n\n }\n else {\n\n $outputFileName = Utils::joinPaths($currentWorkingDir,\"results\",$outputFileName); \n\n }\n \n $outputFileName = str_replace('\\\\', \"/\", $outputFileName); # as we are on linux-ubuntu \n\n }\n\n\n # Debug \n echo \"inputFileName: \", $inputFileName, \"\\noutputFileName: \", $outputFileName, \"\\n\";\n\n return array($inputFileName, $outputFileName); \n }\n\n # Function to get the file extension \n\n public static function getFileExtension($fileName=null) {\n\n if($fileName) {\n\n $ext = pathinfo($fileName, PATHINFO_EXTENSION);\n # printf(\"returning File extension: %s\\n\",$ext);\n return $ext;\n } \n\n # echo(\"returning nothing as file_name is not provided\\n\");\n return null;\n }\n \n # Function to create output directory if missing\n\n public static function createOutputDirectory($fileName=null) {\n\n if ($fileName){\n\n # Get the directory \n $fileDir = pathinfo($fileName)['dirname'];\n \n if (!file_exists($fileDir)) {\n printf(\"Creating the output directory: \\n\",$fileDir);\n mkdir($fileDir, 0777, true);\n return true;\n }\n\n }\n\n echo(\"Output directory already present\\n\");\n return false;\n }\n\n\n # Function to delete directory if existing\n\n public static function deleteDirectory($dirName) {\n\n if ($dirName){\n\n try {\n\n rmdir($dirName);\n printf(\"directory %s deleted!\\n\",$dirName);\n return true;\n }\n catch (Exception $e) {\n printf(\"Error in deleting directory %s\\nError: %s\\n\",$dirName,$e->getMessage());\n }\n\n }\n\n return false;\n }\n\n}\n \n?>"
},
{
"alpha_fraction": 0.5857860445976257,
"alphanum_fraction": 0.6051687002182007,
"avg_line_length": 27.4489803314209,
"blob_id": "7ba544c10ba67a77b39a248a0caaa6ebd9765a21",
"content_id": "592ab1cdb8f546a89df6d3573ff08fc6038e4fed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1393,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 49,
"path": "/modules/csv_parser_test.php",
"repo_name": "wordwarrior01/MultiFileReader",
"src_encoding": "UTF-8",
"text": "<?php\n\n#\n# Nimish Nayak\n# 05-07-2017\n#\n\n# Test Project to test the code base \n# Functional Test cases\n\n# Note: Developed using PHP 7.0.18-0ubuntu0.16.04.1 (cli) ( NTS )\n\nrequire_once(\"./modules/csv_parser.php\");\nrequire_once(\"./modules/utils.php\");\n\nclass CsvParserTest extends PHPUnit_Framework_TestCase\n{\n # Tests \n\n public function testParser() {\n \n $testFile1 = Utils::joinPaths(getcwd(),\"testdata\",\"test_correct.csv\"); \n $this->csvParser = new CsvParser($testFile1);\n # get the list of dictinary of the yml contents \n $this->csvParser->parseFile();\n # process the value \n $this->csvParser->processFile();\n # get the processed value from the parser as a string\n $this->data = $this->csvParser->getValue(); \n $this->assertEquals($this->data, \"900\");\n\n }\n\n public function testParserWithIncorrectYaml() {\n \n $testFile2 = Utils::joinPaths(getcwd(),\"testdata\",\"test_incorrect.csv\"); \n $this->csvParser = new YmlParser($testFile2);\n # get the list of dictinary of the yml contents \n $this->csvParser->parseFile();\n # process the value \n $this->csvParser->processFile();\n # get the processed value from the parser as a string\n $this->data = $this->csvParser->getValue(); \n $this->assertEquals($this->data, 0);\n }\n\n}\n\n?>"
}
] | 24 |
octowhale/python | https://github.com/octowhale/python | 477e25ab5f420b2cda6653ac3793e1ee70efff50 | 6fba07481514665a06803bfdb8e694961941f078 | 061f9cb1171c75070ce5580d9c71fc18840b6eb5 | refs/heads/master | 2020-06-26T04:31:05.948253 | 2017-08-01T07:32:22 | 2017-08-01T07:32:22 | 74,550,755 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6175588965415955,
"alphanum_fraction": 0.6295503377914429,
"avg_line_length": 24.380434036254883,
"blob_id": "19c2070f82c636ada4b007dd82f6df2d49857e62",
"content_id": "f21dd2226e06dd49b97bedf2ec560b631bf752e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2387,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 92,
"path": "/python_example/ss_checkin/ss_config_setup.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n\n\"\"\"\n@version: ??\n@author: TangHsin\n@license: Apache Licence\n@mailto: [email protected]\n@site: \n@software: PyCharm Community Edition\n@FILE: py_setup_config.py\n@time: 2016/8/7 11:19\n\"\"\"\n\nimport os\nimport sys\nimport re\n\n#################\njson_tmpl_abs = 'gui-config.json.tmpl'\n# json_setup_abs = 'gui-config.json'\nif os.name == 'nt':\n json_setup_abs = r'E:\\Documents\\OneDrive\\tools\\shadowsocks-win-3.0\\gui-config.json'\nelse:\n json_setup_abs = r'/mnt/e/Documents/OneDrive/tools/shadowsocks-win-3.0/gui-config.json'\n\nlocalPort = 36363\n\n# line pattern\nremarks_patt = re.compile('\\${remarks\\}')\nserver_patt = re.compile('\\${server\\}')\nserver_port_patt = re.compile('\\${server_port\\}')\npassword_patt = re.compile('\\${password\\}')\nmethod_patt = re.compile('\\${method\\}')\nobfs_patt = re.compile('\\${obfs\\}')\nprotocol_patt = re.compile('\\${protocol\\}')\n\nlocalPort_patt = re.compile('\\${localPort\\}')\n\n# node block pattern\nnode_block_patt = re.compile(r'\\[\\[(.*)\\]\\]', flags=re.M + re.DOTALL)\n\n\ndef node_block_sub_line(line, node_info, user_info):\n line = remarks_patt.sub(node_info[0], line)\n line = server_patt.sub(node_info[1], line)\n line = method_patt.sub(node_info[2], line)\n line = protocol_patt.sub(node_info[3], line)\n line = obfs_patt.sub(node_info[4], line)\n line = server_port_patt.sub(user_info['ss_port'], line)\n line = password_patt.sub(user_info['ss_passwd'], line)\n\n return line\n\n\ndef setup_ss_json(user_info, nodes_info, json_path_name=json_setup_abs):\n #\n # 开始执行\n #\n print len(nodes_info)\n\n # 读取 模板 文件\n f = open(json_tmpl_abs, 'r')\n content = f.read()\n f.close()\n\n # 获取 node block 模板\n node_block_tmpl = node_block_patt.findall(content)\n\n nodes_block = ''\n for node_info in nodes_info:\n for line in node_block_tmpl:\n nodes_block += node_block_sub_line(line, node_info, user_info)\n nodes_block += '\\n'\n\n content = node_block_patt.sub(nodes_block, content)\n\n ## line 其他配置\n content = localPort_patt.sub(str(localPort), content)\n # print content\n\n # 以UTF-8的模式写入文件\n import codecs\n # f = codecs.open(json_setup_abs, 'w', 'utf-8')\n f = codecs.open(json_path_name, 'w', 'utf-8')\n f.write(content)\n f.close()\n\n\nif __name__ == '__main__':\n setup_ss_json(user_info, nodes_info)\n"
},
{
"alpha_fraction": 0.6168224215507507,
"alphanum_fraction": 0.6220145225524902,
"avg_line_length": 23.100000381469727,
"blob_id": "97016ed2547cdab7f66c482c333326afda685dd6",
"content_id": "1650783959e5482ee9959f3951a211be71c7c25c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1037,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 40,
"path": "/python_code_piece/check_os_platform.md",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "# 判断操作系统类型\n\n## 使用 `os.name` 判断\n\n```python\n\nimport os\nif os.name == \"posix\":\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Check the os, if it's linux then\n myping = \"ping -c 2 \"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# This is the ping command\nelif os.name in (\"nt\", \"dos\", \"ce\"):\t\t\t\t\t\t\t\t\t\t\t# Check the os, if it's windows then\n myping = \"ping -n 2 \"\t\n \n```\n\n\n## 使用 `sys.platform` 判断\n\n该片段是用来在不同系统环境下导入加密模块的\n\n> https://github.com/geekcomputers/Python/blob/master/password_cracker.py\n\n```\nfrom sys import platform as _platform\n\n# Check the current operating system to import the correct version of crypt\nif _platform == \"linux\" or _platform == \"linux2\":\n import crypt # Import the module\n # print \"Unix-like\"\nelif _platform == \"darwin\":\n # Mac OS X\n import crypt\n # print \"Mac OS X\"\nelif _platform == \"win32\":\n # Windows\n # print \"Windows\"\n try:\n import fcrypt # Try importing the fcrypt module\n except ImportError:\n print 'Please install fcrypt if you are on Windows'\n```"
},
{
"alpha_fraction": 0.6118980050086975,
"alphanum_fraction": 0.6270065903663635,
"avg_line_length": 15.546875,
"blob_id": "21fec622a6941053fe353f7e30348bbdf5bdab40",
"content_id": "7da4302213d70c17f89e1b9965ae2d7da4629594",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1229,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 64,
"path": "/python_code_piece/check_samefile.md",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "# 判断两个文件是否为相同文件\n\n在 unix-like 操作系统中, python 判断两个文件是否使用同一个 `inode` 。\n在 windows 操作系统中, python 判断两个文件的路径是否一致。\n\n\n## 创建文件\n\n```bash\nln get-pip.py get-pip.py.2\ncp -a get-pip.py get-pip.py.3\nln -s get-pip.py get-pip.py.link\n```\n\n## 测试文件是否相同\n\n```python\n\nimport os\nf1 = '/root/get-pip.py'\nf2 = '/root/get-pip.py.2'\nf3 = '/root/get-pip.py.3'\nflink = '/root/get-pip.link'\n\n\ndef is_samefile(f1,f2):\n if os.path.samefile(f1, f2):\n print \"yes, the samefile\"\n else:\n print \"no, not the samefile\"\n\n\nis_samefile(f1,f2)\n# yes, the samefile\n\nis_samefile(f1,f3)\n# no, not the samefile\n\nis_samefile(f1,flink)\n# no, not the samefile\n\n```\n\n\n## 创建判断相同文件函数\n\n```python\n# 判断文件是否相同\n# hasattr\n# os.path.samefile\ndef _samefile(src, dst):\n\n # Macintosh, Unix.\n if hasattr(os.path, 'samefile'):\n try:\n return os.path.samefile(src, dst)\n except OSError:\n return False\n\n # All other platforms: check for same pathname.\n return (os.path.normcase(os.path.abspath(src)) ==\n os.path.normcase(os.path.abspath(dst)))\n\n```\n"
},
{
"alpha_fraction": 0.7186872363090515,
"alphanum_fraction": 0.7230408787727356,
"avg_line_length": 51.28070068359375,
"blob_id": "e48ca04af71a86647dd8638bb13b16518a10a36e",
"content_id": "5d8ed1a5d989807c651b7d8ca809f6939c6ae20c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2986,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 57,
"path": "/README.md",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "# My python examples and exercises\n\n+ [py_get_ipaddr.py](python_example/py_get_ipaddr.py) \n - get your public ip address by ` re ` and ` urllib `\n+ [python_base64_qrcode.py](python_example/python_base64_qrcode.py) \n - Using ` base64 ` to encode string and using ` qrcode ` and ` Image ` to generate qrcode image\n+ [python_file_finder.py](python_example/python_file_finder.py) \n - to specify the file extensions and print out the files' os.path .\n+ [python_getopt.py](python_example/python_getopt.py) \n - ` getopt ` options test \n+ [python_qiniu_image_upload.py](python_example/python_qiniu_image_upload.py) \n - upload images into qiniu bucket and use images' md5hash code as image name\n+ [batch_files_rename.py](python_example/batch_files_rename.py) \n - rename file with specify extension to new extension\n+ [python_matplotlib_xaxis_datetime_format.py](python_example/python_matplotlib_xaxis_datetime_format.py)\n - format the image's x_axis datetime printout \n+ [qiniuSync.py](python_example/qiniuSync/qiniuSync.py)\n - sync local path to qiniu bucket, configs like [user_cfg.py](python_example/qiniuSync/user_cfg.py.sample)\n+ [aliyun_oss_sync.py](python_example/aliyun_oss_sync/aliyun_oss_sync.py.py)\n - sync local path to aliyun oss bucket, configs like [user_cfg.py](python_example/aliyun_oss_sync/user_cfg.py.sample)\n+ [ss_checkin.py](python_example/ss_checkin/ss_checkin.py)\n - auto login and checkin for ss site module, configs like [user_cfg.py](python_example/ss_checkin/user_cfg.py.sample)\n+ [python_auto_mailaaaa.py](python_example/python_auto_mailaaaa.py)\n - send email via python, work in OSX.\n+ [image_uuid.py](python_example/image_uuid.py)\n - generate uuid of image's binary content via `uuid.uuid3(uuid.NAMESPACE_X500,base64_content)`.\n \n\n\n# My python command\n\n+ [pytree.py](python_command/pytree.py) \n - command ` tree ` by python\n+ [pyoudao.py](python_command/pyoudao.py) \n - tranlsate Enghlish characters into English by ` re ` and ` urllib `\n+ [pypaste.py](python_command/pypaste.py) \n - command ` paste ` by python\n+ [pyseq.py](python_command/pyseq.py) \n - command ` seq ` by python\n+ [pymkdir.py](python_command/pymkdir.py) \n - command ` mkdir ` by python\n+ [pycopy_file.py](python_command/pycopy_file.py) \n - command ` copy ` but only work on file from SRC to DEST\n+ [pycopye.py](python_command/pycopy.py) \n - command ` copy `; SRC support file and directory. support using '-f' or '-i' to force or interactive to overwrite DST which already exists.\n+ [pyfindext.py](pyhont_command/pycopy.py)\n - command ` find `; but only support to specify extensions to search.\n\n\n# Python Code Piece\n\n+ [check_os_platform.md](python_code_piece/check_os_platform.md)\n - check which the os platform is \n+ [check_samefile.md](python_code_piece/check_samefile.md)\n - check two files if or not the same file\n+ [open_file_via_with.md](python_code_piece/open_file_via_with.md)\n - use `with` to open files instead of `try ... except ... `\n\n \n"
},
{
"alpha_fraction": 0.555084764957428,
"alphanum_fraction": 0.5974576473236084,
"avg_line_length": 15.38888931274414,
"blob_id": "f4183895a0a10dd04bc410f2de3ee046e96da968",
"content_id": "5e63e7969ec175197326d17bf64ba29b42dcdfc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1408,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 72,
"path": "/python_example/python_base64_qrcode.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: python_arukas_api.py\n@time: 2016/11/14 12:18\n\"\"\"\n\n\"\"\"\npip install qrcode\npip install Image\n\"\"\"\n\n# import os, sys\nimport base64\nimport qrcode\n# 生成二维码还需要 Image 库\n# import Image # 但此处不需要导入\n\n\ndef get_base64_encode(s):\n '''\n 对字符串执行base64编码和解码\n '''\n\n # 编码\n # 不需要手动去除最后面的(占位符)等号,否则解码会出错\n # s_base64 = base64.b64encode(s).rstrip('=') # 这是错的\n\n s_base64 = base64.b64encode(s)\n\n # 解码\n # s= base64.b64decode(s_encode)\n\n return s_base64\n\n\ndef gen_qrcode(s, image_name=\"pictname.png\"):\n '''\n 将字符串生成二维码\n '''\n\n # 创建对象,所有参数都有默认值。\n # qr=qrcode.QRCode()\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=5,\n border=4,\n )\n\n # 为对象添加数据\n qr.add_data(s)\n\n # 生成适应大小的图片\n qr.make(fit=True) # 可以省略\n\n # 创建图片对象并保存\n img = qr.make_image()\n img.save(image_name)\n\n\nif __name__ == \"__main__\":\n s = \"i have a dream\"\n s_encode = get_base64_encode(s)\n gen_qrcode(s)\n"
},
{
"alpha_fraction": 0.5968468189239502,
"alphanum_fraction": 0.6131756901741028,
"avg_line_length": 24.014083862304688,
"blob_id": "8362e7d3dcfe7a106a85bbcb2729e4480594e82e",
"content_id": "7af10fbdb61243fe210776da7fd4785f26c4e3f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1776,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 71,
"path": "/python_command/pymkdir.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: pymkdir.py\n@time: 2016/11/23 18:48\n\"\"\"\n\nimport os\nimport sys\n\n\ndef mkdir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n else:\n print \"%s: cannot create directory '%s': No such file or directory\" % (sys.argv[0], path)\n\n\ndef mkdir_p(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef print_help():\n print '''Usage: mkdir [OPTION]... DIRECTORY...\nCreate the DIRECTORY(ies), if they do not already exist.\n\nMandatory arguments to long options are mandatory for short options too.\n -m, --mode=MODE set file mode (as in chmod), not a=rwx - umask\n -p, --parents no error if existing, make parent directories as needed\n -v, --verbose print a message for each created directory\n -Z, --context[=CTX] set the SELinux security context of each created\n directory to default type or to CTX if specified\n -h, --help display this help and exit\n -v, --version output version information and exit\n '''\n sys.exit(0)\n\n\ndef print_version():\n print \"pymkdir 0.1\"\n\n\ndef main():\n # print out help infomation\n if \"-h\" in sys.argv or \"--help\" in sys.argv:\n print_help()\n\n # print out version infomation\n if \"-v\" in sys.argv or \"--version\" in sys.argv:\n print_version()\n\n if '-p' == sys.argv[1] or '--parents' == sys.argv[1]:\n # create dir even if it's parent dir is not exist\n for path in sys.argv[2:]:\n mkdir_p(path)\n else:\n # create dir\n for path in sys.argv[1:]:\n mkdir(path)\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.48170730471611023,
"alphanum_fraction": 0.5109755992889404,
"avg_line_length": 21.054054260253906,
"blob_id": "875ae8d76ce350f3deb6ccb57072b39bc16f2537",
"content_id": "df1ff172d58a8877c74ca109c7974e6737b19e7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 856,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 37,
"path": "/python_example/python_getopt.py",
"repo_name": "octowhale/python",
"src_encoding": "GB18030",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@software: PyCharm Community Edition\n@file: python_optget.py\n@time: 2016/11/7 15:56\n\"\"\"\n\nimport sys\nimport os\nimport getopt\n\n\ndef switch(argvs):\n try:\n opts, args = getopt.getopt(argvs, 'ho:', ['help', 'output='])\n\n for o, a in opts:\n # @ o for opt\n # @ a for arg\n print ' %s -> %s ' % (o, a)\n if o in ('-h', '--help'):\n print \"这里全部都是帮助信息\"\n if o in ('-o', '--output'):\n print \"新的输出文件名为 %s\" % a\n except getopt.GetoptError, err:\n print err\n\n\nif __name__ == '__main__':\n argvs = ['-h', '-o', 'filename1', '--help', '--output', 'filename2', 'arg1', 'arg2']\n switch(argvs)\n "
},
{
"alpha_fraction": 0.5586538314819336,
"alphanum_fraction": 0.5774038434028625,
"avg_line_length": 21.85714340209961,
"blob_id": "910b99d2517052df97b06ee1d1a6647466c5d191",
"content_id": "be9921353a08b397b9578f0d07b45f8f0da0c008",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2080,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 91,
"path": "/python_command/pycopy_file.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\r# encoding: utf-8\r#\r\r\"\"\"\r@version: 0.0.1\r@author: TangHsin\r@license: Apache Licence\r@mailto: octowhale@github\r@site: \r@software: PyCharm Community Edition\r@python ver: Python 2.7.12\r@FILE: pycopy_file.py\r@time: 2016/11/23 21:17\r\"\"\"\r\rimport os\rimport sys\r\r\rdef write(src, dest):\r # how to copy\r # open a file and write to anther\r\r src_content = open(src, 'rb').read()\r\r dest_object = open(dest, 'wb')\r dest_object.write(src_content)\r dest_object.close()\r\r\rdef copy(src, dest):\r # check src is exist\r if not os.path.exists(src):\r print \"Error: %s is not exist\" % src\r\r if os.path.isdir(src):\r print \"Error: %s is a directory\" % src\r\r src_filename = os.path.basename(src)\r\r # if dest's parent dir is not exit\r # without os.path.join, dest_dirname may be a blank.\r dest = os.path.join(os.curdir, dest)\r dest_dirname = os.path.dirname(dest)\r if not os.path.exists(dest_dirname):\r print \"Error: Directory %s is not exist!\" % dest_dirname\r sys.exit(1)\r\r # if dest is dir, copy file into it\r if os.path.isdir(dest):\r dest_file = os.path.join(dest, src_filename)\r write(src, dest_file)\r\r # if dest is file, copy file to cover it\r elif os.path.isfile(dest):\r dest_file = dest\r write(src, dest_file)\r\r # if dest is not exist, dest is the new name\r else:\r dest_file = dest\r write(src, dest_file)\r\r\rdef main():\r # not enough arguments\r if len(sys.argv) < 3:\r print \"Error: Not enough arguments\"\r sys.exit(1)\r\r # copy file\r elif len(sys.argv) == 3:\r copy(sys.argv[1], sys.argv[-1])\r\r else:\r # copy files into a directory\r if not os.path.isdir(sys.argv[-1]):\r print \"Error: %s is not a directory\" % sys.argv[-1]\r sys.exit(1)\r else:\r for src in sys.argv[1:-1]:\r copy(src, sys.argv[-1])\r\r\rif __name__ == \"__main__\":\r # copy('src.txt', r'e:\\1\\2\\a\\c\\d\\dest.txt')\r # copy('src.txt', 'dest.txt')\r # copy(r'e:\\1\\2', r'e:\\1\\2_2')\r\r main()\r"
},
{
"alpha_fraction": 0.5750798583030701,
"alphanum_fraction": 0.6293929815292358,
"avg_line_length": 23.710525512695312,
"blob_id": "28ced30ba3ade5596ca28f6579227aad5561db3d",
"content_id": "1758baa82f461e867fd3060fca0a91cd2b0390f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 939,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 38,
"path": "/python_example/image_uuid.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@author: [email protected]\n@python_version: python2.7\n@file: image_uuid.py\n@time: 2017/8/1 14:47\n\"\"\"\n\nimport os\nimport sys\nimport uuid\nfrom base64 import b64encode\n\nPYTHON_VER = sys.version_info.major\n\nENCODING = 'utf-8'\n\nclass ImageUUID(object):\n def __init__(self, imagefile):\n self.imagefile = imagefile\n\n @property\n def uuid(self):\n with open(self.imagefile, 'rb') as data_obj:\n data_content = data_obj.read()\n date_base64_bytes = b64encode(data_content)\n # print(date_base64_bytes)\n if PYTHON_VER == 2:\n return uuid.uuid3(uuid.NAMESPACE_X500, date_base64_bytes.encode(ENCODING))\n elif PYTHON_VER == 3:\n return uuid.uuid3(uuid.NAMESPACE_X500, date_base64_bytes.decode(ENCODING))\n\n\nif __name__ == '__main__':\n image = ImageUUID('005DO33Hly1fhr7flzt6bj30qu0l4ds8.jpg')\n print(image.uuid)\n"
},
{
"alpha_fraction": 0.5285505056381226,
"alphanum_fraction": 0.5541727542877197,
"avg_line_length": 18.797101974487305,
"blob_id": "a26a6cc76f0ca93d6fff485624a1dae35222cab0",
"content_id": "8bdbad029c461e4c8f3050e8cdaeed2bd03ca9c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1366,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 69,
"path": "/python_command/pyfindext.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@python_version: python_x86 3.5.2\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: pyfindext.py\n@time: 2016/12/5 16:39\n\"\"\"\n\n__doc__ = '''find file by specify file extension'''\n\nimport os\nimport sys\n\n\ndef usage():\n print __doc__\n print \"Usage pyfindext.py path ext1 [ext2 ext3 ...]\"\n sys.exit(1)\n\n\ndef _init(ext):\n ext = ext.lstrip('.')\n ext = '.' + ext\n\n return ext.lower()\n\n\ndef find_ext(path, ext):\n ext = _init(ext)\n\n for dir_name, sub_dirs, sub_files in os.walk(path):\n\n for sub_file in sub_files:\n file_ext = os.path.splitext(sub_file)[-1]\n # print file_ext\n file_ext = file_ext.lower()\n if ext == file_ext:\n file_path = os.path.join(dir_name, sub_file)\n print os.path.normcase(file_path)\n\n\ndef main(path, exts):\n if not os.path.exists(path):\n print \"Path %s doesn't exist\" % path\n usage()\n\n for ext in exts:\n find_ext(path, ext)\n\n\nif __name__ == '__main__':\n # path = r'E:\\Documents\\GitHub\\python'\n # ext = 'Py'\n # l = ['', path, 'pY', '.XML']\n # main(l[1], l[2:])\n\n if len(sys.argv) < 3:\n usage()\n\n path = sys.argv[1]\n exts = sys.argv[2:]\n main(path, exts)\n"
},
{
"alpha_fraction": 0.530778169631958,
"alphanum_fraction": 0.5667828321456909,
"avg_line_length": 16.571428298950195,
"blob_id": "b2655eb78b6f87fe2b66843b1f2a184a9166519a",
"content_id": "a13e728ab126a428fef02f65bd00bc4e9fd7cd94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 861,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 49,
"path": "/python_example/qiniuSync/utils.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@python_version: python_x86 3.5.2\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: utils.py\n@time: 2016/12/1 18:25\n\"\"\"\n\nimport os\nimport sys\n\n\ndef _uri_encode(f, pfix):\n # for linux and windows platform\n\n f_list = f.split(os.path.sep)\n uri = '/'.join(f_list[1:])\n return \"%s%s\" % (pfix, uri)\n\n\ndef _uri_encode_win32(f):\n # f=r\".\\path\\filename.png\"\n # f=r\".filename.png\"\n\n f = f[2:]\n\n # '/'.join(os.path.split(f))\n\n # f_tuple = os.path.split(f)\n f_tuple = f.split(os.path.sep)\n\n\n if len(f_tuple[0]) == 0:\n # print f\n return f\n else:\n # print '/'.join(f_tuple)\n return '/'.join(f_tuple)\n\n\ndef _uri_encode_posix(f):\n # f = './path/filename.png'\n # f = './filename.png'\n\n return f[2:]\n"
},
{
"alpha_fraction": 0.4891067445278168,
"alphanum_fraction": 0.5098039507865906,
"avg_line_length": 22.538461685180664,
"blob_id": "31c029fe3307fcba67e390127adc1706fb99b73f",
"content_id": "7b2863d4952d3e90288829930cf2cf7905dea5e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 918,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 39,
"path": "/python_command/pytree.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\n# File Name: pytree.py\n# Author: uyinn\n# mail: [email protected]\n# Created Time: Sat 19 Apr 2014 09:59:56 AM CST\n#########################################################################\n\nimport os\nimport sys\n\n# print 'hello world'\n\ndef main(path,pushcount):\n pushcount=pushcount+1\n dirLists=os.listdir(path)\n for dirlist in dirLists:\n son_path=os.path.join(path,dirlist)\n print ' |'*(pushcount),\n if os.path.isdir(son_path):\n print '--*',dirlist\n main(son_path,pushcount)\n# else:\n# print '|__',dirlist\n if os.path.isfile(son_path):\n print '|__',dirlist\n\n\n\nif __name__==\"__main__\":\n if len(sys.argv)==1:\n path=os.getcwdu()\n elif len(sys.argv)>1:\n path=sys.argv[1]\n else:\n print 'Usage: %s [path]' % sys.argv[0]\n print '%s' % path\n main(path,pushcount=-1)\n"
},
{
"alpha_fraction": 0.44844719767570496,
"alphanum_fraction": 0.4645962715148926,
"avg_line_length": 27.75,
"blob_id": "d9b284ca58a00694d0e37daeb7a9c55e159866ae",
"content_id": "6c5365c3a8a83ca09307f10678efea85430acdc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1768,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 56,
"path": "/python_example/python_file_finder.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# -------------------------------------------------------------------------------\n# Name: pyFileFinder.py\n# Purpose:\n#\n# Author: uyinn\n# Mailto: [email protected]\n#\n# Created: 18/04/2014\n# Copyright: (c) uyinn 2014\n# Licence: <your licence>\n# -------------------------------------------------------------------------------\n\nimport os # import libs\nimport sys\n\ndef main(path, types):\n\n try:\n # 获取目录中的文件名\n folder_lists = os.listdir(path)\n\n for folder_list in folder_lists:\n son_path = os.path.join(path, folder_list) # 组合原目录路径和文件名\n if os.path.isdir(son_path): # get new path is a directory or not\n main(son_path, types) ## true: use main function again\n else:\n ## print son_path\n file_type = son_path.split('.')[-1].lower() ## false: 获取文件后缀名\n ## print file_type\n if file_type in types: # 如果后最匹配。则输出结果\n print son_path\n except:\n pass\n\ndef usage(command_name):\n print \"\"\"\n 在指定目录中path中查找包含指定后缀的文件\n Usage:\n %s path pf1 [ pf2 pf3]\n \"\"\" % command_name\n\nif __name__ == '__main__':\n ## main(u'd:\\python',('pyc','gz'))\n if len(sys.argv) < 3:\n # print \"Usage: %s path postfix1[ pf2 pf3 ] \" % sys.argv[0]\n usage(sys.argv[0])\n sys.exit(1)\n\n path = sys.argv[1] # 获取所需查找路径\n types = [] # 创建后缀列表\n for x in xrange(2, len(sys.argv)):\n types.append(sys.argv[x].lower()) # 通过参数获取后缀\n\n main(path, types)\n"
},
{
"alpha_fraction": 0.41698113083839417,
"alphanum_fraction": 0.5799528360366821,
"avg_line_length": 43.16666793823242,
"blob_id": "3d171ea87641438653d09dd63c8a4d0bc5f95208",
"content_id": "b99992ad3589849cf26e0252ef51b43cd2dfae34",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4354,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 96,
"path": "/python_example/python_matplotlib_xaxis_datetime_format.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: gen_online_image.py\n@time: 2016/11/28 15:15\n\"\"\"\n\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nimport datetime\n# from matplotlib.dates import YearLocator, MonthLocator, DayLocator\n# from matplotlib.dates import drange, DateLocator, DateFormatter\n# from matplotlib.dates import HourLocator, MinuteLocator, SecondLocator\nimport matplotlib.dates as mdates\n\n\ndef gen_image_2(l):\n # 格式化刻度单位\n # years=mdates.YearLocator()\n # months=mdates.MonthLocator()\n # days=mdates.DayLocator()\n hours = mdates.HourLocator()\n minutes = mdates.MinuteLocator()\n seconds = mdates.SecondLocator()\n\n # dateFmt = mdates.DateFormatter('%Y-%m-%d %H:%M')\n # dateFmt = mdates.DateFormatter('%Y-%m-%d')\n dateFmt = mdates.DateFormatter('%H:%M') # 显示格式化后的结果\n\n if len(l) != 2:\n return False\n\n x = l[0]\n y = l[1]\n\n fig, ax = plt.subplots()\n # format the ticks\n ax.xaxis.set_major_locator(hours) # 设置主要刻度\n ax.xaxis.set_minor_locator(minutes) # 设置次要刻度\n ax.xaxis.set_major_formatter(dateFmt) # 刻度标志格式\n\n # 添加图片数据\n # plt.plot_date(dates, y, 'm-', marker='.', linewidth=1)\n plt.plot_date(x, y, '-', marker='.')\n # plt.plot(x, y)\n\n\n fig.autofmt_xdate() # 自动格式化显示方式\n\n plt.show() # 显示图片\n plt.savefig('filename.png') # 保存图片\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n # main()\n\n # result_list = DbUtils.connet()\n\n result_list = [[datetime.datetime(2016, 11, 28, 14, 43, 48), datetime.datetime(2016, 11, 28, 14, 45, 48),\n datetime.datetime(2016, 11, 28, 14, 52, 15), datetime.datetime(2016, 11, 28, 14, 57, 2),\n datetime.datetime(2016, 11, 28, 15, 4, 14), datetime.datetime(2016, 11, 28, 15, 5, 14),\n datetime.datetime(2016, 11, 28, 15, 11, 7), datetime.datetime(2016, 11, 28, 15, 18, 21),\n datetime.datetime(2016, 11, 28, 15, 20, 21), datetime.datetime(2016, 11, 28, 15, 25, 39),\n datetime.datetime(2016, 11, 28, 15, 30, 54), datetime.datetime(2016, 11, 28, 15, 35, 54),\n datetime.datetime(2016, 11, 28, 15, 41, 32), datetime.datetime(2016, 11, 28, 15, 46, 24),\n datetime.datetime(2016, 11, 28, 15, 51, 13), datetime.datetime(2016, 11, 28, 15, 55, 13),\n datetime.datetime(2016, 11, 28, 16, 0, 13), datetime.datetime(2016, 11, 28, 16, 5, 21),\n datetime.datetime(2016, 11, 28, 16, 11, 22), datetime.datetime(2016, 11, 28, 16, 15, 3),\n datetime.datetime(2016, 11, 28, 16, 20, 20), datetime.datetime(2016, 11, 28, 16, 25, 16),\n datetime.datetime(2016, 11, 28, 16, 30, 48), datetime.datetime(2016, 11, 28, 16, 35, 48),\n datetime.datetime(2016, 11, 28, 16, 40, 18), datetime.datetime(2016, 11, 28, 16, 47, 38),\n datetime.datetime(2016, 11, 28, 16, 50, 17), datetime.datetime(2016, 11, 28, 16, 58, 10),\n datetime.datetime(2016, 11, 28, 17, 0, 40), datetime.datetime(2016, 11, 28, 17, 5, 40),\n datetime.datetime(2016, 11, 28, 17, 10, 40), datetime.datetime(2016, 11, 28, 17, 15, 40),\n datetime.datetime(2016, 11, 28, 17, 20, 40), datetime.datetime(2016, 11, 28, 17, 27, 19),\n datetime.datetime(2016, 11, 28, 17, 30, 43), datetime.datetime(2016, 11, 28, 17, 36, 6),\n datetime.datetime(2016, 11, 28, 17, 41, 13), datetime.datetime(2016, 11, 28, 17, 45, 39),\n datetime.datetime(2016, 11, 28, 17, 51, 39), datetime.datetime(2016, 11, 28, 17, 59, 22),\n datetime.datetime(2016, 11, 28, 18, 0, 42), datetime.datetime(2016, 11, 28, 18, 5, 39),\n datetime.datetime(2016, 11, 28, 18, 10, 39), datetime.datetime(2016, 11, 28, 18, 15, 39)],\n [5L, 4L, 1L, 5L, 9L, 16L, 5L, 5L, 3L, 5L, 8L, 18L, 6L, 8L, 22L, 1L, 16L, 11L, 14L, 5L, 7L, 11L, 5L,\n 2L, 7L, 6L, 15L, 6L, 9L, 20L, 23L, 22L, 28L, 4L, 4L, 1L, 4L, 9L, 19L, 4L, 21L, 23L, 24L, 5L]]\n\n gen_image_2(result_list)\n"
},
{
"alpha_fraction": 0.5366917848587036,
"alphanum_fraction": 0.5583102107048035,
"avg_line_length": 29.7439022064209,
"blob_id": "a5a7ac3b8737d4cae0ad15737dc0d95c8818baf9",
"content_id": "319a83aebc41044e20500bd1410b97426bdf0602",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5194,
"license_type": "no_license",
"max_line_length": 280,
"num_lines": 164,
"path": "/python_example/ss_checkin/ss_checkin.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n\n\"\"\"\n@version: ??\n@author: TangHsin\n@license: Apache Licence\n@mailto: [email protected]\n@site:\n@software: PyCharm Community Edition\n@FILE: pyspider_s3_feng666.py.py\n@time: 2016/8/6 23:12\n\"\"\"\n\nimport os\nimport sys\n\nimport cookielib\nimport urllib, urllib2\nimport re\n\n\ndef get_opener():\n cj = cookielib.CookieJar()\n cookie_support = urllib2.HTTPCookieProcessor(cj)\n # opener = urllib2.build_opener(cookie_support, urllib2.HTTPSHandler, urllib2.HTTPSHandler)\n opener = urllib2.build_opener(cookie_support)\n opener.add_handler(urllib2.HTTPSHandler())\n opener.add_handler(urllib2.HTTPHandler())\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36',\n # 'X-Forwarded-For': '171.212.113.133', # 伪装IP地址\n 'Accept': 'image/webp,image/*,*/*;q=0.8',\n # 'Accept-Encoding': 'gzip, deflate, sdch', # 使用后压缩结果\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n # 'Content-Type': 'application/html',\n }\n\n header_list = []\n for key, value in headers.items():\n header_list.append((key, value))\n\n opener.addheaders = header_list\n\n return opener\n\n\ndef do_login(username, password):\n loginURI = 'auth/login'\n loginInfo = {\n 'email': username,\n 'passwd': password,\n 'code': '',\n 'remember_me': 'week',\n }\n login_paras = urllib.urlencode(loginInfo)\n opener = get_opener()\n\n try:\n print 'use https'\n loginURL = 'https://%s/%s' % (hostname, loginURI)\n # resp = urllib2.urlopen(loginURL, login_paras, timeout=3)\n resp = opener.open(loginURL, login_paras, timeout=3)\n data = resp.read()\n print data\n if data == '{\"ret\":1,\"msg\":\"\\u6b22\\u8fce\\u56de\\u6765\"}':\n return {\n 'http_type': 'https',\n 'opener': opener,\n }\n except Exception as err:\n print err\n\n try:\n print 'use http'\n loginURL = 'http://%s/%s' % (hostname, loginURI)\n resp = opener.open(loginURL, login_paras, timeout=3)\n data = resp.read()\n print data\n if data == '{\"ret\":1,\"msg\":\"\\u6b22\\u8fce\\u56de\\u6765\"}':\n return {\n 'http_type': 'http',\n 'opener': opener,\n }\n except Exception as err:\n print err\n\n\ndef do_checkin(opener, http_type):\n checkinURI = 'user/checkin'\n checkinURL = \"%s://%s/%s\" % (http_type, hostname, checkinURI)\n\n try:\n # 签到\n resp = opener.open(checkinURL, '')\n print resp.read()\n except:\n pass\n\n\ndef get_ss_node_info(content):\n # print type(content)\n content = content.decode('utf8')\n # server_str = u'\\<div.*?\\<a.*?\\>([\\d\\w\\uff0c\\u4e00-\\u9fff]+-SS)\\<\\/a\\>.*?\\<p\\>地址:\\<span.*?(\\d+\\.\\d+\\.\\d+\\.\\d+).*?\\<\\/span\\>\\<\\/p\\>.*?\\<p\\>加密方式:\\<span.*?\\t([\\w\\d-]+).*?\\<p\\>协议:\\<span.*?\\t(\\w+).*?\\<p\\>混淆方式:\\<span.*?\\t(\\w+).*?'\n # server_str = u'\\<div.*?\\<a.*?\\>([\\d\\w\\uff0c\\u4e00-\\u9fff]+-SS)\\<\\/a\\>.*?\\<span class=\\\"label label-green\\\"\\>OK\\<\\/span\\>.*?\\<p\\>地址:\\<span.*?(\\d+\\.\\d+\\.\\d+\\.\\d+).*?\\<\\/span\\>\\<\\/p\\>.*?\\<p\\>加密方式:\\<span.*?\\t([\\w\\d-]+).*?\\<p\\>协议:\\<span.*?\\t(\\w+).*?\\<p\\>混淆方式:\\<span.*?\\t(\\w+).*?'\n server_str = u'\\<span class=\\\"icon text-green\\\"\\>backup\\<\\/span\\>.*?\\<div.*?\\<a.*?\\>([\\d\\w\\uff0c\\u4e00-\\u9fff]+-SS)\\<\\/a\\>.*?\\<p\\>地址:\\<span.*?(\\d+\\.\\d+\\.\\d+\\.\\d+).*?\\<\\/span\\>\\<\\/p\\>.*?\\<p\\>加密方式:\\<span.*?\\t([\\w\\d-]+).*?\\<p\\>协议:\\<span.*?\\t(\\w+).*?\\<p\\>混淆方式:\\<span.*?\\t(\\w+).*?'\n\n server_patt = re.compile(server_str, flags=re.DOTALL + re.MULTILINE)\n nodes_info = server_patt.findall(content)\n\n print nodes_info\n return nodes_info\n\n\ndef get_ss_user_info(content):\n ss_port_str = '\\<dt\\>端口\\</dt\\>.*\\<dd\\>(\\d+?)\\</dd\\>'\n ss_port_patt = re.compile(ss_port_str, flags=re.MULTILINE + re.DOTALL)\n\n pwd_str = '\\<dt\\>密码\\</dt\\>.*\\<dd\\>([\\d\\w\\s]+?)\\</dd\\>'\n pwd_patt = re.compile(pwd_str, flags=re.MULTILINE + re.DOTALL)\n\n ss_passwd = pwd_patt.findall(content)\n ss_port = ss_port_patt.findall(content)\n\n user_info = {\n 'ss_port': ss_port[0],\n 'ss_passwd': ss_passwd[0],\n }\n\n return user_info\n\n\ndef do_setup_json(opener, http_type):\n userURL = '%s://%s/user' % (http_type, hostname)\n nodeURL = '%s://%s/user/node' % (http_type, hostname)\n\n user_info = get_ss_user_info(opener.open(userURL).read())\n nodes_infos = get_ss_node_info(opener.open(nodeURL).read())\n\n import ss_config_setup\n ss_config_setup.setup_ss_json(user_info, nodes_infos)\n\n\ndef main(username, password):\n login_stat = do_login(username, password)\n\n http_type = login_stat['http_type']\n opener = login_stat['opener']\n\n do_checkin(opener, http_type) # 签到\n # do_setup_json(opener, http_type) # 生成当日服务器列表\n\n\nif __name__ == '__main__':\n try:\n from user_cfg import *\n except ImportError as err:\n print err\n\n main(username, password)\n"
},
{
"alpha_fraction": 0.5417236685752869,
"alphanum_fraction": 0.565891444683075,
"avg_line_length": 23.920454025268555,
"blob_id": "708598423be929e85f35b15402caaa48e63f73d5",
"content_id": "6de0411b04fe8b648aa1a67e7c66478a95497bb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2327,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 88,
"path": "/python_example/python_get_ipaddr.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n\n\"\"\"\n@version: ??\n@author: TangHsin\n@license: Apache Licence\n@mailto: octowhale@github\n@site: \n@software: PyCharm Community Edition\n@python ver: Python 2.7.12\n@FILE: py_get_ipaddr.py\n@time: 2016/11/5 11:34\n\"\"\"\n\nimport os\nimport sys\nimport urllib2\nimport urllib\nimport re\n\n\ndef get_ipcn_result(ip=''):\n ipcn_url = 'http://ip.cn/index.php?ip=' + ip\n\n opener = urllib2.build_opener(urllib2.HTTPSHandler(), urllib2.HTTPSHandler())\n opener.addheaders = [('User-Agent', 'Chrome/46.0.2490.76')]\n\n content = opener.open(ipcn_url).read()\n\n # print content\n return content\n\n\ndef get_ipaddr(ip=''):\n content = get_ipcn_result(ip)\n\n # ip_patt = r'<p>您查询的 IP:<code>(\\d+.\\d+.\\d+.\\d+)</code></p>'\n ip_patt = r' IP:<code>(\\d+.\\d+.\\d+.\\d+)</code></p>'\n ip_patt_compile = re.compile(ip_patt)\n\n try:\n return ip_patt_compile.findall(content)[0]\n except:\n return \"请输入正确的 V4 IP 或 域名\"\n\n\ndef get_ip_info(ip=''):\n '''\n 获取ip或域名的地址信息\n :param ip: ip或域名\n :return: python 字典 utf-8\n '''\n content = get_ipcn_result(ip)\n\n # ip_info_patt = r'<div id=\"result\"><div class=\"well\"><p>.* IP:<code>(.*?)</code></p><p>所在地理位置:<code>(.*?)</code></p><p>GeoIP: (.*?)</p></div></div>'\n # ip_info_patt = r'<div id=\"result\"><div class=\"well\"><p>您查询的 IP:<code>(.*?)</code></p><p>所在地理位置:<code>(.*?)</code></p><p>GeoIP: (.*?)</p>(<p>.*?</p>)</div></div>'\n ip_info_patt = r' IP:<code>(.*?)</code></p><p>所在地理位置:<code>(.*?)</code></p><p>GeoIP: (.*?)</p>'\n\n ip_info_compile = re.compile(ip_info_patt)\n\n try:\n # print ip_info_compile.findall(content)\n # for info in ip_info_compile.findall(content)[0]:\n # print info\n\n ip_info = ip_info_compile.findall(content)[0]\n\n return {'ipaddr': ip_info[0], 'cn_addr': ip_info[1], 'en_addr': ip_info[2]}\n\n except:\n return \"请输入正确的 V4 IP 或 域名\"\n\n\nif __name__ == \"__main__\":\n # myip = '61.139.2.69'\n # print get_ipaddr(myip)\n # print get_ipaddr()\n\n # print sys.argv\n\n try:\n print get_ipaddr(sys.argv[1])\n # print get_ip_info('ip138.com')\n except:\n print get_ip_info()\n # print get_ip_info('ip138.com')\n"
},
{
"alpha_fraction": 0.5164835453033447,
"alphanum_fraction": 0.5267857313156128,
"avg_line_length": 24.884445190429688,
"blob_id": "7992cc4537ec0e3ac9e6fc75b757d178832b6c10",
"content_id": "e90028987487dadb22f64b560eda80b000aca918",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6312,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 225,
"path": "/python_example/python_qiniu_image_upload.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n\n\"\"\"\n@version: ??\n@author: TangHsin\n@license: Apache Licence\n@mailto: octowhale@github\n@site: \n@software: PyCharm Community Edition\n@python ver: Python 2.7.12\n@FILE: python_qiniu_image_upload.py\n@time: 2016/11/10 21:01\n\"\"\"\n\nimport os\nimport sys\nimport imghdr\nimport hashlib\nimport sqlite3\n\n# pip install qiniu\nimport qiniu\n\n'''\n上传图片到七牛容器\n并返回对应的URL\n\n'''\n\n\nclass QiniuUpload:\n access_key = ''\n secret_key = ''\n bucket_name = ''\n bucket_url = ''\n image_prefix = \"\"\n\n image = ''\n image_md5sum = \"\"\n image_type = \"\"\n image_name = ''\n\n db_path = os.path.abspath(os.path.dirname(sys.argv[0]))\n db_name = os.path.join(db_path, 'image.db')\n\n def get_image_name(self):\n self.image_name = os.path.basename(self.image)\n # print self.image_name\n\n def get_exist(self):\n '''检查文件是否存在'''\n if not os.path.exists(self.image):\n print \"Error: 文件 ( %s ) 不存在。 \" % self.image\n sys.exit(10)\n\n def get_md5sum(self):\n '''获取文件md5码,作为上传文件名,以及数据库主键'''\n\n f = open(self.image, 'rb').read()\n md5sum = hashlib.md5(f).hexdigest()\n self.image_md5sum = md5sum\n return md5sum\n\n def get_type(self):\n '''获取图片类型'''\n\n type_value = imghdr.what(self.image)\n if type_value is not None:\n self.image_type = type_value\n # return type_value\n else:\n print 'Error: 文件 ( %s )不是图片' % self.image\n sys.exit(9)\n\n def to_connect_qiniu_image_database(self):\n '''\n 连接数据库\n 如果没有则创建数据库及表\n '''\n\n # 如果数据库文件不存在,则创建\n # if not os.path.exists(self.db_name):\n # print self.db_name\n cx = sqlite3.connect(self.db_name)\n cursor = cx.cursor()\n try:\n sql = \"create table qiniu_image_url ( image_md5sum varchar(32) primary key, image_type varchar(4), image_prefix varchar(50))\"\n cursor.execute(sql)\n cx.commit()\n cx.close()\n except:\n pass\n\n cx = sqlite3.connect(self.db_name)\n cursor = cx.cursor()\n # return cursor\n return [cursor, cx]\n\n def to_select_image_database(self, cursor):\n '''\n 查看文件是否已经存在于数据库中,如果存在则直接返回七牛URL\n :param cursor: 数据库连接指针\n :return: 七牛URL\n '''\n sql = \"select * from qiniu_image_url where image_md5sum='%s'\" % self.image_md5sum\n # cx = sqlite3.connect(self.db_name)\n # cursor = cx.cursor()\n try:\n # print sql\n cursor.execute(sql)\n r = cursor.fetchall()\n if len(r) == 1:\n # abs_url = \"http://%s/%s%s.%s\" % (self.bucket_url, r[0][-1], r[0][0], r[0][1])\n # print 'Success: file \"%s\" is already exist' % self.image\n # print abs_url\n # return abs_url\n self.to_print_urls(r[0])\n return r[0]\n except:\n pass\n\n def to_print_urls(self, the_tuple):\n '''\n 按照格式打印输出\n :param the_tuple: 数据库中的图片信息 [image_md5sum,image_type,image_prefix_url]\n :return: None\n '''\n\n abs_url = \"http://%s/%s%s.%s\" % (self.bucket_url, the_tuple[-1], the_tuple[0], the_tuple[1])\n \n print abs_url # qiniu abs_url\n print \"\" % (self.image_name, abs_url) # markdown\n print '<img src=\"%s\">%s</img>' % (abs_url, self.image_name) # html\n\n def to_update_image_database(self, cursor, cx):\n '''\n 插入成功后更新数据库,并返回七牛URL\n :param cursor: 数据库指针\n :param cx: 数据库实例\n :return: 通过to_select_image_database()返回七牛URL\n '''\n sql = \"insert into qiniu_image_url values ('%s','%s','%s')\" % (\n self.image_md5sum, self.image_type, self.image_prefix)\n # print sql\n try:\n cursor.execute(sql)\n cx.commit() # 提交到数据库\n # cx.close()\n self.to_select_image_database(cursor)\n except:\n pass\n\n def to_upload_image_to_qiniu(self):\n '''\n 上传文件到七牛仓库\n :return: 成功或失败\n '''\n try:\n # print self.image_prefix\n # print 'md5' + self.image_md5sum\n # print self.image_type\n # print '开始上传'\n q = qiniu.Auth(self.access_key, self.secret_key)\n key = \"%s%s.%s\" % (self.image_prefix, self.image_md5sum, self.image_type)\n\n # print key\n token = q.upload_token(self.bucket_name, key)\n\n qiniu.put_file(token, key, self.image)\n # self.to_update_image_database(self.cursor)\n return True\n except:\n return False\n\n def get_url(self):\n '''\n @breif : main 方法\n :return:\n '''\n self.get_image_name()\n # 检查文件是否存在\n self.get_exist()\n\n # 获取图片 type\n self.get_type()\n\n # 获取 图片 md5\n self.get_md5sum()\n\n # 连接数据库\n cursor, cx = self.to_connect_qiniu_image_database()\n\n # 检查图片是否已经上传到七牛\n if self.to_select_image_database(cursor) is not None:\n\n cx.close()\n sys.exit()\n pass\n\n # 之前没有上传\n elif self.to_upload_image_to_qiniu():\n self.to_update_image_database(cursor, cx)\n # self.to_select_image_database(cursor)\n\n # cursor.close()\n cx.commit()\n cx.close()\n\n\nif __name__ == \"__main__\":\n image = r'C:\\Users\\owners\\Desktop\\PNG\\loading_logo.png'\n\n import user_auth\n\n qr_upload = QiniuUpload()\n qr_upload.access_key = user_auth.accKey\n qr_upload.secret_key = user_auth.secKey\n qr_upload.bucket_name = user_auth.bucketName\n qr_upload.bucket_url = user_auth.bucketUrl\n qr_upload.image_prefix = ''\n qr_upload.image = image\n\n qr_upload.get_url()\n"
},
{
"alpha_fraction": 0.5597802996635437,
"alphanum_fraction": 0.5644275546073914,
"avg_line_length": 28.962024688720703,
"blob_id": "f5bd2cff293872986265c48fdd8a5aea9a0c56c2",
"content_id": "177edcb29faa252653f0cd966bfa5744c158b271",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2585,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 79,
"path": "/python_example/python_auto_mailaaaa.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n#coding:utf-8\n# author: QQ 群友\n#\nimport urllib, urllib2\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.application import MIMEApplication\nimport datetime\nimport time\nimport os\nos.chdir('/data/application/tomcat-transnwe/bin/logs/')\n\n\nmail_host = 'smtp.163.com' \nmail_user = '*********@163.com' #邮箱账号\nmail_pass = '*******' #邮箱密码\nmail_postfix = '163.com'\n#以上内容根据你的实际情况进行修改\n\ndef send_mail(to_list,subject,content,log_path,log_name):\n me = mail_user+\"<\"+mail_user+\"@\"+mail_postfix+\">\"\n\n msg = MIMEMultipart() #用于发送多个类型\n msg['Subject'] = subject #邮件主题\n msg['From'] = '***********@163.com'\n msg['to'] = to_list #发送给谁,抄送\n \n \n # 下面是文字部分,也就是纯文本\n log_test = MIMEText(content) #邮件文本\n msg.attach(log_test) \n \n # 首先是log类型的附件\n logpart = MIMEApplication(open(log_path, 'rb').read())\n logpart.add_header('Content-Disposition', 'attachment', filename=log_name)\n msg.attach(logpart)\n\n try:\n s = smtplib.SMTP()\n s.connect(mail_host)\n s.login(mail_user,mail_pass)\n s.sendmail(me,to_list,msg.as_string())\n s.close()\n return True\n except Exception,e:\n print str(e)\n return False\n\nif __name__ == \"__main__\":\n \n times = datetime.date.today() - datetime.timedelta(days=1)\n time_str = times.strftime('%Y-%m-%d')\n \n log_path = '/data/application/tomcat-transnwe/bin/logs/' + time_str + '_errlr_log.tgz' \n log_name = time_str + '_errlr_log.tgz'\n shells = ' wetransn_' + time_str + '*error.log'\n num = os.popen('ls wetransn_' + time_str + '*error.log | wc -l').read()\n title = time_str + '_woordee_error'\n date = time.strftime('%Y-%m-%d %H:%M:%S')\n \n if int(num) > 0:\n err = os.system('tar zcvf ' + log_name + shells)\n\n filename = r'/data/application/tomcat-transnwe/bin/logs/%s' %(log_name)\n if not os.path.isfile(filename) :\n print '附件路径:' + log_path + '不存在'\n\n print '附件路径:' + log_path\n if err > 0 : exit()\n \n send_mail('[email protected]', title , date , log_path , log_name)\n \n os.system('rm -rf ' + filename) \n#\t收件人地址、主题、详细内容、附件路径、附件name \n else: \n print '没有日志记录'\n exit()\n"
},
{
"alpha_fraction": 0.5915588736534119,
"alphanum_fraction": 0.6085772514343262,
"avg_line_length": 18.328947067260742,
"blob_id": "4899a5f01b09029f55499e366f0b21db96fc93e3",
"content_id": "795c0bd6c911ef2c3ea7fa2ee046286746ef9450",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1561,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 76,
"path": "/python_example/pyurldownload.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n#\n\n\"\"\"\n@version: ??\n@author: TangHsin\n@license: Apache Licence\n@mailto: [email protected]\n@site: \n@software: PyCharm Community Edition\n@FILE: pyurldownload.py\n@time: 2016/7/9 9:45\n\"\"\"\n\nimport urllib\nimport urllib2\n# import requests\nimport os\n\n\ndef urllib_down(url):\n # 获取文件名\n file_list = os.path.split(url)\n filename = file_list[-1]\n\n # 创建保存目录\n file_dir = os.path.join('e:', 'pydown')\n try:\n os.makedirs(file_dir)\n except Exception as err:\n pass\n file_full_name = os.path.join(file_dir, filename)\n\n # 下载文件\n urllib.urlretrieve(url, file_full_name)\n\n print os.listdir(file_dir)\n pass\n\n\ndef urllib2_down(url):\n # 获取文件名\n filename = os.path.split(url)[-1]\n # 创建保存路径\n file_fullpath = os.path.join('e:', 'pydown', filename)\n try:\n os.makedirs(os.path.split(file_fullpath)[0])\n except:\n pass\n\n f = urllib2.urlopen(url) # 打开一个文件\n data = f.read() # 读取文件\n\n with open(file_fullpath, 'wb') as code: # 以二进制方式写入文件\n code.write(data)\n\n print os.listdir(os.path.split(file_fullpath)[0])\n pass\n\ndef request_down(url):\n r = requests.get(url)\n with open(\"code3.zip\", \"wb\") as code:\n code.write(r.content)\n\ndef main():\n file_url = ur'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'\n\n urllib2_down(file_url)\n # urllib_down(file_url)\n\n pass\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5094265341758728,
"alphanum_fraction": 0.5231736302375793,
"avg_line_length": 19.699186325073242,
"blob_id": "97372512453aa8c845e7664314d2b59572698170",
"content_id": "51d537201cab9735522e9235025f8b766ecba211",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2546,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 123,
"path": "/python_command/pycopy.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: pycopy.py\n@time: 2016/11/24 10:22\n\"\"\"\n\nimport os\nimport sys\nimport shutil\nimport getopt\n\n\ndef usage():\n print '''\n Usage:\n pycopy.py [OPTIONS] src dst\n pycopy.py [OPTIONS] src1 src2 src3 directory\n\n OPTIONS:\n '-f' : force to overwrite dst\n '-i' : interactive to overwrite dst\n '-r' : recutive copy directory # didn't use\n '''\n\n\ndef copy(src, dst):\n if os.path.isdir(src):\n if os.path.exists(dst):\n print \"Error: Directory %s already exists!\"\n else:\n shutil.copytree(src, dst)\n elif os.path.isfile(src):\n shutil.copy(src, dst)\n else:\n pass\n\n print \"%s -> %s\" % (src, dst)\n\n\ndef overwrite(dst, flag):\n if flag:\n return True\n\n ans = raw_input(\"pycopy.py: overwrite '%s' , Y or N ? \" % dst)\n if ans in \"Yy\":\n return True\n else:\n return False\n\n\ndef copy_files(src, dst, ow_flag=False):\n # copy multipule files\n print src\n\n if len(src) == 1:\n fd = src[0]\n if os.path.isdir(dst):\n base_name = os.path.basename(fd)\n dst = os.path.join(dst, base_name)\n\n if os.path.exists(dst) and not overwrite(dst, ow_flag):\n # don't overwrite, next one\n sys.exit(0)\n\n copy(fd, dst)\n\n elif len(src) > 1:\n if not os.path.isdir(dst):\n print \"Error: %s is not exist or not a directory.\"\n sys.exit(1)\n\n for fd in src:\n dst_new = os.path.join(dst, os.path.basename(fd))\n if os.path.exists(dst_new) and not overwrite(dst_new, ow_flag):\n # don't overwrite, next one\n continue\n\n copy(fd, dst_new)\n\n\ndef copy_dir(src, dst):\n pass\n\n\ndef main():\n if '-h' in sys.argv:\n usage()\n sys.exit(0)\n\n opts, args = getopt.getopt(sys.argv[1:], \"hifr\")\n\n if len(args) < 2:\n print \"Error: not enough arguments\"\n sys.exit(1)\n else:\n src = args[:-1]\n dst = args[-1]\n\n for o, a in opts:\n if '-f' in o:\n ow_flag = True\n copy_files(src, dst, ow_flag)\n return None\n if '-i' in o:\n ow_flag = False\n copy_files(src, dst, ow_flag)\n return None\n if '-r' in o:\n pass\n\n copy_files(src, dst)\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5877862572669983,
"alphanum_fraction": 0.5877862572669983,
"avg_line_length": 15.375,
"blob_id": "25d0ae00be89ca6dcbecac7808953cafb0c6320e",
"content_id": "0df75ddf1192a332bbfeb94cf6289e10cf072b8e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 151,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 8,
"path": "/python_code_piece/open_file_via_with.md",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "# 使用with打开文件\n\n```python\n# 打开文件\nwith open(src, 'rb') as fsrc:\n with open(dst, 'wb') as fdst:\n copyfileobj(fsrc, fdst)\n```\n"
},
{
"alpha_fraction": 0.5463743805885315,
"alphanum_fraction": 0.5568296909332275,
"avg_line_length": 22.911291122436523,
"blob_id": "2a890ad135fe41b07c314146369100b11826b17f",
"content_id": "8c1de605f4bfc594fe2312ff6609e0db859b9900",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2965,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 124,
"path": "/python_example/qiniuSync/qiniuSync.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@python_version: python_x86 3.5.2\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: qiniuSync.py\n@time: 2016/12/1 14:44\n\"\"\"\n\nimport os\nimport qiniu\nimport user_cfg\n\nif os.name in ('nt', 'dos', 'ce'):\n from utils import _uri_encode_win32 as _uri_encode\n # import utils._uri_encode_win32 as _uri_encode\nelse:\n from utils import _uri_encode_posix as _uri_encode\n # import utils._uri_encode_posix as _uri_encode\n\n\ndef _local_etag(f):\n return qiniu.etag(f)\n\n\ndef _remote_etag(key):\n ret, info = bucket.stat(bucket_name, key)\n\n # print ret.get('hash')\n try:\n # assert 'hash' in ret\n return ret.get('hash')\n except:\n return None\n\n\ndef _samefile(f):\n if _local_etag(f) == _remote_etag(f):\n # print \"File %s is exist\" % f\n return True\n else:\n # print \"File %s is not exist\" % f\n return False\n\n\ndef _samefile2(l_etag, r_etag):\n if l_etag == r_etag:\n return True\n else:\n return False\n\n\ndef _putfile(f, key):\n local_file = f\n token = auth.upload_token(bucket_name, key)\n\n ret, info = qiniu.put_file(token, key, local_file)\n\n r_etag = ret.get('hash')\n\n print \" Uploading %s -> %s ... \" % (local_file, key),\n if r_etag == _local_etag(local_file):\n print \"SUCCESS\"\n else:\n print \"FAILED\"\n\n\ndef walk_path(path):\n # auth = qiniu.Auth(access_key, secret_key)\n # bucket = qiniu.BucketManager(auth)\n\n os.chdir(path)\n\n path = os.curdir\n for p_path, sub_paths, sub_files in os.walk(path):\n\n for sub_file in sub_files:\n # print os.path.join(p_path, sub_file)\n f = os.path.join(p_path, sub_file)\n\n # get file key in bucket\n if len(bucket_prefix) == 0:\n key = _uri_encode(f)\n else:\n key = \"%s%s\" % (bucket_prefix, _uri_encode(f))\n\n # check file is or not in bucket\n remote_etag = _remote_etag(key)\n local_etag = _local_etag(f)\n if remote_etag is None:\n print \"File %s doesn't exist\" % f\n _putfile(f, key)\n else:\n # _local_etag(f) == _remote_etag(f)\n if not local_etag == remote_etag:\n print \"File %s exists, but etag %s != %s \" % (f, local_etag, remote_etag)\n _putfile(f, key)\n else:\n print \"File %s already exists\" % f\n\n\nif __name__ == '__main__':\n\n bucket_prefix = ''\n access_key = user_cfg.access_key\n secret_key = user_cfg.secret_key\n bucket_name = user_cfg.bucket_name\n local_path = user_cfg.local_path\n\n try:\n bucket_prefix = user_cfg.bucket_prefix\n except:\n pass\n\n auth = qiniu.Auth(access_key, secret_key)\n bucket = qiniu.BucketManager(auth)\n\n walk_path(local_path)\n"
},
{
"alpha_fraction": 0.393180251121521,
"alphanum_fraction": 0.41336116194725037,
"avg_line_length": 25.090909957885742,
"blob_id": "40301a2308b29b028aaa66e252f7495b5bb814c1",
"content_id": "a349bd203ff0bb5d0687d190b6eb8b359e990630",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1437,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 55,
"path": "/python_command/pyseq.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#-------------------------------------------------------------------------------\n# Name: pyseq\n# Author: uyinn\n# Mailto: [email protected]\n# Created: 21/04/2014\n# version: python2.7\n#-------------------------------------------------------------------------------\nimport sys\n\nif __name__ == '__main__':\n sysargv=sys.argv\n# print sysargv\n# get paraments\n westr='%d'\n sep='\\n'\n\n try:\n # to get paraments by overview arguments\n for x in xrange(len(sysargv)):\n if sysargv[1] =='-w':\n sysargv.pop(1)\n we=len(str(sysargv[-1]))\n westr='%0'+str(we)+'d'\n\n elif sysargv[1] == '-s':\n sysargv.pop(1)\n sep=sysargv.pop(1)\n\n # get start-point,stop-point,and step\n start,step=1,1\n\n if len(sysargv) == 2:\n stop=sysargv[1]\n elif len(sysargv) == 3 or len(sysargv)==4:\n start=sysargv[1]\n stop=sysargv[2]\n try:\n step=sysargv[3]\n except:\n pass\n else:\n print 'error argvs'\n sys.exit(1)\n\n wesep=westr+sep\n\n # call pyseq\n output=''\n for x in xrange(int(start),int(stop)+1,int(step)):\n output+=(wesep % x)\n print output\n except:\n print 'Usage: %s [[-w] [-f sepchar]] [start] stop [step]'\n\n\n"
},
{
"alpha_fraction": 0.5039768815040588,
"alphanum_fraction": 0.5216919779777527,
"avg_line_length": 19.64179039001465,
"blob_id": "28efa1f631e590679935bb625827e69d7fe38b23",
"content_id": "3374f78e67533b450b2435fb562d30407d380c07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3162,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 134,
"path": "/python_command/pyoudao.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/evn python\n# encoding:utf-8\n#\n# 有道词典\n#\nimport urllib\nimport re\nimport os\nimport sys\n\n'''\n2016-11-08:\n + 增加 getopt 参数选择\n + \"-s / --split \" 分别查询参数\n + 默认,将所有参数当成一个短语来查询\n\n2016-11-07:\n + 增加查询短语\n + 增加分别查询单词中的所有参数\n to do: 增加参数 -s --split , 判断选择查询短语或单词\n'''\n\n\ndef get_youdao(word):\n word = to_remove_blank(word)\n youdaoDict_url = r'http://youdao.com/w/eng/%s/' % word\n\n # print youdaoDict_url\n content = urllib.urlopen(youdaoDict_url).read()\n\n # dict_patt = r'<li> \\w*?</li>'\n dict_patt = r'<li>(.*?)</li>'\n\n patt = re.compile(dict_patt)\n\n results = patt.findall(content)\n\n # print results\n\n for result in results:\n #\n # print result //\n '''\n result=ur'<li>num. 一;一个</li>'\n\n 分解步骤:\n result2=result.split('<li>')[1]\n 设<li>为分隔符,对result进行分割,获得一个数组,取右边得result2\n result3=result2.rsplit('</li>')[0]\n 设</li>为分隔符,对result2进行分割,获得一个数组,取左边得result3\n '''\n try:\n # print \" %s\" % result.split('<li>')[1].rsplit('</li>')[0]\n # print result[0]\n if result[0] != r'<':\n # print result\n print result.decode('utf-8') # 强制使用utf-8编码\n\n except:\n pass\n\n\ndef to_remove_blank(string):\n '''\n 删除左右空格并将中间空格转换成为 '%20'\n :param string: 一个包含空格的字符串\n :return: 字符串\n '''\n return '%20'.join(string.strip(' ').split(' '))\n\n\ndef to_translate_phrase(args):\n '''\n :param argvs: 系统参数\n :return: 将参数列表转换为字符串并返回\n '''\n try:\n # print str(argvs)\n print \"\\n%s : \" % ' '.join(args)\n # return '%20'.join(argvs)\n get_youdao('%20'.join(args))\n # get_youdao(args)\n except:\n pass\n\n\ndef to_translate_every_word(args):\n for word in args:\n print \"\\n%s : \" % word\n get_youdao(word)\n\n\ndef to_switch(opts, args):\n try:\n # print opts\n # print args\n if len(opts) == 0:\n to_translate_phrase(args)\n sys.exit(0)\n if opts[0][0] in ('-s', '--split'):\n # print \"opt is not none\"\n to_translate_every_word(args)\n sys.exit(0)\n except:\n pass\n\n\nif __name__ == \"__main__\":\n # sys.argv 是一个数组,包含文件本身所有变量。\n # py文件本身为sys.argv[0]\n\n # if len(sys.argv) == 2:\n # word = sys.argv[1]\n # print \"%s : \" % word\n # get_youdao(word)\n\n # get_youdao(to_remove_blank(word))\n\n # word = \"go on\"\n # get_youdao(to_remove_blank(word))\n\n # get_youdao(to_list2string(sys.argv))\n\n # to_translate_phrase(sys.argv)\n\n import getopt\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"s\", \"split\")\n to_switch(opts, args)\n # print opts\n # print args\n except getopt.GetoptError, err:\n print err\n"
},
{
"alpha_fraction": 0.44399091601371765,
"alphanum_fraction": 0.4947845935821533,
"avg_line_length": 22.210525512695312,
"blob_id": "283cafabbd95e56b15bed155e90f4b067b122c86",
"content_id": "e6ec53d3fea7b92ecefdf780ec8fb30ba359d1f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2471,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 95,
"path": "/python_command/pypaste.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\n# File Name: pypaste.py\n# Author: uyinn\n# mail: [email protected]\n# Created Time: Sat 19 Apr 2014 11:27:24 AM CST\n#########################################################################\n\nimport os\nimport sys\n\n\ndef usage(command_name):\n print ur\"\"\"\n 将两个文件合并左右合并为一个文件\n $ cat file1.txt file2.txt\n Tue Sep 8 14:41:55 HKT 2015\n Tue Sep 8 14:41:59 HKT 2015\n\n $ python pypaste.py -d \\- file1.txt file2.txt\n Tue Sep 8 14:41:59 HKT 2015 - Tue Sep 8 14:41:55 HKT 2015\n\n Usage:\n %s -d sep file1 file2\n + 如果分隔符为特殊字符(空格、引号)时,需要用使用跳脱符号\n\n \"\"\" % command_name\n\n# 三元运算符表达式\n# def trans(a,b):\n# return a if a > b else b\n\ndef main(file1, file2, sep='\\t'):\n # 判断给予的文件是否存在\n for path in file1, file2:\n if not os.path.isfile(path):\n print '%s : is not a file or not exist' % path\n sys.exit(1)\n\n # 创建两个列表文件\n f1list = list()\n f2list = list()\n\n # 向之前的两个列表文件中各自添加file1 and file2 的行。\n f = open(file1, 'r')\n f1width = 0\n for line in f.readlines():\n f1list.append(line.strip('\\n'))\n # 获取file1的最长行宽度\n f1width = f1width if f1width > len(f1list[-1]) else len(f1list[-1])\n # print f1width\n f.close()\n\n f = open(file2, 'r')\n for line in f.readlines():\n f2list.append(line.strip('\\n'))\n f.close()\n\n # 获取两个文件最大行数\n maxraw = len(f1list) if len(f1list) > len(f2list) else len(f2list)\n\n # 输出结果\n for x in xrange(maxraw):\n try:\n # 如果file1是空行,使用空格补全\n # if len(f1list[x]) == 0:\n # print len(f1list[x])\n # print ' ' * f1width-1,\n print f1list[x],\n except:\n # 如果file1无此行,使用空格补全\n # print ' ' * f1width,\n pass\n print sep,\n try:\n print f2list[x],\n except:\n pass\n print ''\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 5:\n if sys.argv[1] == '-d':\n sep = sys.argv[2]\n elif len(sys.argv) == 3:\n sep = '\\t'\n else:\n usage(sys.argv[0])\n\n file1 = sys.argv[-2]\n file2 = sys.argv[-1]\n\n main(file1, file2, sep)\n"
},
{
"alpha_fraction": 0.5309381484985352,
"alphanum_fraction": 0.5482368469238281,
"avg_line_length": 20.16901397705078,
"blob_id": "5464cc3e1d1f62add9b3a0fb61d2ba21566cada2",
"content_id": "da843d505880f9339f79d2491fb2bd99fae9bdf8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1503,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 71,
"path": "/python_example/batch_files_rename.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: batch_files_rename.py\n@time: 2016/11/23 15:56\n\"\"\"\n\nimport os\nimport sys\n\n\ndef rename_file(work_dir, old_ext, new_ext):\n for old_name in os.listdir(work_dir):\n # print old_name\n\n file_name, file_ext = os.path.splitext(old_name)\n # print file_name, file_ext\n\n # file extension matched\n if file_ext == old_ext:\n # print old_name\n\n # 2 ways to get new_name\n new_name = old_name.replace(old_ext, new_ext)\n # new_name = filename + new_ext\n\n # print old_name, new_name\n\n # have to use os.path.join()\n # otherwise may missing file\n os.renames(\n os.path.join(work_dir, old_name),\n os.path.join(work_dir, new_name)\n )\n\n\ndef usage():\n print \"Usage: %s work_dir old_ext new_ext\" % (sys.argv[0])\n\n\ndef main():\n # work_dir = r'E:\\Documents\\GitHub\\python'\n # old_ext = '.bak'\n # new_ext = '.ori'\n\n try:\n # the files in which folder\n work_dir = sys.argv[1]\n\n # which kind of files to rename\n old_ext = sys.argv[2]\n\n # the new extension for files\n new_ext = sys.argv[3]\n\n # do rename\n rename_file(work_dir, old_ext, new_ext)\n\n except:\n usage()\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.5081713795661926,
"alphanum_fraction": 0.5216431021690369,
"avg_line_length": 23.085105895996094,
"blob_id": "db00eebe37c38f32a1df92ab2af810dcbf65c571",
"content_id": "f06292c9fb7179022ebbf1dade5357e62b7b05de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4528,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 188,
"path": "/python_example/aliyun_oss_sync/aliyun_oss_sync.py",
"repo_name": "octowhale/python",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 01\n@author: \n@license: Apache Licence \n@python_version: python_x86 2.7.11\n@python_version: python_x86 3.5.2\n@site: octowahle@github\n@software: PyCharm Community Edition\n@file: aliyun_oss_sync.py\n@time: 2016/12/2 10:29\n\n# 2016-12-05\n + add cdn refresh log in put_files function.\n + like cdn_refresh_2016-12-02_19-37.log\n + module at cdn_refresh_log_obj\n + add get_files fuction.\n\"\"\"\n\nimport os\nimport sys\nimport oss2\nimport hashlib\nimport datetime\n\nfrom user_cfg import *\n\n\ndef _local_etag(data):\n md5_hash = hashlib.md5(data).hexdigest()\n\n # print \"line 28: %s\" % md5_hash\n return md5_hash.upper()\n\n\ndef _remote_etag(key):\n try:\n result = bucket.get_object_meta(key)\n etag = result.etag\n\n return etag\n except:\n return None\n\n\ndef _put_file(key, data):\n print \"Uploading ... \",\n\n try:\n bucket.put_object(key, data)\n print \"Success!\"\n return None\n except oss2.exceptions as err:\n print err\n print \"Failed!\"\n print \"Failed!\"\n\n\ndef _get_file(key):\n print \"Downloading ... \",\n try:\n file_obj = bucket.get_object(key)\n\n # remove the prefix in key\n if \"remove_prefix\" is True:\n key = '/'.join(key.split('/')[1:])\n\n # f = open(key, 'wb')\n # f.write(file_obj.read())\n # f.close()\n\n with open(key, 'wb') as f:\n f.write(file_obj.read())\n\n print \"Success!\"\n except oss2.exceptions as err:\n print err\n print \"Failed!\"\n\n\ndef _uri_encode(f, pfix):\n f_list = f.split(os.path.sep)\n uri = '/'.join(f_list[1:])\n return \"%s%s\" % (pfix, uri)\n\n\ndef usage():\n print \"Usage: aliyun_oss_sync.py [get|put] -c config.json \"\n sys.exit(1)\n\n\ndef put_files(path):\n # log file for cdn refresh\n dt = datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\")\n cdn_refresh_log = 'cdn_refresh_%s.log' % dt\n cdn_refresh_log_obj = open(cdn_refresh_log, 'w+')\n\n os.chdir(path)\n path = os.curdir\n\n for dir_path, dir_names, file_names in os.walk(path):\n for file_name in file_names:\n f = os.path.join(dir_path, file_name)\n\n key = _uri_encode(f, bucket_prefix)\n\n with open(f, 'rb') as f_obj:\n data = f_obj.read()\n remote_etag = _remote_etag(key)\n local_etag = _local_etag(data)\n\n if remote_etag is None:\n print \"File: %s doesn't exist. -> \" % f,\n _put_file(key, data)\n continue\n\n if remote_etag == local_etag:\n print \"File: %s already exists -> skip\" % f\n continue\n else:\n print \"File: %s exists, but etag '%s' != '%s'. -> \" % (f, local_etag, remote_etag),\n _put_file(key, data)\n\n cdn_refresh_url = \"http://%s/%s\" % (cdn_domain, key)\n cdn_refresh_log_obj.write(cdn_refresh_url)\n\n cdn_refresh_log_obj.close()\n\n\ndef get_files(path):\n\n os.chdir(path)\n list_obj = bucket.list_objects(bucket_prefix)\n obj_list = list_obj.object_list\n\n for obj in obj_list:\n\n # print dir(obj) # \"'etag', 'is_prefix', 'key', 'last_modified', 'size', 'storage_class', 'type'\"\n key = obj.key\n\n if os.path.exists(key) is True:\n\n remote_etag = obj.etag\n with open(key, 'rb') as data:\n local_etag = _local_etag(data.read())\n\n if local_etag == remote_etag:\n print \"File %s exists -> skip\" % key\n continue\n else:\n print \"File %s exists, but etag %s != %s -> \" % (key, local_etag, remote_etag),\n _get_file(key)\n else:\n\n # file_name = os.path.basename(key)\n dir_name = os.path.dirname(key)\n\n if os.path.exists(dir_name) is False:\n os.makedirs(dir_name)\n\n print \"File %s doesn't exist -> \" % key,\n _get_file(key)\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n usage()\n\n action = sys.argv[1]\n\n # run function\n try:\n auth = oss2.Auth(access_key, secret_key)\n bucket = oss2.Bucket(auth, endpoint, bucket_name)\n\n if action == 'get':\n get_files(local_path)\n elif action == 'put':\n put_files(local_path)\n else:\n usage()\n\n except Exception as err:\n print err\n usage()\n"
}
] | 27 |
aka-sham/sublime | https://github.com/aka-sham/sublime | 118e755018389f66d9c0178c7dd9d1663ac05ed0 | eb6f55c8c8e066df0800e5ae8ba355610c1374d4 | 47b61c36aaf9559baa9d3f596f97a1f4268e3011 | refs/heads/master | 2023-04-15T06:22:00.076654 | 2014-03-21T16:50:21 | 2014-03-21T16:50:21 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4364791214466095,
"alphanum_fraction": 0.4455535411834717,
"avg_line_length": 28,
"blob_id": "1a963fdd4143b313e2e06a3e8dd8967ec6466597",
"content_id": "459cc56a6a5d68040f12ded58961f770f66d8726",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1102,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 38,
"path": "/Tests/test_server.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : test_server.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 03/09/2013\n##\n\nimport unittest\n\nfrom sublime.server import SubtitleProvider\n\n\n# -----------------------------------------------------------------------------\n#\n# SubtitleProviderTestCase class\n#\n# -----------------------------------------------------------------------------\nclass SubtitleProviderTestCase(unittest.TestCase):\n \"\"\" Tests SubtitleProvider class. \"\"\"\n\n def test_get_providers(self):\n \"\"\" Tests getting all Subtitle Providers. \"\"\"\n all_providers = SubtitleProvider.get_providers()\n open_subtitle_provider = SubtitleProvider(\n \"OpenSubtitles\", \"http://www.opensubtitles.org\", \"os\")\n self.assertIn(open_subtitle_provider, all_providers)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n# EOF\n"
},
{
"alpha_fraction": 0.49473413825035095,
"alphanum_fraction": 0.49897250533103943,
"avg_line_length": 30.522266387939453,
"blob_id": "a0fed4aed1410595832c41e6ad2226a9f1ff8e68",
"content_id": "29f003b33954942610e41aeac8215c28c7fa913d",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7786,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 247,
"path": "/Sources/sublime/util.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : util.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 29/08/2013\n##\n\nimport os\nimport sys\nimport logging.config\nimport subprocess\nimport csv\n\n\n# -----------------------------------------------------------------------------\n#\n# Signature class\n#\n# -----------------------------------------------------------------------------\nclass Signature(object):\n \"\"\" Signature class which hold information about file signatures. \"\"\"\n\n def __init__(self, magic_number, description):\n \"\"\" Initializes instance. \"\"\"\n self.magic_number = magic_number\n self.description = description\n self.extensions = set()\n\n def __eq__(self, other):\n return self.magic_number == other.magic_number\n\n def __repr__(self):\n return \"<Signature('{}', '{}', '{}')>\".format(\n self.magic_number, self.description, self.extensions)\n\n\n# -----------------------------------------------------------------------------\n#\n# FileMagic class\n#\n# -----------------------------------------------------------------------------\nclass FileMagic(object):\n \"\"\" FileMagic will try to determine the file's type by using\n file signatures (magic numbers in the file's header). \"\"\"\n\n # Singleton pattern\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n \"\"\" If there is already a FileMagic instance\n returns this one.\n Ensures that there is only one instance of FileMagic\n is running in SubLime.\"\"\"\n if not FileMagic._instance:\n FileMagic._instance = FileMagic.__FileMagic(*args, **kwargs)\n return FileMagic._instance\n\n def __getattr__(self, attr):\n return getattr(self._instance, attr)\n\n def __setattr__(self, attr, val):\n return setattr(self._instance, attr, val)\n\n class __FileMagic():\n \"\"\" Inner class for Singleton purpose. \"\"\"\n\n def __init__(self, video_extensions):\n \"\"\" Initializes instance. \"\"\"\n self._video_extensions = video_extensions\n self._magic_numbers = {}\n self._max_nb_bytes = 0\n\n # Loads CSV config file containing all magic numbers\n signatures_filepath = os.path.join(\n get_exe_dir(), \"Config\", \"file_signatures.csv\")\n with open(signatures_filepath, \"r\", encoding='utf-8') as sign_file:\n reader = csv.reader(\n sign_file, delimiter=',', quoting=csv.QUOTE_ALL)\n for line in reader:\n extension = line[0].strip()\n magic_number = line[1].strip()\n description = line[2].strip()\n\n if extension in self._video_extensions:\n magic_number = tuple(\n int(figure, 16) for figure in magic_number.split()\n )\n\n cur_signature = Signature(magic_number, description)\n signature = self._magic_numbers.setdefault(\n magic_number, cur_signature)\n signature.extensions.add(extension)\n\n self._max_nb_bytes = max(\n [len(magic) for magic in self._magic_numbers.keys()])\n\n self._mkv_magic_number = tuple(\n int(figure, 16) for figure in \"1A 45 DF A3 93 42 82 88\".split()\n )\n\n def get_video_signature(self, filepath):\n \"\"\" Gets video file signature\n if a file given by its filepath is a video. \"\"\"\n recognized = False\n file_signature = None\n\n _, ext = os.path.splitext(filepath)\n\n if ext in self._video_extensions:\n\n all_magic_numbers = self._magic_numbers.keys()\n\n with open(filepath, 'rb') as file_handler:\n header = tuple(\n int(o) for o in file_handler.read(self._max_nb_bytes)\n )\n\n for magic in all_magic_numbers:\n if header[:len(magic)] == magic:\n file_signature = self._magic_numbers[magic]\n if ext in file_signature.extensions:\n recognized = True\n break\n\n if not recognized:\n if file_signature:\n raise FileExtensionMismatchError(\n filepath, file_signature)\n else:\n raise FileUnknownError(filepath)\n\n return file_signature\n\n def is_mkv(self, file_signature):\n \"\"\" Determines if a file signature is a MKV. \"\"\"\n return file_signature.magic_number == self._mkv_magic_number\n\n\n# -----------------------------------------------------------------------------\n#\n# Exceptions\n#\n# -----------------------------------------------------------------------------\nclass FileMagicError(Exception):\n pass\n\n\nclass FileExtensionMismatchError(FileMagicError):\n \"\"\" Exception raised if the extension of a file and its signature mismatch.\n\n Attributes:\n filepath -- path of file\n file_signature -- File signature detected by FileMagic. \"\"\"\n\n def __init__(self, filepath, file_signature):\n self.filepath = filepath\n self.file_signature = file_signature\n\n def __str__(self):\n return (\n \"The video file called {} is supposed to be a video but \"\n \"its signature doesn't: {}.\"\n \"\\nExpected extension: {}\".format(\n self.filepath,\n self.file_signature.description,\n \" or \".join(self.file_signature.extensions))\n )\n\n\nclass FileUnknownError(FileMagicError):\n \"\"\" Exception raised if a file is not recognized by FileMagic.\n\n Attributes:\n filepath -- path of file \"\"\"\n\n def __init__(self, filepath):\n self.filepath = filepath\n\n def __str__(self):\n return (\n \"The file called {} was not recognized by Sublime.\".format(\n self.filepath)\n )\n\n\n# -----------------------------------------------------------------------------\n#\n# Module methods\n#\n# -----------------------------------------------------------------------------\ndef get_exe_dir():\n \"\"\" Gets Executable directory. \"\"\"\n if 'sublime' in os.path.basename(sys.executable).lower():\n exe_dir = os.path.dirname(sys.executable)\n else:\n exe_dir = '.'\n\n return exe_dir\n\n\ndef init_logging():\n \"\"\" Loads logging configuration file and inits logging system. \"\"\"\n exe_dir = get_exe_dir()\n\n # Log directory\n log_dir = os.path.join(exe_dir, 'logs')\n if not os.path.exists(log_dir):\n os.mkdir(log_dir)\n\n # Configuration file for logger\n log_file = os.path.join(exe_dir, 'Config', 'logging.conf')\n # Load configuration file\n logging.config.fileConfig(log_file)\n\n return logging.getLogger(\"sublime\")\n\n\ndef system(*args, **kwargs):\n \"\"\" Launches a command line system. \"\"\"\n kwargs.setdefault('stdout', subprocess.PIPE)\n proc = subprocess.Popen(args, **kwargs)\n out, err = proc.communicate()\n\n return out\n\n\ndef get_version_from_git():\n \"\"\" Gets the version number of application\n from Git repository. \"\"\"\n verstr = \"Unknow\"\n try:\n verstr = system(\n 'git', 'describe', '--abbrev=0').strip().decode(\"utf-8\")\n except Exception as error:\n print(\"Cannot find the version number of SubLime. Error: {}\".format(\n error))\n\n return verstr\n\n\n# EOF\n"
},
{
"alpha_fraction": 0.6032693982124329,
"alphanum_fraction": 0.6131719350814819,
"avg_line_length": 36.20467758178711,
"blob_id": "db31d04547da6d1343be6c518fb3f3e332cfb682",
"content_id": "4704df1fb1211fe3f75b32b70273d11fc4c2b467",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6362,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 171,
"path": "/Tests/test_providers.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : test_providers.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 18/03/2014\n##\n\nimport unittest\nimport os\nimport shutil\n\nimport babelfish\n\nfrom sublime.util import get_exe_dir\n\nfrom sublime.core import Video\nfrom sublime.core import VideoSizeError\nfrom sublime.core import VideoHashCodeError\n\nfrom sublime.providers.opensubtitles import OpenSubtitlesServer\n\n\n# -----------------------------------------------------------------------------\n#\n# OpenSubtitlesServerTestCase class\n#\n# -----------------------------------------------------------------------------\nclass OpenSubtitlesServerTestCase(unittest.TestCase):\n \"\"\" Tests OpenSubtitlesServer functions. \"\"\"\n\n def setUp(self):\n self.languages = ['eng', 'fra']\n self.babel_languages = [\n babelfish.Language(code) for code in self.languages\n ]\n\n self.mock_hashcode = lambda filepath: \"8fcf0167e19c41be\"\n\n self.video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'movie.avi')\n self.video2_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'small.mp4')\n self.expected_french_subtitle_filename = \\\n os.path.join(get_exe_dir(), 'Tests', 'Fixtures', 'movie.fr.srt')\n self.expected_english_subtitle_filename = \\\n os.path.join(get_exe_dir(), 'Tests', 'Fixtures', 'movie.en.srt')\n\n self.expected_renamed_video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Louie_S01E01_Pilot.avi')\n self.expected_renamed_french_subtitle_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Louie_S01E01_Pilot.fr.srt')\n self.expected_renamed_english_subtitle_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Louie_S01E01_Pilot.en.srt')\n\n def test_generate_hash_code(self):\n \"\"\" Tests that generate_hash_code generates a correct hash code. \"\"\"\n server = OpenSubtitlesServer()\n\n video_filepath = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'hashcode.txt')\n expected_hash = \"13fb1d63375cf197\"\n result_hash = server.hashcode(video_filepath)\n\n self.assertEqual(result_hash, expected_hash)\n\n # Test exception file too small\n video_filepath = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'hashcode_small.txt')\n with self.assertRaises(VideoSizeError) as error:\n server.hashcode(video_filepath)\n\n self.assertEqual(error.exception.video_filepath, video_filepath)\n\n # Test exception file does not exist\n video_filepath = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'DUMMY')\n with self.assertRaises(VideoHashCodeError) as error:\n server.hashcode(video_filepath)\n\n self.assertEqual(error.exception.video_filepath, video_filepath)\n self.assertIsNotNone(error.exception.error)\n\n def test_connect_to_OpenSubtitles(self):\n \"\"\" Tests if it is possible to connect to OpenSubtitles. \"\"\"\n server = OpenSubtitlesServer()\n server.connect()\n self.assertTrue(server.connected)\n server.disconnect()\n self.assertFalse(server.connected)\n\n def test_download_from_OpenSubtitles(self):\n \"\"\" Tests if it is possible to download\n a subtitle from OpenSubtitles. \"\"\"\n episode = Video(self.video_filename)\n episode.size = str(243500836)\n episode.languages_to_download = self.babel_languages\n\n server = OpenSubtitlesServer()\n server.connect()\n response = server.download_subtitles(\n [episode], self.babel_languages,\n mock_hash=self.mock_hashcode)\n self.assertTrue(response)\n self.assertTrue(os.path.exists(\n self.expected_french_subtitle_filename))\n self.assertTrue(os.path.exists(\n self.expected_english_subtitle_filename))\n server.disconnect()\n\n def test_download_and_rename_from_OpenSubtitles(self):\n \"\"\" Tests if it is possible to download\n and rename a subtitle from OpenSubtitles. \"\"\"\n episode = Video(self.video_filename)\n episode.size = str(243500836)\n episode.languages_to_download = self.babel_languages\n\n server = OpenSubtitlesServer()\n server.connect()\n response = server.download_subtitles(\n [episode], self.babel_languages, True,\n mock_hash=self.mock_hashcode)\n self.assertTrue(response)\n self.assertTrue(os.path.exists(self.expected_renamed_video_filename))\n self.assertTrue(os.path.exists(\n self.expected_renamed_french_subtitle_filename))\n self.assertTrue(os.path.exists(\n self.expected_renamed_english_subtitle_filename))\n server.disconnect()\n\n def test_download_but_no_result_from_OpenSubtitles(self):\n \"\"\" Tests what happens when there is\n no subtitle from OpenSubtitles. \"\"\"\n video = Video(self.video2_filename)\n\n video.languages_to_download = self.babel_languages\n\n server = OpenSubtitlesServer()\n server.connect()\n response = server.download_subtitles([video], self.babel_languages)\n self.assertFalse(response)\n server.disconnect()\n\n def tearDown(self):\n \"\"\" Clean up \"\"\"\n if os.path.exists(self.expected_renamed_video_filename):\n shutil.move(\n self.expected_renamed_video_filename, self.video_filename)\n\n if os.path.exists(self.expected_french_subtitle_filename):\n os.remove(self.expected_french_subtitle_filename)\n\n if os.path.exists(self.expected_english_subtitle_filename):\n os.remove(self.expected_english_subtitle_filename)\n\n if os.path.exists(self.expected_renamed_french_subtitle_filename):\n os.remove(self.expected_renamed_french_subtitle_filename)\n\n if os.path.exists(self.expected_renamed_english_subtitle_filename):\n os.remove(self.expected_renamed_english_subtitle_filename)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n# EOF\n"
},
{
"alpha_fraction": 0.34489402174949646,
"alphanum_fraction": 0.3641618490219116,
"avg_line_length": 19.760000228881836,
"blob_id": "836877d6107fc0fd964620813ad913585dc42a49",
"content_id": "53899097016a2a74626c6286a2c8e2b661dcdacd",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 519,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 25,
"path": "/Sources/SubLime.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : SubLime.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 28/02/2014\n##\n\nfrom sublime import cli\nfrom sublime import util\n\n__version__ = util.get_version_from_git()\n\n###\n# MAIN\n##\nif __name__ == '__main__':\n cli.run()\n\n# EOF\n"
},
{
"alpha_fraction": 0.5210905075073242,
"alphanum_fraction": 0.526349663734436,
"avg_line_length": 34.69731903076172,
"blob_id": "6ba4459bbd61724e8989d0a4f3b8cae7e68587ba",
"content_id": "c20f272bb72d176d6e2adc6e4e969d6a343cbf84",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9317,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 261,
"path": "/Sources/sublime/providers/opensubtitles.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : OpenSubtitles.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 18/03/2014\n##\n\nimport logging\nimport zlib\nimport base64\nimport re\nimport itertools\nimport struct\nimport os\n\nfrom babelfish import Language\n\nfrom sublime.core import Subtitle\nfrom sublime.core import Movie\nfrom sublime.core import Episode\nfrom sublime.core import VideoFactory\nfrom sublime.core import VideoError\nfrom sublime.core import VideoSizeError\nfrom sublime.core import VideoHashCodeError\n\nfrom sublime.server import SubtitleProvider\nfrom sublime.server import XMLRPCServer\nfrom sublime.server import SubtitleServerError\n\n# Logger\nLOG = logging.getLogger(\"sublime.providers.OpenSubtitles\")\n\n\n# -----------------------------------------------------------------------------\n#\n# OpenSubtitlesServer class\n#\n# -----------------------------------------------------------------------------\nclass OpenSubtitlesServer(SubtitleProvider, XMLRPCServer):\n \"\"\" \"\"\"\n XMLRPC_URI = \"http://api.opensubtitles.org/xml-rpc\"\n DEFAULT_LANGUAGE = \"en\"\n\n STATUS_REGEXP = r'(?P<code>\\d+) (?P<message>\\w+)'\n SERIES_REGEXP = r'^\"(?P<serie_name>.*)\" (?P<episode_name>.*)$'\n\n def __init__(self):\n \"\"\" Initializes instance. \"\"\"\n SubtitleProvider.__init__(\n self,\n \"OpenSubtitles\",\n \"http://www.opensubtitles.org\",\n \"os\"\n )\n XMLRPCServer.__init__(self, OpenSubtitlesServer.XMLRPC_URI)\n\n self._status_regexp = re.compile(OpenSubtitlesServer.STATUS_REGEXP)\n self._series_regexp = re.compile(OpenSubtitlesServer.SERIES_REGEXP)\n\n def _do_connect(self):\n \"\"\" Connect to Server. \"\"\"\n response = self._proxy.LogIn(\n \"\", \"\",\n OpenSubtitlesServer.DEFAULT_LANGUAGE, XMLRPCServer.USER_AGENT)\n\n LOG.debug(\"Connect response: {}\".format(response))\n\n if self.status_ok(response):\n self._session_string = response['token']\n self.connected = True\n else:\n raise SubtitleServerError(self, self.get_status_reason(response))\n\n return self.connected\n\n def _do_disconnect(self):\n \"\"\" Disconnect from Server. \"\"\"\n response = self._proxy.LogOut(self._session_string)\n\n if self.status_ok(response):\n self._proxy(\"close\")()\n self.connected = False\n else:\n raise SubtitleServerError(self, self.get_status_reason(response))\n\n return not self.connected\n\n def _do_search_subtitles(self, videos_hashcode, languages):\n \"\"\" Search list of subtitles. \"\"\"\n subtitles_infos = []\n\n # Search subtitles\n hashcodes_sizes = [\n {'moviehash': hash_code, 'moviebytesize': video.size}\n for hash_code, video in videos_hashcode.items()\n ]\n response = self._proxy.SearchSubtitles(\n self._session_string, hashcodes_sizes)\n\n if self.status_ok(response):\n if 'data' in response and response['data']:\n for data_subtitle in response['data']:\n # Retrieve important info\n sub_video_hashcode = data_subtitle['MovieHash']\n sub_video = videos_hashcode[sub_video_hashcode]\n sub_lang = Language.fromopensubtitles(\n data_subtitle['SubLanguageID'])\n\n if sub_lang in sub_video.languages_to_download \\\n and sub_lang in languages:\n # Subtitle infos\n sub_id = data_subtitle['IDSubtitleFile']\n sub_rating = float(data_subtitle['SubRating'])\n sub_format = data_subtitle['SubFormat']\n\n # Video infos\n sub_video_name = data_subtitle['MovieName']\n\n if data_subtitle['MovieKind'] == \"movie\":\n sub_video = VideoFactory.make_from_type(\n sub_video, Movie)\n elif data_subtitle['MovieKind'] == \"episode\":\n sub_video = VideoFactory.make_from_type(\n sub_video, Episode)\n\n videos_hashcode[sub_video_hashcode] = sub_video\n\n if isinstance(sub_video, Movie):\n sub_video.name = sub_video_name\n elif isinstance(sub_video, Episode):\n # Retrieves serie name and episode name\n match_result = re.match(\n self._series_regexp, sub_video_name)\n sub_video.name = match_result.group(\"serie_name\")\n sub_video.episode_name = match_result.group(\n \"episode_name\")\n\n sub_video.season = int(\n data_subtitle['SeriesSeason'])\n sub_video.episode = int(\n data_subtitle['SeriesEpisode'])\n\n subtitle = Subtitle(\n sub_id, sub_lang, sub_video,\n sub_rating, sub_format)\n subtitles_infos.append(subtitle)\n else:\n raise SubtitleServerError(\n self, \"There is no result when searching for subtitles.\")\n else:\n raise SubtitleServerError(self, self.get_status_reason(response))\n\n return subtitles_infos\n\n def _do_download_subtitles(self, subtitles):\n \"\"\" Download a list of subtitles. \"\"\"\n response = False\n matching_subtitles = {}\n\n # Clean up list of subtitles by taking highest rating per language\n subtitles.sort()\n for _, group in itertools.groupby(subtitles):\n best_subtitle = max(list(group))\n matching_subtitles[best_subtitle.id] = best_subtitle\n\n # Download Subtitles\n subtitles_id = list(matching_subtitles.keys())\n response = self._proxy.DownloadSubtitles(\n self._session_string, subtitles_id)\n\n if self.status_ok(response):\n if 'data' in response and response['data']:\n for encoded_file in response['data']:\n subtitle_id = encoded_file['idsubtitlefile']\n decoded_file = base64.standard_b64decode(\n encoded_file['data'])\n file_data = zlib.decompress(decoded_file, 47)\n\n subtitle = matching_subtitles[subtitle_id]\n subtitle.write(file_data)\n response = True\n else:\n raise SubtitleServerError(\n self, \"There is no result when downloading subtitles.\")\n else:\n raise SubtitleServerError(\n self, self.get_status_reason(response))\n\n return response\n\n def status_ok(self, response):\n \"\"\" Is status returned by server is OK ? \"\"\"\n is_ok = False\n status = response.get(\"status\", None)\n\n if status is not None:\n match_result = re.match(self._status_regexp, status)\n code = int(match_result.group(\"code\"))\n\n if code is 200:\n is_ok = True\n\n return is_ok\n\n def get_status_reason(self, response):\n \"\"\" Returns explanation for a status returned by server. \"\"\"\n reason = \"Unknown error\"\n status = response.get(\"status\", None)\n\n if status is not None:\n match_result = re.match(self._status_regexp, status)\n reason = match_result.group(\"message\")\n\n return reason\n\n def hashcode(self, video_filepath):\n \"\"\" Generates Video Hash code. \"\"\"\n hash_code = None\n\n try:\n struct_format = 'q' # long long\n struct_size = struct.calcsize(struct_format)\n\n with open(video_filepath, \"rb\") as movie_file:\n\n filesize = os.path.getsize(video_filepath)\n movie_hash = filesize\n\n if filesize < 65536 * 2:\n raise VideoError()\n\n for x in range(65536//struct_size):\n buffer = movie_file.read(struct_size)\n (l_value,) = struct.unpack(struct_format, buffer)\n movie_hash += l_value\n movie_hash = movie_hash & 0xFFFFFFFFFFFFFFFF\n\n movie_file.seek(max(0, filesize - 65536), 0)\n\n for x in range(65536//struct_size):\n buffer = movie_file.read(struct_size)\n (l_value,) = struct.unpack(struct_format, buffer)\n movie_hash += l_value\n movie_hash = movie_hash & 0xFFFFFFFFFFFFFFFF\n\n hash_code = \"%016x\" % movie_hash\n except VideoError as error:\n raise VideoSizeError(video_filepath)\n except Exception as error:\n raise VideoHashCodeError(video_filepath, error)\n\n return hash_code\n\n\n# EOF\n"
},
{
"alpha_fraction": 0.5834154486656189,
"alphanum_fraction": 0.5852216482162476,
"avg_line_length": 32.278690338134766,
"blob_id": "d73a6de004273aecd37635fff1e03602b1d75f38",
"content_id": "fe47766e4d6e04d2b6fcf7a08196e07982b97fe3",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6090,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 183,
"path": "/Sources/sublime/cli.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : cli.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 29/08/2013\n##\n\nimport sys\nimport os\nimport argparse\n\nimport babelfish\n\nfrom sublime import util\nfrom sublime.server import SubtitleProvider\nfrom sublime.core import Episode\nfrom sublime.core import VideoFactory\n\n__version__ = util.get_version_from_git()\n\n# Gets execution directory\nexe_dir = util.get_exe_dir()\n\n# Sets environment variable for the application\nos.environ['SUBLIME_HOME'] = exe_dir\n\n# Gets a logger\nLOG = util.init_logging()\n\n\ndef execute(args):\n \"\"\" Executes SubLime with given arguments. \"\"\"\n videos = []\n selected_languages = [\n babelfish.Language(selected_lang)\n for selected_lang in args.selected_languages\n ]\n\n # List of filenames directly given by user\n if args.video_files:\n videos = [\n VideoFactory.make_from_filename(video_filename)\n for video_filename in args.video_files\n ]\n # Or list of filenames by walking through directories\n elif args.directories:\n for movie_dir in args.directories:\n for root, _, files in os.walk(movie_dir):\n for name in files:\n video_filename = os.path.join(root, name)\n video = VideoFactory.make_from_filename(video_filename)\n if video:\n videos.append(video)\n\n # Informs user that there is already existing subtitles\n for video in videos:\n for selected_lang in selected_languages:\n if video.has_subtitle(selected_lang):\n video_type = video.__class__.__name__\n video_name = os.path.basename(video.filename)\n if not args.force:\n LOG.warning(\n \"{} named {} already has a subtitle \"\n \"for {} and nothing will happen for it! \"\n \"Use option '-f --force' to replace.\".format(\n video_type, video_name, selected_lang.name))\n else:\n LOG.info(\n 'Replacing {} subtitle for {} named {}.'.format(\n selected_lang.name, video_type, video_name))\n video.languages_to_download.append(selected_lang)\n else:\n video.languages_to_download.append(selected_lang)\n\n # Search subtitles for videos\n for sub_server in SubtitleProvider.get_providers():\n sub_server.connect()\n sub_server.download_subtitles(\n videos, selected_languages,\n args.rename, args.rename_pattern, args.underscore)\n sub_server.disconnect()\n\n\ndef _file_exists(video_file):\n \"\"\" Checks if given movie file exists. \"\"\"\n if not os.path.exists(video_file):\n raise argparse.ArgumentTypeError(\n \"The video file {} doesn't exist.\".format(video_file))\n elif not os.path.isfile(video_file):\n raise argparse.ArgumentTypeError(\n \"The video {} is not a file.\".format(video_file))\n\n return video_file\n\n\ndef _directory_exists(video_directory):\n \"\"\" Checks if given movie directory exists. \"\"\"\n if not os.path.exists(video_directory):\n raise argparse.ArgumentTypeError(\n \"The video directory {} doesn't exist.\".format(video_directory))\n elif not os.path.isdir(video_directory):\n raise argparse.ArgumentTypeError(\n \"The video directory {} is not a directory.\".format(\n video_directory))\n\n return video_directory\n\n\ndef run():\n \"\"\" Main command-line execution loop. \"\"\"\n # Languages\n language_codes = babelfish.language.LANGUAGES\n default_languages = ('eng', 'fra')\n\n # create the arguments parser\n parser = argparse.ArgumentParser(\n description=(\n \"SubLime is a command-line program for searching \"\n \"and downloading the right subtitles for movies.\"\n ),\n prog='SubLime')\n\n sublime_version = '%(prog)s ' + __version__\n\n parser.add_argument(\n '--version', action='version',\n version=sublime_version)\n\n # Arguments to select video which need subtitles\n files_group = parser.add_mutually_exclusive_group(required=True)\n files_group.add_argument(\n '-m', '--movie', action='append',\n help='List of movie files.', type=_file_exists,\n dest='video_files', metavar='FILES')\n files_group.add_argument(\n '-d', '--directory', action='append',\n help='List of directories containing movie files (recursive search).',\n type=_directory_exists, dest='directories', metavar=\"DIRECTORY\")\n\n # Optional arguments\n parser.add_argument(\n '-l', '--language', action='append',\n default=default_languages, help='Sets languages to filter.',\n dest='selected_languages',\n choices=language_codes, metavar=\"LANGUAGE CODE\")\n parser.add_argument(\n '-f', '--force', action='store_true',\n default=False, help='Replaces existing subtitles.',\n dest='force')\n parser.add_argument(\n '-r', '--rename', action='store_true',\n default=False,\n help='Renames video and their subtitles according to a pattern.',\n dest='rename')\n parser.add_argument(\n '-p', '--pattern', action='store',\n default=Episode.RENAME_PATTERN,\n help='Change default rename pattern for Episodes.',\n dest='rename_pattern')\n parser.add_argument(\n '-u', '--with-underscore', action='store_true',\n default=False,\n help='When renaming video replaces blanks with underscores.',\n dest='underscore')\n\n # Parse the arguments line\n try:\n args = parser.parse_args()\n execute(args)\n except Exception as error:\n LOG.exception(error)\n sys.exit(2)\n\n sys.exit()\n\n\n# EOF\n"
},
{
"alpha_fraction": 0.5662974119186401,
"alphanum_fraction": 0.5814031362533569,
"avg_line_length": 34.04705810546875,
"blob_id": "bcaa334e50334b2a1b084459673fd282e7e782ab",
"content_id": "eafe1cc961f96300761ba5f108642621bfc81100",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2979,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 85,
"path": "/Tests/test_util.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : test_util.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 26/02/2014\n##\n\nimport unittest\nimport os\n\nfrom sublime.core import Video\n\nfrom sublime.util import get_exe_dir\nfrom sublime.util import Signature\nfrom sublime.util import FileMagic\nfrom sublime.util import FileExtensionMismatchError\nfrom sublime.util import FileUnknownError\n\n\n# -----------------------------------------------------------------------------\n#\n# FileMagicTestCase class\n#\n# -----------------------------------------------------------------------------\nclass FileMagicTestCase(unittest.TestCase):\n \"\"\" Tests FileMagic class. \"\"\"\n\n def test_Signature_creation(self):\n \"\"\" Tests creation of a Signature object. \"\"\"\n signature = Signature((45, 67, 21, 112), \"A file signature\")\n\n self.assertEqual(signature.magic_number, (45, 67, 21, 112))\n self.assertEqual(signature.description, \"A file signature\")\n\n def test_FileMagic_as_singleton(self):\n \"\"\" Tests that a FileMagic object is a singleton. \"\"\"\n file_magic_01 = FileMagic(Video.EXTENSIONS)\n file_magic_02 = FileMagic(Video.EXTENSIONS)\n\n self.assertEqual(id(file_magic_01), id(file_magic_02))\n\n def test_FileMagic_get_video_signature(self):\n \"\"\" Tests if FileMagic get a Video file signature. \"\"\"\n file_magic = FileMagic(Video.EXTENSIONS)\n\n video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'submarine.avi')\n not_a_video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'not_a_movie.avi')\n video_filename_with_bad_extension = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'submarine.mp4')\n\n # Tests if a Video file\n self.assertIsNotNone(file_magic.get_video_signature(video_filename))\n\n # Tests a fake video file that raises an Exception\n with self.assertRaises(FileUnknownError) as error:\n file_magic.get_video_signature(not_a_video_filename)\n\n self.assertEqual(\n error.exception.filepath, not_a_video_filename)\n\n # Tests a video file with bad extensions that raises an Exception\n expected_signature = Signature(\n (82, 73, 70, 70), \"Resource Interchange File Format\")\n expected_signature.extensions.add(\".avi\")\n with self.assertRaises(FileExtensionMismatchError) as error:\n file_magic.get_video_signature(video_filename_with_bad_extension)\n\n self.assertEqual(\n error.exception.filepath, video_filename_with_bad_extension)\n self.assertEqual(\n error.exception.file_signature, expected_signature)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n# EOF\n"
},
{
"alpha_fraction": 0.4893028438091278,
"alphanum_fraction": 0.4929634630680084,
"avg_line_length": 30.5205135345459,
"blob_id": "e27032c244b924736e88f1497b2868b30bd91511",
"content_id": "6814e04dfccdf5fa348b3d09af1a0028b0b9ba7a",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12293,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 390,
"path": "/Sources/sublime/core.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : core.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 17/01/2014\n##\n\nimport logging\nimport os\nimport shutil\nimport guessit\nimport enzyme\nimport glob\nimport uuid\n\nfrom babelfish import Language\nfrom babelfish import Error as BabelfishError\n\nfrom sublime.util import FileMagic\nfrom sublime.util import FileMagicError\n\n# Logger\nLOG = logging.getLogger(\"sublime.core\")\n\n\n# -----------------------------------------------------------------------------\n#\n# Video class\n#\n# -----------------------------------------------------------------------------\nclass Video(object):\n \"\"\" Video class. \"\"\"\n\n # List of video extensions\n EXTENSIONS = (\n '.3g2', '.3gp', '.3gp2', '.3gpp', '.60d', '.ajp', '.asf',\n '.asx', '.avchd', '.avi', '.bik', '.bix', '.box', '.cam',\n '.dat', '.divx', '.dmf', '.dv', '.dvr-ms', '.evo', '.flc',\n '.fli', '.flic', '.flv', '.flx', '.gvi', '.gvp', '.h264',\n '.m1v', '.m2p', '.m2ts', '.m2v', '.m4e', '.m4v', '.mjp',\n '.mjpeg', '.mjpg', '.mkv', '.moov', '.mov', '.movhd',\n '.movie', '.movx', '.mp4', '.mpe', '.mpeg', '.mpg', '.mpv',\n '.mpv2', '.mxf', '.nsv', '.nut', '.ogg', '.ogm', '.omf',\n '.ps', '.qt', '.ram', '.rm', '.rmvb', '.swf', '.ts', '.vfw',\n '.vid', '.video', '.viv', '.vivo', '.vob', '.vro', '.wm',\n '.wmv', '.wmx', '.wrap', '.wvx', '.wx', '.x264', '.xvid'\n )\n\n UNDERSCORE = True\n\n # FileMagic to determine file type\n FILE_MAGIC = FileMagic(EXTENSIONS)\n\n def __init__(self, video_filepath):\n \"\"\" Initializes instance. \"\"\"\n self.id = uuid.uuid4()\n self.filename = os.path.abspath(video_filepath)\n self.size = str(os.path.getsize(self.filename))\n self.signature = None\n self.languages_to_download = []\n\n def rename(self):\n \"\"\" Rename movie to a cleaner name. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def _move(self, new_name):\n \"\"\" Move to a new name. \"\"\"\n dir_name = os.path.dirname(self.filename)\n _, extension = os.path.splitext(os.path.basename(self.filename))\n\n new_filename = os.path.join(dir_name, new_name + extension)\n\n try:\n shutil.move(self.filename, new_filename)\n except Exception as error:\n LOG.error(\n \"Cannot rename the file {}: {}\".format(self.filename, error))\n else:\n self.filename = new_filename\n\n def has_subtitle(self, language):\n \"\"\" Returns true if the video has already\n a subtitle for a specific language. \"\"\"\n has_subtitle = False\n\n # Look for embedded subtitle in mkv video\n if Video.is_mkv(self.signature):\n with open(self.filename, 'rb') as file_handler:\n mkv_video = enzyme.MKV(file_handler)\n\n for sub in mkv_video.subtitle_tracks:\n try:\n if sub.language and \\\n Language.fromalpha3b(sub.language) == language:\n has_subtitle = True\n break\n elif sub.name and \\\n Language.fromname(sub.name) == language:\n has_subtitle = True\n break\n except BabelfishError:\n LOG.error(\n \"Embedded subtitle track\"\n \"language {} is not a valid language\"\n .format(sub.language))\n\n # Look for external subtitle\n dir_name = os.path.dirname(self.filename)\n base_name, _ = os.path.splitext(os.path.basename(self.filename))\n\n search_subtitle = os.path.join(\n dir_name, \"{}.{}.*\".format(base_name, language.alpha2))\n existing_subtitles = [\n sub_file for sub_file in glob.glob(search_subtitle)\n if os.path.splitext(sub_file)[1] in Subtitle.EXTENSIONS\n ]\n\n if existing_subtitles:\n has_subtitle = True\n\n return has_subtitle\n\n @staticmethod\n def get_video_signature(video_filepath):\n \"\"\" Gets video file signature\n if a file given by its filepath is a video. \"\"\"\n return Video.FILE_MAGIC.get_video_signature(video_filepath)\n\n @staticmethod\n def is_mkv(file_signature):\n \"\"\" Determines if a file signature is a MKV. \"\"\"\n return Video.FILE_MAGIC.is_mkv(file_signature)\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __repr__(self):\n return \"<Video('{}', '{}', '{}', '{}')>\".format(\n self.filename, self.id, self.size)\n\n\n# -----------------------------------------------------------------------------\n#\n# Movie class\n#\n# -----------------------------------------------------------------------------\nclass Movie(Video):\n \"\"\" Movie class. \"\"\"\n\n def __init__(self, video_filepath):\n \"\"\" Initializes instance. \"\"\"\n Video.__init__(self, video_filepath)\n\n self.name = \"UNKNOWN MOVIE\"\n\n def rename(self):\n \"\"\" Rename movie to a cleaner name. \"\"\"\n new_name = \"{}\".format(self.name)\n\n if Video.UNDERSCORE:\n new_name = new_name.replace(\" \", \"_\")\n\n Video._move(self, new_name)\n\n return self.filename\n\n def __repr__(self):\n return \"<Movie('{}')>\".format(self.name)\n\n\n# -----------------------------------------------------------------------------\n#\n# Episode class\n#\n# -----------------------------------------------------------------------------\nclass Episode(Video):\n \"\"\" Episode class. \"\"\"\n\n RENAME_PATTERN = \"{serie_name} S{season:02d}E{episode:02d} {episode_name}\"\n\n def __init__(self, video_filepath):\n \"\"\" Initializes instance. \"\"\"\n Video.__init__(self, video_filepath)\n\n self.name = \"UNKNOWN SERIE\"\n self.season = 0\n self.episode = 0\n self.episode_name = \"UNKNOWN EPISODE\"\n\n def rename(self):\n \"\"\" Rename movie to a cleaner name. \"\"\"\n new_name = Episode.RENAME_PATTERN.format(\n serie_name=self.name,\n season=self.season,\n episode=self.episode,\n episode_name=self.episode_name\n )\n\n if Video.UNDERSCORE:\n new_name = new_name.replace(\" \", \"_\")\n\n Video._move(self, new_name)\n\n return self.filename\n\n def __repr__(self):\n return \"<Episode('{}', '{}', '{}', '{}')>\".format(\n self.name, self.season, self.episode, self.episode_name)\n\n\n# -----------------------------------------------------------------------------\n#\n# NamePattern class as Context Manager\n#\n# -----------------------------------------------------------------------------\nclass NamePattern(object):\n \"\"\" Pattern context manager used for renaming video files. \"\"\"\n\n def __init__(self, pattern=None, underscore=True):\n self.default_pattern = Episode.RENAME_PATTERN\n self.pattern = pattern\n self.underscore = underscore\n\n def __enter__(self):\n if self.pattern:\n Episode.RENAME_PATTERN = self.pattern\n\n Video.UNDERSCORE = self.underscore\n\n return self.pattern\n\n def __exit__(self, type, value, traceback):\n Episode.RENAME_PATTERN = self.default_pattern\n Video.UNDERSCORE = True\n\n\n# -----------------------------------------------------------------------------\n#\n# VideoFactory class\n#\n# -----------------------------------------------------------------------------\nclass VideoFactory(object):\n \"\"\" VideoFactory class which creates Video instances. \"\"\"\n\n @staticmethod\n def make_from_filename(video_filepath):\n \"\"\" Returns a Movie or an Episode instance if it is possible,\n else returns a Video instance or None. \"\"\"\n video = None\n\n if os.path.exists(video_filepath):\n try:\n video_signature = Video.get_video_signature(video_filepath)\n\n if video_signature:\n guess = guessit.guess_movie_info(\n video_filepath, info=['filename'])\n if guess['type'] == 'movie':\n video = Movie(video_filepath)\n elif guess['type'] == 'episode':\n video = Episode(video_filepath)\n else:\n video = Video(video_filepath)\n\n video.signature = video_signature\n except FileMagicError:\n LOG.warning(\n \"This file was not recognized as a video file: {}\".format(\n video_filepath))\n else:\n LOG.error(\n \"The following doesn't exists: {}\".format(video_filepath))\n\n return video\n\n @staticmethod\n def make_from_type(video, video_type):\n \"\"\" Transforms a video into a Movie or Episode\n depending on video_type. \"\"\"\n if not isinstance(video, (Movie, Episode)):\n new_video = video_type(video.filename)\n new_video.signature = video.signature\n new_video.languages_to_download = video.languages_to_download\n else:\n new_video = video\n\n return new_video\n\n\n# -----------------------------------------------------------------------------\n#\n# Subtitle class\n#\n# -----------------------------------------------------------------------------\nclass Subtitle(object):\n \"\"\" Subtitle class manages subtitle files. \"\"\"\n\n # List of subtitles extensions\n EXTENSIONS = (\n \".aqt\", \".jss\", \".sub\", \".ttxt\",\n \".pjs\", \".psb\", \".rt\", \".smi\",\n \".ssf\", \".srt\", \".gsub\", \".ssa\",\n \".ass\", \".usf\", \".txt\"\n )\n\n def __init__(self, unique_id, language, video, rating=0, extension=None):\n \"\"\" Initializes instance. \"\"\"\n self.id = unique_id\n self.language = language\n self.video = video\n self.rating = rating\n self.extension = extension\n\n @property\n def filepath(self):\n \"\"\" Get filepath of subtitle file we want to write. \"\"\"\n dir_name = os.path.dirname(self.video.filename)\n base_name, _ = os.path.splitext(os.path.basename(self.video.filename))\n filename = \"{}.{}.{}\".format(\n base_name, self.language.alpha2, self.extension)\n\n return os.path.join(dir_name, filename)\n\n def write(self, data):\n \"\"\" Writes Subtitle on disk. \"\"\"\n with open(self.filepath, 'wb') as out_file:\n out_file.write(data)\n\n def __eq__(self, other):\n return (self.language == other.language and self.video == other.video)\n\n def __lt__(self, other):\n return (self == other and self.rating < other.rating)\n\n def __gt__(self, other):\n return (self == other and self.rating > other.rating)\n\n def __repr__(self):\n return \"<Subtitle('{}', '{}', '{}', '{}')>\".format(\n self.id, self.language.alpha3, self.rating, self.extension)\n\n\n# -----------------------------------------------------------------------------\n#\n# Exceptions\n#\n# -----------------------------------------------------------------------------\nclass VideoError(Exception):\n pass\n\n\nclass VideoSizeError(VideoError):\n \"\"\" Exception raised if the size of a movie file is too small.\n\n Attributes:\n video_filepath -- path of video file \"\"\"\n\n def __init__(self, video_filepath):\n self.video_filepath = video_filepath\n\n def __str__(self):\n return \"Size of movie file called {} is too small.\".format(\n self.video_filepath)\n\n\nclass VideoHashCodeError(VideoError):\n \"\"\" Exception raised if there is an error during hash code generation.\n\n Attributes:\n video_filepath -- path of video file\n error -- error raised during hash code generation. \"\"\"\n\n def __init__(self, video_filepath, error):\n self.video_filepath = video_filepath\n self.error = error\n\n def __str__(self):\n return (\n \"Error during hash code generation for movie file called {}: {}.\"\n .format(self.video_filepath, self.error)\n )\n\n\n# EOF\n"
},
{
"alpha_fraction": 0.5182561278343201,
"alphanum_fraction": 0.5329700112342834,
"avg_line_length": 26.388059616088867,
"blob_id": "6775b85089344f7fe4ada9b657d0a6362d705da2",
"content_id": "111d707a28d09dc69051e7ebe44221f4fd492565",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1835,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 67,
"path": "/setup.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : setup.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 28/08/2013\n##\n\n# Add sources of SubLime in path\nimport sys\nsource_dir = \"Sources\"\nsys.path.append(source_dir)\n\nfrom sublime import util\n\ntry:\n from setuptools import setup\n from setuptools import find_packages\nexcept ImportError:\n from distutils.core import setup\n\n__version__ = util.get_version_from_git()\n\nsetup(\n name=\"SubLime\",\n version=__version__,\n description=\"SubLime is a command-line program for searching \"\n \"and downloading the right subtitles for movies.\",\n author=\"sham\",\n author_email=\"[email protected]\",\n url=\"https://github.com/shamsan/sublime\",\n keywords=[\"substitles\", \"video\"],\n package_dir={'': source_dir},\n packages=find_packages(source_dir),\n entry_points={\n 'console_scripts': [\n 'SubLime = sublime.cli:run',\n ],\n },\n license=\"License :: OSI Approved :: BSD License\",\n classifiers=[\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 2 - Pre-Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: End Users/Desktop\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Home Automation\",\n \"Topic :: Utilities\",\n ],\n install_requires=[\n \"babelfish==0.5.1\",\n \"enzyme==0.4.1\",\n \"guessit==0.7\",\n \"stevedore==0.14.1\"\n ],\n test_suite='nose.collector',\n tests_require=['nose>=1.3.0'],\n)\n\n# EOF\n"
},
{
"alpha_fraction": 0.526135265827179,
"alphanum_fraction": 0.5275071859359741,
"avg_line_length": 30.969297409057617,
"blob_id": "5dbc1a464121d24c9c433a0e6674949f2f88617a",
"content_id": "33700d4cf8a03e5aec765aedcdfb287000496652",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7289,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 228,
"path": "/Sources/sublime/server.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : server.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 30/08/2013\n##\n\nimport os\nimport sys\nimport logging\nimport xmlrpc.client\nimport pkgutil\n\nfrom sublime.core import Movie\nfrom sublime.core import Episode\nfrom sublime.core import NamePattern as pattern\n\n# Logger\nLOG = logging.getLogger(\"sublime.server\")\n\n\n# -----------------------------------------------------------------------------\n#\n# ProviderMount class\n#\n# -----------------------------------------------------------------------------\nclass ProviderMount(type):\n \"\"\" Metaclass ProviderMount to store all SubtitleServers\n into a dictionary. \"\"\"\n\n def __init__(cls, name, bases, attrs):\n \"\"\" Metaclass Initializes instance. \"\"\"\n if not hasattr(cls, 'providers'):\n cls.providers = []\n else:\n cls.providers.append(cls)\n LOG.debug(\n \"A new SubtitleServer class has been registered: {}\".format(\n name))\n\n\n# -----------------------------------------------------------------------------\n#\n# SubtitleProvider class\n#\n# -----------------------------------------------------------------------------\nclass SubtitleProvider(metaclass=ProviderMount):\n \"\"\" Mount point for subtitles providers.\n\n Providers implementing this reference should provide\n the following attributes:\n\n name -- Name of the provider that will be displayed\n address -- Official address of the provider\n code -- Unique code for this provider \"\"\"\n\n _instances = []\n\n def __init__(self, name, address, code):\n \"\"\" Initializes instance. \"\"\"\n self.name = name\n self.address = address\n self.code = code\n\n @staticmethod\n def get_providers():\n \"\"\" Returns several SubtitleProvider. \"\"\"\n # Import all existing providers\n path = os.path.join(os.path.dirname(__file__), \"providers\")\n modules = pkgutil.iter_modules(path=[path])\n\n for _, mod_name, _ in modules:\n # Ensure that module isn't already loaded\n if mod_name not in sys.modules:\n try:\n mod_path = \"sublime.providers.\" + mod_name\n __import__(mod_path, fromlist=[mod_name])\n except ImportError as error:\n LOG.fatal(\"Cannot import {} provider: {}\".format(\n mod_name, error))\n\n if not SubtitleProvider._instances:\n SubtitleProvider._instances = [\n provider() for provider in SubtitleProvider.providers\n ]\n\n return SubtitleProvider._instances\n\n def __eq__(self, other):\n return (self.name == other.name and\n self.address == other.address and\n self.code == other.code)\n\n\n# -----------------------------------------------------------------------------\n#\n# XMLRPCServer class\n#\n# -----------------------------------------------------------------------------\nclass XMLRPCServer(object):\n \"\"\" Class to connect via XMLRPC to subtitles server\n and download subtitles. \"\"\"\n\n USER_AGENT = \"OS Test User Agent\"\n\n def __init__(self, xmlrpc_uri):\n \"\"\" Initializes instance. \"\"\"\n self.xmlrpc_uri = xmlrpc_uri\n self._session_string = None\n self._proxy = None\n self.connected = False\n\n def connect(self):\n \"\"\" Connect to a subtiles server. \"\"\"\n LOG.info(\"Connect to {}...\".format(self.name))\n self._proxy = xmlrpc.client.ServerProxy(self.xmlrpc_uri)\n\n return self._execute(self._do_connect)\n\n def disconnect(self):\n \"\"\" Disconnect from a subtitles server. \"\"\"\n LOG.info(\"Disconnect from {}...\".format(self.name))\n\n return self._execute(self._do_disconnect)\n\n def download_subtitles(\n self, videos, languages,\n rename=False, rename_pattern=None, underscore=True,\n mock_hash=None):\n \"\"\" Download a list of subtitles. \"\"\"\n LOG.info(\"Download subtitles from {}...\".format(self.name))\n\n # Use for testing purpose\n if mock_hash is not None:\n hashcode = mock_hash\n else:\n hashcode = self.hashcode\n\n response = False\n videos_hashcode = {\n hashcode(video.filename): video for video in videos\n }\n\n with pattern(rename_pattern, underscore):\n # First search if subtitles are available\n subtitles = self._execute(\n self._do_search_subtitles,\n [videos_hashcode, languages])\n\n # Rename videos if demanded\n if rename:\n [video.rename() for video in videos_hashcode.values()\n if isinstance(video, (Movie, Episode))]\n\n # Download subtitles\n if subtitles:\n response = self._execute(\n self._do_download_subtitles, [subtitles])\n\n return response\n\n def hashcode(self, video_filepath):\n \"\"\" Generates Video Hash code depending. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def _execute(self, method, args=[]):\n \"\"\" Decorates method of SubtitleServer. \"\"\"\n try:\n return method(*args)\n except xmlrpc.client.Fault as error:\n LOG.error(\n \"A fault occurred.\\nFault code: {}\\nFault string: {}\"\n .format(error.faultCode, error.faultString))\n except SubtitleServerError as error:\n LOG.warning(error)\n\n def _do_connect(self):\n \"\"\" Connect to a subtiles server. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def _do_disconnect(self):\n \"\"\" Disconnect from a subtitles server. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def _do_search_subtitles(self, videos_hashcode, languages):\n \"\"\" Search list of subtitles. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def _do_download_subtitles(self, subtitles):\n \"\"\" Download a list of subtitles. \"\"\"\n raise NotImplementedError(\"Please Implement this method\")\n\n def __repr__(self):\n return \"<SubtitleServer('{}', '{}', '{}')>\".format(\n self.code, self.name, self.address)\n\n\n# -----------------------------------------------------------------------------\n#\n# Exceptions\n#\n# -----------------------------------------------------------------------------\nclass ServerError(Exception):\n pass\n\n\nclass SubtitleServerError(ServerError):\n \"\"\" Exception raised if a subtitle server return an error status.\n\n Attributes:\n subtitles_server -- subtitles server which returns a wrong status\n message -- meaning of the error status \"\"\"\n\n def __init__(self, subtitles_server, message):\n self.subtitles_server = subtitles_server\n self.message = message\n\n def __str__(self):\n return \"Subtitles Server {} returns an error status: {}.\" \\\n .format(self.subtitles_server.name, self.message)\n\n# EOF\n"
},
{
"alpha_fraction": 0.769911527633667,
"alphanum_fraction": 0.769911527633667,
"avg_line_length": 27.25,
"blob_id": "7234c6837a270f4c740657fc4ff0e2511d52a3b7",
"content_id": "03b8ed2ff6b5f0754535d17d800637fd4775e92f",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 113,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 4,
"path": "/README.md",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "sublime\n=======\n\nSubLime is a command-line program for searching and downloading the right subtitles for movies.\n"
},
{
"alpha_fraction": 0.5442042946815491,
"alphanum_fraction": 0.5523903369903564,
"avg_line_length": 33.314605712890625,
"blob_id": "cc820aef936423f45c38cde7e5d9f6aaa617eadc",
"content_id": "aeeea1256147b6a089f249a2c7b6d356eb1d37a2",
"detected_licenses": [
"BSD-3-Clause"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3054,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 89,
"path": "/Tests/test_core.py",
"repo_name": "aka-sham/sublime",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n\n###\n# Project : SubLime\n# FileName : test_movie.py\n# -----------------------------------------------------------------------------\n# Author : sham\n# E-Mail : [email protected]\n# -----------------------------------------------------------------------------\n# Creation date : 17/01/2014\n##\n\nimport unittest\nimport os\nimport shutil\n\nfrom sublime.util import get_exe_dir\nfrom sublime.core import Episode\nfrom sublime.core import NamePattern as pattern\n\n\n# -----------------------------------------------------------------------------\n#\n# EpisodeTestCase class\n#\n# -----------------------------------------------------------------------------\nclass EpisodeTestCase(unittest.TestCase):\n \"\"\" Tests Episode class functions. \"\"\"\n\n def setUp(self):\n self.video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'movie.avi')\n self.expected_renamed_video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Twin_Peaks_S01E01_Pilot.avi')\n self.expected_renamed_new_pattern_video_filename = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Twin_Peaks_1x01_Pilot.avi')\n self.expected_renamed_video_filename_without_underscore = os.path.join(\n get_exe_dir(), 'Tests', 'Fixtures', 'Twin Peaks S01E01 Pilot.avi')\n\n def test_change_pattern(self):\n \"\"\" Tests that the rename method use different\n pattern defined by user. \"\"\"\n new_pattern = \"{serie_name}_{season}x{episode:02d}_{episode_name}\"\n\n episode = Episode(self.video_filename)\n episode.name = \"Twin Peaks\"\n episode.season = 1\n episode.episode = 1\n episode.episode_name = \"Pilot\"\n\n # Rename episode with default pattern\n episode.rename()\n self.assertTrue(os.path.exists(self.expected_renamed_video_filename))\n\n # Rename again with a new pattern\n with pattern(new_pattern):\n episode.rename()\n self.assertTrue(os.path.exists(\n self.expected_renamed_new_pattern_video_filename))\n\n # Rename again without underscore\n with pattern(underscore=False):\n episode.rename()\n self.assertTrue(os.path.exists(\n self.expected_renamed_video_filename_without_underscore))\n\n def tearDown(self):\n \"\"\" Clean up \"\"\"\n if os.path.exists(self.expected_renamed_video_filename):\n shutil.move(\n self.expected_renamed_video_filename, self.video_filename)\n\n if os.path.exists(self.expected_renamed_new_pattern_video_filename):\n shutil.move(\n self.expected_renamed_new_pattern_video_filename,\n self.video_filename)\n\n if os.path.exists(\n self.expected_renamed_video_filename_without_underscore):\n shutil.move(\n self.expected_renamed_video_filename_without_underscore,\n self.video_filename)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n# EOF\n"
}
] | 12 |
mamueller/toxTest | https://github.com/mamueller/toxTest | 85f94b887258294f54f2fc5174515cb292e5a3c3 | ab128584b91ece606f25bca23ae46262dc4eeda0 | 8b6c837bad798735379443b9e7e691fdd07dd37b | refs/heads/master | 2021-05-10T13:19:00.770530 | 2019-04-10T13:59:33 | 2019-04-10T13:59:33 | 118,471,316 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7639257311820984,
"alphanum_fraction": 0.7745358347892761,
"avg_line_length": 33.272727966308594,
"blob_id": "a77e7cd172802da54fa938423f2c9d3637eb67e5",
"content_id": "88a011c180b71bc23cd9d414b1b38b89a464f076",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 377,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 11,
"path": "/tox.ini",
"repo_name": "mamueller/toxTest",
"src_encoding": "UTF-8",
"text": "# this file has to live in the same directory as setup.py\n[tox]\nenvlist = py36\n[testenv:freeze]\ninstall_command = pip install -rrequirements.freeze {opts} {packages}\ncommands= python3 run_tests.py\n\n[testenv:bleadingEdge]\n#install_command = pip install -rrequirements.bleadingEdge {opts} {packages}\ninstall_command = pip install {opts} {packages}\ncommands= python3 run_tests.py\n"
},
{
"alpha_fraction": 0.8025316596031189,
"alphanum_fraction": 0.8075949549674988,
"avg_line_length": 55.28571319580078,
"blob_id": "a71fdabccc2ef7528452af9571bcafca2c316c41",
"content_id": "d3b7976123d7efc4c8c0a00779019cd68b1c03b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 395,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 7,
"path": "/README.md",
"repo_name": "mamueller/toxTest",
"src_encoding": "UTF-8",
"text": "# toxTest\nExample project to explore the tox tool for our buildbot setup\nThe purpose of this repository is to create a tox.ini that checks our production code against \n1. different virtual environments that differ in the amount of version pinning\n1. different versions of the python interpreter.\n\nThe python source code of the package is the minimun needed to mock a real package to be tested.\n\n"
},
{
"alpha_fraction": 0.5930851101875305,
"alphanum_fraction": 0.5992907881736755,
"avg_line_length": 35.35483932495117,
"blob_id": "a4b1ba4a5687cba2d1671aadd770d263e1318d3d",
"content_id": "67416f01e9c01c725ddbfafde1b764333f6402b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1128,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 31,
"path": "/setup.py",
"repo_name": "mamueller/toxTest",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# vim:set ff=unix expandtab ts=4 sw=4:\nfrom setuptools import setup, find_packages\ndef readme():\n with open('README.md') as f:\n return f.read()\n\nsetup(name='toxTest',\n version='1.0',\n description='explore tox ',\n long_description=readme(),#avoid duplication \n author='Markus Müller',\n author_email='[email protected]',\n packages=find_packages(), #find all packages (multifile modules) recursively\n classifiers = [\n \"Programming Language :: Python :: 3\",\n \"Development Status :: 4 - Beta\",\n \"Environment :: Other Environment\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)\",\n \"Operating System :: POSIX :: Linux\",\n \"Topic :: Education \"\n ],\n # setuptools should not be bothered with explicit versions, those will be specified in\n # for pip in requirements.txt\n install_requires=[\n \"sympy\",\n ],\n # to hopefully make RTD work\n include_package_data=True,\n zip_safe=False)\n\n"
},
{
"alpha_fraction": 0.6349999904632568,
"alphanum_fraction": 0.6800000071525574,
"avg_line_length": 23.875,
"blob_id": "dc27cfc695f8919a08789865738f777f3b9c66eb",
"content_id": "ddd8a4aabd4352837cfc8ac65a9f455978d997e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 200,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 8,
"path": "/tests/TestSym2Num.py",
"repo_name": "mamueller/toxTest",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# vim:set ff=unix expandtab ts=4 sw=4:\n\nfrom unittest import TestCase\nclass Test_Sym2Num(TestCase):\n def test_sym2num(self):\n res=42\n self.assertEqual(res,42)\n\n"
},
{
"alpha_fraction": 0.6271186470985413,
"alphanum_fraction": 0.6483050584793091,
"avg_line_length": 28.375,
"blob_id": "cd410bd362a0685708273a98336b97ecbce75031",
"content_id": "8fb655bd17e8a42189524be1a4d380eb3a63854a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 236,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 8,
"path": "/toxTest/Sym2Num.py",
"repo_name": "mamueller/toxTest",
"src_encoding": "UTF-8",
"text": "def sym2num():\n #at the moment we fake\n import sympy\n import pkg_resources\n v=pkg_resources.get_distribution('sympy').version\n if v=='1.0': \n return(42)\n raise(Exception('The sympy Version is not compatible'))\n\n"
}
] | 5 |
Darrenrodricks/DiceRoller | https://github.com/Darrenrodricks/DiceRoller | da04e1e357c057e938a271bc66c3ace83fff24bf | 9e26e7bd60b27f34594361e57c9c653e86e34b2c | cd9e6aa773eb518adbe0fc69a84bd05393e811a1 | refs/heads/main | 2023-07-13T09:10:08.958010 | 2021-08-31T08:38:25 | 2021-08-31T08:38:25 | 401,614,002 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5791855454444885,
"alphanum_fraction": 0.6063348650932312,
"avg_line_length": 38.818180084228516,
"blob_id": "446f1b3d487e688bcdd8719cdbca1c9564a1b8b2",
"content_id": "75df3a22224e013e88c6a90bb91ce98a5c34fc82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 442,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 11,
"path": "/diceRoller.py",
"repo_name": "Darrenrodricks/DiceRoller",
"src_encoding": "UTF-8",
"text": "import random\nroll_dice = input(\"Please guess which side the dice will land on: \")\n\nif roll_dice == \"1\" or \"2\" or \"3\" or \"4\" or \"5\" or \"6\":\n possible_results = [1, 2, 3, 4, 5, 6]\n result = random.choice(possible_results)\n if roll_dice == result:\n print(\"Wow you guessed correctly\")\n print(\"The dice landed on: \" + str(result))\n else:\n print(\"You guessed incorrectly, The dice landed on: \" + str(result))\n "
},
{
"alpha_fraction": 0.69808030128479,
"alphanum_fraction": 0.7975566983222961,
"avg_line_length": 190,
"blob_id": "4816d66d07eb0942d628fe305d44f7d7c69bc044",
"content_id": "980e907dafd42196d0c2d00fc0fde8ec6bc3e992",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 573,
"license_type": "no_license",
"max_line_length": 358,
"num_lines": 3,
"path": "/README.md",
"repo_name": "Darrenrodricks/DiceRoller",
"src_encoding": "UTF-8",
"text": "# [Dice Roller](https://github.com/Darrenrodricks/DiceRoller)\n\n* This was the second project that I completed this week. This code again is very simple and helped me a lot. This code helped me understand loops and comparisons very well. I enjoyed playing this game after I made it and felt asthough this is a great step to help my python journey. I will continue to make more and more games because I love the end result.\n"
}
] | 2 |
Clarence7/Algorithm-in-Python | https://github.com/Clarence7/Algorithm-in-Python | 7a9e8d614044404da69c78b92b0415d20ce9ec9f | 80451dc9ddb613d495d1e5add97d672160d4bbf7 | 550cdd0ee69576151bed796b53147cf3f7a55f38 | refs/heads/master | 2021-07-18T09:45:57.056562 | 2017-10-24T06:25:46 | 2017-10-24T06:25:46 | 108,085,701 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5286458134651184,
"alphanum_fraction": 0.589062511920929,
"avg_line_length": 27.507692337036133,
"blob_id": "3151a45942ee75a18c5d6a1f5f1104a05896b796",
"content_id": "b65ed93a6a6d3567b55ae986eca9d790ea8bceca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1920,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 65,
"path": "/BFPRT.py",
"repo_name": "Clarence7/Algorithm-in-Python",
"src_encoding": "UTF-8",
"text": "import timeit\r\nimport math\r\nimport random\r\nimport sys\r\n\r\n# too much recursion\r\n# stack overflow\r\n# not practical\r\n\r\ndef BFPRT(alist,start,end,k):\r\n if start == end:\r\n return start\r\n pivotIndex = getPivotIndex(alist,start,end)\r\n cur = partition(alist,start,end,pivotIndex)\r\n if k == cur:\r\n return cur\r\n elif k < cur:\r\n return BFPRT(alist,start,cur-1,k)\r\n else:\r\n return BFPRT(alist,cur+1,end,k-cur)\r\n\r\n# get the index of the median of medians\r\ndef getPivotIndex(alist,start,end):\r\n if end-start<5:\r\n alist = sorted(alist[start:end+1])\r\n return (start+end)>>1\r\n length = math.floor((end-start)/5)\r\n mds = start - 1\r\n for i in range(length):\r\n st = start + i * 5\r\n ed = start + i * 5 + 5\r\n md = start + i * 5 + 2\r\n alist[st:ed] = sorted(alist[st:ed])\r\n mds += 1\r\n alist[mds], alist[md] = alist[md], alist[mds]\r\n return BFPRT(alist,start,mds,((mds+start)>>1)-start+1)\r\n\r\ndef partition(alist,start,end,pivotIndex):\r\n alist[pivotIndex],alist[end] = alist[end],alist[pivotIndex]\r\n j = start - 1\r\n for i in range(start,end):\r\n if alist[i] < alist[end]:\r\n j += 1\r\n alist[i],alist[j] = alist[j],alist[i]\r\n j += 1\r\n alist[j],alist[end] = alist[end],alist[j]\r\n return j\r\n\r\nsys.setrecursionlimit(1000000)\r\nalist = [24,45,25,23,64,73,45,3,54,56,46,234,46,72,54,73,45,24,754,235,7,35,24]\r\nprint(alist[BFPRT(alist,0,len(alist)-1,3)])\r\n\r\n# sys.setrecursionlimit(1000000)\r\n# alist = list(range(100))\r\n# random.shuffle(alist)\r\n# BFPRT(alist,0,len(alist)-1,5)\r\n\r\n\r\n# sys.setrecursionlimit(1000000)\r\n# for i in range(100,10001,200):\r\n# t = timeit.Timer(\"BFPRT(alist,0,len(alist)-1,5)\", \"from __main__ import random,alist,BFPRT\")\r\n# alist = list(range(i))\r\n# random.shuffle(alist)\r\n# lst_time = t.timeit(number=1000)\r\n# print(\"%d,%10.3f\" % (i, lst_time))\r\n\r\n"
}
] | 1 |
maeof/ScrapeNewsAgencies | https://github.com/maeof/ScrapeNewsAgencies | d652cc4d9fc79d076637bf276f57b6d0a3a09d57 | 81600b75d11816f696a28f7cf54abf3784dd465b | c30725ff41456677383dff12606da7fd74cad752 | refs/heads/master | 2023-01-05T20:07:56.274721 | 2020-11-03T07:30:07 | 2020-11-03T07:30:07 | 309,605,543 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6072191596031189,
"alphanum_fraction": 0.6110187768936157,
"avg_line_length": 31.312021255493164,
"blob_id": "d496b37bb665fc83592a5b5e076c541f90e04e66",
"content_id": "534d6a347d68d9d63c99bc479aa59faadc784465",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12633,
"license_type": "no_license",
"max_line_length": 160,
"num_lines": 391,
"path": "/ContentScraper.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import abc\n\nimport ScraperHelper as helper\n\nfrom bs4 import BeautifulSoup\nimport json\n\nfrom urllib.parse import urlparse\nfrom datetime import date, datetime\n\nimport re\n\n\nclass ContentScraperAbstract(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def getArticleDatePublished(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleDateModified(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleTitle(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleCategory(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleAuthor(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleAuthorPosition(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getArticleScope(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getNotFoundValue(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def isArticleCompliant(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def createParser(self, pageContent):\n \"\"\"Required Method\"\"\"\n\n\nclass FifteenContentScraper(ContentScraperAbstract):\n def __init__(self, url):\n self._url = url\n\n def getArticleDatePublished(self):\n datePublishedTag = self._soup.find(\"meta\", attrs={\"itemprop\":\"datePublished\"})\n\n datePublished = None\n if datePublishedTag:\n datePublished = datePublishedTag.get(\"content\")\n\n return datePublished\n\n def getArticleDateModified(self):\n dateModifiedTag = self._soup.find(\"meta\", attrs={\"itemprop\":\"dateModified\"})\n\n dateModified = None\n if dateModifiedTag:\n dateModified = dateModifiedTag.get(\"content\")\n\n return dateModified\n\n def getArticleTitle(self):\n articleTitleTag = self._soup.find(\"h1\", attrs={\"itemprop\":\"headline\"})\n articleTitle = articleTitleTag.text.strip()\n return articleTitle\n\n def getArticleCategory(self):\n categoryTags = self._soup.findAll(\"li\", attrs={\"itemprop\":\"itemListElement\"})\n categoryName = \"\"\n for categoryTag in categoryTags:\n categoryNameTag = categoryTag.find(\"span\", attrs={\"itemprop\":\"name\"})\n\n if len(categoryName) != 0:\n categoryName += \" > \"\n categoryName += categoryTag.text.strip()\n\n return categoryName\n\n def getArticleAuthor(self): #TODO: optimize - only perform find of authorTag once per url, reuse authorTag in getArticleAuthorPosition etc.\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"author-name-block\"}) #this tag represents author block if it's 15min employee and the source is 15min\n if authorTag is None:\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"author-info author-text\"}) #this tag represents author from another source\n\n if authorTag is not None:\n authorName = authorTag.find(\"span\", attrs={\"itemprop\":\"name\"}).text.strip()\n else:\n authorName = self.getNotFoundValue()\n\n return authorName\n\n def getArticleAuthorPosition(self):\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"author-name-block\"})\n if authorTag is not None:\n authorPosition = authorTag.find(\"div\", attrs={\"class\":\"author-position\"}).text.strip()\n else:\n authorPosition = self.getNotFoundValue()\n\n return authorPosition\n\n def getArticleScope(self):\n articleTitleTag = self._soup.find(\"h1\", attrs={\"itemprop\":\"headline\"})\n articleIntroTag = self._soup.find(\"h4\", attrs={\"class\":\"intro\"})\n articleContentTag = self._soup.find(\"div\", attrs={\"class\": \"article-content\"})\n\n scopes = [articleTitleTag, articleIntroTag, articleContentTag]\n return scopes\n\n def getNotFoundValue(self):\n return \"n/a\"\n\n def isArticleCompliant(self):\n return True\n\n def createParser(self, pageContent):\n self._pageContent = pageContent\n self._soup = BeautifulSoup(pageContent, \"html.parser\")\n\n\nclass DelfiContentScraper(ContentScraperAbstract):\n def __init__(self, url):\n self._url = url\n\n def getArticleDatePublished(self):\n datePublishedTag = self._soup.find(\"div\", attrs={\"class\":\"source-date\"})\n if (datePublishedTag is None):\n datePublishedTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-source-date\"})\n\n datePublished = \"\"\n if datePublishedTag is not None:\n datePublished = datePublishedTag.text.strip()\n else:\n datePublished = None\n\n return datePublished\n\n def getArticleDateModified(self):\n dateModified = None\n return dateModified\n\n def getArticleTitle(self):\n articleTitle = self._getRegularArticleTitle()\n\n if len(articleTitle) == 0:\n articleTitle = self._getMultimediaArticleTitle()\n\n if len(articleTitle) == 0:\n articleTitle = self.getNotFoundValue()\n\n return articleTitle\n\n def _getRegularArticleTitle(self):\n articleTitleTag = self._soup.find(\"div\", attrs={\"class\": \"article-title\"})\n\n articleTitle = \"\"\n if articleTitleTag is not None:\n articleTitle = articleTitleTag.find(\"h1\").text.strip()\n articleTitle = articleTitle.replace(\"\\n\", \" \")\n articleTitle = articleTitle.replace(\"\\t\", \"\")\n\n return articleTitle\n\n def _getMultimediaArticleTitle(self):\n articleTitleTag = self._soup.find(\"h1\", attrs={\"itemprop\": \"headline\"})\n\n articleTitle = \"\"\n if articleTitleTag is not None:\n articleTitle = articleTitleTag.text.strip()\n articleTitle = articleTitle.replace(\"\\n\", \" \")\n articleTitle = articleTitle.replace(\"\\t\", \"\")\n\n return articleTitle\n\n def getArticleCategory(self):\n categoryName = \"\"\n\n categoryFatherTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-breadcrumbs delfi-category-location\"})\n if categoryFatherTag is not None:\n categoryTags = categoryFatherTag.findAll(\"span\", attrs={\"itemprop\":\"itemListElement\"})\n\n if categoryTags is not None:\n for categoryTag in categoryTags:\n if len(categoryName) != 0:\n categoryName += \" > \"\n categoryName += categoryTag.text.strip()\n\n if len(categoryName) == 0:\n categoryName = self.getNotFoundValue()\n\n return categoryName\n\n def getArticleAuthor(self):\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-author-name\"})\n if authorTag is None:\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-source-name\"})\n\n if authorTag is not None:\n authorName = authorTag.text.strip()\n else:\n authorName = self.getNotFoundValue()\n\n return authorName\n\n def getArticleAuthorPosition(self):\n authorTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-author-name\"})\n\n authorPosition = \"\"\n if authorTag is not None:\n authorBioLinkTag = authorTag.find(\"a\")\n if authorBioLinkTag is not None:\n authorBioLink = authorBioLinkTag.get(\"href\")\n bioPageContent = helper.httpget(authorBioLink)\n\n if bioPageContent is not None:\n babySoup = BeautifulSoup(bioPageContent, \"html.parser\")\n authorPosition = babySoup.find(\"div\", attrs={\"class\":\"title\"}).text.strip()\n\n if len(authorPosition) == 0:\n authorPosition = self.getNotFoundValue()\n else:\n authorPosition = self.getNotFoundValue()\n\n return authorPosition\n\n def getArticleScope(self):\n articleTitleTag = self._soup.find(\"div\", attrs={\"class\":\"article-title\"})\n articleIntroTag = self._soup.find(\"div\", attrs={\"class\":\"delfi-article-lead\"})\n\n bigColumnTag = self._soup.find(\"div\", attrs={\"class\": \"col-xs-8\"})\n articleContentTag = bigColumnTag.find(\"div\") #or bigColumnTag.div (finds the first <div> in bigColumnTag because delfi\n\n scopes = [articleTitleTag, articleIntroTag, articleContentTag]\n return scopes\n\n def getNotFoundValue(self):\n return \"n/a\"\n\n def isArticleCompliant(self):\n return True\n\n def createParser(self, pageContent):\n self._pageContent = pageContent\n self._soup = BeautifulSoup(pageContent, \"html.parser\")\n\n\nclass LrytasContentScraper(ContentScraperAbstract):\n def __init__(self, url, webDriverPath):\n self._url = url\n self._webDriverPath = webDriverPath\n\n def getArticleDatePublished(self):\n datePublishedTag = self._soup.find(\"meta\", attrs={\"itemprop\":\"datePublished\"})\n\n datePublished = None\n if datePublishedTag:\n datePublished = datePublishedTag.get(\"content\")\n\n return datePublished\n\n def getArticleDateModified(self):\n dateModified = None\n return dateModified\n\n def getArticleTitle(self):\n articleTitle = self.getNotFoundValue()\n\n aboutBlockJson = self._soup.find(\"script\", type=\"application/ld+json\").contents\n if aboutBlockJson:\n jsonText = aboutBlockJson[0]\n jsonText = jsonText.strip().replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n jsonText = self._cleanHtml(jsonText)\n about = json.loads(jsonText)\n articleTitle = about[\"headline\"].strip()\n\n return articleTitle\n\n def _cleanHtml(self, raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\n def getArticleCategory(self):\n categoryName = \"\"\n aboutBlockJson = self._soup.findAll(\"script\", attrs={\"type\": \"application/ld+json\"})[-1].contents\n\n if aboutBlockJson:\n jsonText = aboutBlockJson[0]\n jsonText = jsonText.strip().replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n jsonText = self._cleanHtml(jsonText)\n about = json.loads(jsonText)\n for itemListElement in about[\"itemListElement\"]:\n if len(categoryName) != 0:\n categoryName += \" > \"\n categoryName += itemListElement[\"item\"][\"name\"]\n\n if len(categoryName) == 0:\n categoryName = self.getNotFoundValue()\n\n return categoryName\n\n def getArticleAuthor(self):\n authorName = self.getNotFoundValue()\n\n aboutBlockJson = self._soup.find(\"script\", type=\"application/ld+json\").contents\n if aboutBlockJson:\n jsonText = aboutBlockJson[0]\n jsonText = jsonText.strip().replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n jsonText = self._cleanHtml(jsonText)\n about = json.loads(jsonText)\n authorName = about[\"publisher\"][\"name\"]\n\n return authorName\n\n def getArticleAuthorPosition(self):\n return self.getNotFoundValue()\n\n def getArticleScope(self):\n script = self._soup.find(\"body\").find(\"script\").contents[0]\n script = script.strip().replace(\"\\t\", \"\").replace(\"\\n\", \"\")\n script = self._cleanHtml(script)\n\n pos = script.find(\"{\")\n pos2 = script.find(\"};\")\n\n jsonbby = script[pos:pos2 + 1]\n\n articleJsonObj = json.loads(jsonbby)\n\n scopes = [articleJsonObj[\"clearContent\"], articleJsonObj[\"title\"]]\n return scopes\n\n def getNotFoundValue(self):\n return \"n/a\"\n\n def isArticleCompliant(self):\n isCompliant = True\n articleDate = self._getArticleDate()\n\n if articleDate and (articleDate < date(2019, 1, 1) or articleDate > date(2019, 12, 31)):\n isCompliant = False\n\n return isCompliant\n\n def _getArticleDate(self):\n url = self._url\n parsedUrl = urlparse(url)\n\n sectorPosition = 0\n pathParts = parsedUrl.path[1:].split(\"/\")\n articleDate = None\n for sector in pathParts:\n try:\n value = int(sector)\n except:\n value = 0\n\n if value != 0:\n year = value\n try:\n month = int(pathParts[sectorPosition + 1])\n day = int(pathParts[sectorPosition + 2])\n articleDate = date(year, month, day)\n except:\n articleDate = None\n\n break\n\n sectorPosition += 1\n\n return articleDate\n\n def createParser(self, pageContent):\n self._pageContent = pageContent\n self._soup = BeautifulSoup(pageContent, \"html.parser\")"
},
{
"alpha_fraction": 0.6438480019569397,
"alphanum_fraction": 0.6492762565612793,
"avg_line_length": 27.350427627563477,
"blob_id": "0ae8c948d19bd97dc97476246f3b1c1861543a5c",
"content_id": "bf3f4380efe87dcbeab2d16696ceb8b6427492f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3316,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 117,
"path": "/Scripts/ScrapeIt.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "from requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nimport urllib3 as urllib\nimport sys\nimport os\nfrom datetime import datetime\n\ndef getCurrentDateTime():\n now = datetime.now()\n return now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n\ndef createWorkSessionFolder(createInPath):\n createdFolder = createInPath + \"\\\\\" + \"session_\" + getCurrentDateTime()\n os.mkdir(createdFolder)\n return createdFolder\n\nworkFolder = \"C:\\Data\\GetLinks\"\nworkSessionFolder = createWorkSessionFolder(workFolder)\n\ndef httpget(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None.\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if isResponseOK(resp):\n return resp.content\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(url, str(e)))\n return None\n\ndef isResponseOK(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise.\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)\n\ndef getIncrementalUrl(url, i):\n return url.replace(\"{0}\", str(i))\n\ndef isIncrementalUrl(url):\n if (url.find(\"{0}\") != -1):\n return True\n else:\n return False\n\ndef getLinksFromPageContent(pageContent):\n soup = BeautifulSoup(pageContent, 'html.parser')\n links = []\n\n for a in soup.find_all('a'):\n links.append(a.get('href'))\n\n return links\n\ndef saveToFile(path, links):\n fileNameWithPath = path + \"\\\\\" + \"result.csv\"\n file = open(fileNameWithPath, \"w+\")\n for link in links:\n if (link is not None):\n file.write(link + \"\\r\\n\")\n file.close()\n\ndef getLinks(regularUrls):\n for url in regularUrls:\n pageContent = httpget(url)\n links = getLinksFromPageContent(pageContent)\n saveToFile(workSessionFolder, links)\n\ndef getLinksFromIncrementalUrls(incrementalUrls, pagesCount):\n for i in range(1, pagesCount):\n for url in incrementalUrls:\n urlForRequest = getIncrementalUrl(url, i)\n pageContent = httpget(urlForRequest)\n links = getLinksFromPageContent(pageContent)\n saveToFile(workSessionFolder, links)\n\ndef validateArgs(args):\n if (args[1] is None or args[2] is None):\n print(\"Wrong arguments. 1st argument is the file of links, 2nd argument is the incremental value of how many pages to view.\")\n return False\n\ndef main(args):\n if (validateArgs(args) == False):\n return\n\n linksFilePath = str(args[1])\n pagesCount = int(args[2])\n\n file = open(linksFilePath, \"r\")\n fileLines = file.readlines()\n file.close()\n\n incrementalUrls = []\n regularUrls = []\n\n for line in fileLines:\n if (isIncrementalUrl(line)):\n incrementalUrls.append(line)\n else:\n regularUrls.append(line)\n\n getLinksFromIncrementalUrls(incrementalUrls, pagesCount)\n getLinks(regularUrls)\n\nif __name__ == '__main__':\n main(sys.argv)"
},
{
"alpha_fraction": 0.675159215927124,
"alphanum_fraction": 0.6815286874771118,
"avg_line_length": 22.549999237060547,
"blob_id": "af624951d114b9bc0be9b7fd2a08c18307993840",
"content_id": "fd2bd7859920f9c32e0fda6f2898cef4b72a3d66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 471,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 20,
"path": "/ParallelTest.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import multiprocessing\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\nimport time\n\ndef myfunction(i, parameters):\n time.sleep(4)\n print(i)\n return i\n\nnum_cores = multiprocessing.cpu_count()\nprint(num_cores)\n\nmyList = [\"a\", \"b\", \"c\", \"d\"]\nparameters = [\"param1\", \"param2\"]\ninputs = tqdm(myList)\n\nif __name__ == \"__main__\":\n processed_list = Parallel(n_jobs = num_cores)(delayed(myfunction)(i, parameters) for i in inputs)\n print(processed_list)\n"
},
{
"alpha_fraction": 0.7704402804374695,
"alphanum_fraction": 0.7735849022865295,
"avg_line_length": 30.899999618530273,
"blob_id": "664e890e1c9947056f96f32f564623835b34c7c5",
"content_id": "9f81b697013b4da46e2a62bbcd83d0213c795b72",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 318,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 10,
"path": "/driverWrapper.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nimport time\n\nservice = Service('c:\\\\data\\\\chromedriver\\\\chromedriver.exe')\nservice.start()\ncdi = webdriver.Remote(service.service_url)\ncdi.get('http://www.google.com/');\ntime.sleep(5) # Let the user actually see something!\ncdi.quit()"
},
{
"alpha_fraction": 0.6647357940673828,
"alphanum_fraction": 0.666431188583374,
"avg_line_length": 40.8875732421875,
"blob_id": "439e56b892f319bd06698bae837a0d79a8f8d21b",
"content_id": "a1acbb7db6a60013ab56857977a79dc97a597db6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7078,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 169,
"path": "/AnalyzeLinks.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import ScraperHelper as helper\nfrom ContentFetcher import FileContentFetcher, HttpContentFetcher\nfrom ContentScraper import ContentScraperAbstract, FifteenContentScraper, DelfiContentScraper, LrytasContentScraper\n\nimport os\nimport multiprocessing\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\n\nimport csv\nimport re\n\n\nclass SimpleContentScraper:\n def __init__(self, contentFetcherStrategy, workSessionFolder, cpuCount, regexCompliancePatterns):\n self._contentFetcherStrategy = contentFetcherStrategy\n self._workSessionFolder = workSessionFolder\n self._cpuCount = cpuCount\n self._regexCompliancePatterns = regexCompliancePatterns\n\n def scrape(self):\n workList = tqdm(self._contentFetcherStrategy.getWorkList())\n\n results = Parallel(n_jobs=self._cpuCount)(delayed(self._processResource)(resource) for resource in workList)\n\n results.insert(0, self._getDataSetHeader())\n return self._removeEmptyEntries(results)\n\n def _processResource(self, resource):\n contentScraperStrategy = self.getContentScraperStrategy(self._contentFetcherStrategy.getContentScraperSuggestion(resource), resource)\n\n pageContent = self._contentFetcherStrategy.getContent(resource)\n result = []\n try:\n if pageContent is not None:\n contentScraperStrategy.createParser(pageContent) #TODO: rename to init\n allMatches = self._getPatternMatches(contentScraperStrategy.getArticleScope())\n\n if self._isArticleCompliant(allMatches) and contentScraperStrategy.isArticleCompliant():\n result.append(self._contentFetcherStrategy.getResourceName(resource))\n result.append(contentScraperStrategy.getArticleTitle())\n result.append(contentScraperStrategy.getArticleCategory())\n result.append(contentScraperStrategy.getArticleDatePublished())\n result.append(contentScraperStrategy.getArticleDateModified())\n result.append(contentScraperStrategy.getArticleAuthor())\n result.append(contentScraperStrategy.getArticleAuthorPosition())\n result = self._getPatternMatchesColumns(result, allMatches)\n result.append(resource)\n\n savedContentFileName = self._savePageContentToFile(resource, pageContent)\n result.append(savedContentFileName)\n except Exception as ex:\n result.clear()\n print(str(os.getpid()) + \" failed to process: \" + resource)\n self._log(ex, resource)\n\n return result\n\n def _removeEmptyEntries(self, entries):\n cleanedEntries = [x for x in entries if x != []]\n return cleanedEntries\n\n def _getDataSetHeader(self):\n dataSetHeader = [\"Source\", \"Title\", \"Category\", \"Date published\", \"Date modified\", \"Author\", \"Author position\"]\n for pattern in self._regexCompliancePatterns:\n dataSetHeader.append(\"Count of {0}\".format(pattern))\n dataSetHeader.append(\"Url\")\n dataSetHeader.append(\"Path to local source\")\n return dataSetHeader\n\n def _savePageContentToFile(self, resource, pageContent):\n resourceName = self._contentFetcherStrategy.getFullSafeResourceName(resource)\n\n outputFileName = self._workSessionFolder + \"\\\\\" + str(os.getpid()) + \"_\" + helper.getCurrentDateTime() + resourceName + \".htm\"\n\n pageContentFile = open(outputFileName, \"w+\", encoding=\"utf-8\")\n pageContentFile.writelines(pageContent)\n pageContentFile.close()\n\n return outputFileName\n\n def _log(self, exception, url):\n try:\n logFile = open(self._workSessionFolder + \"\\\\\" + \"log.txt\", \"a+\")\n logFile.write(\"Exception has occured: \" + str(url) + \"\\n\")\n logFile.write(str(exception) + \"\\n\")\n logFile.write(str(exception.args) + \"\\n\")\n logFile.write(str(os.getpid()) + \" tried to process it at \" + str(helper.getCurrentDateTime()) + \" but failed.\" + \"\\n\\n\")\n logFile.close()\n except:\n print(\"lol failed to write to the log file but please do continue: \" + url)\n\n def _getPatternMatchesColumns(self, currentResult, allPatternMatches):\n for i in range(0, len(self._regexCompliancePatterns)):\n count = 0\n for matches in allPatternMatches[i]:\n count += len(matches)\n currentResult.append(count)\n return currentResult\n\n @staticmethod\n def getContentScraperStrategy(suggestion, resource):\n contentScraperStrategy = ContentScraperAbstract()\n\n if suggestion == \"www.15min.lt\":\n contentScraperStrategy = FifteenContentScraper(resource)\n elif suggestion == \"www.delfi.lt\":\n contentScraperStrategy = DelfiContentScraper(resource)\n elif suggestion == \"www.lrytas.lt\":\n contentScraperStrategy = LrytasContentScraper(resource, \"c:\\\\data\\\\chromedriver\\\\chromedriver.exe\")\n else:\n raise Exception(\"Could not pick content scraper strategy for \" + resource)\n\n return contentScraperStrategy\n\n def _getPatternMatches(self, articleScopes):\n allMatches = []\n for pattern in self._regexCompliancePatterns:\n matches = []\n for scope in articleScopes:\n try:\n scopeText = scope.text\n except:\n scopeText = str(scope)\n matches.append(re.findall(pattern, scopeText, flags=re.IGNORECASE))\n\n allMatches.append(matches)\n\n return allMatches\n\n def _isArticleCompliant(self, allMatches):\n isCompliant = False\n\n for i in range(0, len(self._regexCompliancePatterns)):\n for matches in allMatches[i]:\n if len(matches) > 0:\n isCompliant = True\n break\n\n return isCompliant\n\ndef main():\n linksFile = \"C:\\\\Data\\\\AnalyzeLinks\\\\links.csv\"\n linksFile = \"C:\\\\Data\\\\AnalyzeLinks\\\\linksTest.csv\" #Test\n\n workFolder = \"C:\\Data\\AnalyzeLinks\"\n workSessionFolder = helper.createWorkSessionFolder(workFolder)\n resultFile = workSessionFolder + \"\\\\\" + \"result.csv\"\n\n filesPathFileContentFetcher = \"C:\\Data\\deliverables\\iteration3\\sources\"\n filesPathFileContentFetcher = workSessionFolder #Test\n\n cpuCount = multiprocessing.cpu_count()\n #cpuCount = 1 #Test\n regexCompliancePatterns = [r\"(skandal.*?\\b)\"]\n\n simpleContentScraper = SimpleContentScraper(HttpContentFetcher(linksFile), workSessionFolder, cpuCount, regexCompliancePatterns)\n scrapeResult = simpleContentScraper.scrape()\n\n simpleContentScraper = SimpleContentScraper(FileContentFetcher(filesPathFileContentFetcher), workSessionFolder, cpuCount, regexCompliancePatterns)\n scrapeResult = simpleContentScraper.scrape()\n\n with open(resultFile, \"w+\", encoding=\"utf-8\", newline='') as resultFile:\n writer = csv.writer(resultFile)\n writer.writerows(scrapeResult)\n\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.6542019844055176,
"alphanum_fraction": 0.661526620388031,
"avg_line_length": 32.269229888916016,
"blob_id": "01076ab3a44048c0119adec992a9759c42f51b61",
"content_id": "478229fb61af149fe1c10ba4fb44a4ce4b77c6a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2594,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 78,
"path": "/test.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "from urllib.parse import urlparse\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nimport os\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\ndef httpget(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None.\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if isResponseOK(resp):\n return resp.text\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(url, str(e)))\n return None\n\ndef isResponseOK(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise.\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)\n\ndef getCurrentDateTime():\n now = datetime.now()\n return now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n\ndef createWorkSessionFolder(createInPath):\n createdFolder = createInPath + \"\\\\\" + \"session_\" + getCurrentDateTime()\n os.mkdir(createdFolder)\n return createdFolder\n\ndef to_unicode_or_bust(obj, encoding='utf-8'):\n if isinstance(obj, basestring):\n if not isinstance(obj, unicode):\n obj = unicode(obj, encoding)\n return obj\n\ndef cleanPageContent(html):\n soup = BeautifulSoup(html, \"html.parser\") # create a new bs4 object from the html data loaded\n for script in soup([\"script\", \"style\"]): # remove all javascript and stylesheet code\n script.extract()\n # get text\n text = soup.get_text()\n # break into lines and remove leading and trailing space on each\n lines = (line.strip() for line in text.splitlines())\n # break multi-headlines into a line each\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n # drop blank lines\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n return text\n\ndef main():\n url = \"https://www.delfi.lt/news/daily/world/naujas-skandalas-vokietijoje-tarsi-sprogimas-isikiso-ir-merkel.d?id=77357427\"\n pageContent = httpget(url)\n pageText = cleanPageContent(pageContent)\n\n writeFile = open(\"test.txt\", \"w+\", encoding='utf-8')\n writeFile.writelines(pageText)\n writeFile.close()\n\n writeFile = open(\"test.htm\", \"w+\", encoding='utf-8')\n writeFile.writelines(pageContent)\n writeFile.close()\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.6370670199394226,
"alphanum_fraction": 0.6414629817008972,
"avg_line_length": 30.600000381469727,
"blob_id": "c38da50bf66c81374eeeded35f7bcfba6789c5c2",
"content_id": "253ff56d21da87e1f77bc78c74dbb0d13fae8b9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5687,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 180,
"path": "/ContentFetcher.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import abc\n\nfrom urllib.parse import urlparse\n\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\n\nfrom os import listdir\nfrom os.path import isfile, join\n\n\nclass ContentFetcherAbstract(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def getWorkList(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getContentScraperSuggestion(self, resource):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getContent(self, resource):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getResourceName(self, resource):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getFullSafeResourceName(self, resource):\n \"\"\"Required Method\"\"\"\n\n\nclass FileContentFetcher(ContentFetcherAbstract):\n def __init__(self, filesPath):\n self._filesPath = filesPath\n\n def getWorkList(self):\n onlyFiles = [self._filesPath + \"\\\\\" + f for f in listdir(self._filesPath) if isfile(join(self._filesPath, f))]\n return onlyFiles\n\n def getContentScraperSuggestion(self, resource):\n contentScraperSuggestion = \"\"\n\n if resource.find(\"15minlt\") != -1:\n contentScraperSuggestion = \"www.15min.lt\"\n elif resource.find(\"delfilt\") != -1:\n contentScraperSuggestion = \"www.delfi.lt\"\n elif resource.find(\"lrytaslt\") != -1:\n contentScraperSuggestion = \"www.lrytas.lt\"\n else:\n raise Exception(\"Could not pick content scraper strategy for \" + resource)\n\n return contentScraperSuggestion\n\n def getContent(self, resource):\n resourceFile = open(resource, \"r\", encoding=\"utf-8\")\n fileContent = resourceFile.readlines()\n mergedFileContent = self._getMergedFileContent(fileContent)\n return mergedFileContent\n\n def getResourceName(self, resource):\n return self.getContentScraperSuggestion(resource)\n\n def getFullSafeResourceName(self, resource):\n return self._getFullSafeResourceName(resource)\n\n def _getFullSafeResourceName(self, resource):\n translationTable = dict.fromkeys(map(ord, '!@#$%^&?*()_+=[];/\\\\,.:'), None)\n stripped = resource.translate(translationTable)[:40]\n\n safeUrl = stripped\n return safeUrl\n\n def _getMergedFileContent(self, fileContent):\n mergedFileContent = \"\"\n\n for line in fileContent:\n mergedFileContent += str(line)\n\n return mergedFileContent\n\n\nclass HttpContentFetcher(ContentFetcherAbstract):\n def __init__(self, inputFilePath):\n self._inputFilePath = inputFilePath\n\n def getWorkList(self):\n return self._getContentFromInputFile()\n\n def getContentScraperSuggestion(self, resource):\n return self._getContentScraperSuggestion(resource)\n\n def getResourceName(self, resource):\n return self._getSourceHostname(resource)\n\n def getContent(self, resource):\n return self._httpget(resource)\n\n def getFullSafeResourceName(self, resource):\n return self._getFullSafeResourceName(resource)\n\n def _getFullSafeResourceName(self, url):\n parsedUrl = urlparse(url)\n translationTable = dict.fromkeys(map(ord, '!@#$%^&?*()_+=[];/\\\\,.:'), None)\n strippedPath = parsedUrl.path.translate(translationTable)[:40]\n\n strippedHostname = parsedUrl.hostname.replace(\"w\", \"\").replace(\".\", \"\")\n safeUrl = strippedHostname + \"_\" + strippedPath\n return safeUrl\n\n def _getSourceHostname(self, url):\n return urlparse(url).hostname\n\n def _getContentScraperSuggestion(self, url):\n parsedUrl = urlparse(url)\n contentScraperSuggestion = \"\"\n\n if parsedUrl.hostname == \"www.15min.lt\":\n contentScraperSuggestion = \"www.15min.lt\"\n elif parsedUrl.hostname == \"www.delfi.lt\":\n contentScraperSuggestion = \"www.delfi.lt\"\n elif parsedUrl.hostname == \"www.lrytas.lt\":\n contentScraperSuggestion = \"www.lrytas.lt\"\n else:\n raise Exception(\"Could not pick content scraper strategy for \" + url)\n\n return contentScraperSuggestion\n\n def _getContentFromInputFile(self):\n inputFile = open(self._inputFilePath, \"r\")\n fileContent = inputFile.readlines()\n inputFile.close()\n\n fileContent = self._filterFile(fileContent)\n\n fileContentCleansed = []\n for line in fileContent:\n fileContentCleansed.append(self._cleanurl(line))\n\n return fileContentCleansed\n\n def _filterFile(self, fileContent):\n doNotIncludeTheseLinksPlease = [\"video\", \"multimedija\"]\n filteredFileContent = []\n for url in fileContent:\n parsedUrl = urlparse(url)\n firstPathInUrl = parsedUrl.path[1:parsedUrl.path.find(\"/\", 1)]\n if firstPathInUrl in doNotIncludeTheseLinksPlease:\n continue\n filteredFileContent.append(url)\n return filteredFileContent\n\n def _cleanurl(self, url):\n return str(url).strip()\n\n def _httpget(self, url):\n try:\n with closing(get(url, stream=True)) as resp:\n if self._isResponseOK(resp):\n return resp.text\n else:\n return None\n\n except RequestException as e:\n print(str(e))\n return None\n\n def _isResponseOK(self, resp):\n content_type = resp.headers['Content-Type'].lower()\n\n if resp.status_code != 200:\n saveToFile(\"C:\\Data\\AnalyzeLinks\", [resp.status_code, resp.url])\n\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)"
},
{
"alpha_fraction": 0.5899929404258728,
"alphanum_fraction": 0.5950669646263123,
"avg_line_length": 28.32231330871582,
"blob_id": "4f66ea2b4b3b6e67845a16b6859369fa6d6ce831",
"content_id": "7ff74cae6558a015c51a07d311c85b4463c747b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7095,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 242,
"path": "/LinkScraper.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import abc\n\nfrom datetime import date, timedelta\nimport time\n\nfrom urllib.parse import urlparse\n\nfrom bs4 import BeautifulSoup\n\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium import webdriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\n\nimport ScraperHelper as helper\n\n\nclass LinkScraperAbstract(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def getWorkUrls(self):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getLinksFromPage(self, pageContent):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getPageContent(self, resourceLink):\n \"\"\"Required Method\"\"\"\n\n @abc.abstractmethod\n def getCpuCount(self):\n \"\"\"Required Method\"\"\"\n\n\nclass FifteenLinkScraper(LinkScraperAbstract):\n def __init__(self, cpuCount, fromDate, toDate, seedUrl, params):\n self._cpuCount = cpuCount\n self._fromDate = fromDate\n self._toDate = toDate\n self._seedUrl = seedUrl\n self._params = params\n\n def getWorkUrls(self):\n workUrls = []\n iterationsCount = self.getIterationsCount()\n\n for i in range(0, iterationsCount):\n url = self._seedUrl\n newDate = self._toDate - timedelta(i)\n urlParams = str(self._params).format(self.formatDate(newDate))\n url += urlParams\n workUrls.append(url)\n\n return workUrls\n\n def formatDate(self, date = date(2000, 1, 1)):\n return date.strftime(\"%Y-%m-%d\")\n\n def getIterationsCount(self):\n dateDelta = self._toDate - self._fromDate\n iterationsCount = dateDelta.days\n iterationsCount += 1\n return iterationsCount\n\n def getLinksFromPage(self, pageContent):\n soup = BeautifulSoup(pageContent, 'html.parser')\n links = set()\n\n for article in soup.findAll(\"article\"):\n for a in article.findAll(\"a\", attrs={\"class\":\"vl-img-container\"}):\n links.add(a.get('href'))\n\n return links\n\n def getPageContent(self, resourceLink):\n return helper.httpget(resourceLink)\n\n def getCpuCount(self):\n return self._cpuCount\n\n\nclass DelfiLinkScraper(LinkScraperAbstract):\n def __init__(self, cpuCount, fromDate, toDate, seedUrl, params, iterationsCount = 0):\n self._cpuCount = cpuCount\n self._fromDate = fromDate\n self._toDate = toDate\n self._seedUrl = seedUrl\n self._params = params\n self._iterationsCount = iterationsCount\n\n def getWorkUrls(self):\n workUrls = []\n iterationsCount = self.getIterationsCount()\n\n fromDateText = self.formatDate(self._fromDate)\n toDateText = self.formatDate(self._toDate)\n\n for i in range(1, iterationsCount):\n url = self._seedUrl\n urlParams = str(self._params).format(fromDateText, toDateText, i)\n url += urlParams\n workUrls.append(url)\n\n return workUrls\n\n def formatDate(self, date=date(2000, 1, 1)):\n return date.strftime(\"%d.%m.%Y\")\n\n def getIterationsCount(self):\n return self._iterationsCount + 1\n\n def getLinksFromPage(self, pageContent):\n soup = BeautifulSoup(pageContent, 'html.parser')\n links = set()\n\n for div in soup.findAll(\"div\", attrs={\"class\":\"row\"}):\n for a in div.findAll(\"a\", attrs={\"class\":\"img-link\"}):\n links.add(a.get('href'))\n\n return links\n\n def getPageContent(self, resourceLink):\n return helper.httpget(resourceLink)\n\n def getCpuCount(self):\n return self._cpuCount\n\n\nclass LrytasLinkScraper(LinkScraperAbstract):\n def __init__(self, fromDate, toDate, seedUrl, webDriverPath):\n self._fromDate = fromDate\n self._toDate = toDate\n self._seedUrl = seedUrl\n self._webDriverPath = webDriverPath\n\n def getWorkUrls(self):\n workUrls = []\n workUrls.append(self._seedUrl)\n return workUrls\n\n def getIterationsCount(self):\n return self._iterationsCount\n\n def getLinksFromPage(self, pageContent):\n soup = BeautifulSoup(pageContent, 'html.parser')\n links = set()\n\n if soup:\n for article in soup.findAll(\"article\", attrs={\"class\":\"post\"}):\n articleLinkTag = article.find(\"a\")\n if articleLinkTag:\n articleLink = articleLinkTag.get(\"href\")\n if self._isLinkValid(articleLink):\n links.add(articleLink)\n\n return links\n\n def getPageContent(self, resourceLink):\n chrome_options = Options()\n #chrome_options.add_argument(\"--headless\")\n cdi = webdriver.Chrome(self._webDriverPath, options=chrome_options)\n\n loadMoreElement = (By.ID, \"loadMore\")\n cdi.get(resourceLink)\n timesLoaded = 1\n\n pageContent = None\n try:\n continueLoading = True\n while continueLoading:\n time.sleep(1)\n WebDriverWait(cdi, 10).until(EC.element_to_be_clickable(loadMoreElement)).click()\n timesLoaded += 1\n\n if (timesLoaded % 25) == 0:\n partialPageContent = cdi.page_source\n continueLoading = self._continueLoading(partialPageContent)\n\n pageContent = cdi.page_source\n except Exception as ex:\n print(\"Exception has occured on iteration \" + str(timesLoaded) + \": \" + str(ex))\n\n cdi.quit()\n\n return pageContent\n\n def _continueLoading(self, pageContent):\n continueLoading = True\n\n soup = BeautifulSoup(pageContent, 'html.parser')\n lastArticleTag = soup.findAll(\"article\", attrs={\"class\":\"post\"})[-1]\n lastArticleLinkTag = lastArticleTag.find(\"a\")\n\n lastArticleDate = None\n\n if lastArticleLinkTag:\n url = lastArticleLinkTag.get(\"href\")\n parsedUrl = urlparse(url)\n\n sectorPosition = 0\n pathParts = parsedUrl.path[1:].split(\"/\")\n for sector in pathParts:\n try:\n value = int(sector)\n except:\n value = 0\n\n if value != 0:\n year = value\n try:\n month = int(pathParts[sectorPosition + 1])\n day = int(pathParts[sectorPosition + 2])\n lastArticleDate = date(year, month, day)\n except:\n lastArticleDate = None\n\n break\n\n sectorPosition += 1\n\n if lastArticleDate and lastArticleDate < self._fromDate:\n continueLoading = False\n\n if lastArticleDate:\n print(\"Currently on date: \" + str(lastArticleDate))\n\n return continueLoading\n\n def _isLinkValid(self, link):\n isValid = True\n\n if len(link) == 0 or link is None:\n isValid = False\n\n return isValid\n\n def getCpuCount(self):\n return 1"
},
{
"alpha_fraction": 0.728386640548706,
"alphanum_fraction": 0.7420013546943665,
"avg_line_length": 38.716217041015625,
"blob_id": "27990ffb2eed2367971956397a6d6cf29716f726",
"content_id": "11cb736dcde5b25e12ca74fdfc24550174d8e4e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2938,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 74,
"path": "/GetLinks.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "from LinkScraper import FifteenLinkScraper, DelfiLinkScraper, LrytasLinkScraper\nimport ScraperHelper as helper\n\nfrom datetime import date\n\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\nimport multiprocessing\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\n\nclass SimpleLinkScraper:\n def __init__(self, linkScraperStrategy):\n self._linkScraperStrategy = linkScraperStrategy\n\n def getLinks(self):\n workUrls = self._linkScraperStrategy.getWorkUrls()\n inputs = tqdm(workUrls)\n\n links = Parallel(n_jobs=self._linkScraperStrategy.getCpuCount())(delayed(self._processUrl)(url) for url in inputs)\n\n return self._mergeResults(links)\n\n def _processUrl(self, url):\n pageContent = self._linkScraperStrategy.getPageContent(url)\n linksFromPage = self._linkScraperStrategy.getLinksFromPage(pageContent)\n return linksFromPage\n\n def _mergeResults(self, setsOfLinks):\n merged = set()\n for eachSet in setsOfLinks:\n merged = merged.union(eachSet)\n return merged\n\ndef main():\n workFolder = \"C:\\Data\\GetLinks\"\n workSessionFolder = helper.createWorkSessionFolder(workFolder)\n\n fromDate = date(2019, 1, 1)\n toDate = date(2019, 12, 31)\n\n fifteenSeedUrl = \"https://www.15min.lt/naujienos/aktualu/lietuva\"\n fifteenParams = \"?offset={0}%2023:59:59\" #15min date format: year-month-day\n\n delfiSeedUrl = \"https://www.delfi.lt/archive/index.php\"\n delfiParams = \"?fromd={0}&tod={1}&channel=1&category=0&query=&page={2}\" #delfi date in format: day.month.year\n delfiIterationsCount = 866\n #delfiIterationsCount = 2 #Test\n\n # Iterations justification: each click on \"Daugiau\" loads 24 unique articles. We load articles forever and at each 25th\n # load we check the last article's date from it's url - if it's still newer than fromDate - we continue the articles loading.\n # This strategy was set up to work like so because there is no trivial way to access the archive in lrytas.lt portal.\n lrytasSeedUrl = \"https://www.lrytas.lt/lietuvosdiena/aktualijos/\"\n lrytasWebDriverPath = ChromeDriverManager().install()\n\n cpuCount = multiprocessing.cpu_count()\n\n fifteenLinkScraper = SimpleLinkScraper(FifteenLinkScraper(cpuCount, fromDate, toDate, fifteenSeedUrl, fifteenParams))\n fifteenLinks = fifteenLinkScraper.getLinks()\n helper.saveToFile(workSessionFolder, fifteenLinks)\n\n delfiLinkScraper = SimpleLinkScraper(DelfiLinkScraper(cpuCount, fromDate, toDate, delfiSeedUrl, delfiParams, delfiIterationsCount))\n delfiLinks = delfiLinkScraper.getLinks()\n helper.saveToFile(workSessionFolder, delfiLinks)\n\n lrytasLinkScraper = SimpleLinkScraper(LrytasLinkScraper(fromDate, toDate, lrytasSeedUrl, lrytasWebDriverPath))\n lrytasLinks = lrytasLinkScraper.getLinks()\n helper.saveToFile(workSessionFolder, lrytasLinks)\n\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.6324940323829651,
"alphanum_fraction": 0.6378896832466125,
"avg_line_length": 27.775861740112305,
"blob_id": "832e824c7eef558f756a9da0dcf58ca70bac3032",
"content_id": "f7dab3b4b313a3a8d1a33241e5680d5b4413640f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1668,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 58,
"path": "/ScraperHelper.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import os\nfrom datetime import datetime\n\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\n\n\ndef getCurrentDateTime():\n now = datetime.now()\n return now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n\n\ndef createWorkSessionFolder(createInPath):\n createdFolder = createInPath + \"\\\\\" + \"session_\" + getCurrentDateTime()\n os.mkdir(createdFolder)\n return createdFolder\n\n\ndef saveToFile(path, links):\n fileNameWithPath = path + \"\\\\\" + \"result.csv\" #TODO: result.csv is hardcoded, make it dynamic\n file = open(fileNameWithPath, \"a+\")\n for link in links:\n if (link is not None):\n file.write(link + \"\\n\")\n file.close()\n\n\ndef httpget(url):\n \"\"\"\n Attempts to get the content at `url` by making an HTTP GET request.\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None.\n \"\"\"\n try:\n with closing(get(url, stream=True)) as resp:\n if isResponseOK(resp):\n return resp.text\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(url, str(e))) #TODO: would this even work?\n return None\n\n\ndef isResponseOK(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise.\n \"\"\"\n content_type = resp.headers['Content-Type'].lower()\n\n if resp.status_code != 200:\n saveToFile(\"C:\\Data\\GetLinks\", [resp.status_code, resp.url]) #TODO: make it dynamic\n\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)"
},
{
"alpha_fraction": 0.6557863354682922,
"alphanum_fraction": 0.6587536931037903,
"avg_line_length": 36.55555725097656,
"blob_id": "6bd28181b45871facaf9e460bad9b68b83a69dc0",
"content_id": "e81418730ffd60e68cdf2d7cb5b486456bcf7541",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 9,
"path": "/regex.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import re\n\nprint(re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats'))\n# Output: ['cats', 'dogs']\n\nprint([x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')])\n# Output: ['all cats are', 'all dogs are']\n\nprint(\"stringidfngidfs\"[:5])"
},
{
"alpha_fraction": 0.6371794939041138,
"alphanum_fraction": 0.6471154093742371,
"avg_line_length": 30.525253295898438,
"blob_id": "a2d8b80d8754dce231d417c3fc11f8b20fb5fd15",
"content_id": "afa28269dfd1c55b45f80b430c54e840cb79be69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3126,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 99,
"path": "/Dictionary.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "import ScraperHelper as helper\nfrom AnalyzeLinks import SimpleContentScraper\nfrom ContentFetcher import FileContentFetcher\nfrom ContentScraper import FifteenContentScraper, DelfiContentScraper, LrytasContentScraper\n\nfrom bs4 import BeautifulSoup\n\nimport multiprocessing\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\n\n\ndef cleanPageContent(html):\n soup = BeautifulSoup(html, \"html.parser\") # create a new bs4 object from the html data loaded\n for script in soup([\"script\", \"style\"]): # remove all javascript and stylesheet code\n script.extract()\n # get text\n text = soup.get_text()\n # break into lines and remove leading and trailing space on each\n lines = (line.strip() for line in text.splitlines())\n # break multi-headlines into a line each\n chunks = (phrase.strip() for line in lines for phrase in line.split(\" \"))\n # drop blank lines\n text = '\\n'.join(chunk for chunk in chunks if chunk)\n\n return text\n\n\ndef createDictionary(work, fetcher):\n scraper = SimpleContentScraper.getContentScraperStrategy(fetcher.getContentScraperSuggestion(work), work)\n scraper.createParser(fetcher.getContent(work))\n articleScopes = scraper.getArticleScope()\n\n wordsDict = {}\n\n text = \"\"\n for scope in articleScopes:\n try:\n text += \" \" + scope.text\n except:\n text += \" \" + scope\n\n translation_table = dict.fromkeys(map(ord, '!@#$%^&?*()_+=[]-;<>/\\|~1234567890\\,.:\"„“'), None)\n text = text.translate(translation_table)\n text = text.replace(\"\\n\", \" \")\n text = text.replace(\"\\t\", \"\")\n text = text.replace(\"–\", \" \")\n text = text.strip()\n\n for word in text.split(\" \"):\n word = word.strip()\n\n if len(word) == 0:\n continue\n\n if word not in wordsDict:\n wordsDict[word] = 1\n else:\n wordsDict[word] = wordsDict[word] + 1\n\n return wordsDict\n\n\ndef processWork(work, fetcher):\n wordsDict = {}\n try:\n wordsDict = createDictionary(work, fetcher)\n except Exception as ex:\n print(\"Could not process, exception caught: \" + str(ex))\n return wordsDict\n\n\ndef main():\n mypath = \"C:\\Data\\deliverables\\iteration3\\sources\"\n #mypath = \"C:\\Data\\AnalyzeLinks\\session_10_05_2020_17_48_14\" #Test\n dictionariesPath = \"C:\\Data\\Dictionary\"\n cpuCount = multiprocessing.cpu_count()\n\n fetcher = FileContentFetcher(mypath)\n workList = tqdm(fetcher.getWorkList())\n\n wordDictionaries = Parallel(n_jobs=cpuCount)(delayed(processWork)(work, fetcher) for work in workList)\n\n wordDict = {}\n for dictionary in wordDictionaries:\n for key in dictionary:\n if key not in wordDict:\n wordDict[key] = dictionary[key]\n else:\n wordDict[key] = wordDict[key] + dictionary[key]\n\n dictFileName = dictionariesPath + \"\\\\\" + \"dictionary_\" + helper.getCurrentDateTime() + \".csv\"\n resultFile = open(dictFileName, \"w+\", encoding=\"utf-8\")\n for key in wordDict:\n resultFile.write(key + \",\" + str(wordDict[key]) + \"\\n\")\n resultFile.close()\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.654530942440033,
"alphanum_fraction": 0.6598458886146545,
"avg_line_length": 26.676469802856445,
"blob_id": "0bec9fc4bc641b891f7e3447d66a400d81ec1e41",
"content_id": "84ff653ef9a4f2233ed46c9f7e4bd4fd090a45ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3763,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 136,
"path": "/oldGetLinks2.py",
"repo_name": "maeof/ScrapeNewsAgencies",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nimport time\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\n\n#service = Service('c:\\\\data\\\\chromedriver\\\\chromedriver.exe')\n#service.start()\ncdi = webdriver.Chrome(\"c:\\\\data\\\\chromedriver\\\\chromedriver.exe\", options=chrome_options)\n#cdi = webdriver.Remote(service.service_url)\n\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nimport urllib3 as urllib\nfrom urllib.parse import urlparse\nimport sys\nimport os\nfrom datetime import datetime\n\ndef getCurrentDateTime():\n now = datetime.now()\n return now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n\ndef createWorkSessionFolder(createInPath):\n createdFolder = createInPath + \"\\\\\" + \"session_\" + getCurrentDateTime()\n os.mkdir(createdFolder)\n return createdFolder\n\nworkFolder = \"C:\\Data\\GetLinks\"\nworkSessionFolder = createWorkSessionFolder(workFolder)\n\ndef httpget(url):\n cdi.get(url)\n time.sleep(3)\n return cdi.page_source\n\ndef getIncrementalUrl(url, i):\n return url.replace(\"{0}\", str(i))\n\ndef isIncrementalUrl(url):\n if (url.find(\"{0}\") != -1):\n return True\n else:\n return False\n\ndef getLinksFromPageContent(pageContent):\n soup = BeautifulSoup(pageContent, 'html.parser')\n links = set()\n\n for a in soup.find_all('a'):\n url = a.get('href')\n links.add(url)\n\n return links\n\ndef saveToFile(path, links):\n fileNameWithPath = path + \"\\\\\" + \"result.csv\"\n file = open(fileNameWithPath, \"a+\")\n for link in links:\n if (link is not None):\n file.write(link + \"\\n\")\n file.close()\n\ndef getLinks(regularUrls):\n allLinks = set()\n for url in regularUrls:\n pageContent = httpget(url)\n links = getLinksFromPageContent(pageContent)\n allLinks = allLinks.union(links)\n\n saveToFile(workSessionFolder, allLinks)\n\ndef getLinksFromIncrementalUrls(incrementalUrls, pagesCount):\n allLinks = set()\n for url in incrementalUrls:\n for i in range(1, pagesCount + 1):\n urlForRequest = getIncrementalUrl(url, i)\n\n print(urlForRequest)\n\n startTime = time.time()\n pageContent = httpget(urlForRequest)\n endTime = time.time()\n print(\"httpget: {0}\".format(endTime - startTime))\n\n startTime = time.time()\n links = getLinksFromPageContent(pageContent)\n endTime = time.time()\n print(\"getLinksFromPageContent: {0}\".format(endTime - startTime))\n\n startTime = time.time()\n allLinks = allLinks.union(links)\n print(\"allLinks.union(links): {0}\".format(endTime - startTime))\n endTime = time.time()\n\n saveToFile(workSessionFolder, allLinks)\n\ndef validateArgs(args):\n if (args[1] is None or args[2] is None):\n print(\"Wrong arguments. 1st argument is the file of links, 2nd argument is the incremental value of how many pages to view.\")\n return False\n\ndef main(args):\n #if (validateArgs(args) == False):\n #return\n\n #linksFilePath = str(args[1])\n #pagesCount = int(args[2])\n #linksFilePath = \"links2.txt\"\n linksFilePath = \"links.txt\"\n pagesCount = 10\n\n file = open(linksFilePath, \"r\")\n fileLines = file.readlines()\n file.close()\n\n incrementalUrls = []\n regularUrls = []\n\n for line in fileLines:\n if (isIncrementalUrl(line)):\n incrementalUrls.append(line)\n else:\n regularUrls.append(line)\n\n getLinksFromIncrementalUrls(incrementalUrls, pagesCount)\n #getLinks(regularUrls)\n\n cdi.quit()\n\nif __name__ == '__main__':\n main(sys.argv)"
}
] | 13 |
zonghengqidian/Data-analysis | https://github.com/zonghengqidian/Data-analysis | faa603c258ad1113686bdaedb60ba8e999e02967 | 4a1d6c70bbd1713384688b5677553eb3492bfde5 | fe4e0710dec9b1b88685f08cff1c8f1e4be99788 | refs/heads/master | 2020-07-18T08:42:23.367737 | 2019-09-07T11:09:32 | 2019-09-07T11:09:32 | 206,215,798 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6355894207954407,
"alphanum_fraction": 0.6553115248680115,
"avg_line_length": 41.75,
"blob_id": "f14a396efe6736717ca57c3adb8df01164c34536",
"content_id": "1611bdaa1756fa4d6770ca632a6142989aa5c28f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6483,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 104,
"path": "/手写识别系统代码.py",
"repo_name": "zonghengqidian/Data-analysis",
"src_encoding": "UTF-8",
"text": "'''\n使用k近邻算法实现手写识别系统\n'''\nimport numpy as np\nfrom os import listdir\n'''\nk近邻算法\n\nInput: inX: 一个测试数据,是(1xN)的数组\n dataSet: 样本数据的特征矩阵,是(NxM)的数组,其中N为样本数据的个数,M是每个样本具有的特征数\n labels: 已知数据的标签或类别,是(1xM)的数组\n k: k近邻算法中的k,含义是选取距离最近的k个点 \nOutput: 测试样本所属的标签,属于labels中的一个\n\n'''\ndef classify0(inX, dataSet, labels, k):\n dataSetSize = dataSet.shape[0]\n # shape[0]返回dataSet的行数,也就是样本数据个数N\n diffMat = np.tile(inX, (dataSetSize,1)) - dataSet\n # np.tile(inX,(a,b))函数将inX重复a行,重复b列\n sqDiffMat = diffMat**2\n #作差后,对数组中每个值求平方\n sqDistances = sqDiffMat.sum(axis=1)\n #np.sum()是对数组中所有元素求和,sum(axis=0)是每列所有元素求和,sum(axis=1)是每行所有元素求和\n distances = sqDistances**0.5\n #开平方,求欧式距离\n sortedDistIndicies = distances.argsort()\n #np.argsort()函数返回的是数组中值从小到大排序所对应的在还未排序的数组中的索引值,这个很重要,最好在自己电脑上打开ipython自己试一下\n classCount={}\n #建立一个空字典,存储对这个测试数据的判断结果\n for i in range(k):\n voteIlabel = labels[sortedDistIndicies[i]]\n #取出前k个距离测试点最近的点对应的标签\n classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1\n #计算每个标签的样本数。字典get()函数返回指定键的值,如果值不在字典中返回默认值0,与dict.key()不一样\n sortedClassCount = sorted(classCount.items(), key=lambda x:x[1], reverse=True)\n #reverse=True为降序排列,不写的话都是默认升序排列字,这时结果是一个由键值对组成的元组组成的列表,也就是列表中包含元组,元组中包含有键值对\n return sortedClassCount[0][0] #返回列表的第一个元组的第一个值,也就是测试样本所属的标签\n\n'''\n函数功能:将(32x32)的二进制图像转换为长1024的一维数组\n\nInput: filename :文件名\nOutput: 长1024的一维数组\n\n'''\ndef img2vector(filename): #第一种方法\n fr = open(filename)\n first_str = fr.read()\n second_str = first_str.split()\n last_str = ''.join(second_str)\n returnVect1 = list(last_str)\n returnVect = [int(i) for i in returnVect1] #这句话必须要有,不然列表中的数字会有引号,导致出现dtype<'U1'的情况,最终程序将无法运行\n return returnVect\n#def img2vector(filename): #第二种方法\n# returnVect = np.zeros((1,1024)) #创建空numpy数组,是一个(1×10)的二维数组\n# fr = open(filename) #打开文件,只要不使用close语句,文件就一直会打开\n# for i in range(32):\n# lineStr = fr.readline() #读取每一行内容,返回的是str,readlines()返回的是字典,不可搞混了\n# for j in range(32):\n# returnVect[0,32*i+j] = int(lineStr[j])#将每行前32个字符值存储在numpy数组中\n# return returnVect\n\n'''\n函数功能:手写数字分类测试\n'''\ndef handwritingClassTest(filename,filename2):\n hwLabels = [] #建立一个存储标签(labels)的列表,便于索引\n trainingFileList = listdir(filename) #加载训练集,返回的是个列表,得到的是filename文件夹下面文件的列表\n m = len(trainingFileList) #计算文件夹下文件的个数,因为每一个文件是一个手写体数字,每一个文件都对应着特征与标签\n trainingMat = np.zeros((m,1024)) #初始化训练数组(样本数组),大小为(M,N)的数组\n for i in range(m):\n fileNameStr = trainingFileList[i] #获取文件名\n fileStr = fileNameStr.split('.')[0] #从文件名中解析出分类的第一个结果,\n classNumStr = int(fileStr.split('_')[0]) #根据实际情况,从文件名通过split分类,又通过'_'分类,最后得到这个测试数据到底是0-9中哪个标签\n hwLabels.append(classNumStr) #将得到的标签添加到最开始存储标签的列表hwLabels中\n trainingMat[i,:] = img2vector(filename+'/%s' % fileNameStr) #对每一个样本数组,添加相应的特征值\n testFileList = listdir(filename2) #加载测试数据集,结果是个列表。下面过程是一个验证算法准确度的过程\n errorCount = 0.0 #常用的计数方法\n mTest = len(testFileList) #获取测试数据组合的长度,返回int\n for i in range(mTest):\n fileNameStr = testFileList[i] #第i个位置处的文件名称\n fileStr = fileNameStr.split('.')[0] #将文件名按照split('.'')分裂后形成一个新的列表,再选前者\n classNumStr = int(fileStr.split('_')[0]) #将上步得到的结果按照'_'进行分割,得到测试数据对应的真是标签,便于两者之间比较\n vectorUnderTest = img2vector(filename2+'/%s' % fileNameStr)\n classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3) #开始分类\n print ('the classifier came back with: %d, the real answer is: %d' % (classifierResult, classNumStr))\n if (classifierResult != classNumStr):\n errorCount += 1.0 #计算分错的样本数\n print ('\\nthe total number of errors is: %d' % errorCount)\n print ('\\nthe total error rate is: %f' % (errorCount/float(mTest))) #错的样本数量与实际进行测试的数据数量的比值,就是错误的概率,也是算法的正确度\n\n'''\n主函数\n'''\nif __name__ == '__main__':\n filename = 'F:/BaiduNetdiskDownload/机器学习实战源代码MLiA_SourceCode/machinelearninginaction/Ch02/digits/trainingDigits'#文件的绝对路径\n filename2 = 'F:/BaiduNetdiskDownload/机器学习实战源代码MLiA_SourceCode/machinelearninginaction/Ch02/digits/testDigits' #文件的绝对路径\n handwritingClassTest(filename,filename2)\n\n\n#最后的结果\n#the total number of errors is: 10\n#the total error rate is: 0.010571\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7535098195075989,
"alphanum_fraction": 0.7716214656829834,
"avg_line_length": 43.22748947143555,
"blob_id": "ff26631ff06b99441ea8ef102b69e9e0326f31cd",
"content_id": "fd58afde601fb32d768fd337eb92df3e73865054",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14471,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 211,
"path": "/titanic.py",
"repo_name": "zonghengqidian/Data-analysis",
"src_encoding": "UTF-8",
"text": "#泰坦尼克号生还者预测\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport pandas as pd\nimport seaborn as sns\ntrain_data = pd.read_csv('F:/taitannike/titanic/train.csv')\ntest_data = pd.read_csv('F:/taitannike/titanic/test.csv')\n\ntrain_data.info() #查看相关数据信息(每列数据总数,每列数据有无空值之类)\ntest_data.info()\n#此处运行一次,发现train_test一共有891行数据,但是age只有714行数据,Cabin更少,只有204行数据,Embarked有889行数据,也少两行\n#test_data一共有418行数据,但是age只有332行数据,Fare只有417行数据,Cabin只有91行数据,\n#对这些数据缺失的特征值而言,如何处理他们是一个大问题,关系着模型的准确度train_data.describe()\n\n#查看最大值,最小值,百分数之类的数据,与如何处理缺失值有很大关系(name,sex,ticket,cabin,embarked这些不是数字的在处理过程中都被忽略了\n#可以看出,至少百分之五十以上的人Pclass都是3,平均年龄接近30岁,至少50%以上的人旅途中没有同乘的兄弟姐妹或者配偶,70%以上的人旅途中没有同乘的\n#父母或者小孩。另外,对比平均值mean与中位数50%对应的值,可以观察出数据的大概分布。比如说,age的mean和50%很接近,说明左右分布对称,fare的mean\n#和50%相差很大,说明位于中位值之后的数据比位于中位数前的数据少得多,大多数人都坐的是比较便宜的位置\n#平均值mean的计算\n\ntrain_data.describe()\n\n#查看最大值,最小值,百分数之类的数据,与如何处理缺失值有很大关系(name,sex,ticket,cabin,embarked这些不是数字的在处理过程中都被忽略了\n#可以看出,至少百分之五十以上的人Pclass都是3,平均年龄接近30岁,至少50%以上的人旅途中没有同乘的兄弟姐妹或者配偶,70%以上的人旅途中没有同乘的\n#父母或者小孩。另外,对比平均值mean与中位数50%对应的值,可以观察出数据的大概分布。比如说,age的mean和50%很接近,说明左右分布对称,fare的mean\n#和50%相差很大,说明位于中位值之后的数据比位于中位数前的数据少得多,大多数人都坐的是比较便宜的位置\n#平均值mean的计算\n\ntest_data.describe(include='all') #include='all'包括了所有的信息,有可能对特征值的选择有很大用处,比如top(频数最高者)。还有看unique这一行\n#我们可以知道,name,ticket,cabin这几列值都很多,因此很难作为特征值(初步这样认为),其余的sex,embarked都是有数的,好分类,因此可以使用\n\ntrain_data.head() #查看数据具体信息,其中passengerId只是一个编号,应该与survived无关,Name不仅是字符而且毫无规律,因此初步认为无关,Sex列有\n#两类,分成male与female,因此需要进行one-hot编码,后续的Embarked也是如此\n\n#现在可视化分析特征与结果的关系\nfig = plt.figure()\nax1 = fig.add_subplot(1,1,1)\nplt.plot(train_data['PassengerId'],train_data['Survived'].cumsum())\nax1.set_title('PassengerId--Survived')\nax1.set_xlabel('PassengerId')\nax1.set_ylabel('all_number_of_survived')\n\n#在图中,我们可以清楚的看到,乘客的id和总的获救的人数基本是成一条直线,因此可以认为两者无关,passengerId不作为特征值。\n#其实我的理解就是这个Id编号应该是我们后来者自己家的,因此肯定是与结果无关的\n\n#接下来分析Pclass,Sex,Age,SibSp,Parch,Fare,Embarked这几个特征与结果Survived的关系,Cabin这个特征最后分析\nfig = plt.figure(figsize=(25,20))\nax1 = fig.add_subplot(2,4,1)\n#这种画图最好选择seaborn画,相比于matplotlib功能更强大,也更简单\n#对Pclass画图,因为Pclass值很少,因此可用卡方图画出它与Survived的关系\n#可以看出,Pclass越小(等级越高),获救的概率越大(1与0 的比值),在pclass=3的时候,概率更是大幅度下降\nsns.countplot(x='Pclass',hue='Survived',data=train_data)\n\n#对Sex画图,和Pclass一样,使用卡方图\n#从图看出,女性获救的概率远大于男性\nax2=fig.add_subplot(2,4,2)\nsns.countplot(x='Sex',hue='Survived',data=train_data)\n\n#对SibSp画图,Age值很多,不适用卡方图,稍后使用密度图画\n#从图看出,在sibsp=1或者2的时候获救的概率更大,它的值对于结果是有影响的\nax3 = fig.add_subplot(2,4,3)\nsns.countplot(x='SibSp',hue='Survived',data=train_data)\n\n#对Parch画图\n#从图看出,在Parch=1,2的时候获救的概率更大,它的值对于结果是有影响的\nax4 = fig.add_subplot(2,4,4)\nsns.countplot(x='Parch',hue='Survived',data=train_data)\n\n#对Embarked画图\n#从图可以看出,在C港口上船的人获救概率最大,S港口上船的人获救概率最小\nax5 = fig.add_subplot(2,4,5)\nsns.countplot(x='Embarked',hue='Survived',data=train_data)\n\n#对age画图.这里我们不仅需要找到年龄与结果Survived的关系,同样,最好还有获救的人和没获救的人的年龄对比。如下\n#从结果上看,明显整体而言,中间年龄段的人获救和没获救的概率都很大,这应该主要是因为这个年龄段的人比较多,因此,单纯的分析一条线没有意义\n#对比获救的人和没获救的人,我们可以看出获救的(红线)0-10这个年龄段的人相比没获救的人概率要大,因此,年龄和结果相关\nax6 = fig.add_subplot(2,4,6)\nsns.kdeplot(train_data.loc[train_data['Survived'] == 0,'Age'],color='k',shade=True,label='not survived')\nsns.kdeplot(train_data.loc[train_data['Survived'] == 1,'Age'],color='r',shade=True,label='survived')\nax6.set_xlabel('age')\nax6.set_ylabel('frequency')\n\n#同理,对Fare画图.同样,可以看出票价在30-60附近的最多,价格越高,红线(获救的人)的概率越大,价格在降低的时候,黑线(未获救)的人的概率远超红线\nax7 = fig.add_subplot(2,4,7)\nsns.kdeplot(train_data.loc[train_data['Survived'] == 0,'Fare'],color='k',shade=True,label='not survived')\nsns.kdeplot(train_data.loc[train_data['Survived'] == 1,'Fare'],color='r',shade=True,label='survived')\nax7.set_xlabel('fare')\nax7.set_ylabel('frequency')\n\n#分析Cabin这个特征,这个特征值很杂,而且还有大量缺失,因此简单的方法是直接将拥有cabin的记为yes,没有的记为no,实际上还可能与每个客舱里面的作为\n#有关,这个可以留待以后来考虑。\n#可以看出,have_cabin中,获救的人数是未获救的人数的两倍左右,而在no_cabin中,恰恰相反,没获救的人的数量是获救的人的数量的一倍多,因此cabin对\n#Survived的结果有很大影响,把它作为特征值考虑。\nax8 = fig.add_subplot(2,4,8)\nhave_cabin = train_data.Survived[pd.notnull(train_data.Cabin)].value_counts()\nprint(have_cabin) #查看have_cabin的结果\nno_cabin = train_data.Survived[pd.isnull(train_data.Cabin)].value_counts()\nprint(no_cabin) #查看no_cabin的结果)\ndf = pd.DataFrame({'have':have_cabin,'no':no_cabin})\ndf.plot(kind='bar',ax=ax8)\ndf\n\n#通过以上7个图,我们可以发现,这7个特征与Surviver的结果都是有关系的,因此全部作为特征考虑\n\n#现在对缺失值进行处理。首先数据缺失的一共有3种,分别是age,cabin,embarked\n#首先Embarked的数据缺失的最少,首先处理这列,直接用出现频率最高的值填充缺失值就好。但不能简单的用全体的出现频率,要考虑特征\ntrain_data[train_data['Embarked'].isnull()]\n#可以观察得到,两人survived,pclass都为1,sex都为female,sibsp,survived都为0,fare,cabin,甚至ticket都相同,因此可以认为两人的embarked都相同\n#下面寻找具有相同特征的样本,注意特征不能全选,选择一些最有代表性的就好\ntest1=train_data.loc[(train_data['Pclass']==1)&(train_data['Sex']=='female')&(train_data['SibSp']==0)&(train_data['Parch']==0)] #注意每个条件之间的小括号不能省略\n\ntest1.describe(include='all') #我们可以看到满足条件的一共有32种,出现频率最高的是C,所以给Embarked填充C\ntrain_data['Embarked']=train_data['Embarked'].fillna('C')\n\n#接下来填充age列的缺失值,同样的,因为age列缺失数值较多,所以考虑填充考虑了特征之后的平均值\nage_group_mean = train_data.groupby(['Pclass','Sex','Embarked'])['Age'].mean().reset_index()\ndef age_fill(row):\n return age_group_mean[((row['Pclass']==age_group_mean['Pclass'])&(row['Sex']==age_group_mean['Sex'])\n &(row['Embarked']==age_group_mean['Embarked']))]['Age'] #注意此时age_group_mean中接的是一个Series格式的布尔数组,按行取值\n#接下来就是填充age缺失值了\n\ntrain_data['Age'] = train_data.apply(lambda x:age_fill(x) if np.isnan(x['Age']) else x['Age'],axis=1) #此时x是样本数组中的一行,x['Age']是一个数字\ntrain_data.info() #看一下结果\n#这一步我们把age列的缺失值填好了\n\n#现在考虑填充最后一个缺失值Cabin列。因为Cabin缺失值很多,因此不能仔细考虑,在此简单的将他们分为有(have)和无(no)。\n#同样的原因,需要考虑test_data,因此在此使用函数\ndef set_cabin_type(dataframe):\n dataframe.loc[(dataframe.Cabin.isnull()),'Cabin'] = 'no'\n dataframe.loc[(dataframe.Cabin.notnull()),'Cabin'] = 'yes'\n return dataframe\ndataframe=train_data\ntrain_data=set_cabin_type(dataframe)\ntrain_data.info() #看看现在整体情况\n\ntrain_data.head() #看看现在数据的具体情况,我们发现age,fare这些数据都很大,pclass这些数据却很小,这会导致两者之间权重不同,因此,需要对\n#他们进行标准化处理。sex,cabin,embarked这几列都是字符串而不是数字,因此也需要对他们进行热编码\n\n#对pclass,sex,sibsp,parch,cabin,embarked这些属性进行热编码\ndummies_Pclass = pd.get_dummies(train_data['Pclass'],prefix='Pclass')\n#dummies_SibSp = pd.get_dummies(train_data['SibSp'],prefix='SibSp') 特征量太多,先不用\n#dummies_Parch = pd.get_dummies(train_data['Parch'],prefix='Parch') 特征量太多,先不用\ndummies_three = pd.get_dummies(train_data[['Sex','Cabin','Embarked']],prefix=['Sex','Cabin','Embarked'])\ntrain_data_result = pd.concat([train_data,dummies_Pclass,dummies_three],axis=1)\ntrain_data_result.drop(['Pclass','Sex','Cabin','Embarked','Name','Ticket'],axis=1,inplace=True)\n#axis=1不要忘了,除了对dataframe进行索引是直接在列上以外,其余的都默认在行上\n#看一下具体的数据\ntrain_data_result.head()\n\n#现在标准化数据,引入StandardScaler模块\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(train_data_result[['Age','SibSp','Parch','Fare']]) #此处必须而且只能选择age,fare这两列数据进行标准化,这个数据test_data标准化的时候也会用到\ntrain_data_result[['Age','SibSp','Parch','Fare']] = scaler.transform(train_data_result[['Age','SibSp','Parch','Fare']])\ntrain_data_result.head() #看看结果\n\n#用逻辑回归建模\nfrom sklearn.linear_model import LogisticRegression #引入逻辑回归模块\nlast_train_data = train_data_result.drop(['PassengerId','Survived'],axis=1,inplace=False) #除去PassengerId,Survived这两个特征,这个作为训练数据\ngoal_train_data = train_data_result['Survived'] #作为训练数据的目标\nmodel = LogisticRegression()\nmodel.fit(last_train_data,goal_train_data)\nmodel #看看自己创建的模型\n\n#接下来对test_data作和train_data一样的数据处理\n#同样,最初观察可知,test_data有三个特征数据缺失,分别是Fare,Cabin,Age。Fare只缺少一个,age缺少86个,Cabin缺少327个\ntest_data[test_data['Fare'].isnull()] #已知重要的特征为pclass,sex,age,sibsp,parch,embarked,但是显然age不能作为确定特征,但可以以一个范围作为特征\n\ntest2=test_data.loc[(test_data['Pclass']==3)&(test_data['Sex']=='male')&(test_data['Age']>40)&(test_data['SibSp']==0)\n &(test_data['Parch']==0)&(test_data['Embarked']=='S')] #注意每个条件之间的小括号不能省略\n\ntest2.describe(include='all') #我们可以看到满足条件的一共有4种,fare的均值是10.28,我们就给fare的缺失值为10.28\ntest_data['Fare']=test_data['Fare'].fillna(10.28)\ntest_data.head()\n\n#这一步处理age列数据,因为age列缺失数值较多,所以考虑填充考虑了特征之后的平均值\nage_group_mean2 = test_data.groupby(['Pclass','Sex','Embarked'])['Age'].mean().reset_index()\n\n#直接使用train_test数据处理时候建好的age_fill函数。然后填充age缺失值\n\ntest_data['Age'] = test_data.apply(lambda x:age_fill(x) if np.isnan(x['Age']) else x['Age'],axis=1) #此时x是样本数组中的一行,x['Age']是一个数字\ntest_data.info() #看一下结果\n#这一步我们把age列的缺失值填好了\n\n#这一步处理cabin数据,使用既有的set_cabin_type函数\ndataframe2=test_data\ntest_data=set_cabin_type(dataframe2)\ntest_data.info() #看看现在整体情况\ntest_data.head() #看看具体情况\n\n#对test_data数据进行独热编码\n#对pclass,sex,sibsp,parch,cabin,embarked这些属性进行热编码\ndummies2_Pclass = pd.get_dummies(test_data['Pclass'],prefix='Pclass')\ndummies2_three = pd.get_dummies(test_data[['Sex','Cabin','Embarked']],prefix=['Sex','Cabin','Embarked'])\ntest_data_result = pd.concat([test_data,dummies2_Pclass,dummies2_three],axis=1)\ntest_data_result.drop(['Pclass','Sex','Cabin','Embarked','Name','Ticket'],axis=1,inplace=True)\n#axis=1不要忘了,除了对dataframe进行索引是直接在列上以外,其余的都默认在行上\n#看一下具体的数据\ntest_data_result.head()\n\n#现在标准化test_data数据,必须使用早已计算好的标准化模块\n\ntest_data_result[['Age','SibSp','Parch','Fare']] = scaler.transform(test_data_result[['Age','SibSp','Parch','Fare']])\ntest_data_result.head() #看看结果\n\n#最后一步,数据预测\nlast_test_data = test_data_result.drop('PassengerId',axis=1,inplace=False)\npredictions = model.predict(last_test_data)\nresult = pd.DataFrame({'PassengerId':test_data['PassengerId'].values,'Survived':predictions.astype(np.int)})\nresult.to_csv(\"F:/taitannike/titanic/predictions_result.csv\",index=False)"
}
] | 2 |
rasakereh/time-series-predictors | https://github.com/rasakereh/time-series-predictors | e5c1e0a09872a0a7b2dface6acb1a9492de4e528 | 2539ab538cbcabfd82fc70e615bcfadef8ea38b7 | 195e3bf57029849808e9c3f69342135db13f5834 | refs/heads/master | 2023-08-16T10:58:01.291247 | 2021-09-10T16:49:43 | 2021-09-10T16:49:43 | 330,789,385 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5594030022621155,
"alphanum_fraction": 0.5701492428779602,
"avg_line_length": 48.25490188598633,
"blob_id": "d10fde3b26f22c6cc542d9539d7c376e791f0702",
"content_id": "8c72a7db3ef67daeabe6719f4c6058bbe1844471",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5025,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 102,
"path": "/src/MLShepard.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport faiss\nfrom .utils import rolling_window\n\nclass MLShepard:\n def __init__(\n self,\n future_scope=3,\n dimension=10,\n minor_days=3,\n trust_treshold=4,\n max_point_usage=5,\n avr_elemwise_dist=0.04,\n epsilon=1e-10\n ):\n self.future_scope = future_scope\n self.dimension = dimension\n self.minor_days = minor_days\n self.trust_threshold = trust_treshold\n self.max_point_usage = max_point_usage\n self.avr_elemwise_dist = avr_elemwise_dist\n self.epsilon = epsilon\n\n self.relevance_threshold = dimension**.5 * avr_elemwise_dist\n \n def fit(self, price_indices):\n self.price_indices = {}\n for capital_name in price_indices:\n self.price_indices[capital_name] = {'X': np.array([]), 'f': np.array([]), 'data': np.array([])}\n if price_indices[capital_name].shape[0] == 0:\n continue\n curr_prices = price_indices[capital_name]\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n self.price_indices[capital_name]['data'] = seq_price\n X = rolling_window(seq_price, self.dimension)\n padding = np.ones((self.dimension-1, self.dimension)) #np.random.normal(0, self.epsilon, (self.dimension-1, self.dimension))\n X = np.vstack((padding, X))\n self.price_indices[capital_name]['X'] = faiss.IndexFlatL2(X.shape[1])\n self.price_indices[capital_name]['X'].add(X.astype(np.float32))\n cum_sum = np.cumsum(curr_prices)\n moving_avr = curr_prices.copy()\n moving_avr[:-self.future_scope] = (cum_sum[self.future_scope:] - cum_sum[:-self.future_scope]) / self.future_scope\n self.price_indices[capital_name]['f'] = np.zeros((curr_prices.shape[0],))\n self.price_indices[capital_name]['f'][:] = (moving_avr - curr_prices) / curr_prices\n\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n distances, indices = self.price_indices[capital_name]['X'].search(all_daily_changes.astype(np.float32), k=self.max_point_usage)\n closeDays = distances < self.relevance_threshold\n for row in recent_prices[capital_name]:\n proximity = distances[row_number][closeDays[row_number]]\n if proximity.shape[0] < self.trust_threshold:\n res = row[-1]\n else:\n daily_changes = all_daily_changes[row_number]\n currIndices = indices[row_number][closeDays[row_number]]\n fluctuations = np.vstack([self.price_indices[capital_name]['data'][(i-self.dimension+1):(i+1)] for i in currIndices])\n changes = self.price_indices[capital_name]['f'][currIndices]\n\n general_w = self.dimension/(2*self.dimension - self.minor_days)\n major_w = 1 - general_w\n\n ws = np.dot(fluctuations, daily_changes)*general_w + np.dot(fluctuations[:, self.minor_days:], daily_changes[self.minor_days:])*major_w\n ws /= (np.sum(ws)+self.epsilon)\n\n change_ratio = np.sum(ws * changes)\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update:\n newF = (true_values[capital_name][row_number] - row[-1]) / row[-1]\n self.price_indices[capital_name]['X'].add(daily_changes.reshape((1,-1)).astype(np.float32))\n self.price_indices[capital_name]['f'] = np.concatenate((self.price_indices[capital_name]['f'], [newF]))\n \n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n\n"
},
{
"alpha_fraction": 0.5337331295013428,
"alphanum_fraction": 0.5590954422950745,
"avg_line_length": 33.055320739746094,
"blob_id": "3057b125f83fa4f0e9e8a21767efa677fe31da73",
"content_id": "a00768b0f14a1d19c7701908e5e5b8ea906e1d44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8004,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 235,
"path": "/master.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nfrom dfply import *\nfrom pprint import pprint\nfrom os import listdir\nfrom os.path import isfile, join\nfrom time import time\nimport datetime\nimport matplotlib.pyplot as plt\nfrom src.utils import rolling_window, NumpyEncoder\nfrom src.GBL import GBLM\nfrom src.MLShepard import MLShepard\nfrom src.MondrianForest import MondrianForest\nfrom src.OARIMA import OARIMA\nfrom src.OSVR import OSVR\nfrom src.RandConLSTM import RandConLSTM\nfrom src.WHLR import WHLR\n\nimport sys\nsys.setrecursionlimit(sys.getrecursionlimit() * 100)\n\nTRAIN_PORTION = .8\n\nDIM = 200\n# DIM = 15\n\n# Uncomment the method and its parameters to include the corresponding result\nmethods = {\n 'GBLM': {\n 'class': GBLM,\n 'options': {\n 'dimension': DIM,\n 'epsilon': 5e-3,\n 'forgetting_rate': .59,\n 'p_learning_rate': .008,\n 's_learning_rate': .001,\n 'decay_rate': .25,\n 'oe_penalty': -1.5,\n 'ue_penalty': -1.5,\n 'reward': 1,\n 'epochs': 1\n }\n },\n # 'MLShepard': {\n # 'class': MLShepard,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM,\n # 'minor_days': 3,\n # 'trust_treshold': 4,\n # 'max_point_usage': 5,\n # 'avr_elemwise_dist': 0.04,\n # 'epsilon': 1e-10\n # }\n # },\n # 'OARIMA (ogd)': {\n # 'class': OARIMA,\n # 'options': {\n # 'dimension': DIM,\n # 'lrate': 1e-2,\n # 'epsilon': 1e-10,\n # 'method': 'ogd'\n # }\n # },\n # 'OARIMA (ons)': {\n # 'class': OARIMA,\n # 'options': {\n # 'dimension': DIM,\n # 'lrate': 1e-2,\n # 'epsilon': 1e-10,\n # 'method': 'ons'\n # }\n # },\n # 'OSVR': {\n # 'class': OSVR,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM,\n # 'C': 10,\n # 'kernelParam': 30,\n # 'epsilon': 1e-10\n # }\n # }, RUNNING TIME IS: [ 9.84e-002, -3.39e-003, 2.63e-005, 5.94e-007] @ [n, n**2, n**3, n**4]\n # 'LSTM': {\n # 'class': RandConLSTM,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM,\n # 'epochs': 2,\n # 'batch_size': 128,\n # 'num_layers': 1,\n # 'epsilon': 1e-10,\n # 'hidden_size': 100,\n # 'connectivity': 1\n # }\n # },\n # 'RandConLSTM': {\n # 'class': RandConLSTM,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM,\n # 'epochs': 2,\n # 'batch_size': 128,\n # 'num_layers': 1,\n # 'epsilon': 1e-10,\n # 'hidden_size': 100,\n # 'connectivity': .2\n # }\n # },\n # 'WHLR': {\n # 'class': WHLR,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM,\n # 'avr_elemwise_dist': 0.04,\n # 'learning_rate': 1e-2\n # }\n # },\n # 'MondrianForest': {\n # 'class': MondrianForest,\n # 'options': {\n # 'future_scope': 3,\n # 'dimension': DIM\n # }\n # },\n}\n\nprint('Preparing dataset...')\n# Here is the data directory. Each stock/crypto must be stored in a seperated csv file\ndataDir = 'data/stocks'\ndataFiles = {f: join(dataDir, f) for f in listdir(dataDir) if isfile(join(dataDir, f)) and f[-4:] == '.csv' and f not in ['stock_metadata.csv', 'NIFTY50_all.csv']}\nprint(list(dataFiles.keys()))\npriceIndices = {f: pd.read_csv(dataFiles[f]) for f in dataFiles}\n\n# dataFiles = {'dummy1': 1, 'dummy2': 1, 'dummy3': 1, 'dummy4': 1, 'dummy5': 1, 'dummy6': 1}\n# T_SIZE = 3000\n# priceIndices = {\n# f: pd.DataFrame({\n# 'Date': list(range(T_SIZE)),\n# 'Price': np.random.normal(\n# np.random.uniform(70, 300),\n# np.random.uniform(1, 1.5),\n# (T_SIZE,)\n# )\n# }) for f in dataFiles\n# }\n\nprices = {}\npricePartitions = {'train': {}, 'test': {}}\ntrueVals = {}\nintervalLength = float('Inf')\n# intervalLength = 0\n\nfor cryptoID in priceIndices:\n priceIndices[cryptoID].fillna(method='ffill')\n priceIndices[cryptoID][\"Date\"] = priceIndices[cryptoID][\"Date\"].astype(\"datetime64[ns]\")\n priceIndices[cryptoID] = priceIndices[cryptoID] >> arrange(X.Date)\n indexLength = priceIndices[cryptoID].shape[0]\n indexMean = mean(priceIndices[cryptoID][\"Price\"].values)\n prices[cryptoID] = priceIndices[cryptoID][\"Price\"].values + np.random.normal(loc=0, scale=indexMean/500, size=indexLength)\n intervalLength = min(indexLength, intervalLength)\n # intervalLength = min(2000, intervalLength)\n\ncutOff = int(intervalLength * TRAIN_PORTION)\n\nfor cryptoID in priceIndices:\n # if intervalLength != prices[cryptoID].shape[0]:\n # prices[cryptoID] = np.concatenate((\n # prices[cryptoID],\n # np.repeat(prices[cryptoID][-1], intervalLength - prices[cryptoID].shape[0])\n # ))\n \n pricePartitions['train'][cryptoID] = prices[cryptoID][:cutOff]\n pricePartitions['test'][cryptoID] = rolling_window(prices[cryptoID][cutOff:intervalLength], (DIM+1))[:-1]\n trueVals[cryptoID] = prices[cryptoID][cutOff:intervalLength][(DIM+1):]\n\n\nMSE = lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))\nPMSE = lambda truth, estimate, _prices: np.sqrt(np.mean(((truth-estimate)/truth)**2))\nPASE = lambda truth, estimate, _prices: np.mean((np.abs(truth-estimate)/truth))\nDMSE = lambda truth, estimate, prices: np.sqrt(np.mean((np.heaviside(-(truth - prices[:,-1])*(estimate - prices[:,-1]), [0]) * (truth-estimate)/truth)**2))\nwrongs = lambda truth, estimate, prices: np.sqrt(np.mean(np.heaviside(-(truth - prices[:,-1])*(estimate - prices[:,-1]), [0])))\n# DMSESD = lambda truth, estimate, prices: np.sqrt(np.std((np.heaviside(-(truth - prices[:,-1])*(estimate - prices[:,-1]), [0]) * (truth-estimate)/truth)**2))\n# DMSE = lambda truth, estimate, prices: print(*[truth, estimate, prices], sep='\\n')\n\n# methods['MondrianForest']['later_values'] = {'X': pricePartitions['test'], 'f': trueVals}\nimport json\nfor method_name in methods:\n print(\"==================== %s ====================\"%(method_name))\n method = methods[method_name]\n pClass, options = method['class'], method['options']\n model = pClass(**options)\n\n print('Fitting model...')\n startTime = time()\n model.fit({f: pricePartitions['train'][f] for f in dataFiles})\n fittedTime = time()\n\n print('Predicting values...')\n predStartTime = time()\n res = model.predict(pricePartitions['test'], update=True, true_values=trueVals,\n loss_functions={'MSE': MSE, 'PMSE': PMSE, 'PASE': PASE, 'DMSE': DMSE, 'wrongs': wrongs})\n finishedTime = time()\n\n pprint({coin: {l: np.mean(res[1][coin][l]) for l in res[1][coin]} for coin in res[1]})\n\n print('Plotting results...')\n indices = np.random.choice(list(dataFiles.keys()), 1, False)\n plt.plot(range((DIM+1)+cutOff, (DIM+1)+cutOff+res[0][indices[0]].shape[0]), res[0][indices[0]])\n plt.plot(range(prices[indices[0]].shape[0]), prices[indices[0]])\n\n learnT = (fittedTime - startTime) * 1000\n predT = (finishedTime - predStartTime) * 1000\n avrPredT = (finishedTime - predStartTime) / (intervalLength-cutOff) * 1000\n totalT = learnT + predT\n timingString = '''\n learning time:\\t%.1f ms\n predicting time:\\t%.1f ms\n prediction/test:\\t%.1f ms\n total time:\\t%.1fms\n '''%(learnT, predT, avrPredT, totalT)\n print(timingString)\n \n print('saving dump...')\n currentTime = datetime.datetime.now()\n dump_file = open('dumps/Results-%s-%s.dmp'%(method_name, currentTime), 'w')\n json.dump(res, dump_file, cls=NumpyEncoder)\n dump_file.close()\n dump_file = open('dumps/Timing-%s-%s.txt'%(method_name, currentTime), 'w')\n dump_file.write(timingString)\n dump_file.close()\n \n\n\nplt.show()\n\n"
},
{
"alpha_fraction": 0.6673346757888794,
"alphanum_fraction": 0.6773546934127808,
"avg_line_length": 34.64285659790039,
"blob_id": "4ffdf34c67677b3ebaed281e0ad2416aef8a0446",
"content_id": "dd853d22861fa1f666ae983360e16b1d9e3a0129",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 499,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 14,
"path": "/data/cryptos/prep.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import pandas as pd \nfrom dfply import X, arrange\n\ndef loadPriceIndex(dataFile):\n priceIndex = pd.read_csv(dataFile)\n priceIndex[\"Price\"] = priceIndex.apply(lambda x: x.Price if isinstance(x.Price, float) else float(x.Price.replace(',', '')), axis=1)\n priceIndex[\"Date\"] = priceIndex[\"Date\"].astype(\"datetime64[ns]\")\n priceIndex = priceIndex >> arrange(X.Date)\n \n return priceIndex\n\nfor i in range(1, 4):\n coins = loadPriceIndex('coin%d.csv'%i)\n coins.to_csv('coin%d.csv'%i)\n"
},
{
"alpha_fraction": 0.5123196840286255,
"alphanum_fraction": 0.5223482847213745,
"avg_line_length": 42.29105758666992,
"blob_id": "a67d2aa459def330357f6272672f5a75a791ea35",
"content_id": "4aeef0609c17c4022c6d40f10af8628f2c6acb19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 26624,
"license_type": "no_license",
"max_line_length": 393,
"num_lines": 615,
"path": "/src/OSVR.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "\"\"\"Implementation of Online Support Vector Regression (OSVR) as library for a class project in 16-831 \nStatistical Techniques in Robotics.\n\nRequires Python 3.5\n\nAuthor: Adam Werries, [email protected], 12/2015.\nAdapted from MATLAB code available at http://onlinesvr.altervista.org/\n\nParameters defined in main() below. C is the regularization parameter, essentially defining the limit on how close the learner must adhere to the dataset (smoothness). Epsilon is the acceptable error, and defines the width of what is sometimes called the \"SVR tube\". The kernel parameter is the scaling factor for comparing feature distance (this implementation uses a Radial Basis Function). \n\"\"\"\n\nimport sys\nimport numpy as np\nfrom .utils import rolling_window\nfrom time import time\n\ndef sign(x):\n \"\"\" Returns sign. Numpys sign function returns 0 instead of 1 for zero values. :( \"\"\"\n if x >= 0:\n return 1\n else:\n return -1\n\nclass OnlineSVR:\n def __init__(self, numFeatures, C, eps, kernelParam, bias = 0, debug = False):\n # Configurable Parameters\n self.numFeatures = numFeatures\n self.C = C\n self.eps = eps\n self.kernelParam = kernelParam\n self.bias = bias\n self.debug = debug\n \n print('SELF',self.C,self.eps,self.kernelParam, file=sys.stderr)\n # Algorithm initialization\n self.numSamplesTrained = 0\n self.weights = np.array([])\n \n # Samples X (features) and Y (truths)\n self.X = list()\n self.Y = list()\n # Working sets, contains indices pertaining to X and Y\n self.supportSetIndices = list()\n self.errorSetIndices = list()\n self.remainderSetIndices = list()\n self.R = np.matrix([])\n\n def findMinVariation(self, H, beta, gamma, i):\n \"\"\" Finds the variations of each sample to the new set.\n Lc1: distance of the new sample to the SupportSet\n Lc2: distance of the new sample to the ErrorSet\n Ls(i): distance of the support samples to the ErrorSet/RemainingSet\n Le(i): distance of the error samples to the SupportSet\n Lr(i): distance of the remaining samples to the SupportSet\n \"\"\"\n # Find direction q of the new sample\n q = -sign(H[i])\n # Compute variations\n Lc1 = self.findVarLc1(H, gamma, q, i)\n q = sign(Lc1)\n Lc2 = self.findVarLc2(H, q, i)\n Ls = self.findVarLs(H, beta, q)\n Le = self.findVarLe(H, gamma, q)\n Lr = self.findVarLr(H, gamma, q)\n # Check for duplicate minimum values, grab one with max gamma/beta, set others to inf\n # Support set\n if Ls.size > 1:\n minS = np.abs(Ls).min()\n results = np.array([k for k,val in enumerate(Ls) if np.abs(val)==minS])\n if len(results) > 1:\n betaIndex = beta[results+1].argmax()\n Ls[results] = q*np.inf\n Ls[results[betaIndex]] = q*minS\n # Error set\n if Le.size > 1:\n minE = np.abs(Le).min()\n results = np.array([k for k,val in enumerate(Le) if np.abs(val)==minE])\n if len(results) > 1:\n errorGamma = gamma[self.errorSetIndices]\n gammaIndex = errorGamma[results].argmax()\n Le[results] = q*np.inf\n Le[results[gammaIndex]] = q*minE\n # Remainder Set\n if Lr.size > 1:\n minR = np.abs(Lr).min()\n results = np.array([k for k,val in enumerate(Lr) if np.abs(val)==minR])\n if len(results) > 1:\n remGamma = gamma[self.remainderSetIndices]\n gammaIndex = remGamma[results].argmax()\n Lr[results] = q*np.inf\n Lr[results[gammaIndex]] = q*minR\n \n # Find minimum absolute variation of all, retain signs. Flag determines set-switching cases.\n minLsIndex = np.abs(Ls).argmin()\n minLeIndex = np.abs(Le).argmin()\n minLrIndex = np.abs(Lr).argmin()\n minIndices = [None, None, minLsIndex, minLeIndex, minLrIndex]\n minValues = np.array([Lc1, Lc2, Ls[minLsIndex], Le[minLeIndex], Lr[minLrIndex]])\n\n if np.abs(minValues).min() == np.inf:\n print('No weights to modify! Something is wrong.', file=sys.stderr)\n sys.exit()\n flag = np.abs(minValues).argmin()\n if self.debug:\n print('MinValues',minValues, file=sys.stderr)\n return minValues[flag], flag, minIndices[flag]\n\n def findVarLc1(self, H, gamma, q, i):\n # weird hacks below\n Lc1 = np.nan\n if gamma.size < 2:\n g = gamma\n else:\n g = gamma.item(i)\n # weird hacks above\n\n if g <= 0:\n Lc1 = np.array(q*np.inf)\n elif H[i] > self.eps and -self.C < self.weights[i] and self.weights[i] <= 0:\n Lc1 = (-H[i] + self.eps) / g\n elif H[i] < -self.eps and 0 <= self.weights[i] and self.weights[i] <= self.C:\n Lc1 = (-H[i] - self.eps) / g\n else:\n print('Something is weird.', file=sys.stderr)\n print('i',i, file=sys.stderr)\n print('q',q, file=sys.stderr)\n print('gamma',gamma, file=sys.stderr)\n print('g',g, file=sys.stderr)\n print('H[i]',H[i], file=sys.stderr)\n print('weights[i]',self.weights[i], file=sys.stderr)\n \n if np.isnan(Lc1):\n Lc1 = np.array(q*np.inf)\n return Lc1.item()\n\n def findVarLc2(self, H, q, i):\n if len(self.supportSetIndices) > 0:\n if q > 0:\n Lc2 = -self.weights[i] + self.C\n else:\n Lc2 = -self.weights[i] - self.C\n else:\n Lc2 = np.array(q*np.inf)\n if np.isnan(Lc2):\n Lc2 = np.array(q*np.inf)\n return Lc2\n\n def findVarLs(self, H, beta, q):\n if len(self.supportSetIndices) > 0 and len(beta) > 0:\n Ls = np.zeros([len(self.supportSetIndices),1])\n supportWeights = self.weights[self.supportSetIndices]\n supportH = H[self.supportSetIndices]\n for k in range(len(self.supportSetIndices)):\n if q*beta[k+1] == 0:\n Ls[k] = q*np.inf\n elif q*beta[k+1] > 0:\n if supportH[k] > 0:\n if supportWeights[k] < -self.C:\n Ls[k] = (-supportWeights[k] - self.C) / beta[k+1]\n elif supportWeights[k] <= 0:\n Ls[k] = -supportWeights[k] / beta[k+1]\n else:\n Ls[k] = q*np.inf\n else:\n if supportWeights[k] < 0:\n Ls[k] = -supportWeights[k] / beta[k+1]\n elif supportWeights[k] <= self.C:\n Ls[k] = (-supportWeights[k] + self.C) / beta[k+1]\n else:\n Ls[k] = q*np.inf\n else:\n if supportH[k] > 0:\n if supportWeights[k] > 0:\n Ls[k] = -supportWeights[k] / beta[k+1]\n elif supportWeights[k] >= -self.C:\n Ls[k] = (-supportWeights[k] - self.C) / beta[k+1]\n else:\n Ls[k] = q*np.inf\n else:\n if supportWeights[k] > self.C:\n Ls[k] = (-supportWeights[k] + self.C) / beta[k+1]\n elif supportWeights[k] >= self.C:\n Ls[k] = -supportWeights[k] / beta[k+1]\n else:\n Ls[k] = q*np.inf\n else:\n Ls = np.array([q*np.inf])\n\n # Correct for NaN\n Ls[np.isnan(Ls)] = q*np.inf\n if Ls.size > 1:\n Ls.shape = (len(Ls),1)\n # Check for broken signs\n for val in Ls:\n if sign(val) == -sign(q) and val != 0:\n print('Sign mismatch error in Ls! Exiting.', file=sys.stderr)\n sys.exit()\n # print('findVarLs',Ls, file=sys.stderr)\n return Ls\n \n def findVarLe(self, H, gamma, q):\n if len(self.errorSetIndices) > 0:\n Le = np.zeros([len(self.errorSetIndices),1])\n errorGamma = gamma[self.errorSetIndices]\n errorWeights = self.weights[self.errorSetIndices]\n errorH = H[self.errorSetIndices]\n for k in range(len(self.errorSetIndices)):\n if q*errorGamma[k] == 0:\n Le[k] = q*np.inf\n elif q*errorGamma[k] > 0:\n if errorWeights[k] > 0:\n if errorH[k] < -self.eps:\n Le[k] = (-errorH[k] - self.eps) / errorGamma[k]\n else:\n Le[k] = q*np.inf\n else:\n if errorH[k] < self.eps:\n Le[k] = (-errorH[k] + self.eps) / errorGamma[k]\n else:\n Le[k] = q*np.inf\n else:\n if errorWeights[k] > 0:\n if errorH[k] > -self.eps:\n Le[k] = (-errorH[k] - self.eps) / errorGamma[k]\n else:\n Le[k] = q*np.inf\n else:\n if errorH[k] > self.eps:\n Le[k] = (-errorH[k] + self.eps) / errorGamma[k]\n else:\n Le[k] = q*np.inf\n else:\n Le = np.array([q*np.inf])\n\n # Correct for NaN\n Le[np.isnan(Le)] = q*np.inf\n if Le.size > 1:\n Le.shape = (len(Le),1)\n # Check for broken signs\n for val in Le:\n if sign(val) == -sign(q) and val != 0:\n print('Sign mismatch error in Le! Exiting.', file=sys.stderr)\n sys.exit()\n # print('findVarLe',Le, file=sys.stderr)\n return Le\n\n def findVarLr(self, H, gamma, q):\n if len(self.remainderSetIndices) > 0:\n Lr = np.zeros([len(self.remainderSetIndices),1])\n remGamma = gamma[self.remainderSetIndices]\n remH = H[self.remainderSetIndices]\n for k in range(len(self.remainderSetIndices)):\n if q*remGamma[k] == 0:\n Lr[k] = q*np.inf\n elif q*remGamma[k] > 0:\n if remH[k] < -self.eps:\n Lr[k] = (-remH[k] - self.eps) / remGamma[k]\n elif remH[k] < self.eps:\n Lr[k] = (-remH[k] + self.eps) / remGamma[k]\n else:\n Lr[k] = q*np.inf\n else:\n if remH[k] > self.eps:\n Lr[k] = (-remH[k] + self.eps) / remGamma[k]\n elif remH[k] > -self.eps:\n Lr[k] = (-remH[k] - self.eps) / remGamma[k]\n else:\n Lr[k] = q*np.inf\n else:\n Lr = np.array([q*np.inf])\n\n # Correct for NaN\n Lr[np.isnan(Lr)] = q*np.inf\n if Lr.size > 1:\n Lr.shape = (len(Lr),1)\n # Check for broken signs\n for val in Lr:\n if sign(val) == -sign(q) and val != 0:\n print('Sign mismatch error in Lr! Exiting.', file=sys.stderr)\n sys.exit()\n # print('findVarLr',Lr, file=sys.stderr)\n return Lr\n\n def computeKernelOutput(self, set1, set2):\n \"\"\"Compute kernel output. Uses a radial basis function kernel.\"\"\"\n X1 = np.matrix(set1)\n X2 = np.matrix(set2).T\n # Euclidean distance calculation done properly\n [S,R] = X1.shape\n [R2,Q] = X2.shape\n X = np.zeros([S,Q])\n if Q < S:\n copies = np.zeros(S,dtype=int)\n for q in range(Q):\n if self.debug:\n print('X1',X1, file=sys.stderr)\n print('X2copies',X2.T[q+copies,:], file=sys.stderr)\n print('power',np.power(X1-X2.T[q+copies,:],2), file=sys.stderr)\n xsum = np.sum(np.power(X1-X2.T[q+copies,:],2),axis=1)\n xsum.shape = (xsum.size,)\n X[:,q] = xsum\n else:\n copies = np.zeros(Q,dtype=int)\n for i in range(S):\n X[i,:] = np.sum(np.power(X1.T[:,i+copies]-X2,2),axis=0)\n X = np.sqrt(X)\n y = np.matrix(np.exp(-self.kernelParam*X**2))\n if self.debug:\n print('distance',X, file=sys.stderr)\n print('kernelOutput',y, file=sys.stderr)\n return y\n \n def predict(self, newSampleX):\n X = np.array(self.X)\n newX = np.array(newSampleX)\n weights = np.array(self.weights)\n weights.shape = (weights.size,1)\n if self.numSamplesTrained > 0:\n y = self.computeKernelOutput(X, newX)\n return (weights.T @ y).T + self.bias\n else:\n return np.zeros_like(newX) + self.bias\n\n def computeMargin(self, newSampleX, newSampleY):\n fx = self.predict(newSampleX)\n newSampleY = np.array(newSampleY)\n newSampleY.shape = (newSampleY.size, 1)\n if self.debug:\n print('fx',fx, file=sys.stderr)\n print('newSampleY',newSampleY, file=sys.stderr)\n print('hx',fx-newSampleY, file=sys.stderr)\n return fx-newSampleY\n\n def computeBetaGamma(self,i):\n \"\"\"Returns beta and gamma arrays.\"\"\"\n # Compute beta vector\n X = np.array(self.X)\n Qsi = self.computeQ(X[self.supportSetIndices,:], X[i,:])\n if len(self.supportSetIndices) == 0 or self.R.size == 0:\n beta = np.array([])\n else:\n beta = -self.R @ np.append(np.matrix([1]),Qsi,axis=0)\n # Compute gamma vector\n Qxi = self.computeQ(X, X[i,:])\n Qxs = self.computeQ(X, X[self.supportSetIndices,:])\n if len(self.supportSetIndices) == 0 or Qxi.size == 0 or Qxs.size == 0 or beta.size == 0:\n gamma = np.array(np.ones_like(Qxi))\n else:\n gamma = Qxi + np.append(np.ones([self.numSamplesTrained,1]), Qxs, 1) @ beta\n\n # Correct for NaN\n beta[np.isnan(beta)] = 0\n gamma[np.isnan(gamma)] = 0\n if self.debug:\n print('R',self.R, file=sys.stderr)\n print('beta',beta, file=sys.stderr)\n print('gamma',gamma, file=sys.stderr)\n return beta, gamma\n\n def computeQ(self, set1, set2):\n set1 = np.matrix(set1)\n set2 = np.matrix(set2)\n Q = np.matrix(np.zeros([set1.shape[0],set2.shape[0]]))\n for i in range(set1.shape[0]):\n for j in range(set2.shape[0]):\n Q[i,j] = self.computeKernelOutput(set1[i,:],set2[j,:])\n return np.matrix(Q)\n \n def adjustSets(self, H, beta, gamma, i, flag, minIndex):\n print('Entered adjustSet logic with flag {0} and minIndex {1}.'.format(flag,minIndex), file=sys.stderr)\n if flag not in range(5):\n print('Received unexpected flag {0}, exiting.'.format(flag), file=sys.stderr)\n sys.exit()\n # add new sample to Support set\n if flag == 0:\n print('Adding new sample {0} to support set.'.format(i), file=sys.stderr)\n H[i] = np.sign(H[i])*self.eps\n self.supportSetIndices.append(i)\n self.R = self.addSampleToR(i,'SupportSet',beta,gamma)\n return H,True\n # add new sample to Error set\n elif flag == 1: \n print('Adding new sample {0} to error set.'.format(i), file=sys.stderr)\n self.weights[i] = np.sign(self.weights[i])*self.C\n self.errorSetIndices.append(i)\n return H,True\n # move sample from Support set to Error or Remainder set\n elif flag == 2: \n index = self.supportSetIndices[minIndex]\n weightsValue = self.weights[index]\n if np.abs(weightsValue) < np.abs(self.C - abs(weightsValue)):\n self.weights[index] = 0\n weightsValue = 0\n else:\n self.weights[index] = np.sign(weightsValue)*self.C\n weightsValue = self.weights[index]\n # Move from support to remainder set\n if weightsValue == 0:\n print('Moving sample {0} from support to remainder set.'.format(index), file=sys.stderr)\n self.remainderSetIndices.append(index)\n self.R = self.removeSampleFromR(minIndex)\n self.supportSetIndices.pop(minIndex)\n # move from support to error set\n elif np.abs(weightsValue) == self.C:\n print('Moving sample {0} from support to error set.'.format(index), file=sys.stderr)\n self.errorSetIndices.append(index)\n self.R = self.removeSampleFromR(minIndex)\n self.supportSetIndices.pop(minIndex)\n else:\n print('Issue with set swapping, flag 2.','weightsValue:',weightsValue, file=sys.stderr)\n sys.exit()\n # move sample from Error set to Support set\n elif flag == 3: \n index = self.errorSetIndices[minIndex]\n print('Moving sample {0} from error to support set.'.format(index), file=sys.stderr)\n H[index] = np.sign(H[index])*self.eps\n self.supportSetIndices.append(index)\n self.errorSetIndices.pop(minIndex)\n self.R = self.addSampleToR(index, 'ErrorSet', beta, gamma)\n # move sample from Remainder set to Support set\n elif flag == 4: \n index = self.remainderSetIndices[minIndex]\n print('Moving sample {0} from remainder to support set.'.format(index), file=sys.stderr)\n H[index] = np.sign(H[index])*self.eps\n self.supportSetIndices.append(index)\n self.remainderSetIndices.pop(minIndex)\n self.R = self.addSampleToR(index, 'RemainingSet', beta, gamma)\n return H, False\n\n def addSampleToR(self, sampleIndex, sampleOldSet, beta, gamma):\n print('Adding sample {0} to R matrix.'.format(sampleIndex), file=sys.stderr)\n X = np.array(self.X)\n sampleX = X[sampleIndex,:]\n sampleX.shape = (sampleX.size//self.numFeatures,self.numFeatures)\n # Add first element\n if self.R.shape[0] <= 1:\n Rnew = np.ones([2,2])\n Rnew[0,0] = -self.computeKernelOutput(sampleX,sampleX)\n Rnew[1,1] = 0\n # Other elements\n else:\n # recompute beta/gamma if from error/remaining set\n if sampleOldSet == 'ErrorSet' or sampleOldSet == 'RemainingSet':\n # beta, gamma = self.computeBetaGamma(sampleIndex)\n Qii = self.computeKernelOutput(sampleX, sampleX)\n Qsi = self.computeKernelOutput(X[self.supportSetIndices[0:-1],:], sampleX)\n beta = -self.R @ np.append(np.matrix([1]),Qsi,axis=0)\n beta[np.isnan(beta)] = 0\n beta.shape = (len(beta),1)\n gamma[sampleIndex] = Qii + np.append(1,Qsi.T)@beta\n gamma[np.isnan(gamma)] = 0\n gamma.shape = (len(gamma),1)\n # add a column and row of zeros onto right/bottom of R\n r,c = self.R.shape\n Rnew = np.append(self.R, np.zeros([r,1]), axis=1)\n Rnew = np.append(Rnew, np.zeros([1,c+1]), axis=0)\n # update R\n if gamma[sampleIndex] != 0:\n # Numpy so wonky! SO WONKY.\n beta1 = np.append(beta, [[1]], axis=0)\n Rnew = Rnew + 1/gamma[sampleIndex].item()*[email protected]\n if np.any(np.isnan(Rnew)):\n print('R has become inconsistent. Training failed at sampleIndex {0}'.forma, file=sys.stderrt(sampleIndex))\n sys.exit()\n return Rnew\n\n def removeSampleFromR(self, sampleIndex):\n print('Removing sample {0} from R matrix.'.format(sampleIndex), file=sys.stderr)\n sampleIndex += 1\n I = list(range(sampleIndex))\n I.extend(range(sampleIndex+1,self.R.shape[0]))\n I = np.array(I)\n I.shape = (1,I.size)\n if self.debug:\n print('I',I, file=sys.stderr)\n print('RII',self.R[I.T,I], file=sys.stderr)\n # Adjust R\n if self.R[sampleIndex,sampleIndex] != 0:\n Rnew = self.R[I.T,I] - (self.R[I.T,sampleIndex]*self.R[sampleIndex,I]) / self.R[sampleIndex,sampleIndex].item()\n else:\n Rnew = np.copy(self.R[I.T,I])\n # Check for bad things\n if np.any(np.isnan(Rnew)):\n print('R has become inconsistent. Training failed removing sampleIndex {0}'.forma, file=sys.stderrt(sampleIndex))\n sys.exit()\n if Rnew.size == 1:\n print('Time to annhilate R? R:',Rnew, file=sys.stderr)\n Rnew = np.matrix([])\n return Rnew\n\n def learn(self, newSampleX, newSampleY):\n self.numSamplesTrained += 1\n self.X.append(newSampleX)\n self.Y.append(newSampleY)\n self.weights = np.append(self.weights,0)\n i = self.numSamplesTrained - 1 # stupid off-by-one errors\n H = self.computeMargin(self.X, self.Y)\n\n # correctly classified sample, skip the rest of the algorithm!\n if (abs(H[i]) <= self.eps):\n print('Adding new sample {0} to remainder set, within eps.'.format(i), file=sys.stderr)\n if self.debug:\n print('weights',self.weights, file=sys.stderr)\n self.remainderSetIndices.append(i)\n return\n\n newSampleAdded = False\n iterations = 0\n while not newSampleAdded:\n # Ensure we're not looping infinitely\n iterations += 1\n if iterations > self.numSamplesTrained*100:\n print('Warning: we appear to be in an infinite loop.', file=sys.stderr)\n sys.exit()\n iterations = 0\n # Compute beta/gamma for constraint optimization\n beta, gamma = self.computeBetaGamma(i)\n # Find minimum variation and determine how we should shift samples between sets\n deltaC, flag, minIndex = self.findMinVariation(H, beta, gamma, i)\n # Update weights and bias based on variation\n if len(self.supportSetIndices) > 0 and len(beta)>0:\n self.weights[i] += deltaC\n delta = beta*deltaC\n self.bias += delta.item(0)\n # numpy is wonky...\n weightDelta = np.array(delta[1:])\n weightDelta.shape = (len(weightDelta),)\n self.weights[self.supportSetIndices] += weightDelta\n H += gamma*deltaC\n else:\n self.bias += deltaC\n H += deltaC\n # Adjust sets, moving samples between them according to flag\n H,newSampleAdded = self.adjustSets(H, beta, gamma, i, flag, minIndex)\n if self.debug:\n print('weights',self.weights, file=sys.stderr)\n\nclass OSVR:\n def __init__(\n self,\n future_scope=3,\n dimension=10,\n C=10,\n kernelParam=30,\n epsilon=1e-10\n ):\n self.future_scope = future_scope\n self.dimension = dimension\n self.C = C\n self.kernelParam = kernelParam\n self.epsilon = epsilon\n\n \n def fit(self, price_indices):\n self.models = {}\n for capital_name in price_indices:\n times = []\n curr_prices = price_indices[capital_name]\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n X = rolling_window(seq_price, self.dimension)\n padding = np.ones((self.dimension-1, self.dimension))\n X = np.vstack((padding, X))\n cum_sum = np.cumsum(curr_prices)\n moving_avr = curr_prices.copy()\n moving_avr[:-self.future_scope] = (cum_sum[self.future_scope:] - cum_sum[:-self.future_scope]) / self.future_scope\n f = np.zeros((curr_prices.shape[0],))\n f[:] = (moving_avr - curr_prices) / curr_prices\n self.models[capital_name] = OnlineSVR(numFeatures = X.shape[1], C = self.C, eps = self.epsilon, kernelParam = self.kernelParam, bias = 0, debug = False)\n for i in range(X.shape[0]):\n if i % 20 == 0:\n times.append((i,time()))\n if i % 40 == 0:\n # print('%%%%%%%%%%%%%%% Data point {0} %%%%%%%%%%%%%%%'.format(i))\n print(times)\n self.models[capital_name].learn(X[i,:], f[i])\n\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n for row in recent_prices[capital_name]:\n daily_changes = all_daily_changes[row_number]\n change_ratio = self.models[capital_name].predict(np.array([daily_changes]))[0]\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update:\n newF = (true_values[capital_name][row_number] - row[-1]) / row[-1]\n self.models[capital_name].learn(daily_changes)\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n"
},
{
"alpha_fraction": 0.6451612710952759,
"alphanum_fraction": 0.6543778777122498,
"avg_line_length": 32.38461685180664,
"blob_id": "8082109d353d20f50cc9df7f9dca075fe0a9f5cf",
"content_id": "24af67cc013c1573e06b4cfc6ba13de5d3807af2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 434,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 13,
"path": "/src/utils.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport json\n\ndef rolling_window(a, window):\n shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n strides = a.strides + (a.strides[-1],)\n return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n"
},
{
"alpha_fraction": 0.5613316297531128,
"alphanum_fraction": 0.5715749263763428,
"avg_line_length": 47.79999923706055,
"blob_id": "6f864a1c19f2cdc85998b90e57b3c038c311625c",
"content_id": "6435d37f9a51ba062a145dd87d9cd94df03a0eb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3905,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 80,
"path": "/src/WHLR.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom sklearn.linear_model import LinearRegression as LR\nfrom sklearn.kernel_approximation import RBFSampler\nfrom .utils import rolling_window\n\nclass WHLR:\n def __init__(\n self,\n future_scope=3,\n dimension=10,\n avr_elemwise_dist=0.04,\n learning_rate=1e-2\n ):\n self.future_scope = future_scope\n self.dimension = dimension\n self.avr_elemwise_dist = avr_elemwise_dist\n self.learning_rate = learning_rate\n\n self.gamma = (.33 / (dimension**.5 * avr_elemwise_dist))**2\n \n def fit(self, price_indices):\n self.models = {}\n for capital_name in price_indices:\n self.models[capital_name] = {'rbf': RBFSampler(gamma=self.gamma), 'lr': LR()}\n curr_prices = price_indices[capital_name]\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n X = rolling_window(seq_price, self.dimension)\n padding = np.ones((self.dimension-1, self.dimension)) #np.random.normal(0, self.epsilon, (self.dimension-1, self.dimension))\n X = np.vstack((padding, X))\n cum_sum = np.cumsum(curr_prices)\n moving_avr = curr_prices.copy()\n moving_avr[:-self.future_scope] = (cum_sum[self.future_scope:] - cum_sum[:-self.future_scope]) / self.future_scope\n f = np.zeros((curr_prices.shape[0],))\n f[:] = (moving_avr - curr_prices) / curr_prices\n X = self.models[capital_name]['rbf'].fit_transform(X)\n self.models[capital_name]['lr'].fit(X, f)\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n for row in recent_prices[capital_name]:\n daily_changes = all_daily_changes[row_number]\n daily_changes = self.models[capital_name]['rbf'].transform([daily_changes])[0]\n change_ratio = self.models[capital_name]['lr'].predict([daily_changes])[0]\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update:\n newF = (true_values[capital_name][row_number] - row[-1]) / row[-1]\n augmentedX = np.concatenate([[1], daily_changes])\n w = np.concatenate([[self.models[capital_name]['lr'].intercept_], self.models[capital_name]['lr'].coef_])\n w = w - self.learning_rate * (np.dot(w, augmentedX) - newF) * augmentedX\n self.models[capital_name]['lr'].intercept_ = w[0]\n self.models[capital_name]['lr'].coef_ = w[1:]\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n\n"
},
{
"alpha_fraction": 0.5104909539222717,
"alphanum_fraction": 0.5224506855010986,
"avg_line_length": 46.650001525878906,
"blob_id": "4a1e8f77f20a6d9033bed56f89447adebb222ba6",
"content_id": "2f8d72f2294a54357e5027e449b3c05133cc9f2f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4766,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 100,
"path": "/src/OARIMA.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pmdarima as pm\nfrom math import sqrt\nfrom .utils import rolling_window\n\nclass OARIMA:\n def __init__(\n self,\n dimension=10,\n lrate=1e-2,\n epsilon=1e-10,\n method='ogd'\n ):\n self.dimension = dimension\n self.lrate = lrate\n self.epsilon = epsilon\n self.method = method\n \n def fit(self, price_indices):\n self.model = {}\n self.order = None\n with_intercept = None\n for capital_name in price_indices:\n self.model[capital_name] = {'ma': None, 'data': None, 'size': 0}\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n if self.order is None:\n model = pm.auto_arima(seq_price, seasonal=False, start_p=0, max_p=0, start_q=3, max_q=50, trace=True)\n params = model.get_params()\n self.order, _with_intercept = params['order'], params['with_intercept']\n if self.order[2] < 4:\n self.order = (self.order[0], self.order[1], 4)\n model = pm.ARIMA(order=self.order, with_intercept=False)\n model.fit(seq_price)\n \n self.model[capital_name]['ma'] = model.maparams()\n self.model[capital_name]['data'] = seq_price[-(self.order[1] + self.order[2]):]\n self.model[capital_name]['size'] = seq_price.shape[0] - (self.order[1] + self.order[2])\n \n pass\n\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n A_trans = np.identity(self.order[2]) * self.epsilon\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n for row in recent_prices[capital_name]:\n diffed_values = self.model[capital_name]['data']\n if self.order[1]:\n diffed_sum = diffed_values[-1]\n else:\n diffed_sum = 0\n for _ in range(self.order[1]):\n diffed_values = diffed_values[1:] - diffed_values[:-1]\n diffed_sum += diffed_values[-1]\n estimate = (self.model[capital_name]['ma'] @ diffed_values)\n change_ratio = diffed_sum + estimate\n res = (change_ratio + 1) * row[-1]\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n self.model[capital_name]['data'] = np.concatenate((self.model[capital_name]['data'][1:], [change_ratio]))\n self.model[capital_name]['size'] += 1\n\n if update:\n exact = (true_values[capital_name][row_number] - row[-1])/row[-1]\n self.model[capital_name]['data'][-1] = exact\n diff = estimate - exact\n if self.method == 'ogd':\n s = self.model[capital_name]['size']\n self.model[capital_name]['ma'] = self.model[capital_name]['ma'] - diffed_sum*2*diff/sqrt(row_number+s+1)*self.lrate\n elif self.method == 'ons':\n grad = (2*diffed_values*diff).reshape((1, -1))\n # print(A_trans, A_trans.shape)\n # print(grad, grad.shape)\n A_trans = A_trans - A_trans @ grad.T @ grad @ A_trans/(1 + grad @ A_trans @ grad.T)\n self.model[capital_name]['ma'] = self.model[capital_name]['ma'] - self.lrate * grad @ A_trans\n self.model[capital_name]['ma'] = self.model[capital_name]['ma'].reshape((-1,))\n self.model[capital_name]['ma'] = self.model[capital_name]['ma'] / np.sum(self.model[capital_name]['ma'])\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n\n"
},
{
"alpha_fraction": 0.5295708775520325,
"alphanum_fraction": 0.5416205525398254,
"avg_line_length": 44.674156188964844,
"blob_id": "5c1019797dcf7f1abf8a43a518d21930738827c2",
"content_id": "5767ecda7b7b89af55a43e20e43f2d8bb91d6d46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8133,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 178,
"path": "/src/RandConLSTM.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport math\nimport torch\nfrom torch import nn, optim\n# from torch.autograd import Variable\nfrom torch.nn.utils import clip_grad_norm\nfrom collections import OrderedDict\nimport pandas as pd \n\nfrom .RCLSTM import rclstm\nfrom .RCLSTM.rclstm import RNN\n\nfrom .utils import rolling_window\n\nloss_fn = nn.MSELoss()\n\ndef compute_loss_accuracy(model, data, label):\n hx = None\n _, (h_n, _) = model[0](input_=data, hx=hx)\n logits = model[1](h_n[-1])\n loss = torch.sqrt(loss_fn(input=logits, target=label))\n return loss, logits\n\n#learning rate decay\ndef exp_lr_scheduler(optimizer, epoch, init_lr=1e-2, lr_decay_epoch=3):\n lr = init_lr * (0.1 ** (epoch // lr_decay_epoch))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return optimizer\n\nclass RandConLSTM:\n def __init__(\n self,\n future_scope=3,\n dimension=10,\n epochs=2,\n batch_size=128,\n num_layers=1,\n epsilon=1e-10,\n hidden_size=100,\n connectivity=.2\n ):\n self.future_scope = future_scope\n self.dimension = dimension\n self.epochs = epochs\n self.batch_size = batch_size\n self.num_layers = num_layers\n self.epsilon = epsilon\n self.hidden_size = hidden_size\n self.connectivity = connectivity\n \n def fit(self, price_indices):\n self.models = {}\n for capital_name in price_indices:\n curr_prices = price_indices[capital_name]\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n X = rolling_window(seq_price, self.dimension)\n padding = np.ones((self.dimension-1, self.dimension)) #np.random.normal(0, self.epsilon, (self.dimension-1, self.dimension))\n X = np.vstack((padding, X))\n cum_sum = np.cumsum(curr_prices)\n moving_avr = curr_prices.copy()\n moving_avr[:-self.future_scope] = (cum_sum[self.future_scope:] - cum_sum[:-self.future_scope]) / self.future_scope\n f = np.zeros((curr_prices.shape[0],))\n f[:] = (moving_avr - curr_prices) / curr_prices\n rnn_model = RNN(device='cpu', cell_class='rclstm', input_size=1,\n hidden_size=self.hidden_size, connectivity=self.connectivity, \n num_layers=self.num_layers, batch_first=True, dropout=1)\n\n fc2 = nn.Linear(in_features=self.hidden_size, out_features=1)\n self.models[capital_name] = nn.Sequential(OrderedDict([\n ('rnn', rnn_model),\n ('fc2', fc2),\n ]))\n\n # if use_gpu:\n # model.cuda()\n self.models[capital_name].to('cpu')\n\n optim_method = optim.Adam(params=self.models[capital_name].parameters())\n\n iter_cnt = 0\n num_batch = int(math.ceil(len(X) // self.batch_size))\n while iter_cnt < self.epochs:\n optimizer = exp_lr_scheduler(optim_method, iter_cnt, init_lr=0.01, lr_decay_epoch=3)\n for i in range(num_batch):\n low_index = self.batch_size*i\n high_index = self.batch_size*(i+1)\n if low_index <= len(X)-self.batch_size:\n batch_inputs = X[low_index:high_index].reshape(self.batch_size, self.dimension, 1).astype(np.float32)\n batch_targets = f[low_index:high_index].reshape((self.batch_size, 1)).astype(np.float32)\n else:\n batch_inputs = X[low_index:].astype(float)\n batch_targets = f[low_index:].astype(float)\n\n batch_inputs = torch.from_numpy(batch_inputs).to('cpu')\n batch_targets = torch.from_numpy(batch_targets).to('cpu')\n \n # if use_gpu:\n # batch_inputs = batch_inputs.cuda()\n # batch_targets = batch_targets.cuda()\n\n self.models[capital_name].train(True)\n self.models[capital_name].zero_grad()\n train_loss, _logits = compute_loss_accuracy(self.models[capital_name], data=batch_inputs, label=batch_targets)\n train_loss.backward()\n optimizer.step()\n \n if i % 100 == 0:\n print('the %dth iter, the %d/%dth batch, train loss is %.4f' % (iter_cnt, i, num_batch, train_loss.item()))\n\n # save model\n # save_path = '{}/{}'.format(save_dir, int(round(connectivity/.01)))\n # if os.path.exists(save_path):\n # torch.save(model, os.path.join(save_path, str(iter_cnt)+'.pt'))\n # else:\n # os.makedirs(save_path)\n # torch.save(model, os.path.join(save_path, str(iter_cnt)+'.pt'))\n iter_cnt += 1\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n for row in recent_prices[capital_name]:\n daily_changes = all_daily_changes[row_number]\n self.models[capital_name].train(False)\n tdc = daily_changes.reshape((1,-1,1)).astype(np.float32)\n torch_daily_changes = torch.from_numpy(tdc).to('cpu')\n lstm_out = self.models[capital_name][0](torch_daily_changes)[0]\n change_ratio = self.models[capital_name][1](lstm_out)[0].detach().numpy().reshape((-1,))[0]\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update:\n self.models[capital_name].train(True)\n optim_method = optim.Adam(params=self.models[capital_name].parameters())\n newF = (true_values[capital_name][row_number] - row[-1]) / row[-1]\n\n iter_cnt = 0\n while iter_cnt < self.epochs:\n optimizer = exp_lr_scheduler(optim_method, iter_cnt, init_lr=0.01, lr_decay_epoch=3)\n batch_inputs = daily_changes.reshape((1, -1, 1)).astype(np.float32)\n batch_targets = np.array([newF]).reshape((1, 1)).astype(np.float32)\n batch_inputs = torch.from_numpy(batch_inputs).to('cpu')\n batch_targets = torch.from_numpy(batch_targets).to('cpu')\n \n self.models[capital_name].train(True)\n self.models[capital_name].zero_grad()\n train_loss, _logits = compute_loss_accuracy(self.models[capital_name], data=batch_inputs, label=batch_targets)\n train_loss.backward()\n optimizer.step()\n\n iter_cnt += 1\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n\n\n\n"
},
{
"alpha_fraction": 0.5707915425300598,
"alphanum_fraction": 0.5741360187530518,
"avg_line_length": 35.95833206176758,
"blob_id": "babaaf307bf386788aa98e47f2fc8a6ef149d6e9",
"content_id": "378311919815581d31e34e4d61960ea2db319d52",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 897,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 24,
"path": "/results/dumps.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "from os import listdir\nfrom os.path import join, isfile\nimport json\nimport numpy as np\n\ndataDir = '../dumps'\ndataFiles = {f: join(dataDir, f) for f in listdir(dataDir) if isfile(join(dataDir, f)) and f[-4:] == '.dmp'}\n# print(list(dataFiles.keys()))\n\nfor f in dataFiles:\n dump = open(dataFiles[f], 'r')\n res = json.load(dump)\n print('============ %s ============'%(f))\n loss = res[1]\n loss_funcs = list(loss[list(loss.keys())[0]].keys())\n loss_vals = {loss_func: [] for loss_func in loss_funcs}\n for loss_func in loss_funcs:\n for capital in loss:\n if not np.isnan(loss[capital][loss_func]):\n loss_vals[loss_func].append(loss[capital][loss_func])\n print('''loss: %s\n (mean, sd, n#)\n (%f, %f, %d)'''%(loss_func, np.mean(loss_vals[loss_func]), np.std(loss_vals[loss_func]), len(loss_vals[loss_func])))\n print()\n \n \n"
},
{
"alpha_fraction": 0.6080626845359802,
"alphanum_fraction": 0.6349384188652039,
"avg_line_length": 26.90625,
"blob_id": "41febab745ffb120cd349a8c3b093c869231b46e",
"content_id": "1aa94b75d87d3ea38d423c5fc51aeb8ee60d9f4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 893,
"license_type": "no_license",
"max_line_length": 190,
"num_lines": 32,
"path": "/data/RTcryptos/AAA_delta.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import pandas as pd \nfrom dfply import X, arrange, mutate, drop\nimport numpy as np\n\nfrom os import listdir\nfrom os.path import isfile\n\ncsvFiles = [f for f in listdir('.') if isfile(f) and f[-4:] == '.csv']\n\ndef loadPriceIndex(dataFile):\n priceIndex = pd.read_csv(dataFile) >> arrange(X.Date)\n dates = priceIndex['Date'].values\n deltas = (dates[1:] - dates[:-1])/1000\n \n return deltas\n\n\nallDeltas = []\n\nfor csvFile in csvFiles:\n print(csvFile, end=':\\t\\t')\n try:\n deltas = loadPriceIndex(csvFile)\n pIndex = (np.min(deltas), np.max(deltas), np.median(deltas), np.mean(deltas), np.std(deltas), (np.sum(deltas) / 3600 / 24), '%d,%d'%(deltas.shape[0] // 1000, deltas.shape[0] % 1000))\n print(pIndex)\n allDeltas.append(np.log(deltas + 1))\n except:\n print('Failed')\n \nimport matplotlib.pyplot as plt\nplt.boxplot(allDeltas)\nplt.show()\n"
},
{
"alpha_fraction": 0.5581272840499878,
"alphanum_fraction": 0.5661230683326721,
"avg_line_length": 49.2910041809082,
"blob_id": "5fc9f795706a359b2c964700f8968ce6eeba6f3e",
"content_id": "6f23acdea5632009d0c5f7d585d7668e3830cc65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9505,
"license_type": "no_license",
"max_line_length": 259,
"num_lines": 189,
"path": "/src/MondrianForest.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport math\nfrom .MF.mondrianforest import MondrianForest as MondrianForest_Main\nfrom .MF.mondrianforest_utils import precompute_minimal\nfrom .utils import rolling_window\n\ndef prepareData(X, f, settings, single=False):\n data = {\n 'x_train': X,\n 'y_train': f,\n 'n_dim': X.shape[1],\n 'n_train': f.shape[0],\n 'x_test': None,\n 'y_test': None,\n 'n_test': 0,\n 'is_sparse': False\n }\n # ------ beginning of hack ----------\n is_mondrianforest = True\n n_minibatches = 1 if single else settings.n_minibatches\n if is_mondrianforest:\n # creates data['train_ids_partition']['current'] and data['train_ids_partition']['cumulative'] \n # where current[idx] contains train_ids in minibatch \"idx\", cumulative contains train_ids in all\n # minibatches from 0 till idx ... can be used in gen_train_ids_mf or here (see below for idx > -1)\n data['train_ids_partition'] = {'current': {}, 'cumulative': {}}\n train_ids = np.arange(data['n_train'])\n try:\n draw_mondrian = settings.draw_mondrian\n except AttributeError:\n draw_mondrian = False\n # if is_mondrianforest and (not draw_mondrian):\n # reset_random_seed(settings)\n # np.random.shuffle(train_ids)\n # NOTE: shuffle should be the first call after resetting random seed\n # all experiments would NOT use the same dataset otherwise\n train_ids_cumulative = np.arange(0)\n n_points_per_minibatch = data['n_train'] / n_minibatches\n assert n_points_per_minibatch > 0\n idx_base = np.arange(n_points_per_minibatch)\n for idx_minibatch in range(n_minibatches):\n is_last_minibatch = (idx_minibatch == n_minibatches - 1)\n idx_tmp = idx_base + idx_minibatch * n_points_per_minibatch\n if is_last_minibatch:\n # including the last (data[n_train'] % settings.n_minibatches) indices along with indices in idx_tmp\n idx_tmp = np.arange(idx_minibatch * n_points_per_minibatch, data['n_train'])\n idx_tmp = list(map(int, idx_tmp))\n train_ids_current = train_ids[idx_tmp]\n # print idx_minibatch, train_ids_current\n data['train_ids_partition']['current'][idx_minibatch] = train_ids_current\n train_ids_cumulative = np.append(train_ids_cumulative, train_ids_current)\n data['train_ids_partition']['cumulative'][idx_minibatch] = train_ids_cumulative\n return data\n\nclass Settings:\n def __init__(self, **entries):\n self.__dict__.update(entries)\n\nclass MondrianForest:\n def __init__(\n self,\n future_scope=3,\n dimension=10,\n later_values=None\n ):\n self.future_scope = future_scope\n self.dimension = dimension\n self.settings = Settings(**{\n \"bagging\": 0,\n \"budget\": -1,\n \"budget_to_use\": float('inf'),\n \"data_path\": \"../../process_data/\",\n \"dataset\": \"msg-4dim\",\n \"debug\": 0,\n \"discount_factor\": 10,\n \"draw_mondrian\": 0,\n \"init_id\": 1,\n \"min_samples_split\": 2,\n \"batch_size\": 128,\n \"n_minibatches\": 10,\n \"n_mondrians\": 10,\n \"name_metric\": \"mse\",\n \"normalize_features\": 0,\n \"op_dir\": \"results\",\n \"optype\": \"real\",\n \"perf_dataset_keys\": [\"train\", \"test\"],\n \"perf_metrics_keys\": [\"log_prob\", \"mse\"],\n \"perf_store_keys\": [\"pred_mean\", \"pred_prob\"],\n \"save\": 0,\n \"select_features\": 0,\n \"smooth_hierarchically\": 1,\n \"store_every\": 0,\n \"tag\": \"\",\n \"verbose\": 1,\n })\n if later_values is not None:\n self.laterX = later_values['X']\n self.laterF = later_values['f']\n else:\n self.laterX = None\n self.laterF = None\n \n def fit(self, price_indices):\n self.models = {}\n self.aux_data = {}\n for capital_name in price_indices:\n trainPortion = 1\n curr_prices = price_indices[capital_name]\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n X = rolling_window(seq_price, self.dimension)\n padding = np.ones((self.dimension-1, self.dimension))\n X = np.vstack((padding, X))\n cum_sum = np.cumsum(curr_prices)\n moving_avr = curr_prices.copy()\n moving_avr[:-self.future_scope] = (cum_sum[self.future_scope:] - cum_sum[:-self.future_scope]) / self.future_scope\n f = np.zeros((curr_prices.shape[0],))\n f[:] = (moving_avr - curr_prices) / curr_prices\n ##### if update is expected\n if self.laterX is not None:\n trainSize = price_indices[capital_name].shape[0]\n testSize = self.laterX[capital_name].shape[0]\n trainPortion = trainSize / (trainSize + testSize)\n all_daily_changes = (self.laterX[capital_name][:,1:] - self.laterX[capital_name][:,:-1]) / self.laterX[capital_name][:,:-1]\n X = np.vstack([X, all_daily_changes])\n f = np.concatenate([f, self.laterF[capital_name]])\n self.settings.n_minibatches = math.ceil(f.shape[0] / self.settings.batch_size)\n data = prepareData(X, f, self.settings)\n param, cache = precompute_minimal(data, self.settings)\n self.aux_data[capital_name] = {'param': param, 'cache': cache, 'untrainedBatch': self.settings.n_minibatches, 'data': data}\n self.models[capital_name] = MondrianForest_Main(self.settings, data)\n for idx_minibatch in range(self.settings.n_minibatches):\n if idx_minibatch/self.settings.n_minibatches > trainPortion:\n self.aux_data[capital_name]['untrainedBatch'] = idx_minibatch\n break\n\n if idx_minibatch % 10 == 0:\n print('========== %d/%d minibaches =========='%(idx_minibatch, self.settings.n_minibatches))\n train_ids_current_minibatch = data['train_ids_partition']['current'][idx_minibatch]\n if idx_minibatch == 0:\n self.models[capital_name].fit(data, train_ids_current_minibatch, self.settings, param, cache)\n else:\n self.models[capital_name].partial_fit(data, train_ids_current_minibatch, self.settings, param, cache)\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n ZERO_ARR = np.array([0])\n weights_prediction = np.ones(self.settings.n_mondrians) * 1.0 / self.settings.n_mondrians\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n for row in recent_prices[capital_name]:\n daily_changes = all_daily_changes[row_number]\n change_ratio = self.models[capital_name].evaluate_predictions({}, daily_changes.reshape((1,-1)), ZERO_ARR, self.settings, self.aux_data[capital_name]['param'], weights_prediction, False)['pred_mean'][0]\n change_ratio = self.models[capital_name].evaluate_predictions({}, daily_changes.reshape((1,-1)), np.array([true_values[capital_name][row_number]]), self.settings, self.aux_data[capital_name]['param'], weights_prediction, False)['pred_mean'][0]\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update and ((row_number + 1) % self.settings.batch_size == 0):\n idx_minibatch = self.aux_data[capital_name]['untrainedBatch']\n try:\n train_ids_current_minibatch = self.aux_data[capital_name]['data']['train_ids_partition']['current'][idx_minibatch]\n self.models[capital_name].partial_fit(self.aux_data[capital_name]['data'], train_ids_current_minibatch, self.settings, self.aux_data[capital_name]['param'], self.aux_data[capital_name]['cache'])\n self.aux_data[capital_name]['untrainedBatch'] += 1\n except:\n # idx is not aligned\n pass\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n"
},
{
"alpha_fraction": 0.55275958776474,
"alphanum_fraction": 0.5658701658248901,
"avg_line_length": 48.7684211730957,
"blob_id": "764279203705e8dd96baeed3102d0ae054b12aaa",
"content_id": "e12b259e843edd64fd30f252bb1fa8b78fecf1bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4729,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 95,
"path": "/src/GBL.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom .utils import rolling_window\n\n# parameters (except epsilon) offered by https://link.springer.com/article/10.1007/s00521-016-2314-8\nclass GBLM:\n def __init__(\n self,\n dimension=10,\n epsilon=5e-3,\n forgetting_rate=.59,\n p_learning_rate=.008,\n s_learning_rate=.001,\n decay_rate=.25,\n oe_penalty=-1.5,\n ue_penalty=-1.5,\n reward=1,\n epochs=1\n ):\n self.dimension = dimension\n self.epsilon = epsilon\n self.forgetting_rate = forgetting_rate\n self.p_learning_rate = p_learning_rate\n self.s_learning_rate = s_learning_rate\n self.decay_rate = decay_rate\n self.oe_penalty = oe_penalty\n self.ue_penalty = ue_penalty\n self.reward = reward\n self.epochs = epochs\n \n def fit(self, price_indices):\n self.models = {}\n initial_weight = np.random.uniform(-1, 1, self.dimension)\n initial_weight /= np.sum(initial_weight)\n for capital_name in price_indices:\n self.models[capital_name] = {'w': initial_weight, 'rlF': 0, 'rlR': 0}\n seq_price = price_indices[capital_name].copy()\n seq_price[1:] = (seq_price[1:] - seq_price[:-1]) / seq_price[:-1]\n seq_price[0] = 0\n X = rolling_window(seq_price, self.dimension)\n f = seq_price[self.dimension:]\n for _ in range(self.epochs):\n for x, y in zip(X, f):\n w = self.models[capital_name]['w']\n yHat = np.dot(w, x)\n self.models[capital_name]['rlF'] = self.models[capital_name]['rlF']*self.decay_rate + yHat\n diff = yHat - y\n reward = self.oe_penalty if diff > self.epsilon else self.ue_penalty if diff < -self.epsilon else self.reward\n self.models[capital_name]['rlR'] = self.models[capital_name]['rlR']*self.decay_rate + reward\n self.models[capital_name]['w'] = self.forgetting_rate*w + self.p_learning_rate*x*self.models[capital_name]['rlF']*self.models[capital_name]['rlR']\n self.models[capital_name]['w'] = self.models[capital_name]['w'] / np.sum(self.models[capital_name]['w'])\n \n\n\n def predict(self, recent_prices, update=True, true_values=None, loss_functions=None):\n if true_values is None and update:\n raise Exception('True values must be provided if update parameter is set to true')\n\n if loss_functions is None:\n loss_functions = {'MSE': lambda truth, estimate, _prices: np.sqrt(np.mean((truth-estimate)**2))}\n \n loss_results = {}\n result = {}\n for capital_name in recent_prices:\n result[capital_name] = np.array([])\n row_number = 0\n\n if recent_prices[capital_name].shape[1] != self.dimension+1:\n raise Exception('The matrix to be predicted must be of the shape (*, dimension+1)')\n\n all_daily_changes = (recent_prices[capital_name][:,1:] - recent_prices[capital_name][:,:-1]) / recent_prices[capital_name][:,:-1]\n for row in recent_prices[capital_name]:\n w = self.models[capital_name]['w']\n daily_changes = all_daily_changes[row_number]\n change_ratio = np.dot(w, daily_changes)\n res = (change_ratio + 1) * row[-1]\n\n result[capital_name] = np.concatenate((result[capital_name], [res]))\n\n if update:\n newF = (true_values[capital_name][row_number] - row[-1]) / row[-1]\n self.models[capital_name]['rlF'] = self.models[capital_name]['rlF']*self.decay_rate + change_ratio\n diff = change_ratio - newF\n reward = self.oe_penalty if diff > self.epsilon else self.ue_penalty if diff < -self.epsilon else self.reward\n self.models[capital_name]['rlR'] = self.models[capital_name]['rlR']*self.decay_rate + reward\n self.models[capital_name]['w'] = self.forgetting_rate*w + self.s_learning_rate*daily_changes*self.models[capital_name]['rlF']*self.models[capital_name]['rlR']\n self.models[capital_name]['w'] = self.models[capital_name]['w'] / np.sum(self.models[capital_name]['w'])\n \n row_number += 1\n \n if true_values is not None:\n loss_results[capital_name] = {}\n for loss_name in loss_functions:\n loss_results[capital_name][loss_name] = loss_functions[loss_name](true_values[capital_name], result[capital_name], recent_prices[capital_name])\n \n return result, loss_results\n\n"
},
{
"alpha_fraction": 0.6438356041908264,
"alphanum_fraction": 0.6449771523475647,
"avg_line_length": 27.25806427001953,
"blob_id": "f3cb4e7e4aaa4e049576f92329402d741bd8bccc",
"content_id": "fb74e75766e92b90a1e80c9e585c6346d10990c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 876,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 31,
"path": "/data/RTcryptos/AAA_prep.py",
"repo_name": "rasakereh/time-series-predictors",
"src_encoding": "UTF-8",
"text": "import pandas as pd \nfrom dfply import X, arrange, mutate, drop\n\nfrom os import listdir\nfrom os.path import isfile\n\ncsvFiles = [f for f in listdir('.') if isfile(f) and f[-4:] == '.csv']\n\nheader = 'id|Price|volume|timestamp|buy\\n'\n\ndef loadPriceIndex(dataFile):\n original = open(dataFile, 'r')\n data = header + original.read()\n original.close()\n modified = open(dataFile, 'w')\n modified.write(data)\n modified.close()\n priceIndex = pd.read_csv(dataFile, sep='|')\n # priceIndex['Date'] = pd.to_datetime(priceIndex['Date'])\n priceIndex = priceIndex >> mutate(Date = priceIndex.timestamp) >> drop(X.timestamp) >> arrange(X.Date)\n \n return priceIndex\n\nfor csvFile in csvFiles:\n print(csvFile, end=':\\t\\t')\n try:\n pIndex = loadPriceIndex(csvFile)\n pIndex.to_csv(csvFile)\n print('Done')\n except:\n print('Failed')\n"
}
] | 13 |
ssd-73/Cellular-Automata-based-on-Stock-Market | https://github.com/ssd-73/Cellular-Automata-based-on-Stock-Market | a14894d2fcae29537783f0ced629cef2d06cb9f6 | 9c0881f9f31ed50b6b90fc8356b04e959d49c785 | d133b7250cfb1d7a30903a9e12f7a917dc17d56b | refs/heads/master | 2022-12-08T10:05:16.785492 | 2020-08-17T01:28:46 | 2020-08-17T01:28:46 | 286,967,647 | 3 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.7621878981590271,
"alphanum_fraction": 0.779231071472168,
"avg_line_length": 119.14286041259766,
"blob_id": "7de0c6962a943bc4c5bf6f06c718c193b376caac",
"content_id": "dad53930bfcbccf3b464488e7bd4496237116648",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2524,
"license_type": "no_license",
"max_line_length": 980,
"num_lines": 21,
"path": "/README.md",
"repo_name": "ssd-73/Cellular-Automata-based-on-Stock-Market",
"src_encoding": "UTF-8",
"text": "I. Project Name: The Research of Herd Behavior in Stock Market Based on the Cellular Automata\n\nII. Background: Herd Behavior shows that a large number of investors utilize the identical trading strategies or have the same preference for specific assets in a certain period of time, which can well explain the \"bounded rationality\" in the real world. Through the establishment of a cellular automata model with 90 imitative rules based on three categories of investors and three kinds of market messages, the cellular automata is applied for a simulation experiment on Herd Behavior in the real stock market, and proves that different types of investor behavior and different market messages will affect the behavior of investors. Based on the comparison of stock price, returns time series and investor behavior chart per round, we find that Herd Behavior will begin to highlight in the period of stock price acute fluctuations. Finally, a further statistical test is conducted on the variables such as the stock price and return rates generated by the simulation experiment.\n\nIII. Instructions:\n1. The skeleton of this cellular automata contains several parts:\n (1) The map is 100×100. which means there are up to 10,000 investors.\n (2) Investors are divided into 3 categories, namely, institutional investors, ordinary investors, and noise investors.\n (3) There are 3 different categories of message in the market, obeying N(0, 1). If greater than 0.75, it is called \"good news\". If smaller than 0.25, it is called \"bad news\". Otherwise, it is called \"No news\".\n (4) Based on three kinds of investors and three kinds of market message, there are up to 90 imitation rules.\n2. How do u conduct this experiment by urself?\n (1) Modules requirement: math, numpy, pandas, and matplotlib\n (2) IDLE requirement: Python version >= 3\n (3) Use command line \"Python Automata.py\" in Linux, or open and run Automata.py directly in Windows\n (4) The folder called Figure contains the results of one experiment. If you wish, you can set any folder to save the results figures\n\nIV. Suggestions:\n1. I recommend u to test or run the codes in Jupyter notebook. If not, up to 2000 rounds can occupy about couples of hours to do so.\n2. Because there are many random variables, the results of each simulatition will be different.\n3. If u wanna use this code directly, please specify \"@Author: Shao Shidong\" in your Python files, and appendix of your paper, if possible. \n Meanwhile, I still recommend u to code by urself.\n"
},
{
"alpha_fraction": 0.7621247172355652,
"alphanum_fraction": 0.7898383140563965,
"avg_line_length": 107.25,
"blob_id": "e57a60acbceae0a89d10c108925f247d4b0a1899",
"content_id": "3c74e76a54bbee4a706ad86487d7d247cf312c5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 433,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 4,
"path": "/Figure/README.txt",
"repo_name": "ssd-73/Cellular-Automata-based-on-Stock-Market",
"src_encoding": "UTF-8",
"text": "1. There are two zip files which contain up to 2000 figures, 1000 figures each, recording the result of one simulation experiment.\n2. The .csv file records the data of return rates, which can be used to do the statistical tests or some regression tests.\n3. The isolated figure in this folder records the stock price and return rates time series.\n4. All of the files are output in one experiment. Thus, they can be analyzed together.\n"
},
{
"alpha_fraction": 0.3601619601249695,
"alphanum_fraction": 0.41119396686553955,
"avg_line_length": 31.254514694213867,
"blob_id": "e9a052e37a1665ce0b118be949e714c38a4396ca",
"content_id": "45e8c3f93012b0a2c570b36d3afa7a45fc859392",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 41460,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 1218,
"path": "/Automata.py",
"repo_name": "ssd-73/Cellular-Automata-based-on-Stock-Market",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Name: Automata.py\r\n# Author: Shao Shidong\r\n# Date: 2020/7/28\r\n# Version: Python 3.6 64-bit\r\n\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as mpatches\r\n\r\ninvestors = [\"Institutional Investor\",\"Ordinary Investors\",\"Noise Investors\"]\r\noperations = [\"Buy\",\"Hold\",\"Sell\"]\r\nbuy = []; sell = []\r\nprice = [15]\r\nRseries = [0]\r\n\r\ndef Message():\r\n m = np.random.normal(loc=0.5, scale=1)\r\n return m\r\n\r\ndef Plot(a,b):\r\n fig=plt.figure(dpi=80,figsize=(20,30))\r\n ax=fig.add_subplot(2,1,1)\r\n ax.plot(range(len(a)),a ,color='r',label='Price')\r\n plt.legend(loc='upper left')\r\n ax=fig.add_subplot(2,1,2)\r\n ax.plot(range(len(b)),b ,color='r',label='Return Series')\r\n plt.legend(loc='upper left')\r\n plt.savefig(\"E:/Figure/figure\")\r\n plt.show()\r\n\r\n\r\nclass GameOfLife(object):\r\n def __init__(self, cells_shape):\r\n self.cells = np.ones(cells_shape)\r\n self.cells_state = np.zeros(cells_shape)\r\n self.cells_return = np.zeros(cells_shape)\r\n real_width = cells_shape[0] - 2\r\n real_height = cells_shape[1] - 2\r\n count1 = 0; count2 = 0\r\n \"\"\"\r\n 随机生成23个机构投资者、5986个普通投资者和3991个噪声投资者\r\n \"\"\"\r\n while count1 < 23:\r\n x1 = np.random.randint(1,101); y1 = np.random.randint(1,101)\r\n if self.cells_state[x1, y1] == 0:\r\n self.cells_state[x1, y1] = 1\r\n count1 += 1\r\n while count2 < 5986:\r\n x2 = np.random.randint(1,101); y2 = np.random.randint(1,101)\r\n if self.cells_state[x2, y2] == 0:\r\n self.cells_state[x2, y2] = 2\r\n count2 += 1\r\n for i in range(1,101):\r\n for j in range(1,101):\r\n if self.cells_state[i, j] == 0:\r\n self.cells_state[i, j] = 3\r\n \"\"\"\r\n 随机生成投资者的行为,买入用+100表示、持仓用0表示、卖出用-100表示\r\n \"\"\"\r\n for i in range(0,102):\r\n for j in range(0,102):\r\n if i==0 or i==101 or j==0 or j==101: self.cells[i,j] = -101\r\n else:\r\n flag = np.random.randint(1,4)\r\n if flag == 1: self.cells[i,j] = 100\r\n elif flag == 2: self.cells[i,j] = 0\r\n elif flag == 3: self.cells[i,j] = -100\r\n \r\n self.period = 0\r\n\r\n\r\n def Find_max(self, x, y, flag, target):\r\n \"\"\"\r\n 函数功能:\r\n -------------------------------------\r\n 找出坐标为(x,y)的元胞邻居中的target投资者的多数行为,并返回\r\n\r\n 参数:\r\n ----------------------------------\r\n flag, target:1->机构投资者;2->普通投资者;3->噪声投资者\r\n count_buy:邻居中选择“买入”的投资者数量\r\n count_hold:邻居中选择“持有”的投资者数量\r\n count_sell:邻居中选择“卖出”的投资者数量\r\n Max_operation: 邻居中的多数选择\r\n \"\"\"\r\n cells = self.cells\r\n cells_state = self.cells_state\r\n count_buy = 0; count_hold = 0; count_sell = 0\r\n if flag == 1:\r\n if x <= 5:\r\n tool_x1 = 1\r\n tool_x2 = x+6\r\n elif x >= 96:\r\n tool_x1 = x-5\r\n tool_x2 = 101\r\n else:\r\n tool_x1 = x-5\r\n tool_x2 = x+6\r\n for i in range(tool_x1, tool_x2):\r\n if i <= x: tool_j = abs(x-5-i)\r\n else: tool_j = abs(x+5-i)\r\n if y-tool_j <= 0:\r\n y = tool_j+1\r\n if y+tool_j >= 101:\r\n y = 100-tool_j\r\n for j in range(y-tool_j, y+tool_j+1):\r\n if i!=x and j!=y:\r\n if cells_state[i, j] == target:\r\n if cells[i, j] == 100: count_buy += 1\r\n elif cells[i, j] == 0: count_hold += 1\r\n elif cells[i, j] == -100: count_sell += 1\r\n else:\r\n if x == 1:\r\n tool_x1 = 1\r\n tool_x2 = x+2\r\n elif x == 100:\r\n tool_x1 = x-1\r\n tool_x2 = 101\r\n else:\r\n tool_x1 = x-1\r\n tool_x2 = x+1\r\n for i in range(tool_x1,tool_x2):\r\n if y == 1:\r\n if cells_state[i, y+1] == target:\r\n if cells[i, y+1] == 100: count_buy += 1\r\n elif cells[i, y+1] == 0: count_hold += 1\r\n elif cells[i, y+1] == -100: count_sell += 1\r\n elif y == 100:\r\n if cells_state[i, y-1] == target:\r\n if cells[i, y-1] == 100: count_buy += 1\r\n elif cells[i, y-1] == 0: count_hold += 1\r\n elif cells[i, y-1] == -100: count_sell += 1\r\n else:\r\n if cells_state[i, y+1] == target:\r\n if cells[i, y+1] == 100: count_buy += 1\r\n elif cells[i, y+1] == 0: count_hold += 1\r\n elif cells[i, y+1] == -100: count_sell += 1\r\n if cells_state[i, y-1] == target:\r\n if cells[i, y-1] == 100: count_buy += 1\r\n elif cells[i, y-1] == 0: count_hold += 1\r\n elif cells[i, y-1] == -100: count_sell += 1\r\n if cells_state[x-1, y] == target:\r\n if cells[x-1, y] == 100: count_buy += 1\r\n elif cells[x-1, y] == 0: count_hold += 1\r\n elif cells[x-1, y] == -100: count_sell += 1\r\n if cells_state[x+1, y] ==target:\r\n if cells[x+1, y] == 100: count_buy += 1\r\n elif cells[x+1, y] == 0: count_hold += 1\r\n elif cells[x+1, y] == -100: count_sell += 1 \r\n \r\n Max = count_buy\r\n Max_operation = operations[0]\r\n if Max < count_hold:\r\n Max = count_hold\r\n Max_operation = operations[1]\r\n if Max < count_sell:\r\n Max = count_hold\r\n Max_operation = operations[2]\r\n return Max_operation \r\n\r\n \r\n def Count(self, x, y, flag, target):\r\n \"\"\"\r\n 函数功能:\r\n ----------------------------------\r\n 计算邻居中存在target数字代表的投资者的数量,并返回\r\n\r\n 参数:\r\n ----------------------------------\r\n flag, target:1->机构投资者;2->普通投资者;3->噪声投资者\r\n count:target代表的投资者的数量\r\n \"\"\"\r\n count = 0\r\n if flag == 1:\r\n \"\"\"对机构投资者邻居\"\"\"\r\n if x <= 5:\r\n tool_x1 = 1\r\n tool_x2 = x+6\r\n elif x >= 96:\r\n tool_x1 = x-5\r\n tool_x2 = 101\r\n else:\r\n tool_x1 = x-5\r\n tool_x2 = x+6\r\n for i in range(tool_x1, tool_x2):\r\n if i <= x: tool_j = abs(x-5-i)\r\n else: tool_j = abs(x+5-i)\r\n if y-tool_j <= 0: y = tool_j+1\r\n if y+tool_j >= 101: y = 100-tool_j\r\n for j in range(y-tool_j, y+tool_j+1):\r\n if i!=x and j!=y:\r\n if self.cells_state[i, j] == target:\r\n count += 1\r\n return count\r\n else:\r\n \"\"\"\"对普通和噪声投资者\"\"\"\r\n if x == 1:\r\n tool_x1 = 1\r\n tool_x2 = x+2\r\n elif x == 100:\r\n tool_x1 = x-1\r\n tool_x2 = 101\r\n else:\r\n tool_x1 = x-1\r\n tool_x2 = x+1\r\n for i in range(tool_x1,tool_x2):\r\n if y == 1:\r\n if self.cells_state[i, y+1] == target:\r\n count += 1\r\n elif y == 100:\r\n if self.cells_state[i, y-1] == target:\r\n count += 1\r\n else:\r\n if self.cells_state[i, y+1] == target:\r\n count += 1\r\n if self.cells_state[i, y-1] == target:\r\n count += 1\r\n if self.cells_state[x-1, y] == target or self.cells_state[x+1, y] ==target:\r\n count += 1\r\n return count\r\n\r\n\r\n def Max_return(self, x, y, flag, target):\r\n \"\"\"\r\n 函数功能:\r\n ----------------------------------\r\n 计算机构投资者邻居中target数字代表的投资者的累计最大收益率,并返回其当期操作\r\n\r\n 参数:\r\n ----------------------------------\r\n target:2->普通投资者;3->噪声投资者\r\n \"\"\"\r\n count = 0\r\n Oper = []\r\n Oper_x = []\r\n Oper_y = []\r\n if flag == 1:\r\n \"\"\"\r\n 对机构投资者邻居\r\n \"\"\"\r\n if x <= 5:\r\n tool_x1 = 1\r\n tool_x2 = x+6\r\n elif x >= 96:\r\n tool_x1 = x-5\r\n tool_x2 = 101\r\n else:\r\n tool_x1 = x-5\r\n tool_x2 = x+6\r\n for i in range(tool_x1, tool_x2):\r\n if i <= x: tool_j = abs(x-5-i)\r\n else: tool_j = abs(x+5-i)\r\n if y-tool_j <= 0: y = tool_j+1\r\n if y+tool_j >= 101: y = 100-tool_j\r\n for j in range(y-tool_j, y+tool_j+1):\r\n if i!=x and j!=y:\r\n if self.cells_state[i, j] == target:\r\n if self.cells_return[i, j] >= 15 and target == 2:\r\n count += 1\r\n Oper.append(self.cells[i, j])\r\n Oper_x.append(i)\r\n Oper_y.append(j)\r\n elif self.cells_return[i, j] >= 20 and target == 3:\r\n count += 1\r\n Oper.append(self.cells[i, j])\r\n Oper_x.append(i)\r\n Oper_y.append(j)\r\n if count >= 1:\r\n Max_return = 0\r\n for i in range(len(Oper)):\r\n if self.cells_return[Oper_x[i],Oper_y[i]] >= Max_return:\r\n Max_return = self.cells_return[Oper_x[i],Oper_y[i]]\r\n Max_i = Oper_x[i]; Max_j = Oper_y[i];\r\n return self.cells[Max_i,Max_j]\r\n else:\r\n return -1\r\n\r\n\r\n def Rule(self, x, y, message, flag):\r\n \"\"\"\r\n 函数功能:\r\n ----------------------------------\r\n 设定三类投资者的模仿规则,并在不同情况下更新坐标为(x,y)的元胞状态\r\n\r\n 参数:\r\n ----------------------------------\r\n flag:1->机构投资者;2->普通投资者;3->噪声投资者\r\n Message~N(0.5,1):市场消息,超过0.75为利好消息,低于0.25为利空消息,其他无消息\r\n \"\"\"\r\n cell = self.cells\r\n cells_state = self.cells_state\r\n count1 = self.Count(x,y,flag,1)\r\n count2 = self.Count(x,y,flag,2)\r\n count3 = self.Count(x,y,flag,3)\r\n if flag == 1:\r\n if message >= 0.75:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if p1*(2-message)>=1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<= p1*(2-message):\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1*(1-message):\r\n cell[x, y] = -100\r\n elif prob>p1*(1-message) and prob<=0.5+7*(1-message)/8:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = 100\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1:\r\n cell[x, y] = 0\r\n elif prob>p1 and prob<=0.5+p1*(2-message)/4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n standard_operation2 = self.Max_return(x, y, 1, 2)\r\n standard_operation3 = self.Max_return(x, y, 1, 3)\r\n if standard_operation2==-1 and standard_operation3==-1:\r\n prob = np.random.random()\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n elif prob>=message and prob<(1+message)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n if standard_operation2 != -1:\r\n cell[x, y] = standard_operation2\r\n elif standard_operation3 != -1 and standard_operation2 == -1:\r\n cell[x, y] = standard_operation3\r\n elif message <= 0.25:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Sell\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if p1*(2-message)>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<= p1*(2-message):\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Buy\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1*(1-message):\r\n cell[x, y] = 100\r\n elif prob>p1*(1-message) and prob<=0.5+7*(1-message)/8:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1:\r\n cell[x, y] = 0\r\n elif prob>p1 and prob<=0.5+p1*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n standard_operation2 = self.Max_return(x, y, 1, 2)\r\n standard_operation3 = self.Max_return(x, y, 1, 3)\r\n if standard_operation2==-1 and standard_operation3==-1:\r\n prob = np.random.random()\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n elif prob>=message and prob<(1+message)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n if standard_operation2 != -1:\r\n cell[x, y] = standard_operation2\r\n elif standard_operation3 != -1 and standard_operation2 == -1:\r\n cell[x, y] = standard_operation3 \r\n else:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p1:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p1 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p1:\r\n cell[x, y] = 0\r\n elif prob>p1 and prob<=(1+p1)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n standard_operation2 = self.Max_return(x, y, 1, 2)\r\n standard_operation3 = self.Max_return(x, y, 1, 3)\r\n if standard_operation2==-1 and standard_operation3==-1:\r\n cell[x, y] = 0\r\n else:\r\n if standard_operation2 != -1:\r\n cell[x, y] = standard_operation2\r\n elif standard_operation3 != -1 and standard_operation2 == -1:\r\n cell[x, y] = standard_operation3 \r\n \r\n elif flag == 2:\r\n if message >= 0.75:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if p2*(1+message)>=1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<= p2*(1+message):\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p2*(1-message):\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p2:\r\n cell[x, y] = 0\r\n elif prob>p2 and prob<=0.5+p2*(2-message)/4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if p3*(1+message) >= 1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<p3*(1+message):\r\n cell[x, y] = 100\r\n elif prob>=p3*(1+message) and prob<(2*p3+2*message*p3+1)/3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3:\r\n cell[x, y] = 0\r\n elif prob>=p3 and prob<=0.5+0.5*p3-0.25*message*p3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3*(1-message):\r\n cell[x, y] = -100\r\n elif prob>=p3*(1-message) and prob<(2*p3-2*message*p3+1)/3:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,3)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4*(1+message):\r\n cell[x, y] = 100\r\n elif prob>=p4*(1+message) and prob<(p4+message*p4+1)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4:\r\n cell[x, y] = 0\r\n elif prob>=p3 and prob<=0.5+0.5*p4-0.25*message*p4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4*(1-message):\r\n cell[x, y] = -100\r\n elif prob>=p4*(1-message) and prob<(p4-message*p4+1)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n prob = np.random.random()\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n elif prob>=message and prob<(message+1)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 100\r\n elif message <= 0.25:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p2*(1-message):\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if p2*(1+message) >= 1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<=p2*(1+message):\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p2:\r\n cell[x, y] = 0\r\n elif prob>p2 and prob<=0.5+p2*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3*(1-message):\r\n cell[x, y] = 100\r\n elif prob>=p3*(1-message) and prob<(1+2*(1-message)*p3)/3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3:\r\n cell[x, y] = 0\r\n elif prob>=p3 and prob<0.5+p3*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if (1+message)*p3>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<(1+message)*p3:\r\n cell[x, y] = -100\r\n elif prob>=message and prob<(1+2*(1+message)*p3)/3:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4*(1-message):\r\n cell[x, y] = 100\r\n elif prob>=p4*(1-message) and prob<(1+(1-message)*p4)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4:\r\n cell[x, y] = 0\r\n elif prob>=p4 and prob<0.5+p4*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if (1+message)*p4>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<(1+message)*p4:\r\n cell[x, y] = -100\r\n elif prob>=message and prob<(1+(1+message)*p4)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n prob = np.random.random()\r\n if prob>=0 and prob<message/2:\r\n cell[x, y] = 100\r\n elif prob>=message/2 and prob<message:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=p2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p2 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<=(1-p2)/2:\r\n cell[x, y] = 100\r\n elif prob>(1-p2)/2 and prob<=1-p2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3:\r\n cell[x, y] = 100\r\n elif prob>=p3 and prob<(1+2*p3)/3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3:\r\n cell[x, y] = -100\r\n elif prob>=p3 and prob<(1+2*p3)/3:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p3 = np.random.uniform(0.25,1)\r\n if prob>=0 and prob<p3:\r\n cell[x, y] = 0\r\n elif prob>=p3 and prob<(1+p3)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,3)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4:\r\n cell[x, y] = 100\r\n elif prob>=p4 and prob<(1+p4)/2:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4:\r\n cell[x, y] = -100\r\n elif prob>=p4 and prob<(1+p4)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p4 = np.random.uniform(0,0.5)\r\n if prob>=0 and prob<p4:\r\n cell[x, y] = 0\r\n elif prob>=p4 and prob<(1+p4)/2:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n prob = np.random.random()\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<2/3:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n if prob>=0 and prob<2/3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n if prob>=0 and prob<0.3:\r\n cell[x, y] = 100\r\n elif prob>=0.3 and prob<0.6:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n\r\n elif flag == 3:\r\n if message >= 0.75:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if p5*(1+message)>=1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<= p5*(1+message):\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if (2-message)*p5>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<=p5*(2-message):\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<=p5:\r\n cell[x, y] = 0\r\n elif prob>p5 and prob<=0.5+p5*(2-message)/4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if (1+message)*p6>=1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<(1+message)*p6:\r\n cell[x, y] = 100\r\n elif prob>=(1+message)*p6 and prob<(1+4*(1+message)*p6)/5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<(1-message)*p6:\r\n cell[x, y] = -100\r\n elif prob>=(1-message)*p6 and prob<(1+4*p6*(1-message))/5:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p6:\r\n cell[x, y] = 0\r\n elif prob>=p6 and prob<0.5+p6*(2-message)/4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,3)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if (1+message)*p7>=1:\r\n cell[x, y] = 100\r\n else:\r\n if prob>=0 and prob<(1+message)*p7:\r\n cell[x, y] = 100\r\n elif prob>=(1+message)*p7 and prob<(1+4*p7*(1+message))/5:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<(1-message)*p7:\r\n cell[x, y] = -100\r\n elif prob>=(1-message)*p7 and prob<(1+4*p7*(1-message))/5:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<p7:\r\n cell[x, y] = 0\r\n elif prob>=p7 and prob<0.5+p7*(2-message)/4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n prob = np.random.random()\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<(1-message)/2:\r\n cell[x, y] = 100\r\n elif prob>=(1-message)/2 and prob<1-message:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n \r\n elif message <= 0.25:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Sell\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if p5*(1+message)>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<= p5*(1+message):\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Buy\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<=p5*(1-message):\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<=p5:\r\n cell[x, y] = 0\r\n elif prob>p5 and prob<=0.5+p5*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Sell\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if (1+message)*p6>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<(1+message)*p6:\r\n cell[x, y] = -100\r\n elif prob>=(1+message)*p6 and prob<(1+4*(1+message)*p6)/5:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Buy\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<(1-message)*p6:\r\n cell[x, y] = 100\r\n elif prob>=(1-message)*p6 and prob<(1+4*p6*(1-message))/5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p6:\r\n cell[x, y] = 0\r\n elif prob>=p6 and prob<0.5+p6*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,3)\r\n if Op == \"Sell\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if (1+message)*p7>=1:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<(1+message)*p7:\r\n cell[x, y] = -100\r\n elif prob>=(1+message)*p7 and prob<(1+2*p7*(1+message))/3:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Buy\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<(1-message)*p7:\r\n cell[x, y] = 100\r\n elif prob>=(1-message)*p7 and prob<(1+2*p7*(1-message))/3:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<p7:\r\n cell[x, y] = 0\r\n elif prob>=p7 and prob<0.5+p7*(2-message)/4:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n prob = np.random.random()\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n if prob>=0 and prob<message:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<message/2:\r\n cell[x, y] = 100\r\n elif prob>=message/2 and prob<message:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n\r\n else:\r\n if count1!=0:\r\n Op = self.Find_max(x,y,flag,1)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<= p5:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<=p5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Hold\":\r\n prob = np.random.random()\r\n p5 = np.random.uniform(0.75,1)\r\n if prob>=0 and prob<=p5:\r\n cell[x, y] = 0\r\n elif prob>p5 and prob<=0.5+0.5*p5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n elif count2 == 8:\r\n Op = self.Find_max(x,y,flag,2)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p6:\r\n cell[x, y] = 100\r\n elif prob>=p6 and prob<(1+4*p6)/5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p6:\r\n cell[x, y] = -100\r\n elif prob>=p6 and prob<(1+4*p6)/5:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p6 = np.random.uniform(0.5,1)\r\n if prob>=0 and prob<p6:\r\n cell[x, y] = 0\r\n elif prob>=p6 and prob<0.5+p6*0.5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n elif count3 == 8:\r\n Op = self.Find_max(x,y,flag,3)\r\n if Op == \"Buy\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<p7:\r\n cell[x, y] = 100\r\n elif prob>=p7 and prob<0.5+0.5*p7:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n elif Op == \"Sell\":\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<p7:\r\n cell[x, y] = -100\r\n elif prob>=p7 and prob<0.5+0.5*p7:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n else:\r\n prob = np.random.random()\r\n p7 = np.random.uniform(0,0.75)\r\n if prob>=0 and prob<p7:\r\n cell[x, y] = 0\r\n elif prob>=p7 and prob<0.5+p7*0.5:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 100\r\n else:\r\n Op = self.Find_max(x,y,flag,2)\r\n prob = np.random.random()\r\n if Op == \"Buy\":\r\n if prob>=0 and prob<0.8:\r\n cell[x, y] = 100\r\n else:\r\n cell[x, y] = 0\r\n elif Op == \"Sell\":\r\n if prob>=0 and prob<0.2:\r\n cell[x, y] = 0\r\n else:\r\n cell[x, y] = -100\r\n else:\r\n if prob>=0 and prob<0.2:\r\n cell[x, y] = 100\r\n elif prob>=0.2 and prob<0.4:\r\n cell[x, y] = -100\r\n else:\r\n cell[x, y] = 0\r\n \r\n return cell[x, y]\r\n\r\n \r\n def update_BHS(self,time):\r\n \"\"\"\r\n 函数功能:\r\n --------------------------------\r\n 根据制定的模仿规则,更新每个元胞在time时刻的市场状态\r\n\r\n 参数\r\n ----------\r\n time : 该时刻模拟市场轮次\r\n \"\"\"\r\n cells = self.cells\r\n cells_state = self.cells_state\r\n cells_return = self.cells_return\r\n volume_buy = 0; volume_sell = 0\r\n currentR = 0\r\n BHS = np.zeros(self.cells.shape)\r\n for i in range(0, cells.shape[0]):\r\n for j in range(0, cells.shape[0]):\r\n BHS[i, j] = -101\r\n message = Message()\r\n k = np.random.normal(loc=0, scale=1)\r\n for i in range(1, cells.shape[0] - 1):\r\n for j in range(1, cells.shape[0] - 1):\r\n BHS[i, j] = self.Rule(i,j,message,cells_state[i, j])\r\n if BHS[i, j] == 100:\r\n volume_buy += 1\r\n elif BHS[i, j] == -100:\r\n volume_sell += 1\r\n if time != 0:\r\n p = (1+k*0.00001*(volume_buy-volume_sell))*price[time-1]\r\n price.append(p)\r\n currentR = 100*(math.log(price[time])-math.log(price[time-1]))\r\n Rseries.append(currentR)\r\n for i in range(1, cells.shape[0] - 1):\r\n for j in range(1, cells.shape[0] - 1):\r\n if BHS[i, j] == 100:\r\n cells_return[i ,j] -= currentR\r\n elif BHS[i, j] == -100:\r\n cells_return[i ,j] += currentR\r\n buy.append(volume_buy); sell.append(volume_sell)\r\n self.cells = BHS\r\n self.period += 1\r\n\r\n\r\n def update_Draw(self, N_round):\r\n \"\"\"\r\n 函数功能:\r\n --------------------------------\r\n 1.在做图中画出每轮市场中投资者的行为,共N-round轮\r\n 2.在右图中画出该次模拟市场中投资者的分布情况\r\n\r\n 参数\r\n ----------\r\n N_round : 更新的轮数\r\n \"\"\"\r\n plt.figure(figsize=(20,15))\r\n plt.ion()\r\n for i in range(N_round):\r\n plt.figure(figsize=(20,15))\r\n ax1 = plt.subplot(1,2,1)\r\n ax1.set_title('Round :{}'.format(self.period))\r\n \"\"\"画出左图\"\"\"\r\n data = self.cells\r\n values = np.unique(data.ravel())\r\n values = values[1:]\r\n im = plt.imshow(self.cells)\r\n colors = [ im.cmap(im.norm(value)) for value in values]\r\n patches = [ mpatches.Patch(color=colors[i], label=\"{}\".format(operations[i]) ) for i in range(len(values))]\r\n plt.legend(handles=patches, bbox_to_anchor=(1, 1), loc=2, borderaxespad=0. )\r\n \"\"\"画出右图\"\"\"\r\n ax2 = plt.subplot(1,2,2)\r\n ax2.set_title('Investors')\r\n data2 = self.cells_state\r\n values2 = np.unique(data2.ravel())\r\n values2 = values2[1:]\r\n im2 = plt.imshow(self.cells_state)\r\n colors2 = [ im2.cmap(im2.norm(value)) for value in values2]\r\n patches2 = [ mpatches.Patch(color=colors2[i], label=\"{}\".format(investors[i]) ) for i in range(len(values2))]\r\n plt.legend(handles=patches2, bbox_to_anchor=(1, 1), loc=2, borderaxespad=0. )\r\n plt.savefig(\"E:/Figure/Operations of {}\".format(i))\r\n self.update_BHS(i)\r\n plt.pause(0.05)\r\n plt.ioff()\r\n\r\n\r\nif __name__ == '__main__':\r\n game = GameOfLife(cells_shape=(102, 102))\r\n game.update_Draw(2000)\r\n Plot(price,Rseries)\r\n test=pd.DataFrame(data=Rseries)\r\n test.to_csv('E:/Figure/return.csv')\r\n print(\"提取完毕!\")\r\n"
}
] | 3 |
XushengZhao/Backtest_Platform | https://github.com/XushengZhao/Backtest_Platform | d14d1449e6ec37c3fa1fa73dafda12881f07408e | 6f07bb494aa204e0306c15e44b9c85ffc1fb103a | d4501a27db1864700d8d69ac052aaf14958152c5 | refs/heads/master | 2023-02-14T14:50:15.902608 | 2021-01-11T00:17:15 | 2021-01-11T00:17:15 | 274,031,688 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.48148149251937866,
"alphanum_fraction": 0.5502645373344421,
"avg_line_length": 14.833333015441895,
"blob_id": "da7a6307402313ab0e8b435ce732b0ed45f97662",
"content_id": "5ad591c27b2e0cb74116a8e7f88981ec4c3439c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 12,
"path": "/Order_class.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 18:24:50 2020\n\n@author: Xzhao\n\"\"\"\n\nclass Order:\n\n def __init__(self, buy, shares):\n self.shares = shares;\n self.buy = buy;"
},
{
"alpha_fraction": 0.6640477776527405,
"alphanum_fraction": 0.682589590549469,
"avg_line_length": 33.978023529052734,
"blob_id": "505e1b19b2b2ac7539aa44dd79a9e2992a67a697",
"content_id": "6a910ea2d03159f4b380aba84609a58bfb6783be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3182,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 91,
"path": "/Strategies/Equal_weight/Equal_weight_iex.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport requests\nimport xlsxwriter\nimport math\n\ndef chunks(lst,n):\n for i in range (0,len(lst),n):\n yield lst[i:i +n]\n\n'''This script will create a excel spreadsheet of buy orders using an user input portfolio balance that mimics an equal weight SP500 fund.\nIt uses IEX API to get stock prices and a spreadsheet for current SP500 stocks.\nIt will output the final buy orders as an excel spreadsheet.\n'''\n\n#API TOKEN\nfrom secrets import IEX_CLOUD_API_TOKEN\n\n#currently using a preset file with list of sp500 instead of gathering the list of stocks from some API\nsp500_list_csv_filepath = \"sp_500_stocks.csv\"\nsp500_stocklist = pd.read_csv(sp500_list_csv_filepath)\n\n#the current batch API of IEX only accepts at most 100 stock tickers. We are splitting the stock list up\nsymbol_groups = list(chunks(sp500_stocklist['Ticker'],100))\nsymbol_strings = []\nfor i in range(len(symbol_groups)):\n symbol_strings.append(','.join(symbol_groups[i]))\n \nmy_columns = ['Ticker', 'Stock Price', ' Market Cap', 'Number of shares to buy']\nfinal_df= pd.DataFrame(columns = my_columns)\n\n#Extract stock price using IEX API\nbase_url = 'https://sandbox.iexapis.com/stable'\nfor stocklist in symbol_strings: \n request = f'/stock/market/batch?symbols={stocklist}&types=quote&token={IEX_CLOUD_API_TOKEN}'\n final_url = base_url + request\n data = requests.get(final_url).json()\n for symbol in stocklist.split(','): \n price = data[symbol]['quote']['latestPrice']\n mkt_cap = data[symbol]['quote']['marketCap']/(10**9)\n final_df = final_df.append(\n pd.Series([symbol, price, mkt_cap, 'N/A'],index = my_columns), ignore_index=True,\n )\n\n#user input section to get a portfolio value\nportfolio_balance = input('Enter portfolio value : ')\ntry:\n val = float(portfolio_balance)\nexcept ValueError:\n print(\"Please enter a number\")\n portfolio_balance = input('Enter portfolio value : ')\n val = float(portfolio_balance)\n \nposition_size = val/len(final_df.index)\nnum_shares = position_size\nfor i in range(len(final_df.index)):\n final_df.loc[i,'Number of shares to buy'] = math.floor(position_size/final_df.loc[i,'Stock Price'])\n \n#write to the excel spreadsheet\nwriter = pd.ExcelWriter('sp500_trades.xlsx',engine = 'xlsxwriter')\nfinal_df.to_excel(writer, 'SP500 trades',index = False)\nbackground_color = '#ffffff'\nfont_color = '#000000'\n\nstring_format = writer.book.add_format({\n 'font_color':font_color,\n 'bg_color': background_color,\n 'border' : 1 \n})\n\ndollar_format = writer.book.add_format({\n 'num_format' : '$0.00',\n 'font_color':font_color,\n 'bg_color': background_color,\n 'border' : 1 \n})\n\ninteger_format = writer.book.add_format({\n 'num_format' : '0',\n 'font_color':font_color,\n 'bg_color': background_color,\n 'border' : 1 \n})\ncolumn_formats = {\n 'A': ['Ticker', string_format],\n 'B': ['Stock Price', dollar_format],\n 'C': ['Market Cap', integer_format],\n 'D': ['Number of Shares to Buy', integer_format]\n}\nfor column in column_formats.keys():\n writer.sheets['SP500 trades'].set_column(f'{column}:{column}',18,column_formats[column][1])\nwriter.save()"
},
{
"alpha_fraction": 0.4117647111415863,
"alphanum_fraction": 0.5647059082984924,
"avg_line_length": 13,
"blob_id": "c94f426f340ab08473d443f78f436a4200d4a9eb",
"content_id": "679bc47e313ffba63d8c7d58ef20f0a2a8148891",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 85,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 6,
"path": "/__init__.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 18:51:41 2020\n\n@author: Xzhao\n\"\"\"\n\n"
},
{
"alpha_fraction": 0.7212189435958862,
"alphanum_fraction": 0.7663657069206238,
"avg_line_length": 26.71875,
"blob_id": "9704a026c049e568e6c43f7053bbd3fbc3400041",
"content_id": "5c69b3d9100a9713aac9b5b186f5a5ba640e0e3a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 886,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 32,
"path": "/Tutorial_main.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 19:02:04 2020\n\n@author: Xzhao\n\"\"\"\nfrom Platform_class import BT_platform\nfrom BOSC_strategy import BOSC\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\nBacktest_platform = BT_platform()\nBOSC_strat = BOSC()\n\nfilepath = r'C:\\Users\\Xzhao\\source\\Backtrader\\csv_files\\SPY_1993_2020.csv'\nfromdate = datetime(1900,1,1)\ntodate = datetime(2020,6,30)\nBacktest_platform.csv_filepath(filepath)\nBacktest_platform.startdate(fromdate)\nBacktest_platform.enddate(todate)\nBacktest_platform.set_balance(10000.0)\nBacktest_platform.set_strategy(BOSC_strat)\nBacktest_platform.run()\n\nxdata = Backtest_platform.portfolio_x_data()\nydata = Backtest_platform.portfolio_y_data()\nplt.plot(xdata,ydata,label = \"Buy Open, Sell Close\")\nplt.title(\"Portfolio performance for a SPY\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Portfolio Value\")\nplt.legend()\nplt.show()"
},
{
"alpha_fraction": 0.7913998365402222,
"alphanum_fraction": 0.7968893051147461,
"avg_line_length": 53.54999923706055,
"blob_id": "a64e241c4ddd91e5b31f4dfeb18f80536f00ef82",
"content_id": "fc3b420bf403d4128f0b9bd8c4dd897a3cdf31a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1093,
"license_type": "no_license",
"max_line_length": 339,
"num_lines": 20,
"path": "/README.md",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# Backtest_Platform\n\n## This is my basic stock backtesting platform\n\nRight now it has the currently capabilities:\n\n1. Read an OHLC bar (Open High Low Close) csv file\n2. Use a specific user implemented strategy class\n3. Simulate portfolio results over the OHLC file over the date range\n\nA basic BUY open, SELL close (BOSC) strategy is given as an example.\nTo get started the Tutorial_main.py script is given, which will run the simulation with the BOSC strategy and graph the results.\n\n# Strategies\n\nThere are two uploaded simple strategies from when I started. The two algorithms take an list of stocks as input and using IEX (stock broker) API will retrieve stock data and perform the necessary analysis. The two strategies will output an excel spreadsheet with the number of shares to buy for each stock selected based on the analysis. \n\nThe two stratgies are an equal weight SP500 and an High quantitative momentum strategy.\n\nThey are located in the Strategy folder and when run will prompt an portfolio balance input and then output the excel spreadsheet with the list of stocks to buy. \n\n"
},
{
"alpha_fraction": 0.5358285307884216,
"alphanum_fraction": 0.5403071045875549,
"avg_line_length": 39.610389709472656,
"blob_id": "924857ba01dd2c8cb308e1f031f54c58d955f527",
"content_id": "bfa21096e8143ea9a72e038ee6e72e90f3428b6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3126,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 77,
"path": "/Platform_class.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 17:14:49 2020\n\n@author: Xzhao\n\"\"\"\nfrom datetime import datetime\nimport pandas\nfrom Order_class import Order\n\nclass BT_platform:\n def __init__(self):\n pass\n #define a CSV filepath to open\n def csv_filepath(self, filepath):\n self.csv_filepath = filepath\n #set the startdate for CSV file\n def startdate(self,startdate):\n self.startdate = startdate\n #set the enddate for the CSV file\n def enddate(self,enddate):\n self.enddate = enddate\n #functions to set starting balance and get the current money\n def set_balance(self, balance):\n self.balance = balance\n def curr_balance (self):\n return self.balance\n \n def run(self):\n csv_file = pandas.read_csv(self.csv_filepath)\n dates = csv_file.set_index('Date',drop=False)\n self.Portfolio_balance = []\n self.shares_total = 0\n self.date_track = []\n for index,row in dates.iterrows():\n currdate = datetime.strptime(index, '%Y-%m-%d')\n #run only within the dates specified\n if currdate >= self.startdate and currdate <= self.enddate:\n curropen = row['Open']\n currclose = row['Close']\n \n #get order for open price\n openorder = self.strategy.open(curropen,self.balance,self.shares_total)\n if openorder:\n if openorder.buy:\n if openorder.shares * curropen > self.balance:\n print(\"NOT ENOUGH CASH to fill BUY order\")\n else:\n self.balance -= openorder.shares * curropen\n self.shares_total += openorder.shares\n else:\n self.balance += openorder.shares * curropen\n self.shares_total -= openorder.shares\n \n #get order for close price\n closeorder = self.strategy.close(curropen,self.balance,self.shares_total)\n if closeorder:\n if closeorder.buy:\n if closeorder.shares * currclose > self.balance:\n print(\"NOT ENOUGH CASH to fill BUY order\")\n else:\n self.balance -= closeorder.shares * currclose\n self.shares_total += closerorder.shares\n else:\n self.balance += closeorder.shares * currclose\n self.shares_total -= closeorder.shares\n \n #data keeping\n self.date_track.append(currdate)\n self.Portfolio_balance.append(self.balance + (self.shares_total * currclose))\n print(\"End portfolio value = \", self.balance + (self.shares_total * currclose))\n def portfolio_y_data(self):\n return self.Portfolio_balance\n def portfolio_x_data(self):\n return self.date_track\n def set_strategy (self, strategy):\n self.strategy = strategy"
},
{
"alpha_fraction": 0.5912842750549316,
"alphanum_fraction": 0.6054803729057312,
"avg_line_length": 37.83333206176758,
"blob_id": "0205c50c387f211c83f9e99441c585f12753d1c4",
"content_id": "e3ea98ef9d89d0af596fc4af55a23b4262b63b27",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6058,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 156,
"path": "/Strategies/Equal_weight/Momentum_Strategy.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport requests\nfrom scipy import stats\nimport xlsxwriter\nimport math\n\n'''This Python file implements an equal weight high momentum portfolio strategy based on the stocks included in the sp500.\nIt will extract data from IEX using its API.\nThe buy information will be output into a excel spreadsheet. It can easily be extended to work on a specfic broker service\n'''\n\n\n\n#function for portfolio input \ndef Portfolio_input():\n portfolio_balance = input('Enter portfolio value : ')\n try:\n val = float(portfolio_balance)\n except ValueError:\n print(\"Please enter a number\")\n portfolio_balance = input('Enter portfolio value : ')\n val = float(portfolio_balance)\n return val\n\n#This function calculates the number of shares to buy given a portfolio size and Panda dataframe\ndef calc_shares(portfolio_val,dataframe):\n position_size = portfolio_val/len(dataframe.index)\n num_shares = position_size\n for i in range(len(dataframe.index)):\n dataframe.loc[i,'Number of Shares to Buy'] = math.floor(position_size/dataframe.loc[i,'Price'])\n return dataframe\n# Function sourced from \n# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n] \n return\ndef main():\n from secrets import IEX_CLOUD_API_TOKEN\n sp500_list_csv_filepath = \"sp_500_stocks.csv\"\n sp500_stocklist = pd.read_csv(sp500_list_csv_filepath)\n my_columns = ['Ticker', 'Price', 'One-Year Price Return', 'Number of Shares to Buy']\n #create the strategy using quantitative momentum as our signal\n hqm_columns = [\n 'Ticker', 'Price', 'Number of Shares to Buy', '1-year Price Return', '1-year Return Percentile', \n '6-month Price Return', '6-month Return Percentile', '3-month Price Return', '3-month Return Percentile',\n '1-month Price Return', '1-month Return Percentile', 'HQM SCORE'\n ]\n base_url = 'https://sandbox.iexapis.com/stable'\n hqm_df = pd.DataFrame(columns = hqm_columns)\n symbol_groups = list(chunks(sp500_stocklist['Ticker'], 100))\n symbol_strings = []\n for i in range(0, len(symbol_groups)):\n symbol_strings.append(','.join(symbol_groups[i]))\n #extract stock data using API\n for stocklist in symbol_strings: \n request = f'/stock/market/batch?symbols={stocklist}&types=stats,quote&token={IEX_CLOUD_API_TOKEN}'\n final_url = base_url + request\n data = requests.get(final_url).json()\n for symbol in stocklist.split(','): \n price = data[symbol]['quote']['latestPrice']\n yearlyreturn = data[symbol]['stats']['year1ChangePercent']\n if yearlyreturn == None:\n yearlyreturn = 0\n month6return =data[symbol]['stats']['month6ChangePercent']\n if month6return == None:\n month6return = 0\n month3return = data[symbol]['stats']['month3ChangePercent']\n if month3return == None:\n month3return = 0\n monthreturn = data[symbol]['stats']['month1ChangePercent']\n if monthreturn == None:\n monthreturn = 0\n hqm_df = hqm_df.append(\n pd.Series([symbol, price, 'N/A',\n yearlyreturn, 'N/A',\n month6return, 'N/A',\n month3return, 'N/A',\n monthreturn, 'N/A','N/A'],index = hqm_columns), ignore_index=True,\n )\n \n #calculate percentile data for each stock\n time_periods = ['1-year','6-month', '3-month', '1-month']\n for row in hqm_df.index:\n for time_period in time_periods:\n hqm_df.loc[row,f'{time_period} Return Percentile'] = \\\n stats.percentileofscore(hqm_df[f'{time_period} Price Return'],hqm_df.loc[row,f'{time_period} Price Return'])\n \n hqm_df.sort_values('HQM SCORE',ascending = False, inplace=True)\n hqm_df = hqm_df[:50]\n hqm_df.reset_index(inplace=True,drop=True)\n pf_val = Portfolio_input()\n hqm_df = calc_shares(pf_val,hqm_df)\n \n #write to the excel file\n writer = pd.ExcelWriter('Momentum_strategy.xlsx',engine='xlsxwriter')\n hqm_df.to_excel(writer,sheet_name= \"buy\")\n background_color = '#ffffff'\n font_color = '#000000'\n\n string_template = writer.book.add_format(\n {\n 'font_color': font_color,\n 'bg_color': background_color,\n 'border': 1\n }\n )\n\n dollar_template = writer.book.add_format(\n {\n 'num_format':'$0.00',\n 'font_color': font_color,\n 'bg_color': background_color,\n 'border': 1\n }\n )\n\n integer_template = writer.book.add_format(\n {\n 'num_format':'0',\n 'font_color': font_color,\n 'bg_color': background_color,\n 'border': 1\n }\n )\n\n percent_template = writer.book.add_format(\n {\n 'num_format':'0.0%',\n 'font_color': font_color,\n 'bg_color': background_color,\n 'border': 1\n }\n )\n column_formats = {\n 'A': ['Ticker', string_template],\n 'B': ['Price', dollar_template],\n 'C':['Number of Shares to Buy', integer_template],\n 'D':['1-year Price Return', percent_template],\n 'E':['1-year Return Percentile', percent_template],\n 'F':['6-month Price Return', percent_template], \n 'G':['6-month Return Percentile', percent_template],\n 'H':['3-month Price Return', percent_template],\n 'I':['3-month Return Percentile', percent_template],\n 'J':['1-month Price Return', percent_template],\n 'K':['1-month Return Percentile', percent_template], \n 'L':['HQM SCORE', percent_template]\n}\n for column in column_formats.keys():\n writer.sheets['buy'].set_column(f'{column}:{column}',25,column_formats[column][1])\n writer.save()\n print(\"Finished\")\n return\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5540540814399719,
"alphanum_fraction": 0.5833333134651184,
"avg_line_length": 19.571428298950195,
"blob_id": "68eabb389d3136bad82a387a0e86717c9de21deb",
"content_id": "c9255db872615ac11ac41d501c9f2f7cc5b78e44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 444,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 21,
"path": "/BOSC_strategy.py",
"repo_name": "XushengZhao/Backtest_Platform",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 21 18:56:05 2020\n\n@author: Xzhao\n\"\"\"\nfrom Order_class import Order\n\nclass BOSC:\n \n def __init__(self):\n pass\n\n def open(self,curropen,balance,shares_cur):\n shares = int(balance / curropen)\n order = Order(True,shares)\n return order\n \n def close(self,currclose, balance,shares_cur):\n order = Order(False,shares_cur)\n return order\n\n\n\n \n"
}
] | 8 |
divyanshusahu/CodeMonk | https://github.com/divyanshusahu/CodeMonk | 768a207c77e772cf8ac41d1d31bcd7328f4ac16d | 5b2b9332e74dd05098d9d2f1a0ac90bd27f2f7f5 | d806396011b0ab8503449fc8ac30a27d131acac4 | refs/heads/master | 2020-04-09T12:29:20.492917 | 2019-11-25T17:24:28 | 2019-11-25T17:24:28 | 160,352,169 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4200819730758667,
"alphanum_fraction": 0.46413934230804443,
"avg_line_length": 16.428571701049805,
"blob_id": "c53a6646593255d14e95454c2e9a5fc500e82e44",
"content_id": "8706c1aab562ecbfe1c81d660cd112aba93c60e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 976,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 56,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Two Strings/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "// find minimum number of deletion required to make two strings anagram\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint posInt(int x)\n{\n if (x<0)\n return -x;\n return x;\n}\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n string s1, s2;\n cin>>s1>>s2;\n map<char, int> map_s1;\n map<char, int> map_s2;\n for (int i=0; i<s1.size(); i++)\n map_s1[s1[i]] = 0;\n for (int i=0; i<s1.size(); i++)\n map_s1[s1[i]] += 1;\n\n for (int i=0; i<s2.size(); i++)\n map_s2[s2[i]] = 0;\n for (int i=0; i<s2.size(); i++)\n map_s2[s2[i]] += 1;\n\n int flag = 0;\n map<char, int>::iterator it1 = map_s1.begin();\n while(it1 != map_s1.end())\n {\n if (map_s2.count(it1->first) == 0)\n {\n flag = 1;\n break;\n }\n else if (map_s1[it1->first] != map_s2[it1->first])\n {\n flag = 1;\n break;\n }\n it1++;\n }\n\n if (flag)\n cout<<\"NO\\n\";\n else\n cout<<\"YES\\n\";\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4501992166042328,
"alphanum_fraction": 0.47011953592300415,
"avg_line_length": 14.75,
"blob_id": "20ed4007f9e9f0a5c136b1685075df3a1d0cb066",
"content_id": "6ad8d960203410dc8949d4776f31cd81c364a87e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 251,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 16,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Conversion/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = int(raw_input())\n\twhile(t) :\n\t\ts = raw_input()\n\t\ts = s.lower()\n\t\tresult = ''\n\t\tfor i in s :\n\t\t\tif ord(i) == 32 :\n\t\t\t\tresult += '$'\n\t\t\t\tcontinue\n\t\t\tresult += str(ord(i) - 96)\n\t\tprint result\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.41329964995384216,
"alphanum_fraction": 0.43855220079421997,
"avg_line_length": 15.5,
"blob_id": "bd8277b13db89a1cbc6d06a172b7a777395e62b3",
"content_id": "416216a1782d0150b1c475e8779b110c22231e95",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1188,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 72,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Seating Arrangement/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "/*\n// Sample code to perform I/O:\n\ncin >> name; // Reading input from STDIN\ncout << \"Hi, \" << name << \".\\n\"; // Writing output to STDOUT\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n*/\n\n// Write your code here\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint isWindow(int x)\n{\n if (x%6 == 1 || x%6 == 0)\n return 1;\n return 0;\n}\n\nint isAsile(int x)\n{\n if (x%6 == 3 || x%6 == 4)\n return 1;\n return 0;\n}\n\nint isMiddle(int x)\n{\n if (x%6==2 || x%6 == 5)\n return 1;\n return 0;\n}\n\nint oppositeSeat(int x)\n{\n int y = x%12;\n if (y == 0)\n return x-11;\n int z = x/12;\n int os = 12 - y + 1;\n return 12*z + os;\n}\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int n;\n cin>>n;\n int opSeat = oppositeSeat(n);\n cout<<opSeat;\n if (isWindow(n))\n {\n cout<<\" WS\\n\";\n continue;\n }\n if (isMiddle(n))\n {\n cout<<\" MS\\n\";\n continue;\n }\n if (isAsile(n))\n {\n cout<<\" AS\\n\";\n continue;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.4593749940395355,
"alphanum_fraction": 0.4781250059604645,
"avg_line_length": 15.435897827148438,
"blob_id": "78d57daa05c6d8d7c51b548297bb03116400edb6",
"content_id": "81057f5cc8bbdcf13450235de946732bd6968f2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 640,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 39,
"path": "/InterviewBit/Array/Add One To Number/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> plusOne(vector<int> A) {\n unsigned int last = A.size() - 1;\n while(true) {\n if (last<0) {\n A.emplace(A.begin(),1);\n break;\n }\n A[last] = A[last] + 1;\n if (A[last] == 10) {\n A[last] = 0;\n last--;\n }\n else {\n break;\n }\n }\n while(true) {\n if (A[0] == 0) {\n A.erase(A.begin());\n }\n else {\n break;\n }\n }\n return A;\n}\n\nint main() {\n vector<int> v;\n v.assign(4,1);\n vector<int> answer = plusOne(v);\n for (auto iterator = v.begin(); iterator != v.end(); iterator++) {\n cout<<*iterator<<\" \";\n }\n return 0;\n}"
},
{
"alpha_fraction": 0.47043702006340027,
"alphanum_fraction": 0.5244215726852417,
"avg_line_length": 12.928571701049805,
"blob_id": "3fa9bf9da63e6e7de7470aea2aa9f5521ba8b340",
"content_id": "c9802c565c6746be9137264fad0b724d69b914b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 28,
"path": "/Hackerearth-CodeMonk/10-Hashing/Aman and lab file work/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint n;\n\tcin>>n;\n\n\tvector<int> total_time[2*1000000 + 1];\n\n\tfor (int i=1; i<=n; i++)\n\t{\n\t\tint ti, di;\n\t\tcin>>ti>>di;\n\t\ttotal_time[ti+di].push_back(i);\n\t}\n\n\tfor (int i=1; i<= 2*1000000; i++)\n\t{\n\t\tif (total_time[i].size())\n\t\t{\n\t\t\tfor (int k = 0; k<total_time[i].size(); k++)\n\t\t\t\tcout<<total_time[i].at(k)<<\" \";\n\t\t}\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.3333333432674408,
"alphanum_fraction": 0.34967321157455444,
"avg_line_length": 19.399999618530273,
"blob_id": "addd7144bad63a225a4922216b837607abdf1d82",
"content_id": "955d3f1658a15f8dd0bf628565d8c71a6b4c3a9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 15,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Bit Manipulation/Subham and Binary/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n t = int(raw_input())\n while(t) :\n n = int(raw_input())\n s = raw_input()\n \"\"\"count = 0\n for i in s :\n if i == '0' :\n count += 1\n print count\"\"\"\n print s.count('0')\n t -= 1\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.4314720928668976,
"alphanum_fraction": 0.45888325572013855,
"avg_line_length": 14.887096405029297,
"blob_id": "e4840f5ba943a83717a16695a34310ae59ca7e58",
"content_id": "b8cbe7b104762ab2bdbe4648aef44e80b22d0ebe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 985,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 62,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Implementation/Min-Max/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\nvoid check(int a[],int n,int x[]);\nint minimum(int a[],int n);\nint maximum(int a[],int n);\nint main() {\n // your code goes here\n int n;\n cin>>n;\n string ans=\"YES\";\n int a[n];\n for (int i=0;i<n;i++)\n cin>>a[i];\n int x[101];\n check(a,n,x);\n//\tfor (int i=0;i<101;i++)\n//\tcout<<x[i]<<\" \";\n int min=minimum(a,n);\n int max=maximum(a,n);\n for (int i=min;i<=max;i++)\n {\n if (x[i]==0)\n {\n ans=\"NO\";\n break;\n }\n }\n cout<<ans;\n\n return 0;\n}\nvoid check(int a[],int n,int x[])\n{\n int c[101];\n for (int i=0;i<101;i++)\n c[i]=0;\n for (int i=0;i<n;i++)\n c[a[i]]++;\n for (int i=0;i<101;i++)\n x[i]=c[i];\n}\nint minimum(int a[],int n)\n{\n int min=a[0];\n for (int i=1;i<n;i++)\n {\n if (a[i]<min)\n min=a[i];\n }\n return min;\n}\nint maximum(int a[],int n)\n{\n int max=a[0];\n for (int i=1;i<n;i++)\n {\n if (a[i]>max)\n max=a[i];\n }\n return max;\n}\n"
},
{
"alpha_fraction": 0.48065173625946045,
"alphanum_fraction": 0.48472505807876587,
"avg_line_length": 14.375,
"blob_id": "006eda7ed7df03af1519f6fa8a3122bb03dc6cd9",
"content_id": "c28ef671216e2ee54f7fa8379a08a8ec5235018f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 491,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 32,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/DNA Pride! /solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "import sys\n\ndef main() :\n\tt = int(raw_input())\n\twhile(t) :\n\t\ttry :\n\t\t\tn = int(raw_input())\n\t\texcept EOFError :\n\t\t\tbreak\n\t\ts = raw_input()\n\t\ts = s.upper()\n\t\tif s.find('U') >= 0 :\n\t\t\tprint 'Error RNA nucleobases found!'\n\t\t\tcontinue\n\n\t\tnew_string = ''\n\n\t\tfor i in s :\n\t\t\tif i == 'A' :\n\t\t\t\tnew_string += 'T'\n\t\t\telif i == 'T' :\n\t\t\t\tnew_string += 'A'\n\t\t\telif i == 'G' :\n\t\t\t\tnew_string += 'C'\n\t\t\telif i == 'C' :\n\t\t\t\tnew_string += 'G'\n\n\t\tprint new_string\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.33414044976234436,
"alphanum_fraction": 0.35593220591545105,
"avg_line_length": 16.25,
"blob_id": "917d2f1ad129e3f19b3066528356700c87950424",
"content_id": "5907c9830e82e1f45c1469594cc284a4c0a748f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 413,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 24,
"path": "/InterviewBit/Array/Noble Integer/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint solve(vector<int> &A)\n{\n sort(A.begin(), A.end());\n for (int i = 0; i < A.size() - 1; i++)\n {\n if (A[i] == A[i + 1])\n {\n continue;\n }\n int cur = A[i];\n if (cur == (A.size() - i - 1))\n {\n return 1;\n }\n }\n if (A[A.size() - 1] == 0)\n {\n return 1;\n }\n return -1;\n}"
},
{
"alpha_fraction": 0.4625668525695801,
"alphanum_fraction": 0.4839572310447693,
"avg_line_length": 14.625,
"blob_id": "fce2c94f1b04e1ab4ac2b5b0079935b79c6c0e38",
"content_id": "cc0a55a7cea74caa04d73c7e75a7249db2f168d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 374,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 24,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Help Oz/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint m;\n\tscanf(\"%d\", &m);\n\tint a[m];\n\tfor (int i=0;i<m;i++)\n\t\tscanf(\"%d\",&a[i]);\n\tsort(a,a+m);\n\tint min_dif = INT_MAX;\n\tfor (int i=0;i<m-1;i++)\n\t{\n\t\tif (a[i+1] - a[i] < min_dif)\n\t\t\tmin_dif = a[i+1] - a[i];\n\t}\n\tfor (int i=2;i<=(min_dif/2);i++)\n\t{\n\t\tif (min_dif%i==0)\n\t\t\tprintf(\"%d \",i);\n\t}\n\tprintf(\"%d\", min_dif);\n}"
},
{
"alpha_fraction": 0.36974790692329407,
"alphanum_fraction": 0.3907563090324402,
"avg_line_length": 26.176469802856445,
"blob_id": "6531c184605c59a296b56c1dc84137bf913c2eab",
"content_id": "8e456327ed0624b08d0b9f384f37df3a4b8c37c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 476,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 17,
"path": "/InterviewBit/Math/FizzBuzz/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "class Solution:\n # @param A : integer\n # @return a list of strings\n def fizzBuzz(self, A):\n ans = []\n for i in range(1, A+1) :\n if i%3==0 and i%5==0 :\n ans.append(\"FizzBuzz\")\n continue\n if i%3==0 :\n ans.append(\"Fizz\")\n continue\n if i%5==0 :\n ans.append(\"Buzz\")\n continue\n ans.append(i)\n return ans\n \n\n"
},
{
"alpha_fraction": 0.45215311646461487,
"alphanum_fraction": 0.46411484479904175,
"avg_line_length": 22.27777862548828,
"blob_id": "2a2b893720b0946ea611913a1012c63f75198987",
"content_id": "c1a2d4c2778fa67a396ea4cce9350d0868c3bd07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 418,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 18,
"path": "/InterviewBit/Array/Min Steps in Infinite Grid/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint coverPoints(vector<int> &A, vector<int> &B)\n{\n int min_distance = 0;\n for (int i = 0; i < A.size() - 1; i++)\n {\n int xi = A[i];\n int xf = A[i + 1];\n int yi = B[i];\n int yf = B[i + 1];\n int dx = abs(xf - xi);\n int dy = abs(yf - yi);\n min_distance += min(dx, dy) + abs(dx - dy);\n }\n return min_distance;\n}"
},
{
"alpha_fraction": 0.5189620852470398,
"alphanum_fraction": 0.5329341292381287,
"avg_line_length": 13.764705657958984,
"blob_id": "8d107250aa2e5c1a2bdba2953932de6505fd6fde",
"content_id": "bb6e6ba5a6b6bf25800e809394cd148090a10d6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 501,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 34,
"path": "/Hackerearth-CodeMonk/10-Hashing/Maximum occurrence/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tstring s;\n\tgetline(cin, s);\n\t\n\tmap<char, int> freq;\n\tfor (int i=0;i<s.length();i++)\n\t{\n\t\tif (freq.count(s[i]))\n\t\t\tfreq[s[i]]++;\n\t\telse\n\t\t\tfreq[s[i]] = 1;\n\t}\n\n\tint max = 0;\n\tint max_char = 128;\n\n\tmap<char, int>::iterator it = freq.begin();\n\twhile(it!=freq.end())\n\t{\n\t\tif ( (it->second > max) && (int(it->first) < max_char) )\n\t\t{\n\t\t\tmax = it->second;\n\t\t\tmax_char = int(it->first);\n\t\t}\n\t\tit++;\n\t}\n\tcout<<char(max_char)<<\" \"<<max;\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.32549020648002625,
"alphanum_fraction": 0.3529411852359772,
"avg_line_length": 11.75,
"blob_id": "78de298b05eb59cab0c6a27487a117101b58bbd7",
"content_id": "0157960bf22a7b7a9fe089523963f01c9c055332",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 255,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Implementation/Digit Problem/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n char x[19];\n cin>>x;\n int k;\n cin>>k;\n for (int i=0;k>0;i++)\n {\n if (x[i]!='9')\n {\n x[i]='9';\n k--;\n }\n }\n cout<<x;\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5324324369430542,
"alphanum_fraction": 0.5351351499557495,
"avg_line_length": 20.14285659790039,
"blob_id": "6288a10f685494624ff7587cee18c83deefb4d67",
"content_id": "f34f00b241e6f3f3c75daaefb2fb1f0a87e3707b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 740,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 35,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Roy and Profile Picture/solve.java",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "import java.util.Scanner;\nclass a\n{\n\tpublic static void main(String args[])\n\t{\n\t\tScanner in = new Scanner (System.in);\n\t\tint l=in.nextInt();\n\t\tint n=in.nextInt();\n\t\tint w,h;\n\t\t//int[] w = new int[n];\n\t\t//int[] h = new int[n];\n\t\t//for (int i=0;i<n;i++)\n\t\t//{\n\t\t//\tw[i]=in.nextInt();\n\t\t//\th[i]=in.nextInt();\n\t\t//}\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tw=in.nextInt();\n\t\t\th=in.nextInt();\n\t\t\tif (w<l || h<l)\n\t\t\tSystem.out.println(\"UPLOAD ANOTHER\");\n\t\t\telse if (w==h && w>=l)\n\t\t\tSystem.out.println(\"ACCEPTED\");\n\t\t\telse\n\t\t\tSystem.out.println(\"CROP IT\");\n\t\t//\tif (w[i]<l || h[i]<l)\n\t\t//\tSystem.out.println(\"UPLOAD ANOTHER\");\n\t\t//\telse if (w[i]==h[i] && w[i]>=l)\n\t\t//\tSystem.out.println(\"ACCEPTED\");\n\t\t//\telse\n\t\t//\tSystem.out.println(\"CROP IT\");\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.4816414713859558,
"alphanum_fraction": 0.49028077721595764,
"avg_line_length": 10.600000381469727,
"blob_id": "377a51f8e13eb819af3b76fcb6133b617be652e3",
"content_id": "9193ade4af9d713b61ec131421ca904b4e047e25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 463,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 40,
"path": "/Hackerearth-CodeMonk/10-Hashing/KK and crush/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint array[n];\n\t\tfor (int i=0;i<n;i++)\n\t\t\tcin>>array[i];\n\n\t\tmap<int, int> lookUp;\n\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tif (lookUp.count(array[i]))\n\t\t\t\tlookUp[array[i]]++;\n\t\t\telse\n\t\t\t\tlookUp[array[i]] = 1;\n\t\t}\n\n\t\tint k;\n\t\tcin>>k;\n\t\twhile(k--)\n\t\t{\n\t\t\tint x;\n\t\t\tcin>>x;\n\t\t\tif (lookUp.count(x))\n\t\t\t\tcout<<\"Yes\\n\";\n\t\t\telse\n\t\t\t\tcout<<\"No\\n\";\n\t\t}\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.33888888359069824,
"alphanum_fraction": 0.4166666567325592,
"avg_line_length": 24.714284896850586,
"blob_id": "0695a8080371555d805d9d4f15cb3032ff47d34e",
"content_id": "8bc5973cdefc10e9c4f92a4553676e2b3777f08f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 360,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 14,
"path": "/InterviewBit/Math/Reverse Integer/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "class Solution:\n # @param A : integer\n # @return an integer\n def reverse(self, A):\n ans = 0\n b = -2147483648\n if (str(A)[0] == \"-\") :\n ans = int(str(A)[0] + str(A)[1:][::-1])\n ans = int(str(A)[::-1])\n if ans > 2147483647 :\n return 0\n if b > ans :\n return 0\n return ans\n"
},
{
"alpha_fraction": 0.41842901706695557,
"alphanum_fraction": 0.4380664527416229,
"avg_line_length": 24.5,
"blob_id": "75cd6dcbcf78881f1d979637a007c2b5fc5e9938",
"content_id": "08c3e3f867264ea802d813feec476a16b8d41d8b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 662,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 26,
"path": "/InterviewBit/Hashing/Length of longest substring/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def lengthOfLongestSubstring(A):\n n = len(A)\n cur_len = 1\n max_len = 1\n prev_index = 0\n i = 0\n\n visited = [-1] * 256\n visited[ord(A[0])] = 0\n\n for i in range(1,n) :\n prev_index = visited[ord(A[i])]\n\n if prev_index == -1 or (i - cur_len > prev_index) :\n cur_len += 1\n else :\n if cur_len > max_len :\n max_len = cur_len\n cur_len = i - prev_index\n visited[ord(A[i])] = i\n if cur_len > max_len :\n max_len = cur_len\n\n return max_len\n\nprint(lengthOfLongestSubstring(\"deacadrtea\"))"
},
{
"alpha_fraction": 0.27586206793785095,
"alphanum_fraction": 0.28352490067481995,
"avg_line_length": 16.399999618530273,
"blob_id": "74b3d51c44d0543e5990d2c624e8ae45640a3fe9",
"content_id": "223e52d30b2492d545f038fda9d0f142acb51523",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 522,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 30,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Bit Manipulation/The Castle Gate/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n int t;\n cin>>t;\n while (t--)\n {\n int n;\n cin>>n;\n int count=0;\n for (int i=1;i<=n;i++)\n {\n for (int j=i+1;j<=n;j++)\n {\n int x = i^j;\n if (x <= n)\n {\n count++;\n // cout<<i<<\" \"<<j<<endl;\n }\n //cout<<(i^j)<<endl;\n }\n }\n cout<<count<<endl;\n }\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5121951103210449,
"alphanum_fraction": 0.5222381353378296,
"avg_line_length": 15.209301948547363,
"blob_id": "88107c820400ed75fe5834eed9a7a65957cd50a4",
"content_id": "413d0582e041de938d716fa9c9d9e51d0cb144a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 697,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 43,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Bricks Game/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "/*\n// Sample code to perform I/O:\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint num;\n\tcin >> num;\t\t\t\t\t\t\t\t\t\t// Reading input from STDIN\n\tcout << \"Input number is \" << num << endl;\t\t// Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n*/\n\n// Write your code here\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin>>n;\n int i = 1;\n int cur = 0;\n int flag = 1;\n while(cur<n)\n {\n cur += i;\n if (cur>=n)\n flag = 0;\n cur += i*2;\n i++;\n }\n if (flag == 0)\n cout<<\"Patlu\";\n else\n cout<<\"Motu\";\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.550684928894043,
"alphanum_fraction": 0.5835616588592529,
"avg_line_length": 16.428571701049805,
"blob_id": "55b6877cea7b25471a2fb835f7e82700be7c435c",
"content_id": "caf413f2e9158d1c59829052afa5981c5c9d2b82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 21,
"path": "/Hackerearth-CodeMonk/10-Hashing/The Monk and Kundan/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = input()\n\tstring = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\twhile(t) :\n\t\ttry :\n\t\t\ts = raw_input()\n\t\texcept EOFError :\n\t\t\tbreak\n\t\tx = s.split(' ')\n\t\tmul_factor = len(x)\n\t\tsum = 0\n\t\tfor i in x :\n\t\t\tfor j in range(len(i)) :\n\t\t\t\tsum += j + string.find(i[j])\n\n\t\tprint mul_factor*sum\n\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.5035605430603027,
"alphanum_fraction": 0.5076296925544739,
"avg_line_length": 13.909090995788574,
"blob_id": "e65e4792afe5d73a63ae028ee8ec1535b237b03d",
"content_id": "3fcc77d806fff0cf6dab1258c18c6a9c6d5a2fcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 983,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 66,
"path": "/Hackerearth-CodeMonk/10-Hashing/Difficult Characters/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring s;\n\t\tcin>>s;\n\n\t\tmap<char, int> lookUp;\n\t\tstring allChars = \"zyxwvutsrqponmlkjihgfedcba\";\n\n\t\tfor (int i=0; i<s.size(); i++)\n\t\t{\n\t\t\tif (lookUp.count(s[i]))\n\t\t\t\tlookUp[s[i]]++;\n\t\t\telse\n\t\t\t\tlookUp[s[i]] = 1;\n\t\t}\n\n\t\tfor (int i=0; i<allChars.size(); i++)\n\t\t{\n\t\t\tif (!lookUp.count(allChars[i]))\n\t\t\t\tcout<<allChars[i]<<\" \";\n\t\t}\n\n\t\tvector<int> freq;\n\n\t\tmap<char, int>::iterator it = lookUp.begin();\n\t\twhile (it != lookUp.end())\n\t\t{\n\t\t\tfreq.push_back(it->second);\n\t\t\tit++;\n\t\t}\n\n\t\tsort(freq.begin(), freq.end());\n\n\t\tauto vec_it = freq.begin();\n\n\t\twhile(vec_it != freq.end())\n\t\t{\n\t\t\tint cur_freq = *vec_it;\n\t\t\tvector<char> v;\n\t\t\tit = lookUp.begin();\n\t\t\twhile(it != lookUp.end())\n\t\t\t{\n\t\t\t\tif (it->second == cur_freq)\n\t\t\t\t\tv.push_back(it->first);\n\t\t\t\tit++;\n\t\t\t}\n\n\t\t\tsort(v.rbegin(), v.rend());\n\n\t\t\tfor (auto z = v.begin(); z!=v.end(); ++z)\n\t\t\t\tcout<<*z<<\" \";\n\n\t\t\tvec_it += v.size();\n\t\t}\n\t\tcout<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.42810457944869995,
"alphanum_fraction": 0.4346405267715454,
"avg_line_length": 11.75,
"blob_id": "bac4fe9d42e7d68a0302aeea1f973f6f07796ffe",
"content_id": "4ad01785cb0de6b9122ac12cda55c554d5fe68c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 24,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Ladderophilia/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid oneStepLadder()\n{\n cout<<\"* *\\n* *\\n*****\\n* *\\n* *\\n\";\n}\n\nvoid addSteps(int k)\n{\n while(k--)\n {\n cout<<\"*****\\n* *\\n* *\\n\";\n }\n}\n\nint main()\n{\n int n;\n cin>>n;\n oneStepLadder();\n addSteps(n-1);\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4189307689666748,
"alphanum_fraction": 0.4671340882778168,
"avg_line_length": 18.672412872314453,
"blob_id": "292717515102bced33c9a7e08e4a63d358c22228",
"content_id": "16d7041a70a1267bf1245147a6a2d0b3001dc4ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1141,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 58,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Anagrams/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint posInt(int x)\n{\n if (x<0)\n return -x;\n return x;\n}\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n string s1, s2;\n cin>>s1>>s2;\n map<char, int> map_s1;\n map<char, int> map_s2;\n for (int i=0; i<s1.size(); i++)\n map_s1[s1[i]] = 0;\n for (int i=0; i<s1.size(); i++)\n map_s1[s1[i]] += 1;\n\n for (int i=0; i<s2.size(); i++)\n map_s2[s2[i]] = 0;\n for (int i=0; i<s2.size(); i++)\n map_s2[s2[i]] += 1;\n\n int deletions = 0;\n map<char, int>::iterator it1 = map_s1.begin();\n while(it1 != map_s1.end())\n {\n //cout<<it1->first<<\" : \"<<it1->second<<endl;\n //it1++;\n if (map_s2.count(it1->first) == 0)\n {\n deletions += it1->second;\n }\n else if (map_s2.count(it1->first))\n {\n deletions += posInt(map_s1[it1->first] - map_s2[it1->first]);\n }\n it1++;\n }\n map<char, int>::iterator it2 = map_s2.begin();\n while(it2 != map_s2.end())\n {\n if (map_s1.count(it2->first) == 0)\n {\n deletions += it2->second;\n }\n it2++;\n }\n cout<<deletions<<endl;\n }\n}\n"
},
{
"alpha_fraction": 0.5108004808425903,
"alphanum_fraction": 0.531130850315094,
"avg_line_length": 15.416666984558105,
"blob_id": "bce3c53b60d5e655876ca381c43dd75feec505d3",
"content_id": "33111545b0ef411a4e846f1d96ea1e3f7ee0d6d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 787,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 48,
"path": "/Hackerearth-CodeMonk/10-Hashing/Cricket Balls/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tint a[n];\n\t\tfor (int i=0;i<n;i++)\n\t\t\tcin>>a[i];\n\t\tint k, count1, count2;\n\t\tcin>>k;\n\t\tcount1 = 0;\n\t\tcount2 = 0;\n\n\t\tmap<int, int> ball_lookup;\n\n\t\tfor (int i=0;i<n;i++)\n\t\t{\n\t\t\tif (ball_lookup.count(a[i]))\n\t\t\t\tball_lookup[a[i]]++;\n\t\t\telse\n\t\t\t\tball_lookup[a[i]] = 1;\n\t\t}\n\n\t\tmap<int, int>::iterator it = ball_lookup.begin();\n\t\twhile(it!= ball_lookup.end())\n\t\t{\n\t\t\tint cur = it->first;\n\t\t\tint req = k - cur;\n\n\t\t\tif (cur == req)\n\t\t\t\tcount1 += (ball_lookup[cur]*(ball_lookup[cur]-1))/2;\n\n\t\t\tif (ball_lookup.count(req) && cur != req)\n\t\t\t\tcount2 += ball_lookup[cur] * ball_lookup[req];\n\n\t\t\t//cout<<it->first<<\" \"<<it->second<<endl;\n\t\t\tit++;\n\t\t}\n\n\t\tcout<<(count1 + count2/2)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.39274924993515015,
"alphanum_fraction": 0.4290030300617218,
"avg_line_length": 16.421052932739258,
"blob_id": "674042b9383ff80c083089bf6ddb09a803e2445d",
"content_id": "5609773f73271b34d97ea05a25e63b5588b23345",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 331,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 19,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Book of Potion making/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def check(s) :\n if len(s) != 10 :\n return 0\n ts = 0\n for i in range(10) :\n ts += (i+1)*int(s[i])\n if ts % 11 != 0 :\n return 0\n return 1\n\ndef main() :\n s = raw_input()\n if check(s) :\n print 'Legal ISBN'\n else :\n print 'Illegal ISBN'\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.43113771080970764,
"alphanum_fraction": 0.443113774061203,
"avg_line_length": 13,
"blob_id": "fd2f95b49d64808aaef74d85520b287248a3ccad",
"content_id": "c442072a26b4bdfad5c493bd4f9f5e44f9ebfd0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 167,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 12,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Palindrome/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = int(raw_input())\n\twhile(t) :\n\t\ts = raw_input()\n\t\tif s == s[::-1] :\n\t\t\tprint \"YES\"\n\t\telse :\n\t\t\tprint \"NO\"\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.4583333432674408,
"alphanum_fraction": 0.48188406229019165,
"avg_line_length": 8.701754570007324,
"blob_id": "5a145117bad47634876c5b97db6d5aa63e0a0512",
"content_id": "0cd45583d2daddc5c0527e99224d3eb7c6e22f87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 552,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 57,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Mystery/solve_partial2.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool isPrime(int n)\n{\n\tfor (int i=2;i*i<=n;i++)\n\t{\n\t\tif (n%i==0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nint divisors(int n)\n{\n\tif (n==1)\n\t\treturn 1;\n\tif (isPrime(n))\n\t\treturn 2;\n\n\tint result = 1;\n\tint count = 0;\n\n\twhile(n>1)\n\t{\n\t\tfor (int i=2;i<=n;)\n\t\t{\n\t\t\tif (n%i==0)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\tn = n/i;\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\n\t\t\t\tresult *= (count+1);\n\t\t\t\tcount = 0;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tcout<<divisors(n)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4207221269607544,
"alphanum_fraction": 0.42700156569480896,
"avg_line_length": 19.54838752746582,
"blob_id": "109535d8f4ef6c89d97234fc74b53ff6c86549b7",
"content_id": "25e170efa4ab00b36bd8516ff2c869758753a1cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 31,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Best Index/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin>>n;\n int a[n];\n for (int i=0;i<n;i++)\n cin>>a[i];\n\n int bestSum = INT_MIN;\n for (int index=0; index<n; index++)\n {\n int curSum = a[index];\n int curIndex = index;\n for (int curTimes = 2; curIndex + curTimes <= n-1; curTimes++)\n {\n int x = curTimes;\n while(x--)\n {\n curIndex++;\n curSum += a[curIndex];\n //cout<<curIndex;\n }\n }\n if (curSum > bestSum)\n bestSum = curSum;\n }\n cout<<bestSum;\n}\n"
},
{
"alpha_fraction": 0.5021276473999023,
"alphanum_fraction": 0.5148935914039612,
"avg_line_length": 15.857142448425293,
"blob_id": "67f0758b1cfbe09651e2899ca9e60fec1e1a41d4",
"content_id": "79da54ff8768b6437e94143f51211dcc5dd06375",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 235,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 14,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Password/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = int(raw_input())\n\tpass_list = []\n\twhile(t) :\n\t\ts = raw_input()\n\t\tpass_list.append(s)\n\t\tt -= 1\n\tfor i in pass_list :\n\t\tif i[::-1] in pass_list :\n\t\t\tprint len(i), i[len(i)/2]\n\t\t\tbreak\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.3741007149219513,
"alphanum_fraction": 0.384892076253891,
"avg_line_length": 16.375,
"blob_id": "a37354b40a2b0c9e5479fbe76fdb50896bdca7a5",
"content_id": "e4b7aea85326ca62831fffef3ba220ca61199c26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 834,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 48,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/1-D/Team Selection/solve2.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong find(map<int, int> s, int a)\n{\n long c = 0;\n map<int, int>::iterator it = s.begin();\n while(it != s.end())\n {\n if (it->first > a)\n c += it->second;\n it++;\n }\n return c;\n}\n\nint main()\n{\n int n;\n cin>>n;\n int a[n], b[n];\n for (int i=0;i<n;i++)\n cin>>a[i];\n for (int i=0;i<n;i++)\n cin>>b[i];\n\n map<int, int> striker;\n for (int i=0;i<n;i++)\n {\n if (striker.count(b[i]) == 0)\n striker[b[i]] = 1;\n else\n striker[b[i]] = striker[b[i]] + 1;\n }\n\n long count;\n for (int i=0;i<n;i++)\n {\n for (int j=i+1;j<n;j++)\n {\n if (a[j]>a[i])\n {\n count += find(striker,a[j]);\n }\n }\n }\n cout<<count;\n}\n"
},
{
"alpha_fraction": 0.3967914581298828,
"alphanum_fraction": 0.4021390378475189,
"avg_line_length": 20.744186401367188,
"blob_id": "3ad3e9e155d2bdc6ab80de70f8a2f6bc5bc1f61b",
"content_id": "351eb989a37c14bf8718481051fa0636cd7eebb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 935,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 43,
"path": "/InterviewBit/Array/Max Non negative Sub Array/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> maxset(vector<int> &A)\n{\n int arr_start, arr_end, cur_start, cur_end;\n vector<int> answer;\n vector<int> cur;\n long long int max_sum = 0;\n long long int cur_sum = 0;\n for (int i = 0; i < A.size(); i++)\n {\n //cout<<cur_sum<<endl;\n if (A[i] >= 0)\n {\n cur_sum += A[i];\n cur.push_back(A[i]);\n }\n else\n {\n if (max_sum < cur_sum)\n {\n answer = cur;\n max_sum = cur_sum;\n }\n if (max_sum == cur_sum && answer.size() < cur.size())\n {\n answer = cur;\n }\n cur.clear();\n cur_sum = 0;\n }\n }\n if (cur_sum > max_sum)\n {\n answer = cur;\n }\n if (cur_sum == max_sum && answer.size() < cur.size())\n {\n answer = cur;\n }\n return answer;\n}\n"
},
{
"alpha_fraction": 0.33043476939201355,
"alphanum_fraction": 0.343478262424469,
"avg_line_length": 14.862069129943848,
"blob_id": "a10272d5797745a337a7b9089c1967b8341a2f94",
"content_id": "443360186df3f91008b358386a9704d692528090",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 460,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 29,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/1-D/Team Selection/solve1.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin>>n;\n long a[n], b[n];\n for (int i=0;i<n;i++)\n cin>>a[i];\n for (int i=0;i<n;i++)\n cin>>b[i];\n long count = 0;\n for (int i=0;i<n;i++)\n {\n for (int j=i+1;j<n;j++)\n {\n if (a[j]>a[i])\n {\n for (int k=0;k<n;k++)\n {\n if (b[k] > a[j])\n count++;\n }\n }\n }\n }\n cout<<count;\n}\n"
},
{
"alpha_fraction": 0.43515849113464355,
"alphanum_fraction": 0.4639769494533539,
"avg_line_length": 15.571428298950195,
"blob_id": "be76bde96c1087a99d88cb78516ea90262fd0f24",
"content_id": "48a22a2eae8d1b7b2c64a202caf216375bf6151e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 347,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 21,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Sumit's String/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = int(raw_input())\n\twhile(t) :\n\t\ttry :\n\t\t\ts = raw_input()\n\t\texcept EOFError :\n\t\t\tbreak\n\t\tf = 0\n\t\tfor i in range(len(s) - 1) :\n\t\t\tif abs(ord(s[i]) - ord(s[i+1])) != 1 and abs(ord(s[i]) - ord(s[i+1])) != 25 :\n\t\t\t\tprint 'NO'\n\t\t\t\tf = 1\n\t\t\t\tbreak\n\t\tif f :\n\t\t\tt -= 1\n\t\t\tcontinue\n\t\tprint 'YES'\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.4838709533214569,
"alphanum_fraction": 0.4985337257385254,
"avg_line_length": 12.15384578704834,
"blob_id": "27f0368aea20272bb64d5c5dad09a9747da46865",
"content_id": "86f72ec31675b2eec304a2ea0a7f0d5a8b2cf591",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 26,
"path": "/Hackerearth-CodeMonk/10-Hashing/All Vowels/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tn = input()\n\ts = raw_input()\n\tans = \"NO\"\n\n\tif s.find('a') == -1 :\n\t\tprint ans\n\t\treturn\n\tif s.find('e') == -1 :\n\t\tprint ans\n\t\treturn\n\tif s.find('i') == -1 :\n\t\tprint ans\n\t\treturn\n\tif s.find('o') == -1 :\n\t\tprint ans\n\t\treturn\n\tif s.find('u') == -1 :\n\t\tprint ans\n\t\treturn\n\n\tans = \"YES\"\n\tprint ans\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.5245535969734192,
"alphanum_fraction": 0.5334821343421936,
"avg_line_length": 15.629630088806152,
"blob_id": "7f6a43c87dcfeaf0a9461eeda2fafe843874b28c",
"content_id": "97b9f48a82d8d64c14f1b367aa97ba9744ab872f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 448,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 27,
"path": "/Hackerearth-CodeMonk/10-Hashing/Aman and lab file work/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "import sys\n\ndef main() :\n\tn = input()\n\tfreq = {}\n\tfor i in range(1,n+1) :\n\t\ts = raw_input()\n\t\ts = s.split(' ')\n\t\tti = int(s[0])\n\t\tdi = int(s[1])\n\t\tif (ti+di) not in freq :\n\t\t\tfreq[ti+di] = []\n\t\t\tfreq[ti+di].append(i)\n\t\telse :\n\t\t\tfreq[ti+di].append(i)\n\n\tsorted_time = sorted(freq)\n\n\tfor i in sorted_time :\n\t\torder = freq[i]\n\t\t#order.sort()\n\t\tfor o in order :\n\t\t\tsys.stdout.write(str(o))\n\t\t\tsys.stdout.write(' ')\t\t\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.2996894419193268,
"alphanum_fraction": 0.39906832575798035,
"avg_line_length": 33.83783721923828,
"blob_id": "8bf66b1a7104277a7b5158780df20270deb9c9a1",
"content_id": "b968e5eefb50657aa834785c74a071cd1b176eb0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1288,
"license_type": "no_license",
"max_line_length": 312,
"num_lines": 37,
"path": "/InterviewBit/Hashing/Two Sum/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def twoSum(A, B):\n hash_map = {}\n for i in A :\n hash_map[i] = []\n for i in range(len(A)) :\n hash_map[A[i]].append(i)\n \n ans = [10**10, 10**10]\n ini_ans = ans\n for i in hash_map:\n \tcur_ans = []\n \tif (B-i) in hash_map :\n \t\tindex1 = min(hash_map[i]) + 1\n \t\tindex2 = min(hash_map[B-i]) + 1\n \t\tif index1 == index2 and len(hash_map[i])==1 :\n \t\t\tcontinue\n \t\tif index1 == index2 :\n \t\t\tindex2 = sorted(hash_map[B-i])[1]+1\n \t\tcur_ans.append(index1)\n \t\tcur_ans.append(index2)\n \t\tcur_ans = sorted(cur_ans)\n \t\tif cur_ans[1] < ans[1] :\n \t\t\tans = cur_ans\n if ans == ini_ans :\n \tans = []\n \treturn ans\n if ans[0] == ans[1] and len(hash_map[B/2]) :\n \tans = []\n \tc = sorted(hash_map[B/2])\n \tans.append(c[0]+1)\n \tans.append(c[1]+1)\n\n return ans\n\na = (2, 5, 0, -6, 7, -4, 0, 4, 3, 0, -2, 0, 9, -3, -9, -3, 9, 3, 2, -10, -8, -3, -10, -5, 2, -8, 4, 5, 6, 7, -10, 4, -3, -10, 5, 4, 1, 5, 5, -3, -1, -8, -3, -6, -7, -8, -8, -7, 0, -2, 7, 7, 10, -7, -7, 10, -4, 0, 0, -6, -5, -5, 0, 8, 4, 1, 4, -1, -10, -4, -6, 10, -2, 9, -6, -3, -4, -1, 10, -9, -5, 10, -5, 8, 3)\nb = 0\nprint(twoSum(a,b))"
},
{
"alpha_fraction": 0.43968871235847473,
"alphanum_fraction": 0.4630350172519684,
"avg_line_length": 11.899999618530273,
"blob_id": "bce4f6777c08d9d551a09820b683960a83e5258e",
"content_id": "9b621aadce0ea063a631cd8538abe7fc9d57fbeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Palindromes/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\ts = raw_input()\n\tif s != s[::-1] :\n\t\tprint len(s)\n\t\treturn\n\n\tfreq = {}\n\tfor i in s :\n\t\tif i not in freq :\n\t\t\tfreq[i] = 1\n\t\telse :\n\t\t\tfreq[i] += 1\n\t\n\tif len(freq) == 1 :\n\t\tprint '0'\n\telse :\n\t\tprint len(s) - 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.5764192342758179,
"alphanum_fraction": 0.6026200652122498,
"avg_line_length": 10.5,
"blob_id": "70bf4e53f48c6aa19d1227fed91b5121438611b2",
"content_id": "45ec6e13f28d7f7fb2731451d3aa42a2315e30c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 229,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Love Triangle/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong long int solve(long long int n)\n{\n\tif (n<9)\n\t\treturn n;\n\treturn n%9 + 10*solve(n/9);\n}\n\nint main()\n{\n\tlong long int n;\n\twhile(cin>>n)\n\t{\n\t\tcout<<solve(n)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5130434632301331,
"alphanum_fraction": 0.52173912525177,
"avg_line_length": 9.5,
"blob_id": "aeeff18ec32806a29c80795f1d679221c177955d",
"content_id": "29b5a0c01eb6e67d3f7955ef29168601219ccdf5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 22,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Gas Stations/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint n,x;\n\tcin>>n>>x;\n\tint count = 0;\n\tint temp = x;\n\twhile(n--)\n\t{\n\t\tint p;\n\t\tcin>>p;\n\t\ttemp = temp - p;\n\t\tif (temp > 0)\n\t\t\tcount++;\n\t\telse\n\t\t\tbreak;\n\t}\n\n\tcout<<count;\n}"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5359477400779724,
"avg_line_length": 14.350000381469727,
"blob_id": "03cd9936caf74fc50e2c5bccba359113ca08ee0c",
"content_id": "878d3f8511d56f610660e3416c3bca243a0aacfd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Calculate the Power/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong int power(long int a, long int b, long int x)\n{\n\tif (b==0)\n\t\treturn 1;\n\tif (b%2==0)\n\t\treturn power( (a*a)%x, b/2, x );\n\treturn (a*power( (a*a)%x, (b-1)/2, x ))%x;\n\n}\n\nint main()\n{\n\tlong int a, b, x;\n\tcin>>a>>b;\n\tx = pow(10,9) + 7;\n\tcout<<power(a,b,x);\n}"
},
{
"alpha_fraction": 0.502267599105835,
"alphanum_fraction": 0.5170068144798279,
"avg_line_length": 20,
"blob_id": "329123b6506a222220c2b5359bc07ad72806aa44",
"content_id": "ee5a15390dbc9b7486cd993ffe9b365ac3bfa0a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 882,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 42,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Alice and Strings/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def checkPrefixLength(s1, s2) :\n length = 0\n for i,j in zip(s1, s2) :\n if i != j :\n length += 1\n if ord(i) > ord(j) :\n return 0\n\n return length\n\ndef increasebyone(s, l) :\n changed_string = ''\n for i in range(l) :\n if ord(s[i]) == 122 :\n return 0\n changed_string += chr(ord(s[i]) + 1)\n changed_string += s[l:]\n\n return changed_string\n\ndef main() :\n sa = raw_input()\n sb = raw_input()\n\n if len(sa) != len(sb) :\n print \"NO\"\n return\n\n prefixLength = checkPrefixLength(sa, sb)\n changed_sa = sa\n\n while(prefixLength and changed_sa != 0) :\n changed_sa = increasebyone(changed_sa, prefixLength)\n prefixLength = checkPrefixLength(changed_sa, sb)\n\n if changed_sa == sb :\n print \"YES\"\n else :\n print \"NO\"\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.39546599984169006,
"alphanum_fraction": 0.4382871389389038,
"avg_line_length": 12.724138259887695,
"blob_id": "2b49fc16a23fbe73ed9874a9105fe286386fdeb4",
"content_id": "d558320954748b0a331f8a96baa3964225d26c43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 397,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 29,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Caesar's Cipher/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def shift(s, k) :\n\tresult = ''\n\tfor i in s :\n\t\tli = ord(i) - 65\n\t\tls = (li + k) % 26\n\t\tls += 65\n\t\tresult += chr(ls)\n\treturn result\n\ndef main() :\n\t\tt = input()\n\t\twhile(t) :\n\t\t\ts1 = raw_input()\n\t\t\ts2 = raw_input()\n\t\t\tf = 0\n\n\t\t\tfor k in range(26) :\n\t\t\t\tru = shift(s1, k)\n\t\t\t\tif ru == s2 :\n\t\t\t\t\tprint k\n\t\t\t\t\tf = 1\n\t\t\t\t\tbreak\n\n\t\t\tif f == 0 :\n\t\t\t\tprint '-1'\n\t\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.42142024636268616,
"alphanum_fraction": 0.429569274187088,
"avg_line_length": 17.276596069335938,
"blob_id": "2c0ef467263080c83b8309cb22ab539f96cad65e",
"content_id": "78f35fd8b294ebd068d214474f258ad736dfe1e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 859,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 47,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/e-maze-in/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "/*\n// Sample code to perform I/O:\n\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n\tint num;\n\tcin >> num;\t\t\t\t\t\t\t\t\t\t// Reading input from STDIN\n\tcout << \"Input number is \" << num << endl;\t\t// Writing output to STDOUT\n}\n\n// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n*/\n\n// Write your code here\n\n#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n string s;\n cin>>s;\n int x = 0;\n int y = 0;\n for (int i=0; i<s.size(); i++)\n {\n switch(s[i])\n {\n case 'L' :\n x -= 1;\n break;\n case 'R' :\n x += 1;\n break;\n case 'D' :\n y -= 1;\n break;\n case 'U' :\n y += 1;\n break;\n }\n }\n cout<<x<<\" \"<<y;\n}\n"
},
{
"alpha_fraction": 0.375,
"alphanum_fraction": 0.3787878751754761,
"avg_line_length": 12.199999809265137,
"blob_id": "70240461d81a6a1b91ae4d8acb2009ed25b1107d",
"content_id": "a41e627236448d99794c8afa8cd58ce083939771",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 264,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Goki and his breakup/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int n;\n cin>>n;\n int s;\n cin>>s;\n while(n--)\n {\n int y;\n cin>>y;\n if (y>=s)\n cout<<\"YES\\n\";\n else\n cout<<\"NO\\n\";\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.45922747254371643,
"alphanum_fraction": 0.4914163053035736,
"avg_line_length": 13.353846549987793,
"blob_id": "6ecd12bdb79941a3efca69474e402a09e875d10c",
"content_id": "bb0582a37063f64a473e9b9630ddec59a9b4b8bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 932,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 65,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Mogu Loves Numbers/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvoid fastscan(int &number) \n{ \n bool negative = false; \n register int c; \n number = 0; \n \n c = getchar(); \n if (c=='-') \n { \n negative = true; \n c = getchar(); \n } \n\n for (; (c>47 && c<58); c=getchar()) \n number = number *10 + c - 48; \n\n if (negative) \n number *= -1; \n} \n\nbool isPrime(int n)\n{\n\tif (n==1)\n\t\treturn false;\n\tfor (int i=2;i*i<=n;i++)\n\t{\n\t\tif (n%i==0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nint main()\n{\n\tios_base::sync_with_stdio(false);\n\tint q;\n\t//cin>>q;\n\tfastscan(q);\n\tbool primes[1000001];\n\tprimes[0] = false;\n\tfor (int i=1;i<1000001;i++)\n\t\tprimes[i] = isPrime(i);\n\t\n\twhile(q--)\n\t{\n\t\tint l,r;\n\t\t//cin>>l>>r;\n\t\tfastscan(l);\n\t\tfastscan(r);\n\t\tint a,b;\n\t\ta = min(l,r);\n\t\tb = max(l,r);\n\t\tint count = 0;\n\t\tfor (int i=a;i<=b;i++)\n\t\t{\n\t\t\tif (primes[i])\n\t\t\t\tcount++;\n\t\t}\n\t\t//cout<<count<<\"\\n\";\n\t\tprintf(\"%d\\n\",count);\n\t}\n}"
},
{
"alpha_fraction": 0.34876543283462524,
"alphanum_fraction": 0.37345677614212036,
"avg_line_length": 22.178571701049805,
"blob_id": "d4fed2d31e91d64ff7a00b0977ce640ebfd0c311",
"content_id": "008ee9d1443880df1ecf531bc201738c77972a54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 648,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 28,
"path": "/InterviewBit/Hashing/Largest Continious sequence zero sum/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def lszero(A):\n\t hash_map = {}\n\t cur_sum = 0\n\t max_len = 0\n\t ans = []\n\t \n\t for i in range(len(A)) :\n\t cur_sum += A[i]\n\t \n\t if A[i] == 0 and max_len == 0 :\n\t max_len = 1\n\t ans.append(A[i])\n\t \n\t if cur_sum == 0 :\n\t max_len = i+1\n\t ans = A[:i+1]\n\t \n\t if cur_sum in hash_map :\n\t if max_len < (i-hash_map[cur_sum]) :\n\t max_len = i-hash_map[cur_sum]\n\t ans = A[hash_map[cur_sum]+1:i+1]\n\t else :\n\t hash_map[cur_sum] = i\n\t \n\t return ans\n\narr = [1, 2, -2, 0, 4, -4]\nprint(lszero(arr))"
},
{
"alpha_fraction": 0.35990530252456665,
"alphanum_fraction": 0.38279399275779724,
"avg_line_length": 15.671052932739258,
"blob_id": "c9b4593c8a5ddc70fdd7145931b5df0b351e97e7",
"content_id": "14051311ca5ecf389457e58c590282e2f4e6f395",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1267,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 76,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Magical Word/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint prime(int n)\n{\n for (int i=2;i*i<=n;i++)\n {\n if (n%i==0)\n return 0;\n }\n return 1;\n}\n\nint posInt(int x)\n{\n if (x<0)\n return -x;\n return x;\n}\n\nint minDistance(vector<int> x, int y)\n{\n int minDist = INT_MAX;\n int primeAscii;\n int dist;\n for (auto i = x.begin(); i != x.end(); ++i)\n {\n dist = posInt(*i - y);\n if (dist < minDist)\n {\n minDist = dist;\n primeAscii = *i;\n }\n }\n return primeAscii;\n}\n\nint main()\n{\n int t;\n cin>>t;\n vector<int> lookUp;\n\n for (int x=65; x<=90; x++)\n {\n if (prime(x))\n lookUp.push_back(x);\n }\n for (int y=97; y<=122; y++)\n {\n if (prime(y))\n lookUp.push_back(y);\n }\n while(t--)\n {\n int n;\n cin>>n;\n string s;\n cin>>s;\n string s1=\"\";\n for (int i=0;i<n;i++)\n {\n int x=(int)s[i];\n if ((prime(x)) && (x>=65 && x<=90) && (x>=97 && x<=122))\n s1 += s[i];\n else\n {\n int y = minDistance(lookUp, x);\n s1 += char(y);\n }\n }\n cout<<s1<<endl;\n }\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5252918004989624,
"alphanum_fraction": 0.5369649529457092,
"avg_line_length": 15.125,
"blob_id": "b100c877e7ebbe6c7280b7740cccb579abce8325",
"content_id": "1a4b4516095650f069749d207200ed49ecba1024",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 16,
"path": "/Hackerearth-CodeMonk/10-Hashing/Frequency of Students/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tn = input()\n\tfreq = {}\n\twhile(n) :\n\t\tname = raw_input()\n\t\tif name in freq :\n\t\t\tfreq[name] += 1\n\t\telse :\n\t\t\tfreq[name] = 1\n\t\tn -= 1\n\tsorted_keys = sorted(freq)\n\tfor key in sorted_keys :\n\t\tprint key, freq[key]\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.4749498963356018,
"alphanum_fraction": 0.49298596382141113,
"avg_line_length": 11.820512771606445,
"blob_id": "8f159ccbb357da2423335409d269f20a4e96104f",
"content_id": "26b296ad6e084d64f6e47bdba6a4b87cf5d986a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 499,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 39,
"path": "/Hackerearth-CodeMonk/10-Hashing/Xsquare And Palindromes Insertion/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring s;\n\t\tcin>>s;\n\t\tmap<char, int> lookUp;\n\n\t\tfor (int i=0; i<s.size(); i++)\n\t\t{\n\t\t\tif (lookUp.count(s[i]))\n\t\t\t\tlookUp[s[i]]++;\n\t\t\telse\n\t\t\t\tlookUp[s[i]] = 1;\n\t\t}\n\n\t\tint count = 0;\n\n\t\tmap<char, int>::iterator it = lookUp.begin();\n\t\twhile (it != lookUp.end())\n\t\t{\n\t\t\tif ( (it->second % 2) == 1)\n\t\t\t\tcount++;\n\t\t\tit++;\n\t\t}\n\n\t\tif (count == 0)\n\t\t\tcout<<\"0\\n\";\n\t\telse\n\t\t\tcout<<(count-1)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4767932593822479,
"alphanum_fraction": 0.48945146799087524,
"avg_line_length": 13,
"blob_id": "e71027aa224de9f272e8a05f4234d68f16f05173",
"content_id": "e184ae0744ff64ee549b67471cc2058c046dfbc3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 237,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 17,
"path": "/Hackerearth-CodeMonk/10-Hashing/N - Co Ordinates/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = input()\n\tfreq = {}\n\twhile(t) :\n\t\tn = raw_input()\n\t\tif n in freq :\n\t\t\tfreq[n] += 1\n\t\telse :\n\t\t\tfreq[n] = 1\n\t\tt -= 1\n\t\n\ts_freq = sorted(freq)\n\tfor key in s_freq :\n\t\tprint key, freq[key]\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.47902870178222656,
"alphanum_fraction": 0.5011037588119507,
"avg_line_length": 9.088889122009277,
"blob_id": "10859971dea0d34cd231c27987bfcd9643c9674e",
"content_id": "5d986746f3450595571b7db937240b077dd4e594",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 453,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 45,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Can you Guess ?/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nlong divisor_sum(int n)\n{\n\tif (n==1)\n\t\treturn 0;\n\t\n\tlong sum = 1;\n\tfor (int i=2;i<=n/2;i++)\n\t{\n\t\tif (n%i==0)\n\t\t\tsum += i;\n\t}\n\n\treturn sum;\n}\n\nbool isPrime(int n)\n{\n\tfor (int i=2;i*i<=n;i++)\n\t{\n\t\tif (n%i==0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nint main()\n{\n\tint q;\n\tcin>>q;\n\twhile(q--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tif (isPrime(n) && n!=1)\n\t\t{\n\t\t\tcout<<\"1\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tcout<<divisor_sum(n)<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.4742489159107208,
"alphanum_fraction": 0.4806866943836212,
"avg_line_length": 11.621622085571289,
"blob_id": "792819c882bbaebc95a64918d5f4829cc23d9f1b",
"content_id": "7ae76a0ade5ce294f1a75aecffa0561e583efcd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 466,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 37,
"path": "/Hackerearth-CodeMonk/10-Hashing/Xsquare And Double Strings/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring s;\n\t\tcin>>s;\n\n\t\tmap<char, int> freq;\n\n\t\tfor (int i=0;i<s.length();i++)\n\t\t{\n\t\t\tif (freq.count(s[i]))\n\t\t\t\tfreq[s[i]]++;\n\t\t\telse\n\t\t\t\tfreq[s[i]] = 1;\n\t\t}\n\n\t\tstring result = \"No\";\n\t\t map<char, int>::iterator it = freq.begin();\n\t\t while(it!=freq.end())\n\t\t {\n\t\t \tif (it->second >= 2)\n\t\t \t{\n\t\t \t\tresult = \"Yes\";\n\t\t \t\tbreak;\n\t\t \t}\n\t\t \tit++;\n\t\t }\n\n\t\t cout<<result<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.3642241358757019,
"alphanum_fraction": 0.3771551847457886,
"avg_line_length": 15.571428298950195,
"blob_id": "dea402ab0a908f5e1390824aacfe191d07cc3258",
"content_id": "e6ac2144b0f1257e91b1428aa6d45bd5f70a4294",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 464,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 28,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Bit Manipulation/Aish and Xor/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\nint main()\n{\n int n;\n cin>>n;\n int a[n];\n for (int i=0;i<n;i++)\n cin>>a[i];\n int t;\n cin>>t;\n while(t--)\n {\n int l,r;\n cin>>l>>r;\n int answer=a[l-1],count=0;\n if (a[l-1]==0)\n count++;\n for (int i=l;i<r;i++)\n {\n answer=answer^a[i];\n if (a[i]==0)\n count++;\n }\n cout<<answer<<\" \"<<count<<endl;\n }\n}\n"
},
{
"alpha_fraction": 0.5020747184753418,
"alphanum_fraction": 0.5103734731674194,
"avg_line_length": 12.416666984558105,
"blob_id": "45a0775e7450ad1ec725d81db431aa004c842de5",
"content_id": "1c9b34deeb83e49f5f86610fb1145c2dc81eb171",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 482,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 36,
"path": "/Hackerearth-CodeMonk/10-Hashing/N - Co Ordinates/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint n;\n\tcin>>n;\n\n\tvector<pair <int, int>> xy;\n\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tint x, y;\n\t\tcin>>x>>y;\n\t\txy.push_back(make_pair(x, y));\n\t}\n\n\tmap< pair<int, int>, int> freq;\n\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tif (freq.count(xy[i]))\n\t\t\tfreq[xy[i]]++;\n\t\telse\n\t\t\tfreq[xy[i]] = 1;\n\t}\n\n\tsort(xy.begin(), xy.end());\n\n\tint it = 0;\n\twhile(it<n)\n\t{\n\t\tcout<<xy[it].first<<\" \"<<xy[it].second<<\" \"<<freq[xy[it]]<<endl;\n\t\tit += freq[xy[it]];\n\t}\n}"
},
{
"alpha_fraction": 0.3122362792491913,
"alphanum_fraction": 0.3291139304637909,
"avg_line_length": 15.928571701049805,
"blob_id": "eebdfcd9b47924137a8737fbec95d711223b3681",
"content_id": "c668858c995249cbefcfb71c449f5d625ea6ee1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 237,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 14,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Capicúa/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n t = int(raw_input())\n while(t) :\n n = raw_input()\n n1 = n[::-1]\n\n if n == n1 :\n print \"YES\"\n else :\n print \"NO\"\n t -= 1\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.49128368496894836,
"alphanum_fraction": 0.5245642066001892,
"avg_line_length": 15.631579399108887,
"blob_id": "43c5494836e236effd8714aab493baade111e727",
"content_id": "2caa0fd3939ddddfaf96ba5b11c7a7f4f428c0b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 631,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 38,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Marut and Strings/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = raw_input()\n\ttry :\n\t\tt = int(t)\n\texcept :\n\t\tprint 'Invalid Test'\n\t\treturn\n\tif t<1 or t>10 :\n\t\tprint \"Invalid Test\"\n\t\treturn\n\twhile(t) :\n\t\ttry :\n\t\t\ts = raw_input()\n\t\texcept EOFError :\n\t\t\tbreak\n\t\tif len(s) > 100 :\n\t\t\tprint 'Invalid Input'\n\t\t\tbreak\n\t\talphabets_U = range(65,91)\n\t\talphabets_L = range(97,123)\n\t\tfreq = {}\n\t\tfreq['U'] = 0\n\t\tfreq['L'] = 0\n\t\tfor i in s :\n\t\t\tif ord(i) in alphabets_U :\n\t\t\t\tfreq['U'] += 1\n\t\t\telif ord(i) in alphabets_L :\n\t\t\t\tfreq['L'] += 1\n\n\t\tif freq['U'] + freq['L'] == 0 :\n\t\t\tprint 'Invalid Input'\n\t\telse :\n\t\t\tprint min(freq['U'], freq['L'])\n\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.5087108016014099,
"alphanum_fraction": 0.5354239344596863,
"avg_line_length": 14.122806549072266,
"blob_id": "6dc3f2ed60fce223d6ebacb4425a8127f1fc1ef4",
"content_id": "625273775ce0c0671fef6dcfb76a1853c96ecc61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 861,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 57,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/The Confused Monk/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint gcd(int a, int b)\n{\n\tif (b==0)\n\t\treturn a;\n\treturn gcd(b, a%b);\n}\n\nint gcd_of_n_numbers(int a[], int n)\n{\n\tif (n==1)\n\t\treturn a[0];\n\tint cur_gcd = gcd(a[0], a[1]);\n\tfor (int i=2; i<n;i++)\n\t{\n\t\tcur_gcd = gcd(cur_gcd,a[i]);\n\t\tif (cur_gcd == 1)\n\t\t\treturn 1;\n\t}\n\treturn cur_gcd;\n}\n\nlong int power(long int a, long int b, long int x)\n{\n\tif (b==0)\n\t\treturn 1;\n\telse if (b%2==0)\n\t\treturn power((a*a)%x, b/2, x);\n\telse\n\t\treturn (a*power((a*a)%x, (b-1)/2, x)%x);\n}\n\nint main()\n{\n\tint n;\n\t//cin>>n;\n\tscanf(\"%d\",&n);\n\tint a[n];\n\tfor (int i=0;i<n;i++)\n\t\tscanf(\"%d\",&a[i]);\n\n\tlong int result = 1;\n\tint arr_gcd = gcd_of_n_numbers(a, n);\n\tlong int me = pow(10,9)+7;\n\n\tfor (int i=0;i<n;i++)\n\t{\n\t\tlong int temp = power(a[i], arr_gcd,me);\n\t\tresult = (result * temp)%me;\n\t}\n\n\t//printf(\"%d\\n\", result);\n\tcout<<result;\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5175438523292542,
"alphanum_fraction": 0.5219298005104065,
"avg_line_length": 13.28125,
"blob_id": "1a6e9b5e35dcf9e9a89f89e150800b5bdec32312",
"content_id": "701cb8e03aa3e14279133bb1e2a1450e38802305",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 456,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 32,
"path": "/Hackerearth-CodeMonk/10-Hashing/Frequency of Students/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint n;\n\tcin>>n;\n\tvector<string> names;\n\twhile(n--)\n\t{\n\t\tstring s;\n\t\tcin>>s;\n\t\tnames.push_back(s);\n\t}\n\n\tsort(names.begin(), names.end());\n\n\tmap<string, int> freq;\n\n\tfor (auto i = names.begin(); i != names.end(); ++i)\n\t{\n\t\tif (freq.count(*i) == 0)\n\t\t\tfreq[*i] = 1;\n\t\telse\n\t\t\tfreq[*i]++;\n\t}\n\n\tfor (auto i = names.begin(); i != names.end(); i = i + freq[*i])\n\t{\n\t\tcout<<*i<<\" \"<<freq[*i]<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5218604803085327,
"alphanum_fraction": 0.5581395626068115,
"avg_line_length": 25.2439022064209,
"blob_id": "a96c3ccba14676bd03f4dd8a9723ef5fde286a73",
"content_id": "0e524fa7480cf11ef994088c9caf78fb39c4d9b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1079,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 41,
"path": "/InterviewBit/Hashing/Four Sum/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "# For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, \n# then your function should print “3 5 7 8” (3 + 5 + 7 + 8 = 23).\nimport itertools\ndef solveAnswers(A, B):\n ans = []\n for i in A:\n c = []\n for j in B:\n c = i+j\n if len(set(c)) == 4 :\n ans.append(c)\n return ans\n\ndef fourSum(A, B):\n n = len(A)\n pairSumMap = {}\n for i in range(n):\n for j in range(i+1, n):\n pairSumMap[A[i]+A[j]] = []\n for i in range(n) :\n for j in range(i+1, n) :\n pairSumMap[A[i]+A[j]].append([i,j])\n answers = []\n for i in pairSumMap:\n if (B-i) in pairSumMap:\n #print(pairSumMap[i], pairSumMap[B-i])\n answers += solveAnswers(pairSumMap[i], pairSumMap[B-i])\n original_answers = []\n for i in answers:\n c = sorted(i)\n if c not in original_answers:\n original_answers.append(c)\n #print(original_answers)\n solution = []\n for i in original_answers:\n a,b,c,d = A[i[0]],A[i[1]],A[i[2]],A[i[3]]\n solution.append(sorted([a,b,c,d]))\n return sorted(solution)\n\nA = [10, 2, 3, 4, 5, 9, 7, 8]\nprint(fourSum(A, 23))"
},
{
"alpha_fraction": 0.27262693643569946,
"alphanum_fraction": 0.3256070613861084,
"avg_line_length": 24.16666603088379,
"blob_id": "842b95fefd5c09f4d69b0d09ebe923938eae60bc",
"content_id": "e108792c8eaace102dbc2aea57a4d0edef238874",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 906,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 36,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Cipher/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def encrypt(s, k) :\n cipher = ''\n shift = range(48,58) + range(65,91) + range(97,123)\n for i in s :\n if ord(i) not in shift :\n cipher += i\n else :\n if ord(i) >= 65 and ord(i) <=90 :\n ke = k%26\n y = ord(i) + ke\n if y > 90 :\n y = y - 90 + 64\n cipher += chr(y)\n elif ord(i) >= 97 and ord(i) <= 122 :\n ke = k%26\n y = ord(i) + ke\n if y > 122 :\n y = y - 122 + 96\n cipher += chr(y)\n else :\n ke = k%10\n y = ord(i) + ke\n if y > 57 :\n y = y - 57 + 47\n cipher += chr(y)\n\n return cipher\n\n\ndef main() :\n s = raw_input()\n k = raw_input()\n print encrypt(s, int(k))\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.5795724391937256,
"alphanum_fraction": 0.5866983532905579,
"avg_line_length": 21.157894134521484,
"blob_id": "7d685ce3f97983f834400c3841af87fbcd1162e4",
"content_id": "84f3845b748bf983e3e08ceeb0771c5fca1716d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 421,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 19,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Char Sum/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "'''\n# Sample code to perform I/O:\n\nname = raw_input() # Reading input from STDIN\nprint 'Hi, %s.' % name # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n'''\n\n# Write your code here\ndef main() :\n s = raw_input()\n weight = 0\n for i in s :\n weight += ord(i) - 96\n print weight\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.5262515544891357,
"alphanum_fraction": 0.5323565602302551,
"avg_line_length": 14.185185432434082,
"blob_id": "c0219e99edab14f5c9fb5ad1f6322fe8f4880d17",
"content_id": "e4d740f0732c06d2a31462ed72aeb4b339df188d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 819,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 54,
"path": "/Hackerearth-CodeMonk/10-Hashing/Alien language/Bob and String/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\n\tstring s,t;\n\tcin>>s>>t;\n\n\tmap<char, int> freq_s, freq_t;\n\n\tfor (int i=0; i<s.size(); i++)\n\t{\n\t\tif (freq_s.count(s[i]))\n\t\t\tfreq_s[s[i]]++;\n\t\telse\n\t\t\tfreq_s[s[i]] = 1;\n\t}\n\n\tfor (int i=0; i<t.size(); i++)\n\t{\n\t\tif (freq_t.count(t[i]))\n\t\t\tfreq_t[t[i]]++;\n\t\telse\n\t\t\tfreq_t[t[i]] = 1;\n\t}\n\n\tint operations = 0;\n\n\tmap<char, int>::iterator it_t = freq_t.begin();\n\twhile (it_t != freq_t.end())\n\t{\n\t\tif (freq_s.count(it_t->first))\n\t\t\toperations += abs(freq_s[it_t->first] - freq_t[it_t->first]);\n\t\telse\n\t\t\toperations += it_t->second;\n\t\tit_t++;\n\t}\n\n\tmap<char, int>::iterator it_s = freq_s.begin();\n\twhile(it_s != freq_s.end())\n\t{\n\t\tif (!freq_t.count(it_s->first))\n\t\t\toperations += it_s->second;\n\t\tit_s++;\n\t}\n\n\tcout<<operations<<endl;\n\t}\n}"
},
{
"alpha_fraction": 0.5504587292671204,
"alphanum_fraction": 0.5557701587677002,
"avg_line_length": 18.009174346923828,
"blob_id": "eb83e73f456e9667061f887f502a02ab595c20bb",
"content_id": "4a4254d073d75ac87e396492d15068ac3d224e20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2071,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 109,
"path": "/Hackerearth-CodeMonk/10-Hashing/Crushing Violence/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\n\t\tmap<int, int> boys, girls;\n\n\t\tfor (int i=1;i<=n;i++)\n\t\t{\n\t\t\tint x;\n\t\t\tcin>>x;\n\t\t\tboys[i] = x;\n\t\t}\n\n\t\tfor (int i=1;i<=n;i++)\n\t\t{\n\t\t\tint x;\n\t\t\tcin>>x;\n\t\t\tgirls[i] = x;\n\t\t}\n\n\t\tmap< pair<int, int>, int> beating_boys_pair, beating_girls_pair;\n\t\tmap<int, int> poor_boys, poor_girls;\n\n\t\tmap<int, int>::iterator itb = boys.begin();\n\t\twhile( itb != boys.end() )\n\t\t{\n\t\t\tif (girls[itb->second] != itb->first)\n\t\t\t\t{\n\t\t\t\t\tbeating_boys_pair[make_pair(itb->first, girls[itb->second])] = 1;\n\t\t\t\t\tif (poor_boys.count(girls[itb->second]))\n\t\t\t\t\t\tpoor_boys[girls[itb->second]]++;\n\t\t\t\t\telse\n\t\t\t\t\t\tpoor_boys[girls[itb->second]] = 1;\n\t\t\t\t}\n\t\t\titb++;\n\t\t}\n\n\t\tint count_each = 0;\n\t\tint poorb = 0;\n\n\t\tmap< pair<int, int>, int>::iterator bbp = beating_boys_pair.begin();\n\t\twhile (bbp!=beating_boys_pair.end())\n\t\t{\n\t\t\tint a = (bbp->first).first;\n\t\t\tint b = (bbp->first).second;\n\n\t\t\tif (beating_boys_pair.count(make_pair(b,a)))\n\t\t\t\tcount_each++;\n\t\t\tbbp++;\n\t\t}\n\n\t\tmap<int, int>::iterator pb = poor_boys.begin();\n\t\twhile(pb!=poor_boys.end())\n\t\t{\n\t\t\tif (pb->second > poorb)\n\t\t\t\tpoorb = pb->second;\n\t\t\tpb++;\n\t\t}\n\n\t\t//cout<<poorb<<\" \"<<count_each;\n\n\t\tmap<int, int>::iterator itg = girls.begin();\n\t\twhile(itg!=girls.end())\n\t\t{\n\t\t\tif (boys[itg->second] != itg->first)\n\t\t\t{\n\t\t\t\tbeating_girls_pair[make_pair(itg->first, boys[itg->second])] = 1;\n\t\t\t\tif (poor_girls.count(boys[itg->second]))\n\t\t\t\t\tpoor_girls[boys[itg->second]]++;\n\t\t\t\telse\n\t\t\t\t\tpoor_girls[boys[itg->second]] = 1;\n\t\t\t}\n\t\t\titg++;\n\t\t}\n\n\t\tint poorg = 0;\n\n\t\tmap< pair<int, int>, int>::iterator bgp = beating_girls_pair.begin();\n\t\twhile(bgp!=beating_girls_pair.end())\n\t\t{\n\t\t\tint a = (bgp->first).first;\n\t\t\tint b = (bgp->first).second;\n\n\t\t\tif (beating_girls_pair.count(make_pair(b,a)))\n\t\t\t\tcount_each++;\n\t\t\tbgp++;\n\t\t}\n\n\t\tmap<int, int>::iterator pg = poor_girls.begin();\n\t\twhile(pg!=poor_girls.end())\n\t\t{\n\t\t\tif (pg->second > poorg)\n\t\t\t\tpoorg = pg->second;\n\t\t\tpg++;\n\t\t}\n\n\t\tcout<<max(poorg, poorb)<<\" \"<<(count_each/2)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.39413681626319885,
"alphanum_fraction": 0.3973941504955292,
"avg_line_length": 18.1875,
"blob_id": "3d0c1fa672f13dc7d17a9d69798e15978612be11",
"content_id": "085d86537efde0c9c9ed1591225013f109ae24b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 307,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 16,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Print first Occurence/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "import sys\n\ndef main() :\n t = int(raw_input())\n while(t) :\n s = raw_input()\n present = []\n for i in s :\n if i not in present :\n sys.stdout.write(i)\n present.append(i)\n print ''\n t -= 1\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.47438016533851624,
"alphanum_fraction": 0.48264461755752563,
"avg_line_length": 10.65384578704834,
"blob_id": "be353a59f22aa28743438a026e10dc71f85ca131",
"content_id": "e6856fbc8aeaf50d7f5da05b2f6c863de9b01632",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 605,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 52,
"path": "/Hackerearth-CodeMonk/10-Hashing/Pair Sums/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint n, k;\n\tcin>>n>>k;\n\tint a[n];\n\tfor (int i=0; i<n; i++)\n\t\tcin>>a[i];\n\n\tmap<int, int> freq;\n\n\tfor (int i=0; i<n; i++)\n\t{\n\t\tif (freq.count(a[i]))\n\t\t\tfreq[a[i]]++;\n\t\telse\n\t\t\tfreq[a[i]] = 1;\n\t}\n\n\tmap<int, int>::iterator it = freq.begin();\n\tstring result = \"NO\";\n\n\twhile(it != freq.end())\n\t{\n\t\tint cur = it->first;\n\t\tint req = k - cur;\n\n\t\tif (cur == req)\n\t\t{\n\t\t\tif (freq[req] >= 2)\n\t\t\t{\n\t\t\t\tresult = \"YES\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (freq.count(req))\n\t\t{\n\t\t\tresult = \"YES\";\n\t\t\tbreak;\n\t\t}\n\t\tit++;\n\t}\n\n\tcout<<result;\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.4595959484577179,
"alphanum_fraction": 0.46464645862579346,
"avg_line_length": 18.899999618530273,
"blob_id": "f2a2e232e5492839c79154f7f84180c18b24eae8",
"content_id": "1f7f0eaae8eacb1d29a86c2657ef0c27b331fc55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 198,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 10,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/VowelPhobia/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n\tt = int(raw_input())\n\twhile(t) :\n\t\ts = raw_input()\n\t\tv = s.count('a') + s.count('e') + s.count('i') + s.count('o') + s.count('u')\n\t\tprint v\n\t\tt -= 1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.4736842215061188,
"alphanum_fraction": 0.4917293190956116,
"avg_line_length": 9.40625,
"blob_id": "4528b47544528a8d29dd1c6671ed28d5881b6bf4",
"content_id": "c8024f60c4a3e2acc9af5bb2f104738c84ca8c23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 665,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 64,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Mystery/solve_partial1.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nbool isPrime(int n)\n{\n\tfor (int i=2;i*i<=n;i++)\n\t{\n\t\tif (n%i==0)\n\t\t\treturn false;\n\t}\n\treturn true;\n}\n\nint divisors(int n)\n{\n\tif (n==1)\n\t\treturn 1;\n\tif (isPrime(n))\n\t\treturn 2;\n\t\n\tmap<int, int> div;\n\n\twhile(n>1)\n\t{\n\t\tfor (int i=2;i<=n;)\n\t\t{\n\t\t\tif (n%i==0)\n\t\t\t{\n\t\t\t\tif (div.count(i))\n\t\t\t\t\tdiv[i]++;\n\t\t\t\telse\n\t\t\t\t\tdiv[i] = 1;\n\t\t\t\tn = n/i;\n\t\t\t}\n\t\t\telse\n\t\t\t\ti++;\n\t\t}\n\t}\n\n\tint result = 1;\n\n\tmap<int, int>::iterator it = div.begin();\n\twhile(it!=div.end())\n\t{\n\t\tresult *= (it->second+1);\n\t\tit++;\n\t}\n\n\treturn result;\n}\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tcout<<divisors(n)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.5053957104682922,
"alphanum_fraction": 0.5269784331321716,
"avg_line_length": 16.375,
"blob_id": "2abf4dad0b2793ced17ef938b1f331df6c9f4eef",
"content_id": "ffd4540ebb7ac385020ed3a521841430a2b19fe2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 556,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 32,
"path": "/Hackerearth-CodeMonk/2-Array and Strings/Basics of String Manipulation/Monk Teaches Palindrome/solve.java",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "import java.util.Scanner;\nclass a\n{\n\tpublic static void main (String args[])\n\t{\n\t\tScanner in = new Scanner (System.in);\n\t\tint t=in.nextInt();\n\t\tint c=0;\n\t\tfor (int i=0;i<t;i++)\n\t\t{\n\t\t\tString s=in.nextLine();\n\t\t\tif (c==0){\n\t\t\ts=in.nextLine(); c=1; }\n\t\t\tint l=s.length();\n\t\t\tint flag=1;\n\t\t\tfor (int j=0,k=l-1;j<(l/2);j++,k--)\n\t\t\t{\n\t\t\t\tif (s.charAt(j)!=s.charAt(k))\n\t\t\t\t{\n\t\t\t\t\tflag=0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (flag==0)\n\t\t\tSystem.out.println(\"NO\");\n\t\t\telse if (l%2==0)\n\t\t\tSystem.out.println(\"YES EVEN\");\n\t\t\telse\n\t\t\tSystem.out.println(\"YES ODD\");\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.4927953779697418,
"alphanum_fraction": 0.5187320113182068,
"avg_line_length": 8.942856788635254,
"blob_id": "c944c3a96d425a94aadf86a92e11ca3e5e74257a",
"content_id": "7cbfc33834156172ec281544542e055f6d78eaf9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 347,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 35,
"path": "/Hackerearth-CodeMonk/6-Number Theory/Basic Number Theory-1/Mystery/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint divisor(int n)\n{\n\tif (n==1)\n\t\treturn 1;\n\t\n\tint count = 0;\n\tfor (int i=1;i*i<=n; i++)\n\t{\n\t\tif (n%i==0)\n\t\t\tcount++;\n\t}\n\n\tint x = sqrt(n);\n\tif (x*x==n)\n\t\treturn 2*count-1;\n\n\treturn 2*count;\n}\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint n;\n\t\tcin>>n;\n\t\tcout<<divisor(n)<<endl;\n\t}\n\n\treturn 0;\n}"
},
{
"alpha_fraction": 0.39045554399490356,
"alphanum_fraction": 0.41431671380996704,
"avg_line_length": 11.80555534362793,
"blob_id": "a4e94921d43bee9cbd5d9bf6e666a3969003f71b",
"content_id": "fb66a00624aac683d7b6c6f350889a11f264686e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 461,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 36,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Time and Space Complexity/Prime Minister's Number/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint digitsum(int n)\n{\n int sum = 0;\n while(n>0)\n {\n sum += n%10;\n n /= 10;\n }\n return sum;\n}\n\nint isPrime(int n)\n{\n for (int i=2;i*i<=n;i++)\n {\n if(n%i == 0)\n return 0;\n }\n return 1;\n}\n\nint main()\n{\n int a,b;\n cin>>a>>b;\n\n for (int i=a; i<=b; i++)\n {\n if (isPrime(i) && isPrime(digitsum(i)))\n cout<<i<<\" \";\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.4111405909061432,
"alphanum_fraction": 0.4190981388092041,
"avg_line_length": 18.789474487304688,
"blob_id": "caeb825e11e15634549b394b1963831158421c07",
"content_id": "214682b56901398c42dca0de149ba184e7905165",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 377,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 19,
"path": "/InterviewBit/Math/Prime Sum/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "bool isPrime(int n) {\n for (int i=2; i*i<=n; i++) {\n if (n%i==0) {\n return false;\n }\n }\n return true;\n}\n\nvector<int> Solution::primesum(int A) {\n vector<int> ans;\n for (int i=2; i<A; i++) {\n if (isPrime(i) && isPrime(A-i)) {\n ans.push_back(i);\n ans.push_back(A-i);\n return ans;\n }\n }\n}\n\n"
},
{
"alpha_fraction": 0.41516709327697754,
"alphanum_fraction": 0.4215938448905945,
"avg_line_length": 21.882352828979492,
"blob_id": "729d9ed2e3fa840d78f3b9e7317eb686dcd1c63d",
"content_id": "f25b3c9ba59cd1686aed963242c5f5df748879da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 778,
"license_type": "no_license",
"max_line_length": 174,
"num_lines": 34,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Time and Space Complexity/Vowel Recognition/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint findVowles(string s)\n{\n transform(s.begin(), s.end(), s.begin(), ::tolower);\n int sum = 0;\n sum += count(s.begin(), s.end(), 'a') + count(s.begin(), s.end(), 'e') + count(s.begin(), s.end(), 'i') + count(s.begin(), s.end(), 'o') + count(s.begin(), s.end(), 'u');\n\n return sum;\n}\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n string s;\n cin>>s;\n string sub;\n long count = 0;\n for (int i = 0; i < s.length(); i++)\n {\n for (int len = 1; len <= s.length() - i; len++)\n {\n sub = s.substr(i, len);\n count += findVowles(sub);\n }\n }\n cout<<count<<endl;\n }\n return 0;\n}\n"
},
{
"alpha_fraction": 0.5302826166152954,
"alphanum_fraction": 0.539703905582428,
"avg_line_length": 14.183673858642578,
"blob_id": "b9b02e35112724c7b43aceeae037890e63f44f9c",
"content_id": "cb9eccff7498398c99c074a1467e256cf23f4641",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 743,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 49,
"path": "/Hackerearth-CodeMonk/10-Hashing/Alien language/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tstring text, pattern;\n\t\tcin>>text>>pattern;\n\n\t\tmap<char, int> map_text, map_pattern;\n\n\t\tfor (int i=0; i<text.length(); i++)\n\t\t{\n\t\t\tif (map_text.count(text[i]))\n\t\t\t\tmap_text[text[i]] += 1;\n\t\t\telse\n\t\t\t\tmap_text[text[i]] = 1;\n\t\t}\n\n\t\tfor (int i=0; i<pattern.length(); i++)\n\t\t{\n\t\t\tif (map_pattern.count(pattern[i]))\n\t\t\t\tmap_pattern[pattern[i]] += 1;\n\t\t\telse\n\t\t\t\tmap_pattern[pattern[i]] = 1;\n\t\t}\n\n\t\tmap<char, int>::iterator it = map_pattern.begin();\n\t\tstring result = \"YES\";\n\t\t\n\t\twhile (it != map_pattern.end())\n\t\t{\n\t\t\tif (map_text.count(it->first) == 0)\n\t\t\t{\n\t\t\t\tresult = \"NO\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t\tbreak;\n\t\t\tit++;\n\t\t}\n\n\t\tcout<<result<<endl;\n\n\t}\n}"
},
{
"alpha_fraction": 0.3349282443523407,
"alphanum_fraction": 0.3444976210594177,
"avg_line_length": 19.899999618530273,
"blob_id": "3cd534b3beac5cf975c6cc70eb98b52b36029580",
"content_id": "0f38bebb2d158fac2a9546428f9c4891afceb75b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 20,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Operators/Let us Understand Computer/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def main() :\n t = int(raw_input())\n while(t) :\n n = int(raw_input())\n div = 1\n while(True) :\n q = n/div\n blen_div = len(bin(div))\n blen_q = len(bin(q))\n if blen_q > blen_div :\n div += 1\n continue\n else :\n break\n\n print (n-div+1)\n t -= 1\n\nif __name__ == \"__main__\" :\n main()\n"
},
{
"alpha_fraction": 0.46948355436325073,
"alphanum_fraction": 0.48356807231903076,
"avg_line_length": 17.521739959716797,
"blob_id": "1e717b567ae5a034f4f977977611418d69516f8f",
"content_id": "40926efbc160fbd9cce238b6e902cbea092e963f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 426,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 23,
"path": "/InterviewBit/Hashing/Fraction/solve.py",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "def fraction(n,d):\n q = n/d\n r = n%d\n hash_map = {}\n solution = str(q)\n isRap = False\n rep = \"\"\n while r != 0:\n x = r*10\n r = x%d\n q = x/d\n if r in hash_map:\n isRap = True\n break\n hash_map[r] = 1\n rep += str(q)\n if rep != \"\" and isRap:\n solution = solution + \".\" + \"(\" + rep + \")\"\n if rep != \"\" and not isRap:\n solution = solution + \".\" + rep\n return solution\n\nprint(fraction(5,8))\n"
},
{
"alpha_fraction": 0.33791208267211914,
"alphanum_fraction": 0.34890109300613403,
"avg_line_length": 14.82608699798584,
"blob_id": "abea73aa04c4168bb8c5932e5dd21605ab4a3e08",
"content_id": "4f332fc3393ccb792530f3df60a7eda6c90e4aff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 364,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 23,
"path": "/Hackerearth-CodeMonk/1-Basics of Programming/Basics of Input\\Output/Duration/solve.cpp",
"repo_name": "divyanshusahu/CodeMonk",
"src_encoding": "UTF-8",
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n int t;\n cin>>t;\n while(t--)\n {\n int sh, sm, eh, em;\n cin>>sh>>sm>>eh>>em;\n int th, tm;\n th = eh - sh;\n tm = em - sm;\n if (tm < 0)\n {\n th--;\n tm = 60 + tm;\n }\n cout<<th<<\" \"<<tm<<endl;\n }\n return 0;\n}\n"
}
] | 77 |
JoseEvanan/frikr | https://github.com/JoseEvanan/frikr | 6ce823cc81bfe6b1cdcd073704571f1cb222b8b9 | 6c02ad2f6213b53ad7a387a9ab5156fbb63d9cb3 | b2dbcbc305b6811a12ba0adbc6887812be192347 | refs/heads/master | 2020-04-01T19:40:58.532713 | 2018-10-29T05:18:43 | 2018-10-29T05:18:43 | 153,566,490 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "54dbc97977ea7c64f5bc3e0e64f34eec2034f0e2",
"content_id": "71b09d09b402dc9bfed1209f8515c7c461fb1c62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/fnmatch.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/fnmatch.py"
},
{
"alpha_fraction": 0.7250000238418579,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 40,
"blob_id": "df199dbe51535a1aa13879849941788e2ae41369",
"content_id": "3c3d6d93c003de99626a589557a86f6f2a870e69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 40,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 1,
"path": "/env/lib/python3.6/re.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/re.py"
},
{
"alpha_fraction": 0.760869562625885,
"alphanum_fraction": 0.8260869383811951,
"avg_line_length": 46,
"blob_id": "51068a16c2ab5b0db3fb80befbf5f2bd76ae677d",
"content_id": "7923f428c1f83d183a7317245ea594eec0d2e2fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 1,
"path": "/env/lib/python3.6/operator.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/operator.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "408e8bb65191098efba6a864ec1cd27fbc6ed23d",
"content_id": "da412a8586bf13f132507d2f24407a95d58d9e68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/struct.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/struct.py"
},
{
"alpha_fraction": 0.6212023496627808,
"alphanum_fraction": 0.6231415867805481,
"avg_line_length": 32.65217208862305,
"blob_id": "b4fc629e5abdf602a0252f7155bf218a98d2951d",
"content_id": "e54bb6c40c6e6459eeee7c1b9a22cea6a0b91220",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1547,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 46,
"path": "/users/permissions.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "from rest_framework.permissions import BasePermission\n\n\n\n\nclass UserPermission(BasePermission):\n def has_permission(self, request, view):\n \"\"\"\n Priemro en ejecutarse\n\n DEfine si el usuario authenticado en request.user tiene permiso para realizar el (GET, POST, PUT o DELETE)\n :param request:\n :param view:\n :return:\n \"\"\"\n from users.api import UserDetailAPI\n #Si quiere crear u usuario sea quien sea, debe poder crearlo\n if request.method == \"POST0\":\n return True\n #si es superuser, puede acer lo que quiera\n elif request.user.is_superuser:\n return True\n # si no es POST( es GET, PUT o DELETE), el usuario no es superuser\n # la peticion va a la vista de detalle, entonces lo permitimos\n # para tomar la decision en el metodo has_object_permission\n elif isinstance(view, UserDetailAPI):\n return True\n #si la peticion es un GET de listado, o lo permitimos (porque s llega\n #aqui, el usuario o es superusuario y solo pueden los superuser)\n else:\n #GEt a /api/1.0/photos\n return False\n\n\n def has_object_permission(self, request, view, obj):\n \"\"\"\n Segundo en ejecutarse\n\n SI el usuario authenticado tiene permissio para realizar la accion (GEt, PUT o DELETE)sobre el objeto obj\n\n :param request:\n :param view:\n :param obj:\n :return:\n \"\"\"\n return request.user.is_superuser or request.user == obj"
},
{
"alpha_fraction": 0.7551020383834839,
"alphanum_fraction": 0.8163265585899353,
"avg_line_length": 49,
"blob_id": "ed394ed2f262e0e3b67f9a0fbcf3eb9c62acb7cb",
"content_id": "acbfa8ee5de179cd29ac9178e515009f9efd49b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 1,
"path": "/env/lib/python3.6/sre_compile.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/sre_compile.py"
},
{
"alpha_fraction": 0.7659574747085571,
"alphanum_fraction": 0.8297872543334961,
"avg_line_length": 47,
"blob_id": "3467d29ca594661d172ea97775e51be6908305a7",
"content_id": "b4763b47d922986f48f110a8f14c1284f35cce17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 1,
"path": "/env/lib/python3.6/linecache.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/linecache.py"
},
{
"alpha_fraction": 0.7441860437393188,
"alphanum_fraction": 0.8139534592628479,
"avg_line_length": 43,
"blob_id": "d3ee1cb2b59d2c331a3ca55afad99083a7675268",
"content_id": "5c700dc02a44846714b710c5988d97b47fa4f7ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 43,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 1,
"path": "/env/lib/python3.6/types.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/types.py"
},
{
"alpha_fraction": 0.7551020383834839,
"alphanum_fraction": 0.8163265585899353,
"avg_line_length": 49,
"blob_id": "dcdd4633ca6324293bdb70a55110eff95c2cb164",
"content_id": "b1df0d3a51cc23a27247fecdb31981c8763db67e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 1,
"path": "/env/lib/python3.6/_weakrefset.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/_weakrefset.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "2b41e9bbf45d93cf3fbf3f2716c432025dd8b404",
"content_id": "419f07b131766807262abc9ac98c0f1f90862913",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/locale.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/locale.py"
},
{
"alpha_fraction": 0.7647058963775635,
"alphanum_fraction": 0.8235294222831726,
"avg_line_length": 51,
"blob_id": "086d5b08b22fa7d2761c2b736093f7f4b18ef1ae",
"content_id": "4066ccc373d686f51055487fe3233ba958654e7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 1,
"path": "/env/lib/python3.6/sre_constants.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/sre_constants.py"
},
{
"alpha_fraction": 0.7592592835426331,
"alphanum_fraction": 0.8148148059844971,
"avg_line_length": 54,
"blob_id": "e99f59a552f3a87445337c6ad328d9963434f75d",
"content_id": "23ef69d3ff73c3f306cac676c652f040d72cf2a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 54,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 1,
"path": "/env/lib/python3.6/_collections_abc.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/_collections_abc.py"
},
{
"alpha_fraction": 0.738095223903656,
"alphanum_fraction": 0.8095238208770752,
"avg_line_length": 42,
"blob_id": "2faf652ed04df2b4712977ba633abe96fcf9a898",
"content_id": "9877dcaa1fa522304ff575363a892936bcce35d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 42,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 1,
"path": "/env/lib/python3.6/stat.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/stat.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "d8f5e171d0a40d5a1726bb8f735470a655679e3d",
"content_id": "c03f712a2868d8885d0d2b3842d8211ef5028a51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/codecs.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/codecs.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "7ad8c495fe358fa3a546d9d2671af9c7f8a4721b",
"content_id": "64b8d505bd80ed51955b7df6d173f4905a99fbab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/shutil.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/shutil.py"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "df80064be9e00745e42badc95c1ded658e839b8c",
"content_id": "bd78bb6c137128b954ad51771cfb825f5fbe6ddc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/keyword.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/keyword.py"
},
{
"alpha_fraction": 0.5436046719551086,
"alphanum_fraction": 0.5901162624359131,
"avg_line_length": 27.66666603088379,
"blob_id": "e438d6ba60094b43d7f9ff0542658de774cf1bb7",
"content_id": "669721909e9c5cca2bd696b414777abb500e8328",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 688,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 24,
"path": "/photos/migrations/0003_auto_20181022_0740.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.2 on 2018-10-22 07:40\n\nfrom django.db import migrations, models\nimport photos.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('photos', '0002_auto_20181016_0738'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='photo',\n name='description',\n field=models.TextField(blank=True, default='', null=True, validators=[photos.validators.badwords_detector]),\n ),\n migrations.AlterField(\n model_name='photo',\n name='license',\n field=models.CharField(choices=[('QUE', 'Quentin Tarantino'), ('DSH', 'Dr. Schutz')], max_length=3),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7446808218955994,
"alphanum_fraction": 0.8085106611251831,
"avg_line_length": 47,
"blob_id": "bec176f7b8dc5f5770ad609a8a366b90608ef9e2",
"content_id": "3f753722f7d3a422e85ce6eff117a74bb9800e54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 1,
"path": "/env/lib/python3.6/sre_parse.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/sre_parse.py"
},
{
"alpha_fraction": 0.7317073345184326,
"alphanum_fraction": 0.8048780560493469,
"avg_line_length": 41,
"blob_id": "017cf65e00bb85967ef81b9c92c085173595d667",
"content_id": "23b85916055b1bfe7bb130a54ef67a5213a719f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 41,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 1,
"path": "/env/lib/python3.6/imp.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/imp.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "16a085e31d6ea2194c3770ee4a20fb7d36aa8c43",
"content_id": "5be5e8753db00987f08458fd4c9fc3f7f3dee0f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/bisect.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/bisect.py"
},
{
"alpha_fraction": 0.7755101919174194,
"alphanum_fraction": 0.8367347121238708,
"avg_line_length": 49,
"blob_id": "c5565d86ddcc2e6b220536bc2ae4117578ebd811",
"content_id": "9f562176d6495c759c89f3d133f976e35c2467b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 1,
"path": "/env/lib/python3.6/rlcompleter.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/rlcompleter.py"
},
{
"alpha_fraction": 0.7659574747085571,
"alphanum_fraction": 0.8297872543334961,
"avg_line_length": 47,
"blob_id": "19d688be8adc6118f5467ac00a55ac760d9a3c1c",
"content_id": "9f681cd53951510fb3535b422b6fdf0e0ec581ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 1,
"path": "/env/lib/python3.6/posixpath.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/posixpath.py"
},
{
"alpha_fraction": 0.6499999761581421,
"alphanum_fraction": 0.6519230604171753,
"avg_line_length": 27.88888931274414,
"blob_id": "5e12244b63a465ad3c988c9068426008f20c3167",
"content_id": "8a7afce4ad4f1a1519a1bad8ed1c9b631d66adfa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 521,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 18,
"path": "/photos/validators.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "\nfrom django.core.exceptions import ValidationError\n\nfrom photos.settings import BADWORDS\n\n\ndef badwords_detector(value):\n \"\"\"\n Valida si en value se han puesto tacos en settings.BADWORDS\n :return: Boolean\n \"\"\"\n print(\"ENTRA A FUNCION\")\n for badword in BADWORDS:\n if badword.lower() in value.lower():\n print(\"ERROR\")\n raise ValidationError(\n 'La palabraa {0} no está permitida'.format(badword))\n #SI todo va OK, se devuelven todos lo datos\n return True"
},
{
"alpha_fraction": 0.738095223903656,
"alphanum_fraction": 0.8095238208770752,
"avg_line_length": 42,
"blob_id": "a292dd4c3a41f511fab2e9a591a27ae9f227622b",
"content_id": "58bd0e0c8f4ddfa1f4dc53136c2db4368a5facc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 42,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 1,
"path": "/env/lib/python3.6/hmac.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/hmac.py"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "ca91c0c54700472321d54bfd436e748d8b1f6a0e",
"content_id": "98c676d2d685cbc08f2c4c33e7b414b1c364e77b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/weakref.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/weakref.py"
},
{
"alpha_fraction": 0.6380646824836731,
"alphanum_fraction": 0.6474204659461975,
"avg_line_length": 33.321102142333984,
"blob_id": "b62cf56c2dccf87f442afe9dfc2d87f5c31afd97",
"content_id": "75820862ace79707b715a877e7331e8970446d99",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3741,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 109,
"path": "/users/api.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom django.views.generic import View\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework import status\nfrom rest_framework.pagination import PageNumberPagination\nfrom users.serializers import UserSerializer\nfrom django.shortcuts import get_object_or_404\nfrom users.permissions import UserPermission\n\n\"\"\"\nadmin\n1234\n\njose\nMaucaylle2018\n-----------\n#View personalizada\nclass UserListAPI(View):\n def get(self, request, *args, **kwargs):\n users = User .objects.all()\n serializer = UserSerializer(users, many=True)\n serialized_users = serializer.data\n renderer = JSONRenderer()\n json_users = renderer.render(serialized_users)#Lista de diccionarios -> JSON\n return HttpResponse(json_users)\"\"\"\n\nclass UserListAPI(APIView):\n\n permission_classes = (UserPermission,)\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n API users\n #Plitic:\n - Si la peticion es GET dejar acceder si esta authenticado\n - Si la peticion es POST\n \"\"\"\n self.check_permissions(request)\n paginator = PageNumberPagination()\n users = User.objects.all()\n #Paginar el queryset\n paginator.paginate_queryset(users, request)\n serializer = UserSerializer(users, many=True) #Lista de diccionarios\n serializer_users = serializer.data\n #Devolverla respuesta paginada\n return paginator.get_paginated_response(serializer_users)\n \n def post(self, request):\n \"\"\"\n Crea la foto \n :param request: HttpRequest\n :return: HttpResponse\n \"\"\"\n self.check_permissions(request)\n serializer = UserSerializer(data=request.data)\n if serializer.is_valid():\n new_user = serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\nclass UserDetailAPI(APIView):\n \"\"\"\n GET : solo authenticado\n PUT: si no es superadmin solo actualiza su usuario\n\n \"\"\"\n permission_classes = (UserPermission,)\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n API users\n \"\"\"\n self.check_permissions(request)\n user = get_object_or_404(User, pk=kwargs.get('pk')) #Leer como retorna si salir del metodo\n self.check_object_permissions(request, user)\n serializer = UserSerializer(user)\n return Response (serializer.data)\n \n def put(self, request, *args, **kwargs):\n \"\"\"\n API users\n \"\"\"\n\n self.check_permissions(request)\n user = get_object_or_404(User, pk=kwargs.get('pk')) # Leer como retorna si salir del metodo\n self.check_object_permissions(request, user)\n serializer = UserSerializer(instance=user, data=request.data)\n if serializer.is_valid():\n new_user = serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors,\n status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n API users\n \"\"\"\n self.check_permissions(request)\n user = get_object_or_404(User, pk=kwargs.get('pk')) # Leer como retorna si salir del metodo\n self.check_object_permissions(request, user)\n user.delete()\n #serializer = UserSerializer(instance=user, data=request.data)\n return Response(status=status.HTTP_204_NO_CONTENT)\n"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "9932a9df2c98962c3eea365f3e8c6c43b6641003",
"content_id": "17a2b0cf9d761ca765f4fbb832cab49bff272e19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/random.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/random.py"
},
{
"alpha_fraction": 0.7338429689407349,
"alphanum_fraction": 0.7338429689407349,
"avg_line_length": 31.704545974731445,
"blob_id": "392b8fbace39118263d5559c8aa4136cebd5a2bb",
"content_id": "e4e0a5e3a755552ea56af9fccaece207e335cb94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1439,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 44,
"path": "/photos/api.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "from rest_framework.generics import ListCreateAPIView, \\\n RetrieveUpdateDestroyAPIView\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom photos.models import Photo\nfrom photos.serializers import PhotoListSerializer, PhotoSerializer\nfrom photos.views import PhotosQueryset\n\n\n\"\"\"\nclass PhotoListAPI(APIView):\n def get(self, request, *args, **kwargs):\n photos = Photo .objects.all()\n serializer = PhotoSerializer(photos, many=True)\n return Response(serializer.data)\n\"\"\"\n\n\nclass PhotoListAPI(ListCreateAPIView, PhotosQueryset):\n queryset = Photo.objects.all().order_by('id')\n permission_classes = (IsAuthenticatedOrReadOnly,)\n #serializer_class = PhotoListSerializer\n\n def get_serializer_class(self):\n if self.request.method == 'GET':\n return PhotoListSerializer\n else:\n return PhotoSerializer\n \n def get_queryset(self):\n return self.get_photos_queryset(self.request)\n\n def perform_create(self, serializer):\n serializer.save(owner=self.request.user)\n\nclass PhotoDetailAPI(RetrieveUpdateDestroyAPIView, PhotosQueryset):\n queryset = Photo.objects.all()\n serializer_class = PhotoSerializer\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n return self.get_photos_queryset(self.request)\n"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "58a4a5cfebf0e7d8d389d3b9d8c6e0bebeb416ad",
"content_id": "df8699ce1608cab2c35674c6d324f2dee7d797f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/hashlib.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/hashlib.py"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "7db8dc747648a26748a9cb4bbdb48853d732e28c",
"content_id": "45c593025edafea4608329787295d0cf77ca97ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/tarfile.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/tarfile.py"
},
{
"alpha_fraction": 0.760869562625885,
"alphanum_fraction": 0.8260869383811951,
"avg_line_length": 46,
"blob_id": "a52165bddee1af1bb57c6e3ceac2a1d668688163",
"content_id": "ea0681ffb6cd8b37a08d45000137d92070130462",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 1,
"path": "/env/lib/python3.6/warnings.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/warnings.py"
},
{
"alpha_fraction": 0.760869562625885,
"alphanum_fraction": 0.8260869383811951,
"avg_line_length": 46,
"blob_id": "d456655ff99ff03a459e727907901c0293c9e59d",
"content_id": "17a83a6883ed93ff4a6f6a109e671b62a6168091",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 1,
"path": "/env/lib/python3.6/tokenize.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/tokenize.py"
},
{
"alpha_fraction": 0.7755101919174194,
"alphanum_fraction": 0.8367347121238708,
"avg_line_length": 49,
"blob_id": "f8d114eb54de1d60bb01aa83ab55a13682adbf05",
"content_id": "48269aa9350bbe54e66f225a461e57e851be609f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 1,
"path": "/env/lib/python3.6/genericpath.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/genericpath.py"
},
{
"alpha_fraction": 0.7551020383834839,
"alphanum_fraction": 0.8163265585899353,
"avg_line_length": 49,
"blob_id": "e61dd7c78a6ad7469c90144e4a8cabfebf8ab490",
"content_id": "f88940f0fcfea43c9e5da78edab5960f55781216",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 1,
"path": "/env/lib/python3.6/_bootlocale.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/_bootlocale.py"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "340cb1b02b0a3fe2dfc3fe910484dc5e6e78f250",
"content_id": "a5296011b527ceccf67115522dbc4d8cc45c1005",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/reprlib.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/reprlib.py"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "d09f852db8aefbe760201481a4b73b56131229fc",
"content_id": "a51a24aa8079ab6d06f37204b9d9c28846baf11a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/ntpath.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/ntpath.py"
},
{
"alpha_fraction": 0.7250000238418579,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 40,
"blob_id": "f9daaf8b88c46316526c3cabb8d580326f184029",
"content_id": "905aebf9b658999c7b24900f536bd47e14e8ef77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 40,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 1,
"path": "/env/lib/python3.6/os.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/os.py"
},
{
"alpha_fraction": 0.7045454382896423,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 44,
"blob_id": "f690d61d130d092bff0102aca2d282138cb79ba2",
"content_id": "cb2820d8a8f122981ba06966d3679e5e4641b8f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 1,
"path": "/env/lib/python3.6/base64.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/base64.py"
},
{
"alpha_fraction": 0.7250000238418579,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 40,
"blob_id": "7f4c7f584184a4735da6078e38f406c99505d502",
"content_id": "edb6e165c5611a9605c113f8712b423d5175745b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 40,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 1,
"path": "/env/lib/python3.6/io.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/io.py"
},
{
"alpha_fraction": 0.760869562625885,
"alphanum_fraction": 0.8260869383811951,
"avg_line_length": 46,
"blob_id": "c8d26710925dc50b55ef3b5e343e34f270eb389a",
"content_id": "4949fc254c185ac5882fc0a2adbb722fcaac8289",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 1,
"path": "/env/lib/python3.6/tempfile.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/tempfile.py"
},
{
"alpha_fraction": 0.7441860437393188,
"alphanum_fraction": 0.8139534592628479,
"avg_line_length": 43,
"blob_id": "2a57fcb2dba9e2741a87980dfa7b3eabb9e2450b",
"content_id": "1a4e73bed16bcf4de54794dba783e175aedf702a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 43,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 1,
"path": "/env/lib/python3.6/token.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/token.py"
},
{
"alpha_fraction": 0.7317073345184326,
"alphanum_fraction": 0.8048780560493469,
"avg_line_length": 41,
"blob_id": "85bfd1e4a9959a940eb4c8a383835df2a58ded6e",
"content_id": "427094266bb0823fef3afe20fc6cf991e6330bea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 41,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 1,
"path": "/env/lib/python3.6/abc.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/abc.py"
},
{
"alpha_fraction": 0.6624173521995544,
"alphanum_fraction": 0.6732766628265381,
"avg_line_length": 38.22222137451172,
"blob_id": "d233e0ff0a1e7dee017adf2d5daf1754d1593fab",
"content_id": "ae155681a48a79d561ae70edda99f71de8df19eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2118,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 54,
"path": "/Frikr/urls.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "\"\"\"Frikr URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\n\nfrom photos.api import PhotoDetailAPI, PhotoListAPI\nfrom photos.views import CreateView, DetailView, HomeView, PhotoListView, \\\n UserPhotosView\nfrom users.api import UserDetailAPI, UserListAPI\nfrom users.views import LoginView, LogoutView\n\n\n# r le dice que es una expresion regular -^ iniciode cadena - $ fin de cadena\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\n #Photo URLs\n url(r'^$', HomeView.as_view(), name=\"photos_home\"),\n url(r'^photos/(?P<pk>[0-9]+)/$', DetailView.as_view(), name=\"photo_detail\"),\n url(r'^photos/new/$', CreateView.as_view(), name=\"photo_create\"),\n url(r'^photos/$', PhotoListView.as_view(), name=\"photos_list\"),\n url(r'^my-photos/$', login_required(UserPhotosView.as_view()), name=\"user_photos\"),\n\n #Photos API URLs\n url(r'^api/1.0/photos/$', PhotoListAPI.as_view(), name='photo_list_api'),\n url(r'^api/1.0/photos/(?P<pk>[0-9]+)/$',\n PhotoDetailAPI.as_view(), name='photo_detail_api'),\n \n\n #Users URLs\n url(r'^login$', LoginView.as_view(), name='users_login'),\n url(r'^logout$', LogoutView.as_view(), name='users_logout'),\n\n\n #USers API URLs\n url(r'^api/1.0/users/$', UserListAPI.as_view(), name='user_list_api'),\n url(r'^api/1.0/users/(?P<pk>[0-9]+)/$', UserDetailAPI.as_view(), name='user_detail_api')\n \n]\n#path('accounts/', include('accounts.urls')),\n"
},
{
"alpha_fraction": 0.7555555701255798,
"alphanum_fraction": 0.8222222328186035,
"avg_line_length": 45,
"blob_id": "93a0c3716060b90ad24473a784aa95eb229859bc",
"content_id": "35c7cc794e2164f631e55cf7ab77d9e99fe035fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 45,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/env/lib/python3.6/copyreg.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "/home/jose/anaconda3/lib/python3.6/copyreg.py"
},
{
"alpha_fraction": 0.6367576718330383,
"alphanum_fraction": 0.6415258049964905,
"avg_line_length": 38.60344696044922,
"blob_id": "a60768771d974a354b8ea6b4ba2f74e43f4c355d",
"content_id": "6cfcf36c9e2d11274442a8fc36535e1557ce8e07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2307,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 58,
"path": "/users/serializers.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nclass UserSerializer(serializers.Serializer):\n id = serializers.ReadOnlyField() # read only\n first_name = serializers.CharField()\n last_name = serializers.CharField()\n username = serializers.CharField()\n email = serializers.EmailField()\n password = serializers.CharField()\n\n def create(self, validated_data):\n \"\"\"\n Crea una isntancia de user a partir de los datos de \n validated_data que contiene valores deserializados\n :param valdiated_data: Dicionario de datos de usuario\n :return: objeto user.\n \"\"\"\n instance = User()\n return self.update(instance, validated_data)\n\n def update(self, instance, validated_data):\n \"\"\"\n Actualiza una instancia de User a partir de los datos del diccionario \n validated_data que contine valores deserializados\n :param instance: objeto User a actualizar\n :param validated_data: Dicionario de datos de usuario\n :return: objeto user.\n \"\"\"\n instance.first_name = validated_data.get('first_name')\n instance.last_name = validated_data.get('last_name')\n instance.username = validated_data.get('username')\n instance.email = validated_data.get('email')\n instance.set_password(validated_data.get('password'))\n\n instance.save()\n return instance\n\n def validate_username(self,data):\n \"\"\"\n Valida si existe un usuario con ese nombre\n \"\"\"\n print(data)\n user = User.objects.filter(username=data)\n \n #Si estoy creado ( no hay instancia) comprobar si hay usuarios con ese username\n \n if not self.instance and len(user) != 0:\n raise serializers.ValidationError(\n \" Ya existe un usuario con ese username \")\n #Si estoy actualizando, el nuevo username es diferene al de la instancia( esta cambaido el userna,e)\n # y ecise usuarios registrados con ese nuevo username\n elif self.instance and self.instance.username != data and len(user) != 0:\n raise serializers.ValidationError(\n \" Ya existe un usuario con ese username \")\n else:\n return data\n #965079339\n\n \n"
},
{
"alpha_fraction": 0.590528666973114,
"alphanum_fraction": 0.5913451910018921,
"avg_line_length": 31.013071060180664,
"blob_id": "6b5be77bd65499134e1b1c2ce07098809c5f0bf0",
"content_id": "44f9cc24ddc199b7ee7b7337b4321a299642c34c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4903,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 153,
"path": "/photos/views.py",
"repo_name": "JoseEvanan/frikr",
"src_encoding": "UTF-8",
"text": "from django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.http import HttpResponse, HttpResponseNotFound\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views.generic import View, ListView\nfrom django.db.models import Q\n\nfrom photos.forms import PhotoForm\nfrom photos.models import PUBLIC, Photo\n\nclass OnlyAuthenticatedView(View):\n def get(self, request):\n if request.user.is_authenticated:\n \n print(\"LOGEADO\")\n return super(OnlyAuthenticatedView, self).get(request)\n else:\n print(\"NO LOGEADO\")\n return redirect('users_login')\n #redirigir a login\n \n def post(self, request):\n if request.user.is_authenticated:\n return super(OnlyAuthenticatedView, self).get(request)\n else:\n redirect('home')\n #redirigir a login\n \n\n#####\nclass PhotosQueryset(object):\n \n \n def get_photos_queryset(self,request):\n if not request.user.is_authenticated:\n photos = Photo.objects.filter(visibility=PUBLIC)\n elif request.user.is_superuser:\n photos = Photo.objects.all()\n else:\n photos = Photo.objects.filter(Q(owner=request.user) |\n Q(visibility=PUBLIC))\n return photos\n\n\n# Create your views here.\nclass HomeView(View):\n def get(self, request):\n \"\"\"\n Esta función devuelve elhome de mi página\n \"\"\"\n photos = Photo.objects.filter(visibility=PUBLIC).order_by('-created_at')\n context = {}\n context['photos'] = photos[:5]\n return render(request, 'photos/home.html', context)\n\n\nclass DetailView(View, PhotosQueryset):\n @method_decorator(login_required())\n def get(self, request, pk):\n \"\"\"\n Carga la página de detalle de una foto\n :param request: HttpRequest\n :param pk: id de la photo\n :return: HttpResponse\n \"\"\"\n possible_photos = self.get_photos_queryset(\n request).filter(pk=pk).select_related('owner')\n #JOIN Solo una llamada\n #sino haria dos llamdas para photo y para user\n #relacion reversa prefec\n photo = possible_photos[0] if len(possible_photos) == 1 else None\n if photo:\n #Cargar template detatlle\n context = {\n 'photo': photo\n }\n print(photo.owner)\n return render(request, 'photos/detail.html', context)\n else:\n return HttpResponseNotFound(\"NO existe la foto\")\n\n\nclass CreateView(View):\n \n @method_decorator(login_required())\n def get(self, request):\n \"\"\"\n Muestra un formulario para crea una foto \n :param request: HttpRequest\n :return: HttpResponse\n \"\"\"\n form = PhotoForm()\n context = {\n 'form': form\n }\n return render(request, 'photos/new_photo.html', context)\n \n @method_decorator(login_required())\n def post(self, request):\n \"\"\"\n Crea la foto \n :param request: HttpRequest\n :return: HttpResponse\n \"\"\"\n error_messages = []\n success_message = ''\n photo_with_owner = Photo()\n photo_with_owner.owner = request.user # usuario autenticado\n form = PhotoForm(request.POST, instance=photo_with_owner)\n if form.is_valid():\n print(\"FORMULARIO VALIDO\")\n new_photo = form.save() # Guarda el objeto y devolver\n print(new_photo)\n print(\"GUARDAR OBJETO\")\n form = PhotoForm()\n success_message = \"Guardado con éxito!\"\n success_message += \"<a href='{0}'>\".format(\n reverse('photo_detail', args=[new_photo.pk]))\n success_message += \"Ver foto\"\n success_message += \"</a>\"\n context = {\n 'errors': error_messages,\n 'success_message': success_message,\n 'form': form\n }\n return render(request, 'photos/new_photo.html', context)\n\n\nclass PhotoListView(View, PhotosQueryset):\n def get(self, request):\n \"\"\"\n Response:\n - The photos publics if user authenticated\n - The photos of user authenticared or publics other users\n - If user superadmin, all photos\n :param request: HttpRequest\n :return: HttpResponse\n \"\"\"\n photos = self.get_photos_queryset(request)\n context = {\n 'photos':photos\n }\n return render(request, 'photos/photos_list.html', context)\n\n\nclass UserPhotosView(ListView):\n model = Photo\n template_name = 'photos/user_photos.html'\n\n def get_queryset(self):\n queryset = super(UserPhotosView, self).get_queryset()\n return queryset.filter(owner=self.request.user)\n\n"
}
] | 46 |
sukhpreetn/QuizApp | https://github.com/sukhpreetn/QuizApp | 38fd10601ab4971a230ead0db8d8a4f877d80f5f | 6eab1f8a15c79a9e2d249529a34a64ec53479733 | 06989b2a65421a074329806ed8d1850a2606bc6f | refs/heads/master | 2022-12-22T15:19:36.640759 | 2020-04-05T18:12:11 | 2020-04-05T18:12:11 | 249,818,517 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.527999997138977,
"alphanum_fraction": 0.5786666870117188,
"avg_line_length": 19.83333396911621,
"blob_id": "05c0d5b73739a50712dad56a29aecc6a66e86e96",
"content_id": "2aa54e8a39d6df5fd49b48d416765e3687c2ccea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 375,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 18,
"path": "/AIP/migrations/0007_auto_20200403_2152.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.3 on 2020-04-03 21:52\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('AIP', '0006_trainee_attendance'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='attendance',\n old_name='register_time',\n new_name='expire_time',\n ),\n ]\n"
},
{
"alpha_fraction": 0.49238577485084534,
"alphanum_fraction": 0.5786802172660828,
"avg_line_length": 20.88888931274414,
"blob_id": "9d84769aa273e8e8a2c6624fd8499a52df105261",
"content_id": "8a16d70672febeeb99b18d2703b30de7154cc27b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 394,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 18,
"path": "/AIP/migrations/0004_result_c_email.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.3 on 2020-03-25 17:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('AIP', '0003_auto_20200325_1353'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='result',\n name='c_email',\n field=models.CharField(default='', max_length=100),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5209497213363647,
"alphanum_fraction": 0.5516759753227234,
"avg_line_length": 24.571428298950195,
"blob_id": "85b90abb962e2d1e98610cd5fbf79bb175bc3097",
"content_id": "9570fae5018435a82bafe549be606739575280df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 716,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 28,
"path": "/AIP/migrations/0003_auto_20200325_1353.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.3 on 2020-03-25 13:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('AIP', '0002_result_c_quiz_name'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='result',\n name='c_total_ans_correct',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='result',\n name='c_total_ans_incorrect',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='result',\n name='c_total_q_asked',\n field=models.IntegerField(default=0),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5062552094459534,
"alphanum_fraction": 0.7039199471473694,
"avg_line_length": 16.376811981201172,
"blob_id": "48e37879cf5f86a76ba9fbab097c719f1e952854",
"content_id": "60ce9621b0e4930e4885bdbfa9b9da12bb4842d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 1199,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 69,
"path": "/requirements.txt",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "antiorm==1.2.1\nasgiref==3.2.3\nattrs==19.3.0\nawsebcli==3.17.1\nbcrypt==3.1.7\nblessed==1.17.2\nbotocore==1.14.17\nbottle==0.12.18\ncached-property==1.5.1\ncement==2.8.2\ncertifi==2019.11.28\ncffi==1.14.0\nchardet==3.0.4\nClick==7.0\ncolorama==0.3.9\ncryptography==2.8\ndb==0.1.1\ndefusedxml==0.6.0\ndj-database-url==0.5.0\nDjango==3.0.3\ndjango-allauth==0.41.0\ndjango-crispy-forms==1.9.0\ndjango-registration-redux==1.4\ndocker==4.2.0\ndocker-compose==1.25.4\ndockerpty==0.4.1\ndocopt==0.6.2\ndocutils==0.15.2\nFlask==1.1.1\nFlask-SQLAlchemy==2.4.1\nfuture==0.16.0\ngunicorn==19.9.0\nidna==2.7\nimportlib-metadata==1.5.0\nitsdangerous==1.1.0\nJinja2==2.10.3\njmespath==0.9.5\njsonschema==3.2.0\nMarkupSafe==1.1.1\noauthlib==3.1.0\nparamiko==2.7.1\npathspec==0.5.9\npsycopg2-binary==2.7.7\npycparser==2.20\npymongo==3.10.0\nPyMySQL==0.9.3\nPyNaCl==1.3.0\npyrsistent==0.15.7\npython-dateutil==2.8.0\npython3-openid==3.1.0\npytz==2019.3\nPyYAML==5.2\nrequests==2.20.1\nrequests-oauthlib==1.3.0\nsemantic-version==2.5.0\nsimplejson==3.17.0\nsix==1.11.0\nSQLAlchemy==1.3.12\nsqlparse==0.3.0\ntermcolor==1.1.0\ntexttable==1.6.2\nurllib3==1.24.3\nvirtualenv==16.7.9\nwcwidth==0.1.8\nwebsocket-client==0.57.0\nWerkzeug==0.16.0\nwhitenoise==4.1.2\nxlwt==1.3.0\nzipp==3.1.0\n"
},
{
"alpha_fraction": 0.3862857222557068,
"alphanum_fraction": 0.4000000059604645,
"avg_line_length": 38.818180084228516,
"blob_id": "0de05b8374e159f4f69ad21ae3016afa749ab58c",
"content_id": "cc91cf9ffd545afffaa01e226ec77441894baf0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 875,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 22,
"path": "/AIP/forms.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\nfrom django import forms\nfrom .models import Question\n\nclass QuestionForm(forms.ModelForm):\n class Meta:\n model = Question\n labels = {\n 'q_subject' : 'Subject',\n 'q_cat' : 'Category',\n 'q_rank' : 'Rank',\n 'q_text' : 'Question',\n 'q_option1' : 'Answer Option1',\n 'q_option2' : 'Answer Option2',\n 'q_option3' : 'Answer Option3',\n 'q_option4' : 'Answer Option4',\n 'q_answer' : 'Answer',\n }\n\n fields = ('q_subject','q_cat','q_rank','q_text','q_option1','q_option2','q_option3','q_option4','q_answer')\n #fields = '__all__'"
},
{
"alpha_fraction": 0.6797349452972412,
"alphanum_fraction": 0.6813914775848389,
"avg_line_length": 44.275001525878906,
"blob_id": "6cea89c96c54596302c45f8d514959922322b9e7",
"content_id": "2e9f0b79c0338a9a20453761d8b3b46fea0045cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1811,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 40,
"path": "/AIP/urls.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "from django.conf import settings\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.urls import path , include\nfrom . import views\nfrom django.views.generic.base import TemplateView # new\n\napp_name = 'AIP'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('pickskill/', views.pickskill, name='pickskill'),\n path('begin/', views.begin, name='begin'),\n path('quiz/', views.quiz, name='quiz'),\n path('quizsimple/', views.quizsimple, name='quizsimple'),\n path('upload/', views.upload, name='upload'),\n path('comment/', views.comment, name='comment'),\n path('question/', views.question, name='question'),\n path('logout/', views.logout, name='logout'),\n path('export/', views.export, name='export'),\n path('add/', views.add, name='add'),\n path('questionupload/', views.questionupload, name='questionupload'),\n path('scores/', views.scores, name='scores'),\n path('quizzes/', views.quizzes,name='quizzes'),\n path('addquiz/', views.addquiz,name='addquiz'),\n path('addquestion/', views.addquestion, name='addquestion'),\n path('addquestion1/', views.addquestion1, name='addquestion1'),\n path('quizlist/', views.quizbucket, name='quizbucket'),\n path('quiz/<int:pk>/', views.takequiz, name='takequiz'),\n path('searchquiz/<int:pk>/', views.searchquiz, name='searchquiz'),\n path('scores/<int:pk>/', views.scores, name='scores'),\n path('review/', views.review, name='review'),\n path('review/<str:pk>/', views.reviewquiz, name='reviewquiz'),\n path('markattendance/<int:pk>/', views.markattendance, name='markattendance'),\n path('showattendance/<int:pk>/', views.showattendance, name='showattendance'),\n\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)\n"
},
{
"alpha_fraction": 0.8132529854774475,
"alphanum_fraction": 0.8132529854774475,
"avg_line_length": 31.899999618530273,
"blob_id": "fcd6f6dd1bd5f30a1688146014be3330bcae77a9",
"content_id": "501cf2e15a5941435f5b8c1f4211a0c1d9aa4d14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 332,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 10,
"path": "/AIP/admin.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom . models import Question , Answer,Result,Quiz,Attendance,Trainee_Attendance\n\n# Register your models here.\nadmin.site.register(Question)\nadmin.site.register(Answer)\nadmin.site.register(Result)\nadmin.site.register(Quiz)\nadmin.site.register(Attendance)\nadmin.site.register(Trainee_Attendance)\n\n\n\n"
},
{
"alpha_fraction": 0.5586419701576233,
"alphanum_fraction": 0.5925925970077515,
"avg_line_length": 28.454545974731445,
"blob_id": "bc9278cef51e8cb53a86383ee5cf9412dabd81a5",
"content_id": "bbaf2397ca86c3c298da3fcca3966ed59cf062bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 648,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 22,
"path": "/AIP/migrations/0006_trainee_attendance.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.3 on 2020-04-03 21:07\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('AIP', '0005_attendance'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Trainee_Attendance',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('trainee_email', models.CharField(default='', max_length=100)),\n ('login_time', models.DateTimeField(blank=True, default=datetime.datetime.now)),\n ],\n ),\n ]\n"
},
{
"alpha_fraction": 0.5628913044929504,
"alphanum_fraction": 0.5793967247009277,
"avg_line_length": 47.76388931274414,
"blob_id": "976ef38e589a03d06efd1673963596bbf17c90b9",
"content_id": "3a3ddd3efa6ee4f6a95461efa72e70ea5404bfb7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3514,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 72,
"path": "/AIP/models.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom datetime import datetime\n\n# Create your models here.\nclass Attendance(models.Model):\n trainer_name = models.CharField(max_length=200,default='')\n trainee_emails = models.TextField(null=True)\n expire_time = models.DateTimeField(default=datetime.now, blank=True)\n\n def __str__(self):\n return self.trainer_name\n\nclass Trainee_Attendance(models.Model):\n trainee_email = models.CharField(max_length=100,default='')\n login_time = models.DateTimeField(default=datetime.now, blank=True)\n\n def __str__(self):\n return self.trainee_email\n\n\nclass Quiz(models.Model):\n quiz_name = models.CharField(max_length=100,default='')\n quiz_OrgIdentifier = models.CharField(max_length=40,default='')\n quiz_questions = models.TextField(null=True)\n quiz_noofquest = models.IntegerField(default=0)\n\n def __str__(self):\n return self.quiz_name + \"_\" + self.quiz_OrgIdentifier\n\nclass Question(models.Model):\n q_subject = models.CharField(max_length=40)\n q_cat = models.CharField(max_length=40)\n q_rank = models.CharField(max_length=20)\n q_text = models.TextField(null=True,default='')\n q_option1 = models.CharField(max_length=200,default='')\n q_option2 = models.CharField(max_length=200,default='')\n q_option3 = models.CharField(max_length=200,default='')\n q_option4 = models.CharField(max_length=200,default='')\n q_answer = models.CharField(max_length=20)\n q_ask_time = models.DateTimeField(default=datetime.now, blank=True)\n no_times_ques_served = models.IntegerField(default=0)\n no_times_anwered_correctly = models.IntegerField(default=0)\n no_times_anwered_incorrectly = models.IntegerField(default=0)\n difficulty_score = models.DecimalField(default=0,max_digits = 5, decimal_places = 2)\n\n def __str__(self):\n return self.q_text\n\nclass Answer(models.Model):\n question = models.ForeignKey(Question, on_delete=models.CASCADE)\n ans_option = models.CharField(max_length=20)\n is_correct = models.BooleanField(default=False)\n ans_time = models.DateTimeField(default=datetime.now, blank=True)\n\n def __str__(self):\n return self.ans_option\n\nclass Result(models.Model):\n c_user = models.CharField(max_length=100)\n c_email = models.CharField(max_length=100,default='')\n c_quiz_name = models.CharField(max_length=100,default='')\n c_tot_score = models.IntegerField(default=0)\n c_cat_scores = models.TextField(null=True,default=0)\n c_comment = models.TextField(null=True,default='')\n c_new_quest = models.TextField(null=True,default='')\n c_attempt_date = models.DateTimeField(default=datetime.now, blank=True)\n c_total_q_asked = models.IntegerField(default=0)\n c_total_ans_correct = models.IntegerField(default=0)\n c_total_ans_incorrect = models.IntegerField(default=0)\n\n def __str__(self):\n return self.c_user\n\n\n\n"
},
{
"alpha_fraction": 0.597811758518219,
"alphanum_fraction": 0.6050283312797546,
"avg_line_length": 38.83616638183594,
"blob_id": "1bc8133c37a886330530110b2a50b57626d3ae34",
"content_id": "64285de16441e2f287f941d23d43031d01609538",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 25774,
"license_type": "no_license",
"max_line_length": 194,
"num_lines": 647,
"path": "/AIP/views.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "import datetime\nfrom datetime import timedelta\nimport os\nimport pprint\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom smtplib import SMTP\nfrom django.db.models import Count\nimport pandas as pd\nfrom django.conf import settings\nfrom django.http import HttpResponse, request, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, get_list_or_404, redirect, resolve_url\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom django.core.files.storage import FileSystemStorage\nfrom django.views import generic\nfrom django.urls import reverse\nfrom .models import Question, Answer, Result,Quiz,Attendance,Trainee_Attendance\nfrom django.http import HttpResponse\nimport json\nimport random\nimport csv, io\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import permission_required\nfrom .forms import QuestionForm\nfrom django.contrib.auth.models import User\nfrom django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView)\n\n\ndef index(request):\n quizname = request.session.get('quizname',None)\n #quizattend = request.session['fromattend']\n #return HttpResponse(quizname)\n\n if quizname is None:\n #settings.LOGIN_REDIRECT_URL = '/pickskill'\n #return render(request, 'AIP/index.html')\n settings.LOGIN_REDIRECT_URL = '/'\n return render(request, 'AIP/success.html')\n else:\n return redirect('AIP:takequiz', pk=quizname)\n\n\ndef pickskill(request):\n request.session['user'] = request.user.get_full_name()\n request.session['email'] = request.user.email\n user = request.session['user']\n email = request.session['email']\n Result.objects.create(c_user=user,c_email=email)\n category_count = Question.objects.values('q_rank').order_by('q_rank').annotate(count=Count('q_rank'))\n cat_count = list(category_count)\n categories = []\n for item in cat_count:\n cnt = str(item['count'])\n line = item['q_rank'] + ' (' + cnt + ')'\n categories.append(line)\n\n context = {'user':user,'categories':categories}\n return render(request, 'AIP/pickskill.html',context)\n\ndef begin(request):\n if request.method == 'POST':\n subject = request.POST['skill']\n rank = request.POST['proficiency']\n context = {'subject': subject, 'rank': rank}\n request.session['skill'] = subject\n request.session['proficiency'] = rank\n request.session['curr_difficulty_score'] = 1\n request.session['total_q_asked'] = 1\n request.session['total_q_ans_correct'] = 0\n request.session['counter'] = 0\n cat_dict = {'Introduction': 0, 'Syntax': 0, 'OOPS': 0, 'NativeDataTypes': 0, 'FileAndExceptionHandling': 0,\n 'Function': 0, 'Advanced': 0,'All': 0}\n request.session['cat_dict'] = cat_dict\n request.session['score'] = 0\n\n if rank == 'Adaptive':\n return render(request, 'AIP/begin.html', context)\n else:\n return render(request, 'AIP/beginsimple.html', context)\n\n\ndef quizsimple(request):\n subject = request.session['skill']\n rank = request.session['proficiency']\n total_q_asked = request.session['total_q_asked']\n total_q_ans_correct = request.session['total_q_ans_correct']\n counter = request.session['counter']\n score = request.session['score']\n cat_dict = request.session['cat_dict']\n user = request.session['user']\n\n questions = Question.objects.filter(q_subject=subject, q_rank=rank)\n max = Question.objects.filter(q_subject=subject, q_rank=rank).count()\n ind = random.randint(1, max)\n #return HttpResponse(ind)\n question = questions[ind]\n #question = questions[0]\n context = {'total_q_asked': total_q_asked, 'question': question}\n if request.method == 'POST':\n option = request.POST.get('options')\n q = Question(question.pk)\n ans = Answer()\n ans.question = q\n question.no_times_ques_served += 1\n\n total_q_asked += 1\n if question.q_answer == option:\n ans.ans_option = option\n ans.is_correct = True\n question.no_times_anwered_correctly += 1\n total_q_ans_correct += 1\n cat_dict[question.q_cat] += 1\n ans.save()\n else:\n ans.ans_option = option\n ans.is_correct = False\n question.no_times_anwered_incorrectly += 1\n ans.save()\n\n Question.objects.filter(pk=q.pk).update(no_times_ques_served=question.no_times_ques_served,\n no_times_anwered_correctly=question.no_times_anwered_correctly,\n no_times_anwered_incorrectly=question.no_times_anwered_incorrectly)\n if counter == (max-1) or request.POST.get('END') == 'STOP':\n score1 = (total_q_ans_correct / (total_q_asked - 1)) * 100\n score = round(score1)\n cat_scores = json.dumps(cat_dict)\n total_ans_incorrect = ((total_q_asked - 1) - total_q_ans_correct)\n Result.objects.filter(c_user=user).update(c_tot_score=score)\n Result.objects.filter(c_user=user).update(c_cat_scores=cat_scores,c_total_q_asked=(total_q_asked-1),c_total_ans_correct=total_q_ans_correct,c_total_ans_incorrect=total_ans_incorrect)\n score_context = {'score': score, 'cat_dict': cat_dict, 'total_q_asked': total_q_asked - 1,\n 'total_q_ans_correct': total_q_ans_correct}\n return render(request, 'AIP/report.html', score_context)\n\n counter += 1\n request.session['score'] = score\n request.session['counter'] = counter\n request.session['total_q_asked'] = total_q_asked\n request.session['total_q_ans_correct'] = total_q_ans_correct\n request.session['cat_dict'] = cat_dict\n\n questions = Question.objects.filter(q_subject=subject, q_rank=rank)\n max = Question.objects.filter(q_subject=subject, q_rank=rank).count()\n ind = random.randint(1, max)\n question = questions[ind]\n context = {'total_q_asked': total_q_asked, 'question': question}\n return render(request, 'AIP/quizsimple.html', context)\n else:\n # this is GET flow of 1st question\n return render(request, 'AIP/quizsimple.html', context)\n\n\ndef quiz(request):\n subject = request.session['skill']\n rank = request.session['proficiency']\n curr_difficulty_score = request.session['curr_difficulty_score']\n total_q_asked = request.session['total_q_asked']\n total_q_ans_correct = request.session['total_q_ans_correct']\n score = request.session['score']\n cat_dict = request.session['cat_dict']\n user = request.session['user']\n counter = request.session['counter']\n\n questions = Question.objects.filter(q_subject=subject, q_rank=rank).filter(difficulty_score__gt=curr_difficulty_score).order_by('difficulty_score')\n question = questions[0]\n context = {'total_q_asked': total_q_asked, 'question': question}\n\n if request.method == 'POST':\n option = request.POST.get('options')\n q = Question(question.pk)\n ans = Answer()\n ans.question = q\n question.no_times_ques_served += 1\n total_q_asked += 1\n if question.q_answer == option:\n ans.ans_option = option\n ans.is_correct = True\n question.no_times_anwered_correctly += 1\n total_q_ans_correct += 1\n cat_dict[question.q_cat] += 1\n ans.save()\n else:\n ans.ans_option = option\n ans.is_correct = False\n question.no_times_anwered_incorrectly += 1\n ans.save()\n\n Question.objects.filter(pk=q.pk).update(no_times_ques_served=question.no_times_ques_served,\n no_times_anwered_correctly=question.no_times_anwered_correctly,\n no_times_anwered_incorrectly=question.no_times_anwered_incorrectly,\n difficulty_score=curr_difficulty_score)\n\n if counter == 4 or request.POST.get('END') == 'STOP':\n score1 = (total_q_ans_correct / (total_q_asked - 1)) * 100\n score = round(score1)\n cat_scores = json.dumps(cat_dict)\n total_ans_incorrect = ((total_q_asked - 1) - total_q_ans_correct)\n\n Result.objects.filter(c_user=user).update(c_tot_score=score)\n Result.objects.filter(c_user=user).update(c_cat_scores=cat_scores, c_total_q_asked=(total_q_asked-1),\n c_total_ans_correct=total_q_ans_correct,\n c_total_ans_incorrect=total_ans_incorrect)\n score_context = {'score': score, 'cat_dict': cat_dict, 'total_q_asked': total_q_asked - 1,\n 'total_q_ans_correct': total_q_ans_correct}\n return render(request, 'AIP/report.html', score_context)\n\n counter += 1\n request.session['counter'] = counter\n request.session['score'] = score\n request.session['total_q_asked'] = total_q_asked\n request.session['total_q_ans_correct'] = total_q_ans_correct\n request.session['curr_difficulty_score'] = curr_difficulty_score\n request.session['cat_dict'] = cat_dict\n\n # curr_difficulty_score = question.no_times_anwered_incorrectly / question.no_times_anwered_incorrectly + question.no_times_anwered_correctly\n curr_difficulty_score = question.no_times_anwered_incorrectly / question.no_times_ques_served\n questions = Question.objects.filter(q_subject=subject, q_rank=rank).filter(\n difficulty_score__gt=curr_difficulty_score).order_by('difficulty_score')\n question = questions[0]\n context = {'total_q_asked': total_q_asked, 'question': question}\n return render(request, 'AIP/quiz.html', context)\n else:\n return render(request, 'AIP/quiz.html', context)\n\n\ndef comment(request):\n context = {}\n user = request.session['user']\n if request.method == 'POST':\n comment = request.POST.get('comment')\n Result.objects.filter(c_user=user).update(c_comment=comment)\n context['commsuccess'] = \"Comment added . Thank You !\"\n return render(request, 'AIP/report.html', context)\n\n\ndef question(request):\n context = {}\n user = request.session['user']\n if request.method == 'POST':\n question = request.POST.get('question')\n Result.objects.filter(c_user=user).update(c_new_quest=question)\n context['quessuccess'] = \"Question added . Thank You !\"\n return render(request, 'AIP/report.html', context)\n\n\ndef upload(request):\n context = {}\n if request.method == 'POST':\n try:\n uploaded_file = request.FILES['document']\n except MultiValueDictKeyError:\n return HttpResponse(\"Please upload a file\")\n\n fs = FileSystemStorage()\n name = fs.save(uploaded_file.name, uploaded_file)\n context['url'] = fs.url(name)\n return render(request, 'AIP/report.html', context)\n\n\ndef logout(request):\n try:\n del request.session['user']\n except KeyError:\n pass\n\n return render(request, 'AIP/index.html')\n\n@permission_required('admin.can_add_log_entry')\ndef export(request):\n response = HttpResponse(content_type='text/csv')\n writer = csv.writer(response)\n writer.writerow(\n ['q_subject', 'q_cat', 'q_rank', 'q_text', 'q_option1', 'q_option2', 'q_option3', 'q_option4', 'q_answer',\n 'q_ask_time', 'no_times_ques_served', 'no_times_anwered_correctly', 'no_times_anwered_incorrectly',\n 'difficulty_score'])\n for data in Question.objects.all().values_list('q_subject', 'q_cat', 'q_rank', 'q_text', 'q_option1', 'q_option2',\n 'q_option3', 'q_option4', 'q_answer', 'q_ask_time',\n 'no_times_ques_served', 'no_times_anwered_correctly',\n 'no_times_anwered_incorrectly', 'difficulty_score'):\n writer.writerow(data)\n\n response['Content-Disposition'] = 'attachment; filename=\"questions.csv\"'\n return response\n\n@permission_required('admin.can_add_log_entry')\ndef questionupload(request):\n # template = question_upload.html\n\n prompt = {\n 'order': 'Order of CSV should be Question,Option1,Option2,Option3,Option4,answer option'\n }\n if request.method == \"GET\":\n return render(request, 'AIP/question_upload.html', prompt)\n\n csv_file = request.FILES['file']\n if not csv_file.name.endswith('.csv'):\n messages.error(request, 'This is not a cvs file')\n\n data_set = csv_file.read().decode('UTF-8')\n io_string = io.StringIO(data_set)\n next(io_string)\n for column in csv.reader(io_string, delimiter='|'):\n _, created = Question.objects.update_or_create(\n q_subject=column[0],\n q_cat=column[1],\n q_rank=column[2],\n q_text=column[3],\n q_option1=column[4],\n q_option2=column[5],\n q_option3=column[6],\n q_option4=column[7],\n q_answer=column[8]\n )\n context = {}\n return render(request, 'AIP/question_upload.html', context)\n\n\n@permission_required('admin.can_add_log_entry')\ndef scores(request,pk):\n quiz = get_object_or_404(Quiz, pk=pk)\n quiznm = quiz.quiz_OrgIdentifier\n\n results = Result.objects.filter(c_quiz_name=pk).order_by('-c_attempt_date')\n\n if not results:\n context = {'results': results, 'quiz': 'Quiz Not Found'}\n else:\n context = {'results':results,'quiznm':quiznm}\n return render(request, 'AIP/scores.html', context)\n\ndef searchquiz(request,pk):\n results = Result.objects.filter(c_quiz_name = pk).order_by('-c_attempt_date')\n if not results:\n context = {'results': results, 'quiz': 'Quiz Not Found'}\n else:\n context = {'results':results,'quiz':pk}\n return render(request, 'AIP/scores.html', context)\n\n@permission_required('admin.can_add_log_entry')\ndef quizzes(request):\n quizzes = list(Quiz.objects.all())\n context = {'quizzes': quizzes}\n return render(request, 'AIP/quizzes.html',context)\n\ndef addquiz(request):\n return render(request, 'AIP/quizadd.html')\n\ndef add(request):\n subject = request.session['subject']\n category = request.session['category']\n count = request.session['count']\n if request.method == 'POST':\n form = QuestionForm(request.POST)\n if form.is_valid():\n question = form.save()\n question.save()\n\n if count == 2:\n questions = list(Question.objects.all())\n context = {'subject': subject, 'category': category, 'questions': questions}\n return render(request, 'AIP/addquestion.html', context)\n\n count += 1\n request.session['count'] = count\n form = QuestionForm()\n return render(request, 'AIP/add.html', {'form': form})\n else:\n form = QuestionForm()\n return render(request, 'AIP/add.html', {'form': form})\n\ndef addquestion(request):\n subject = request.POST['Subject']\n quizname = request.POST['quizname']\n request.session['subject'] = subject\n request.session['quizname'] = quizname\n request.session['questionlist'] = []\n request.session['count'] = 1\n request.session['countdrop'] = 1\n questions = list(Question.objects.all())\n context = {'subject': subject, 'questions': questions}\n return render(request, 'AIP/addquestion.html', context)\n\ndef addquestion1(request):\n selectedquestion = []\n subject = request.session['subject']\n quizname = request.session['quizname']\n if request.method == 'POST':\n for question in request.POST.getlist('questionchecked'):\n selectedquestion.append(int(question))\n\n q = Quiz()\n q.quiz_name = subject\n q.quiz_OrgIdentifier = quizname\n q.quiz_questions = selectedquestion\n q.quiz_noofquest = len(selectedquestion)\n q.save()\n quizzes = Quiz.objects.all()\n context = {'quizzes': quizzes}\n return render(request, 'AIP/quizzes.html', context)\n\ndef quizbucket(request):\n if request.user.is_authenticated:\n quizzes = Quiz.objects.all()\n context = {'quizzes': quizzes}\n request.session['user'] = request.user.get_full_name()\n user = request.session['user']\n Result.objects.create(c_user=user)\n request.session['q_no'] = 0\n request.session['total_q_asked'] = 1\n request.session['total_q_ans_correct'] = 0\n request.session['counter'] = 0\n cat_dict = {'Introduction': 0, 'Syntax': 0, 'OOPS': 0, 'NativeDataTypes': 0, 'FileAndExceptionHandling': 0,'Function': 0, 'Advanced': 0,'All':0}\n request.session['cat_dict'] = cat_dict\n request.session['score'] = 0\n return render(request, 'AIP/quizbucket.html',context)\n else:\n return render(request, 'AIP/index.html')\n\ndef check_expiry():\n datetimeFormat = '%Y-%m-%d %H:%M:%S'\n\n date1 = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n queryset = Attendance.objects.all()\n reg_time = [p.expire_time for p in queryset]\n\n date2 = reg_time[0].strftime(\"%Y-%m-%d %H:%M:%S\")\n diff = datetime.datetime.strptime(date2, datetimeFormat) \\\n - datetime.datetime.strptime(date1, datetimeFormat)\n print(\"expire_time :\" , date2)\n print(\"login time\" , date1)\n print(\"difference\", diff)\n print(diff.total_seconds())\n if diff.total_seconds() < 5 :\n return True\n else:\n return False\n\ndef takequiz(request, pk):\n if request.user.is_authenticated:\n expired = check_expiry()\n if expired == True:\n return render(request, 'AIP/notfound.html')\n\n now = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n request.session['user'] = request.user.get_full_name()\n user = request.session['user']\n request.session['email'] = request.user.email\n email = request.session['email']\n Trainee_Attendance.objects.create(trainee_email=email,login_time=now)\n quiz = get_object_or_404(Quiz, pk=pk)\n quiz_str = json.loads(quiz.quiz_questions)\n total = len(quiz_str)\n if request.method == 'POST':\n q_no = request.session['q_no']\n total_q_asked = request.session['total_q_asked']\n total_q_ans_correct = request.session['total_q_ans_correct']\n counter = request.session['counter']\n score = request.session['score']\n cat_dict = request.session['cat_dict']\n user = request.session['user']\n question = get_object_or_404(Question, pk=quiz_str[q_no])\n context = {'total_q_asked': total_q_asked, 'question': question}\n\n option = request.POST.get('options')\n q = Question(question.pk)\n ans = Answer()\n ans.question = q\n question.no_times_ques_served += 1\n total_q_asked += 1\n if question.q_answer == option:\n ans.ans_option = option\n ans.is_correct = True\n question.no_times_anwered_correctly += 1\n total_q_ans_correct += 1\n cat_dict[question.q_cat] += 1\n ans.save()\n else:\n ans.ans_option = option\n ans.is_correct = False\n question.no_times_anwered_incorrectly += 1\n ans.save()\n\n Question.objects.filter(pk=q.pk).update(no_times_ques_served=question.no_times_ques_served,\n no_times_anwered_correctly=question.no_times_anwered_correctly,\n no_times_anwered_incorrectly=question.no_times_anwered_incorrectly)\n\n q_no += 1\n if q_no == total or request.POST.get('END') == 'STOP':\n score1 = (total_q_ans_correct / (total_q_asked - 1)) * 100\n total_ans_incorrect = ((total_q_asked-1) - total_q_ans_correct)\n score = round(score1)\n cat_scores = json.dumps(cat_dict)\n Result.objects.create(c_user=user,c_email=email, c_quiz_name=pk,c_tot_score=score,c_cat_scores=cat_scores,\n c_total_q_asked=(total_q_asked-1),c_total_ans_correct=total_q_ans_correct,\n c_total_ans_incorrect=total_ans_incorrect)\n\n score_context = {'score': score, 'cat_dict': cat_dict, 'total_q_asked': total_q_asked - 1,\n 'total_q_ans_correct': total_q_ans_correct}\n\n send_mail(email,score,cat_dict)\n return render(request, 'AIP/report.html', score_context)\n\n request.session['q_no'] = q_no\n request.session['score'] = score\n request.session['total_q_asked'] = total_q_asked\n request.session['total_q_ans_correct'] = total_q_ans_correct\n request.session['cat_dict'] = cat_dict\n\n question = get_object_or_404(Question, pk=quiz_str[q_no])\n quizname = request.session['quizname']\n context = {'total_q_asked': total_q_asked, 'question': question,'quizname':quizname}\n return render(request, 'AIP/quizsimple.html', context)\n\n else:\n request.session['q_no'] = 0\n request.session['total_q_asked'] = 1\n request.session['total_q_ans_correct'] = 0\n request.session['counter'] = 0\n cat_dict = {'Introduction': 0, 'Syntax': 0, 'OOPS': 0, 'NativeDataTypes': 0, 'FileAndExceptionHandling': 0,\n 'Function': 0, 'Advanced': 0, 'All': 0}\n request.session['cat_dict'] = cat_dict\n request.session['score'] = 0\n q_no = request.session['q_no']\n total_q_asked = request.session['total_q_asked']\n question = get_object_or_404(Question, pk=quiz_str[q_no])\n quizname = request.session['quizname']\n context = {'total_q_asked': total_q_asked, 'question': question,'quizname':quizname}\n return render(request, 'AIP/quizsimple.html', context)\n else:\n request.session['quizname'] = '{}'.format(pk)\n quizname = request.session['quizname']\n context = {'quizname':quizname}\n settings.LOGIN_REDIRECT_URL = '/'\n return render(request, 'AIP/index.html',context)\n\ndef send_mail(email,score,cat_dict):\n print(email)\n score_data= pd.DataFrame(\n {\n 'category score':cat_dict,\n }\n )\n #recipients = [email,'[email protected]','[email protected]']\n recipients = [email, '[email protected]']\n emaillist = [elem.strip().split(',') for elem in recipients]\n msg = MIMEMultipart()\n msg['Subject'] = \"Quiz Hop Scores\"\n msg['From'] = '[email protected]'\n\n html = \"\"\"\\\n <html>\n <head></head>\n <body>\n Total Score is : {0} \n <p></p>\n Category wise split of Scores :\n {1}\n </body>\n </html>\n \"\"\".format(score,score_data.to_html())\n\n part1 = MIMEText(html, 'html')\n msg.attach(part1)\n\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login('[email protected]', 'snwylifpbqtszbxe')\n server.sendmail(msg['From'], emaillist , msg.as_string())\n\n\n@permission_required('admin.can_add_log_entry')\ndef review(request):\n questions = Question.objects.all()\n total = len(questions)\n context = {'questions': questions, 'total': total}\n return render(request, 'AIP/compare.html', context)\n\n\n@permission_required('admin.can_add_log_entry')\ndef reviewquiz(request,pk):\n quiz = get_object_or_404(Quiz, pk=pk)\n quiz_str = json.loads(quiz.quiz_questions)\n total = len(quiz_str)\n questions = []\n\n for qid in quiz_str:\n ques = get_object_or_404(Question,pk=qid)\n questions.append(ques)\n\n context = {'questions': questions,'total':total,'subject':questions[0].q_subject,'category':questions[0].q_cat}\n return render(request, 'AIP/compare.html',context)\n\n\ndef markattendance(request, pk):\n if request.method == 'POST':\n\n trainer = request.POST.get('trainer')\n trainees = request.POST.get('trainees')\n expires = request.POST.get('expires')\n\n Attendance.objects.create(trainer_name=trainer, trainee_emails=trainees, expire_time=expires)\n trainee_list = trainees.split(\"\\r\\n\")\n send_mail_attendance(trainee_list,pk)\n\n #request.session['fromattend'] = 'attend'\n return redirect('AIP:showattendance', pk=pk)\n\n else:\n return render(request, 'AIP/markattendance.html')\n\ndef showattendance(request, pk):\n results = Trainee_Attendance.objects.all()\n context = {'results':results,'pk':pk}\n return render(request, 'AIP/showattendance.html',context)\n\ndef send_mail_attendance(trainee_list,pk):\n q_name = str(pk)\n #url = \"http://sukhpreetn.pythonanywhere.com/\"\n url = \"http://127.0.0.1:8000/\"\n\n recipients = trainee_list\n emaillist = [elem.strip().split(',') for elem in recipients]\n msg = MIMEMultipart()\n msg['Subject'] = \"Quiz Hop : Mark your attendance\"\n msg['From'] = '[email protected]'\n\n html = \"\"\"\\\n <html>\n <head></head>\n <body>\n Login <a href= {0}> here </a>\n \n </body>\n </html>\n \"\"\".format(url)\n part1 = MIMEText(html, 'html')\n msg.attach(part1)\n\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.ehlo()\n server.starttls()\n server.ehlo()\n server.login('[email protected]', 'snwylifpbqtszbxe')\n server.sendmail(msg['From'], emaillist , msg.as_string())\n"
},
{
"alpha_fraction": 0.5555555820465088,
"alphanum_fraction": 0.5864979028701782,
"avg_line_length": 29.913043975830078,
"blob_id": "1b44b51b4d79664fd5eb76fde3e91125d6ead14d",
"content_id": "72c9506c8db99c668b8e311ef15a35f5138c02f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 711,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 23,
"path": "/AIP/migrations/0005_attendance.py",
"repo_name": "sukhpreetn/QuizApp",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.3 on 2020-04-03 18:25\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('AIP', '0004_result_c_email'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Attendance',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('trainer_name', models.CharField(default='', max_length=200)),\n ('trainee_emails', models.TextField(null=True)),\n ('register_time', models.DateTimeField(blank=True, default=datetime.datetime.now)),\n ],\n ),\n ]\n"
}
] | 11 |
ulsu/manager | https://github.com/ulsu/manager | 66fe0105a678c35392d31edad094572a0f9b62f3 | 354fcde8af7b98a4676bdb66084b21895a0adcda | f6a594911d6be62cd83735d8dab83573c3a942c2 | refs/heads/master | 2020-05-18T16:46:40.845485 | 2013-12-06T10:47:24 | 2013-12-06T10:47:24 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.8478260636329651,
"alphanum_fraction": 0.8478260636329651,
"avg_line_length": 45,
"blob_id": "d96b7afe3262952ed90c2af7e854b81e23b52a34",
"content_id": "1a3dff67af449a1f14b078cfc06207cddb082111",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 85,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 1,
"path": "/README.md",
"repo_name": "ulsu/manager",
"src_encoding": "UTF-8",
"text": "Менеджер задач для Отдела веб-технологий УлГУ\n"
},
{
"alpha_fraction": 0.2948490083217621,
"alphanum_fraction": 0.29751333594322205,
"avg_line_length": 33.15151596069336,
"blob_id": "c61206b0e93fb9976bdce329e022aa03c5881266",
"content_id": "92b541a980b124096192afa9d44527feb287d840",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1128,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 33,
"path": "/templates/index.html",
"repo_name": "ulsu/manager",
"src_encoding": "UTF-8",
"text": "{% extends 'base.html' %}\n\n{% block title %}Tasks{% endblock %}\n\n{% block content %}\n {% if tasks %}\n {% for t in tasks %}\n {% for p in t.performers.all %}\n {% if p.username == user.username %}\n <a href='/task/{{ t.id }}'>\n <div class='row_{% if t.importance == 0 %}low{% elif t.importance == 1 %}mid{% elif t.importance == 2 %}high{% endif %}'>\n <div>\n {{ t.title }}\n </div>\n\n <div>\n {{ t.description }}\n </div>\n\n <div class='text-right'>\n {% for p in t.performers.all %}\n {{ p.username }},\n {% endfor %} до {{ t.pub_date }}\n </div>\n </div>\n </a>\n {% endif %}\n {% endfor %}\n {% endfor %}\n {% else %}\n No tasks\n {% endif %}\n{% endblock %}"
},
{
"alpha_fraction": 0.6054654121398926,
"alphanum_fraction": 0.6054654121398926,
"avg_line_length": 30.675676345825195,
"blob_id": "60b82168ec6f5d18fac12f41b081b6f27bb08a97",
"content_id": "4c8492ce4ff2907aed642c742a54693dc010ecf0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1171,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 37,
"path": "/accounts/views.py",
"repo_name": "ulsu/manager",
"src_encoding": "UTF-8",
"text": "from forms import *\nfrom django.contrib import auth\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.forms.util import ErrorList\n\ndef login(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n\n if form.is_valid():\n user = auth.authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])\n\n if user is not None and user.is_active:\n auth.login(request, user)\n return HttpResponseRedirect('/')\n else:\n errors = form._errors.setdefault('username', ErrorList())\n errors.append(u'Username or password incorrect')\n\n return render(request, 'accounts/login.html', {\n 'form': form,\n })\n else:\n if request.user.is_authenticated():\n return HttpResponseRedirect('/')\n\n form = LoginForm()\n\n return render(request, 'accounts/login.html', {\n 'form': form,\n })\n\ndef logout(request):\n if request.user.is_authenticated():\n auth.logout(request)\n return HttpResponseRedirect('/')"
},
{
"alpha_fraction": 0.6202090382575989,
"alphanum_fraction": 0.6283391118049622,
"avg_line_length": 33.47999954223633,
"blob_id": "bbe534e5b32c56b1b9fd5385a44f15b5f4c7ae92",
"content_id": "622bc0075a9719705aba1dc417ef0461cfa9e119",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 900,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 25,
"path": "/main/models.py",
"repo_name": "ulsu/manager",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Task(models.Model):\n IMPORTANCE = (\n (0, 'Low'),\n (1, 'Average'),\n (2, 'High'),\n )\n title = models.CharField(max_length=255, verbose_name='Название')\n description = models.TextField(verbose_name='Описание')\n parent = models.ForeignKey('Task', null=True, blank=True, related_name='children')\n importance = models.IntegerField(choices=IMPORTANCE, verbose_name='Важность')\n pub_date = models.DateTimeField(verbose_name='Дата')\n performers = models.ManyToManyField(User, verbose_name='Исполнители')\n\n class Meta:\n ordering = ['-id']\n\n def __unicode__(self):\n if self.parent is None:\n return '%s' % self.title\n else:\n return '%s - %s' % (self.parent.title, self.title)"
}
] | 4 |
brittancreek/walker-1.0 | https://github.com/brittancreek/walker-1.0 | c0453f1e7927584cbdc1e556e4c4706c63474e5e | 2cd8fbbe02b3c7d94f3abed32c28cc37f4813e96 | 80b87f2e65b7d44bd3f7be72946f14db461859aa | refs/heads/master | 2020-05-31T12:33:53.548103 | 2020-02-24T21:55:58 | 2020-02-24T21:55:58 | 190,283,847 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5045045018196106,
"alphanum_fraction": 0.5045045018196106,
"avg_line_length": 13.857142448425293,
"blob_id": "8690e5d620b1e058239aff9da350648026ede480",
"content_id": "b6e8782cdbf2771def6101ac309692784fe59835",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 223,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 14,
"path": "/tests/features/steps/source/device.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "\"\"\"\r\nCopyright © Brittan Creek.\r\n\"\"\"\r\n\r\nclass Device(object):\r\n\r\n def __init__(self):\r\n self.power = False\r\n\r\n def power_up(self):\r\n self.power = True\r\n\r\n def power_down(self):\r\n self.power = False\r\n"
},
{
"alpha_fraction": 0.6728395223617554,
"alphanum_fraction": 0.709876537322998,
"avg_line_length": 12.5,
"blob_id": "8d0dac021c5785281a193657adbec540d9e50530",
"content_id": "11f5ac7eedb683fa0bca7399d119e6435ab75877",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 163,
"license_type": "permissive",
"max_line_length": 29,
"num_lines": 12,
"path": "/tests/features/steps/source/bcconfig.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "'''\nDevice configurations\n\nCopyright © Brittan Creek.\n'''\n\nfrom micropython import const\n\nDEVICE_NAME = \"Walker\"\nDEVICE_LED_COUNT = const(12)\n\nSWITCH_WAIT = const(2000)\n"
},
{
"alpha_fraction": 0.7551020383834839,
"alphanum_fraction": 0.7551020383834839,
"avg_line_length": 22,
"blob_id": "eaca352d666cb8bd1a03b371bcacc78aa0d68d46",
"content_id": "0122434bb261aa89b686c47453d19611fd89c30e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 49,
"license_type": "permissive",
"max_line_length": 36,
"num_lines": 2,
"path": "/README.md",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "\n# walker\nMaking strides in pedestrian safety.\n\n\n"
},
{
"alpha_fraction": 0.7575300931930542,
"alphanum_fraction": 0.7616716623306274,
"avg_line_length": 62.238094329833984,
"blob_id": "1813a0446346353caaf39807a26b149907b96967",
"content_id": "3d5150fe1c3e2aa71adfcb2f9b81ca8c22285f6c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2692,
"license_type": "permissive",
"max_line_length": 357,
"num_lines": 42,
"path": "/docs/README.md",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "### walker\n*Making strides in pedestrian safety.*\n\n<br/>\n\n---\n---\n**Behavior-Driven Development** (BDD) takes the position that you can turn an idea for a requirement into implemented, tested, production-ready code simply and effectively, as long as the requirement is specific enough that everyone knows what’s going on.\n\nTo do this, we need a way to describe the requirement such that everyone – the business folks, the analyst, the developer and the tester – have a common understanding of the scope of the work. From this they can agree a common definition of “done”, and we escape the traps of “that’s not what I asked for” or “I forgot to tell you about this other thing”. ”\n\n“This, then, is the role of a Story. It has to be a description of a requirement and its business benefit, and a set of criteria by which we all agree that it is “done”.\n\nThis is a more rigorous definition than in other agile methodologies, where it is variously described as a “promise of a conversation” or a “description of a feature”. (A BDD story can just as easily describe a non-functional requirement, as long as the work can be scoped, estimated and agreed on.)\n\n[Dan North *What's in a story?*](https://dannorth.net/whats-in-a-story/)\n\n---\n## Template for Writing Scenarios\n**Given** we ***put the system in a known state*** before the user (or external system) starts interacting with the system (in the When steps). Avoid talking about user interaction in givens.\n\n**When** we ***take key actions*** the user (or external system) performs. This is the interaction with your system which should (or perhaps should not) cause some state to change.\n\n**Then** we ***observe outcomes***.\n\n[Integrate TDD with BDD: Using Python, Behave, and Mocking](https://medium.com/@springcalvind/integrate-tdd-with-bdd-using-python-behave-and-mocking-5382e42de93d)\n\n---\n## The London School of Test-Driven Development\n\nThe London school's definitive text is *Growing Object Oriented Software Guided By Tests by Steve Freeman and Nat Pryce.* See the the *#new-user-docs* Slack channel.\n<br/>\n\nA very simplified description of this approach to TDD might be:\n\n- Identify the roles, responsibilities and the key interactions and collaborations between roles in an end-to-end implementation of the solution to satisfy a system-level scenario or acceptance test.\n- Implement the code needed in each collaborator, one at a time, faking it's direct collaborators\n- Work your way down through the \"call stack\" of interactions until you have a working end-to-end implementation that passes the front-end test.\n\n[Classic TDD or \"London School\"?](http://codemanship.co.uk/parlezuml/blog/?postid=987)\n\n---\n"
},
{
"alpha_fraction": 0.5966851115226746,
"alphanum_fraction": 0.6408839821815491,
"avg_line_length": 11.928571701049805,
"blob_id": "78755cd801406c5d6d7773106745dd822d2c24cb",
"content_id": "bfc1d440f3c341fef80533051399b0859e6973ac",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 182,
"license_type": "permissive",
"max_line_length": 29,
"num_lines": 14,
"path": "/tests/features/steps/source/hwconfig.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "'''\nCopyright © Brittan Creek.\n'''\n\nfrom micropython import const\n\nLED_RED = const(1)\nLED_GREEN = const(2)\nLED_AMBER = const(3)\nLED_BLUE = const(4)\n\n# SPI bus pins\nMOSI_X8 = 1\nMOSI_Y8 = 2\n"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 15,
"blob_id": "1d04562ed12e514fec485c48f1b9507f3bd5ac2b",
"content_id": "023ab04cc085398a36214b620b8d2f747559feea",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 64,
"license_type": "permissive",
"max_line_length": 22,
"num_lines": 4,
"path": "/tests/features/steps/system_startup_steps.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "# system_startuo_steps\n\nfrom behave import *\nfrom main import *\n"
},
{
"alpha_fraction": 0.7429511547088623,
"alphanum_fraction": 0.7645676732063293,
"avg_line_length": 69.93333435058594,
"blob_id": "b091d847209f163338c40dc890097f528b05a78b",
"content_id": "842115cc170f4e6e002a8c4d934cd74b89d8c42f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2137,
"license_type": "permissive",
"max_line_length": 243,
"num_lines": 30,
"path": "/docs/dev notes.md",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "**2019-10-18**\n“Area prostriata responds strongly to very fast motion, greater than 500°/s. The functional properties of area prostriata suggest that it may serve to alert the brain quickly to fast visual events, particularly in the peripheral visual field.”\nJohn, I bet we can evaluate, we should have no problem rotating around our ring at 720 Deg/sec. 2 full rotations of one led of 12 = 2x 360. 360/12 is 30 deg/step which exceeds ARL minimum recognition. if I interpreted correctly.\n\n**2019-08-15**\n\n*ok, here is a strategy, untill we know better 3 photo transistors for reliable day/night and 2 headlight detectors may be read at time intervals. e.g. sample rate. if we have threading, low overhead and not blocking?*\n*ADC.read_timed_multi((adcx, adcy, ...), (bufx, bufy, ...), timer)*\n*This is a static method. It can be used to extract relative timing or phase data from multiple ADC’s.*\n*It reads analog values from multiple ADC’s into buffers at a rate set by the timer object. Each time the timer triggers a sample is rapidly read from each ADC in turn.*\n\n*we still need to interpret the buffers but that has to happen anyway. circuit seems to be voltage proportional to light level, -intention is directional but that is TBD.*\n\nWhat's happened here is that DM has designed this down to specifying the function call to be used.\n\nI need to know his thought process here, because BDD is the way to do it, and it should be much less stressful. But we will only get DM's adoption.\n\n**2019-06-23**\n\n**Strategy: Identify collaborators.**\n\nIf so then it's the MCU which consists of the hardware of the micro-controller and it's filesystem '/flash', and the files boot.py and main.py, and the device, represented by the Device class in software.\n\nColor in a Nutshell\n===================\nHue is the term for color in science.\n\nRed Green and Blue are additive primaries that correspond to the Cones in our central/foveal vision. Electronics like TVs and screens use Additive Primaries.\n\nCyan, Magenta, Yellow, and sometimes extra black named K for Japanese Kuro (black) are Subtractive primaries hence CMYK in color printing.\n"
},
{
"alpha_fraction": 0.4960806369781494,
"alphanum_fraction": 0.5106382966041565,
"avg_line_length": 18.413043975830078,
"blob_id": "40ddb01fa6bb787658a347b71ff9f2b4a579f62d",
"content_id": "2f091955a31dca7e6f8d90666177742f54646f30",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 893,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 46,
"path": "/tests/features/steps/source/microbit.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "from micropython import const\nfrom microbit import *\nimport neopixel\n\n\n# config\nr = const(0)\ng = const(64)\nb = const(0)\npx = const(12)\nd = const(30)\nm = const(5)\n\ndef gesture_captured(x):\n pin0.write_digital(x)\n\n\n# ring\nnp = neopixel.NeoPixel(pin1, px)\nnp.clear()\n\n\nwhile True:\n\n if accelerometer.was_gesture('shake') is True:\n gesture_captured(True)\n\n deactivate = False\n accelerometer.get_gestures()\n\n while True:\n for i in range(0, px - 1):\n np[i] = (r, g, b)\n np.show()\n sleep(d)\n np.clear()\n if accelerometer.was_gesture('shake') is True:\n accelerometer.get_gestures()\n gesture_captured(False)\n deactivate = True\n break\n\n if deactivate:\n break\n\n sleep(d * m)\n"
},
{
"alpha_fraction": 0.6682170629501343,
"alphanum_fraction": 0.6682170629501343,
"avg_line_length": 23.80769157409668,
"blob_id": "f66ba9c417aacaa6c1ac7a1ce2ec134ff0603ef4",
"content_id": "c880216f71db379f8fec68ff8a026e147751414b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 645,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 26,
"path": "/tests/system_tests.py",
"repo_name": "brittancreek/walker-1.0",
"src_encoding": "UTF-8",
"text": "# device power tests\nimport unittest\nfrom unittest.mock import MagicMock, Mock\nimport sys\nfrom features.steps.source.device import *\n\n\nclass TestDevice(unittest.TestCase):\n\n def setUp(self):\n self.test_device = Device()\n\n def test_power_up(self):\n self.assertFalse(self.test_device.power)\n self.test_device.power_up()\n self.assertTrue(self.test_device.power)\n\n def test_power_down(self):\n self.test_device.power_up()\n self.assertTrue(self.test_device.power)\n self.test_device.power_down()\n self.assertFalse(self.test_device.power)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
}
] | 9 |
felixkiptoo9888/Cafe | https://github.com/felixkiptoo9888/Cafe | d633eec3871e723e0463154f68636e56fa86ff8f | a9a0f6410422e8471eb126e57b4f372d58620c5f | 62b748f12b3cdf08209a206180b7f1cb0f3ef3e2 | refs/heads/master | 2023-03-05T07:01:45.166439 | 2021-02-16T08:09:38 | 2021-02-16T08:09:38 | 339,326,148 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7008547186851501,
"alphanum_fraction": 0.7008547186851501,
"avg_line_length": 18.5,
"blob_id": "a8eebdd45fdc976fd22d58fc4db370317f890405",
"content_id": "c35285f2f3a150d83997fd92fcacb67032b9a687",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 234,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 12,
"path": "/frontend/BmiCal.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# Calculating BMI\n\n# collecting variables\nweight = float(input('enter your age: '))\nheight = float(input('please enter your height: '))\n\n# calculations\nBMI = weight / (height * height)\n\n# output\n\nprint('Your body mass index is', BMI)\n"
},
{
"alpha_fraction": 0.5948135852813721,
"alphanum_fraction": 0.6580227017402649,
"avg_line_length": 35.264705657958984,
"blob_id": "f97aee5b7846b7ad07d243884a1e789a98b44bfc",
"content_id": "f7b8a9f4fd4d0072a9928cb5f6cf9340859aef74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1234,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 34,
"path": "/frontend/lesson2.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# list and tuples\n# list is an array that stores multiple values in a single variable\npoints = [12, 23, 45, 22, 32, 23, 34, 54, 32, 26, 21]\n# picking a variable in an array\nprint(points[3]) # prints variable 3 only\nprint(points[2:]) # prints variables above variable 2\nprint(points[:3]) # prints variable below variable 3\nprint(points[4:7]) # prints from 4 to 6\n\n# list with strings\nvegetables = ['spinnach', 'sukumawiki', 'cabbages', 'kales', 'corriander', 'x', 'y']\nprint('The grocery has the following greens', vegetables)\nprint(vegetables[:3])\nprint(type(vegetables))\n\n# advantages of a list\n# :they are dynamic and flexible\n\nvegetables.append('fruits')\nvegetables.remove('x')\nvegetables.insert(3, 'kienyeji')\nprint(vegetables)\n\n# more on list\ncars = [[['Hilux', 'filder'], 'Nissan'], ['Ford', 'Canter'], ['Bike', 'Bycycle']]\nprint(cars)\nprint(cars[0][0][1])\n# =================================================================================\n# tuples are same as list, the only difference is that tuples cannot be appended or changed\nENGLISH = (50,54,67,354,76,765,76,56,46,45,45,34,65,65,65,65,45,76,43)\nprint(ENGLISH)\nprint(ENGLISH[:7])\n# list are mutables- update, tuples are immutable - no updating\nprint(type(ENGLISH))\n\n"
},
{
"alpha_fraction": 0.455089807510376,
"alphanum_fraction": 0.5089820623397827,
"avg_line_length": 15.800000190734863,
"blob_id": "445af3c5fe4fac5357e47146aece6ec30684eba5",
"content_id": "1050b1d1931e5ead9b6b90ca48dad33a83d10741",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 167,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 10,
"path": "/frontend/jsonPassing.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "Car = {\n 'Model': 'Benz',\n 'Seater': 'Six',\n 'Price': 600000,\n 'Color': 'grey',\n 'Make': 'german'\n}\nCar['Weight'] = '500KGS'\ndel Car['Price']\nprint(Car)"
},
{
"alpha_fraction": 0.5975103974342346,
"alphanum_fraction": 0.6099585294723511,
"avg_line_length": 29.25,
"blob_id": "0129bce4f2e3a0ca773a0b4724566fd48fb8c2cb",
"content_id": "f2008157d69682703d2d9663f9e0db09b38e7872",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 241,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 8,
"path": "/frontend/lesson3b.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# loops = repeating a task n-times\n# for loop - uses start, stop, step\n\nfor i in range (1, 5, 1):\n p = float(input('enter amount'))\n r = float(input('enter rate'))\n t = float(input('enter duration'))\n print('interest is ', p*r*t)"
},
{
"alpha_fraction": 0.6707921028137207,
"alphanum_fraction": 0.6856435537338257,
"avg_line_length": 25.933332443237305,
"blob_id": "6fab0dc44e6dcb32ebe1eff3b7539ca81168fff9",
"content_id": "ee7598ed69c44b18d0837f028aef2a6a109efd0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 404,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 15,
"path": "/frontend/lesson2Task.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# PROMPTING A NUMBER ENTERED IF ITS NEGATIVE POSITIVE OR ZERO\nNumber= float(input('Enter a number: '))\n# logic\nif Number>0:\n print('The Number is Positive')\n if Number >100:\n print('get bonus points')\nelif Number<0:\n print('The number is negative')\nelif Number ==0:\n print('The number is zero')\nelse:\n print('Invalid')\n\n# calculations with more logic & more conditions (assignment)\n"
},
{
"alpha_fraction": 0.6596858501434326,
"alphanum_fraction": 0.6858638525009155,
"avg_line_length": 18.100000381469727,
"blob_id": "e16d93fbe878544d4db0ca44576089656fd75692",
"content_id": "5de1afcbdf7890f59e50bf068dad51fcf6ca40ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 20,
"path": "/frontend/lesson1a.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# question creat a simple calc\n# solution\n# prt\n\np = 50000\nr = 5\nt = 4\nemployee = \"Anne\"\n\nprint('Your name is', employee)\nprint('Your principle amount is', p)\nprint('at the rate of', r)\nprint('for', t, 'years')\n\n# calculations\nsimple_interest = p*t*(r/100)\nprint(employee, 'your interest will be', simple_interest, 'ksh')\n\namount = p+simple_interest\nprint('Your amount is', amount)\n"
},
{
"alpha_fraction": 0.6782407164573669,
"alphanum_fraction": 0.7199074029922485,
"avg_line_length": 21.153846740722656,
"blob_id": "3ac863f045f75c6c2fa8aadcaec11b81e139638a",
"content_id": "2b00f3276ded57a87a54ed93424080b0e352a5b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 864,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 39,
"path": "/frontend/lesson1.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "print(5000)\nprint(\"hey there\")\n\n# data types\n# int -whole numbers\n# float - numbers with decimals\n# complex numbers with combined letters like equations\n# list - storing multiple items ie [45,67,87,23]\n# string - combination of letters, numbers and characters\n# tuples -\n# dictionary-\n# sets -\n\n# Int example\n# variables -store values\nage = 10\npoints = 1000\nnumber = 100\n\n# floats\nweight = 67.8\nspeed = 108.9\ntemp = 37.6\n\n# string\nstudent = 'felix'\npassword = 'dgdh32'\n\n# naming - this is how you name your variables\n# rules\n# 1. use any word meaningful.\n# 2. use can use numbers but not at the begining\n# 3. no spacing use underscore, no other symbol\n# 4. variables are case sensitive marks and Marks are different variables\n# 5. variables must be initialized using an equal sigh.\n\nprint(age)\nprint(weight)\nprint(\"My name is\", student, 'I am', weight, 'kgs')\n"
},
{
"alpha_fraction": 0.5820895433425903,
"alphanum_fraction": 0.609808087348938,
"avg_line_length": 19.39130401611328,
"blob_id": "b5567cfe6034afc2cb9bd286eb5dcee8910720b1",
"content_id": "b18e6ca03e56603716c1d41953aa717a81d0f74e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 469,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 23,
"path": "/frontend/computation.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# salary computation\nname = 'Jean Zakwani'\nhrs = 40\nhrt = 6.75\nftwr = 0.2\nstwr = 0.09\n\nGP = hrs*hrt\nFTW = ftwr*GP\nSTW = stwr*GP\n\nTD = FTW+STW\n\nNP = GP-TD\n\nprint('Employee Full Name:', name)\nprint('Number of Hours worked in a week:', hrs, 'hours')\nprint('Hourly Pay Rate:', '$', hrt)\nprint('Gross Pay:', '$', GP)\nprint('Federal Tax Withholding (20%):', '$', FTW)\nprint('State Tax Withholding rate(9%):', '$', STW)\nprint('Total Deduction:', '$', TD)\nprint('Net Pay:', '$', NP)\n"
},
{
"alpha_fraction": 0.4683544337749481,
"alphanum_fraction": 0.49367088079452515,
"avg_line_length": 25.5,
"blob_id": "21b1bf2f82e7c9a1c9236dab9599dc828af6713e",
"content_id": "c25d7dce8a8a80120fa4c4e2903d76eb8b066de7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 6,
"path": "/frontend/calculator.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "x = (int(input('Enter a number you multiply with: ')))\ni = 1\nwhile (i <= 12):\n results = i*x\n print('{} * {} = {}' .format(i, x, results))\n i = i + 1"
},
{
"alpha_fraction": 0.6573556661605835,
"alphanum_fraction": 0.6815642714500427,
"avg_line_length": 25.899999618530273,
"blob_id": "15fd95db8c0aa3cc5ceecfeb5da1c05abce07983",
"content_id": "76a4fcd7932baf306cac6e0e49432abb104a9c5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 537,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 20,
"path": "/frontend/lesson2a.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# operators\n# control statements - if, if else, elif, for loop, nested program\n# if, if else, elif, are for decision making\nweight = float(input('enter your weight: '))\nheight = float(input('please enter your height: '))\n\nBMI = weight/pow(height,2)\n\nprint('Your weight is', weight,'kgs')\nprint('Your height is', height,'meters')\nprint('Your body mass index is', BMI)\n\nif BMI <=17:\n print('Underweight')\nelif BMI>17 and BMI<=22.5:\n print('normal')\nelif BMI>22.5 and BMI<30:\n print('Overweight')\nelse:\n print('see a physician')"
},
{
"alpha_fraction": 0.6129541993141174,
"alphanum_fraction": 0.6334913372993469,
"avg_line_length": 24.360000610351562,
"blob_id": "16c20c578c9a0f464bf687e7080857082c0e0fad",
"content_id": "cdd9293439e58e65c6c9948498e7193116c9d46e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 633,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 25,
"path": "/frontend/lesson3.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "# dictionary stores data using key/ value approach\n# mostly used to store an object data in json format: ie car details\nperson = {'name': 'Ken',\n 'age': 22,\n 'residence': 'nairobi',\n 'weight': 72.5,\n 'height': 1.5,\n 'email': '[email protected]',\n 'marks': 410}\nprint(person)\nprint(person['name'])\nprint(person['email'])\n\n# append a new entry into a dictionary\nperson['marks'] = 500\nprint(person)\n\nperson['address'] = 'Haven Court, Waiyaki Way'\nprint('adding address', person)\ndel person ['weight']\nprint('delete weight', person)\n\n# CRUD\n# Delete the whole dictionary: del person\ndel person"
},
{
"alpha_fraction": 0.5747126340866089,
"alphanum_fraction": 0.6398467421531677,
"avg_line_length": 31.3125,
"blob_id": "9ddb13fb16acd3bb22bd21747f83acf307274301",
"content_id": "195bd19c1fb8fceb2a33021cfd1b610efa34a4a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 522,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 16,
"path": "/frontend/Income_Task_saga.py",
"repo_name": "felixkiptoo9888/Cafe",
"src_encoding": "UTF-8",
"text": "\nFirst_Name = str(input('Enter your first name: '))\nSecond_Name = str(input('Enter your second name: '))\nGross = float(input('Enter your gross salary: '))\nChildren = int(input('Enter the number of children you have: '))\n\nNet_Income = (Gross-(Children*3000))\n\n# tax calculation\nif Net_Income > 50000:\n tax = (0.15*50000) + (0.25*(Net_Income-50000))\n print('Your Income Tax Is', '$', tax)\nelif Net_Income < 500000:\n tax = (0.15*Net_Income)\n print('Your income tax is: ', '$', tax)\nelse:\n print('Invalid')\n\n\n\n\n"
}
] | 12 |
sumitnicmar/PetCover | https://github.com/sumitnicmar/PetCover | e145c3b5dddb946aa05feb23f4ad8e0c17c54707 | a4d478d3e141b9c4e5c0050800aa37e90580fad9 | 4948250bd7ca92e47742bb40e89dfc74c3f50463 | refs/heads/main | 2023-03-10T16:04:40.744012 | 2021-02-15T18:58:02 | 2021-02-15T18:58:02 | 339,175,398 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5787337422370911,
"alphanum_fraction": 0.6461039185523987,
"avg_line_length": 42.85714340209961,
"blob_id": "387a26ce00818261b3b4128ea4c5eab5487ae8a1",
"content_id": "83ebba930d17299ad002f50380f295b610a7bdcb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2536,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 56,
"path": "/projectwork/testapp/models.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.db.models.constraints import UniqueConstraint\n\n# Create your models here.\n\nclass Doctor(models.Model):\n user = models.OneToOneField(User,related_name='doctor', null=True, on_delete=models.CASCADE)\n location_choice = (('kothrud','Kothrud'),('swargate','Swargate'),('wakad','Wakad'),('aundh','Aundh'),('katraj','Katraj'))\n name = models.CharField(max_length=100)\n address = models.CharField(max_length=256)\n location = models.CharField(max_length=20,choices=location_choice,default='kothrud')\n number = models.BigIntegerField(null=True)\n date = models.DateField(default=timezone.now)\n\n def __str__(self):\n return str('{} {}'.format(self.user.first_name,self.user.last_name))\n\nclass Customer(models.Model):\n location_choice = (('kothrud','Kothrud'),('swargate','Swargate'),('wakad','Wakad'),('aundh','Aundh'),('katraj','Katraj'))\n user = models.OneToOneField(User,related_name='profile', null=True, on_delete=models.CASCADE)\n name = models.CharField(max_length=100,null=True)\n address = models.CharField(max_length=256,null=True)\n location = models.CharField(max_length=20,choices=location_choice,default='kothrud')\n number = models.BigIntegerField(null=True)\n date = models.DateField(default=timezone.now)\n\n def __str__(self):\n return str(self.name)\n\nclass Appointment(models.Model):\n TIMESLOT_LIST = (\n ('09:00 – 10:00','09:00 – 10:00'),\n ('10:00 – 11:00','10:00 – 11:00'),\n ('11:00 – 12:00','11:00 – 12:00'),\n ('12:00 – 13:00','12:00 – 13:00'),\n ('13:00 – 14:00','13:00 – 14:00'),\n ('14:00 – 15:00','14:00 – 15:00'),\n ('15:00 – 16:00','15:00 – 16:00'),\n ('16:00 – 17:00','16:00 – 17:00'),\n ('17:00 – 18:00','17:00 – 18:00')\n )\n STATUS_CHOICE = ((1,'Pending'),(2,'Closed'),(3,'Cancle'))\n doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)\n date = models.DateField()\n timeslot = models.CharField(max_length=20, choices=TIMESLOT_LIST)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n status = models.SmallIntegerField(choices=STATUS_CHOICE,default=1)\n today = models.BooleanField(default=False)\n\n class Meta:\n unique_together = ['doctor','date','timeslot']\n\n def __str__(self):\n return str('Appointment ID-{} on date {}'.format(self.id,self.date))\n\n\n \n\n"
},
{
"alpha_fraction": 0.28111886978149414,
"alphanum_fraction": 0.525874137878418,
"avg_line_length": 38.72222137451172,
"blob_id": "b56af4914dd111e425bed8e4010a7a535a1a046e",
"content_id": "69e82ab5e79c67ba9d64e040664cba9e387904cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 751,
"license_type": "no_license",
"max_line_length": 372,
"num_lines": 18,
"path": "/projectwork/testapp/migrations/0009_auto_20210202_1301.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-02 07:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0008_auto_20210201_1716'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='appointment',\n name='timeslot',\n field=models.IntegerField(choices=[('09:00 – 10:00', '09:00 – 10:00'), ('10:00 – 11:00', '10:00 – 11:00'), ('11:00 – 12:00', '11:00 – 12:00'), ('12:00 – 13:00', '12:00 – 13:00'), ('13:00 – 14:00', '13:00 – 14:00'), ('14:00 – 15:00', '14:00 – 15:00'), ('15:00 – 16:00', '15:00 – 16:00'), ('16:00 – 17:00', '16:00 – 17:00'), ('17:00 – 18:00', '17:00 – 18:00')]),\n ),\n ]\n"
},
{
"alpha_fraction": 0.34125638008117676,
"alphanum_fraction": 0.5314091444015503,
"avg_line_length": 31.72222137451172,
"blob_id": "95fa8e95e4490b712f9c2f122ffb609925eb826d",
"content_id": "0b0557c161a0d1bdd643eeea0d1a1841dcc001ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 607,
"license_type": "no_license",
"max_line_length": 246,
"num_lines": 18,
"path": "/projectwork/testapp/migrations/0010_auto_20210202_1303.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-02 07:33\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0009_auto_20210202_1301'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='appointment',\n name='timeslot',\n field=models.IntegerField(choices=[(0, '09:00 – 10:00'), (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00')]),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5992779731750488,
"alphanum_fraction": 0.6004813313484192,
"avg_line_length": 30.884614944458008,
"blob_id": "de24f12f84ae5eb2b971f68eda2c8379773932a8",
"content_id": "cd574ba797328f6f6cf62d55b06f7259202f3a5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 831,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 26,
"path": "/projectwork/testapp/decorators.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "from django.http import HttpResponse\nfrom django.shortcuts import redirect\n\ndef authenticaton(view_func):\n def wraper_func(request,*args,**kwargs):\n if request.user.is_authenticated:\n return redirect('userhome')\n else:\n return view_func(request,*args,**kwargs)\n return wraper_func\n\ndef allowed_users(allowed_rolls=[]):\n def decorator(view_func):\n def wraper_func(request,*args,**kwargs):\n\n group = None\n if request.user.groups.exists():\n group = request.user.groups.all()[0].name\n\n if group in allowed_rolls:\n return view_func(request,*args,**kwargs)\n \n else:\n return HttpResponse('You are not authorised to view this page')\n return wraper_func\n return decorator\n\n\n"
},
{
"alpha_fraction": 0.5438144207000732,
"alphanum_fraction": 0.592783510684967,
"avg_line_length": 20.55555534362793,
"blob_id": "dc96a3ac353fee064720e8ca51d64b5aa4cb02c7",
"content_id": "9e00b2dd9da17e4dbe33e133edddc2ddd5395022",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 388,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 18,
"path": "/projectwork/testapp/migrations/0003_auto_20210130_2238.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-01-30 17:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0002_appointment_doctor'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='doctor',\n name='number',\n field=models.BigIntegerField(null=True),\n ),\n ]\n"
},
{
"alpha_fraction": 0.8285714387893677,
"alphanum_fraction": 0.8285714387893677,
"avg_line_length": 25.25,
"blob_id": "c42e8060d252993cf746c650b64cc949994c1975",
"content_id": "7091c22bfd579ed0c4d1e728648d8babc0074c14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 8,
"path": "/projectwork/testapp/admin.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom testapp.models import Customer,Doctor,Appointment\n\n# Register your models here.\n\nadmin.site.register(Customer)\nadmin.site.register(Doctor)\nadmin.site.register(Appointment)\n"
},
{
"alpha_fraction": 0.502525269985199,
"alphanum_fraction": 0.5883838534355164,
"avg_line_length": 21,
"blob_id": "ea397f37bba9d1c79b2e844a05d3dadb8c1ff4c2",
"content_id": "00f9fa5062c06a9cf40156a64f847b30ebaf1988",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 396,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 18,
"path": "/projectwork/testapp/migrations/0016_customer_name.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-14 15:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0015_auto_20210214_2039'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='customer',\n name='name',\n field=models.CharField(max_length=100, null=True),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5144454836845398,
"alphanum_fraction": 0.5661696195602417,
"avg_line_length": 48.906978607177734,
"blob_id": "51231b4d0db7cb8b2952d330fd1f54ee806cb3d0",
"content_id": "d935132cd47a0053b0b5aa397f3f35d8301a24bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2164,
"license_type": "no_license",
"max_line_length": 258,
"num_lines": 43,
"path": "/projectwork/testapp/migrations/0002_appointment_doctor.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-01-30 16:54\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('testapp', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Doctor',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('address', models.CharField(max_length=256)),\n ('location', models.CharField(choices=[('kothrud', 'Kothrud'), ('swargate', 'Swargate'), ('wakad', 'Wakad'), ('aundh', 'Aundh'), ('katraj', 'Katraj')], default='kothrud', max_length=20)),\n ('number', models.IntegerField()),\n ('email', models.EmailField(max_length=100)),\n ('date', models.DateField(default=django.utils.timezone.now)),\n ('user', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='doctor', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Appointment',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('date', models.DateField()),\n ('timeslot', models.IntegerField(choices=[(0, '09:00 – 10:00'), (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00')])),\n ('doctor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='testapp.doctor')),\n ('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='testapp.customer')),\n ],\n options={\n 'unique_together': {('doctor', 'date', 'timeslot')},\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.47685185074806213,
"alphanum_fraction": 0.5486111044883728,
"avg_line_length": 19.571428298950195,
"blob_id": "ee7a412bf4dfd743f5d3b97f22cf763774ddf4e1",
"content_id": "9a5fc53025e36279d146e55519e4c2ca80d30ed5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 432,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 21,
"path": "/projectwork/testapp/migrations/0015_auto_20210214_2039.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-14 15:09\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0014_auto_20210209_0032'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='customer',\n name='email',\n ),\n migrations.RemoveField(\n model_name='customer',\n name='name',\n ),\n ]\n"
},
{
"alpha_fraction": 0.6021713614463806,
"alphanum_fraction": 0.6021713614463806,
"avg_line_length": 32.55263137817383,
"blob_id": "30bfe387ab5f2502040abba56c651d4df70774b6",
"content_id": "80a3dba921211998a76bf33efef8f543bfb32070",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2579,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 76,
"path": "/projectwork/testapp/forms.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .models import Customer,Appointment\nfrom datetime import date\n'''from datetimewidget.widgets import DateTimeWidget'''\n\nclass CreateUserForm(UserCreationForm):\n \n class Meta:\n model=User\n fields = ['username', 'email', 'password1', 'password2','first_name','last_name']\n \n def __init__(self, *args, **kwargs):\n super(CreateUserForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs = {'class': 'form-control'}\n\nclass UpdateUserForm(forms.ModelForm):\n \n class Meta:\n model=User\n fields = ['first_name','last_name','email']\n \n def __init__(self, *args, **kwargs):\n super(UpdateUserForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs = {'class': 'form-control'}\n\nclass CustomerForm(forms.ModelForm):\n class Meta:\n model=Customer\n fields = ['number','address','location']\n \n def __init__(self, *args, **kwargs):\n super(CustomerForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs = {'class': 'form-control'}\n \n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\nclass AppointmentForm(forms.ModelForm):\n class Meta:\n model = Appointment\n fields = ['doctor','date','timeslot']\n widgets = {'date':DateInput()}\n \n def clean_date(self):\n day = self.cleaned_data['date']\n if day <= date.today():\n raise forms.ValidationError('Date should be upcoming (tomorrow or later)')\n return day\n\n def __init__(self, *args, **kwargs):\n super(AppointmentForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs = {'class': 'form-control'}\n\nclass UpdateAppointmentForm(forms.ModelForm):\n class Meta:\n model = Appointment\n fields = ['date','timeslot','doctor']\n widgets = {'date':DateInput()}\n\n def clean_date(self):\n day = self.cleaned_data['date']\n if day <= date.today():\n raise forms.ValidationError('Date should be upcoming (tomorrow or later)')\n return day\n\n def __init__(self, *args, **kwargs):\n super(UpdateAppointmentForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.widget.attrs = {'class': 'form-control'}\n\n\n \n\n \n \n\n\n\n "
},
{
"alpha_fraction": 0.427839457988739,
"alphanum_fraction": 0.6097352504730225,
"avg_line_length": 44.03845977783203,
"blob_id": "96411d36af6e59d6705a3d8df729fb63abb50b3f",
"content_id": "e5893af7a58ca726d07a0438259bb5b97a2012f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1207,
"license_type": "no_license",
"max_line_length": 492,
"num_lines": 26,
"path": "/projectwork/testapp/migrations/0011_auto_20210202_2101.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-02 15:31\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('testapp', '0010_auto_20210202_1303'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='appointment',\n name='timeslot',\n field=models.CharField(choices=[('09:00\\xa0–\\xa010:00', '09:00\\xa0–\\xa010:00'), ('10:00\\xa0–\\xa011:00', '10:00\\xa0–\\xa011:00'), ('11:00\\xa0–\\xa012:00', '11:00\\xa0–\\xa012:00'), ('12:00\\xa0–\\xa013:00', '12:00\\xa0–\\xa013:00'), ('13:00\\xa0–\\xa014:00', '13:00\\xa0–\\xa014:00'), ('14:00\\xa0–\\xa015:00', '14:00\\xa0–\\xa015:00'), ('15:00\\xa0–\\xa016:00', '15:00\\xa0–\\xa016:00'), ('16:00\\xa0–\\xa017:00', '16:00\\xa0–\\xa017:00'), ('17:00\\xa0–\\xa018:00', '17:00\\xa0–\\xa018:00')], max_length=20),\n ),\n migrations.AlterField(\n model_name='appointment',\n name='user',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auth.user'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6804585456848145,
"alphanum_fraction": 0.687623143196106,
"avg_line_length": 34.088050842285156,
"blob_id": "3d08dd30419abd4e1c200e0a1bbb1839a0229efa",
"content_id": "8e73a41fd121eb12b6c19c867214fcd1ff19fb53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5583,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 159,
"path": "/projectwork/testapp/views.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render,redirect\nfrom testapp.forms import CreateUserForm,CustomerForm,AppointmentForm,UpdateAppointmentForm,UpdateUserForm\nfrom django.shortcuts import get_object_or_404\nfrom testapp.models import Appointment\n\nfrom django.contrib.auth.models import User\n\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom .decorators import authenticaton,allowed_users\n\n\nfrom django.dispatch import receiver\n\nfrom testapp.models import Customer\nfrom django.contrib.auth.models import Group\n\nfrom datetime import date\n\n# Create your views here.\n# Customer views\n@authenticaton\ndef homeview(request):\n return render(request,'testapp/home.html')\n\n@authenticaton\ndef registration(request):\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, 'Account was created for ' + username)\n return redirect ('login')\n \n return render(request,'testapp/registration.html',{'form':form})\n\n@authenticaton\ndef loginpage(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(redirect,username=username,password=password)\n if user is not None:\n login(request,user)\n return redirect('userhome')\n else:\n messages.info(request,'Username or password is incorrect')\n return render(request,'testapp/login.html')\n\ndef logoutuser(request):\n logout(request)\n return redirect('home')\n\n@login_required(login_url='login')\ndef userhome(request):\n return render(request,'testapp/userhome.html')\n\n\n@login_required(login_url='login')\ndef appointmentview(request):\n if request.method == 'POST':\n form = AppointmentForm(request.POST)\n if form.is_valid():\n form = form.save(commit=False)\n form.user = request.user\n form.save()\n return redirect('userhome')\n if request.method == 'GET':\n form = AppointmentForm()\n return render (request,'testapp/appointment.html',{'form':form})\n\n\n@login_required(login_url='login')\ndef displayinfo(request):\n current_id = request.user.id\n info = Customer.objects.get(user_id=current_id)\n return render (request,'testapp/displayinfo.html',{'info':info})\n\n@login_required(login_url='login')\ndef display_history(request):\n form = Appointment.objects.filter(user_id = request.user.id).order_by('-date')\n formdoc = Appointment.objects.filter(doctor__user_id = request.user.id).order_by('-date')\n return render(request,'testapp/display_history.html',{'form':form,'formdoc':formdoc})\n\n@login_required(login_url='login')\ndef display_appointment(request,id):\n form = Appointment.objects.filter(id=id)\n return render(request,'testapp/display_allhistory.html',{'form':form})\n\n@login_required(login_url='login')\ndef upcoming_appointment(request):\n form = Appointment.objects.filter(user_id = request.user.id, date__gte=date.today(),status=1).order_by('date','timeslot')\n docform = Appointment.objects.filter(doctor__user_id = request.user.id, date__gte=date.today(),status=1).order_by('date','timeslot')\n return render(request,'testapp/upcoming_appointment.html',{'form':form,'docform':docform})\n\n@login_required(login_url='login')\ndef update_appointment(request,id):\n update = get_object_or_404(Appointment,id=id,user_id=request.user.id)\n\n if request.method=='POST':\n form = UpdateAppointmentForm(request.POST,instance=update)\n \n if form.is_valid():\n form = form.save(commit=False)\n form.user = request.user\n form.save()\n return redirect('upcoming')\n \n else:\n form = UpdateAppointmentForm(instance=update)\n \n return render(request,'testapp/updateappointment.html',{'form':form})\n\n@login_required(login_url='login')\ndef change_status(request,id):\n status = get_object_or_404(Appointment,id=id)\n if status.status == 1:\n status.status = 3\n status.save()\n return redirect('userhome')\n\n@login_required(login_url='login')\ndef close_status(request,id):\n status = get_object_or_404(Appointment,id=id)\n if status.status == 1:\n status.status = 2\n status.save()\n return redirect('userhome')\n\n@login_required(login_url='login')\ndef update_customerform(request):\n\n update_profile_customer = get_object_or_404(Customer,user_id=request.user.id)\n update_profile_user = get_object_or_404(User,id=request.user.id)\n\n if request.method == 'POST':\n form1 = CustomerForm(request.POST,instance=update_profile_customer)\n form2 = UpdateUserForm(request.POST,instance=update_profile_user)\n if form1.is_valid() and form2.is_valid():\n profile1 = form1.save(commit=False)\n profile1.save()\n profile2 = form2.save(commit=False)\n profile2.save()\n return redirect ('userhome')\n else:\n form1 = CustomerForm(instance=update_profile_customer)\n form2 = UpdateUserForm(instance=update_profile_user)\n return render (request,'testapp/updatecuform.html',{'form1':form1,'form2':form2})\n\n@login_required(login_url='login')\ndef delete_user(request,id):\n user = User.objects.get(id=request.user.id)\n user.delete()\n return redirect('home')\n\n# Doctor views\n\n\n\n\n"
},
{
"alpha_fraction": 0.6064981818199158,
"alphanum_fraction": 0.6624549031257629,
"avg_line_length": 26.700000762939453,
"blob_id": "9fa566b1e2b4080c8b5bd204b010bbe5686b9fb8",
"content_id": "957ac991ff87043dcda82597f39e8efeb041891e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 554,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 20,
"path": "/projectwork/testapp/migrations/0004_auto_20210201_1458.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-01 09:28\n\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0003_auto_20210130_2238'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='appointment',\n name='patient',\n field=models.ForeignKey(default=django.contrib.auth.models.User, on_delete=django.db.models.deletion.CASCADE, to='testapp.customer'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7037463784217834,
"alphanum_fraction": 0.7083573341369629,
"avg_line_length": 44.657894134521484,
"blob_id": "9884cceb0f2e3faa828955a38964444f6948ccf2",
"content_id": "425401df7ced006709a5c30d98e7a64dabefa693",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1735,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 38,
"path": "/projectwork/projectwork/urls.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "\"\"\"projectwork URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom testapp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.homeview,name='home'),\n path('register/',views.registration,name='register'),\n path('login/',views.loginpage,name='login'),\n path('userhome',views.userhome,name='userhome'),\n path('logout/',views.logoutuser,name='logout'),\n path('updateform/',views.update_customerform,name='updateform'),\n path('deleteuser/<int:id>/',views.delete_user,name='deleteuser'),\n path('displayinfo/',views.displayinfo,name='displayinfo'),\n path('appointment/',views.appointmentview,name='appointment'),\n path('history/',views.display_history,name='history'),\n path('allhistory/<int:id>/',views.display_appointment,name='allhistory'),\n path('upcoming',views.upcoming_appointment,name='upcoming'),\n path('updateappointment/<int:id>/',views.update_appointment,name='updateappointment'),\n path('status/<int:id>/',views.change_status,name='statuschange'),\n path('clstatus/<int:id>/',views.close_status,name='closestatus'),\n\n]\n"
},
{
"alpha_fraction": 0.5249999761581421,
"alphanum_fraction": 0.5954545736312866,
"avg_line_length": 23.44444465637207,
"blob_id": "1c738726052af80ea5d243bfab27a55d4012d344",
"content_id": "a244e6383a293df517f549094fca3b5c8c4655f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 440,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 18,
"path": "/projectwork/testapp/migrations/0012_appointment_status.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-05 07:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('testapp', '0011_auto_20210202_2101'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='appointment',\n name='status',\n field=models.BooleanField(choices=[(False, 'Pending'), (True, 'Closed')], default=False),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5781466364860535,
"alphanum_fraction": 0.6224066615104675,
"avg_line_length": 26.80769157409668,
"blob_id": "a78b23f189571be5d0b660be116b863b64d5d070",
"content_id": "4bf0a2d263c64955471cadc4518778bd77c7feaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 723,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 26,
"path": "/projectwork/testapp/migrations/0006_auto_20210201_1633.py",
"repo_name": "sumitnicmar/PetCover",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.1.3 on 2021-02-01 11:03\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('testapp', '0005_auto_20210201_1557'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='appointment',\n name='patient',\n ),\n migrations.AddField(\n model_name='appointment',\n name='user',\n field=models.ForeignKey(default=2, on_delete=django.db.models.deletion.CASCADE, to='auth.user'),\n preserve_default=False,\n ),\n ]\n"
}
] | 16 |
noahwoelki/random | https://github.com/noahwoelki/random | 780f8e0f3be7c9870687267f430f7e9826fa479f | 59b5fc272865eec31637dd96b8f2f034bb403de5 | 6965340a3b357614d12e6a74959479ad6f542a14 | refs/heads/main | 2023-01-19T23:19:33.570384 | 2020-12-01T12:53:12 | 2020-12-01T12:53:12 | 317,540,031 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5277777910232544,
"alphanum_fraction": 0.5324074029922485,
"avg_line_length": 15.833333015441895,
"blob_id": "6067a2c145c2a688c7b689663739493fc39bb12d",
"content_id": "ad8ac3bb572d8d3961e41056a617dfd012e25439",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 432,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 24,
"path": "/main.py",
"repo_name": "noahwoelki/random",
"src_encoding": "UTF-8",
"text": "\r\n\r\ndef my_decorator(func):\r\n def wrapper(a, n):\r\n print(generator.__doc__)\r\n func(a, n)\r\n return wrapper\r\n\r\n\r\ndef generator(a, n):\r\n \"\"\"Description of this function:\r\n\r\n This function calculates the different powers of input a:\r\n\r\n a^i with i<= n\r\n\r\n \"\"\"\r\n for i in range(n):\r\n print(a, \"^\", i, \"=\")\r\n print(pow(a, i))\r\n\r\n\r\ngenerator = my_decorator(generator)\r\n\r\n\r\ngenerator(4, 5)\r\n"
}
] | 1 |
jzc/webpy | https://github.com/jzc/webpy | 4263b171c8dd6a43602d330aa75c2e776a834468 | 2f838ae33a5338534b35579bdb0e591a08f79607 | 92941f8a8c39b4bdac94fc7249e1f9c88682cfe7 | refs/heads/master | 2020-05-01T14:36:59.405649 | 2019-03-25T04:38:48 | 2019-03-25T04:38:48 | 177,524,852 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5536755919456482,
"alphanum_fraction": 0.5542590618133545,
"avg_line_length": 23.154930114746094,
"blob_id": "af4f15d922b846de4c3302495ca56c5b2ec40d4a",
"content_id": "488088056edce3761e8f13504c78ab25a19927ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1714,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 71,
"path": "/webpy.py",
"repo_name": "jzc/webpy",
"src_encoding": "UTF-8",
"text": "import ast\nfrom itertools import chain, islice, tee\n\nclass JSCompiler(ast.NodeVisitor):\n def generic_visit(self, node):\n raise ValueError(f\"Unsupported node: {node.__class__.__name__}\")\n\n def visit_Module(self, node):\n return \";\\n\".join(chain((self.visit(stmt) for stmt in node.body), ['']))\n\n def visit_Expr(self, node):\n return self.visit(node.value)\n\n def visit_Num(self, node):\n return str(node.n)\n\n def visit_Name(self, node):\n return node.id\n\n def visit_BinOp(self, node):\n left = self.visit(node.left)\n op = self.visit(node.op)\n right = self.visit(node.right)\n return f\"{left} {op} {right}\"\n\n\n def visit_Compare(self, node):\n comparators = chain([node.left], node.comparators)\n comparators = map(self.visit, comparators)\n lefts, rights = tee(comparators)\n rights = islice(rights, 1, None)\n ops = map(self.visit, node.ops)\n return \" && \".join(\n f\"({left} {op} {right})\" \n for left, op, right in zip(lefts, ops, rights)\n )\n \n def visit_Add(self, node):\n return \"+\"\n\n def visit_Sub(self, node):\n return \"-\"\n\n def visit_Mult(self, node):\n return \"*\"\n\n def visit_Div(self, node):\n return \"/\"\n\n def visit_Lt(self, node):\n return \"<\"\n\n def visit_LtE(self, node):\n return \"<=\"\n\n def visit_Gt(self, node):\n return \">\"\n\n def visit_GtE(self, node):\n return \">=\"\n\n def visit_Eq(self, node):\n return \"===\"\n\n def visit_NotEq(self, node):\n return \"!==\"\n\n @classmethod\n def compile(cls, s):\n compiler = cls()\n return compiler.visit(ast.parse(s))"
}
] | 1 |
nicolas-dlp/Tec-Info | https://github.com/nicolas-dlp/Tec-Info | e8676995d9ee45e7117b30d6d22961e5d5d24e2b | 23198efa8db16bae4014dbfae8a79f047d83390d | 86a943d5a0f17ff00559616cc946bb6d55a40858 | refs/heads/master | 2020-05-31T21:05:43.076584 | 2019-06-06T01:50:50 | 2019-06-06T01:50:50 | 190,491,620 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6633039116859436,
"alphanum_fraction": 0.6633039116859436,
"avg_line_length": 24.366666793823242,
"blob_id": "20f5f1e1be0c7ca2c873111141ea1dae89125f92",
"content_id": "44cd5bf5a99a22e23cc983b65fe74deebf747562",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 793,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 30,
"path": "/Tec+Info.py",
"repo_name": "nicolas-dlp/Tec-Info",
"src_encoding": "UTF-8",
"text": "#descargar procesador lenguaje\r\nimport nltk\r\nnltk.download()\r\n#descargar fichero de chat\r\n#pip install chatterbot\r\n#iniciar chatterbot\r\nfrom chtatterbot import ChatBot\r\nchatbot = ChatBot(\r\n \"Bot TecInfo\"\r\n trainer = \"chatterbot.trainers.ChatterbotCorpusTrainer\"\r\n)\r\nchatbot.train(\r\n \"chatterbot.corpus.spanish\"\r\n)\r\n#el input debe iniciar con >\r\nwhile True:\r\n usuario = input(\">\")\r\n respuesta = chatbot.get_response(usuario)\r\n print (\"BOT \"+str(respuesta))\r\n#debe entrenarse con conceptos necesarios, entonces\r\nChatbot = ChatBot(\r\n \"Bot TecInfo\"\r\n trainer = \"chatterbot.trainers.ListTrainers\")\r\n chatbot.train([\r\n \"precio cacao\",\r\n \"precio del cacao\",\r\n \"precio del cacao hoy\",\r\n \"precio cacao hoy\",\r\n \"clima_municipio\",\r\n ])\r\n\r\n"
}
] | 1 |
shivin9/will-your-essay-make-it- | https://github.com/shivin9/will-your-essay-make-it- | beef23d84144bcb0f4c6764ae5522a12a14c83e6 | ecb0f594f60100b3035c23ef56370ce2e7f69bca | cc5b5b8847885e5cb83714beddcecc34b77ee67e | refs/heads/master | 2016-08-09T07:27:01.056062 | 2016-01-13T05:46:10 | 2016-01-13T05:46:10 | 48,949,629 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.738095223903656,
"alphanum_fraction": 0.738095223903656,
"avg_line_length": 13,
"blob_id": "0962fdffa5d8c21df7079164defddeb4cf3c2574",
"content_id": "c820b54348ce8743cf2e4db2e4499769b4e85610",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 84,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 6,
"path": "/src/clean.py",
"repo_name": "shivin9/will-your-essay-make-it-",
"src_encoding": "UTF-8",
"text": "import os\nimport nltk\ncur = os.getcwd()\nfor filename in os.listdir(cur):\n\nprint cur\n"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.7352941036224365,
"avg_line_length": 21.66666603088379,
"blob_id": "b306583bbfb074fb85434b53125294b8a36b49d8",
"content_id": "2c746cee8f03462bc18f24ba2db6b6b390986d4a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 3,
"path": "/README.md",
"repo_name": "shivin9/will-your-essay-make-it-",
"src_encoding": "UTF-8",
"text": "# will-your-essay-make-it-\n\ncleaned the book, now we have 50 essays\n"
},
{
"alpha_fraction": 0.5789473652839661,
"alphanum_fraction": 0.6105263233184814,
"avg_line_length": 22.75,
"blob_id": "5986da912a6ea0febb00ee92c8a3f1dd6be30c88",
"content_id": "73829f1a5925306d41111b196c6194ba2a6b754a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 475,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 20,
"path": "/corpora/clean_titles.py",
"repo_name": "shivin9/will-your-essay-make-it-",
"src_encoding": "UTF-8",
"text": "import re\nf = open('book','rw')\nstr1 = f.read().decode('utf8','ignore').encode('ascii','ignore')\n\n##separate the essays\nessays = str1.split(\"##\")\n\n\nwith open(essays[0].split('\\n',1)[0],'w') as file1:\n file1.write(essays[0])\nfile1.close()\n\n## place the essays in different files\nfor i in range(1, len(essays)):\n essay = essays[i]\n title = essay.split('\\n')\n name = \"./books/\"+title[1]\n with open(name,'w') as file1:\n file1.write(essay)\n file1.close()\n"
}
] | 3 |
dotJPG/dotJPG.github.io | https://github.com/dotJPG/dotJPG.github.io | 06fd882fb7fe2e758cf4e1b09140345868009c03 | 26a795b67473b564f620a1dd28fefad7936e74ed | d054493be62074ee23b3395af01bc6ad1b9de0aa | refs/heads/master | 2021-09-14T02:09:45.039836 | 2018-02-14T01:42:33 | 2018-02-14T01:42:33 | 105,667,497 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6087743043899536,
"alphanum_fraction": 0.617367684841156,
"avg_line_length": 20.5670108795166,
"blob_id": "e9d9028826027fc118a8b1a4737b52c04d1b1a18",
"content_id": "53316591336f727d00d665aef4a6ed1db1ae878f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2211,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 97,
"path": "/successFail.py",
"repo_name": "dotJPG/dotJPG.github.io",
"src_encoding": "UTF-8",
"text": "import bs4, csv, pandas\r\nfrom datetime import datetime\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\nclass successFail(object):\r\n\r\n\tresultsCSV = ''\r\n\tindexHTML = ''\r\n\tstatisticsCSV = ''\r\n\timagePath = ''\r\n\tfailCount = 0\r\n\t\r\n\t\r\n\t\r\n\tdef __init__(self, resultsCSV, indexHTML, statisticsCSV, imagePath):\r\n\t\tself.resultsCSV = resultsCSV\r\n\t\tself.indexHTML = indexHTML\r\n\t\tself.statisticsCSV = statisticsCSV\r\n\t\tself.imagePath = imagePath\r\n\t\t\t\t\r\n\tdef checkFailures(self):\r\n\t\twith open(self.resultsCSV) as resultsFile:\r\n\t\t\treader = csv.reader(resultsFile, delimiter = ',')\r\n\t\t\tfor row in reader:\r\n\t\t\t\tif \"FAILURE\" == row[2]:\r\n\t\t\t\t\tself.failCount += 1\r\n\t\t\t\tif \"ERROR\" == row[2]:\r\n\t\t\t\t\tself.failCount += 1\r\n\t\t\t\t\t\r\n\tdef areFails(self):\r\n\t\tif self.failCount > 0:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False \r\n\t\t\r\n\t\t\r\n\tdef count(self):\r\n\t\treturn self.failCount\r\n\t\r\n\t\r\n\tdef setButton(self, button):\r\n\t\twith open(self.indexHTML, \"r\") as index:\r\n\t\t\ttxt = index.read()\r\n\t\t\tsoup = bs4.BeautifulSoup(txt)\r\n\t\t\tfailButton = soup.find('a')\r\n\t\t\tfailButton['class'] = button\r\n\t\t\t\r\n\t\twith open(self.indexHTML, \"w\") as out:\r\n\t\t\tout.write(str(soup))\r\n\t\t\t\r\n\tdef updateStatistics(self):\r\n\t\r\n\t\tlines = []\r\n\t\twith open(self.statisticsCSV, \"r\") as stats:\r\n\t\t\treader = csv.reader(stats, delimiter= ',')\r\n\t\t\tfor row in reader:\r\n\t\t\t\tlines.append(row)\r\n\r\n\t\tfor line in lines:\r\n\t\t\tprint (line)\r\n\t\t\t\r\n\t\tlines.pop(1)\r\n\t\tlines.append([datetime.strftime(datetime.now(), '%b %d'), str(self.count())])\r\n\t\t\t\r\n\r\n\t\tfor line in lines:\r\n\t\t\tprint (line)\r\n\t\t\t\r\n\t\t\t\r\n\t\twith open(self.statisticsCSV, \"w\") as statsout:\r\n\t\t\twriter = csv.writer(statsout, dialect='excel', lineterminator = '\\n')\r\n\t\t\tfor line in lines:\r\n\t\t\t\twriter.writerow(line)\r\n\t\t\t\t\t\t\r\n\r\n\tdef drawGraph(self):\r\n\t\tcolnames = ['Date', 'Errors']\r\n\t\tdata = pandas.read_csv(self.statisticsCSV, header=None, names=colnames)\r\n\r\n\t\tdates = data.Date.tolist()\r\n\r\n\t\terrors = data.Errors.tolist()\r\n\t\r\n\t\ty_pos = range(len(dates) - 1)\r\n\r\n\r\n\t\tplt.bar(y_pos, errors[1:], align='center', color='#f09100')\r\n\t\tplt.xticks(y_pos, dates[1:])\r\n\t\tplt.ylim([0,5])\r\n\t\tplt.xlabel('Day')\r\n\t\tplt.ylabel('Errors & Failures')\r\n\t\tplt.title('Site Link Performance')\r\n\t\tplt.savefig(self.imagePath)\r\n\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t"
},
{
"alpha_fraction": 0.5910041928291321,
"alphanum_fraction": 0.6391213536262512,
"avg_line_length": 58.625,
"blob_id": "a2351940c0cc726c81d1e8c2933d61619682025b",
"content_id": "f7db89a282a70fc46a75239f5750d23d73c480e4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 956,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 16,
"path": "/Wraith/configs/user.properties",
"repo_name": "dotJPG/dotJPG.github.io",
"src_encoding": "UTF-8",
"text": "1.\t# Change this parameter if you want to change the granularity of over time graphs. \n2.\t# Granularity must be higher than 1000 (1second) otherwise Throughput graphs will be incorrect \n3.\t# see Bug 60149 \n4.\tjmeter.reportgenerator.overall_granularity=10000 \n5.\t \n6.\t Change this parameter if you want to change the granularity of Response time distribution \n7.\t# Set to 500 ms by default \n8.\tjmeter.reportgenerator.graph.responseTimeDistribution.property.set_granularity=10000 \n9.\t \n10.\t#--------------------------------------------------------------------------- \n11.\t# Results file configuration \n12.\t#--------------------------------------------------------------------------- \n13.\t# Timestamp format - this only affects CSV output files \n14.\t# legitimate values: none, ms, or a format suitable for SimpleDateFormat \n15.\tjmeter.save.saveservice.timestamp_format=ms \n16.\tjmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS \n"
},
{
"alpha_fraction": 0.7813267707824707,
"alphanum_fraction": 0.7813267707824707,
"avg_line_length": 27.214284896850586,
"blob_id": "39be5b4463c6f0320f9798a881f9d24fa82d114a",
"content_id": "7b65c8f14a2eeb5a990fb4589af81f6b204886a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 407,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 14,
"path": "/updatePage.py",
"repo_name": "dotJPG/dotJPG.github.io",
"src_encoding": "UTF-8",
"text": "import successFail\r\n\r\n\r\nresultOrganizer = successFail.successFail('Serenity/results.csv', 'index.html', 'statistics/weekPerformance.csv', 'img/barGraph.png')\r\n\r\nresultOrganizer.checkFailures()\r\n\r\nif resultOrganizer.areFails():\r\n\tresultOrganizer.setButton('btn btn-danger btn-lg')\r\nelse:\r\n\tresultOrganizer.setButton('btn btn-success btn-lg')\r\n\r\nresultOrganizer.updateStatistics()\r\nresultOrganizer.drawGraph()"
}
] | 3 |
anc1revv/coding_practice | https://github.com/anc1revv/coding_practice | f067dfd333253ef9aa7646816fa99504531e13f2 | 32cd0bdde409b7d1c256355252ba6281d2d9a265 | fae741b3f373a88086473c95ad68aedc08f3382c | refs/heads/master | 2020-12-29T02:31:53.063787 | 2018-01-12T16:39:21 | 2018-01-12T16:39:21 | 54,278,823 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6849173307418823,
"alphanum_fraction": 0.692148745059967,
"avg_line_length": 20.065217971801758,
"blob_id": "7dfc5f415bfaff4f5b5bc216bc1f5a6c809b156a",
"content_id": "958409f4776c225d270fb373ee0d192f1503d61c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 968,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 46,
"path": "/ctci/array_and_strings/unique_characters.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "# Implement an algorithm to determine if a string has all unique\n# characters. What if you cannot use additional data structures?\n\ndef check_unique(input_str):\n\tprint \"Checking string: {0}\".format(input_str)\n\n\tchar_set = set()\n\n\tfor char in input_str:\n\t\tif char in char_set:\n\t\t\treturn False\n\t\telse:\n\t\t\tchar_set.add(char)\n\n\treturn True\n\ndef check_unique_without_ds(input_str):\n\tprint \"Checking string without ds: {0}\".format(input_str)\n\tif not input_str or len(input_str) < 1:\n\t\tprint \"Invalid String\"\n\t\treturn False\n\n\tindex = 0\n\tfor outer_letter in input_str:\n\t\tindex =+ index + 1\n\t\tprint \"outer letter: {0}\".format(outer_letter)\n\t\tfor inner_letter in input_str[index:]:\n\t\t\tprint \"inner letter:{0}\".format(inner_letter)\n\t\t\tif outer_letter == inner_letter:\n\t\t\t\treturn False\n\n\n\treturn True\n\n\ndef main():\n\thello = \"hello\"\n\tandrew = \"andrew\"\n\n\tprint check_unique(hello)\n\tprint check_unique(andrew)\n\n\tprint check_unique_without_ds(hello)\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.6213873028755188,
"alphanum_fraction": 0.6372832655906677,
"avg_line_length": 16.769229888916016,
"blob_id": "d4b76a729891358e4e63dc28470e8fe1dcb15377",
"content_id": "9c2f3f5c1959511efc65b2e3f3fcf4b6782e672a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 692,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 39,
"path": "/data_structures/stack.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "class stack:\n\tdef __init__(self):\n\t\tself.the_stack = []\n\n\tdef push(self, value):\n\t\tself.the_stack.append(value)\n\n\tdef pop(self):\n\t\tself.the_stack = self.the_stack[:-1]\n\n\tdef __str__(self):\n\t\tstr_list = []\n\t\tfor item in self.the_stack:\n\t\t\tstr_list.append(str(item))\n\n\t\treturn ','.join(str_list)\n\n\ndef main():\n\tprint \"hh\"\n\tmy_new_stack = stack()\n\tmy_new_stack.push(1)\n\tmy_new_stack.push(5)\n\tmy_new_stack.push(3)\n\tmy_new_stack.push(4)\n\tmy_new_stack.push(5)\n\tmy_new_stack.push(6)\n\tmy_new_stack.push(7)\n\tmy_new_stack.push(8)\n\tmy_new_stack.pop()\n\tprint my_new_stack\n\n\tmy_other_stack = stack()\n\tmy_other_stack.push(4)\n\tmy_other_stack.push(1)\n\tprint my_other_stack\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.6734693646430969,
"alphanum_fraction": 0.6755102276802063,
"avg_line_length": 20.34782600402832,
"blob_id": "e9ffcaced1121fa20de7c5f4df840bc8821a3c58",
"content_id": "dd8f3891c2c4434c01007bd3cc53e8afb54d6d06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 490,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 23,
"path": "/leetcode/easy/letter_capitalize.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nUsing the Python language, have the function LetterCapitalize(str) take the str \nparameter being passed and capitalize the first letter of each word. \nWords will be separated by only one space. \n\n'''\ndef letter_capitalize(input_str):\n\tlist_words = input_str.split(\" \")\n\n\t\n\tfor word in list_words:\n\t\tfor i in range(len(word)):\n\t\t\tif i == 0:\n\n\n\n\treturn ' '.join(list_words)\n\ndef main():\n input_str = \"hello bye\"\n print letter_capitalize(input_str)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6125873923301697,
"alphanum_fraction": 0.6405594348907471,
"avg_line_length": 20.636363983154297,
"blob_id": "f8807f972f04192b0681c0347336fead32bb76ca",
"content_id": "b85a05fef1df3800158f4ff33e9fe49947636fbc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 715,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 33,
"path": "/leetcode/easy/add_digits.java",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "/**\n* https://leetcode.com/problems/add-digits/\n*\n* Given a non-negative integer num, repeatedly add all its digits\n* until the result has only one digit.\n*\n* For example:\n* Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. \n* Since 2 has only one digit, return it.\n* \n* Follow up:\n* Could you do it without any loop/recursion in O(1) runtime?\n**/\npublic class add_digits {\n\tstatic int getSingleDigit (int num){\n\t\tint sum=0;\n\t\twhile(num>0){\n\t\t\tint last_digit = num%10;\n\t\t\tsum = sum + last_digit;\n\t\t\tnum = num/10;\n\t\t}\n\t\tif (sum > 9) {\n\t\t\treturn getSingleDigit(sum);\n\t\t} else {\n\t\t\treturn sum;\n\t\t}\n\t}\n\n\tpublic static void main(String[] args){\n\t\tint num = 19;\n\t\tSystem.out.println(getSingleDigit(num));\n\t}\n}\n\n"
},
{
"alpha_fraction": 0.679425835609436,
"alphanum_fraction": 0.7009569406509399,
"avg_line_length": 23.647058486938477,
"blob_id": "78c465e7092094239851d7aec9199840f12a068c",
"content_id": "24307f3cae4c42bc9dad0f2338d07cd34600f7ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 17,
"path": "/leetcode/medium/single_number.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''Given an array of integers, every element appears twice except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?'''\n\n\ndef single_number(input_array):\n\tfor num in input_array:\n\t\t\n\n\treturn rev_string\n\ndef main():\n input_array = [3,4,3,2,2,4,1,5,1]\n print single_number(input_array)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.7428571581840515,
"alphanum_fraction": 0.75,
"avg_line_length": 68.5,
"blob_id": "c6804b7b7a127306f44d83a706b6229ef6ca838c",
"content_id": "8b03ffbc5340512f128c5f8f8b50a0154ec04296",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 140,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 2,
"path": "/facebook/min_and_max.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''Write a function to return minimum and maximum in an array.\nYou program should make minimum number of comparisons. (less than O(2n))'''\n\n"
},
{
"alpha_fraction": 0.6147540807723999,
"alphanum_fraction": 0.6393442749977112,
"avg_line_length": 27.764705657958984,
"blob_id": "7ac9d4f5b7a79273bf36af884c77c161b4788f14",
"content_id": "a5f8c86ca56b9b716f21ee8482a683082e5807ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 488,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 17,
"path": "/leetcode/easy/factorial.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''Using the Python language, have the function FirstFactorial(num) \ntake the num parameter being passed and return the factorial of it \n(ie. if num = 4, return (4 * 3 * 2 * 1)). \nFor the test cases, the range will be between 1 and 18.'''\n\ndef factorial(input_num):\n output_num = 1\n for i in range(1,input_num+1):\n print i\n output_num = output_num*i\n return output_num\n\ndef main():\n input_num = 4\n print factorial(input_num)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6067193746566772,
"alphanum_fraction": 0.6501976251602173,
"avg_line_length": 25.6842098236084,
"blob_id": "0477200668b68d6e13e885413b215fec6c62972e",
"content_id": "540bb3f55463c552b715002f56f1c5375eb4ba0f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 506,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 19,
"path": "/leetcode/easy/move_zeros.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nGiven an array nums, write a function to move all 0's to the end of it \nwhile maintaining the relative order of the non-zero elements.\nFor example, given nums = [0, 1, 0, 3, 12], after calling your function, \nnums should be [1, 3, 12, 0, 0].'''\n\ndef move_zeros(input_array):\n\tfor num in input_array:\n\t\tif num == 0:\n\t\t\tinput_array.remove(0)\n\t\t\tinput_array.append(0)\n\n\treturn input_array\n\ndef main():\n input_array = [0, 1, 0, 3, 12]\n print move_zeros(input_array)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 64,
"blob_id": "3276cbc849fa556a3f6005d24c1eb57d3df3af9b",
"content_id": "98af86ce5f55bee9b1f2add1ed1201cd992fc3b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 64,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 1,
"path": "/facebook/anagrams.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''Given a string list return all the anagrams formed by them'''"
},
{
"alpha_fraction": 0.5422839522361755,
"alphanum_fraction": 0.6009259223937988,
"avg_line_length": 30.163461685180664,
"blob_id": "64ae5657db83b5f6b4e59569e05fea8de4d8cc70",
"content_id": "6ab6da837cd4311f6cd40e84e1a428ebf5f71647",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3240,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 104,
"path": "/dedupe_interview_question/interview_task_creator.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "import csv\nfrom random import randint\n\ndef create_delta4_table():\n user_dict = {}\n for i in range(10000):\n if(randint(1,4) == 4):\n user_dict[i+1] = [randint(5000,7000),randint(0,50),randint(0,1000),randint(6001,8000)]\n\n create_csv(user_dict,'delta4.csv')\n\ndef create_delta3_table():\n user_dict = {}\n for i in range(10000):\n if(randint(1,4) == 3):\n user_dict[i+1] = [randint(4000,5000),randint(0,50),randint(0,1000),randint(4501,6000)]\n\n create_csv(user_dict,'delta3.csv')\n\ndef create_delta2_table():\n user_dict = {}\n for i in range(10000):\n if(randint(1,4) == 2):\n user_dict[i+1] = [randint(3000,4000),randint(0,50),randint(0,1000),randint(3001,4500)]\n\n create_csv(user_dict,'delta2.csv')\n\ndef create_delta1_table():\n user_dict = {}\n for i in range(10000):\n if(randint(1,4) == 1):\n user_dict[i+1] = [randint(2000,3000),randint(0,50),randint(0,1000),randint(2001,3000)]\n\n create_csv(user_dict,'delta1.csv')\n\ndef create_delta0_table():\n user_dict = {}\n for i in range(10000):\n user_dict[i+1] = [randint(0,2000),randint(0,50),randint(0,1000),randint(0,2000)]\n\n create_csv(user_dict,'base_table.csv')\n\ndef dedupe_table(*file_names):\n files = locals().values()\n deduped_table = {}\n\n for f in file_names:\n pick_latest_batch(deduped_table,f)\n\n create_csv(deduped_table,'deduped_table.csv') \n\ndef pick_latest_batch(dedupe_dict, new_file):\n with open(new_file, mode='r') as infile:\n infile.readline() #skip header row\n reader = csv.reader(infile)\n for rows in reader:\n if dedupe_dict.has_key(rows[0]):\n # if the batch_id is greater in the new file, overwrite for that user's row\n if int(rows[4]) > int(dedupe_dict.get(rows[0])[3]):\n dedupe_dict[rows[0]] = rows[1:]\n else:\n dedupe_dict[rows[0]] = rows[1:]\n\n return dedupe_dict\n\ndef file_to_dict(file_name):\n mydict = {}\n with open(file_name, mode='r') as infile:\n reader = csv.reader(infile)\n mydict = {rows[0]:rows[1:] for rows in reader}\n return mydict\n\n\ndef create_csv(user_dict, file_name):\n with open(file_name,'wb') as csvFile:\n csv_writer = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow(['user_id','total_spend','count_saved_items','loyalty_credits','batch_id'])\n for k,v in user_dict.items():\n csv_writer.writerow([k] + v)\n\ndef users_spent_over_twothousand(file_name):\n usercount = 0\n with open(file_name, mode='r') as infile:\n infile.readline() #skip header row\n reader = csv.reader(infile) \n for rows in reader:\n if int(rows[1]) > 2000:\n usercount += 1\n\n return usercount\n\ndef main():\n #print users_spent_over_twothousand('customer_correct_table.csv')\n #print users_spent_over_twothousand('AIQ_Broken_table.csv')\n\n #AIQ_Broken_table\n dedupe_table('delta0.csv','delta1.csv','delta2.csv','delta4.csv')\n '''create_base_table()\n create_delta1_table()\n create_delta2_table()\n create_delta3_table()\n create_delta4_table()'''\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6720647811889648,
"alphanum_fraction": 0.6720647811889648,
"avg_line_length": 29.91666603088379,
"blob_id": "eb7c1bcf0216360d5330721f30800d8e7513a193",
"content_id": "8216fa102c4e908d99fa424568196a7abce8c319",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 741,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 24,
"path": "/leetcode/easy/longest_word.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nUsing the Python language, have the function LongestWord(sen) \ntake the sen parameter being passed and return the largest word in the string.\nIf there are two or more words that are the same length, \nreturn the first word from the string with that length. \nIgnore punctuation and assume sen will not be empty. \n'''\nimport re\ndef longest_word(input_str):\n word_list = input_str.split(\" \")\n longest_word = \"\"\n\n for word in word_list:\n scrubbed_word = re.sub(r'\\W+','',word)\n if len(scrubbed_word) > len(longest_word):\n longest_word = scrubbed_word\n\n return longest_word\n\ndef main():\n input_str = \"longe$%^st word in this sentence\"\n print longest_word(input_str)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6099476218223572,
"alphanum_fraction": 0.6361256837844849,
"avg_line_length": 24.53333282470703,
"blob_id": "f0c217b47c56e0f3ff08de5a1fc8f820edc52a1a",
"content_id": "79828d8c3e3d3f56e4ef4574c2e4aa8d32fa6e02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 382,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 15,
"path": "/leetcode/easy/simple_adding.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nUsing the Python language, have the function SimpleAdding(num) add up all the numbers from 1 to num. \nFor the test cases, the parameter num will be any number from 1 to 1000. \n'''\ndef simple_adding(num):\n total = 0\n for i in range(1,num+1):\n total = total + i\n return total\n\ndef main():\n num = 5\n print simple_adding(num)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.641697883605957,
"alphanum_fraction": 0.6516854166984558,
"avg_line_length": 16.822221755981445,
"blob_id": "55e372fc6fa41faaebcc0b1a94844e4a8b9601ca",
"content_id": "5a4ec53d11a748d94b7ee1537bc656818e2d7725",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 801,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 45,
"path": "/ctci/stacks_and_queues/linked_list.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "class LinkedList():\n\tclass Node:\n\t\tdef __init__(self, value, next):\n\t\t\tself.value = value\n\t\t\tself.next = next\n\n\t\tdef __repr__(self):\n\t\t\treturn self.value\n\n\tdef __init__(self):\n\t\tself.first = None\n\n\tdef isEmpty(self):\n\t\tif self.first:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\tdef appendToList(self, value):\n\t\toldFirst = self.first\n\t\tself.first = LinkedList.Node(value, oldFirst)\n\t\tprint self.first\n\n\tdef __repr__(self):\n\t\tnodes = []\n\t\tfirst = self.first\n\t\tprint type(first)\n\t\tprint \"first: {0}\".format(first)\n\t\twhile first:\n\t\t\tnodes.append(str(first.value))\n\t\t\tfirst = first.next\n\n\t\treturn \n\n\n\ndef main():\n\tlist1 = LinkedList()\n\tprint \"Is List Empty? {0}\".format(list1.isEmpty())\n\tlist1.appendToList(\"firstObjectfromAP\")\n\tlist1.appendToList(\"2ndfromAP\")\n\tprint list1\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.6571428775787354,
"alphanum_fraction": 0.6736263632774353,
"avg_line_length": 20.186046600341797,
"blob_id": "9a3036e4e9609e9e1258c96772cbd4c32d1efc9b",
"content_id": "b437489652268e507ebde88b65f6af5e164d990c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 910,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 43,
"path": "/ctci/array_and_strings/string_compression.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "def string_compress(input_string):\n\tif len(input_string) < 3:\n\t\treturn input_string\n\n\tprocessed_string = \"\"\n\n\tabsolute_counter = 0\n\tcounter = 0\n\tchar_of_interest = input_string[0]\n\n\tfor char in input_string:\n\t\tabsolute_counter += 1\n\t\tif char ==char_of_interest:\n\t\t\tcounter += 1\n\t\telse:\n\t\t\tprocessed_string += '{}{}'.format(char_of_interest, counter)\n\t\t\tchar_of_interest = char\n\t\t\tcounter = 1\n\t\t\t#run on last character \n\t\t\tif absolute_counter == len(input_string):\n\t\t\t\tprocessed_string += '{}{}'.format(char_of_interest, counter)\n\n\n\treturn processed_string\n\ndef main():\n\tellen_name = \"ellen\"\n\tellen_compress = \"e1l2e1n1\"\n\tfor char in ellen_name:\n\t\tprint char\n\n\traw_string = 'ellen'\n\tcompress_string = 'e1l2e1n1'\n\n\tprocessed_string = string_compress(raw_string)\n\tprint processed_string\n\tif processed_string == compress_string:\n\t\tprint \"you did it!\"\n\telse:\n\t\tprint \"try again.\"\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.5812720656394958,
"alphanum_fraction": 0.6219081282615662,
"avg_line_length": 22.625,
"blob_id": "4100ef11d69841af869b76b1681d69b5f04ee48e",
"content_id": "92eb9b1094760b612673379d0921cf89b87136e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 566,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 24,
"path": "/leetcode/easy/intersection_arrays.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nGiven two arrays, write a function to compute their intersection.\n\nExample:\nGiven nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].\n\nNote:\nEach element in the result must be unique.\nThe result can be in any order.'''\n\ndef get_intersection(array1,array2):\n intersection = []\n for num in array1:\n if num in array2:\n if num not in intersection:\n intersection.append(num)\n return intersection\n\ndef main():\n array1 = [1,2,3]\n array2 = [2,3,4]\n print get_intersection(array1,array2)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6635220050811768,
"alphanum_fraction": 0.6635220050811768,
"avg_line_length": 21.785715103149414,
"blob_id": "b9fd780faa2c484a331a03941c8cd9521793ee5a",
"content_id": "75de0d5073172db7d73a886ffad15728c852e09d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 318,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 14,
"path": "/leetcode/easy/reverse_string.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''Write a function that takes a string as input and returns the string reversed.'''\n\ndef reverse_string(input_str):\n\trev_string = ''\n\tfor char in input_str:\n\t\trev_string = char + rev_string\n\n\treturn rev_string\n\ndef main():\n input_str = \"hello\"\n print reverse_string(input_str)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6407766938209534,
"alphanum_fraction": 0.6537216901779175,
"avg_line_length": 14.871794700622559,
"blob_id": "0a4f0ec1d75b1bda67cccf8f2a79ae1153497c44",
"content_id": "45137d8e0f9b5bb06db1554165c17863b67c0302",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 39,
"path": "/reverse_string.java",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "/**\n* http://courses.csail.mit.edu/iap/interview/Hacking_a_Google_Interview_Handout_2.pdf\n*\n* Write
a
function
to
reverse
the
order
of
words
in
a
string
in
place.\n*\n**/\n\npublic class reverse_string {\n\tstatic String reverseString(String input) {\n\t\tif (input.length() == 1) {\n\t\t\treturn input;\n\t\t}\n\t\tString reverse=\"\";\n\t\tfor(int i=input.length()-1; i>=0; i--) {\n\t\t\treverse = reverse + input.charAt(i);\n\t\t}\n\t\treturn reverse;\n\t}\n\n\tpublic static void main (String[] args) {\n\t\tString st1 = \"Andrew\";\n\t\tString st2 = \"Andre\";\n\t\tSystem.out.println(reverseString(st1));\n\t\tSystem.out.println(reverseString(st2));\n\t}\n}"
},
{
"alpha_fraction": 0.6092342138290405,
"alphanum_fraction": 0.6137387156486511,
"avg_line_length": 30.75,
"blob_id": "cf9619b13920c0c02c2019d6fe3c3f5dc501b94a",
"content_id": "bb108d41b4c67f236996130d36c02f470fc069f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 888,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 28,
"path": "/leetcode/easy/letter_changes.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "'''\nUsing the Python language, have the function LetterChanges(str) take the str \nparameter being passed and modify it using the following algorithm. \nReplace every letter in the string with the letter following it in the alphabet \n(ie. c becomes d, z becomes a). \nThen capitalize every vowel in this new string (a, e, i, o, u) \nand finally return this modified string. \n'''\ndef letter_changes(input_str):\n output_str=\"\"\n for char in input_str:\n if char.isalpha():\n ascii_code = ord(char)\n if char in ['z','d','h','n','t']:\n output_str = output_str + chr(ascii_code-31)\n else:\n output_str = output_str + chr(ascii_code+1)\n else:\n output_str = output_str + char\n\n return output_str\n\n\ndef main():\n input_str = \"hello*3\"\n print letter_changes(input_str)\n\nif __name__ == \"__main__\": main()"
},
{
"alpha_fraction": 0.6659877896308899,
"alphanum_fraction": 0.6965376734733582,
"avg_line_length": 20.39130401611328,
"blob_id": "2df1f9c07f3cb9b9248340162ad99945456d7da1",
"content_id": "9099f5040517d402a281ed586377ea20c9401076",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 491,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 23,
"path": "/ctci/array_and_strings/string_permutation.py",
"repo_name": "anc1revv/coding_practice",
"src_encoding": "UTF-8",
"text": "# Given two strings, write a method that decides if one is a permutation\n# of the other.\n\ndef check_perm(input_string1, input_string2):\n\tprint \"Checking '{0}' against '{1}'\".format(input_string1,input_string2)\n\n\tif len(input_string1) != len(input_string2):\n\t\treturn False\n\n\t\n\n\ndef main():\n\tinput_string1 = \"hello\"\n\tinput_string2 = \"bye\"\n\tinput_string3 = \"eyb\"\n\n\tprint check_perm(input_string1,input_string2)\n\tprint check_perm(input_string2,input_string3)\n\n\nif __name__ == '__main__':\n\tmain()"
}
] | 19 |
ArunWSU/Short-time-series-forecasting | https://github.com/ArunWSU/Short-time-series-forecasting | 1a0519a9ac85453957ce317220a16efa3571fc4c | d49140ca65cabbe599bb7e8065ada3e23b30e0c1 | ae8be9f5ba2fb02088ac032348a2d047a145eddc | refs/heads/master | 2020-04-08T09:34:26.247357 | 2019-03-08T22:21:40 | 2019-03-08T22:21:40 | 159,230,079 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6770563721656799,
"alphanum_fraction": 0.6955665349960327,
"avg_line_length": 47.83241653442383,
"blob_id": "ab1f0017b2af48c5b250fddd07c79f3cd452b264",
"content_id": "ea36dba8572822a67b4bf18a456da20326166831",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 17774,
"license_type": "no_license",
"max_line_length": 177,
"num_lines": 364,
"path": "/MLP_weekly_final_no_scaling.py",
"repo_name": "ArunWSU/Short-time-series-forecasting",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nimport statistics\nimport math\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom scipy.stats import probplot\nfrom statsmodels.stats.diagnostic import acorr_ljungbox\nimport matplotlib.pyplot as plt\nfrom pandas import ExcelWriter\nfrom scipy.stats import norm\n\n# Fixing the random number for neural net\nnp.random.seed(1)\n\n# Creates the input and output data for time series forecasting\ndef data_preparation(X,nlags):\n X_t,Y_t=[],[]\n # One for zero Index One for last point # if(i+nlags!=len(X))\n for i in range(0,len(X)-window_size,1):\n Row=X[i:i+nlags]\n X_t.append(Row)\n Y_t.append(X[i+nlags])\n return np.array(X_t).reshape(-1,window_size),np.array(Y_t).ravel()\n\ndef error_compute(X,Y):\n return np.mean(np.power(abs(np.array(X)-np.array(Y)),2)),np.mean(abs(np.array(X)-np.array(Y))),np.mean(abs(np.array(X)-np.array(Y))/np.array(X))*100\n\nclass ModelPerformance:\n # To view the values used in error computation\n actual_list,forecast_list=[],[]\n \n def __init__(self,forecast_size):\n ModelPerformance.error_metrics=np.zeros((forecast_size+3,3))\n \n def rolling_window_error(self,forecast_output_actual,mlp_forecast_actual,i,performance_window_size):\n if(performance_window_size==1):\n self.actual_values=forecast_output_actual[i] \n self.forecast_values=mlp_forecast_actual[i]\n self.error_metrics[i][0],self.error_metrics[i][1],self.error_metrics[i][2]=error_compute(self.actual_values,self.forecast_values)\n else:\n end_index=i+1\n if(end_index>=performance_window_size):\n self.actual_values=forecast_output_actual[end_index-performance_window_size:end_index] \n self.actual_list.append(self.actual_values)\n self.forecast_values=mlp_forecast_actual[end_index-performance_window_size:end_index] \n self.forecast_list.append(self.forecast_values)\n self.error_metrics[i][0],self.error_metrics[i][1],self.error_metrics[i][2]=error_compute(self.actual_values,self.forecast_values)\n\nclass AnomalyDetect:\n select=1\n threshold_violations=[]\n \n def __init__(self,forecast_size):\n AnomalyDetect.threshold_violations=np.zeros((forecast_size,1)) \n \n def check_anomalies(GaussianThresholds,select,current_value,i):\n if(select==1):\n GaussianThresholds.gaussian_check(current_value,i)\n else:\n raise Exception('Not a valid selection!')\n\nclass GaussianThresholds(AnomalyDetect):\n def __init__(self,annual_data1,forecast_size):\n AnomalyDetect.__init__(self,forecast_size)\n GaussianThresholds.annual_data=annual_data1\n annual_data_mean=statistics.mean(annual_data)\n annual_data_sd=statistics.stdev(annual_data)\n self.upper_threshold=annual_data_mean+3*annual_data_sd\n self.lower_threshold=annual_data_mean-3*annual_data_sd\n \n def gaussian_check(GaussianThresholds,current_value,i): \n if((GaussianThresholds.lower_threshold < current_value) and (current_value < GaussianThresholds.upper_threshold)):\n GaussianThresholds.threshold_violations[i]=0\n else:\n GaussianThresholds.threshold_violations[i]=1\n \n## Does Line plot if length of different input matches\ndef plot_results(plot_list,individual_plot_labels,fig_labels,mark_select,save_plot,save_plot_name):\n no_datapoints=plot_list[0].size\n no_line_plots=len(plot_list)\n color_list=['crimson','gray','blue','green']\n if(mark_select==1):\n marker_list=[\"o\",\"^\",\"+\",\"x\",'*']\n line_style=['-','--',':','-.']\n else:\n marker_list=['None']*no_line_plots\n line_style=['--']*no_line_plots\n try:\n if(all(x.size==no_datapoints for x in plot_list)):\n plt.figure()\n X_scale=np.arange(1,no_datapoints+1,1)\n for i in range(no_line_plots):\n plt.plot(X_scale,plot_list[i],color=color_list[i],label=individual_plot_labels[i],linewidth=3,marker=marker_list[i],linestyle=line_style[i])\n plt.title(fig_labels[0]) \n plt.xlabel(fig_labels[1], fontsize=18)\n plt.ylabel(fig_labels[2], fontsize=18)\n plt.legend()\n plt.show()\n if(save_plot==1):\n plt.savefig(save_plot_name) \n else:\n raise Exception\n except Exception:\n print('Length mismatch among different vectors to plot') \n \n# writing outputs to excel or csv file\ndef file_store(input_data,excel_select,filename,index_name):\n column_list=['RMSE', 'MAE','MAPE']\n sheet_list=['sheet1','sheet2','sheet3','sheet4','sheet5','sheet6','sheet7','sheet8','sheet9','sheet10','sheet11']\n if(excel_select==1):\n filename_with_ext=''.join([filename,'.xlsx']) \n writer=ExcelWriter(filename_with_ext)\n for n,df in enumerate(input_data):\n output_dataframe=pd.DataFrame(data=df,columns=column_list)\n output_dataframe.index.name=index_name[n]\n output_dataframe.to_excel(writer,sheet_list[n])\n writer.save() \n else:\n output_dataframe=pd.DataFrame(data=input_data,columns=column_list)\n output_dataframe.index.name=index_name\n filename_with_ext=''.join([filename,'.csv']) \n output_dataframe.to_csv(filename_with_ext) \n\n# Reading and creating the history vector\nAnnual=pd.read_csv(\"Annual_load_profile_PJM.csv\",header=0,index_col=0,parse_dates=True)\nWeek1=Annual['2017-01-02':'2017-01-08']\nhistory=Week1['mw']\nhistory.index=np.arange(0,len(history),1)\nhistory=history.values.reshape(-1,1)\nannual_data=Annual['2017'].mw\n\n'''\n# Checking for normal fit\nplt.figure()\nannual_data.plot.hist()\nplt.title('Histogram of Annual data',fontsize=18)\nplt.figure()\nprobplot(annual_data,plot=plt)\nplt.show()\nnormalized_values=norm.pdf(annual_data.values)\nscale=np.arange(0,normalized_values.shape[0],1)\nplt.plot(scale,normalized_values)\nplt.show()\n'''\n\n\n'''\n### FINDING MODEL PARAMETERS\n## CHOICE OF WINDOW SIZE FOR FORECASTING\nMetrics_output_window_select=np.zeros((20,6))\n\nfor x in range(1,15):\n # Input to MLP is of form No of samples, No of features\n window_size=x\n history_input,history_output=data_preparation(history,window_size)\n forecast_input,forecast_output=data_preparation(forecast,window_size)\n \n # Specify MLP regressor model\n mlp=MLPRegressor(hidden_layer_sizes=(7,),activation='identity',solver='lbfgs',random_state=1)\n mlp.fit(history_input,history_output)\n \n # Predict the outputs\n mlp_history_output=mlp.predict(history_input).reshape(-1,1)\n mlp_forecast_output=mlp.predict(forecast_input).reshape(-1,1)\n \n # Calculate the error metrics\n Metrics_output_window_select[x][0]=mean_squared_error(history_output,mlp_history_output)\n Metrics_output_window_select[x][1]=mean_absolute_error(history_output,mlp_history_output)\n Metrics_output_window_select[x][2]=mape(history_output,mlp_history_output)\n Metrics_output_window_select[x][3]=mean_squared_error(forecast_output,mlp_forecast_output)\n Metrics_output_window_select[x][4]=mean_absolute_error(forecast_output,mlp_forecast_output)\n Metrics_output_window_select[x][5]=mape(forecast_output,mlp_forecast_output)\n \nMetrics_output_window_select1=pd.DataFrame(data=Metrics_output_window_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\nMetrics_output_window_select1.to_csv('window_check.csv')\n\n\n## CHOICE OF NUMBER OF NEURONS FOR HIDDEN LAYER\nMetrics_output_neurons_select=np.zeros((20,6))\nwindow_size=4\nhistory_input,history_output=data_preparation(history,window_size)\nforecast_input,forecast_output=data_preparation(forecast,window_size)\n\nfor x in range(1,10):\n \n # Specify MLP regressor model\n mlp=MLPRegressor(hidden_layer_sizes=(x,),activation='identity',solver='lbfgs',random_state=1)\n mlp.fit(history_input,history_output)\n \n # Predict the outputs\n mlp_history_output=mlp.predict(history_input).reshape(-1,1)\n mlp_forecast_output=mlp.predict(forecast_input).reshape(-1,1)\n \n # Calculate the error metrics\n Metrics_output_neurons_select[x][0]=mean_squared_error(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][1]=mean_absolute_error(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][2]=mape(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][3]=mean_squared_error(forecast_output,mlp_forecast_output)\n Metrics_output_neurons_select[x][4]=mean_absolute_error(forecast_output,mlp_forecast_output)\n Metrics_output_neurons_select[x][5]=mape(forecast_output,mlp_forecast_output)\n \nMetrics_output_neurons_select1=pd.DataFrame(data=Metrics_output_neurons_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\nMetrics_output_neurons_select1.to_csv('neuron_check.csv') \n'''\n\n## Training using the determined model parameters\n# Choice of window size for window based forecasting\nwindow_size=5\nhistory_input,history_output=data_preparation(history,window_size)\n\n# Specify MLP regressor model\nmlp=MLPRegressor(hidden_layer_sizes=(7,),activation='identity',solver='lbfgs',random_state=1)\n\n# LBFGS for small samples No batch size Learning rate for SGD\nmlp.fit(history_input,history_output)\nmlp_history_output=mlp.predict(history_input)\n'''\n# plot visulaiztion with zeros\nindividual_plot_labels=['Training load','MLP Training Load','Actual load without zeros']\nfig_labels=['Training Set','Time(Hours)','Load(MW)']\nplot_list=[history_output,mlp_history_output]\nsave_plot_name='Try 2'\nplot_results(plot_list,individual_plot_labels,fig_labels,1,0,save_plot_name)\n'''\n## Forecasting\ndates=pd.date_range(start='2017-01-09',end='2017-12-31')\nB=[]\ny=0\nStartDate=pd.Series('2017-01-02')\nEndDate=pd.Series('2017-01-08')\n\n# Length and time to be forecasted\nforecast_start_date='2017-01-09' #str(dates[0].date())\nforecast_end_date='2017-01-15'\nforecast=Annual[forecast_start_date:forecast_end_date].mw.copy() # 2017-12-31\n#forecast['2017-01-10 00:00:00':'2017-01-10 16:00:00']=0 24:41\nforecast=forecast.values\nactual_forecast=forecast.copy()\nwindow_index=0\n\n# 1. Normal 2.Retraining 3. Missing measurements, Singlepoint, Collective outliers 4. Effect of noise\nuse_case=1\nif(use_case==1):\n forecast_output_actual=forecast[window_size:].copy()\n mlp_forecast_actual=np.zeros(forecast_output_actual.shape[0]) \n adam_forecast_output=np.zeros(forecast.shape[0]).reshape(-1,1)\n adam_forecast_output[0:window_size]=forecast[0:window_size].reshape(-1,1).copy() \n threshold_violations=mlp_forecast_actual.copy()\n model_mlp_obj=ModelPerformance(forecast_output_actual.shape[0])\n performance_window_size=2\n max_window_size=11\n overall_error_metrics=np.zeros((max_window_size,3))\n rolling_error_list,actual_list,forecast_list=[0]*(max_window_size-1),[0]*max_window_size,[0]*max_window_size\n for y in range(1,max_window_size,1):\n window_index=0\n performance_window_size=y\n anomaly_detection_method=1 \n no_of_forecast_points=forecast_output_actual.shape[0]\n gaus_obj=GaussianThresholds(annual_data,forecast_output_actual.shape[0])\n \n for i in range(0,no_of_forecast_points,1):\n previous_window=adam_forecast_output[window_index:window_index+window_size].reshape(-1,window_size)\n mlp_forecast_actual[i]=mlp.predict(previous_window) \n gaus_obj.check_anomalies(anomaly_detection_method,forecast_output_actual[i],i)\n if(gaus_obj.threshold_violations[i]==0):\n adam_forecast_output[window_index+window_size]=forecast_output_actual[i].copy()\n model_mlp_obj.rolling_window_error(forecast_output_actual,mlp_forecast_actual,i,performance_window_size)\n # model_mlp_obj.error_compute(forecast_output_actual,mlp_forecast_actual,i,performance_window_size)\n else:\n adam_forecast_output[window_index+window_size]=mlp_forecast_actual[i].copy() \n window_index=window_index+1\n actual_list[y-1] =model_mlp_obj.actual_list\n forecast_list[y-1]=model_mlp_obj.forecast_list\n model_mlp_obj.actual_list,model_mlp_obj.forecast_list=[],[]\n rolling_error_list[y-1]=model_mlp_obj.error_metrics\n model_mlp_obj.error_metrics=np.zeros((forecast_output_actual.shape[0]+3,3))\n overall_error_metrics[y][0],overall_error_metrics[y][1],overall_error_metrics[y][2]=error_compute(forecast_output_actual,mlp_forecast_actual)\n # plot visulaiztion with zeros\n# individual_plot_labels=['ActuaL_load','MLP Forecasted Load','Actual load without zeros']\n# fig_labels=['Testing Set','Time(Hours)','Load(MW)']\n# plot_list=[forecast_output_actual,mlp_forecast_actual]\n# save_plot_name='Try 2'\n# plot_results(plot_list,individual_plot_labels,fig_labels,1,0,save_plot_name)\n \n # Storing in files\n index_names=['Rolling_window_forecast']*(max_window_size+2)\n file_store(rolling_error_list,1,'Effect_rolling_window',index_names)\n\nelif(use_case==3):\n zero_start_index=19\n no_simulated_zeros=48\n overall_error_metrics,error_zero_interval,error_post_zero_interval=np.zeros((no_simulated_zeros+1,3)),np.zeros((no_simulated_zeros+1,3)),np.zeros((no_simulated_zeros+1,3))\n mlp_zero_forecast_list,forecast_zero_list=[],[]\n mlp_forecast_list,forecast_list=[],[]\n for y in range(1,no_simulated_zeros+1,1):\n forecast_output_actual=forecast[window_size:].copy()\n forecast_output_actual_unmodified=forecast_output_actual.copy()\n #zero_end_index=36\n zero_end_index=zero_start_index+y\n forecast_output_actual[zero_start_index:zero_end_index]=0\n forecast_list.append(forecast_output_actual)\n no_of_forecast_points=forecast_output_actual.shape[0]\n mlp_forecast_actual=np.zeros(no_of_forecast_points)\n mlp_forecast_list.append(mlp_forecast_actual)\n window_index=0\n adam_forecast_output=np.zeros(forecast.shape[0]).reshape(-1,1)\n adam_forecast_output[0:window_size]=forecast[0:window_size].reshape(-1,1).copy() \n threshold_violations=mlp_forecast_actual.copy()\n \n model_mlp_obj=ModelPerformance(forecast_output_actual.shape[0])\n performance_window_size=1\n anomaly_detection_method=1\n \n \n gaus_obj=GaussianThresholds(annual_data,forecast_output_actual.shape[0])\n \n for i in range(0,no_of_forecast_points,1):\n previous_window=adam_forecast_output[window_index:window_index+window_size].reshape(-1,window_size)\n mlp_forecast_actual[i]=mlp.predict(previous_window) \n gaus_obj.check_anomalies(anomaly_detection_method,forecast_output_actual[i],i)\n if(gaus_obj.threshold_violations[i]==0):\n adam_forecast_output[window_index+window_size]=forecast_output_actual[i].copy()\n model_mlp_obj.rolling_window_error(forecast_output_actual,mlp_forecast_actual,i,performance_window_size)\n # model_mlp_obj.error_compute(forecast_output_actual,mlp_forecast_actual,i,performance_window_size)\n else:\n adam_forecast_output[window_index+window_size]=mlp_forecast_actual[i].copy() \n window_index=window_index+1\n \n # Simpler approach using mask\n zero_index=np.zeros((no_of_forecast_points,1))\n zero_index[zero_start_index:zero_end_index]=1\n mask=(zero_index==1).reshape(-1)\n mlp_forecast_zero_interval_mask,actual_val_zero_interval_mask=mlp_forecast_actual[mask],forecast_output_actual_unmodified[mask]\n mlp_forecast_actual_no_zeros_mask,forecast_output_actual_no_zeros_mask=mlp_forecast_actual[~mask],forecast_output_actual_unmodified[~mask]\n mlp_forecast_post_zeros,forecast_output_post_zeros=mlp_forecast_actual[zero_end_index:],forecast_output_actual_unmodified[zero_end_index:]\n \n overall_error_metrics[y][0],overall_error_metrics[y][1],overall_error_metrics[y][2]=error_compute(forecast_output_actual_no_zeros_mask,mlp_forecast_actual_no_zeros_mask)\n error_zero_interval[y][0],error_zero_interval[y][1],error_zero_interval[y][2]=error_compute(actual_val_zero_interval_mask,mlp_forecast_zero_interval_mask)\n error_post_zero_interval[y][0],error_post_zero_interval[y][1],error_post_zero_interval[y][2]=error_compute(mlp_forecast_post_zeros,forecast_output_post_zeros)\n # To check individual forecasts\n mlp_zero_forecast_list.append(mlp_forecast_zero_interval_mask)\n forecast_zero_list.append(actual_val_zero_interval_mask)\n \n \n # Storing in files\n# performance_list=[error_zero_interval,overall_error_metrics,error_post_zero_interval]\n# index_names=['Errors_zero_interval','Overall_performance_metrics','Post_error_metrics']\n# file_store(performance_list,1,'Errors_missing_measurements_post',index_names)\n \n# \n# # plot visulaiztion with zeros\n# individual_plot_labels=['ActuaL_load','MLP Forecasted Load','Actual load without zeros']\n# fig_labels=['Testing Set','Time(Hours)','Load(MW)']\n# plot_list=[forecast_output_actual,mlp_forecast_actual,forecast_output_actual_unmodified]\n# save_plot_name='Try 2'\n# plot_results(plot_list,individual_plot_labels,fig_labels,1,0,save_plot_name)\n# \n# # plotting just forecast vector\n# plot_list=[forecast_output_actual,mlp_forecast_actual]\n# fig_labels[0]='Forecasting set'\n# plot_results(plot_list,individual_plot_labels,fig_labels,0,0,save_plot_name)"
},
{
"alpha_fraction": 0.6603692770004272,
"alphanum_fraction": 0.6766997575759888,
"avg_line_length": 49.92119598388672,
"blob_id": "d47283e09a4b2b3c3c63717dd0e734281675451e",
"content_id": "3ea98548b8a7b4cdbe229799d09ed83d08094855",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 18738,
"license_type": "no_license",
"max_line_length": 232,
"num_lines": 368,
"path": "/smart_meter_neural_net_forecast.py",
"repo_name": "ArunWSU/Short-time-series-forecasting",
"src_encoding": "UTF-8",
"text": "#%% IMPORT FILES\nimport numpy as np\nimport pandas as pd\nimport statistics\nimport math\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neural_network import MLPRegressor\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom scipy.stats import probplot\nfrom statsmodels.stats.diagnostic import acorr_ljungbox\nimport matplotlib.pyplot as plt\nfrom pandas import ExcelWriter\nfrom scipy.stats import norm\nimport seaborn as sns\n\n# Fixing the random number for neural net\nnp.random.seed(1)\n# FUNCTIONS AND CLASS DEFINITIONS\n# Creates the input and output data for time series forecasting\n# Model select 1.MLP 2.LSTM\n\nclass FeaturePreparation:\n actual_time_series,time_series_values=[],[] # Available attributes of class\n data_input,data_output,model_forecast_output=[],[],[]\n time_related_features=[]\n window_size=[]\n neural_model=[]\n \n def __init__(self,data):\n self.actual_time_series=data\n \n def prepare_neural_input_output(self,model_select,individual_paper_select):\n self.time_series_values=self.actual_time_series.values\n self.data_input,self.data_output=[],[]\n for i in range(0,len(self.time_series_values)-self.window_size,1):\n last_lag_data=self.time_series_values[i:i+self.window_size]\n if(individual_paper_select==1):\n last_lag_data=np.vstack((last_lag_data,self.individual_meter_forecast_features(last_lag_data).reshape(-1,1))) # Overloading might be possible variable args\n self.data_input.append(last_lag_data)\n self.data_output.append(self.time_series_values[i+self.window_size])# Y_t=history[5:] \n self.data_input=np.array(self.data_input)\n self.data_output=np.array(self.data_output)\n if(model_select==1):\n self.data_input=self.data_input.reshape(-1,last_lag_data.shape[0])\n self.data_output=self.data_output.ravel()\n \n def find_time_related_features(self):\n self.time_related_features=pd.DataFrame(self.actual_time_series.index.dayofweek)\n self.time_related_features['Working day']=np.logical_not(((self.time_related_features==5)|(self.time_related_features==6))).astype('int')\n self.time_related_features['Hour']=pd.DataFrame(self.actual_time_series.index.hour)\n self.time_related_features=self.time_related_features[self.window_size:]\n self.time_related_features.reset_index(drop=True,inplace=True)\n self.time_related_features.rename(columns={'local_15min':'Day of week'},inplace=True)\n \n def individual_meter_forecast_features(self,input):\n individual_forecast_paper_features=np.zeros((16,1))\n x=np.array((-3,-6,-12,0))\n split_list=[input[a:] for a in x]\n for i,current_value in enumerate(split_list):\n individual_forecast_paper_features[i],individual_forecast_paper_features[i+4],individual_forecast_paper_features[i+8],individual_forecast_paper_features[i+12]=self.individual_meter_forecast_value_calculate(current_value)\n return individual_forecast_paper_features\n \n def individual_meter_forecast_value_calculate(self,previous_3): # Average, Maximum, Minimum, range of values\n return np.average(previous_3),np.amax(previous_3),np.amin(previous_3),np.ptp(previous_3)\n \n def neural_predict(self,FeaturePrepration,accuracy_select):\n self.accuracy_select=accuracy_select\n self.model_forecast_output=self.neural_model.predict(self.data_input)\n FeaturePrepration.neural_model=self.neural_model\n FeaturePrepration.model_forecast_output=FeaturePrepration.neural_model.predict(FeaturePrepration.data_input)\n \n # Model Performance Computation\n self.hist_perf_obj=ModelPerformance(self.data_output.reshape(-1,1),self.model_forecast_output.reshape(-1,1))\n self.hist_perf_obj.error_compute()\n FeaturePrepration.fore_perf_obj=ModelPerformance(FeaturePrepration.data_output.reshape(-1,1),FeaturePrepration.model_forecast_output.reshape(-1,1))\n FeaturePrepration.fore_perf_obj.error_compute()\n if(self.accuracy_select==1):\n self.hist_perf_obj.point_accuracy_compute()\n FeaturePrepration.fore_perf_obj.point_accuracy_compute()\n \n \nclass MLPModelParameters(FeaturePreparation):\n # CHOICE OF WINDOW SIZE FOR FORECASTING \n def __init__(self,data,window_size_max,neuron_number_max):\n self.window_size_max=window_size_max\n self.neuron_number_max=neuron_number_max\n FeaturePreparation.__init__(self,data)\n \n def window_size_select(self,MLPModelParameters): # self is hist_obj, MLPModelParameters refers to the fore_obj\n self.hist_inp_list,self.hist_out_list,self.fore_inp_list,self.fore_out_list=[0]*(self.window_size_max+3),[0]*(self.window_size_max+3),[0]*(self.window_size_max+3),[0]*(self.window_size_max+3)\n self.Metrics_output_window_select=[]\n \n # Data as function of window sizes\n for x in range(1,self.window_size_max+1):\n # Input to MLP is of form No of samples, No of features\n self.window_size,MLPModelParameters.window_size=x,x\n self.prepare_neural_input_output(model_select,individual_paper_select)\n self.hist_inp_list[x-1],self.hist_out_list[x-1]=self.data_input,self.data_output\n MLPModelParameters.prepare_neural_input_output(model_select,individual_paper_select)\n self.fore_inp_list[x-1],self.fore_out_list[x-1]=MLPModelParameters.data_input,MLPModelParameters.data_output\n \n# mlp=MLPRegressor(hidden_layer_sizes=(9,),activation='logistic',solver='lbfgs',random_state=1)\n# self.mlp_fit_predict(mlp,MLPModelParameters,x)\n self.neural_fit()\n self.neural_predict(MLPModelParameters,0)\n self.current_iter_error=np.array((self.hist_perf_obj.MSE,self.hist_perf_obj.MAE,self.hist_perf_obj.MAPE,MLPModelParameters.fore_perf_obj.MSE,MLPModelParameters.fore_perf_obj.MAE,MLPModelParameters.fore_perf_obj.MAPE))\n self.Metrics_output_window_select.append(self.current_iter_error)\n \n self.Metrics_output_window_select1=pd.DataFrame(data=self.Metrics_output_window_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\n self.Metrics_output_window_select1.to_excel('Window_check.xlsx') \n \n # CHOICE OF NUMBER OF NEURONS FOR HIDDEN LAYER\n def neuron_select(self,MLPModelParameters,window_size):\n self.data_input,self.data_output=self.hist_inp_list[window_size-1],self.hist_out_list[window_size-1]\n MLPModelParameters.data_input,MLPModelParameters.data_output=self.fore_inp_list[window_size-1],self.fore_out_list[window_size-1]\n \n self.Metrics_output_neuron_select=[]\n for x in range(1,self.neuron_number_max+1):\n# mlp=MLPRegressor(hidden_layer_sizes=(x,),activation='logistic',solver='lbfgs',random_state=1)\n# self.mlp_fit_predict(mlp,MLPModelParameters,x)\n self.neural_fit()\n self.neural_predict(MLPModelParameters,0)\n self.Metrics_output_neuron_select.append(self.current_iter_error)\n \n self.Metrics_output_neurons_select1=pd.DataFrame(data=self.Metrics_output_neuron_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\n self.Metrics_output_neurons_select1.to_excel('Neuron_check.xlsx') \n \n def neural_fit(self):\n print(\"MLP\")\n mlp=MLPRegressor(hidden_layer_sizes=(10,),activation='logistic',solver='lbfgs',random_state=1)\n self.neural_model=mlp\n self.neural_model.fit(self.data_input,self.data_output)\n \n def mlp_fit_predict(self,mlp,MLPModelParameters,x):\n mlp.fit(self.data_input,self.data_output)\n \n # Predict the outputs\n self.model_forecast_output=mlp.predict(self.data_input).reshape(-1,1)\n MLPModelParameters.model_forecast_output=mlp.predict(self.data_input).reshape(-1,1)\n \n hist_perf_obj=ModelPerformance(self.data_output,self.model_forecast_output)\n fore_perf_obj=ModelPerformance(MLPModelParameters.data_output,MLPModelParameters.model_forecast_output)\n \n hist_perf_obj.error_compute()\n fore_perf_obj.error_compute()\n \n self.current_iter_error=np.array((hist_perf_obj.MSE,hist_perf_obj.MAE,hist_perf_obj.MAPE,fore_perf_obj.MSE,fore_perf_obj.MAE,fore_perf_obj.MAPE))\n\nclass LSTMModelParameters(FeaturePreparation):\n \n def neural_fit(self):\n print(\"LSTM Model\")\n self.LSTM_model_param()\n \n def LSTM_model_param(LSTMModelParameters):\n # Train LSTM model\n model=Sequential()\n model.add(LSTM(14,input_shape=(LSTMModelParameters.data_input.shape[1],LSTMModelParameters.data_input.shape[2])))\n model.add(Dense(1)) # First argument specifies the output\n model.compile(optimizer='adam',loss='mean_squared_error')\n model.fit(LSTMModelParameters.data_input,LSTMModelParameters.data_output,epochs=5,batch_size=1,verbose=2)\n LSTMModelParameters.neural_model=model\n \n \nclass ModelPerformance():\n # To view the values used in error computation\n actual_list,forecast_list=[],[]\n data_output,model_forecast_output=[],[]\n \n def __init__(self,X,Y):\n self.data_output=X\n self.model_forecast_output=Y\n \n def rolling_window_error(self,forecast_output_actual,mlp_forecast_actual,i,performance_window_size):\n ModelPerformance.error_metrics=np.zeros((forecast_output_actual.shape[0]+3,3))\n if(performance_window_size==1):\n self.actual_values=forecast_output_actual[i] \n self.forecast_values=mlp_forecast_actual[i]\n self.error_metrics[i][0],self.error_metrics[i][1],self.error_metrics[i][2]=self.error_compute(self.actual_values,self.forecast_values)\n else:\n end_index=i+1\n if(end_index>=performance_window_size):\n self.actual_values=forecast_output_actual[end_index-performance_window_size:end_index] \n self.actual_list.append(self.actual_values)\n self.forecast_values=mlp_forecast_actual[end_index-performance_window_size:end_index] \n self.forecast_list.append(self.forecast_values)\n self.error_metrics[i][0],self.error_metrics[i][1],self.error_metrics[i][2]=self.error_compute(self.actual_values,self.forecast_values)\n \n # returns MSE,MAE, MAPE \n def error_compute(self):\n X,Y=self.data_output,self.model_forecast_output\n np.seterr(divide='ignore')\n self.MSE,self.MAE,self.MAPE=np.mean(np.power(abs(np.array(X)-np.array(Y)),2)),np.mean(abs(np.array(X)-np.array(Y))),np.mean(abs(np.array(X)-np.array(Y))/np.array(X))*100\n\n def point_accuracy_compute(self):\n X,Y=self.data_output,self.model_forecast_output\n Accurate_forecast_points=((((X > 1.5) & ((abs(X-Y)) < (X*0.10)))) | ((X < 1.5) & ((abs(X-Y)) < (0.10))))\n self.model_accuracy=np.sum(Accurate_forecast_points)/Accurate_forecast_points.shape[0]\n\nclass AnomalyDetect:\n select=1\n threshold_violations=[]\n \n def __init__(self,forecast_size):\n AnomalyDetect.threshold_violations=np.zeros((forecast_size,1)) \n \n def check_anomalies(GaussianThresholds,select,current_value,i):\n if(select==1):\n GaussianThresholds.gaussian_check(current_value,i)\n else:\n raise Exception('Not a valid selection!')\n\nclass GaussianThresholds(AnomalyDetect):\n def __init__(self,annual_data,forecast_size):\n AnomalyDetect.__init__(self,forecast_size)\n GaussianThresholds.annual_data=annual_data\n annual_data_mean=statistics.mean(annual_data)\n annual_data_sd=statistics.stdev(annual_data)\n self.upper_threshold=annual_data_mean+3*annual_data_sd\n self.lower_threshold=annual_data_mean-3*annual_data_sd\n \n def gaussian_check(GaussianThresholds,current_value,i): \n if((GaussianThresholds.lower_threshold < current_value) and (current_value < GaussianThresholds.upper_threshold)):\n GaussianThresholds.threshold_violations[i]=0\n else:\n GaussianThresholds.threshold_violations[i]=1\n \n## Does Line plot if length of different input matches\ndef plot_results(plot_list,individual_plot_labels,fig_labels,mark_select,save_plot,save_plot_name):\n no_datapoints=plot_list[0].size\n no_line_plots=len(plot_list)\n color_list=['crimson','gray','blue','green']\n if(mark_select==1):\n marker_list=[\"o\",\"^\",\"+\",\"x\",'*']\n line_style=['-','--',':','-.']\n else:\n marker_list=['None']*no_line_plots\n line_style=['-','--']*no_line_plots\n try:\n if(all(x.size==no_datapoints for x in plot_list)):\n plt.figure()\n X_scale=np.arange(1,no_datapoints+1,1)\n for i in range(no_line_plots):\n plt.plot(X_scale,plot_list[i],color=color_list[i],label=individual_plot_labels[i],linewidth=4,marker=marker_list[i],linestyle=line_style[i])\n plt.title(fig_labels[0]) \n plt.xlabel(fig_labels[1], fontsize=18)\n plt.ylabel(fig_labels[2], fontsize=18)\n plt.legend()\n plt.show()\n if(save_plot==1):\n plt.savefig(save_plot_name) \n else:\n raise Exception\n except Exception:\n print('Length mismatch among different vectors to plot') \n \n# writing outputs to excel or csv file\ndef file_store(input_data,excel_select,filename,index_name):\n column_list=['RMSE', 'MAE','MAPE']\n sheet_list=['sheet1','sheet2','sheet3','sheet4','sheet5','sheet6','sheet7','sheet8','sheet9','sheet10','sheet11']\n if(excel_select==1):\n filename_with_ext=''.join([filename,'.xlsx']) \n writer=ExcelWriter(filename_with_ext)\n for n,df in enumerate(input_data):\n output_dataframe=pd.DataFrame(data=df,columns=column_list)\n output_dataframe.index.name=index_name[n]\n output_dataframe.to_excel(writer,sheet_list[n])\n writer.save() \n else:\n output_dataframe=pd.DataFrame(data=input_data,columns=column_list)\n output_dataframe.index.name=index_name\n filename_with_ext=''.join([filename,'.csv']) \n output_dataframe.to_csv(filename_with_ext) \n\n# Checking for normal fit\ndef norm_fit(annual_data,plot_select):\n annual_data_series=pd.Series(annual_data)\n if(plot_select==1):\n plt.figure()\n plt.title('Histogram of annual data',fontsize=14)\n plt.hist(annual_data_series)\n mean_data=statistics.mean(annual_data_series)\n stddev_data=statistics.stdev(annual_data_series)\n m,s=norm.fit(annual_data_series)\n print('Mean %f Stddev %f using normal fit'%(m,s))\n print('Mean %f Stddev %f using statistics'%(mean_data,stddev_data))\n return m,s\n\nfrom contextlib import contextmanager\nimport os\n\n@contextmanager\ndef cd(newdir):\n prevdir = os.getcwd()\n os.chdir(os.path.expanduser(newdir))\n try:\n yield\n finally:\n os.chdir(prevdir)\n \ndef obj_create(annual_data,start_date,end_date,model_select,individual_paper_select,*var_args):\n data=annual_data[start_date:end_date]\n# a=[var_args[i] for i in range(len(var_args))]\n if(model_select==1):\n hist_object=MLPModelParameters(data,var_args[1],var_args[2]) # use parameter\n else:\n hist_object=LSTMModelParameters(data)\n hist_object.window_size=var_args[0]\n hist_object.find_time_related_features()\n hist_object.prepare_neural_input_output(model_select,individual_paper_select) \n return hist_object\n#%%\n'''\n# history vector \n#with cd('C:/Users/WSU-PNNL/Desktop/Data-pec'):\n#with cd('C:/Users/Arun Imayakumar/Desktop/Pecan street data'):\n# Annual=pd.read_csv(\"3967_data_2015_2018.csv\",header=0,index_col=0,parse_dates=True,usecols=['local_15min','use']) # Annual_data.idxmax() # Annual_data.idxmin()\n# Annual_complete=pd.read_csv(\"3967_data_2015_2018_all.csv\",header=0,index_col=1,parse_dates=True) \n#Annual=Annual_complete.furnace1\n#Annual=Annual.resample('H').asfreq()\n\n#Specify MLP regressor model\nx=int(input(\"Enter 1. MLP 2. LSTM\"))\nmodel_select=1\nindividual_paper_select=0\nwindow_size_final=5\ntransform=0\n\nvariable_args=window_size_final\nif model_select==1:\n window_size_max=int(input('Enter the maximum window size:'))\n neuron_number_max=int(input('Enter the maximum number of neurons:'))\n hist_object=obj_create(Annual,'2017-01-02','2017-01-08',model_select,individual_paper_select,window_size_final,window_size_max,neuron_number_max)\n fore_object=obj_create(Annual,'2017-01-09','2017-01-15',model_select,individual_paper_select,window_size_final,window_size_max,neuron_number_max)\nelse:\n hist_object=obj_create(Annual,'2017-01-02','2017-01-08',0,0,5)\n fore_object=obj_create(Annual,'2017-01-09','2017-01-15',0,0,5)\n \n\n#hist_object.data_input=np.hstack((hist_object.data_input,hist_object.time_related_features['Day of week'].values.reshape(-1,1)))\n#fore_object.data_input=np.hstack((fore_object.data_input,fore_object.time_related_features['Day of week'].values.reshape(-1,1)))\n \n#hist_object.data_input=np.hstack((hist_object.data_input,hist_object.time_related_features.values)) \n#fore_object.data_input=np.hstack((fore_object.data_input,fore_object.time_related_features.values))\n \nhist_object.neural_fit()\nhist_object.window_size_select(fore_object)\nhist_object.neuron_select(fore_object,5)\nhist_object.neural_predict(fore_object,1)\n\n# plot visualization\n#individual_plot_labels=['Training load','MLP Training Load','Actual load without zeros']\nindividual_plot_labels=['Actual Jan 2','MLP forecast']\n#individual_plot_labels=['Actual Jan 2','LSTM forecast']\nfig_labels=['Training Set','Time(Datapoint(15min))','Load(KW)']\n#plot_list=[annual_data_series[140:170]]\nplot_list=[hist_object.data_output[0:97],hist_object.model_forecast_output[0:97]]#97:193 history_output_old[0:97]\nsave_plot_name='Try 2'\nplot_results(plot_list,individual_plot_labels,fig_labels,1,0,save_plot_name)\nplot_list=[fore_object.data_output[0:97],fore_object.model_forecast_output[0:97]]\nindividual_plot_labels[0]='Actual Jan 9'\nfig_labels[0]='Testing dataset'\nplot_results(plot_list,individual_plot_labels,fig_labels,1,0,save_plot_name)\n'''"
},
{
"alpha_fraction": 0.7197312116622925,
"alphanum_fraction": 0.7527517080307007,
"avg_line_length": 34.51852035522461,
"blob_id": "fc8fbe3a1ad8661a4d54894cc48b94a8f058c3e6",
"content_id": "90d885ea87a58b21e27427a2ec6b0864b8f208d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8631,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 243,
"path": "/MLP_window.py",
"repo_name": "ArunWSU/Short-time-series-forecasting",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom statsmodels.graphics.tsaplots import plot_acf\nimport pandas as pd\nimport statistics as stats\nfrom scipy.stats import probplot\nfrom statsmodels.stats.diagnostic import acorr_ljungbox\nimport seaborn as sns\nfrom scipy.stats import norm\n\n# Fixing the random number for neural net\nnp.random.seed(1)\n\ndef data_Preparation(X,nlags):\n X_t,Y_t=[],[]\n for i in range(0,len(X)-Window_size,1):# One for zero Index One for last point # if(i+nlags!=len(X))\n Row=X[i:i+nlags]\n X_t.append(Row)\n Y_t.append(X[i+nlags])\n return np.array(X_t),np.array(Y_t)\n\ndef mape(X,Y):\n X1,Y1=np.array(X),np.array(Y)\n APE=abs((X1-Y1)/X1)\n mape_calc=np.mean(APE)*100\n return mape_calc\n\n'''\nHistory=pd.read_csv(\"History_noise.csv\",squeeze=True)\nForecast=pd.read_csv(\"Forecast_validation_noise.csv\",squeeze=True)\n''' \n\n# History vector\nAnnual=pd.read_csv(\"Annual_load_profile_PJM.csv\",header=0,index_col=0,parse_dates=True)\nAnnual_data=Annual['mw']\nMean=stats.mean(Annual_data)\nStdev=stats.stdev(Annual_data)\nUpper_threshold=Mean+3*Stdev\nLower_threshold=Mean-3*Stdev\n\nWeek1=Annual['2017-01-02':'2017-01-08']\nHistory=Week1['mw']\nHistory.index=np.arange(0,len(History),1)\n# History=pd.Series(np.ones((len(Week1),))) # Input all ones\n\n# Forecast vector\nWeek2=Annual['2017-01-10':'2017-12-31'] # '2017-01-10':'2017-12-31' Annual\nForecast=Week2['mw']\nForecast.loc['2017-01-12 07:00:00']= Mean+20*Stdev\nForecast.loc['2017-01-12 14:00:00']= Mean+7*Stdev\nForecast.loc['2017-01-12 22:00:00']= Mean+4*Stdev\n#Forecast['2017-01-12']=0 # case when it is zero\n#Forecast[24:30]=0\nForecast.index=np.arange(0,len(Forecast),1)\n\n# Reshaping and sclaer fit transformation\nHistory=History.values.reshape(-1,1)\nForecast=Forecast.values.reshape(-1,1)\n\n#normalization\nscaler1=MinMaxScaler(feature_range=(0,1))\nHistory_norm=scaler1.fit_transform(History)\nscaler=MinMaxScaler(feature_range=(0,1))\nForecast_norm=scaler.fit_transform(Forecast)\n\n# Choice of window size for window based forecasting\nWindow_size=5\nHistory_input,History_output=data_Preparation(History_norm,Window_size)\nForecast_input,Forecast_output=data_Preparation(Forecast_norm,Window_size)\n\n# Input column vector and Output is one example\nHistory_output=History_output.ravel()\nForecast_output=Forecast_output.ravel()\n\n# Input to MLP is of form No of samples, No of features\nHistory_input=History_input.reshape(-1,Window_size)\nForecast_input=Forecast_input.reshape(-1,Window_size)\n\n# Specify MLP regressor model\nmlp=MLPRegressor(hidden_layer_sizes=(7,),activation='identity',\n solver='lbfgs',random_state=1)\n\n# LBFGS for small samples No batch size Learning rate for SGD\nmlp.fit(History_input,History_output)\n\n# Predictions for training and testing data set\nMLP_History_output=mlp.predict(History_input).reshape(-1,1)\nMLP_Forecast_output=mlp.predict(Forecast_input).reshape(-1,1)\n\n#Reshape for Inverse Transform\nHistory_output=History_output.reshape(-1,1)\nForecast_output=Forecast_output.reshape(-1,1)\n\n# Change scale\nHistory_input_inv=scaler1.inverse_transform(History_input)\nHistory_input_inv=History_input_inv.reshape(-1)\nHistory_output_inv=scaler1.inverse_transform(History_output)\nMLP_History_output_inv=scaler1.inverse_transform(MLP_History_output)\n\nForecast_output_inv=scaler.inverse_transform(Forecast_output)\nMLP_Forecast_output_inv=scaler.inverse_transform(MLP_Forecast_output)\nHistory=History.reshape(-1)\n\n'''\n# plotting in matplotlib\nScale_Xh=np.arange(1,len(History_output)+1,1)\nfig=plt.figure()\nplt.plot(Scale_Xh,History_output_inv,color='gray',label='Training load',linewidth=2,linestyle='-')\nplt.plot(Scale_Xh,MLP_History_output_inv,color='crimson',label='MLP Training Load',linewidth=2,linestyle='--')\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Training Set')\nplt.legend()\nplt.show()\n\n# Testing dataset\nfig=plt.figure()\nScale_Xh=np.arange(1,len(Forecast_output)+1,1)\nplt.plot(Scale_Xh,Forecast_output_inv,color='gray',label='Actual load',marker=\"v\")\nplt.plot(Scale_Xh,MLP_Forecast_output_inv,color='crimson',label='MLP Forecasted Load',marker=\"^\") # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Testing Set')\nplt.legend()\nplt.show()\n\n\n\n\nfig=plt.figure()\nScale_Xh=np.arange(1,len(Forecast_output)+1,1)\nplt.scatter(Scale_Xh,Forecast_output_inv,color='gray',marker=\"v\",label='Actual load')\nplt.scatter(Scale_Xh,MLP_Forecast_output_inv,color='crimson',marker=\"^\",label='MLP Forecasted Load') # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.legend()\nplt.show()\n\n# https://www.propharmagroup.com/blog/understanding-statistical-intervals-part-2-prediction-intervals/\nAlpha=0.05\nDelta=Alpha/2*\n'''\n# Weeks\nerror_metrics=np.zeros((52,5))\nerror_metrics[0][0]=(mean_squared_error(History_output,MLP_History_output))\nerror_metrics[0][1]=(mean_absolute_error(History_output,MLP_History_output))\nerror_metrics[0][2]=(mean_squared_error(History_output_inv,MLP_History_output_inv))\nerror_metrics[0][3]=(mean_absolute_error(History_output_inv,MLP_History_output_inv))\nerror_metrics[0][4]=(mape(History_output_inv,MLP_History_output_inv))\n\nno_of_datapoints=Week2.shape[0]\noneweek_datapoints=7*24\nno_of_weeks=int(no_of_datapoints/oneweek_datapoints)\nindex=0\n\nfor x in range(0,no_of_weeks,1):\n forecast_output_norm=Forecast_output[index:index+no_of_datapoints]\n mlp_forecast_weekly_norm=MLP_Forecast_output[index:index+no_of_datapoints] \n forecast_output_actual=Forecast_output_inv[index:index+no_of_datapoints]\n mlp_forecast_weekly_actual=MLP_Forecast_output_inv[index:index+no_of_datapoints]\n index=index+oneweek_datapoints\n \n # calculate RMSE\n Test_score=(mean_squared_error(forecast_output_norm,mlp_forecast_weekly_norm))\n error_metrics[x+1][0]=Test_score\n\n # calculate MAE\n Test_score1=(mean_absolute_error(forecast_output_norm,mlp_forecast_weekly_norm))\n error_metrics[x+1][1]=Test_score1\n\n # Calculate RMSe\n Test_score=(mean_squared_error(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][2]=Test_score\n\n # calculate MAE\n Test_score1=(mean_absolute_error(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][3]=Test_score1\n\n # Calculate mape\n Test_score1=(mape(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][4]=Test_score1\n \nfilename='Annual1.xlsx'\ndifferent_regression_metrics=pd.DataFrame(data=error_metrics,columns=['RMSE_Scale','MAE_Scale','RMSE_Actual','MAE_Actual','MAPE'])\n#different_regression_metrics.to_excel(filename,'Sheet1')\n\nfilename='Annual1.xlsx'\ncomplete_forecast_output=np.stack((Forecast_output,Forecast_output_inv,MLP_Forecast_output,MLP_Forecast_output_inv),axis=1).reshape(-1,4)\ncomplete_forecast_data=pd.DataFrame(data=complete_forecast_output,columns=['Actual Norm','Actual','MLP norm','MLP'])\n#complete_forecast_data.to_excel(filename,'Sheet2')\n\nOutput1=np.zeros((2,40))\nOutput1[0]=Forecast_output_inv[60:100].reshape(-1)\nOutput1[1]=MLP_Forecast_output_inv[60:100].reshape(-1)\nOutput1=Output1.transpose()\n\n'''\nfig=plt.figure()\nScale_Xh=np.arange(1,Output1.shape[0]+1,1)\nplt.plot(Scale_Xh,Output1[:,0],color='gray',label='Actual load',marker=\"v\")\nplt.plot(Scale_Xh,Output1[:,1],color='crimson',label='MLP Forecasted Load',marker=\"^\") # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Zoomed Section')\nplt.legend()\nplt.show()\n\nfilename='Window1.xlsx'\ncomplete_forecast_output=np.stack((Forecast_output,Forecast_output_inv,MLP_Forecast_output,MLP_Forecast_output_inv),axis=1)\ncomplete_forecast_data=pd.DataFrame(data=complete_forecast_output,columns=['Actual Norm','Actual','MLP norm','MLP'])\ncomplete_forecast_data.to_excel(filename,'Sheet2')\n\n# Residual Check for fit\nResiduals=History_input_inv-MLP_History_output_inv\nResiduals=Forecast_output_inv-MLP_Forecast_output_inv\nResiduals=np.array(Residuals).reshape(-1)\nplot_acf(Residuals)\nplt.show()\n\nMean,variance=norm.fit(Residuals)\nOutput[10]=Mean\nOutput[11]=variance\n\n# Check the normality usiong probaility plot Default normal\nfig=plt.figure()\nprobplot(Residuals,plot=plt)\n\n# Histogram of residuals\nfig=plt.figure()\nplt.hist(Residuals)\nplt.show()\n\nsns.kdeplot(Residuals)\nAcorr=acorr_ljungbox(Residuals)\n\nMeanse=[0]*10\nfor i in range(1,10):\n Meanse[i]=1\n'''\n"
},
{
"alpha_fraction": 0.7135130167007446,
"alphanum_fraction": 0.7363402843475342,
"avg_line_length": 41.443580627441406,
"blob_id": "e26ca74636023a979fdf5c5b3ca127711cdadba0",
"content_id": "9b2f9f07e722cb0c7ad306fafea73a60c11879dc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10908,
"license_type": "no_license",
"max_line_length": 325,
"num_lines": 257,
"path": "/Pecan_MLP_data.py",
"repo_name": "ArunWSU/Short-time-series-forecasting",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nimport math\nimport statistics\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.neural_network import MLPRegressor\nfrom statsmodels.graphics.tsaplots import plot_acf\nimport matplotlib.pyplot as plt\nfrom scipy.stats import probplot\nfrom statsmodels.stats.diagnostic import acorr_ljungbox\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom scipy.stats import norm\n\n# Fixing the random number for neural net\nnp.random.seed(1)\n# Creates the input and output data for time series forecasting\ndef data_preparation(X,nlags):\n X_t,Y_t=[],[]\n # One for zero Index One for last point # if(i+nlags!=len(X))\n for i in range(0,len(X)-window_size,1):\n Row=X[i:i+nlags]\n X_t.append(Row)\n Y_t.append(X[i+nlags])\n return np.array(X_t).reshape(-1,window_size),np.array(Y_t).ravel()\n\ndef mape(X,Y):\n X1,Y1=np.array(X).reshape(-1,1),np.array(Y).reshape(-1,1)\n APE=abs((X1-Y1)/X1)\n mape_calc=np.mean(APE)*100\n return mape_calc\n\n\n# history vector\nAnnual=pd.read_csv(\"3967_data_2015_2018.csv\",header=0,index_col=0,parse_dates=True,usecols=['local_15min','use']) # Annual_data.idxmax() # Annual_data.idxmin()\nhistory_start_date='2017-01-02' \nhistory_end_date='2017-10-17'\nhistory=Annual[history_start_date:history_end_date] # Approximately 0.8=9.5 months\nhistory=history.values # Long way history.index=np.arange(0,len(history),1) history=history.values.reshape(-1,1)\nforecast=Annual['2017-10-18':'2017-12-31']\nforecast=forecast.values\n'''\n## CHOICE OF WINDOW SIZE FOR FORECASTING\nMetrics_output_window_select=np.zeros((20,6))\n\nfor x in range(1,15):\n # Input to MLP is of form No of samples, No of features\n window_size=x\n history_input,history_output=data_preparation(history,window_size)\n forecast_input,forecast_output=data_preparation(forecast,window_size)\n \n # Specify MLP regressor model\n mlp=MLPRegressor(hidden_layer_sizes=(7,),activation='identity',solver='lbfgs',random_state=1)\n mlp.fit(history_input,history_output)\n \n # Predict the outputs\n mlp_history_output=mlp.predict(history_input).reshape(-1,1)\n mlp_forecast_output=mlp.predict(forecast_input).reshape(-1,1)\n \n # Calculate the error metrics\n Metrics_output_window_select[x][0]=mean_squared_error(history_output,mlp_history_output)\n Metrics_output_window_select[x][1]=mean_absolute_error(history_output,mlp_history_output)\n Metrics_output_window_select[x][2]=mape(history_output,mlp_history_output)\n Metrics_output_window_select[x][3]=mean_squared_error(forecast_output,mlp_forecast_output)\n Metrics_output_window_select[x][4]=mean_absolute_error(forecast_output,mlp_forecast_output)\n Metrics_output_window_select[x][5]=mape(forecast_output,mlp_forecast_output)\n \nMetrics_output_window_select1=pd.DataFrame(data=Metrics_output_window_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\nMetrics_output_window_select1.to_csv('window_check.csv')\n\n\n## CHOICE OF NUMBER OF NEURONS FOR HIDDEN LAYER\nMetrics_output_neurons_select=np.zeros((20,6))\nwindow_size=4\nhistory_input,history_output=data_preparation(history,window_size)\nforecast_input,forecast_output=data_preparation(forecast,window_size)\n\nfor x in range(1,10):\n \n # Specify MLP regressor model\n mlp=MLPRegressor(hidden_layer_sizes=(x,),activation='identity',solver='lbfgs',random_state=1)\n mlp.fit(history_input,history_output)\n \n # Predict the outputs\n mlp_history_output=mlp.predict(history_input).reshape(-1,1)\n mlp_forecast_output=mlp.predict(forecast_input).reshape(-1,1)\n \n # Calculate the error metrics\n Metrics_output_neurons_select[x][0]=mean_squared_error(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][1]=mean_absolute_error(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][2]=mape(history_output,mlp_history_output)\n Metrics_output_neurons_select[x][3]=mean_squared_error(forecast_output,mlp_forecast_output)\n Metrics_output_neurons_select[x][4]=mean_absolute_error(forecast_output,mlp_forecast_output)\n Metrics_output_neurons_select[x][5]=mape(forecast_output,mlp_forecast_output)\n \nMetrics_output_neurons_select1=pd.DataFrame(data=Metrics_output_neurons_select,columns=['MSE_train','MAE_train','MAPE_train','MSE_test','MAE_test','MAPE_test'])\nMetrics_output_neurons_select1.to_csv('neuron_check.csv')\n \n'''\n# Choice of window size for window based forecasting\nwindow_size=4\nhistory_input,history_output=data_preparation(history,window_size)\n\n# Specify MLP regressor model\nmlp=MLPRegressor(hidden_layer_sizes=(9,),activation='identity',solver='lbfgs',random_state=1)\n\n# LBFGS for small samples No batch size Learning rate for SGD\nmlp.fit(history_input,history_output)\nmlp_history_output=mlp.predict(history_input)\n\n# Weeks\nerror_metrics=np.zeros((52,3))\nerror_metrics[0][0]=(mean_squared_error(history_output,mlp_history_output))\nerror_metrics[0][1]=(mean_absolute_error(history_output,mlp_history_output))\nerror_metrics[0][2]=(mape(history_output,mlp_history_output))\n\n# Checking for normal fit\nannual_data=Annual['2017'].use\n#plt.figure()\n#annual_data.plot.hist()\n#plt.title('Histogram of Annual data',fontsize=18)\n##plt.figure()\n##probplot(annual_data)\n##plt.show()\n#normalized_values=norm.pdf(annual_data.values)\n#plt.hist(normalized_values)\n#plt.show()\n\n# Calculate thresholds\nannual_data_mean=statistics.mean(annual_data)\nannual_data_sd=statistics.stdev(annual_data)\nupper_threshold=annual_data_mean+3*annual_data_sd # 18089 small\nlower_threshold=annual_data_mean-3*annual_data_sd\n\n\nB=[]\ny=0\nforecast_start_date_list=pd.Series(history_start_date)\nforecast_end_date_list=pd.Series(history_end_date)\n\n# Length and time to be forecasted\nforecast_start_date='2017-10-18' \nforecast_end_date='2017-12-31'\nforecast=Annual[forecast_start_date:forecast_end_date].use.copy()\ndates=pd.date_range(start=forecast_start_date,end=forecast_end_date)\n\n# Check on data frequency\ndaily_datapoints=96 \nmax_weekly_points=daily_datapoints*7\nno_of_dates=dates.shape[0]\nno_of_weeks=math.floor(no_of_dates/7) # Instead of int use ceil func to round up\n\nLastwindow=[]\nretrain=0\nADAM=1\nadam_forecast_output=np.zeros(forecast.shape[0]).reshape(-1,1)\nthreshold_violations=adam_forecast_output.copy()\nAct1=np.array([]) \nMLP1=np.array([])\nwindow_index=0\nfor x in range(0,no_of_weeks,1):\n # Modification maybe Mon to Mon\n start_index=str(dates[y].date())\n y=y+6\n if(x==no_of_weeks):\n y=-1\n end_index=str(dates[y].date())\n y=y+1\n \n forecast_start_date_list=forecast_start_date_list.append(pd.Series(start_index),ignore_index=True)\n forecast_end_date_list=forecast_end_date_list.append(pd.Series(end_index),ignore_index=True)\n\n # Weekly Data\n weekly_data=forecast[start_index:end_index] \n weekly_data.index=np.arange(0,len(weekly_data),1)\n forecast_output_actual=weekly_data.values.copy()\n if(x==0):\n adam_forecast_output[0:window_size]=forecast_output_actual[0:window_size].reshape(-1,1).copy() \n forecast_output_actual=forecast_output_actual[window_size:]\n\n mlp_forecast_weekly_actual=np.zeros(forecast_output_actual.shape[0]) \n no_of_datapoints_in_week=forecast_output_actual.shape[0]\n for i in range(0,no_of_datapoints_in_week,1):\n previous_window=adam_forecast_output[window_index:window_index+window_size].reshape(-1,window_size)\n mlp_forecast_weekly_actual[i]=mlp.predict(previous_window) \n if((lower_threshold < forecast_output_actual[i]) and (forecast_output_actual[i] < upper_threshold)):\n adam_forecast_output[window_index+window_size]=forecast_output_actual[i].copy()\n else:\n adam_forecast_output[window_index+window_size]=mlp_forecast_weekly_actual[i].copy()\n threshold_violations[window_index+window_size]=1\n window_index=window_index+1\n\n # Calculate RMSE\n error_metrics[x+1][0]=(mean_squared_error(forecast_output_actual,mlp_forecast_weekly_actual))\n\n # calculate MAE\n error_metrics[x+1][1]=(mean_absolute_error(forecast_output_actual,mlp_forecast_weekly_actual))\n \n # Calculate MAPE\n error_metrics[x+1][2]=(mape(forecast_output_actual,mlp_forecast_weekly_actual))\n B.append(mlp_forecast_weekly_actual)\n \n Act1=np.append(Act1,forecast_output_actual.reshape(-1,1))\n MLP1=np.append(MLP1,mlp_forecast_weekly_actual.reshape(-1,1))\n\n if(x==0): # USE CLASS DEFINITION\n Actual_forecast1=forecast_output_actual.reshape(-1,1) # Alternate Actual_forecast=Forecast[-Window_Size:]\n MLP_forecast=mlp_forecast_weekly_actual.reshape(-1,1)\n else:\n Actual_forecast1=np.concatenate([Actual_forecast1,forecast_output_actual.reshape(-1,1)])\n MLP_forecast=np.concatenate([MLP_forecast,mlp_forecast_weekly_actual.reshape(-1,1)])\n\nActual_forecast=Actual_forecast1[window_size:].reshape(-1,1)\n\n#filename='Annual1.xlsx'\ndifferent_regression_metrics=pd.DataFrame(data=error_metrics,columns=['RMSE_Actual','MAE_Actual','MAPE'])\ndifferent_regression_metrics['forecast_start_date_list'],different_regression_metrics['forecast_end_date_list']=[forecast_start_date_list,forecast_end_date_list] # different_regression_metrics['forecast_start_date_list']=forecast_start_date_list # different_regression_metrics['forecast_end_date_list']=forecast_end_date_list\n# different_regression_metrics.to_excel(filename,'Sheet1')\n\n# filename='Annual1.xlsx'\ncomplete_forecast_output=np.stack((Actual_forecast1,MLP_forecast),axis=1).reshape(-1,2)\ncomplete_forecast_data=pd.DataFrame(data=complete_forecast_output,columns=['Actual','MLP'])\n\n\n# plotting in matplotlib\n'''\nScale_Xh=np.arange(1,len(History_output)+1,1)\nfig=plt.figure()\nplt.plot(Scale_Xh,Actual_forecast,color='gray',label='Training load',linewidth=2,linestyle='-')\nplt.plot(Scale_Xh,MLP_History_output_inv,color='crimson',label='MLP Training Load',linewidth=2,linestyle='--')\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Training Set')\nplt.legend()\nplt.show()\n'''\n# Testing dataset\nfig=plt.figure()\nScale_Xh=np.arange(1,len(Actual_forecast1)+1,1)\nplt.plot(Scale_Xh,Actual_forecast1,color='gray',label='Actual load',marker=\"v\")\nplt.plot(Scale_Xh,MLP_forecast,color='crimson',label='MLP Forecasted Load',marker=\"^\") # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Testing Set')\nplt.legend()\nplt.show()\n\n# Testing dataset\nfig=plt.figure()\nScale_Xh=np.arange(1,len(forecast)+1,1)\nplt.plot(Scale_Xh,forecast,color='gray',label='Actual load',marker=\"v\")\nplt.plot(Scale_Xh,adam_forecast_output,color='crimson',label='ADAM Forecasted Load',marker=\"^\") # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Testing Set')\nplt.legend()\nplt.show()\n"
},
{
"alpha_fraction": 0.6967713832855225,
"alphanum_fraction": 0.7213132381439209,
"avg_line_length": 40.48868942260742,
"blob_id": "c1f0bb4b6a236be994398511723279945208d5b5",
"content_id": "c212ad06f1c362dd8fb4ec02f1b0eb9681235bf0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9168,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 221,
"path": "/MLP_weekly_final.py",
"repo_name": "ArunWSU/Short-time-series-forecasting",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom statsmodels.graphics.tsaplots import plot_acf\nimport pandas as pd\nimport statistics as stats\nfrom scipy.stats import probplot\nfrom statsmodels.stats.diagnostic import acorr_ljungbox\nimport seaborn as sns\nfrom scipy.stats import norm\nimport statistics\n\n# Fixing the random number for neural net\nnp.random.seed(1)\n# Creates the input and output data for time series forecasting\ndef data_preparation(X,nlags):\n X_t,Y_t=[],[]\n # One for zero Index One for last point # if(i+nlags!=len(X))\n for i in range(0,len(X)-window_size,1):\n Row=X[i:i+nlags]\n X_t.append(Row)\n Y_t.append(X[i+nlags])\n return np.array(X_t).reshape(-1,window_size),np.array(Y_t).ravel()\n\n\ndef mape(X,Y):\n X1,Y1=np.array(X),np.array(Y)\n APE=abs((X1-Y1)/X1)\n mape_calc=np.mean(APE)*100\n return mape_calc\n\n\n# History vector\nAnnual=pd.read_csv(\"Annual_load_profile_PJM.csv\",header=0,index_col=0,parse_dates=True)\nAnnual_data=Annual['mw']\nWeek1=Annual['2017-01-02':'2017-01-08']\nHistory=Week1['mw']\nHistory.index=np.arange(0,len(History),1)\nHistory=History.values.reshape(-1,1)\n\nannual_data_mean=statistics.mean(Annual_data)\nannual_data_sd=statistics.stdev(Annual_data)\nupper_threshold=annual_data_mean+3*annual_data_sd\nlower_threshold=annual_data_mean-3*annual_data_sd\n\n\nscaler_history=MinMaxScaler(feature_range=(0,1))\nHistory_norm=scaler_history.fit_transform(History)\n\n# Choice of window size for window based forecasting\nwindow_size=5\nHistory_input,History_output=data_preparation(History_norm,window_size)\n\n# Specify MLP regressor model\nmlp=MLPRegressor(hidden_layer_sizes=(7,),activation='identity',\n solver='lbfgs',random_state=1)\n\n# LBFGS for small samples No batch size Learning rate for SGD\nmlp.fit(History_input,History_output)\nMLP_History_output=mlp.predict(History_input)\n\n#Reshape for Inverse Transform\nHistory_input_inv=scaler_history.inverse_transform(History_input).reshape(-1)\nHistory_output_inv=scaler_history.inverse_transform(History_output.reshape(-1,1))\nMLP_History_output_inv=scaler_history.inverse_transform(MLP_History_output.reshape(-1,1))\n\n# Weeks\nerror_metrics=np.zeros((52,5))\nerror_metrics[0][0]=(mean_squared_error(History_output,MLP_History_output))\nerror_metrics[0][1]=(mean_absolute_error(History_output,MLP_History_output))\nerror_metrics[0][2]=(mean_squared_error(History_output_inv,MLP_History_output_inv))\nerror_metrics[0][3]=(mean_absolute_error(History_output_inv,MLP_History_output_inv))\nerror_metrics[0][4]=(mape(History_output_inv,MLP_History_output_inv))\n\n# History=pd.Series(np.ones((len(Week1),))) Input all ones\ndates=pd.date_range(start='2017-01-09',end='2017-12-31')\nno_of_dates=dates.size\nB=[]\nStart_list=[0]\ny=0\nw=int(no_of_dates/7)\nStartDate=pd.Series('2017-01-02')\nEndDate=pd.Series('2017-01-08')\nretrain=0\nForecast=Annual['2017-01-09':'2017-12-31'].mw\nForecast['2017-01-09']=0\nLastwindow=[]\nADAM=1\nmlp_forecast_weekly_actual_individual=np.zeros(Forecast.shape[0]).reshape(-1,1)\nforecast1_output=np.zeros(Forecast.shape[0]).reshape(-1,1)\n\n# Time stamp object to convert to date and then string str function\nfor x in range(0,w,1):\n StartIndex=str(dates[y].date())\n EndIndex=str(dates[y+6].date())\n y=y+7\n \n StartDate=StartDate.append(pd.Series(StartIndex),ignore_index=True)\n EndDate=EndDate.append(pd.Series(EndIndex),ignore_index=True)\n# # Pandas list to Series conversions\n# if(x==0):\n# Start_list=[StartIndex]\n# else:\n# Start_list.append(StartIndex)\n#\n# StartDate=pd.Series(Start_list)\n#\n# # Direct Series Object creation\n# if(x==0):\n# EndDate=pd.Series(EndIndex)\n# else:\n# EndDate=EndDate.append(pd.Series(EndIndex),ignore_index=True)\n\n # Weekly Data\n weekly_data=Annual[StartIndex:EndIndex].mw\n weekly_data.index=np.arange(0,len(weekly_data),1)\n scaler_forecast=MinMaxScaler(feature_range=(0,1))\n forecast_output_actual=weekly_data.values\n min_weekly_forecast=min(forecast_output_actual)\n forecast_output_norm=scaler_forecast.fit_transform(forecast_output_actual.reshape(-1,1))\n # o,forecast_output_norm=data_preparation(forecast_output_norm,window_size)\n \n Forecast_output_actual=scaler_forecast.inverse_transform(forecast_output_norm.reshape(-1,1))\n if(x==0):\n forecast_output_actual=forecast_output_actual[window_size:]\n forecast_output_norm_continous=forecast_output_norm\n forecast_output_norm=forecast_output_norm[window_size:]\n no_of_datapoints_in_week=forecast_output_norm.shape[0]\n else:\n forecast_output_norm_continous=np.concatenate([forecast_output_norm_continous,forecast_output_norm]) \n no_of_datapoints_in_week=forecast_output_norm.shape[0] \n if(retrain==1):\n scaler_hist=MinMaxScaler(feature_range=(0,1))\n history=Annual[StartDate[x]:EndDate[x]].mw\n history.index=np.arange(0,len(history),1)\n history_norm=scaler_hist.fit_transform(history.values.reshape(-1,1))\n history_input,history_output=data_preparation(history_norm,window_size)\n mlp.fit(history_input,history_output)\n \n mlp_forecast_weekly_norm=np.zeros(forecast_output_norm.shape[0])\n \n for i in range(0,no_of_datapoints_in_week,1): \n previous_window=forecast_output_norm_continous[i:i+window_size].reshape(-1,window_size)\n mlp_forecast_weekly_norm[i]=mlp.predict(previous_window) \n #mlp_forecast_weekly_actual_individual[i]=scaler_forecast.inverse_transform(mlp_forecast_weekly_norm[i]).reshape(1,-1)\n if(ADAM==1):\n if((lower_threshold < forecast_output_actual[i]) and (forecast_output_actual[i] < upper_threshold)):\n forecast1_output[i]=forecast_output_actual[i]\n else:\n forecast1_output[i]=mlp_forecast_weekly_actual_individual[i]\n \n forecast_output_norm_continous=forecast_output_norm[-window_size:].reshape(-1,1) \n mlp_forecast_weekly_actual=scaler_forecast.inverse_transform(mlp_forecast_weekly_norm.reshape(-1,1))\n # calculate RMSE\n Test_score=(mean_squared_error(forecast_output_norm,mlp_forecast_weekly_norm))\n error_metrics[x+1][0]=Test_score\n\n # calculate MAE\n Test_score1=(mean_absolute_error(forecast_output_norm,mlp_forecast_weekly_norm))\n error_metrics[x+1][1]=Test_score1\n\n # Calculate RMSE\n Test_score=(mean_squared_error(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][2]=Test_score\n\n # calculate MAE\n Test_score1=(mean_absolute_error(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][3]=Test_score1\n\n # Calculate MAPE\n Test_score1=(mape(forecast_output_actual,mlp_forecast_weekly_actual))\n error_metrics[x+1][4]=Test_score1\n B.append(mlp_forecast_weekly_actual)\n\n if(x==0): # USE CLASS DEFINITION\n Actual_norm=forecast_output_norm.reshape(-1,1)\n Actual_forecast=forecast_output_actual.reshape(-1,1)\n MLP_forecast_norm=mlp_forecast_weekly_norm.reshape(-1,1)\n MLP_forecast=mlp_forecast_weekly_actual.reshape(-1,1)\n else:\n Actual_norm=np.concatenate([Actual_norm,forecast_output_norm.reshape(-1,1)])\n Actual_forecast=np.concatenate([Actual_forecast,Forecast_output_actual.reshape(-1,1)])\n MLP_forecast_norm=np.concatenate([MLP_forecast_norm,mlp_forecast_weekly_norm.reshape(-1,1)])\n MLP_forecast=np.concatenate([MLP_forecast,mlp_forecast_weekly_actual.reshape(-1,1)])\n\nfilename='Annual1.xlsx'\ndifferent_regression_metrics=pd.DataFrame(data=error_metrics,columns=['RMSE_Scale','MAE_Scale','RMSE_Actual','MAE_Actual','MAPE'])\ndifferent_regression_metrics['StartDate']=StartDate\ndifferent_regression_metrics['EndDate']=EndDate\ndifferent_regression_metrics.to_excel(filename,'Sheet1')\n\nfilename='Annual1.xlsx'\ncomplete_forecast_output=np.stack((Actual_norm,Actual_forecast,MLP_forecast_norm,MLP_forecast),axis=1).reshape(-1,4)\ncomplete_forecast_data=pd.DataFrame(data=complete_forecast_output,columns=['Actual Norm','Actual','MLP norm','MLP'])\ncomplete_forecast_data.to_excel(filename,'Sheet2')\n'''\n# plotting in matplotlib\nScale_Xh=np.arange(1,len(History_output)+1,1)\nfig=plt.figure()\nplt.plot(Scale_Xh,History_output_inv,color='gray',label='Training load',linewidth=2,linestyle='-')\nplt.plot(Scale_Xh,MLP_History_output_inv,color='crimson',label='MLP Training Load',linewidth=2,linestyle='--')\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Training Set')\nplt.legend()\nplt.show()\n\n# Testing dataset\nfig=plt.figure()\nScale_Xh=np.arange(1,len(Actual_Forecast)+1,1)\nplt.plot(Scale_Xh,Actual_Forecast,color='gray',label='Actual load',marker=\"v\")\nplt.plot(Scale_Xh, MLP_Forecast,color='crimson',label='MLP Forecasted Load',marker=\"^\") # linewidth=2,linestyle='--'\nplt.xlabel('Time(Hours)', fontsize=18)\nplt.ylabel('Load(MW)', fontsize=18)\nplt.title('Testing Set')\nplt.legend()\nplt.show()\n'''"
}
] | 5 |
Epiconcept-Paris/infra-files-flow | https://github.com/Epiconcept-Paris/infra-files-flow | 0cd3fe6a2e23ae23125988831cd3375cab5fe8d5 | e479255923be59daaf885738406ff3ca4cde5e34 | 7636ba89b282e8b91c1e302c8e79f98b17810579 | refs/heads/master | 2023-08-27T01:02:02.608406 | 2023-08-24T10:48:10 | 2023-08-24T10:48:10 | 162,454,859 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5735502243041992,
"alphanum_fraction": 0.6004243493080139,
"avg_line_length": 32.66666793823242,
"blob_id": "9c02a4d32a6fa16ed500db461dca49e98e92b28d",
"content_id": "01be65a255debd01d957969eb23af21972707656",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1414,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 42,
"path": "/bash/bash-fix",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n#\n#\tbash/bash-fix - Patch/unpatch /usr/local/bin/indird to use bash-5.0\n#\t\t\tbash-static package (and install / purge it) to fix\n#\t\t\ta bash-4.0 'hang' bug in jobs.c:bgp_delete()\n#\nPrg=$(basename $0)\ntest $(id -u) -eq 0 || { echo \"$Prg: must be run as root\" >&2; exit 1; }\n\nMain='/usr/local/bin/indird'\ntest -x $Main || { echo \"$Prg: $Main is not installed, aborting\" >&2; exit 2; }\n\nBang='#!/usr/bin/env'\nfix()\n{\n sed -i \"s;^$Bang .*$;$Bang $1;\" $Main\n}\n\nBash=$(command -v bash)\nVer=$($Bash --version | sed -nr 's/^.* version ([0-9]+)\\..*$/\\1/p')\nexpr \"$Ver\" : '[0-9][0-9]*$' >/dev/null || { echo \"$Prg: cannot determine version of $Bash, aborting\" >&2; exit 3; }\n\nif [ \"$Ver\" -lt 5 ]; then\n if ! command -v bash-static >/dev/null; then\n\tPkg=${1:-bash-static_5.0-4_amd64.deb}\n\tdpkg -I $Pkg >/dev/null 2>&1 || { echo \"$Prg: $Pkg is not a valid Debian package\" >&2; exit 4; }\n\techo \"Installing $Pkg\"\n\tdpkg -i $Pkg\n fi\n grep \"^$Bang bash-static\\$\" $Main >/dev/null && { echo \"$Prg: $Main is already fixed for bash$Ver\" >&2; exit 0; }\n echo \"Patching $Main for bash-static\"\n fix bash-static\nelse\n grep \"^$Bang bash\\$\" $Main >/dev/null && { echo \"$Prg: standard $Main works with bash$Ver\" >&2; exit 0; }\n echo \"Restoring standard $Main\"\n fix bash\n if dpkg -L bash-static >/dev/null 2>&1; then\n\techo \"Removing now useless bash-static package\"\n\tdpkg -P bash-static\n fi\nfi\nexit 0\n"
},
{
"alpha_fraction": 0.5311355590820312,
"alphanum_fraction": 0.553113579750061,
"avg_line_length": 21.83333396911621,
"blob_id": "9c58e0fb91ffa372016ae19e787100805dbae56a",
"content_id": "6e85a8671a6cb196b4a60cdb1ae067a3a2232367",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 273,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 12,
"path": "/ansible/files/stated_indird",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nABS=$(cd $(dirname \"${BASH_SOURCE[0]}\") && pwd)\nmode=$1\nif [ -z \"$mode\" ]; then mode='normal'; fi\n\nvalues=$($ABS/../indirdctl check | xargs)\nif [ ! -z \"$values\" ]; then\n\techo -e \"\\e[1m\\e[41m $values \\e[0m\"\nelse \n\tif [ \"$mode\" == \"full\" ]; then echo \"ok\"; fi\nfi"
},
{
"alpha_fraction": 0.6609053611755371,
"alphanum_fraction": 0.7292181253433228,
"avg_line_length": 36.96875,
"blob_id": "e221e524653c83ca506b99754ef9a921ea35a049",
"content_id": "017759ef5a20beccb4c5c2bcf2ed094de80fe608",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1215,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 32,
"path": "/start-limit/getsrc",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nPrg=$(basename $0)\ncd $(dirname $0)\nmkdir work || { echo \"$Prg: directory 'work' already exists. Remove or rename it to proceed...\" >&2; exit 1; }\nexec 2>$Prg.log\nget()\n{\n wget --progress=dot:mega \"$@\"\n}\ncd work\nget http://ftp.debian.org/debian/pool/main/s/systemd/systemd_232.orig.tar.gz\nget http://deb.freexian.com/extended-lts/pool/main/s/systemd/systemd_232-25+deb9u15.debian.tar.xz\nget http://ftp.debian.org/debian/pool/main/s/systemd/systemd_241.orig.tar.gz\nget http://ftp.debian.org/debian/pool/main/s/systemd/systemd_241-7~deb10u8.debian.tar.xz\nget http://ftp.debian.org/debian/pool/main/s/systemd/systemd_247.3.orig.tar.gz\nget http://ftp.debian.org/debian/pool/main/s/systemd/systemd_247.3-7+deb11u1.debian.tar.xz\nget \"http://ftp.debian.org/debian/pool/main/s/systemd\" \nmv systemd systemd.html\ntar xf systemd_232.orig.tar.gz\ncd systemd-232\ntar xf ../systemd_232-25+deb9u15.debian.tar.xz \ncd ..\ntar xf systemd_241.orig.tar.gz\ncd systemd-241\ntar xf ../systemd_241-7~deb10u8.debian.tar.xz\ncd ..\ntar xf systemd_247.3.orig.tar.gz\ncd systemd-stable-247.3\ntar xf ../systemd_247.3-7+deb11u1.debian.tar.xz\ncd ..\nfind systemd-* -type f -print0 | sort -z | xargs -0 grep '[^t]StartLimitInter' >grep.out\n"
},
{
"alpha_fraction": 0.738724946975708,
"alphanum_fraction": 0.7404497265815735,
"avg_line_length": 66.7662353515625,
"blob_id": "6740cf09660c50a1b9f8ba2c972afae78783fb93",
"content_id": "fd5146914e585aef75bf8806c971de4ada8ef4d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 15913,
"license_type": "no_license",
"max_line_length": 502,
"num_lines": 231,
"path": "/README.md",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "# infra_files_flow\nConfiguration `systemd` et script de gestion de répertoires d'arrivée\n\n## Introduction\nLe script `bash` \"`indird`\" gère un flux de fichiers entrants, déposés dans un unique répertoire d'arrivée. \nLes fichiers peuvent être de différents types et les actions effectuées sur ces fichiers peuvent varier selon le type, l'ensemble étant paramétrable dans un fichier de configuration au format JSON, sans qu'il soit nécessaire de modifier le script. Le fichier de configuration peut être extrait d'un fichier de configuration au format YAML, éventuellement plus global (plusieurs *hosts*). \nLe script `indird` fonctionne comme un *service* `indird` de `systemd` (`man systemd.service`), donc en tant que *daemon*, en utilisant la possibilité de `systemd` de gérer plusieurs **instances** d'un même service, ce qui peut permettre dans un même système de gérer avec `indird` plusieurs répertoires d'arrivée. La configuration de ces instances peut être regroupée dans un même fichier de configuration global au système, chaque instance étant accessible par un **tag** (étiquette). \nEn l'absence d'arrivée de fichiers, le script `indird` attend par une commande `sleep` de durée paramètrable, cependant qu'une fonction spéciale de `systemd` (`man systemd.path`), paramétrée comme `indirdwake`, surveille toute modification du répertoire d'arrivée. Lorsque celle-ci se produit, `systemd` rappelle par la commande `indird <tag> wakeup` un `indird` secondaire qui `kill` s'il y a lieu le `sleep` en cours du `indird` principal, relançant ainsi la boucle de traitement des fichiers.\n\n## Utilitaire prérequis\nLe script `indird` utilise l'utilitaire `jq`, qui est disponible dans les paquets Linux Debian standards.\nUne vérification de l'accessibilité de `jq` est faite au lancement de `indird`.\n\n## Installation du script indird\n\nIl faut copier les fichiers aux emplacements suivants :\n```\nindird/indird\t\t/usr/local/bin\[email protected]\t\t/etc/systemd/system\[email protected]\t/etc/systemd/system\[email protected]\t/etc/systemd/system\nexamples/indird.conf\t/etc\n```\net accessoirement les utilitaires fournis (voir la section **Utilitaires** dans ce document) :\n```\nutils/yaml2json\t\t/usr/local/bin\nutils/mkiconf\t\t/usr/local/bin\nutils/ckiyaml\t\t/usr/local/bin\n```\nLes utilitaires `mkiconf` et `ckiyaml` dépendent de l'utilitaire `yaml2json`, qui lui même nécessite les packages Debian `python-yaml` et `python-docopt`.\n\nAprès modification du fichier `/etc/indird.conf`, il faut lancer :\n```\n# systemctl enable indird@<tag>.service\n# systemctl enable indirdwake@<tag>.path\n\n# systemctl start indird@<tag>.service\n```\ndans lequel *\\<tag>* est le nom de la section du fichier de configuration à utiliser (voir ci-dessous), qui sert d'instance à `systemd`. Exemples :\n```\n# systemctl start indird@sspdamoc\n# systemctl start indird@sspnice\n```\nLes *\\<tag>* `sspdamoc` et `sspnice` sont donc à la fois des instances de `indird@` pour `systemd.service` et `systemd.path` et des *\\<tag>* pour `indird`, correspondant chacun à la gestion d'un répertoire.\n\nPour arrêter / désinstaller :\n\n```\n# systemctl stop indird@<tag>.service\n\n# systemctl disable indirdwake@<tag>.path\n# systemctl disable indird@<tag>.service\n\n```\nPour obtenir le status :\n```\n# systemctl status indird@<tag>\n# systemctl status indirdwake@<tag>.path\n```\nLe rechargement de la configuration `indird.conf` (après modifications) est géré :\n```\n# systemctl reload indird@<tag>\n```\nNOTE : En cas, de modification de l'élément `path` de la configuration, le lien symbolique `/run/indird/<tag>_path` vers le chemin indiqué par `path` est automatiquement mis à jour par `indird`.\n\nLe fichier de log interne de `indird` est pour l'instant `/var/log/indird.log` et des liens symboliques de fonctionnement son créés dans le répertoire `/run/indird` (créé par le script si nécessaire). Le scipt `indird` crée également des fichiers temporaires dans `/tmp`. C'est trois chemins sont déterminés par les variables shell `LogFile`, `RunDir` et `TmpDir` au début du script.\n\n## Algorithme de fonctionnement\n\nIl a été mis au point après discussions entre TDE, CGD et CTY.\nL'idée de base est d'exécuter pour chaque fichier entrant une ou plusieurs commandes shell (`actions`) qui peuvent réussir ou échouer, ce qui détermine à nouveau pour chacune des `actions` une ou plusieurs commandes de traitement de fin (`ends`), variables selon le succès ou l'échec de l'`action` correspondante, qui est déterminé par un jeu de conditions (`conds`). Puis le résultat de l'action est journalisé selon des modalités prédéfinies (`logs`).\n\nAprès lecture et vérification du fichier de configuration, `indird` entre dans la boucle principale suivante:\n```\nindéfiniment (jusqu'à un arrêt par SIGTERM)\n sortir de 'sleep' (par fin du délai ou par 'kill') et sauver le dernier 'mtime' de `path`\n tant que `path` a été modifié ('mtime') depuis le dernier tour (de cette boucle)\n pour toutes les `filetypes` membres de l'objet global `rules`\n pour tous les fichiers correspondant à ce membre de `filetypes`\n\tpour toutes les étapes de la règle\n\t lancer l'action de l'étape\n\t pour toutes les fins (`ends`) de l'étape\n\t vérifier si la condition `cond` de fin s'applique\n\t exécuter le `end` correspondant défini dans l'objet global `ends` des fins\n\t pour tous les (`logs`) de l'étape\n\t logger le résultat de l'action de l'étape\n attendre par 'sleep' la durée `sleep` spécifiée dans la configuration\nl'activation par `systemd` de `indirdwake` rappelle un `indird` secondaire pour interrompre le 'sleep'\n```\n\n## Fichier de configuration\n\n### Emplacement du fichier\nIl s'agit par défaut de `/etc/indird.conf`, mais il est possible de spécifier (pour des tests par exemple) un autre chemin de fichier dans la variable d'environnement `INDIRD_CONFIG`. Exemple :\n```\nINDIRD_CONFIG=indird.conf indird sspdamoc check\n```\n\n### Structure du fichier de configuration\nLe fichier de configuration de `indird` est au format JSON. Au niveau principal, les membres de l'objet racine (anonyme) sont les différentes instances (au moins une) spécifiés dans le fichier par leur **\\<tag>**. Chaque membre **\\<tag>** est à son tour un objet JSON avec un certain nombre de membres obligatoires [o] et facultatifs [f] selon la liste suivante:\n\n* `path` [o] - Le chemin absolu du répertoire à surveiller. Son existence est vérifiée au lancement de `indird`, sinon *abort*\n* `sleep` {o] - Le délai d'attente quand `path` ne reçoit pas de fichier. La valeur doit bien sur être numérique et d'au moins 5 (secondes) (variable `MinSleep` dans le script), sinon *abort*\n* `host` [f] - Le nom réseau du système, qui doit correspondre au résultat de `hostname`, sinon *abort* de `indird`\n* `shell` [f] - Le nom d'un shell autre que `sh` pour exécuter les commandes. La commande doit être disponible, sinon *abort* de `indird`\n* `debug` [f] - Une valeur `true` ou `false` (par défaut), sinon *abort*, qui active ou non les logs de debug de `indird`\n\n* `env_prefix` [f] - Le préfixe des variables d'environnement qui seront disponibles dans les commandes de `actions`, `ends` et `conds` (voir ci-dessous) et pour le `path` des `logs` de type `file` (voir `logs`ci dessous). Si non spécifié, il vaut `INDIRD_`\n* `env` [f] - Un objet global dont chaque membre indique un suffixe de variable d'environnement et la valeur de ce suffixe. Le script `indird` ajoute automatiquement à cet objet les variables suivantes:\n - `${env_prefix}HOST` - le nom `hostname` du système\n - `${env_prefix}CONF` - le **\\<tag>** spécifié\n - `${env_prefix}PATH` - la valeur de `path`\n - `${env_prefix}FILE` - le nom du fichier en cours de traitement\n - `${env_prefix}CODE` - la code de retour de l'`action` (voir ci-dessous) après son exécution)\n\n* `filetypes` [o] - Un objet global dont chaque membre est un objet décrivant un type de fichier à gérer par `indird`, avec les (sous-)membres obligatoires suivants :\n - `desc` - un texte de description du type, pour usage dans les logs\n - `method` - la méthode, `fileglob` ou `regexp`, du filtre de nom de fichiers. La méthode `fileglob` utilise le *matching* du shell (`bash`), le méthode `regexp` utilise `grep`\n - `pattern` - le motif pour le filtre\n\n* `actions` [o] - Un objet global dont chaque membre est un objet décrivant une commande shell principale à exécuter (passée à `sh -c`) sur le fichier, avec les (sous-)membres suivants:\n - `desc` [f] - un texte de description\n - `cmd` [o] - la commande à exécuter, qui sera passée à sh -c\n - `chdir` [f] - un répertoire de travail optionel pour la commande\n - `env` [f] - un complément de variables d'environnement pour la commande, analogue au `env` global\n\n* `ends` [f] - Un objet global dont chaque membre est un objet décrivant une commande shell *de nettoyage* à exécuter (passée à `sh -c`) sur le fichier, avec les (sous-)membres suivants:\n - `desc` [f] - un texte de description\n - `cmd` [o] - la commande à exécuter, qui sera passée à sh -c\n - `chdir` [f] - un répertoire de travail optionel pour la commande\n - `env` [f] - un complément de variables d'environnement pour la commande, analogue au `env` global\n - `stdin` [f] - les valeurs 'out', 'err', 'all' exclusivement, indiquant quel(s) élément(s) des stdout/stderr de l'`action` associée seront passés en stdin à la commande de ce membre de `ends`\n\n* `logs` [f] - Un objet global dont chaque membre est un objet décrivant une méthode de journalisation à employer pour le résultat de l'action associée, avec les (sous-)membres suivants:\n - `desc` [f] - un texte de description\n - `type` [o] - le type du log, actuellement `file` ou `syslog` seulement\n - `args` [f] - les arguments du log, qui varient selon `type`. Pour `file`, on a la valeur obigatoire `path` qui indique le nom du fichier de log et pour `syslog`, deux arguments :\n + `facility` [o] - la 'facility' de syslog. Valeurs admises : `user` et `daemon`\n + `level` [o] - le niveau de log, parmi toutes les valeurs admises par logger(1), soit `emerg`, `alert`, `crit`, `err`, `warning`, `notice`, `info`, `debug` ainsi que `panic` pour `emerg`, `error` pour `err` et `warn` pour `warning`\n\n* `conds` [f] - Un objet global dont chaque membre est une commande à exécuter, dont le code de retour détermine une condition pour les `rules` ci-dessous\n\n* `rules` [o] - L'objet global principal, dont chaque membre a le nom d'un type de fichiers membre de `filetypes` et définit le jeu de règles pour gérer ce type de fichiers, sous la forme d'une liste (tableau) d'étapes (steps) ayant chacune la structure suivante :\n - `desc` [f] - un texte de description\n - `hide` [f] - une valeur `true` ou `false` (par défaut). Si true, l'étape (step) est ignorée\n - `action` [o] - le nom d'une action membre de l'objet global `actions`\n - `ends` [f] - une liste (tableau) d'objets comportant les (sous-)membres suivants:\n + `cond` [o] - le nom d'une condition dans `conds`\n + `end` [o] - le nom d'un membre de l'objet global `ends`\n - `logs` [f] - une liste (tableau) de méthodes de log du résultat de `action`, méthodes définie dans l'objet global `logs`\n\nDans le cas où l'exécution d'une commande `cmd` de `actions` risque d'être trop longue, il est possible de limiter sa durée en préfixant la commande avec la commande standard `timeout`. Exemple :\n```\ntimeout 30 rsync -e \"ssh -i $i_PATH/.ssh/rsync -l $i_user\" \"$i_FILE\" $i_front:\n```\n\nSi la commande `cmd` de `actions` d'une étape (step) échoue, les étapes suivantes ne seront pas exécutées.\n\nPour l'instant, seul le résultat de la commande est loggé par `logs` (global et `rules`) avec le texte fixe suivant : \"$Tag $act for $file returned $Ret\" dans lequel les variables internes suivantes sont affectées par `indird` :\n - `$Tag` est l'instance (*\\<tag>*) de `indird`, par exemple `sspdamoc`\n - `$act` est le chemin de config de l'action en cours, par exemple `actions.copy`\n - `$file` est le nom du fichier en cours\n - `$Ret` est le résultat de `$act` : `success` ou par exemple `failure (exit=3)`\n\nUne extension facile des logs est prévue dans `indird`, les `logs` d'une étape (step) étant traités par une fonction interne StepLogs.\n\n## Exemples de fichiers de configuration\n\n[examples/indird.yml]: examples/indird.yml \"fichier local\"\n[examples/indird.conf]: examples/indird.conf \"fichier local\"\n\nLa définition du projet a donné lieu à la rédaction de l'exemple de fichier de configuration en YAML [examples/indird.yml][], pour trois hosts différents.\nLes nombreux commentaires du fichier, reprenant des parties de cette documentation, permettent de situer celles-ci dans leur contexte.\n\nCe fichier YAML peut être transformé en JSON avec l'utilitaire `yaml2json` fourni, dérivant de celui de `https://github.com/drbild/json2yaml.git` et nécessitant comme lui les packages Debian `python-yaml` et `python-docopt`. Exemple:\n```\nyaml2json examples/indird.yml | jq .hosts.procom1.confs >indird.conf\n```\n\nLe fichier [examples/indird.conf][] contient un exemple de fichier de configuration généré pour le *host* `procom1` de [examples/indird.yml][]. Il est aussi possible (entre autres solutions), après l'installation de `indird`, de le générer avec l'utilitaire `mkiconf` fourni :\n```\nmkiconf examples/indird.yml procom1 >indird.conf\n```\n\nEst également disponible en open-source le package Javascript `yamljs` que l'on peut, sur un système ne disposant pas de `nodejs`, installer par exemple par :\n\n```\ncurl -sL https://deb.nodesource.com/setup_6.x | sudo bash -\nsudo npm install -g yamljs\n```\n## Utilitaires\n\n### `indird`\n`indird` dispose d'options destinées à être utilisées en ligne de commande :\n - `config` - cette option affiche sans vérification la configuration pour un *\\<tag> donné, sous une forme analogue à celle des *MIB SNMP* (par exemple : `filetypes.hl7.method=\"fileglob\"`)\n - `check` - cette option vérifie la cohérence de la configuration entre ses différents objets, ainsi que l'existence ou la conformité des éléments *externes* à cette configuration : les chemins (`path`, `shell`) et le `host`\n - `nlcheck` - cette option (non-local check) vérifie uniquement la cohérence de la configuration entre ses objets, pas les chemins effectifs et le `host`. Elle est utilisée par `ckiyaml`, décrit ci-dessous, pour vérifier la configuration d'un *host* non-local (sur un autre *host*)\n\nExemples d'utilisation :\n```\nindird sspdamoc config\nindird sspnice check\nINDIRD_CONFIG=procom1.conf indird rdvradio nlcheck\n```\n\n### `yaml2json`\n`yaml2json` est un utilitaire Python permettant de convertir un fichier YAML en fichier JSON.\n\nExemples d'utilisation :\n```\nyaml2json examples/indird.yml indird.conf\nyaml2json examples/indird.yml | jq .hosts.procom1.confs >indird.conf\n```\nLes fichiers peuvent être des noms ou des *pipes* (stdin ou stdou)\n\n### `mkiconf`\n`mkiconf` est un petit utilitaire d'extraction de configuration, qui illustre l'utilisation de `yaml2json` ci-dessus. Il facilite la génération du fichier de configuration d'un *host*.\n\nExemples d'utilisation :\n```\nmkiconf examples/indird.yml procom1 >procom1.conf\nmkiconf examples/indird.yml profnt2 >profnt2.conf\n```\n\n### `ckiyaml`\n`ckiyaml` est un petit utilitaire de vérification de fichier YAML global (multi-host), qui illustre également l'utilisation de `yaml2json`, ce dernier assurant, avec la conversion en JSON, la vérification de la syntaxe YAML. Il nécessite aussi `indird` pour la vérification de la cohérence de sa configuration. La commande génère pour chaque *host* un fichier de configuration temporaire dont chaque *\\<tag>* est ensuite vérifié avec la commande `INDIRD_CONFIG=<config_temporaire> indird <tag> nlcheck`\n\nExemple d'utilisation :\n```\nckiyaml globalconf.yml\n```\n"
},
{
"alpha_fraction": 0.6627218723297119,
"alphanum_fraction": 0.668639063835144,
"avg_line_length": 14.363636016845703,
"blob_id": "da93636c474376655863c55ef18f111ced8ba707",
"content_id": "02d22c17d4ad807d926c9639ddac250f5f3bb7a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 169,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 11,
"path": "/ansible/docker/compose/docker-compose.yml",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "version: '2'\n\nservices:\n\n source:\n build: ../build/source\n container_name: source\n\n destination:\n build: ../build/destination\n container_name: destination\n"
},
{
"alpha_fraction": 0.7105963826179504,
"alphanum_fraction": 0.7364217042922974,
"avg_line_length": 33.14545440673828,
"blob_id": "2574ce31e7257f478daa815c3c3f746c8384ca40",
"content_id": "8545c1c7614f9073037f54bdd5471ed572068ca1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3788,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 110,
"path": "/ansible/README.md",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "# Usage déploiement indird\n\n* en attendant le changement d'inventaire\n```\nansible-playbook -i ~/bin/list_new_servers.txt deploiement.yml -D\n```\n\n* pour générer les configurations dans /tmp/\n```\nansible-playbook -i ~/bin/list_new_servers.txt deploiement.yml -D -t local\n```\n\n* pour juste déployer une maj de conf (retirer le -C quand c'est validé)\n```\nANSIBLE_MAX_DIFF_SIZE=1000000 ansible-playbook -i ~/bin/list_new_servers.txt deploiement.yml -DC -t reconf\n```\n\nNote: l'exécution en Check va planter avec ce message, sans importance ici\n```\nfatal: [procom1.admin2]: FAILED! => {\"msg\": \"'dict object' has no attribute 'stdout_lines'\"}\nfatal: [profntd1.admin2]: FAILED! => {\"msg\": \"'dict object' has no attribute 'stdout_lines'\"}\n```\n\n# Docker de test\n\n* lancement des containers\n```\ndocker-compose --file=docker/compose/docker-compose.yml --project-name=lsyncd up\n```\n\n* tester le fonctionnement\n```\nansible all -i docker/hosts -m ping\n```\n\n* déploiement \n```\nansible-playbook -i docker/hosts lsyncd.yml\n```\n\n* test conf lsyncd manuelle\n```\nlsyncd -nodaemon /etc/lsyncd.lad_test.conf\n```\n\n# Sources\n\n* déploiement manuel par TDE : https://github.com/Epiconcept-Paris/infra-journals-indexed/blob/master/indexed/all/tde/journal/2019-11-25_TDE_indird.md\n\n# Todo\n\n* intégrer la gestion des liens\n```\n(preprod front 2)cedric@prefnt2:/space/applisdata/esisdoccu/LAD_RP$ ls -lha\ntotal 8.0K\ndrwxr-xr-x 2 www-data www-data 4.0K Jul 7 15:44 .\ndrwxr-xr-x 6 www-data www-data 4.0K Jul 7 15:42 ..\nlrwxrwxrwx 1 www-data www-data 39 Jul 7 15:44 lad_test -> /space/home/lad_lsyncd_preprod/lad_test\nlrwxrwxrwx 1 www-data www-data 44 Jul 7 15:44 lad_test_mhu -> /space/home/lad_lsyncd_preprod/lad_test_mhu/\n\ncedric@profntd1:/space/applisdata/esisdoccu$ sudo -u www-data mkdir /space/applisdata/esisdoccu/LAD_RP\ncedric@profntd1:/space/applisdata/esisdoccu$ sudo -u www-data ln -s /space/home/lad_lsyncd_prod/LADDOCCU38/ /space/applisdata/esisdoccu/LAD_RP/\n\ncedric@profntd1:/space/applisdata/esisdoccu/LAD_RP$ ls -lh\ntotal 0\nlrwxrwxrwx 1 www-data www-data 39 Sep 4 16:45 LADDOCCU38 -> /space/home/lad_lsyncd_prod/LADDOCCU38/\ncedric@profntd1:/space/applisdata/esisdoccu/LAD_RP$ ls LADDOCCU38/KU/RP/\ncedric\n```\n\n* utiliser l'inventaire 2019 par TDE\n* paths dont dépend le logiciel (aujourd'hui, infra-data-misc), à gérer en fonction des utilisateurs\n* intégrer et tester les accès ssh entre procom1 et les frontaux\n* intégrer la création des accès SFTP sur procom (récup depuis https://github.com/Epiconcept-Paris/infra-mini-plays, ou à minima rationnalisation des comptes)\n* commit sur /etc/ à ajouter\n\n# Lsyncd\n\n## TODO\n\n* ré-intégrer procom1:/etc/lsyncd/conf.d/* à la conf au lieu de générer selon le template\n * infra-files-flow/ansible/templates/ged_lsyncd_preprod.conf.j2\n * infra-files-flow/ansible/templates/lad_lsyncd_preprod.conf.j2\n\n## Déploiement\n\n* ansible-playbook lsyncd_users.yml -D\n* **attention, procom1:/etc/lsyncd/conf.d/* gérer à la main, à ré-intégrer** ansible-playbook lsyncd.yml -D\n\n## Test\n\n* ansible-playbook lsyncd_tests_KU.yml \n* ansible-playbook lsyncd_tests_GED.yml \n\n## Flux\n\n### Légende\n\n* => flux rsync over SSH\n* -> symlink au sein d'un serveur\n\n### GED\n\n* procom1:/space/home/lad_test_mhu/GED/ => prefnt2:/space/home/lad_lsyncd_preprod/GED/ -> /space/applisdata/esisdoccu/GED/geddoccu_test\n\n### KU/RP\n\n* procom1:/space/home/lad_test/KU \t\t=> prefnt2:/space/home/lad_lsyncd_preprod/lad_test/KU \t\t-> /space/applisdata/esisdoccu/LAD_RP/lad_test/KU\n* procom1:/space/home/lad_test_mhu/KU \t=> prefnt2:/space/home/lad_lsyncd_preprod/lad_test_mhu/KU \t-> /space/applisdata/esisdoccu/LAD_RP/lad_test_mhu/KU\n* procom1:/space/home/LADDOCCU38 \t\t=> profntd1:/space/home/lad_lsyncd_prod \t\t\t\t\t-> /space/applisdata/esisdoccu-alpes/LAD_RP/LADDOCCU38\n"
},
{
"alpha_fraction": 0.7185314893722534,
"alphanum_fraction": 0.7272727489471436,
"avg_line_length": 34.6875,
"blob_id": "2ac58f8688e33438e532561d0c25982921ebbff9",
"content_id": "ad883ee6c951a0959c6e75107f99ba932cc7e610",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 16,
"path": "/ansible/docker/build/destination/Dockerfile",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "FROM debian:8\nMAINTAINER Epiconcept\n\nRUN echo \"export TERM=xterm\" >> /root/.bashrc\n\nRUN apt-get update && apt-get upgrade -y && apt-get install python lsyncd vim openssh-client openssh-server net-tools tree -y\nRUN mkdir -p /space/dest\n\nRUN mkdir /var/run/sshd\n# SSH login fix. Otherwise user is kicked off after login\n#RUN sed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd\n#RUN echo \"net.ipv4.ip_nonlocal_bind = 1\" >> /etc/sysctl.conf\n#RUN echo \"export VISIBLE=now\" >> /etc/profile\n\nEXPOSE 22\nCMD [\"/usr/sbin/sshd\", \"-D\"]\n\n"
},
{
"alpha_fraction": 0.7088363170623779,
"alphanum_fraction": 0.74456787109375,
"avg_line_length": 61.75757598876953,
"blob_id": "2adce37aa557d9b6884553b26972cfc54d243dc5",
"content_id": "b94128ffdcfbee712a79014daab9d47804e9facb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2071,
"license_type": "no_license",
"max_line_length": 293,
"num_lines": 33,
"path": "/start-limit/README.md",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "# StartLimit errors with indirdwake\n\n## Discovery\nEarly 2023, thanks to the deployment of `grafana`, repeated messages like \n`<date> <system>systemd[1]: indirdwake@SSP_POiTIERS_ADT.service: Failed with result 'start-limit-hit'.` \nwere noticed in `/var/log/daemon.log` on a Debian 9 system running many instances of `indird`.\n\n## Fix\nIt was quickly determined that the messages needed the use of a `SmartLimitInterval*` systemd setting. \nFirst, a `StartLimitIntervalSec=0` setting was put in `[email protected]`. It was recognized (no error) but it had no visible effect. \nSecond, this setting was moved to [email protected] where `systemd-analyze verify [email protected]` immediately detected it as invalid. \nThird, further research led to the discovery of a `SmartLimitInterval=` setting on the different systemd releases of Debian versions 9,10,11. Tests on version 232 of systemd on Debian 9 showed that this setting was not only recognized in `[email protected]`, but also **worked** as expected.\n\n## Check for `SmartLimitInterval` in systemd's source code\nA quick search was then done on the sources of the different versions of systemd:\n\n| systemd version | Debian version |\n|---|---|\n| systemd-232-25+deb9u15 | 9.13 |\n| systemd-241-7~deb10u8 | 10.13 |\n| systemd-247.3-7+deb11u1 | 11.6 |\n\nThe fetch, untar and grep process was consigned in the `getsrc` script.\nAs the `work/grep.out` file points out to, a post-232 comment has been added to version 229's NEWS in `work/systemd-241/NEWS` and `work/systemd-stable-247.3/NEWS` that seems to announce that the `SmartLimitInterval=` setting will still work on Debian 10 and 11:\n```\n * The settings StartLimitBurst=, StartLimitInterval=, StartLimitAction=\n and RebootArgument= have been moved from the [Service] section of\n unit files to [Unit], and they are now supported on all unit types,\n not just service units. Of course, systemd will continue to\n understand these settings also at the old location, in order to\n maintain compatibility.\n```\n2023-02-23\n"
},
{
"alpha_fraction": 0.6368715167045593,
"alphanum_fraction": 0.6424580812454224,
"avg_line_length": 21.5,
"blob_id": "8a3b093b0295a2c99659f5bc3ac1c974f00ed77f",
"content_id": "82e0a53e899972a3f94a460c3995a1d09477c3be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 179,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 8,
"path": "/ansible/files/normed_indird.sh",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nABS=$(cd $(dirname \"${BASH_SOURCE[0]}\") && pwd)\n\nIFS=$'\\n'\nfor i in $($ABS/../indirdctl check); do \n\techo \"SERVEUR;serveur;services;SERVICE_DOWN;service $i down\"\ndone"
},
{
"alpha_fraction": 0.7295918464660645,
"alphanum_fraction": 0.7295918464660645,
"avg_line_length": 23.625,
"blob_id": "ffa2de7af56f6f1b68a9971e0134ce0754bf2799",
"content_id": "5f6b047d20d6d07c121d350d28368b55f80d9a67",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 196,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 8,
"path": "/docker/run.sh",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nsource ~/bin/public/bashlibs/docker.lib.sh\n\nid=$(docker run -d --name filesflow_files tests_ssh:latest)\ncntip $id\nid=$(docker run -d --name filesflow_front tests_ssh:latest)\ncntip $id"
},
{
"alpha_fraction": 0.6202531456947327,
"alphanum_fraction": 0.6213080286979675,
"avg_line_length": 46.400001525878906,
"blob_id": "c5fad74cb7e42c22a0156842b55a2d047e897892",
"content_id": "a27feb4a1f59c0d7b1923231e34e8c3c5a8a045f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1901,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 40,
"path": "/ansible/files/indirdctl",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n#todo extraire les dossiers fail et montrer les fichiers qui s'y trouvent (et doivent être re-traités)\n#todo surveillance des logs, à définir\n#todo montrer les dossiers pour chaque instance\n\nlist=$(cat /etc/indird.conf|jq '.|reduce path(.[]?) as $path (.; setpath($path; {}))' |grep -vEe '^({|})' |sed -e 's/[ ]*\"//' -e 's/\".*//')\n\ncase $1 in\nstatus) for i in $list; do systemctl status indird@$i; done ;;\nstart) for i in $list; do echo $i; sudo systemctl start indird@$i; done ;;\nstop) for i in $list; do echo $i; sudo systemctl stop indird@$i; done ;;\nrestart) for i in $list; do echo $i; sudo systemctl restart indird@$i; done ;;\nreload) for i in $list; do echo $i; sudo systemctl reload indird@$i; done ;;\nps) systemctl |grep 'indird@' ;;\ncheck) \n\tif [ \"$list\" != \"null\" ]; then\n\t\tfor servicetype in indird indirdwake; do\n\t\t\tservices=$(systemctl list-units --all | grep -v masked | grep $servicetype@)\n\t\t\tfor i in $list; do \n\t\t\t\tresult=$(echo \"$services\" | grep \"$servicetype@$i.service\")\n\t\t\t\tif [ -z \"$result\" ]; then echo \"$servicetype@$i.service (absent)\"; fi\n\t\t\t\tif [[ \"$result\" =~ \"failed\" ]]; then echo \"$servicetype@$i.service (failed) $result\"\n\t\t\t\telif [[ \"$result\" =~ \"dead\" && $servicetype == \"indird\" ]]; then echo \"$servicetype@$i.service (dead)\"; fi\n\t\t\tdone\n\t\tdone\n\tfi\n\t;;\ndebug)\n\tfor instance in $list; do \n\t\tcmd=$(cat /etc/indird.conf| jq .$instance.actions.copy.cmd -r| sed 's/\"\\$i_FILE\"/$FILE/g')\n\t\tlistvars=$(cat /etc/indird.conf| jq .$instance.env |jq '.|reduce path(.[]?) as $path (.; setpath($path; {}))' |grep -vEe '^({|})' |sed -e 's/[ ]*\"//' -e 's/\".*//' |xargs)\n\t\t\n\t\techo -e \"$instance\\n - cmd: $cmd\\n - vars: $listvars\"\n\t\tfor var in $listvars; do value=$(cat /etc/indird.conf | jq .$instance.env.$var -r); cmd=$(echo $cmd|sed -e \"s#\\$i_${var}#$value#g\"); done\n\t\techo \" - cmd calculée: $cmd\"\n\tdone\n\t;;\n*) \n\techo \"$0 status|ps|debug|start|stop|check\"\nesac\n"
},
{
"alpha_fraction": 0.7122302055358887,
"alphanum_fraction": 0.7374100685119629,
"avg_line_length": 30,
"blob_id": "0b57b283ebfb003f31908f3992832376499c7c99",
"content_id": "c89b58b9a44089f90ae226b14a28143fe267ba42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 278,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 9,
"path": "/ansible/docker/build/source/Dockerfile",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "FROM debian:8\nMAINTAINER Epiconcept\n\nRUN echo \"export TERM=xterm\" >> /root/.bashrc\n\nRUN apt-get update && apt-get upgrade -y && apt-get install python lsyncd vim openssh-client tree -y\nRUN mkdir -p /space/source/un /space/source/deux /space/source/trois\n\nCMD [\"sleep\", \"360000\"]"
},
{
"alpha_fraction": 0.8213165998458862,
"alphanum_fraction": 0.8213165998458862,
"avg_line_length": 52.33333206176758,
"blob_id": "8b8336fca00f8b7639f490ba4af3f4bf08de59c3",
"content_id": "1efe4862817e84907191d58f238d61adceea4964",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 319,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 6,
"path": "/docker/test.sh",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "docker cp indird/indird filesflow_files:/usr/local/bin/\ndocker cp indird/indird.conf filesflow_files:/etc/\n\ndocker cp indird/[email protected] filesflow_files:/etc/systemd/system\ndocker cp indird/[email protected] filesflow_files:/etc/systemd/system\ndocker cp indird/[email protected] filesflow_files:/etc/systemd/system"
},
{
"alpha_fraction": 0.5582386255264282,
"alphanum_fraction": 0.5724431872367859,
"avg_line_length": 31,
"blob_id": "02fcd2bc38c977c9a19ac9e6ad62217df9280b3f",
"content_id": "42e59c0497453a271c05538bbed0f71b81a322c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 708,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 22,
"path": "/examples/old_incrond_conf.md",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "# Exemples de fichiers générés\n\n## sur le serveur de fichiers\n\n* cedric@procom1:~$ cat /etc/incron.d/sspnice \n```\n/space/home/sspnice/hl7 IN_CLOSE_WRITE,IN_MOVED_TO /usr/local/bin/sspnice $@/$#\n```\n* cedric@procom1:~$ cat /usr/local/bin/sspnice\n```\n#!/bin/bash\n\nrsync -e \"ssh -i /space/home/sspnice/.ssh/rsync -l sspnice\" \"$1\" \\\n --whole-file --partial-dir ../tmp profnt2.front2:hl7\n```\n\n## sur le serveur frontal\n\n* cedric@profnt2:~$ cat /etc/incron.d/sspnice \n```\n/space/applistmp/sspnice/hl7 IN_MOVED_TO sudo -u www-data /usr/bin/php /space/www/apps/ssp/ressources/hl7/import.php $@/$#\n```\n"
},
{
"alpha_fraction": 0.5764023065567017,
"alphanum_fraction": 0.5947775840759277,
"avg_line_length": 27.72222137451172,
"blob_id": "321733ba41834893c92a31d2a223bfe98f1e1d76",
"content_id": "b3db14553cc20fa9a1ba9082de3a63c437bdf37c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1034,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 36,
"path": "/utils/ckiyaml",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n#\n#\tckiconf - Check a YAML file for indird config errors\n#\nPrg=`basename $0`\n\n# check args\ntest \"$1\" && yaml=\"$1\" || { echo \"Usage: $Prg <yaml-file>\" >&2; exit 1; }\n\n# check if $yaml exists\ntest -f \"$yaml\" || { echo \"$Prg: cannot find YAML file \\\"$yaml\\\"\" >&2; exit 2; }\n\n# check if $yaml is valid YAML\nyaml2json \"$yaml\" >/dev/null || exit 3\n\n# check if $yaml is has hosts\nyaml2json \"$yaml\" | jq -e -r '.hosts|keys[]' >/dev/null 2>&1 || { echo \"$Prg: no '.hosts' key in $yaml\" >&2; exit 4; }\n\nwork=`mktemp -d`\ntest -d \"$work\" || { echo \"Cannot create '$work' working directory ??\" >&2; exit 5; }\nreal=`realpath $1`\ncd $work\nfor host in `yaml2json $real | jq -r '.hosts|keys[]'`\ndo\n conf=$host.conf\n #\tExtract $host config\n yaml2json \"$real\" | jq \".hosts.$host.confs\" >$conf\n #\tCheck each tag in $conf\n echo \"------- Checking $yaml host $host -------\"\n for tag in `jq -r '.|keys[]' <$conf`\n do\n\tINDIRD_CONFIG=$conf indird $tag nlcheck\t# use non-local check mode\n done\n rm -f $conf\ndone\nrmdir $work\n"
},
{
"alpha_fraction": 0.6646706461906433,
"alphanum_fraction": 0.6739022135734558,
"avg_line_length": 31.852458953857422,
"blob_id": "7f52ab70125b3a5be33dafbebac0ecac563db144",
"content_id": "ab105f0a50b83939f578d9e88d5f52574d698fd0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4008,
"license_type": "no_license",
"max_line_length": 180,
"num_lines": 122,
"path": "/utils/yaml2json",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n# Origin: https://github.com/drbild/json2yaml (commit df499b6)\n# Requires packages python-yaml and python-docopt\n#\n# Copyright 2015 David R. Bild\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\"\"\"\nUsage:\n yaml2json (--version|--help)\n yaml2json [-i <indent>] [<yaml_file>] [<json_file>]\n\nArguments:\n -i, --indent=INDENT Number of spaces to indent [default: 4]\n <yaml_file> The input file containing the YAML to convert. If not\n specified, reads from stdin.\n <json_file> The output file to which to write the converted JSON. If\n not specified, writes to stdout.\n\"\"\"\n\nimport sys, os\nimport json, yaml\nimport docopt\n\nfrom collections import OrderedDict\nfrom yaml import MappingNode\n\n__version__ = \"1.1.2-epi\"\n\nsys.tracebacklimit = 0\n\n# Configure PyYaml to create ordered dicts\n# using code taken from yaml/contructor.py\n\ndef flatten_ordered_mapping(loader, node):\n merge = []\n index = 0\n while index < len(node.value):\n\tkey_node, value_node = node.value[index]\n\tif key_node.tag == u'tag:yaml.org,2002:merge':\n\t del node.value[index]\n\t if isinstance(value_node, MappingNode):\n\t\tflatten_ordered_mapping(loader, value_node)\n\t\tmerge.extend(value_node.value)\n\t elif isinstance(value_node, SequenceNode):\n\t\tsubmerge = []\n\t\tfor subnode in value_node.value:\n\t\t if not isinstance(subnode, MappingNode):\n\t\t\traise ConstructorError(\"while constructing a mapping\", node.start_mark, \"expected a mapping for merging, but found %s\" % subnode.id, subnode.start_mark)\n\t\t flatten_ordered_mapping(loader, subnode)\n\t\t submerge.append(subnode.value)\n\t\tsubmerge.reverse()\n\t\tfor value in submerge:\n\t\t merge.extend(value)\n\t else:\n\t\traise ConstructorError(\"while constructing a mapping\", node.start_mark, \"expected a mapping or list of mappings for merging, but found %s\" % value_node.id, value_node.start_mark)\n\n\telif key_node.tag == u'tag:yaml.org,2002:value':\n\t key_node.tag = u'tag:yaml.org,2002:str'\n\t index += 1\n\telse:\n\t index += 1\n\n\tif merge:\n\t for val in merge:\n\t\tnode.value.insert(index, val)\n\t\tindex += 1\n\t merge = []\n\ndef construct_ordered_mapping(loader, node, deep=False):\n if isinstance(node, MappingNode):\n flatten_ordered_mapping(loader, node)\n return OrderedDict(loader.construct_pairs(node, deep))\n\ndef construct_yaml_ordered_map(loader, node, deep=False):\n data = OrderedDict()\n yield data\n value = construct_ordered_mapping(loader, node, deep)\n data.update(value)\n\nyaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_yaml_ordered_map)\n\n# Multipurpose open\ndef safeopen(name, mode='r', buffering=1):\n if isinstance(name, file):\n return name\n elif name == '-':\n return sys.stdin\n else:\n return open(name, mode, buffering)\n\n# Convert from YAML to JSON\ndef convert(yaml_file, json_file, indent):\n loaded_yaml = yaml.load(yaml_file)\n json.dump(loaded_yaml, json_file, separators=(',',': '), indent=indent)\n json_file.write('\\n')\n\nif __name__ == '__main__':\n args = docopt.docopt(\n __doc__,\n version=\"version \"+__version__\n )\n\n yaml_arg = args.get('<yaml_file>') or sys.stdin\n json_arg = args.get('<json_file>') or sys.stdout\n indent_arg = int(args.get('--indent'))\n\n with safeopen(yaml_arg, 'r') as yaml_file:\n with safeopen(json_arg, 'w') as json_file:\n convert(yaml_file, json_file, indent=indent_arg)\n"
},
{
"alpha_fraction": 0.7816174626350403,
"alphanum_fraction": 0.7820974588394165,
"avg_line_length": 68.43333435058594,
"blob_id": "97338a8f669d782df63378f7174f1555ccab8c11",
"content_id": "e0c290f5eb2ea56e39cc9a2a64a35e106a3361d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4259,
"license_type": "no_license",
"max_line_length": 385,
"num_lines": 60,
"path": "/Planning.md",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "Vocabulaire\n===========\n\n* serveur d'entrée des fichiers, ou serveur de fichiers : serveur où les fichiers sont déposés par un intervenant externe à Epiconcept (sftp, transfert node, etc...)\n* serveur apache, frontal, serveur de traitement : frontal Apache/PHP qui sert l'application web et assure le traitement des fichiers (via un script PHP fournit par l'application)\n* flux de fichiers : un ensemble de fichiers de nature identique, déposés dans un dossier précis sur un serveur de fichiers, et traités sur un serveur apache (donc transférés entre les deux). En résumé, pour le définir, nous avons donc\n\n * un serveur de fichiers, sur lequel nous avons un chemin de dépot\n * un serveur apache, sur lequel nous avons un chemin de stockage et un script PHP de traitement à exécuter\n\nWorkflow\n========\n\n* des fichiers sont déposés sur un serveur d'entrée dans un dossier propre au flux\n\n * via SFTP\n * protocole spécifique \n\n* ils doivent être copiés sur un serveur de traitement, un frontal Apache/PHP, dans un dossier propre au flux\n\n * un log doit permettre de suivre chaque fichier transféré\n * les fichiers correctement transférés doivent être archivés dans un dossier spécifique (dans une autre partie de l'arborescence par rapport au dossier d'entrée)\n\n* sur ce frontal, un script sera appelé pour traiter le fichier\n\n * un log doit tracer chaque traitement, avec son résultat et d'éventuelles traces sur les sorties error/std\n * les fichiers sont archivés si un drapeau spécifique est activé (sinon c'est le script de traitement qui s'en occupe)\n\n* optionnellement (ce n'est pas le cas de tous les flux), le script peut fournir un fichier d'acquitement qui doit être renvoyé en retour\n\n * il le dépose dans un dossier 'out', ou le fournit à un script pour traitement immédiat\n * ce fichier doit in fine être déposé dans un dossier 'out' sur le serveur de fichiers\n\nContraintes\n===========\n\n* traitement en temps réel à l'échelle de quelques secondes\n* tous les chemins peuvent être configurés indépendamment (via Ansible et remplacement dans un template de script ou de fichier de conf au besoin)\n\n * typiquement, le dépot se fait dans /space/home/$user/inbox, mais sur un flux c'est totalement différent\n * le dossier sur le frontal est généralement dans /space/applistmp/$application/hl7\n * le script est variable\n * les logs seront généralement dans /var/log/epiconcept/flux/$nomflux.log (et mis en rotation via nos scripts existants)\n\n* liberté sur la technologie utilisée, avec juste une discussion sur la facilité de déploiement, la non multiplication des services/daemons\n* journaux pour tous les traitements réalisés, avec l'idée de sortir (travail epiconcept) un CR à donner aux chefs de projets sur l'activité du flux\n* archivage des fichiers une fois traités\n* possibilité de relancer le traitement sur des fichiers qui n'auraient pas été traités dans le flux (genre serveur éteint ou injoignable), via cron ou manuellement (pour inotify, un touch sur les fichiers non traités suffirait)\n* possibilité de lister les fichiers en attente de traitement, sur le serveur de fichiers ou sur le serveur de traitement (s'ils ne sont plus des fichiers sur disque, auquel cas ls suffit)\n* fonctionnement sur Debian Jessie et Stretch\n* un seul utilisateur unix (correspondant à un projet) peut avoir plusieurs flux entrants et resortants, il faut donc identifier le flux dans le transfert.\n* intégrer une vérification sur la nature du fichier en entrée : juste prévoir d'appeler un script en lui passant le fichier fraichement arrivé, et si le script répond autre chose que 0, mettre le fichier en quarantaine dans un dossier spécifique qu'il suffira de surveiller pour signaler les problèmes. On verra ensuite à l'usage si un simple file suffit ou s'il faut aller plus loin.\n\nLivrable\n========\n\n* ensemble de script et configuration, avec procédure manuelle de déploiement (la partie Ansible sera faite par Epiconcept)\n* documentation sur l'usage normal et la récupération de fonctionnement en manuel\n* procédure de test sur un grand nombre de fichiers (éventuellement à définir ensemble)\n* documentation technique (choix, logiciels, etc...) \n"
},
{
"alpha_fraction": 0.5870967507362366,
"alphanum_fraction": 0.6193548440933228,
"avg_line_length": 18.375,
"blob_id": "9b3c15a294dedef730f43bf5a67709094dc78ed6",
"content_id": "6c511aea6c20fc7471e71df3b4ad3aecc8949091",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 310,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 16,
"path": "/docker/docker-compose.yml",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "version: '2'\n\nservices:\n\n# only needed for development\n serverfiles:\n build: ../../build/serversssh\n image: mysql-dev:v0\n container_name: mysql\n command: --sql-mode=\"\"\n ports:\n - 3307:3306\n environment:\n MYSQL_ROOT_PASSWORD: root\n volumes:\n - mysql:/var/lib/mysql:rw\n"
},
{
"alpha_fraction": 0.5901495218276978,
"alphanum_fraction": 0.6121371984481812,
"avg_line_length": 33.45454406738281,
"blob_id": "6b9bb8ef1de05093d4e50ea215ab9db9bd87464d",
"content_id": "42ae001e7018d8252829f50b14676e0e0b5834a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1137,
"license_type": "no_license",
"max_line_length": 223,
"num_lines": 33,
"path": "/utils/mkiconf",
"repo_name": "Epiconcept-Paris/infra-files-flow",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n#\n#\tmkiconf - Output host's indird.conf from a global YAML file\n#\nIndentJSON()\n{\n python -c \"import json, sys, collections; print json.dumps(json.load(sys.stdin, object_pairs_hook=collections.OrderedDict), separators=(',',': '), indent=$1)\" | unexpand --first-only\n}\n\nPrg=`basename $0`\n# check args\ntest \"$2\" || { echo \"Usage: $Prg <yaml-file> <host>\" >&2; exit 1; }\nyaml=$1\nhost=$2\n\n# check if $yaml exists\ntest -f \"$yaml\" || { echo \"$Prg: cannot find YAML file \\\"$yaml\\\"\" >&2; exit 2; }\n\n# check if $yaml is valid YAML\nyaml2json \"$yaml\" >/dev/null || exit 3\n\n# check if $yaml has hosts\nyaml2json \"$yaml\" | jq -e -r '.hosts|keys[]' >/dev/null 2>&1 || { echo \"$Prg: no '.hosts' key in $yaml\" >&2; exit 4; }\n\n# check if $host is host in $yaml\nyaml2json \"$yaml\" | jq -r '.hosts|keys[]' | grep \"^$host\\$\" >/dev/null || { echo \"$Prg: unknown host $host in $yaml\" >&2; echo \"Available hosts:\" >&2; yaml2json $yaml | jq -r '.hosts|keys[]' | sed 's/^/ /' >&2; exit 5; }\n\n# all ok, output our config\nyaml2json \"$yaml\" | jq \".hosts.$host.confs\" | IndentJSON 4 | sed \"1i\\\\\n#\\\\\n#\tindird.conf for $host\\\\\n#\tgenerated from $yaml\\\\\n#\"\n"
}
] | 19 |
GKozakjian/P2P | https://github.com/GKozakjian/P2P | 98a4350b23d77d8903173e23c25b84d8c388a1d6 | e943af418d29c86a05851b1209aaf00ca82c8c00 | 4e852fed853b71f19dca574be795b5411d98a107 | refs/heads/master | 2022-01-17T04:59:54.137863 | 2019-07-21T23:03:31 | 2019-07-21T23:03:31 | 198,113,020 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7853602766990662,
"alphanum_fraction": 0.7914601564407349,
"avg_line_length": 61.4523811340332,
"blob_id": "090a2cb783d26c07b4fbf17229d98e8a12f175d3",
"content_id": "c7429a5227e03a5bdd264b588817891553fcacf5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2623,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 42,
"path": "/README.md",
"repo_name": "GKozakjian/P2P",
"src_encoding": "UTF-8",
"text": "# P2P\n\n## Introduction\nThe `Client-Server` centralized architecture model worked for the past 50 years and provided the backbone of all the amazing services that\nhumans consumed. However, this architecture model is not holding still today, since the number of users being humans or devices has \ngrown exponentially. This resulted in the melting of our best invented architecture models, which raised the danger flag for the \ntechnologists in order to come up with a new model that will, for some period of time, stand still against the needs of this new \ntechnological era.\n\n\nHence, The `Peer-To-Peer` architecture model emerged, bringing with it new architectural, design and implementational challenges with \nthe promise of addressing the main limitations and weaknesses of the centralized architecture model. The main challenges in any P2P network\nare the number of hopes that any peer needs to take to reach some other destination peer, and the routing table that a peer joining the \nP2P network has to maintain at each time in orde to be able to reach other peers. This goal is to create a P2P overlay network\nwhere a middle point solution for the two challenges is found: `(1) any peer can reach other in limited number of hopes`, `(\n2) peers don't need to store the full P2P network in the routing table, which may be a big problem, because at any time, there can be \nmillions of peers in the network` .\n\n\nThis new model builds its pillerson the notion that today end devices including personal computers and IoT devices are no longer thin, \nlow end clients, but `poweful computational devices` that can provide as well as consume services. So the basic idea of the P2P architecture is for the nodes to act \nas both clients and servers, and they will be known as peers, since they are equal in their functionalities in the P2P network. \n\n\nIn this P2P implementation, a `basic P2P overlay network` will be designed and implemented based on the well-known chord DHT protocol. Also, \na new and basic P2P overlay network will be designed and implemented.\n\n\n## Implementation& Code\nThis implementation tries to simulate an overlay P2P networkc based on the chord-protocol whcih used DHTs to build the overlay network\nand add peers to the DHT. The goal is to have a O(n) peer-join chord-like network, where peers join in linear time based on total \nnumber of peers in the P2P network so far. \n\nThe Code is written in Python, and includes a good documentation to build on, or translate to other programming languages.\n\n\n## Read More about it\nPlease read more in the \"Report\" directory of each Part.\n\n\n## Developers \nGeorge Kozakjian\n"
},
{
"alpha_fraction": 0.42858490347862244,
"alphanum_fraction": 0.43348732590675354,
"avg_line_length": 54.53403091430664,
"blob_id": "775a6abf6896a4fccf12ef4493e73494f8503969",
"content_id": "e32811662e84692c208ca62870b3e1914eddc622",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10607,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 191,
"path": "/Part1/Threads/Peer_Server_Thread.py",
"repo_name": "GKozakjian/P2P",
"src_encoding": "UTF-8",
"text": "import threading\nimport time\nimport socket\n\nimport random\nimport hashlib\nfrom Part1.Peer.Peer import *\nimport pickle\nfrom Part1.PDU.PDU import *\n\nclass Peer_Server_Thread(threading.Thread):\n local_peer = None\n hash_function = None\n\n def __init__(self, peer):\n threading.Thread.__init__(self)\n self.local_peer = peer\n self.hash_function = hashlib.sha1()\n\n def run(self):\n self.local_peer.local_peer_tcp_socket.listen(1)\n print(\"-Local Peer: Started Listening On Bound Socket\")\n self.start_receiving()\n\n def start_receiving(self):\n while True:\n try:\n if self.local_peer.stop_local_peer:\n print(\"-Local Peer: Server Thread Stopped\")\n break\n\n # accept new connection\n established_tcp_connection, established_tcp_connection_address = self.local_peer.local_peer_tcp_socket.accept()\n print()\n print(\"-Local Peer: Accepted New TCP Connection With Remote Peer: \" + str(\n established_tcp_connection_address))\n\n received_data = established_tcp_connection.recv(4096)\n received_pdu = pickle.loads(received_data)\n\n # if received message is a message from a peer in chrod network\n if received_pdu['type'] == \"message\":\n received_peer_CID = received_pdu['id']\n for x in self.local_peer.chord_net_peers:\n if x['ID'] == received_peer_CID:\n print(\"-Local Peer: Received Message: \" +received_pdu['message'] +\", From Pere: \" + established_tcp_connection[0] + \":\" +established_tcp_connection[1])\n break\n\n # new node joined by other peers\n elif received_pdu['type'] == \"newnodejoin\":\n # add new node to the chord array\n new_node_info = received_pdu['message']\n # add peer to chord network\n new_chord_peer = \\\n {\n \"id\": new_node_info['id'],\n \"ip\": new_node_info['ipv4'],\n \"port\": new_node_info['port']\n }\n self.local_peer.chord_net_peers.append(new_chord_peer)\n print(\"-Local Peer: New Node Joined Chord Network with ID: \" + new_node_info['id'] + \", IP:\" +\n new_node_info['ipv4'] + \" And Port: \" + new_node_info['port'])\n\n # if received message is join request\n elif received_pdu['type'] == \"join\":\n # if static ID exist in join request\n if received_pdu['id'] is not None:\n received_join_CID = received_pdu['id']\n # check for collision\n for x in self.local_peer.chord_net_peers:\n if x['id'] == received_join_CID:\n # generate new ID based on remote peer IPv4 and Port\n received_join_peer_socket = received_pdu['ipv4'] + \":\" + received_pdu['port']\n self.hash_function.update(received_join_peer_socket.encode())\n received_join_CID = self.hash_function.hexdigest()\n # add peer to chord network\n new_chord_peer = \\\n {\n \"id\": received_join_CID,\n \"ip\": received_pdu['ipv4'],\n \"port\": received_pdu['port']\n }\n self.local_peer.chord_net_peers.append(new_chord_peer)\n print(\"-Local Peer: New Node Joined Chord Network with ID: \" + received_join_CID + \", IP:\" +\n received_pdu['ipv4'] + \" And Port: \" + received_pdu['port'])\n if received_join_CID != received_pdu['id']:\n msg = received_join_CID\n join_reply_pdu = PDU(1, \"joinack\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port, msg, \"\")\n serialized_join_reply = pickle.dumps(join_reply_pdu)\n established_tcp_connection.send(serialized_join_reply)\n else:\n join_reply_pdu = PDU(1, \"joinackid\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port, \"\", \"\")\n serialized_join_reply = pickle.dumps(join_reply_pdu)\n established_tcp_connection.send(serialized_join_reply)\n\n # notify chord network that a new node joined\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n socket_once.bind((self.local_peer.local_host_ip, int(random_port_once)))\n\n message = \\\n {\n 'id': received_join_CID,\n 'ip': received_pdu['ipv4'],\n 'port': received_pdu['port']\n }\n for x in self.local_peer.chord_net_peers:\n if x['id'] != received_join_CID or x['id'] != self.local_peer.local_peer_CID:\n\n socket_once.connect((x['ip'], int(x['port'])))\n\n # prepare message\n pdu = PDU(1, \"newnodejoin\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port, message, \"\")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n\n # close socket once when finished sending\n socket_once.shutdown(2)\n\n # if there is no static ID in join request\n else:\n received_join_peer_socket = received_pdu['ipv4'] + \":\" + received_pdu['port']\n self.hash_function.update(received_join_peer_socket.encode())\n received_join_CID = self.hash_function.hexdigest()\n\n for x in self.local_peer.chord_net_peers:\n # check if node already exist in chord network\n if x['id'] == received_join_CID:\n break\n # join new node to chord net if it doesnt exist in network\n else:\n new_chord_peer = \\\n {\n \"id\": received_join_CID,\n \"ip\": received_pdu['ipv4'],\n \"port\": received_pdu['port']\n }\n self.local_peer.chord_net_peers.append(new_chord_peer)\n print(\n \"-Local Peer: New Node Joined Chord Network with ID: \" + received_join_CID + \", IP:\" +\n received_pdu['ipv4'] + \" And Port: \" + received_pdu['port'])\n\n msg = \\\n {\n \"id\": received_join_CID\n }\n join_reply_pdu = PDU(1, \"joinack\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port,\n msg, \"\")\n serialized_join_reply = pickle.dumps(join_reply_pdu)\n established_tcp_connection.send(serialized_join_reply)\n\n # notify chord network that a new node joined\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n socket_once.bind((self.local_peer.local_host_ip, int(random_port_once)))\n\n message = \\\n {\n 'id': received_join_CID,\n 'ip': received_pdu['ipv4'],\n 'port': received_pdu['port']\n }\n for x in self.local_peer.chord_net_peers:\n if x['id'] != received_join_CID:\n socket_once.connect((x['ip'], int(x['port'])))\n\n # prepare message\n pdu = PDU(1, \"newnodejoin\", self.local_peer.TTL,\n self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port,\n message, \"\")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n\n # close socket once when finished sending\n socket_once.shutdown(2)\n\n time.sleep(10)\n except Exception as e:\n print(\"im fucking here\")\n print(e)\n pass\n # print(\"-Local Peer: No New Incoming Connections\")\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.5095089673995972,
"avg_line_length": 49.74561309814453,
"blob_id": "e10c2eae84deb461c11c0101ab67fb3baca3eae5",
"content_id": "697e4248433090fa7502bb641ef18e0abec6ba0c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5784,
"license_type": "no_license",
"max_line_length": 191,
"num_lines": 114,
"path": "/Part2/Threads/Peer_Client_Thread2.py",
"repo_name": "GKozakjian/P2P",
"src_encoding": "UTF-8",
"text": "import threading\nimport time\nimport socket\nimport pickle\nimport random\nfrom Part2.Peer.Peer2 import *\nfrom Part2.Threads.PDU2 import *\nimport pickle\nimport hashlib\nimport signal\n\n\nclass Peer_Client_Thread2(threading.Thread):\n local_peer = None\n hash_function = None\n\n def __init__(self, peer):\n threading.Thread.__init__(self)\n self.local_peer = peer\n self.hash_function = hashlib.sha1()\n # signal.signal(signal.SIGINT, self.signal_handler)\n #\n # def signal_handler(signal, frame):\n # print(\"ahyyy\")\n # pass\n\n def run(self):\n while True:\n try:\n # get peer message from CLI interface\n remote_peer = input(\"-Local peer: Enter Peer you want to send a message to, in IP:Port Format, or enter Q to exit\")\n if remote_peer == \"Q\" or remote_peer == \"q\":\n self.local_peer.stop_local_peer = True\n print(\"-Local Peer: Client Thread Stopped\")\n break\n message = input(\"-Local Peer: Enter Message\")\n\n # check if peer in chord network\n self.hash_function.update(remote_peer.encode())\n remote_peer_CID = self.hash_function.hexdigest()\n remote_found = False\n for x in self.local_peer.chord_net_peers:\n if x['id'] == remote_peer_CID:\n remote_found = True\n remote_peer_ip, remote_peer_port = remote_peer.split(':')\n\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once =socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n socket_once.bind((self.local_peer.local_host_ip, int(random_port_once)))\n socket_once.connect((remote_peer_ip, int(remote_peer_port)))\n\n # prepare message\n pdu = PDU2(1, \"message\", self.local_peer.TTL, self.local_peer.local_peer_CID, self.local_peer.local_host_ip, self.local_peer.local_host_port, message, \"Dumb Message \")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n print(\"-Local Peer: Message Sent To Peer with ID: \" + x['id'] + \", IP: \" + remote_peer_ip + \", Port: \" + remote_peer_port)\n # close socket once when finished sending\n socket_once.shutdown(2)\n break\n if not remote_found:\n # try to send it to successor\n # check for successor and predecessor\n if int(remote_peer_CID, 16) < int(self.local_peer.successor, 16):\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n socket_once.bind((self.local_peer.local_host_ip, int(random_port_once)))\n socket_once.connect((remote_peer_ip, int(remote_peer_port)))\n\n # prepare message\n pdu = PDU2(1, \"message\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port, message,\n \"Dumb Message \")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n print(\"-Local Peer: Message Sent To Peer with ID: \" + x[\n 'id'] + \", IP: \" + remote_peer_ip + \", Port: \" + remote_peer_port)\n # close socket once when finished sending\n socket_once.shutdown(2)\n break\n pass\n elif int(remote_peer_CID, 16) > int(self.local_peer.predecessor):\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n socket_once.bind((self.local_peer.local_host_ip, int(random_port_once)))\n socket_once.connect((remote_peer_ip, int(remote_peer_port)))\n\n # prepare message\n pdu = PDU2(1, \"message\", self.local_peer.TTL, self.local_peer.local_peer_CID,\n self.local_peer.local_host_ip, self.local_peer.local_host_port, message,\n \"Dumb Message \")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n print(\"-Local Peer: Message Sent To Peer with ID: \" + x[\n 'id'] + \", IP: \" + remote_peer_ip + \", Port: \" + remote_peer_port)\n # close socket once when finished sending\n socket_once.shutdown(2)\n break\n pass\n else:\n print(\"-Local Peer: Entered Remote Peer Not In Chord Network\")\n time.sleep(1)\n\n except KeyboardInterrupt:\n print(\"CLI Thread Stopped\")\n exit()"
},
{
"alpha_fraction": 0.4742990732192993,
"alphanum_fraction": 0.4883177578449249,
"avg_line_length": 20.25,
"blob_id": "1e25c0be5a3e1ef0af58c8b820cc4b68272ec59b",
"content_id": "fa910869e66be9fae76da4e6d6dec8bb5b20fe67",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 428,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 20,
"path": "/Part1/PDU/PDU.py",
"repo_name": "GKozakjian/P2P",
"src_encoding": "UTF-8",
"text": "\n\nclass PDU():\n version = \"\"\n ttl = 0\n id = \"\"\n Port = 0\n ipv4 = \"\"\n type = \"\"\n message = \"\"\n reserved = \"\"\n\n\n def __init__(self, version, type, ttl, ID, ipv4, port, message, reserved):\n self.version = version\n self.ttl = ttl\n self.id = ID\n self.Port = port\n self.ipv4 = ipv4\n self.type = type\n self.message = message\n self.reserved = reserved\n\n"
},
{
"alpha_fraction": 0.5162935256958008,
"alphanum_fraction": 0.5262438058853149,
"avg_line_length": 39.81218338012695,
"blob_id": "46c9bee93839cdd074b1c355faa807345240c5ab",
"content_id": "05fa48f8f311beee02d7b256130140f4e8a147c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8040,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 197,
"path": "/Part2/Peer/Peer2.py",
"repo_name": "GKozakjian/P2P",
"src_encoding": "UTF-8",
"text": "import sys\nimport socket\nfrom Part2.Threads.Peer_Client_Thread2 import *\nfrom Part2.Threads.Peer_Server_Thread2 import *\nimport random\nfrom pickle import *\nimport hashlib\nfrom Part2.Peer.PDU2 import *\n\nclass Peer2:\n successor = None\n predecessor = None\n local_host_ip = None\n local_host_port = None\n local_peer_CID = None\n local_peer_tcp_socket = None\n local_peer_server_thread = None\n local_peer_client_thread = None\n local_peer_cli_thread = None\n chord_net_peers = []\n latest_remote_peer_ip = None\n latest_remote_peer_port = None\n TTL = None\n hash_function = None\n stop_local_peer = False\n\n\n def __init__(self, opcode, remote_peer_ip_port, SID_Option, CSID, TTL_Option, TTL):\n try:\n self.message_available_to_send = False\n self.local_peer_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.local_host_ip = \"localhost\"\n self.hash_function = hashlib.sha1()\n\n # bind the socket\n self.bind_socket()\n\n # check opcode, and act accordingly\n if opcode == '-p':\n self.latest_remote_peer_ip, self.latest_remote_peer_port = remote_peer_ip_port.split(':')\n if SID_Option == \"-I\":\n self.local_peer_CID = CSID\n if TTL_Option == \"-t\":\n self.TTL = TTL\n else:\n self.TTL = 255\n else:\n self.local_peer_CID = \"\"\n if TTL_Option == \"-t\":\n self.TTL = TTL\n else:\n self.TTL = 255\n\n self.join_chord()\n\n elif opcode == \"-I\":\n self.local_peer_CID = CSID\n if TTL_Option == \"-t\":\n self.TTL = TTL\n else:\n self.TTL = 255\n # create new chord network\n self.create_new_chord()\n else:\n if opcode == \"-t\":\n self.TTL = TTL\n else:\n self.TTL = 255\n # create new chord network\n self.create_new_chord()\n\n # start local peer's sender and receiver threads\n self.assign_threads()\n\n # join the threads\n self.join_threads()\n\n # both trheads stopped\n print(\"-Local Peer: Started Chord Leave Process\")\n # establish connection to remote peer and send message\n random_port_once = random.randint(30000, 60000)\n socket_once = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_once.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n socket_once.bind((self.local_host_ip, int(random_port_once)))\n\n for x in self.chord_net_peers:\n if x['id'] != self.local_peer_CID:\n socket_once.connect((x['ip'], int(x['port'])))\n\n # prepare message\n pdu = PDU2(1, \"leave\", self.TTL, self.local_peer_CID,\n self.local_host_ip, self.local_host_port, \"By Bcs\")\n picled_pdu = pickle.dumps(pdu)\n socket_once.send(picled_pdu)\n print(\"-Local Peer: Leave Request Sent to Peer with ID: \" + x['id'] + \", IP: \" + x['ip'] + \", Port: \" + x['port'])\n # close socket once when finished sending\n socket_once.shutdown(2)\n print(\"-Local Peer: Stopped\")\n sys.exit()\n except KeyboardInterrupt:\n # disconnect from network\n print(\" by by im going home\")\n pass\n\n\n\n def bind_socket(self):\n # Generate a random socket for local host\n self.local_host_port = random.randint(30000, 60000)\n self.local_peer_tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.local_peer_tcp_socket.settimeout(10)\n self.local_peer_tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.local_peer_tcp_socket.bind((self.local_host_ip, self.local_host_port))\n print(\"-Local Peer: Socket Bind Completed On IP: \" + self.local_host_ip + \" & Port: \" + str(self.local_host_port))\n\n def assign_threads(self):\n self.local_peer_client_thread = Peer_Client_Thread2(self)\n self.local_peer_server_thread = Peer_Server_Thread2(self)\n print(\"-Local Peer: Sender & Receiver Threads Started\")\n self.local_peer_server_thread.start()\n self.local_peer_client_thread.start()\n\n\n def join_threads(self):\n self.local_peer_client_thread.join()\n self.local_peer_server_thread.join()\n\n def join_chord(self):\n try:\n # send join message to join a chord network\n join_pdu = PDU2(1, \"join\", self.TTL, self.local_peer_CID, self.local_host_ip, self.local_host_port, \"join the network\", \"\")\n serialized_pdu = pickle.dumps(join_pdu, pickle.HIGHEST_PROTOCOL)\n serialized_join_pdu = pickle.dumps(join_pdu, pickle.HIGHEST_PROTOCOL)\n\n self.local_peer_tcp_socket.connect((self.latest_remote_peer_ip, int(self.latest_remote_peer_port)))\n self.local_peer_tcp_socket.send(serialized_join_pdu)\n except Exception as e:\n print(e)\n\n # receive join confirm\n while True:\n try:\n join_reply_pdu = self.local_peer_tcp_socket.recv(1024)\n serialized_join_reply_pdu = pickle.loads(join_reply_pdu)\n if serialized_join_reply_pdu['type'] == \"joinackid\":\n new_chord_peer = \\\n {\n \"id\": serialized_join_reply_pdu['id'],\n \"ip\": serialized_join_reply_pdu['ipv4'],\n \"port\": serialized_join_reply_pdu['port']\n }\n self.chord_net_peers.append(new_chord_peer)\n print(\"-Local Peer: Joined Chord Network With Static ID\")\n elif serialized_join_reply_pdu['type'] == 'joinack':\n reply_CID_message = serialized_join_reply_pdu['message']\n self.local_peer_CID = reply_CID_message['id']\n new_chord_peer = \\\n {\n \"id\": serialized_join_reply_pdu['id'],\n \"ip\": serialized_join_reply_pdu['ipv4'],\n \"port\": serialized_join_reply_pdu['port']\n }\n self.chord_net_peers.append(new_chord_peer)\n\n print(\"-Local Peer: Joined Chord Network With New Generated ID\")\n break\n except:\n print(\"-Local Peer: Still Waiting for Join Reply\")\n\n\n def create_new_chord(self):\n print(\"-Local Peer: New Chord Network Created\")\n if self.local_peer_CID is None:\n cid_gen_str = self.local_host_ip + \":\" + str(self.local_host_port)\n self.local_peer_CID = self.hash_function.update(cid_gen_str.encode())\n self.local_peer_CID = self.hash_function.hexdigest()\n new_chord_peer = \\\n {\n \"id\": self.local_peer_CID,\n \"ip\": self.local_host_ip,\n \"port\": self.local_host_port\n }\n self.chord_net_peers.append(new_chord_peer)\n print(\"-Local Peer: Joined Chord Network With Chord ID: \" + str(self.local_peer_CID))\n\n\nif __name__ == \"__main__\":\n option = sys.argv[1]\n if option == '-p':\n if sys.argv[3] == \"-I\":\n p = Peer2(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6])\n else:\n p = Peer2(sys.argv[1], sys.argv[2], \"\", \"\", sys.argv[3], sys.argv[4])\n elif option == '-I':\n p = Peer2(sys.argv[1], sys.argv[2], \"\", \"\", sys.argv[3], sys.argv[4])\n elif option == \"-t\":\n p = Peer2(sys.argv[1], \"\", \"\", \"\", \"\", sys.argv[2])\n"
}
] | 5 |
TomasAlvarez78/Proyecto-LabIV | https://github.com/TomasAlvarez78/Proyecto-LabIV | dcce7354de6b95decea03ad1fd4f67712347d879 | a1e31cc3e0c38fdcf58ab36f5fcd0b5b46b1e830 | 60c9fbe24595b708944b1de457879c1fb51c69b8 | refs/heads/master | 2023-08-23T07:33:20.023278 | 2021-08-11T19:44:31 | 2021-08-11T19:44:31 | 394,460,778 | 0 | 3 | null | 2021-08-09T22:52:19 | 2021-08-11T19:44:51 | 2021-09-20T20:41:55 | Python | [
{
"alpha_fraction": 0.539893627166748,
"alphanum_fraction": 0.553856372833252,
"avg_line_length": 36.599998474121094,
"blob_id": "533e31a4ac6d164e003f675594fa54716c47f745",
"content_id": "078f7eb714ce08851deaa0e9259874b431c10943",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1504,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 40,
"path": "/eCommerce/Carrito/migrations/0006_detallecarrito_pago.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.2.6 on 2021-08-11 19:41\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Carrito', '0005_carrito_usuario'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Pago',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('modoPago', models.CharField(max_length=20)),\n ('carrito', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.carrito')),\n ],\n options={\n 'verbose_name': 'Pago',\n 'verbose_name_plural': 'Pagos',\n },\n ),\n migrations.CreateModel(\n name='DetalleCarrito',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('cantidad', models.IntegerField()),\n ('precioVenta', models.FloatField()),\n ('carrito', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.carrito')),\n ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.producto')),\n ],\n options={\n 'verbose_name': 'DetalleCarrito',\n 'verbose_name_plural': 'DetalleCarritos',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.5126705765724182,
"alphanum_fraction": 0.5497075915336609,
"avg_line_length": 21.30434799194336,
"blob_id": "6072e4a2071ed7a7ee77b45ea16967877f1e1ece",
"content_id": "b007fd07d51870176bfcc4ba62679d6bce89d939",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 513,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 23,
"path": "/eCommerce/Carrito/migrations/0004_auto_20210811_1940.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.2.6 on 2021-08-11 19:40\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Carrito', '0003_compra'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='compra',\n old_name='idDetalleCompra',\n new_name='detalleCompra',\n ),\n migrations.RenameField(\n model_name='compra',\n old_name='idProveedor',\n new_name='proveedor',\n ),\n ]\n"
},
{
"alpha_fraction": 0.5203443169593811,
"alphanum_fraction": 0.5367761850357056,
"avg_line_length": 32.6315803527832,
"blob_id": "f5ed87d3d6d0b4169e3e07a2998086bd50cefd85",
"content_id": "a0a64b199ea793d3f5fd00eba07706487ac1521e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1278,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 38,
"path": "/eCommerce/Carrito/migrations/0002_detallecompra_proveedor.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.2.6 on 2021-08-11 19:39\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Carrito', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Proveedor',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Proveedor',\n 'verbose_name_plural': 'Proveedores',\n },\n ),\n migrations.CreateModel(\n name='DetalleCompra',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('cantidad', models.IntegerField()),\n ('precioCompra', models.FloatField()),\n ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.producto')),\n ],\n options={\n 'verbose_name': 'DetalleCompra',\n 'verbose_name_plural': 'DetalleCompras',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.5058900713920593,
"alphanum_fraction": 0.5340313911437988,
"avg_line_length": 35.380950927734375,
"blob_id": "090742f0308bb0a1ffe6709a1cd10631292a95fd",
"content_id": "fbd361f43efeef00350bebaa97ed1e15512579e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1528,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 42,
"path": "/eCommerce/Carrito/migrations/0005_carrito_usuario.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.2.6 on 2021-08-11 19:41\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Carrito', '0004_auto_20210811_1940'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Usuario',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombreUsuario', models.CharField(max_length=50)),\n ('contrasenia', models.CharField(max_length=50)),\n ('email', models.CharField(max_length=50)),\n ('telefono', models.IntegerField()),\n ('nombre', models.CharField(max_length=50)),\n ('apellido', models.CharField(max_length=50)),\n ('direccion', models.CharField(max_length=50)),\n ],\n options={\n 'verbose_name': 'Usuario',\n 'verbose_name_plural': 'Usuarios',\n },\n ),\n migrations.CreateModel(\n name='Carrito',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.usuario')),\n ],\n options={\n 'verbose_name': 'Carrito',\n 'verbose_name_plural': 'Carritos',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.6475965976715088,
"alphanum_fraction": 0.6561486124992371,
"avg_line_length": 31.922330856323242,
"blob_id": "fefd81a1702d19a5bbe09dfe87f7783ad187ad98",
"content_id": "0b23f50759b132e8e4f8da1c7976d1ed89a324dc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3391,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 103,
"path": "/eCommerce/Carrito/models.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\nclass Categoria(models.Model):\n nombre = models.CharField(null=False,max_length=50)\n\n def __str__(self):\n return self.nombre\n\n class Meta:\n verbose_name='Categoria'\n verbose_name_plural='Categorias'\n\nclass Producto(models.Model):\n nombre = models.CharField(null=False,max_length=50)\n descripcion = models.CharField(null=False,max_length=300)\n precio = models.FloatField()\n cantidadStock = models.FloatField()\n categoria = models.ForeignKey(Categoria,on_delete=models.CASCADE,verbose_name='Categoria')\n\n def __str__(self):\n return self.nombre\n\n class Meta:\n verbose_name='Producto'\n verbose_name_plural='Productos'\n\nclass DetalleCompra(models.Model):\n producto = models.ForeignKey(Producto,on_delete=models.CASCADE)\n cantidad = models.IntegerField()\n precioCompra = models.FloatField()\n\n class Meta:\n verbose_name='DetalleCompra'\n verbose_name_plural='DetalleCompras'\n\nclass Proveedor(models.Model):\n nombre = models.CharField(null=False, max_length=50)\n\n def __str__(self):\n return self.nombre\n\n class Meta:\n verbose_name='Proveedor'\n verbose_name_plural='Proveedores'\n\nclass Compra(models.Model):\n proveedor = models.ForeignKey(Producto,on_delete=models.CASCADE)\n detalleCompra = models.ForeignKey(DetalleCompra,on_delete=models.CASCADE)\n\n class Meta:\n verbose_name='Compra'\n verbose_name_plural='Compras'\n\nclass Usuario(models.Model):\n nombreUsuario = models.CharField(null=False, max_length=50)\n contrasenia = models.CharField(null=False, max_length=50)\n email = models.CharField(null=False, max_length=50)\n telefono = models.IntegerField(null=False)\n nombre = models.CharField(null=False, max_length=50)\n apellido = models.CharField(null=False, max_length=50)\n direccion = models.CharField(null=False, max_length=50)\n\n def __str__(self):\n txt = \"{0} {1}\"\n return txt.format(self.apellido,self.nombre)\n\n class Meta:\n verbose_name='Usuario'\n verbose_name_plural='Usuarios'\n\nclass Carrito(models.Model):\n usuario = models.ForeignKey(Usuario,on_delete=models.CASCADE)\n class Meta:\n verbose_name='Carrito'\n verbose_name_plural='Carritos'\n\nclass DetalleCarrito(models.Model):\n carrito = models.ForeignKey(Carrito,on_delete=models.CASCADE)\n producto = models.ForeignKey(Producto,on_delete=models.CASCADE)\n cantidad = models.IntegerField()\n precioVenta = models.FloatField()\n\n class Meta:\n verbose_name='DetalleCarrito'\n verbose_name_plural='DetalleCarritos'\n\nclass Pago(models.Model):\n carrito = models.ForeignKey(Carrito,on_delete=models.CASCADE)\n modoPago = models.CharField(null=False, max_length=20)\n\n class Meta:\n verbose_name='Pago'\n verbose_name_plural='Pagos'\n\nclass Venta(models.Model):\n pago = models.ForeignKey(Carrito,on_delete=models.CASCADE)\n modoEnvio = models.CharField(null=False, max_length=20)\n precioVenta = models.FloatField()\n descripcion = models.CharField(null=False, max_length=50)\n \n class Meta:\n verbose_name='Venta'\n verbose_name_plural='Ventas'\n"
},
{
"alpha_fraction": 0.5334063768386841,
"alphanum_fraction": 0.5585980415344238,
"avg_line_length": 31.60714340209961,
"blob_id": "4a32d7f5afa8b6fbfdd8e94df46869649370f90b",
"content_id": "26950aae30c3ee48553191b2ddaba1c8a4a62b9f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 913,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 28,
"path": "/eCommerce/Carrito/migrations/0007_venta.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.2.6 on 2021-08-11 19:41\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Carrito', '0006_detallecarrito_pago'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Venta',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('modoEnvio', models.CharField(max_length=20)),\n ('precioVenta', models.FloatField()),\n ('descripcion', models.CharField(max_length=50)),\n ('pago', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Carrito.carrito')),\n ],\n options={\n 'verbose_name': 'Venta',\n 'verbose_name_plural': 'Ventas',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.8269720077514648,
"alphanum_fraction": 0.8269720077514648,
"avg_line_length": 27.14285659790039,
"blob_id": "344fe5c0363926c82609f3a3ecf1b27fa34e78ae",
"content_id": "645e50b8bf63628fc427f2b8f467daeea4ebc113",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 393,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/eCommerce/Carrito/admin.py",
"repo_name": "TomasAlvarez78/Proyecto-LabIV",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom Carrito.models import *\n# Register your models here.\n\nadmin.site.register(Categoria)\nadmin.site.register(Producto)\nadmin.site.register(DetalleCompra)\nadmin.site.register(Proveedor)\nadmin.site.register(Compra)\nadmin.site.register(Usuario)\nadmin.site.register(Carrito)\nadmin.site.register(DetalleCarrito)\nadmin.site.register(Pago)\nadmin.site.register(Venta)"
}
] | 7 |
palinnilap/happy-planet | https://github.com/palinnilap/happy-planet | 75021ab04a5311101bb2319774b041b352cb6c88 | b775289c99984fd9679e45ee1c4168c3ad7e98e3 | 4e3565731f8f00ce97fea78d28926074b9d3bebc | refs/heads/master | 2020-09-16T16:11:12.166776 | 2019-11-30T03:29:32 | 2019-11-30T03:29:32 | 222,730,918 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4544375240802765,
"alphanum_fraction": 0.48975956439971924,
"avg_line_length": 28.552631378173828,
"blob_id": "79e5df9898c8e81b8adfdf381d881b2cd97ebc04",
"content_id": "b9e29ecf4b240d3bdcbfaf2cc3b5f9421e4f826e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3389,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 114,
"path": "/gameloop.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "\nfrom player import Player\nfrom level import Level\nfrom typing import Tuple\n\nclass GameLoop:\n\n def __init__(self, \n player : Player, \n main_levels : Tuple[Level], start_lev, \n lev_tutorial=None, lev_won=None, lev_lost=None):\n self._levels = main_levels\n self._player = player\n self._cur_lev_num = 0\n self._cur_lev = lev_tutorial\n self._level_won = lev_won\n self._level_lost = lev_lost\n self._status = 0 \n # 0 --> in progress\n # 1 --> won\n # -1 --> lost\n\n @property\n def level_rgbs(self):\n return self._get_rgbs()\n \n @property\n def status(self):\n return self._status\n\n @property\n def score(self):\n return str(self._player._score)\n \n @property\n def emoji(self):\n return self._get_emoji()\n\n @property\n def happy(self):\n return str(self._player._happy)\n\n\n def get_next_challenge(self):\n return self._cur_lev.get_next_challenge()\n\n def submit_results(self, score : int, happy : int):\n self._player.add_score(score)\n self._player.add_happy(happy)\n self.check_happy()\n\n def check_happy(self):\n if self._player.happy == -2019:\n #you are in the tutorial, do nothing.\n return\n elif self._player.happy <= 0:\n self._change_status(-1)\n self._cur_lev = self._level_lost\n elif self._player.happy < 25:\n self._set_level(0)\n elif self._player.happy < 50:\n self._set_level(1)\n elif self._player.happy < 75:\n self._set_level(2)\n elif self._player.happy < 100:\n self._set_level(3)\n elif self._player.happy > 100:\n self._change_status(1)\n self._cur_lev = self._level_won\n\n def _set_level(self, lev_num : int):\n self._cur_lev_num = lev_num\n self._cur_lev = self._levels[lev_num]\n\n def _change_status(self, to_what : int):\n self._status = to_what\n if to_what == 1:\n self._cur_lev_num = 100\n self._cur_lev = self._level_won\n elif to_what == -1:\n self._cur_lev_num = -1\n self._cur_lev = self._level_lost\n\n def _get_rgbs(self):\n if self._status == -1: #lost\n return [.1,.1,.5,1], [0,0,.2,1]\n elif self._status == 1: #won\n return [1,.8,0,1], [.7,0,0,1]\n\n elif self._player.happy == -2019:\n return [1,.8,0,1], [.7,0,0,1]\n elif self._cur_lev_num == 0:\n return [.2,.2,.5,1], [.1,.1,.3,1]\n elif self._cur_lev_num == 1:\n return [1,.8,.8,1], [.6,.4,.4,1]\n elif self._cur_lev_num == 2:\n return [1,.4,.4,1], [.6,.3,.3,1]\n elif self._cur_lev_num == 3:\n return [1,.1,.1,1], [.2,.2,.2,1]\n\n def _get_emoji(self):\n if self._player.happy == -2019:\n return '(•_•)'\n elif self._player._happy < 10:\n return r'.·´¯`(>_<)´¯`·.'\n elif self._player._happy < 25:\n return r'¯\\_(•_•)_/¯'\n elif self._player._happy < 50:\n return '(•_•)'\n elif self._player._happy < 75:\n return '(^__^)'\n elif self._player._happy < 100:\n return r'*\\(^__^)/*'\n elif self._player._happy >= 100:\n return r'*(0_o)*'"
},
{
"alpha_fraction": 0.5236486196517944,
"alphanum_fraction": 0.5270270109176636,
"avg_line_length": 18.66666603088379,
"blob_id": "3462fad836ddfa50a34f743047a5bfe486bc8c2a",
"content_id": "91c50bb176fc6dd1486039ce265dc8767b0f6831",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 296,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 15,
"path": "/player.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "\n\nclass Player():\n\n def __init__(self, start_happy):\n self._happy = start_happy\n self._score = 0\n\n def add_happy(self, val):\n self._happy += val\n \n def add_score(self, val):\n self._score += val\n\n @property\n def happy(self):\n return self._happy"
},
{
"alpha_fraction": 0.5584415793418884,
"alphanum_fraction": 0.5600649118423462,
"avg_line_length": 24.625,
"blob_id": "b96d194886025e4931e28f8999452e4508359582",
"content_id": "18daf55b1a162d53016a861b3476b196196c0871",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 616,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 24,
"path": "/challenge.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "\nfrom typing import Tuple\n\nclass Challenge:\n \n def __init__(\n self, prompt : Tuple[str], \n choices : Tuple[str],\n ans_vals : Tuple[int],\n ans_expl : Tuple[str]\n ):\n self._prompt = prompt\n self._choices = choices\n self._ans_vals = ans_vals\n self._ans_expl = ans_expl\n\n def get_prompt(self) -> tuple:\n return self._prompt\n\n def get_choices(self) -> tuple:\n return self._choices\n \n def asses_choice(self, choice : int):\n choice -= 1 #tuples are zero indexed\n return self._ans_vals[choice], self._ans_expl[choice]\n"
},
{
"alpha_fraction": 0.6416938304901123,
"alphanum_fraction": 0.6482084393501282,
"avg_line_length": 24.58333396911621,
"blob_id": "7441fbb19dba471d86eac940ecaa92c0629a588d",
"content_id": "ff4fbdc124a49578160c1caa53729f4d2e196b04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 614,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 24,
"path": "/level.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "\nfrom random import randrange\nfrom typing import Tuple\nfrom challenge import Challenge\n\nclass Level:\n\n def __init__(self, challenges : Tuple[Challenge]):\n self._challenges = challenges\n\n def get_next_challenge(self):\n rand = randrange(0, len(self._challenges))\n return self._challenges[rand]\n\nclass LevelSequential(Level):\n CURRENT = 0\n\n def get_next_challenge(self):\n challenge = self._challenges[self.CURRENT]\n \n #in order to avoid an indexing error\n if len(self._challenges) - 1 > self.CURRENT:\n self.CURRENT += 1\n\n return challenge"
},
{
"alpha_fraction": 0.5601904988288879,
"alphanum_fraction": 0.5862318277359009,
"avg_line_length": 36.364864349365234,
"blob_id": "d906716d35907b32a35f6f041e26c848b0bccc24",
"content_id": "505bd34960853bd8d0420365f1a0ca591f57cfe4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16593,
"license_type": "no_license",
"max_line_length": 223,
"num_lines": 444,
"path": "/factory.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "from challenge import Challenge\nfrom level import Level, LevelSequential\nfrom player import Player\nfrom gameloop import GameLoop\n\ndef create_gameloop():\n player = Player(-2019)\n levels = (create_level_0(), create_level_1(), create_level_2(), create_level_3())\n return GameLoop(player, levels, 1, create_tut_lev(), create_won_lev(), create_lost_lev())\n\ndef create_level_0():\n challenges = (\n challenge00(), challenge01(), challenge02(), challenge03()\n )\n return Level(challenges)\n\ndef create_level_1():\n challenges = (\n challenge11(), challenge12(), challenge13()\n )\n return Level(challenges)\n\ndef create_level_2():\n challenges = (\n challenge20(), challenge21(), challenge22()\n )\n return Level(challenges)\n\ndef create_level_3():\n challenges = (\n challenge30(), challenge31(), challenge32(), challenge33()\n )\n return Level(challenges)\n\ndef create_tut_lev():\n challenges = (\n challenge_t0(), challenge_t1()\n )\n return LevelSequential(challenges)\n\ndef create_lost_lev():\n challenges = (\n challenge_lost0(), challenge_lost0()\n )\n return LevelSequential(challenges)\n\ndef create_won_lev():\n challenges = (\n challenge_won0(), challenge_won1(), challenge_won2(), challenge_won3(),\n challenge_won4(), challenge_won5(), challenge_won6(), challenge_won7(),\n challenge_won8(), challenge_won9(), challenge_won10()\n )\n return LevelSequential(challenges)\n\n\n############ level 0 #############################\n\ndef challenge00():\n prompt = '''Your mood is low.\\n\n You feel so sad even snuggling a baby bulldog wouldn't cheer you up.\n What do you do?'''\n choices = ('Call Stan', 'Eat something', 'Fetal position', 'Pep talk')\n ans_vals = (-10,3,3,-10)\n ans_expl = (\n 'Stan doesn\\'t like you.', \n 'You feel your strength reviving...', \n 'What doesn\\'t kill you makes you stronger?',\n 'Your best try quickly soured into you listing reasons mold is more likeable than you are.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge01():\n prompt = '''Your mood is low.\\n\nMovieFlix just released all 4 seasons of \"Pathetic People with Lives You Will Enjoy Judging\".'''\n choices = ('Sounds like a plan!', 'I\\'m going to train for a marathon instead!',\n 'I\\'ll take a walk first', 'I\\'ll go outside. To do what, I don\\'t know.')\n ans_vals = (-8,-10,5,5)\n ans_expl = (\n 'You have melted into a puddle on the couch. No one is quite sure where you end and butt-imprinted foam begins.', \n 'You put on running shoes, decided you would never be able to do it, and then watched movies with shoes on', \n 'Good choice!',\n 'Anything is better than nothing!'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge02():\n prompt = '''Your mood is low.\\n\n You just realized you spent the last 3 hours thinking about how jealous you are of house plants. What in the world are you going to do next?'''\n choices = ('Take it one day at a time', 'Take it one hour at a time',\n 'Take it one minute at a time', 'Take it 10 seconds at a time')\n ans_vals = (1,2,3,-1)\n ans_expl = (\n 'Let tomorrow worry about itself!', \n 'Small steps!', \n 'Just got through another minute!',\n 'You tried, but forgot the word for 7 and gave up.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge03():\n prompt = '''Your mood is low.\\n\\nYou are always talking to yourself. What are you saying right now?'''\n choices = ('I have the personality of a sponge', \n 'I\\'m pretty sure the only reason my friends like me is because I have a pogo stick.',\n 'I wish my face was a pogo stick', 'Life is like my underwear. It doesn\\'t change.')\n ans_vals = (-1,-1,-1,-1)\n ans_expl = (\n 'Oddly enough, so do sponges.', \n 'Imagine if you DIDN\\'T have that pogo stick then.', \n 'That is the weirdest thing I have ever heard.',\n 'Bruh, change them drawers.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\n\n############ level 1 #############################\n\n\ndef challenge11():\n prompt1 = 'What a nice day!\\n\\nWhat would you like to do?'\n choices1 = ('Smile', 'Laugh', 'Hugs', 'Cry')\n ans_vals1 = (3,5,-10,-5)\n ans_expl1 = (\n \"Show them pearls!\", \n 'The best medicine!\\n\\n(this statement has not been approved by the FDA)',\n 'You chose a bear.\\nFrom now on, your hugs will all be one-armed.',\n 'Well, you haven\\'t quite gotten the hang of this game yet...'\n ) \n return Challenge(prompt1, choices1, ans_vals1, ans_expl1)\n\ndef challenge12():\n prompt1 = 'I KNOW. Let\\'s do something for four hours straight!'\n choices1 = ('Ski', 'Scream', 'Video Games', 'Read a biography, help orphans, and write well-informed letters to congress')\n ans_vals1 = (-5,7,-10,-1)\n ans_expl1 = (\n \"You had fun for 3 hours and 15 minutes. At 3 hours and 16 minutes you swerved to avoid a moose, went off a ledge, and landed on top of a CIA operative, thus blowing his cover. Oh. And you broke your collar bone.\", \n 'Your shrieks were heard by a famous metal band. They offer you a lucrative contract.',\n 'You won the MMORPG battle, but lost the afternoon',\n 'No points awarded to the brown-noser.\\n\\nAnd, minus 1 points for lying.'\n ) \n return Challenge(prompt1, choices1, ans_vals1, ans_expl1)\n\ndef challenge13():\n prompt1 = 'Time to pick a name for your new band.'\n choices1 = ('Shredder Kitties', 'AC/Defroster', 'Shotguns and Petunias', 'Steel Dirgible')\n ans_vals1 = (5,3,-5,1)\n ans_expl1 = (\n 'Solid choice.\\n\\nYou captured both your unbridled rage and cuddly inner soul.', \n 'Familiar but catchy.',\n 'Your first single: \"Welcome to the Forest\"\\n\\n was not a hit',\n 'Definitely better than your runner up choice:\\n\\n \"The Stink Beatles\"'\n ) \n return Challenge(prompt1, choices1, ans_vals1, ans_expl1)\n############ level 2 #############################\n\ndef challenge20():\n prompt1 = 'Is it just me, or is it getting AWESOME in here?'\n choices1 = ('It\\'s just you', 'Did someone open up a can of YEEEHAAA?', \n 'I heard on the radio that today it will be sunny with a chance of SHABAM!', \n 'Let\\'s blast some country music!!'\n )\n ans_vals1 = (-5,5,5,-10)\n ans_expl1 = (\n 'Party pooper\\n >:|', \n 'YOU\\'RE DARN RIGHT I DID',\n 'Are you a tornado? \\'Cause you raisin\\' the roof!',\n 'How about let\\'s not'\n ) \n return Challenge(prompt1, choices1, ans_vals1, ans_expl1)\n\ndef challenge21():\n prompt = ('''\"Ridonculous\" took the civil world by storm. \"Classic\" took a fine word and made it on point.\\n\n What's the next annoying phrase you will grace humanity with?''')\n choices = ('Spectankulous', 'Counterfactual', 'Tiktoktakular', 'Typey')\n ans_vals = (5,7,-10,8)\n ans_expl = (\n 'Nerdy high schoolers everywhere thank you for giving them something they think will make them sound cool', \n 'PRENTENSION LEVEL UP. You sound crazy smart without actually having to know what the word means because you are using it \"ironically.\"',\n 'Sorry, not that creative. Plus China is spying on you.',\n 'What\\'s old? Typewriters. See that guy looking at a map? That is SO typey.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge22():\n prompt = ('''You are about to get on an airplane to sign a disarmament treaty with North Korea\n when you hear some CRANKED UP music and the sounds of people dancing in the distance.''')\n choices = ('Treaty Smeaty. Dance is life.', 'Call me Kim Jung Una FIESTA DE BAILE', \n '“Without delayed gratification, there is no power over self.”', \n 'The greatest joy is a job well done'\n )\n ans_vals = (3,2,-10,0)\n ans_expl = (\n 'NO JOY IS REAL BUT THE PRESENT!', \n 'Is that confetti? Oh, it\\'s nuclear ash? HEY SARAH, WE DON\\'T NEED GLOWSTICKS ANYMORE. YEAH, wE ArE ABOuT to BECOme GLoW hUMANS',\n 'Did you go to college? Because it sounds like you have a bachelor\\'s degree in BORING.',\n 'Life\\'s uncertain. Eat dessert first.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\n#People are having so much fun, but they are hipsters. What will you do to get in?\n\n############ level 3 #############################\n\ndef challenge30():\n prompt = ('''Man, you are SO FREAKIN\\' EXCITED\\n\n How are you going to take this to the next level?''')\n choices = ('Eat cake', 'Punch a clown', 'Eat ice cream ALL DAY', 'Be Yourself')\n ans_vals = (2,7,-10,-20)\n ans_expl = (\n \"SUGAR RUSH!!!!!!!!!!\", \n 'How can something that feels so right be wrong?',\n 'Diarrhea\\n :`(',\n 'Not to be offensive, but everyone you know is worse off for having known you.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge31():\n prompt = ('''ARE. YOU. HAPPY. YET?!''')\n choices = ('Yes', 'YHEEESSSS', 'No', 'I\\'m only getting started')\n ans_vals = (1,-10,5,-5)\n ans_expl = (\n 'WHERE IS THE PASSION?', \n 'CAN YOU EVEN SPELL?!',\n 'THAT\\'S RIGHT. NEVER BE CONTENT! Compared to how happy you GONNA BE, THIS IS NOTHING YET!!!!!',\n 'THEN START FOR REAL, BRO.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge32():\n prompt = ('''WHAT IS THE PURPOSE OF LIFE?!!!''')\n choices = ('Be happy','Make a meaningful impact on the world', \n 'Become famous', 'DIE WITH MORE MONEY THAN GOD.')\n ans_vals = (5,-5,-5,-5)\n ans_expl = (\n 'A THOUSAND TIMES YES. NOTHING ELSE MATTERS.', \n 'But what if you are crying while you do it? Then what is it worth?!',\n 'FAMOUS PEOPLE DON\\'T LOOK HAPPY TO ME',\n 'IF YOU ARE GOING TO DIE, IT WILL ONLY BE FROM BEING TOO HAPPY.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge33():\n prompt = '''You are RUNNING through the streets SHOUTING FOR JOY and you see someone NOT looking COMPLETELY ENTHUSED about life.'''\n choices = ('Give him a high-five', \n 'SCREAM in his face like A DRILL SERGEANT OF HAPPINESS until FEELS THE HAPPYS to the core of his middle-aged being', \n 'Punch him on the shoulder and say, \"JOY BUGGY\"', \n 'Keep walking. Don\\'t let him vampire your joy.')\n ans_vals = (-5,5,2,-10)\n ans_expl = (\n 'He did not give you a high five back. Your face burns with the indignation of unrequited love.', \n 'DON\\'T YOU SEE THE HAPPYS YOU ARE MISSING?! QUIT YOUR JOB. EAT TWINKIES UNTIL YOU PUKE. DO WHATEVER YOU MUST TO ACQUIRE LOLS',\n 'Great idea, but it didn\\'t do enough. PUNCH HIM AGAIN UNTIL HE FEELS THE LOVE',\n 'NO. NO ONE CAN MISS OUT ON THIS. THEY MUST FEEL THE JOY.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\n############ Tutorial #############################\n\ndef challenge_t0():\n prompt = ('''H A P P Y \\n\\nP L A N E T''')\n choices = ('', '', '', 'continue')\n ans_vals = (0,0,0,0)\n ans_expl = (\n '', \n '',\n '',\n 'by palinnilap and dragongirl'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_t1():\n prompt = ('''You will be given 25 mood to start.\\n\\n\n Don\\'t screw this up.''')\n choices = ('', '', 'Start Game', '')\n ans_vals = (0,0,2019+25,0)\n ans_expl = (\n '', \n '',\n 'Time to make the world a happy place',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\n############ Lost #############################\n\ndef challenge_lost0():\n prompt = ('''Congratulations. You lost.''')\n choices = ('', '', '', 'I want to try again.')\n ans_vals = (0,0,0,0)\n ans_expl = (\n '', \n '',\n '',\n 'What about \"you lost\" was hard to understand?'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\n############ Won #############################\n\ndef challenge_won0():\n prompt = ('''You HaVE DONE IT! YOu HAvE REACHED PeaK hAPPINESS! HWAAHHAHA ''')\n choices = ('', '', '', 'I am the best.')\n ans_vals = (0,0,0,1000)\n ans_expl = (\n '', \n '',\n '',\n 'Yes, our jolly monarch, you are.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won1():\n prompt = ('''BuT LOOK AT THEM, UNHAPPY mAsseS. ''')\n choices = ('', '', 'SOMEthing must be DONE!', '')\n ans_vals = (0,0,1324,1000)\n ans_expl = (\n '', \n '',\n 'WhY DO YOU nOT SeE WHAT HAPpYS ARe FOR YOUR TAKINg, PEOpLES OF THE WORLD?!',\n '.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won2():\n prompt = ('''SHOULDN\\'T YoU DO SOmEtHING ABOUT THEM? theIR MISERy MUsTN\\'T ToUCh YOu! ''')\n choices = ('YES!', 'No', '', '')\n ans_vals = (9999,9999,1000,0)\n ans_expl = (\n 'OF COURSE WE SHOULD! WHY WOULDN\\'T WE?!', \n 'THAT IS CRAZY TALK MY FRIEND, WE MUST GIVE THEM OUR GIFT',\n '',\n '.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won3():\n prompt = ('''BUT HOw CaN WE GIVE OuR gIFT?''')\n choices = ('USE THE SKY', 'A ROCKET OF GOOD TIDINGS', 'VIRUS OF JOY', '')\n ans_vals = (89764,89764,89764,89764)\n ans_expl = (\n 'YES, OF COURSE, WE cAN SpREAD THE JOY THROUGH THE hEAVENS', \n 'bOMBs HAvE DeSTRoYED BUt OURs CAN GIVE LIFE!',\n 'HAPPINESS GOES VIRAL',\n '.'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won4():\n prompt = ('''Sir, the ROCKET is READY. WE WILL SPREAD OUR JOY THROUGHOUT THE EARTH''')\n choices = ('HIt thE BUTToN', 'I\\m having second thoughts', '', '')\n ans_vals = (1001,1010,1001,1001)\n ans_expl = (\n '3... 2... 1... Isn\\'t it beautiful, sir?', \n 'WE HAVE COME TOO FAR. THERE IS NO BACKING OUT NOW!!\\n\\n*hits button for you',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won5():\n prompt = ('''You drive out to the city to see what happens.\n For a long time nothing, then blinding light, a ferocious wind, and ...''')\n choices = ('HIt thE BUTToN', 'I\\m having second thoughts', '', '')\n ans_vals = (1000,1000,1000,1000)\n ans_expl = (\n 'Continue', \n '',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won6():\n prompt = ('''It\\'s working! The initial shock has washed off and people push themselves off the ground and back to their feet.\n And they are... happy.. smiling... laughing ''')\n choices = ('', 'This laughter is truly inFECTIous!', '', '')\n ans_vals = (1000,9999,1000,1000)\n ans_expl = (\n '', \n 'IT WORKED! UtOPIA HAs cOME!!!!!',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won7():\n prompt = ('''bUT WAIT. PeOPLE can\\'t stop laughing. They can't talk. They can\\'t eat.\\n\n The uproar of the city takes on an ominous tone.''')\n choices = ('', '', '', 'HAHAHAHA!!')\n ans_vals = (1000,9999,100000,1000)\n ans_expl = (\n '', \n '',\n '',\n 'Sir?'\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won8():\n prompt = ('''Sir, you haven't slept or ate for days!!!''')\n choices = ('', 'HAHAHAHAH!!!!!', '', '')\n ans_vals = (1000,9999,100000,1000)\n ans_expl = (\n '', \n 'Sir, you should.... heh.. ha... HAHAHAHA!!',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won9():\n prompt = ('''HAHAHAH hahaha h...''')\n choices = ('', '', 'ha ... ha .... h', '')\n ans_vals = (1000,9999,100000,1000)\n ans_expl = (\n '', \n '',\n 'h',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won10():\n prompt = ('''...''')\n choices = ('...', '', '', '')\n ans_vals = (10000000,9999,100000,1000)\n ans_expl = (\n '', \n '',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)\n\ndef challenge_won10():\n prompt = ('''GAME OVER''')\n choices = ('', '', '', '')\n ans_vals = (1000,9999,100000,1000)\n ans_expl = (\n '', \n '',\n '',\n ''\n ) \n return Challenge(prompt, choices, ans_vals, ans_expl)"
},
{
"alpha_fraction": 0.7785235047340393,
"alphanum_fraction": 0.7785235047340393,
"avg_line_length": 28.799999237060547,
"blob_id": "95d91027640c9cceb0419677db8c7a1fb41d98a1",
"content_id": "65fe028cb2ccb3df49433b59f53d05db7b6fd248",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 149,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 5,
"path": "/README.md",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "# Happy Planet\n\nNot well written, doesn't follow good coding rules. It's just a fun way to teach a friend basics of programming!\n\nUnder construction\n"
},
{
"alpha_fraction": 0.5859326124191284,
"alphanum_fraction": 0.5990330576896667,
"avg_line_length": 34.230770111083984,
"blob_id": "1533e913b65ca6123f24cc4e0e3beb557df91636",
"content_id": "42da736e99e57592c4261c66f5690e8ffc87d667",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6412,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 182,
"path": "/main.py",
"repo_name": "palinnilap/happy-planet",
"src_encoding": "UTF-8",
"text": "from kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import (\n ObjectProperty, StringProperty\n)\nfrom kivy.clock import Clock\nimport factory\nimport time\n\nclass HappyGame(Widget):\n #color management\n BUTTON_DN = []\n BUTTON_UP = []\n BUTTON_DISABLED = [0,0,0,0]\n \n #uix elements\n score = ObjectProperty(None)\n emoji = ObjectProperty(None)\n happy_meter = ObjectProperty(None)\n score_updater = ObjectProperty(None)\n prompt = ObjectProperty(None) \n button1 = ObjectProperty(None)\n button2 = ObjectProperty(None)\n button3 = ObjectProperty(None)\n button4 = ObjectProperty(None)\n\n #class stats\n PRESSED = 0\n CONTINUE = 0\n BUTTON_ENBLD = 1\n\n #setup gameloop\n gameloop = factory.create_gameloop()\n cur_challenge = gameloop.get_next_challenge()\n\n def update(self, dt):\n '''main cycle for reacting to user input'''\n self.set_rgbs()\n self.check_status()\n self.check_for_user_input()\n self.set_scores()\n \n def check_for_user_input(self):\n if self.prompt.text == 'error': \n #need to set up intial values\n self.populate_challenge()\n \n if self.CONTINUE and self.PRESSED == 1:\n #if user hit continue, present next challenge\n self.cur_challenge = self.gameloop.get_next_challenge()\n self.score_updater.text = ''\n self.populate_challenge()\n self.CONTINUE = 0\n self.PRESSED = 0\n \n if self.PRESSED and not self.CONTINUE:\n #user choice an answer, process it\n self.hide_unpicked_buttons()\n self.prompt.text = ''\n self.BUTTON_ENBLD = 0\n self.CONTINUE = 1\n self.process_choice()\n self.PRESSED = 0 #this can't come earlier\n \n def process_choice(self) -> None:\n val, expl = self.cur_challenge.asses_choice(self.PRESSED)\n self.gameloop.submit_results(1, val) #score always increments by 1\n Clock.schedule_once(lambda dt: self.display_score_update(val), .5)\n Clock.schedule_once(lambda dt: self.display_expl(expl), 1)\n Clock.schedule_once(lambda dt: self.set_buttons_to_continue(), 2)\n Clock.schedule_once(lambda dt: self.enable_buttons(), 2)\n\n def hide_unpicked_buttons(self):\n if not self.PRESSED == 1:\n self.button1.text = ''\n self.button1.background_color = self.BUTTON_DISABLED\n if not self.PRESSED == 2:\n self.button2.text = ''\n self.button2.background_color = self.BUTTON_DISABLED \n if not self.PRESSED == 3:\n self.button3.text = ''\n self.button3.background_color = self.BUTTON_DISABLED\n if not self.PRESSED == 4:\n self.button4.text = ''\n self.button4.background_color = self.BUTTON_DISABLED\n \n def enable_buttons(self):\n self.BUTTON_ENBLD = 1\n\n def display_score_update(self, val):\n self.score_updater.text = self.format_val(val)\n\n def display_expl(self, expl):\n self.prompt.text = expl\n\n def set_buttons_to_continue(self):\n \n self.button1.text = \"Continue\"\n self.button1.background_color = self.BUTTON_DISABLED\n self.button2.text = ''\n self.button2.background_color = self.BUTTON_DISABLED\n self.button3.text = ''\n self.button3.background_color = self.BUTTON_DISABLED\n self.button4.text = '' \n self.button4.background_color = self.BUTTON_DISABLED\n\n def format_val(self, val : int) -> None:\n if val >= 0:\n return '+' + str(val)\n \n else:\n return str(val)\n\n def set_scores(self) -> None:\n self.score.text = self.gameloop.score\n self.emoji.text = self.gameloop.emoji\n self.happy_meter.text = self.gameloop.happy\n\n def populate_challenge(self) -> None:\n self.prompt.text = self.cur_challenge.get_prompt()\n self.button1.text = self.cur_challenge.get_choices()[0]\n self.button2.text = self.cur_challenge.get_choices()[1]\n self.button3.text = self.cur_challenge.get_choices()[2]\n self.button4.text = self.cur_challenge.get_choices()[3]\n\n if self.cur_challenge.get_choices()[0] == '':\n self.button1.background_color = self.BUTTON_DISABLED\n else:\n self.button1.background_color = self.BUTTON_UP\n if self.cur_challenge.get_choices()[1] == '':\n self.button2.background_color = self.BUTTON_DISABLED\n else:\n self.button2.background_color = self.BUTTON_UP\n if self.cur_challenge.get_choices()[2] == '':\n self.button3.background_color = self.BUTTON_DISABLED\n else:\n self.button3.background_color = self.BUTTON_UP\n if self.cur_challenge.get_choices()[3] == '':\n self.button4.background_color = self.BUTTON_DISABLED\n else:\n self.button4.background_color = self.BUTTON_UP\n \n def on_touch_down(self, touch):\n '''lets self.update know which button was pressed. changes color'''\n # this code is not DRY. kv language made simpler code hard to write\n if not self.BUTTON_ENBLD:\n return\n if self.button1.collide_point(*touch.pos):\n self.PRESSED = 1\n self.button1.background_color = self.BUTTON_DN\n elif self.button2.collide_point(*touch.pos):\n self.PRESSED = 2\n self.button2.background_color = self.BUTTON_DN\n elif self.button3.collide_point(*touch.pos):\n self.PRESSED = 3 \n self.button3.background_color = self.BUTTON_DN\n elif self.button4.collide_point(*touch.pos):\n self.PRESSED = 4\n self.button4.background_color = self.BUTTON_DN\n \n def on_touch_up(self, touch):\n pass\n\n def check_status(self):\n if self.gameloop.status == 1:\n pass # you won!\n elif self.gameloop.status == -1:\n pass # you lost\n\n def set_rgbs(self):\n a, b = self.gameloop.level_rgbs\n self.BUTTON_UP, self.BUTTON_DN = a, b\n self.score.color = self.happy_meter.color = a\n\nclass HappyApp(App):\n def build(self):\n game = HappyGame()\n Clock.schedule_interval(game.update, 1.0/60.0)\n return game\n\nif __name__ == '__main__':\n HappyApp().run()\n"
}
] | 7 |
DeeptiAgl/Reverse-Geo-Code | https://github.com/DeeptiAgl/Reverse-Geo-Code | 96ad022e49b98b85778f72bbfb8bbfd1230d9cc5 | 0a218a86f51d413a6310d2d1c3b0dee1ac38f7cb | 86c4fab1ceb98fbc9b9f67e2dc0d807a41766ebd | refs/heads/master | 2020-11-26T02:15:23.747690 | 2019-12-18T22:58:02 | 2019-12-18T22:58:02 | 228,934,745 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5987499952316284,
"alphanum_fraction": 0.6274999976158142,
"avg_line_length": 36.19047546386719,
"blob_id": "d5122bfa85054815d7c971f0782295054717390c",
"content_id": "a6ab85d421f65bbc07119c78b1f285f98b0bb389",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 800,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 21,
"path": "/RevGeoCode.py",
"repo_name": "DeeptiAgl/Reverse-Geo-Code",
"src_encoding": "UTF-8",
"text": "import geocoder\r\nimport pandas as pd\r\nCoStar = pd.read_csv(r\"abc.csv\",encoding = \"ISO-8859-1\",low_memory=False)\r\nprint(\"File Loaded into the system\")\r\nCoStar['LAT LON'] = CoStar[\"Latitude\"].astype(str) +\",\" + CoStar[\"Longitude\"].astype(str)\r\nlatlon = (CoStar['LAT LON'] ).tolist()\r\nprint(f\"{CoStar['LAT LON']} lat: {CoStar.Latitude} lon: {CoStar.Longitude} \")\r\nZC = []\r\nfor address in latlon:\r\n g = geocoder.mapquest(address, method='reverse', key='****') #key=please create youw own key at mapquest website\r\n \r\n # g = geocoder.mapquest([34.036453, -118.226467], method='reverse', key='PGpRDQRBrH7DqjF0OkYODgc2lmODm2c9')\r\n \r\n if g :\r\n ZC.append(g.postal)\r\n print(g.postal)\r\n # longitude.append(location.lng)\r\n else:\r\n ZC.append(0)\r\nCoStar['ZC'] = ZC\r\nCoStar.to_csv('CoStar_ZC.csv')"
},
{
"alpha_fraction": 0.8113207817077637,
"alphanum_fraction": 0.8113207817077637,
"avg_line_length": 25.5,
"blob_id": "9b88bb7d7852a910d5ff425b88baf6d082e5e03a",
"content_id": "21dff1265df7dd612cdef411f919410e1948154c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 53,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 2,
"path": "/README.md",
"repo_name": "DeeptiAgl/Reverse-Geo-Code",
"src_encoding": "UTF-8",
"text": "# Reverse-Geo-Code\nReverse geo coding using MapQuest\n"
}
] | 2 |
rongliangzi/CrowdCountingBaseline | https://github.com/rongliangzi/CrowdCountingBaseline | 736ea2a56b2ddf67dbc0a4474f2b1d9cf9d41f36 | db336e73ddca274ce1e543e5df109d84b62bb013 | 8c55743a66470f5c90b5ba0406967f89a1463db0 | refs/heads/master | 2021-01-06T10:31:48.068585 | 2020-03-02T13:29:13 | 2020-03-02T13:29:13 | 241,296,761 | 8 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7609561681747437,
"alphanum_fraction": 0.788844645023346,
"avg_line_length": 24.200000762939453,
"blob_id": "6e11e450bc2eb2598229ab86bae93703d50df198",
"content_id": "a0fb5f96ec9aacb67c8f5d92a05bb68d55fbf1bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 251,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 10,
"path": "/modeling/__init__.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "from .utils import *\n\nfrom .m_vgg import M_VGG\nfrom .Res50_C3 import Res50\nfrom .sanet import SANet\nfrom .inceptionv3_cc import Inception3CC\nfrom .def_ccnet import DefCcNet\nfrom .cannet import CANNet\nfrom .csrnet import CSRNet\nfrom .u_vgg import U_VGG"
},
{
"alpha_fraction": 0.5156826376914978,
"alphanum_fraction": 0.5525830388069153,
"avg_line_length": 36.36206817626953,
"blob_id": "e671c8f6870a8b480fa88b458e3d043de4ba7f6e",
"content_id": "c8e6390c2e221d3a3aac7515ae106d9919eccf83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2168,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 58,
"path": "/modeling/csrnet.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom .utils import *\n\n\nclass CSRNet(nn.Module):\n def __init__(self, load_model='', downsample=1, bn=False):\n super(CSRNet, self).__init__()\n self.downsample = downsample\n self.bn = bn\n self.features_cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512]\n self.features = make_layers(self.features_cfg)\n self.backend_cfg = [512, 512, 512, 256, 128, 64]\n self.backend = make_layers(self.backend_cfg, in_channels=512, dilation=True)\n \n self.output_layer = nn.Conv2d(64, 1, kernel_size=1)\n self.load_model = load_model\n self._init_weights()\n\n def forward(self, x_in):\n x = self.features(x_in)\n \n x = self.backend(x)\n \n x = self.output_layer(x)\n x = torch.abs(x)\n return x\n\n def _random_init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _init_weights(self):\n if not self.load_model:\n pretrained_dict = dict()\n model_dict = self.state_dict()\n path = \"/home/datamining/Models/vgg16_bn-6c64b313.pth\" if self.bn else '/home/datamining/Models/vgg16-397923af.pth'\n pretrained_model = torch.load(path)\n print(path,' loaded!')\n self._random_init_weights()\n # load the pretrained vgg16 parameters\n for k, v in pretrained_model.items():\n if k in model_dict and model_dict[k].size() == v.size():\n pretrained_dict[k] = v\n print(k, ' parameters loaded!')\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n else:\n self.load_state_dict(torch.load(self.load_model))\n print(self.load_model,' loaded!')\n\n"
},
{
"alpha_fraction": 0.5617828965187073,
"alphanum_fraction": 0.588408350944519,
"avg_line_length": 41.22981262207031,
"blob_id": "4b78bc04c27d3aa3038640bcf9477221256b55b3",
"content_id": "03189caec6021c40603c0cdcd96fe06ce459e239",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6798,
"license_type": "no_license",
"max_line_length": 213,
"num_lines": 161,
"path": "/modeling/utils.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch\n\n\nclass conv_act(nn.Module):\n '''\n basic module for conv-(bn-)activation\n '''\n def __init__(self, in_channels, out_channels, kernel_size, NL='relu', dilation=1, stride=1, same_padding=True, use_bn=False):\n super(conv_act, self).__init__()\n padding = (kernel_size + (dilation - 1) * (kernel_size - 1) - 1) // 2 if same_padding else 0\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=padding, dilation=dilation)\n self.use_bn = use_bn\n if self.use_bn:\n self.bn = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0, affine=True)\n if NL == 'relu' :\n self.activation = nn.ReLU(inplace=True) \n elif NL == 'prelu':\n self.activation = nn.PReLU() \n elif NL == 'swish':\n self.activation = Swish()\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn(x)\n x = self.activation(x)\n return x\n\n\ndef make_layers(cfg, in_channels=3, batch_norm=False, dilation=False, NL='relu', se=False):\n if dilation:\n d_rate = 2\n else:\n d_rate = 1\n layers = []\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=d_rate, dilation=d_rate)\n if NL=='prelu':\n nl_block = nn.PReLU()\n elif NL=='swish':\n nl_block = Swish()\n else:\n nl_block = nn.ReLU(inplace=True)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nl_block]\n else:\n layers += [conv2d, nl_block]\n if se:\n layers += [SEModule(v)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\nclass DilationPyramid(nn.Module):\n '''\n aggregate different dilations\n '''\n def __init__(self, in_channels, out_channels, dilations=[1,2,3,6], NL='relu'):\n super(DilationPyramid, self).__init__()\n assert len(dilations)==4, 'length of dilations must be 4'\n self.conv1 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL, dilation=dilations[0]))\n self.conv2 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL, dilation=dilations[1]))\n self.conv3 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL, dilation=dilations[2]))\n self.conv4 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL, dilation=dilations[3]))\n self.conv5 = conv_act(4*out_channels, 4*out_channels, 1, NL)\n def forward(self, x):\n x1 = self.conv1(x)\n x2 = self.conv2(x)\n x3 = self.conv3(x)\n x4 = self.conv4(x)\n output = torch.cat([x1, x2, x3, x4], 1)\n output = self.conv5(output)\n return output\n\n\nclass SizePyramid(nn.Module):\n '''\n aggregate different filter sizes, [1,3,5,7] like ADCrowdNet's decoder\n '''\n def __init__(self, in_channels, out_channels, NL='relu'):\n super(SizePyramid, self).__init__()\n self.conv1 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL))\n self.conv2 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 5, NL))\n self.conv3 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 7, NL))\n self.conv4 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL))\n self.conv5 = conv_act(4*out_channels, 4*out_channels, 1, NL)\n def forward(self, x):\n x1 = self.conv1(x)\n x2 = self.conv2(x)\n x3 = self.conv3(x)\n x4 = self.conv4(x)\n output = torch.cat([x1, x2, x3, x4], 1)\n output = self.conv5(output)\n return output\n \n \nclass DepthPyramid(nn.Module):\n '''\n aggregate different depths, like TEDNet's decoder\n '''\n def __init__(self, in_channels, out_channels, NL='relu'):\n super(DepthPyramid, self).__init__()\n self.conv1 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL))\n self.conv2 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL), conv_act(out_channels, out_channels, 3, NL))\n self.conv3 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL), conv_act(out_channels, out_channels, 3, NL), conv_act(out_channels, out_channels, 3, NL), conv_act(out_channels, out_channels, 3, NL))\n self.conv4 = nn.Sequential(conv_act(in_channels, out_channels, 1, NL))\n self.conv5 = conv_act(4*out_channels, 4*out_channels, 1, NL)\n def forward(self, x):\n x1 = self.conv1(x)\n x2 = self.conv2(x)\n x3 = self.conv3(x)\n x4 = self.conv4(x)\n output = torch.cat([x1, x2, x3, x4], 1)\n output = self.conv5(output)\n return output\n \n \nclass Swish(nn.Module):\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\nclass SPModule(nn.Module):\n def __init__(self, in_channels, branch_out=None):\n super(SPModule, self).__init__()\n if not branch_out:\n # ensure the in and out have the same channels.\n branch_out = in_channels\n self.dilated1 = nn.Sequential(nn.Conv2d(in_channels, branch_out,3,padding=2, dilation=2),nn.ReLU(True))\n self.dilated2 = nn.Sequential(nn.Conv2d(in_channels, branch_out,3,padding=4, dilation=4),nn.ReLU(True))\n self.dilated3 = nn.Sequential(nn.Conv2d(in_channels, branch_out,3,padding=8, dilation=8),nn.ReLU(True))\n self.dilated4 = nn.Sequential(nn.Conv2d(in_channels, branch_out,3,padding=12, dilation=12),nn.ReLU(True))\n self.down_channels = nn.Sequential(nn.Conv2d(branch_out*4, in_channels,1),nn.ReLU(True))\n def forward(self,x):\n x1 = self.dilated1(x)\n x2 = self.dilated2(x)\n x3 = self.dilated3(x)\n x4 = self.dilated4(x)\n # concat\n x = torch.cat([x1,x2,x3,x4],1)\n x = self.down_channels(x)\n return x\n\n\nclass SEModule(nn.Module):\n def __init__(self, in_, reduction=16):\n super().__init__()\n squeeze_ch = in_//reduction\n self.se = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(in_, squeeze_ch, kernel_size=1, stride=1, padding=0, bias=True),\n Swish(),\n nn.Conv2d(squeeze_ch, in_, kernel_size=1, stride=1, padding=0, bias=True),\n )\n\n def forward(self, x):\n return x * torch.sigmoid(self.se(x))"
},
{
"alpha_fraction": 0.5051971673965454,
"alphanum_fraction": 0.5274707078933716,
"avg_line_length": 31.767566680908203,
"blob_id": "4b96f5b3d7b15a045f06ef6b5f63500a1f89d5e5",
"content_id": "8d56e46a4ddfe16affeea3ac12ae89452c489e2c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6061,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 185,
"path": "/utils/functions.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch\nimport logging\nimport torch.nn as nn\nimport numpy as np\nimport math\nfrom .pytorch_ssim import *\nimport torch.nn.functional as F\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = 1.0 * self.sum / self.count\n\n def get_avg(self):\n return self.avg\n\n def get_count(self):\n return self.count\n\n\ndef linear_warm_up_lr(optimizer, epoch, warm_up_steps, lr):\n for param_group in optimizer.param_groups:\n warm_lr = lr*(epoch+1.0)/warm_up_steps\n param_group['lr'] = warm_lr\n\n\ndef get_logger(filename):\n logger = logging.getLogger('train_logger')\n\n while logger.handlers:\n logger.handlers.pop()\n logger.setLevel(logging.INFO)\n fh = logging.FileHandler(filename, 'w')\n fh.setLevel(logging.INFO)\n \n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n \n formatter = logging.Formatter('[%(asctime)s], ## %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n \n logger.addHandler(fh)\n logger.addHandler(ch)\n return logger\n\n\ndef val(model, test_loader, factor=1.0, verbose=False, downsample = 8):\n print('validation on whole images!')\n model.eval()\n mae, rmse = 0.0, 0.0\n psnr = 0.0\n ssim = 0.0\n ssim_d = 0.0\n psnr_d = 0.0\n with torch.no_grad():\n for it,data in enumerate(test_loader):\n img, target, count = data[0:3]\n \n img = img.cuda()\n target = target.unsqueeze(1).cuda()\n output = model(img)\n if isinstance(output, tuple):\n dmp, amp = output\n hard_amp = (amp > 0.5).float()\n dmp = dmp * hard_amp\n else:\n dmp = output\n est_count = dmp.sum().item()/factor\n if verbose:\n print('gt:{:.1f}, est:{:.1f}'.format(count.item(),est_count))\n elif it < 10:\n print('gt:{:.1f}, est:{:.1f}'.format(count.item(),est_count))\n mae += abs(est_count - count.item())\n rmse += (est_count - count.item())**2\n if verbose:\n mse = torch.mean((dmp - target)**2).float()\n \n psnr += 10 * math.log(1.0/mse, 10)\n ssim += cal_ssim(dmp, target)\n \n dmp_d = F.interpolate(dmp, [target.shape[2]//downsample, target.shape[3]//downsample]) * downsample**2\n target_d = F.interpolate(target, [target.shape[2]//downsample, target.shape[3]//downsample]) * downsample**2\n mse_d = torch.mean((dmp_d - target_d)**2).float()\n psnr_d += 10 * math.log(1.0/mse_d, 10)\n ssim_d += cal_ssim(dmp_d, target_d)\n mae /= len(test_loader)\n rmse /= len(test_loader)\n rmse = rmse**0.5\n psnr /= len(test_loader)\n ssim /= len(test_loader)\n psnr_d /= len(test_loader)\n ssim_d /= len(test_loader)\n if verbose:\n print('psnr:{:.2f}, ssim:{:.4f}, psnr of 1/8 size:{:.2f}, ssim of 1/8 size:{:.2f}'.format(psnr, ssim, psnr_d, ssim_d))\n return mae, rmse\n\n\ndef test_ssim():\n img1 = (torch.rand(1, 1, 16, 16))\n img2 = (torch.rand(1, 1, 16, 16))\n\n if torch.cuda.is_available():\n img1 = img1.cuda()\n img2 = img2.cuda()\n print(torch.max(img1))\n print(torch.max(img2))\n print(max(torch.max(img1),torch.max(img2)))\n print(cal_ssim(img1, img2).float())\n \n \n \n# validate on bayes dataloader\ndef val_bayes(model, test_loader, factor=1.0, verbose=False):\n print('validation on bayes loader!')\n model.eval()\n epoch_res=[]\n for it,(inputs, count, name) in enumerate(test_loader):\n inputs = inputs.cuda()\n # inputs are images with different sizes\n assert inputs.size(0) == 1, 'the batch size should equal to 1 in validation mode'\n with torch.set_grad_enabled(False):\n outputs = model(inputs)\n est = torch.sum(outputs).item()/factor\n res = count[0].item() - est\n if verbose:\n print('gt:{:.1f}, est:{:.1f}'.format(count[0].item(),torch.sum(outputs).item()))\n elif it<10:\n print('gt:{:.1f}, est:{:.1f}'.format(count[0].item(),torch.sum(outputs).item()))\n epoch_res.append(res)\n epoch_res = np.array(epoch_res)\n rmse = np.sqrt(np.mean(np.square(epoch_res)))\n mae = np.mean(np.abs(epoch_res))\n return mae, rmse\n\n\n# validate with 4 non-overlapping patches\ndef val_patch(model, test_loader, factor=1.0, verbose=False):\n print('validaiton on 4 quarters!')\n model.eval()\n mae, rmse = 0.0, 0.0\n with torch.no_grad():\n for it, data in enumerate(test_loader):\n img, _, count = data[0:3]\n h,w = img.shape[2:]\n h_d = h//2\n w_d = w//2\n \n img_1 = (img[:,:,:h_d,:w_d].cuda())\n img_2 = (img[:,:,:h_d,w_d:].cuda())\n img_3 = (img[:,:,h_d:,:w_d].cuda())\n img_4 = (img[:,:,h_d:,w_d:].cuda())\n img_patches = [img_1, img_2, img_3, img_4]\n est_count = 0\n for img_p in img_patches:\n output = model(img_p)\n if isinstance(output, tuple):\n dmp, amp = output\n dmp = dmp *amp\n else:\n dmp = output\n est_count += dmp.sum().item()/factor\n if verbose:\n print('gt:{:.1f}, est:{:.1f}'.format(count.item(),est_count))\n elif it < 10:\n print('gt:{:.1f}, est:{:.1f}'.format(count.item(),est_count))\n mae += abs(est_count - count.item())\n rmse += (est_count - count.item())**2\n mae /= len(test_loader)\n rmse /= len(test_loader)\n rmse = rmse**0.5\n return mae, rmse"
},
{
"alpha_fraction": 0.2785443663597107,
"alphanum_fraction": 0.3898809552192688,
"avg_line_length": 61.61864471435547,
"blob_id": "589942a3ba9d6a201487bd405c6df2926939b5b1",
"content_id": "8709696c2e865291535105802bd3c85122afe4e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 7392,
"license_type": "no_license",
"max_line_length": 301,
"num_lines": 118,
"path": "/README.md",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "# Crowd Counting Baseline\n\nWe set up a strong baseline for crowd counting easy to follow and implement. Following tricks are adopted to improve the performance. We are continuing with this work.\n\nExperiments are conducted on ShanghaiTech PartA dataset.\n\n## Baseline Network Architecture\n\nFirst 13 layers of VGG-16 without batch-norm followed by upsample and conv layers to get **the same size** density maps as input images. In the backend, SE blocks is adopted. Swish activation replaces ReLU. Figure will be added soon.\n\nMult-Adds is calculated using 1\\*3\\*224\\*224 as input.\n\nUse full images and MSE loss function to train.\n\nVGG16-13 not converge.\n\nWhen applying pyramids in the whole decoder, the model converge to a bad local minimum, so only first 2 layers use pyramids.\n\nProblems to be issued:\n\n- [ ] When training U-VGG, loss converge to 1.1e-4. and MAE ~240. Try (1)use SGD (2)random init instead of vgg16 and simplify. but they do not work.\n\n- [ ] When training CSRNet, if init the parameters randomly instead of using pretrained, converge to MAE ~330.\n- [ ] If use first 13 layers of VGG16 in M_VGG, downsample = 8, training loss converges to ~0.0030 and do not reduce. MAE is 86.4.\n- [x] When adding 3 upsample layers into CSRNet so that to regress 1 size density maps, loss converges to ~1.218e-5, and MAE > 200. When adding 2 upsample layers, , loss converges to ~1.8e-4, and MAE > 120. When adding 1 upsample layer, loss converges to ~2e-3, and MAE ~94. Reducing the lr will work.\n- [ ] When use ResNet-50, the outputs seem to be quite close to each other.\n\n| Model | MAE | RMSE | PSNR | SSIM | Params | Mult-Adds |\n| ------------------------------------ | ----: | ----: | ----: | ---: | -----: | --------: |\n| ResNet-50 + decoder | 80.6 | 130.1 | | | 11.6G | 29.6G |\n| Res2Net-50 + decoder | | | | | 11.8G | 29.7G |\n| InceptionV3 + decoder | 119.4 | 170.5 | | | | |\n| VGG16-10 + decoder(CSRNet) | 72.6 | 114.8 | 22.66 | 0.70 | 16.3M | 30.6G |\n| VGG16-10 + decoder(1,3,5,7 filter) | 70.9 | 110.8 | | | 13.0M | 28.0G |\n| VGG16-10 + decoder(1,2,3,6 dilation) | 74.7 | 113.1 | | | 11.4M | 26.8G |\n| VGG16-10 + decoder(depth pyramid) | 74.2 | 112.5 | | | 12.0M | 27.3G |\n| VGG16-13 + decoder | 86.4 | 125.1 | | | | |\n| VGG16-10 + decoder, 1 size | >200 | >300 | | | | |\n| VGG16-10 + decoder, 1/2 size | 119.4 | 192.9 | | | | |\n| VGG16-10 + decoder, 1/4 size | 94 | | | | | |\n| VGG16-10 + Dense | 72.5 | 113.8 | | | 13.0M | 28.8G |\n| VGG16-10 + DenseRes | 72.1 | 116.0 | | | 10.6M | 29.6G |\n| VGG16-10 + Res | 74.4 | 113.3 | | | 16.3M | 30.6G |\n| VGG16-13 + decoder + swish | 73.9 | 117.8 | | | | |\n| VGG16-13 + decoder + se | 74.8 | 119.7 | | | | |\n\nSelect model: VGG16-10 + decoder(CSRNet)\n\n\n\n## Augmentation\n\nWhen calculating PSNR and SSIM, different resolutions lead to different result. For original size density maps, the value of each pixel is quite small so that PSNR and SSIM is bigger than 1/8 size.\n\n$Loss = L_{MSE}+100*downsample*L_{C}$\n\n| Strategy | MAE | RMSE | PSNR | SSIM | PSNR(1/8) | SSIM(1/8) | Time/epoch |\n| ------------ | -------: | -------: | --------: | ---------: | --------: | --------: | ---------------: |\n| 0.3$\\times$ | **62.9** | 99.7 | **58.61** | **0.9869** | **22.51** | 0.62 | **0.33$\\times$** |\n| 0.4$\\times$ | 64.8 | **95.8** | 58.44 | 0.9864 | 22.35 | 0.61 | 0.39$\\times$ |\n| 0.5$\\times$ | 64.3 | 100.4 | 58.27 | 0.9861 | 22.18 | 0.58 | 0.43$\\times$ |\n| 0.6$\\times$ | 64.4 | 98.8 | 58.36 | 0.9862 | 22.27 | 0.60 | 0.51$\\times$ |\n| 0.7$\\times$ | 64.8 | 99.7 | 58.16 | 0.9858 | 22.09 | 0.56 | 0.61$\\times$ |\n| 0.8$\\times$ | 64.2 | 99.6 | 58.23 | 0.9858 | 22.15 | 0.60 | 0.71$\\times$ |\n| 0.9$\\times$ | 66.5 | 100.3 | 58.12 | 0.9856 | 22.04 | 0.58 | 0.86$\\times$ |\n| Original | 67.7 | 103.1 | 58.02 | 0.9854 | 21.94 | 0.56 | 1.00$\\times$ |\n| fixed | 64.9 | 101.2 | 58.34 | 0.9862 | 22.26 | 0.62 | 1.20$\\times$ |\n| fixed+random | 63.8 | 101.1 | 58.39 | 0.9865 | 22.30 | **0.64** | 2.43$\\times$ |\n| mixed | 68.7 | 106.5 | 58.01 | 0.9854 | 21.92 | 0.56 | 5.01$\\times$ |\n\n\n\n## Map Size\n\n| | MAE | RMSE | PSNR | SSIM | PSNR(1/8) | SSIM(1/8) |\n| -------------------------------------------- | -------: | -------: | ----: | -----: | --------: | --------: |\n| 1 | 62.9 | 99.7 | 58.61 | 0.9869 | **22.51** | **0.62** |\n| $\\frac{1}{2}$ | **62.0** | 95.4 | 46.47 | 0.9416 | 22.42 | **0.62** |\n| $\\frac{1}{4}$ | **62.0** | **93.0** | 34.38 | 0.8197 | 22.35 | 0.61 |\n| $\\frac{1}{4}, L_{MSE}+400*downsample*L_{C}$ | 61.4 | 92.6 | | | | |\n| $\\frac{1}{4}, L_{MSE}+1000*downsample*L_{C}$ | 60.0 | 92.6 | | | | |\n| $\\frac{1}{4}, L_{MSE}+25*downsample*L_{C}$ | 63.5 | 93.4 | | | | |\n| $\\frac{1}{8}$ | 63.0 | 95.6 | 22.24 | 0.6122 | 22.24 | 0.61 |\n\n| | | |\n| ---- | ---- | ----- |\n| SHB | | |\n| qnrf | 95.3 | 166.9 |\n| | | |\n\n\n\n## Loss Function\n\nSize = 1\n\n| | MAE | RMSE | PSNR | SSIM |\n| ------------------------------ | -----------: | ----: | ---: | ---: |\n| $L_{MSE}$ | | | | |\n| $L_{MSE}+100*downsample*L_{C}$ | 62.9 | 99.7 | | |\n| $DMS-SSIM$ | 71.7 | 108.9 | | |\n| $MS-SSIM$ | 69.8 | 104.4 | | |\n| $L_{SA}+L_{SC}$ | Not converge | | | |\n| 1 | 71.9 | 110.0 | | |\n| 2 | 70.6 | 112.9 | | |\n| 3 | 71.6 | 110.2 | | |\n| 4 | 69.9 | 109.2 | | |\n| 5 | 69.6 | 105.5 | | |\n\n\n\n## Learning Objective\n\n| | MAE | RMSE | PSNR | SSIM | Params(M) |\n| -------------------------------- | ---: | ---: | ---: | ---: | --------: |\n| Density Map | | | | | 23.45 |\n| Density Map + Soft Attention Map | | | | | 23.53 |\n| Density Map + Hard Attention Map | | | | | 23.53 |\n\n\n\n"
},
{
"alpha_fraction": 0.5052038431167603,
"alphanum_fraction": 0.5442324280738831,
"avg_line_length": 41.72222137451172,
"blob_id": "87dc5d800af8547b57c65e88ecbf0df46308bd53",
"content_id": "b127ab7fa8ae350c5abfe4f6eb4add5661135066",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2306,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 54,
"path": "/modeling/sanet.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch.nn.functional as F\n\ndef ConvINReLU(cfg, in_planes):\n layers = []\n for c in cfg:\n if len(c)==2:\n plane, k = c\n layers += [nn.Conv2d(in_planes, plane, k, padding=(k-1)//2), nn.InstanceNorm(plane, affine=True), nn.ReLU(True)]\n in_planes = plane\n if len(c)==1:\n # im not sure \n layers += [nn.ConvTranspose2d(in_planes, in_planes, 2, stride=2), nn.InstanceNorm(in_planes, affine=True), nn.ReLU(True)]\n return nn.Sequential(*layers)\n\n\nclass SAModule(nn.Module):\n def __init__(self, reduc, in_planes, out_planes):\n super(self, SAModule).__init__()\n # if there is reduction \n self.reduc = reduc\n sub_planes = out_planes // 4\n self.branch1 = nn.Sequential(nn.Conv2d(in_planes, sub_planes, 1), nn.ReLU(True))\n if self.reduc:\n self.branch2 = ConvINReLU(((in_planes // 2, 1), (sub_planes, 3)),in_planes)\n self.branch3 = ConvINReLU(((in_planes // 2, 1), (sub_planes, 5)),in_planes)\n self.branch4 = ConvINReLU(((in_planes // 2, 1), (sub_planes, 7)),in_planes)\n else:\n self.branch2 = ConvINReLU(((sub_planes, 3)),in_planes)\n self.branch3 = ConvINReLU(((sub_planes, 5)),in_planes)\n self.branch4 = ConvINReLU(((sub_planes, 7)),in_planes)\n def forward(self, x):\n out1 = self.branch1(x)\n out2 = self.branch2(x)\n out3 = self.branch3(x)\n out4 = self.branch4(x)\n out = torch.cat([out1, out2, out3, out4], 1)\n return out\n\n\nclass SANet(nn.Module):\n def __init__(self):\n super(self, SANet).__init__()\n #first\n self.encoder = nn.Sequential(SAModule(False, 3, 64), nn.MaxPool2d(kernel_size=2, stride=2),\n SAModule(True, 64, 128), nn.MaxPool2d(kernel_size=2, stride=2),\n SAModule(True, 128, 128), nn.MaxPool2d(kernel_size=2, stride=2),\n SAModule(True, 128, 64))\n self.decoder_cfg = ([64, 9], [T], [32, 7], [T], [16, 5], [T], [16, 3], [16, 5], [1, 1])\n self.decoder = ConvINReLU(cfg=self.decoder_cfg, in_planes=64)\n def forward(self, x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x"
},
{
"alpha_fraction": 0.5400893688201904,
"alphanum_fraction": 0.5718316435813904,
"avg_line_length": 30.92481231689453,
"blob_id": "2bfa57d5b2f86e173cc35fb0cbb6d57ad7747110",
"content_id": "7044c7b948db76df1cbfff45f11b46a840366799",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4253,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 133,
"path": "/modeling/Res50_C3.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch\nfrom torchvision import models\n\nfrom .utils import *\n\nimport torch.nn.functional as F\n\n\ndef initialize_weights(models):\n for model in models:\n real_init_weights(model)\n\n\ndef real_init_weights(m):\n\n if isinstance(m, list):\n for mini_m in m:\n real_init_weights(mini_m)\n else:\n if isinstance(m, nn.Conv2d): \n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0.0, std=0.01)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m,nn.Module):\n for mini_m in m.children():\n real_init_weights(mini_m)\n else:\n print( m )\n\n\nclass Res50(nn.Module):\n def __init__(self, pretrained=True, bn=True):\n super(Res50, self).__init__()\n self.bk1 = make_layers([512,512,512], in_channels=1024, dilation=True, batch_norm=False)\n self.bk2 = conv_act(512, 256, 3, same_padding=True, NL='relu', dilation=2, bn=False)\n self.bk3 = conv_act(256, 128, 3, same_padding=True, NL='relu', dilation=2, bn=False)\n self.output_layer = conv_act(128, 1, 1, same_padding=True, NL='relu', bn=False)\n '''\n self.de_pred = nn.Sequential(conv_act(1024, 128, 1, same_padding=True, NL='relu'),\n conv_act(128, 1, 1, same_padding=True, NL='relu'))\n '''\n initialize_weights(self.modules())\n\n res = models.resnet50(pretrained=True)\n #res.load_state_dict(torch.load(\"/home/datamining/Models/resnet50-19c8e357.pth\"))\n \n self.frontend = nn.Sequential(\n res.conv1, res.bn1, res.relu, res.maxpool, res.layer1, res.layer2\n )\n self.own_reslayer_3 = make_res_layer(Bottleneck, 256, 6, stride=1) \n self.own_reslayer_3.load_state_dict(res.layer3.state_dict())\n\n def forward(self,x_in):\n \n x = self.frontend(x_in)\n\n x = self.own_reslayer_3(x) #1/8\n \n x = F.interpolate(x,scale_factor=2)\n #x = self.de_pred(x)\n x = self.bk1(x) #1/4\n x = F.interpolate(x,scale_factor=2)\n x = self.bk2(x) #1/2\n \n x = F.interpolate(x,size=x_in.shape[2:]) # input size\n x = self.bk3(x)\n x = self.output_layer(x)\n return x \n\n\ndef make_res_layer(block, planes, blocks, stride=1):\n\n downsample = None\n inplanes=512\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(inplanes, planes, stride, downsample))\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(inplanes, planes))\n\n return nn.Sequential(*layers) \n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out "
},
{
"alpha_fraction": 0.47611919045448303,
"alphanum_fraction": 0.5265758633613586,
"avg_line_length": 42.64706039428711,
"blob_id": "8ebb65d5c2ccadb406a11ecc8af5302ad27932cb",
"content_id": "46931aa969996aeb3196db41fe368d4b0e74c656",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6679,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 153,
"path": "/modeling/u_vgg.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom .utils import *\n\n\nclass U_VGG(nn.Module):\n def __init__(self, load_model='', downsample=1, bn=False, NL='swish', objective='dmp', sp=False, se=True, pyramid=''):\n super(U_VGG, self).__init__()\n self.downsample = downsample\n self.bn = bn\n self.NL = NL\n self.objective = objective\n self.pyramid = pyramid\n self.front0 = make_layers([64, 64], in_channels=3, batch_norm=bn, NL=self.NL)\n self.front1 = make_layers(['M', 128, 128], in_channels=64, batch_norm=bn, NL=self.NL)\n self.front2 = make_layers(['M', 256, 256, 256], in_channels=128, batch_norm=bn, NL=self.NL)\n self.front3 = make_layers(['M', 512, 512, 512], in_channels=256, batch_norm=bn, NL=self.NL)\n self.sp = sp\n if sp:\n print('use sp module')\n self.sp_module = SPModule(512)\n # basic cfg for backend is [512, 512, 256, 128, 64, 64]\n if not self.pyramid:\n self.backconv0 = make_layers([512, 512, 256], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv1 = make_layers([128], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv2 = make_layers([64], in_channels=256, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv3 = make_layers([64], in_channels=128, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n \n elif self.pyramid == 'dilation':\n print('use dilation pyramid in backend')\n self.backconv0 = nn.Sequential(DilationPyramid(512, 128), DilationPyramid(512, 128), DilationPyramid(512, 128))\n self.backconv1 = nn.Sequential(DilationPyramid(512, 64))\n self.backconv2 = nn.Sequential(DilationPyramid(256, 32))\n self.backconv3 = nn.Sequential(DilationPyramid(128, 16))\n \n elif self.pyramid == 'size':\n print('use size pyramid in backend')\n self.backconv0 = nn.Sequential(SizePyramid(512, 128), SizePyramid(512, 128), SizePyramid(512, 128))\n self.backconv1 = nn.Sequential(SizePyramid(512, 64))\n self.backconv2 = nn.Sequential(SizePyramid(256, 32))\n self.backconv3 = nn.Sequential(SizePyramid(128, 16))\n \n elif self.pyramid == 'depth':\n print('use depth pyramid in backend')\n self.backconv0 = nn.Sequential(DepthPyramid(512, 128), DepthPyramid(512, 128), DepthPyramid(512, 128))\n self.backconv1 = nn.Sequential(DepthPyramid(512, 64))\n self.backconv2 = nn.Sequential(DepthPyramid(256, 32))\n self.backconv3 = nn.Sequential(DepthPyramid(128, 16))\n \n # objective is density map(dmp) and (binary) attention map(amp)\n if self.objective == 'dmp+amp':\n print('objective dmp+amp!')\n self.amp_process = make_layers([64,64], in_channels=64, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.amp_layer = nn.Conv2d(64, 1, kernel_size=1)\n self.sgm = nn.Sigmoid()\n elif self.objective == 'dmp':\n print('objective dmp')\n else:\n raise Exception('objective must in [dmp, dmp+amp]')\n self.output_layer = nn.Conv2d(64, 1, kernel_size=1)\n self.load_model = load_model\n #self._init_weights()\n self._random_init_weights()\n\n def forward(self, x_in):\n x1 = self.front0(x_in)#1 size, 64\n x2 = self.front1(x1)#1/2 size, 128\n x3 = self.front2(x2)#1/4 size, 256\n x4 = self.front3(x3)#1/8 size, 512\n \n if self.sp:\n x4 = self.sp_module(x4)\n \n x = self.backconv0(x4) #1/8 size, 512\n \n x = F.interpolate(x, size=[s//4 for s in x_in.shape[2:]]) #1/4 size, 256\n \n x = torch.cat([x3, x], dim=1) #1/4 size,\n x = self.backconv1(x) #1/4 size, \n \n x = F.interpolate(x, size=[s//2 for s in x_in.shape[2:]]) #1/2 size, \n \n x = torch.cat([x2, x], dim=1) #1/2 size, \n x = self.backconv2(x) #1/2 size, \n \n x = F.interpolate(x, size=x_in.shape[2:]) #1 size, \n \n x = torch.cat([x1, x], dim=1) #1 size, \n x = self.backconv3(x) #1 size, 64\n \n if self.objective == 'dmp+amp':\n dmp = self.output_layer(x)\n amp = self.amp_layer(self.amp_process(x))\n amp = self.sgm(amp)\n dmp = amp * dmp\n del x\n dmp = torch.abs(dmp)\n return dmp, amp\n else:\n x = self.output_layer(x)\n x = torch.abs(x)\n return x\n\n def _random_init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _init_weights(self):\n if not self.load_model:\n pretrained_dict = dict()\n model_dict = self.state_dict()\n path = \"/home/datamining/Models/vgg16_bn-6c64b313.pth\" if self.bn else '/home/datamining/Models/vgg16-397923af.pth'\n pretrained_model = torch.load(path)\n self._random_init_weights()\n # load the pretrained vgg16 parameters\n \n for i, (k, v) in enumerate(pretrained_model.items()):\n #print(i, k)\n \n if i < 4:\n layer_id = 0\n module_id = k.split('.')[-2]\n elif i < 8:\n layer_id = 1\n module_id = int(k.split('.')[-2]) - 4\n elif i < 14:\n layer_id = 2\n module_id = int(k.split('.')[-2]) - 9\n elif i < 20:\n layer_id = 3\n module_id = int(k.split('.')[-2]) - 16\n else:\n break\n k = 'front' + str(layer_id) + '.' + str(module_id) + '.' + k.split('.')[-1]\n \n if k in model_dict and model_dict[k].size() == v.size():\n print(k, ' parameters loaded!')\n pretrained_dict[k] = v\n \n print(path, 'weights loaded!')\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n else:\n self.load_state_dict(torch.load(self.load_model))\n print(self.load_model,' loaded!')\n\n"
},
{
"alpha_fraction": 0.5903072357177734,
"alphanum_fraction": 0.6041178107261658,
"avg_line_length": 53.98257827758789,
"blob_id": "9798489f6e29d31d759f2476cc8021f10c57cc63",
"content_id": "4fc1ead4fb4608ef295caa3cc23f215d9ecc1f3b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15785,
"license_type": "no_license",
"max_line_length": 516,
"num_lines": 287,
"path": "/train_generic.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch\nimport torchvision\nimport torch.nn as nn\nimport os\nimport glob\nfrom modeling import *\nimport torchvision.transforms as transforms\nfrom torch.optim import lr_scheduler\nfrom dataset import *\nimport torch.nn.functional as F\nfrom utils.functions import *\nfrom utils import pytorch_ssim\nimport argparse\nfrom tqdm import tqdm\nfrom datasets.crowd import Crowd\nfrom losses.bay_loss import Bay_Loss\nfrom losses.post_prob import Post_Prob\n\n\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])\n\n\ndef get_loader(train_path, test_path, downsample_ratio, args):\n train_img_paths = []\n for img_path in glob.glob(os.path.join(train_path, '*.jpg')):\n train_img_paths.append(img_path)\n bg_img_paths = []\n for bg_img_path in glob.glob(os.path.join('/home/datamining/Datasets/CrowdCounting/bg/', '*.jpg')):\n bg_img_paths.append(bg_img_path)\n if args.use_bg:\n train_img_paths += bg_img_paths\n test_img_paths = []\n for img_path in glob.glob(os.path.join(test_path, '*.jpg')):\n test_img_paths.append(img_path)\n \n if args.loss=='bayes':\n bayes_dataset = Crowd(train_path, args.crop_size, downsample_ratio, False, 'train')\n train_loader = torch.utils.data.DataLoader(bayes_dataset, collate_fn=bayes_collate, batch_size=args.bs, shuffle=True, num_workers=8, pin_memory=True)\n test_loader = torch.utils.data.DataLoader(Crowd(test_path, args.crop_size, downsample_ratio, False, 'val'),batch_size=1, num_workers=8, pin_memory=True)\n elif args.bn>0:\n bn_dataset=PatchSet(train_img_paths, transform, c_size=(args.crop_size,args.crop_size), crop_n=args.random_crop_n)\n train_loader = torch.utils.data.DataLoader(bn_dataset, collate_fn=my_collate_fn, shuffle=True, batch_size=args.bs, num_workers=8, pin_memory=True)\n test_loader = torch.utils.data.DataLoader(RawDataset(test_img_paths, transform, mode='one', downsample_ratio=downsample_ratio, test=True), shuffle=False, batch_size=1, pin_memory=True)\n else:\n single_dataset=RawDataset(train_img_paths, transform, args.crop_mode, downsample_ratio, args.crop_scale)\n train_loader = torch.utils.data.DataLoader(single_dataset, shuffle=True, batch_size=1, num_workers=8, pin_memory=True)\n test_loader = torch.utils.data.DataLoader(RawDataset(test_img_paths, transform, mode='one', downsample_ratio=downsample_ratio, test=True), shuffle=False, batch_size=1, pin_memory=True)\n \n return train_loader, test_loader, train_img_paths, test_img_paths\n\n\ndef main(args):\n # use gpu\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n cur_device=torch.device('cuda:{}'.format(args.gpu))\n if args.loss=='bayes':\n root = '/home/datamining/Datasets/CrowdCounting/sha_bayes_512/'\n train_path = root+'train/'\n test_path = root+'test/'\n elif args.bn:\n root = '/home/datamining/Datasets/CrowdCounting/sha_512_a/'\n train_path = root+'train/'\n test_path = root+'test/'\n else:\n if args.dataset=='sha':\n root = '/home/datamining/Datasets/CrowdCounting/shanghaitech/part_A_final/'\n train_path = root+'train_data/images'\n test_path = root+'test_data/images/'\n elif args.dataset=='shb':\n root = '/home/datamining/Datasets/CrowdCounting/shb_1024_f15/'\n train_path = root+'train/'\n test_path = root+'test/'\n elif args.dataset =='qnrf':\n root = '/home/datamining/Datasets/CrowdCounting/qnrf_1024_a/'\n train_path = root+'train/'\n test_path = root+'test/'\n \n downsample_ratio = args.downsample\n train_loader, test_loader, train_img_paths, test_img_paths = get_loader(train_path, test_path, downsample_ratio, args)\n \n model_dict = {'VGG16_13': M_CSRNet, 'DefCcNet':DefCcNet, 'Res50_back3':Res50, 'InceptionV3':Inception3CC, 'CAN':CANNet}\n model_name = args.model\n dataset_name = args.dataset\n net = model_dict[model_name](downsample=args.downsample, bn=args.bn>0, objective=args.objective, sp=(args.sp>0),se=(args.se>0),NL=args.nl)\n net.cuda()\n if args.bn>0:\n save_name = '{}_{}_{}_bn{}_ps{}_{}'.format(model_name, dataset_name, str(int(args.bn)), str(args.crop_size),args.loss)\n else:\n save_name = '{}_d{}{}{}{}{}_{}_{}_cr{}_{}{}{}{}{}{}'.format(model_name, str(args.downsample), '_sp' if args.sp else '', '_se' if args.se else '', '_'+args.nl if args.nl!='relu' else '', '_vp' if args.val_patch else '', dataset_name, args.crop_mode, str(args.crop_scale), args.loss, '_wu' if args.warm_up else '', '_cl' if args.curriculum=='W' else '', '_v'+str(int(args.value_factor)) if args.value_factor!=1 else '', '_amp'+str(args.amp_k) if args.objective=='dmp+amp' else '', '_bg' if args.use_bg else '')\n save_path = \"/home/datamining/Models/CrowdCounting/\"+save_name+\".pth\"\n logger = get_logger('logs/'+save_name+'.txt')\n for k, v in args.__dict__.items(): # save args\n logger.info(\"{}: {}\".format(k, v))\n if os.path.exists(save_path) and args.resume:\n net.load_state_dict(torch.load(save_path))\n print('{} loaded!'.format(save_path))\n \n value_factor=args.value_factor\n freq = 100\n \n if args.optimizer == 'Adam':\n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.decay)\n elif args.optimizer == 'SGD':\n # not converage\n optimizer=torch.optim.SGD(net.parameters(),lr=args.lr, momentum=0.95, weight_decay=args.decay)\n \n if args.loss=='bayes':\n bayes_criterion=Bay_Loss(True, cur_device)\n post_prob=Post_Prob(sigma=8.0,c_size=args.crop_size,stride=1,background_ratio=0.15,use_background=True,device=cur_device)\n else:\n mse_criterion = nn.MSELoss().cuda()\n \n if args.scheduler == 'plt':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.9,patience=10, verbose=True)\n elif args.scheduler == 'cos':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer,T_max=50,eta_min=0)\n elif args.scheduler == 'step':\n scheduler = lr_scheduler.StepLR(optimizer,step_size=100, gamma=0.8)\n elif args.scheduler == 'exp':\n scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=0.99)\n elif args.scheduler == 'cyclic' and args.optimizer == 'SGD':\n scheduler = lr_scheduler.CyclicLR(optimizer, base_lr=args.lr*0.01, max_lr=args.lr, step_size_up=25,)\n elif args.scheduler == 'None':\n scheduler = None\n else:\n print('scheduler name error!')\n \n if args.val_patch:\n best_mae, best_rmse = val_patch(net, test_loader, value_factor)\n elif args.loss=='bayes':\n best_mae, best_rmse = val_bayes(net, test_loader, value_factor)\n else:\n best_mae, best_rmse = val(net, test_loader, value_factor)\n if args.scheduler=='plt':\n scheduler.step(best_mae)\n ssim_loss = pytorch_ssim.SSIM(window_size=11)\n for epoch in range(args.epochs):\n if args.crop_mode == 'curriculum':\n # every 20%, change the dataset\n if (epoch+1) % (args.epochs//5) == 0:\n print('change dataset')\n single_dataset = RawDataset(train_img_paths, transform, args.crop_mode, downsample_ratio, args.crop_scale, (epoch+1.0+args.epochs//5)/args.epochs)\n train_loader = torch.utils.data.DataLoader(single_dataset, shuffle=True, batch_size=1, num_workers=8)\n \n train_loss = 0.0\n if args.loss=='bayes':\n epoch_mae = AverageMeter()\n epoch_mse = AverageMeter()\n net.train()\n if args.warm_up and epoch < args.warm_up_steps:\n linear_warm_up_lr(optimizer, epoch, args.warm_up_steps,args.lr)\n for it, data in enumerate(train_loader):\n if args.loss == 'bayes':\n inputs, points, targets, st_sizes=data\n img = inputs.to(cur_device)\n st_sizes = st_sizes.to(cur_device)\n gd_count = np.array([len(p) for p in points], dtype=np.float32)\n points = [p.to(cur_device) for p in points]\n targets = [t.to(cur_device) for t in targets]\n else:\n img, target, _, amp_gt = data\n img = img.cuda()\n target = value_factor*target.float().unsqueeze(1).cuda()\n amp_gt = amp_gt.cuda()\n #print(img.shape)\n optimizer.zero_grad()\n \n #print(target.shape)\n if args.objective == 'dmp+amp':\n output, amp = net(img)\n output = output * amp\n else:\n output = net(img)\n \n if args.curriculum == 'W':\n delta = (output - target)**2\n k_w = 2e-3 * args.value_factor * args.downsample**2\n b_w = 5e-3 * args.value_factor * args.downsample**2\n T = torch.ones_like(target,dtype=torch.float32) * epoch * k_w + b_w\n W = T / torch.max(T,output)\n delta = delta * W\n mse_loss = torch.mean(delta)\n else:\n mse_loss = mse_criterion(output, target)\n \n if args.loss == 'mse+lc':\n loss = mse_loss + 1e2 * cal_lc_loss(output, target) * args.downsample\n elif args.loss == 'ssim':\n loss = 1 - ssim_loss(output, target)\n elif args.loss == 'mse+ssim':\n loss = 100 * mse_loss + 1e-2*(1-ssim_loss(output,target))\n elif args.loss == 'mse+la':\n loss = mse_loss + cal_spatial_abstraction_loss(output, target)\n elif args.loss == 'la':\n loss = cal_spatial_abstraction_loss(output, target)\n elif args.loss == 'ms-ssim':\n #to do\n pass\n elif args.loss == 'adversial':\n # to do \n pass\n elif args.loss == 'bayes':\n prob_list = post_prob(points, st_sizes)\n loss = bayes_criterion(prob_list, targets, output)\n else:\n loss = mse_loss\n \n # add the cross entropy loss for attention map\n if args.objective == 'dmp+amp':\n cross_entropy = (amp_gt * torch.log(amp) + (1 - amp_gt) * torch.log(1 - amp)) * -1\n cross_entropy_loss = torch.mean(cross_entropy)\n loss = loss + cross_entropy_loss * args.amp_k\n \n loss.backward()\n optimizer.step()\n data_loss = loss.item()\n train_loss += data_loss\n if args.loss=='bayes':\n N = inputs.size(0)\n pre_count = torch.sum(output.view(N, -1), dim=1).detach().cpu().numpy()\n res = pre_count - gd_count\n epoch_mse.update(np.mean(res * res), N)\n epoch_mae.update(np.mean(abs(res)), N)\n \n if args.loss!='bayes' and it%freq==0:\n print('[ep:{}], [it:{}], [loss:{:.8f}], [output:{:.2f}, target:{:.2f}]'.format(epoch+1, it, data_loss, output[0].sum().item(), target[0].sum().item()))\n if args.val_patch:\n mae, rmse = val_patch(net, test_loader, value_factor)\n elif args.loss=='bayes':\n mae, rmse = val_bayes(net, test_loader, value_factor)\n else:\n mae, rmse = val(net, test_loader, value_factor)\n if not (args.warm_up and epoch<args.warm_up_steps):\n if args.scheduler == 'plt':\n scheduler.step(best_mae)\n elif args.scheduler != 'None':\n scheduler.step()\n \n if mae + 0.1 * rmse < best_mae + 0.1 * best_rmse:\n best_mae, best_rmse = mae, rmse\n torch.save(net.state_dict(), save_path)\n \n if args.loss=='bayes':\n logger.info('{} Epoch {}/{} Loss:{:.8f},MAE:{:.2f},RMSE:{:.2f} lr:{:.8f}, [CUR]:{mae:.1f}, {rmse:.1f}, [Best]:{b_mae:.1f}, {b_rmse:.1f}'.format(model_name, epoch+1, args.epochs, train_loss/len(train_loader),epoch_mae.get_avg(), np.sqrt(epoch_mse.get_avg()),optimizer.param_groups[0]['lr'], mae=mae, rmse=rmse, b_mae=best_mae, b_rmse=best_rmse))\n else:\n logger.info('{} Epoch {}/{} Loss:{:.8f}, lr:{:.8f}, [CUR]:{mae:.1f}, {rmse:.1f}, [Best]:{b_mae:.1f}, {b_rmse:.1f}'.format(model_name, epoch+1, args.epochs, train_loss/len(train_loader), optimizer.param_groups[0]['lr'], mae=mae, rmse=rmse, b_mae=best_mae, b_rmse=best_rmse))\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch Crowd Counting')\n parser.add_argument('--model', metavar='model name', default='VGG16_13', choices=['VGG16_13', 'DefCcNet', 'InceptionV3', 'CAN', 'Res50_back3'], type=str)\n parser.add_argument('--downsample', metavar='downsample ratio', default=1, choices=[1, 2, 4, 8], type=int)\n parser.add_argument('--dataset', metavar='dataset name', default='sha', choices=['sha','shb','qnrf'], type=str)\n parser.add_argument('--resume', metavar='resume model if exists', default=0, type=int)\n parser.add_argument('--lr', type=float, default=1e-5, help='the initial learning rate')\n parser.add_argument('--gpu', default='0', help='assign device')\n parser.add_argument('--scheduler', default='plt', help='lr scheduler', choices=['plt', 'cos', 'step', 'cyclic', 'exp', 'None'], type=str)\n parser.add_argument('--optimizer', default='Adam', help='optimizer', choices=['Adam','SGD'], type=str)\n parser.add_argument('--decay', default=1e-4, help='weight decay', type=float)\n parser.add_argument('--epochs', default=200, type=int)\n \n parser.add_argument('--loss', default='mse', choices=['mse','mse+lc','ssim','mse+ssim','mse+la','la','ms-ssim','bayes','adversial'])\n parser.add_argument('--val_patch', metavar='val on patch if set to True', default=0, choices=[0,1], type=int)\n \n parser.add_argument('--crop_mode', default='random', choices=['random', 'one', 'fixed+random', 'fixed', 'mixed', 'curriculum'], type=str)\n parser.add_argument('--crop_scale', metavar='patch scale, work when not using batch norm or bayes', default=0.5, type=float)\n parser.add_argument('--crop_size', default=256, help='the size of cropping from original images. Work when using batch norm or bayes', type=int)\n \n parser.add_argument('--warm_up', default=0, help='warm up from 0.1*lr to lr by warm up steps', type=int)\n parser.add_argument('--warm_up_steps', default=10, help='warm up steps', type=int)\n \n parser.add_argument('--curriculum', default='None', metavar='curriculum learning', choices=['None','W'])\n parser.add_argument('--value_factor', default=1.0, metavar='value factor * gt', type=float)\n parser.add_argument('--objective', default='dmp', choices=['dmp', 'dmp+amp'], type=str)\n parser.add_argument('--amp_k', default=0.1, help=\"only work when objective is 'dmp+amp'. loss = loss + k * cross_entropy_loss\", type=float)\n parser.add_argument('--use_bg', default=0, help='if using background images(without any person) in training', choices=[0,1], type=int)\n \n parser.add_argument('--bn', default=0, help='if using batch normalization', type=int)\n parser.add_argument('--bs', default=4, help='batch size if using bn', type=int)\n parser.add_argument('--random_crop_n', default=4, metavar='random crop number for each image, only work when using bn', type=int)\n \n parser.add_argument('--sp', default=0, help='spatial pyramid module', type=int)\n parser.add_argument('--se', default=0, help='squeeze excitation module', type=int)\n parser.add_argument('--nl', default='relu', help='non-linear layer', choices=['relu', 'prelu', 'swish'], type=str)\n args = parser.parse_args()\n \n main(args)\n \n"
},
{
"alpha_fraction": 0.5166372060775757,
"alphanum_fraction": 0.5558592081069946,
"avg_line_length": 43.74820327758789,
"blob_id": "6dea1ba6257c081e7d483892aa1b93f9f7b5deb0",
"content_id": "87a39b5f2aeb26b9426a22ac18a9110dd849c0f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6221,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 139,
"path": "/modeling/m_vgg.py",
"repo_name": "rongliangzi/CrowdCountingBaseline",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\nfrom .utils import *\n\n\nclass M_VGG(nn.Module):\n def __init__(self, load_model='', downsample=1, bn=False, NL='swish', objective='dmp', sp=False, se=True, pyramid=''):\n super(M_VGG, self).__init__()\n self.downsample = downsample\n self.bn = bn\n self.NL = NL\n self.objective = objective\n self.pyramid = pyramid\n self.features_cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512]\n self.features = make_layers(self.features_cfg, batch_norm=bn, NL=self.NL)\n self.sp = False\n if sp:\n print('use sp module')\n self.sp = True\n self.sp_module = SPModule(512)\n # basic cfg for backend is [512, 512, 512, 256, 128, 64]\n if not self.pyramid:\n self.backconv0 = make_layers([512, 512, 512], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv1 = make_layers([256], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv2 = make_layers([128], in_channels=256, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv3 = make_layers([64], in_channels=128, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n \n elif self.pyramid == 'dilation':\n print('use dilation pyramid in backend')\n self.backconv0 = nn.Sequential(DilationPyramid(512, 128), DilationPyramid(512, 128))\n self.backconv1 = make_layers([256], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv2 = make_layers([128], in_channels=256, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv3 = make_layers([64], in_channels=128, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n \n elif self.pyramid == 'size':\n print('use size pyramid in backend')\n self.backconv0 = nn.Sequential(SizePyramid(512, 128), SizePyramid(512, 128))\n self.backconv1 = make_layers([256], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv2 = make_layers([128], in_channels=256, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv3 = make_layers([64], in_channels=128, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n \n elif self.pyramid == 'depth':\n print('use depth pyramid in backend')\n self.backconv0 = nn.Sequential(DepthPyramid(512, 128), DepthPyramid(512, 128))\n self.backconv1 = make_layers([256], in_channels=512, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv2 = make_layers([128], in_channels=256, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.backconv3 = make_layers([64], in_channels=128, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n \n # objective is density map(dmp) and (binary) attention map(amp)\n if self.objective == 'dmp+amp':\n print('objective dmp+amp!')\n self.amp_process = make_layers([64,64], in_channels=64, dilation=True, batch_norm=bn, NL=self.NL, se=se)\n self.amp_layer = nn.Conv2d(64, 1, kernel_size=1)\n self.sgm = nn.Sigmoid()\n elif self.objective == 'dmp':\n print('objective dmp')\n else:\n raise Exception('objective must in [dmp, dmp+amp]')\n self.output_layer = nn.Conv2d(64, 1, kernel_size=1)\n self.load_model = load_model\n self._init_weights()\n\n def forward(self, x_in):\n x = self.features(x_in)\n \n if self.sp:\n x = self.sp_module(x)\n \n x = self.backconv0(x)\n \n if self.downsample == 8:\n x = F.interpolate(x, size=[s//8 for s in x_in.shape[2:]])\n elif self.downsample<8:\n x = F.interpolate(x, scale_factor=2)\n #\n x = self.backconv1(x)\n \n if self.downsample == 4:\n x = F.interpolate(x, size=[s//4 for s in x_in.shape[2:]])\n elif self.downsample<4:\n x = F.interpolate(x, scale_factor=2)\n #\n x = self.backconv2(x)\n \n if self.downsample == 2:\n x = F.interpolate(x, size=[s//2 for s in x_in.shape[2:]])\n elif self.downsample<2:\n x = F.interpolate(x, scale_factor=2)\n \n x = self.backconv3(x)\n \n if self.downsample == 1:\n x = F.interpolate(x, size=x_in.shape[2:])\n \n if self.objective == 'dmp+amp':\n dmp = self.output_layer(x)\n amp = self.amp_layer(self.amp_process(x))\n amp = self.sgm(amp)\n dmp = amp * dmp\n del x\n dmp = torch.abs(dmp)\n return dmp, amp\n else:\n x = self.output_layer(x)\n x = torch.abs(x)\n return x\n\n def _random_init_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.normal_(m.weight, std=0.01)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _init_weights(self):\n if not self.load_model:\n pretrained_dict = dict()\n model_dict = self.state_dict()\n path = \"/home/datamining/Models/vgg16_bn-6c64b313.pth\" if self.bn else '/home/datamining/Models/vgg16-397923af.pth'\n pretrained_model = torch.load(path)\n \n self._random_init_weights()\n # load the pretrained vgg16 parameters\n for k, v in pretrained_model.items():\n if k in model_dict and model_dict[k].size() == v.size():\n pretrained_dict[k] = v\n print(k, ' parameters loaded!')\n \n print(path, 'weights loaded!')\n model_dict.update(pretrained_dict)\n self.load_state_dict(model_dict)\n else:\n self.load_state_dict(torch.load(self.load_model))\n print(self.load_model,' loaded!')\n\n"
}
] | 10 |
kvnlnt/native-demo | https://github.com/kvnlnt/native-demo | fc2ad7713c7d28e32e79c6e6e5f28227cb8d4ee0 | bf171fb7b4c2ecc871d779a3ee222302581c5b3b | d59dfd29cbe779c6e04c5d6428ff96976fdb4265 | refs/heads/master | 2021-01-19T00:44:30.414225 | 2015-04-22T17:08:09 | 2015-04-22T17:08:09 | 34,403,029 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4958159029483795,
"alphanum_fraction": 0.508368194103241,
"avg_line_length": 18.15999984741211,
"blob_id": "1a4d9f36334ef641b78cdae147a0919f3ffe77b2",
"content_id": "e1440eab239ec9fcef4df53866b714111e88ac82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 478,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 25,
"path": "/tests/specs/utilities-spec.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "describe(\"utilities:debounce\", function() {\n\n // params\n var value = 0;\n var adder = function(done){ value += 1; done(); };\n var debouncer = flowroute.util.debounce(adder, 100);\n\n // before\n beforeEach(function(done) {\n\n debouncer(done);\n debouncer(done);\n debouncer(done);\n\n });\n\n // setup\n it(\"should support async \", \n function(done) {\n expect(value).toBe(1);\n done();\n }\n );\n\n});"
},
{
"alpha_fraction": 0.6468468308448792,
"alphanum_fraction": 0.6558558344841003,
"avg_line_length": 24.272727966308594,
"blob_id": "acb60705b7f7aad1b7c1bf26376d67829c7bd146",
"content_id": "3d727a1e0bede6d2417c4ad7deb59893605c90bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 555,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 22,
"path": "/www/static/scripts/scripts.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/** \n * flowroute is the global default namespace all modules should be attached to and accessed by. \n * @example\n * // Access the menu module's DOM elements\n * flowroute.menu.el;\n * @type {Object}\n * \n */\nvar flowroute = {};\n\n// GLOBAL JSDOCS MARKUP\n\n/**\n * @name 1. External Docs\n * @global\n * @description \n * <ul>\n * <li>{@link http://localhost:9000/build/html|Backend} : Backend documentation</li>\n * <li>{@link http://zeptojs.com|zepto} : DOM manipulation tool</li>\n * <li>{@link http://modernizr.com|modernizr} : Feature detection</li>\n * </ul>\n */"
},
{
"alpha_fraction": 0.46346554160118103,
"alphanum_fraction": 0.46346554160118103,
"avg_line_length": 22.899999618530273,
"blob_id": "938788a11a444138fb224cde28f9655a3c31bff4",
"content_id": "533d2d7c9d0cd5599cea514ac282ddd10390b37f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 20,
"path": "/tasks/options/sass.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "module.exports = {\n app_files: {\n options: {\n style: 'compressed',\n sourcemap:'file',\n },\n files: {\n 'www/static/assets/styles.min.css': 'www/static/styles/styles.scss'\n }\n },\n vendor_files: {\n options: {\n style: 'compressed',\n sourcemap:'file',\n },\n files: {\n 'www/static/assets/vendor.min.css': 'www/static/vendor/styles/vendor.scss'\n }\n }\n}\n\n"
},
{
"alpha_fraction": 0.5116279125213623,
"alphanum_fraction": 0.6744186282157898,
"avg_line_length": 9.875,
"blob_id": "1fdcbe53aa1a6c51be647ff74b48a054f1759bec",
"content_id": "c00afb1d1779b4ce480be089a4683c64c317cd0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 8,
"path": "/requirements.txt",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "Flask==0.10.1\n\n# Extensions\nFlask-Script==2.0.5\nJinja2==2.7.3\n\n# Testing\npytest==2.6.0"
},
{
"alpha_fraction": 0.49872124195098877,
"alphanum_fraction": 0.5191816091537476,
"avg_line_length": 27,
"blob_id": "040416a74018c307d418b0a7a17075489f486068",
"content_id": "31f704aedbf3f4f4a96c463f897ae7766a50a627",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 391,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 14,
"path": "/tasks/options/connect.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "module.exports = {\n docs: {\n options: {\n port: 9000,\n base: 'docs',\n keepalive:true,\n open:{\n target: 'http://localhost:9000/build/html', // target url to open\n appName: 'Google Chrome', // name of the app that opens, ie: open, start, xdg-open\n callback: function() {} // called when the app has opened\n }\n }\n }\n}"
},
{
"alpha_fraction": 0.6033434867858887,
"alphanum_fraction": 0.6063829660415649,
"avg_line_length": 27.65217399597168,
"blob_id": "6b7d07d331554e157474cff6be1db3eb0781672d",
"content_id": "df431225675bfd2e9be65dc94b0be5443c539954",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 658,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 23,
"path": "/tests/specs/images-spec.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "describe(\"images\", function() {\n\n // params\n var image_1;\n var image_2;\n\n // setup\n beforeEach(function() {\n naked_directive = new flowroute.images.degrade_svg('<img src=\"test.svg\" fr-image/>');\n paramd_directive = new flowroute.images.degrade_svg('<img src=\"test.svg\" fr-image=\"random.jpg\"/>');\n });\n\n // assertions\n it(\"Replaces src with png version automatically\", function() {\n expect(naked_directive.$el.attr('src')).toBe('test.png');\n });\n\n // assertions\n it(\"Replaces src with specified file version\", function() {\n expect(paramd_directive.$el.attr('src')).toBe('random.jpg');\n });\n\n});"
},
{
"alpha_fraction": 0.3553299605846405,
"alphanum_fraction": 0.4568527936935425,
"avg_line_length": 18.799999237060547,
"blob_id": "29eac4980a2cad9b4e1964677dc552d3a1e78dce",
"content_id": "b3169087c0ce7244e70c47d17e3cca1d435c02e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 197,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 10,
"path": "/tasks/options/open.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "module.exports = {\n dev: {\n path: 'http://127.0.0.1:5000',\n app: 'Google Chrome'\n },\n docs: {\n path: 'http://127.0.0.1:9000/docs',\n app: 'Google Chrome'\n }\n}"
},
{
"alpha_fraction": 0.5335990786552429,
"alphanum_fraction": 0.535876989364624,
"avg_line_length": 19.91666603088379,
"blob_id": "47965aef314334ec57ae3a4d523d47cad8eb03db",
"content_id": "66b68b422c415d32ecb248fcfa5342f4f42ccab1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1756,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 84,
"path": "/www/static/scripts/patterns/toggle.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/**\n* Toggle directive\n* @module toggle\n* @version 1.0\n* @example USAGE\n* // shows result on click\n* <a fr-toggle=\"showme\">show the hidden content</a>\n* <div id=\"showme\" style=\"display:none;\">I'm currently hidden</div>\n*/\n\nflowroute.toggle = (function(module){\n\n \"use strict\";\n\n /** @exports toggle */\n\n /**\n * DOM elements\n * @memberOf module:toggle\n */\n module.directive = 'fr-toggle';\n\n /**\n * Container for all registered elements\n * @memberOf module:toggle\n */\n module.elements = [];\n\n /**\n * Toggle function\n * @memberOf module:toggle\n * @param {Object} element - click event\n */\n module.toggle = function(el, target){\n\n // set element\n var that = this;\n this.el = el;\n this.$el = $(el);\n this.target = target || $('#'+this.$el.attr(module.directive));\n this.$target = $(this.target);\n\n // toggle target on el click\n this.$el.on('click', function(e){\n that.$target.toggleClass('show');\n that.$el.find('i').toggleClass('fa-rotate-90');\n });\n\n // return func\n return this;\n\n };\n\n /**\n * Helper iterate function\n * @memberOf module:toggle\n * @param {number} k key or index\n * @param {object} v value\n */\n module.each = function(k, v){\n\n module.elements.push(new module.toggle(v));\n return this;\n\n };\n\n /**\n * Initialize module\n * @memberOf module:toggle\n */\n module.init = function(){\n \n // register each element\n $('['+module.directive+']').each(module.each);\n\n };\n\n // boot file\n $(document).on('ready', module.init);\n\n // export\n return module;\n\n})(flowroute.toggle || {});"
},
{
"alpha_fraction": 0.6588921546936035,
"alphanum_fraction": 0.6588921546936035,
"avg_line_length": 17.052631378173828,
"blob_id": "fcf680f475ba5e7b8d703408c8fd975a913e37c0",
"content_id": "18f55bc1d009add80ca3beee84a6bbe421e55c17",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 343,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 19,
"path": "/www/settings.py",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "class Config(object):\n DEBUG = False\n SECRET_KEY = 'secret key'\n\n\nclass ProdConfig(Config):\n CACHE_TYPE = 'simple'\n\n\nclass TestConfig(Config):\n DEBUG = True\n DEBUG_TB_INTERCEPT_REDIRECTS = False\n CACHE_TYPE = 'null'\n\n\nclass DevConfig(Config):\n DEBUG = True\n DEBUG_TB_INTERCEPT_REDIRECTS = False\n CACHE_TYPE = 'null'\n"
},
{
"alpha_fraction": 0.5178571343421936,
"alphanum_fraction": 0.5223214030265808,
"avg_line_length": 13.966666221618652,
"blob_id": "944e3418ca2af125b5dcca50d503e65098e197f4",
"content_id": "e51463b99f9ed6d04996539e400e5ae60ae17c54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 448,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 30,
"path": "/www/static/scripts/patterns/api.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/**\n* Command pattern for any backend api calls\n* @module api\n* @version 1.0\n*/\n\nflowroute.api = (function(module){\n\n \"use strict\";\n\n /** @exports api */\n\n /**\n * Initialize module\n * @memberOf module:api\n */\n module.init = function(){\n \n // register wow api\n // $(document)\n\n };\n\n // boot file\n $(document).on('ready', module.init);\n\n // export\n return module;\n\n})(flowroute.api || {});"
},
{
"alpha_fraction": 0.5548628568649292,
"alphanum_fraction": 0.557356595993042,
"avg_line_length": 17.674419403076172,
"blob_id": "3241e214fc0662767852e548410a2c3e0174bb04",
"content_id": "558b59090edf827b1e4ab0f40a623e56500cd7b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 802,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 43,
"path": "/www/static/scripts/patterns/analytics.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/**\n* Command pattern for any backend analytics calls\n* @module analytics\n* @version 1.0\n*/\n\nflowroute.analytics = (function(module){\n\n \"use strict\";\n\n /** @exports analytics */\n\n /**\n * Log event\n * @param {string} type categorical type\n * @param {string} evt event name\n * @param {string} data data to be stored\n * @memberOf module:analytics\n */\n module.log = function(type, evt, data){\n \n // console.log('analytics', type, evt, data);\n\n };\n\n /**\n * Initialize module\n * @memberOf module:analytics\n */\n module.init = function(){\n \n // register wow analytics\n // $(document)\n\n };\n\n // boot file\n $(document).on('ready', module.init);\n\n // export\n return module;\n\n})(flowroute.analytics || {});"
},
{
"alpha_fraction": 0.5655509233474731,
"alphanum_fraction": 0.569037675857544,
"avg_line_length": 21.076923370361328,
"blob_id": "1a574bd70c01ae31b23f806ce1bb305473a569a8",
"content_id": "856bf5f751d2440cd7155b26396de3730173fe97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1434,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 65,
"path": "/www/static/scripts/patterns/viewport.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/**\n* Viewport manager\n* @module viewport\n* @version 1.0\n*/\n\nflowroute.viewport = (function(module){\n\n \"use strict\";\n\n /** @exports viewport */\n\n /**\n * Check if element is in viewport\n * @memberOf module:viewport\n * @param {object} el part object (should be a <section>)\n */\n module.contains_part = function(el, elTop){\n\n // get params\n var part = $(el);\n var part_top = elTop || part.offset().top;\n var in_viewport = part_top >= this.top && part_top <= this.bottom;\n\n return in_viewport;\n\n };\n\n /**\n * Calc and set viewport dimensions and broadcast update event\n * @memberOf module:viewport\n */\n module.set_viewport = function(){\n\n // viewport, height and vertical scroll position\n var viewport = $(window);\n module.height = viewport.height();\n module.top = viewport.scrollTop();\n module.bottom = module.top + module.height;\n\n // publish scroll event\n flowroute.pubsub.publish('VIEWPORT:UPDATE');\n\n return module;\n\n };\n\n /**\n * Initialize\n * @memberOf module:viewport\n */\n module.init = function(){\n\n $(document).on('scroll', flowroute.util.debounce(module.set_viewport, 100));\n module.set_viewport();\n\n };\n\n // boot file\n $(document).on('ready', module.init);\n\n // export\n return module;\n\n})(flowroute.viewport || {});"
},
{
"alpha_fraction": 0.5923009514808655,
"alphanum_fraction": 0.5923009514808655,
"avg_line_length": 19.23008918762207,
"blob_id": "3764214ee9c4e959675838c1a458c8c8f64f3868",
"content_id": "2d7e4f20b752a6b80e0fba231f3163aa149cd238",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2286,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 113,
"path": "/www/controller.py",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "\"\"\"\n:synopsis: Main blueprint router and controller\n\"\"\"\n\nfrom flask import Blueprint, render_template\n\n\nmain = Blueprint('main', __name__, template_folder='templates')\n\n\[email protected]('/')\ndef home():\n \"\"\" home page \"\"\"\n return render_template(\"pages/home.html\")\n\n\[email protected]('/voice')\ndef voice():\n \"\"\" voice page \"\"\"\n return render_template(\n \"pages/voice.html\",\n section=\".voice\",\n has_submenu=False,\n )\n\n\[email protected]('/solutions')\ndef solutions():\n \"\"\" solutions page \"\"\"\n return render_template(\n \"pages/solutions.html\",\n section=\".solutions\",\n has_submenu=True,\n )\n\n\[email protected]('/solutions/unified-communications')\ndef unified_communication():\n \"\"\" unified communications page \"\"\"\n return render_template(\n \"pages/unified-communications.html\",\n section=\".solutions\",\n has_submenu=True,\n )\n\n\[email protected]('/solutions/call-center')\ndef call_center():\n \"\"\" call center page \"\"\"\n return render_template(\n \"pages/call-center.html\",\n section=\".solutions\",\n has_submenu=True,\n )\n\n\[email protected]('/solutions/pbx-and-phone-systems')\ndef pbx_and_phone_systems():\n \"\"\" pbx and phone systems page \"\"\"\n return render_template(\n \"pages/pbx-and-phone-systems.html\",\n section=\".solutions\",\n has_submenu=True,\n )\n\n\[email protected]('/pricing')\ndef pricing():\n \"\"\" pricing page \"\"\"\n return render_template(\n \"pages/pricing.html\",\n section=\".pricing\",\n has_submenu=False,\n )\n\n\[email protected]('/developers')\ndef developers():\n \"\"\" developers page \"\"\"\n return render_template(\n \"pages/developers.html\",\n section=\".developers\",\n has_submenu=False,\n )\n\n\[email protected]('/partners')\ndef partners():\n \"\"\" partners page \"\"\"\n return render_template(\n \"pages/partners.html\",\n section=\".partners\",\n has_submenu=False,\n )\n\n\[email protected]('/patterns')\ndef patterns():\n \"\"\" patterns page \"\"\"\n return render_template(\n \"pages/patterns.html\",\n section=\".patterns\", has_subpage=False\n )\n\n\[email protected]('/login')\ndef login():\n \"\"\" login page \"\"\"\n return render_template(\n \"pages/login.html\",\n section=\".login\",\n has_submenu=False,\n )\n"
},
{
"alpha_fraction": 0.5756241083145142,
"alphanum_fraction": 0.5917767882347107,
"avg_line_length": 24.22222137451172,
"blob_id": "f69f63f4ae1d1cf3822898078b3afd87e3cb2430",
"content_id": "774a5841d4bb2c46ac44fc443c4e33a6b16de856",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1362,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 54,
"path": "/tests/test_controller.py",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "#! ../env/bin/python\n# -*- coding: utf-8 -*-\nfrom www import create_app\n\n\nclass TestController:\n\n def setup(self):\n\n # get app test config\n app = create_app('www.settings.TestConfig', env='dev')\n\n # create test app\n self.app = app.test_client()\n\n def teardown(self):\n\n # destroy session and tables\n print \"done\"\n\n def test_home(self):\n endpoint = '/'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_voice(self):\n endpoint = '/voice'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_solutions(self):\n endpoint = '/solutions'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_pricing(self):\n endpoint = '/pricing'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_developers(self):\n endpoint = '/developers'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_partners(self):\n endpoint = '/partners'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n\n def test_login(self):\n endpoint = '/login'\n response = self.app.get(endpoint)\n assert response.status_code == 200\n"
},
{
"alpha_fraction": 0.6166666746139526,
"alphanum_fraction": 0.643750011920929,
"avg_line_length": 24.157894134521484,
"blob_id": "cb3400217dd90686bd725b5f80993294fcda786b",
"content_id": "08b46b2306fb66c172db05646665146f01c3195f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 480,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 19,
"path": "/docs/source/index.rst",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": ".. flowroute.com documentation master file, created by\n sphinx-quickstart on Wed Nov 12 09:34:43 2014.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nWelcome to flowroute.com's documentation!\n=========================================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* `Frontend Documentation <../../scripts/index.html>`_\n\nAPI\n\n.. toctree::\n :maxdepth: 2\n\n.. automodule:: controller\n :members:\n\n\n"
},
{
"alpha_fraction": 0.5787476301193237,
"alphanum_fraction": 0.5806451439857483,
"avg_line_length": 20.079999923706055,
"blob_id": "2f17fc281afc93a04295010c93484378305c0247",
"content_id": "1d017a3a1bb1b4f444daa09ff6bf75e2a3bf7be4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1054,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 50,
"path": "/www/static/scripts/patterns/pubsub.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "/**\n * Publish/Subscribe module\n * @module pubsub\n * @version 1.0\n * @example USAGE\n * // subscribe handler to event\n * flowroute.pubsub.subscribe(\"/some/topic\", handle);\n * // Unsubscribe handler from event\n * flowroute.pubsub.unsubscribe(\"/some/topic\", handle);\n * // publish event with data\n * flowroute.pubsub.publish(\"/some/topic\", [ \"a\", \"b\", \"c\" ]); \n */\n\nflowroute.pubsub = (function(module) {\n\n \"use strict\";\n\n /** @exports pubsub */\n\n // event object\n module.o = $({});\n\n /**\n * Subscribe to event\n * @memberOf module:pubsub\n */\n module.subscribe = function() {\n module.o.on.apply(module.o, arguments);\n };\n\n /**\n * Unsubscribe to event\n * @memberOf module:pubsub\n */\n module.unsubscribe = function() {\n module.o.off.apply(module.o, arguments);\n };\n\n /**\n * Publish event\n * @memberOf module:pubsub\n */\n module.publish = function() {\n module.o.trigger.apply(module.o, arguments);\n };\n\n // export\n return module;\n\n})(flowroute.pubsub || {});\n"
},
{
"alpha_fraction": 0.49275362491607666,
"alphanum_fraction": 0.49275362491607666,
"avg_line_length": 15,
"blob_id": "0423ff0435a30d7f2e4c257b96dda0f4b95aadfb",
"content_id": "6c5a4f4bacc1086d2391b31c49af7bf308aeb2f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 13,
"path": "/tests/specs/bp.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "// describe(\"boilerplate\", function() {\n\n// // params\n// var params;\n\n// // setup\n// beforeEach(function() {});\n\n// // assertions\n// it(\"should do something\", function() {});\n\n\n// });"
},
{
"alpha_fraction": 0.6622613668441772,
"alphanum_fraction": 0.6622613668441772,
"avg_line_length": 36.88888931274414,
"blob_id": "31d38a71e0a047e93c62b2629a844f87b09ef6be",
"content_id": "f686a0892b8a5067706e2c7ac104cb49c17268c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 681,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 18,
"path": "/tasks/tasks.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "module.exports = function(grunt) {\n\n // main dev task, kill any running servers, starts up new ones, opens up a browser and starts watching scripts and styles\n grunt.registerTask('dev', ['shell:killservers', 'shell:runserver', 'open:dev', 'watch']);\n \n // default grunt task...\n grunt.registerTask('default', 'dev');\n\n // compile all assets\n grunt.registerTask('assets', ['uglify:app_files', 'uglify:vendor_files', 'sass:app_files', 'sass:vendor_files']);\n\n // run both serverside and clientside tests\n grunt.registerTask('test', ['shell:test', 'jasmine']);\n\n // run jsdocs\n grunt.registerTask('doc', ['shell:sphinx', 'jsdoc', 'connect:docs']);\n\n};"
},
{
"alpha_fraction": 0.46875,
"alphanum_fraction": 0.46875,
"avg_line_length": 24.178571701049805,
"blob_id": "558febcad769a47b2d123d4ba44b72c91a8dffc8",
"content_id": "fc185914ded61e572a5cdde79412c8b50253ea4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 704,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 28,
"path": "/tasks/options/watch.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "module.exports = {\n app_styles: {\n files: ['www/static/styles/**/*.scss'],\n tasks: ['sass:app_files'],\n options: {\n livereload: true,\n },\n },\n vendor_styles: {\n files: ['www/static/vendor/styles/**/*.scss'],\n tasks: ['sass:vendor_files'],\n options: {\n livereload: true,\n },\n },\n app_scripts: {\n files: ['www/static/scripts/**/*.js'],\n tasks: ['uglify:app_files', 'jasmine']\n },\n vendor_scripts: {\n files: ['www/static/vendor/scripts/**/*.js'],\n tasks: ['uglify:vendor_files']\n },\n test_scripts: {\n files: ['tests/specs/**/*.js'],\n tasks: ['jasmine']\n }\n}"
},
{
"alpha_fraction": 0.6091644167900085,
"alphanum_fraction": 0.6159029603004456,
"avg_line_length": 25.535715103149414,
"blob_id": "afa498cd5dfe9b30bdc8d27fb1df5466737cacbc",
"content_id": "105c699f0ce0a768827a27ed5877a3642f9c39e1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 28,
"path": "/tests/specs/viewport-spec.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "describe(\"viewport\", function() {\n\n // params\n var el;\n\n // setup\n beforeEach(function() {\n el = $('<div></div>');\n });\n\n // assertions\n it(\"should have height, top and bottom\", function() {\n expect(flowroute.viewport.height).toBeGreaterThan(0);\n expect(flowroute.viewport.top).toBe(0);\n expect(flowroute.viewport.bottom).toBe(flowroute.viewport.height);\n });\n\n it(\"should detect parts in view\", function(){\n expect(flowroute.viewport.contains_part(el)).toBe(true);\n });\n\n it(\"should detect parts out of view\", function(){\n var outOfBounds = flowroute.viewport.height + 100;\n expect(flowroute.viewport.contains_part(el, outOfBounds)).toBe(false);\n });\n\n\n});"
},
{
"alpha_fraction": 0.6154791116714478,
"alphanum_fraction": 0.6167076230049133,
"avg_line_length": 25.29032325744629,
"blob_id": "79ae93971b676dafe2f3d948d3ec8d32f357ff4d",
"content_id": "c8b1f8329472d4618d616e2eeee563710e50478b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 814,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 31,
"path": "/tests/specs/tracker-spec.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "describe(\"elements\", function() {\n\n // params\n var html;\n var elements;\n\n // setup\n beforeEach(function() {\n html = '<section></section><section fr-track=\"test\"></section>';\n elements = $(html).filter('['+flowroute.tracker.directive+']');\n });\n\n // assertions\n it(\"should correctly track viewed elements\", function() {\n\n var test = flowroute.tracker.track({}, elements);\n expect(test.length).toBe(1);\n\n });\n\n it(\"should correctly mark elements as tracked on view\", function(){\n\n var element = elements.not('.'+flowroute.tracker.tracked);\n expect(element.hasClass(flowroute.tracker.tracked)).toBe(false);\n\n var test = flowroute.tracker.on_view(element);\n expect(test.hasClass(flowroute.tracker.tracked)).toBe(true);\n\n });\n\n});"
},
{
"alpha_fraction": 0.5609136819839478,
"alphanum_fraction": 0.5642977952957153,
"avg_line_length": 25.886363983154297,
"blob_id": "f4b096c05395decdd27a5dda7de747242e839ef8",
"content_id": "29c3833aa49e865a79692e7aba7704df23ce3505",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1182,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 44,
"path": "/tests/specs/toggle-spec.js",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "describe(\"toggle\", function() {\n\n // params\n var el;\n var target;\n var toggle;\n\n // setup\n beforeEach(function() {\n el = '<button fr-toggle=\"the_target\"><i class=\"fa fa-bars\"></i></button>';\n target = '<div id=\"the_target\">target</div>';\n toggle = new flowroute.toggle.toggle(el, target);\n });\n\n // assertions\n it(\"should toggle a show class\", function() {\n\n // on\n toggle.$el.trigger('click');\n var test_target_showing = toggle.$target.hasClass('show');\n expect(test_target_showing).toBe(true);\n\n // off\n toggle.$el.trigger('click');\n var test_target_showing = toggle.$target.hasClass('show');\n expect(test_target_showing).toBe(false);\n\n });\n\n it(\"should toggle a rotation class\", function() {\n\n // on\n toggle.$el.trigger('click');\n var test_icon_rotation = toggle.$el.find('i').hasClass('fa-rotate-90');\n expect(test_icon_rotation).toBe(true);\n\n // off\n toggle.$el.trigger('click');\n var test_icon_rotation = toggle.$el.find('i').hasClass('fa-rotate-90');\n expect(test_icon_rotation).toBe(false);\n\n });\n\n});"
},
{
"alpha_fraction": 0.6379114389419556,
"alphanum_fraction": 0.6379114389419556,
"avg_line_length": 23.47222137451172,
"blob_id": "9c3641acccf58e4176a67f77bf3f2bbb9bc84817",
"content_id": "67ec5129d28835b8655fcfac978d2898aa2558fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 881,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 36,
"path": "/www/__init__.py",
"repo_name": "kvnlnt/native-demo",
"src_encoding": "UTF-8",
"text": "#! ../env/bin/python\nimport os\n\nfrom flask import Flask, g\nfrom www.controller import main\n\n\ndef create_app(object_name, env=\"prod\"):\n \"\"\"\n An flask application factory, as explained here:\n http://flask.pocoo.org/docs/patterns/appfactories/\n\n Arguments:\n object_name: the python path of the config object,\n e.g. ark.settings.ProdConfig\n\n env: The name of the current environment, e.g. prod or dev\n \"\"\"\n\n app = Flask(__name__)\n\n app.config.from_object(object_name)\n app.config['ENV'] = env\n\n # register our blueprints\n app.register_blueprint(main)\n\n return app\n\nif __name__ == '__main__':\n # Import the config for the proper environment using the\n # shell var APPNAME_ENV\n env = os.environ.get('APPNAME_ENV', 'prod')\n app = create_app('www.settings.%sConfig' % env.capitalize(), env=env)\n\n app.run()\n"
}
] | 23 |
techwar007k/CSB003 | https://github.com/techwar007k/CSB003 | 63503c22ebd17f725005c92e96eae8dcb3c75ab9 | d2201efcde058603a18184fbe96460c8b5b56c7a | b9fb8be3858cfcb7f1d76274444089b680dbad51 | refs/heads/master | 2023-04-05T01:46:16.735179 | 2021-04-28T09:14:32 | 2021-04-28T09:14:32 | 362,402,033 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.3606557250022888,
"alphanum_fraction": 0.4754098355770111,
"avg_line_length": 6.638888835906982,
"blob_id": "9e049c72172a9cdf40f26e391a20f8b37da9f930",
"content_id": "6d7390fe8011dd342d86e25b6467b2f1fcd81452",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 549,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 72,
"path": "/Pratice number 3/Pratice2.py",
"repo_name": "techwar007k/CSB003",
"src_encoding": "UTF-8",
"text": "# Ex 1.1\n\nx=0\nprint(x)\n\n#Ex 1.2\n\nx = .0\nprint(x)\n\n#Ex 1.3\n\nx= 101\nprint(x)\n\n#Ex 1.4\n\nfloat(1000)\nx = 1000.000\n\n#Ex 1.5\n\nx = 1e3\n\n#Ex 1.6\n\nx = float(input(\"Enter x: \"))\nif x > 0:\n print(\"Positive number\")\nelif x == 0:\n print(\"Zero\")\nelse:\n print(\"Negative number\")\n\n#Ex 1.7\n\nx = 15\ny = 4\n\n\nprint('x + y =',x+y)\n\n\nprint('x - y =',x-y)\n\n\nprint('x * y =',x*y)\n\n\nprint('x / y =',x/y)\n\n\nprint('x // y =',x % y)\n\n\nprint('x ** y =',x**y)\n\n#Ex 1.8\nx, y = 2.3, 4.5\n\n#Ex 1.9\n\nx = (2.6+5.5)\n\n#Ex 1.10\n\nx = (2.6+5)*6\n\n#Ex 1.11\n\nres = 8 / 7\nres = float(8)%7"
}
] | 1 |
pstuhlmueller/Day-NightStrategy | https://github.com/pstuhlmueller/Day-NightStrategy | 32a16ea0ac0d7dd39cd1a97576c203b758cc7850 | 1b215d0fbb32e8bce8bc844a94180036fde737d3 | c7673e97a1a50df0460f583f7c70799211ad1d92 | refs/heads/main | 2023-06-07T12:40:04.256406 | 2021-07-05T15:06:21 | 2021-07-05T15:06:21 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7796609997749329,
"alphanum_fraction": 0.8220338821411133,
"avg_line_length": 46.20000076293945,
"blob_id": "84fb6bc97ebd0fe9bbca518bb1ed9046aadf97e4",
"content_id": "2d1197872bc04cacb58b94f152034f8dd116237c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 236,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 5,
"path": "/README.md",
"repo_name": "pstuhlmueller/Day-NightStrategy",
"src_encoding": "UTF-8",
"text": "# Day-NightStrategy\nAlgorithmic Trading Strategy that measures the overnight returns of Apple and Amazon stock.\n\nCheck out the whole blog at:\nhttps://medium.com/analytics-vidhya/a-simple-day-and-night-strategy-using-python-a36c18578161\n"
},
{
"alpha_fraction": 0.6863560676574707,
"alphanum_fraction": 0.7034109830856323,
"avg_line_length": 41.91071319580078,
"blob_id": "d8f5424820777ad725b446630a14a333aaf7668d",
"content_id": "2601722351c18c0447615f869278525573182f47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2404,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 56,
"path": "/code.py",
"repo_name": "pstuhlmueller/Day-NightStrategy",
"src_encoding": "UTF-8",
"text": "#importing required modules\nimport pandas as pd\nimport yfinance as yf\nimport datetime \n\n# Taking investment amount and Date of Investment as input\nInvestment = int(input('Enter Investment Amount in $ '))\nsd = input('Enter Date of Investment in DD-MM-YYYY format: ').split('-')\nstart_date = datetime.date(int(sd[2]), int(sd[1]), int(sd[0]))\nend_date = datetime.datetime.today()\n\n# using yahoo finance api to access stock data for inputted time period\namzn_data = yf.download('AMZN', start= start_date, end= end_date)\naapl_data = yf.download('AAPL', start= start_date, end= end_date)\n\n# reseting index for easier access of Date\namzn = pd.DataFrame(amzn_data)\namzn.reset_index(inplace=True)\naapl = pd.DataFrame(aapl_data)\naapl.reset_index(inplace=True)\n\n\n#cleaning the data\namzn.drop(['High','Low','Adj Close', 'Volume'],axis=1,inplace=True)\naapl.drop(['High','Low','Adj Close', 'Volume'],axis=1,inplace=True)\n\n# Calculating overnight return % by using ((Open-Prev.CLose)/Close)*100 for AMZN\namzn['Overnight Return %'] = ((amzn['Open'].shift(-1) - amzn['Close']).shift(1)/amzn['Close'])*100\namzn['Overnight Return %'] = amzn['Overnight Return %'].fillna(0)\n\n# Calculating overnight return % by using ((Open-Prev.CLose)/Close)*100 for AAPL\naapl['Overnight Return %'] = ((aapl['Open'].shift(-1) - aapl['Close']).shift(1)/aapl['Close'])*100 \naapl['Overnight Return %'] = aapl['Overnight Return %'].fillna(0)\n\n\n#Printing Daily overnight returns and total Profit & Loss(AMZN)\nprint(str(Investment)+'$ invested in Amazon Stock on',start_date) \namzn_investment = Investment\namzn_profit = 0\nfor i in range(1,amzn['Date'].count()):\n amzn_pnl = (amzn['Overnight Return %'][i]/100)*Investment\n print('PnL on',amzn['Date'][i],'is $',amzn_pnl)\n amzn_profit = amzn_profit + amzn_pnl\nprint('Current Investment Value: ',(amzn_investment+amzn_profit))\nprint('Total PnL % :',((amzn_profit/Investment)*100).round(3))\n\n #Printing Daily overnight returns and total Profit & Loss(AMZN)\nprint(str(Investment)+'$ invested in Apple Stock on',start_date) \naapl_investment = Investment\naapl_profit = 0\nfor i in range(1,aapl['Date'].count()):\n aapl_pnl = (aapl['Overnight Return %'][i]/100)*Investment\n print('PnL on',aapl['Date'][i],'is',aapl_pnl)\n aapl_profit = aapl_profit + aapl_pnl\nprint('Current Investment Value',(aapl_investment+aapl_profit))\nprint('Total PnL % :',((aapl_profit/Investment)*100).round(3))\n\n"
}
] | 2 |
BON-JIN/Reservation-system | https://github.com/BON-JIN/Reservation-system | 00e2336a98660ad8c3fd272573592abfdc20d8ec | 0fb017ec137d7370c7e1454a5ea15c33825be4f2 | 69069a54988987f7b1fc381411585e5d6b2dca5d | refs/heads/master | 2020-05-01T18:49:57.499473 | 2019-03-25T17:34:22 | 2019-03-25T17:34:22 | 177,632,917 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7090908885002136,
"alphanum_fraction": 0.7090908885002136,
"avg_line_length": 54,
"blob_id": "c635a9549d91168c4132dc5b87a64a41e5b3311d",
"content_id": "9f9fe0a33959ff13e975f00affe0302d7357f29f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 55,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/compile.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "javac client/*.java middleware/*.java server/**/*.java\n"
},
{
"alpha_fraction": 0.8333333134651184,
"alphanum_fraction": 0.8333333134651184,
"avg_line_length": 35,
"blob_id": "c6f8bb95d94646915ca05fc2c6855b18b05344b5",
"content_id": "0058e74fd4b864934a78f5b493f574a30767470f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 36,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/middleware.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "java middleware.MiddlewareServer $@\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6367021203041077,
"avg_line_length": 30.872880935668945,
"blob_id": "ce73498faabb8a0ae903b1896567b7d046ea56d3",
"content_id": "478a638e266e114050a69271f1eb11f87b3193ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3760,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 118,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/test_many_clients.py",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\nimport math\nimport os\nimport sys\n\nfrom subprocess import Popen\n\n\n\n# Convert a list of commands into a string that is piped into the client shell script\ndef client_script(client_path: str, commands: [str], process_num: int):\n return \"echo '\" + \"\\n\".join(commands).format(i=process_num) + \"\\nquit\\n' | sh \" + client_path\n\n\n# Execute given list of commands concurrently on the given number of processes\ndef execute(path, commands: [str], num_processes: int):\n processes = [Popen(client_script(path, commands, i), shell=True)\n for i in range(1, num_processes + 1)]\n wait(processes)\n\n\n# Execute given list of commands with one unique string in the middle of the sequence\ndef execute_two(path: int, commands: [str], second_commands: [str], total_processes: int):\n processes = [Popen(client_script(path, second_commands if i == math.floor(total_processes / 2) else commands, i), shell=True)\n for i in range(1, total_processes)]\n wait(processes)\n\n\ndef wait(processes: [Popen]):\n for p in processes:\n p.wait()\n\n\nadd_setup = [\n \"newflight, {i:d}, 123, 3, 250\",\n \"newflight, {i:d}, 124, 5, 200\",\n \"newflight, {i:d}, 125, 5, 200\",\n \"newcar, {i:d}, Cookeville, 5, 90\",\n \"newroom, {i:d}, Cookeville, 5, 80\",\n \"newcustomerid, {i:d}, 999999\",\n \"newcar, {i:d}, Spam, 5, 150\",\n \"newroom, {i:d}, Spam, 5, 100\"\n]\ndelete_setup = [\n \"deleteflight, {i:d}, 123\",\n \"deleteflight, {i:d}, 124\",\n \"deleteflight, {i:d}, 125\",\n \"deletecar, {i:d}, Cookeville\",\n \"deleteroom, {i:d}, Cookeville\",\n \"deletecustomer, {i:d}, 999999\",\n \"deletecar, {i:d}, Spam\",\n \"deleteroom, {i:d}, Spam\"\n]\nadd_customers = [\n \"newcustomerid, {i:d}, {i:d}\"\n]\ndelete_customers = [\n \"deletecustomer, {i:d}, {i:d}\"\n]\nreserve_flights = [\n \"reserveflight, {i:d}, {i:d}, 123\",\n \"queryflight, {i:d}, 123\",\n \"querycustomer, {i:d}, {i:d}\"\n]\nreserve_itinerary = [\n \"itinerary, {i:d}, {i:d}, 124, 125, Cookeville, true, true\",\n \"queryflight, {i:d}, 124\",\n \"queryflight, {i:d}, 125\",\n \"querycar, {i:d}, Cookeville\",\n \"queryroom, {i:d}, Cookeville\",\n \"querycustomer, {i:d}, {i:d}\"\n]\nspam_customer = [\n \"querycustomer, {i:d}, 999999\",\n \"querycustomer, {i:d}, 999999\",\n \"querycustomer, {i:d}, 999999\",\n \"querycustomer, {i:d}, 999999\",\n \"querycustomer, {i:d}, 999999\"\n]\nspam_customer_reserve = [\n \"reservecar, {i:d}, 999999, Spam\",\n \"reserveroom, {i:d}, 999999, Spam\"\n]\n\n# Expects path to client shell script\ndef main():\n if len(sys.argv) != 3:\n print(\"Error: expected 2 arguments: /path/to/client.sh, middleware-port-number\")\n return\n path = os.path.abspath(sys.argv[1]) + \" \" + sys.argv[2]\n\n # Setup\n num_customers = 5\n execute(path, add_setup, 1)\n execute(path, add_customers, num_customers)\n\n # Reserve more seats than available \n # (only 3 customers should get flight seats)\n input(\"Press enter to begin reserving flight 123...\")\n execute(path, reserve_flights, num_customers)\n\n # Reserve itinerary with limited availablility \n # (only 5 customers should get their itinerary)\n input(\"Press enter to begin reserving flight 124, flight 125, cars in Cookeville, and rooms in Cookeville...\")\n execute(path, reserve_itinerary, num_customers)\n\n # Reserve car and room while other clients are flooding the servers with customer queries\n input(\"Press enter to begin spamming a querycustomer while reserving with that customer...\")\n execute_two(path, spam_customer, spam_customer_reserve, num_customers)\n\n # cleanup\n input(\"Press enter to start cleanup...\")\n execute(path, delete_customers, num_customers)\n execute(path, delete_setup, 1)\n\n\nif __name__ == \"__main__\":\n main()"
},
{
"alpha_fraction": 0.5055261850357056,
"alphanum_fraction": 0.507688581943512,
"avg_line_length": 39.402217864990234,
"blob_id": "81106c95bb8744842c985ab2badf2bbcde5f2500",
"content_id": "6684a7fc615534b61a794298f04c1f71998cbf3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 29134,
"license_type": "no_license",
"max_line_length": 230,
"num_lines": 721,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/server/ResImpl/ResourceManagerImpl.java",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "// -------------------------------\n// adapated from Kevin T. Manley\n// CSE 593\n//\npackage server.ResImpl;\n\nimport java.net.*; \nimport java.io.*;\n\nimport server.ResInterface.*;\nimport util.Command;\n\nimport java.util.*;\n\nimport static util.Command.*;\nimport static util.Util.*;\n\npublic class ResourceManagerImpl {// implements ResourceManager {\n\n public static void main(String args[]) {\n Vector <ServerSocket> servers;\n String address = \"localhost\";\n // if (args.length != 4) {\n // System.err.println(\"Wrong usage\");\n // System.out.println(\"Usage: java ResImpl.ResourceManagerImpl location [port1] [port2] [port3]\");\n // System.exit(1);\n // } \n try{\n Socket socket = new Socket(address, Integer.parseInt(args[0])); \n \n String request = \"\";\n request = args[1] + \", \" + args[2] + \", \" + args[3] + \", \" + args[4];\n System.out.println(request);\n\n System.out.println(\"Updating Loadbalancer in master server.\");\n String valid_message = (String) send_receive(socket, request);\n socket.close();\n System.out.println(valid_message);\n\n for(int i = 2; i < args.length; i++){\n ServerSocket server = new ServerSocket(Integer.parseInt(args[i]));\n Thread t = new ClientHandler(Integer.parseInt(args[i]));\n System.out.println(\"Server started: \" + t.getName());\n t.start();\n }\n }\n catch (IOException e){\n System.out.println(e);\n error(e, \"A TCP error occurred.\");\n }\n }\n}\n\n\nclass ClientHandler extends Thread{\n\n protected RMHashtable m_itemHT = new RMHashtable();\n\n // Initialize the variables\n private Vector data;\n private String message;\n private int port;\n\n public ClientHandler(int p){\n this.port = p;\n } \n\n @Override\n public void run(){\n // Establish server\n\n while (true) {\n try {\n ServerSocket server = new ServerSocket(port);\n System.out.println(\"Waiting on: \" + port); \n Socket socket = server.accept();\n System.out.println(\"Client accepted: \" + port);\n\n Command command = null;\n data = (Vector) receive(socket); // Read data from input stream.\n System.out.println(\"Received a request from the client (middleware). :\" + this.port);\n\n command = findCommand((String)data.elementAt(0));\n\n // Execute the command and returns result as String message\n message = executeRequest(command, data);\n \n // Only message will be sent from server to middleware.\n send(socket, message);\n System.out.println(\"Message has been sent back\"); \n socket.close();\n server.close();\n }\n catch (IOException e) {\n\n } \n // close connection\n //System.out.println(\"Closing connection\"); \n }\n\n }\n\n\n\n public int getInt(Object temp) throws Exception {\n try {\n return (new Integer((String)temp)).intValue();\n }\n catch(Exception e) {\n throw e;\n }\n }\n\n public boolean getBoolean(Object temp) throws Exception {\n try {\n return (new Boolean((String)temp)).booleanValue();\n }\n catch(Exception e) {\n throw e;\n }\n }\n\n public String getString(Object temp) throws Exception {\n try {\n return (String)temp;\n }\n catch (Exception e) {\n throw e;\n }\n }\n\n public String executeRequest(Command command, Vector data) {\n String message = \"Request failed.\";\n try {\n int id = 0;\n int flightNum, flightSeats, flightPrice, numCars, numRooms, price, customer;\n if (data.size() > 1) {\n id = this.getInt(data.elementAt(1));\n }\n String location;\n switch (command) {\n case NEWFLIGHT:\n flightNum = this.getInt(data.elementAt(2));\n flightSeats = this.getInt(data.elementAt(3));\n flightPrice = this.getInt(data.elementAt(4));\n\n if (this.addFlight(id, flightNum, flightSeats, flightPrice)) {\n System.out.println(\"Flight added\");\n\n message = \"Added a new Flight using id: \" + id + \"\\n\"\n + \"Flight number: \" + flightNum + \"\\n\"\n + \"Add Flight Seats: \" + flightSeats + \"\\n\"\n + \"Set Flight Price: \" + flightPrice + \"\\n\";\n } else\n message = \"Flight could not be added\";\n break;\n\n case DELETEFLIGHT: //delete Flight\n flightNum = this.getInt(data.elementAt(2));\n\n if (this.deleteFlight(id, flightNum)) {\n System.out.println(\"Flight Deleted\");\n\n message = \"Deleted a flight using id: \" + id + \"\\n\"\n + \"Flight Number: \" + flightNum;\n\n } else\n message = \"Flight could not be deleted\";\n break;\n\n case QUERYFLIGHT: //querying a flight\n flightNum = this.getInt(data.elementAt(2));\n\n int seats = this.queryFlight(id, flightNum);\n message = \"Querying a flight using id: \" + id + \"\\n\"\n + \"Flight number: \" + flightNum + \"\\n\"\n + \"Number of seats available:\" + seats;\n break;\n\n case QUERYFLIGHTPRICE: //querying a flight Price\n flightNum = this.getInt(data.elementAt(2));\n flightPrice = this.queryFlightPrice(id, flightNum);\n\n message = \"Querying a flight Price using id: \" + id + \"\\n\"\n + \"Flight number: \" + flightNum + \"\\n\"\n + \"Price of a seat:\" + flightPrice;\n break;\n\n case RESERVEFLIGHT: //reserve a flight\n customer = this.getInt(data.elementAt(2));\n flightNum = this.getInt(data.elementAt(3));\n\n if (this.reserveFlight(id, customer, flightNum))\n message = \"Reserving a seat on a flight using id: \" + id + \"\\n\"\n + \"Customer id: \" + customer + \"\\n\"\n + \"Flight number: \" + flightNum + \"\\n\"\n + \"Flight Reserved\";\n else\n message = \"Flight could not be reserved.\";\n break;\n\n case NEWCAR: //new Car\n location = this.getString(data.elementAt(2));\n numCars = this.getInt(data.elementAt(3));\n price = this.getInt(data.elementAt(4));\n\n if (this.addCars(id, location, numCars, price)) {\n message = \"Adding a new Car using id: \" + id + \"\\n\"\n + \"Car Location: \" + location + \"\\n\"\n + \"Add Number of Cars: \" + numCars + \"\\n\"\n + \"Set Price: \" + price + \"\\n\"\n + \"Cars added\";\n } else\n message = \"Cars could not be added\";\n break;\n\n case DELETECAR: //delete Car\n location = this.getString(data.elementAt(2));\n\n if (this.deleteCars(id, location)) {\n message = \"Deleting the cars from a particular location using id: \" + id + \"\\n\"\n + \"Car Location: \" + location + \"\\n\"\n + \"Cars Deleted\";\n } else\n message = \"Cars could not be deleted\";\n break;\n\n\n case QUERYCAR: //querying a Car Location\n location = this.getString(data.elementAt(2));\n numCars = this.queryCars(id, location);\n\n message = \"Querying a car location using id: \" + id + \"\\n\"\n + \"Car location: \" + location + \"\\n\"\n + \"number of Cars at this location:\" + numCars + \"\\n\";\n break;\n\n\n case QUERYCARPRICE: //querying a Car Price\n location = this.getString(data.elementAt(2));\n price = this.queryCarsPrice(id, location);\n\n message = \"Querying a car price using id: \" + id + \"\\n\"\n + \"Car location: \" + location + \"\\n\"\n + \"Price of a car at this location:\" + price;\n break;\n\n case RESERVECAR: //reserve a car\n customer = this.getInt(data.elementAt(2));\n location = this.getString(data.elementAt(3));\n\n if (this.reserveCar(id, customer, location)) {\n message = \"Reserving a car at a location using id: \" + id + \"\\n\"\n + \"Customer id: \" + customer + \"\\n\"\n + \"Location: \" + location + \"\\n\"\n + \"Car Reserved\";\n } else\n message = \"Car could not be reserved.\";\n break;\n\n\n case NEWROOM: //new Room\n location = this.getString(data.elementAt(2));\n numRooms = this.getInt(data.elementAt(3));\n price = this.getInt(data.elementAt(4));\n\n if (this.addRooms(id, location, numRooms, price)) {\n message = \"Adding a new Room using id: \" + id + \"\\n\"\n + \"Room Location: \" + location + \"\\n\"\n + \"Add Number of Rooms: \" + numRooms + \"\\n\"\n + \"Set Price: \" + price + \"\\n\"\n + \"Rooms added\";\n } else\n message = \"Rooms could not be added\";\n break;\n\n case DELETEROOM: //delete Room;\n location = this.getString(data.elementAt(2));\n if (this.deleteRooms(id, location)) {\n message = \"Deleting all rooms from a particular location using id: \" + id + \"\\n\"\n + \"Room Location: \" + location + \"\\n\"\n + \"Rooms Deleted\";\n } else\n message = \"Rooms could not be deleted\";\n\n break;\n\n\n case QUERYROOM: //querying a Room location\n location = this.getString(data.elementAt(2));\n numRooms = this.queryRooms(id, location);\n\n message = \"Querying a room location using id: \" + id + \"\\n\"\n + \"Room location: \" + location + \"\\n\"\n + \"number of Rooms at this location:\" + numRooms;\n break;\n\n\n case QUERYROOMPRICE: //querying a Room price\n location = this.getString(data.elementAt(2));\n price = this.queryRoomsPrice(id, location);\n\n message = \"Querying a room price using id: \" + id + \"\\n\"\n + \"Room Location: \" + location + \"\\n\"\n + \"Price of Rooms at this location:\" + price;\n\n\n System.out.println();\n break;\n\n case RESERVEROOM: //reserve a room\n customer = this.getInt(data.elementAt(2));\n location = this.getString(data.elementAt(3));\n\n if (this.reserveRoom(id, customer, location)) {\n message = \"Reserving a room at a location using id: \" + id + \"\\n\"\n + \"Customer id: \" + customer + \"\\n\"\n + \"Location: \" + location + \"\\n\"\n + \"Room Reserved\";\n } else\n message = \"Room could not be reserved.\";\n break;\n\n\n // Purpose: Get the system to provide a new customer id (same as adding a new customer)\n case NEWCUSTOMER: //new Customer\n customer = this.newCustomer(id);\n\n message = \"Adding a new Customer using id:\" + id + \"\\n\"\n + \"new customer id:\" + customer;\n break;\n\n // Purpose: creates a new customer with id provided as input\n case NEWCUSTOMERID: //new Customer given id\n int Cid = this.getInt(data.elementAt(2));\n boolean result = this.newCustomer(id, Cid);\n message = \"Adding a new Customer using id:\" + id + \" and cid \" + Cid + \"\\n\"\n + \"new customer id:\" + Cid;\n break;\n\n case QUERYCUSTOMER: //querying Customer Information\n customer = this.getInt(data.elementAt(2));\n String bill = this.queryCustomerInfo(id, customer);\n message = \"Querying Customer information using id: \" + id + \"\\n\"\n + \"Customer id:\" + customer + \"\\n\"\n + \"Customer info:\" + bill;\n break;\n\n case DELETECUSTOMER: //delete Customer\n customer = this.getInt(data.elementAt(2));\n\n if (this.deleteCustomer(id, customer))\n message = \"Deleting a customer from the database using id: \" + data.elementAt(1) + \"\\n\"\n + \"Customer id: \" + data.elementAt(2) + \"\\n\"\n + \"Customer Deleted\";\n else\n message = \"Customer could not be deleted\";\n break;\n\n case QUIT: //reserve a room\n message = \"Thanks for using our service.\";\n break;\n }\n } catch (Exception e) {\n error(e, e.getMessage());\n }\n return message;\n }\n\n public boolean itinerary(int id, int customer, Vector flightNumbers, String location, boolean Car, boolean Room) {\n return true;\n }\n\n // Reads a data item\n private RMItem readData( int id, String key )\n {\n synchronized(m_itemHT){\n return (RMItem) m_itemHT.get(key);\n }\n }\n\n // Writes a data item\n private void writeData( int id, String key, RMItem value )\n {\n synchronized(m_itemHT){\n m_itemHT.put(key, value);\n }\n }\n\n // Remove the item out of storage\n protected RMItem removeData(int id, String key){\n synchronized(m_itemHT){\n return (RMItem)m_itemHT.remove(key);\n }\n }\n\n\n // deletes the entire item\n protected boolean deleteItem(int id, String key)\n {\n Trace.info(\"RM::deleteItem(\" + id + \", \" + key + \") called\" );\n ReservableItem curObj = (ReservableItem) readData( id, key );\n // Check if there is such an item in the storage\n if( curObj == null ) {\n Trace.warn(\"RM::deleteItem(\" + id + \", \" + key + \") failed--item doesn't exist\" );\n return false;\n } else {\n if(curObj.getReserved()==0){\n removeData(id, curObj.getKey());\n Trace.info(\"RM::deleteItem(\" + id + \", \" + key + \") item deleted\" );\n return true;\n }\n else{\n Trace.info(\"RM::deleteItem(\" + id + \", \" + key + \") item can't be deleted because some customers reserved it\" );\n return false;\n }\n } // if\n }\n\n\n // query the number of available seats/rooms/cars\n protected int queryNum(int id, String key) {\n Trace.info(\"RM::queryNum(\" + id + \", \" + key + \") called\" );\n ReservableItem curObj = (ReservableItem) readData( id, key);\n int value = 0;\n if( curObj != null ) {\n value = curObj.getCount();\n } // else\n Trace.info(\"RM::queryNum(\" + id + \", \" + key + \") returns count=\" + value);\n return value;\n }\n\n // query the price of an item\n protected int queryPrice(int id, String key){\n Trace.info(\"RM::queryCarsPrice(\" + id + \", \" + key + \") called\" );\n ReservableItem curObj = (ReservableItem) readData( id, key);\n int value = 0;\n if( curObj != null ) {\n value = curObj.getPrice();\n } // else\n Trace.info(\"RM::queryCarsPrice(\" + id + \", \" + key + \") returns cost=$\" + value );\n return value;\n }\n\n // reserve an item\n protected boolean reserveItem(int id, int customerID, String key, String location){\n Trace.info(\"RM::reserveItem( \" + id + \", customer=\" + customerID + \", \" +key+ \", \"+location+\" ) called\" );\n // Read customer object if it exists (and read lock it)\n Customer cust = (Customer) readData( id, Customer.getKey(customerID) );\n if( cust == null ) {\n Trace.warn(\"RM::reserveCar( \" + id + \", \" + customerID + \", \" + key + \", \"+location+\") failed--customer doesn't exist\" );\n return false;\n }\n\n // check if the item is available\n ReservableItem item = (ReservableItem)readData(id, key);\n if(item==null){\n Trace.warn(\"RM::reserveItem( \" + id + \", \" + customerID + \", \" + key+\", \" +location+\") failed--item doesn't exist\" );\n return false;\n }else if(item.getCount()==0){\n Trace.warn(\"RM::reserveItem( \" + id + \", \" + customerID + \", \" + key+\", \" + location+\") failed--No more items\" );\n return false;\n }else{\n cust.reserve( key, location, item.getPrice());\n writeData( id, cust.getKey(), cust );\n\n // decrease the number of available items in the storage\n item.setCount(item.getCount() - 1);\n item.setReserved(item.getReserved()+1);\n\n Trace.info(\"RM::reserveItem( \" + id + \", \" + customerID + \", \" + key + \", \" +location+\") succeeded\" );\n return true;\n }\n }\n\n // Create a new flight, or add seats to existing flight\n // NOTE: if flightPrice <= 0 and the flight already exists, it maintains its current price\n public boolean addFlight(int id, int flightNum, int flightSeats, int flightPrice)\n {\n Trace.info(\"RM::addFlight(\" + id + \", \" + flightNum + \", $\" + flightPrice + \", \" + flightSeats + \") called\" );\n Flight curObj = (Flight) readData( id, Flight.getKey(flightNum) );\n if( curObj == null ) {\n // doesn't exist...add it\n Flight newObj = new Flight( flightNum, flightSeats, flightPrice );\n writeData( id, newObj.getKey(), newObj );\n Trace.info(\"RM::addFlight(\" + id + \") created new flight \" + flightNum + \", seats=\" +\n flightSeats + \", price=$\" + flightPrice );\n } else {\n // add seats to existing flight and update the price...\n curObj.setCount( curObj.getCount() + flightSeats );\n if( flightPrice > 0 ) {\n curObj.setPrice( flightPrice );\n } // if\n writeData( id, curObj.getKey(), curObj );\n Trace.info(\"RM::addFlight(\" + id + \") modified existing flight \" + flightNum + \", seats=\" + curObj.getCount() + \", price=$\" + flightPrice );\n } // else\n return(true);\n }\n\n public boolean deleteFlight(int id, int flightNum)\n {\n return deleteItem(id, Flight.getKey(flightNum));\n }\n\n // Create a new room location or add rooms to an existing location\n // NOTE: if price <= 0 and the room location already exists, it maintains its current price\n public boolean addRooms(int id, String location, int count, int price)\n {\n Trace.info(\"RM::addRooms(\" + id + \", \" + location + \", \" + count + \", $\" + price + \") called\" );\n Hotel curObj = (Hotel) readData( id, Hotel.getKey(location) );\n if( curObj == null ) {\n // doesn't exist...add it\n Hotel newObj = new Hotel( location, count, price );\n writeData( id, newObj.getKey(), newObj );\n Trace.info(\"RM::addRooms(\" + id + \") created new room location \" + location + \", count=\" + count + \", price=$\" + price );\n } else {\n // add count to existing object and update price...\n curObj.setCount( curObj.getCount() + count );\n if( price > 0 ) {\n curObj.setPrice( price );\n } // if\n writeData( id, curObj.getKey(), curObj );\n Trace.info(\"RM::addRooms(\" + id + \") modified existing location \" + location + \", count=\" + curObj.getCount() + \", price=$\" + price );\n } // else\n return(true);\n }\n\n\n // Delete rooms from a location\n public boolean deleteRooms(int id, String location)\n {\n return deleteItem(id, Hotel.getKey(location));\n }\n\n\n // Create a new car location or add cars to an existing location\n // NOTE: if price <= 0 and the location already exists, it maintains its current price\n public boolean addCars(int id, String location, int count, int price)\n {\n Trace.info(\"RM::addCars(\" + id + \", \" + location + \", \" + count + \", $\" + price + \") called\" );\n Car curObj = (Car) readData( id, Car.getKey(location) );\n if( curObj == null ) {\n // car location doesn't exist...add it\n Car newObj = new Car( location, count, price );\n writeData( id, newObj.getKey(), newObj );\n Trace.info(\"RM::addCars(\" + id + \") created new location \" + location + \", count=\" + count + \", price=$\" + price );\n } else {\n // add count to existing car location and update price...\n curObj.setCount( curObj.getCount() + count );\n if( price > 0 ) {\n curObj.setPrice( price );\n } // if\n writeData( id, curObj.getKey(), curObj );\n Trace.info(\"RM::addCars(\" + id + \") modified existing location \" + location + \", count=\" + curObj.getCount() + \", price=$\" + price );\n } // else\n return(true);\n }\n\n\n // Delete cars from a location\n public boolean deleteCars(int id, String location)\n {\n return deleteItem(id, Car.getKey(location));\n }\n\n\n // Returns the number of empty seats on this flight\n public int queryFlight(int id, int flightNum)\n {\n return queryNum(id, Flight.getKey(flightNum));\n }\n\n // Returns price of this flight\n public int queryFlightPrice(int id, int flightNum )\n {\n return queryPrice(id, Flight.getKey(flightNum));\n }\n\n\n // Returns the number of rooms available at a location\n public int queryRooms(int id, String location)\n {\n return queryNum(id, Hotel.getKey(location));\n }\n\n\n // Returns room price at this location\n public int queryRoomsPrice(int id, String location)\n {\n return queryPrice(id, Hotel.getKey(location));\n }\n\n\n // Returns the number of cars available at a location\n public int queryCars(int id, String location)\n {\n return queryNum(id, Car.getKey(location));\n }\n\n\n // Returns price of cars at this location\n public int queryCarsPrice(int id, String location)\n {\n return queryPrice(id, Car.getKey(location));\n }\n\n // Returns data structure containing customer reservation info. Returns null if the\n // customer doesn't exist. Returns empty RMHashtable if customer exists but has no\n // reservations.\n public RMHashtable getCustomerReservations(int id, int customerID)\n {\n Trace.info(\"RM::getCustomerReservations(\" + id + \", \" + customerID + \") called\" );\n Customer cust = (Customer) readData( id, Customer.getKey(customerID) );\n if( cust == null ) {\n Trace.warn(\"RM::getCustomerReservations failed(\" + id + \", \" + customerID + \") failed--customer doesn't exist\" );\n return null;\n } else {\n return cust.getReservations();\n } // if\n }\n\n\n // return a bill\n public String queryCustomerInfo(int id, int customerID)\n {\n Trace.info(\"RM::queryCustomerInfo(\" + id + \", \" + customerID + \") called\" );\n Customer cust = (Customer) readData( id, Customer.getKey(customerID) );\n if( cust == null ) {\n Trace.warn(\"RM::queryCustomerInfo(\" + id + \", \" + customerID + \") failed--customer doesn't exist\" );\n return \"\"; // NOTE: don't change this--WC counts on this value indicating a customer does not exist...\n } else {\n String s = cust.printBill();\n Trace.info(\"RM::queryCustomerInfo(\" + id + \", \" + customerID + \"), bill follows...\" );\n System.out.println( s );\n return s;\n } // if\n }\n\n\n // customer functions\n // new customer just returns a unique customer identifier\n public int newCustomer(int id)\n {\n Trace.info(\"INFO: RM::newCustomer(\" + id + \") called\" );\n // Generate a globally unique ID for the new customer\n int cid = Integer.parseInt( String.valueOf(id) +\n String.valueOf(Calendar.getInstance().get(Calendar.MILLISECOND)) +\n String.valueOf( Math.round( Math.random() * 100 + 1 )));\n Customer cust = new Customer( cid );\n writeData( id, cust.getKey(), cust );\n Trace.info(\"RM::newCustomer(\" + id + \") returns ID=\" + cid );\n return cid;\n }\n\n\n // I opted to pass in customerID instead. This makes testing easier\n public boolean newCustomer(int id, int customerID )\n {\n Trace.info(\"INFO: RM::newCustomer(\" + id + \", \" + customerID + \") called\" );\n Customer cust = (Customer) readData( id, Customer.getKey(customerID) );\n if( cust == null ) {\n cust = new Customer(customerID);\n writeData( id, cust.getKey(), cust );\n Trace.info(\"INFO: RM::newCustomer(\" + id + \", \" + customerID + \") created a new customer\" );\n return true;\n } else {\n Trace.info(\"INFO: RM::newCustomer(\" + id + \", \" + customerID + \") failed--customer already exists\");\n return false;\n } // else\n }\n\n\n // Deletes customer from the database.\n public boolean deleteCustomer(int id, int customerID)\n {\n Trace.info(\"RM::deleteCustomer(\" + id + \", \" + customerID + \") called\" );\n Customer cust = (Customer) readData( id, Customer.getKey(customerID) );\n if( cust == null ) {\n Trace.warn(\"RM::deleteCustomer(\" + id + \", \" + customerID + \") failed--customer doesn't exist\" );\n return false;\n } else {\n // Increase the reserved numbers of all reservable items which the customer reserved.\n RMHashtable reservationHT = cust.getReservations();\n for(Enumeration e = reservationHT.keys(); e.hasMoreElements();){\n String reservedkey = (String) (e.nextElement());\n ReservedItem reserveditem = cust.getReservedItem(reservedkey);\n Trace.info(\"RM::deleteCustomer(\" + id + \", \" + customerID + \") has reserved \" + reserveditem.getKey() + \" \" + reserveditem.getCount() + \" times\" );\n ReservableItem item = (ReservableItem) readData(id, reserveditem.getKey());\n Trace.info(\"RM::deleteCustomer(\" + id + \", \" + customerID + \") has reserved \" + reserveditem.getKey() + \"which is reserved\" + item.getReserved() + \" times and is still available \" + item.getCount() + \" times\" );\n item.setReserved(item.getReserved()-reserveditem.getCount());\n item.setCount(item.getCount()+reserveditem.getCount());\n }\n\n // remove the customer from the storage\n removeData(id, cust.getKey());\n\n Trace.info(\"RM::deleteCustomer(\" + id + \", \" + customerID + \") succeeded\" );\n return true;\n } // if\n }\n\n // Adds car reservation to this customer.\n public boolean reserveCar(int id, int customerID, String location)\n {\n return reserveItem(id, customerID, Car.getKey(location), location);\n }\n\n\n // Adds room reservation to this customer.\n public boolean reserveRoom(int id, int customerID, String location)\n {\n return reserveItem(id, customerID, Hotel.getKey(location), location);\n }\n\n\n // Adds flight reservation to this customer.\n public boolean reserveFlight(int id, int customerID, int flightNum)\n {\n return reserveItem(id, customerID, Flight.getKey(flightNum), String.valueOf(flightNum));\n }\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.8160919547080994,
"alphanum_fraction": 0.8160919547080994,
"avg_line_length": 86,
"blob_id": "ce1a02e35b2e1ddaae5668937744de1dc892a2f8",
"content_id": "946be48fdf38d08936a2360e2a6c93a0cc365290",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/sever.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "java -Djava.security.policy=./server/java.policy server.ResImpl.ResourceManagerImpl $@\n"
},
{
"alpha_fraction": 0.5826210975646973,
"alphanum_fraction": 0.5854700803756714,
"avg_line_length": 17.44444465637207,
"blob_id": "7cfcbdd05e31bfe0f2b0d4ea8c8a8713acc8861c",
"content_id": "975c10fe517b104b2903ceb734ad9a9e4592eda6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 702,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 36,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/middleware/LookUpServer.java",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "package middleware;\r\n\r\nimport java.net.*;\r\nimport java.io.*;\r\nimport java.util.*;\r\n\r\nimport static util.Util.*;\r\n\r\npublic class LookUpServer\r\n{\r\n\tpublic static void main(String args[])\r\n\t{\r\n\t\t// String address = \"localhost\";\r\n\r\n\t\t// Hashtable<String, Long> routerTable = new Hashtable<String, Socket>();\r\n\r\n\t\t// try {\r\n\t\t// \tServerSocket server = new ServerSocket(Integer.parseInt(args[0]));\r\n\r\n\t\t// \twhile(true){\r\n\t\t// \t\tSocket s = server.accept();\r\n\t\t// \t\tSystem.out.println(\"Connected a server.\");\r\n\r\n\t\t// \t\tStrings location = (String)recieve(s);\r\n\t\t// \t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t// \tSocket s = new Socket(address, Integer.parseInt(args[i + 1]));\r\n\t\r\n\t\t// }\r\n\t\t// catch(IOException e){\r\n\r\n\t\t// }\r\n\t\t\r\n\t}\r\n}\r\n\r\n"
},
{
"alpha_fraction": 0.8372092843055725,
"alphanum_fraction": 0.8372092843055725,
"avg_line_length": 42,
"blob_id": "a2d9e0965ad52156b2758af12a13b21053adbcbd",
"content_id": "3d42c97373262bec53cf59a6bbd5867a03fb09c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 43,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/server.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "java server.ResImpl.ResourceManagerImpl $@\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7222222089767456,
"avg_line_length": 35,
"blob_id": "678fd6e04cc3bf4c958297d06e2a6ff19e6884ed",
"content_id": "e981bdb4591061edb1f7ce6de9c817d332b1b4c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 36,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/test_client.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "cat test_commands.txt | ./client.sh\n"
},
{
"alpha_fraction": 0.6043425798416138,
"alphanum_fraction": 0.6043425798416138,
"avg_line_length": 29.703702926635742,
"blob_id": "c91a44f5111081822d51214ae20bb0131a5b510c",
"content_id": "abae23c61e8324404dcdc1661112257bbd860986",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1658,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 54,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/util/Util.java",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "package util;\n\nimport java.io.*;\nimport java.net.Socket;\nimport java.util.*;\n\npublic class Util {\n public static void error(Exception e, String message) {\n System.err.println(message);\n e.printStackTrace();\n }\n\n // Sends message to given server and returns any reply\n public static Object send_receive(Socket server, Object message) {\n send(server, message);\n return receive(server);\n }\n\n public static void send(Socket server, Object message) {\n try {\n ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());\n out.writeObject(message);\n } catch (IOException e) {\n error(e, \"A TCP error occurred opening output stream from \" + server.toString());\n }\n }\n\n public static Object receive(Socket server) {\n Object reply = null;\n try {\n ObjectInputStream in = new ObjectInputStream(server.getInputStream());\n reply = in.readObject();\n } catch (IOException e) {\n error(e, \"A TCP error occurred opening input stream from \" + server.toString());\n } catch (ClassNotFoundException e) {\n error(e, \"Object could not be read from \" + server.toString());\n }\n return reply;\n }\n\n public static Vector parse(String command) {\n Vector data = new Vector();\n StringTokenizer tokenizer = new StringTokenizer(command,\",\");\n String argument;\n\n while (tokenizer.hasMoreTokens()){\n argument = tokenizer.nextToken();\n argument = argument.trim();\n data.add(argument);\n }\n\n return data;\n }\n}\n"
},
{
"alpha_fraction": 0.8119266033172607,
"alphanum_fraction": 0.8119266033172607,
"avg_line_length": 30.14285659790039,
"blob_id": "a326960c915bb87dcbfb32a134bc030b13280512",
"content_id": "41cc1b738f0c0da0347409f4c1424883fad2db40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 7,
"path": "/README.md",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "# Reservation-system\nClient/Server connection with TCP.\nMultiple Clients, Server connections and threads.\nDetails are written in a repot text file in the root repository.\n\n(Updated)\nImplemented a simple load balancer.\n"
},
{
"alpha_fraction": 0.7272727489471436,
"alphanum_fraction": 0.7272727489471436,
"avg_line_length": 21,
"blob_id": "658050dd4fcc06a5c74206369c0418ee7f00534c",
"content_id": "58e99855b0d323e495897e7413e97f8bbac70724",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 22,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 1,
"path": "/csc4770-clientserver-LOAD Balancer/src/main/java/client.sh",
"repo_name": "BON-JIN/Reservation-system",
"src_encoding": "UTF-8",
"text": "java client.Client $@\n"
}
] | 11 |
erikbrorson/pythonTutorial | https://github.com/erikbrorson/pythonTutorial | 1971fd8f0ade9b81b5e52efe7f59ec46b4baafd8 | 06993a90eaf2163107344d9fa98d274377465523 | d32db426b2c8f657ccad79c2632ccc3b0fca5204 | refs/heads/master | 2021-01-19T07:41:26.690006 | 2017-10-01T16:16:30 | 2017-10-01T16:16:30 | 100,643,356 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5545976758003235,
"alphanum_fraction": 0.5603448152542114,
"avg_line_length": 21.66666603088379,
"blob_id": "fc8cfcbebe07f90ce05d11267c027e066b7ea357",
"content_id": "8e8e1f47a282a459345d7f957b3aef2c15e502ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 696,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 30,
"path": "/irisHelloWorld/helloWorld.py",
"repo_name": "erikbrorson/pythonTutorial",
"src_encoding": "UTF-8",
"text": "\nimport numpy as np\nimport pandas as pd\nfrom sklearn import tree\n\niris = pd.read_csv(\"/Users/Erik/Dropbox/Python Tutorial/irisHelloWorld/iris.csv\")\n\n\n# Create decision tree \n\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(y= iris.species, \n X = iris[[\"sepalLength\", \"sepalWidth\",\n \"petalLength\",\n \"petalWidth\"]])\n\nprediciton = clf.predict(X = iris[[\"sepalLength\", \"sepalWidth\",\n \"petalLength\",\n \"petalWidth\"]])\n\ndef numberCorrect(array):\n n = 0\n i = 0\n for x in array:\n if x == iris.species[i]:\n n = n + 1\n i = i + 1\n return n\n \n\nprint(numberCorrect(prediciton))\n\n\n \n "
},
{
"alpha_fraction": 0.8269230723381042,
"alphanum_fraction": 0.8269230723381042,
"avg_line_length": 68.33333587646484,
"blob_id": "ad9a7ff577617659306a64284b853717a1157773",
"content_id": "3518a911becb7db2a81f90ed0f3dfc6d5e362afe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 189,
"num_lines": 3,
"path": "/README.md",
"repo_name": "erikbrorson/pythonTutorial",
"src_encoding": "UTF-8",
"text": "# pythonTutorial\n\nIn order to get more comfortable with the python programming language, I collect some code snippets and smallers projects that I have completed to try out different packages and techniques.\n"
}
] | 2 |
ptiwaree/gregreda.com | https://github.com/ptiwaree/gregreda.com | e767bb8f76dc6e5e5ce4561a1c45c9a047f65f64 | 6528fc4a98ef43823859346e9ddcb36ad58c18b1 | 6ad21cc26d83629eaad5b01be22f5d84e7a5f3e8 | refs/heads/master | 2021-01-18T00:26:37.725755 | 2015-03-31T21:14:12 | 2015-03-31T21:14:12 | 33,423,681 | 1 | 0 | null | 2015-04-04T23:16:44 | 2015-03-31T21:14:21 | 2015-03-31T21:14:20 | null | [
{
"alpha_fraction": 0.5056179761886597,
"alphanum_fraction": 0.7078651785850525,
"avg_line_length": 15.952381134033203,
"blob_id": "e59972c66835c0aec5bebd9f0f55885fab5b21aa",
"content_id": "1041c70c0f6109888b7969c1afc5a74cc4cc25d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 356,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 21,
"path": "/requirements.txt",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Jinja2==2.7.3\nMarkdown==2.5.2\nMarkupSafe==0.23\nPygments==2.0.1\nUnidecode==0.04.17\nbackports.ssl-match-hostname==3.4.0.2\nblinker==1.3\ncertifi==14.05.14\ncssmin==0.2.0\ndocutils==0.12\nfeedgenerator==1.7\ngnureadline==6.3.3\nipython==1.2.1\npelican==3.5.0\npython-dateutil==2.3\npytz==2014.10\npyzmq==14.4.1\nsix==1.8.0\ntornado==4.0.2\nwebassets==0.10.1\nwsgiref==0.1.2\n"
},
{
"alpha_fraction": 0.7418546080589294,
"alphanum_fraction": 0.7418546080589294,
"avg_line_length": 39,
"blob_id": "79f3169721c497306f06dfd52113c43d5bcbac40",
"content_id": "b1a40d7f29f315f5f86a8e782541b70f9160b422",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 411,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 10,
"path": "/content/pages/coffee.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: Coffee?\nSlug: coffee\n\n\n\nI like coffee. You like coffee. So let’s get some together.\n\nWe can talk about tech, data, startups, sports, Chicago, life, … you name it. We’ll both probably learn something new in the process, and that’s fun.\n\n[Get in touch](mailto:[email protected]?subject=coffee) if you’re in Chicago and would like to grab coffee together. It’d be my pleasure."
},
{
"alpha_fraction": 0.7259658575057983,
"alphanum_fraction": 0.7879604697227478,
"avg_line_length": 91.83333587646484,
"blob_id": "92819ebd5fc7fb47bced64f6a7d5803922cbf73e",
"content_id": "2a31f736dc008ada895325ce0874123fa4121de6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1113,
"license_type": "no_license",
"max_line_length": 447,
"num_lines": 12,
"path": "/content/2013/10/intro-to-pandas-data-structures.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: Intro to pandas data structures\nDate: 2013-10-26 1:00\nSlug: intro-to-pandas-data-structures\nTags: python, pandas, sql, tutorial, data science\nDescription: Part one of a three part introduction to the pandas library. Geared towards SQL users, but is useful for anyone wanting to get started with pandas.\nAffiliate_Link: <iframe style=\"width:120px;height:240px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\" src=\"//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=gregrecom-20&marketplace=amazon®ion=US&placement=1449319793&asins=1449319793&linkId=FKL6YFFR7RIEILGT&show_border=true&link_opens_in_new_window=true\"></iframe>\n\n_UPDATE: If you're interested in learning pandas from a SQL perspective and would prefer to watch a video, you can find video of my 2014 PyData NYC talk [here](http://reda.io/sql2pandas)._\n\n{% notebook intro-to-pandas.ipynb cells[0:56] %}\n\n_Move onto the next section, which covers [working with DataFrames](/2013/10/26/working-with-pandas-dataframes/)._"
},
{
"alpha_fraction": 0.720588207244873,
"alphanum_fraction": 0.7677696347236633,
"avg_line_length": 36.953487396240234,
"blob_id": "8fd511b755b4306d2201306475e79aaf04dee5f3",
"content_id": "f2ad9bd18c7595110780527e50a23ba9eaeb8976",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1636,
"license_type": "no_license",
"max_line_length": 185,
"num_lines": 43,
"path": "/content/pages/about.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: About\nSlug: about\nTemplate: about\nurl: index.html\nsave_as: index.html\n\nI'm a freelance data scientist, developer, and occassional writer living in Chicago.\n\nPreviously, I was the first data hire at [GrubHub](https://www.grubhub.com/), \nwhere I led the data team for three years. \nI've also worked at [Datascope](http://www.datascopeanalytics.com) \nand [PwC](http://www.pwc.com).\n\nI'd love to work together. [Get in touch](mailto:[email protected]?subject=Work).\n\n<center>\n<hr class=“small”>\n## Press\n[Interview: Boost Data Literacy to Advance In Business](http://news.investors.com/management-leaders-in-success/020615-738296-data-literate-executives-understand-big-data-analytics.htm)\n\n- Investor's Business Daily, February 2015\n\n[Which Fantasy Football Sites Have The Best Projections?](http://regressing.deadspin.com/which-fantasy-football-sites-have-the-best-projections-1672790103)\n\n- Deadspin, December 2014\n\n[Interview: Are ESPN's Fantasy Football Projections Worthless?](http://chicagoinno.streetwise.co/2014/12/16/are-espn-fantasy-football-projections-legit-datascope-investigates/)\n\n- ChicagoInno, December 2014\n\n[How Accurate are ESPN's Fantasy Football Projections?](http://regressing.deadspin.com/how-accurate-are-espns-fantasy-football-projections-1669439884)\n\n- Deadspin, December 2014\n\n[The week in big data on Twitter, visualized](https://gigaom.com/2013/07/19/the-week-in-big-data-on-twitter-visualized/)\n\n- Gigaom, July 2013\n\n## Talks\n[Translating SQL to pandas. And back.](http://reda.io/pydata2014nyc)\n\n- PyData, New York, NY [[Video](http://reda.io/pydata2014nyc)] [[Slides](http://reda.io/sql2pandas)]\n</center>\n"
},
{
"alpha_fraction": 0.5710337162017822,
"alphanum_fraction": 0.5870646834373474,
"avg_line_length": 31.026548385620117,
"blob_id": "b307f0141c0e618b02e401366b733363204fe36a",
"content_id": "8c40b9d7a4caf46aadf8f45a56c95f52f0f97a62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3618,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 113,
"path": "/content/js/movie-releases.js",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "var path = \"/data/movie-releases.tsv\"\n\n// dynamically generate chart width\nvar parentWidth = $(\".article-content\").innerWidth();\n\nvar margin = {top: 20, right: 50, bottom: 20, left: 50},\n width = parentWidth - margin.left - margin.right,\n height = (parentWidth/2.0) - margin.top - margin.bottom;\n\nvar monthNames = [ \"Jan.\", \"Feb.\", \"Mar.\", \"Apr.\", \"May\", \"June\",\n \"July\", \"Aug.\", \"Sep.\", \"Oct.\", \"Nov.\", \"Dec.\" ];\n\nvar parseDate = d3.time.format(\"%Y-%m\").parse,\n bisectDate = d3.bisector(function(d) { return d.release_date; }).left,\n formatPercent = function(d) { return (d * 100).toFixed(2) + \"%\"; },\n formatDate = function(d) { return monthNames[d.getMonth()] + \" \" + d.getFullYear(); };\n\nvar x = d3.time.scale().range([0, width]);\nvar y = d3.scale.linear().range([height, 0]);\n\nvar xAxis = d3.svg.axis().scale(x).orient(\"bottom\");\nvar yAxis = d3.svg.axis().scale(y).orient(\"left\");\n\nvar line = d3.svg.line()\n .x(function(d) { return x(d.release_date); })\n .y(function(d) { return y(d.cumulative); });\n\nvar svg = d3.select(\"#vis\").append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n.append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\nd3.tsv(path, function(error, data) {\ndata.forEach(function(d) {\n d.release_date = parseDate(d.release_date);\n d.percentage = +d.percentage;\n d.cumulative = +d.cumulative;\n});\n\nx.domain(d3.extent(data, function(d) { return d.release_date; }));\ny.domain(d3.extent(data, function(d) { return d.cumulative; }));\n\nsvg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis);\n\nsvg.append(\"g\")\n .attr(\"class\", \"y axis\")\n .call(yAxis)\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(\"% of total films\");\n\nsvg.append(\"path\")\n .datum(data)\n .attr(\"class\", \"line\")\n .attr(\"d\", line);\n\n// draw bar chart\n// svg.selectAll(\".bar\")\n// .data(data)\n// .enter().append(\"rect\")\n// .attr(\"class\", \"bar\")\n// .attr(\"x\", function(d) { return x(d.release_date); })\n// .attr(\"width\", \"3px\")\n// .attr(\"y\", function(d) { return y(d.percentage); })\n// .attr(\"height\", function(d){ return height - y(d.percentage); });\n\n// mouseover labels\nvar focus = svg.append(\"g\")\n .attr(\"class\", \"focus\")\n .style(\"display\", \"none\");\n\nfocus.append(\"circle\")\n .attr(\"r\", 4.5);\n\nfocus.append(\"text\")\n .attr(\"x\", 9)\n .attr(\"dy\", \".35em\");\n\nsvg.append(\"rect\")\n .attr(\"class\", \"overlay\")\n .attr(\"width\", width)\n .attr(\"height\", height)\n .on(\"mouseover\", function() { focus.style(\"display\", null); })\n .on(\"mouseout\", function() { focus.style(\"display\", \"none\"); })\n .on(\"mousemove\", mousemove);\n\nvar textArea = svg.append(\"text\")\n .attr(\"class\", \"mouseover-text\")\n .attr(\"x\", width - 125)\n .attr(\"y\", height - 10)\n .on(\"mouseover\", function() { focus.style(\"display\", null); })\n .on(\"mouseout\", function() { focus.style(\"display\", \"none\"); })\n .on(\"mousemove\", mousemove);\n\nfunction mousemove() {\n var x0 = x.invert(d3.mouse(this)[0]),\n i = bisectDate(data, x0, 1),\n d0 = data[i - 1],\n d1 = data[i],\n d = x0 - d0.release_date > d1.release_date - x0 ? d1 : d0;\n focus.attr(\"transform\", \"translate(\" + x(d.release_date) + \",\" + y(d.cumulative) + \")\");\n // focus.select(\"text\")\n // .text(formatDate(d.release_date) + \": \" + formatPercent(d.cumulative));\n textArea.text(formatDate(d.release_date) + \": \" + formatPercent(d.cumulative));\n}\n});"
},
{
"alpha_fraction": 0.6717921495437622,
"alphanum_fraction": 0.6887592673301697,
"avg_line_length": 26.735294342041016,
"blob_id": "d0a701a6fae21938ce3c623a5f516343baaac813",
"content_id": "98b75849b8950738a399aec87e7b9b9ea5f3febd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1886,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 68,
"path": "/pelicanconf.py",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\n\nAUTHOR = u'Greg Reda'\nSITENAME = u'Greg Reda'\nEMAIL_ADDRESS = u'[email protected]'\nSITEURL = 'http://www.gregreda.com'\nTIMEZONE = 'America/Chicago'\nTHEME = 'void/'\nAVATAR = '/theme/images/avatar.jpg'\nTITLE = \"Greg Reda: independent data science and strategy consulting.\"\nDESCRIPTION = \"Greg Reda is an independent data science and strategy \\\nconsultant, helping clients effectively utilize data to gain insight, \\\ninform decisions, and grow their business.\"\n\n# TODO: switch to /blog/slug/index.html -- need to setup redirects first\nARTICLE_URL = '{date:%Y}/{date:%m}/{date:%d}/{slug}/'\nARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html'\n\n# Static Pages\nPAGE_PATHS = ['pages']\nPAGE_URL = '{slug}/'\nPAGE_SAVE_AS = '{slug}/index.html'\nABOUT_PAGE_HEADER = 'Nice to meet you.'\n\n# DEFAULTS\nDEFAULT_LANG = 'en'\nDEFAULT_CATEGORY = 'misc'\nDEFAULT_DATE = 'fs'\nDEFAULT_DATE_FORMAT = '%b %d, %Y'\nDEFAULT_PAGINATION = False\n\n# FEEDS\nFEED_ALL_ATOM = \"feeds/all.atom.xml\"\nTAG_FEED_ATOM = \"feeds/tag/%s.atom.xml\"\n\n# PLUGINS\nPLUGIN_PATHS = ['pelican-plugins', 'pelican_dynamic']\nPLUGINS = ['assets', 'liquid_tags.notebook', 'pelican_dynamic', 'render_math']\n\nCODE_DIR = 'code'\nNOTEBOOK_DIR = 'notebooks'\nEXTRA_HEADER = open('_nb_header.html').read().decode('utf-8')\n\nSTATIC_PATHS = ['images', 'code', 'notebooks', 'extra']\nEXTRA_PATH_METADATA = {'extra/robots.txt': {'path': 'robots.txt'},}\n\n# TODO: NAVBAR - make it dynamic\nNAVIGATION = [\n (),\n]\n\n# TODO: SOCIAL - make it dynamic\nTWITTER_CARDS = True\nTWITTER_NAME = \"gjreda\"\nGITHUB_NAME = 'gjreda'\nLINKEDIN_URL = 'http://linkedin.com/in/gjreda'\nGOOGLE_PLUS_URL = 'https://plus.google.com/111658599948853828157?rel=author'\nLASTFM_NAME = 'gjreda'\n\n#### Analytics\nGOOGLE_ANALYTICS = 'UA-34295039-1'\nDOMAIN = \"gregreda.com\"\n\n# Other\nMAILCHIMP = True\nCACHE_CONTENT = False\nAUTORELOAD_IGNORE_CACHE = True\n"
},
{
"alpha_fraction": 0.7330508232116699,
"alphanum_fraction": 0.7796609997749329,
"avg_line_length": 84.86363983154297,
"blob_id": "c1ad31b1c40faee1add31efa516215ca6c74591f",
"content_id": "66527137e6a10c4124fdddd22b8c87aaabff1114",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1888,
"license_type": "no_license",
"max_line_length": 447,
"num_lines": 22,
"path": "/content/2013/10/using-pandas-on-the-movielens-dataset.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: Using pandas on the MovieLens dataset\nDate: 2013-10-26 3:00\nSlug: using-pandas-on-the-movielens-dataset\nTags: python, pandas, sql, tutorial, data science\nDescription: Part three of a three part introduction to the pandas library for Python. It is geared towards SQL users, but is useful for anyone wanting to get started with pandas.\nAffiliate_Link: <iframe style=\"width:120px;height:240px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\" src=\"//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=gregrecom-20&marketplace=amazon®ion=US&placement=1449319793&asins=1449319793&linkId=FKL6YFFR7RIEILGT&show_border=true&link_opens_in_new_window=true\"></iframe>\n\n_UPDATE: If you're interested in learning pandas from a SQL perspective and would prefer to watch a video, you can find video of my 2014 PyData NYC talk [here](http://reda.io/sql2pandas)._\n\n_This is part three of a three part introduction to [pandas](http://pandas.pydata.org), a Python library for data analysis. The tutorial is primarily geared towards SQL users, but is useful for anyone wanting to get started with the library._\n\n_Part 1: [Intro to pandas data structures](/2013/10/26/intro-to-pandas-data-structures/)_\n\n_Part 2: [Working with DataFrames](/2013/10/26/working-with-pandas-dataframes/)_\n\n_Part 3: [Using pandas with the MovieLens dataset](/2013/10/26/using-pandas-on-the-movielens-dataset/)_\n\n{% notebook intro-to-pandas.ipynb cells[124:] %}\n\n**Closing**\n\nThis is the point where I finally wrap this tutorial up. Hopefully I've covered the basics well enough to pique your interest and help you get started with the library. If I've missed something critical, feel free to [let me know on Twitter](https://twitter.com/gjreda) or in the comments - I'd love constructive feedback."
},
{
"alpha_fraction": 0.7460238337516785,
"alphanum_fraction": 0.7673956155776978,
"avg_line_length": 51.94736862182617,
"blob_id": "8348ef5466ae5139ecca4ea2db040648078be14b",
"content_id": "6ce1c40abdbd1d3a124de88128ff56a92f36aa60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2012,
"license_type": "no_license",
"max_line_length": 325,
"num_lines": 38,
"path": "/content/2014/01/majority-of-movies-made.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: Finding the midpoint of film releases\nDate: 2014-01-23\nSlug: film-releases-midpoint\nTags: data science, movies, d3js, visualization\nDescription: Looking film release dates throughout history to determine the date that has an equal number of films made before and after it.\nD3:\nScripts: movie-releases.js\nStyles: styles.css\n\n> \"We're talking about Thunderdome. It's from before you were born.\"\n\n> \"Most movies are from before I was born.\"\n\nThat statement spurred a pretty interesting question: *what's the date where that statement is no longer true?* Put another way, *what date in history has an equal number of films made before and after it?*\n\nMy birthday, November 4, 1985, *felt* like a relatively safe date, but really, no one had a clue if what I said was true, including me. Guesses by about a dozen coworkers included dates from September 1963 all the way to September 2001.\n\nKnowing that [IMDB](http://imdb.com) makes their [data publicly available](http://www.imdb.com/interfaces), I decided to find the actual date. Using the most current [releases.list file](ftp://ftp.fu-berlin.de/pub/misc/movies/database/release-dates.list.gz) (1/17/14 at the time of writing), I held the following assumptions:\n\n1. Only films. The release-dates.list also includes TV shows and video games. It also includes movies that went straight to video - those count.\n\n2. Films with a release date in the future do not count.\n\n3. If the film was released multiple times (different release dates for different countries), use the earliest release date.\n\n4. If only a release month and year were provided, assume the 15th of that month.\n\n5. If only a release year was provided, assume [July 2nd](http://en.wikipedia.org/wiki/July_2) of that year.\n\nThe result?\n\n<div id=\"vis\" class=\"chart\"></div>\n\nMay 15, 2002.\n\nOf course, given the current rate at which films are being made, this analysis is already out of date.\n\nFor those interested, you can find the code [here](https://github.com/gjreda/movie-release-timeline).\n"
},
{
"alpha_fraction": 0.7200971245765686,
"alphanum_fraction": 0.7795992493629456,
"avg_line_length": 81.4000015258789,
"blob_id": "55d465b0e891027f5de16fa4b94447e530a2012c",
"content_id": "6b089b2d52a7127a42c9aa8598800d19becd8557",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1647,
"license_type": "no_license",
"max_line_length": 447,
"num_lines": 20,
"path": "/content/2013/10/working-with-pandas-dataframes.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: Working with DataFrames\nDate: 2013-10-26 2:00\nSlug: working-with-pandas-dataframes\nTags: python, pandas, sql, tutorial, data science\nDescription: Part two of a three part introduction to the pandas library for Python. It is geared towards SQL users, but is useful for anyone wanting to get started with pandas.\nAffiliate_Link: <iframe style=\"width:120px;height:240px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\" src=\"//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=gregrecom-20&marketplace=amazon®ion=US&placement=1449319793&asins=1449319793&linkId=FKL6YFFR7RIEILGT&show_border=true&link_opens_in_new_window=true\"></iframe>\n\n_UPDATE: If you're interested in learning pandas from a SQL perspective and would prefer to watch a video, you can find video of my 2014 PyData NYC talk [here](http://reda.io/sql2pandas)._\n\n_This is part two of a three part introduction to [pandas](http://pandas.pydata.org), a Python library for data analysis. The tutorial is primarily geared towards SQL users, but is useful for anyone wanting to get started with the library._\n\n_Part 1: [Intro to pandas data structures](/2013/10/26/intro-to-pandas-data-structures/)_\n\n_Part 2: [Working with DataFrames](/2013/10/26/working-with-pandas-dataframes/)_\n\n_Part 3: [Using pandas with the MovieLens dataset](/2013/10/26/using-pandas-on-the-movielens-dataset/)_\n\n{% notebook intro-to-pandas.ipynb cells[56:124] %}\n\n_Move onto part three, [using pandas with the MovieLens dataset](/2013/10/26/using-pandas-on-the-movielens-dataset/)._"
},
{
"alpha_fraction": 0.7569060921669006,
"alphanum_fraction": 0.7817679643630981,
"avg_line_length": 44.375,
"blob_id": "15b704bbf5f92f1f4a46345adddffd531c150110",
"content_id": "982b8a53cac0c4dab184dc3431ef8982dcc613f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 362,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 8,
"path": "/content/2013/12/three-pointers-after-rebounds.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Title: 3-pointers after offensive rebounds\nDate: 2013-12-26\nSlug: three-pointers-after-offensive-rebounds\nTags: scraping, pandas, data science, basketball, sports, simulation\n\n{% notebook three-pointers-after-rebounds.ipynb cells[:] %}\n\nWas there something I missed or got wrong? [I'd love to hear from you](mailto:[email protected]?subject=Three+pointers+after+rebounds)."
},
{
"alpha_fraction": 0.7400000095367432,
"alphanum_fraction": 0.7400000095367432,
"avg_line_length": 82.33333587646484,
"blob_id": "eef69bc0505b21eae5104a20f8a781916611500b",
"content_id": "1a678f2b7526d95366ae3c4682437b34248f5728",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 250,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 3,
"path": "/README.md",
"repo_name": "ptiwaree/gregreda.com",
"src_encoding": "UTF-8",
"text": "Source for my personal site, [gregreda.com](http://www.gregreda.com).\n\nThe site is built with [Pelican](https://github.com/getpelican/pelican/), [Font Awesome](http://fortawesome.github.io/Font-Awesome/), and [Skeleton](http://www.getskeleton.com/).\n"
}
] | 11 |
shanmuk184/SalesCrmbackend | https://github.com/shanmuk184/SalesCrmbackend | d32e9c51bad4e0d1e3d96dcd3b9ca62c13031c29 | 6580314cf418d1a4609cf04c585d368847a02259 | 64d6bcbb4052fb7ad5a7d2399eab8ff0324c788f | refs/heads/master | 2022-12-09T12:02:11.003266 | 2019-12-02T16:55:03 | 2019-12-02T16:55:03 | 223,997,894 | 0 | 0 | null | 2019-11-25T16:51:56 | 2019-12-02T16:55:14 | 2022-12-08T06:56:34 | Python | [
{
"alpha_fraction": 0.5251364707946777,
"alphanum_fraction": 0.5277219414710999,
"avg_line_length": 32.786407470703125,
"blob_id": "cde63457f12e1b3df2d77446639633eb7c47a32d",
"content_id": "b05f1dfec607f6dd3c51cf384079222c8d3ae73b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3481,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 103,
"path": "/api/stores/base.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "import datetime\n\nclass BaseStoreModel:\n def __init__(self):\n self._data_dict = {}\n\n class BaseProperties:\n CreatedAt = 'created_at'\n UpdatedAt = 'updated_at'\n _reverseMapping = {}\n\n class PropertyNames:\n pass\n\n class ReverseMapping:\n pass\n\n @property\n def datadict(self):\n _flat_dict = {}\n for key in self._data_dict:\n value = self._data_dict.get(key)\n if isinstance(value, BaseStoreModel):\n _flat_dict[key] = value.datadict\n elif isinstance(value, list):\n entries = []\n for listItem in value:\n if isinstance(listItem, BaseStoreModel):\n entries.append(listItem.datadict)\n else:\n entries.append(listItem)\n _flat_dict[key] = entries\n else:\n _flat_dict[key] = value\n if not self.BaseProperties.CreatedAt not in _flat_dict:\n _flat_dict[self.BaseProperties.CreatedAt]=datetime.datetime.now()\n if not self.BaseProperties.UpdatedAt not in _flat_dict:\n _flat_dict[self.BaseProperties.UpdatedAt] = datetime.datetime.now()\n return _flat_dict\n\n def populate_data_dict(self, dictParam=None):\n _flat_dict=dictParam\n if self._reverseMapping:\n for key in _flat_dict:\n reverseMapping = self._reverseMapping.get(key)\n value = dictParam[key]\n if reverseMapping:\n if len(reverseMapping) == 2:\n if not isinstance(value, reverseMapping[1]):\n value = reverseMapping[1](dictParam[key])\n self.set_value(key, value)\n elif len(reverseMapping) == 3:\n valueList = dictParam[key]\n values = []\n for value in valueList:\n holding_container = reverseMapping[2]()\n holding_container.populate_data_dict(value)\n values.append(holding_container)\n self.set_value(key, values)\n else:\n self.set_value(key, value)\n\n\n\n def __getattr__(self, item):\n item_key = [key for key in self._reverseMapping if self._reverseMapping[key][0] ==item]\n if item_key:\n return self._data_dict.get(item_key[0])\n # return super().__g(item)\n\n\n def __setattr__(self, item, value):\n item_key = [key for key in self._reverseMapping if self._reverseMapping[key][0] == item]\n if item_key:\n self._data_dict[item_key[0]] = value\n super().__setattr__(item, value)\n\n# For future\n# class BaseApiModel(object):\n# def __init__(self):\n# self._data_dict = {}\n# def populate_data_dict(self, dictParam):\n# if not dictParam:\n# raise NotImplementedError()\n# missing_fields = list(set(list(self._fields)).difference(set(dictParam.keys())))\n# if missing_fields:\n# raise ValueError(missing_fields)\n# for key in dictParam:\n# self._data_dict[key] = dictParam.get(key)\n#\n\n\n def get_value(self, key):\n if not key:\n raise NotImplementedError()\n return self._data_dict.get(key)\n\n def set_value(self, key, value):\n\n self._data_dict[key] = value\n\n\n _fields = ()\n\n"
},
{
"alpha_fraction": 0.7010935544967651,
"alphanum_fraction": 0.7010935544967651,
"avg_line_length": 36.3636360168457,
"blob_id": "2411d36e551204f9c9a5f4495401c10bb7a4692d",
"content_id": "c79a85519f907bb7f3185a6f5d579f70fdf1205a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 823,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 22,
"path": "/api/models/Product.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado.gen import *\nfrom api.core.product import ProductHelper\nfrom api.stores.product import Product\nfrom api.models.base import BaseModel\n\nclass ProductModel(BaseModel):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self._ph = ProductHelper(**kwargs)\n\n @coroutine\n def create_product_for_group(self, productDict):\n if not productDict:\n raise Return((False))\n\n product = Product()\n product.Name = productDict.get(product.PropertyNames.Name)\n product.ProductCode = productDict.get(product.PropertyNames.ProductCode)\n product.ProductId = productDict.get(product.PropertyNames.ProductId)\n product.GroupId = productDict.get(product.PropertyNames.GroupId)\n product_result = yield self._ph.create_product(product.datadict)\n\n"
},
{
"alpha_fraction": 0.6703833937644958,
"alphanum_fraction": 0.6709702610969543,
"avg_line_length": 39.84000015258789,
"blob_id": "916565eb8653c883d663e687efcb07262cff17fb",
"content_id": "1e0b861b6af165c6f2581f961d9eab730e60b906",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5112,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 125,
"path": "/api/models/group.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from api.stores.group import *\nfrom api.stores.user import User, GroupMapping, UserStatus, LinkedAccount, LinkedAccountType\nfrom api.stores.employee import Employee, SupportedRoles, GroupStatus\nfrom tornado.gen import *\nfrom api.core.user import UserHelper\nfrom api.models.base import BaseModel\nfrom api.core.group import GroupHelper\nimport uuid\nimport datetime\n\nclass GroupModel(BaseModel):\n @coroutine\n def create_group(self, groupDict, userId=None, type=None):\n if not userId:\n userId = self._user.UserId\n group = Group()\n group.Name = groupDict.get(CreateGroupRequestParams.Name)\n group.Type = groupDict.get(CreateGroupRequestParams.Type)\n group.OwnerId = userId\n # membermappings = [self._gh.create_member_mapping(userId, [SupportedRoles.Admin])]\n # group.MemberMappings = membermappings\n group.set_value(group.PropertyNames.CreatedTimeStamp, datetime.datetime.now())\n group.set_value(group.PropertyNames.UpdatedTimeStamp, datetime.datetime.now())\n group.Id = uuid.uuid4()\n yield self._gh.create_group_for_user(group.datadict)\n yield self.create_employee_profile(userId, group.Id, SupportedRoles.Admin)\n\n #\n # @coroutine\n # def create_employee(self, employeeDict, addedby=None):\n # # create member mapping for employee\n # employeeId = employeeDict.get('employee')\n # membermappings = [self._gh.create_member_mapping(userId, [SupportedRoles.Admin])]\n #\n # Pharmaceutical distributor is a kind of group that don't have link to Pharmacy company only reverse link\n\n\n @coroutine\n def create_pharmaceutical_distributor(self, **kwargs):\n group = self.create_group(kwargs, self._user.UserId, GroupType.PharmaDistributor)\n raise Return(group)\n\n @coroutine\n def create_employee_profile(self, userId, groupId, role):\n employee = Employee()\n employee.Id = uuid.uuid4()\n employee.UserId = userId\n employee.GroupId = groupId\n employee.Role = role\n if role == SupportedRoles.Admin:\n employee.Status = GroupStatus.Joined\n else:\n employee.Status = GroupStatus.Invited\n employee.CreatedTimeStamp = datetime.datetime.utcnow()\n employee.UpdatedTimeStamp = datetime.datetime.utcnow()\n yield self._uh.save_user(employee.datadict)\n\n\n # Dummy team for employees\n @coroutine\n def create_employee_team(self, **kwargs):\n group = self.create_group(kwargs, self._user.UserId, GroupType.EmployeeTeam)\n raise Return(group)\n\n def populate_group_response(self, group):\n returning_dict = {}\n returning_dict[GroupResponse.Name] = group.Name\n returning_dict[GroupResponse.Id] = str(group.Id)\n returning_dict[GroupResponse.MemberCount] = len(group.MemberMappings)\n return returning_dict\n\n @coroutine\n def create_invited_state_user(self, invitedDict, groupId):\n employee = User()\n employee.Name = invitedDict.get(CreateEmployeeRequestParams.Name)\n employee.Phone = invitedDict.get(CreateEmployeeRequestParams.Phone)\n employee.UserId = uuid.uuid4()\n account = LinkedAccount()\n password = yield self.get_hashed_password(invitedDict.get(CreateEmployeeRequestParams.Password))\n account.AccountName = employee.Phone\n account.AccountHash = password.get('hash')\n account.AccountType = LinkedAccountType.Native\n employee.Status = UserStatus.Invited\n employee.EmailValidated = False\n employee.CreatedTimeStamp = datetime.datetime.now()\n employee.UpdatedTimeStamp = datetime.datetime.now()\n yield self._uh.save_user(employee.datadict)\n raise Return(employee)\n\n @coroutine\n def get_groups_where_user_is_owner(self, userId):\n if not userId:\n userId = self._user.UserId\n try:\n (groups) = yield self._gh.get_groups_where_user_is_owner(userId)\n groupsToReturn = list(map(lambda x: self.populate_group_response(x), groups))\n\n except Exception as e:\n raise Return((False, str(e)))\n else:\n raise Return((True, groupsToReturn))\n\n # @coroutine\n # def create_unique_invitation_code(self):\n # invitation_codes = yield self._uh.get_all_invitation_codes()\n\n @coroutine\n def create_employee(self, groupId, employeeDict):\n \"\"\"\n Employee added by admin.\n This method takes input from admin and creates user profile and\n creates membermapping for corresponding group.\n employeeDict should contain\n name,\n designation\n emailid\n :return:\n \"\"\"\n if not isinstance(groupId, uuid.UUID):\n groupId = uuid.UUID(groupId)\n if not (employeeDict and groupId):\n raise NotImplementedError()\n employee = yield self.create_invited_state_user(employeeDict, groupId)\n yield self.create_employee_profile(employee.UserId, groupId, SupportedRoles.SalesRep)\n raise Return({'status':'success'})\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7116182446479797,
"alphanum_fraction": 0.7116182446479797,
"avg_line_length": 28.18181800842285,
"blob_id": "7111a23a738643c249454de72ea288b95ffb25ab",
"content_id": "288303d2bf5ba3c73833fd39d7d12d5fd0087741",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 964,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 33,
"path": "/docs/flow.md",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "## Start Server\npython app.py\n## Start mongo\nmongod --fork --logpath /var/log/mongodb.log\n\n\n### This part defines different sections of Application flow\n####Registration service\n```\n User has to register as admin user.\n create his group.\n add employees to his group.\n Let's add email as authentication for now.\n Each employees are registered by their emailids.\n Employees can then register using their registered email address.\n Password will be the same as emailid for now.\n This is for registration service.\n```\n####User Service\n```\n There are two kinds of users in this system for now.\n One is admin and another is employee.\n Admin has to create a group to add employees.\n Each employees are registered to their groups as members.\n \n```\n####Attendance service\n```\n This service assumes different user types by default.\n Employees submit their attendance by submitting their location, Fingerprint.\n \n \n```\n\n"
},
{
"alpha_fraction": 0.5633898377418518,
"alphanum_fraction": 0.5728813409805298,
"avg_line_length": 31.086956024169922,
"blob_id": "728be9c3920bbfb10b9cf8535038361fab952518",
"content_id": "d7c7b698847a382c1d5e680ac22139a2a44e4d67",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1475,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 46,
"path": "/app.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "import tornado.ioloop\nimport tornado.web\nfrom urls import urlpatterns\nfrom db.db import Database\nfrom config.config import Settings\nfrom tornado_swirl.swagger import Application, describe\nfrom tornado_swirl import api_routes\nfrom tornado.options import define, options\n\nsettings = Settings()\n\ndescribe(title='UMS API', description='Manages User Operations')\ndefine('mongo_host', default='127.0.0.1:')\n\n\nclass MyApplication(object):\n def __init__(self):\n self.database = Database()\n self.initiateApp()\n\n def initiateApp(self):\n app = self.make_app()\n app.listen(8888)\n\n def make_app(self):\n db = self.database.get_motor_connection()\n return tornado.web.Application(api_routes(),\n db = db,\n cookie_secret=settings.CookieSecret,\n debug=settings.Debug,\n key_version=settings.KeyVersion,\n version=settings.Version,\n login_url='api/login'\n )\n\nclass MainHandler(tornado.web.RequestHandler):\n \"\"\"This is the main handler\"\"\"\n def get(self):\n self.write(\"Hello, world\")\n\n\nif __name__ == \"__main__\":\n app = MyApplication()\n print(\"server is running on 8888\")\n tornado.ioloop.IOLoop.current().start()\n io_loop = tornado.ioloop.IOLoop.instance()"
},
{
"alpha_fraction": 0.471321702003479,
"alphanum_fraction": 0.6882793307304382,
"avg_line_length": 15.039999961853027,
"blob_id": "6d76c029aa595dbffbf3d7f060b7b1361a9d8336",
"content_id": "a8b61815ccc4aea728967fa27a02b4084ec90ef0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 401,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 25,
"path": "/requirements.txt",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "apispec==2.0.2\nattrs==19.1.0\nbcrypt==3.1.7\ncertifi==2019.9.11\ncffi==1.12.3\nchardet==3.0.4\neasydict==1.9\nidna==2.8\njsonschema==3.0.2\nmotor==1.2.1\nmotorengine==1.0.0\nopenapi-spec-validator==0.2.8\nprance==0.16.0\npycparser==2.19\nPyJWT==1.7.1\npymongo==3.6.0\npyrsistent==0.15.4\nPyYAML==5.1.2\nrequests==2.22.0\nsemver==2.8.1\nsimplejson==3.16.0\nsix==1.12.0\ntornado==6.0.3\ntornado-swirl==0.1.19\nurllib3==1.25.3\n"
},
{
"alpha_fraction": 0.6191369891166687,
"alphanum_fraction": 0.6228892803192139,
"avg_line_length": 34.53333282470703,
"blob_id": "976723c819a84cd65c120f303f63c3bccf57025a",
"content_id": "9c27d07dba98f5f96931d4d02552a2fbaefaedd5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1066,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 30,
"path": "/api/models/base.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from api.core.user import UserHelper\nfrom api.core.group import GroupHelper\nfrom tornado.gen import coroutine, Return\nimport bcrypt\n\nclass BaseModel(object):\n def __init__(self, **kwargs):\n if not kwargs.get('db'):\n raise ValueError('db should be present')\n self._user = None\n if kwargs.get('user'):\n self._user = kwargs.get('user')\n self.db = kwargs.get('db')\n\n if self._user:\n self._gh = GroupHelper(**kwargs)\n self._uh = UserHelper(**kwargs)\n elif self.db:\n self._gh = GroupHelper(db=self.db)\n self._uh = UserHelper(db=self.db)\n\n @coroutine\n def get_hashed_password(self, plain_text_password:str):\n if not plain_text_password:\n raise NotImplementedError()\n raise Return({'hash':bcrypt.hashpw(plain_text_password.encode('utf-8'), bcrypt.gensalt(12))})\n\n @coroutine\n def check_hashed_password(self, text_password, hashed_password):\n raise Return(bcrypt.checkpw(text_password.encode('utf-8'), hashed_password))\n"
},
{
"alpha_fraction": 0.6051020622253418,
"alphanum_fraction": 0.6051020622253418,
"avg_line_length": 24.789474487304688,
"blob_id": "3ce532130c8e41c9378c873d930539c4425d0e22",
"content_id": "3c25ebefcebcec81bf0ea5f9ed07a6028aaeac7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1960,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 76,
"path": "/api/stores/product.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from api.stores.base import BaseStoreModel\nfrom bson import ObjectId\n\n\n\nclass Product(BaseStoreModel):\n class PropertyNames:\n Name = 'name'\n ProductCode = 'pc'\n Type = 'type'\n SaleScheme = 'ss'\n PurchaseScheme = 'ps'\n CostPrice = 'cp'\n MRP = 'mrp'\n Id = '_id'\n AvailableQuantity = 'aq'\n SalePrice = 'sp'\n PurchasePrice = 'pp'\n GroupId = 'groupid'\n\n @property\n def AvailableQuantity(self):\n return self.get_value(self.PropertyNames.AvailableQuantity)\n\n\n # _reverseMapping={\n # '_id':(_id, ObjectId),\n # 'pc':(ProductCode, str),\n # 'name':('Name', str),\n # 'pId':('ProductId', str)\n # }\n\n @property\n def Name(self):\n name = self.get_value(self.PropertyNames.Name)\n if name:\n return name\n @Name.setter\n def Name(self, name):\n if not name:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Name, name)\n\n @property\n def GroupId(self):\n name = self.get_value(self.PropertyNames.GroupId)\n\n return name\n @GroupId.setter\n def GroupId(self, groupId):\n if not groupId:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.GroupId, groupId)\n\n @property\n def ProductCode(self):\n productcode = self.get_value(self.PropertyNames.ProductCode)\n\n return productcode\n @ProductCode.setter\n def ProductCode(self, productcode):\n if not productcode:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.ProductCode, productcode)\n\n\n @property\n def ProductId(self):\n productid = self.get_value(self.PropertyNames.ProductId)\n return productid\n\n @ProductId.setter\n def ProductId(self, productid):\n if not productid:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.ProductId, productid)\n"
},
{
"alpha_fraction": 0.6408461928367615,
"alphanum_fraction": 0.6408461928367615,
"avg_line_length": 25.871795654296875,
"blob_id": "96952d09768d418aa45c7db0e8d10a4323fe2ccb",
"content_id": "605a72f734bc59e2d934e20b7a231addb0953223",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6287,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 234,
"path": "/api/stores/group.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from .base import BaseStoreModel\nfrom enum import Enum\nfrom api.stores.product import Product\nfrom bson import ObjectId\nfrom datetime import datetime\nimport uuid\n\n\nclass CreateEmployeeRequestParams:\n Name = 'name'\n Designation='designation'\n Password = 'password'\n EmailId = 'email_id'\n Phone = 'phone'\n\n\nclass GroupType(Enum):\n Stockist = 'res'\n Direct = 'phc'\n Doctor = 'phd'\n Counter = 'emt'\n\nclass GroupResponse:\n Name = 'name'\n Id = 'id'\n MemberCount = 'memberCount'\n createdDateTime = 'createdDateTime'\n updatedDateTime = 'updatedDateTime'\n\n\n\nclass MemberMapping(BaseStoreModel):\n class PropertyNames:\n MemberId = 'member_id'\n Designation = \"designation\"\n Roles = 'roles'\n Status = 'status'\n Shifts = 'shift'\n Tasks = 'tasks'\n JoinedTimeStamp='jts'\n LastUpdatedTimeStamp='lts'\n\n @property\n def MemberId(self):\n return self.get_value(self.PropertyNames.MemberId)\n\n @MemberId.setter\n def MemberId(self, memberId):\n if not memberId:\n raise NotImplementedError('you must enter memberId')\n return self.set_value(self.PropertyNames.MemberId, memberId)\n\n @property\n def Designation(self):\n return self.get_value(self.PropertyNames.Designation)\n\n @Designation.setter\n def Designation(self, title):\n if not title:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Designation, title)\n\n @property\n def Roles(self):\n return self.get_value(self.PropertyNames.Roles)\n\n @Roles.setter\n def Roles(self, roles):\n if not roles:\n raise NotImplementedError('you must give roles')\n return self.set_value(self.PropertyNames.Roles, roles)\n\n\n @property\n def Status(self):\n return self.get_value(self.PropertyNames.Status)\n\n @Status.setter\n def Status(self, status):\n if not status:\n raise NotImplementedError('you must give roles')\n return self.set_value(self.PropertyNames.Status, status)\n\n @property\n def JoinedTimeStamp(self):\n return self.get_value(self.PropertyNames.JoinedTimeStamp)\n\n @JoinedTimeStamp.setter\n def JoinedTimeStamp(self, jts):\n if not jts:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.JoinedTimeStamp, jts)\n\n\n @property\n def LastUpdatedTimeStamp(self):\n return self.get_value(self.PropertyNames.LastUpdatedTimeStamp)\n\n @LastUpdatedTimeStamp.setter\n def LastUpdatedTimeStamp(self, lts):\n if not lts:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.LastUpdatedTimeStamp, lts)\n\n\nclass SubGroupType:\n EmployeeGroup = 'emg'\n\nclass SubGroup(BaseStoreModel):\n class PropertyNames:\n Name = 'name'\n Type = 'type'\n\n\n @property\n def Name(self):\n return self.get_value(self.PropertyNames.Name)\n\n @Name.setter\n def Name(self, name):\n if not name:\n raise NotImplementedError('you must give roles')\n return self.set_value(self.PropertyNames.Name, name)\n\n\n @property\n def Type(self):\n return self.get_value(self.PropertyNames.Type)\n\n @Type.setter\n def Type(self, subgroupType):\n if not subgroupType:\n raise NotImplementedError('you must give roles')\n return self.set_value(self.PropertyNames.Type, subgroupType)\n\nclass ProductMapping(BaseStoreModel):\n pass\n\nclass CreateGroupRequestParams:\n Name = 'groupName'\n Type = 'groupType'\nclass Group(BaseStoreModel):\n\n class PropertyNames:\n Id = '_id'\n Name = 'name'\n EmployeeCount = 'employee_count'\n OwnerId = 'owner_id'\n Type = 'type'\n MemberMappings = 'membermappings'\n Products = 'products'\n CreatedTimeStamp = 'cts'\n UpdatedTimeStamp = 'uts'\n\n _reverseMapping = {\n '_id': ('Id', uuid.UUID),\n 'name':('Name', str),\n 'employee_count': ('EmployeeCount', int),\n 'owner_id': ('OwnerId', uuid.UUID),\n 'membermappings': ('MemberMappings', list, MemberMapping),\n 'products': ('Products', list, Product),\n 'cts':('CreatedTimeStamp', datetime),\n 'uts': ('UpdatedTimeStamp', datetime)\n }\n\n @property\n def Id(self):\n return self.get_value(self.PropertyNames.Id)\n @Id.setter\n def Id(self, id):\n if not id:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Id, id)\n\n\n @property\n def Name(self):\n return self.get_value(self.PropertyNames.Name)\n\n @Name.setter\n def Name(self, name):\n if not name:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Name, name)\n\n @property\n def OwnerId(self):\n self.get_value(self.PropertyNames.OwnerId)\n\n @OwnerId.setter\n def OwnerId(self, ownerid):\n if not ownerid:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.OwnerId, ownerid)\n\n @property\n def Type(self):\n return self.get_value(self.PropertyNames.Type)\n\n @Type.setter\n def Type(self, type):\n if not type:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Type, type)\n\n @property\n def Products(self):\n return self.get_value(self.PropertyNames.Products)\n\n @Products.setter\n def Products(self, products):\n if not products:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Products, products)\n\n @property\n def MemberMappings(self):\n return self.get_value(self.PropertyNames.MemberMappings)\n\n @MemberMappings.setter\n def MemberMappings(self, membermappings):\n if not membermappings:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.MemberMappings, membermappings)\n\n # def populate_data_dict(self,dictParam=None):\n # self._data_dict = dictParam\n # productsList = dictParam.get(self.PropertyNames.Products)\n # products = []\n # for product in productsList:\n # product = Product()\n # product.populate_data_dict(product)\n # products.append(product)\n # self.set_value(self.PropertyNames.Products, products)"
},
{
"alpha_fraction": 0.6427350640296936,
"alphanum_fraction": 0.6427350640296936,
"avg_line_length": 26.85714340209961,
"blob_id": "6b963512f16976f9d18cce0a79c26bcbfe7c6c78",
"content_id": "df1c8254a8ba45717df549ea6a4f60a50418f136",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 585,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 21,
"path": "/tests/test_user_store.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from api.stores.user import User\n\nfrom tornado.testing import AsyncHTTPTestCase\nfrom app import MyApplication\nfrom tornado.testing import AsyncHTTPClient\nfrom tornado.httputil import HTTPServerRequest\n\nclass TestServiceApp(AsyncHTTPTestCase):\n def get_app(self):\n application = MyApplication()\n return application.make_app()\n\n def test_register(self):\n testDict = {\n 'name':'loki',\n 'phone':'killll',\n 'email':'saerty@34',\n 'password':'donega'\n }\n client = AsyncHTTPClient()\n client.fetch()\n"
},
{
"alpha_fraction": 0.6239725947380066,
"alphanum_fraction": 0.6280822157859802,
"avg_line_length": 30.021276473999023,
"blob_id": "2613c59fd46dc2996548364728616ac184b6148d",
"content_id": "d4aae8b68f4faacc1d9b67e5ad2a8f5fdc85b311",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1460,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 47,
"path": "/api/handlers/group.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado.gen import *\nfrom .baseHandler import BaseHandler, BaseApiHandler\nfrom api.models.group import GroupModel\nimport json\nfrom tornado import web\nfrom bson.json_util import dumps\nfrom tornado_swirl.swagger import schema, restapi\n@restapi('/api/user/groups')\nclass GroupsListHandler(BaseApiHandler):\n @web.authenticated\n @coroutine\n def get(self):\n model = GroupModel(user=self._user, db=self.db)\n (status, _) = yield model.get_groups_where_user_is_owner(self._user.UserId)\n if status:\n self.finish(dumps(_))\n else:\n self.set_status(400, _)\n self.finish()\n\n@restapi('/api/group')\nclass GroupHandler(BaseHandler):\n @web.authenticated\n @coroutine\n def post(self):\n user = yield self.current_user\n model = GroupModel(user=user, db=self.db)\n try:\n yield model.create_group(self.args)\n except Exception as e:\n pass\n self.finish(json.dumps({'status': 'success'}))\n\n@restapi('/api/(.*)/group')\nclass CreateEmloyeeHandler(BaseApiHandler):\n @coroutine\n def post(self, groupId):\n user = yield self.current_user\n model = GroupModel(user=user, db=self.db)\n # e=''\n employee = None\n try:\n employee = yield model.create_employee(groupId, self.args)\n except Exception as e:\n self.set_status(400, str(e))\n self.finish()\n self.write(employee)\n\n\n"
},
{
"alpha_fraction": 0.6497584581375122,
"alphanum_fraction": 0.6497584581375122,
"avg_line_length": 23.352941513061523,
"blob_id": "3c806535a27e7ed1b91976e7b82f059cb60e2b65",
"content_id": "5ba5bcc39ad1b9a9299810a2da3407684501eb9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 414,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 17,
"path": "/api/models/event.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado.gen import *\nfrom api.core.event import EventHelper\nfrom api.models.base import BaseModel\n\n\nclass EventModel(BaseModel):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self._eh = EventHelper(**kwargs)\n\n\n @coroutine\n def create_event(self, eventDict):\n if not eventDict:\n raise NotImplementedError()\n yield self._eh.create_event(eventDict)\n"
},
{
"alpha_fraction": 0.6480228900909424,
"alphanum_fraction": 0.6490634679794312,
"avg_line_length": 40.78260803222656,
"blob_id": "2e91968e5e5f416d447056f71a1e14010ae7bc5c",
"content_id": "d4867ddccc98e467acfd78bc80686525a9cd2bfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3844,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 92,
"path": "/api/models/user.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado.gen import *\nimport bcrypt\nimport jwt\nimport base64\nfrom api.stores.user import User, LinkedAccount, LinkedAccountType, RegisterRequestParams, UserStatus, EmailValidationStatus, NewUserStatus\nfrom api.stores.group import Group, CreateEmployeeRequestParams\nfrom api.models.base import BaseModel\nimport tornado.ioloop\nimport uuid\n\nclass UserModel(BaseModel):\n @coroutine\n def check_if_user_exists_with_same_email(self, email):\n if not email:\n raise NotImplementedError()\n user = yield self._uh.getUserByEmail(email)\n if user:\n raise Return((True, user))\n raise Return((False, None))\n\n @coroutine\n def check_if_user_exists_with_same_employee_id(self, employee_id):\n if not employee_id:\n raise NotImplementedError()\n user = yield self._uh.getUserByEmployeeId(employee_id)\n if user:\n raise Return((True, user))\n raise Return((False, None))\n\n @coroutine\n def create_admin_user(self, postBodyDict):\n \"\"\"\n :param postBodyDict:\n password\n email\n \"\"\"\n user = User()\n user.Name = postBodyDict.get(user.PropertyNames.Name)\n user.Phone = postBodyDict.get(user.PropertyNames.Phone)\n user.PrimaryEmail = postBodyDict.get(RegisterRequestParams.Email)\n # employee_exists = False\n # if postBodyDict.get(user.PropertyNames.EmployeeId):\n # user.EmployeeId = postBodyDict.get(user.PropertyNames.EmployeeId)\n # (employee_exists, _) = yield self.check_if_user_exists_with_same_employee_id(user.EmployeeId)\n (user_exists, _) = yield self.check_if_user_exists_with_same_email(user.PrimaryEmail)\n if user_exists:\n raise Return((False, 'User already exists'))\n password = yield self.get_hashed_password(postBodyDict.get(RegisterRequestParams.Password))\n linkedaccount = LinkedAccount()\n user.UserId = uuid.uuid4()\n linkedaccount.AccountName = user.PrimaryEmail\n linkedaccount.AccountHash = password.get('hash')\n linkedaccount.AccountType = LinkedAccountType.Native\n user.LinkedAccounts = [linkedaccount]\n user.Status=UserStatus.Registered\n user.EmailValidated = EmailValidationStatus.NotValidated\n user_result = yield self._uh.save_user(user.datadict)\n # user = yield self._uh.getUserByUserId(user_result.inserted_id)\n # group = yield self._gh.createDummyGroupForUser(user_result.inserted_id)\n # yield self._gh.createGroupMemberMappingForDummyGroup(group.inserted_id, user_result.inserted_id)\n raise Return((True, user))\n\n def get_profile(self):\n if self._user:\n return self._user.datadict\n\n\n @coroutine\n def validate_password(self, postBodyDict):\n if postBodyDict['password'] != postBodyDict['password2']:\n return {'status':'error', 'message':'you must enter same password'}\n\n @coroutine\n def login(self, dict):\n username = dict.get('username')\n password = dict.get('password')\n if not username or not password:\n raise Return((False, 'You must enter both fields'))\n try:\n user = yield self._uh.getUserByEmail(username)\n if user:\n linkedAccount = user.LinkedAccounts[0]\n accounthash = linkedAccount.get(LinkedAccount.PropertyNames.AccountHash)\n isvalidPassword = yield self.check_hashed_password(password, accounthash)\n if isvalidPassword:\n raise Return((True, user))\n else:\n raise Return((False,'Wrong password'))\n else:\n raise Return((False, 'user email does not exist'))\n except IndexError:\n raise Return((False, 'user email does not exist'))\n"
},
{
"alpha_fraction": 0.6344495415687561,
"alphanum_fraction": 0.6350511312484741,
"avg_line_length": 26.549724578857422,
"blob_id": "8b52e0be0e8ee3c6010a46e88f62f0640d6ab186",
"content_id": "e585ca73c0b2a5b90653382289aac1e014095f3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9974,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 362,
"path": "/api/stores/user.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from enum import Enum\nfrom .base import BaseStoreModel\nimport re\nfrom bson import ObjectId\nimport uuid\nimport datetime\nfrom tornado_swirl.swagger import schema\nclass SupportedRoles:\n Admin = 'ad'\n Member = 'me'\n\nclass DisplayRoles:\n Employee = 'Employee'\n Owner = 'Owner'\n\nclass UserStatus:\n Invited = 'invited'\n Registered = 'registered'\n\nclass EmailValidationStatus:\n Validated = 'validated'\n NotValidated = 'not_validated'\n\nclass NewUserStatus:\n Yes = 'yes'\n No = 'no'\n\n@schema\nclass RegisterRequestParams:\n \"\"\"\n Properties:\n name (str) -- Required Shanmuk\n email (email) -- Required\n phone (str) -- Required\n employeeid (int) -- Required\n password (password) -- Required\n \"\"\"\n Name = 'name'\n Email = 'email'\n Phone = 'phone'\n EmployeeId = 'employeeid'\n Password = 'password'\n\n@schema\nclass LoginRequestParams:\n \"\"\"\n Properties:\n username (email) -- Required\n password (password) -- Required\n \"\"\"\n UserName = 'username'\n Password = 'password'\n\n@schema\nclass SuccessResponse:\n \"\"\"\n Properties:\n status (str) -- Required\n authToken (str) -- Required\n \"\"\"\n Status = 'status'\n AuthToken = 'authToken'\n\n\nclass LinkedAccountType:\n Native = 'native'\n\nclass StatusType:\n Invited = 'invited'\n Accepted = 'accepted'\n\nclass GroupMapping(BaseStoreModel):\n class PropertyNames:\n GroupId ='group_id'\n Roles = 'roles'\n Status = 'status'\n Shifts = 'shift'\n Tasks = 'tasks'\n\n\n @property\n def GroupId(self):\n return self.get_value(self.PropertyNames.GroupId)\n\n @GroupId.setter\n def GroupId(self, group_id):\n return self.set_value(self.PropertyNames.GroupId, group_id)\n\n @property\n def Roles(self):\n return self.get_value(self.PropertyNames.Roles)\n\n @property\n def Status(self):\n return self.get_value(self.PropertyNames.Status)\n\n @Status.setter\n def Status(self, status):\n if not status:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Status, status)\n\n\n\n @Roles.setter\n def Roles(self, roles):\n if not isinstance(roles, list):\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Roles, roles)\n\nclass LinkedAccount(BaseStoreModel):\n def __init__(self,accountname=None, accounthash=None, accounttype=None, **kwargs):\n super().__init__()\n if accountname and accounthash:\n self.set_value(self.PropertyNames.AccountName, accountname)\n self.set_value(self.PropertyNames.AccountHash, accounthash)\n\n @property\n def AccountName(self):\n return self.get_value(self.PropertyNames.AccountName)\n\n @AccountName.setter\n def AccountName(self, accountname):\n if not accountname:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.AccountName, accountname)\n\n @property\n def AccountHash(self):\n return self.get_value(self.PropertyNames.AccountHash)\n\n\n @AccountHash.setter\n def AccountHash(self, accounthash):\n if not accounthash:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.AccountHash, accounthash)\n\n @property\n def AccountType(self):\n return self.get_value(self.PropertyNames.AccountType)\n\n @AccountType.setter\n def AccountType(self, accounttype):\n if not accounttype:\n raise NotImplemented()\n\n class PropertyNames:\n AccountName = 'accountname'\n AccountHash = 'accounthash'\n AccountType = 'accounttype'\n AuthToken = 'authtoken'\n _reverseMapping = {\n 'accountname':('AccountName', str),\n 'accounthash':('AccountHash', str),\n 'accounttype': ('AccountType', str),\n 'authtoken': ('AuthToken', str),\n }\n\n @property\n def AuthToken(self):\n return self.get_value(self.PropertyNames.AuthToken)\n\n @AuthToken.setter\n def AuthToken(self, auth_token):\n return self.set_value(self.PropertyNames.AuthToken, auth_token)\n\n class ReverseMapping:\n accountname = 'AccountName'\n accounthash = 'AccountHash'\n\n\n@schema\nclass ProfileSchema:\n \"\"\"\n Properties:\n _id (str) -- Userid\n primaryemail (email) -- Email\n phone (str) -- Phone\n employeeid -- EmployeeId\n \"\"\"\n pass\n\n\nclass User(BaseStoreModel):\n '''\n This Design assumes All other baseModels are populated and entered into user\n\n '''\n\n @property\n def UserId(self):\n return self.get_value(self.PropertyNames.UserId)\n\n @UserId.setter\n def UserId(self, userId):\n if not userId:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.UserId, userId)\n\n @property\n def PrimaryEmail(self):\n return self.get_value(self.PropertyNames.PrimaryEmail)\n\n\n @PrimaryEmail.setter\n def PrimaryEmail(self, primaryemail):\n if not primaryemail:\n raise NotImplementedError()\n isValid = re.search('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)',primaryemail)\n if isValid:\n self.set_value(self.PropertyNames.PrimaryEmail, primaryemail)\n else:\n raise ValueError('you must enter valid email')\n\n @property\n def LinkedAccounts(self):\n return self.get_value(self.PropertyNames.LinkedAccounts)\n\n\n @LinkedAccounts.setter\n def LinkedAccounts(self, linkedAccounts:list):\n '''Accepts array argument to be set'''\n if not linkedAccounts:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.LinkedAccounts, linkedAccounts)\n\n @property\n def Groups(self):\n return self.get_value(self.PropertyNames.Groups)\n\n @Groups.setter\n def Groups(self, groups:list):\n if not groups:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Groups, groups)\n\n @property\n def Name(self):\n return self.get_value(self.PropertyNames.Name)\n\n @Name.setter\n def Name(self, name:str):\n if not name:\n raise NotImplementedError('you must enter name')\n self.set_value(self.PropertyNames.Name, name)\n @property\n def EmployeeId(self):\n return self.get_value(self.PropertyNames.EmployeeId)\n\n @EmployeeId.setter\n def EmployeeId(self, employeeId:int):\n if not employeeId:\n raise NotImplementedError('you must enter employee id')\n self.set_value(self.PropertyNames.EmployeeId, employeeId)\n\n @property\n def Phone(self):\n return self.get_value(self.PropertyNames.Phone)\n\n @Phone.setter\n def Phone(self, phone: str):\n if not phone:\n raise NotImplementedError('you must enter phone')\n self.set_value(self.PropertyNames.Phone, phone)\n\n _reverseMapping = {\n '_id': ('UserId', uuid.UUID),\n 'name':('Name', str),\n 'primaryemail': ('PrimaryEmail', str),\n 'linkedaccounts': ('LinkedAccounts', list, LinkedAccount),\n 'groups': ('Groups', list, GroupMapping),\n 'phone': ('Phone', str),\n 'employeeid':('EmployeeId', int),\n 'status':('Status',str),\n 'emailvalidated':('EmailValidated', bool),\n 'invitationCode':('InvitationCode', int),\n 'cts':('CreatedTimeStamp', datetime.datetime),\n 'uts': ('UpdatedTimeStamp', datetime.datetime)\n }\n\n class PropertyNames:\n UserId = '_id'\n Name = 'name'\n PrimaryEmail = 'primaryemail'\n LinkedAccounts = 'linkedaccounts'\n Groups = 'groups'\n Phone = 'phone'\n EmployeeId = 'employeeid'\n Status='status'\n EmailValidated='emailvalidated'\n InvitationCode = 'invitationCode'\n CreatedTimeStamp = 'cts'\n UpdatedTimeStamp = 'uts'\n\n\n\n @property\n def Status(self):\n return self.get_value(self.PropertyNames.Status)\n\n @Status.setter\n def Status(self, status):\n if not status:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.Status, status)\n\n @property\n def EmailValidated(self):\n return self.get_value(self.PropertyNames.EmailValidated)\n\n @EmailValidated.setter\n def EmailValidated(self, emv):\n if not isinstance(emv, bool):\n raise NotImplementedError()\n self.set_value(self.PropertyNames.EmailValidated, emv)\n\n @property\n def CreatedTimeStamp(self):\n return self.get_value(self.PropertyNames.CreatedTimeStamp)\n\n @CreatedTimeStamp.setter\n def CreatedTimeStamp(self, jts):\n if not jts:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.CreatedTimeStamp, jts)\n\n\n @property\n def UpdatedTimeStamp(self):\n return self.get_value(self.PropertyNames.UpdatedTimeStamp)\n\n @UpdatedTimeStamp.setter\n def UpdatedTimeStamp(self, lts):\n if not lts:\n raise NotImplementedError()\n self.set_value(self.PropertyNames.UpdatedTimeStamp, lts)\n\n\n #\n # def populate_data_dict(self,dictParam=None):\n # self._data_dict = dictParam\n # linkedAccountsList = dictParam.get(self.PropertyNames.LinkedAccounts)\n # groupsList = dictParam.get(self.PropertyNames.Groups)\n # linkedaccounts = []\n # groups = []\n # for linkedAccount in linkedAccountsList:\n # linkedaccount = LinkedAccount()\n # linkedaccount.populate_data_dict(linkedAccount)\n # linkedaccounts.append(linkedAccount)\n # if groupsList:\n # for group in groupsList:\n # groupMapping = GroupMapping()\n # groupMapping.populate_data_dict(group)\n # groups.append(groupMapping)\n # self.set_value(self.PropertyNames.LinkedAccounts, linkedaccounts)\n # if groupsList:\n # self.set_value(self.PropertyNames.Groups, groups)\n\n#\n# class UserRegistrationForm(BaseApiModel):\n# _fields = ()\n\n"
},
{
"alpha_fraction": 0.5433186292648315,
"alphanum_fraction": 0.5532305240631104,
"avg_line_length": 29.27777862548828,
"blob_id": "d13dc3167052ca22d4cb0f3caa0f243cb22af6ff",
"content_id": "f0ea5c8c72e39fed3acf24549c2668f069bd1ea7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2724,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 90,
"path": "/api/handlers/user.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado import web\nfrom tornado.gen import *\nfrom .baseHandler import BaseHandler, BaseApiHandler\nimport simplejson as json\nfrom api.models.user import UserModel\nfrom bson.json_util import dumps\nfrom tornado_swirl.swagger import schema, restapi\n\n@restapi('/api/register')\nclass RegisterHandler(BaseHandler):\n\n @coroutine\n def post(self):\n \"\"\"Handles registration of user\n Handles native user signup and sends authToken back in the\n response\n\n Request Body:\n user (RegisterRequestParams) -- RegisterRequestParams data.\n\n 200 Response:\n status (SuccessResponse) -- success\n authToken ([jwt]) -- jwtToken\n Error Responses:\n 400 () -- Bad Request\n 500 () -- Internal Server Error\n \"\"\"\n model = UserModel(db=self.db)\n try:\n (status, _) = yield model.create_admin_user(self.args)\n except Exception as e:\n (status, _) = (False, str(e))\n if status:\n authToken = yield self.authorize(_)\n self.write(json.dumps({'status': 'success', 'auth_token': authToken}))\n self.finish()\n else:\n self.set_status(400)\n self.write(_)\n self.finish()\n\n@restapi('/api/login')\nclass LoginHandler(BaseHandler):\n\n @coroutine\n def post(self):\n \"\"\"Handles registration of user\n Handles native user signup and sends authToken back in the\n response\n\n Request Body:\n user (LoginRequestParams) -- LoginRequestParams data.\n\n 200 Response:\n status (SuccessResponse) -- success\n authToken ([jwt]) -- jwtToken\n Error Responses:\n 400 () -- Bad Request\n 500 () -- Internal Server Error\n \"\"\"\n model = UserModel(db=self.db)\n (status, _) = yield model.login(self.args)\n if status:\n authToken = yield self.authorize(_)\n self.write(json.dumps({'status': 'success', 'auth_token': authToken}))\n else:\n self.set_status(400)\n self.write(json.dumps(_))\n self.finish()\n\n@restapi('/api/profile')\nclass ProfileHandler(BaseApiHandler):\n @web.authenticated\n @coroutine\n def get(self):\n \"\"\"\n Returns user Profile\n\n HTTP Header:\n Authorization (str) -- Required\n\n 200 Response:\n status (ProfileSchema) -- success\n :return:\n \"\"\"\n\n model = UserModel(user=self._user,db=self.db)\n profile = model.get_profile()\n\n self.write(dumps(profile))"
},
{
"alpha_fraction": 0.6991018056869507,
"alphanum_fraction": 0.6991018056869507,
"avg_line_length": 32.400001525878906,
"blob_id": "289013af81ee41e37f388185277ef1ad6fceacc8",
"content_id": "a5129c9204131966a47fa1d4c4baa33459c1757d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 668,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 20,
"path": "/urls.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from api.handlers.user import *\nfrom api.handlers.group import GroupsListHandler, GroupHandler, CreateEmloyeeHandler\nfrom api.handlers.product import ProductHandler\nfrom api.handlers.event import EventHandler\n\n\nurlpatterns = [\n # Admin register handler\n (r\"/api/register$\", RegisterHandler),\n (r\"/api/login$\",LoginHandler),\n (r\"/api/group$\", GroupHandler),\n (r\"/api/profile$\", ProfileHandler),\n (r\"/api/employee$\", GroupsListHandler),\n (r\"/api/product$\", ProductHandler),\n (r\"/api/event$\", EventHandler),\n (r\"/api/groups$\", GroupsListHandler),\n (r\"/api/user/groups$\", GroupsListHandler),\n (r\"/api/(.*)/group\", CreateEmloyeeHandler)\n\n]\n"
},
{
"alpha_fraction": 0.6578394174575806,
"alphanum_fraction": 0.6586801409721375,
"avg_line_length": 36.171875,
"blob_id": "3024177d651a1de80e1f5f0010fb6c2167b1b846",
"content_id": "76391b68cc29a821d5e796cfeb2d8a980f94ccad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2379,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 64,
"path": "/api/core/group.py",
"repo_name": "shanmuk184/SalesCrmbackend",
"src_encoding": "UTF-8",
"text": "from tornado.gen import *\nfrom api.stores.group import Group, MemberMapping\nfrom api.stores.user import SupportedRoles, StatusType\nfrom db.db import QueryConstants\nfrom db.db import Database\n\nclass GroupHelper:\n def __init__(self,**kwargs):\n self._user = kwargs.get('user')\n database = Database(kwargs.get('db'))\n self.db = database\n\n\n @coroutine\n def createDummyGroupForUser(self, userid):\n if not userid:\n raise NotImplementedError()\n group = Group()\n group.Name = 'Dummy Group'\n group.Admins = [userid]\n group_result = yield self.db.GroupCollection.insert_one(group.datadict)\n raise Return(group_result)\n\n @coroutine\n def create_group_for_user(self, groupDict:dict):\n if not groupDict:\n raise Return('error')\n group = yield self.db.GroupCollection.insert_one(groupDict)\n raise Return(group)\n\n @coroutine\n def get_groups_where_user_is_owner(self, userId):\n groupCursor = self.db.GroupCollection.find({Group.PropertyNames.OwnerId:userId})\n groups = []\n while (yield groupCursor.fetch_next):\n groupDict = groupCursor.next_object()\n group = Group()\n group.populate_data_dict(groupDict)\n groups.append(group)\n raise Return((groups))\n\n def create_member_mapping(self, memberId, roles):\n memberMapping = MemberMapping()\n memberMapping.MemberId = memberId\n memberMapping.Roles = roles\n if SupportedRoles.Admin in roles:\n memberMapping.Status = StatusType.Accepted\n else:\n memberMapping.Status = StatusType.Invited\n return memberMapping\n\n @coroutine\n def insert_member_mapping_into_group(self, groupId, mappingDict):\n if not mappingDict or not groupId:\n raise NotImplementedError()\n yield self.db.GroupCollection.update({'_id':groupId}, {QueryConstants.AddToSet:{Group.PropertyNames.MemberMappings:mappingDict}}, w=1)\n\n @coroutine\n def insert_group_mapping_into_user(self, userId, mappingDict):\n if not mappingDict or not userId:\n raise NotImplementedError()\n user_result = yield self.db.UserCollection.update({'_id': userId}, {\n QueryConstants.AddToSet: {Group.PropertyNames.MemberMappings: mappingDict}}, w=1)\n raise Return(user_result)\n"
}
] | 17 |
kepolo97/practice | https://github.com/kepolo97/practice | 578358b29503a953c02081f9a9aa2a62251adcb0 | 3a3e6bd8bc639c7f07538e3af9f6e667304087a6 | f60fb1fc1fde358e437a4624ef4c207d55c49004 | refs/heads/master | 2021-01-26T06:45:02.195849 | 2020-02-26T20:42:15 | 2020-02-26T20:42:15 | 243,352,257 | 0 | 0 | null | 2020-02-26T19:52:19 | 2020-02-26T20:32:24 | 2020-02-26T20:42:15 | Python | [
{
"alpha_fraction": 0.6730769276618958,
"alphanum_fraction": 0.7029914259910583,
"avg_line_length": 25,
"blob_id": "7bd8d252d35bf4d6156baed2e8e5ca67fe49ee83",
"content_id": "2d99b11b93b8fa3b2ede668eda90b893e0fc4b21",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 468,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 18,
"path": "/calcusensilla.py",
"repo_name": "kepolo97/practice",
"src_encoding": "UTF-8",
"text": "n1=float(input(\"ingrese el primer numero 1: \"))\nn2=float(input(\"ingrese el segundo numero 2: \"))\n#Esta es la parte de los cometarios\n\nsuma = n1 + n2\nresta = n1 - n2\nmultiplicacion = n1 * n2\ndivision = n1 / n2\ncuadrado = n1**2\n\nsuma=str(suma)\nprint(\"El resultado de la suma es: \" + suma)\nresta=str(resta)\nprint(\"El resultado de la resta es: \", resta)\n\nprint(\"El resultado de la multiplicacion es: \", multiplicacion)\n\nprint(\"El resultado de la division es: \", division)\n"
}
] | 1 |
j-doka/unkbot | https://github.com/j-doka/unkbot | 6668bce934305a57c846839123f252a5963b0079 | 9a2709fa578b6e16129f6a6bc7b99acc1d11eef2 | 40aff3b17a3092a36a40a633d88846a9e15da893 | refs/heads/main | 2023-07-20T16:13:30.766919 | 2021-08-18T01:23:28 | 2021-08-18T01:23:28 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6693548560142517,
"alphanum_fraction": 0.6787634491920471,
"avg_line_length": 18.076923370361328,
"blob_id": "65b277aeaf476037046c6102130fa91fc22e9cf6",
"content_id": "278f13932644059a8153afbbdd16f71dfe1ef5b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 744,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 39,
"path": "/README.md",
"repo_name": "j-doka/unkbot",
"src_encoding": "UTF-8",
"text": "# unkbot\n\n## How to use the bot\nCerate a bot from the discord developer portal.\nCreate a config.json: \n```json\n {\n \"token\": \"Your Token\"\n }\n```\nwithin seq2seq/data put in the chat data in form of: \n```\nq: do you like pancakes?\na: no, I like waffles \n``` \n\nThen use: \n```bash\npython3 data.py \n```\nwhich will give three files: `idx_a.npy`, `idx_q.npy` and `metadata.pkl`\n\n### Training The bot\n\n`python3 main.py`\n\nThis allows to you to use the `infer.py`, which generates the answers\n\n### Running the bot on your server\n\n```shell\nnode index.js\n```\n\n\n## Next Steps \n\nGetting Unkbot to be trained eeffectly on whole data folder, which holds 4.1 million comments!\n(I know that one of the other commits say 4.3 million commments, my bad)\n"
},
{
"alpha_fraction": 0.7936508059501648,
"alphanum_fraction": 0.7936508059501648,
"avg_line_length": 7.285714149475098,
"blob_id": "824089bc64f89e43ceeb1ffce2c88d772a084c2d",
"content_id": "704548c3e0a6e6730abd4298dd5741b219246a58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 7,
"path": "/unk_seq2seq/requirements.txt",
"repo_name": "j-doka/unkbot",
"src_encoding": "UTF-8",
"text": "scikit-learn\r\ntensorflow\r\ntensorlayer\r\nnumpy\r\nclick\r\ntqdm\r\nnltk"
},
{
"alpha_fraction": 0.5529640316963196,
"alphanum_fraction": 0.5549076795578003,
"avg_line_length": 27.171428680419922,
"blob_id": "f98d47cce1cd2b8ab60a1058a16dcc3307a96456",
"content_id": "ae76ab34a05c3ae962dac3410a3c43512850160b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1029,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 35,
"path": "/unk_seq2seq/infer.py",
"repo_name": "j-doka/unkbot",
"src_encoding": "UTF-8",
"text": "import os\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\nfrom main import * # import the main python file with model from the example\r\nimport time\r\nimport tensorlayer as tl\r\nimport json \r\n# ---------------------------------------------------------\r\n# you dont need to change any of this \r\n\r\nload_weights = tl.files.load_npz(name='saved/unk-model.npz')\r\ntl.files.assign_weights(load_weights, model_)\r\n\r\ntop_n = 3\r\n\r\ndef respond(input):\r\n sentence = inference(input, top_n)\r\n response=' '.join(sentence)\r\n return response\r\n# ------------------------------------------------------------\r\n\r\nq_file = open(r'/mnt/d/dev/unkbot/bot/query.json', \"r\")\r\nquery = json.loads(q_file.read())\r\nq_file.close()\r\n\r\nquery[\"answer\"] = respond(query[\"question\"])\r\n\r\nq_file = open(r'/mnt/d/dev/unkbot/bot/query.json', 'w')\r\nvalue = json.dumps(query)\r\nq_file.write(value)\r\n\r\nif __name__ == '__main__':\r\n while True:\r\n userInput = input(\"Query > \")\r\n for i in range(top_n):\r\n print(\"bot# \", respond(userInput))\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6306589245796204,
"alphanum_fraction": 0.6320036053657532,
"avg_line_length": 24.58333396911621,
"blob_id": "632c06e8ae7efd5733fd30285c13dd603520d9ea",
"content_id": "d85fea66d659373d7b70dae17016fd7c90dfe928",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2231,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 84,
"path": "/bot/index.js",
"repo_name": "j-doka/unkbot",
"src_encoding": "UTF-8",
"text": "/* eslint-disable no-unused-vars */\r\n/* eslint-disable no-undef */\r\n// require the discord.js module\r\nconst Discord = require('discord.js');\r\nconst { NONAME } = require('dns');\r\n// create a new Discord client\r\nconst client = new Discord.Client();\r\nconst { prefix, token } = require('./config.json');\r\n\r\nconst fs = require('graceful-fs')\r\nlet crypto = require('crypto')\r\n\r\n// when the client is ready, run this code\r\n// this event will only trigger one time after logging in\r\nclient.once('ready', () => {\r\n\tconsole.log('Ready!');\r\n\tclient.user.setPresence({\r\n\t\tstatus: 'online',\r\n\t\tactivity: {\r\n\t\t\ttype: 'WATCHING',\r\n\t\t\tname: 'The Unk is with you',\r\n\t\t},\r\n\t});\r\n});\r\n\r\n// login to Discord with your app's token\r\nclient.login(token);\r\n\r\nclient.on('message', message => {\r\n\tconsole.log(`${message.channel.name}: ${message.author.username} has sent: ${message.content}`);\r\n\r\n\t// So that it does not talk to itself\r\n\tif (message.author.bot == message.author.username) return; \r\n\r\n\tconst sleep = (milliseconds) => {\r\n\t\treturn new Promise(resolve => setTimeout(resolve, milliseconds))\r\n\t}\r\n\r\n\t// Here is a object, linking answer and comment\r\n\t// Not really a question: change it to comment. \r\n\tlet dict = {\r\n\t\t'question': message.content,\r\n\t\t'answer': null\r\n\t}\r\n\r\n\t// Turn object to JSON and write that file to a JSON file. \r\n\tlet dicstring = JSON.stringify(dict)\r\n\tlet md_text = dicstring\r\n\r\n\r\n\t// writes file to query.json\r\n\tfs.writeFile(`query.json`, md_text, function (err) {\r\n\t\tif (err)\r\n\t\t\treturn console.log(err);\r\n\t\tconsole.log(\"The file was saved!\");\r\n\t});\r\n\t\r\n\tconst { exec } = require(\"child_process\");\r\n\r\n\texec(\"cd ..; cd unk_seq2seq; python3 infer.py\", (error, stdout, stderr) => {\r\n\t\tif (error) {\r\n\t\t\tconsole.log(`error: ${error.message}`);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (stderr) {\r\n\t\t\tconsole.log(`stderr: ${stderr}`);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tconsole.log('running command')\r\n\t\tconsole.log(`stdout: ${stdout}`);\r\n\t});\r\n\r\n\tfs.readFile('/mnt/d/dev/unkbot/bot/query.json', 'utf-8', function (err, data){\r\n\t\tif (err)\r\n\t\t\treturn console.log(err);\r\n\t\t\r\n\t\tconsole.log(`this is the result: ${data}`);\r\n\t\tlet value = JSON.parse(data)\r\n\t\tanswer = value[\"answer\"]\r\n\t\tconsole.log('sending message...')\r\n\t\tmessage.channel.send(answer);\r\n\t})\r\n\r\n});"
}
] | 4 |
unmade/phonebook | https://github.com/unmade/phonebook | 4e4005e507807e66848d4756501bd65f6dd23280 | 121b2e5bb2eb217f5e183aa0c39a6d12f227d5e3 | faae735aeb3e82188e5ee02a80beebc74178be3c | refs/heads/master | 2021-01-10T02:06:25.920793 | 2018-02-06T18:47:17 | 2018-02-06T18:47:17 | 53,571,002 | 1 | 0 | MIT | 2016-03-10T09:13:32 | 2017-12-22T20:09:58 | 2018-02-06T18:47:18 | Python | [
{
"alpha_fraction": 0.5051546096801758,
"alphanum_fraction": 0.5051546096801758,
"avg_line_length": 21.823530197143555,
"blob_id": "9e2548b1798a866cb46a14ab0e11a3bf3a358e29",
"content_id": "c15d3ad4d7026a75c24c622afa286e1242308e29",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 388,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 17,
"path": "/frontend/src/js/app/employees/directives/employee-list-item.directive.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.employees')\n .directive('employeeListItem', EmployeeListItem);\n\n function EmployeeListItem() {\n return {\n restrict: 'AE',\n templateUrl: 'directives/employee-list-item.directive.html',\n scope: {\n 'employee': '=employee'\n }\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.39386188983917236,
"alphanum_fraction": 0.4104859232902527,
"avg_line_length": 25.066667556762695,
"blob_id": "c4cb9b640984271a168caa108d2d96341e7cad49",
"content_id": "f45ff6e54bd976eab6e63b52ef64ca246c37bed6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 892,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 30,
"path": "/frontend/test/unit/responds/employees.detail.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "function getEmployeeDetail() {\n return {\n \"id\": 15,\n \"firstname\": \"Владимир\",\n \"patronymic\": \"Данилович\",\n \"surname\": \"Проненко\",\n \"position\": \"Доцент, к.т.н.\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/no-logo.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 5,\n \"number\": \"308\",\n \"name\": \"Информационные технологии\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n }\n}\n"
},
{
"alpha_fraction": 0.5693512558937073,
"alphanum_fraction": 0.5749440789222717,
"avg_line_length": 28.799999237060547,
"blob_id": "0ef177c6e7d046258bcb961fb94ba8e4c043954c",
"content_id": "855e45f4aedecc0f55cfbce66ece3ed05975b28b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 894,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 30,
"path": "/backend/phonebook/feedback/models.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Feedback(models.Model):\n DEFAULT = 'DF'\n IN_PROCESS = 'PR'\n NEW = 'NW'\n SOLVED = 'SL'\n REJECTED = 'RJ'\n STATUS_CHOICES = (\n (DEFAULT, \"Don't need to be solved\"),\n (IN_PROCESS, _('In progress')),\n (NEW, _('New')),\n (SOLVED, _('Solved')),\n (REJECTED, _(\"Won't be solved\")),\n )\n\n sender = models.CharField(_('Sender'), max_length=50)\n text = models.TextField(_('Text'))\n created_at = models.DateField(_('Created at'), auto_now_add=True)\n status = models.CharField(_('Status'), max_length=2, choices=STATUS_CHOICES, default=NEW)\n\n class Meta:\n verbose_name = _('Feedback')\n verbose_name_plural = _('Feedback')\n ordering = ('-created_at', )\n\n def __str__(self):\n return f'{self.sender} {self.text[:20]}'\n"
},
{
"alpha_fraction": 0.7086092829704285,
"alphanum_fraction": 0.7814569473266602,
"avg_line_length": 24.16666603088379,
"blob_id": "506a5ab3eaca7956b6ec05a197504844bbd1d208",
"content_id": "805d5638b6c4f66a5a3fad2f14da56a8a8e569a3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 151,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 6,
"path": "/compose/web/local.sh",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env sh\n\ncd phonebook\npython3 manage.py collectstatic --noinput\npython3 manage.py migrate --noinput\npython3 manage.py runserver 0.0.0.0:8000\n"
},
{
"alpha_fraction": 0.5943970680236816,
"alphanum_fraction": 0.6321558952331543,
"avg_line_length": 30.576923370361328,
"blob_id": "302edb744d45a4b211c14cf2b4069c7f0c6707b6",
"content_id": "d0633de5b9d298d6c06e133da4c0e0461ea9fc73",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 856,
"license_type": "permissive",
"max_line_length": 194,
"num_lines": 26,
"path": "/backend/phonebook/employees/migrations/0004_auto_20160226_1739.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-02-26 17:39\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0003_auto_20160102_1338'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='employee',\n name='is_retired',\n field=models.BooleanField(default=False, verbose_name='Числится уволеным'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='boss',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='secretary', to='employees.Employee', verbose_name='Является секретарем у'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7435387969017029,
"alphanum_fraction": 0.7475149035453796,
"avg_line_length": 22.952381134033203,
"blob_id": "1638da0ce945163beabf118a4beb831f2f97fe80",
"content_id": "53a9dd7a2ab8da7d86926607805f57606b8dce41",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1006,
"license_type": "permissive",
"max_line_length": 162,
"num_lines": 42,
"path": "/README.md",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Phonebook\n\n\n[](https://coveralls.io/github/unmade/phonebook?branch=coveralls)\n\n\n\nThis is just simple phonebook to store employees contacts.\nSee how it [looks](docs/LOOK.md)\n\n\n## QuickStart\n\nSimply run:\n```\ndocker-compose up --build\n```\n\nCreate superuser for django admin:\n```\ndocker-compose run web python3 phonebook/manage.py createsuperuser\n```\n\n> Don't forget to change password and security settings in [secrets](secrets/)\n\n\n## Development\n\nJust run:\n```\ndocker-compose -f docker-compose.yml -f docker-compose.local.yml up --build\n```\n\n> You could set up settings suitable for development in `.env` file\n\n\n## Testing\n\nTo run test locally:\n```\ndocker-compose -f docker-compose.yml -f docker-compose.test.yml up test\n```\n"
},
{
"alpha_fraction": 0.5792258381843567,
"alphanum_fraction": 0.5917571783065796,
"avg_line_length": 45.94117736816406,
"blob_id": "0f4cdfeba587129b602492701afc59065c05a752",
"content_id": "7ac39040e010bde17d1a394adf7082d82de0de02",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 7196,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 153,
"path": "/frontend/test/unit/employees/employees.controllers.spec.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "describe('Employees controllers', function() {\n\n beforeEach(function(){\n jasmine.addMatchers({\n toEqualData: function(util, customEqualityTesters) {\n return {\n compare: function(actual, expected) {\n return {\n pass: angular.equals(actual, expected)\n };\n }\n };\n }\n });\n });\n\n beforeEach(module('pbApp'));\n beforeEach(module('pbApp.companies'));\n beforeEach(module('pbApp.employees'));\n\n describe('EmployeeListCtrl Test', function() {\n var scope, $httpBackend, ctrl,\n employeeRespond = {\n employees: {results: getEmployeeList().results.slice(0, 20)},\n employeesNext: {results: getEmployeeList().results.slice(20, 40)},\n filteredByCompany: {results: getEmployeeList().results.slice(0, 2)},\n filteredByCompanyAndCenter: {results: getEmployeeList().results.slice(0, 3)},\n filteredByCompanyAndCenterAndDivision: {results: getEmployeeList().results.slice(0, 8)},\n employeeSearch: {results: getEmployeeList().results.slice(0, 5)},\n search: {results: getEmployeeList().results.slice(0, 6)}\n },\n companiesRespond = {\n companyList: getCompanyList(),\n centerList: getCenterList(),\n divisionList: getDivisionList()\n };\n\n beforeEach(inject(function(_$httpBackend_, $rootScope, $routeParams, $controller) {\n $httpBackend = _$httpBackend_;\n $httpBackend.whenGET('employees/api/employee/?limit=20&offset=0')\n .respond(employeeRespond.employees);\n $httpBackend.whenGET('employees/api/employee/?limit=20&offset=20')\n .respond(employeeRespond.employeesNext);\n $httpBackend.whenGET('employees/api/employee/?company=1&limit=20&offset=0')\n .respond(employeeRespond.filteredByCompany);\n $httpBackend.whenGET('employees/api/employee/?center=1&company=1&limit=20&offset=0')\n .respond(employeeRespond.filteredByCompanyAndCenter);\n $httpBackend.whenGET('employees/api/employee/?center=1&company=1&division=1&limit=20&offset=0')\n .respond(employeeRespond.filteredByCompanyAndCenterAndDivision);\n $httpBackend.whenGET('employees/api/employee/?limit=8&offset=0&search=%D0%BC%D0%BE%D1%80%D0%BE%D0%B7%D0%BE%D0%B2')\n .respond(employeeRespond.employeeSearch);\n $httpBackend.whenGET('employees/api/employee/?limit=20&offset=0&search=%D0%9C%D0%BE%D1%80%D0%BE%D0%B7%D0%BE%D0%B2')\n .respond(employeeRespond.search);\n $httpBackend.whenGET('companies/api/company/').respond(companiesRespond.companyList);\n $httpBackend.whenGET('companies/api/center/?company=1').respond(companiesRespond.centerList);\n $httpBackend.whenGET('companies/api/division/?center=1').respond(companiesRespond.divisionList);\n scope = $rootScope.$new();\n ctrl = $controller('EmployeeListCtrl', {$scope: scope});\n }));\n\n it('should fetch employees', function() {\n expect(ctrl.employees).toEqualData({\n results: [],\n after: undefined,\n params: {limit: 20, offset: 0},\n busy: false\n });\n ctrl.employees.nextPage();\n expect(ctrl.employees.busy).toBe(true);\n $httpBackend.flush();\n expect(ctrl.employees.results).toEqualData(employeeRespond.employees.results);\n expect(ctrl.employees.params.limit).toEqual(20);\n expect(ctrl.employees.params.offset).toEqual(20);\n expect(ctrl.employees.after).toBe(undefined);\n expect(ctrl.employees.busy).toBe(false);\n });\n\n it('should return results for autocomplete search query', function() {\n ctrl.searchText = \"Морозов\";\n var res = ctrl.employeeSearch(ctrl.searchText);\n $httpBackend.flush();\n expect(res.$$state.value).toEqualData(employeeRespond.employeeSearch.results);\n });\n\n it('should update employees list according to search query', function() {\n ctrl.searchText = \"Морозов\";\n ctrl.selectedCompany = 1;\n ctrl.selectedCenter = 1;\n ctrl.selectedDivision = 1;\n ctrl.search(ctrl.searchText);\n $httpBackend.flush();\n expect(ctrl.selectedCompany).toBeNull();\n expect(ctrl.selectedCenter).toBeNull();\n expect(ctrl.selectedDivision).toBeNull();\n expect(ctrl.employees.results).toEqualData(employeeRespond.search.results);\n });\n\n it('should load companies', function() {\n expect(ctrl.companies).toBeNull();\n ctrl.loadCompanies();\n $httpBackend.flush();\n expect(ctrl.companies).toEqualData(companiesRespond.companyList);\n });\n\n it('should load centers', function() {\n expect(ctrl.selectedCompany).toBeNull();\n expect(ctrl.centers).toBeNull();\n ctrl.selectedCompany = 1;\n ctrl.loadCenters();\n $httpBackend.flush();\n expect(ctrl.centers).toEqualData(companiesRespond.centerList);\n });\n\n it('should load divisions', function() {\n expect(ctrl.selectedCenter).toBeNull();\n expect(ctrl.divisions).toBeNull();\n ctrl.selectedCenter = 1;\n ctrl.loadDivisions();\n $httpBackend.flush();\n expect(ctrl.divisions).toEqualData(companiesRespond.divisionList);\n });\n\n it('should update employees list and clear selected center and division on company change', function() {\n ctrl.selectedCompany = 1;\n ctrl.selectedCenter = 1;\n ctrl.selectedDivision = 1;\n ctrl.companyChanged();\n expect(ctrl.selectedCenter).toBeNull();\n expect(ctrl.selectedDivision).toBeNull();\n $httpBackend.flush();\n expect(ctrl.employees.results).toEqualData(employeeRespond.filteredByCompany.results);\n });\n\n it('should update employees list and clear selected division on center change', function() {\n ctrl.selectedCompany = 1;\n ctrl.selectedCenter = 1;\n ctrl.selectedDivision = 1;\n ctrl.centerChanged();\n expect(ctrl.selectedDivision).toBeNull();\n $httpBackend.flush();\n expect(ctrl.employees.results).toEqualData(employeeRespond.filteredByCompanyAndCenter.results);\n });\n\n it('should update employees list on division change', function() {\n ctrl.selectedCompany = 1;\n ctrl.selectedCenter = 1;\n ctrl.selectedDivision = 1;\n ctrl.divisionChanged();\n $httpBackend.flush();\n expect(ctrl.employees.results).toEqualData(employeeRespond.filteredByCompanyAndCenterAndDivision.results);\n });\n });\n});\n"
},
{
"alpha_fraction": 0.5692394971847534,
"alphanum_fraction": 0.588535726070404,
"avg_line_length": 37.30434799194336,
"blob_id": "7eb32600f6386ef815ff4c30ce7c4e973dd09886",
"content_id": "30ece9cbb3b893d4cb341edc7b539bd6b10d196b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1857,
"license_type": "permissive",
"max_line_length": 185,
"num_lines": 46,
"path": "/backend/phonebook/employees/migrations/0003_auto_20160102_1338.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-02 13:38\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0002_auto_20151229_1509'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='employee',\n options={'ordering': ['surname', 'firstname', 'patronymic'], 'verbose_name': 'Сотрудник', 'verbose_name_plural': 'Сотрудники'},\n ),\n migrations.AlterModelOptions(\n name='firstname',\n options={'ordering': ['name'], 'verbose_name': 'Имя', 'verbose_name_plural': 'Имена'},\n ),\n migrations.AlterModelOptions(\n name='patronymic',\n options={'ordering': ['name'], 'verbose_name': 'Отчество', 'verbose_name_plural': 'Отчества'},\n ),\n migrations.AlterModelOptions(\n name='position',\n options={'ordering': ['name'], 'verbose_name': 'Должность', 'verbose_name_plural': 'Должности'},\n ),\n migrations.AlterModelOptions(\n name='surname',\n options={'ordering': ['name'], 'verbose_name': 'Фамилия', 'verbose_name_plural': 'Фамилии'},\n ),\n migrations.AlterField(\n model_name='employee',\n name='boss',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='secretary', to='employees.Employee', verbose_name='Руководитель'),\n ),\n migrations.AlterField(\n model_name='position',\n name='name',\n field=models.CharField(max_length=255, unique=True, verbose_name='Название'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.748024582862854,
"alphanum_fraction": 0.748024582862854,
"avg_line_length": 24.311111450195312,
"blob_id": "0f7321449d9ebfeb615be5f6fb773bb0dd949117",
"content_id": "eb7d8d18fe9435e2705874c24921a1b992a48e71",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1139,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 45,
"path": "/backend/phonebook/employees/tests/conftest.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "import factory\nfrom faker import Factory as FakerFactory\nfrom pytest_factoryboy import register\n\nfrom employees.models import Employee, FirstName, Patronymic, Surname\n\nfaker = FakerFactory.create()\n\n\n@register\nclass FirstNameFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(lambda s, x: f'{faker.first_name()}{x}')\n\n class Meta:\n model = FirstName\n\n\n@register\nclass PatronymicFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(lambda s, x: f'{faker.name()}{x}')\n\n class Meta:\n model = Patronymic\n\n\n@register\nclass SurnameFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(lambda s, x: f'{faker.last_name()}{x}')\n\n class Meta:\n model = Surname\n\n\nclass EmployeeFactory(factory.django.DjangoModelFactory):\n surname = factory.SubFactory(SurnameFactory)\n firstname = factory.SubFactory(FirstNameFactory)\n patronymic = factory.SubFactory(PatronymicFactory)\n\n boss = factory.SubFactory('employees.tests.conftest.EmployeeFactory')\n\n class Meta:\n model = Employee\n\n\nregister(EmployeeFactory)\n"
},
{
"alpha_fraction": 0.32981929183006287,
"alphanum_fraction": 0.3674698770046234,
"avg_line_length": 24.538461685180664,
"blob_id": "90efb184a5dc2f8d866b4098e6d6d67af56aca9e",
"content_id": "a393afd65cf90c377bc796fb95414c23702ab90e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 758,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 26,
"path": "/frontend/test/unit/responds/companies.center.detail.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "function getCenterDetail() {\n return {\n \"id\": 6,\n \"head\": null,\n \"phones\": [\n {\n \"id\": 21,\n \"category\": \"Городской\",\n \"number\": \"84991582721\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 8,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\",\n \"comment\": \"Время работы: с 10:00 до 17:00 ежедневно\",\n \"company\": 6\n }\n}\n"
},
{
"alpha_fraction": 0.27569329738616943,
"alphanum_fraction": 0.3118542730808258,
"avg_line_length": 36.15151596069336,
"blob_id": "2368162b468eea225b51644d90192801e379afc5",
"content_id": "e077f85949c8641233f7dc7b5db662d58586fdca",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4195,
"license_type": "permissive",
"max_line_length": 178,
"num_lines": 99,
"path": "/frontend/test/unit/responds/companies.company.list.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "function getCompanyList() {\n return {\n \"count\": 2,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"id\": 6,\n \"ceo\": \"Рождественский Александр Викторович\",\n \"phones\": [\n {\n \"id\": 14,\n \"category\": \"Городской\",\n \"number\": \"158-58-70\",\n \"comment\": \"Справочная\"\n },\n {\n \"id\": 17,\n \"category\": \"Городской\",\n \"number\": \"84991582571\",\n \"comment\": \"Отдел кадров\"\n },\n {\n \"id\": 12,\n \"category\": \"Факс\",\n \"number\": \"84991582977\",\n \"comment\": \"\"\n },\n {\n \"id\": 15,\n \"category\": \"Городской\",\n \"number\": \"84991584300\",\n \"comment\": \"Приемная комиссия\"\n },\n {\n \"id\": 13,\n \"category\": \"Городской\",\n \"number\": \"84991584333\",\n \"comment\": \"Справочная\"\n },\n {\n \"id\": 16,\n \"category\": \"Городской\",\n \"number\": \"84991589209\",\n \"comment\": \"Общий отдел\"\n }\n ],\n \"emails\": [\n {\n \"id\": 6,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"full_name\": \"Московский авиационный институт (Национальный исследовательский университет)\",\n \"short_name\": \"МАИ\",\n \"address\": \"Волоколамское шоссе, д. 4, г. Москва, A-80, ГСП-3, 125993\",\n \"logo\": \"http://localhost:8000/media/logos/no-logo.png\",\n \"comment\": \"\",\n \"category\": 5\n },\n {\n \"id\": 7,\n \"ceo\": \"Садовничий Виктор Антонович\",\n \"phones\": [\n {\n \"id\": 28,\n \"category\": \"Факс\",\n \"number\": \"84959390126\",\n \"comment\": \"\"\n },\n {\n \"id\": 27,\n \"category\": \"Городской\",\n \"number\": \"84959391000\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 11,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"name\": \"МГУ имени М.В.Ломоносова\",\n \"full_name\": \"Федеральное государственное бюджетное образовательное учреждение высшего образования «Московский государственный университет имени М.В.Ломоносова»\",\n \"short_name\": \"МГУ\",\n \"address\": \"119991, Российская Федерация, Москва, Ленинские горы, д. 1, Московский государственный университет имени М.В.Ломоносова\",\n \"logo\": \"http://localhost:8000/media/logos/no-logo.png\",\n \"comment\": \"\",\n \"category\": 6\n }\n ]\n }\n}\n"
},
{
"alpha_fraction": 0.7003745436668396,
"alphanum_fraction": 0.7003745436668396,
"avg_line_length": 23.272727966308594,
"blob_id": "7244125156c561043a8dfcef2e625b52d21f1182",
"content_id": "a86fe2835404916f9c00d29b8a3aa9d850db3daf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 267,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 11,
"path": "/backend/phonebook/employees/api_urls.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'api'\n\n\nurlpatterns = [\n path('employee/', views.EmployeeListAPIView.as_view(), name='employee-list'),\n path('employee/<int:pk>/', views.EmployeeRetrieveAPIView.as_view(), name='employee-detail'),\n]\n"
},
{
"alpha_fraction": 0.5571796894073486,
"alphanum_fraction": 0.5765262246131897,
"avg_line_length": 35.92063522338867,
"blob_id": "8c771367c9dc8190d458dd658f559fd2eae80819",
"content_id": "bfb901d5f877bdf6b48447afe4f6fd525ad70e2f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2442,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 63,
"path": "/backend/phonebook/contacts/migrations/0003_auto_20160102_1338.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-02 13:38\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contacts', '0002_auto_20151228_1123'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='category',\n options={'ordering': ['name'], 'verbose_name': 'Категория', 'verbose_name_plural': 'Категории'},\n ),\n migrations.AlterModelOptions(\n name='email',\n options={'ordering': ['email'], 'verbose_name': 'Электронный адрес', 'verbose_name_plural': 'Электронные адреса'},\n ),\n migrations.AlterModelOptions(\n name='phone',\n options={'ordering': ['number'], 'verbose_name': 'Телефон', 'verbose_name_plural': 'Телефоны'},\n ),\n migrations.AlterField(\n model_name='category',\n name='name',\n field=models.CharField(max_length=100, unique=True, verbose_name='Название'),\n ),\n migrations.AlterField(\n model_name='email',\n name='category',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Категория'),\n ),\n migrations.AlterField(\n model_name='email',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n migrations.AlterField(\n model_name='email',\n name='email',\n field=models.EmailField(max_length=254, unique=True, verbose_name='Эл. адрес'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='category',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Категория'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='number',\n field=models.CharField(max_length=20, unique=True, verbose_name='Номер'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5768781900405884,
"alphanum_fraction": 0.5873880982398987,
"avg_line_length": 35.70000076293945,
"blob_id": "21c5f1e1a0be54d2b8fdd51e8d80be8bbd42067f",
"content_id": "3fbc76d08578893bf354b19c20ae6d22502621dd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2569,
"license_type": "permissive",
"max_line_length": 159,
"num_lines": 70,
"path": "/backend/phonebook/companies/migrations/0002_auto_20151228_1029.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2015-12-28 10:29\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('companies', '0001_initial'),\n ('employees', '0001_initial'),\n ('contacts', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='division',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='division_head', to='employees.Employee'),\n ),\n migrations.AddField(\n model_name='division',\n name='phones',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Phone'),\n ),\n migrations.AddField(\n model_name='company',\n name='category',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.CompanyCategory'),\n ),\n migrations.AddField(\n model_name='company',\n name='ceo',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='company_ceo', to='employees.Employee'),\n ),\n migrations.AddField(\n model_name='company',\n name='emails',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Email'),\n ),\n migrations.AddField(\n model_name='company',\n name='phones',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Phone'),\n ),\n migrations.AddField(\n model_name='center',\n name='company',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Company'),\n ),\n migrations.AddField(\n model_name='center',\n name='emails',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Email'),\n ),\n migrations.AddField(\n model_name='center',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='center_head', to='employees.Employee'),\n ),\n migrations.AddField(\n model_name='center',\n name='phones',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Phone'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7151051759719849,
"alphanum_fraction": 0.7246654033660889,
"avg_line_length": 25.149999618530273,
"blob_id": "eb7d077559cb1aa66d3ce0489bf332ee31a516f4",
"content_id": "6dba82c38165603216c1d02179562de17f11b312",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 523,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 20,
"path": "/compose/web/local.Dockerfile",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "FROM alpine\n\nRUN apk update && \\\n apk upgrade && \\\n apk add --update python3 python3-dev git postgresql-client postgresql-dev build-base gettext jpeg-dev zlib-dev\n\nCOPY ./backend/requirements /requirements\nRUN pip3 install --upgrade pip && \\\n pip3 install -r /requirements/local.txt && \\\n apk del -r python3-dev postgresql git\n\nCOPY ./compose/web/local.sh /local.sh\nRUN chmod +x /local.sh\n\nCOPY ./compose/web/entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nWORKDIR /app\n\nENTRYPOINT [\"/entrypoint.sh\"]\n"
},
{
"alpha_fraction": 0.5786187052726746,
"alphanum_fraction": 0.5871334075927734,
"avg_line_length": 41.620967864990234,
"blob_id": "230f4ae9b0189621ea8a823fd53c3d16830c4d29",
"content_id": "ee20ce670f1f5eed6f36ca811ba3f95ba91a617f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5285,
"license_type": "permissive",
"max_line_length": 177,
"num_lines": 124,
"path": "/backend/phonebook/employees/migrations/0005_auto_20171208_2003.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 17:03\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0004_auto_20160226_1739'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='employee',\n options={'ordering': ['surname', 'firstname', 'patronymic'], 'verbose_name': 'Employee', 'verbose_name_plural': 'Employees'},\n ),\n migrations.AlterModelOptions(\n name='firstname',\n options={'ordering': ['name'], 'verbose_name': 'First name', 'verbose_name_plural': 'First names'},\n ),\n migrations.AlterModelOptions(\n name='patronymic',\n options={'ordering': ['name'], 'verbose_name': 'Patronymic', 'verbose_name_plural': 'Patronymics'},\n ),\n migrations.AlterModelOptions(\n name='position',\n options={'ordering': ['name'], 'verbose_name': 'Position', 'verbose_name_plural': 'Positions'},\n ),\n migrations.AlterModelOptions(\n name='surname',\n options={'ordering': ['name'], 'verbose_name': 'Surname', 'verbose_name_plural': 'Surnames'},\n ),\n migrations.AlterField(\n model_name='employee',\n name='birthday',\n field=models.DateField(blank=True, null=True, verbose_name='Birthday'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='boss',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='secretary', to='employees.Employee', verbose_name='Boss'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='center',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='companies.Center', verbose_name='Center'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='company',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='companies.Company', verbose_name='Company'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='division',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='companies.Division', verbose_name='Division'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Emails'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='firstname',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='employees.FirstName', verbose_name='First name'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='is_retired',\n field=models.BooleanField(default=False, verbose_name='Is retired'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='patronymic',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='employees.Patronymic', verbose_name='Patronymic'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Phones'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='place',\n field=models.CharField(blank=True, max_length=255, verbose_name='Place'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='position',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='employees.Position', verbose_name='Position'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='surname',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='employees.Surname', verbose_name='Surname'),\n ),\n migrations.AlterField(\n model_name='firstname',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='First name'),\n ),\n migrations.AlterField(\n model_name='patronymic',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='Patronymic'),\n ),\n migrations.AlterField(\n model_name='position',\n name='name',\n field=models.CharField(max_length=255, unique=True, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='surname',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='Surname'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6541033387184143,
"alphanum_fraction": 0.6607902646064758,
"avg_line_length": 40.125,
"blob_id": "0be72992b25d92c7850953a2259268e038227157",
"content_id": "4701de626584979b20ca0602426431596ee1800d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4935,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 120,
"path": "/backend/phonebook/companies/models.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass CompanyQuerySet(models.QuerySet):\n def select_ceo(self):\n return self.select_related('ceo__surname', 'ceo__firstname', 'ceo__patronymic', 'ceo__position')\n\n def prefetch_contacts(self):\n return self.prefetch_related('phones', 'emails', 'phones__category', 'emails__category')\n\n\nclass CenterQuerySet(models.QuerySet):\n def select_head(self):\n return self.select_related('head', 'head__surname', 'head__firstname', 'head__patronymic')\n\n def prefetch_contacts(self):\n return self.prefetch_related('phones', 'emails', 'phones__category', 'emails__category')\n\n\nclass DivisionQuerySet(models.QuerySet):\n def select_head(self):\n return self.select_related('head', 'head__surname', 'head__firstname', 'head__patronymic')\n\n def prefetch_contacts(self):\n return self.prefetch_related('phones', 'emails', 'phones__category', 'emails__category')\n\n\nclass CompanyCategory(models.Model): # TODO: rename to BusinessEntity\n category = models.CharField(_('Abbreviation'), max_length=50, unique=True) # TODO: rename to abbreviation\n name = models.CharField(_('Name'), max_length=500)\n\n class Meta:\n verbose_name = _('Business entity')\n verbose_name_plural = _('Business entities')\n ordering = ['category']\n\n def __str__(self):\n return self.category\n\n\nclass Company(models.Model):\n ceo = models.ForeignKey(\n 'employees.Employee', null=True, blank=True, on_delete=models.SET_NULL,\n related_name='company_ceo', verbose_name=_('CEO')\n )\n category = models.ForeignKey(\n 'CompanyCategory', null=True, blank=True, verbose_name=_('Business entity'), on_delete=models.SET_NULL\n )\n name = models.CharField(max_length=255, verbose_name=_('Name'))\n full_name = models.TextField(_('Full name'), blank=True)\n short_name = models.CharField(_('Short name'), max_length=255, blank=True)\n address = models.CharField(_('Address'), max_length=400, blank=True)\n phones = models.ManyToManyField('contacts.Phone', blank=True, verbose_name=_('Phones'))\n emails = models.ManyToManyField('contacts.Email', blank=True, verbose_name=_('Emails'))\n logo = models.ImageField(_('Logo'), upload_to='logos', default='logos/no-logo.png', blank=True)\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n objects = CompanyQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('Company')\n verbose_name_plural = _('Companies')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n def get_absolute_api_url(self):\n return reverse('companies:api:company-detail', kwargs={'pk': self.pk})\n\n\nclass Center(models.Model):\n company = models.ForeignKey('Company', verbose_name=_('Company'), on_delete=models.CASCADE)\n head = models.ForeignKey(\n 'employees.Employee', null=True, blank=True, on_delete=models.SET_NULL,\n related_name='center_head', verbose_name=_('Head')\n )\n number = models.CharField(_('Code'), max_length=10) # TODO: rename to Code\n name = models.CharField(_('Name'), max_length=255)\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n phones = models.ManyToManyField('contacts.Phone', blank=True, verbose_name=_('Phones'))\n emails = models.ManyToManyField('contacts.Email', blank=True, verbose_name=_('Emails'))\n objects = CenterQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('Center')\n verbose_name_plural = _('Centers')\n ordering = ['number', 'name']\n\n def __str__(self):\n return f'{self.number} - {self.name}'\n\n def get_absolute_api_url(self):\n return reverse('companies:api:center-detail', kwargs={'pk': self.pk})\n\n\nclass Division(models.Model):\n center = models.ForeignKey('Center', verbose_name=_('Center'), on_delete=models.CASCADE)\n head = models.ForeignKey(\n 'employees.Employee', null=True, blank=True, on_delete=models.SET_NULL,\n related_name='division_head', verbose_name=_('Head')\n )\n number = models.CharField(_('Code'), max_length=10) # TODO: rename to Code\n name = models.CharField(_('Name'), max_length=255, blank=True)\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n phones = models.ManyToManyField('contacts.Phone', blank=True, verbose_name=_('Phones'))\n emails = models.ManyToManyField('contacts.Email', blank=True, verbose_name=_('Emails'))\n objects = DivisionQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('Division')\n verbose_name_plural = _('Divisions')\n ordering = ['number', 'name']\n\n def __str__(self):\n return f'{self.number} - {self.name}'\n\n def get_absolute_api_url(self):\n return reverse('companies:api:division-detail', kwargs={'pk': self.pk})\n"
},
{
"alpha_fraction": 0.698924720287323,
"alphanum_fraction": 0.698924720287323,
"avg_line_length": 15.909090995788574,
"blob_id": "2bd3161388e09f6f1df43207cc38e9382cb80dc3",
"content_id": "f6071121407b6a7f9649a07f9a67323f85ea9902",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 186,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 11,
"path": "/backend/phonebook/feedback/urls.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\nfrom django.urls import include\n\nfrom . import api_urls\n\napp_name = 'feedback'\n\n\nurlpatterns = [\n url(r'^api/', include(api_urls, namespace='api'))\n]\n"
},
{
"alpha_fraction": 0.4993065297603607,
"alphanum_fraction": 0.5048543810844421,
"avg_line_length": 26.730770111083984,
"blob_id": "483c884cb3c88c223f3ff4dfda4b44b69f804277",
"content_id": "0a11ffc711eec98843f56be66c2f6a32c6a98773",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 721,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 26,
"path": "/frontend/test/unit/employees/employees.filters.test.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "'use strict';\n\n\ndescribe('Employees filter', function() {\n beforeEach(module('pbApp'));\n beforeEach(module('pbApp.employees'));\n\n describe('toFullname', function() {\n\n it('should get employee full name (as a string)', inject(function(toFullnameFilter) {\n var employee1 = {\n surname: 'Smith',\n firstname: 'GE',\n patronymic: '.'\n },\n employee2 = {\n surname: 'Smith',\n firstname: 'GE',\n patronymic: null\n };\n\n expect(toFullnameFilter(employee1)).toEqual('Smith GE .');\n expect(toFullnameFilter(employee2)).toEqual('Smith GE');\n }));\n });\n});\n"
},
{
"alpha_fraction": 0.5024825930595398,
"alphanum_fraction": 0.5024825930595398,
"avg_line_length": 22.9761905670166,
"blob_id": "47dd7086a1fc4606734197f1e6ab8521dc108aa9",
"content_id": "f96d977f67c503ea4c19610003f2b704f3b57e72",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1041,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 42,
"path": "/frontend/src/js/app/layout/menu.directive.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.layout')\n .directive('mainMenu', mainMenu);\n\n mainMenu.$inject = [];\n\n function mainMenu() {\n return {\n controller: MainMenuCtrl,\n controllerAs: 'menu',\n restrict: 'AE',\n replace: true,\n templateUrl: 'menu.directive.html'\n }\n }\n\n MainMenuCtrl.$inject = ['$mdSidenav'];\n\n function MainMenuCtrl($mdSidenav) {\n var self = this;\n\n self.pages = [\n {'url': 'employees', name: 'Сотрудники', icon: 'contact_phone'},\n {'url': 'companies', name: 'Организации', icon: 'business'},\n {'url': 'feedback', name: 'Обратная связь', icon: 'feedback'},\n ]\n\n self.closeMenu = closeMenu;\n self.openMenu = openMenu;\n\n function closeMenu() {\n $mdSidenav('left-menu').close();\n }\n\n function openMenu() {\n $mdSidenav('left-menu').toggle();\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.2666793167591095,
"alphanum_fraction": 0.28573235869407654,
"avg_line_length": 33.26898193359375,
"blob_id": "bce10e366c546edf0429ba1b732f9b5a1a484d53",
"content_id": "11ed74ad08504029901f4c142725d5836e571ffc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 17301,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 461,
"path": "/frontend/test/unit/responds/employees.list.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "function getEmployeeList() {\n return {\n \"count\": 14,\n \"next\": null,\n \"previous\": null,\n \"results\": [\n {\n \"id\": 14,\n \"firstname\": \"Анатолий\",\n \"patronymic\": \"Махтеевич\",\n \"surname\": \"Малик\",\n \"position\": \"Доцент, к.т.н.\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 5,\n \"number\": \"308\",\n \"name\": \"Информационные технологии\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 17,\n \"firstname\": \"Николай\",\n \"patronymic\": \"Борисович\",\n \"surname\": \"Барчев\",\n \"position\": \"Старший преподаватель\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 6,\n \"number\": \"302\",\n \"name\": \"Автоматизированные системы обработки информации и управления\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 22,\n \"firstname\": \"Александр\",\n \"patronymic\": \"Михайлович\",\n \"surname\": \"Денисов\",\n \"position\": \"Заведующий кафедрой\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 8,\n \"number\": \"-\",\n \"name\": \"Факультет вычислительной математики и кибернетики\"\n },\n \"division\": {\n \"id\": 8,\n \"number\": \"-\",\n \"name\": \"Кафедра математической физики\"\n },\n \"phones\": [],\n \"emails\": [\n {\n \"id\": 12,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"birthday\": \"1946-07-23\",\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 18,\n \"firstname\": \"Александр\",\n \"patronymic\": \"Евгеньевич\",\n \"surname\": \"Ефремов\",\n \"position\": \"Декан\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 7,\n \"number\": \"1\",\n \"name\": \"Авиационная техника\"\n },\n \"division\": null,\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 21,\n \"firstname\": \"Евгений\",\n \"patronymic\": \"Иванович\",\n \"surname\": \"Моисеев\",\n \"position\": \"Декан\",\n \"company\": {\n \"id\": 7,\n \"name\": \"МГУ имени М.В.Ломоносова\",\n \"logo\": \"http://localhost:8000/media/logos/logo-mgu.png\"\n },\n \"center\": {\n \"id\": 8,\n \"number\": \"-\",\n \"name\": \"Факультет вычислительной математики и кибернетики\"\n },\n \"division\": null,\n \"phones\": [],\n \"emails\": [],\n \"birthday\": \"1948-03-07\",\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 23,\n \"firstname\": \"Генрих\",\n \"patronymic\": \"Иванович\",\n \"surname\": \"Морозов\",\n \"position\": null,\n \"company\": null,\n \"center\": null,\n \"division\": null,\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 16,\n \"firstname\": \"Геннадий\",\n \"patronymic\": \"Федорович\",\n \"surname\": \"Хахулин\",\n \"position\": \"Заведующий кафедрой\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 6,\n \"number\": \"302\",\n \"name\": \"Автоматизированные системы обработки информации и управления\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 13,\n \"firstname\": \"Анатолий\",\n \"patronymic\": \"Васильевич\",\n \"surname\": \"Шаронов\",\n \"position\": \"Заведующий кафедрой\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 5,\n \"number\": \"308\",\n \"name\": \"Информационные технологии\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 19,\n \"firstname\": \"Юрий\",\n \"patronymic\": \"Михайлович\",\n \"surname\": \"Игнаткин\",\n \"position\": \"Заведующий кафедрой\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 7,\n \"number\": \"1\",\n \"name\": \"Авиационная техника\"\n },\n \"division\": {\n \"id\": 7,\n \"number\": \"102\",\n \"name\": \"Проектирование вертолетов\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 12,\n \"firstname\": \"Михаил\",\n \"patronymic\": \"Юрьевич\",\n \"surname\": \"Куприков\",\n \"position\": \"И.о. проректора по учебной работе\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": null,\n \"division\": null,\n \"phones\": [\n {\n \"id\": 20,\n \"category\": \"Городской\",\n \"number\": \"84991584002\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 7,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"birthday\": null,\n \"place\": \"211 ГАК\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 24,\n \"firstname\": \"Ицхак\",\n \"patronymic\": \"Давидович\",\n \"surname\": \"Либерман\",\n \"position\": \"Доцент, к.т.н.\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 5,\n \"number\": \"308\",\n \"name\": \"Информационные технологии\"\n },\n \"phones\": [\n {\n \"id\": 36,\n \"category\": \"Внутренний\",\n \"number\": \"3808\",\n \"comment\": \"\"\n },\n {\n \"id\": 34,\n \"category\": \"SIP\",\n \"number\": \"411\",\n \"comment\": \"\"\n },\n {\n \"id\": 32,\n \"category\": \"Внутренний\",\n \"number\": \"4507\",\n \"comment\": \"\"\n },\n {\n \"id\": 31,\n \"category\": \"Мобильный\",\n \"number\": \"8-906-456-23-48\",\n \"comment\": \"\"\n },\n {\n \"id\": 35,\n \"category\": \"Мобильный\",\n \"number\": \"8-921-345-65-67\",\n \"comment\": \"\"\n },\n {\n \"id\": 30,\n \"category\": \"Городской\",\n \"number\": \"84956780909\",\n \"comment\": \"\"\n },\n {\n \"id\": 33,\n \"category\": \"Факс\",\n \"number\": \"84995431232\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 15,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"Личная\"\n },\n {\n \"id\": 14,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"birthday\": \"1968-01-03\",\n \"place\": \"к. 109\",\n \"comment\": \"Принимает экзамены по средам и четвергам. Всех валит.\",\n \"boss\": null\n },\n {\n \"id\": 15,\n \"firstname\": \"Владимир\",\n \"patronymic\": \"Данилович\",\n \"surname\": \"Проненко\",\n \"position\": \"Доцент, к.т.н.\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": {\n \"id\": 6,\n \"number\": \"3\",\n \"name\": \"Системы управления, информатика и электроэнергетика\"\n },\n \"division\": {\n \"id\": 5,\n \"number\": \"308\",\n \"name\": \"Информационные технологии\"\n },\n \"phones\": [],\n \"emails\": [],\n \"birthday\": null,\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 20,\n \"firstname\": \"Виктор\",\n \"patronymic\": \"Антонович\",\n \"surname\": \"Садовничий\",\n \"position\": \"Ректор\",\n \"company\": {\n \"id\": 7,\n \"name\": \"МГУ имени М.В.Ломоносова\",\n \"logo\": \"http://localhost:8000/media/logos/logo-mgu.png\"\n },\n \"center\": null,\n \"division\": null,\n \"phones\": [],\n \"emails\": [\n {\n \"id\": 11,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"birthday\": \"1939-04-03\",\n \"place\": \"\",\n \"comment\": \"\",\n \"boss\": null\n },\n {\n \"id\": 11,\n \"firstname\": \"Александр\",\n \"patronymic\": \"Викторович\",\n \"surname\": \"Рождественский\",\n \"position\": \"И.о. ректора\",\n \"company\": {\n \"id\": 6,\n \"name\": \"НИУ \\\"МАИ\\\"\",\n \"logo\": \"http://localhost:8000/media/logos/emblema_mai.png\"\n },\n \"center\": null,\n \"division\": null,\n \"phones\": [\n {\n \"id\": 18,\n \"category\": \"Городской\",\n \"number\": \"84991581343\",\n \"comment\": \"\"\n },\n {\n \"id\": 19,\n \"category\": \"Городской\",\n \"number\": \"84991581373\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 6,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"birthday\": null,\n \"place\": \"238 ГАК\",\n \"comment\": \"\",\n \"boss\": null\n }\n ]\n }\n}\n"
},
{
"alpha_fraction": 0.7264367938041687,
"alphanum_fraction": 0.7264367938041687,
"avg_line_length": 21.894737243652344,
"blob_id": "0f5a0395cac01d02a033d970b2f7598687c7b2db",
"content_id": "cdae006c7db364ba84e061762830b187f14b454b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 435,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 19,
"path": "/backend/phonebook/contacts/serializers.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\n\nfrom .models import Email, Phone\n\n\nclass PhoneSerializer(serializers.ModelSerializer):\n category = serializers.StringRelatedField()\n\n class Meta:\n model = Phone\n fields = serializers.ALL_FIELDS\n\n\nclass EmailSerializer(serializers.ModelSerializer):\n category = serializers.StringRelatedField()\n\n class Meta:\n model = Email\n fields = serializers.ALL_FIELDS\n"
},
{
"alpha_fraction": 0.5098963379859924,
"alphanum_fraction": 0.5127238631248474,
"avg_line_length": 30.205883026123047,
"blob_id": "dcda89ce905dac0504ead94fb5b66c6763d5019a",
"content_id": "464dd243e78d95fd7763096f4a9623c13287d926",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1061,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 34,
"path": "/frontend/src/js/app/utils/scroll.service.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.utils')\n .factory('Scroll', Scroll);\n\n function Scroll() {\n var InfiniteScroll = function(service, params) {\n this.results = [];\n this.after = undefined;\n this.params = angular.copy(params) || {};\n this.params.offset = (params && params.offset) ? params.offset : 0;\n this.params.limit = (params && params.limit) ? params.limit : 20;\n this.busy = false;\n this.service = service;\n };\n\n InfiniteScroll.prototype.nextPage = function() {\n if (this.busy) return;\n if (this.after === null) return;\n this.busy = true;\n\n this.service.query(this.params, function(data) {\n this.results = this.results.concat(data.results);\n this.params.offset += this.params.limit;\n this.after = data.next;\n this.busy = false;\n }.bind(this));\n };\n\n return InfiniteScroll;\n }\n})();\n"
},
{
"alpha_fraction": 0.778761088848114,
"alphanum_fraction": 0.778761088848114,
"avg_line_length": 37,
"blob_id": "82cbfc2a8c58e5e16884c02867baf3603cd934c0",
"content_id": "addd9bf592c3f6cc6bcd6c36dff3e240db35b39d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 113,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 3,
"path": "/backend/pytest.ini",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "[pytest]\nDJANGO_SETTINGS_MODULE = phonebook.settings.production\naddopts = --reuse-db --cov phonebook --cov-branch"
},
{
"alpha_fraction": 0.5330471992492676,
"alphanum_fraction": 0.5540772676467896,
"avg_line_length": 39.877193450927734,
"blob_id": "4b811bd168dd5cca5e957073326a49728eda7bde",
"content_id": "c80abdee76ec9a864cae39417162a17a39637495",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2330,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 57,
"path": "/backend/phonebook/companies/migrations/0001_initial.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2015-12-28 10:29\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('contacts', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Center',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('number', models.CharField(max_length=10)),\n ('name', models.CharField(max_length=255)),\n ('comment', models.CharField(blank=True, max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='Company',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255)),\n ('full_name', models.TextField()),\n ('short_name', models.CharField(max_length=255)),\n ('address', models.CharField(max_length=400)),\n ('logo', models.ImageField(blank=True, default='logos/no-logo.png', upload_to='logos')),\n ('comment', models.CharField(blank=True, max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='CompanyCategory',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('category', models.CharField(max_length=50, unique=True)),\n ('name', models.CharField(max_length=500)),\n ],\n ),\n migrations.CreateModel(\n name='Division',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('number', models.CharField(max_length=10)),\n ('name', models.CharField(blank=True, max_length=255)),\n ('center', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Center')),\n ('emails', models.ManyToManyField(blank=True, null=True, to='contacts.Email')),\n ],\n ),\n ]\n"
},
{
"alpha_fraction": 0.6277322173118591,
"alphanum_fraction": 0.6277322173118591,
"avg_line_length": 30.826086044311523,
"blob_id": "5b34d78fd5532ae5991fd51600578b6f89b84074",
"content_id": "5ded5be7320b05e896f16211e7581111296463c8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1464,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 46,
"path": "/backend/phonebook/employees/admin.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import Employee, FirstName, Patronymic, Position, Surname\n\n\[email protected](FirstName)\nclass FirstNameAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n\n\[email protected](Patronymic)\nclass PatronymicAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n\n\[email protected](Surname)\nclass SurnameAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n\n\[email protected](Position)\nclass PositionAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n\n\[email protected](Employee)\nclass EmployeeAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('surname', 'firstname', 'patronymic', 'birthday', 'comment')\n }),\n (_('Job'), {\n 'fields': ('company', 'center', 'division', 'position', 'place', 'boss', 'is_retired')\n }),\n (_('Contacts'), {\n 'fields': (('phones', 'emails'), )\n })\n )\n filter_horizontal = ('phones', 'emails')\n list_display = ('surname', 'firstname', 'company', 'center', 'division')\n list_filter = ('is_retired', 'company', 'center', 'division')\n list_select_related = ('surname', 'firstname', 'company', 'center', 'division')\n autocomplete_fields = ['surname', 'firstname', 'patronymic', 'company', 'center', 'division', 'boss', 'position']\n search_fields = ('surname__name', 'firstname__name')\n ordering = ('surname', 'firstname')\n"
},
{
"alpha_fraction": 0.7486376166343689,
"alphanum_fraction": 0.7486376166343689,
"avg_line_length": 35.70000076293945,
"blob_id": "712b7f2b08c6848d39fffab02f3488f52a438d5a",
"content_id": "4cadd69700f726c1d9c4c3bc4de2dfcc83451dee",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1468,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 40,
"path": "/backend/phonebook/companies/views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import generics\n\nfrom .models import Center, Company, Division\nfrom .serializers import CenterSerializer, CompanySerializer, DivisionSerializer\n\n\nclass CompanyListAPIView(generics.ListAPIView):\n queryset = Company.objects.all().select_ceo().prefetch_contacts()\n serializer_class = CompanySerializer\n search_fields = ('name', 'short_name')\n filter_fields = ('phones__number', 'emails__email')\n\n\nclass CompanyRetrieveAPIView(generics.RetrieveAPIView):\n queryset = Company.objects.all().select_ceo().prefetch_contacts()\n serializer_class = CompanySerializer\n\n\nclass CenterListAPIView(generics.ListAPIView):\n queryset = Center.objects.all().select_head().prefetch_contacts()\n serializer_class = CenterSerializer\n search_fields = ('number', 'name')\n filter_fields = ('company', 'phones__number', 'emails__email')\n\n\nclass CenterRetrieveAPIView(generics.RetrieveAPIView):\n queryset = Center.objects.all().select_head().prefetch_contacts()\n serializer_class = CenterSerializer\n\n\nclass DivisionListAPIView(generics.ListAPIView):\n queryset = Division.objects.all().select_head().prefetch_contacts()\n serializer_class = DivisionSerializer\n search_fields = ('number', 'name')\n filter_fields = ('center', 'phones__number', 'emails__email')\n\n\nclass DivisionRetrieveAPIView(generics.RetrieveAPIView):\n queryset = Division.objects.all().select_head().prefetch_contacts()\n serializer_class = DivisionSerializer\n"
},
{
"alpha_fraction": 0.5415472984313965,
"alphanum_fraction": 0.5616045594215393,
"avg_line_length": 31.314815521240234,
"blob_id": "23dcd93257dcbe6f4db489a238d2f0207c12e706",
"content_id": "8f60e48c4a173cbd9230fdcd84794482b0d52cf3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1745,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 54,
"path": "/frontend/test/unit/utils/scroll.service.test.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "'use strict';\n\ndescribe('Scroll Factory', function () {\n\n beforeEach(module('pbApp'));\n beforeEach(module('pbApp.utils'));\n\n\n it('should init and test new Scroll factory without params', inject(function(Scroll) {\n expect(Scroll).toBeDefined();\n var testService = {\n query: function(params, callback) {\n callback({results: [1, 2, 3, 4]});\n }\n }\n var scroll = new Scroll(testService);\n expect(scroll.results).toEqual([]);\n expect(scroll.busy).toBe(false);\n expect(scroll.service).toEqual(testService);\n expect(scroll.params.offset).toBe(0);\n expect(scroll.params.limit).toEqual(20);\n\n scroll.nextPage();\n\n expect(scroll.results).toEqual([1, 2, 3, 4]);\n expect(scroll.params.offset).toBe(20);\n expect(scroll.params.limit).toEqual(20);\n }));\n\n it('should init and test new Scroll factory with params', inject(function(Scroll) {\n expect(Scroll).toBeDefined();\n var testService = {\n query: function(params, callback) {\n callback({results: [1, 2, 3, 4]});\n }\n },\n params = {\n limit: 40,\n offset: 10\n };\n var scroll = new Scroll(testService, params);\n expect(scroll.results).toEqual([]);\n expect(scroll.busy).toBe(false);\n expect(scroll.service).toEqual(testService);\n expect(scroll.params.offset).toBe(10);\n expect(scroll.params.limit).toEqual(40);\n\n scroll.nextPage();\n\n expect(scroll.results).toEqual([1, 2, 3, 4]);\n expect(scroll.params.offset).toBe(50);\n expect(scroll.params.limit).toEqual(40);\n }));\n});\n"
},
{
"alpha_fraction": 0.5869565010070801,
"alphanum_fraction": 0.6391304135322571,
"avg_line_length": 18.25,
"blob_id": "efdba25592d44d56fd66b1b086ba21e945cff145",
"content_id": "b027f60cd7979bd1693e401706a89db63cea3334",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 230,
"license_type": "permissive",
"max_line_length": 42,
"num_lines": 12,
"path": "/compose/web/runtest.sh",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env sh\n\nGREEN='\\033[0;32m'\nNC='\\033[0m'\n\nisort --check-only -q || exit 1\necho -e \"${GREEN}isort: OK${NC}\"\n\npylint phonebook/* --errors-only || exit 1\necho -e \"${GREEN}pylint: OK${NC}\"\n\npytest phonebook --cov-report term"
},
{
"alpha_fraction": 0.519615113735199,
"alphanum_fraction": 0.5240562558174133,
"avg_line_length": 31.16666603088379,
"blob_id": "043ef87540f4594ccf4f1592ac799c092ecf881b",
"content_id": "644493d871e1dd32d9c5c099e99fe0d35ce49294",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1351,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 42,
"path": "/frontend/test/unit/feedback/feedbacks.controller.spec.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "describe('feedbacks.controllers', function() {\n\n var scope, $httpBackend, ctrl,\n feedbackRespond = {\n feedbacks: {results: getFeedbackList().results.slice(0, 50)}\n }\n\n beforeEach(function(){\n jasmine.addMatchers({\n toEqualData: function(util, customEqualityTesters) {\n return {\n compare: function(actual, expected) {\n return {\n pass: angular.equals(actual, expected)\n };\n }\n };\n }\n });\n });\n\n beforeEach(module('pbApp'));\n beforeEach(module('pbApp.feedback'));\n\n\n describe('FeedbackListCtrl', function() {\n beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {\n $httpBackend = _$httpBackend_;\n $httpBackend.whenGET('feedback/api/feedback/?limit=20&offset=0')\n .respond(feedbackRespond.feedbacks);\n scope = $rootScope.$new();\n ctrl = $controller('FeedbackListCtrl', {$scope: scope});\n }));\n\n it('should fetch feedbacks list', function() {\n ctrl.feedbacks.nextPage();\n $httpBackend.flush();\n expect(ctrl.feedbacks.results).toEqualData(feedbackRespond.feedbacks.results);\n });\n });\n\n});\n"
},
{
"alpha_fraction": 0.49735450744628906,
"alphanum_fraction": 0.49735450744628906,
"avg_line_length": 20,
"blob_id": "b865216595f3773b78cefec355a8b86e06fa619c",
"content_id": "1c829e53a323721726c901ece405f7f59b80ec9b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 378,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 18,
"path": "/frontend/src/js/app/employees/directives/employee-detail.directive.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.employees')\n .directive('employeeDetail', EmployeeDetail);\n\n function EmployeeDetail() {\n return {\n restrict: 'AE',\n templateUrl: 'directives/employee-detail.directive.html',\n scope: {\n employee: \"=employee\"\n }\n }\n }\n\n})();\n"
},
{
"alpha_fraction": 0.6213507652282715,
"alphanum_fraction": 0.6213507652282715,
"avg_line_length": 30.013513565063477,
"blob_id": "b396b9cfcfb46dc8570ac724a182763b24d4994f",
"content_id": "1930f7fb72fd12eabb98a0f0064d45038db03ecc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4590,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 148,
"path": "/frontend/gulpfile.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "var gulp = require('gulp'),\n concat = require('gulp-concat'),\n less = require('gulp-less'),\n minifyCss = require('gulp-minify-css'),\n sourcemaps = require('gulp-sourcemaps'),\n templateCache = require('gulp-angular-templatecache'),\n uglify = require('gulp-uglify'),\n path = require('path');\n\nvar pathToSrc = 'src/',\n pathToBuild = 'build/',\n pathToStatic = '../backend/phonebook/static/',\n pathToLess = pathToSrc + 'less/**/*.less'\n paths = {\n dependenciesCss: [\n 'bower_components/angular-material/angular-material.min.css'\n ],\n dependenciesScripts: [\n 'bower_components/jquery/dist/jquery.min.js',\n 'bower_components/angular/angular.min.js',\n 'bower_components/angular-messages/angular-messages.min.js',\n 'bower_components/angular-resource/angular-resource.min.js',\n 'bower_components/angular-route/angular-route.min.js',\n 'bower_components/angular-animate/angular-animate.min.js',\n 'bower_components/angular-aria/angular-aria.min.js',\n 'bower_components/angular-material/angular-material.min.js',\n 'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.min.js'\n ],\n appStyles: [\n pathToSrc + 'less/main.less'\n ],\n appScripts: [\n pathToSrc + 'js/app/**/*.module.js',\n pathToSrc + 'js/app/**/*.js',\n pathToBuild + 'js/templates/*.js'\n ],\n partials: [\n pathToSrc + 'js/app/**/*.html',\n '!' + pathToSrc + 'js/app/**/*.directive.html'\n ],\n companiesTemplates: [pathToSrc + 'js/app/companies/**/*.directive.html'],\n employeesTemplates: [pathToSrc + 'js/app/employees/**/*.directive.html'],\n feedbackTemplates: [pathToSrc + 'js/app/feedback/**/*.directive.html'],\n layoutTemplates: [pathToSrc + 'js/app/layout/**/*.directive.html']\n };\n\n\ngulp.task('dependencies-css', function() {\n return gulp.src(paths.dependenciesCss)\n .pipe(concat('dependencies.min.css'))\n .pipe(gulp.dest('build/css'));\n});\n\n\ngulp.task('dependencies-scripts', function() {\n return gulp.src(paths.dependenciesScripts)\n .pipe(concat('dependencies.min.js'))\n .pipe(gulp.dest('build/js'));\n});\n\n\ngulp.task('app-less', function () {\n return gulp.src(paths.appStyles)\n .pipe(less({\n paths: [ path.join(__dirname, 'less', 'includes') ]\n }))\n .pipe(concat('pb-app.min.css'))\n .pipe(minifyCss())\n .pipe(gulp.dest('build/css'));\n});\n\n\ngulp.task('copy-partials', function () {\n return gulp.src(paths.partials)\n .pipe(gulp.dest(pathToStatic + 'partials/'));\n});\n\n\ngulp.task('companies-templates', function () {\n return gulp.src(paths.companiesTemplates)\n .pipe(templateCache('pb-app.companies.tmpl.js', {module:'pbApp.companies'}))\n .pipe(gulp.dest('build/js/templates'));\n});\n\n\ngulp.task('employees-templates', function () {\n return gulp.src(paths.employeesTemplates)\n .pipe(templateCache('pb-app.employees.tmpl.js', {module:'pbApp.employees'}))\n .pipe(gulp.dest('build/js/templates'));\n});\n\ngulp.task('feedback-templates', function () {\n return gulp.src(paths.feedbackTemplates)\n .pipe(templateCache('pb-app.feedback.tmpl.js', {module:'pbApp.feedback'}))\n .pipe(gulp.dest('build/js/templates'));\n});\n\ngulp.task('layout-templates', function () {\n return gulp.src(paths.layoutTemplates)\n .pipe(templateCache('pb-app.layout.tmpl.js', {module:'pbApp.layout'}))\n .pipe(gulp.dest('build/js/templates'));\n});\n\n\ngulp.task('app-scripts', [\n 'companies-templates',\n 'employees-templates',\n 'feedback-templates',\n 'layout-templates'\n], function() {\n return gulp.src(paths.appScripts)\n .pipe(sourcemaps.init())\n .pipe(uglify())\n .pipe(concat('pb-app.min.js'))\n .pipe(sourcemaps.write())\n .pipe(gulp.dest('build/js'));\n});\n\n\ngulp.task('watch', function() {\n gulp.watch(paths.partials, ['copy-partials']);\n gulp.watch([\n paths.companiesTemplates,\n paths.employeesTemplates,\n paths.feedbackTemplates,\n paths.layoutTemplates\n ], ['copy-to-static']);\n gulp.watch(paths.appScripts, ['copy-to-static']);\n gulp.watch(pathToLess, ['copy-to-static']);\n});\n\n\ngulp.task('copy-to-static', [\n 'dependencies-css',\n 'dependencies-scripts',\n 'app-scripts',\n 'app-less'\n], function() {\n return gulp.src([pathToBuild + '**/*', '!' + pathToBuild + '**/templates/*'])\n .pipe(gulp.dest(pathToStatic))\n});\n\n\ngulp.task('default', [\n 'watch',\n 'copy-partials',\n 'copy-to-static',\n]);\n"
},
{
"alpha_fraction": 0.6853932738304138,
"alphanum_fraction": 0.6853932738304138,
"avg_line_length": 18.77777862548828,
"blob_id": "97b8ba54ff74f8be8b86619ec5aa7c3779c92ff3",
"content_id": "79f4275ff2b44a4cad522ebfa3d8a06fee8734d3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 178,
"license_type": "permissive",
"max_line_length": 52,
"num_lines": 9,
"path": "/backend/phonebook/phonebook/urls/local.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# pylint: disable=import-error,no-member\n\nimport debug_toolbar\n\nfrom .prod import * # NOQA\n\nurlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n] + urlpatterns\n"
},
{
"alpha_fraction": 0.5383877158164978,
"alphanum_fraction": 0.555662214756012,
"avg_line_length": 33.733333587646484,
"blob_id": "1911b9765edf422ec5c24833c0a47116ef5e79a9",
"content_id": "f49907926f88dfa1130971f830ce72fc17e285ed",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1117,
"license_type": "permissive",
"max_line_length": 170,
"num_lines": 30,
"path": "/backend/phonebook/feedback/migrations/0001_initial.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-04 15:16\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Feedback',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('sender', models.CharField(max_length=50, verbose_name='Отправитель')),\n ('text', models.TextField(verbose_name='Отзыв')),\n ('created_at', models.DateField(auto_now_add=True, verbose_name='Дата создания')),\n ('status', models.CharField(choices=[('SLVD', 'Решено'), (('RJCT',), 'Не решено'), ('DFLT', 'Не требует решения')], max_length=2, verbose_name='Статус')),\n ],\n options={\n 'verbose_name_plural': 'Отзывы',\n 'verbose_name': 'Отзыв',\n },\n ),\n ]\n"
},
{
"alpha_fraction": 0.7242472171783447,
"alphanum_fraction": 0.7337559461593628,
"avg_line_length": 21.535715103149414,
"blob_id": "5934100d30ae767bf50d600e6e6710ffd21795ac",
"content_id": "1817410518478debe98244d08dc6bf9c054adfd7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 631,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 28,
"path": "/backend/phonebook/phonebook/settings/local.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from .base import * # pylint: disable=wildcard-import,unused-wildcard-import\n\nDEBUG = True\n\n# See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup\nINSTALLED_APPS += (\n 'debug_toolbar',\n)\n\nMIDDLEWARE += [\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\nDEBUG_TOOLBAR_PATCH_SETTINGS = False\n\n# http://django-debug-toolbar.readthedocs.org/en/latest/installation.html\nINTERNAL_IPS = ('127.0.0.1',)\n\nROOT_URLCONF = 'phonebook.urls.local'\n\n\ndef show_toolbar(request):\n return DEBUG\n\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': 'phonebook.settings.local.show_toolbar',\n}\n"
},
{
"alpha_fraction": 0.5663484930992126,
"alphanum_fraction": 0.5741994976997375,
"avg_line_length": 39.599998474121094,
"blob_id": "d3d9ca5004a61a3f5c55903b3561bde71c6c0ecf",
"content_id": "f364636bcc7df4c1c0e166e99c07f2250bab3108",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6496,
"license_type": "permissive",
"max_line_length": 181,
"num_lines": 160,
"path": "/backend/phonebook/companies/migrations/0005_auto_20171208_2003.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 17:03\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('companies', '0004_division_comment'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='center',\n options={'ordering': ['number', 'name'], 'verbose_name': 'Center', 'verbose_name_plural': 'Centers'},\n ),\n migrations.AlterModelOptions(\n name='company',\n options={'ordering': ['name'], 'verbose_name': 'Company', 'verbose_name_plural': 'Companies'},\n ),\n migrations.AlterModelOptions(\n name='companycategory',\n options={'ordering': ['category'], 'verbose_name': 'Business entity', 'verbose_name_plural': 'Business entities'},\n ),\n migrations.AlterModelOptions(\n name='division',\n options={'ordering': ['number', 'name'], 'verbose_name': 'Division', 'verbose_name_plural': 'Divisions'},\n ),\n migrations.AlterField(\n model_name='center',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='center',\n name='company',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Company', verbose_name='Company'),\n ),\n migrations.AlterField(\n model_name='center',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Emails'),\n ),\n migrations.AlterField(\n model_name='center',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='center_head', to='employees.Employee', verbose_name='Head'),\n ),\n migrations.AlterField(\n model_name='center',\n name='name',\n field=models.CharField(max_length=255, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='center',\n name='number',\n field=models.CharField(max_length=10, verbose_name='Code'),\n ),\n migrations.AlterField(\n model_name='center',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Phones'),\n ),\n migrations.AlterField(\n model_name='company',\n name='address',\n field=models.CharField(blank=True, max_length=400, verbose_name='Address'),\n ),\n migrations.AlterField(\n model_name='company',\n name='category',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='companies.CompanyCategory', verbose_name='Business entity'),\n ),\n migrations.AlterField(\n model_name='company',\n name='ceo',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='company_ceo', to='employees.Employee', verbose_name='CEO'),\n ),\n migrations.AlterField(\n model_name='company',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='company',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Emails'),\n ),\n migrations.AlterField(\n model_name='company',\n name='full_name',\n field=models.TextField(blank=True, verbose_name='Full name'),\n ),\n migrations.AlterField(\n model_name='company',\n name='logo',\n field=models.ImageField(blank=True, default='logos/no-logo.png', upload_to='logos', verbose_name='Logo'),\n ),\n migrations.AlterField(\n model_name='company',\n name='name',\n field=models.CharField(max_length=255, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='company',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Phones'),\n ),\n migrations.AlterField(\n model_name='company',\n name='short_name',\n field=models.CharField(blank=True, max_length=255, verbose_name='Short name'),\n ),\n migrations.AlterField(\n model_name='companycategory',\n name='category',\n field=models.CharField(max_length=50, unique=True, verbose_name='Abbreviation'),\n ),\n migrations.AlterField(\n model_name='companycategory',\n name='name',\n field=models.CharField(max_length=500, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='division',\n name='center',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Center', verbose_name='Center'),\n ),\n migrations.AlterField(\n model_name='division',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='division',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Emails'),\n ),\n migrations.AlterField(\n model_name='division',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='division_head', to='employees.Employee', verbose_name='Head'),\n ),\n migrations.AlterField(\n model_name='division',\n name='name',\n field=models.CharField(blank=True, max_length=255, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='division',\n name='number',\n field=models.CharField(max_length=10, verbose_name='Code'),\n ),\n migrations.AlterField(\n model_name='division',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Phones'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5791642069816589,
"alphanum_fraction": 0.585834801197052,
"avg_line_length": 39.7760009765625,
"blob_id": "56ca67eb65193dcbcae3237e76b337eaaaaec9d9",
"content_id": "abbe3e29536e216f03883f7b160a9f5f8492c403",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5313,
"license_type": "permissive",
"max_line_length": 184,
"num_lines": 125,
"path": "/backend/phonebook/employees/migrations/0002_auto_20151229_1509.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2015-12-29 15:09\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='employee',\n options={'verbose_name': 'Сотрудник', 'verbose_name_plural': 'Сотрудники'},\n ),\n migrations.AlterModelOptions(\n name='firstname',\n options={'verbose_name': 'Имя', 'verbose_name_plural': 'Имена'},\n ),\n migrations.AlterModelOptions(\n name='patronymic',\n options={'verbose_name': 'Отчество', 'verbose_name_plural': 'Отчества'},\n ),\n migrations.AlterModelOptions(\n name='position',\n options={'verbose_name': 'Должность', 'verbose_name_plural': 'Должности'},\n ),\n migrations.AlterModelOptions(\n name='surname',\n options={'verbose_name': 'Фамилия', 'verbose_name_plural': 'Фамилии'},\n ),\n migrations.RemoveField(\n model_name='employee',\n name='first_name',\n ),\n migrations.AddField(\n model_name='employee',\n name='firstname',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.FirstName', verbose_name='Имя'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='birthday',\n field=models.DateField(blank=True, null=True, verbose_name='Дата рождения'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='boss',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='secretary', to='employees.Employee', verbose_name='Руководитель'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='center',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Center', verbose_name='Центр'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='company',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Company', verbose_name='Предприятие'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='division',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Division', verbose_name='Отделение/Отдел'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Эл. адреса'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='patronymic',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Patronymic', verbose_name='Отчество'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Телефоны'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='place',\n field=models.CharField(blank=True, max_length=255, verbose_name='Рабочее место'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='position',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Position', verbose_name='Должность'),\n ),\n migrations.AlterField(\n model_name='employee',\n name='surname',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Surname', verbose_name='Фамилия'),\n ),\n migrations.AlterField(\n model_name='firstname',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='Имя'),\n ),\n migrations.AlterField(\n model_name='patronymic',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='Отчество'),\n ),\n migrations.AlterField(\n model_name='position',\n name='name',\n field=models.CharField(max_length=255, verbose_name='Название'),\n ),\n migrations.AlterField(\n model_name='surname',\n name='name',\n field=models.CharField(max_length=50, unique=True, verbose_name='Фамилия'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5435596108436584,
"alphanum_fraction": 0.5435596108436584,
"avg_line_length": 28.234375,
"blob_id": "2a1b1494ba368c57d32d94ba4ef00f657bdd6249",
"content_id": "e90ffa2f6d28e558393aa7f8f369eee82e7f68fd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1871,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 64,
"path": "/backend/phonebook/companies/admin.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import Center, Company, CompanyCategory, Division\n\n\[email protected](Company)\nclass CompanyAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('name', 'ceo', 'category')\n }),\n (_('Additional info'), {\n 'fields': ('full_name', 'short_name', 'logo', 'comment', )\n }),\n (_('Contacts'), {\n 'fields': ('address', ('phones', 'emails'))\n })\n )\n filter_horizontal = ('phones', 'emails')\n list_display = ('name', 'ceo')\n search_fields = ('name', 'full_name', 'short_name')\n autocomplete_fields = ['ceo']\n\n\[email protected](Center)\nclass CenterAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('number', 'name', 'head', 'company', 'comment')\n }),\n (_('Contacts'), {\n 'fields': (('phones', 'emails'), )\n })\n )\n filter_horizontal = ('phones', 'emails')\n list_display = ('number', 'name', 'company', 'head')\n list_display_links = ('number', 'name')\n list_filter = ('company__name', )\n list_select_related = ('company', )\n search_fields = ('number', 'name')\n autocomplete_fields = ['head']\n\n\[email protected](Division)\nclass DivisionAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('number', 'name', 'head', 'center', 'comment')\n }),\n (_('Contacts'), {\n 'fields': (('phones', 'emails'), )\n })\n )\n filter_horizontal = ('phones', 'emails')\n list_display = ('number', 'name', 'center', 'head')\n list_display_links = ('number', 'name')\n list_filter = ('center', )\n list_select_related = ('center', )\n search_fields = ('number', 'name')\n autocomplete_fields = ['head']\n\n\nadmin.site.register(CompanyCategory)\n"
},
{
"alpha_fraction": 0.5692695379257202,
"alphanum_fraction": 0.5994962453842163,
"avg_line_length": 27.35714340209961,
"blob_id": "c128cedf84d2e7f85971cb41be900b75a1cd2c86",
"content_id": "d10739d197bfe514b46bdbfa57086d0b5238b671",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 794,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 28,
"path": "/frontend/src/js/app/app.config.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp')\n .config(config);\n\n config.$inject = ['$httpProvider', '$resourceProvider', '$mdThemingProvider'];\n\n function config($httpProvider, $resourceProvider, $mdThemingProvider) {\n $httpProvider.defaults.xsrfCookieName = 'csrftoken';\n $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';\n\n $resourceProvider.defaults.stripTrailingSlashes = false;\n\n\n var myBlue = $mdThemingProvider.extendPalette('blue', {\n '400': '4688f1',\n '500': '4688f1',\n '600': '4688f1'\n });\n $mdThemingProvider.definePalette('myBlue', myBlue);\n $mdThemingProvider.theme('default')\n .primaryPalette('myBlue')\n .accentPalette('red');\n }\n\n})();\n"
},
{
"alpha_fraction": 0.6739130616188049,
"alphanum_fraction": 0.6827697157859802,
"avg_line_length": 30.846153259277344,
"blob_id": "c031cbc06542f49d420e6d3a0075c871cb7502b7",
"content_id": "7bc1b704af999723ff8c8cf4d97cb3df9af47f7b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1242,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 39,
"path": "/backend/phonebook/employees/tests/test_views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# pylint: disable=unused-argument,no-self-use\n\nimport pytest\nfrom django.urls import reverse\n\n\nclass TestEmployeeListAPIView:\n url = reverse('employees:api:employee-list')\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, employee_factory):\n employee_factory.create_batch(5, boss__boss=None)\n response = client.get(self.url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, employee_factory):\n employee_factory.create_batch(10, boss=None)\n with django_assert_num_queries(5):\n client.get(self.url)\n\n\nclass TestEmployeeRetrieveAPIView:\n\n @pytest.fixture\n def employee(self, employee_factory):\n return employee_factory.create(boss__boss=None)\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, employee):\n url = employee.get_absolute_api_url()\n response = client.get(url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, employee):\n url = employee.get_absolute_api_url()\n with django_assert_num_queries(4):\n client.get(url)\n"
},
{
"alpha_fraction": 0.7289220690727234,
"alphanum_fraction": 0.7342582941055298,
"avg_line_length": 29.225807189941406,
"blob_id": "1fa0c9409361c50769a01c2b17fb53516bcaade8",
"content_id": "366a825c275f99734c6209410ba3e34d28e63799",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 937,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 31,
"path": "/backend/phonebook/contacts/tests/conftest.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "import factory\nfrom faker import Factory as FakerFactory\n\nfrom contacts.models import Category, Email, Phone\n\nfaker = FakerFactory.create()\n\n\nclass CategoryFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(lambda s, x: f'{faker.sentence(nb_words=3)}{x}')\n\n class Meta:\n model = Category\n\n\nclass EmailFactory(factory.django.DjangoModelFactory):\n email = factory.LazyAttributeSequence(lambda s, x: f'{faker.email()}{x}')\n category = factory.SubFactory(CategoryFactory)\n comment = factory.LazyAttribute(lambda x: faker.sentence(nb_words=10))\n\n class Meta:\n model = Email\n\n\nclass PhoneFactory(factory.django.DjangoModelFactory):\n number = factory.LazyAttributeSequence(lambda s, x: f'{faker.phone_number()}')\n category = factory.SubFactory(CategoryFactory)\n comment = factory.LazyAttribute(lambda x: faker.sentence(nb_words=10))\n\n class Meta:\n model = Phone\n"
},
{
"alpha_fraction": 0.5604770183563232,
"alphanum_fraction": 0.5945485234260559,
"avg_line_length": 28.350000381469727,
"blob_id": "b23f7e91cbb1cbf825dbe67a1c875ed6715ac8c0",
"content_id": "354609e38f787f66d4f6242fcae58a864a4fd9c2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 632,
"license_type": "permissive",
"max_line_length": 197,
"num_lines": 20,
"path": "/backend/phonebook/feedback/migrations/0002_auto_20160104_1521.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-04 15:21\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('feedback', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='feedback',\n name='status',\n field=models.CharField(choices=[('SLVD', 'Решено'), ('RJCT', 'Не решено'), ('DFLT', 'Не требует решения'), ('PRCS', 'В процессе')], default='PRCS', max_length=2, verbose_name='Статус'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.4892241358757019,
"alphanum_fraction": 0.4892241358757019,
"avg_line_length": 28.935483932495117,
"blob_id": "1581855740b105988e5a97f994246fee2ea0fee4",
"content_id": "477479ed16eb26d4fc999d84106685667f08f58e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 928,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 31,
"path": "/frontend/src/js/app/app.routes.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.routes')\n .config(config);\n\n config.$inject = ['$routeProvider'];\n\n function config($routeProvider) {\n $routeProvider.\n when('/companies', {\n templateUrl: '/static/partials/companies/company-list.html',\n controller: 'CompanyListCtrl',\n controllerAs: 'ctrl'\n }).\n when('/employees', {\n templateUrl: '/static/partials/employees/employee-list.html',\n controller: 'EmployeeListCtrl',\n controllerAs: 'ctrl'\n }).\n when('/feedback', {\n templateUrl: '/static/partials/feedback/feedbacks.html',\n controller: 'FeedbackListCtrl',\n controllerAs: 'ctrl'\n }).\n otherwise({\n redirectTo: '/employees'\n })\n };\n})();\n"
},
{
"alpha_fraction": 0.748633861541748,
"alphanum_fraction": 0.748633861541748,
"avg_line_length": 25.14285659790039,
"blob_id": "ff8af0e10c8e665ff526ad287ee33fe76847a748",
"content_id": "4ec78e2867f57e61b3a462af57904174f5f4accc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 183,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 7,
"path": "/backend/phonebook/companies/apps.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.apps import AppConfig\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass CompaniesConfig(AppConfig):\n name = 'companies'\n verbose_name = _('Companies')\n"
},
{
"alpha_fraction": 0.6153846383094788,
"alphanum_fraction": 0.6153846383094788,
"avg_line_length": 12,
"blob_id": "679d79438d8359177140fc8b7fa4f496d0bb0525",
"content_id": "8012bfc1c9eae68a942983dfcf4fc124e4a397c7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 52,
"license_type": "permissive",
"max_line_length": 19,
"num_lines": 4,
"path": "/backend/.coveragerc",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "[paths]\nsource =\n phonebook/\n /app/phonebook/\n"
},
{
"alpha_fraction": 0.41876429319381714,
"alphanum_fraction": 0.41876429319381714,
"avg_line_length": 20.850000381469727,
"blob_id": "7e3e2449c2013bc524bdb81ddd9065e5123376b9",
"content_id": "f38076c3ce3660c4245f82e552d6c89bad8227f5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 437,
"license_type": "permissive",
"max_line_length": 39,
"num_lines": 20,
"path": "/frontend/src/js/app/app.module.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n\n 'use strict';\n angular\n .module('pbApp', [\n 'ngRoute',\n 'ngResource',\n 'ngMessages',\n 'ngMaterial',\n 'infinite-scroll',\n 'pbApp.routes',\n 'pbApp.layout',\n 'pbApp.employees',\n 'pbApp.companies',\n 'pbApp.feedback',\n 'pbApp.utils'\n ]);\n\n angular.module('pbApp.routes', []);\n})();\n"
},
{
"alpha_fraction": 0.48459959030151367,
"alphanum_fraction": 0.48459959030151367,
"avg_line_length": 26.05555534362793,
"blob_id": "dab7d573872041e70486d71d6da99ce93566368c",
"content_id": "a9855677e4af23ae00e194aee47bf40108fbff00",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 487,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 18,
"path": "/frontend/src/js/app/employees/employees.filters.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.employees')\n .filter('toFullname', toFullname);\n\n function toFullname() {\n return function(employee) {\n var strOrEmpty = function(str) {\n return (str) ? str : \"\";\n }\n return (strOrEmpty(employee.surname) + ' ' +\n strOrEmpty(employee.firstname) + ' ' +\n strOrEmpty(employee.patronymic)).trim();\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.7659090757369995,
"alphanum_fraction": 0.7659090757369995,
"avg_line_length": 23.44444465637207,
"blob_id": "bbefe93e738fbb608f9f9da474fce22caed6d831",
"content_id": "42fc1f92ea63130abb87b2a433225cf241a61089",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 440,
"license_type": "permissive",
"max_line_length": 58,
"num_lines": 18,
"path": "/backend/phonebook/feedback/tests/conftest.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# pylint: disable=unused-argument,no-self-use\n\nimport factory\nfrom faker import Factory as FakerFactory\nfrom pytest_factoryboy import register\n\nfrom feedback.models import Feedback\n\nfaker = FakerFactory.create()\n\n\n@register\nclass FeedbackFactory(factory.django.DjangoModelFactory):\n sender = factory.LazyAttribute(lambda x: faker.name())\n text = factory.LazyAttribute(lambda x: faker.text())\n\n class Meta:\n model = Feedback\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6746411323547363,
"avg_line_length": 32.58928680419922,
"blob_id": "052d66a12f00327add0adfe0ae1efca888ab9f7f",
"content_id": "ac9279ae46ceb326e649f467180eb4e6b4f2d7ca",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3762,
"license_type": "permissive",
"max_line_length": 115,
"num_lines": 112,
"path": "/backend/phonebook/companies/tests/test_views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# pylint: disable=unused-argument,no-self-use\n\nimport pytest\nfrom django.urls import reverse\n\n\nclass TestCompanyListAPIView:\n url = reverse('companies:api:company-list')\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, company_factory):\n company_factory.create_batch(5, ceo__boss=None)\n response = client.get(self.url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, company_factory):\n company_factory.create_batch(5, ceo__boss=None)\n\n with django_assert_num_queries(6):\n client.get(self.url)\n\n\nclass TestCompanyRetrieveAPIView:\n\n @pytest.fixture\n def company(self, company_factory):\n return company_factory.create(ceo__boss=None)\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, company):\n url = company.get_absolute_api_url()\n response = client.get(url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, company):\n url = company.get_absolute_api_url()\n with django_assert_num_queries(5):\n client.get(url)\n\n\nclass TestCenterListAPIView:\n url = reverse('companies:api:center-list')\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, center_factory):\n center_factory.create_batch(5, head__boss=None, company__ceo__boss=None)\n response = client.get(self.url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, center_factory):\n center_factory.create_batch(5, head__boss=None, company__ceo__boss=None)\n\n with django_assert_num_queries(6):\n client.get(self.url)\n\n\nclass TestCenterRetrieveAPIView:\n\n @pytest.fixture\n def center(self, center_factory):\n return center_factory.create(head__boss=None, company__ceo__boss=None)\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, center):\n url = center.get_absolute_api_url()\n response = client.get(url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, center):\n url = center.get_absolute_api_url()\n with django_assert_num_queries(5):\n client.get(url)\n\n\nclass TestDivisionListAPIView:\n url = reverse('companies:api:division-list')\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, division_factory):\n division_factory.create_batch(5, head__boss=None, center__head__boss=None, center__company__ceo__boss=None)\n response = client.get(self.url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, division_factory):\n division_factory.create_batch(5, head__boss=None, center__head__boss=None, center__company__ceo__boss=None)\n\n with django_assert_num_queries(6):\n client.get(self.url)\n\n\nclass TestDivisionRetrieveAPIView:\n\n @pytest.fixture\n def division(self, division_factory):\n return division_factory.create(head__boss=None, center__head__boss=None, center__company__ceo__boss=None)\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, division):\n url = division.get_absolute_api_url()\n response = client.get(url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_num_queries(self, client, django_assert_num_queries, division):\n url = division.get_absolute_api_url()\n with django_assert_num_queries(5):\n client.get(url)\n"
},
{
"alpha_fraction": 0.7016574740409851,
"alphanum_fraction": 0.7016574740409851,
"avg_line_length": 19.11111068725586,
"blob_id": "fe8e2c5ca2b45b5bfceaacc13a6116530ebfff7f",
"content_id": "91c9d0ef07544c6216bf83752ac7020d1c1da046",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 362,
"license_type": "permissive",
"max_line_length": 42,
"num_lines": 18,
"path": "/backend/phonebook/contacts/admin.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import Category, Email, Phone\n\n\[email protected](Phone)\nclass PhoneAdmin(admin.ModelAdmin):\n list_filter = ('category', )\n search_fields = ('number', )\n\n\[email protected](Email)\nclass EmailAdmin(admin.ModelAdmin):\n list_filter = ('category', )\n search_fields = ('email', )\n\n\nadmin.site.register(Category)\n"
},
{
"alpha_fraction": 0.5346938967704773,
"alphanum_fraction": 0.6040816307067871,
"avg_line_length": 23.5,
"blob_id": "173f5301d2bfcf6cd2129f391374eed281829c31",
"content_id": "e8e7b29970da5a1eab5ed23f45134ffdd4b75682",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 496,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 20,
"path": "/backend/phonebook/companies/migrations/0004_division_comment.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-02 13:37\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('companies', '0003_auto_20160102_1337'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='division',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.8148148059844971,
"alphanum_fraction": 0.8148148059844971,
"avg_line_length": 53,
"blob_id": "bf9a881276a51740a81b4c1e15dbc626fac330b2",
"content_id": "6d26a4ff07486f409255ebda090c535ccd5456de",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 54,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 1,
"path": "/backend/phonebook/companies/__init__.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "default_app_config = 'companies.apps.CompaniesConfig'\n"
},
{
"alpha_fraction": 0.6206070184707642,
"alphanum_fraction": 0.6293929815292358,
"avg_line_length": 28.809524536132812,
"blob_id": "eef8484aa1ec0e7b1786c6f4551f80b198489f71",
"content_id": "6bf4d96b2c9e0b48f18b7c8cead17939329c7d78",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1252,
"license_type": "permissive",
"max_line_length": 98,
"num_lines": 42,
"path": "/backend/phonebook/contacts/models.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Category(models.Model):\n name = models.CharField(_('Name'), max_length=100, unique=True)\n\n class Meta:\n verbose_name = _('Category')\n verbose_name_plural = _('Categories')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Email(models.Model):\n email = models.EmailField(_('Email'), unique=True)\n category = models.ForeignKey('Category', verbose_name=_('Category'), on_delete=models.CASCADE)\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n\n class Meta:\n verbose_name = _('Email')\n verbose_name_plural = _('Emails')\n ordering = ['email']\n\n def __str__(self):\n return self.email\n\n\nclass Phone(models.Model):\n number = models.CharField(_('Number'), max_length=20, unique=True)\n category = models.ForeignKey('Category', verbose_name=_('Category'), on_delete=models.CASCADE)\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n\n class Meta:\n verbose_name = _('Phone')\n verbose_name_plural = _('Phones')\n ordering = ['number']\n\n def __str__(self):\n return self.number\n"
},
{
"alpha_fraction": 0.7303370833396912,
"alphanum_fraction": 0.7696629166603088,
"avg_line_length": 28.66666603088379,
"blob_id": "1f0cc8b0dbbbd1dbe4ac98af1dc671f7aeecae5f",
"content_id": "90508f159d5dbd3194436c73ae4f661bb708a5c1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 178,
"license_type": "permissive",
"max_line_length": 67,
"num_lines": 6,
"path": "/compose/web/start.sh",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env sh\n\ncd phonebook\npython3 manage.py collectstatic --noinput\npython3 manage.py migrate --noinput\n/usr/bin/gunicorn phonebook.wsgi:application -w 2 -b :8000 --reload\n"
},
{
"alpha_fraction": 0.4193548262119293,
"alphanum_fraction": 0.4193548262119293,
"avg_line_length": 14.5,
"blob_id": "d5c6ee86542e5f234520cb2c4d639c20110d5159",
"content_id": "432e422d26bae1fccd76dbccaa673145fd3ce81c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 155,
"license_type": "permissive",
"max_line_length": 36,
"num_lines": 10,
"path": "/frontend/src/js/app/employees/employees.module.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function () {\n 'use strict';\n\n angular\n .module('pbApp.employees', [\n 'ngResource',\n 'pbApp.layout'\n ]);\n\n})();\n"
},
{
"alpha_fraction": 0.557939887046814,
"alphanum_fraction": 0.5622317790985107,
"avg_line_length": 30.066667556762695,
"blob_id": "4ddce9a17dd98264c5efb271ef8f3dda38265289",
"content_id": "09a247ef7f9934141af39dbf381e9cb09ff2977b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1398,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 45,
"path": "/frontend/src/js/app/companies/company-list.controllers.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.companies')\n .controller('CompanyListCtrl', CompanyListCtrl);\n\n CompanyListCtrl.$inject = ['$q', '$filter', '$mdSidenav', 'Scroll', 'companyService'];\n\n function CompanyListCtrl($q, $filter, $mdSidenav, Scroll, companyService) {\n var self = this;\n\n self.companies = new Scroll(companyService, {limit: 40, offset: 0});\n\n self.companySearch = companySearch;\n self.closeCompanyDetail = closeCompanyDetail;\n self.openCompanyDetail = openCompanyDetail;\n\n function companySearch(query) {\n var limit = 4;\n if (!query) return self.companies.results.slice(0, limit);\n var deferred = $q.defer(),\n translated = $filter('englishCharsToRussian')(query);\n companyService.query({\n search: translated,\n limit: limit,\n offset: 0\n }, function(results, status) {\n deferred.resolve(results.results)\n });\n\n return deferred.promise\n }\n\n function closeCompanyDetail() {\n $mdSidenav('company-detail-right').close();\n }\n\n function openCompanyDetail(company) {\n if (!company) return;\n self.company = company;\n $mdSidenav('company-detail-right').toggle();\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.5538668036460876,
"alphanum_fraction": 0.5735359787940979,
"avg_line_length": 35.6721305847168,
"blob_id": "922b89a2b103e2411eb2e587ef56263fd0c6a07d",
"content_id": "1d306109f657edc654848b9d8395482d62aa52f4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2237,
"license_type": "permissive",
"max_line_length": 130,
"num_lines": 61,
"path": "/backend/phonebook/contacts/migrations/0004_auto_20171208_2003.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 17:03\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contacts', '0003_auto_20160102_1338'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='category',\n options={'ordering': ['name'], 'verbose_name': 'Category', 'verbose_name_plural': 'Categories'},\n ),\n migrations.AlterModelOptions(\n name='email',\n options={'ordering': ['email'], 'verbose_name': 'Email', 'verbose_name_plural': 'Emails'},\n ),\n migrations.AlterModelOptions(\n name='phone',\n options={'ordering': ['number'], 'verbose_name': 'Phone', 'verbose_name_plural': 'Phones'},\n ),\n migrations.AlterField(\n model_name='category',\n name='name',\n field=models.CharField(max_length=100, unique=True, verbose_name='Name'),\n ),\n migrations.AlterField(\n model_name='email',\n name='category',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Category'),\n ),\n migrations.AlterField(\n model_name='email',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='email',\n name='email',\n field=models.EmailField(max_length=254, unique=True, verbose_name='Email'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='category',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Category'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'),\n ),\n migrations.AlterField(\n model_name='phone',\n name='number',\n field=models.CharField(max_length=20, unique=True, verbose_name='Number'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5287175178527832,
"alphanum_fraction": 0.5546813607215881,
"avg_line_length": 33.35135269165039,
"blob_id": "988d158706630827174c33fb292a87608d23a74b",
"content_id": "694ee0bb2bdaa2c2d5a0cef3850951bd78d26cf0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1271,
"license_type": "permissive",
"max_line_length": 214,
"num_lines": 37,
"path": "/backend/phonebook/feedback/migrations/0004_auto_20171208_2249.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 19:49\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('feedback', '0003_auto_20171208_2003'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='feedback',\n options={'ordering': ('-created_at',), 'verbose_name': 'Feedback', 'verbose_name_plural': 'Feedback'},\n ),\n migrations.AlterField(\n model_name='feedback',\n name='created_at',\n field=models.DateField(auto_now_add=True, verbose_name='Created at'),\n ),\n migrations.AlterField(\n model_name='feedback',\n name='sender',\n field=models.CharField(max_length=50, verbose_name='Sender'),\n ),\n migrations.AlterField(\n model_name='feedback',\n name='status',\n field=models.CharField(choices=[('DF', \"Don't need to be solved\"), ('PR', 'In progress'), ('NW', 'New'), ('SL', 'Solved'), ('RJ', \"Won't be solved\")], default='NW', max_length=2, verbose_name='Status'),\n ),\n migrations.AlterField(\n model_name='feedback',\n name='text',\n field=models.TextField(verbose_name='Text'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6384615302085876,
"alphanum_fraction": 0.6424403190612793,
"avg_line_length": 32.07017517089844,
"blob_id": "21825276d3431271fb769e6b19d5e910eb6ff46d",
"content_id": "4fada13a83e26ecec1c6614c9a040b0c305150dc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3770,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 114,
"path": "/backend/phonebook/employees/models.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.urls import reverse\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass FirstName(models.Model):\n name = models.CharField(_('First name'), max_length=50, unique=True)\n\n class Meta:\n verbose_name = _('First name')\n verbose_name_plural = _('First names')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Patronymic(models.Model):\n name = models.CharField(_('Patronymic'), max_length=50, unique=True)\n\n class Meta:\n verbose_name = _('Patronymic')\n verbose_name_plural = _('Patronymics')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Surname(models.Model):\n name = models.CharField(_('Surname'), max_length=50, unique=True)\n\n class Meta:\n verbose_name = _('Surname')\n verbose_name_plural = _('Surnames')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass Position(models.Model):\n name = models.CharField(_('Name'), max_length=255, unique=True)\n\n class Meta:\n verbose_name = _('Position')\n verbose_name_plural = _('Positions')\n ordering = ['name']\n\n def __str__(self):\n return self.name\n\n\nclass EmployeeQuerySet(models.QuerySet):\n\n def select_name(self):\n return self.select_related('firstname', 'patronymic', 'surname')\n\n def select_job(self):\n return self.select_related('company', 'center', 'division', 'position')\n\n def prefetch_contacts(self):\n return self.prefetch_related('phones', 'emails', 'phones__category', 'emails__category')\n\n def prefetch_secretaries(self):\n return self.prefetch_related('secretaries')\n\n\nclass Employee(models.Model):\n surname = models.ForeignKey(\n 'Surname', null=True, blank=True, verbose_name=_('Surname'), on_delete=models.SET_NULL\n )\n firstname = models.ForeignKey(\n 'FirstName', null=True, blank=True, verbose_name=_('First name'), on_delete=models.SET_NULL\n )\n patronymic = models.ForeignKey(\n 'Patronymic', null=True, blank=True, verbose_name=_('Patronymic'), on_delete=models.SET_NULL\n )\n\n birthday = models.DateField(_('Birthday'), null=True, blank=True)\n\n company = models.ForeignKey(\n 'companies.Company', null=True, blank=True, verbose_name=_('Company'), on_delete=models.SET_NULL\n )\n center = models.ForeignKey(\n 'companies.Center', null=True, blank=True, verbose_name=_('Center'), on_delete=models.SET_NULL\n )\n division = models.ForeignKey(\n 'companies.Division', null=True, blank=True, verbose_name=_('Division'), on_delete=models.SET_NULL\n )\n position = models.ForeignKey(\n 'Position', null=True, blank=True, verbose_name=_('Position'), on_delete=models.SET_NULL\n )\n boss = models.ForeignKey(\n 'self', null=True, blank=True, on_delete=models.SET_NULL, related_name='secretaries', verbose_name=_('Boss')\n )\n place = models.CharField(_('Place'), max_length=255, blank=True)\n\n comment = models.CharField(_('Additional info'), max_length=255, blank=True)\n phones = models.ManyToManyField('contacts.Phone', blank=True, verbose_name=_('Phones'))\n emails = models.ManyToManyField('contacts.Email', blank=True, verbose_name=_('Emails'))\n is_retired = models.BooleanField(_('Is retired'), default=False)\n objects = EmployeeQuerySet.as_manager()\n\n class Meta:\n verbose_name = _('Employee')\n verbose_name_plural = _('Employees')\n ordering = ['surname', 'firstname', 'patronymic']\n\n def __str__(self):\n return f'{self.surname} {self.firstname} {self.patronymic}'\n\n def get_absolute_api_url(self):\n return reverse('employees:api:employee-detail', kwargs={'pk': self.pk})\n"
},
{
"alpha_fraction": 0.41873669624328613,
"alphanum_fraction": 0.6004258394241333,
"avg_line_length": 49.32143020629883,
"blob_id": "0cccf227001d79124cf1db29816cfc7a3300926c",
"content_id": "763fead557d223ea6ceed2d170f7f073b4008b98",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1409,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 28,
"path": "/frontend/test/unit/utils/phone-filter.test.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "'use strict';\n\n\ndescribe('Utils filter', function() {\n\n beforeEach(module('pbApp'));\n\n describe('formatPhone', function() {\n\n it('should format phone number', inject(function(formatPhoneFilter) {\n expect(formatPhoneFilter('3808')).toEqual('38-08');\n expect(formatPhoneFilter('38-08')).toEqual('38-08');\n expect(formatPhoneFilter('38 08')).toEqual('38-08');\n expect(formatPhoneFilter('1580134')).toEqual('158-01-34');\n expect(formatPhoneFilter('158-01-34')).toEqual('158-01-34');\n expect(formatPhoneFilter('158 01 34')).toEqual('158-01-34');\n expect(formatPhoneFilter('9061583434')).toEqual('(906) 158-34-34');\n expect(formatPhoneFilter('906-158-34-34')).toEqual('(906) 158-34-34');\n expect(formatPhoneFilter('(906)-158-34-34')).toEqual('(906) 158-34-34');\n expect(formatPhoneFilter('(906) 158-34-34')).toEqual('(906) 158-34-34');\n expect(formatPhoneFilter('89061583434')).toEqual('8 (906) 158-34-34');\n expect(formatPhoneFilter('8-906-158-34-34')).toEqual('8 (906) 158-34-34');\n expect(formatPhoneFilter('8 906 158 34 34')).toEqual('8 (906) 158-34-34');\n expect(formatPhoneFilter('8 (906) 158-34-34')).toEqual('8 (906) 158-34-34');\n expect(formatPhoneFilter('+79061583434')).toEqual('+7 (906) 158-34-34');\n }));\n });\n});\n"
},
{
"alpha_fraction": 0.3670295476913452,
"alphanum_fraction": 0.3670295476913452,
"avg_line_length": 23.730770111083984,
"blob_id": "03d96254db1da1177e3eb8e272688c4610339e00",
"content_id": "6010373b723bc4e8f812a5d6c3a3c40bbca5da59",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 682,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 26,
"path": "/frontend/src/js/app/feedback/feedback.filters.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.feedback')\n .filter('getStatusName', getStatusName);\n\n function getStatusName() {\n return function(code) {\n switch(code) {\n case 'DF':\n return '';\n case 'PR':\n return 'В процессе';\n case 'NW':\n return 'Новое';\n case 'SL':\n return 'Выполнено';\n case 'RJ':\n return 'Не будет выполнено';\n default:\n return \"\";\n }\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.8102409839630127,
"alphanum_fraction": 0.8102409839630127,
"avg_line_length": 29.18181800842285,
"blob_id": "04dcef0e0c6c0e0d74b9b9d440b9196ef25dbcb4",
"content_id": "140075d27e6b1402070210a482f65a8f84edda4f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 332,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 11,
"path": "/backend/phonebook/feedback/views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import generics\nfrom rest_framework.permissions import AllowAny\n\nfrom .models import Feedback\nfrom .serializers import FeedbackSerializer\n\n\nclass FeedbackListAPIView(generics.ListCreateAPIView):\n queryset = Feedback.objects.all()\n serializer_class = FeedbackSerializer\n permission_classes = (AllowAny,)\n"
},
{
"alpha_fraction": 0.5930656790733337,
"alphanum_fraction": 0.6478102207183838,
"avg_line_length": 27.842105865478516,
"blob_id": "0c6aff11d1c22926b224e0d8a1b2613b1c1ea03e",
"content_id": "f78d70167d75f96b795b7693cdbd4e563ed90ec0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 548,
"license_type": "permissive",
"max_line_length": 179,
"num_lines": 19,
"path": "/backend/phonebook/employees/migrations/0006_auto_20171208_2249.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 19:49\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('employees', '0005_auto_20171208_2003'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='employee',\n name='boss',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='secretaries', to='employees.Employee', verbose_name='Boss'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.8148148059844971,
"alphanum_fraction": 0.8148148059844971,
"avg_line_length": 53,
"blob_id": "6fdb743b1e4ff1c59fcd892d746691d4f653cf01",
"content_id": "2fd7c38c96e10cd013765bb12b5fd09544a0216f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 54,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 1,
"path": "/backend/phonebook/employees/__init__.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "default_app_config = 'employees.apps.EmployeesConfig'\n"
},
{
"alpha_fraction": 0.7104072570800781,
"alphanum_fraction": 0.7104072570800781,
"avg_line_length": 25,
"blob_id": "15ca88a801adeab44cec649662218267145e326d",
"content_id": "29df92f8ed87196d2e1f33b6030af64d4507a737",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1768,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 68,
"path": "/backend/phonebook/companies/serializers.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\n\nfrom contacts.serializers import EmailSerializer, PhoneSerializer\nfrom employees.models import Employee\n\nfrom .models import Center, Company, Division\n\n\nclass EmployeeShortSerializer(serializers.ModelSerializer):\n firstname = serializers.StringRelatedField()\n patronymic = serializers.StringRelatedField()\n surname = serializers.StringRelatedField()\n position = serializers.StringRelatedField()\n\n class Meta:\n model = Employee\n fields = ('id', 'firstname', 'patronymic', 'surname', 'position')\n\n\nclass CompanySerializer(serializers.ModelSerializer):\n ceo = EmployeeShortSerializer()\n phones = PhoneSerializer(many=True)\n emails = EmailSerializer(many=True)\n\n class Meta:\n model = Company\n fields = serializers.ALL_FIELDS\n\n\nclass CenterSerializer(serializers.ModelSerializer):\n head = serializers.StringRelatedField()\n phones = PhoneSerializer(many=True)\n emails = EmailSerializer(many=True)\n\n class Meta:\n model = Center\n fields = serializers.ALL_FIELDS\n\n\nclass DivisionSerializer(serializers.ModelSerializer):\n head = serializers.StringRelatedField()\n phones = PhoneSerializer(many=True)\n emails = EmailSerializer(many=True)\n\n class Meta:\n model = Division\n fields = serializers.ALL_FIELDS\n\n\nclass CompanyShortSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Company\n fields = ('id', 'name', 'logo')\n\n\nclass CenterShortSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Center\n fields = ('id', 'number', 'name')\n\n\nclass DivisionShortSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Division\n fields = ('id', 'number', 'name')\n"
},
{
"alpha_fraction": 0.5708267688751221,
"alphanum_fraction": 0.5808320045471191,
"avg_line_length": 43.16279220581055,
"blob_id": "68d8cfd1371234e09832a6e4aad5fb44da5ed80f",
"content_id": "09b5eef0a0a61c64edb638bb7fb89d9c9c4087dd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3798,
"license_type": "permissive",
"max_line_length": 163,
"num_lines": 86,
"path": "/backend/phonebook/employees/migrations/0001_initial.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2015-12-28 10:29\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('companies', '0001_initial'),\n ('contacts', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Employee',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('birthday', models.DateField(blank=True, null=True)),\n ('place', models.CharField(blank=True, max_length=255)),\n ('comment', models.CharField(blank=True, max_length=255)),\n ('boss', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='secretary', to='employees.Employee')),\n ('center', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Center')),\n ('company', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Company')),\n ('division', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.Division')),\n ('emails', models.ManyToManyField(blank=True, null=True, to='contacts.Email')),\n ],\n ),\n migrations.CreateModel(\n name='FirstName',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50, unique=True)),\n ],\n ),\n migrations.CreateModel(\n name='Patronymic',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50, unique=True)),\n ],\n ),\n migrations.CreateModel(\n name='Position',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='Surname',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50, unique=True)),\n ],\n ),\n migrations.AddField(\n model_name='employee',\n name='first_name',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.FirstName'),\n ),\n migrations.AddField(\n model_name='employee',\n name='patronymic',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Patronymic'),\n ),\n migrations.AddField(\n model_name='employee',\n name='phones',\n field=models.ManyToManyField(blank=True, null=True, to='contacts.Phone'),\n ),\n migrations.AddField(\n model_name='employee',\n name='position',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Position'),\n ),\n migrations.AddField(\n model_name='employee',\n name='surname',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='employees.Surname'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.572933554649353,
"alphanum_fraction": 0.5737439393997192,
"avg_line_length": 20.275861740112305,
"blob_id": "c7a2147ecfa0eb65a54d91cc0f4a169edc448bd7",
"content_id": "7a98b1f51b3321aeb5350acbf079ae5bf2d1f193",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2468,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 116,
"path": "/docs/API.md",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# API\n\nEach GET-method accepts following parameters:\n\n| Name | Type | Description |\n| :-------- | :--- | :---------- |\n| limit | int | Defines page size. Default to 50 |\n| offset | int | Defines offset of the elements |\n| ordering | str | Field to apply ordering by |\n\n\n## Companies\n\n### /companies/api/company\n\n**Method GET**\n\nReturns list of companies\n\n| Name | Type | Description |\n| :------------- | :--- | :---------- |\n| search | str | Search by name |\n| phones__number | str | Filters by provided phone number |\n| emails__emails | str | Filters by provided email |\n\n\n### /companies/api/company/:id\n\n**Method GET**\n\nReturns company with specified `id`\n\n\n### /companies/api/center\n\n**Method GET**\n\nReturns list of centers\n\n| Name | Type | Description |\n| :------------- | :--- | :---------- |\n| company | int | Filters by id of the company |\n| search | str | Search by name |\n| phones__number | str | Filters by provided phone number |\n| emails__emails | str | Filter by provided email |\n\n\n### /companies/api/center/:id\n\n**Method GET**\n\nReturns center with specified `id`\n\n\n### /companies/api/division\n\n**Method GET**\n\nReturns list of divisions\n\n| Name | Type | Description |\n| :------------- | :--- | :---------- |\n| center | int | Filters by id of the center |\n| search | str | Search by name |\n| phones__number | str | Filters by provided phone number |\n| emails__emails | str | Filter by provided email |\n\n\n### /companies/api/division/:id\n\n**Method GET**\n\nReturns division with provided `id`\n\n\n## Employees\n\n### /employees/api/employee\n\n**Method GET**\n\nReturn list of employees\n\n| Name | Type | Description |\n| :------------- | :--- | :---------- |\n| company | int | Filters by id of the company |\n| center | int | Filters by id of the center |\n| division | int | Filters by id of the division |\n| search | str | Search by first name, surname and patronymic |\n| phones__number | str | Filters by provided phone number |\n| emails__emails | str | Filter by provided email |\n\n\n### /employees/api/employee/:id\n\n**Method GET**\n\nReturns employee with specified `id`\n\n\n## Feedback\n\n### /feedback/api/feedback\n\n**Method GET**\n\nReturns list of feedbacks\n\n**Method POST**\n\nCreate new feedback\n\n| Name | Type | Description |\n| :---------| :--- | :---------- |\n| sender | str | Sender name |\n| text | text | text |\n"
},
{
"alpha_fraction": 0.5401380062103271,
"alphanum_fraction": 0.5466763377189636,
"avg_line_length": 37.23611068725586,
"blob_id": "68ea2c1f3ba5b16fde4b64dbe836c446cc2c8ed9",
"content_id": "0ba37b23141c7d5323fa6a4e211baab7e23f73dc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2757,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 72,
"path": "/frontend/test/unit/companies/companies.controller.spec.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "describe('Companies controllers', function() {\n\n beforeEach(function(){\n jasmine.addMatchers({\n toEqualData: function(util, customEqualityTesters) {\n return {\n compare: function(actual, expected) {\n return {\n pass: angular.equals(actual, expected)\n };\n }\n };\n }\n });\n });\n\n beforeEach(module('pbApp'));\n beforeEach(module('pbApp.companies'));\n\n describe('CompanyListCtrl Test', function() {\n var scope, $httpBackend, ctrl,\n companyRespond = {\n companies: {results: getCompanyList().results.slice(0, 40)},\n companySearch: {results: getCompanyList().results.slice(0, 5)},\n }\n\n beforeEach(inject(function(_$httpBackend_, $rootScope, $routeParams, $controller) {\n $httpBackend = _$httpBackend_;\n $httpBackend.whenGET('companies/api/company/?limit=40&offset=0')\n .respond(companyRespond.companies);\n $httpBackend.whenGET('companies/api/company/?limit=4&offset=0&search=%D0%BD%D0%BF%D0%BE%D0%BB')\n .respond(companyRespond.companySearch);\n scope = $rootScope.$new();\n ctrl = $controller('CompanyListCtrl', {$scope: scope});\n }));\n\n\n it('should fetch companies', function() {\n var limit = 40;\n expect(ctrl.companies).toEqualData({\n results: [],\n after: undefined,\n params: {limit: limit, offset: 0},\n busy: false\n });\n ctrl.companies.nextPage();\n expect(ctrl.companies.busy).toBe(true);\n $httpBackend.flush();\n expect(ctrl.companies.results).toEqualData(companyRespond.companies.results);\n expect(ctrl.companies.params.limit).toEqual(limit);\n expect(ctrl.companies.params.offset).toEqual(limit);\n expect(ctrl.companies.after).toBe(undefined);\n expect(ctrl.companies.busy).toBe(false);\n });\n\n\n it('should return results for autocomplete search query', function() {\n ctrl.searchText = \"нпол\";\n var res = ctrl.companySearch(ctrl.searchText);\n $httpBackend.flush();\n expect(res.$$state.value).toEqualData(companyRespond.companySearch.results);\n });\n\n\n it('should set ctrl.company to company', function() {\n expect(ctrl.company).toBeUndefined();\n var company = companyRespond.companies.results[0];\n ctrl.openCompanyDetail(company);\n expect(ctrl.company).toEqual(company);\n });\n });\n});\n"
},
{
"alpha_fraction": 0.6941176652908325,
"alphanum_fraction": 0.6941176652908325,
"avg_line_length": 16,
"blob_id": "42ca6ea445e3773d6e94f90801bab092ef530176",
"content_id": "9718a0ed6f01f23ad936662b43d446280f31233b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 170,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 10,
"path": "/backend/phonebook/feedback/api_urls.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'api'\n\n\nurlpatterns = [\n path('feedback/', views.FeedbackListAPIView.as_view(), name='feedback-list'),\n]\n"
},
{
"alpha_fraction": 0.5838509202003479,
"alphanum_fraction": 0.6086956262588501,
"avg_line_length": 22,
"blob_id": "05a146b6bafef610b838153c9a426713b995d043",
"content_id": "fd7beb966a3306eb325e8277d2db9749d59e0d56",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 161,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 7,
"path": "/compose/web/entrypoint.sh",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env sh\nfind . -name \"*.pyc\" -exec rm -f {} \\;\n\nexport DJANGO_DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}\n\ncmd=\"$@\"\nexec $cmd\n"
},
{
"alpha_fraction": 0.729106605052948,
"alphanum_fraction": 0.729106605052948,
"avg_line_length": 37.55555725097656,
"blob_id": "13b07f2464932219abce949551ad550062cdd272",
"content_id": "09e9ee6205c3fc97cd76a2e984cef2c3f9e2dffc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1041,
"license_type": "permissive",
"max_line_length": 99,
"num_lines": 27,
"path": "/backend/phonebook/employees/serializers.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\n\nfrom companies.serializers import (\n CenterShortSerializer, CompanyShortSerializer, DivisionShortSerializer, EmployeeShortSerializer\n)\nfrom contacts.serializers import EmailSerializer, PhoneSerializer\n\nfrom .models import Employee\n\n\nclass EmployeeSerializer(serializers.ModelSerializer):\n firstname = serializers.StringRelatedField()\n patronymic = serializers.StringRelatedField()\n surname = serializers.StringRelatedField()\n position = serializers.StringRelatedField()\n company = CompanyShortSerializer()\n center = CenterShortSerializer()\n division = DivisionShortSerializer()\n secretaries = EmployeeShortSerializer(many=True)\n phones = PhoneSerializer(many=True)\n emails = EmailSerializer(many=True)\n\n class Meta:\n model = Employee\n fields = ('id', 'firstname', 'patronymic', 'surname', 'position',\n 'company', 'center', 'division', 'place', 'is_retired',\n 'secretaries', 'phones', 'emails', 'birthday', 'comment')\n"
},
{
"alpha_fraction": 0.47777777910232544,
"alphanum_fraction": 0.47777777910232544,
"avg_line_length": 20.176469802856445,
"blob_id": "a98d8a5a9f5f3e6935df7a590169ea37fda578f6",
"content_id": "d4056f2b8cad2c1d02a2951c3027f50ce7d7a48d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 360,
"license_type": "permissive",
"max_line_length": 57,
"num_lines": 17,
"path": "/frontend/src/js/app/companies/company-detail.directive.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.companies')\n .directive('companyDetail', companyDetail);\n\n function companyDetail() {\n return {\n restrict: 'AE',\n templateUrl: 'company-detail.directive.html',\n scope: {\n company: '=company'\n }\n }\n }\n})();\n"
},
{
"alpha_fraction": 0.7094653844833374,
"alphanum_fraction": 0.7129710912704468,
"avg_line_length": 30.69444465637207,
"blob_id": "dd4eeffe2db2d45ee81ef2afdfc69008b925e459",
"content_id": "c7ce489a976cbfbca4fde6c710db6ca0e3f4ed26",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2282,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 72,
"path": "/backend/phonebook/companies/tests/conftest.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# pylint: disable=unused-argument,no-self-use\n\nimport factory\nfrom faker import Factory as FakerFactory\nfrom pytest_factoryboy import register\n\nfrom companies.models import Center, Company, CompanyCategory, Division\nfrom contacts.tests.conftest import EmailFactory, PhoneFactory\nfrom employees.tests.conftest import EmployeeFactory\n\nfaker = FakerFactory.create()\n\n\n@register\nclass CompanyCategoryFactory(factory.django.DjangoModelFactory):\n category = factory.LazyAttributeSequence(lambda s, x: f'{faker.word()}{x}')\n name = factory.LazyAttribute(lambda x: faker.sentence(nb_words=4))\n\n class Meta:\n model = CompanyCategory\n\n\n@register\nclass CompanyFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttribute(lambda x: faker.company)\n ceo = factory.SubFactory(EmployeeFactory)\n category = factory.SubFactory(CompanyCategoryFactory)\n\n class Meta:\n model = Company\n\n @factory.post_generation\n def groups(self, create, extracted, **kwargs):\n for _ in range(3):\n self.phones.add(PhoneFactory())\n self.emails.add(EmailFactory())\n\n\n@register\nclass CenterFactory(factory.django.DjangoModelFactory):\n company = factory.SubFactory(CompanyFactory)\n head = factory.SubFactory(EmployeeFactory)\n number = factory.LazyAttribute(lambda x: faker.word()[:10])\n name = factory.LazyAttribute(lambda x: faker.word())\n comment = factory.LazyAttribute(lambda x: faker.paragraph())\n\n class Meta:\n model = Center\n\n @factory.post_generation\n def groups(self, create, extracted, **kwargs):\n for _ in range(3):\n self.phones.add(PhoneFactory())\n self.emails.add(EmailFactory())\n\n\n@register\nclass DivisionFactory(factory.django.DjangoModelFactory):\n center = factory.SubFactory(CenterFactory)\n head = factory.SubFactory(EmployeeFactory)\n number = factory.LazyAttribute(lambda x: faker.word()[:10])\n name = factory.LazyAttribute(lambda x: faker.word())\n comment = factory.LazyAttribute(lambda x: faker.paragraph())\n\n class Meta:\n model = Division\n\n @factory.post_generation\n def groups(self, create, extracted, **kwargs):\n for _ in range(3):\n self.phones.add(PhoneFactory())\n self.emails.add(EmailFactory())\n"
},
{
"alpha_fraction": 0.6975609660148621,
"alphanum_fraction": 0.6975609660148621,
"avg_line_length": 35.17647171020508,
"blob_id": "a2df4b4fe627a4cc4c3cdadad584aaafff929c78",
"content_id": "541d6d02d9e8aebcd308a2221cde45c5153951fa",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 615,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 17,
"path": "/backend/phonebook/companies/api_urls.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom . import views\n\napp_name = 'companies'\n\n\nurlpatterns = [\n path('company/', views.CompanyListAPIView.as_view(), name='company-list'),\n path('company/<int:pk>/', views.CompanyRetrieveAPIView.as_view(), name='company-detail'),\n\n path('center/', views.CenterListAPIView.as_view(), name='center-list'),\n path('center/<int:pk>/', views.CenterRetrieveAPIView.as_view(), name='center-detail'),\n\n path('division/', views.DivisionListAPIView.as_view(), name='division-list'),\n path('division/<int:pk>/', views.DivisionRetrieveAPIView.as_view(), name='division-detail'),\n]\n"
},
{
"alpha_fraction": 0.7181628346443176,
"alphanum_fraction": 0.7181628346443176,
"avg_line_length": 35.846153259277344,
"blob_id": "11b0cd22fba88c9bdf97b948ee5b26c059b1b819",
"content_id": "8bb56524150fd226bee31eb7a6f577c6f438c5ef",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 479,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 13,
"path": "/backend/phonebook/phonebook/urls/prod.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import include\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.views import generic\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('companies/', include('companies.urls', namespace='companies')),\n path('feedback/', include('feedback.urls', namespace='feedback')),\n path('employees/', include('employees.urls', namespace='employees')),\n path('', generic.TemplateView.as_view(template_name='index.html'))\n]\n"
},
{
"alpha_fraction": 0.7070175409317017,
"alphanum_fraction": 0.7175438404083252,
"avg_line_length": 26.14285659790039,
"blob_id": "ea71d1904f9059610f78fc202c759ed806bc501a",
"content_id": "247e487c78696bde7efcbc9e7bf475ffd33810ab",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 570,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 21,
"path": "/compose/web/Dockerfile",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "FROM alpine\n\nRUN apk update && \\\n apk upgrade && \\\n apk add --update python3 python3-dev git postgresql-client postgresql-dev build-base gettext jpeg-dev zlib-dev\n\nCOPY ./backend/requirements /requirements\nRUN pip3 install --upgrade pip && \\\n pip3 install -r /requirements/prod.txt && \\\n pip3 install -r /requirements/test.txt && \\\n apk del -r python3-dev postgresql git\n\nCOPY ./compose/web/start.sh /start.sh\nRUN chmod +x /start.sh\n\nCOPY ./compose/web/entrypoint.sh /entrypoint.sh\nRUN chmod +x /entrypoint.sh\n\nWORKDIR /app\n\nENTRYPOINT [\"/entrypoint.sh\"]\n"
},
{
"alpha_fraction": 0.5281206965446472,
"alphanum_fraction": 0.570644736289978,
"avg_line_length": 32.1363639831543,
"blob_id": "643416653435a7b319a6ffedde392be44f9ad052",
"content_id": "0d2edc42ce7763fb0f08cd3c953aaf4b8349c09e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 790,
"license_type": "permissive",
"max_line_length": 204,
"num_lines": 22,
"path": "/backend/phonebook/feedback/migrations/0003_auto_20171208_2003.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.0 on 2017-12-08 17:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('feedback', '0002_auto_20160104_1521'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='feedback',\n options={'ordering': ('-created_at',), 'verbose_name': 'Отзыв', 'verbose_name_plural': 'Отзывы'},\n ),\n migrations.AlterField(\n model_name='feedback',\n name='status',\n field=models.CharField(choices=[('DF', 'Не требует решения'), ('PR', 'В процессе'), ('NW', 'Новое'), ('SL', 'Решено'), ('RJ', 'Не решено')], default='NW', max_length=2, verbose_name='Статус'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5623268485069275,
"alphanum_fraction": 0.5623268485069275,
"avg_line_length": 21.5625,
"blob_id": "c8e80b3b5b7ba0205b184f885f604e43ce45a028",
"content_id": "26cefaff572147c6b71ec553305e9f141ef5142d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 361,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 16,
"path": "/frontend/src/js/app/employees/employees.services.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "(function() {\n 'use strict';\n\n angular\n .module('pbApp.employees')\n .factory('employeeService', employeeService);\n\n employeeService.$inject = ['$resource'];\n\n function employeeService($resource) {\n return $resource('employees/api/employee/:id', {}, {\n query: {method: 'GET', isArray: false}\n });\n };\n\n})();\n"
},
{
"alpha_fraction": 0.2897351086139679,
"alphanum_fraction": 0.32119205594062805,
"avg_line_length": 22.230770111083984,
"blob_id": "102f78d83db655e56a3c251b45c19999ac92643b",
"content_id": "fec60b838dcf2074dcb7da8cd31e556b550c9b44",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 653,
"license_type": "permissive",
"max_line_length": 48,
"num_lines": 26,
"path": "/frontend/test/unit/responds/companies.division.detail.js",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "function getDivisionDetail() {\n return {\n \"id\": 5,\n \"head\": \"Шаронов Анатолий Васильевич\",\n \"phones\": [\n {\n \"id\": 22,\n \"category\": \"Городской\",\n \"number\": \"84951584367\",\n \"comment\": \"\"\n }\n ],\n \"emails\": [\n {\n \"id\": 9,\n \"category\": \"Электронная почта\",\n \"email\": \"[email protected]\",\n \"comment\": \"\"\n }\n ],\n \"number\": \"308\",\n \"name\": \"Информационные технологии\",\n \"comment\": \"\",\n \"center\": 6\n }\n}\n"
},
{
"alpha_fraction": 0.6552072763442993,
"alphanum_fraction": 0.6643073558807373,
"avg_line_length": 31.96666717529297,
"blob_id": "5c4379d8305f1a76d7b746ec40e5c7cb4b3c7e16",
"content_id": "dae40cd551accef64d4bae96162b4c14b50e3322",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 989,
"license_type": "permissive",
"max_line_length": 91,
"num_lines": 30,
"path": "/backend/phonebook/feedback/tests/test_views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom django.urls import reverse\n\nfrom feedback.models import Feedback\n\n\nclass TestFeedbackListAPIView:\n url = reverse('feedback:api:feedback-list')\n\n @pytest.mark.django_db\n def test_response_status_code(self, client, feedback_factory):\n feedback_factory.create_batch(5)\n response = client.get(self.url)\n assert response.status_code == 200\n\n @pytest.mark.django_db\n def test_assert_num_queries(self, client, django_assert_num_queries, feedback_factory):\n feedback_factory.create_batch(5)\n with django_assert_num_queries(2):\n client.get(self.url)\n\n @pytest.mark.django_db\n def test_create(self, client):\n data = {'sender': 'Junior', 'text': 'Wow! This is great!'}\n response = client.post(self.url, data)\n assert response.status_code == 201\n\n feedback = Feedback.objects.filter().first()\n assert feedback.sender == data['sender']\n assert feedback.text == data['text']\n"
},
{
"alpha_fraction": 0.7626112699508667,
"alphanum_fraction": 0.7626112699508667,
"avg_line_length": 41.125,
"blob_id": "d7ddaee30f4b5cb7ccc66dbabf33f2d387413b37",
"content_id": "edd8ed87eb6a08b5e850310b2ee3e3e68b37e167",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 674,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 16,
"path": "/backend/phonebook/employees/views.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from rest_framework import generics\n\nfrom .models import Employee\nfrom .serializers import EmployeeSerializer\n\n\nclass EmployeeListAPIView(generics.ListAPIView):\n queryset = Employee.objects.select_name().select_job().prefetch_contacts().prefetch_secretaries()\n serializer_class = EmployeeSerializer\n search_fields = ('firstname__name', 'patronymic__name', 'surname__name')\n filter_fields = ('company', 'center', 'division', 'phones__number', 'emails__email')\n\n\nclass EmployeeRetrieveAPIView(generics.RetrieveAPIView):\n queryset = Employee.objects.select_name().select_job().prefetch_contacts().prefetch_secretaries()\n serializer_class = EmployeeSerializer\n"
},
{
"alpha_fraction": 0.5683980584144592,
"alphanum_fraction": 0.5779129862785339,
"avg_line_length": 39.83439636230469,
"blob_id": "8049bc92cda0b98e34ab592f8a83ce31d481a3d7",
"content_id": "db343e09dc2a68bf8b8e1b50f65b6a757612067f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6727,
"license_type": "permissive",
"max_line_length": 187,
"num_lines": 157,
"path": "/backend/phonebook/companies/migrations/0003_auto_20160102_1337.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2016-01-02 13:37\nfrom __future__ import unicode_literals\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('companies', '0002_auto_20151228_1029'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='center',\n options={'ordering': ['number', 'name'], 'verbose_name': 'Центр', 'verbose_name_plural': 'Центры'},\n ),\n migrations.AlterModelOptions(\n name='company',\n options={'ordering': ['name'], 'verbose_name': 'Предприятие', 'verbose_name_plural': 'Предприятия'},\n ),\n migrations.AlterModelOptions(\n name='companycategory',\n options={'ordering': ['category'], 'verbose_name': 'Тип предприятие', 'verbose_name_plural': 'Типы предприятий'},\n ),\n migrations.AlterModelOptions(\n name='division',\n options={'ordering': ['number', 'name'], 'verbose_name': 'Отделение/Отдел', 'verbose_name_plural': 'Отделения/Отделы'},\n ),\n migrations.AlterField(\n model_name='center',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n migrations.AlterField(\n model_name='center',\n name='company',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Company', verbose_name='Предприятие'),\n ),\n migrations.AlterField(\n model_name='center',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Эл. адреса'),\n ),\n migrations.AlterField(\n model_name='center',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='center_head', to='employees.Employee', verbose_name='Начальник'),\n ),\n migrations.AlterField(\n model_name='center',\n name='name',\n field=models.CharField(max_length=255, verbose_name='Название'),\n ),\n migrations.AlterField(\n model_name='center',\n name='number',\n field=models.CharField(max_length=10, verbose_name='Номер'),\n ),\n migrations.AlterField(\n model_name='center',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Телефоны'),\n ),\n migrations.AlterField(\n model_name='company',\n name='address',\n field=models.CharField(max_length=400, verbose_name='Адрес'),\n ),\n migrations.AlterField(\n model_name='company',\n name='category',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='companies.CompanyCategory', verbose_name='Тип предприятия'),\n ),\n migrations.AlterField(\n model_name='company',\n name='ceo',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='company_ceo', to='employees.Employee', verbose_name='Руководитель'),\n ),\n migrations.AlterField(\n model_name='company',\n name='comment',\n field=models.CharField(blank=True, max_length=255, verbose_name='Доп. инф.'),\n ),\n migrations.AlterField(\n model_name='company',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Эл. адреса'),\n ),\n migrations.AlterField(\n model_name='company',\n name='full_name',\n field=models.TextField(verbose_name='Полное название'),\n ),\n migrations.AlterField(\n model_name='company',\n name='logo',\n field=models.ImageField(blank=True, default='logos/no-logo.png', upload_to='logos', verbose_name='Логотип'),\n ),\n migrations.AlterField(\n model_name='company',\n name='name',\n field=models.CharField(max_length=255, verbose_name='Название'),\n ),\n migrations.AlterField(\n model_name='company',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Телефоны'),\n ),\n migrations.AlterField(\n model_name='company',\n name='short_name',\n field=models.CharField(max_length=255, verbose_name='Сокращенное название'),\n ),\n migrations.AlterField(\n model_name='companycategory',\n name='category',\n field=models.CharField(max_length=50, unique=True, verbose_name='Аббревиатура'),\n ),\n migrations.AlterField(\n model_name='companycategory',\n name='name',\n field=models.CharField(max_length=500, verbose_name='Полное название'),\n ),\n migrations.AlterField(\n model_name='division',\n name='center',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.Center', verbose_name='Центр'),\n ),\n migrations.AlterField(\n model_name='division',\n name='emails',\n field=models.ManyToManyField(blank=True, to='contacts.Email', verbose_name='Эл. адреса'),\n ),\n migrations.AlterField(\n model_name='division',\n name='head',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='division_head', to='employees.Employee', verbose_name='Начальник'),\n ),\n migrations.AlterField(\n model_name='division',\n name='name',\n field=models.CharField(blank=True, max_length=255, verbose_name='Название'),\n ),\n migrations.AlterField(\n model_name='division',\n name='number',\n field=models.CharField(max_length=10, verbose_name='Номер'),\n ),\n migrations.AlterField(\n model_name='division',\n name='phones',\n field=models.ManyToManyField(blank=True, to='contacts.Phone', verbose_name='Телефоны'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.6901960968971252,
"alphanum_fraction": 0.6901960968971252,
"avg_line_length": 24.5,
"blob_id": "1fb5b8cab6eb83fee050b4d73235898e699051e7",
"content_id": "d8cde80674eeab416c1c618a88e6ccfbc303fb84",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 255,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 10,
"path": "/backend/phonebook/feedback/admin.py",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import Feedback\n\n\[email protected](Feedback)\nclass FeedbackAdmin(admin.ModelAdmin):\n list_display = ('sender', 'text', 'created_at', 'status')\n list_editable = ('status', )\n list_filter = ('status',)\n"
},
{
"alpha_fraction": 0.7517843246459961,
"alphanum_fraction": 0.778747022151947,
"avg_line_length": 38.40625,
"blob_id": "601a91b93baa38abc7eec7a3cc55a736390245e4",
"content_id": "44d380d12f9da5d16e8ab86a3557e16cefa9f872",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1261,
"license_type": "permissive",
"max_line_length": 152,
"num_lines": 32,
"path": "/docs/LOOK.md",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "## Phonebook look\n\n\n### Employees page\n\n**Employee detail**\n\n\n**Adaptive design**\n\n\n**Print dialog**\n\n\n\n### Companies page\n\n\n**Companies list**\n\n\n\n### Feedback\n\n\n**New feedback**\n\n\n\n### Admin\n\n\n"
},
{
"alpha_fraction": 0.6772486567497253,
"alphanum_fraction": 0.6772486567497253,
"avg_line_length": 62,
"blob_id": "c22f3f9e556be1313f17a02c292ea4264d0719ef",
"content_id": "c6750a77e15bdd26a764fcfd33e49f5d2ca71341",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 189,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 3,
"path": "/compose/db/docker-entrypoint-initdb.d/phonebook_db.sh",
"repo_name": "unmade/phonebook",
"src_encoding": "UTF-8",
"text": "psql -U postgres -c \"CREATE USER ${DB_USER} PASSWORD '${DB_PASSWORD}'\"\npsql -U postgres -c \"CREATE DATABASE ${DB_NAME} OWNER ${DB_USER}\"\npsql -U postgres -c \"ALTER USER ${DB_USER} CREATEDB\"\n"
}
] | 85 |
Hellen02Henandez2021/Ejercicioclase5 | https://github.com/Hellen02Henandez2021/Ejercicioclase5 | 2b46e9d7e89542c69dccb7b6dd6fdf464b040690 | 46af2a0374047d4cfc01667b02b424292ee690ef | 906738308801256288116f89a129c2f8ec8d79c2 | refs/heads/main | 2023-07-22T02:20:59.183783 | 2021-08-28T16:46:03 | 2021-08-28T16:46:03 | 400,841,846 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6304348111152649,
"alphanum_fraction": 0.6884058117866516,
"avg_line_length": 18.571428298950195,
"blob_id": "e70a8c198dcfd05794de4eae23c7bb85d68f5a9c",
"content_id": "42fbe634d60fd3e921f168d0f89a5cfebba4b97f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 138,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 7,
"path": "/ejercicio5/ejercicioclase5.py",
"repo_name": "Hellen02Henandez2021/Ejercicioclase5",
"src_encoding": "UTF-8",
"text": " valor=int(\"imput\"(\"valor del producto\" )\n \n if valor>=100: \n descuento=0.10\nelse: descuento=0\npagar=valor*(1-descuento)\nprint(pagar)\n"
}
] | 1 |
TheRealAsk/TheAsker | https://github.com/TheRealAsk/TheAsker | b81f6619c1d7dc368dc206ddaf626f501da6deb0 | 1d6e60265b9fc8bd51c12debf24d684bbbb522e4 | e7667b545c0a940dc0bc431fac980e9a7e38a8ed | refs/heads/master | 2022-08-01T07:51:59.365472 | 2020-05-16T14:26:42 | 2020-05-16T14:26:42 | 264,442,439 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6177839040756226,
"alphanum_fraction": 0.6303635835647583,
"avg_line_length": 26.73762321472168,
"blob_id": "b9fdda2ae5061bab7b67a86da2e600c9ec2efa63",
"content_id": "b523da1841078fba901d8fbad25379581e537a03",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6539,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 202,
"path": "/bot.py",
"repo_name": "TheRealAsk/TheAsker",
"src_encoding": "UTF-8",
"text": "import discord\r\nfrom discord.utils import get\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import Bot\r\nimport random\r\nimport youtube_dl\r\nimport os\r\nimport pyowm\r\nfrom discord.ext.commands.errors import *\r\n\r\n\r\nlist_landscape = ['a.jpg', 'b.jpg', 's.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg']\r\nlist_cat = ['c.jpg', 'm.jpg', 'z.jpg', 'n.jpg', 'v.jpg', 'q.jpg', 'w.jpg', 'e.jpg', 'r.jpg', 't.jpg', 'y.jpg',]\r\nlist_dog = ['dog1.jpg', 'dog2.jpg', 'dog3.jpg', 'dog4.jpg','dog5.jpg', 'dog6.jpg']\r\n\r\nBot = commands.Bot(command_prefix = '-')\r\n\r\nBot.remove_command('help')\r\n\r\[email protected]\r\nasync def on_ready():\r\n print('+')\r\n\r\n\r\[email protected]()\r\nasync def join(ctx):\r\n global voice\r\n channel = ctx.message.author.voice.channel\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n\r\n if voice and voice.is_connected():\r\n await voice.move_to(channel)\r\n else:\r\n voice = await channel.connect()\r\n await ctx.send(f'bot connected to voice channel {channel}')\r\n\r\n\r\[email protected]()\r\nasync def leave(ctx):\r\n channel = ctx.message.author.voice.channel\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n\r\n if voice and voice.is_connected():\r\n await voice.disconnect()\r\n else:\r\n voice = await channel.connect()\r\n await ctx.send(f'bot disconnected to voice channel {channel}')\r\n\r\n\r\[email protected]()\r\nasync def play(ctx, url : str):\r\n song_there = os.path.exists('song.mp3')\r\n\r\n try:\r\n if song_there:\r\n os.remove('song.mp3')\r\n print('[log] Старый файл удален')\r\n except PermissionError:\r\n print('[log] не удалось удалить файл')\r\n\r\n await ctx.send('Ожидание...')\r\n\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n\r\n ydl_opts = {\r\n 'format' : 'bestaudio/best',\r\n 'postprocessors' : [{\r\n 'key' : 'FFmpegExtractAudio',\r\n 'preferredcodec' : 'mp3',\r\n 'preferredquality' : '192'\r\n }],\r\n }\r\n\r\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\r\n print('[log] Загружаю МУЗОН...')\r\n ydl.download([url])\r\n\r\n for file in os.listdir('./'):\r\n if file.endswith('.mp3'):\r\n name = file\r\n print(f'[log] Переименовываю файл: {file}')\r\n os.rename(file, 'song.mp3')\r\n\r\n voice.play(discord.FFmpegPCMAudio('song.mp3'), after = lambda e: print(f'[log] {name}, Музыка закончила своё прогирование'))\r\n voice.source = discord.PCMVolumeTransformer(voice.source)\r\n voice.source.volume = 0.6\r\n\r\n song_name = name.rsplit('-', 2)\r\n await ctx.send(f'проигрывание {song_name[1]}')\r\n\r\n\r\[email protected]()\r\nasync def stop(ctx):\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n voice.stop()\r\n\r\n\r\[email protected]()\r\nasync def pause(ctx):\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n voice.pause()\r\n\r\n\r\[email protected]()\r\nasync def resume(ctx):\r\n voice = get(Bot.voice_clients, guild = ctx.guild)\r\n voice.resume()\r\n\r\n\r\[email protected]()\r\nasync def help(ctx):\r\n await ctx.send('''Что я умею делать\r\n#Комманды для картинок\r\n```1)landscape - выдает рандомный пейзаж\r\n2)cat - высылает рандомного котика ^-^\r\n3)dog - высылает рандомную собачку ^-^\r\n4)stonks - Ну тупо стонкс\r\n5)nostonks - Ну тупо не стонкс```\r\n#Комманды для музыки\r\n```1)join - добавляет бота в войс чат в котором вы сидите\r\n2)leave - удаляет бота из войс чата в котором вы сидите\r\n3)play (Ссылка url на видео в youtube) - проигрывает песню (бот должен быть в войсе и после команды надо вставить ссылку на видео на ютубе)\r\n4)stop - останавливает музыку \r\n5)pause - ставит на паузу музыку\r\n6)resume - возобновляет воспроизведение музыки```\r\n#Бесполезные, но интересные комманды\r\n```1)dyrka - вызывает дурку\r\n2)whydimaisgay - говорит почему же дима гей\r\n3)sanyasotky - САНЯ ЭТО УЖЕ НЕ СМЕШНО\r\n4)weather (Город/Страна) - выясняет погоду в каком то городе\r\n5)donate - Поддержка разрабов```''')\r\n\r\n\r\[email protected]()\r\nasync def landscape(ctx):\r\n await ctx.send(file = discord.File(fp = list_landscape[random.randint(0, 2)]))\r\n\r\[email protected]()\r\nasync def cat(ctx):\r\n await ctx.send(file = discord.File(fp = 'cats/' + list_cat[random.randint(0, 10)]))\r\n\r\n\r\[email protected]()\r\nasync def dyrka(ctx):\r\n await ctx.send(file = discord.File(fp = 'Dyrka.png'))\r\n\r\n\r\[email protected]()\r\nasync def whydimaisgay(ctx):\r\n await ctx.send('''Потому что так надо''')\r\n\r\n\r\[email protected]()\r\nasync def stonks(ctx):\r\n await ctx.send(file = discord.File(fp = 'stonks.jpg'))\r\n\r\n\r\[email protected]()\r\nasync def nostonks(ctx):\r\n await ctx.send(file = discord.File(fp = 'notstonks.jpg'))\r\n\r\n\r\[email protected]()\r\nasync def dog(ctx):\r\n await ctx.send(file = discord.File(fp = 'dogs/' + list_dog[random.randint(0, 5)]))\r\n\r\n\r\[email protected]()\r\nasync def sanyasotky(ctx):\r\n await ctx.send('''САНЯ СОТКУ ВЕРНИ!!!''')\r\n\r\n\r\[email protected]()\r\nasync def weather(ctx, place : str):\r\n owm = pyowm.OWMowm = pyowm.OWM('63f515875baf3226d7689dc6ae18d157', language = 'ru')\r\n observation = owm.weather_at_place(place)\r\n w = observation.get_weather()\r\n temp = w.get_temperature('celsius')['temp']\r\n await ctx.send('В городе ' + place + ' сейчас ' + str(temp) + ' по цельсию ' + str(w.get_detailed_status()))\r\n\r\n\r\[email protected]()\r\nasync def donate(ctx):\r\n await ctx.send('Хочешь поддержать разрабов? https://www.donationalerts.com/r/kirill0712')\r\n\r\n\r\n#errors\r\[email protected]\r\nasync def weather_error(ctx, error):\r\n if isinstance(error, commands.MissingRequiredArgument):\r\n await ctx.send(f'{ctx.author.mention}, Пример: -weather Москва')\r\n\r\n\r\[email protected]\r\nasync def play_error(ctx, error):\r\n if isinstance(error, commands.MissingRequiredArgument):\r\n await ctx.send(f'{ctx.author.mention}, Шаблон: play url_adress')\r\n\r\n\r\ntoken = os.environ.get('BOT_TOKEN')\r\n\r\nBot.run(token)"
},
{
"alpha_fraction": 0.762499988079071,
"alphanum_fraction": 0.762499988079071,
"avg_line_length": 9.428571701049805,
"blob_id": "e1e47438d42f09b769f641196ffc98b2ce51809f",
"content_id": "c3a95d6e356f0f05b82f8034746399a766c38652",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 80,
"license_type": "no_license",
"max_line_length": 17,
"num_lines": 7,
"path": "/requirements.txt",
"repo_name": "TheRealAsk/TheAsker",
"src_encoding": "UTF-8",
"text": "discord.py\r\ndiscord.py[voice]\r\nyoutube-dl\r\npyowm\r\naiohttp\r\nwebsockets\r\nchardet\r\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7222222089767456,
"avg_line_length": 8,
"blob_id": "7a6b1cdb0ae7e90bce17458230ecb725dbdf0547",
"content_id": "030b25d6ef95ba4f10ee5c589e3c68261431bde5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 18,
"license_type": "no_license",
"max_line_length": 10,
"num_lines": 2,
"path": "/README.md",
"repo_name": "TheRealAsk/TheAsker",
"src_encoding": "UTF-8",
"text": "# TheAsker\nmy bot\n"
}
] | 3 |
fabiand/non-orchestrated-vm-playground | https://github.com/fabiand/non-orchestrated-vm-playground | 00a0b02ee10dfca22a64667637506a2c93585749 | c535b1d4d4cf5642fa1953959bbe80f4ebf8d0b8 | 9f540fc6f1c879f580a0ca6774a15c35b68a0aa8 | refs/heads/master | 2021-08-29T16:05:34.339885 | 2017-12-14T08:24:23 | 2017-12-14T08:24:23 | 111,911,220 | 1 | 1 | null | 2017-11-24T11:30:33 | 2017-12-01T19:14:37 | 2017-12-14T08:24:24 | XSLT | [
{
"alpha_fraction": 0.6570155620574951,
"alphanum_fraction": 0.6636971235275269,
"avg_line_length": 20.380952835083008,
"blob_id": "84b55a076f536b02326967d58ee1ee14e60fa981",
"content_id": "ef969bb3936b3609d0218fda8f61374efa0ee72a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 21,
"path": "/launch.d/yaml2xml",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "#!/bin/env python3\n\nimport sys\nimport xmltodict\nimport yaml\n\nvm = None\nif len(sys.argv) > 1:\n with open(sys.argv[1]) as src:\n vm = src.read()\nelse:\n vm = sys.stdin.read()\n\nvmdata = yaml.load(vm)\n\n# Dropping these fields because they will lead to slahses in tag names\nfor k in [\"annotations\", \"labels\"]:\n if k in vmdata[\"metadata\"]:\n del vmdata[\"metadata\"][k]\n\nprint(xmltodict.unparse({\"VirtualMachine\": vmdata}, pretty=True))\n"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.720588207244873,
"avg_line_length": 21.66666603088379,
"blob_id": "bdff0144ce687d8ed2b13f42c4c86530de9d3860",
"content_id": "628ed52fcc7422dd9abb0e2911ec9c8dcf680987",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 3,
"path": "/vm/serial",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nSOCKET=$(basename $0)\nsocat unix-connect:/$SOCKET stdio\n"
},
{
"alpha_fraction": 0.5913757681846619,
"alphanum_fraction": 0.6098562479019165,
"avg_line_length": 17.037036895751953,
"blob_id": "2848d9c1a0bf8da3bd8ac7350020589c560fb8ff",
"content_id": "e6ae6339514ab50ed4bbffd7b8bfabb6e11478f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 27,
"path": "/launch",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nset -xe\n\nusage() { echo \"$0 VIRTUALMACHINE\"; exit 2 ; }\nmirror() { tee /dev/stderr ; }\ngetYAML() {\nif [[ -f \"$1\" ]]; then\n cat \"$1\"\nelse\n kubectl get -o yaml vms ${1:-$(hostname)} ;\nfi\n}\n\necho Args:\necho $@\n\necho Starting:\ngetYAML \"$1\" \\\n | mirror | ./launch.d/yaml2xml \\\n | mirror | xsltproc launch.d/vmspec2domxml.xsl /dev/stdin \\\n | mirror | xsltproc launch.d/domxml2qemu.xsl /dev/stdin \\\n | mirror > .launchline\n\ncat .launchline\n\n[[ -z \"$DRY\" ]] && bash .launchline\n"
},
{
"alpha_fraction": 0.744415819644928,
"alphanum_fraction": 0.7504295706748962,
"avg_line_length": 25.454545974731445,
"blob_id": "f4bbdc2fe2438d49eb30663d36e096cb5fcc1c6a",
"content_id": "62abac34cc4ac55df150910fe2d62ab62e194f4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2330,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 88,
"path": "/README.md",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "# Run non-orchestrated (or standalone) VMs\n\nNon-orchestrated VMs could be VMs which are not managed by KubeVirt controllers,\ninstead they are directly consumed by pods.\n\nIf only a pod is required to launch a VM, then VMs can be used with everything\nwhich is launching pods. I.e. Deployments, ReplicaSets, …\nOn the other hand this has drawbacks as the feature set is limited.\n\n## How it works\n\nThe pod is responsible for launching the VM, so it does everything itself.\nThe logic required to do this is shipped in the launch container.\n\nIn general it works as follows:\n\n- Guess the VM definition to use\n- Pull down the VM definition\n- [Create the VM](launch.d/) based on this definition\n\n## Entities\n\nThe following example is generally using [this VM definition](manifests/vm.yaml)\nand [this pod definition](manifests/pod.yaml).\nIn general it's worth to take a look into the [`manifests/`](manifests/) dir.\n\n## Example\n\nYou will need `minikube` or a different Kubernetes cluster.\n\nThe next step is to clone the repository (not required, but then you can cut\nand paste the steps below).\n\n```bash\n$ git clone https://github.com/fabiand/non-orchestrated-vm-playground/\n$ cd non-orchestrated-vm-playground\n```\n\nNow we can start to setup the cluster:\n\n```bash\n# Deploy some dependencies\n$ kubectl apply -f manifests/deps.yaml\n\n# Define the VM definition\n$ kubectl apply -f manifests/vm.yaml\n\n\n# Launch a pod using the defined VM definition\n$ kubectl apply -f manifests/pod.yaml\n\n# To watch it boot\n$ kubectl logs -f testvm\n\n# To access the serial\n$ kubectl exec -it testvm /vm/serial\n\n# To access the monitor\n$ kubectl exec -it testvm /vm/monitor\n$ kubectl exec -it testvm /vm/qmp\n\n# To access it's vnc display\n$ socat SYSTEM:\"kubectl exec -i testvm /vm/vnc\" tcp-listen:5942\n$ remote-viewer vnc://127.0.0.1:5942\n```\n\n### Higher level workload types\n\nThis approach also works for higher level workloads:\n\n```bash\n# Launch a deployment using the VM definition\n$ kubectl apply -f manifests/deployment.yaml\n\n# See the spawned pods\n$ kubectl get pods\n```\n\n## Known Issues\n\n- Alpine does not bring up networking by default\n- Exposing ports is [not done yet](https://github.com/fabiand/pod-network-poc)\n- No checks about if the VM fits into the pod\n\n## Charming next steps\n\n- `ServiceAccount`\n- Policies for `hostNetwork` in order to use PVs\n"
},
{
"alpha_fraction": 0.7232620120048523,
"alphanum_fraction": 0.740641713142395,
"avg_line_length": 24.758621215820312,
"blob_id": "27cb0067ec73fc5291113fb38df411342ea438bf",
"content_id": "23e84fa492eb43dd3c985dcc7540f7f443da8302",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 748,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 29,
"path": "/Makefile",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "\ndomxml2qemu:\n\txsltproc launch.d/domxml2qemu.xsl data/fedora27.xml\n\ndata/%.yaml.xml: data/%.yaml\n\t./launch.d/yaml2xml $< > $@\n\nvmspec2domxml: data/vm.yaml.xml\n\txsltproc launch.d/vmspec2domxml.xsl $<\n\nbuild:\n\tsudo docker build -t docker.io/fabiand/lvm .\n\npush:\n\tsudo docker push docker.io/fabiand/lvm\n\nrun-container:\n\tsudo docker run --rm -it docker.io/fabiand/lvm launch applied-vm.yaml\n\nrun-pod:\n\tkubectl apply -f manifests/pod.yaml\n\ndeploy-deps:\n\tkubectl apply -f manifests/iscsi-demo-target.yaml -f manifests/vm-resource.yaml\n\tkubectl apply -f data/vm.yaml\n\t./launch.d/kubeObjWait pods\n\ntest: deploy-deps run-pod\n\ttimeout 300 sh -c \"until kubectl logs --tail=10 testvm | grep Welcome ; do sleep 3 ; echo -n . ; done\"\n\tkubectl delete pods testvm\n"
},
{
"alpha_fraction": 0.7327327132225037,
"alphanum_fraction": 0.7537537813186646,
"avg_line_length": 29.18181800842285,
"blob_id": "5589a3292bfce87aa9ca2469e1391e45e4961b80",
"content_id": "853ed10675cf43b508c828f1019edac1551e93ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 333,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 11,
"path": "/Dockerfile",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "FROM kubevirt/libvirt\n\nRUN dnf install -y libxslt python3-xmltodict python3-PyYAML socat\nRUN curl -L -o /usr/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v1.8.0/bin/linux/amd64/kubectl && chmod a+x /usr/bin/kubectl\n\nCMD /launch\n\nADD data/applied-vm.yaml /\nADD launch.d/ /launch.d/\nADD vm/ /vm/\nADD launch /\n\n"
},
{
"alpha_fraction": 0.6977777481079102,
"alphanum_fraction": 0.7200000286102295,
"avg_line_length": 33.61538314819336,
"blob_id": "79be9bd2ce51a06708483258604fe03412457f97",
"content_id": "71c5bdac894b9ce0b5a3a98e3aa1e1d3192cff05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 450,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 13,
"path": "/launch.d/README.md",
"repo_name": "fabiand/non-orchestrated-vm-playground",
"src_encoding": "UTF-8",
"text": "The launcher works pretty simple\n\n1. Fetch spec in yaml from cluster using `kubectl`\n2. Translate _spec yaml_ to _spec xml_ using\n using `python3` (`yaml` and `xmltodict`)\n (usually not required)\n3. Transform _spec xml_ to _domxml_\n using [vmspec2domxml.xsl](vmspec2domxml.xsl)\n (usually done by `virt-handler`)\n4. Transform _domxml_ to _qemu cmdline_\n using [domxml2qemu.xsl](domxml2qemu.xsl)\n (usually done by `libvirt`)\n5. Launch qemu\n"
}
] | 7 |
Oxymoren/discord-stats-and-bot | https://github.com/Oxymoren/discord-stats-and-bot | fc3e0d79bc868892274b6ae04a08b594032ff906 | 522a0975d86e76965bf996997f9d23986d3f1831 | 54e58d4a769c123076f07952dc79112a296cd5bf | refs/heads/master | 2020-05-16T22:31:49.504658 | 2019-04-25T02:15:17 | 2019-04-25T02:15:17 | 183,338,980 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7612612843513489,
"alphanum_fraction": 0.7657657861709595,
"avg_line_length": 48.22222137451172,
"blob_id": "44297a830e1118795cf5abb4ddb862c0373877ee",
"content_id": "a4c58328e1268d857fc19cf18f360611cb6f6052",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 444,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 9,
"path": "/README.md",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "# Discord Stats & Bot\n\nThe project began by collecting stats on a discord server with a few close friends.\n\nUsing that data, the bot has two main features. \n\n1. Output markov chains, by user, based off the history of the discord server. Also included a combined model and some fun models. \n\n2. A RNG \"league\" which where users could challenge each other to see who had the best luck. Included an elo system to keep track of who was luckiest. \n"
},
{
"alpha_fraction": 0.5943204760551453,
"alphanum_fraction": 0.6146044731140137,
"avg_line_length": 25,
"blob_id": "f98112202d364076dfc081c5a42334afd8a765f1",
"content_id": "620198d15a7c6b12e8bc18b327b2b332d32099cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 493,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 19,
"path": "/PyScripts/GetEmojiCount.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "RAW_DATA_PATH = \"REMOVED FOR GITHUB\"\n\nwith open(RAW_DATA_PATH, 'r') as RawFile:\n FileText = RawFile.read()\n\t\nEmojiDict = {}\nfor Word in FileText.split():\n\tif len(Word) > 1 and Word[0] == ':':\n\t\tif Word[1:].find(':') != -1:\n\t\t\tWord = Word[: Word[1:].find(':')+2]\n\t\t\tif Word in EmojiDict.keys():\n\t\t\t\tEmojiDict[Word] = EmojiDict[Word] + 1\n\t\t\telse:\n\t\t\t\tEmojiDict[Word] = 1\n\n\t\n\t\nfor Emoji in sorted(EmojiDict, key = EmojiDict.get, reverse=True):\n\tprint(\"{0} {1}\".format(Emoji, EmojiDict[Emoji]))"
},
{
"alpha_fraction": 0.6876770257949829,
"alphanum_fraction": 0.6919263601303101,
"avg_line_length": 32.64285659790039,
"blob_id": "7d37cd82a6cf523a34015efb2b0d63e46b934943",
"content_id": "62efed8e1662f55ecb17c331ad14096340da8534",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1412,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 42,
"path": "/PyScripts/FilterText.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport numpy as np\nimport re as re\n\nRAW_DATA_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nEVERYONE_EXPORT_PATH =\"REMOVED FOR GITHUB\"\n\t\t\t\t\t\nExportPathItr = iter(RAW_EXPORT_PATHS)\nfor RawDataPath in RAW_DATA_PATHS:\n\tTextDF = pd.read_csv(RawDataPath)\n\tOutputFile = open(next(ExportPathItr), \"wb\")\n\tfor index, Message in TextDF.iterrows():\n\t\tFilteredMessage = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', '', str(Message[\"Content\"]), flags=re.MULTILINE)\n\t\tFilteredMessage = re.sub(r'@\\w+', '', str(FilteredMessage), flags=re.MULTILINE)\n\t\tFilteredMessage+=\". \"\n\t\tif FilteredMessage[0:3] == \"/r \" or FilteredMessage==\"nan. \":\n\t\t\tcontinue\n\t\t\n\t\tFilteredMessage = FilteredMessage.encode('utf8', 'ignore')\n\t\tOutputFile.write(FilteredMessage)\n\tOutputFile.close() \n\nOutputFile = open(EVERYONE_EXPORT_PATH, \"wb\")\t\nfor RawDataPath in RAW_DATA_PATHS:\n\tTextDF = pd.read_csv(RawDataPath)\n\tfor index, Message in TextDF.iterrows():\n\t\tFilteredMessage = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', '', str(Message[\"Content\"]), flags=re.MULTILINE)\n\t\tFilteredMessage = re.sub(r'@\\w+', '', str(FilteredMessage), flags=re.MULTILINE)\n\t\tFilteredMessage+=\". \"\n\t\tif FilteredMessage[0:3] == \"/r \" or FilteredMessage==\"nan. \":\n\t\t\tcontinue\n\t\t\n\t\tFilteredMessage = FilteredMessage.encode('utf8', 'ignore')\n\t\tOutputFile.write(FilteredMessage)\nOutputFile.close()"
},
{
"alpha_fraction": 0.6769230961799622,
"alphanum_fraction": 0.689230740070343,
"avg_line_length": 22.285715103149414,
"blob_id": "eb9ad4b835e48d72cf5260e11d8dd670aeb69fca",
"content_id": "c6d783414df2923fa30e51e1a9521257937de6d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 325,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 14,
"path": "/PyScripts/TestGenerator.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import markovify as mk\nimport random\nimport string\n\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\t\t\t\t\n\t\t\t\t\t\nJsonImport = open(RAW_EXPORT_PATHS[0]).read()\nModel=mk.Text.from_json(JsonImport)\n#print(\" \".join(Model.make_sentence() for i in range(5)))\nfor i in range(10):\n\tprint(Model.make_sentence())"
},
{
"alpha_fraction": 0.7033898234367371,
"alphanum_fraction": 0.7097457647323608,
"avg_line_length": 21.5238094329834,
"blob_id": "808252fab6fb678c0b60a451db6a43f548780c15",
"content_id": "0666a2a9f60c6ae2f613c9e55e79da6e98c7cf92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 472,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/PyScripts/CreateAllCT.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport numpy as np\n\nRAW_DATA_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nExpPathItr = iter(RAW_EXPORT_PATHS)\n\nAllData = pd.read_csv(RAW_DATA_PATHS[0])\n\nfor DataPath in range(1, len(RAW_DATA_PATHS)):\n\tCurrentData = pd.read_csv(RAW_DATA_PATHS[DataPath])\n\tAllData = AllData.append(CurrentData)\n\t\nAllData.to_csv(RAW_EXPORT_PATHS[0], index=False)\nprint (len(AllData))"
},
{
"alpha_fraction": 0.6241534948348999,
"alphanum_fraction": 0.6264108419418335,
"avg_line_length": 29.586206436157227,
"blob_id": "53135c24a1632a2d107a1540fc422e05b6f14369",
"content_id": "8766bd46e65ee8280fed8b43bda080f91df9ecec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 886,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 29,
"path": "/PyScripts/CountingStats.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport numpy as np\n\nRAW_DATA_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nExpPathItr = iter(RAW_EXPORT_PATHS)\n\t\nprint(\"\\n\\n=================================\\nMessage Count\\n\"\n\t + \"=================================\\n\\n\")\nfor DataPath in RAW_DATA_PATHS:\n\tName = DataPath[-9:-4]\n\tprint(\"\\n-----------------\" + Name.upper() + \"-----------------\")\n\t\n\tRawChatDataFrame = pd.read_csv(DataPath)\n\tprint(\"Number of Messages: \" + str(len(RawChatDataFrame)))\n\t\n\tChatByUser = RawChatDataFrame.groupby(\"Author\").count()\n\tprint(ChatByUser)\n\tChatByUser.to_csv(next(ExpPathItr))\n\t\n\tChatMessageMean = RawChatDataFrame.groupby(\"Author\")[\"Content\"].apply(lambda x: np.mean(x.str.len())).reset_index(name='mean_chat_message_length')\n\tprint(ChatMessageMean)\n\tChatMessageMean.to_csv(next(ExpPathItr))"
},
{
"alpha_fraction": 0.7009202241897583,
"alphanum_fraction": 0.703987717628479,
"avg_line_length": 24.076923370361328,
"blob_id": "d26fb75b5a6859dd44bfcd93b2b1c574d0ed2c96",
"content_id": "d2fdbd8afc33906a5ae071e29b16e749a7fa9b99",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 652,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 26,
"path": "/PyScripts/TimeStatsByPerson.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport numpy as np\n\nRAW_DATA_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\n\t\t\t\t\t\nExportPathItr = iter(RAW_EXPORT_PATHS)\n\nfor RawDataPath in RAW_DATA_PATHS:\n\tRawData = pd.read_csv(RawDataPath)\n\tRawData[\"Date\"] = pd.to_datetime(RawData[\"Date\"])\n\tRawData.index = RawData[\"Date\"]\n\n\ttimes= pd.DatetimeIndex(RawData[\"Date\"])\n\tGroupedData = RawData.groupby(times.hour).count()\n\tGroupedData = GroupedData.iloc[:,0:1] \n\tGroupedData.index.names = [\"Hour\"]\n\tGroupedData.columns = [\"Count\"]\n\tGroupedData.to_csv(next(ExportPathItr))\n\tprint (GroupedData)\n"
},
{
"alpha_fraction": 0.6616393327713013,
"alphanum_fraction": 0.6834972500801086,
"avg_line_length": 28.522581100463867,
"blob_id": "ce6748e620d88b4f235f98000e29ad2b6e5da570",
"content_id": "7b8c914819c54ef002d902bda0f3064fa362034b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4575,
"license_type": "no_license",
"max_line_length": 267,
"num_lines": 155,
"path": "/PyScripts/Discord/DiscordMain.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import discord\nimport random\nimport markovify as mk\n\nclient = discord.Client()\n\n\n\nELO_PATH = \"REMOVED FOR GITHUB\"\nELO_NAMES = [[\"REMOVED FOR GITHUB\", \"REMOVED FOR GITHUB\"],\n\t\t\t[\"REMOVED FOR GITHUB\", \"REMOVED FOR GITHUB\"]]\n\t\t\t\t\n\n\n\n\t\t\t\t\nMODEL_PATHS = {\"REMOVED FOR GITHUB\",\n\t\t\t\t\"REMOVED FOR GITHUB\"}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\ndef GenerateMarkov(Name):\n\tOutputMessage = \"\"\n\tSentenceCount = 0\n\tJsonImport = open(MODEL_PATHS[Name]).read()\n\tModel=mk.Text.from_json(JsonImport)\n\twhile OutputMessage == \"\" or SentenceCount < 5:\n\t\tGeneratedMessage = Model.make_sentence()\n\t\tif GeneratedMessage != None:\n\t\t\tOutputMessage = OutputMessage + ' ' + GeneratedMessage\n\t\tSentenceCount += 1\n\treturn OutputMessage\n\n\n\ndef RNGLeague(Sender, Reciever, Dice):\n\tfor EloIndex in range(len(ELO_NAMES)):\n\t\tif Sender == ELO_NAMES[EloIndex][1]:\n\t\t\tSenderIndex = EloIndex\n\t\tif Reciever == ELO_NAMES[EloIndex][0]:\n\t\t\tRecieverIndex = EloIndex\n\tif SenderIndex==RecieverIndex:\n\t\treturn \"You can't challenge yourself!\"\n\tEloFile = open(ELO_PATH, \"r+\")\n\tEloList = EloFile.readlines()\n\t\n\tEloSender = int(EloList[SenderIndex])\n\tEloReciever = int(EloList[RecieverIndex])\n\tExpSender = 1 / (1 + 10 ** ((EloReciever - EloSender) / 400))\n\tExpReciever = 1 / (1 + 10 ** ((EloSender - EloReciever) / 400))\n\t\n\tSenderRoll = random.randint(0, Dice)\n\tRecieverRoll = random.randint(0, Dice)\n\t\n\tif SenderRoll < RecieverRoll:\n\t\tEloSender = int(round(EloSender + 128 * (0 - ExpSender)))\n\t\tEloReciever = int(round(EloReciever + 128 * (1 - ExpSender)))\n\t\tWinner=ELO_NAMES[RecieverIndex][0]\n\telif SenderRoll > RecieverRoll:\n\t\tEloSender = int(round(EloSender + 128 * (1 - ExpSender)))\n\t\tEloReciever = int(round(EloReciever + 128 * (0 - ExpSender)))\n\t\tWinner=ELO_NAMES[SenderIndex][0]\n\t\n\telse: \n\t\tWinner=\"nobody\"\n\t\t\n\tEloList[SenderIndex] = str(EloSender) + \"\\n\"\n\tEloList[RecieverIndex] = str(EloReciever) + \"\\n\"\n\t\n\tEloFile.seek(0)\n\tEloFile.writelines(EloList)\n\tEloFile.truncate()\n\tEloFile.close()\n\treturn \"{0}: {1}, {2}: {3} | {4} wins! | {5} elo: {6}, {7} elo: {8}\".format(ELO_NAMES[SenderIndex][0], str(SenderRoll), ELO_NAMES[RecieverIndex][0], str(RecieverRoll), Winner, ELO_NAMES[SenderIndex][0], str(EloSender), ELO_NAMES[RecieverIndex][0], str(EloReciever))\n\t\t\ndef RNGLeagueList():\n\tEloFile = open(ELO_PATH)\n\tEloList = EloFile.readlines()\n\tEloFile.close()\n\tmsg = \"-\\n\"\n\tfor EloI in range(len(EloList)):\n\t\tmsg = msg + ELO_NAMES[EloI][0] + \": \" + EloList[EloI]\n\treturn msg\n\[email protected]\nasync def on_message(message):\n\tif message.author.bot:\n\t\treturn #Ignore Bots\n\t\n\telif message.content.lower().startswith(\"!help\"):\n\t\tmsg = \"Current Commands:\\n!Simulate: Simulates a a _REMOVED_\\n!List: Lists the _REMOVED_ keywords for !Simulate\\n!RNGLeague: Challenge someone to a bout of RNG\\nRNGLeagueList: Display RNGLeague Elos\"\n\t\tawait client.send_message(message.channel, msg)\n\t\treturn\n\t\t\t\n\telif message.content.lower().startswith(\"!list\"):\n\t\tmsg=\"REMOVED FOR GITHUB\"\n\t\tawait client.send_message(message.channel, msg)\n\t\treturn\n\t\t\n\telif message.content.lower().startswith(\"!simulate\"):\n\t\tName = message.content.split()[0:50][1]\n\t\tif Name.lower() in MODEL_PATHS.keys():\n\t\t\tmsg = GenerateMarkov(Name.lower())\n\t\t\tawait client.send_message(message.channel, msg)\n\t\t\treturn\n\t\telse:\n\t\t\tmsg = \"Sorry I don't recognize that person (see !list)\"\n\t\t\tawait client.send_message(message.channel, msg)\n\t\t\treturn\n\t\t\n\telif message.content.lower().startswith(\"i'm\"):\n\t\tif random.randint(0,100)==50:\n\t\t\tmsg = \"Hi {0}, I'm Dad... wait what?\".format(message.content[4:])\n\t\t\tawait client.send_message(message.channel, msg)\n\t\t\treturn\n\t\n\telif message.content.lower().startswith(\"!rngleaguelist\"):\n\t\tmsg = RNGLeagueList()\n\t\tawait client.send_message(message.channel, msg)\n\t\t\n\telif message.content.lower().startswith(\"!rngleague\"):\n\t\tSplitMessage = message.content.split()[0:50]\n\t\tif len(SplitMessage) >= 2 and SplitMessage[1].lower() in MODEL_PATHS.keys() and SplitMessage[1].lower() != \"ubergoon\":\n\t\t\ttry:\n\t\t\t\tif len(SplitMessage) == 2:\n\t\t\t\t\tdice = 1000\n\t\t\t\telse:\n\t\t\t\t\tdice = int(SplitMessage[2])\n\t\t\t\tif dice <= 10000 and dice >= 10:\n\t\t\t\t\tmsg = RNGLeague(message.author.name, SplitMessage[1].lower(), dice)\n\t\t\t\telse:\n\t\t\t\t\tmsg = \"Dice number is not betweeen 10 and 10000\"\n\t\t\texcept ValueError:\n\t\t\t\tmsg = \"Unable to interpret dice number\"\n\t\t\n\t\telse:\n\t\t\tmsg = \"Invalid Challenge. Use !RNGLeague [usr] [Dice 10-10000]\" \n\t\tawait client.send_message(message.channel, msg)\n\t\treturn\n\t\[email protected]\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n\t\n\t\n\t\n\t\n\t\nTOKEN = 'REMOVED FOR GITHUB'\nclient.run(TOKEN)"
},
{
"alpha_fraction": 0.7217742204666138,
"alphanum_fraction": 0.7217742204666138,
"avg_line_length": 22.619047164916992,
"blob_id": "222789e9a8f07d4212764cdff5ca0fec0dc29a7a",
"content_id": "28d46f7c3310de6c5c0443a3bd30a16b3f4a03c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 496,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 21,
"path": "/PyScripts/SplitByPerson.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport numpy as np\n\nRAW_DATA_PATH = \"REMOVED FOR GITHUB\"\n\t\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\t\t\t\t\t\nACTUAL_NAMES = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nActualNamesItr = iter(ACTUAL_NAMES)\nRawData = pd.read_csv(RAW_DATA_PATH)\nRawData.set_index(\"Author\")\n\nfor ExportDataPath in RAW_EXPORT_PATHS:\n\tSinglePerson = RawData.loc[RawData[\"Author\"] == next(ActualNamesItr)]\n\tSinglePerson.to_csv(ExportDataPath)\n\tprint (SinglePerson)\n"
},
{
"alpha_fraction": 0.7041284441947937,
"alphanum_fraction": 0.7087156176567078,
"avg_line_length": 22,
"blob_id": "99ae24f27f55a2989b8b1d77127cd3c874f6c577",
"content_id": "6a6dcbcc9916382514c64805d8360ab5e729d537",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 436,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 19,
"path": "/PyScripts/GenerateMarkov.py",
"repo_name": "Oxymoren/discord-stats-and-bot",
"src_encoding": "UTF-8",
"text": "import markovify as mk\n\nRAW_IMPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nRAW_EXPORT_PATHS = [ \n \"REMOVED FOR GITHUB\",\n\t\"REMOVED FOR GITHUB\"]\n\nExportPathItr = iter(RAW_EXPORT_PATHS)\n\n\nfor FilePath in RAW_IMPORT_PATHS:\n\tInputFile = open(FilePath, encoding='utf8').read()\n\tOutputFile = open(next(ExportPathItr), \"w\")\n\tModel = mk.Text(InputFile, state_size=3)\n\tOutputFile.write(Model.to_json())\n\tOutputFile.close()"
}
] | 10 |
Persistent-Kingdoms/persistent-factions | https://github.com/Persistent-Kingdoms/persistent-factions | 8d2edb01168e0bd9497d18e957bebc7376450abc | 204122d1c6f0b455598fc4e187852c300e3a35ee | d00f4358c00541aa9b8c397d7bed8724bc45263e | refs/heads/master | 2020-08-14T17:31:38.511764 | 2019-11-10T17:27:05 | 2019-11-10T17:27:05 | 215,208,062 | 4 | 9 | null | 2019-10-15T04:40:02 | 2019-11-02T04:05:10 | 2019-11-02T04:05:08 | Lua | [
{
"alpha_fraction": 0.5843843817710876,
"alphanum_fraction": 0.6018018126487732,
"avg_line_length": 32.75,
"blob_id": "fbfaf48c1a6b7ee56a90142913e413710cd19758",
"content_id": "53ff14721bb6b7598e20fd20a8550e56aa634fbf",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 9991,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 296,
"path": "/mods/advmarkers/sscsm.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- Minetest advmarkers SSCSM\n--\n-- Copyright © 2019 by luk3yx\n-- License: https://git.minetest.land/luk3yx/advmarkers/src/branch/master/LICENSE.md\n--\n\nadvmarkers = {}\nlocal data = {}\n\nassert(not sscsm.restrictions or not sscsm.restrictions.chat_messages,\n 'The advmarkers SSCSM needs to be able to send chat messages!')\n\n-- Convert positions to/from strings\nlocal function pos_to_string(pos)\n if type(pos) == 'table' then\n pos = minetest.pos_to_string(vector.round(pos))\n end\n if type(pos) == 'string' then\n return pos\n end\nend\n\nlocal function string_to_pos(pos)\n if type(pos) == 'string' then\n pos = minetest.string_to_pos(pos)\n end\n if type(pos) == 'table' then\n return vector.round(pos)\n end\nend\n\n-- Run remote command\n-- This is easier to do with chatcommands because servers cannot send mod\n-- channel messages to specific clients.\nlocal csm_key = string.char(1) .. 'ADVMARKERS_SSCSM' .. string.char(1)\nlocal function run_remote_command(cmd, param)\n local msg = csm_key\n if cmd then\n msg = msg .. cmd\n if param then msg = msg .. param end\n end\n minetest.run_server_chatcommand('wp', msg)\nend\n\n-- Display a waypoint\nfunction advmarkers.display_waypoint(name)\n name = tostring(name)\n if data['marker-' .. name] then\n run_remote_command('0', tostring(name))\n return true\n else\n return false\n end\nend\n\n-- Get a waypoint\nfunction advmarkers.get_waypoint(name)\n return string_to_pos(data['marker-' .. tostring(name)])\nend\nadvmarkers.get_marker = advmarkers.get_waypoint\n\n-- Delete a waypoint\nfunction advmarkers.delete_waypoint(name)\n name = tostring(name)\n if data['marker-' .. name] ~= nil then\n data['marker-' .. name] = nil\n run_remote_command('D', name)\n end\nend\nadvmarkers.delete_marker = advmarkers.delete_waypoint\n\n-- Set a waypoint\nfunction advmarkers.set_waypoint(pos, name)\n pos = pos_to_string(pos)\n if not pos then return end\n name = tostring(name)\n data['marker-' .. name] = pos\n run_remote_command('S', pos:gsub(' ', '') .. ' ' .. name)\n return true\nend\nadvmarkers.set_marker = advmarkers.set_waypoint\n\n-- Rename a waypoint and re-interpret the position.\nfunction advmarkers.rename_waypoint(oldname, newname)\n oldname, newname = tostring(oldname), tostring(newname)\n local pos = advmarkers.get_waypoint(oldname)\n if not pos or not advmarkers.set_waypoint(pos, newname) then return end\n if oldname ~= newname then\n advmarkers.delete_waypoint(oldname)\n end\n return true\nend\nadvmarkers.rename_marker = advmarkers.rename_waypoint\n\n-- Import waypoints - Note that this won't import strings made by older\n-- versions of the CSM.\nfunction advmarkers.import(s, clear)\n if type(s) ~= 'table' then\n if s:sub(1, 1) ~= 'J' then return end\n s = minetest.decode_base64(s:sub(2))\n local success, msg = pcall(minetest.decompress, s)\n if not success then return end\n s = minetest.parse_json(msg)\n end\n\n -- Iterate over waypoints to preserve existing ones and check for errors.\n if type(s) ~= 'table' then return end\n if clear then data = {} end\n for name, pos in pairs(s) do\n if type(name) == 'string' and type(pos) == 'string' and\n name:sub(1, 7) == 'marker-' and minetest.string_to_pos(pos) and\n data[name] ~= pos then\n -- Prevent collisions\n local c = 0\n while data[name] and c < 50 do\n name = name .. '_'\n c = c + 1\n end\n\n -- Sanity check\n if c < 50 then\n data[name] = pos\n end\n end\n end\nend\n\n-- Get waypoint names\nfunction advmarkers.get_waypoint_names(sorted)\n local res = {}\n for name, pos in pairs(data) do\n if name:sub(1, 7) == 'marker-' then\n table.insert(res, name:sub(8))\n end\n end\n if sorted or sorted == nil then table.sort(res) end\n return res\nend\n\n-- Display the formspec\nlocal formspec_list = {}\nlocal selected_name = false\nfunction advmarkers.display_formspec()\n local formspec = 'size[5.25,8]' ..\n 'label[0,0;Waypoint list ' ..\n minetest.colorize('#888888', '(SSCSM)') .. ']' ..\n 'button_exit[0,7.5;1.3125,0.5;display;Display]' ..\n 'button[1.3125,7.5;1.3125,0.5;teleport;Teleport]' ..\n 'button[2.625,7.5;1.3125,0.5;rename;Rename]' ..\n 'button[3.9375,7.5;1.3125,0.5;delete;Delete]' ..\n 'textlist[0,0.75;5,6;marker;'\n\n -- Iterate over all the markers\n local id = 0\n local selected = 1\n formspec_list = advmarkers.get_waypoint_names()\n for id, name in ipairs(formspec_list) do\n if id > 1 then formspec = formspec .. ',' end\n if not selected_name then selected_name = name end\n if name == selected_name then selected = id end\n formspec = formspec .. '##' .. minetest.formspec_escape(name)\n end\n\n -- Close the text list and display the selected marker position\n formspec = formspec .. ';' .. tostring(selected) .. ']'\n if selected_name then\n local pos = advmarkers.get_marker(selected_name)\n if pos then\n pos = minetest.formspec_escape(tostring(pos.x) .. ', ' ..\n tostring(pos.y) .. ', ' .. tostring(pos.z))\n pos = 'Waypoint position: ' .. pos\n formspec = formspec .. 'label[0,6.75;' .. pos .. ']'\n end\n else\n -- Draw over the buttons\n formspec = formspec .. 'button_exit[0,7.5;5.25,0.5;quit;Close dialog]' ..\n 'label[0,6.75;No waypoints. Add one with \"/add_wp\".]'\n end\n\n -- Display the formspec\n return minetest.show_formspec('advmarkers-sscsm', formspec)\nend\n\n-- Register chatcommands\nlocal mrkr_cmd\nfunction mrkr_cmd(param)\n if param == '' then return advmarkers.display_formspec() end\n if param == '--ssm' then param = '' end\n minetest.run_server_chatcommand('wp', param)\nend\nsscsm.register_chatcommand('mrkr', mrkr_cmd)\nsscsm.register_chatcommand('wp', mrkr_cmd)\nsscsm.register_chatcommand('wps', mrkr_cmd)\nsscsm.register_chatcommand('waypoint', mrkr_cmd)\nsscsm.register_chatcommand('waypoints', mrkr_cmd)\n\nfunction mrkr_cmd(param)\n minetest.run_server_chatcommand('add_wp', param)\n run_remote_command()\nend\n\nsscsm.register_chatcommand('add_wp', mrkr_cmd)\nsscsm.register_chatcommand('add_waypoint', mrkr_cmd)\nsscsm.register_chatcommand('add_mrkr', mrkr_cmd)\n\nmrkr_cmd = nil\n\n-- Set the HUD\nminetest.register_on_formspec_input(function(formname, fields)\n if formname == 'advmarkers-ignore' then\n return true\n elseif formname ~= 'advmarkers-sscsm' then\n return\n end\n local name = false\n if fields.marker then\n local event = minetest.explode_textlist_event(fields.marker)\n if event.index then\n name = formspec_list[event.index]\n end\n else\n name = selected_name\n end\n\n if name then\n if fields.display then\n if not advmarkers.display_waypoint(name) then\n minetest.display_chat_message('Error displaying waypoint!')\n end\n elseif fields.rename then\n minetest.show_formspec('advmarkers-sscsm', 'size[6,3]' ..\n 'label[0.35,0.2;Rename waypoint]' ..\n 'field[0.3,1.3;6,1;new_name;New name;' ..\n minetest.formspec_escape(name) .. ']' ..\n 'button[0,2;3,1;cancel;Cancel]' ..\n 'button[3,2;3,1;rename_confirm;Rename]')\n elseif fields.rename_confirm then\n if fields.new_name and #fields.new_name > 0 then\n if advmarkers.rename_waypoint(name, fields.new_name) then\n selected_name = fields.new_name\n else\n minetest.display_chat_message('Error renaming waypoint!')\n end\n advmarkers.display_formspec()\n else\n minetest.display_chat_message(\n 'Please enter a new name for the waypoint.'\n )\n end\n elseif fields.teleport then\n minetest.show_formspec('advmarkers-sscsm', 'size[6,2.2]' ..\n 'label[0.35,0.25;' .. minetest.formspec_escape(\n 'Teleport to a waypoint\\n - ' .. name\n ) .. ']' ..\n 'button[0,1.25;3,1;cancel;Cancel]' ..\n 'button_exit[3,1.25;3,1;teleport_confirm;Teleport]')\n elseif fields.teleport_confirm then\n -- Teleport with /teleport\n local pos = advmarkers.get_waypoint(name)\n if pos then\n minetest.run_server_chatcommand('teleport',\n pos.x .. ', ' .. pos.y .. ', ' .. pos.z)\n else\n minetest.display_chat_message('Error teleporting to waypoint!')\n end\n elseif fields.delete then\n minetest.show_formspec('advmarkers-sscsm', 'size[6,2]' ..\n 'label[0.35,0.25;Are you sure you want to delete this marker?]' ..\n 'button[0,1;3,1;cancel;Cancel]' ..\n 'button[3,1;3,1;delete_confirm;Delete]')\n elseif fields.delete_confirm then\n advmarkers.delete_waypoint(name)\n selected_name = false\n advmarkers.display_formspec()\n elseif fields.cancel then\n advmarkers.display_formspec()\n elseif name ~= selected_name then\n selected_name = name\n advmarkers.display_formspec()\n end\n elseif fields.display or fields.delete then\n minetest.display_chat_message('Please select a marker.')\n end\n return true\nend)\n\n-- Update the waypoint list\nminetest.register_on_receiving_chat_message(function(message)\n if message:sub(1, #csm_key) == csm_key then\n advmarkers.import(message:sub(#csm_key + 1), true)\n return true\n end\nend)\n\nrun_remote_command()\n"
},
{
"alpha_fraction": 0.6665576696395874,
"alphanum_fraction": 0.668519139289856,
"avg_line_length": 35.404762268066406,
"blob_id": "ee4cf847b0917b3fc804ee61f6c85704dfcca51c",
"content_id": "2cb568a1ad86743760e4ee5d97b2afad5408d2af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 6118,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 168,
"path": "/mods/factions/siege.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "factions.sieges = {}\n\nlocal function format_pos(pos) \n return \"(\" .. pos.x .. \", \" .. pos.y .. \", \" .. pos.z .. \")\"\nend\n\nlocal function siege_banner_onplace_check(player, pointed_thing, attacking_player, attacking_faction, pointedpos, parcelpos, defending_faction) \n if attacking_player == nil then \n minetest.chat_send_player(player:get_player_name(), \"You don't belong to a faction\")\n return false\n end\n\n if not pointed_thing.type == \"node\" then\n minetest.chat_send_player(player:get_player_name(), \"Point a node to place a Siege Banner\")\n return false\n end\n\n if attacking_faction == nil then\n minetest.chat_send_player(player:get_player_name(), \"You don't belong to a faction\")\n return false\n end\n\n if pointedpos.y <= config.protection_max_depth then \n minetest.chat_send_player(player:get_player_name(), \"You can't place a Siege Banner that deep\")\n return false\n end\n\n if pointedpos.y >= config.siege_max_height then\n minetest.chat_send_player(player:get_player_name(), \"You can't place a Siege Banner that high\")\n end\n\n if defending_faction == nil then\n minetest.chat_send_player(player:get_player_name(), \"This parcel doesn't belong to a faction\")\n return false\n end\n\n if defending_faction == attacking_faction then\n minetest.chat_send_player(player:get_player_name(), \"This parcel belongs to your own faction\")\n return false\n end\n\t\n\tif not defending_faction.enemies[attacking_faction.name] then\n\t minetest.chat_send_player(player:get_player_name(), \"You are not at war with \"..defending_faction.name)\n return false\n end\n\n if attacking_faction.power < config.power_per_parcel then\n minetest.chat_send_player(player:get_player_name(), \"Your faction doesn't have enough power to siege\")\n return false\n end\n\n local is_defending_faction_online = false\n\n for i, _player in pairs(minetest.get_connected_players()) do\n local playername = _player:get_player_name()\n\n if factions.get_player_faction(playername) == defending_faction then\n is_defending_faction_online = true\n break\n end\n end\n\n if not is_defending_faction_online then\n minetest.chat_send_player(player:get_player_name(), \"There are no players from the defending faction online\")\n return false\n end\n\n return true\nend\n\nminetest.register_craftitem(\"factions:siege_banner\", {\n description = \"Siege Banner\",\n inventory_image = \"siege_banner.png\",\n stack_max = 1,\n groups = {banner = 1},\n \n on_place = function(itemstack, player, pointed_thing) \n local attacking_player = factions.players[player:get_player_name()]\n local attacking_faction = factions.factions[attacking_player]\n local pointedpos = pointed_thing.above\n local parcelpos = factions.get_parcel_pos(pointedpos)\n local defending_faction = factions.get_parcel_faction(parcelpos)\n\n if not siege_banner_onplace_check(player, pointed_thing, attacking_player, attacking_faction, pointedpos, parcelpos, defending_faction) then\n return nil\n end\n\n minetest.chat_send_player(player:get_player_name(), \"Sieging parcel at \" .. format_pos(pointed_thing.above))\n \n local defending_faction = factions.get_faction_at(pointed_thing.above)\n\n defending_faction:broadcast(player:get_player_name() .. \" is sieging your parcel at \" .. format_pos(pointed_thing.above))\n\n minetest.set_node(pointed_thing.above, {\n name = \"factions:siege_banner_sieging\"\n })\n\n local meta = minetest.get_meta(pointed_thing.above)\n\n\t\tmeta:set_int(\"stage\", 1)\n meta:set_string(\"attacking_faction\", attacking_faction.name)\n meta:set_string(\"defending_faction\", defending_faction.name)\n \n meta:set_string(\"infotext\", \"Siege Banner 1/4 (\" .. attacking_faction.name .. \" vs \" .. defending_faction.name .. \")\")\n\n return \"\" \n end\n})\n\nlocal siege_banner_stages = 4\n\nminetest.register_node(\"factions:siege_banner_sieging\", {\n\tdrawtype = \"normal\",\n\ttiles = {\"siege_banner.png\"},\n\tdescription = \"Siege Banner\",\n\tgroups = {cracky=3},\n\tdiggable = true,\n\tparamtype = \"light\",\n\tparamtype2 = \"facedir\",\n\tdrop = \"\",\n\ton_construct = function(pos)\n\t\tminetest.get_node_timer(pos):start(150)\n\tend,\n\ton_timer = function(pos, elapsed)\n\t\tlocal meta = minetest.get_meta(pos)\n\t\tlocal att_fac_name = meta:get_string(\"attacking_faction\")\n\t\tlocal def_fac_name = meta:get_string(\"defending_faction\")\n\t\tlocal stage = meta:get_int(\"stage\")\n\t\tstage = stage + 1\n\n\t\tif stage <= siege_banner_stages then\n\t\t\tmeta:set_string(\"infotext\", \"Siege Banner \" .. stage .. \"/\" .. siege_banner_stages .. \" (\" .. att_fac_name .. \" vs \" .. def_fac_name .. \")\")\n\t\t\tfactions.get_faction(def_fac_name):broadcast(\"Your parcel at \" .. format_pos(pos) .. \" is being sieged (\" .. stage .. \"/\" .. siege_banner_stages .. \")\")\n\t\t\tmeta:set_int(\"stage\",stage)\n\t\t\tmeta:set_string(\"attacking_faction\", att_fac_name)\n\t\t\tmeta:set_string(\"defending_faction\", def_fac_name)\n\t\t\treturn true\n\t\telse\n\t\t\tlocal attacking_faction = factions.get_faction(att_fac_name)\n\t\t\tlocal defending_faction = factions.get_faction(def_fac_name)\n\t\t\tlocal parcelpos = factions.get_parcel_pos(pos)\n\n\t\t\tif defending_faction then\n\t\t\t\tdefending_faction:bulk_unclaim_parcel(parcelpos)\n\n\t\t\t\tdefending_faction:broadcast(att_fac_name .. \" has successfully conquered your parcel at \" .. format_pos(pos))\n\t\t\tend\n\n\t\t\tif attacking_faction then\n\t\t\t\tattacking_faction:bulk_claim_parcel(parcelpos)\n\n\t\t\t\tattacking_faction:broadcast(\"Successfully conquered parcel at \" .. format_pos(pos) .. \" !\")\n\t\t\tend\n\t\t\tminetest.set_node(pos, { name = \"bones:bones\" })\n\t\tend\n\tend\n})\n\nif minetest.get_modpath(\"default\") and minetest.get_modpath(\"bones\") then\n\tminetest.register_craft({\n\t\toutput = 'factions:siege_banner',\n\t\trecipe = {\n\t\t\t{'default:diamond','default:diamond','default:diamond'},\n\t\t\t{'default:diamond','bones:bones','default:diamond'},\n\t\t\t{'default:diamond','default:diamond','default:diamond'}\n\t\t}\n\t})\nend\n\n\n"
},
{
"alpha_fraction": 0.6643784046173096,
"alphanum_fraction": 0.6716175675392151,
"avg_line_length": 29.237735748291016,
"blob_id": "38a67a7d6019bc81b110864038a808f519b19b27",
"content_id": "9311f40d47ff6c5c0ec0f10fbcc26e0f0903d8d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 8012,
"license_type": "no_license",
"max_line_length": 207,
"num_lines": 265,
"path": "/mods/playertools/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--[[ privileges ]]\nminetest.register_privilege(\"heal\",{description = \"Allows player to set own health with /sethp and /sethealth.\", give_to_singleplayer = false})\nminetest.register_privilege(\"physics\",{description = \"Allows player to set own gravity, jump height and movement speed with /setgravity, /setjump and /setspeed, respectively.\", give_to_singleplayer = false})\nminetest.register_privilege(\"hotbar\",{description = \"Allows player to set the number of slots of the hotbar with /sethotbarsize.\", give_to_singleplayer = false})\n\n--[[ informational commands ]]\nminetest.register_chatcommand(\"whoami\", {\n\tparams = \"\",\n\tdescription = \"Shows your name.\",\n\tprivs = {},\n\tfunc = function(name)\n\t\tminetest.chat_send_player(name, \"Your name is \\\"\"..name..\"\\\".\")\n\tend,\n})\n\nminetest.register_chatcommand(\"crashserver\", {\n\tparams = \"\",\n\tdescription = \"Crashes the server.\",\n\tprivs = {server=true},\n\tfunc = function(name)\n\t\tminetest.log(name .. \" is crashing the server.\")\n\t\tcrash_server_now.boi = name\n\tend,\n})\n\nminetest.register_chatcommand(\"ip\", {\n\tparams = \"\",\n\tdescription = \"Shows your IP address.\",\n\tprivs = {},\n\tfunc = function(name)\n\t\tminetest.chat_send_player(name, \"Your IP address is \\\"\"..minetest.get_player_ip(name)..\"\\\".\")\n\tend\n})\n\n--[[ HUD commands ]]\nminetest.register_chatcommand(\"sethotbarsize\", {\n\tparams = \"<1...23>\",\n\tdescription = \"Sets the size of your hotbar to the provided number of slots. The number must be between 1 and 23.\",\n\tprivs = {hotbar=true},\n\tfunc = function(name, slots)\n\t\tif slots == \"\" then\n\t\t\tminetest.chat_send_player(name, \"You did not specify the parameter.\")\n\t\t\treturn\n\t\tend\n\t\tif type(tonumber(slots)) ~= \"number\" then\n\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\treturn\n\t\tend\n\t\tif tonumber(slots) < 1 or tonumber(slots) > 23 then\n\t\t\tminetest.chat_send_player(name, \"Number of slots out of bounds. The number of slots must be between 1 and 23.\")\n\t\t\treturn\n\t\tend\n\t\tlocal player = minetest.get_player_by_name(name)\n\t\tplayer:hud_set_hotbar_itemcount(tonumber(slots))\n\tend,\n})\n\n--[[ health commands ]]\nminetest.register_chatcommand(\"sethp\", {\n\tparams = \"<hp>\",\n\tdescription = \"Sets your health to <hp> HP (=hearts/2).\",\n\tprivs = {heal=true},\n\tfunc = function(name, hp)\n\t\tif(minetest.setting_getbool(\"enable_damage\")==true) then\n\t\t\tlocal player = minetest.get_player_by_name(name)\n\t\t\tif not player then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif hp == \"\" then\n\t\t\t\tminetest.chat_send_player(name, \"You did not specify the parameter.\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif type(tonumber(hp)) ~= \"number\" then\n\t\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\thp = math.floor(hp+0.5)\t-- round the number\n\t\t\tplayer:set_hp(tonumber(hp))\n\t\telse\n\t\t\tminetest.chat_send_player(name, \"Damage is disabled on this server. This command does not work when damage is disabled.\")\n\t\tend\n\tend,\n})\n\nminetest.register_chatcommand(\"sethealth\", {\n\tparams = \"<hearts>\",\n\tdescription = \"Sets your health to <hearts> hearts.\",\n\tprivs = {heal=true},\n\tfunc = function(name, hearts)\n\t\tif(minetest.setting_getbool(\"enable_damage\")==true) then\n\t\t\tlocal player = minetest.get_player_by_name(name)\n\t\t\tif not player then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif hearts == \"\" then\n\t\t\t\tminetest.chat_send_player(name, \"You did not specify the parameter.\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tif type(tonumber(hearts)) ~= \"number\" then\n\t\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tlocal hp = tonumber(hearts) * 2\n\t\t\thp = math.floor(hp+0.5)\t-- round the number\n\t\t\tplayer:set_hp(hp)\n\t\telse\n\t\t\tminetest.chat_send_player(name, \"Damage is disabled on this server. This command does not work when damage is disabled.\")\n\t\tend\n\tend,\n})\n\n\nminetest.register_chatcommand(\"killme\", {\n\tparams = \"\",\n\tdescription = \"Kills yourself.\",\n\tfunc = function(name, param)\n\t\tif(minetest.setting_getbool(\"enable_damage\")==true) then\n\t\t\tlocal player = minetest.get_player_by_name(name)\n\t\t\tif not player then\n\t\t\t\treturn\n\t\t\tend\n\t\t\tplayer:set_hp(0)\n\t\telse\n\t\t\tminetest.chat_send_player(name, \"Damage is disabled on this server. This command does not work when damage is disabled.\")\n\t\tend\n\tend,\n})\n\n--[[ Player physics commands ]]\n\n-- speed\nminetest.register_chatcommand(\"setspeed\", {\n\tparams = \"[<speed>]\",\n\tdescription = \"Sets your movement speed to <speed> (default: 1).\",\n\tprivs={physics=true},\n\tfunc = function(name, speed)\n\t\tlocal player = minetest.get_player_by_name(name)\n\t\tif not player then\n\t\t\treturn\n\t\tend\n\t\tif speed == \"\" then\n\t\t\tspeed=1\n\t\tend\n\t\tif type(tonumber(speed)) ~= \"number\" then\n\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\treturn\n\t\tend\n\n\t\tplayer:set_physics_override(tonumber(speed), nil, nil)\n\tend,\n})\n\n-- gravity\nminetest.register_chatcommand(\"setgravity\", {\n\tparams = \"[<gravity>]\",\n\tdescription = \"Sets your gravity to [<gravity>] (default: 1).\",\n\tprivs={physics=true},\n\tfunc = function(name, gravity)\n\t\tlocal player = minetest.get_player_by_name(name)\n\t\tif not player then\n\t\t\treturn\n\t\tend\n\t\tif gravity == \"\" then\n\t\t\tgravity=1\n\t\tend\n\t\tif type(tonumber(gravity)) ~= \"number\" then\n\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\treturn\n\t\tend\n\t\tplayer:set_physics_override(nil, tonumber(gravity), nil)\n\tend,\n})\n\n-- jump height\nminetest.register_chatcommand(\"setjump\", {\n\tparams = \"[<jump height>]\",\n\tdescription = \"Sets your jump height to [<jump height>] (default: 1).\",\n\tprivs = {physics=true},\n\tfunc = function(name, jump_height)\n\t\tlocal player = minetest.get_player_by_name(name)\n\t\tif not player then\n\t\t\treturn\n\t\tend\n\t\tif jump_height == \"\" then\n\t\t\tjump_height=1\n\t\tend\n\t\tif type(tonumber(jump_height)) ~= \"number\" then\n\t\t\tminetest.chat_send_player(name, \"This is not a number.\")\n\t\t\treturn\n\t\tend\n\t\tplayer:set_physics_override(nil, nil, jump_height)\n\tend,\n})\n\nminetest.register_chatcommand(\"pulverizeall\", {\n\tparams = \"\",\n\tdescription = \"Destroys all items in your player inventory and crafting grid.\",\n\tfunc = function(name, param)\n\t\tlocal player = minetest.get_player_by_name(name)\n\t\tif not player then\n\t\t\treturn\n\t\tend\n\t\tlocal inv = player:get_inventory()\n\t\tinv:set_list(\"main\", {})\n\t\tinv:set_list(\"craft\", {})\n\tend,\n})\n\nminetest.register_chatcommand(\"grief_check\", {\n\tparams = \"[<range>] [<hours>] [<limit>]\",\n\tdescription = \"Check who last touched a node or a node near it\"\n\t\t\t.. \" within the time specified by <hours>. Default: range = 0,\"\n\t\t\t.. \" hours = 24 = 1d, limit = 5\",\n\tprivs = {interact=true},\n\tfunc = function(name, param)\n\t\tif not minetest.setting_getbool(\"enable_rollback_recording\") then\n\t\t\treturn false, \"Rollback functions are disabled.\"\n\t\tend\n\t\tlocal range, hours, limit =\n\t\t\tparam:match(\"(%d+) *(%d*) *(%d*)\")\n\t\trange = tonumber(range) or 0\n\t\thours = tonumber(hours) or 24\n\t\tlimit = tonumber(limit) or 5\n\t\tif range > 10 then\n\t\t\treturn false, \"That range is too high! (max 10)\"\n\t\tend\n\t\tif hours > 168 then\n\t\t\treturn false, \"That time limit is too high! (max 168: 7 days)\"\n\t\tend\n\t\tif limit > 100 then\n\t\t\treturn false, \"That limit is too high! (max 100)\"\n\t\tend\n\t\tlocal seconds = (hours*60)*60\n\t\tminetest.rollback_punch_callbacks[name] = function(pos, node, puncher)\n\t\t\tlocal name = puncher:get_player_name()\n\t\t\tminetest.chat_send_player(name, \"Checking \" .. minetest.pos_to_string(pos) .. \"...\")\n\t\t\tlocal actions = minetest.rollback_get_node_actions(pos, range, seconds, limit)\t\t\t\n\t\t\tif not actions then\n\t\t\t\tminetest.chat_send_player(name, \"Rollback functions are disabled\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tlocal num_actions = #actions\n\t\t\tif num_actions == 0 then\n\t\t\t\tminetest.chat_send_player(name, \"Nobody has touched\"\n\t\t\t\t\t\t.. \" the specified location in \" .. hours .. \" hour(s)\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tlocal time = os.time()\n\t\t\tfor i = num_actions, 1, -1 do\n\t\t\t\tlocal action = actions[i]\n\t\t\t\tminetest.chat_send_player(name,\n\t\t\t\t\t(\"%s %s %s -> %s %d seconds ago.\")\n\t\t\t\t\t\t:format(\n\t\t\t\t\t\t\tminetest.pos_to_string(action.pos),\n\t\t\t\t\t\t\taction.actor,\n\t\t\t\t\t\t\taction.oldnode.name,\n\t\t\t\t\t\t\taction.newnode.name,\n\t\t\t\t\t\t\ttime - action.time))\n\t\t\tend\n\t\tend\n\n\t\treturn true, \"Punch a node (range=\" .. range .. \", hours=\"\n\t\t\t\t.. hours .. \"s, limit=\" .. limit .. \")\"\n\tend,\n})"
},
{
"alpha_fraction": 0.5399201512336731,
"alphanum_fraction": 0.5743513107299805,
"avg_line_length": 29.830768585205078,
"blob_id": "96696446f1314989b2ffd4ad8873f6e39010efbb",
"content_id": "3231ec19232117273a7392344184390ab2611373",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4008,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 130,
"path": "/mods/factions/nodes.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "function factions.get_chest_formspec(pos)\n local spos = pos.x..\",\"..pos.y..\",\"..pos.z\n return \"size[8,9]\" ..\n default.gui_bg ..\n default.gui_bg_img ..\n default.gui_slots ..\n \"list[nodemeta:\"..spos..\";main;0,0.3;8,4;]\" ..\n \"list[current_player;main;0,4.85;8,1;]\"..\n \"list[current_player;main;0,6.08;8,3;8]\"..\n \"listring[nodemeta:\"..spos..\";main]\"..\n \"listring[current_player;main]\"..\n default.get_hotbar_bg(0, 4.85)\nend\n\nfunction factions.can_use_chest(pos, player)\n if not player then\n return false\n end\n local parcel_faction = factions.get_faction_at(pos)\n local player_faction = factions.get_player_faction(player)\n if not parcel_faction then\n return true\n end\n return player_faction and (parcel_faction.name == player_faction.name)\nend\n--[[\nminetest.register_node(\"factions:chest\", {\n tiles = {\"factions_chest_top.png\", \"factions_chest_top.png\",\n \"factions_chest_side.png\", \"factions_chest_side.png\",\n \"factions_chest_side.png\", \"factions_chest_front.png\"},\n groups = {choppy = 2},\n description = \"Faction chest\",\n paramtype2 = \"facedir\",\n on_construct = function(pos)\n local meta = minetest.get_meta(pos)\n meta:get_inventory():set_size(\"main\", 8*4)\n meta:mark_as_private(\"main\")\n end,\n allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player)\n if factions.can_use_chest(pos, player:get_player_name()) then\n return count\n else\n return 0\n end\n end,\n allow_metadata_inventory_put = function(pos, listname, index, stack, player)\n if factions.can_use_chest(pos, player:get_player_name()) then\n return stack:get_count()\n else\n return 0\n end\n end,\n allow_metadata_inventory_take = function(pos, listname, index, stack, player)\n if factions.can_use_chest(pos, player:get_player_name()) then\n return stack:get_count()\n else\n return 0\n end\n end,\n on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)\n if factions.can_use_chest(pos, clicker:get_player_name()) then\n minetest.show_formspec(clicker:get_player_name(), \"factions:chest\", factions.get_chest_formspec(pos))\n end\n return itemstack\n end\n on_punch = function(pos)\n local meta = minetest.get_meta(pos)\n meta:mark_as_private(\"main\")\n end\n})\n\nminetest.register_craft({\n output = \"factions:chest\",\n type = \"shapeless\",\n recipe = {\"default:chest_locked\", \"default:steel_ingot\"}\n})\n--]]\n\n-- Code below was copied from TenPlus1's protector mod(MIT) and changed up a bit.\n\nlocal x = math.floor(32. / 2.1)\n\nminetest.register_node(\"factions:display_node\", {\n\ttiles = {\"factions_display.png\"},\n\tuse_texture_alpha = true,\n\twalkable = false,\n\tdrawtype = \"nodebox\",\n\tnode_box = {\n\t\ttype = \"fixed\",\n\t\tfixed = {\n\t\t\t-- sides\n\t\t\t{-(x+.55), -(x+.55), -(x+.55), -(x+.45), (x+.55), (x+.55)},\n\t\t\t{-(x+.55), -(x+.55), (x+.45), (x+.55), (x+.55), (x+.55)},\n\t\t\t{(x+.45), -(x+.55), -(x+.55), (x+.55), (x+.55), (x+.55)},\n\t\t\t{-(x+.55), -(x+.55), -(x+.55), (x+.55), (x+.55), -(x+.45)},\n\t\t\t-- top\n\t\t\t{-(x+.55), (x+.45), -(x+.55), (x+.55), (x+.55), (x+.55)},\n\t\t\t-- bottom\n\t\t\t{-(x+.55), -(x+.55), -(x+.55), (x+.55), -(x+.45), (x+.55)},\n\t\t\t-- middle (surround parcel)\n\t\t\t{-.55,-.55,-.55, .55,.55,.55},\n\t\t},\n\t},\n\tselection_box = {\n\t\ttype = \"regular\",\n\t},\n\tparamtype = \"light\",\n\tgroups = {dig_immediate = 3, not_in_creative_inventory = 1},\n\tdrop = \"\",\n})\n\nminetest.register_entity(\"factions:display\", {\n\tphysical = false,\n\tcollisionbox = {0, 0, 0, 0, 0, 0},\n\tvisual = \"wielditem\",\n\tvisual_size = {x = 1.0 / 1.5, y = 1.0 / 1.5},\n\ttextures = {\"factions:display_node\"},\n\ttimer = 0,\n\n\ton_step = function(self, dtime)\n\n\t\tself.timer = self.timer + dtime\n\n\t\tif self.timer > 6 then\n\t\t\tself.object:remove()\n\t\tend\n\tend,\n})\n\n-- End\n"
},
{
"alpha_fraction": 0.6896345019340515,
"alphanum_fraction": 0.6980227828025818,
"avg_line_length": 28.803571701049805,
"blob_id": "26420363ad36158226ed89a10021235722eab5c7",
"content_id": "6bccf84b52c11cb34bfc14a27e2ce503dde3f783",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1669,
"license_type": "permissive",
"max_line_length": 175,
"num_lines": 56,
"path": "/mods/bedrock2/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-- Boilerplate to support localized strings if intllib mod is installed.\nlocal S\nif minetest.get_modpath(\"intllib\") then\n\tS = intllib.Getter()\nelse\n\tS = function(s) return s end\nend\n\nlocal bedrock = {}\n\nbedrock.layer = -2000 -- determined as appropriate by experiment\nbedrock.node = {name = \"bedrock2:bedrock\"}\n\nlocal depth = tonumber(minetest.setting_get(\"bedrock2_y\"))\nif depth ~= nil then\n\tbedrock.layer = depth\nend\n\nminetest.register_on_generated(function(minp, maxp)\n\tif maxp.y >= bedrock.layer and minp.y <= bedrock.layer then\n\t\tlocal vm, emin, emax = minetest.get_mapgen_object(\"voxelmanip\")\n\t\tlocal data = vm:get_data()\n\t\tlocal area = VoxelArea:new({MinEdge=emin, MaxEdge=emax})\n\t\tlocal c_bedrock = minetest.get_content_id(\"bedrock2:bedrock\")\n\n\t\tfor x = minp.x, maxp.x do\n\t\t\tfor z = minp.z, maxp.z do\n\t\t\t\tlocal p_pos = area:index(x, bedrock.layer, z)\n\t\t\t\tdata[p_pos] = c_bedrock\n\t\t\tend\n\t\tend\n\n\t\tvm:set_data(data)\n\t\tvm:calc_lighting()\n\t\tvm:update_liquids()\n\t\tvm:write_to_map()\n\tend\nend)\n\nminetest.register_node(\"bedrock2:bedrock\", {\n\tdescription = S(\"Bedrock\"),\n\t_doc_items_longdesc = S(\"Bedrock is a very hard block. It cannot be mined, altered, destroyed or moved by any means. It appears at the bottom of the world in a flat layer.\"),\n\ttiles = {\"bedrock2_bedrock.png\"},\n\tgroups = {immortal=1, not_in_creative_inventory=1, },\n\tsounds = { footstep = { name = \"bedrock2_step\", gain = 1 } },\n\tis_ground_content = false,\n\ton_blast = function() end,\n\ton_destruct = function () end,\n\tcan_dig = function() return false end,\n\tdiggable = false,\n\tdrop = \"\",\n})\n\nif minetest.get_modpath(\"mesecons_mvps\") ~= nil then\n\tmesecon.register_mvps_stopper(\"bedrock2:bedrock\")\nend\n"
},
{
"alpha_fraction": 0.5508948564529419,
"alphanum_fraction": 0.5741610527038574,
"avg_line_length": 27.562299728393555,
"blob_id": "4cd504ad96db369ccef85bd861d4e93d38927aa6",
"content_id": "185069689876a40bcb234a149e720dbfd1b76f35",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 8940,
"license_type": "permissive",
"max_line_length": 123,
"num_lines": 313,
"path": "/mods/signs/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-- Font: 04.jp.org\n\n-- load characters map\nlocal chars_file = io.open(minetest.get_modpath(\"signs\")..\"/characters\", \"r\")\nlocal charmap = {}\nlocal max_chars = 16\nif not chars_file then\n print(\"[signs] E: character map file not found\")\nelse\n while true do\n local char = chars_file:read(\"*l\")\n if char == nil then\n break\n end\n local img = chars_file:read(\"*l\")\n chars_file:read(\"*l\")\n charmap[char] = img\n end\nend\n\nlocal signs = {\n {delta = {x = 0, y = 0, z = 0.399}, yaw = 0},\n {delta = {x = 0.399, y = 0, z = 0}, yaw = math.pi / -2},\n {delta = {x = 0, y = 0, z = -0.399}, yaw = math.pi},\n {delta = {x = -0.399, y = 0, z = 0}, yaw = math.pi / 2},\n}\n\nlocal signs_yard = {\n {delta = {x = 0, y = 0, z = -0.05}, yaw = 0},\n {delta = {x = -0.05, y = 0, z = 0}, yaw = math.pi / -2},\n {delta = {x = 0, y = 0, z = 0.05}, yaw = math.pi},\n {delta = {x = 0.05, y = 0, z = 0}, yaw = math.pi / 2},\n}\n\nlocal sign_groups = {choppy=2, dig_immediate=2}\n\nlocal construct_sign = function(pos)\n local meta = minetest.env:get_meta(pos)\n\tmeta:set_string(\"formspec\", \"field[text;;${text}]\")\n\tmeta:set_string(\"infotext\", \"\")\nend\n\nlocal destruct_sign = function(pos)\n local objects = minetest.env:get_objects_inside_radius(pos, 0.5)\n for _, v in ipairs(objects) do\n if v:get_entity_name() == \"signs:text\" then\n v:remove()\n end\n end\nend\n\nlocal update_sign = function(pos, fields)\n local meta = minetest.env:get_meta(pos)\n\tmeta:set_string(\"infotext\", \"\")\n\tif fields then\n\t\tmeta:set_string(\"text\", fields.text)\n\tend\n local text = meta:get_string(\"text\")\n local objects = minetest.env:get_objects_inside_radius(pos, 0.5)\n for _, v in ipairs(objects) do\n if v:get_entity_name() == \"signs:text\" then\n v:set_properties({textures={generate_texture(create_lines(text))}})\n\t\t\treturn\n end\n end\n\t\n\t-- if there is no entity\n\tlocal sign_info\n\tif minetest.env:get_node(pos).name == \"signs:sign_yard\" then\n\t\tsign_info = signs_yard[minetest.env:get_node(pos).param2 + 1]\n\telseif minetest.env:get_node(pos).name == \"default:sign_wall_wood\" then\n\t\tsign_info = signs[minetest.env:get_node(pos).param2 + 1]\n\tend\n\tif sign_info == nil then\n\t\treturn\n\tend\n\tlocal text = minetest.env:add_entity({x = pos.x + sign_info.delta.x,\n\t\t\t\t\t\t\t\t\t\ty = pos.y + sign_info.delta.y,\n\t\t\t\t\t\t\t\t\t\tz = pos.z + sign_info.delta.z}, \"signs:text\")\n\ttext:setyaw(sign_info.yaw)\nend\n\nminetest.register_node(\":default:sign_wall_wood\", {\n description = \"Sign\",\n inventory_image = \"signs_inv.png\",\n wield_image = \"signs_inv.png\",\n node_placement_prediction = \"\",\n paramtype = \"light\",\n\tsunlight_propagates = true,\n paramtype2 = \"facedir\",\n drawtype = \"nodebox\",\n node_box = {type = \"fixed\", fixed = {-0.45, -0.15, 0.4, 0.45, 0.45, 0.498}},\n selection_box = {type = \"fixed\", fixed = {-0.45, -0.15, 0.4, 0.45, 0.45, 0.498}},\n tiles = {\"signs_top.png\", \"signs_bottom.png\", \"signs_side.png\", \"signs_side.png\", \"signs_back.png\", \"signs_front.png\"},\n groups = sign_groups,\n\n on_place = function(itemstack, placer, pointed_thing)\n local above = pointed_thing.above\n local under = pointed_thing.under\n\t\t\t\n\tpname = placer:get_player_name()\n\tif minetest.is_protected(above, pname) then\n\t\tminetest.record_protection_violation(above, pname)\n\t\treturn itemstack\n\tend\n\t\t\t\n local dir = {x = under.x - above.x,\n y = under.y - above.y,\n z = under.z - above.z}\n\n local wdir = minetest.dir_to_wallmounted(dir)\n\n local placer_pos = placer:getpos()\n if placer_pos then\n dir = {\n x = above.x - placer_pos.x,\n y = above.y - placer_pos.y,\n z = above.z - placer_pos.z\n }\n end\n\n local fdir = minetest.dir_to_facedir(dir)\n\n local sign_info\n\t\t\n\t\tif minetest.env:get_node(above).name == \"air\" then\n\t\t\n if wdir == 0 then\n --how would you add sign to ceiling?\n minetest.env:add_item(above, \"default:sign_wall_wood\")\n\t\t\titemstack:take_item()\n\t\t\treturn itemstack\n elseif wdir == 1 then\n minetest.env:add_node(above, {name = \"signs:sign_yard\", param2 = fdir})\n sign_info = signs_yard[fdir + 1]\n else\n minetest.env:add_node(above, {name = \"default:sign_wall_wood\", param2 = fdir})\n sign_info = signs[fdir + 1]\n end\n\n local text = minetest.env:add_entity({x = above.x + sign_info.delta.x,\n y = above.y + sign_info.delta.y,\n z = above.z + sign_info.delta.z}, \"signs:text\")\n text:setyaw(sign_info.yaw)\n\n\t\titemstack:take_item()\n return itemstack\n\t\tend\n end,\n on_construct = function(pos)\n construct_sign(pos)\n end,\n on_destruct = function(pos)\n destruct_sign(pos)\n end,\n on_receive_fields = function(pos, formname, fields, sender)\n update_sign(pos, fields)\n end,\n\ton_punch = function(pos, node, puncher)\n\t\tupdate_sign(pos)\n\tend,\n})\n\nminetest.register_node(\"signs:sign_yard\", {\n paramtype = \"light\",\n\tsunlight_propagates = true,\n paramtype2 = \"facedir\",\n drawtype = \"nodebox\",\n node_box = {type = \"fixed\", fixed = {\n {-0.45, -0.15, -0.049, 0.45, 0.45, 0.049},\n {-0.05, -0.5, -0.049, 0.05, -0.15, 0.049}\n }},\n selection_box = {type = \"fixed\", fixed = {-0.45, -0.15, -0.049, 0.45, 0.45, 0.049}},\n tiles = {\"signs_top.png\", \"signs_bottom.png\", \"signs_side.png\", \"signs_side.png\", \"signs_back.png\", \"signs_front.png\"},\n groups = {choppy=2, dig_immediate=2},\n drop = \"default:sign_wall_wood\",\n\n on_construct = function(pos)\n construct_sign(pos)\n end,\n on_destruct = function(pos)\n destruct_sign(pos)\n end,\n on_receive_fields = function(pos, formname, fields, sender)\n update_sign(pos, fields)\n end,\n\ton_punch = function(pos, node, puncher)\n\t\tupdate_sign(pos)\n\tend,\n})\n\nminetest.register_entity(\"signs:text\", {\n collisionbox = { 0, 0, 0, 0, 0, 0 },\n visual = \"upright_sprite\",\n textures = {},\n\n on_activate = function(self)\n local meta = minetest.env:get_meta(self.object:getpos())\n local text = meta:get_string(\"text\")\n self.object:set_properties({textures={generate_texture(create_lines(text))}})\n end\n})\n\n-- CONSTANTS\nlocal SIGN_WITH = 110\nlocal SIGN_PADDING = 8\n\nlocal LINE_LENGTH = 16\nlocal NUMBER_OF_LINES = 4\n\nlocal LINE_HEIGHT = 14\nlocal CHAR_WIDTH = 5\n\nstring_to_array = function(str)\n\tlocal tab = {}\n\tfor i=1,string.len(str) do\n\t\ttable.insert(tab, string.sub(str, i,i))\n\tend\n\treturn tab\nend\n\nstring_to_word_array = function(str)\n\tlocal tab = {}\n\tlocal current = 1\n\ttab[1] = \"\"\n\tfor _,char in ipairs(string_to_array(str)) do\n\t\tif char ~= \" \" then\n\t\t\ttab[current] = tab[current]..char\n\t\telse\n\t\t\tcurrent = current+1\n\t\t\ttab[current] = \"\"\n\t\tend\n\tend\n\treturn tab\nend\n\ncreate_lines = function(text)\n\tlocal line = \"\"\n\tlocal line_num = 1\n\tlocal tab = {}\n\tfor _,word in ipairs(string_to_word_array(text)) do\n\t\tif string.len(line)+string.len(word) < LINE_LENGTH and word ~= \"|\" then\n\t\t\tif line ~= \"\" then\n\t\t\t\tline = line..\" \"..word\n\t\t\telse\n\t\t\t\tline = word\n\t\t\tend\n\t\telse\n\t\t\ttable.insert(tab, line)\n\t\t\tif word ~= \"|\" then\n\t\t\t\tline = word\n\t\t\telse\n\t\t\t\tline = \"\"\n\t\t\tend\n\t\t\tline_num = line_num+1\n\t\t\tif line_num > NUMBER_OF_LINES then\n\t\t\t\treturn tab\n\t\t\tend\n\t\tend\n\tend\n\ttable.insert(tab, line)\n\treturn tab\nend\n\ngenerate_texture = function(lines)\n local texture = \"[combine:\"..SIGN_WITH..\"x\"..SIGN_WITH\n local ypos = 12\n for i = 1, #lines do\n texture = texture..generate_line(lines[i], ypos)\n ypos = ypos + LINE_HEIGHT\n end\n return texture\nend\n\ngenerate_line = function(s, ypos)\n local i = 1\n local parsed = {}\n local width = 0\n local chars = 0\n while chars < max_chars and i <= #s do\n local file = nil\n if charmap[s:sub(i, i)] ~= nil then\n file = charmap[s:sub(i, i)]\n i = i + 1\n elseif i < #s and charmap[s:sub(i, i + 1)] ~= nil then\n file = charmap[s:sub(i, i + 1)]\n i = i + 2\n else\n print(\"[signs] W: unknown symbol in '\"..s..\"' at \"..i..\" (probably \"..s:sub(i, i)..\")\")\n i = i + 1\n end\n if file ~= nil then\n width = width + CHAR_WIDTH\n table.insert(parsed, file)\n chars = chars + 1\n end\n end\n width = width - 1\n\n local texture = \"\"\n local xpos = math.floor((SIGN_WITH - 2 * SIGN_PADDING - width) / 2 + SIGN_PADDING)\n for i = 1, #parsed do\n texture = texture..\":\"..xpos..\",\"..ypos..\"=\"..parsed[i]..\".png\"\n xpos = xpos + CHAR_WIDTH + 1\n end\n return texture\nend\nmodpath=minetest.get_modpath(\"signs\")\n\ndofile(modpath..\"/steelsign.lua\")\nif minetest.setting_get(\"log_mods\") then\n\tminetest.log(\"action\", \"signs loaded\")\nend\n"
},
{
"alpha_fraction": 0.6513513326644897,
"alphanum_fraction": 0.6594594717025757,
"avg_line_length": 51.92856979370117,
"blob_id": "d69915a554736bdedfdf65152c09860efc6f8942",
"content_id": "22bcec89a8b38f5d8c5f5d397f6c2d69271b2484",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 740,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 14,
"path": "/mods/give_initial_stuff/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "minetest.register_on_newplayer(function(player)\n\t--print(\"on_newplayer\")\n\tif minetest.setting_getbool(\"give_initial_stuff\") then\n\t\tminetest.log(\"action\", \"Giving initial stuff to player \"..player:get_player_name())\n player:get_inventory():add_item('main', 'default:pick_stone')\n\t\t\tplayer:get_inventory():add_item('main', 'xdecor:crafting_guide')\n player:get_inventory():add_item('main', 'default:torch')\n player:get_inventory():add_item('main', 'farming:bread 6')\n player:get_inventory():add_item('main', 'default:sapling 4')\n player:get_inventory():add_item('main', 'default:papyrus 8')\n\t\t\tplayer:get_inventory():add_item('main', 'wiki:wiki')\n\t\t\tplayer:setpos({x=0,y=0,z=0})\n\tend\nend)"
},
{
"alpha_fraction": 0.7648953199386597,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 34.82692337036133,
"blob_id": "d9f40cc8db9a8960edf4b52d14b205e435c639d7",
"content_id": "6062c7f611c8b255f7671967bce882136480547c",
"detected_licenses": [
"WTFPL",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1863,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 52,
"path": "/mods/tnt/sprint/README.md",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "Sprint Mod For Minetest by GunshipPenguin \n\nAllows the player to sprint by double tapping w. By default, \nsprinting will make the player travel 50% faster and allow him/her \nto jump 10% higher.\n \nLicence: WTFPL (see LICENCE file)\n\n\n---\n\nThis mod can be configured by changing the variables declared in \nthe start of init.lua. The following is a brief explanation of each \none.\n \nSPRINT_SPEED (default 1.5)\n \nHow fast the player will move when sprinting as opposed to normal \nmovement speed. 1.0 represents normal speed so 1.5 would mean that a \nsprinting player would travel 50% faster than a walking player and \n2.4 would mean that a sprinting player would travel 140% faster than \na walking player.\n\nSPRINT_JUMP (default 1.1)\n\nHow high the player will jump when sprinting as opposed to normal \njump height. Same as SPRINT_SPEED, just controls jump height while \nsprinting rather than speed.\n\nSPRINT_STAMINA (default 20)\n\nHow long the player can sprint for in seconds. Each player has a \nstamina variable assigned to them, it is initially set to \nSPRINT_STAMINA and can go no higher. When the player is sprinting, \nthis variable ticks down once each second, and when it reaches 0, \nthe player stops sprinting and may be sent a warning depending on \nthe value of SPRINT_WARN. It ticks back up when the player isn't \nsprinting and stops at SPRINT_STAMINA. Set this to a huge value if \nyou want unlimited sprinting.\n\nSPRINT_TIMEOUT (default 0.5)\n\nHow much time the player has after releasing w, to press w again and \nstart sprinting. Setting this too high will result in unwanted \nsprinting and setting it too low will result in it being \ndifficult/impossible to sprint.\n\nSPRINT_WARN (default true)\n\nIf the player should be warned that his/her stamina has run out via \nthe in game chat system. You may want to set this to false if the \nnotifications get annoying.\n"
},
{
"alpha_fraction": 0.5774000287055969,
"alphanum_fraction": 0.5886251926422119,
"avg_line_length": 31.994709014892578,
"blob_id": "3aa9a9ffb079b64b0f1e11f577dc6cbdd9a0544c",
"content_id": "d85c7eeff9f05e9ad84ac8e0d2c7ba9d30ff37eb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 18709,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 567,
"path": "/mods/advmarkers/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- Minetest advmarkers mod\n--\n-- © 2019 by luk3yx\n--\n\nadvmarkers = {\n dated_death_markers = false\n}\n\n-- Get the mod storage\nlocal storage = minetest.get_mod_storage()\nlocal hud = {}\nadvmarkers.last_coords = {}\n\n-- Convert positions to/from strings\nlocal function pos_to_string(pos)\n if type(pos) == 'table' then\n pos = minetest.pos_to_string(vector.round(pos))\n end\n if type(pos) == 'string' then\n return pos\n end\nend\n\nlocal function string_to_pos(pos)\n if type(pos) == 'string' then\n pos = minetest.string_to_pos(pos)\n end\n if type(pos) == 'table' then\n return vector.round(pos)\n end\nend\n\n-- Get player name or object\nlocal get_player_by_name = minetest.get_player_by_name\nlocal get_connected_players = minetest.get_connected_players\nif minetest.get_modpath('cloaking') then\n get_player_by_name = cloaking.get_player_by_name\n get_connected_players = cloaking.get_connected_players\nend\n\nlocal function get_player(player, t)\n local name\n if type(player) == 'string' then\n name = player\n if t ~= 0 then\n player = get_player_by_name(name)\n end\n else\n name = player:get_player_name()\n end\n if t == 0 then\n return name\n elseif t == 1 then\n return player\n end\n return name, player\nend\n\n-- Set the HUD position\nfunction advmarkers.set_hud_pos(player, pos, title)\n local name, player = get_player(player)\n pos = string_to_pos(pos)\n if not player or not pos then return end\n if not title then\n title = pos.x .. ', ' .. pos.y .. ', ' .. pos.z\n end\n if hud[player] then\n player:hud_change(hud[player], 'name', title)\n player:hud_change(hud[player], 'world_pos', pos)\n else\n hud[player] = player:hud_add({\n hud_elem_type = 'waypoint',\n name = title,\n text = 'm',\n number = 0xbf360c,\n world_pos = pos\n })\n end\n minetest.chat_send_player(name, 'Waypoint set to ' .. title)\n return true\nend\n\n-- Get and save player storage\nlocal function get_storage(name)\n name = get_player(name, 0)\n return minetest.deserialize(storage:get_string(name)) or {}\nend\n\nlocal function save_storage(name, data)\n name = get_player(name, 0)\n if type(data) == 'table' then\n data = minetest.serialize(data)\n end\n if type(data) ~= 'string' then return end\n if #data > 0 then\n storage:set_string(name, data)\n else\n storage:set_string(name, '')\n end\n return true\nend\n\n-- Add a waypoint\nfunction advmarkers.set_waypoint(player, pos, name)\n pos = pos_to_string(pos)\n if not pos then return end\n local data = get_storage(player)\n data['marker-' .. tostring(name)] = pos\n return save_storage(player, data)\nend\nadvmarkers.set_marker = advmarkers.set_waypoint\n\n-- Delete a waypoint\nfunction advmarkers.delete_waypoint(player, name)\n local data = get_storage(player)\n data['marker-' .. tostring(name)] = nil\n return save_storage(player, data)\nend\nadvmarkers.delete_marker = advmarkers.delete_waypoint\n\n-- Get a waypoint\nfunction advmarkers.get_waypoint(player, name)\n local data = get_storage(player)\n return string_to_pos(data['marker-' .. tostring(name)])\nend\nadvmarkers.get_marker = advmarkers.get_waypoint\n\n-- Rename a waypoint and re-interpret the position.\nfunction advmarkers.rename_waypoint(player, oldname, newname)\n player = get_player(player, 0)\n oldname, newname = tostring(oldname), tostring(newname)\n local pos = advmarkers.get_waypoint(player, oldname)\n if not pos or not advmarkers.set_waypoint(player, pos, newname) then\n return\n end\n if oldname ~= newname then\n advmarkers.delete_waypoint(player, oldname)\n end\n return true\nend\nadvmarkers.rename_marker = advmarkers.rename_waypoint\n\n-- Get waypoint names\nfunction advmarkers.get_waypoint_names(name, sorted)\n local data = get_storage(name)\n local res = {}\n for name, pos in pairs(data) do\n if name:sub(1, 7) == 'marker-' then\n table.insert(res, name:sub(8))\n end\n end\n if sorted or sorted == nil then table.sort(res) end\n return res\nend\nadvmarkers.get_marker_names = advmarkers.get_waypoint_names\n\n-- Display a waypoint\nfunction advmarkers.display_waypoint(player, name)\n return advmarkers.set_hud_pos(player, advmarkers.get_waypoint(player, name),\n name)\nend\nadvmarkers.display_marker = advmarkers.display_waypoint\n\n-- Export waypoints\nfunction advmarkers.export(player, raw)\n local s = get_storage(player)\n if raw == 'M' then\n s = minetest.compress(minetest.serialize(s))\n s = 'M' .. minetest.encode_base64(s)\n elseif not raw then\n s = minetest.compress(minetest.write_json(s))\n s = 'J' .. minetest.encode_base64(s)\n end\n return s\nend\n\n-- Import waypoints - Note that this won't import strings made by older\n-- versions of the CSM.\nfunction advmarkers.import(player, s)\n if type(s) ~= 'table' then\n if s:sub(1, 1) ~= 'J' then return end\n s = minetest.decode_base64(s:sub(2))\n local success, msg = pcall(minetest.decompress, s)\n if not success then return end\n s = minetest.parse_json(msg)\n end\n\n -- Iterate over waypoints to preserve existing ones and check for errors.\n if type(s) == 'table' then\n local data = get_storage(player)\n for name, pos in pairs(s) do\n if type(name) == 'string' and type(pos) == 'string' and\n name:sub(1, 7) == 'marker-' and minetest.string_to_pos(pos) and\n data[name] ~= pos then\n -- Prevent collisions\n local c = 0\n while data[name] and c < 50 do\n name = name .. '_'\n c = c + 1\n end\n\n -- Sanity check\n if c < 50 then\n data[name] = pos\n end\n end\n end\n return save_storage(player, data)\n end\nend\n\n-- Get the waypoints formspec\nlocal formspec_list = {}\nlocal selected_name = {}\nfunction advmarkers.display_formspec(player)\n player = get_player(player, 0)\n if not get_player_by_name(player) then return end\n local formspec = 'size[5.25,8]' ..\n 'label[0,0;Waypoint list]' ..\n 'button_exit[0,7.5;1.3125,0.5;display;Display]' ..\n 'button[1.3125,7.5;1.3125,0.5;teleport;Teleport]' ..\n 'button[2.625,7.5;1.3125,0.5;rename;Rename]' ..\n 'button[3.9375,7.5;1.3125,0.5;delete;Delete]' ..\n 'textlist[0,0.75;5,6;marker;'\n\n -- Iterate over all the waypoints\n local selected = 1\n formspec_list[player] = advmarkers.get_waypoint_names(player)\n\n for id, name in ipairs(formspec_list[player]) do\n if id > 1 then formspec = formspec .. ',' end\n if not selected_name[player] then selected_name[player] = name end\n if name == selected_name[player] then selected = id end\n formspec = formspec .. '##' .. minetest.formspec_escape(name)\n end\n\n -- Close the text list and display the selected waypoint position\n formspec = formspec .. ';' .. tostring(selected) .. ']'\n if selected_name[player] then\n local pos = advmarkers.get_waypoint(player, selected_name[player])\n if pos then\n pos = minetest.formspec_escape(tostring(pos.x) .. ', ' ..\n tostring(pos.y) .. ', ' .. tostring(pos.z))\n pos = 'Waypoint position: ' .. pos\n formspec = formspec .. 'label[0,6.75;' .. pos .. ']'\n end\n else\n -- Draw over the buttons\n formspec = formspec .. 'button_exit[0,7.5;5.25,0.5;quit;Close dialog]' ..\n 'label[0,6.75;No waypoints. Add one with \"/add_wp\".]'\n end\n\n -- Display the formspec\n return minetest.show_formspec(player, 'advmarkers-ssm', formspec)\nend\n\n-- Get waypoint position\nfunction advmarkers.get_chatcommand_pos(player, pos)\n local pname = get_player(player, 0)\n\n -- Validate the position\n if pos == 'h' or pos == 'here' then\n pos = get_player(player, 1):get_pos()\n elseif pos == 't' or pos == 'there' then\n if not advmarkers.last_coords[pname] then\n return false, 'No-one has used \".coords\" and you have not died!'\n end\n pos = advmarkers.last_coords[pname]\n else\n pos = string_to_pos(pos)\n if not pos then\n return false, 'Invalid position!'\n end\n end\n return pos\nend\n\nlocal function register_chatcommand_alias(old, ...)\n local def = assert(minetest.registered_chatcommands[old])\n def.name = nil\n for i = 1, select('#', ...) do\n minetest.register_chatcommand(select(i, ...), table.copy(def))\n end\nend\n\n-- Open the waypoints GUI\nlocal csm_key = string.char(1) .. 'ADVMARKERS_SSCSM' .. string.char(1)\nminetest.register_chatcommand('mrkr', {\n params = '',\n description = 'Open the advmarkers GUI',\n func = function(pname, param)\n if param:sub(1, #csm_key) == csm_key then\n -- SSCSM communication\n param = param:sub(#csm_key + 1)\n local cmd = param:sub(1, 1)\n\n if cmd == 'D' then\n -- D: Delete\n advmarkers.delete_waypoint(pname, param:sub(2))\n elseif cmd == 'S' then\n -- S: Set\n local s, e = param:find(' ')\n if s and e then\n local pos = string_to_pos(param:sub(2, s - 1))\n if pos then\n advmarkers.set_waypoint(pname, pos, param:sub(e + 1))\n end\n end\n elseif cmd == '0' then\n -- 0: Display\n if not advmarkers.display_waypoint(pname, param:sub(2)) then\n minetest.chat_send_player(pname,\n 'Error displaying waypoint!')\n end\n end\n\n minetest.chat_send_player(pname, csm_key\n .. advmarkers.export(pname))\n elseif param == '' then\n advmarkers.display_formspec(pname)\n else\n local pos, err = advmarkers.get_chatcommand_pos(pname, param)\n if not pos then\n return false, err\n end\n if not advmarkers.set_hud_pos(pname, pos) then\n return false, 'Error setting the waypoint!'\n end\n end\n end\n})\n\nregister_chatcommand_alias('mrkr', 'wp', 'wps', 'waypoint', 'waypoints')\n\n-- Add a waypoint\nminetest.register_chatcommand('add_mrkr', {\n params = '<pos / \"here\" / \"there\"> <name>',\n description = 'Adds a waypoint.',\n func = function(pname, param)\n -- Get the parameters\n local s, e = param:find(' ')\n if not s or not e then\n return false, 'Invalid syntax! See /help add_mrkr for more info.'\n end\n local pos = param:sub(1, s - 1)\n local name = param:sub(e + 1)\n\n -- Get the position\n local pos, err = advmarkers.get_chatcommand_pos(pname, pos)\n if not pos then\n return false, err\n end\n\n -- Validate the name\n if not name or #name < 1 then\n return false, 'Invalid name!'\n end\n\n -- Set the waypoint\n return advmarkers.set_waypoint(pname, pos, name), 'Done!'\n end\n})\n\nregister_chatcommand_alias('add_mrkr', 'add_wp', 'add_waypoint')\n\n-- Set the HUD\nminetest.register_on_player_receive_fields(function(player, formname, fields)\n local pname, player = get_player(player)\n if formname == 'advmarkers-ignore' then\n return true\n elseif formname ~= 'advmarkers-ssm' then\n return\n end\n local name = false\n if fields.marker then\n local event = minetest.explode_textlist_event(fields.marker)\n if event.index then\n name = formspec_list[pname][event.index]\n end\n else\n name = selected_name[pname]\n end\n\n if name then\n if fields.display then\n if not advmarkers.display_waypoint(player, name) then\n minetest.chat_send_player(pname, 'Error displaying waypoint!')\n end\n elseif fields.rename then\n minetest.show_formspec(pname, 'advmarkers-ssm', 'size[6,3]' ..\n 'label[0.35,0.2;Rename waypoint]' ..\n 'field[0.3,1.3;6,1;new_name;New name;' ..\n minetest.formspec_escape(name) .. ']' ..\n 'button[0,2;3,1;cancel;Cancel]' ..\n 'button[3,2;3,1;rename_confirm;Rename]')\n elseif fields.rename_confirm then\n if fields.new_name and #fields.new_name > 0 then\n if advmarkers.rename_waypoint(pname, name, fields.new_name) then\n selected_name[pname] = fields.new_name\n else\n minetest.chat_send_player(pname, 'Error renaming waypoint!')\n end\n advmarkers.display_formspec(pname)\n else\n minetest.chat_send_player(pname,\n 'Please enter a new name for the waypoint.'\n )\n end\n elseif fields.teleport then\n minetest.show_formspec(pname, 'advmarkers-ssm', 'size[6,2.2]' ..\n 'label[0.35,0.25;' .. minetest.formspec_escape(\n 'Teleport to a waypoint\\n - ' .. name\n ) .. ']' ..\n 'button[0,1.25;3,1;cancel;Cancel]' ..\n 'button_exit[3,1.25;3,1;teleport_confirm;Teleport]')\n elseif fields.teleport_confirm then\n -- Teleport with /teleport\n local pos = advmarkers.get_waypoint(pname, name)\n if not pos then\n minetest.chat_send_player(pname, 'Error teleporting to waypoint!')\n elseif minetest.check_player_privs(pname, 'teleport') then\n player:set_pos(pos)\n minetest.chat_send_player(pname, 'Teleported to waypoint \"' ..\n name .. '\".')\n else\n minetest.chat_send_player(pname, 'Insufficient privileges!')\n end\n elseif fields.delete then\n minetest.show_formspec(pname, 'advmarkers-ssm', 'size[6,2]' ..\n 'label[0.35,0.25;Are you sure you want to delete this waypoint?]' ..\n 'button[0,1;3,1;cancel;Cancel]' ..\n 'button[3,1;3,1;delete_confirm;Delete]')\n elseif fields.delete_confirm then\n advmarkers.delete_waypoint(pname, name)\n selected_name[pname] = nil\n advmarkers.display_formspec(pname)\n elseif fields.cancel then\n advmarkers.display_formspec(pname)\n elseif name ~= selected_name[pname] then\n selected_name[pname] = name\n if not fields.quit then\n advmarkers.display_formspec(pname)\n end\n end\n elseif fields.display or fields.delete then\n minetest.chat_send_player(pname, 'Please select a waypoint.')\n end\n return true\nend)\n\n-- Auto-add waypoints on death.\nminetest.register_on_dieplayer(function(player)\n local name\n if advmarkers.dated_death_markers then\n name = os.date('Death on %Y-%m-%d %H:%M:%S')\n else\n name = 'Death waypoint'\n end\n local pos = player:get_pos()\n advmarkers.last_coords[player] = pos\n advmarkers.set_waypoint(player, pos, name)\n minetest.chat_send_player(player:get_player_name(),\n 'Added waypoint \"' .. name .. '\".')\nend)\n\n-- Allow string exporting\nminetest.register_chatcommand('mrkr_export', {\n params = '',\n description = 'Exports an advmarkers string containing all your waypoints.',\n func = function(name, param)\n local export\n if param == 'old' then\n export = advmarkers.export(name, 'M')\n else\n export = advmarkers.export(name)\n end\n minetest.show_formspec(name, 'advmarkers-ignore',\n 'field[_;Your waypoint export string;' ..\n minetest.formspec_escape(export) .. ']')\n end\n})\n\nregister_chatcommand_alias('mrkr_export', 'wp_export', 'waypoint_export')\n\n-- String importing\nminetest.register_chatcommand('mrkr_import', {\n params = '<advmarkers string>',\n description = 'Imports an advmarkers string. This will not overwrite ' ..\n 'existing waypoints that have the same name.',\n func = function(name, param)\n if advmarkers.import(name, param) then\n return true, 'Waypoints imported!'\n else\n return false, 'Invalid advmarkers string!'\n end\n end\n})\n\nregister_chatcommand_alias('mrkr_export', 'wp_import', 'waypoint_import')\n\n-- Chat channels .coords integration.\n-- You do not need to have chat channels installed for this to work.\nlocal function get_coords(msg, strict)\n local s = 'Current Position: %-?[0-9]+, %-?[0-9]+, %-?[0-9]+%.'\n if strict then\n s = '^' .. s\n end\n local s, e = msg:find(s)\n local pos = false\n if s and e then\n pos = string_to_pos(msg:sub(s + 18, e - 1))\n end\n return pos\nend\n\n-- Get global co-ords\ntable.insert(minetest.registered_on_chat_messages, 1, function(name, msg)\n if msg:sub(1, 1) == '/' then return end\n local pos = get_coords(msg, true)\n if pos then\n advmarkers.last_coords = {}\n for _, player in ipairs(get_connected_players()) do\n advmarkers.last_coords[player:get_player_name()] = pos\n end\n end\nend)\n\n-- Override chat_send_player to get PMed co-ords etc\nlocal old_chat_send_player = minetest.chat_send_player\nfunction minetest.chat_send_player(name, msg, ...)\n if type(name) == 'string' and type(msg) == 'string' and\n get_player_by_name(name) then\n local pos = get_coords(msg)\n if pos then\n advmarkers.last_coords[name] = pos\n end\n end\n return old_chat_send_player(name, msg, ...)\nend\n\n-- Clean up variables if a player leaves\nminetest.register_on_leaveplayer(function(player)\n local name = get_player(player, 0)\n hud[name] = nil\n formspec_list[name] = nil\n selected_name[name] = nil\n advmarkers.last_coords[name] = nil\nend)\n\n-- Add '/mrkrthere'\nminetest.register_chatcommand('mrkrthere', {\n params = '',\n description = 'Alias for \"/mrkr there\".',\n func = function(name, param)\n return minetest.registered_chatcommands['mrkr'].func(name, 'there')\n end\n})\n\n-- SSCSM support\nif minetest.global_exists('sscsm') and sscsm.register then\n sscsm.register({\n name = 'advmarkers',\n file = minetest.get_modpath('advmarkers') .. '/sscsm.lua',\n })\nend\n"
},
{
"alpha_fraction": 0.6749225854873657,
"alphanum_fraction": 0.6904024481773376,
"avg_line_length": 19.1875,
"blob_id": "7dc7ec7f6d0868d577d41492853c7d8167c2d81b",
"content_id": "cddc76c2347c293617f9750f10a4c3fff88ae07d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 16,
"path": "/mods/initial_items/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "local items = {\n\t\"farming:seed_wheat 5\",\n\t\"default:pick_stone\",\n\t\"default:apple 20\",\n\t\"default:sapling 3\",\n\t\"craftguide:book\",\n\t\"boats:boat\",\n\t\"default:papyrus 8\",\n}\n\nminetest.register_on_newplayer(function(player)\n\tlocal inv = player:get_inventory()\n\tfor _, item in ipairs(items) do\n\t\tinv:add_item(\"main\", item)\n\tend\nend)\n"
},
{
"alpha_fraction": 0.6565275192260742,
"alphanum_fraction": 0.6591714024543762,
"avg_line_length": 28.717010498046875,
"blob_id": "0c748e3a5b0a8a4ffe4a370707364a3c81ceee2e",
"content_id": "20419fbbfaed0a3e2cbdd21c121b1f927f6d3615",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 38958,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 1311,
"path": "/mods/factions/factions.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-------------------------------------------------------------------------------\n-- factions Mod by Sapier\n--\n-- License WTFPL\n--\n--! @file factions.lua\n--! @brief factions core file\n--! @copyright Sapier, agrecascino, shamoanjac, Coder12a\n--! @author Sapier, agrecascino, shamoanjac, Coder12a\n--! @date 2016-08-12\n--\n-- Contact sapier a t gmx net\n-------------------------------------------------------------------------------\n\n--read some basic information\nlocal factions_worldid = minetest.get_worldpath()\nlocal storage = minetest.get_mod_storage()\n\n--! @class factions\n--! @brief main class for factions\nfactions = {}\n\n--! @brief runtime data\nfactions.factions = {}\nfactions.parcels = {}\nfactions.players = {}\n\n--- settings\nfactions.protection_max_depth = config.protection_max_depth\nfactions.power_per_parcel = config.power_per_parcel\nfactions.power_per_death = config.power_per_death\nfactions.power_per_tick = config.power_per_tick\nfactions.tick_time = config.tick_time\nfactions.power_per_attack = config.power_per_attack\nfactions.faction_name_max_length = config.faction_name_max_length\nfactions.rank_name_max_length = config.rank_name_max_length\nfactions.maximum_faction_inactivity = config.maximum_faction_inactivity\n\n---------------------\n--! @brief returns whether a faction can be created or not (allows for implementation of blacklists and the like)\n--! @param name String containing the faction's name\nfactions.can_create_faction = function(name)\n if #name > factions.faction_name_max_length then\n return false\n elseif factions.factions[name] then\n return false\n else\n return true\n end\nend\n\n\nfactions.Faction = {\n}\n\nutil = {\n coords3D_string = function(coords)\n return coords.x..\", \"..coords.y..\", \"..coords.z\n end\n}\n\nfactions.Faction.__index = factions.Faction\n\n-- Faction permissions:\n--\n-- disband: disband the faction\n-- claim: (un)claim parcels\n-- playerslist: invite/kick players and open/close the faction\n-- build: dig and place nodes\n-- description: set the faction's description\n-- ranks: create and delete ranks\n-- spawn: set the faction's spawn\n-- banner: set the faction's banner\n-- promote: set a player's rank\n-- diplomacy: make war, peace, or an alliance.\n\nfactions.permissions = {\"disband\", \"claim\", \"playerslist\", \"build\", \"description\", \"ranks\", \"spawn\", \"banner\", \"promote\", \"diplomacy\"}\n\nfunction factions.Faction:new(faction) \n faction = {\n --! @brief power of a faction (needed for parcel claiming)\n power = config.power,\n --! @brief maximum power of a faction\n maxpower = config.maxpower,\n --! @brief power currently in use\n usedpower = 0.,\n --! @brief list of player names\n players = {},\n --! @brief table of ranks/permissions\n ranks = {[\"leader\"] = {\"disband\", \"claim\", \"playerslist\", \"build\", \"description\", \"ranks\", \"spawn\", \"banner\", \"promote\", \"diplomacy\"},\n [\"moderator\"] = {\"claim\", \"playerslist\", \"build\", \"spawn\"},\n [\"member\"] = {\"build\"}\n },\n --! @brief name of the leader\n leader = nil,\n --! @brief default joining rank for new members\n default_rank = \"member\",\n --! @brief default rank assigned to the leader\n default_leader_rank = \"leader\",\n --! @brief faction's description string\n description = \"Default faction description.\",\n --! @brief list of players currently invited (can join with /f join)\n invited_players = {},\n --! @brief table of claimed parcels (keys are parcelpos strings)\n land = {},\n --! @brief table of allies\n allies = {},\n\t\t--\n\t\trequest_inbox = {},\n --! @brief table of enemies\n enemies = {},\n\t\t--!\n\t\tneutral = {},\n --! @brief table of parcels/factions that are under attack\n attacked_parcels = {},\n --! @brief whether faction is closed or open (boolean)\n join_free = false,\n --! @brief banner texture string\n banner = \"bg_white.png\",\n --! @brief gives certain privileges\n is_admin = false,\n --! @brief last time anyone logged on\n last_logon = os.time(),\n } or faction\n setmetatable(faction, self)\n return faction\nend\n\n\n--! @brief create a new empty faction\nfactions.new_faction = function(name)\n local faction = factions.Faction:new(nil)\n faction.name = name\n factions.factions[name] = faction\n faction:on_create()\n factions.save()\n return faction\nend\n\nfunction factions.start_diplomacy(name,faction)\n\tfor i,fac in pairs(factions.factions) do\n\t\tif i ~= name and not (faction.neutral[i] or faction.allies[i] or faction.enemies[i]) then\n\t\t\tfaction:new_enemy(i)\n\t\t\tfac:new_enemy(name)\n\t\tend\n\tend\nend\n\nfunction factions.Faction.set_name(self, name)\n\tlocal oldname = self.name\n\tlocal oldfaction = factions.factions[oldname]\n\tself.name = name\n\tfor i,fac in pairs(factions.factions) do\n\t\tif i ~= oldname then\n\t\t\tif fac.neutral[oldname] then\n\t\t\t\tfac.neutral[oldname] = nil\n\t\t\t\tfac.neutral[name] = true\n\t\t\tend\n\t\t\tif fac.allies[oldname] then\n\t\t\t\tfac.allies[oldname] = nil\n\t\t\t\tfac.allies[name] = true\n\t\t\tend\n\t\t\tif fac.enemies[oldname] then\n\t\t\t\tfac.enemies[oldname] = nil\n\t\t\t\tfac.enemies[name] = true\n\t\t\tend\n\t\tend\n\tend\n\tfor parcel in pairs(self.land) do\n\tfactions.parcels[parcel] = self.name\n\tend\n\tfor playername in pairs(self.players) do\n\tfactions.players[playername] = self.name\n\tend\n\tfactions.factions[oldname] = nil\n\tfactions.factions[name] = oldfaction\n\tfactions.factions[name].name = name\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tremoveHud(realplayer,\"1\")\n\t\t\t\tcreateHudFactionName(realplayer,name)\n\t\t\tend\n\t\tend\n\tend\n\tself:on_set_name(oldname)\n\tfactions.save()\nend\n\nfunction factions.Faction.increase_power(self, power)\n self.power = self.power + power\n if self.power > self.maxpower - self.usedpower then\n self.power = self.maxpower - self.usedpower\n end\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\n factions.save()\nend\n\nfunction factions.Faction.decrease_power(self, power)\n self.power = self.power - power\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\n factions.save()\nend\n\nfunction factions.Faction.increase_maxpower(self, power)\n self.maxpower = self.maxpower + power\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\n factions.save()\nend\n\nfunction factions.Faction.decrease_maxpower(self, power)\n self.maxpower = self.maxpower - power\n if self.maxpower < 0. then -- should not happen\n self.maxpower = 0.\n end\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction factions.Faction.increase_usedpower(self, power)\n\tfactions.Faction.increase_maxpower(self, power)\n self.usedpower = self.usedpower + power\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction factions.Faction.decrease_usedpower(self, power)\n\tfactions.Faction.decrease_maxpower(self, power)\n self.usedpower = self.usedpower - power\n if self.usedpower < 0. then\n self.usedpower = 0.\n end\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tfor player, _ in pairs(self.players) do\n\t\t\tlocal realplayer = playerslist[i]\n\t\t\tif realplayer:get_player_name() == player then\n\t\t\t\tupdateHudPower(realplayer,self)\n\t\t\tend\n\t\tend\n\tend\nend\n\nfunction factions.Faction.count_land(self)\n local count = 0.\n for k, v in pairs(self.land) do\n count = count + 1\n end\n return count\nend\n\nfunction factions.Faction.add_player(self, player, rank)\n self:on_player_join(player)\n self.players[player] = rank or self.default_rank\n factions.players[player] = self.name\n self.invited_players[player] = nil\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tlocal realplayer = playerslist[i]\n\t\tif realplayer:get_player_name() == player then\n\t\t\tcreateHudFactionName(realplayer,self.name)\n\t\t\tcreateHudPower(realplayer,self)\n\t\t\tbreak\n\t\tend\n\tend\n factions.save()\nend\n\nfunction factions.Faction.check_players_in_faction(self)\n\tlocal i = 0\n\tif self.players then\n\t\tfor player in pairs(self.players) do\n\t\t\ti = i + 1\n\t\tend\n\tend\n\t--local players = #self.players\n\tif i < 1 then\n\t\tself:disband(\"Zero players on faction.\")\n\tend\nend\n\nfunction factions.Faction.remove_player(self, player)\n self.players[player] = nil\n factions.players[player] = nil\n self:on_player_leave(player)\n\tself:check_players_in_faction(self)\n\tlocal playerslist = minetest.get_connected_players()\n\tfor i in pairs(playerslist) do\n\t\tlocal realplayer = playerslist[i]\n\t\tif realplayer:get_player_name() == player then\n\t\t\tremoveHud(realplayer,\"1\")\n\t\t\tremoveHud(realplayer,\"2\")\n\t\tend\n\tend\n factions.save()\nend\n\n--! @param parcelpos position of the wanted parcel\n--! @return whether this faction can claim a parcelpos\nfunction factions.Faction.can_claim_parcel(self, parcelpos)\n local fac = factions.parcels[parcelpos]\n if fac then\n if factions.factions[fac].power <= 0 and self.power >= factions.power_per_parcel then\n return true\n else\n return false\n end\n elseif self.power < factions.power_per_parcel then\n return false\n end\n return true\nend\n\n--! @brief claim a parcel, update power and update global parcels table\nfunction factions.Faction.claim_parcel(self, parcelpos)\n -- check if claiming over other faction's territory\n local otherfac = factions.parcels[parcelpos]\n if otherfac then\n local faction = factions.factions[otherfac]\n faction:unclaim_parcel(parcelpos)\n end\n factions.parcels[parcelpos] = self.name\n self.land[parcelpos] = true\n self:decrease_power(factions.power_per_parcel)\n self:increase_usedpower(factions.power_per_parcel)\n self:on_claim_parcel(parcelpos)\n factions.save()\nend\n\nfunction factions.Faction.bulk_claim_parcel(self, parcelpos)\n factions.parcels[parcelpos] = self.name\n self.land[parcelpos] = true\n factions.save()\nend\n\n--! @brief claim a parcel, update power and update global parcels table\nfunction factions.Faction.unclaim_parcel(self, parcelpos)\n factions.parcels[parcelpos] = nil\n self.land[parcelpos] = nil\n self:increase_power(factions.power_per_parcel)\n self:decrease_usedpower(factions.power_per_parcel)\n self:on_unclaim_parcel(parcelpos)\n factions.save()\nend\n\nfunction factions.Faction.bulk_unclaim_parcel(self, parcelpos)\n factions.parcels[parcelpos] = nil\n self.land[parcelpos] = nil\n factions.save()\nend\n\n--! @brief disband faction, updates global players and parcels table\nfunction factions.Faction.disband(self, reason)\n local playerslist = minetest.get_connected_players()\n\tfor i,v in pairs(factions.factions) do\n\t\tif v.name ~= self.name then\n\t\t\tif v.enemies[self.name] then\n\t\t\t\tv:end_enemy(self.name)\n\t\t\tend\n\t\t\tif v.allies[self.name] then\n\t\t\t\tv:end_alliance(self.name)\n\t\t\tend\n\t\t\tif v.neutral[self.name] then\n\t\t\t\tv:end_neutral(self.name)\n\t\t\tend\n\t\tend\n\tend\n for k, _ in pairs(factions.players) do -- remove players affiliation\n if(factions.players[k] == self.name) then\n factions.players[k] = nil\n end\n end\n for k, v in pairs(self.land) do -- remove parcel claims\n if(factions.parcels[k] == self.name) then\n factions.parcels[k] = nil\n end\n end\n\n self:on_disband(reason)\n factions.factions[self.name] = nil\n\tfor i in pairs(playerslist) do\n\t\tlocal realplayer = playerslist[i]\n\t\tlocal faction = factions.get_player_faction(realplayer:get_player_name())\n if not faction then\n\t\t\tremoveHud(realplayer,\"1\")\n\t\t\tremoveHud(realplayer,\"2\")\n\t\tend\n end\n\n factions.save()\nend\n\n--! @brief change the faction leader\nfunction factions.Faction.set_leader(self, player)\n if self.leader then\n self.players[self.leader] = self.default_rank\n end\n self.leader = player\n self.players[player] = self.default_leader_rank\n self:on_new_leader()\n factions.save()\nend\n\n--! @brief check permissions for a given player\n--! @return boolean indicating permissions. Players not in faction always receive false\nfunction factions.Faction.has_permission(self, player, permission)\n local p = self.players[player]\n if not p then\n return false\n end\n\n local perms = self.ranks[p]\n if not perms then\n return false\n end\n\n for i in ipairs(perms) do\n if perms[i] == permission then\n return true\n end\n end\n return false\nend\nfunction factions.Faction.set_description(self, new)\n self.description = new\n self:on_change_description()\n factions.save()\nend\n\n--! @brief places player in invite list\nfunction factions.Faction.invite_player(self, player)\n self.invited_players[player] = true\n self:on_player_invited(player)\n factions.save()\nend\n\n--! @brief removes player from invite list (can no longer join via /f join)\nfunction factions.Faction.revoke_invite(self, player)\n self.invited_players[player] = nil\n self:on_revoke_invite(player)\n factions.save()\nend\n--! @brief set faction openness\nfunction factions.Faction.toggle_join_free(self, bool)\n self.join_free = bool\n self:on_toggle_join_free()\n factions.save()\nend\n\n--! @return true if a player can use /f join, false otherwise\nfunction factions.Faction.can_join(self, player)\n return self.join_free or self.invited_players[player]\nend\n\nfunction factions.Faction.new_alliance(self, faction)\n self.allies[faction] = true\n self:on_new_alliance(faction)\n if self.enemies[faction] then\n self:end_enemy(faction)\n end\n\tif self.neutral[faction] then\n self:end_neutral(faction)\n end\n factions.save()\nend\n\nfunction factions.Faction.end_alliance(self, faction)\n self.allies[faction] = nil\n self:on_end_alliance(faction)\n factions.save()\nend\n\nfunction factions.Faction.new_neutral(self, faction)\n self.neutral[faction] = true\n self:on_new_neutral(faction)\n if self.allies[faction] then\n self:end_alliance(faction)\n end\n if self.enemies[faction] then\n self:end_enemy(faction)\n end\n factions.save()\nend\n\nfunction factions.Faction.end_neutral(self, faction)\n self.neutral[faction] = nil\n self:on_end_neutral(faction)\n factions.save()\nend\n\nfunction factions.Faction.new_enemy(self, faction)\n self.enemies[faction] = true\n self:on_new_enemy(faction)\n if self.allies[faction] then\n self:end_alliance(faction)\n end\n\tif self.neutral[faction] then\n self:end_neutral(faction)\n end\n factions.save()\nend\n\nfunction factions.Faction.end_enemy(self, faction)\n self.enemies[faction] = nil\n self:on_end_enemy(faction)\n factions.save()\nend\n\n--! @brief faction's member will now spawn in a new place\nfunction factions.Faction.set_spawn(self, pos)\n self.spawn = {x=pos.x, y=pos.y, z=pos.z}\n self:on_set_spawn()\n factions.save()\nend\n\n--! @brief create a new rank with permissions\n--! @param rank the name of the new rank\n--! @param rank a list with the permissions of the new rank\nfunction factions.Faction.add_rank(self, rank, perms)\n self.ranks[rank] = perms\n self:on_add_rank(rank)\n factions.save()\nend\n\n--! @brief replace an rank's permissions\n--! @param rank the name of the rank to edit\n--! @param add or remove permissions to the rank\nfunction factions.Faction.replace_privs(self, rank, perms)\n self.ranks[rank] = perms\n self:on_replace_privs(rank)\n factions.save()\nend\n\nfunction factions.Faction.remove_privs(self, rank, perms)\n\tlocal revoked = false\n\tlocal p = self.ranks[rank]\n\tfor index, perm in pairs(p) do\n\t\tif table_Contains(perms,perm) then\n\t\t\trevoked = true\n\t\t\ttable.remove(p,index)\n\t\tend\n\tend\n\tself.ranks[rank] = p\n\tif revoked then\n\t\tself:on_remove_privs(rank,perms)\n\telse\n\t\tself:broadcast(\"No privilege was revoked from rank \"..rank..\".\")\n\tend\n factions.save()\nend\n\nfunction factions.Faction.add_privs(self, rank, perms)\n\tlocal added = false\n\tlocal p = self.ranks[rank]\n\tfor index, perm in pairs(perms) do\n\t\tif not table_Contains(p,perm) then\n\t\t\tadded = true\n\t\t\ttable.insert(p,perm)\n\t\tend\n\tend\n\tself.ranks[rank] = p\n\tif added then\n\t\tself:on_add_privs(rank,perms)\n\telse\n\t\tself:broadcast(\"The rank \"..rank..\" already has these privileges.\")\n\tend\n factions.save()\nend\n\nfunction factions.Faction.set_rank_name(self, oldrank, newrank)\n\tlocal copyrank = self.ranks[oldrank]\n\tself.ranks[newrank] = copyrank\n\tself.ranks[oldrank] = nil\n\tfor player, r in pairs(self.players) do\n if r == oldrank then\n self.players[player] = newrank\n end\n end\n\tif oldrank == self.default_leader_rank then\n\t\tself.default_leader_rank = newrank\n\t\tself:broadcast(\"The default leader rank has been set to \"..newrank)\n\tend\n\tif oldrank == self.default_rank then\n\t\tself.default_rank = newrank\n\t\tself:broadcast(\"The default rank given to new players is set to \"..newrank)\n\tend\n self:on_set_rank_name(oldrank, newrank)\n factions.save()\nend\n\n--! @brief delete a rank and replace it\n--! @param rank the name of the rank to be deleted\n--! @param newrank the rank given to players who were previously \"rank\"\nfunction factions.Faction.delete_rank(self, rank, newrank)\n for player, r in pairs(self.players) do\n if r == rank then\n self.players[player] = newrank\n end\n end\n self.ranks[rank] = nil\n self:on_delete_rank(rank, newrank)\n\tif rank == self.default_leader_rank then\n\t\tself.default_leader_rank = newrank\n\t\tself:broadcast(\"The default leader rank has been set to \"..newrank)\n\tend\n\tif rank == self.default_rank then\n\t\tself.default_rank = newrank\n\t\tself:broadcast(\"The default rank given to new players is set to \"..newrank)\n\tend\n factions.save()\nend\n\n--! @param newbanner texture string of the new banner\nfunction factions.Faction.set_banner(self, newbanner)\n self.banner = newbanner\n self:on_new_banner()\nend\n\n--! @brief set a player's rank\nfunction factions.Faction.promote(self, member, rank)\n self.players[member] = rank\n self:on_promote(member)\nend\n\n--! @brief send a message to all members\nfunction factions.Faction.broadcast(self, msg, sender)\n local message = self.name..\"> \"..msg\n if sender then\n message = sender..\"@\"..message\n end\n message = \"Faction<\"..message\n for k, _ in pairs(self.players) do\n minetest.chat_send_player(k, message)\n end\nend\n\n--! @brief checks whether a faction has at least one connected player\nfunction factions.Faction.is_online(self)\n for playername, _ in pairs(self.players) do\n if minetest.get_player_by_name(playername) then\n return true\n end\n end\n return false\nend\n\nfunction factions.Faction.attack_parcel(self, parcelpos)\n\tif config.attack_parcel then\n\t\tlocal attacked_faction = factions.get_parcel_faction(parcelpos)\n\t\tif attacked_faction then\n\t\t\tif self.power < factions.power_per_attack then\n\t\t\t\tself:broadcast(\"You do not have enough power to attack!!\")\n\t\t\t\treturn\n\t\t\tend\n\t\t\tself.power = self.power - factions.power_per_attack\n\t\t\tif attacked_faction.attacked_parcels[parcelpos] then \n\t\t\t\tattacked_faction.attacked_parcels[parcelpos][self.name] = true\n\t\t\telse\n\t\t\t\tattacked_faction.attacked_parcels[parcelpos] = {[self.name] = true}\n\t\t\tend\n\t\t\tattacked_faction:broadcast(\"Parcel (\"..parcelpos..\") is being attacked by \"..self.name..\"!!\")\n\t\t\tif self.power < 0. then -- punish memers\n\t\t\t\tminetest.chat_send_all(\"Faction \"..self.name..\" has attacked too much and has now negative power!\")\n\t\t\tend\n\t\t\tfactions.save()\n\t\tend \n\tend\nend\n\nfunction factions.Faction.stop_attack(self, parcelpos)\n local attacked_faction = factions.parcels[parcelpos]\n if attacked_faction then\n attacked_faction = factions.factions[attacked_faction]\n if attacked_faction.attacked_parcels[parcelpos] then\n attacked_faction.attacked_parcels[parcelpos][self.name] = nil\n attacked_faction:broadcast(\"Parcel (\"..parcelpos..\") is no longer under attack from \"..self.name..\".\")\n self:broadcast(\"Parcel (\"..parcelpos..\") has been reconquered by \"..attacked_faction.name..\".\")\n end\n factions.save()\n end\nend\n\nfunction factions.Faction.parcel_is_attacked_by(self, parcelpos, faction)\n if self.attacked_parcels[parcelpos] then\n return self.attacked_parcels[parcelpos][faction.name]\n else\n return false\n end\nend\n\n--------------------------\n-- callbacks for events --\nfunction factions.Faction.on_create(self) --! @brief called when the faction is added to the global faction list\n minetest.chat_send_all(\"Faction \"..self.name..\" has been created.\")\nend\n\nfunction factions.Faction.on_set_name(self,oldname)\n minetest.chat_send_all(\"Faction \"..oldname..\" changed its name to \"..self.name..\".\")\nend\n\nfunction factions.Faction.on_player_leave(self, player)\n self:broadcast(player..\" has left this faction.\")\nend\n\nfunction factions.Faction.on_player_join(self, player)\n self:broadcast(player..\" has joined this faction.\")\nend\n\nfunction factions.Faction.on_claim_parcel(self, pos)\n self:broadcast(\"Parcel (\"..pos..\") has been claimed.\")\nend\n\nfunction factions.Faction.on_unclaim_parcel(self, pos)\n self:broadcast(\"Parcel (\"..pos..\") has been unclaimed.\")\nend\n\nfunction factions.Faction.on_disband(self, reason)\n local msg = \"Faction \"..self.name..\" has been disbanded.\"\n if reason then\n msg = msg..\" (\"..reason..\")\"\n end\n minetest.chat_send_all(msg)\nend\n\nfunction factions.Faction.on_new_leader(self)\n self:broadcast(self.leader..\" is now the leader of this faction.\")\nend\n\nfunction factions.Faction.on_change_description(self)\n self:broadcast(\"Faction description has been modified to: \"..self.description)\nend\n\nfunction factions.Faction.on_player_invited(self, player)\n minetest.chat_send_player(player, \"You have been invited to faction \"..self.name)\nend\n\nfunction factions.Faction.on_toggle_join_free(self, player)\n if self.join_free then\n self:broadcast(\"This faction is now invite-free.\")\n else\n self:broadcast(\"This faction is no longer invite-free.\")\n end\nend\n\nfunction factions.Faction.on_new_alliance(self, faction)\n self:broadcast(\"This faction is now allied with \"..faction)\nend\n\nfunction factions.Faction.on_end_alliance(self, faction)\n self:broadcast(\"This faction is no longer allied with \"..faction..\"!\")\nend\n\nfunction factions.Faction.on_new_neutral(self, faction)\n self:broadcast(\"This faction is now neutral with \"..faction)\nend\n\nfunction factions.Faction.on_end_neutral(self, faction)\n self:broadcast(\"This faction is no longer neutral with \"..faction..\"!\")\nend\n\nfunction factions.Faction.on_new_enemy(self, faction)\n self:broadcast(\"This faction is now at war with \"..faction)\nend\n\nfunction factions.Faction.on_end_enemy(self, faction)\n self:broadcast(\"This faction is no longer at war with \"..faction..\"!\")\nend\n\nfunction factions.Faction.on_set_spawn(self)\n self:broadcast(\"The faction spawn has been set to (\"..util.coords3D_string(self.spawn)..\").\")\nend\n\nfunction factions.Faction.on_add_rank(self, rank)\n self:broadcast(\"The rank \"..rank..\" has been created with privileges: \"..table.concat(self.ranks[rank], \", \"))\nend\n\nfunction factions.Faction.on_replace_privs(self, rank)\n self:broadcast(\"The privileges in rank \"..rank..\" have been delete and changed to: \"..table.concat(self.ranks[rank], \", \"))\nend\n\nfunction factions.Faction.on_remove_privs(self, rank,privs)\n self:broadcast(\"The privileges (\"..table.concat(privs, \", \")..\")\"..\" in rank \"..rank..\" have been revoked: \")\nend\n\nfunction factions.Faction.on_add_privs(self, rank,privs)\n\tself:broadcast(\"The privileges (\"..table.concat(privs, \", \")..\")\"..\" in rank \"..rank..\" have been added: \")\nend\n\nfunction factions.Faction.on_set_rank_name(self, rank,newrank)\n self:broadcast(\"The name of rank \"..rank..\" has been changed to \"..newrank)\nend\n\nfunction factions.Faction.on_delete_rank(self, rank, newrank)\n self:broadcast(\"The rank \"..rank..\" has been deleted and replaced by \"..newrank)\nend\n\nfunction factions.Faction.on_new_banner(self)\n self:broadcast(\"A new banner has been set.\")\nend\n\nfunction factions.Faction.on_promote(self, member)\n minetest.chat_send_player(member, \"You have been promoted to \"..self.players[member])\nend\n\nfunction factions.Faction.on_revoke_invite(self, player)\n minetest.chat_send_player(player, \"You are no longer invited to faction \"..self.name)\nend\n\n--??????????????\n\nfunction factions.get_parcel_pos(pos)\n return math.floor(pos.x / 32.)..\",\"..math.floor(pos.z / 32.)\nend\n\nfunction factions.get_player_faction(playername)\n local facname = factions.players[playername]\n if facname then\n local faction = factions.factions[facname]\n return faction\n end\n return nil\nend\n\nfunction factions.get_parcel_faction(parcelpos)\n local facname = factions.parcels[parcelpos]\n if facname then\n local faction = factions.factions[facname]\n return faction\n end\n return nil\nend\n\nfunction factions.get_faction(facname)\n return factions.factions[facname]\nend\n\nfunction factions.get_faction_at(pos)\n local parcelpos = factions.get_parcel_pos(pos)\n return factions.get_parcel_faction(parcelpos)\nend\n\n\n-------------------------------------------------------------------------------\n-- name: add_faction(name)\n--\n--! @brief add a faction\n--! @memberof factions\n--! @public\n--\n--! @param name of faction to add\n--!\n--! @return faction object/false (succesfully added faction or not)\n-------------------------------------------------------------------------------\nfunction factions.add_faction(name)\n if factions.can_create_faction(name) then\n local fac = factions.new_faction(name)\n fac:on_create()\n return fac\n else\n return nil\n end\nend\n\n-------------------------------------------------------------------------------\n-- name: get_faction_list()\n--\n--! @brief get list of factions\n--! @memberof factions\n--! @public\n--!\n--! @return list of factions\n-------------------------------------------------------------------------------\nfunction factions.get_faction_list()\n\n local retval = {}\n\n for key,value in pairs(factions.factions) do\n table.insert(retval,key)\n end\n\n return retval\nend\n\n-------------------------------------------------------------------------------\n-- name: save()\n--\n--! @brief save data to file\n--! @memberof factions\n--! @private\n-------------------------------------------------------------------------------\nfunction factions.save()\n\n --saving is done much more often than reading data to avoid delay\n --due to figuring out which data to save and which is temporary only\n --all data is saved here\n --this implies data needs to be cleant up on load\n\n local file,error = io.open(factions_worldid .. \"/\" .. \"factions.conf\",\"w\")\n\n if file ~= nil then\n file:write(minetest.serialize(factions.factions))\n file:close()\n else\n minetest.log(\"error\",\"MOD factions: unable to save factions world specific data!: \" .. error)\n end\n\nend\n\n-------------------------------------------------------------------------------\n-- name: load()\n--\n--! @brief load data from file\n--! @memberof factions\n--! @private\n--\n--! @return true/false\n-------------------------------------------------------------------------------\nfunction factions.load()\n local file,error = io.open(factions_worldid .. \"/\" .. \"factions.conf\",\"r\")\n\n if file ~= nil then\n local raw_data = file:read(\"*a\")\n factions.factions = minetest.deserialize(raw_data)\n for facname, faction in pairs(factions.factions) do\n minetest.log(\"action\", facname..\",\"..faction.name)\n for player, rank in pairs(faction.players) do\n minetest.log(\"action\", player..\",\"..rank)\n factions.players[player] = facname\n end\n for parcelpos, val in pairs(faction.land) do\n factions.parcels[parcelpos] = facname\n end\n setmetatable(faction, factions.Faction)\n -- compatiblity and later additions\n if not faction.maxpower or faction.maxpower <= 0. then\n faction.maxpower = faction.power\n if faction.power < 0. then\n faction.maxpower = 0.\n end\n end\n if not faction.attacked_parcels then\n faction.attacked_parcels = {}\n end\n if not faction.usedpower then\n faction.usedpower = faction:count_land() * factions.power_per_parcel\n end\n if #faction.name > factions.faction_name_max_length then\n faction:disband()\n end\n if not faction.last_logon then\n faction.last_logon = os.time()\n end\n\t\t\tif not faction.request_inbox then\n\t\t\t\tfaction.request_inbox = {}\n\t\t\tend\n\t\t\tif not faction.enemies then\n\t\t\t\tfaction.enemies = {}\n\t\t\tend\n\t\t\tif not faction.neutral then\n\t\t\t\tfaction.neutral = {}\n\t\t\tend\n\t\t\tif not faction.allies then\n\t\t\t\tfaction.allies = {}\n\t\t\tend\n end\n\t\tfor facname, faction in pairs(factions.factions) do\n\t\t\tfactions.start_diplomacy(facname,faction)\n\t\tend\n file:close()\n end\nend\n\nfunction factions.convert(filename)\n local file, error = io.open(factions_worldid .. \"/\" .. filename, \"r\")\n if not file then\n minetest.chat_send_all(\"Cannot load file \"..filename..\". \"..error)\n return false\n end\n local raw_data = file:read(\"*a\")\n local data = minetest.deserialize(raw_data)\n local factionsmod = data.factionsmod\n local objects = data.objects\n for faction, attrs in pairs(factionsmod) do\n local newfac = factions.new_faction(faction)\n newfac:add_player(attrs.owner, \"leader\")\n for player, _ in pairs(attrs.adminlist) do\n if not newfac.players[player] then\n newfac:add_player(player, \"moderator\")\n end\n end\n for player, _ in pairs(attrs.invitations) do\n newfac:invite_player(player)\n end\n for i in ipairs(attrs.parcel) do\n local parcelpos = table.concat(attrs.parcel[i],\",\")\n newfac:claim_parcel(parcelpos)\n end\n end\n for player, attrs in pairs(objects) do\n local facname = attrs.factionsmod\n local faction = factions.factions[facname]\n if faction then\n faction:add_player(player)\n end\n end\n return true\nend\n\nminetest.register_on_dieplayer(\nfunction(player)\n local faction = factions.get_player_faction(player:get_player_name())\n if not faction then\n return true\n end\n faction:decrease_power(factions.power_per_death)\n return true\nend\n)\n\n\nfactions.faction_tick = function()\n local now = os.time()\n for facname, faction in pairs(factions.factions) do\n if faction:is_online() then\n faction:increase_power(factions.power_per_tick)\n end\n if faction.is_admin == false and now - faction.last_logon > factions.maximum_faction_inactivity then\n faction:disband()\n end\n end\nend\n--[[\nlocal hudUpdate = 0.\nlocal factionUpdate = 0.\n\nminetest.register_globalstep(\nfunction(dtime)\n hudUpdate = hudUpdate + dtime\n factionUpdate = factionUpdate + dtime\n if hudUpdate > .5 then\n local playerslist = minetest.get_connected_players()\n for i in pairs(playerslist) do\n local player = playerslist[i]\n local faction = factions.get_faction_at(player:getpos())\n player:hud_remove(\"factionLand\")\n player:hud_add({\n hud_elem_type = \"text\",\n name = \"factionLand\",\n number = 0xFFFFFF,\n position = {x=0.1, y = .98},\n text = (faction and faction.name) or \"Wilderness\",\n scale = {x=1, y=1},\n alignment = {x=0, y=0},\n })\n end\n hudUpdate = 0.\n end\n if factionUpdate > factions.tick_time then\n factions.faction_tick()\n factionUpdate = 0.\n end\nend\n)\n--]]\n\nhud_ids = {}\n\ncreateHudFactionName = function(player,factionname)\n\tlocal name = player:get_player_name()\n\tlocal id_name = name .. \"1\"\n\tif not hud_ids[id_name] then\n\t\thud_ids[id_name] = player:hud_add({\n\t\t\thud_elem_type = \"text\",\n\t\t\tname = \"factionName\",\n\t\t\tnumber = 0xFFFFFF,\n\t\t\tposition = {x=1, y = 0},\n\t\t\ttext = \"Faction \"..factionname,\n\t\t\tscale = {x=1, y=1},\n\t\t\talignment = {x=-1, y=0},\n\t\t\toffset = {x = -20, y = 20}\n\t\t})\n\tend\nend\n\ncreateHudPower = function(player,faction)\n\tlocal name = player:get_player_name()\n\tlocal id_name = name .. \"2\"\n\tif not hud_ids[id_name] then\n\t\thud_ids[id_name] = player:hud_add({\n\t\t\thud_elem_type = \"text\",\n\t\t\tname = \"powerWatch\",\n\t\t\tnumber = 0xFFFFFF,\n\t\t\tposition = {x=0.9, y = .98},\n\t\t\ttext = \"Power \"..faction.power..\"/\"..faction.maxpower - faction.usedpower..\"/\"..faction.usedpower,\n\t\t\tscale = {x=1, y=1},\n\t\t\talignment = {x=-1, y=0},\n\t\t\toffset = {x = 0, y = 0}\n\t\t})\n\tend\nend\n\nupdateHudPower = function(player,faction)\n\tlocal name = player:get_player_name()\n\tlocal id_name = name .. \"2\"\n\tif hud_ids[id_name] then\n\t\tplayer:hud_change(hud_ids[id_name],\"text\",\"Power \"..faction.power..\"/\"..faction.maxpower - faction.usedpower..\"/\"..faction.usedpower)\n\tend\nend\n\nremoveHud = function(player,numberString)\n\tlocal name = player:get_player_name()\n\tlocal id_name = name .. numberString\n\tif hud_ids[id_name] then\n\t\tplayer:hud_remove(hud_ids[id_name])\n\t\thud_ids[id_name] = nil\n\tend\nend\n\nhudUpdate = function()\n\tminetest.after(.5, \n\tfunction()\n\t\tlocal playerslist = minetest.get_connected_players()\n\t\tfor i in pairs(playerslist) do\n\t\t\tlocal player = playerslist[i]\n\t\t\tlocal name = player:get_player_name()\n\t\t\tlocal faction = factions.get_faction_at(player:getpos())\n\t\t\tlocal id_name = name .. \"0\"\n\t\t\tif hud_ids[id_name] then\n\t\t\t\tplayer:hud_change(hud_ids[id_name],\"text\",(faction and faction.name) or \"Wilderness\")\n\t\t\tend\n\t\tend\n\t\thudUpdate()\n\tend)\nend\n\nfactionUpdate = function()\n\tminetest.after(factions.tick_time, \n\tfunction()\n\t\tfactions.faction_tick()\n\t\tfactionUpdate()\n\tend)\nend\n\nminetest.register_on_joinplayer(\nfunction(player)\n\tlocal name = player:get_player_name()\n\thud_ids[name .. \"0\"] = player:hud_add({\n\t\thud_elem_type = \"text\",\n\t\tname = \"factionLand\",\n\t\tnumber = 0xFFFFFF,\n\t\tposition = {x=0.1, y = .98},\n\t\ttext = \"Wilderness\",\n\t\tscale = {x=1, y=1},\n\t\talignment = {x=0, y=0},\n\t})\n local faction = factions.get_player_faction(name)\n\n if faction then\n faction.last_logon = os.time()\n\t\tcreateHudFactionName(player,faction.name)\n\t\tcreateHudPower(player,faction)\n\t\tif faction:has_permission(name,\"diplomacy\") then\n\t\t\tfor _ in pairs(faction.request_inbox) do minetest.chat_send_player(name,\"You have diplomatic requests in the inbox.\") break end\n\t\tend\n end\n\n local pos = player:get_pos()\n\n local parcel_faction = factions.get_faction_at(pos)\n\t-- Login-Time-Stamp\n\t\n\tlocal key = \"LTS:\"..name\n\tlocal value = storage:get_int(key)\n\tlocal facname = \"\"\n\t\n\tif faction then\n\t\tfacname = faction.name\n\tend\n\t\n\t-- 300 seconds = 5 minutes\n\t-- Kill unstamped players.\n if parcel_faction and parcel_faction.is_admin == false and (value == 0 or os.time() - value >= 300) then\n if (not faction or parcel_faction.name ~= facname) and (facname == \"\" or parcel_faction.enemies[facname]) then\n minetest.after(1, function()\n if player then\n player:set_hp(0)\n end\n end)\n end\n end\n\tstorage:set_int(key,os.time())\nend\n)\n\nminetest.register_on_leaveplayer(\n\tfunction(player)\n\t\tlocal name = player:get_player_name()\n\t\tlocal id_name = name .. \"0\"\n\t\tif hud_ids[id_name] then\n\t\t\tplayer:hud_remove(hud_ids[id_name])\n\t\t\thud_ids[id_name] = nil\n\t\tend\n\t\tremoveHud(player,\"1\")\n\t\tremoveHud(player,\"2\")\n\t\t-- Login-Time-Stamp\n\t\tlocal key = \"LTS:\"..name\n\t\tstorage:set_int(key,os.time())\n\tend\n)\n\nminetest.register_on_respawnplayer(\n function(player)\n local faction = factions.get_player_faction(player:get_player_name())\n if not faction then\n return false\n else\n if not faction.spawn then\n return false\n else\n player:setpos(faction.spawn)\n return true\n end\n end\n end\n)\n\n\n\nlocal default_is_protected = minetest.is_protected\nminetest.is_protected = function(pos, player)\n if pos.y < factions.protection_max_depth then\n return false\n end\n if factions.disallow_edit_nofac and not player_faction then\n return true\n end\n\n local parcelpos = factions.get_parcel_pos(pos)\n local parcel_faction = factions.get_parcel_faction(parcelpos)\n local player_faction = factions.get_player_faction(player)\n -- check if wielding death banner\n local player_info = minetest.get_player_by_name(player)\n if not player_info then\n if parcel_faction then\n return true\n else\n return false\n end\n end\n local player_wield = player_info:get_wielded_item()\n if player_wield:get_name() == \"banners:death_banner\" and player_faction then --todo: check for allies, maybe for permissions\n return not player_faction:has_permission(player, \"claim\") and player_faction.power > 0. and not parcel_faction.is_admin\n end\n -- no faction\n if not parcel_faction then\n return default_is_protected(pos, player)\n elseif player_faction then\n if parcel_faction.name == player_faction.name then\n return not parcel_faction:has_permission(player, \"build\")\n elseif parcel_faction.allies[player_faction.name] then\n\t\t\treturn not player_faction:has_permission(player, \"build\")\n\t\telse\n return not parcel_faction:parcel_is_attacked_by(parcelpos, player_faction)\n end\n else\n return true\n end\nend\n\nhudUpdate()\nfactionUpdate()"
},
{
"alpha_fraction": 0.4955882430076599,
"alphanum_fraction": 0.5061764717102051,
"avg_line_length": 28.059829711914062,
"blob_id": "180c5a928549001d63b4ebb3d76d6dfe889347fd",
"content_id": "19be02ddd31d43a219c4b7811ca8063a18fe0163",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 3401,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 117,
"path": "/mods/sscsm/minify.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- A primitive code minifier\n--\n-- Copyright © 2019 by luk3yx\n--\n\n-- Find multiple patterns\nlocal function find_multiple(text, ...)\n local n = select('#', ...)\n local s, e, pattern\n for i = 1, n do\n local p = select(i, ...)\n local s2, e2 = text:find(p)\n if s2 and (not s or s2 < s) then\n s, e, pattern = s2, e2 or s2, p\n end\n end\n return s, e, pattern\nend\n\n-- Matches\n-- These take 2-3 arguments (code, res, char) and should return code and res.\nlocal matches = {\n -- Handle multi-line strings\n ['%[=*%['] = function(code, res, char)\n res = res .. char\n char = char:sub(2, -2)\n local s, e = code:find(']' .. char .. ']', nil, true)\n if not s or not e then return code, res end\n return code:sub(e + 1), res .. code:sub(1, e)\n end,\n\n -- Handle regular comments\n ['--'] = function(code, res, char)\n local s, e = code:find('\\n', nil, true)\n if not s or not e then return '', res end\n\n -- Don't remove copyright or license information.\n if e >= 7 then\n local first_word = (code:match('^[ \\t]*(%w+)') or ''):lower()\n if first_word == 'copyright' or first_word == 'license' then\n return code:sub(s), res .. char .. code:sub(1, s - 1)\n end\n end\n\n -- Shift trailing spaces back\n local spaces = res:match('(%s*)$') or ''\n return spaces .. code:sub(s), res:sub(1, #res - #spaces)\n end,\n\n -- Handle multi-line comments\n ['%-%-%[=*%['] = function(code, res, char)\n char = char:sub(4, -2)\n local s, e = code:find(']' .. char .. ']', nil, true)\n if not s or not e then return code, res end\n\n -- Shift trailing spaces back\n local spaces = res:match('(%s*)$') or ''\n return spaces .. code:sub(e + 1), res:sub(1, #res - #spaces)\n end,\n\n -- Handle quoted text\n ['\"'] = function(code, res, char)\n res = res .. char\n\n -- Handle backslashes\n repeat\n local s, e, pattern = find_multiple(code, '\\\\', char)\n if pattern == char then\n res = res .. code:sub(1, e)\n code = code:sub(e + 1)\n elseif pattern then\n res = res .. code:sub(1, e + 1)\n code = code:sub(e + 2)\n end\n until not pattern or pattern == char\n\n return code, res\n end,\n\n ['%s*[\\r\\n]%s*'] = function(code, res, char)\n return code, res .. '\\n'\n end,\n\n ['[ \\t]+'] = function(code, res, char)\n return code, res .. ' '\n end,\n}\n\n-- Give the functions alternate names\nmatches[\"'\"] = matches['\"']\n\n-- The actual transpiler\nreturn function(code)\n assert(type(code) == 'string')\n\n local res = ''\n\n -- Split the code by \"tokens\"\n while true do\n -- Search for special characters\n local s, e, pattern = find_multiple(code, '[\\'\"\\\\]', '%-%-%[=*%[',\n '%-%-', '%[=*%[', '%s*[\\r\\n]%s*', '[ \\t]+')\n if not s then break end\n\n -- Add non-matching characters\n res = res .. code:sub(1, math.max(s - 1, 0))\n\n -- Call the correct function\n local char = code:sub(s, e)\n local func = matches[char] or matches[pattern]\n assert(func, 'No function found for pattern!')\n code, res = func(code:sub(e + 1), res, char)\n end\n\n return (res .. code):trim()\nend\n"
},
{
"alpha_fraction": 0.7490057349205017,
"alphanum_fraction": 0.7507733106613159,
"avg_line_length": 61.86111068725586,
"blob_id": "34dd695658bb35578648865b1df74b97611aa935",
"content_id": "0862543433cd9aeac0ae49676fcc5a55731a5a54",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2263,
"license_type": "permissive",
"max_line_length": 367,
"num_lines": 36,
"path": "/mods/advmarkers/README.md",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "# advmarkers (non-CSM)\n\nA marker/waypoint mod for Minetest.\n\nUnlike the [CSM], this mod is standalone, and conflicts with the marker mod.\n\n## How to use\n\n`advmarkers` introduces the following chatcommands:\n\n - `/mrkr`: Opens a formspec allowing you to display or delete markers. If you give this command a parameter (`h`/`here`, `t`/`there` or co-ordinates), it will set your HUD position to those co-ordinates.\n - `/add_mrkr`: Adds markers. You can use `.add_mrkr x,y,z Marker name` to add markers. Adding a marker with (exactly) the same name as another will overwrite the original marker. If you replace `x,y,z` with `here`, the marker will be set to your current position, and replacing it with `there` will set the marker to the last `.coords` position.\n - `/mrkr_export`: Exports your markers to an advmarkers string. Remember to not modify the text before copying it. You can use `/mrkr_export old` if you want an export string compatible with older versions of the advmarkers CSM (it should start with `M` instead of `J`). This old format does **not** work with this mod, so only use it if you know what you are doing!\n - `/mrkr_import`: Imports your markers from an advmarkers string (`.mrkr_import <advmarkers string>`). Any markers with the same name will not be overwritten, and if they do not have the same co-ordinates, `_` will be appended to the imported one.\n - `/mrkrthere`: Alias for `/mrkr there`.\n\nIf you die, a marker is automatically added at your death position, and will\nupdate the last `.coords` position.\n\n## Chat channels integration\n\nadvmarkers works with the `.coords` command from chat_channels ([GitHub],\n[GitLab]), even without chat channels installed. When someone does `.coords`,\nadvmarkers temporarily stores this position, and you can set a temporary marker\nat the `.coords` position with `/mrkrthere`, or add a permanent marker with\n`/add_mrkr there Marker name`.\n\n## SSCSM support\n\nWith my [SSCSM] mod installed, advmarkers will register a server-sent CSM to\nreduce visible lag in the markers GUI.\n\n[CSM]: https://git.minetest.land/luk3yx/advmarkers-csm\n[GitHub]: https://github.com/luk3yx/minetest-chat_channels\n[GitLab]: https://gitlab.com/luk3yx/minetest-chat_channels\n[SSCSM]: https://git.minetest.land/luk3yx/sscsm\n"
},
{
"alpha_fraction": 0.700440526008606,
"alphanum_fraction": 0.7035871744155884,
"avg_line_length": 31.10416603088379,
"blob_id": "ed982a7732119f6b4cb1989a25d146ac2d6f6bca",
"content_id": "145fadf44cbff40c5df19ee43bd46652f8630504",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 3178,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 96,
"path": "/mods/latency_protection/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "local players_position = {}\r\n\r\nlocal time_max = tonumber(minetest.settings:get(\"latency_protection.time_max\")) or 2000\r\n\r\nlocal function punishment_teleport()\r\n\tlocal timer = tonumber(minetest.settings:get(\"latency_protection.timer\")) or 20\r\n\tlocal jitter_max = tonumber(minetest.settings:get(\"latency_protection.jitter_max\")) or 1.5\r\n\r\n\tlocal function step()\r\n\t\tfor name, data in pairs(players_position) do\r\n\t\t\tlocal info = minetest.get_player_information(name)\r\n\t\t\tif not data.protection_violation and info.avg_jitter <= jitter_max then\r\n\t\t\t\tdata.pos = minetest.get_player_by_name(name):get_pos()\r\n\t\t\telse\r\n\t\t\t\tdata.protection_violation = false\r\n\t\t\tend\r\n\t\t\tplayers_position[name] = data\r\n\t\tend\r\n\t\tminetest.after(timer, step)\r\n\tend\r\n\r\n\tminetest.register_on_joinplayer(function(player)\r\n\t\tplayers_position[player:get_player_name()] = {pos = player:get_pos(), protection_violation = false, last_time = 0}\r\n\tend)\r\n\r\n\tminetest.register_on_leaveplayer(function(player)\r\n\t\tplayers_position[player:get_player_name()] = nil\r\n\tend)\r\n\r\n\tminetest.after(timer, step)\r\n\r\n\t-- It has to be registered later for it to work.\r\n\tminetest.register_on_mods_loaded(function()\r\n\t\tlocal old_is_protected = minetest.is_protected\r\n\r\n\t\tfunction minetest.is_protected(pos, name)\r\n\t\t\tlocal results = old_is_protected(pos, name)\r\n\t\t\tlocal player = minetest.get_player_by_name(name)\r\n\t\t\tif results and player then\r\n\t\t\t\tlocal data = players_position[name]\r\n\t\t\t\tlocal now = minetest.get_us_time()\r\n\t\t\t\t-- If is_protected is called too quickly from the previous call, the player will be teleported.\r\n\t\t\t\tif now - data.last_time <= time_max then\r\n\t\t\t\t\tplayer:set_pos(data.pos)\r\n\t\t\t\t\tdata.protection_violation = true\r\n\t\t\t\tend\r\n\t\t\t\tdata.last_time = now\r\n\t\t\t\tplayers_position[name] = data\r\n\t\t\tend\r\n\t\t\treturn results\r\n\t\tend\r\n\r\n\t\tminetest.register_on_respawnplayer(function(player)\r\n\t\t\tplayers_position[player:get_player_name()].pos = player:get_pos()\r\n\t\t\treturn false\r\n\t\tend)\r\n\tend)\r\nend\r\n\r\nlocal function punishment_damage()\r\n\tlocal damage = tonumber(minetest.settings:get(\"latency_protection.damage\")) or 3\r\n\t\r\n\tminetest.register_on_joinplayer(function(player)\r\n\t\tplayers_position[player:get_player_name()] = minetest.get_us_time()\r\n\tend)\r\n\r\n\tminetest.register_on_leaveplayer(function(player)\r\n\t\tplayers_position[player:get_player_name()] = nil\r\n\tend)\r\n\r\n\t-- It has to be registered later for it to work.\r\n\tminetest.register_on_mods_loaded(function()\r\n\t\tlocal old_is_protected = minetest.is_protected\r\n\r\n\t\tfunction minetest.is_protected(pos, name)\r\n\t\t\tlocal results = old_is_protected(pos, name)\r\n\t\t\tlocal player = minetest.get_player_by_name(name)\r\n\t\t\tif results and player then\r\n\t\t\t\tlocal now = minetest.get_us_time()\r\n\t\t\t\t-- If is_protected is called too quickly from the previous call, the player will be damaged.\r\n\t\t\t\tif now - players_position[name] <= time_max then\r\n\t\t\t\t\tminetest.log(\"LP: \" .. tostring(now - players_position[name]))\r\n\t\t\t\t\tplayer:set_hp(player:get_hp() - damage)\r\n\t\t\t\tend\r\n\t\t\t\tplayers_position[name] = now\r\n\t\t\tend\r\n\t\t\treturn results\r\n\t\tend\r\n\tend)\r\nend\r\n\r\nif minetest.settings:get(\"latency_protection.punishment\") == \"teleport\" then\r\n\tpunishment_teleport()\r\nelse\r\n\tpunishment_damage()\r\nend\r\n"
},
{
"alpha_fraction": 0.5519043803215027,
"alphanum_fraction": 0.5603684186935425,
"avg_line_length": 31.40322494506836,
"blob_id": "7e2bd8480b403f2630d2928dc4339dc6fbff4bc7",
"content_id": "7685b3dfe128047f4ab3e8862d884ddd0d19b581",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4017,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 124,
"path": "/mods/news/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "news = {}\n\nnews.chat_reasons = {}\nnews.chat_reasons.nodes = {}\nnews.chat_reasons.groups = {}\nnews.chat_reasons.set_hp = {\n \"mysteriously vanishes\",\n \"gave up on life\",\n \"evaporated into nothingness\",\n}\nnews.chat_reasons.punch = {\n \"was sliced' and diced' by\",\n \"got pwned by\",\n \"got a-salt-ed by\",\n}\nnews.chat_reasons.fall = {\n \"hit the ground to hard\",\n \"fell into the abyss\",\n \"walked off a cliff\",\n}\nnews.chat_reasons.drown = {\n \"fell asleep in the tub\",\n \"blew one to many bubbles\",\n \"tried to drink the ocean\",\n}\n\nminetest.register_privilege(\"news_report\", {give_to_admin = true})\n\nfunction news.register_deathmsg_tbl(type, name, msgs)\n if not (type or name or msgs) then\n return\n end\n\n if news.chat_reasons[type] then\n news.chat_reasons[type][name] = msgs\n end\nend\n\nminetest.register_on_dieplayer(function(obj, reason)\n if reason.type then\n local killer = \"\"\n local news_msg = \"\"\n local reason_msg = \"\"\n local player = obj:get_player_name()\n local node = minetest.registered_nodes[reason.node] or nil\n local num = nil\n\n if reason.type == \"node_damage\" and node then\n if node and news.chat_reasons.nodes[node.name] and #news.chat_reasons.nodes[node.name] > 0 then\n num = math.random(1, #news.chat_reasons.nodes[node.name])\n reason_msg = news.chat_reasons.nodes[node.name][num]\n elseif node and node.groups then\n for _, groupname in pairs(node.groups) do\n if news.chat_reasons.groups[groupname] and #news.chat_reasons.groups[groupname] > 0 then\n num = math.random(1, #news.chat_reasons.groups[groupname])\n reason_msg = news.chat_reasons.groups[groupname][num]\n break\n end\n end\n end\n elseif news.chat_reasons[reason.type] and #news.chat_reasons[reason.type] > 0 then\n num = math.random(1, #news.chat_reasons[reason.type])\n reason_msg = news.chat_reasons[reason.type][num]\n end\n\n if reason.object then\n if reason.object:is_player() then\n killer = reason.object:get_player_name()\n else\n killer = reason.object:get_luaentity().name\n end\n\n news_msg = \" BREAKING NEWS: Local player \\\"\" .. player .. \"\\\" \" .. reason_msg .. \" \\\"\" .. killer .. \"\\\".\"\n else\n news_msg = \" BREAKING NEWS: Local player \\\"\" .. player .. \"\\\" \" .. reason_msg .. \".\"\n end\n\n local station = \"[BBC News]\"\n station = minetest.colorize(\"#a8659c\", station)\n\n news_msg = minetest.colorize(\"#7f99b1\", news_msg)\n\n minetest.chat_send_all(station .. news_msg)\n end\nend)\n\n\nminetest.register_chatcommand(\"news\", {\n privs = {\n news_report = true\n },\n func = function(station, param)\n local station, news_msg = string.match(param, \"^([%d%a_-]+) ([%d%a%s%p%%_-]+)$\")\n local bool = string.sub(param, -1, -1)\n\n if station and news_msg then\n \n station = minetest.colorize(\"#a8659c\", \"[\" .. string.upper(station) .. \" News\" .. \"]\")\n \n if bool and bool == \"$\" then\n news_msg = \"BREAKING NEWS: \" .. string.sub(news_msg, 1, #news_msg - 1)\n end\n \n news_msg = minetest.colorize(\"#7f99b1\", news_msg)\n\n minetest.chat_send_all(station .. \" \" .. news_msg)\n else\n local station = \"[BBC News] \"\n station = minetest.colorize(\"#a8659c\", station)\n\n local news_msg = \"BREAKING NEWS: Salt levels rising.\"\n news_msg = minetest.colorize(\"#7f99b1\", news_msg)\n\n minetest.chat_send_all(station .. news_msg)\n end\n end\n})\n\nnews.register_deathmsg_tbl(\"nodes\", \"default:lava_source\", \n{\n \"melted into a ball of fire\",\n \"couldn't resist the warm glow of lava\",\n \"dug straight down\"\n})"
},
{
"alpha_fraction": 0.6566339135169983,
"alphanum_fraction": 0.6836609244346619,
"avg_line_length": 53.266666412353516,
"blob_id": "4df2b70fdc07ada3ceef851f4e25594eb486e90e",
"content_id": "535e67eecab8ede2191c5cab5663e7410d217d29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1628,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 30,
"path": "/mods/factions/config.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-------------------------------------------------------------------------------\n-- factions Mod by Sapier\n--\n-- License WTFPL\n--\n--! @file config.lua\n--! @brief settings file\n--! @copyright Coder12a\n--! @author Coder12a\n--! @date 2018-03-13\n--\n-- Contact sapier a t gmx net\n-------------------------------------------------------------------------------\n\nconfig = {}\nconfig.protection_max_depth = tonumber(minetest.settings:get(\"protection_max_depth\")) or -20\nconfig.siege_max_height = tonumber(minetest.settings:get(\"siege_max_height\")) or 160\nconfig.power_per_parcel = tonumber(minetest.settings:get(\"power_per_parcel\")) or 1\nconfig.power_per_death = tonumber(minetest.settings:get(\"power_per_death\")) or 0.25\nconfig.power_per_tick = tonumber(minetest.settings:get(\"power_per_tick\")) or 0.125\nconfig.tick_time = tonumber(minetest.settings:get(\"tick_time\")) or 60\nconfig.power_per_attack = tonumber(minetest.settings:get(\"power_per_attack\")) or 4\nconfig.faction_name_max_length = tonumber(minetest.settings:get(\"faction_name_max_length\")) or 50\nconfig.rank_name_max_length = tonumber(minetest.settings:get(\"rank_name_max_length\")) or 25\nconfig.maximum_faction_inactivity = tonumber(minetest.settings:get(\"maximum_faction_inactivity\")) or 604800\nconfig.power = tonumber(minetest.settings:get(\"power\")) or 1\nconfig.maxpower = tonumber(minetest.settings:get(\"maxpower\")) or 4\nconfig.power_per_banner = tonumber(minetest.settings:get(\"power_per_banner\")) or 1\nconfig.attack_parcel = minetest.settings:get_bool(\"attack_parcel\") or false\nconfig.siege_banner_interval = tonumber(minetest.settings:get(\"siege_banner_interval\")) or 150\n"
},
{
"alpha_fraction": 0.6498156785964966,
"alphanum_fraction": 0.6519220471382141,
"avg_line_length": 35.528846740722656,
"blob_id": "0689c923752a59036fd8a0331e5d3c11bbe046e0",
"content_id": "3fd4906687f6bd812ac39b6c4504f735f17111fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 3798,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 104,
"path": "/mods/factions/banner.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-- nodes\n--[[minetest.register_node(\"factions:power_banner\", {\n drawtype = \"normal\",\n tiles = {\"power_banner.png\"},\n description = \"Power Banner\",\n groups = {cracky=3},\n diggable = true,\n stack_max = 1,\n paramtype = \"light\",\n paramtype2 = \"facedir\",\n after_place_node = function (pos, player, itemstack, pointed_thing)\n after_powerbanner_placed(pos, player, itemstack, pointed_thing)\n end,\n on_dig = function(pos, n, p)\n if minetest.is_protected(pos, p:get_player_name()) then\n return\n end\n local meta = minetest.get_meta(pos)\n local facname = meta:get_string(\"faction\")\n if facname then\n local faction = factions.factions[facname]\n if faction then\n faction:decrease_maxpower(config.power_per_banner)\n end\n end\n\t\tminetest.node_dig(pos, n, p)\n end,\n})]]\n\nminetest.register_node(\"factions:death_banner\", {\n drawtype = \"normal\",\n tiles = {\"death_banner.png\"},\n description = \"Death Banner\",\n groups = {cracky=3},\n diggable = true,\n stack_max = 1,\n paramtype = \"light\",\n paramtype2 = \"facedir\",\n after_place_node = function (pos, player, itemstack, pointed_thing)\n after_deathbanner_placed(pos, player, itemstack, pointed_thing)\n end,\n on_dig = function(pos, n, p)\n if minetest.is_protected(pos, p:get_player_name()) then\n return\n end\n local meta = minetest.get_meta(pos)\n local defending_facname = meta:get_string(\"faction\")\n local parcelpos = factions.get_parcel_pos(pos)\n if defending_facname then\n local faction = factions.factions[defending_facname]\n if faction then\n faction:stop_attack(parcelpos)\t\n end\n end\n minetest.remove_node(pos)\n end,\n})\n\n--[[after_powerbanner_placed = function(pos, player, itemstack, pointed_thing)\n --minetest.get_node(pos).param2 = determine_flag_direction(pos, pointed_thing)\n local faction = factions.players[player:get_player_name()]\n if not faction then\n minetest.get_meta(pos):set_string(\"banner\", \"bg_white.png\")\n else\n local banner_string = \"bg_white.png\"--factions[faction].banner\n minetest.get_meta(pos):set_string(\"banner\", banner_string)\n minetest.get_meta(pos):set_string(\"faction\", faction)\n factions.factions[faction]:increase_maxpower(config.power_per_banner)\n end\nend]]\n\nafter_deathbanner_placed = function(pos, player, itemstack, pointed_thing)\n -- minetest.get_node(pos).param2 = determine_flag_direction(pos, pointed_thing)\n local attacking_faction = factions.players[player:get_player_name()]\n if attacking_faction ~= nil then\n local parcelpos = factions.get_parcel_pos(pos)\n attacking_faction = factions.factions[attacking_faction]\n if not attacking_faction:attack_parcel(parcelpos) then return false end\n minetest.get_meta(pos):set_string(\"faction\", attacking_faction.name)\n end\n minetest.get_meta(pos):set_string(\"banner\", \"death_uv.png\")\nend\n\n--[[if minetest.get_modpath(\"default\") then\n\tminetest.register_craft({\n\t\toutput = 'factions:power_banner',\n\t\trecipe = {\n\t\t\t{'default:mese_crystal','default:mese_crystal','default:mese_crystal'},\n\t\t\t{'default:mese_crystal','default:diamondblock','default:mese_crystal'},\n\t\t\t{'default:mese_crystal','default:mese_crystal','default:mese_crystal'}\n\t\t}\n\t})\nend]]\n\nif minetest.get_modpath(\"default\") and minetest.get_modpath(\"bones\") then\n\tminetest.register_craft({\n\t\toutput = 'factions:death_banner',\n\t\trecipe = {\n\t\t\t{'default:obsidian','default:obsidian','default:obsidian'},\n\t\t\t{'default:obsidian','bones:bones','default:obsidian'},\n\t\t\t{'default:obsidian','default:obsidian','default:obsidian'}\n\t\t}\n\t})\nend"
},
{
"alpha_fraction": 0.6470588445663452,
"alphanum_fraction": 0.6490195989608765,
"avg_line_length": 24.549999237060547,
"blob_id": "107a25fe9f1f979a1809dbe850d978502d8e4ccc",
"content_id": "f0a265f4870534c3fb38eb6d894cdfe17b2d97fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 510,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 20,
"path": "/mods/whinny/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "dofile(minetest.get_modpath(\"whinny\")..\"/api.lua\")\ndofile(minetest.get_modpath(\"whinny\")..\"/horse.lua\")\n--[[\nminetest.register_craftitem(\"whinny:meat\", {\n description = \"Cooked Meat\",\n inventory_image = \"whinny_meat.png\",\n on_use = minetest.item_eat(4),\n})\n\nminetest.register_craftitem(\"whinny:meat_raw\", {\n description = \"Raw Meat\",\n inventory_image = \"whinny_meat_raw.png\",\n})\n\nminetest.register_craft({\n type = \"cooking\",\n output = \"whinny:meat\",\n recipe = \"whinny:meat_raw\",\n})\n--]]"
},
{
"alpha_fraction": 0.70652174949646,
"alphanum_fraction": 0.7146739363670349,
"avg_line_length": 18.891891479492188,
"blob_id": "b9aed38ab718410a077088d06ba6ff72be9b37e1",
"content_id": "37beb8bc88aec6b9b8408b53dd9240180a4f5eb7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 736,
"license_type": "permissive",
"max_line_length": 151,
"num_lines": 37,
"path": "/mods/lava_ore_gen/README.md",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "# lava_ore_gen\n\nThis mod makes the lava turn stone into ore over time. When lava comes in contact with stone it turns red hot. After a specific time it turns into ore.\n\n# api\n\nlava_ore_gen.blacklist is a table where you can blacklist node names by listing them in the table.\n\nExample code:\n\n``` lua\nlava_ore_gen.blacklist[\"default:stone_with_iron\"] = true\n```\n\n\n# config\n\nThe stone node name to override.\n``` lua\nlava_ore_gen.stone_name = \"default:stone\"\n```\n\nfixed interval of when to change stone to ore.\n``` lua\nlava_ore_gen.interval = 20\n```\n\n\nrandom chance of when to change stone to ore.\n``` lua\nlava_ore_gen.chance = 3600\n```\n\nMake ores random instead of being based on how rare they are.\n``` lua\nlava_ore_gen.random = false\n```\n"
},
{
"alpha_fraction": 0.6969696879386902,
"alphanum_fraction": 0.6969696879386902,
"avg_line_length": 23.090909957885742,
"blob_id": "aebd10faa49cff0db109474c4725313841461616",
"content_id": "d59d042b44c74c7a447c69ca3a243430c2e9ce85",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 264,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 11,
"path": "/mods/tnt/disable_msg/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "minetest.register_chatcommand(\"msg\", {\n\tfunc = function(name, param)\n\t\tminetest.chat_send_player(name, \"/msg is disabled!!\")\n\tend\n})\n\nminetest.register_chatcommand(\"me\", {\n\tfunc = function(name, param)\n\t\tminetest.chat_send_player(name, \"/me is disabled!!\")\n\tend\n})"
},
{
"alpha_fraction": 0.5720899701118469,
"alphanum_fraction": 0.5945767164230347,
"avg_line_length": 31.727272033691406,
"blob_id": "ff0009076982231b21cc1f6499e05a0c9cbbee2e",
"content_id": "96c4b6d5c133694022ad8887961bdbb272fcf3fa",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 7560,
"license_type": "permissive",
"max_line_length": 165,
"num_lines": 231,
"path": "/mods/signs/steelsign.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-- Font: 04.jp.org\n\n-- load characters map\nlocal chars_file = io.open(minetest.get_modpath(\"signs\")..\"/characters\", \"r\")\nlocal charmap = {}\nlocal max_chars = 16\nif not chars_file then\n print(\"[signs] E: character map file not found\")\nelse\n while true do\n local char = chars_file:read(\"*l\")\n if char == nil then\n break\n end\n local img = chars_file:read(\"*l\")\n chars_file:read(\"*l\")\n charmap[char] = img\n end\nend\n\nlocal signs = {\n {delta = {x = 0, y = 0, z = 0.399}, yaw = 0},\n {delta = {x = 0.399, y = 0, z = 0}, yaw = math.pi / -2},\n {delta = {x = 0, y = 0, z = -0.399}, yaw = math.pi},\n {delta = {x = -0.399, y = 0, z = 0}, yaw = math.pi / 2},\n}\n\nlocal signs_yard = {\n {delta = {x = 0, y = 0, z = -0.05}, yaw = 0},\n {delta = {x = -0.05, y = 0, z = 0}, yaw = math.pi / -2},\n {delta = {x = 0, y = 0, z = 0.05}, yaw = math.pi},\n {delta = {x = 0.05, y = 0, z = 0}, yaw = math.pi / 2},\n}\n\nlocal sign_groups = {choppy=2, dig_immediate=2}\n\nlocal construct_sign = function(pos)\n local meta = minetest.env:get_meta(pos)\n\tmeta:set_string(\"formspec\", \"field[text;;${text}]\")\n\tmeta:set_string(\"infotext\", \"\")\nend\n\nlocal destruct_sign = function(pos)\n local objects = minetest.env:get_objects_inside_radius(pos, 0.5)\n for _, v in ipairs(objects) do\n if v:get_entity_name() == \"signs:text\" then\n v:remove()\n end\n end\nend\n\nlocal update_sign = function(pos, fields)\n local meta = minetest.env:get_meta(pos)\n\tif fields then\n\t\tmeta:set_string(\"text\", fields.text)\n\tend\n local text = meta:get_string(\"text\")\n local objects = minetest.env:get_objects_inside_radius(pos, 0.5)\n for _, v in ipairs(objects) do\n if v:get_entity_name() == \"signs:text\" then\n v:set_properties({textures={generate_texture(create_lines(text))}})\n\t\t\treturn\n end\n end\n\t\n\t-- if there is no entity\n\tlocal sign_info\n\tif minetest.env:get_node(pos).name == \"signs:sign_yard_steel\" then\n\t\tsign_info = signs_yard[minetest.env:get_node(pos).param2 + 1]\n\telseif minetest.env:get_node(pos).name == \"default:sign_wall_steel\" then\n\t\tsign_info = signs[minetest.env:get_node(pos).param2 + 1]\n\tend\n\tif sign_info == nil then\n\t\treturn\n\tend\n\tlocal text = minetest.env:add_entity({x = pos.x + sign_info.delta.x,\n\t\t\t\t\t\t\t\t\t\ty = pos.y + sign_info.delta.y,\n\t\t\t\t\t\t\t\t\t\tz = pos.z + sign_info.delta.z}, \"signs:text\")\n\ttext:setyaw(sign_info.yaw)\nend\n\nminetest.register_node(\":default:sign_wall_steel\", {\n description = \"Locked Sign\",\n inventory_image = \"signs_locked_inv.png\",\n wield_image = \"signs_locked_inv.png\",\n node_placement_prediction = \"\",\n paramtype = \"light\",\n\tsunlight_propagates = true,\n paramtype2 = \"facedir\",\n drawtype = \"nodebox\",\n node_box = {type = \"fixed\", fixed = {-0.45, -0.15, 0.4, 0.45, 0.45, 0.498}},\n selection_box = {type = \"fixed\", fixed = {-0.45, -0.15, 0.4, 0.45, 0.45, 0.498}},\n tiles = {\"signs_locked_top.png\", \"signs_locked_bottom.png\", \"signs_locked_side.png\", \"signs_locked_side.png\", \"signs_locked_back.png\", \"signs_locked_front.png\"},\n groups = sign_groups,\n\n on_place = function(itemstack, placer, pointed_thing)\n local above = pointed_thing.above\n local under = pointed_thing.under\n\t\t\t\n\tpname = placer:get_player_name()\n\tif minetest.is_protected(above, pname) then\n\t\tminetest.record_protection_violation(above, pname)\n\t\treturn itemstack\n\tend\n\t\t\n local dir = {x = under.x - above.x,\n y = under.y - above.y,\n z = under.z - above.z}\n\n local wdir = minetest.dir_to_wallmounted(dir)\n\n local placer_pos = placer:getpos()\n if placer_pos then\n dir = {\n x = above.x - placer_pos.x,\n y = above.y - placer_pos.y,\n z = above.z - placer_pos.z\n }\n end\n\n local fdir = minetest.dir_to_facedir(dir)\n\n local sign_info\n\t\t\n\t\tif minetest.env:get_node(above).name == \"air\" then\n\t\t\n if wdir == 0 then\n --how would you add sign to ceiling?\n minetest.env:add_item(above, \"default:sign_wall_steel\")\n\t\t\titemstack:take_item()\n\t\t\treturn itemstack\n elseif wdir == 1 then\n minetest.env:add_node(above, {name = \"signs:sign_yard_steel\", param2 = fdir})\n sign_info = signs_yard[fdir + 1]\n else\n minetest.env:add_node(above, {name = \"default:sign_wall_steel\", param2 = fdir})\n sign_info = signs[fdir + 1]\n end\n\n local text = minetest.env:add_entity({x = above.x + sign_info.delta.x,\n y = above.y + sign_info.delta.y,\n z = above.z + sign_info.delta.z}, \"signs:text\")\n text:setyaw(sign_info.yaw)\n\t\t\n\t\tlocal meta = minetest.get_meta(above)\n\t\tlocal owner = placer:get_player_name()\n\t\tmeta:set_string(\"owner\", owner)\n\t\tmeta:set_string(\"infotext\", (\"Locked sign (Owned by \"..owner..\")\"))\n\t\t\n\t\titemstack:take_item()\n return itemstack\n\t\tend\n end,\n\tcan_dig = function(pos,player)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\treturn player:get_player_name() == owner or owner == \"\"\n\tend,\n on_construct = function(pos)\n construct_sign(pos)\n end,\n on_destruct = function(pos)\n destruct_sign(pos)\n end,\n on_receive_fields = function(pos, formname, fields, sender)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\tif sender:get_player_name() == owner or owner == \"\" then\t\t\n\t\t\tupdate_sign(pos, fields)\n\t\tend\n end,\n\ton_punch = function(pos, node, puncher)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\tif puncher:get_player_name() == owner or owner == \"\" then\t\t\n\t\t\tupdate_sign(pos, fields)\n\t\tend\n\tend,\n})\n\nminetest.register_node(\"signs:sign_yard_steel\", {\n paramtype = \"light\",\n\tsunlight_propagates = true,\n paramtype2 = \"facedir\",\n drawtype = \"nodebox\",\n node_box = {type = \"fixed\", fixed = {\n {-0.45, -0.15, -0.049, 0.45, 0.45, 0.049},\n {-0.05, -0.5, -0.049, 0.05, -0.15, 0.049}\n }},\n selection_box = {type = \"fixed\", fixed = {-0.45, -0.15, -0.049, 0.45, 0.45, 0.049}},\n tiles = {\"signs_locked_top.png\", \"signs_locked_bottom.png\", \"signs_locked_side.png\", \"signs_locked_side.png\", \"signs_locked_back.png\", \"signs_locked_front.png\"},\n groups = {choppy=2, dig_immediate=2},\n drop = \"default:sign_wall_steel\",\n\tcan_dig = function(pos,player)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\treturn player:get_player_name() == owner or owner == \"\"\n\tend,\n on_construct = function(pos)\n construct_sign(pos)\n end,\n on_destruct = function(pos)\n destruct_sign(pos)\n end,\n on_receive_fields = function(pos, formname, fields, sender)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\tif sender:get_player_name() == owner or owner == \"\" then\t\t\n\t\t\tupdate_sign(pos, fields)\n\t\tend\n end,\n\ton_punch = function(pos, node, puncher)\n\t\tlocal meta = minetest.get_meta(pos);\n\t\tlocal owner = meta:get_string(\"owner\")\n\t\tif puncher:get_player_name() == owner or owner == \"\" then\t\t\n\t\t\tupdate_sign(pos, fields)\n\t\tend\n\tend,\n})\n\nminetest.register_craft({\n\toutput = \"default:sign_wall_steel 3\",\n\trecipe = {\n\t\t{\"default:sign_wall_wood\", \"default:sign_wall_wood\", \"default:sign_wall_wood\"},\n\t\t{\"\", \"default:steel_ingot\", \"\"}\n\t}\n})\n\nif minetest.setting_get(\"log_mods\") then\n\tminetest.log(\"action\", \"locked signs loaded\")\nend\n"
},
{
"alpha_fraction": 0.6246973276138306,
"alphanum_fraction": 0.6246973276138306,
"avg_line_length": 26.53333282470703,
"blob_id": "255940fc2aeeca12dfb45ca2162eaae74fa9b38b",
"content_id": "ffd9dc14954e22353b3a262d3e43ab8e8ccb011b",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 413,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 15,
"path": "/mods/player_textures/README.txt",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "Player Textures Mod for Minetest\n================================\n\nThis mod allows players to use different textures. Just place the texture in\nthe player_textures/textures/ folder like this:\nplayer_<player_name>.png\nand the player with the name <player_name> will have this textures.\n\nLicense of source code:\n-----------------------\nWTFPL\n\nLicense of the example textures:\n--------------------------------\nWTFPL\n"
},
{
"alpha_fraction": 0.5869886875152588,
"alphanum_fraction": 0.5958600044250488,
"avg_line_length": 23.445783615112305,
"blob_id": "201db3c04bf0b1f5b3fcdc7e200a9d742b88c775",
"content_id": "da5897bfd9ff2c452a2900a233f3844837a070b4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 2030,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 83,
"path": "/mods/sscsm/sscsm_testing.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- SSCSM: Server-Sent Client-Side Mods proof-of-concept\n-- Testing code\n--\n-- Copyright © 2019 by luk3yx\n-- License: https://git.minetest.land/luk3yx/sscsm/src/branch/master/LICENSE.md\n--\n\n--[==[\nerror(\"Bad\")\n]==]\n\n-- Make sure the minifier is sane\na = 0\n--[[\na = a + 1\n--]]\n\n-- [[\na = a + 2\n--]]\n\n--;a = a + 4\n\na = a + #('Test message with \\'\"quotes\"\\' .')\n\nassert(a == 37, 'The minifier is breaking code!')\n\n-- Create a few chatcommands\nsscsm.register_chatcommand('error_test', function(param)\n error('Testing: ' .. param)\nend)\n\nsscsm.register_chatcommand('sscsm', {\n func = function(param)\n return true, 'Hello from the SSCSM!'\n end,\n})\n\nsscsm.register_chatcommand('slap', function(param)\n if param:gsub(' ', '') == '' then\n return false, 'Invalid usage. Usage: ' .. minetest.colorize('#00ffff',\n '/slap <victim>') .. '.'\n end\n\n minetest.run_server_chatcommand('me', 'slaps ' .. param ..\n ' around a bit with a large trout.')\nend)\n\n-- A potentially useful example\nsscsm.register_chatcommand('msg', function(param)\n -- If you're actually using this, remove this.\n assert(param ~= '<error>', 'Test')\n\n local sendto, msg = param:match('^(%S+)%s(.+)$')\n if not sendto then\n return false, 'Invalid usage, see ' .. minetest.colorize('#00ffff',\n '/help msg') .. '.'\n end\n\n minetest.run_server_chatcommand('msg', param)\nend)\n\nsscsm.register_chatcommand('privs', function(param)\n if param == '' and minetest.get_privilege_list then\n local privs = {}\n for priv, n in pairs(minetest.get_privilege_list()) do\n if n then\n table.insert(privs, priv)\n end\n end\n table.sort(privs)\n return true, minetest.colorize('#00ffff', 'Privileges of ' ..\n minetest.localplayer:get_name() .. ': ') .. table.concat(privs, ' ')\n end\n\n minetest.run_server_chatcommand('privs', param)\nend)\n\n-- Create yay() to test dependencies\nfunction yay()\n print('yay() called')\nend\n"
},
{
"alpha_fraction": 0.5725388526916504,
"alphanum_fraction": 0.5958549380302429,
"avg_line_length": 23.1875,
"blob_id": "29b60ca1923b2ea7d6c33b59cd0d7f3c0bd214ed",
"content_id": "b85061d2a714966ab8f9858493ade206cada484c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 386,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 16,
"path": "/mods/addcrosshair/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "local function setflags(player)\n\tplayer:hud_set_flags({crosshair=false})\nend\nminetest.register_on_joinplayer(function(player)\n\n\tlocal hud = player:hud_add({\n\t\thud_elem_type = \"image\",\n\t\tposition = {x = .5, y = .5},\n\t\toffset = {x = 0, y = 0},\n\t\ttext = \"crosshair.png\",\n\t\tscale = { x = 1, y = 1},\n\t\talignment = { x = 0, y = 0 },\n\t})\n\tminetest.after(0, setflags, player)\n\nend)"
},
{
"alpha_fraction": 0.5369963645935059,
"alphanum_fraction": 0.5583333373069763,
"avg_line_length": 31.117647171020508,
"blob_id": "9d48c93fb8d17fd4ae6b2d2c54145bb840febdd1",
"content_id": "50b4107dd201c501d6a4e77740f44d157a6aad90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 10920,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 340,
"path": "/mods/whinny/horse.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "local function is_ground(pos)\n local nn = minetest.get_node(pos).name\n return minetest.get_item_group(nn, \"crumbly\") ~= 0 or\n minetest.get_item_group(nn, \"cracky\") ~= 0 or\n minetest.get_item_group(nn, \"choppy\") ~= 0 or\n minetest.get_item_group(nn, \"snappy\") ~= 0\nend\n\nlocal function get_sign(i)\n if i == 0 then\n return 0\n else\n return i/math.abs(i)\n end\nend\n\nlocal function get_velocity(speed, yaw, y)\n local x = math.cos(yaw)*speed\n local z = math.sin(yaw)*speed\n return {x=x, y=y, z=z}\nend\n\nlocal function get_speed(velocity)\n return math.sqrt(velocity.x^2+velocity.z^2)\nend\n\n-- ===================================================================\n\nlocal function register_wildhorse (basename)\nwhinny:register_mob (\"whinny:horse\"..basename, {\n type = \"animal\",\n hp_min = 10,\n hp_max = 10,\n collisionbox = {-.45, -0.01, -.45, .45, 1.4, .45},\n available_textures = {\n total = 1,\n texture_1 = {\"whinny_horse\"..basename..\".png\"},\n },\n visual = \"mesh\",\n drops = {\n {name = \"creatures:flesh\",\n chance = 1,\n min = 2,\n max = 3,},\n },\n mesh = \"horsemob.x\",\n makes_footstep_sound = true,\n walk_velocity = 1,\n armor = 100,\n drawtype = \"front\",\n water_damage = 1,\n lava_damage = 5,\n light_damage = 0,\n sounds = {\n random = \"\",\n },\n animation = {\n speed_normal = 20,\n stand_start = 300,\n stand_end = 460,\n walk_start = 10,\n walk_end = 60\n },\n follow = \"farming:wheat\",\n view_range = 5,\n on_rightclick = function(self, clicker)\n local item = clicker:get_wielded_item()\n if item:get_name() == \"farming:wheat\" then\n minetest.add_entity (self.object:getpos(),\n\"whinny:horse\"..basename..\"h1\")\n if not minetest.setting_getbool(\"creative_mode\") then\n item:take_item()\n clicker:set_wielded_item(item)\n end\n self.object:remove()\n end\n end,\n jump = true,\n step=1,\n passive = true,\n})\nend\n\n-- ===================================================================\n\nlocal function register_basehorse(name, craftitem, horse)\n if craftitem ~= nil then\n function craftitem.on_place(itemstack, placer, pointed_thing)\n if pointed_thing.above then\n minetest.env:add_entity(pointed_thing.above, name)\n if not minetest.setting_getbool(\"creative_mode\") then\n itemstack:take_item()\n end\n end\n return itemstack\n end\n minetest.register_craftitem(name, craftitem)\n end\n\n function horse:set_animation(type)\n if type == self.animation_current then \n\t\t\treturn\n\t\tend\n if type == self.animation.mode_stand then\n if\n self.animation.stand_start\n and self.animation.stand_end\n and self.animation.speed_normal\n then\n self.object:set_animation(\n {x=self.animation.stand_start,y=self.animation.stand_end},\n self.animation.speed_normal * 0.6, 0\n )\n self.animation_current = self.animation.mode_stand\n end\n elseif type == self.animation.mode_walk then\n if\n self.animation.walk_start\n and self.animation.walk_end\n and self.animation.speed_normal\n then\n self.object:set_animation(\n {x=self.animation.walk_start,y=self.animation.walk_end},\n self.animation.speed_normal * 3, 0\n )\n self.animation_current = self.animation.mode_walk\n end\n\t\telseif type == self.animation.mode_gallop then\n if\n self.animation.gallop_start\n and self.animation.gallop_end\n and self.animation.speed_normal\n then\n self.object:set_animation(\n {x=self.animation.gallop_start,y=self.animation.gallop_end},\n self.animation.speed_normal * 2, 0\n )\n self.animation_current = self.animation.mode_gallop\n end\n end\n end\n\n function horse:on_step(dtime)\n local p = self.object:getpos()\n p.y = p.y - 0.1\n local on_ground = is_ground(p)\n\t\tlocal inside_block = self.object:getpos()\n\t\tinside_block.y = inside_block.y + 1\n\n self.speed = get_speed(self.object:getvelocity())*get_sign(self.speed)\n\n -- driver controls\n if self.driver then\n local ctrl = self.driver:get_player_control()\n\n -- rotation (the faster we go, the less we rotate)\n if ctrl.left then\n self.object:setyaw(self.object:getyaw()+3*(2-math.abs(self.speed/self.max_speed))*math.pi/90 +dtime*math.pi/90)\n end\n if ctrl.right then\n self.object:setyaw(self.object:getyaw()-3*(2-math.abs(self.speed/self.max_speed))*math.pi/90 -dtime*math.pi/90)\n end\n -- jumping (only if on ground)\n\t\t\t\n\t\t\tif ctrl.jump then\n\t\t\t\tif on_ground then\n\t\t\t\t\tlocal v = self.object:getvelocity()\n\t\t\t\t\tlocal vel = 3\n-- \t v.y = (self.jump_speed or 3)\n\t\t\t\t\tv.y = vel\n\t\t\t\t\tself.object:setvelocity(v)\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t-- forwards/backwards\n\t\t\tif ctrl.up then\n\t\t\t\tself.speed = self.speed + self.forward_boost\n\t\t\telseif ctrl.down then\n\t\t\t\tif self.speed >= -2.9 then\n\t\t\t\t\tself.speed = self.speed - self.forward_boost\n\t\t\t\tend\n\t\t\telseif self.speed < 3 then\n\t\t\t\t--decay speed if not going fast\n\t\t\t\tself.speed = self.speed * 0.85\n\t\t\tend\n else\n if math.abs(self.speed) < 1 then\n self.speed = 0\n else\n self.speed = self.speed * 0.90\n end\n end\n\n if math.abs(self.speed) < 1 then\n self.object:setvelocity({x=0,y=0,z=0})\n self:set_animation(self.animation.mode_stand)\n elseif self.speed > 5 then\n\t\t\tself:set_animation(self.animation.mode_gallop)\n\t\telse\n\t\t\tself:set_animation(self.animation.mode_walk)\n\t\tend\n\n -- make sure we don't go past the limit\n\t\tif minetest.get_item_group(minetest.get_node(inside_block).name, \"water\") ~= 0 then\n\t\t\tif math.abs(self.speed) > self.max_speed * .2 then\n\t\t\t\tself.speed = self.max_speed*get_sign(self.speed)*.2\n\t\t\tend\n\t\telse\n\t\t\tif math.abs(self.speed) > self.max_speed then\n\t\t\t\tself.speed = self.max_speed*get_sign(self.speed)\n\t\t\tend\n\t\tend\n\n local p = self.object:getpos()\n p.y = p.y+1\n if not is_ground(p) then\n if minetest.registered_nodes[minetest.get_node(p).name].walkable then\n self.speed = 0\n end\n self.object:setacceleration({x=0, y=-10, z=0})\n self.object:setvelocity(get_velocity(self.speed, self.object:getyaw(), self.object:getvelocity().y))\n else\n self.object:setacceleration({x=0, y=0, z=0})\n -- falling\n if math.abs(self.object:getvelocity().y) < 1 then\n local pos = self.object:getpos()\n pos.y = math.floor(pos.y)+0.5\n self.object:setpos(pos)\n self.object:setvelocity(get_velocity(self.speed, self.object:getyaw(), 0))\n else\n self.object:setvelocity(get_velocity(self.speed, self.object:getyaw(), self.object:getvelocity().y))\n end\n end\n\n if self.object:getvelocity().y > 0.1 then\n local yaw = self.object:getyaw()\n if self.drawtype == \"side\" then\n yaw = yaw+(math.pi/2)\n end\n local x = math.sin(yaw) * -2\n local z = math.cos(yaw) * 2\n if minetest.get_item_group(minetest.get_node(inside_block).name, \"water\") ~= 0 then\n self.object:setacceleration({x = x, y = .1, z = z})\n else\n self.object:setacceleration({x = x, y = -10, z = z})\n end\n else\n if minetest.get_item_group(minetest.get_node(inside_block).name, \"water\") ~= 0 then\n self.object:setacceleration({x = 0, y = .1, z = 0})\n else\n self.object:setacceleration({x = 0, y = -10, z = 0})\n end\n end\n\n end\n\n function horse:on_rightclick(clicker)\n if not clicker or not clicker:is_player() then\n return\n end\n if self.driver and clicker == self.driver then\n self.driver = nil\n clicker:set_detach()\n\t\t\tclicker:set_eye_offset({x=0, y=0, z=0}, {x=0, y=0, z=0})\n elseif not self.driver then\n self.driver = clicker\n clicker:set_attach(self.object, \"\", {x=0,y=9,z=0}, {x=0,y=90,z=0})\n\t\t\tclicker:set_eye_offset({x=0, y=8, z=0}, {x=0, y=0, z=0})\n --self.object:setyaw(clicker:get_look_yaw())\n end\n end\n\n function horse:on_activate(staticdata, dtime_s)\n self.object:set_armor_groups({fleshy=100})\n if staticdata then\n self.speed = tonumber(staticdata)\n end\n end\n\n function horse:get_staticdata()\n return tostring(self.speed)\n end\n\n function horse:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)\n\tif self.driver then\n\t\tif self.object:get_hp() <= 5 then\n self.driver:set_detach()\n\t\t\tself.driver:set_eye_offset({x=0, y=0, z=0}, {x=0, y=0, z=0})\n\t\t\tself.driver = nil\n\t\t\tend\n\t\tend\n end\n\n minetest.register_entity(name, horse)\nend\n\nlocal function register_tamehorse (basename, description)\nregister_basehorse(\"whinny:horse\"..basename..\"h1\", {\n description = description,\n inventory_image = \"whinny_horse\"..basename..\"_inventory.png\",},{\n physical = true,\n collisionbox = {-.45, -0.01, -.45, .45, 1.4, .45},\n visual = \"mesh\",\n stepheight = 1.1,\n visual_size = {x=1,y=1},\n mesh = \"horse.x\",\n textures = {\"whinny_horse\"..basename..\".png\"},\n animation = {\n speed_normal = 20,\n stand_start = 300,\n stand_end = 460,\n walk_start = 10,\n walk_end = 59,\n\t\tgallop_start = 70,\n gallop_end = 119,\n\t\tmode_stand = 1,\n\t\tmode_walk = 2,\n\t\tmode_gallop = 3,\n },\n\tanimation_current = 0,\n max_speed = 7,\n forward_boost = .2,\n jump_boost = 4,\n\tspeed = 0,\n\tdriver = nil\n})\nend\n\nregister_tamehorse (\"\", \"Brown Horse\")\nregister_wildhorse (\"\")\nregister_tamehorse (\"peg\", \"White Horse\")\nregister_wildhorse (\"peg\")\nregister_tamehorse (\"ara\", \"Black Horse\")\nregister_wildhorse (\"ara\")\n\n--function whinny:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, spawn_func)\n\nwhinny:register_spawn(\"whinny:horse\",\"default:dirt_with_grass\",20, 6, 50000, 1, 100)\nwhinny:register_spawn(\"whinny:horsepeg\",\"default:dirt_with_dry_grass\",20, 6, 50000, 1, 100)\nwhinny:register_spawn(\"whinny:horseara\",\"default:dirt_with_grass\",20, 6, 50000, 1, 100)\n"
},
{
"alpha_fraction": 0.6648044586181641,
"alphanum_fraction": 0.6710894107818604,
"avg_line_length": 23.27118682861328,
"blob_id": "c1722d513d79b0104cdfdfae9a6274afee06d589",
"content_id": "aea71ed4e7ba5af15d9eee49aa0cd0a9ec665270",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 1432,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 59,
"path": "/mods/better_edge/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "local limit = 1500\n\nlocal players = {}\n\nminetest.register_on_joinplayer(function(player)\n\tplayers[player:get_player_name()] = player:get_pos()\t\nend)\n\nminetest.register_on_leaveplayer(function(player)\n\tif player then\n\t\tplayers[player:get_player_name()] = nil\n\tend\nend)\n\nlocal timer = 0\n\nlocal function is_pos_valid(pos)\n\treturn pos.x < limit and pos.x > -limit and pos.z < limit and pos.z > -limit\nend\n\nlocal function get_valid_pos(pos)\n\tnewpos = {}\n\tfor i,val in pairs({x=pos.x, z=pos.z}) do\n\t\tif val > limit then\n\t\t\tnewpos[i] = limit-1\n\t\telse\n\t\t\tnewpos[i] = val\n\t\tend\n\t\tif val < -limit then\n\t\t\tnewpos[i] = -limit+1\n\t\tend\n\tend\n\tnewpos.y = pos.y\n\treturn newpos\nend\n\nminetest.register_globalstep(function(dtime)\n\tif dtime then\n\t\ttimer = timer + dtime\n\t\tif timer >= 5 then\n\t\t\tfor _, player in pairs(minetest.get_connected_players()) do\n\t\t\t\tif not players[player:get_player_name()] then\n\t\t\t\t\tplayers[player:get_player_name()] = player:get_pos()\n\t\t\t\tend\n\t\t\t\tlocal pos = player:get_pos()\n\t\t\t\tif not is_pos_valid(pos) then\n\t\t\t\t\tminetest.chat_send_player(player:get_player_name(), \"Thou fool, to explore beyond the four corners of the world...\")\n\t\t\t\t\tif is_pos_valid(players[player:get_player_name()]) then\n\t\t\t\t\t\tplayer:set_pos(players[player:get_player_name()])\t\t\t\n\t\t\t\t\telse\n\t\t\t\t\t\tplayer:set_pos(get_valid_pos(player:get_pos()))\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tplayers[player:get_player_name()] = player:get_pos()\n\t\t\tend\n\t\t\ttimer = 0\n\t\tend\n\tend\nend)\n"
},
{
"alpha_fraction": 0.6277403235435486,
"alphanum_fraction": 0.6416525840759277,
"avg_line_length": 28.283950805664062,
"blob_id": "57ff2f9ca9d69670d50d803f4f047ded0db3d554",
"content_id": "1379047f93b87cc3135c75b09092c51bfe41a28f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 4745,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 162,
"path": "/mods/sscsm/sscsm_init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- SSCSM: Server-Sent Client-Side Mods proof-of-concept\n-- Initial code sent to the client\n--\n-- Copyright © 2019 by luk3yx\n-- License: https://git.minetest.land/luk3yx/sscsm/src/branch/master/LICENSE.md\n--\n\n-- Make sure table.unpack exists\nif table.unpack then\n unpack = table.unpack\nelse\n table.unpack = unpack\nend\n\n-- Make sure a few basic functions exist, these may have been blocked because\n-- of security or laziness.\nif not rawget then function rawget(n, name) return n[name] end end\nif not rawset then function rawset(n, k, v) n[k] = v end end\nif not rawequal then function rawequal(a, b) return a == b end end\nif not assert then\n function assert(value, err)\n if not value then\n error(err or 'Assertion failed!', 2)\n end\n return value\n end\nend\n\n-- Create the API\nsscsm = {}\nfunction sscsm.global_exists(name)\n return rawget(_G, name) ~= nil\nend\n\nif not sscsm.global_exists('minetest') then\n minetest = assert(core, 'No \"minetest\" global found!')\nend\n\nminetest.global_exists = sscsm.global_exists\n\n-- Check if join_mod_channel and leave_mod_channel exist.\nif sscsm.global_exists('join_mod_channel')\n and sscsm.global_exists('leave_mod_channel') then\n sscsm.join_mod_channel = join_mod_channel\n sscsm.leave_mod_channel = leave_mod_channel\n join_mod_channel, leave_mod_channel = nil, nil\nelse\n local dummy = function() end\n sscsm.join_mod_channel = dummy\n sscsm.leave_mod_channel = dummy\nend\n\n-- Add print()\nfunction print(...)\n local msg = '[SSCSM] '\n for i = 1, select('#', ...) do\n if i > 1 then msg = msg .. '\\t' end\n msg = msg .. tostring(select(i, ...))\n end\n minetest.log('none', msg)\nend\nprint('Hello from the server-sent CSMs!')\n\n-- Add register_on_mods_loaded\ndo\n local funcs = {}\n function sscsm.register_on_mods_loaded(callback)\n if funcs then table.insert(funcs, callback) end\n end\n\n function sscsm._done_loading_()\n sscsm._done_loading_ = nil\n for _, func in ipairs(funcs) do func() end\n funcs = nil\n end\nend\n\nsscsm.register_on_mods_loaded(function()\n print('SSCSMs loaded, leaving mod channel.')\n sscsm.leave_mod_channel()\nend)\n\n-- Helper functions\nif not minetest.get_node then\n function minetest.get_node(pos)\n return minetest.get_node_or_nil(pos) or {name = 'ignore', param1 = 0,\n param2 = 0}\n end\nend\n\n-- Make minetest.run_server_chatcommand allow param to be unspecified.\nfunction minetest.run_server_chatcommand(cmd, param)\n minetest.send_chat_message('/' .. cmd .. ' ' .. (param or ''))\nend\n\n-- Register \"server-side\" chatcommands\n-- Can allow instantaneous responses in some cases.\nsscsm.registered_chatcommands = {}\nlocal function on_chat_message(msg)\n if msg:sub(1, 1) ~= '/' then return false end\n\n local cmd, param = msg:match('^/([^ ]+) *(.*)')\n if not cmd then\n minetest.display_chat_message('-!- Empty command')\n return true\n end\n\n if not sscsm.registered_chatcommands[cmd] then return false end\n\n local _, res = sscsm.registered_chatcommands[cmd].func(param or '')\n if res then minetest.display_chat_message(tostring(res)) end\n\n return true\nend\n\nfunction sscsm.register_chatcommand(cmd, def)\n if type(def) == 'function' then\n def = {func = def}\n elseif type(def.func) ~= 'function' then\n error('Invalid definition passed to sscsm.register_chatcommand.')\n end\n\n sscsm.registered_chatcommands[cmd] = def\n\n if on_chat_message then\n minetest.register_on_sending_chat_message(on_chat_message)\n on_chat_message = nil\n end\nend\n\nfunction sscsm.unregister_chatcommand(cmd)\n sscsm.registered_chatcommands[cmd] = nil\nend\n\n-- A proper get_player_control doesn't exist yet.\nfunction sscsm.get_player_control()\n local n = minetest.localplayer:get_key_pressed()\n return {\n up = n % 2 == 1,\n down = math.floor(n / 2) % 2 == 1,\n left = math.floor(n / 4) % 2 == 1,\n right = math.floor(n / 8) % 2 == 1,\n jump = math.floor(n / 16) % 2 == 1,\n aux1 = math.floor(n / 32) % 2 == 1,\n sneak = math.floor(n / 64) % 2 == 1,\n LMB = math.floor(n / 128) % 2 == 1,\n RMB = math.floor(n / 256) % 2 == 1,\n }\nend\n\n-- Allow SSCSMs to know about CSM restriction flags.\n-- \"__FLAGS__\" is replaced with the actual value in init.lua.\nlocal flags = __FLAGS__\nsscsm.restriction_flags = assert(flags)\nsscsm.restrictions = {\n chat_messages = math.floor(flags / 2) % 2 == 1,\n read_itemdefs = math.floor(flags / 4) % 2 == 1,\n read_nodedefs = math.floor(flags / 8) % 2 == 1,\n lookup_nodes_limit = math.floor(flags / 16) % 2 == 1,\n read_playerinfo = math.floor(flags / 32) % 2 == 1,\n}\n"
},
{
"alpha_fraction": 0.6954482793807983,
"alphanum_fraction": 0.6987544298171997,
"avg_line_length": 32.95561218261719,
"blob_id": "9121ad91a8ed7577a3cccc5d9278024381fa28ab",
"content_id": "54106024308d80fb5b3d15fa477a9aa209b27f5c",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 13006,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 383,
"path": "/mods/tnt/voice/voice.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--[[\nCopyright (c) 2015, Robert 'Bobby' Zenz\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n--]]\n\n\n--- Voice is a system to make the chat of Minetest more like a voice.\n--\n-- The only function that should be called from the client is activate.\nvoice = {\n\t--- Type constant for a global message.\n\tTYPE_GLOBAL = \"global\",\n\t\n\t--- Type constant for a shouted message.\n\tTYPE_SHOUT = \"shout\",\n\t\n\t--- Type constant for a talked message.\n\tTYPE_TALK = \"talk\",\n\t\n\t--- Type constant for a whispered message.\n\tTYPE_WHISPER = \"whisper\",\n\t\n\t--- If the system should be activated automatically.\n\tactivate_automatically = settings.get_bool(\"voice_activate\", true),\n\t\n\t--- If the system is active/has been activated.\n\tactive = false,\n\t\n\t--- The privilege that is needed for using the global command.\n\tglobal_privilege = settings.get_string(\"voice_global_privilege\", \"voice_global\"),\n\t\n\t--- The line of sight modification, which means that if the target does not\n\t-- have line of sight with the source, this mod will be applied to\n\t-- the range to limit it.\n\tline_of_sight_mod = settings.get_number(\"voice_line_of_sight_mod\", 0.40),\n\t\n\t--- The callbacks for when a message is send.\n\tmessage_callbacks = List:new(),\n\t\n\t--- The parameters for talking.\n\t\n\t--- The parameters for shouting.\n\tshout_parameters = {\n\t\t--- Everything within this range (inclusive) will be understandable.\n\t\tunderstandable = settings.get_number(\"voice_shout_understandable\", 45),\n\t\t\n\t\t--- Everything within this range (inclusive) will be abstruse, which\n\t\t-- means that only part of the message (depending on the distance) will\n\t\t-- be understandable.\n\t\tabstruse = settings.get_number(\"voice_shout_abstruse\", 60),\n\t\t\n\t\t--- Everything within this range (inclusive) will not be understandable.\n\t\tincomprehensible = settings.get_number(\"voice_shout_incomprehensible\", 80),\n\t\t\n\t\t-- The type of these parameters.\n\t\ttype = \"shout\"\n\t},\n\t\n\ttalk_parameters = {\n\t\t--- Everything within this range (inclusive) will be understandable.\n\t\tunderstandable = settings.get_number(\"voice_talk_understandable\", 6),\n\t\t\n\t\t--- Everything within this range (inclusive) will be abstruse, which\n\t\t-- means that only part of the message (depending on the distance) will\n\t\t-- be understandable.\n\t\tabstruse = settings.get_number(\"voice_talk_abstruse\", 12),\n\t\t\n\t\t--- Everything within this range (inclusive) will not be understandable.\n\t\tincomprehensible = settings.get_number(\"voice_talk_incomprehenisble\", 17),\n\t\t\n\t\t-- The type of these parameters.\n\t\ttype = \"talk\"\n\t},\n\t\n\t--- The parameters for whispering.\n\twhisper_parameters = {\n\t\t--- Everything within this range (inclusive) will be understandable.\n\t\tunderstandable = settings.get_number(\"voice_whisper_understandable\", 3),\n\t\t\n\t\t--- Everything within this range (inclusive) will be abstruse, which\n\t\t-- means that only part of the message (depending on the distance) will\n\t\t-- be understandable.\n\t\tabstruse = settings.get_number(\"voice_whisper_abstruse\", 4),\n\t\t\n\t\t--- Everything within this range (inclusive) will not be understandable.\n\t\tincomprehensible = settings.get_number(\"voice_whisper_incomprehensible\", 5),\n\t\t\n\t\t-- The type of these parameters.\n\t\ttype = \"whisper\"\n\t}\n}\n\n\n--- Abstruses the given message. That means that parts of it will be blanked,\n-- based on the rate.\n--\n-- @param message The message to abstruse.\n-- @param rate The rate at which to abstruse the message, a value between\n-- 0 and 1, with 1 being everything abstrused.\n-- @return The abstrused message.\nfunction voice.abstruse(message, rate)\n\tlocal abstruse_message = \"\"\n\t\n\tfor index = 1, string.len(message), 1 do\n\t\tlocal piece = string.sub(message, index, index)\n\t\t\n\t\t-- Only abstruse words, leave dots, quotes etc. in place.\n\t\tif string.find(piece, \"%w\") ~= nil then\n\t\t\tif voice.random(rate) then\n\t\t\t\tabstruse_message = abstruse_message .. \".\"\n\t\t\telse\n\t\t\t\tabstruse_message = abstruse_message .. piece\n\t\t\tend\n\t\telse\n\t\t\tabstruse_message = abstruse_message .. piece\n\t\tend\n\tend\n\t\n\treturn abstruse_message\nend\n\n--- Activates the voice system.\nfunction voice.activate()\n\tif voice.activate_automatically then\n\t\tvoice.activate_internal()\n\tend\nend\n\n--- Activates the system, without checking the configuration.\nfunction voice.activate_internal()\n\tif not voice.active then\n\t\tminetest.register_privilege(voice.global_privilege, {\n\t\t\tdescription = \"The privilege needed to use the global chat.\",\n\t\t\tgive_to_singleplayer = true\n\t\t})\n\t\t\n\t\tminetest.register_on_chat_message(voice.on_chat_message)\n\t\t\n\t\tvoice.register_chatcommand(\"t\", \"talk\", \"Talk\", voice.talk_parameters)\n\t\tvoice.register_chatcommand(\"s\", \"shout\", \"Shout\", voice.shout_parameters)\n\t\tvoice.register_chatcommand(\"w\", \"whisper\", \"Whisper\", voice.whisper_parameters)\n\t\tvoice.register_global_chatcommand()\n\t\t\n\t\tvoice.active = true\n\tend\nend\n\n--- Checks if the given distance is in the given range, considering\n-- the line of sight.\n--\n-- @param distance The distance.\n-- @param range The range.\n-- @param line_of_sight If there is line of sight.\n-- @return true if it is in range.\nfunction voice.in_range(distance, range, line_of_sight)\n\tif line_of_sight then\n\t\treturn distance <= range\n\telse\n\t\treturn distance <= (range * voice.line_of_sight_mod)\n\tend\nend\n\n--- Invokes all registered message callbacks.\n--\n-- @param player The player that is sending the message.\n-- @param type The type of the message.\n-- @param message The message to be send.\n-- @return true if the message should be suppressed, and the second return\n-- value is the modified message.\nfunction voice.invoke_message_callbacks(player, type, message)\n\tlocal suppress = false\n\tvoice.message_callbacks:foreach(function(callback, index)\n\t\tlocal modified_suppress = nil\n\t\tlocal modified_message = nil\n\t\t\n\t\tmodified_suppress, modified_message = callback(\n\t\t\tplayer,\n\t\t\ttype,\n\t\t\tsuppress,\n\t\t\tmessage)\n\t\t\n\t\tif modified_suppress ~= nil then\n\t\t\tsuppress = modified_suppress\n\t\tend\n\t\tif modified_message ~= nil then\n\t\t\tmessage = modified_message\n\t\tend\n\tend)\n\t\n\treturn suppress, message\nend\n\n--- Muffles the given messages, meaning replaces everything with dots.\n--\n-- @param message The message to muffle.\n-- @return The muffled message.\nfunction voice.muffle(message)\n\t-- Replace only words.\n\treturn string.gsub(message, \"%w\", \".\")\nend\n\n--- Callback for if a chat message is send.\n--\n-- @param name The name of the sending player.\n-- @param message The message that is send.\n-- @return true if the message has been handled and should not be send.\nfunction voice.on_chat_message(name, message)\n\tlocal player = minetest.get_player_by_name(name)\n\t\n\tvoice.speak(player, message, voice.talk_parameters)\n\t\n\t-- Do not send the message further, we've done that.\n\treturn true\nend\n\n--- Gets a random chance based on the given rate.\n--\n-- @param rate The rate. A number between 0 and 1, with 1 being always true.\n-- @return true if there is a chance.\nfunction voice.random(rate)\n\treturn (random.next_int(0, 100) / 100) <= rate\nend\n\n--- Registers a chat chommand.\n--\n-- @param short The short command.\n-- @param long The long command.\n-- @param description The description of the command.\n-- @param parameters The parameters to use.\nfunction voice.register_chatcommand(short, long, description, parameters)\n\tlocal command = {\n\t\tdescription = description,\n\t\tparams = \"<message>\",\n\t\tfunc = function(player_name, message)\n\t\t\tlocal player = minetest.get_player_by_name(player_name)\n\t\t\t\n\t\t\tvoice.speak(player, message, parameters)\n\t\t\t\n\t\t\treturn true\n\t\tend\n\t}\n\t\n\tminetest.register_chatcommand(short, command)\n\tminetest.register_chatcommand(long, command)\nend\n\n--- Registers the chat command for global messaging.\nfunction voice.register_global_chatcommand()\n\tminetest.register_privilege(\"voice_global\", {\n\t\tdescription = \"Allows the player to send global messages.\",\n\t\tgive_to_singleplayer = true\n\t})\n\t\n\tlocal command = {\n\t\tdescription = \"Global\",\n\t\tparams = \"<message>\",\n\t\tprivs = { [voice.global_privilege] = true },\n\t\tfunc = function(player_name, message)\n\t\t\tlocal suppress, message = voice.invoke_message_callbacks(\n\t\t\t\tminetest.get_player_by_name(player_name),\n\t\t\t\tvoice.TYPE_GLOBAL,\n\t\t\t\tmessage)\n\t\t\t\n\t\t\tif suppress then\n\t\t\t\treturn true\n\t\t\tend\n\t\t\t\n\t\t\tminetest.chat_send_all(\"<\" .. player_name .. \">(Global): \" .. message)\n minetest.log(\"CHAT: <\" .. player_name .. \">(Global): \" .. message)\n irc:say(\"<\" .. player_name .. \">(Global): \" .. message)\n\t\t\t\n\t\t\treturn true\n\t\tend\n\t}\n\t\n\tminetest.register_chatcommand(\"g\", command)\n\tminetest.register_chatcommand(\"global\", command)\nend\n\n--- Registers a callback that is invoked for every message that is send.\n--\n-- @param callback The callback that is to be registered, a function that\n-- accepts the player (Player object), the type of the message\n-- (TYPE_* constants), if the message is going to be send and\n-- the message itself. The callback can return two values,\n-- the first, a boolean that is true if the message should\n-- be suppressed, and the second being a message to be sent\n-- instead. The last callback can determine if the message\n-- should actually be send or not.\nfunction voice.register_on_message(callback)\n\tvoice.message_callbacks:add(callback)\nend\n\n--- Speaks the given message.\n--\n-- @param speaking_player The speaking player, a Player Object.\n-- @param message The message that is spoken.\n-- @param parameters The speak parameters, like talk_parameters.\nfunction voice.speak(speaking_player, message, parameters)\n\tlocal suppress, message = voice.invoke_message_callbacks(\n\t\tspeaking_player,\n\t\tparameters.type,\n\t\tmessage)\n\t\n\tif suppress then\n\t\treturn\n\tend\n\t\n\tlocal source_name = speaking_player:get_player_name()\n\tlocal source_pos = speaking_player:getpos()\n local short = string.sub(parameters.type, 1, 1)\n\t\n\tfor index, player in ipairs(minetest.get_connected_players()) do\n\t\tlocal target_name = player:get_player_name()\n\t\t\n\t\tif source_name ~= target_name then\n\t\t\tlocal target_pos = player:getpos()\n\t\t\tlocal distance = mathutil.distance(source_pos, target_pos)\n\t\t\t\n\t\t\t-- Test now if we're even in range, minor optimization.\n\t\t\tif distance <= parameters.incomprehensible then\n\t\t\t\t-- TODO The y+1 thing is to emulate players height, might be wrong.\n\t\t\t\tlocal line_of_sight = minetest.line_of_sight({\n\t\t\t\t\tx = source_pos.x,\n\t\t\t\t\ty = source_pos.y + 1,\n\t\t\t\t\tz = source_pos.z\n\t\t\t\t}, {\n\t\t\t\t\tx = target_pos.x,\n\t\t\t\t\ty = target_pos.y + 1,\n\t\t\t\t\tz = target_pos.z\n\t\t\t\t})\n\t\t\t\tlocal short_type = string.sub(parameters.type, 1, 1)\n short = short_type\n\t\t\t\t\n\t\t\t\tif voice.in_range(distance, parameters.understandable, line_of_sight) then\n\t\t\t\t\tminetest.chat_send_player(\n\t\t\t\t\t\ttarget_name,\n\t\t\t\t\t\t\"<\" .. source_name .. \"> (\" .. short_type .. \") \" .. message)\n\t\t\t\telseif voice.in_range(distance, parameters.abstruse, line_of_sight) then\n\t\t\t\t\tlocal rate = transform.linear(distance, parameters.understandable, parameters.abstruse)\n\t\t\t\t\t\n\t\t\t\t\t-- Here we have a random chance that the player name is muffeld.\n\t\t\t\t\tif voice.random(rate) then\n\t\t\t\t\t\tminetest.chat_send_player(\n\t\t\t\t\t\t\ttarget_name,\n\t\t\t\t\t\t\t\"<\" .. voice.muffle(source_name) .. \">(\" .. short_type .. \"): \" .. voice.abstruse(message, rate))\n\t\t\t\t\telse\n\t\t\t\t\t\tminetest.chat_send_player(\n\t\t\t\t\t\t\ttarget_name,\n\t\t\t\t\t\t\t\"<\" .. source_name .. \">(\" .. short_type .. \"): \" .. voice.abstruse(message, rate))\n\t\t\t\t\tend\n\t\t\t\telseif voice.in_range(distance, parameters.incomprehensible, line_of_sight) then\n\t\t\t\t\tminetest.chat_send_player(\n\t\t\t\t\ttarget_name,\n\t\t\t\t\t\"<\" .. voice.muffle(source_name) .. \">(\" .. short_type .. \"): \" .. voice.muffle(message))\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n minetest.log(\"CHAT: <\" .. source_name .. \"> (\" .. short .. \") \" .. message)\n irc:say(\"<\" .. source_name .. \"> (\" .. short .. \") \" .. message)\nend\n\n"
},
{
"alpha_fraction": 0.5925548076629639,
"alphanum_fraction": 0.595614492893219,
"avg_line_length": 30.126983642578125,
"blob_id": "c343309ea35c4b8913bbe5279af4035d6fdae59e",
"content_id": "debf5417b4da1e54b7a2203af8a3a2494adb6d5d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5883,
"license_type": "permissive",
"max_line_length": 202,
"num_lines": 189,
"path": "/mods/discordmt/server.py",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nimport sys\nfrom aiohttp import web\nimport aiohttp\nimport discord\nfrom discord.ext import commands\nimport asyncio\nimport json\nimport time\nimport configparser\n\nconfig = configparser.ConfigParser()\n\nconfig.read('relay.conf')\n\nclass Queue():\n def __init__(self):\n self.queue = []\n def add(self, item):\n self.queue.append(item)\n def get(self):\n if len(self.queue) >=1:\n item = self.queue[0]\n del self.queue[0]\n return item\n else:\n return None\n def get_all(self):\n items = self.queue\n self.queue = []\n return items\n def isEmpty(self):\n return len(self.queue) == 0\n\ndef clean_invites(string):\n return ' '.join([word for word in string.split() if not ('discord.gg' in word) and not ('discordapp.com/invite' in word)])\n\noutgoing_msgs = Queue()\ncommand_queue = Queue()\nlogin_queue = Queue()\n\nprefix = config['BOT']['command_prefix']\n\nbot = commands.Bot(command_prefix=prefix, help_command=None)\n\nchannel_id = int(config['RELAY']['channel_id'])\n\nconnected = False\n\nport = int(config['RELAY']['port'])\ntoken = config['BOT']['token']\nlogins_allowed = True if config['RELAY']['allow_logins'] == 'true' else False\ndo_clean_invites = True if config['RELAY']['clean_invites'] == 'true' else False\ndo_use_nicknames = True if config['RELAY']['use_nicknames'] == 'true' else False\n\nlast_request = 0\n\nchannel = None\nauthenticated_users = {}\n\ndef check_timeout():\n return time.time() - last_request <= 1\n\nasync def handle(request):\n global last_request\n last_request = time.time()\n text = await request.text()\n try:\n data = json.loads(text)\n if data['type'] == 'DISCORD-RELAY-MESSAGE':\n msg = discord.utils.escape_mentions(data['content'])[0:2000]\n if 'context' in data.keys():\n id = int(data['context'])\n user = bot.get_user(id)\n if user is not None:\n await user.send(msg)\n else:\n print('unyay')\n else:\n await channel.send(msg)\n return web.Response(text = 'Acknowledged') # discord.send should NOT block extensively on the Lua side\n if data['type'] == 'DISCORD_LOGIN_RESULT':\n user = bot.get_user(int(data['user_id']))\n if user is not None:\n if data['success'] is True:\n authenticated_users[int(data['user_id'])] = data['username']\n await user.send('Login successful.')\n else:\n await user.send('Login failed.')\n except:\n pass\n response = json.dumps({\n 'messages' : outgoing_msgs.get_all(),\n 'commands' : command_queue.get_all(),\n 'logins' : login_queue.get_all()\n })\n return web.Response(text = response)\n \n\napp = web.Application()\napp.add_routes([web.get('/', handle),\n web.post('/', handle)])\n\[email protected]\nasync def on_ready():\n global connected\n if not connected:\n connected = True\n global channel\n channel = await bot.fetch_channel(channel_id)\n\[email protected]\nasync def on_message(message):\n global outgoing_msgs\n if check_timeout():\n if (message.channel.id == channel_id) and (message.author.id != bot.user.id):\n msg = {\n 'author': message.author.name if not do_use_nicknames else message.author.display_name,\n 'content': message.content.replace('\\n', '/')\n }\n if do_clean_invites:\n msg['content'] = clean_invites(msg['content'])\n if msg['content'] != '':\n outgoing_msgs.add(msg)\n \n await bot.process_commands(message)\n\[email protected](help='Runs an ingame command from Discord.')\nasync def cmd(ctx, command, *, args=''):\n if ((ctx.channel.id != channel_id) and ctx.guild is not None) or not logins_allowed:\n return\n if ctx.author.id not in authenticated_users.keys():\n await ctx.send('Not logged in.')\n return\n command = {\n 'name': authenticated_users[ctx.author.id],\n 'command': command,\n 'params': args.replace('\\n', '')\n }\n if ctx.guild is None:\n command['context'] = str(ctx.author.id)\n command_queue.add(command)\n \[email protected](help='Logs into your ingame account from Discord so you can run commands. You should only run this command in DMs with the bot.')\nasync def login(ctx, username, password=''):\n if not check_timeout() or not logins_allowed:\n return\n if ctx.guild is not None:\n await ctx.send(ctx.author.mention+' You\\'ve quite possibly just leaked your password; it is advised that you change it at once.\\n*This message will be automatically deleted*', delete_after = 10)\n return\n login_queue.add({\n 'username' : username,\n 'password' : password,\n 'user_id' : str(ctx.author.id)\n })\n\[email protected](help='Lists connected players and server information.')\nasync def status(ctx, *, args=None):\n if not check_timeout():\n return\n if ((ctx.channel.id != channel_id) and ctx.guild is not None):\n return\n data = {\n 'name': 'discord_relay',\n 'command': 'status',\n 'params': '',\n }\n if ctx.guild is None:\n data['context'] = str(ctx.author.id)\n command_queue.add(data)\n\nasync def runServer():\n runner = web.AppRunner(app)\n await runner.setup()\n site = web.TCPSite(runner, 'localhost', port)\n await site.start()\n\nasync def runBot():\n await bot.login(token)\n await bot.connect()\n\ntry:\n print('='*37+'\\nStarting relay. Press Ctrl-C to exit.\\n'+'='*37)\n loop = asyncio.get_event_loop()\n futures = asyncio.gather(runBot(), runServer())\n loop.run_until_complete(futures)\n\nexcept (KeyboardInterrupt, SystemExit):\n sys.exit()\n"
},
{
"alpha_fraction": 0.6160258650779724,
"alphanum_fraction": 0.619210422039032,
"avg_line_length": 31.475284576416016,
"blob_id": "068090a5fedc3fc631dd9562d31bba32fee12c1b",
"content_id": "172bd8865204c0245a5b1d091b4f1b8e0dafe8e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 42706,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 1315,
"path": "/mods/factions/chatcommands.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "-------------------------------------------------------------------------------\n-- factions Mod by Sapier\n--\n-- License WTFPL\n--\n--! @file chatcommnd.lua\n--! @brief factions chat interface\n--! @copyright Sapier, agrecascino, shamoanjac, Coder12a \n--! @author Sapier, agrecascino, shamoanjac, Coder12a \n--! @date 2016-08-12\n--\n-- Contact sapier a t gmx net\n-------------------------------------------------------------------------------\n\nlocal send_error = function(player, message)\n minetest.chat_send_player(player, message)\nend\n\nfactions_chat = {}\n\nfactions.commands = {}\n\nfactions.register_command = function(cmd_name, cmd, ignore_param_count)\n factions.commands[cmd_name] = { -- default command\n name = cmd_name,\n faction_permissions = {},\n global_privileges = {},\n format = {},\n infaction = true,\n description = \"This command has no description.\",\n run = function(self, player, argv)\n --if self.global_privileges then\n -- local tmp = {}\n -- for i in ipairs(self.global_privileges) do\n -- tmp[self.global_privileges[i]] = true\n -- end\n -- local bool, missing_privs = minetest.check_player_privs(player, tmp)\n -- if not bool then\n -- send_error(player, \"Unauthorized.\")\n -- return false\n -- end\n --end\n -- checks argument formats\n local args = {\n factions = {},\n players = {},\n strings = {},\n other = {}\n }\n\t\t\tif not ignore_param_count then\n\t\t\t\tif #argv < #(self.format) then\n\t\t\t\t\tsend_error(player, \"Not enough parameters.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\telse\n\t\t\t\tif self.format[1] then\n\t\t\t\t\tlocal fm = self.format[1]\n\t\t\t\t\tfor i in ipairs(argv) do\n\t\t\t\t\t\tif #argv > #(self.format) then\n\t\t\t\t\t\t\ttable.insert(self.format, fm)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n for i in ipairs(self.format) do\n local argtype = self.format[i]\n local arg = argv[i]\n if argtype == \"faction\" then\n local fac = factions.get_faction(arg)\n if not fac then\n send_error(player, \"Specified faction \"..arg..\" does not exist\")\n return false\n else\n table.insert(args.factions, fac)\n end\n elseif argtype == \"player\" then\n local pl = arg--minetest.get_player_by_name(arg)\n if not pl and not factions.players[arg] then\n send_error(player, \"Player is not online.\")\n return false\n else\n table.insert(args.players, pl)\n end\n elseif argtype == \"string\" then\n table.insert(args.strings, arg)\n else\n minetest.log(\"error\", \"Bad format definition for function \"..self.name)\n send_error(player, \"Internal server error\")\n return false\n end\n end\n for i=2, #argv do\n\t\t\t\tif argv[i] then\n\t\t\t\t\ttable.insert(args.other, argv[i])\n\t\t\t\tend\n end\n\n -- checks permissions\n local player_faction = factions.get_player_faction(player)\n if self.infaction and not player_faction then\n minetest.chat_send_player(player, \"This command is only available within a faction.\")\n return false\n end\n if self.faction_permissions then\n for i in ipairs(self.faction_permissions) do\n if not player_faction:has_permission(player, self.faction_permissions[i]) then\n send_error(player, \"You don't have permissions to do that.\")\n return false\n end\n end\n end\n\n -- get some more data\n local pos = minetest.get_player_by_name(player):getpos()\n local parcelpos = factions.get_parcel_pos(pos)\n return self.on_success(player, player_faction, pos, parcelpos, args)\n end,\n on_success = function(player, faction, pos, parcelpos, args)\n minetest.chat_send_player(player, \"Not implemented yet!\")\n end\n }\n -- override defaults\n for k, v in pairs(cmd) do\n factions.commands[cmd_name][k] = v\n end\nend\n\n\nlocal init_commands\ninit_commands = function()\n\t--[[\n\tminetest.register_privilege(\"faction_user\",\n\t\t{\n\t\t\tdescription = \"this user is allowed to interact with faction mod\",\n\t\t\tgive_to_singleplayer = true,\n\t\t}\n\t)\n\t\n\t--]]\n\tminetest.register_privilege(\"faction_admin\",\n\t\t{\n\t\t\tdescription = \"this user is allowed to create or delete factions\",\n\t\t\tgive_to_singleplayer = true,\n\t\t}\n\t)\n\t\n\tminetest.register_chatcommand(\"factions\",\n\t\t{\n\t\t\tparams = \"<cmd> <parameter 1> .. <parameter n>\",\n\t\t\tdescription = \"faction administration functions\",\n\t\t\tprivs = { interact=true,}, --faction_user=true },\n\t\t\tfunc = factions_chat.cmdhandler,\n\t\t}\n\t)\n\t\n\t\n\tminetest.register_chatcommand(\"f\",\n\t\t{\n\t\t\tparams = \"<command> parameters\",\n\t\t\tdescription = \"Factions commands. Type /f help for available commands.\",\n privs = { interact=true,},--faction_user=true},\n\t\t\tfunc = factions_chat.cmdhandler,\n\t\t}\n\t)\nend\n\t\n\n-------------------------------------------\n-- R E G I S T E R E D C O M M A N D S |\n-------------------------------------------\n\nfactions.register_command (\"set_name\", {\n faction_permissions = {\"description\"},\n\tformat = {\"string\"},\n description = \"Change the faction's name.\",\n\tglobal_privileges = def_global_privileges,\n on_success = function(player, faction, pos, parcelpos, args)\n local factionname = args.strings[1]\n if factions.can_create_faction(factionname) then\n\t\t\tfaction:set_name(factionname)\n return true\n else\n send_error(player, \"Faction cannot be renamed.\")\n return false\n end\n end\n},false)\n\nfactions.register_command (\"claim\", {\n faction_permissions = {\"claim\"},\n description = \"Claim the plot of land you're on.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local can_claim = faction:can_claim_parcel(parcelpos)\n if can_claim then\n minetest.chat_send_player(player, \"Claming parcel \"..parcelpos)\n faction:claim_parcel(parcelpos)\n return true\n else\n local parcel_faction = factions.get_parcel_faction(parcelpos)\n if not parcel_faction then\n send_error(player, \"You faction cannot claim any (more) parcel(s).\")\n return false\n elseif parcel_faction.name == faction.name then\n send_error(player, \"This parcel already belongs to your faction.\")\n return false\n else\n send_error(player, \"This parcel belongs to another faction.\")\n return false\n end\n end\n end\n},false)\n\nfactions.register_command(\"unclaim\", {\n faction_permissions = {\"claim\"},\n description = \"Unclaim the plot of land you're on.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local parcel_faction = factions.get_parcel_faction(parcelpos)\n\t\tif not parcel_faction then\n\t\t send_error(player, \"This parcel does not exist.\")\n return false\n\t\tend\n if parcel_faction.name ~= faction.name then\n send_error(player, \"This parcel does not belong to you.\")\n return false\n else\n faction:unclaim_parcel(parcelpos)\n return true\n end\n end\n},false)\n\n--list all known factions\nfactions.register_command(\"list\", {\n description = \"List all registered factions.\",\n infaction = false,\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local list = factions.get_faction_list()\n local tosend = \"Existing factions:\"\n \n for i,v in ipairs(list) do\n if i ~= #list then\n tosend = tosend .. \" \" .. v .. \",\"\n else\n tosend = tosend .. \" \" .. v\n end\n end\t\n minetest.chat_send_player(player, tosend, false)\n return true\n end\n},false)\n\n--show factions mod version\nfactions.register_command(\"version\", {\n description = \"Displays mod version.\",\n on_success = function(player, faction, pos, parcelpos, args)\n minetest.chat_send_player(player, \"factions: version \" .. factions_version , false)\n end\n},false)\n\n--show description of faction\nfactions.register_command(\"info\", {\n format = {\"faction\"},\n description = \"Shows a faction's description.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n minetest.chat_send_player(player,\n \"factions: \" .. args.factions[1].name .. \": \" ..\n args.factions[1].description, false)\n return true\n end\n},false)\n\nfactions.register_command(\"leave\", {\n description = \"Leave your faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tminetest.chat_send_player(player, \"You have left your Faction\")\n faction:remove_player(player)\n return true\n end\n},false)\n\nfactions.register_command(\"kick\", {\n faction_permissions = {\"playerslist\"},\n format = {\"player\"},\n description = \"Kick a player from your faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local victim = args.players[1]\n local victim_faction = factions.get_player_faction(victim)\n if victim_faction and victim ~= faction.leader then -- can't kick da king\n faction:remove_player(victim)\n\t\t\tminetest.chat_send_player(player, \"Kicked player '\"..victim..\"'.\")\n return true\n elseif not victim_faction then\n send_error(player, victim..\" is not in your faction.\")\n return false\n else\n send_error(player, victim..\" cannot be kicked from your faction.\")\n return false\n end\n end\n},false)\n\n--create new faction\nfactions.register_command(\"create\", {\n format = {\"string\"},\n infaction = false,\n description = \"Create a new faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n if faction then\n send_error(player, \"You are already in a faction.\")\n return false\n end\n local factionname = args.strings[1]\n if factions.can_create_faction(factionname) then\n new_faction = factions.new_faction(factionname, nil)\n new_faction:add_player(player, new_faction.default_leader_rank)\n\t\t\tminetest.chat_send_player(player, \"Created Faction.\")\n\t\t\tfactions.start_diplomacy(factionname,new_faction)\n return true\n else\n send_error(player, \"Faction cannot be created.\")\n return false\n end\n end\n},false)\n\nfactions.register_command(\"join\", {\n format = {\"faction\"},\n description = \"Join a faction.\",\n infaction = false,\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local new_faction = args.factions[1]\n if new_faction:can_join(player) then\n if faction then -- leave old faction\n faction:remove_player(player)\n end\n new_faction:add_player(player)\n\t\t\tminetest.chat_send_player(player, \"Joined Faction.\")\n else\n send_error(player, \"You cannot join this faction.\")\n return false\n end\n return true\n end\n},false)\n\nfactions.register_command(\"disband\", {\n faction_permissions = {\"disband\"},\n description = \"Disband your faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tminetest.chat_send_player(player, \"Disbanded Faction.\")\n faction:disband()\n return true\n end\n},false)\n\nfactions.register_command(\"close\", {\n faction_permissions = {\"playerslist\"},\n description = \"Make your faction invite-only.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:toggle_join_free(false)\n return true\n end\n},false)\n\nfactions.register_command(\"open\", {\n faction_permissions = {\"playerslist\"},\n description = \"Allow any player to join your faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:toggle_join_free(true)\n return true\n end\n},false)\n\nfactions.register_command(\"description\", {\n faction_permissions = {\"description\"},\n description = \"Set your faction's description\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:set_description(table.concat(args.other,\" \"))\n return true\n end\n},false)\n\nfactions.register_command(\"invite\", {\n format = {\"player\"},\n faction_permissions = {\"playerslist\"},\n description = \"Invite a player to your faction.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:invite_player(args.players[1])\n\t\tminetest.chat_send_player(player, \"Invite Sent.\")\n return true\n end\n},false)\n\nfactions.register_command(\"uninvite\", {\n format = {\"player\"},\n faction_permissions = {\"playerslist\"},\n description = \"Revoke a player's invite.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:revoke_invite(args.players[1])\n\t\tminetest.chat_send_player(player, \"Invite canceled.\")\n return true\n end\n},false)\n\nfactions.register_command(\"delete\", {\n global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n infaction = false,\n description = \"Delete a faction.\",\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tminetest.chat_send_player(player, \"Deleted Faction.\")\n args.factions[1]:disband()\n return true\n end\n},false)\n\nfactions.register_command(\"ranks\", {\n description = \"List ranks within your faction\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n for rank, permissions in pairs(faction.ranks) do\n minetest.chat_send_player(player, rank..\": \"..table.concat(permissions, \" \"))\n end\n return true\n end\n},false)\n\nfactions.register_command(\"send_alliance\", {\n\tdescription = \"Send an alliance request to another faction.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif factions.factions[args.strings[1]] then\n\t\t\tif not factions.factions[args.strings[1]].request_inbox[faction.name] then\n\t\t\t\tif faction.allies[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"You are already allys.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif faction.enemies[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"You need to be neutral in-order to send an alliance request.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif args.strings[1] == faction.name then\n\t\t\t\t\tsend_error(player, \"You can not send an alliance to your own faction.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif faction.request_inbox[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"Faction \" .. args.strings[1] .. \"has already sent a request to you.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tfactions.factions[args.strings[1]].request_inbox[faction.name] = \"alliance\"\n\t\t\t\tfactions.factions[args.strings[1]]:broadcast(\"An alliance request from faction \" .. faction.name .. \" has been sent to you.\")\n\t\t\t\tfaction:broadcast(\"An alliance request was sent to faction \" .. args.strings[1])\n\t\t\t\tfactions.save()\n\t\t\telse\n\t\t\t\tsend_error(player, \"You have already sent a request.\")\n\t\t\tend\n\t\telse\n\t\t\tsend_error(player, args.strings[1] .. \" is not a name of a faction.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"send_neutral\", {\n\tdescription = \"Send neutral to another faction.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif factions.factions[args.strings[1]] then\n\t\t\tif not factions.factions[args.strings[1]].request_inbox[faction.name] then\n\t\t\t\tif faction.allies[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"You are allys.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif faction.neutral[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"You are already neutral with this faction.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif args.strings[1] == faction.name then\n\t\t\t\t\tsend_error(player, \"You can not send a neutral request to your own faction.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tif faction.request_inbox[args.strings[1]] then\n\t\t\t\t\tsend_error(player, \"Faction \" .. args.strings[1] .. \"has already sent a request to you.\")\n\t\t\t\t\treturn false\n\t\t\t\tend\n\t\t\t\tfactions.factions[args.strings[1]].request_inbox[faction.name] = \"neutral\"\n\t\t\t\tfactions.factions[args.strings[1]]:broadcast(\"A neutral request from faction \" .. faction.name .. \" has been sent to you.\")\n\t\t\t\tfaction:broadcast(\"A neutral request was sent to faction \" .. args.strings[1])\n\t\t\t\tfactions.save()\n\t\t\telse\n\t\t\t\tsend_error(player, \"You have already sent a request.\")\n\t\t\tend\n\t\telse\n\t\t\tsend_error(player, args.strings[1] .. \" is not a name of a faction.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"accept\", {\n\tdescription = \"accept an request from another faction.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif faction.request_inbox[args.strings[1]] then\n\t\t\tif args.strings[1] == faction.name then\n\t\t\t\tsend_error(player, \"You can not accept an request from own faction.\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tif not factions.factions[args.strings[1]] then\n \tfaction.request_inbox[args.strings[1]] = nil\n \tfactions.save()\n\t\t\t\treturn false, \"This faction no longer exists!\"\n\t\t\tend\n\t\t\tif faction.request_inbox[args.strings[1]] == \"alliance\" then\n\t\t\t\tfaction:new_alliance(args.strings[1])\n\t\t\t\tfactions.factions[args.strings[1]]:new_alliance(faction.name)\n\t\t\telse\n\t\t\tif faction.request_inbox[args.strings[1]] == \"neutral\" then\n\t\t\t\tfaction:new_neutral(args.strings[1])\n\t\t\t\tfactions.factions[args.strings[1]]:new_neutral(faction.name)\n\t\t\tend\n\t\t\tend\n\t\t\tfaction.request_inbox[args.strings[1]] = nil\n\t\t\tfactions.save()\n\t\telse\n\t\t\tsend_error(player, \"No request was sent to you.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"refuse\", {\n\tdescription = \"refuse an request from another faction.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif faction.request_inbox[args.strings[1]] then\n\t\t\tif args.strings[1] == faction.name then\n\t\t\t\tsend_error(player, \"You can not refuse an request from your own faction.\")\n\t\t\t\treturn false\n\t\t\tend\n if not factions.factions[args.strings[1]] then\n faction.request_inbox[args.strings[1]] = nil\n factions.save()\n return false, \"This faction no longer exists!\"\n end\n\t\t\tfaction.request_inbox[args.strings[1]] = nil\n\t\t\tfactions.factions[args.strings[1]]:broadcast(\"Faction \" .. faction.name .. \" refuse to be your ally.\")\n\t\t\tfaction:broadcast(\"Refused an request from faction \" .. args.strings[1])\n\t\t\tfactions.save()\n\t\telse\n\t\t\tsend_error(player, \"No request was sent to you.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"declare_war\", {\n\tdescription = \"Declare war on a faction.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif not faction.enemies[args.strings[1]] then\n\t\t\tif args.strings[1] == faction.name then\n\t\t\t\tsend_error(player, \"You can not declare war on your own faction.\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tif faction.allies[args.strings[1]] then\n\t\t\t\tfaction:end_alliance(args.strings[1])\n\t\t\t\tfactions.factions[args.strings[1]]:end_alliance(faction.name)\n\t\t\tend\n\t\t\tif faction.neutral[args.strings[1]] then\n\t\t\t\tfaction:end_neutral(args.strings[1])\n\t\t\t\tfactions.factions[args.strings[1]]:end_neutral(faction.name)\n\t\t\tend\n\t\t\tfaction:new_enemy(args.strings[1])\n\t\t\tlocal enemy = factions.factions[args.strings[1]]\n\t\t\tif not enemy then\n\t\t\t\treturn false, \"Failed!\"\n\t\t\tend\n\t\t\tenemy:new_enemy(faction.name)\n\t\t\tfactions.save()\n\t\telse\n\t\t\tsend_error(player, \"You are already at war.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"break\", {\n\tdescription = \"Break an alliance.\",\n\t--global_privileges = {\"faction_user\"},\n\tformat = {\"string\"},\n\tfaction_permissions = {\"diplomacy\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tif faction.allies[args.strings[1]] then\n\t\t\tif args.strings[1] == faction.name then\n\t\t\t\tsend_error(player, \"You can not break an alliance from your own faction.\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tfaction:end_alliance(args.strings[1])\n\t\t\tfactions.factions[args.strings[1]]:end_alliance(faction.name)\n\t\t\tfaction:new_neutral(args.strings[1])\n\t\t\tfactions.factions[args.strings[1]]:new_neutral(faction.name)\n\t\t\tfactions.save()\n\t\telse\n\t\t\tsend_error(player, \"You where not allies to begin with.\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"inbox\", {\n\tdescription = \"Check your diplomacy request inbox.\",\n\t--global_privileges = {\"faction_user\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tlocal empty = true\n\t\tfor i,k in pairs(faction.request_inbox) do\n\t\t\tif k == \"alliance\" then\n\t\t\t\tminetest.chat_send_player(player,\"Alliance request from faction \" .. i .. \"\\n\")\n\t\t\telse \n\t\t\tif k == \"neutral\" then\n\t\t\t\tminetest.chat_send_player(player,\"neutral request from faction \" .. i .. \"\\n\")\n\t\t\tend\n\t\t\tend\n\t\t\tempty = false\n\t\tend\n\t\tif empty then\n\t\t\tminetest.chat_send_player(player,\"none:\")\n\t\tend\n\tend\n},false,true)\n\nfactions.register_command(\"allies\", {\n\tdescription = \"Shows the factions that are allied to you.\",\n\t--global_privileges = {\"faction_user\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tlocal empty = true\n\t\tfor i,k in pairs(faction.allies) do\n\t\t\tminetest.chat_send_player(player,i .. \"\\n\")\n\t\t\tempty = false\n\t\tend\n\t\tif empty then\n\t\t\tminetest.chat_send_player(player,\"none:\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"neutral\", {\n\tdescription = \"Shows the factions that are neutral with you.\",\n\t--global_privileges = {\"faction_user\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tlocal empty = true\n\t\tfor i,k in pairs(faction.neutral) do\n\t\t\tminetest.chat_send_player(player,i .. \"\\n\")\n\t\t\tempty = false\n\t\tend\n\t\tif empty then\n\t\t\tminetest.chat_send_player(player,\"none:\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"enemies\", {\n\tdescription = \"Shows enemies of your faction.\",\n\t--global_privileges = {\"faction_user\"},\n\ton_success = function(player, faction, pos, parcelpos, args)\n\t\tlocal empty = true\n\t\tfor i,k in pairs(faction.enemies) do\n\t\t\tminetest.chat_send_player(player,i .. \"\\n\")\n\t\t\tempty = false\n\t\tend\n\t\tif empty then\n\t\t\tminetest.chat_send_player(player,\"none:\")\n\t\tend\n\tend\n},false)\n\nfactions.register_command(\"who\", {\n description = \"List players in your faction, and their ranks.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n if not faction.players then\n minetest.chat_send_player(player, \"There is nobody in this faction (\"..faction.name..\")\")\n return true\n end\n minetest.chat_send_player(player, \"Players in faction \"..faction.name..\": \")\n for p, rank in pairs(faction.players) do\n minetest.chat_send_player(player, p..\" (\"..rank..\")\")\n end\n return true\n end\n},false)\n\n-- Save a tiny bit of compute time.\nlocal parcel_size_center = 32. / 2\n\nfactions.register_command(\"show_parcel\", {\n description = \"Shows parcel for six seconds.\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tlocal parcel_faction = factions.get_parcel_faction(parcelpos)\n\t\tif not parcel_faction then\n\t\t\tsend_error(player, \"There is no claim here\")\n\t\t\treturn false\n\t\tend\n\t\tlocal psc = parcel_size_center\n\t\tlocal fps = 32.\n\n\t\tlocal ppos = {x = (math.floor(pos.x / fps)*fps)+psc,y = (math.floor(pos.y / fps)*fps)+psc,z = (math.floor(pos.z / fps)*fps)+psc}\n\t\tminetest.add_entity(ppos, \"factions:display\")\n return true\n end\n},false)\n\nfactions.register_command(\"newrank\", {\n description = \"Add a new rank.\",\n format = {\"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tif args.strings[1] then\n\t\t\tlocal rank = args.strings[1]\n\t\t\tif faction.ranks[rank] then\n\t\t\t\tsend_error(player, \"Rank already exists\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlocal success = false\n\t\t\tlocal failindex = -1\n\t\t\tfor _, f in pairs(args.strings) do\n\t\t\t\tif f then\n\t\t\t\t\tfor q, r in pairs(factions.permissions) do\n\t\t\t\t\t\tif f == r then\n\t\t\t\t\t\t\tsuccess = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsuccess = false\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tif not success and _ ~= 1 then\n\t\t\t\t\t\tfailindex = _\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tif not success then\n\t\t\t\tif args.strings[failindex] then\n\t\t\t\t\tsend_error(player, \"Permission \" .. args.strings[failindex] .. \" is invalid.\")\n\t\t\t\t\telse\n\t\t\t\t\tsend_error(player, \"No permission was given.\")\n\t\t\t\tend\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tfaction:add_rank(rank, args.other)\n\t\t\treturn true\n\t\tend\n\t\tsend_error(player, \"No rank was given.\")\n\t\treturn false\n end\n},true)\n\nfactions.register_command(\"replace_privs\", {\n description = \"Deletes current permissions and replaces them with the ones given.\",\n format = {\"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tif args.strings[1] then\n\t\t\tlocal rank = args.strings[1]\n\t\t\tif not faction.ranks[rank] then\n\t\t\t\tsend_error(player, \"Rank does not exist\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlocal success = false\n\t\t\tlocal failindex = -1\n\t\t\tfor _, f in pairs(args.strings) do\n\t\t\t\tif f then\n\t\t\t\t\tfor q, r in pairs(factions.permissions) do\n\t\t\t\t\t\tif f == r then\n\t\t\t\t\t\t\tsuccess = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsuccess = false\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tif not success and _ ~= 1 then\n\t\t\t\t\t\tfailindex = _\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tif not success then\n\t\t\t\tif args.strings[failindex] then\n\t\t\t\t\tsend_error(player, \"Permission \" .. args.strings[failindex] .. \" is invalid.\")\n\t\t\t\telse\n\t\t\t\t\tsend_error(player, \"No permission was given.\")\n\t\t\t\tend\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tfaction:replace_privs(rank, args.other)\n\t\t\treturn true\n\t\tend\n\t\tsend_error(player, \"No rank was given.\")\n\t\treturn false\n end\n},true)\n\nfactions.register_command(\"remove_privs\", {\n description = \"Remove permissions from a rank.\",\n format = {\"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tif args.strings[1] then\n\t\t\tlocal rank = args.strings[1]\n\t\t\tif not faction.ranks[rank] then\n\t\t\t\tsend_error(player, \"Rank does not exist\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlocal success = false\n\t\t\tlocal failindex = -1\n\t\t\tfor _, f in pairs(args.strings) do\n\t\t\t\tif f then\n\t\t\t\t\tfor q, r in pairs(factions.permissions) do\n\t\t\t\t\t\tif f == r then\n\t\t\t\t\t\t\tsuccess = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsuccess = false\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tif not success and _ ~= 1 then\n\t\t\t\t\t\tfailindex = _\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tif not success then\n\t\t\t\tif args.strings[failindex] then\n\t\t\t\t\tsend_error(player, \"Permission \" .. args.strings[failindex] .. \" is invalid.\")\n\t\t\t\telse\n\t\t\t\t\tsend_error(player, \"No permission was given.\")\n\t\t\t\tend\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tfaction:remove_privs(rank, args.other)\n\t\t\treturn true\n\t\tend\n\t\tsend_error(player, \"No rank was given.\")\n\t\treturn false\n end\n},true)\n\nfactions.register_command(\"add_privs\", {\n description = \"add permissions to a rank.\",\n format = {\"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n\t\tif args.strings[1] then\n\t\t\tlocal rank = args.strings[1]\n\t\t\tif not faction.ranks[rank] then\n\t\t\t\tsend_error(player, \"Rank does not exist\")\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlocal success = false\n\t\t\tlocal failindex = -1\n\t\t\tfor _, f in pairs(args.strings) do\n\t\t\t\tif f then\n\t\t\t\t\tfor q, r in pairs(factions.permissions) do\n\t\t\t\t\t\tif f == r then\n\t\t\t\t\t\t\tsuccess = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsuccess = false\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\tif not success and _ ~= 1 then\n\t\t\t\t\t\tfailindex = _\n\t\t\t\t\t\tbreak\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tif not success then\n\t\t\t\tif args.strings[failindex] then\n\t\t\t\t\tsend_error(player, \"Permission \" .. args.strings[failindex] .. \" is invalid.\")\n\t\t\t\telse\n\t\t\t\t\tsend_error(player, \"No permission was given.\")\n\t\t\t\tend\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tfaction:add_privs(rank, args.other)\n\t\t\treturn true\n\t\tend\n\t\tsend_error(player, \"No rank was given.\")\n\t\treturn false\n end\n},true)\n\nfactions.register_command(\"set_rank_name\", {\n description = \"Change the name of given rank.\",\n format = {\"string\",\"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local rank = args.strings[1]\n local newrank = args.strings[2]\n if not faction.ranks[rank] then\n send_error(player, \"The rank does not exist.\")\n return false\n end\n\t\tif faction.ranks[newrank] then\n send_error(player, \"This rank name was already taken.\")\n return false\n end\n faction:set_rank_name(rank, newrank)\n return true\n end\n},false)\n\nfactions.register_command(\"delrank\", {\n description = \"Replace and delete a rank.\",\n format = {\"string\", \"string\"},\n faction_permissions = {\"ranks\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local rank = args.strings[1]\n local newrank = args.strings[2]\n if not faction.ranks[rank] or not faction.ranks[newrank] then\n send_error(player, \"One of the specified ranks do not exist.\")\n return false\n end\n faction:delete_rank(rank, newrank)\n return true\n end\n},false)\n\nfactions.register_command(\"setspawn\", {\n description = \"Set the faction's spawn\",\n faction_permissions = {\"spawn\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n faction:set_spawn(pos)\n return true\n end\n},false)\n\nfactions.register_command(\"where\", {\n description = \"See whose parcel you stand on.\",\n infaction = false,\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local parcel_faction = factions.get_parcel_faction(parcelpos)\n local place_name = (parcel_faction and parcel_faction.name) or \"Wilderness\"\n minetest.chat_send_player(player, \"You are standing on parcel \"..parcelpos..\", part of \"..place_name)\n return true\n end\n},false)\n\nfactions.register_command(\"help\", {\n description = \"Shows help for commands.\",\n infaction = false,\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n factions_chat.show_help(player)\n return true\n end\n},false)\n\nfactions.register_command(\"spawn\", {\n description = \"Shows your faction's spawn\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local spawn = faction.spawn\n if spawn then\n local spawn = {spawn.x, spawn.y, spawn.z}\n minetest.chat_send_player(player, \"Spawn is at (\"..table.concat(spawn, \", \")..\")\")\n return true\n else\n minetest.chat_send_player(player, \"Your faction has no spawn set.\")\n return false\n end\n end\n},false)\n\nfactions.register_command(\"promote\", {\n description = \"Promotes a player to a rank\",\n format = {\"player\", \"string\"},\n faction_permissions = {\"promote\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local rank = args.strings[1]\n if faction.ranks[rank] then\n faction:promote(args.players[1], rank)\n\t\t\tminetest.chat_send_player(player, \"Promoted \"..args.players[1] .. \" to \" .. rank .. \"!\")\n return true\n else\n send_error(player, \"The specified rank does not exist.\")\n return false\n end\n end\n},false)\n\nfactions.register_command(\"power\", {\n description = \"Display your faction's power\",\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n minetest.chat_send_player(player, \"Power: \"..faction.power..\"/\"..faction.maxpower - faction.usedpower..\"/\"..faction.maxpower)\n return true\n end\n},false)\n--[[\nfactions.register_command(\"setbanner\", {\n description = \"Sets the banner you're on as the faction's banner.\",\n faction_permissions = {\"banner\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local meta = minetest.get_meta({x = pos.x, y = pos.y - 1, z = pos.z})\n local banner = meta:get_string(\"banner\")\n if not banner then\n minetest.chat_send_player(player, \"No banner found.\")\n return false\n end\n faction:set_banner(banner)\n end\n},false)\n--]]\n--[[\nfactions.register_command(\"convert\", {\n description = \"Load factions in the old format\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n format = {\"string\"},\n on_success = function(player, faction, pos, parcelpos, args)\n if factions.convert(args.strings[1]) then\n minetest.chat_send_player(player, \"Factions successfully converted.\")\n else\n minetest.chat_send_player(player, \"Error.\")\n end\n return true\n end\n},false)\n--]]\nfactions.register_command(\"free\", {\n description = \"Forcefully frees a parcel\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local parcel_faction = factions.get_parcel_faction(parcelpos)\n if not parcel_faction then\n send_error(player, \"No claim at this position\")\n return false\n else\n parcel_faction:unclaim_parcel(parcelpos)\n return true\n end\n end\n},false)\n\nfactions.register_command(\"chat\", {\n description = \"Send a message to your faction's members\",\n\tformat = {\"string\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local msg = table.concat(args.strings, \" \")\n faction:broadcast(msg, player)\n end\n},true)\n\nfactions.register_command(\"forceupdate\", {\n description = \"Forces an update tick.\",\n global_privileges = {\"faction_admin\"},\n on_success = function(player, faction, pos, parcelpos, args)\n factions.faction_tick()\n end\n},false)\n\nfactions.register_command(\"which\", {\n description = \"Gets a player's faction\",\n infaction = false,\n format = {\"string\"},\n\t--global_privileges = {\"faction_user\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local playername = args.strings[1]\n local faction = factions.get_player_faction(playername)\n if not faction then\n send_error(player, \"Player \"..playername..\" does not belong to any faction\")\n return false\n else\n minetest.chat_send_player(player, \"player \"..playername..\" belongs to faction \"..faction.name)\n return true\n end\n end\n},false)\n\nfactions.register_command(\"setleader\", {\n description = \"Set a player as a faction's leader\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n format = {\"faction\", \"player\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local playername = args.players[1]\n local playerfaction = factions.get_player_faction(playername)\n local targetfaction = args.factions[1]\n if playerfaction.name ~= targetfaction.name then\n send_error(player, \"Player \"..playername..\" is not in faction \"..targetfaction.name..\".\")\n return false\n end\n targetfaction:set_leader(playername)\n return true\n end\n},false)\n\nfactions.register_command(\"setadmin\", {\n description = \"Make a faction an admin faction\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n args.factions[1].is_admin = true\n\t\tfactions.save()\n return true\n end\n},false)\n\nfactions.register_command(\"resetpower\", {\n description = \"Reset a faction's power\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n args.factions[1].power = 0\n return true\n end\n},false)\n\n\nfactions.register_command(\"obliterate\", {\n description = \"Remove all factions\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n on_success = function(player, faction, pos, parcelpos, args)\n for _, f in pairs(factions.factions) do\n f:disband(\"obliterated\")\n end\n return true\n end\n},false)\n\nfactions.register_command(\"getspawn\", {\n description = \"Get a faction's spawn\",\n infaction = false,\n global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local spawn = args.factions[1].spawn\n if spawn then\n minetest.chat_send_player(player, spawn.x..\",\"..spawn.y..\",\"..spawn.z)\n return true\n else\n send_error(player, \"Faction has no spawn set.\")\n return false\n end\n end\n},false)\n\nfactions.register_command(\"whoin\", {\n description = \"Get all members of a faction.\",\n infaction = false,\n --global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local msg = {}\n for player, _ in pairs(args.factions[1].players) do\n table.insert(msg, player)\n end\n minetest.chat_send_player(player, table.concat(msg, \", \"))\n return true\n end\n},false)\n\nfactions.register_command(\"stats\", {\n description = \"Get stats of a faction.\",\n infaction = false,\n --global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local f = args.factions[1]\n minetest.chat_send_player(player, \"Power: \"..f.power..\"/\"..f.maxpower - f.usedpower..\"/\"..f.maxpower)\n return true\n end\n},false)\n\nfactions.register_command(\"seen\", {\n description = \"Check the last time a faction had a member logged in\",\n infaction = false,\n --global_privileges = {\"faction_admin\"},\n format = {\"faction\"},\n on_success = function(player, faction, pos, parcelpos, args)\n local lastseen = args.factions[1].last_logon\n local now = os.time()\n local time = now - lastseen\n local minutes = math.floor(time / 60)\n local hours = math.floor(minutes / 60)\n local days = math.floor(hours / 24)\n minetest.chat_send_player(player, \"Last seen \"..days..\" day(s), \"..\n hours % 24 ..\" hour(s), \"..minutes % 60 ..\" minutes, \"..time % 60 ..\" second(s) ago.\")\n return true\n end\n},false)\n\n-------------------------------------------------------------------------------\n-- name: cmdhandler(playername,parameter)\n--\n--! @brief chat command handler\n--! @memberof factions_chat\n--! @private\n--\n--! @param playername name\n--! @param parameter data supplied to command\n-------------------------------------------------------------------------------\nfactions_chat.cmdhandler = function (playername,parameter)\n\tif not minetest.get_player_by_name(playername) then\n\t\treturn false, \"You cannot run faction commands unless you are online!\"\n\tend\n\n\tlocal player = minetest.env:get_player_by_name(playername)\n\tlocal params = parameter:split(\" \")\n local player_faction = factions.get_player_faction(playername)\n\n\tif parameter == nil or\n\t\tparameter == \"\" then\n if player_faction then\n minetest.chat_send_player(playername, \"You are in faction \"..player_faction.name..\". Type /f help for a list of commands.\")\n else\n minetest.chat_send_player(playername, \"You are part of no faction\")\n end\n\t\treturn\n\tend\n\n\tlocal cmd = factions.commands[params[1]]\n if not cmd then\n send_error(playername, \"Unknown command.\")\n return false\n end\n\n local argv = {}\n for i=2, #params, 1 do\n table.insert(argv, params[i])\n end\n\t\n cmd:run(playername, argv)\n\nend\n\nfunction table_Contains(t,v)\n\tfor k, a in pairs(t) do\n\t\tif a == v then\n\t\t\treturn true\n\t\tend\t\t\n\tend\n\treturn false\nend\n\n-------------------------------------------------------------------------------\n-- name: show_help(playername,parameter)\n--\n--! @brief send help message to player\n--! @memberof factions_chat\n--! @private\n--\n--! @param playername name\n-------------------------------------------------------------------------------\nfunction factions_chat.show_help(playername)\n\n\tlocal MSG = function(text)\n\t\tminetest.chat_send_player(playername,text,false)\n\tend\n\t\n\tMSG(\"factions mod\")\n\tMSG(\"Usage:\")\n\tlocal has, missing = minetest.check_player_privs(playername, {\n faction_admin = true})\n\t\n for k, v in pairs(factions.commands) do\n local args = {}\n\t\tif has or not table_Contains(v.global_privileges,\"faction_admin\") then\n\t\t\tfor i in ipairs(v.format) do\n\t\t\t\ttable.insert(args, v.format[i])\n\t\t\tend\n\t\t\tMSG(\"\\t/factions \"..k..\" <\"..table.concat(args, \"> <\")..\"> : \"..v.description)\n\t\tend\n end\nend\n\ninit_commands()\n\n"
},
{
"alpha_fraction": 0.7779898047447205,
"alphanum_fraction": 0.7849872708320618,
"avg_line_length": 39.30769348144531,
"blob_id": "2f4a8529778d25a43f9008f5b798ca270790ff9e",
"content_id": "8c3179a0ed8b9e17ddd0f972d3f5c582a488b0d5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1574,
"license_type": "permissive",
"max_line_length": 443,
"num_lines": 39,
"path": "/mods/latency_protection/README.md",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "# Latency Protection\nLatency protection mod attempts to prevent players from glitching through protected nodes. By either teleporting the player or damaging them.\n\n# Damage mode\nThis mode attempts to prevent players from glitching through protected nodes. By damaging players who interact with a protected position too fast.\n\n# Teleport mode\nThis mode attempts to prevent players from glitching through protected nodes. By recording position every 20 seconds (This can be changed in settings) and teleporting them if the protection interaction happens in a very quick time frame. If a player interacts with a protected node the position will not be recorded for an extra cycle. Before recording a position, the player’s avg_jitter is checked to make sure the player is not lagging out.\n\nThe timer for when to record a player position.\nThis only works if punishment is set to teleport.\n``` lua\nlatency_protection.timer = 20\n```\n\nThe max jitter a player can have before refusing the position update.\nThis only works if punishment is set to teleport.\n``` lua\nlatency_protection.jitter_max = 1.5\n```\n\nThe time limit between is_protected calls. If the function is called too fast the player will be teleport or damaged.\ntime_max is read in microseconds.\n``` lua\nlatency_protection.time_max = 2000\n```\n\nDamage amount to apply to the player.\nThis only works if punishment is set to damage.\n``` lua\nlatency_protection.damage = 3\n```\n\nSet what type of punishment to be given to a player.\nTeleport the player.\nDamage the player.\n``` lua\nlatency_protection.punishment = \"damage\"\n```\n"
},
{
"alpha_fraction": 0.6739436388015747,
"alphanum_fraction": 0.6820422410964966,
"avg_line_length": 32.80952453613281,
"blob_id": "b5b3e717670a7790abdbbf57810ae757fafd937a",
"content_id": "97edaa147f2b9503f3fad2e791e78f1c2327cf01",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 2840,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 84,
"path": "/mods/lava_ore_gen/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "lava_ore_gen = {}\nlava_ore_gen.blacklist = {}\n\nlocal stone_name = minetest.settings:get(\"lava_ore_gen.stone_name\") or \"default:stone\"\nlocal interval = tonumber(minetest.settings:get(\"lava_ore_gen.interval\")) or 20\nlocal chance = tonumber(minetest.settings:get(\"lava_ore_gen.chance\")) or 3600\nlocal random = minetest.settings:get_bool(\"lava_ore_gen.random\") or false\n\nlocal function create_hotstone()\n\tminetest.register_node(\"lava_ore_gen:stone_hot\", {name = \"lava_ore_gen:stone_hot\"})\nend\nlocal function override_hotstone()\n\tlocal clonenodeForLava = {}\n\tfor k, v in pairs(minetest.registered_nodes[stone_name]) do clonenodeForLava[k] = v end\n\tclonenodeForLava.name = \"lava_ore_gen:stone_hot\"\n\tclonenodeForLava.description = \"Heated Stone\"\n\tclonenodeForLava.groups.not_in_creative_inventory = 1\n\tclonenodeForLava.tiles = {\"default_stone.png^[colorize:red:20\"}\n\tclonenodeForLava.paramtype = \"light\"\n\tclonenodeForLava.light_source = 4\n\tclonenodeForLava.on_timer = function(pos)\n\t\tlocal node = minetest.find_node_near(pos, 1, {\"group:lava\"})\n\t\tif node then\n\t\t\tif not random then\n\t\t\t\t-- Get ores and rarities.\n\t\t\t\tlocal ore_map = {}\n\t\t\t\tfor i, v in next, minetest.registered_ores do\n\t\t\t\t\tlocal name = v.ore\n\t\t\t\t\tif not lava_ore_gen.blacklist[name] then\n\t\t\t\t\t\tif string.match(name, \":stone_with_\") or string.match(name, \":mineral_\") then\n\t\t\t\t\t\t\tlocal rarity = v.clust_scarcity - math.random(0, v.clust_scarcity + 1)\n\t\t\t\t\t\t\tore_map[i] = {rarity = rarity, name = name}\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\t-- Do math to pick a ore.\n\t\t\t\tlocal ore = {rarity = -1, name = stone_name}\n\t\t\t\tfor i, v in next, ore_map do\n\t\t\t\t\tif ore.rarity == -1 or ore.rarity > math.random(0, v.rarity) then\n\t\t\t\t\t\tore = v\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tminetest.set_node(pos, {name = ore.name})\n\t\t\telse\n\t\t\t\tlocal ore_map = {}\n\t\t\t\tfor i, v in next, minetest.registered_ores do\n\t\t\t\t\tlocal name = v.ore\n\t\t\t\t\tif not lava_ore_gen.blacklist[name] then\n\t\t\t\t\t\tore_map[#ore_map + 1] = name\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tminetest.set_node(pos, {name = ore_map[math.random(1, #ore_map + 1)]})\n\t\t\tend\n\t\telse\n\t\t\tminetest.set_node(pos, {name = stone_name})\n\t\tend\n\t\treturn true\n\tend\n\tminetest.register_node(\":lava_ore_gen:stone_hot\", clonenodeForLava)\nend\nlocal function override_stone()\n\t-- make stone floodable --\n\tminetest.override_item(stone_name, {\n\t\tfloodable = true,\n\t\ton_flood = function(pos, oldnode, newnode)\n\t\t\tlocal def = minetest.registered_items[newnode.name]\n\t\t\tif (def and def.groups and def.groups.lava and def.groups.lava > 0) then\n\t\t\t\tminetest.after(0, function(pos)\n\t\t\t\t\tminetest.set_node(pos, {name = \"lava_ore_gen:stone_hot\"})\n\t\t\t\t\tminetest.get_node_timer(pos):start(interval + math.random(1, chance + 1))\n\t\t\t\tend, pos)\n\t\t\telse\n\t\t\t\treturn true\n\t\t\tend\n\t\t\treturn false\n\t\tend,\n\t})\nend\n\ncreate_hotstone()\nminetest.register_on_mods_loaded(function()\n\toverride_hotstone()\n\toverride_stone()\nend)\n"
},
{
"alpha_fraction": 0.5763276219367981,
"alphanum_fraction": 0.5843461751937866,
"avg_line_length": 32.38215637207031,
"blob_id": "98bb4d02d498b5d17dc78461a11b801c626a98be",
"content_id": "0e66edf612ce03198a166caafba14f2b6347134d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 19830,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 594,
"path": "/mods/sscsm/csm_strict/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- SSCSM: Server-Sent Client-Side Mods proof-of-concept: \"Strict\" version\n--\n-- Copyright © 2019 by luk3yx\n--\n\n-- For debugging, this can be a global variable.\nlocal sscsm = {}\n\n-- Add a random number onto the current time in case servers try and predict\n-- the random seed\nmath.randomseed(os.time() + math.random(2, 1200))\n\nlocal storage = minetest.get_mod_storage()\n\n-- Load the Env class\n-- Mostly copied from https://stackoverflow.com/a/26367080\n-- Don't copy metatables\nlocal function copy(obj, s)\n if s and s[obj] ~= nil then return s[obj] end\n if type(obj) ~= 'table' then return obj end\n s = s or {}\n local res = {}\n s[obj] = res\n for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end\n return res\nend\n\n-- Safe functions\nlocal Env = {}\nlocal safe_funcs = {}\n\n-- No getmetatable()\nif rawget(_G, 'getmetatable') then\n safe_funcs[getmetatable] = function() end\nend\n\n-- Get the current value of string.rep in case other CSMs decide to break\ndo\n safe_funcs[math.randomseed] = function() end\n\n local rep = string.rep\n safe_funcs[string.rep] = function(str, n)\n if #str * n > 1048576 then\n error('string.rep: string length overflow', 2)\n end\n return rep(str, n)\n end\n\n local show_formspec = minetest.show_formspec\n safe_funcs[show_formspec] = function(formname, ...)\n if type(formname) == 'string' and formname:sub(1, 6) ~= 'sscsm:' then\n return show_formspec(formname, ...)\n end\n end\n\n local after = minetest.after\n safe_funcs[after] = function(n, ...)\n if type(n) == 'number' then return after(n, pcall, ...) end\n end\n\n local on_fs_input = minetest.register_on_formspec_input\n safe_funcs[on_fs_input] = function(func)\n on_fs_input(function(formname, fields)\n if formname:sub(1, 6) ~= 'sscsm:' then\n pcall(func, formname, copy(fields))\n end\n end)\n end\n\n local deserialize = minetest.deserialize\n safe_funcs[deserialize] = function(str)\n return deserialize(str, true)\n end\n\n local wrap = function(n)\n local orig = minetest[n] or minetest[n .. 's']\n if type(orig) == 'function' then\n return function(func)\n orig(function(...)\n local r = {pcall(func, ...)}\n if r[1] then\n table.remove(r, 1)\n return (table.unpack or unpack)(r)\n else\n minetest.log('error', '[SSCSM] ' .. tostring(r[2]))\n end\n end)\n end\n end\n end\n\n for _, k in ipairs({'register_globalstep', 'register_on_death',\n 'register_on_hp_modification', 'register_on_damage_taken',\n 'register_on_dignode', 'register_on_punchnode',\n 'register_on_placenode', 'register_on_item_use',\n 'register_on_modchannel_message', 'register_on_modchannel_signal',\n 'register_on_inventory_open', 'register_on_sending_chat_message',\n 'register_on_receiving_chat_message'}) do\n safe_funcs[minetest[k]] = wrap(k)\n end\nend\n\n-- Environment\nfunction Env.new_empty()\n local self = {_raw = {}, _seen = copy(safe_funcs)}\n self._raw['_G'] = self._raw\n return setmetatable(self, {__index = Env}) or self\nend\nfunction Env:get(k) return self._raw[self._seen[k] or k] end\nfunction Env:set(k, v) self._raw[copy(k, self._seen)] = copy(v, self._seen) end\nfunction Env:set_copy(k, v)\n self:set(k, v)\n self._seen[k] = nil\n self._seen[v] = nil\nend\nfunction Env:add_globals(...)\n for i = 1, select('#', ...) do\n local var = select(i, ...)\n self:set(var, _G[var])\n end\nend\nfunction Env:update(data) for k, v in pairs(data) do self:set(k, v) end end\nfunction Env:del(k)\n if self._seen[k] then\n self._raw[self._seen[k]] = nil\n self._seen[k] = nil\n end\n self._raw[k] = nil\nend\n\nfunction Env:copy()\n local new = {_seen = copy(safe_funcs)}\n new._raw = copy(self._raw, new._seen)\n return setmetatable(new, {__index = Env}) or new\nend\n\n-- Load code into a callable function.\nfunction Env:loadstring(code)\n if code:byte(1) == 27 then return nil, 'Invalid code!' end\n local f, msg = loadstring(code)\n if not f then return nil, msg end\n setfenv(f, self._raw)\n return function(...)\n local good, msg = pcall(f, ...)\n if good then\n return msg\n else\n minetest.log('error', '[SSCSM] ' .. tostring(msg))\n end\n end\nend\n\nfunction Env:exec(code)\n local f, msg = self:loadstring(code)\n if not f then\n minetest.log('error', '[SSCSM] Syntax error: ' .. tostring(msg))\n return false\n end\n f()\n return true\nend\n\n-- Create the \"base\" environment\nlocal base_env = Env:new_empty()\nfunction Env.new() return base_env:copy() end\n\n-- Clone everything\nbase_env:add_globals('dump', 'dump2', 'error', 'ipairs', 'math', 'next',\n 'pairs', 'pcall', 'select', 'setmetatable', 'string', 'table', 'tonumber',\n 'tostring', 'type', 'vector', 'xpcall', '_VERSION')\n\nbase_env:set_copy('os', {clock = os.clock, difftime = os.difftime,\n time = os.time})\n\n-- Create a slightly locked down \"minetest\" table\ndo\n local t = {}\n for _, k in ipairs({\"add_particle\", \"add_particlespawner\", \"after\",\n \"camera\", \"clear_out_chat_queue\", \"colorize\", \"compress\", \"debug\",\n \"decode_base64\", \"decompress\", \"delete_particlespawner\",\n \"deserialize\", \"disconnect\", \"display_chat_message\",\n \"encode_base64\", \"explode_scrollbar_event\", \"explode_table_event\",\n \"explode_textlist_event\", \"find_node_near\", \"formspec_escape\",\n \"get_background_escape_sequence\", \"get_color_escape_sequence\",\n \"get_day_count\", \"get_item_def\", \"get_language\", \"get_meta\",\n \"get_node_def\", \"get_node_level\", \"get_node_max_level\",\n \"get_node_or_nil\", \"get_player_names\", \"get_privilege_list\",\n \"get_server_info\", \"get_timeofday\", \"get_translator\",\n \"get_us_time\", \"get_version\", \"get_wielded_item\", \"gettext\",\n \"is_nan\", \"is_yes\", \"localplayer\", \"log\",\n \"mod_channel_join\", \"parse_json\", \"pointed_thing_to_face_pos\",\n \"pos_to_string\", \"privs_to_string\", \"register_globalstep\",\n \"register_on_damage_taken\", \"register_on_death\",\n \"register_on_dignode\", \"register_on_formspec_input\",\n \"register_on_hp_modification\", \"register_on_inventory_open\",\n \"register_on_item_use\", \"register_on_modchannel_message\",\n \"register_on_modchannel_signal\", \"register_on_placenode\",\n \"register_on_punchnode\", \"register_on_receiving_chat_message\",\n \"register_on_sending_chat_message\", \"rgba\",\n \"run_server_chatcommand\", \"send_chat_message\", \"send_respawn\",\n \"serialize\", \"sha1\", \"show_formspec\", \"sound_play\", \"sound_stop\",\n \"string_to_area\", \"string_to_pos\", \"string_to_privs\",\n \"strip_background_colors\", \"strip_colors\",\n \"strip_foreground_colors\", \"translate\", \"ui\", \"wrap_text\",\n \"write_json\"}) do\n local func = minetest[k]\n t[k] = safe_funcs[func] or func\n end\n\n base_env:set_copy('minetest', t)\nend\n\n-- Add table.unpack\nif not table.unpack then\n base_env._raw.table.unpack = unpack\nend\n\n-- Make sure copy() worked correctly\nassert(base_env._raw.minetest.register_on_sending_chat_message ~=\n minetest.register_on_sending_chat_message, 'Error in copy()!')\n\n-- SSCSM functions\n-- When calling these from an SSCSM, make sure they exist first.\nlocal mod_channel = minetest.mod_channel_join('sscsm:exec_pipe')\nlocal loaded_sscsms = {}\nbase_env:set('join_mod_channel', function()\n if not mod_channel then\n mod_channel = minetest.mod_channel_join('sscsm:exec_pipe')\n end\nend)\n\nlocal function leave_mod_channel()\n if mod_channel then\n mod_channel:leave()\n mod_channel = false\n end\nend\nbase_env:set('leave_mod_channel', leave_mod_channel)\n\n-- Allow other CSMs to access the new Environment type\nsscsm.Env = Env\n\n-- Get the address\nlocal get_address\ndo\n local addr\n function get_address()\n if not addr then\n local info = minetest.get_server_info()\n addr = tostring(info.address)\n if addr == '' then\n addr = 'singleplayer'\n else\n addr = addr .. ':' .. tostring(info.port)\n end\n end\n return addr\n end\nend\n\n-- Get trusted SSCSMs\nlocal trust, trustdb\nlocal function is_sscsm_trusted(name, code)\n if sscsm.allowed or trust then return true end\n\n -- Don't return false if trust is nil.\n if trust == false then return false end\n\n if code == nil and type(name) == 'table' then\n name, code = name.name, name.code\n end\n if type(name) ~= 'string' or type(code) ~= 'string' then return false end\n\n if not trustdb then\n local raw = storage:get_string('trust-' .. get_address())\n if raw then trustdb = minetest.deserialize(raw) end\n trustdb = trustdb or {}\n end\n\n if trustdb[name] == code then\n return true\n else\n trust = false\n return false\n end\nend\n\n-- exec() code sent by the server.\nlocal sscsm_queue = {}\n\nminetest.register_on_modchannel_message(function(channel_name, sender, message)\n if channel_name ~= 'sscsm:exec_pipe' or (sender and sender ~= '')\n or #sscsm_queue > 512 then\n return\n end\n\n -- The first character is currently a version code, currently 0.\n -- Do not change unless absolutely necessary.\n local version = message:sub(1, 1)\n local name, code\n if version == '0' then\n local s, e = message:find('\\n')\n if not s or not e then return end\n local target = message:sub(2, s - 1)\n if target ~= minetest.localplayer:get_name() then return end\n message = message:sub(e + 1)\n local s, e = message:find('\\n')\n if not s or not e then return end\n name = message:sub(1, s - 1)\n code = message:sub(e + 1)\n else\n return\n end\n\n -- Don't load the same SSCSM twice\n if not loaded_sscsms[name] then\n loaded_sscsms[name] = true\n if sscsm.allowed or is_sscsm_trusted(name, code) then\n -- Create the environment\n minetest.log('action', '[SSCSM] Loading ' .. name)\n if not sscsm.env then sscsm.env = Env:new() end\n sscsm.env:exec(code)\n elseif sscsm_queue then\n if sscsm.allowed == nil then\n local a = get_address()\n minetest.display_chat_message(minetest.colorize('#eeeeee',\n '[SSCSM] This server (' .. minetest.formspec_escape(a) ..\n ') wants to run sandboxed code on your client. ' ..\n 'Run .sscsm to allow or deny this.'))\n if sscsm.env then\n minetest.display_chat_message(minetest.colorize('yellow',\n '[SSCSM] WARNING: New SSCSMs have been added or '\n .. 'modified since you last trusted this server. '\n .. 'SSCSMs are in a partially loaded state, '\n .. 'please run .sscsm and fix this.'))\n end\n sscsm.allowed = false\n end\n table.insert(sscsm_queue, {name=name, code=code})\n end\n end\nend)\n\n-- Send \"0\"\nlocal function request_csms(c)\n c = c or 10\n if c <= 0 then return leave_mod_channel() end\n if minetest.localplayer and mod_channel:is_writeable() then\n mod_channel:send_all('0')\n else\n minetest.after(0.1, request_csms, c - 1)\n end\nend\nminetest.after(0, request_csms)\n\n-- \"Securely\" display a formspec\nlocal function random_identifier()\n return tostring(math.random() + math.random(0, 1000000000))\nend\n\nlocal secure_show_formspec, current_formname\nlocal inspecting = false\ndo\n local _show_formspec = minetest.show_formspec\n function secure_show_formspec(spec, preserve)\n if preserve == nil then\n inspecting = false\n end\n\n -- Regenerate the formname every time.\n current_formname = 'sscsm:' .. random_identifier()\n\n -- Display the formspec\n _show_formspec(current_formname, spec)\n end\nend\n\nlocal allow_id, deny_id, inspect_id, checkbox_id\nlocal function show_default_formspec()\n leave_mod_channel()\n local allow_text, deny_text, allowed\n if sscsm.allowed or (sscsm.env and sscsm_queue and #sscsm_queue == 0) then\n deny_text = 'Exit to menu'\n allow_text = 'Close dialog'\n allowed = minetest.colorize('orange', 'running')\n elseif sscsm_queue then\n allow_text = 'Allow'\n\n if sscsm.env then\n allowed = minetest.colorize('red', 'partially running')\n deny_text = 'Exit to menu'\n else\n allowed = 'inactive'\n deny_text = 'Deny'\n end\n else\n allowed = minetest.colorize('lightgreen', 'disabled')\n end\n\n -- Randomly generate identifiers\n allow_id = 'btn_' .. random_identifier()\n deny_id = allow_id\n while deny_id == allow_id do\n deny_id = 'btn_' .. random_identifier()\n end\n\n local formspec = 'size[8,4]no_prepend[]' ..\n 'image_button[0,0;8,1;;ignore;SSCSM;true;false;]' ..\n 'label[0,1;SSCSMs are currently ' ..\n minetest.formspec_escape(allowed) .. '.]'\n\n if allow_text == 'Allow' then\n inspect_id = allow_id\n while inspect_id == allow_id or inspect_id == deny_id do\n inspect_id = 'btn_' .. random_identifier()\n end\n formspec = formspec ..\n 'label[0,1.5;Do you want to allow this server to ' ..\n 'execute (sandboxed) code locally?]' ..\n 'image_button[6,0.2;2,0.6;;' .. inspect_id ..\n ';Inspect code;true;true;]'\n else\n inspect_id = nil\n formspec = formspec ..\n 'label[0,1.5;You cannot change this without reconnecting.]'\n end\n\n if sscsm.allowed or sscsm_queue then\n local tr = trust\n if tr == nil and sscsm.env and sscsm_queue and #sscsm_queue == 0 then\n tr = true\n end\n\n if tr or sscsm_queue then\n checkbox_id = allow_id\n while checkbox_id == allow_id or checkbox_id == deny_id or\n checkbox_id == inspect_id do\n checkbox_id = 'btn_' .. random_identifier()\n end\n\n formspec = formspec ..'checkbox[0,2;' .. checkbox_id ..\n ';Permanently allow these SSCSMs.;' ..\n (tr and 'true' or 'false') .. ']'\n else\n checkbox_id = nil\n formspec = formspec ..'checkbox[0,2;ignore;' ..\n minetest.colorize('#888888',\n 'Permanently allow these SSCSMs.') .. ';false]'\n end\n\n else\n checkbox_id = nil\n end\n\n if allow_text and deny_text then\n formspec = formspec .. 'button_exit[0,3;4,1;' .. deny_id .. ';' ..\n minetest.formspec_escape(deny_text) .. ']' ..\n 'button_exit[4,3;4,1;' .. allow_id .. ';' ..\n minetest.formspec_escape(allow_text) .. ']'\n else\n formspec = formspec .. 'button_exit[0,3;8,1;' .. deny_id\n .. ';Close dialog]'\n end\n\n secure_show_formspec(formspec)\nend\n\n-- The inspect formspec\nlocal inspect_file = 1\n\nlocal function show_inspect_formspec()\n if not sscsm_queue then return end\n\n if not inspecting then\n inspecting = random_identifier()\n minetest.display_chat_message('[SSCSM] If the number displayed in' ..\n ' the inspector changes, the server has tampered with it and ' ..\n 'you should not allow SSCSMs.')\n end\n inspect_id = random_identifier()\n deny_id = inspect_id\n while deny_id == inspect_id do deny_id = random_identifier() end\n\n local formspec = 'size[10,9]no_prepend[]' ..\n 'label[0,0;SSCSM: Code Inspector.\\n\\n' ..\n minetest.colorize('#eeeeee', 'This number should not change while ' ..\n 'the inspector is running:\\n' .. tostring(inspecting)) .. ']' ..\n 'button[9,0;1,1;' .. deny_id .. ';X]' ..\n 'textlist[0,2;2,7;' .. tostring(inspect_id) .. ';'\n\n for id, code in ipairs(sscsm_queue) do\n if id > 1 then formspec = formspec .. ',' end\n formspec = formspec .. '##' .. minetest.formspec_escape(code.name)\n end\n\n formspec = formspec .. ';' .. inspect_file .. ']' ..\n 'textarea[2.5,2;7.75,8.2;;Code:;'\n\n if sscsm_queue[inspect_file] then\n formspec = formspec ..\n minetest.formspec_escape(sscsm_queue[inspect_file].code)\n end\n\n secure_show_formspec(formspec .. ']box[2.2,2;7.5,7;#000000]', true)\nend\n\n-- Handle formspec input\nminetest.register_on_formspec_input(function(formname, fields)\n -- Sanity check\n if not current_formname or formname ~= current_formname then return end\n\n -- Minetest doesn't(?) leak the formname, however this is still here in\n -- case that changes in the future (or for if the server can somehow trick\n -- the client into leaking formspec inputs).\n current_formname = false\n\n -- Check for options\n if inspecting then\n if fields.quit then\n inspecting = false\n minetest.after(0.1, show_default_formspec)\n return true\n elseif fields[deny_id] then\n inspecting = false\n show_default_formspec()\n return true\n elseif fields[inspect_id] then\n local event = minetest.explode_textlist_event(fields[inspect_id])\n if event.type == 'CHG' then inspect_file = event.index end\n end\n\n show_inspect_formspec()\n elseif fields[deny_id] then\n if sscsm.allowed or sscsm.env then\n minetest.disconnect()\n end\n if sscsm_queue then\n sscsm_queue = false\n minetest.display_chat_message('[SSCSM] SSCSMs have been denied.')\n storage:set_string('trust-' .. get_address(), '')\n end\n elseif fields[allow_id] then\n if sscsm.allowed or (sscsm_queue and #sscsm_queue == 0) then\n return true\n end\n\n minetest.display_chat_message('[SSCSM] SSCSMs have been allowed.')\n sscsm.allowed = true\n if sscsm_queue then\n if not sscsm.env then sscsm.env = Env:new() end\n local mods\n if trust then mods = {} end\n for _, def in ipairs(sscsm_queue) do\n minetest.log('action', '[SSCSM] Loading ' .. def.name)\n if mods then mods[def.name] = def.code end\n sscsm.env:exec(def.code)\n end\n if mods then\n storage:set_string('trust-' .. get_address(),\n minetest.serialize(mods))\n end\n end\n sscsm_queue = false\n elseif fields[inspect_id] then\n inspect_file = 1\n show_inspect_formspec()\n elseif fields.quit then\n minetest.display_chat_message(minetest.colorize('#eeeeee',\n '[SSCSM] No action specified.'))\n elseif fields[checkbox_id] then\n trust = minetest.is_yes(fields[checkbox_id])\n if not trust then\n storage:set_string('trust-' .. get_address(), '')\n end\n show_default_formspec()\n else\n show_default_formspec()\n end\n\n return true\nend)\n\n-- Add .sscsm\nminetest.register_chatcommand('sscsm', {\n descrption = 'Displays SSCSM options for this server.',\n func = function(param)\n if sscsm.allowed == nil and not sscsm.env then\n return false, 'This server has not attempted to load any SSCSMs.'\n else\n show_default_formspec()\n end\n end\n})\n"
},
{
"alpha_fraction": 0.6363636255264282,
"alphanum_fraction": 0.6513441205024719,
"avg_line_length": 23.48492431640625,
"blob_id": "d8f7b5e94ec79351f2326402fd39014939e6a900",
"content_id": "dba44ebd908cc200e24fbdedcab76ab86b11c848",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 9746,
"license_type": "permissive",
"max_line_length": 130,
"num_lines": 398,
"path": "/mods/tnt/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "\n--[[ Default to enabled in singleplayer and disabled in multiplayer\nlocal singleplayer = minetest.is_singleplayer()\nlocal setting = minetest.setting_getbool(\"enable_tnt\")\nif (not singleplayer and setting ~= true) or\n\t\t(singleplayer and setting == false) then\n\treturn\nend--]]\n\n-- loss probabilities array (one in X will be lost)\nlocal loss_prob = {}\n\nloss_prob[\"default:cobble\"] = 3\nloss_prob[\"default:dirt\"] = 4\n\nlocal radius = tonumber(minetest.setting_get(\"tnt_radius\") or 2)\n\n-- Fill a list with data for content IDs, after all nodes are registered\nlocal cid_data = {}\nminetest.after(0, function()\n\tfor name, def in pairs(minetest.registered_nodes) do\n\t\tcid_data[minetest.get_content_id(name)] = {\n\t\t\tname = name,\n\t\t\tdrops = def.drops,\n\t\t\tflammable = def.groups.flammable,\n\t\t\ton_blast = def.on_blast,\n\t\t}\n\tend\nend)\n\nlocal function rand_pos(center, pos, radius)\n\tlocal def\n\tlocal reg_nodes = minetest.registered_nodes\n\tlocal i = 0\n\trepeat\n\t\t-- Give up and use the center if this takes too long\n\t\tif i > 4 then\n\t\t\tpos.x, pos.z = center.x, center.z\n\t\t\tbreak\n\t\tend\n\t\tpos.x = center.x + math.random(-radius, radius)\n\t\tpos.z = center.z + math.random(-radius, radius)\n\t\tdef = reg_nodes[minetest.get_node(pos).name]\n\t\ti = i + 1\n\tuntil def and not def.walkable\nend\n\nlocal function eject_drops(drops, pos, radius)\n\tlocal drop_pos = vector.new(pos)\n\tfor _, item in pairs(drops) do\n\t\tlocal count = item:get_count()\n\t\tlocal max = item:get_stack_max()\n\t\tif count > max then\n\t\t\titem:set_count(max)\n\t\tend\n\t\twhile count > 0 do\n\t\t\tif count < max then\n\t\t\t\titem:set_count(count)\n\t\t\tend\n\t\t\trand_pos(pos, drop_pos, radius)\n\t\t\tlocal obj = minetest.add_item(drop_pos, item)\n\t\t\tif obj then\n\t\t\t\tobj:get_luaentity().collect = true\n\t\t\t\tobj:setacceleration({x=0, y=-10, z=0})\n\t\t\t\tobj:setvelocity({x=math.random(-3, 3), y=10,\n\t\t\t\t\t\tz=math.random(-3, 3)})\n\t\t\tend\n\t\t\tcount = count - max\n\t\tend\n\tend\nend\n\nlocal function add_drop(drops, item)\n\titem = ItemStack(item)\n\tlocal name = item:get_name()\n\tif loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then\n\t\treturn\n\tend\n\n\tlocal drop = drops[name]\n\tif drop == nil then\n\t\tdrops[name] = item\n\telse\n\t\tdrop:set_count(drop:get_count() + item:get_count())\n\tend\nend\n\nlocal fire_node = {name=\"fire:basic_flame\"}\n\nlocal function destroy(drops, pos, cid)\n\tif minetest.is_protected(pos, \"\") then\n\t\treturn\n\tend\n\tlocal def = cid_data[cid]\n\tif def and def.on_blast then\n\t\tdef.on_blast(vector.new(pos), 1)\n\t\treturn\n\tend\n\tif def and def.flammable then\n\t\tminetest.set_node(pos, fire_node)\n\telse\n\t\tminetest.remove_node(pos)\n\t\tif def then\n\t\t\tlocal node_drops = minetest.get_node_drops(def.name, \"\")\n\t\t\tfor _, item in ipairs(node_drops) do\n\t\t\t\tadd_drop(drops, item)\n\t\t\tend\n\t\tend\n\tend\nend\n\n\nlocal function calc_velocity(pos1, pos2, old_vel, power)\n\tlocal vel = vector.direction(pos1, pos2)\n\tvel = vector.normalize(vel)\n\tvel = vector.multiply(vel, power)\n\n\t-- Divide by distance\n\tlocal dist = vector.distance(pos1, pos2)\n\tdist = math.max(dist, 1)\n\tvel = vector.divide(vel, dist)\n\n\t-- Add old velocity\n\tvel = vector.add(vel, old_vel)\n\treturn vel\nend\n\nlocal function entity_physics(pos, radius)\n\t-- Make the damage radius larger than the destruction radius\n\tradius = radius * 2\n\tlocal objs = minetest.get_objects_inside_radius(pos, radius)\n\tfor _, obj in pairs(objs) do\n\t\tlocal obj_pos = obj:getpos()\n\t\tlocal obj_vel = obj:getvelocity()\n\t\tlocal dist = math.max(1, vector.distance(pos, obj_pos))\n\n\t\tif obj_vel ~= nil then\n\t\t\tobj:setvelocity(calc_velocity(pos, obj_pos,\n\t\t\t\t\tobj_vel, radius * 10))\n\t\tend\n\n\t\tlocal damage = (4 / dist) * radius\n\t\tobj:set_hp(obj:get_hp() - damage)\n\tend\nend\n\nlocal function add_effects(pos, radius)\n\tminetest.add_particlespawner({\n\t\tamount = 128,\n\t\ttime = 1,\n\t\tminpos = vector.subtract(pos, radius / 2),\n\t\tmaxpos = vector.add(pos, radius / 2),\n\t\tminvel = {x=-20, y=-20, z=-20},\n\t\tmaxvel = {x=20, y=20, z=20},\n\t\tminacc = vector.new(),\n\t\tmaxacc = vector.new(),\n\t\tminexptime = 1,\n\t\tmaxexptime = 3,\n\t\tminsize = 8,\n\t\tmaxsize = 16,\n\t\ttexture = \"tnt_smoke.png\",\n\t})\nend\n\nlocal function burn(pos)\n\tlocal name = minetest.get_node(pos).name\n\tif name == \"tnt:tnt\" then\n\t\tminetest.sound_play(\"tnt_ignite\", {pos=pos})\n\t\tminetest.set_node(pos, {name=\"tnt:tnt_burning\"})\n\t\tminetest.get_node_timer(pos):start(1)\n\telseif name == \"tnt:gunpowder\" then\n\t\tminetest.sound_play(\"tnt_gunpowder_burning\", {pos=pos, gain=2})\n\t\tminetest.set_node(pos, {name=\"tnt:gunpowder_burning\"})\n\t\tminetest.get_node_timer(pos):start(1)\n\tend\nend\n\nlocal function explode(pos, radius)\n\tlocal pos = vector.round(pos)\n\tlocal vm = VoxelManip()\n\tlocal pr = PseudoRandom(os.time())\n\tlocal p1 = vector.subtract(pos, radius)\n\tlocal p2 = vector.add(pos, radius)\n\tlocal minp, maxp = vm:read_from_map(p1, p2)\n\tlocal a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})\n\tlocal data = vm:get_data()\n\n\tlocal drops = {}\n\tlocal p = {}\n\n\tlocal c_air = minetest.get_content_id(\"air\")\n\n\tfor z = -radius, radius do\n\tfor y = -radius, radius do\n\tlocal vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)\n\tfor x = -radius, radius do\n\t\tif (x * x) + (y * y) + (z * z) <=\n\t\t\t\t(radius * radius) + pr:next(-radius, radius) then\n\t\t\tlocal cid = data[vi]\n\t\t\tp.x = pos.x + x\n\t\t\tp.y = pos.y + y\n\t\t\tp.z = pos.z + z\n\t\t\tif cid ~= c_air then\n\t\t\t\tdestroy(drops, p, cid)\n\t\t\tend\n\t\tend\n\t\tvi = vi + 1\n\tend\n\tend\n\tend\n\n\treturn drops\nend\n\n\nlocal function boom(pos)\n\tminetest.sound_play(\"tnt_explode\", {pos=pos, gain=1.5, max_hear_distance=2*64})\n\tminetest.set_node(pos, {name=\"tnt:boom\"})\n\tminetest.get_node_timer(pos):start(0.5)\n\n\tlocal drops = explode(pos, radius)\n\tentity_physics(pos, radius)\n\teject_drops(drops, pos, radius)\n\tadd_effects(pos, radius)\nend\n\nminetest.register_node(\"tnt:tnt\", {\n\tdescription = \"TNT\",\n\ttiles = {\"tnt_top.png\", \"tnt_bottom.png\", \"tnt_side.png\"},\n\tis_ground_content = false,\n\tgroups = {dig_immediate=2, mesecon=2},\n\tsounds = default.node_sound_wood_defaults(),\n\ton_punch = function(pos, node, puncher)\n\t\tif puncher:get_wielded_item():get_name() == \"default:torch\" then\n\t\t\tminetest.sound_play(\"tnt_ignite\", {pos=pos})\n\t\t\tminetest.set_node(pos, {name=\"tnt:tnt_burning\"})\n\t\tend\n\tend,\n\ton_blast = function(pos, intensity)\n\t\tburn(pos)\n\tend,\n\tmesecons = {effector = {action_on = boom}},\n})\n\nminetest.register_node(\"tnt:tnt_burning\", {\n\ttiles = {\n\t\t{\n\t\t\tname = \"tnt_top_burning_animated.png\",\n\t\t\tanimation = {\n\t\t\t\ttype = \"vertical_frames\",\n\t\t\t\taspect_w = 16,\n\t\t\t\taspect_h = 16,\n\t\t\t\tlength = 1,\n\t\t\t}\n\t\t},\n\t\t\"tnt_bottom.png\", \"tnt_side.png\"},\n\tlight_source = 5,\n\tdrop = \"\",\n\tsounds = default.node_sound_wood_defaults(),\n\ton_construct = function(pos)\n\t\tminetest.get_node_timer(pos):start(4)\n\tend,\n\ton_timer = boom,\n\t-- unaffected by explosions\n\ton_blast = function() end,\n})\n\nminetest.register_node(\"tnt:boom\", {\n\tdrawtype = \"plantlike\",\n\ttiles = {\"tnt_boom.png\"},\n\tlight_source = default.LIGHT_MAX,\n\twalkable = false,\n\tdrop = \"\",\n\tgroups = {dig_immediate=3},\n\ton_timer = function(pos, elapsed)\n\t\tminetest.remove_node(pos)\n\tend,\n\t-- unaffected by explosions\n\ton_blast = function() end,\n})\n\nminetest.register_node(\"tnt:gunpowder\", {\n\tdescription = \"Gun Powder\",\n\tdrawtype = \"raillike\",\n\tparamtype = \"light\",\n\tis_ground_content = false,\n\tsunlight_propagates = true,\n\twalkable = false,\n\ttiles = {\"tnt_gunpowder_straight.png\", \"tnt_gunpowder_curved.png\", \"tnt_gunpowder_t_junction.png\", \"tnt_gunpowder_crossing.png\"},\n\tinventory_image = \"tnt_gunpowder_inventory.png\",\n\twield_image = \"tnt_gunpowder_inventory.png\",\n\tselection_box = {\n\t\ttype = \"fixed\",\n\t\tfixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},\n\t},\n\tgroups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group(\"gunpowder\")},\n\tsounds = default.node_sound_leaves_defaults(),\n\t\n\ton_punch = function(pos, node, puncher)\n\t\tif puncher:get_wielded_item():get_name() == \"default:torch\" then\n\t\t\tburn(pos)\n\t\tend\n\tend,\n\ton_blast = function(pos, intensity)\n\t\tburn(pos)\n\tend,\n})\n\nminetest.register_node(\"tnt:gunpowder_burning\", {\n\tdrawtype = \"raillike\",\n\tparamtype = \"light\",\n\tsunlight_propagates = true,\n\twalkable = false,\n\tlight_source = 5,\n\ttiles = {{\n\t\tname = \"tnt_gunpowder_burning_straight_animated.png\",\n\t\tanimation = {\n\t\t\ttype = \"vertical_frames\",\n\t\t\taspect_w = 16,\n\t\t\taspect_h = 16,\n\t\t\tlength = 1,\n\t\t}\n\t},\n\t{\n\t\tname = \"tnt_gunpowder_burning_curved_animated.png\",\n\t\tanimation = {\n\t\t\ttype = \"vertical_frames\",\n\t\t\taspect_w = 16,\n\t\t\taspect_h = 16,\n\t\t\tlength = 1,\n\t\t}\n\t},\n\t{\n\t\tname = \"tnt_gunpowder_burning_t_junction_animated.png\",\n\t\tanimation = {\n\t\t\ttype = \"vertical_frames\",\n\t\t\taspect_w = 16,\n\t\t\taspect_h = 16,\n\t\t\tlength = 1,\n\t\t}\n\t},\n\t{\n\t\tname = \"tnt_gunpowder_burning_crossing_animated.png\",\n\t\tanimation = {\n\t\t\ttype = \"vertical_frames\",\n\t\t\taspect_w = 16,\n\t\t\taspect_h = 16,\n\t\t\tlength = 1,\n\t\t}\n\t}},\n\tselection_box = {\n\t\ttype = \"fixed\",\n\t\tfixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},\n\t},\n\tdrop = \"\",\n\tgroups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group(\"gunpowder\")},\n\tsounds = default.node_sound_leaves_defaults(),\n\ton_timer = function(pos, elapsed)\n\t\tfor dx = -1, 1 do\n\t\tfor dz = -1, 1 do\n\t\tfor dy = -1, 1 do\n\t\t\tif not (dx == 0 and dz == 0) then\n\t\t\t\tburn({\n\t\t\t\t\tx = pos.x + dx,\n\t\t\t\t\ty = pos.y + dy,\n\t\t\t\t\tz = pos.z + dz,\n\t\t\t\t})\n\t\t\tend\n\t\tend\n\t\tend\n\t\tend\n\t\tminetest.remove_node(pos)\n\tend,\n\t-- unaffected by explosions\n\ton_blast = function() end,\n})\n\nminetest.register_abm({\n\tnodenames = {\"tnt:tnt\", \"tnt:gunpowder\"},\n\tneighbors = {\"fire:basic_flame\", \"default:lava_source\", \"default:lava_flowing\"},\n\tinterval = 4,\n\tchance = 1,\n\taction = burn,\n})\n\nminetest.register_craft({\n\toutput = \"tnt:gunpowder\",\n\ttype = \"shapeless\",\n\trecipe = {\"default:coal_lump\", \"default:gravel\"}\n})\n\nminetest.register_craft({\n\toutput = \"tnt:tnt\",\n\trecipe = {\n\t\t{\"\", \"group:wood\", \"\"},\n\t\t{\"group:wood\", \"tnt:gunpowder\", \"group:wood\"},\n\t\t{\"\", \"group:wood\", \"\"}\n\t}\n})\n"
},
{
"alpha_fraction": 0.6093366146087646,
"alphanum_fraction": 0.6289926171302795,
"avg_line_length": 23,
"blob_id": "a4dc5259150101da1f25ec763328f888b5276e97",
"content_id": "78eaeeabd6052623282bb58808846c08b0ae4687",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 407,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 17,
"path": "/mods/tnt/taghide/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "minetest.register_on_joinplayer(function(player)\n if not player.tag then\n\t\t\tplayer:set_nametag_attributes({\n\t\t\t\tcolor = {a = 0, r = 0, g = 0, b = 0}\n\t\t\t})\n end\nend)\n\nminetest.register_globalstep(function(dtime)\nfor _, player in ipairs(minetest.get_connected_players()) do\n if not player.tag then\n \t\t\tplayer:set_nametag_attributes({\n\t\t\t\tcolor = {a = 0, r = 0, g = 0, b = 0}\n\t\t\t})\n end\nend\nend)"
},
{
"alpha_fraction": 0.5759766101837158,
"alphanum_fraction": 0.5830321907997131,
"avg_line_length": 26.9375,
"blob_id": "d1a3e61ee47d2c3765eb51d80e8d80f62584c03c",
"content_id": "15977082785d0e7022148727b6948fb382b026a4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 5812,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 208,
"path": "/mods/sscsm/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "--\n-- SSCSM: Server-Sent Client-Side Mods proof-of-concept\n--\n-- Copyright © 2019 by luk3yx\n--\n\nlocal modname = minetest.get_current_modname()\n\n-- If this is running as a CSM (improper installation), load the CSM code.\nif INIT == 'client' then\n dofile(modname .. ':csm/init.lua')\n return\nend\n\nlocal sscsm = {minify=true}\n_G[modname] = sscsm\nlocal modpath = minetest.get_modpath(modname)\n\n-- Remove excess whitespace from code to allow larger files to be sent.\nif sscsm.minify then\n local f = loadfile(modpath .. '/minify.lua')\n if f then\n sscsm.minify_code = f()\n else\n minetest.log('warning', '[SSCSM] Could not load minify.lua!')\n end\nend\n\nif not sscsm.minify_code then\n function sscsm.minify_code(code)\n assert(type(code) == 'string')\n return code\n end\nend\n\n-- Register code\nsscsm.registered_csms = {}\nlocal csm_order = false\n\n-- Recalculate the CSM loading order\n-- TODO: Make this nicer\nlocal function recalc_csm_order()\n local loaded = {}\n local staging = {}\n local order = {':init'}\n local unsatisfied = {}\n for name, def in pairs(sscsm.registered_csms) do\n assert(name == def.name)\n if name:sub(1, 1) == ':' then\n loaded[name] = true\n elseif not def.depends or #def.depends == 0 then\n loaded[name] = true\n table.insert(staging, name)\n else\n unsatisfied[name] = {}\n for _, mod in ipairs(def.depends) do\n if mod:sub(1, 1) ~= ':' then\n unsatisfied[name][mod] = true\n end\n end\n end\n end\n while #staging > 0 do\n local name = staging[1]\n for name2, u in pairs(unsatisfied) do\n if u[name] then\n u[name] = nil\n if #u == 0 then\n table.insert(staging, name2)\n end\n end\n end\n\n table.insert(order, name)\n table.remove(staging, 1)\n end\n\n for name, u in pairs(unsatisfied) do\n if next(u) then\n local msg = 'SSCSM \"' .. name .. '\" has unsatisfied dependencies: '\n local n = false\n for dep, _ in pairs(u) do\n if n then msg = msg .. ', ' else n = true end\n msg = msg .. '\"' .. dep .. '\"'\n end\n minetest.log('error', msg)\n end\n end\n\n -- Set csm_order\n table.insert(order, ':cleanup')\n csm_order = order\nend\n\n-- Register SSCSMs\nlocal block_colon = false\nsscsm.registered_csms = {}\nfunction sscsm.register(def)\n -- Read files now in case MT decides to block access later.\n if not def.code and def.file then\n local f = io.open(def.file, 'rb')\n if not f then\n error('Invalid \"file\" parameter passed to sscsm.register_csm.', 2)\n end\n def.code = f:read('*a')\n f:close()\n def.file = nil\n end\n\n if type(def.name) ~= 'string' or def.name:find('\\n')\n or (def.name:sub(1, 1) == ':' and block_colon) then\n error('Invalid \"name\" parameter passed to sscsm.register_csm.', 2)\n end\n\n if type(def.code) ~= 'string' then\n error('Invalid \"code\" parameter passed to sscsm.register_csm.', 2)\n end\n\n def.code = sscsm.minify_code(def.code)\n if (#def.name + #def.code) > 65300 then\n error('The code (or name) passed to sscsm.register_csm is too large.'\n .. ' Consider refactoring your SSCSM code.', 2)\n end\n\n -- Copy the table to prevent mods from betraying our trust.\n sscsm.registered_csms[def.name] = table.copy(def)\n if csm_order then recalc_csm_order() end\nend\n\nfunction sscsm.unregister(name)\n sscsm.registered_csms[name] = nil\n if csm_order then recalc_csm_order() end\nend\n\n-- Recalculate the CSM order once all other mods are loaded\nminetest.register_on_mods_loaded(recalc_csm_order)\n\n-- Handle players joining\nlocal mod_channel = minetest.mod_channel_join('sscsm:exec_pipe')\nminetest.register_on_modchannel_message(function(channel_name, sender, message)\n if channel_name ~= 'sscsm:exec_pipe' or not sender or\n not mod_channel:is_writeable() or message ~= '0' or\n sender:find('\\n') then\n return\n end\n minetest.log('action', '[SSCSM] Sending CSMs on request for ' .. sender\n .. '...')\n for _, name in ipairs(csm_order) do\n mod_channel:send_all('0' .. sender .. '\\n' .. name\n .. '\\n' .. sscsm.registered_csms[name].code)\n end\nend)\n\n-- Register the SSCSM \"builtins\"\nsscsm.register({\n name = ':init',\n file = modpath .. '/sscsm_init.lua'\n})\n\nsscsm.register({\n name = ':cleanup',\n code = 'sscsm._done_loading_()'\n})\n\nblock_colon = true\n\n-- Set the CSM restriction flags\ndo\n local flags = tonumber(minetest.settings:get('csm_restriction_flags'))\n if not flags or flags ~= flags then\n flags = 62\n end\n flags = math.floor(math.max(math.min(flags, 63), 0))\n\n local def = sscsm.registered_csms[':init']\n def.code = def.code:gsub('__FLAGS__', tostring(flags))\nend\n\n-- Testing\nminetest.after(1, function()\n -- Check if any other SSCSMs have been registered.\n local c = 0\n for k, v in pairs(sscsm.registered_csms) do\n c = c + 1\n if c > 2 then break end\n end\n if c ~= 2 then return end\n\n -- If not, enter testing mode.\n minetest.log('warning', '[SSCSM] Testing mode enabled.')\n\n sscsm.register({\n name = 'sscsm:testing_cmds',\n file = modpath .. '/sscsm_testing.lua',\n })\n\n sscsm.register({\n name = 'sscsm:another_test',\n code = 'yay()',\n depends = {'sscsm:testing_cmds'},\n })\n\n sscsm.register({\n name = 'sscsm:badtest',\n code = 'error(\"Oops, badtest loaded!\")',\n depends = {':init', ':cleanup', 'bad_mod', ':bad2', 'bad3'},\n })\nend)\n"
},
{
"alpha_fraction": 0.49407416582107544,
"alphanum_fraction": 0.5925845503807068,
"avg_line_length": 37.16597366333008,
"blob_id": "c8988c94cadfffc67c1cc9d61698648771c90cf6",
"content_id": "dfc9929af202410029a72d7f5e05fa495cf49aba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Lua",
"length_bytes": 9197,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 241,
"path": "/mods/brewing/init.lua",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "minetest.register_node(\"brewing:cauldron_full\",{\n drawtype=\"nodebox\",\n\tdescription= \"Filled Cauldron\",\n tiles = {\"lottpotion_cauldron_top.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\",\n\t\t\"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\"},\n\tparamtype = \"light\",\n\tparamtype2 = \"facedir\",\n\tgroups = {cracky=1},\n\tlegacy_facedir_simple = true,\n node_box = {\n type = \"fixed\",\n fixed = {\n\t\t\t{-0.5, -0.5, -0.5, -0.375, 0.5, -0.375},\n\t\t\t{0.375, -0.5, -0.5, 0.5, 0.5, -0.375}, \n\t\t\t{0.375, -0.5, 0.375, 0.5, 0.5, 0.5},\n\t\t\t{-0.5, -0.5, 0.375, -0.375, 0.5, 0.5},\n\t\t\t{-0.375, -0.375, -0.375, 0.375, -0.3125, 0.375},\n\t\t\t{-0.5, -0.375, -0.375, -0.375, 0.4375, 0.375},\n\t\t\t{0.375, -0.375, -0.375, 0.5, 0.4375, 0.375},\n\t\t\t{-0.375, -0.375, 0.375, 0.375, 0.4375, 0.5},\n\t\t\t{-0.375, -0.375, -0.5, 0.375, 0.4375, -0.375},\n\t\t\t{-0.375, 0.25, -0.375, 0.375, 0.3125, 0.375},\n }\n },\n on_punch = function(pos, node, player)\n local player_inv = player:get_inventory()\n local itemstack = player:get_wielded_item()\n if itemstack:get_name() == \"vessels:drinking_glass\" then\n minetest.set_node(pos, {name=\"brewing:cauldron_two_third_full\"})\n if player_inv:room_for_item(\"main\", 1) then\n itemstack:take_item(1)\n player_inv:add_item(\"main\", \"brewing:drinking_glass_water\")\n end\n player:set_wielded_item(itemstack)\n elseif itemstack:get_name() == \"bucket:bucket_empty\" then\n\t\t minetest.set_node(pos, {name=\"brewing:cauldron_empty\"})\n\t\t\titemstack:take_item()\n player_inv:add_item(\"main\", \"bucket:bucket_water\")\n end\n end,\n})\n\nminetest.register_node(\"brewing:cauldron_two_third_full\",{\n drawtype=\"nodebox\",\n description= \"Two Third Filled Cauldron\",\n tiles = {\"lottpotion_cauldron_top.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\",\n\t\t\"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\"},\n\tparamtype = \"light\",\n\tparamtype2 = \"facedir\",\n groups = {cracky=1, not_in_creative_inventory=1},\n node_box = {\n type = \"fixed\",\n fixed = {\n\t\t\t{-0.5, -0.5, -0.5, -0.375, 0.5, -0.375},\n\t\t\t{0.375, -0.5, -0.5, 0.5, 0.5, -0.375}, \n\t\t\t{0.375, -0.5, 0.375, 0.5, 0.5, 0.5},\n\t\t\t{-0.5, -0.5, 0.375, -0.375, 0.5, 0.5},\n\t\t\t{-0.375, -0.375, -0.375, 0.375, -0.3125, 0.375},\n\t\t\t{-0.5, -0.375, -0.375, -0.375, 0.4375, 0.375},\n\t\t\t{0.375, -0.375, -0.375, 0.5, 0.4375, 0.375},\n\t\t\t{-0.375, -0.375, 0.375, 0.375, 0.4375, 0.5},\n\t\t\t{-0.375, -0.375, -0.5, 0.375, 0.4375, -0.375},\n\t\t\t{-0.375, 0.0625, -0.375, 0.375, 0.125, 0.375},\n }\n },\n on_punch = function(pos, node, player)\n local player_inv = player:get_inventory()\n local itemstack = player:get_wielded_item()\n if itemstack:get_name() == \"vessels:drinking_glass\" then\n minetest.set_node(pos, {name=\"brewing:cauldron_one_third_full\"})\n if player_inv:room_for_item(\"main\", 1) then\n itemstack:take_item(1)\n player_inv:add_item(\"main\", \"brewing:drinking_glass_water\")\n end\n player:set_wielded_item(itemstack)\n end\n end,\n})\n\nminetest.register_node(\"brewing:cauldron_one_third_full\",{\n drawtype=\"nodebox\",\n\tdescription= \"One Third Filled Cauldron\",\n tiles = {\"lottpotion_cauldron_top.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\",\n\t\t\"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\", \"lottpotion_cauldron_side.png\"},\n\tparamtype = \"light\",\n\tparamtype2 = \"facedir\",\n groups = {cracky=1, not_in_creative_inventory=1},\n node_box = {\n type = \"fixed\",\n fixed = {\n\t\t\t{-0.5, -0.5, -0.5, -0.375, 0.5, -0.375},\n\t\t\t{0.375, -0.5, -0.5, 0.5, 0.5, -0.375}, \n\t\t\t{0.375, -0.5, 0.375, 0.5, 0.5, 0.5},\n\t\t\t{-0.5, -0.5, 0.375, -0.375, 0.5, 0.5},\n\t\t\t{-0.375, -0.375, -0.375, 0.375, -0.3125, 0.375},\n\t\t\t{-0.5, -0.375, -0.375, -0.375, 0.4375, 0.375},\n\t\t\t{0.375, -0.375, -0.375, 0.5, 0.4375, 0.375},\n\t\t\t{-0.375, -0.375, 0.375, 0.375, 0.4375, 0.5},\n\t\t\t{-0.375, -0.375, -0.5, 0.375, 0.4375, -0.375},\n\t\t\t{-0.375, -0.125, -0.375, 0.375, -0.0625, 0.375},\n }\n },\n on_punch = function(pos, node, player)\n local player_inv = player:get_inventory()\n local itemstack = player:get_wielded_item()\n if itemstack:get_name() == \"vessels:drinking_glass\" then\n minetest.set_node(pos, {name=\"brewing:cauldron_empty\"})\n if player_inv:room_for_item(\"main\", 1) then\n itemstack:take_item(1)\n player_inv:add_item(\"main\", \"brewing:drinking_glass_water\")\n end\n player:set_wielded_item(itemstack)\n end\n end,\n})\n\nminetest.register_node(\"brewing:cauldron_empty\",{\n drawtype=\"nodebox\",\n\tdescription= \"Empty Cauldron\",\n tiles = {\"lottpotion_cauldron_side.png\"},\n paramtype = \"light\",\n\tparamtype2 = \"facedir\",\n groups = {cracky=1,level=2},\n node_box = {\n type = \"fixed\",\n fixed = {\n\t\t\t{-0.5, -0.5, -0.5, -0.375, 0.5, -0.375},\n\t\t\t{0.375, -0.5, -0.5, 0.5, 0.5, -0.375}, \n\t\t\t{0.375, -0.5, 0.375, 0.5, 0.5, 0.5},\n\t\t\t{-0.5, -0.5, 0.375, -0.375, 0.5, 0.5},\n\t\t\t{-0.375, -0.375, -0.375, 0.375, -0.3125, 0.375},\n\t\t\t{-0.5, -0.375, -0.375, -0.375, 0.4375, 0.375},\n\t\t\t{0.375, -0.375, -0.375, 0.5, 0.4375, 0.375},\n\t\t\t{-0.375, -0.375, 0.375, 0.375, 0.4375, 0.5},\n\t\t\t{-0.375, -0.375, -0.5, 0.375, 0.4375, -0.375},\n\t\t\t{-0.375, -0.125, -0.375, 0.375, -0.25, 0.375},\n },\n },\n on_rightclick = function(pos, node, clicker, itemstack)\n if itemstack:get_name() == \"bucket:bucket_water\" then\n\t\t minetest.set_node(pos, {name=\"brewing:cauldron_full\"})\n\t\t\treturn {name=\"bucket:bucket_empty\"}\n end\n end\n})\n\nminetest.register_node(\"brewing:drinking_glass_water\", {\n\tdescription = \"Drinking Glass (Water)\",\n\tdrawtype = \"plantlike\",\n\ttiles = {\"lottpotion_glass_water.png\"},\n\tinventory_image = \"lottpotion_glass_water.png\",\n\twield_image = \"lottpotion_glass_water.png\",\n\tparamtype = \"light\",\n\twalkable = false,\n\tselection_box = {\n\t\ttype = \"fixed\",\n\t\tfixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25}\n\t},\n\tgroups = {vessel=1,dig_immediate=3,attached_node=1},\n\t--sounds = default.node_sound_glass_defaults(),\n})\n\nlocal recipes = {\n--MAKE YOUR OWN DRINK HERE!\n--drink api: description, itemname, fill value, craft items.\n\t{\"Wine\", \"wine\", 4, {\"default:apple\", \"cake:sugar\", \"brewing:cider\"}},\n {\"Beer\", \"beer\", 2, {\"farming:wheat\", \"farming:wheat\", \"cake:sugar\" ,\"brewing:drinking_glass_water\"}},\n {\"Cider\", \"cider\", 2 , {\"default:apple\", \"cake:sugar\", \"brewing:drinking_glass_water\"}},\n {\"Ale\", \"ale\", 2, {\"farming:seed_wheat\", \"farming:wheat\", \"cake:sugar\", \"brewing:drinking_glass_water\"}},\n\t{\"Root Beer\", \"rootbeer\", 2, {\"farming:seed_wheat\", \"default:sapling\", \"cake:sugar\", \"brewing:drinking_glass_water\"}},\n}\nfor _, data in pairs(recipes) do\n\tminetest.register_node(\"brewing:\"..data[2], {\n\t\tdescription = data[1],\n\t\tdrawtype = \"plantlike\",\n\t\ttiles = {\"lottpotion_\"..data[2]..\".png^brewing_fizz.png\"},\n\t\tinventory_image = \"lottpotion_\"..data[2]..\".png^brewing_fizz.png\",\n\t\twield_image = \"lottpotion_\"..data[2]..\".png^brewing_fizz.png\",\n\t\tparamtype = \"light\",\n\t\twalkable = false,\n\t\ton_punch = function(pos, node, player)\n\t\t\tlocal player_inv = player:get_inventory()\n\t\t\tif not player_inv then return end\n\t\t\tif player_inv:room_for_item(\"main\", 1) then\n\t\t\t\tminetest.remove_node(pos)\n\t\t\t\tplayer_inv:add_item(\"main\", \"brewing:\"..data[2])\n\t\t\tend\n\t\t\t--player:set_wielded_item(itemstack)\n\t\tend,\n\t\ton_place = function(itemstack, placer, pointed_thing)\n\t\t\tlocal pt = pointed_thing\n\t\t\tlocal there = {x=pt.under.x, y=pt.under.y+1, z=pt.under.z}\n\t\t\tif minetest.env:get_node(there).name == \"air\" then\n\t\t\t\tminetest.add_node(there, {name=\"brewing:\"..data[2]})\n\t\t\t\titemstack:take_item()\n\t\t\t\treturn itemstack\n\t\t\tend\n\t\tend,\n\t\tgroups = {vessel=1,dig_immediate=4,attached_node=1},\n\t\t\n\t\ton_use = function(itemstack, player, pointed_thing)\n\t\t\tlocal player_inv = player:get_inventory()\n\t\t\tminetest.item_eat(data[3])\n\t\t\tplayer_inv:add_item(\"main\", \"vessels:drinking_glass\")\n\t\tend,\n\t\t\n\t\tselection_box = {\n\t\t\ttype = \"fixed\",\n\t\t\tfixed = {-0.25, -0.5, -0.25, 0.25, 0.4, 0.25}\n\t\t},\n\t\tgroups = {vessel=1,dig_immediate=3,attached_node=1},\n\t\t--sounds = default.node_sound_glass_defaults(),\n\t})\n\tminetest.register_craftitem( \"brewing:\"..data[2]..\"_unbrewed\", {\n\t\tdescription = \"Unbrewed \".. data[1],\n\t\tinventory_image = \"lottpotion_\"..data[2]..\".png\",\n\t\twield_image = \"lottpotion_\"..data[2]..\".png\",\n\t})\n\tminetest.register_craft({\n\t\ttype = \"shapeless\",\n\t\toutput = \"brewing:\"..data[2]..\"_unbrewed\",\n\t\trecipe = data[4],\n\t})\n\tminetest.register_craft({\n\t\toutput = \"brewing:\"..data[2],\n\t\ttype = \"cooking\",\n\t\tcooktime = 7.9,\n\t\trecipe = \"brewing:\"..data[2]..\"_unbrewed\"\n\t})\n\tif minetest.get_modpath(\"hud\") ~= nil then\n\t\toverwritefood(\"brewing:\"..data[2], data[3], \"vessels:drinking_glass\")\n\tend\nend\nminetest.register_craft({\n\toutput = 'brewing:cauldron_empty',\n\trecipe = {\n\t\t{'default:steel_ingot', '', 'default:steel_ingot'},\n\t\t{'default:steel_ingot', '', 'default:steel_ingot'},\n\t\t{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},\n\t}\n})"
},
{
"alpha_fraction": 0.7338888645172119,
"alphanum_fraction": 0.7361111044883728,
"avg_line_length": 35.98630142211914,
"blob_id": "fdfd6b1e0ebfec1dfc8e5e45f6a10ba01a36c389",
"content_id": "de47ea9e0aade9ed89b4b01ebe149ba7c8508a69",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5400,
"license_type": "permissive",
"max_line_length": 171,
"num_lines": 146,
"path": "/mods/sscsm/README.md",
"repo_name": "Persistent-Kingdoms/persistent-factions",
"src_encoding": "UTF-8",
"text": "# Minetest server-sent CSM proof-of-concept\n\n[Source](https://git.minetest.land/luk3yx/sscsm)\n\nAttempts to run server-sent CSMs locally in a sandbox.\n\n## How it works\n\nAny client with the CSM installed will automatically attempt to request SSCSMs\nfrom the server via a mod channel. If the server has this mod installed, it\nwill reply with a few messages containing the mod name and partially minified\nmod code. The CSM will then create a separate environment so SSCSMs cannot mess\nwith existing CSMs (and so CSMs do not accidentally interfere with SSCSMs), and\nexecute the SSCSMs inside this environment. *Note that it is trivial for users\nto modify this environment.* The server-side mod sends two \"built-in\" SSCSMs\nbefore and after all other SSCSMs to add extra helper functions (in the `sscsm`\nnamespace), to execute `register_on_mods_loaded` callbacks and attempt to leave\nthe mod channel.\n\n## Instructions\n\nTo create a SSCSM:\n\n - Install this mod onto a server.\n - Enable mod channels on the server (add `enable_mod_channels = true` to\n minetest.conf).\n - Create SSCSMs with the API.\n - Install the CSM (in the `csm/` directory) onto clients and enable it.\n\n### Preserving copyright and license notices\n\nThe minifier preserves comments starting with \"copyright\" or \"license\":\n(case-insensitive, excluding leading spaces).\n\nInput:\n\n```lua\n-- Copyright: 1\n-- License: 2\n-- A normal comment.\n--COPYRIGHT5\n\n...\n```\n\nOutput:\n\n```lua\n-- Copyright: 1\n-- License: 2\n--COPYRIGHT5\n...\n```\n\n## Server-side mod facing API\n\n*This API is subject to change.*\n\n### `sscsm.register(def)`\n\nRegisters a server-provided CSM with the following definition table.\n\n - `name` *(string)*: The name of the server-provided CSM. Please use the\n `modname:sscsmname` convention. Cannot start with a colon or contain\n newlines.\n - `code` *(string)*: The code to be sent to clients.\n - `file` *(string)*: The file to read the code from, read during the\n `register()` call.\n - `depends` *(list)*: A list of SSCSMs that must be loaded before this one.\n\nThis definition table must have `name` and either `code` or `file`.\n\n#### Maximum SSCSM size\n\nBecause of Minetest network protocol limitations, the amount of data that can\nbe sent over mod channels is limited, and therefore the maximum SSCSM size is\n65300 (to leave room for the player name and future expansion). The name of the\nSSCSM also counts towards this total.\n\nBecause of this size limitation, SSCSMs are passed through a primitive code\nminifier that removes some whitespace and comments, so even if your code is\nabove this size limit it could still work.\n\n## Server-sent CSM facing API\n\nSSCSMs can access most functions on [client_lua_api.txt](https://github.com/minetest/minetest/blob/master/doc/client_lua_api.txt), as well as a separate `sscsm` namespace:\n\n - `sscsm.global_exists(name)`: The same as `minetest.global_exists`.\n - `sscsm.register_on_mods_loaded(callback)`: Runs the callback once all SSCSMs\n are loaded.\n - `sscsm.register_chatcommand(...)`: Similar to\n `minetest.register_chatcommand`, however overrides commands starting in `/`\n instead. This can be used to make some commands have instantaneous\n responses. The command handler is only added once `register_chatcommand`\n has been called.\n - `sscsm.unregister_chatcommand(name)`: Unregisters a chatcommand.\n - `sscsm.get_player_control()`: Returns a table similar to the server-side\n `player:get_player_control()`.\n - `sscsm.restriction_flags`: The `csm_restriction_flags` setting set in\n the server's `minetest.conf`.\n - `sscsm.restrictions`: A table based on `csm_restriction_flags`:\n - `chat_messages`: When `true`, SSCSMs can't send chat messages or run\n server chatcommands.\n - `read_itemdefs`: When `true`, SSCSMs can't read item definitions.\n - `read_nodedefs`: When `true`, SSCSMs can't read node definitions.\n - `lookup_nodes_limit`: When `true`, any get_node calls are restricted.\n - `read_playerinfo`: When `true`, `minetest.get_player_names()` will return\n `nil`.\n\nTo communicate with the server-side mods, it is possible to open a mod\nchannel.\n\n### CSM restriction flags example\n\n```lua\nminetest.register_chatcommand('m', {\n description = 'Alias for /msg',\n func = function(param)\n if sscsm.restrictions.chat_messages then\n return false, 'Sorry, csm_restriction_flags prevents chat messages'\n .. ' from being sent.'\n end\n minetest.run_server_chatcommand('msg', param)\n end,\n})\n```\n\n*Note that modifying `sscsm.restrictions` or `sscsm.restriction_flags` will\nnot add or remove restrictions and is not recommended.*\n\n## Security considerations\n\nDo not trust any input sent to the server via SSCSMs (and do not store\nsensitive data in SSCSM code), as malicious users can and will inspect code and\nmodify the output from SSCSMs.\n\nI repeat, **do not trust the client** and/or SSCSMs with any sensitive\ninformation and do not trust any output from the client and/or SSCSMs. Make\nsure to rerun any privilege checks on the server.\n\n### Other recommendations\n\nAlthough it is possible to kick clients that do not support SSCSMs, this has\nnot been implemented. Some users may not want to allow servers to automatically\ndownload and run code locally for security reasons. Please try and make sure\nclients without SSCSMs do not suffer from major functionality loss.\n"
}
] | 38 |
Archieyoung/SVAN | https://github.com/Archieyoung/SVAN | 3043a459a49deb7ff08f8e76f5de7872b5c4026e | c2ed4d7aa1039d10ff6c0b738d7b8be361177cff | e28c715bdb567ade0bde4d5e1ba53258b9fb4acd | refs/heads/master | 2021-07-13T03:10:43.449860 | 2018-12-29T07:17:04 | 2018-12-29T07:17:04 | 133,483,056 | 5 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5603448152542114,
"alphanum_fraction": 0.5656814575195312,
"avg_line_length": 35.89393997192383,
"blob_id": "2e8ce2439b73f268852dc236ecc21961b3789079",
"content_id": "e97f33b8998a0adc9892b16f559b408f3a7a4ca8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2436,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 66,
"path": "/range_compare.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\nimport os\nimport subprocess\n\nfrom bed_intersect import intersect_f\nfrom table_check import TableCheck\n\ndef RangeCompare(bedtools, bedA, bedB, min_overlap, tmp_dir, prefix,db_id):\n # result sv dict, key: query sv id, value: db fields\n intersect_result = {}\n\n # calculate query and database fields number\n query_field_num = TableCheck(bedA)\n # db_field_num = table_check(bedB)\n\n range_intersect_tmp_bed = os.path.join(tmp_dir\n ,prefix+\".\"+db_id+\".intersect.tmp.bed\")\n\n if min_overlap > 0:\n with open(range_intersect_tmp_bed,\"w\") as io:\n subprocess.run([bedtools,\"intersect\",\"-a\",bedA,\"-b\",bedB,\"-wo\",\n \"-f\",str(min_overlap),\"-r\"],stdout=io)\n else:\n with open(range_intersect_tmp_bed,\"w\") as io:\n subprocess.run([bedtools,\"intersect\",\"-a\",bedA,\"-b\",bedB,\"-wo\"],\n stdout=io)\n\n # read intersect file\n # bedA query bed\n # chrom start end svtype svid svlen re info;\n # svid is a unique identifier for the sv\n with open(range_intersect_tmp_bed,\"r\") as io:\n lines = io.readlines()\n for line in lines:\n fields = line.strip().split(\"\\t\")\n query_fields = fields[:query_field_num]\n db_fields = fields[query_field_num:-1]\n \n intersect_field = intersect_f(fields, query_field_num)\n \n _query_svtype = intersect_field.query_svtype\n _db_svtype = intersect_field.db_svtype\n\n _query_svid = intersect_field.query_svid\n \n # DEL match DEL or CNV\n if (_query_svtype == \"DEL\" and (_db_svtype == \"DEL\" or\n _db_svtype == \"CNV\")):\n intersect_result.setdefault(_query_svid, []).append(db_fields)\n \n # DUP match DUP or CNV\n if (_query_svtype == \"DUP\" and (_db_svtype == \"DUP\" or\n _db_svtype == \"CNV\")):\n intersect_result.setdefault(_query_svid, []).append(db_fields)\n\n if _query_svtype == \"INV\" and _db_svtype == \"INV\":\n intersect_result.setdefault(_query_svid, []).append(db_fields)\n \n # WILD database SV type matchs any query SV type\n if _db_svtype == \"WILD\":\n intersect_result.setdefault(_query_svid, []).append(db_fields)\n\n return intersect_result\n\n"
},
{
"alpha_fraction": 0.5722347497940063,
"alphanum_fraction": 0.6027088165283203,
"avg_line_length": 34.400001525878906,
"blob_id": "87eba9242c5e20d370994536b3b4141cdc5b3810",
"content_id": "1a13829d8e29cb3f88c8cd559c897ad1a6a6a740",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 886,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 25,
"path": "/format_result.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\n\n\n\"\"\"\ndb fields \"chrom\",\"start\",\"end\",\"svtype\",\"annot1\",\"annot2\",\"annot3\"...\nformat: \"annot1;annot1\",\"annot2,annot2\";\"annot3;annot3\",\"chrom:start-end,svtype;...\"\nif multiple result is founded in database, write all feature in one column,\nand seperate them by semicolon\n\"\"\"\ndef format_result_pub_db(result):\n for i in result:\n variations = []\n #init annotations\n annotations = [[] for p in range(len(result[i][0])-4)]\n for j in result[i]:\n variations.append(\"{}:{}-{},{}\".format(j[0],j[1],j[2],j[3]))\n for k in range(len(annotations)):\n annotations[k].append(j[k+4])\n variations_str = \";\".join(variations)\n annotations_str = [\";\".join(l) for l in annotations]\n result[i] = annotations_str+[variations_str]\n return result\n\n"
},
{
"alpha_fraction": 0.5431034564971924,
"alphanum_fraction": 0.5545976758003235,
"avg_line_length": 35,
"blob_id": "883a29d01ecd89d071c5d7bdb0d27aa6d5b51cd0",
"content_id": "1d78f3d69e98ddd48ae51d5dc54270a7b2e46566",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1044,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 29,
"path": "/table_check.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\n\n\ndef TableCheck(table):\n \"\"\"\n check if the table have consistent field number of each row\n return field number of the table\n \"\"\"\n with open(table,\"r\") as io:\n # skip comment lines\n check_momment_line = io.readline()\n while check_momment_line[0] == \"#\":\n # comment lines start with \"#\"\n check_momment_line = io.readline()\n pass\n first_record_line = check_momment_line # first record line\n first_record_field_num = len(first_record_line.split(\"\\t\"))\n lines = io.readlines()\n for line in lines:\n field_num = len(line.split(\"\\t\"))\n if field_num != first_record_field_num:\n raise RuntimeError(\"field number not consistent: \"\n \"first record field num is {}, but {} \"\n \"field num is {}\".format(first_record_field_num,\n field_num,line))\n return first_record_field_num\n"
},
{
"alpha_fraction": 0.5923212766647339,
"alphanum_fraction": 0.604599118232727,
"avg_line_length": 34.099998474121094,
"blob_id": "c9bebb63a8889a6be9cdbe2ad2ebb08d18e4828f",
"content_id": "28c9780103fbb7b2acdc6882e59baea6a96e23b4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14742,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 420,
"path": "/svan.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\"\"\"\nauthor: archieyoung<[email protected]>\nSVAN: A Struture Variation Annotation Tool\n\"\"\"\nimport sys\nimport os\nimport subprocess\nimport operator\nimport argparse\nimport logging\nfrom multiprocessing import Pool\nfrom glob import iglob\n\n\nimport sv_vcf\nimport pubdb_prepare\nfrom range_compare import RangeCompare\nfrom insertion_compare import InsCompare\nfrom traslocation_compare import TraCompare \n\n\n\ndef queryPrepare_vcf(tmp, prefix, vcf_in, bed_out):\n \"\"\"\n Convert VCF to BED\n Remove query chrom \"chr\" prefix if it exists, because database SV\n chrom do not have \"chr\" prefix.\n Sort bed file by \"chrom\" and \"start\", the same as \"sort -k1,1 -k2,2n\"\n \"\"\"\n bed_tmp1 = os.path.join(tmp, prefix+\".query.bed.tmp1\")\n # vcf to bed\n sv_vcf.vcf_to_bed(vcf_in, bed_tmp1)\n # sort bed\n bed_list = []\n query_list = []\n with open(bed_tmp1, \"r\") as io:\n for line in io:\n line = line.strip()\n fields = line.split(\"\\t\")\n query_list.append(line)\n # Remove query chrom \"chr\" prefix if it exists\n fields[0] = fields[0].replace(\"chr\", \"\")\n fields[1] = int(fields[1])\n bed_list.append(fields)\n bed_list.sort(key = operator.itemgetter(0, 1))\n\n with open(bed_out, \"w\") as io:\n for i in bed_list:\n i[1] = str(i[1])\n io.write(\"\\t\".join(i)+\"\\n\")\n return query_list\n\n\ndef queryPrepare_bed(tmp, prefix, bed_in, bed_out):\n \"\"\"\n Remove query chrom \"chr\" prefix if it exists, because database SV\n chrom do not have \"chr\" prefix.\n Sort bed file by \"chrom\" and \"start\", the same as \"sort -k1,1 -k2,2n\"\n \"\"\"\n # sort bed\n bed_list = []\n query_list = []\n with open(bed_in, \"r\") as io:\n for line in io:\n line = line.strip()\n fields = line.split(\"\\t\")\n query_list.append(line)\n # Remove query chrom \"chr\" prefix if it exists\n fields[0] = fields[0].replace(\"chr\",\"\")\n fields[1] = int(fields[1])\n bed_list.append(fields)\n bed_list.sort(key = operator.itemgetter(0, 1))\n with open(bed_out, \"w\") as io:\n for i in bed_list:\n i[1] = str(i[1])\n io.write(\"\\t\".join(i)+\"\\n\")\n return query_list\n\n\n# db fields \"chrom\",\"start\",\"end\",\"svtype\",\"svid\",\"annot1\",\"annot2\",\"annot3\"...\n# format: \"annot1;annot1\",\"annot2,annot2\";\"annot3;annot3\",\"chrom:start-end,svtype;...\"\n# if multiple result is founded in database, write each feature in one column,\n# and seperate by semicolon\ndef format_pub_result(result, field_names):\n for i in result:\n variations = []\n # init annotations\n annotations = [[] for p in range(len(result[i][0])-5)]\n if (len(field_names)-1) != len(annotations):\n # print(field_names)\n # print(result[i][0][5:])\n raise RuntimeError(\"fields number error.\")\n for j in result[i]:\n variations.append(\"{}:{}-{},{}\".format(j[0],j[1],j[2],j[3]))\n for k in range(len(annotations)):\n annotations[k].append(j[k+5])\n variations_str = \";\".join(variations)\n annotations_str = [\";\".join(l) for l in annotations]\n \n new_fields = [variations_str] + annotations_str\n result[i] = dict() # change the value inplace\n\n for m in range(len(field_names)):\n result[i][field_names[m]] = new_fields[m] \n # return result\n\n\ndef format_local_result(result, local_db_size):\n for i in result:\n variations = []\n for j in result[i]:\n # variations.append(\"{}:{}-{},{}\".format(j[0],j[1],j[2],j[3]))\n variations.append(j[4])\n variations_str = \";\".join(variations)\n frequency = len(variations)/local_db_size\n if frequency > 1:\n frequency = 1 # set max frequency to 1\n frequency = \"{:4.2f}\".format(frequency)\n result[i] = {\"GrandSV_Frequency\":frequency,\n \"GrandSV_Variant\":variations_str} \n # return result\n\n\ndef update_result(updated_result, intersect):\n for i in intersect:\n if i not in updated_result:\n updated_result[i] = intersect[i]\n else:\n updated_result[i].update(intersect[i])\n\n\ndef get_sv_by_type(bed_in, bed_out, svtype):\n result_list = []\n with open(bed_in, \"r\") as io:\n for line in io:\n fields = line.strip().split(\"\\t\")\n if fields[3] in svtype:\n result_list.append(line)\n with open(bed_out, \"w\") as io:\n io.writelines(result_list)\n\n\ndef local_sv_annot(_args):\n (_bedtools, _bed_query, _bed_query_ins, _bed_query_tra, _db_bed,\n _min_overlap, _max_dist, _tmp_dir, _prefix, _id) = _args\n\n _intersect = dict()\n \n # range compare\n range_intersect = RangeCompare(_bedtools, _bed_query, _db_bed,\n _min_overlap, _tmp_dir, _prefix, \"local{}\".format(_id))\n \n # insertion compare\n ins_intersect = InsCompare(_bedtools, _bed_query_ins, _db_bed, _max_dist,\n _tmp_dir, _prefix, \"local{}\".format(_id))\n\n # tra compare\n tra_intersect = TraCompare(_bedtools, _bed_query_tra, _db_bed, _max_dist,\n _tmp_dir, _prefix, \"local{}\".format(_id))\n\n # update intersect result\n _intersect.update(range_intersect)\n _intersect.update(ins_intersect)\n _intersect.update(tra_intersect)\n\n return _intersect\n\n\ndef table_maker(query_list, result, result_field_names):\n table = []\n query_field_names = [\"Chr\", \"Start\", \"End\", \"SVTYPE\", \"SVID\",\n \"SVLEN\", \"RE\", \"INFO\"]\n header = query_field_names + result_field_names\n for i in query_list:\n fields = i.split(\"\\t\")\n record_dict = dict([p for p in zip(query_field_names, fields)])\n svid = record_dict[\"SVID\"]\n if svid in result:\n record_dict.update(result[svid])\n for j in result_field_names:\n if j not in record_dict:\n record_dict[j] = \"NA\"\n else:\n for j in result_field_names:\n if j not in record_dict:\n record_dict[j] = \"NA\"\n # print(record_dict)\n record = \"\\t\".join([record_dict[k] for k in header]) + \"\\n\"\n table.append(record)\n header_str = \"\\t\".join(header) + \"\\n\"\n return header_str, table\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"SVAN: Structure variation annotation\",\n usage=\"usage: %(prog)s [options]\")\n parser.add_argument(\"--vcf\",\n help=\"vcf file [default %(default)s]\", metavar=\"FILE\")\n parser.add_argument(\"--bed\",\n help=\"bed file [default %(default)s]\", metavar=\"FILE\")\n parser.add_argument(\"--pub_dbdir\",\n help=\"public SV database directory [default %(default)s]\", metavar=\"DIR\")\n parser.add_argument(\"--local_dbdir\",\n help=\"local SV database directory [default %(default)s]\", metavar=\"DIR\")\n parser.add_argument(\"--min_overlap\",\n help=\"minimum reciprocal overlap fraction for \\\"Range\\\" SV A and\"\n \" \\\"Rang\\\" SV B [default %(default)s]\", type=float,\n default=0.5, metavar=\"FLOAT\")\n parser.add_argument(\"--max_dist\",\n help=\"maximum distance for \\\"Point\\\" SV A and\"\n \" \\\"Point\\\" SV B [default %(default)s]\", type=int,\n default=1000, metavar=\"FLOAT\")\n parser.add_argument(\"--threads\", default=4,\n help=\"number of threads [default %(default)s]\", type=int, metavar=\"STR\")\n parser.add_argument(\"--prefix\",\n help=\"output file name [default %(default)s]\", metavar=\"STR\")\n parser.add_argument(\"--outdir\",\n help=\"output directory [default %(default)s]\", metavar=\"DIR\")\n parser.add_argument(\"--tmp\",\n help=\"temporary directory [default %(default)s]\",\n default=\"tmp\", metavar=\"DIR\")\n\n if len(sys.argv) <= 1:\n parser.print_help()\n exit()\n return parser.parse_args()\n\n\ndef main():\n \n args = get_args()\n \n # make dirs\n if not os.path.exists(args.outdir):\n os.mkdir(args.outdir)\n\n if not os.path.exists(args.tmp):\n os.mkdir(args.tmp)\n\n \n # prepare query SV\n bed_query = os.path.join(args.tmp, args.prefix+\".query.bed\")\n if args.vcf: # vcf query\n query_list = queryPrepare_vcf(args.tmp, args.prefix,\n args.vcf, bed_query)\n elif args.bed: # bed query\n query_list = queryPrepare_bed(args.tmp, args.prefix, \n args.bed, bed_query)\n else:\n raise RuntimeError(\"Must provide either a bed or vcf a file!!!\")\n\n \n # prepare database \n one_thousand_sv_raw = os.path.join(args.pub_dbdir,\n \"ALL.wgs.integrated_sv_map_v2.20130502.svs.genotypes.1000genome.vcf.gz\")\n dgv_raw = os.path.join(args.pub_dbdir,\n \"DGV.GS.March2016.50percent.GainLossSep.Final.hg19.gff3\")\n dbVar_raw = os.path.join(args.pub_dbdir,\n \"nstd37.GRCh37.variant_call.vcf.gz\")\n decipher_hi_raw = os.path.join(args.pub_dbdir,\n \"decipher_HI_Predictions_Version3.bed.gz\")\n\n for i in [one_thousand_sv_raw,dgv_raw,dbVar_raw,decipher_hi_raw]:\n if not os.path.exists(i):\n raise RuntimeError(\"Error: {} was not founded!\".format(i))\n \n one_thousand_sv_db = os.path.join(args.tmp,\n \"ALL.wgs.integrated_sv_map_v2.20130502.svs.genotypes.1000genome.db.bed\")\n dgv_db = os.path.join(args.tmp,\n \"DGV.GS.March2016.50percent.GainLossSep.Final.hg19.db.bed\")\n dbVar_db = os.path.join(args.tmp,\n \"nstd37.GRCh37.variant_call.db.bed\")\n decipher_hi_db = os.path.join(args.tmp,\n \"decipher_HI_Predictions_Version3.db.bed\")\n\n pubdb_prepare.one_thousand_sv.print_bed(one_thousand_sv_raw, one_thousand_sv_db)\n pubdb_prepare.dgv_gold_cnv.print_bed(dgv_raw, dgv_db)\n pubdb_prepare.dbVar_nstd37_sv.print_bed(dbVar_raw, dbVar_db)\n pubdb_prepare.decipher_HI.print_bed(decipher_hi_raw, decipher_hi_db)\n\n \n bedtools = \"bedtools\" # temp use\n\n # annotation field names\n one_thousand_field_names = [\"1000g_SV\", \"1000g_subtype\", \"1000g_AF\",\n \"1000g_EAS_AF\", \"1000g_EUR_AF\",\"1000g_AFR_AF\",\"1000g_AMR_AF\", \n \"1000g_SAS_AF\"]\n dgv_field_names = [\"dgv_SV\", \"dgv_AF\",\"dgv_sample_size\"]\n dbVar_field_names = [\"dbVar_SV\", \"dbVar_CLNSIG\",\"dbVar_PHENO\"]\n decipher_hi_field_names = [\"Decipher_region\", \"Decipher_HI\"]\n\n \n # public database SV annotate, 1000g, dgv, dbVar, decipher_hi\n # range annotate\n # 1000g\n one_thousand_range_intersect = RangeCompare(bedtools, bed_query,\n one_thousand_sv_db, args.min_overlap,\n args.tmp, args.prefix, \"1000genome\")\n format_pub_result(one_thousand_range_intersect, one_thousand_field_names)\n\n # dgv\n dgv_range_intersect = RangeCompare(bedtools, bed_query,\n dgv_db, args.min_overlap, args.tmp, args.prefix, \"dgv\")\n format_pub_result(dgv_range_intersect, dgv_field_names)\n\n # dbVar\n dbVar_range_intersect = RangeCompare(bedtools, bed_query,\n dbVar_db, args.min_overlap, args.tmp, args.prefix, \"dbVar\")\n format_pub_result(dbVar_range_intersect, dbVar_field_names)\n\n # decipher_hi\n decipher_hi_range_intersect = RangeCompare(bedtools, bed_query,\n decipher_hi_db, 0, args.tmp, args.prefix,\n \"decipher_hi\")\n format_pub_result(decipher_hi_range_intersect, decipher_hi_field_names)\n\n \n # insertion annotate, 1000g and decipher_hi\n # get insertion\n bed_query_ins = os.path.join(args.tmp, args.prefix + \".query.ins.bed\")\n get_sv_by_type(bed_query, bed_query_ins, [\"INS\"])\n\n # 1000g\n one_thousand_ins_intersect = InsCompare(bedtools, bed_query_ins,\n one_thousand_sv_db, args.max_dist,\n args.tmp, args.prefix, \"1000genome\")\n format_pub_result(one_thousand_ins_intersect, one_thousand_field_names)\n\n # decipher hi\n decipher_hi_ins_intersect = InsCompare(bedtools, bed_query_ins,\n decipher_hi_db, args.max_dist, args.tmp, args.prefix,\n \"decipher_hi\")\n format_pub_result(decipher_hi_ins_intersect, decipher_hi_field_names)\n\n # translocation annotate, decipher hi\n # get translocation\n bed_query_tra = os.path.join(args.tmp, args.prefix + \".query.tra.bed\")\n get_sv_by_type(bed_query, bed_query_tra, [\"TRA\"])\n\n # decipher hi\n decipher_hi_tra_intersect = TraCompare(bedtools, bed_query_tra,\n decipher_hi_db, args.max_dist, args.tmp, args.prefix,\n \"decipher_hi\")\n format_pub_result(decipher_hi_tra_intersect, decipher_hi_field_names)\n\n # merge public result\n public_results = dict()\n public_intersect_list = [one_thousand_range_intersect,\n dgv_range_intersect,\n dbVar_range_intersect,\n decipher_hi_range_intersect,\n one_thousand_ins_intersect,\n decipher_hi_ins_intersect,\n decipher_hi_tra_intersect\n ]\n for i in public_intersect_list:\n update_result(public_results, i)\n \n\n # local SV database annotate\n # local SV beds\n local_db_beds = iglob(os.path.join(args.local_dbdir, \"*.sv.database.bed\"))\n\n\n pool = Pool(processes = args.threads)\n intersect_work_list = []\n\n \n n = 1 # used for number the temp files and calculate local database size\n for local_db_bed in local_db_beds:\n local_annot_args = ([bedtools, bed_query, bed_query_ins, bed_query_tra,\n local_db_bed, args.min_overlap, args.max_dist, args.tmp, args.prefix, n],)\n intersect_work_list.append(pool.apply_async(local_sv_annot,\n local_annot_args))\n n += 1\n\n pool.close()\n pool.join()\n\n # merge intersect results\n local_intersect_list = []\n for i in intersect_work_list:\n intersect = i.get()\n local_intersect_list.append(intersect)\n\n local_intersect_merged = dict()\n for i in local_intersect_list:\n for k in i:\n if k not in local_intersect_merged:\n local_intersect_merged[k] = i[k]\n else:\n local_intersect_merged[k].extend(i[k])\n format_local_result(local_intersect_merged, n)\n\n # OMG, got the END...\n annot_result = public_results\n update_result(annot_result, local_intersect_merged)\n # for k in annot_result:\n # print(k, annot_result[k])\n\n # make table\n # fields\n result_field_names = ([\"GrandSV_Frequency\", \"GrandSV_Variant\"] +\n one_thousand_field_names +\n dgv_field_names +\n dbVar_field_names +\n decipher_hi_field_names)\n\n header_str, table = table_maker(query_list, annot_result, result_field_names)\n\n prefix_with_dir = os.path.join(args.outdir, args.prefix)\n with open(prefix_with_dir + \".svan.tsv\", \"w\") as io:\n io.write(header_str)\n io.writelines(table)\n\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5861244201660156,
"alphanum_fraction": 0.6172248721122742,
"avg_line_length": 37,
"blob_id": "f5b88fba1f4dee1c49e6e8983a3eb3fb4a576690",
"content_id": "77fbc085157f89f69603a93a29fe10f02c5221fb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 11,
"path": "/bed_intersect.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\n\nclass intersect_f(object):\n def __init__(self, fields, query_field_num):\n (self.query_chrom, self.query_start, self.query_end, self.query_svtype,\n self.query_svid) = fields[:5]\n (self.db_chrom, self.db_start, self.db_end, self.db_svtype,\n self.db_svid) = fields[query_field_num:query_field_num+5]\n"
},
{
"alpha_fraction": 0.6966292262077332,
"alphanum_fraction": 0.6966292262077332,
"avg_line_length": 28.33333396911621,
"blob_id": "acc13d3f4315b6c379a69295a30cd989dd942ca6",
"content_id": "c87b6dbbb980434ca6c51b6780d515bd20470827",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 89,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 3,
"path": "/README.md",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "# SVAN\n\nA **S**tructure **V**ariation **AN**notation Tool Using bedtools for SV Compare\n\n"
},
{
"alpha_fraction": 0.4796905219554901,
"alphanum_fraction": 0.4978354871273041,
"avg_line_length": 32.50617218017578,
"blob_id": "419ec776465773dc348e0155bbc37fcc9920438f",
"content_id": "ffd5d54d574b1e4f64d62ec3d6d8269c2d6f6a28",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10857,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 324,
"path": "/pubdb_prepare.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\"\"\"\nprepare SV database for annotation\nconvert 1000genome, DGV, dbVar SV files into bed files\n\"\"\"\nimport sys\nimport gzip\nimport logging\nimport operator\nimport os\nfrom glob import iglob\nfrom datetime import date\n\n\nfrom sv_vcf import SV\n\n\n# 1000genome\nclass one_thousand_sv(object):\n def __init__(self,record):\n # 1000genome vcf file parse\n self.record = record\n fields = record.strip().split(\"\\t\")\n (self.chrom,self.pos1,self.id,self.ref,self.alt,self.qual,self.filter,\n self.info,self.format) = fields[:9]\n self.samples = fields[9:]\n # info dict\n self.info_dict = {}\n info_list = self.info.split(\";\")\n for i in info_list:\n if \"=\" in i:\n info_id,info_value = i.split(\"=\")\n self.info_dict[info_id] = info_value\n else:\n self.info_dict[i] = i\n # end\n if \"END\" in self.info_dict:\n self.pos2 = self.info_dict[\"END\"]\n else:\n # if can not find end in info, end = start(eg. insertion)\n self.pos2 = self.pos1\n\n # SVLEN\n if \"SVLEN\" in self.info_dict:\n self.svlen = self.info_dict[\"SVLEN\"]\n else:\n self.svlen = \"NA\"\n\n # SVTYPE\n self.sub_svtype = self.info_dict[\"SVTYPE\"]\n if self.sub_svtype in [\"SVA\",\"LINE1\",\"ALU\",\"INS\"]:\n self.svtype = \"INS\"\n elif self.sub_svtype in [\"DEL\",\"DEL_ALU\",\"DEL_HERV\",\"DEL_LINE1\",\n \"DEL_SVA\"]:\n self.svtype = \"DEL\"\n else:\n self.svtype = self.sub_svtype\n\n # allele frequency\n # multi-alleles(CNVs,0,1,2...) frequency is not considered here,\n # treated as bi-alleles(0,1) frequency\n af_populations = [\"AF\",\"EAS_AF\",\"EUR_AF\",\"AFR_AF\",\"AMR_AF\",\"SAS_AF\"]\n self.AFs = [self._get_af(i) for i in af_populations]\n\n def _get_af(self,af_population):\n # af_population: AF=0.00698882;EAS_AF=0.0069;EUR_AF=0.0189;\n # AFR_AF=0.0;AMR_AF=0.0072;SAS_AF=0.0041;\n try:\n af = sum([float(i) for i in self.info_dict[af_population].split(\n \",\")])\n af = \"{:.6}\".format(af)\n except:\n af = \"NA\"\n logging.warning('Can not find \"{}\" in INFO of record: {}'.format(\n af_population,self.record))\n return af\n\n @classmethod\n def print_bed(cls,vcf_gz,out_name):\n bed_list = []\n with gzip.open(vcf_gz,\"r\") as io:\n n = 0\n for line in io:\n line = line.decode(\"utf-8\")\n if line[0] == \"#\":\n continue\n \n db_svid = \"1000genome{}\".format(n) # make 1000genome SV id\n n += 1\n\n sv = one_thousand_sv(line)\n sv.pos1 = int(sv.pos1)\n bed = [sv.chrom, sv.pos1, sv.pos2, sv.svtype, db_svid,\n sv.sub_svtype]+sv.AFs\n bed_list.append(bed)\n bed_list.sort(key = operator.itemgetter(0, 1))\n bed_lines = []\n for i in bed_list:\n i[1] = str(i[1])\n bed_lines.append(\"\\t\".join(i)+\"\\n\")\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\n\nclass dgv_gold_cnv(object):\n # dgv gff3 file parse\n def __init__(self,record):\n self.record = record\n fields = record.strip().split(\"\\t\")\n # remove \"chr\" prefix in chrom if it exists\n self.chrom = fields[0].replace(\"chr\",\"\")\n self.pos1 = fields[3]\n self.pos2 = fields[4]\n self.info_dict = {}\n for i in fields[-1].split(\";\"):\n if \"=\" in i:\n info_id,info_value = i.split(\"=\")\n self.info_dict[info_id] = info_value\n else:\n self.info_dict[i] = i\n if self.info_dict[\"variant_sub_type\"] == \"Gain\":\n self.svtype = \"DUP\"\n elif self.info_dict[\"variant_sub_type\"] == \"Loss\":\n self.svtype = \"DEL\"\n else:\n raise RuntimeError('variant_sub_type can either be \"Gain\" or \"Loss\"')\n self.af = self.info_dict[\"Frequency\"]\n self.af = str(float(self.af.replace(\"%\",\"\"))*0.01)\n self.sample_size = self.info_dict[\"num_unique_samples_tested\"]\n\n @classmethod\n def print_bed(cls,gff3,out_name):\n bed_list = []\n with open(gff3,\"r\") as io:\n n = 0\n for line in io:\n if line[0] == \"#\":\n continue\n sv = dgv_gold_cnv(line)\n\n db_svid = \"dgv{}\".format(n)\n n += 1\n\n sv.pos1 = int(sv.pos1)\n bed = [sv.chrom, sv.pos1, sv.pos2, sv.svtype, db_svid,\n sv.af, sv.sample_size]\n bed_list.append(bed)\n bed_list.sort(key = operator.itemgetter(0, 1))\n bed_lines = []\n for i in bed_list:\n i[1] = str(i[1])\n bed_lines.append(\"\\t\".join(i)+\"\\n\")\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\n\nclass dbVar_nstd37_sv(object):\n # dbvar vcf file parse\n def __init__(self,record):\n self.record = record\n fields = record.strip().split(\"\\t\")\n (self.chrom,self.pos1,self.id,self.ref,self.alt,self.qual,self.filter,\n self.info) = fields[:8]\n # info dict\n self.info_dict = {}\n info_list = self.info.split(\";\")\n for i in info_list:\n if \"=\" in i:\n info_id,info_value = i.split(\"=\")\n self.info_dict[info_id] = info_value\n else:\n self.info_dict[i] = i\n self.pos2 = self.info_dict[\"END\"]\n self.svtype = self.info_dict[\"SVTYPE\"]\n try:\n self.clnsig = self.info_dict[\"CLNSIG\"]\n except KeyError:\n self.clnsig = \"NA\"\n try:\n self.pheno = self.info_dict[\"PHENO\"]\n except KeyError:\n self.pheno = \"NA\"\n\n @classmethod\n def print_bed(cls,vcf_gz,out_name):\n bed_list = []\n with gzip.open(vcf_gz,\"r\") as io:\n n = 0\n for line in io:\n line = line.decode(\"utf-8\")\n if line[0] == \"#\":\n continue\n sv = dbVar_nstd37_sv(line)\n\n db_svid = \"dbvar{}\".format(n)\n n += 1\n\n sv.pos1 = int(sv.pos1)\n bed = [sv.chrom, sv.pos1, sv.pos2, sv.svtype, db_svid,\n sv.clnsig, sv.pheno]\n bed_list.append(bed)\n bed_list.sort(key = operator.itemgetter(0, 1))\n bed_lines = []\n for i in bed_list:\n i[1] = str(i[1])\n bed_lines.append(\"\\t\".join(i)+\"\\n\")\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\n\nclass decipher_HI(object):\n \"\"\"\n Convert decipher_HI_Predictions_Version3.bed.gz to database bed\n Huang N, Lee I, Marcotte EM, Hurles ME (2010) Characterising and Predicting Haploinsufficiency in the Human Genome. PLOS Genetics 6(10): e1001154.\n \"\"\"\n def __init__(self,record):\n fields = record.strip().split(\"\\t\")\n self.chrom,self.pos1,self.pos2,self.gene_hi = fields[:4]\n # remove \"chr\"\n self.chrom = self.chrom.replace(\"chr\",\"\")\n self.svtype = \"WILD\" # wild means that it can match any SV type, for doing svtye-insensity annotation\n\n @classmethod\n def print_bed(cls,input_gz,out_name):\n bed_list = []\n with gzip.open(input_gz,\"r\") as io:\n io.readline() # remove header\n n = 0\n for line in io:\n line = line.decode(\"utf-8\")\n sv = decipher_HI(line)\n sv.pos1 = int(sv.pos1)\n \n db_svid = \"decipherHI{}\".format(n)\n n += 1\n\n bed = [sv.chrom, sv.pos1, sv.pos2, sv.svtype, db_svid,\n sv.gene_hi]\n bed_list.append(bed)\n bed_list.sort(key = operator.itemgetter(0, 1))\n bed_lines = []\n for i in bed_list:\n i[1] = str(i[1])\n bed_lines.append(\"\\t\".join(i)+\"\\n\")\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\n\nclass cosmic_cnv(object):\n \"\"\"\n Convert CosmicCompleteCNA.tsv.gz(CNV) into database bed\n too many records 31723168, need refine for annotation, beta!!!\n \"\"\"\n def __init__(self,record):\n fields = record.strip().split(\"\\t\")\n self.CNV_ID = fields[0]\n self.Primary_site = fields[5]\n self.Primary_histology = fields[9]\n self.svtype = fields[-4]\n if self.svtype == \"gain\":\n self.svtype = \"DUP\"\n if self.svtype == \"loss\":\n self.svtype = \"DEL\"\n sv_positions = fields[-1] # chrom:start..end\n if \":\" and \"..\" in sv_positions:\n sp1 = sv_positions.split(\":\")\n sp2 = sp1[1].split(\"..\")\n self.chrom = sp1\n self.pos1 = sp2[0]\n self.pos2 = sp2[1]\n else:\n raise RuntimeError(\"{} not match 'chrom:start..end'\".format(\n sv_positions))\n\n @classmethod\n def print_bed(cls,input_gz,out_name):\n bed_list = []\n cnv_ids = []\n with gzip.open(input_gz,\"r\") as io:\n io.readline() # remove header\n n = 0\n for line in io:\n line = line.decode(\"utf-8\")\n sv = cosmic_cnv(line)\n if sv.CNV_ID in cnv_ids:\n continue # remove 'Duplicated' record. CosmicCNA store CNV considering gene informations which is not necessary here\n else:\n cnv_ids.append(sv.CNV_ID)\n sv.pos1 = int(sv.pos1)\n \n db_svid = \"cosmic{}\".format(n)\n n += 1\n\n bed = [sv.chrom, sv.pos1, sv.pos2, sv.svtype, db_svid,\n sv.Primary_site, sv.Primary_histology]\n bed_list.append(bed)\n bed_list.sort(key = operator.itemgetter(0, 1))\n bed_lines = []\n for i in bed_list:\n i[1] = str(i[1])\n bed_lines.append(\"\\t\".join(i)+\"\\n\")\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\n\n#class cosmic_sv(object):\n# \"\"\"\n# convert cosmic CosmicStructExport.tsv.gz into database bed\n# \"\"\"\n# def __init__(self,record):\n# fileds = record.strip().split(\"\\t\")\n\n\ndef main():\n #one_thousand_sv.print_bed(sys.argv[1],sys.argv[2])\n #dgv_gold_cnv.print_bed(sys.argv[1],sys.argv[2])\n #dbVar_nstd37_sv.print_bed(sys.argv[1],sys.argv[2])\n #decipher_HI.print_bed(sys.argv[1],sys.argv[2])\n #cosmic_cnv.print_bed(sys.argv[1],sys.argv[2])\n #make_grand_sv_db(sys.argv[1], \"tmp\")\n pass\n\nif __name__ == \"__main__\":\n main()\n\n"
},
{
"alpha_fraction": 0.46854424476623535,
"alphanum_fraction": 0.4926847219467163,
"avg_line_length": 37.144187927246094,
"blob_id": "6c23d49e0275056fff6531e7da9a5ac2b102b2a5",
"content_id": "e36a83d0edb1c9ba0990e3353bbfd23a767b2692",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8202,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 215,
"path": "/sv_vcf.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nA Universal Stucture Variant VCF parsing module\ntested vcf: sniffles vcf, nanosv vcf, picky vcf\nshared INFO ID are: SVTYPE, END, SVLEN\nRE(reads evidence): sniffles, picky; nano SV: RT(2d,template,complement)\nBND shared format: N[ref:pos2[\n\nBND format:\n N]chr6:25647927]\nSTAT REF ALT Meaning\ns1 s t[p[ piece extending to the right of p is joined after t\ns2 s t]p] reverse comp piece extending left of p is joined after t\ns3 s ]p]t piece extending to the left of p is joined before t\ns4 s [p[t reverse comp piece extending right of p is joined before t\n\"\"\"\nimport sys\nimport logging\n\n\nclass bnd(object):\n # for nano sv BND only, must be adjusted when use in other cases\n def __init__(self,bnd_string):\n self.bnd_string = bnd_string\n\n # fix bnd_string, no matter what is the ref character('N','A','T','C','G','t'), replace it with 'N'\n if \"[\" in self.bnd_string:\n if self.bnd_string[0] == \"[\":\n index_2 = self.bnd_string[1:].index(\"[\")\n self.bnd_string = self.bnd_string[:index_2+2]+\"N\"\n else:\n index_1 = self.bnd_string.index(\"[\")\n self.bnd_string = \"N\"+self.bnd_string[index_1:]\n else:\n if self.bnd_string[0] == \"]\":\n index_2 = self.bnd_string[1:].index(\"]\")\n self.bnd_string = self.bnd_string[:index_2+2]+\"N\"\n else:\n index_1 = self.bnd_string.index(\"]\")\n self.bnd_string = \"N\"+self.bnd_string[index_1:]\n\n # N[chr1:123456[, N]chr1:123456], ]chr1:123456]N, [chr1:123456[N\n if self.bnd_string[:2] == \"N[\":\n self.stat = \"s1\"\n self.pos = self.bnd_string[2:-1]\n if self.bnd_string[:2] == \"N]\":\n self.stat = \"s2\"\n self.pos = self.bnd_string[2:-1]\n if self.bnd_string[0] == \"]\":\n self.stat = \"s3\"\n self.pos = self.bnd_string[1:-2]\n if self.bnd_string[0] == \"[\":\n self.stat = \"s4\"\n self.pos = self.bnd_string[1:-2]\n self.chrom = self.pos.split(\":\")[0]\n self.pos_num = self.pos.split(\":\")[1]\n\n\nclass SV(object):\n def __init__(self,record):\n self.record = record\n fields = record.strip().split(\"\\t\")\n # checked if ID is unique for sniffles, nanosv, picky vcf\n (self.chrom1,self.pos1,self.id,self.ref,self.alt,self.qual,self.filter,\n self.info,self.format) = fields[:9]\n self.samples = fields[9:]\n # info dict\n self.info_dict = {}\n info_list = self.info.split(\";\")\n for i in info_list:\n if \"=\" in i:\n info_id,info_value = i.split(\"=\")\n self.info_dict[info_id] = info_value\n else:\n self.info_dict[i] = i\n\n self.svtype = self.info_dict[\"SVTYPE\"]\n # BND, svtype, pos2\n if self.svtype == \"BND\":\n bnd_pos = bnd(self.alt) # BND position\n self.chrom2 = bnd_pos.chrom\n self.pos2 = bnd_pos.pos_num\n if (self.chrom1 == self.chrom2 and (bnd_pos.stat == \"s2\"\n or bnd_pos.stat == \"s4\")): # INV\n self.svtype = \"INV\"\n elif self.chrom1 != self.chrom2:\n self.svtype = \"TRA\"\n else:\n raise RuntimeError(\"bad line {}\".format(record))\n elif self.svtype == \"TRA\": # sniffles TRA (BND not specified)\n self.chrom2 = self.info_dict[\"CHR2\"]\n self.pos2 = self.info_dict[\"END\"]\n else:\n self.chrom2 = self.chrom1\n self.pos2 = self.info_dict[\"END\"]\n # exchange pos1 and pos2, if pos1 > pos2\n if int(self.pos1) > int(self.pos2):\n tmp = self.pos1\n self.pos1 = self.pos2\n self.pos2 = tmp\n # svlen\n try:\n self.svlen = self.info_dict[\"SVLEN\"]\n except KeyError:\n # INS, TRA do not have SVLEN attribute\n self.svlen = \"NA\"\n # RE(number of read evidence)\n if \"RE\" in self.info_dict: # sniffles and picky\n self.re = self.info_dict[\"RE\"]\n elif \"RT\" in self.info_dict: # nanosv\n # RT=2d,template,compementary; no matter what kind of reads they\n # are, add them up\n self.re = sum([int(i) for i in self.info_dict[\"RT\"].split(\",\")])\n self.re = str(self.re)\n else:\n self.re = \"NA\"\n logging.warning(\"Can not get RE(support reads num) \"\n \"for {}\".format(record))\n\ndef vcf_to_bed(vcf, out_name, filter=False, min_support_reads=0,\n chr_remove=False, sv_id_prefix=None):\n with open(vcf,\"r\") as io:\n lines = io.readlines()\n\n # chromosomes to be kept\n main_chr = (list(range(1,23)) + [\"X\", \"Y\", \"MT\", \"M\", \"chrX\", \"chrY\",\n \"chrM\", \"chrMT\"] + [\"chr\"+str(i) for i in range(1, 23)])\n\n # output bedlines\n bed_lines = []\n\n # check if id is unique\n id_dict = {}\n #chrom1,pos1,chrom2,pos2\n previous_sv_breakpoint = [\"NA\",\"NA\",\"NA\",\"NA\"]\n for line in lines:\n #skip comment lines\n if line.strip()[0] == \"#\":\n continue\n sv = SV(line)\n\n # filter\n if filter:\n if sv.chrom1 not in main_chr or sv.chrom2 not in main_chr:\n continue\n\n if int(sv.re) < min_support_reads:\n continue\n\n # remove 'chr' in chromosome id\n if chr_remove:\n sv.chrom1 = sv.chrom1.replace(\"chr\", \"\")\n sv.chrom2 = sv.chrom2.replace(\"chr\", \"\")\n\n # rename sv id\n if sv_id_prefix:\n sv.id = sv_id_prefix + sv.id\n\n if sv.id not in id_dict:\n id_dict[sv.id] = 1\n else:\n raise RuntimeError(\"Duplicated SV ID in you VCF \"\n \"file {}\".format(sv.id))\n sv_breakpoint = [sv.chrom1,sv.pos1,sv.chrom2,sv.pos2]\n # remove duplicate adjacency BND record in picky vcf\n # Exactly the same\n if ((sv.svtype == \"TRA\" or sv.svtype == \"INV\") and\n sv_breakpoint[:4] == previous_sv_breakpoint[:4]):\n continue\n # just swap breakpoint1 and breakpoint2, still the same\n if ((sv.svtype == \"TRA\" or sv.svtype == \"INV\") and\n sv_breakpoint[:2] == previous_sv_breakpoint[2:] and\n sv_breakpoint[2:] == previous_sv_breakpoint[:2]):\n previous_sv_breakpoint = sv_breakpoint\n continue\n\n previous_sv_breakpoint = sv_breakpoint\n # convert to bed format\n # chrom,start,end,svtype,id,svlen,re,info\n if sv.chrom1 == sv.chrom2:\n if int(sv.pos1) > 1:\n sv.pos1 = str(int(sv.pos1)-1)\n bed_line = \"\\t\".join([sv.chrom1,sv.pos1,sv.pos2,sv.svtype,\n sv.id,sv.svlen,sv.re,sv.info])+\"\\n\"\n else: #TRA\n if int(sv.pos1) > 1:\n pos1_1 = str(int(sv.pos1)-1)\n pos1_2 = sv.pos1\n elif int(sv.pos1) == 1:\n pos1_1 = \"1\"\n pos1_2 = \"1\"\n else:\n continue # invalid position\n if int(sv.pos2) > 1:\n pos2_1 = str(int(sv.pos2)-1)\n pos2_2 = sv.pos2\n elif int(sv.pos2) == 1:\n pos2_1 = \"1\"\n pos2_2 = \"1\"\n else:\n continue # invalid position\n bed_line1 = \"\\t\".join([sv.chrom1,pos1_1,pos1_2,sv.svtype,\n sv.id+\"_1\",sv.svlen,sv.re,sv.info])+\"\\n\"\n bed_line2 = \"\\t\".join([sv.chrom2,pos2_1,pos2_2,sv.svtype,\n sv.id+\"_2\",sv.svlen,sv.re,sv.info])+\"\\n\"\n bed_line = bed_line1+bed_line2\n bed_lines.append(bed_line)\n with open(out_name,\"w\") as io:\n io.writelines(bed_lines)\n\ndef main():\n #test\n vcf_to_bed(sys.argv[1],sys.argv[2])\n\nif __name__ == \"__main__\":\n main()\n\n"
},
{
"alpha_fraction": 0.5065789222717285,
"alphanum_fraction": 0.5173001885414124,
"avg_line_length": 36.65137481689453,
"blob_id": "b8f45267101bd9e82c9a6854d7d0adb657c804a7",
"content_id": "f295e2b8c5011453db69d0eb7a61adfc3ca14505",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4104,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 109,
"path": "/traslocation_compare.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\nimport os\nimport subprocess\nimport sys\n\nfrom bed_intersect import intersect_f\nfrom table_check import TableCheck\n\ndef TraCompare(bedtools, bedA, bedB, max_dist, tmp_dir, prefix, db_id):\n # result sv dict, key: query sv id, value: db fields\n tra_compare_result = {}\n\n # calculate query and database fields number\n query_field_num = TableCheck(bedA)\n # db_field_num = table_check(bedB)\n\n # padding\n padding = max_dist\n padding_tmp_bed = os.path.join(tmp_dir, \n \"{}.{}.tra.padding{}.tmp.bed\".format(prefix, db_id, padding))\n \n with open(padding_tmp_bed, \"w\") as padding_io:\n with open(bedA, \"r\") as bedA_io:\n for line in bedA_io: \n line = line.strip()\n if line[0] == \"#\":\n print(line, file = padding_io)\n else:\n fields = line.split(\"\\t\")\n bed_start = int(fields[1])\n bed_end = int(fields[2])\n if bed_start > padding: # make sure start not less than 1\n bed_start = bed_start - padding\n else:\n bed_start = 1\n bed_end = bed_end + padding\n\n fields[1] = str(bed_start)\n fields[2] = str(bed_end)\n\n print(\"\\t\".join(fields), file = padding_io)\n\n intersect_tmp_bed = os.path.join(tmp_dir,\n \"{}.{}.tra.intersect.tmp.bed\".format(prefix, db_id))\n\n # bedtools intersect, padding + intersect to get all SVs near the brk\n with open(intersect_tmp_bed,\"w\") as io:\n subprocess.run([bedtools, \"intersect\", \"-a\", padding_tmp_bed, \"-b\",\n bedB,\"-wo\"], stdout = io)\n\n # read intersect file\n # chrom start end svtype svid svlen re info;\n # svid is a unique identifier for the sv\n with open(intersect_tmp_bed, \"r\") as io:\n tra_pair = {}\n lines = io.readlines()\n for line in lines:\n fields = line.strip().split(\"\\t\")\n query_fields = fields[:query_field_num]\n db_fields = fields[query_field_num:-1]\n intersect_field = intersect_f(fields, query_field_num)\n\n # 'WILD' type database SVs match any query SV, do breakpoint annotation\n if intersect_field.db_svtype == \"WILD\":\n tra_compare_result.setdefault(intersect_field.query_svid,\n []).append(db_fields)\n elif intersect_field.db_svtype == \"TRA\":\n tra_main_id = \"_\".join(\n intersect_field.query_svid.split(\"_\")[:-1])\n tra_pair.setdefault(tra_main_id,[]).append(fields)\n\n if tra_pair:\n for i in tra_pair:\n\n # print(tra_pair[i])\n # get paired database traslocation\n db_tra_pair = {}\n for r in tra_pair[i]:\n query_fields = r[:query_field_num]\n db_fields = r[query_field_num:-1]\n intersect_field = intersect_f(r, query_field_num)\n\n # print(intersect_field.db_svid)\n db_tra_main_id = \"_\".join(intersect_field.db_svid.split(\"_\")[:-1])\n db_tra_pair.setdefault(db_tra_main_id,[]).append(r)\n # print(db_tra_pair)\n\n for p in db_tra_pair:\n if len(db_tra_pair[p]) == 2:\n if (db_tra_pair[p][0][4] != db_tra_pair[p][1][4]):\n # two query sv ids are not the same\n tra_compare_result.setdefault(db_tra_pair[p][0][4],\n []).append(db_tra_pair[p][0][query_field_num:-1])\n tra_compare_result.setdefault(db_tra_pair[p][1][4],\n []).append(db_tra_pair[p][1][query_field_num:-1])\n return tra_compare_result\n\n\ndef main():\n # test\n result = TraCompare(\"bedtools\", sys.argv[1], sys.argv[2], 1000, \"tmp1\", \"test_tra1\", \"TEST1\")\n for i in result:\n print(i, \":\", result[i])\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.5330693125724792,
"alphanum_fraction": 0.5405940413475037,
"avg_line_length": 32.66666793823242,
"blob_id": "0da87252d718ff0056f151b1034b7c55b3d16571",
"content_id": "4c032d83ab192f18964b6a6283967511ebb039ff",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2525,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 75,
"path": "/insertion_compare.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\nimport os\nimport subprocess\n\n\nfrom bed_intersect import intersect_f\nfrom table_check import TableCheck\n\n\ndef InsCompare(bedtools, bedA, bedB, max_dist, tmp_dir, prefix, db_id):\n # result sv dict, key: query sv id, value: db fields\n intersect_result = {}\n\n # calculate query and database fields number\n query_field_num = TableCheck(bedA)\n # db_field_num = table_check(bedB)\n\n # padding\n padding = max_dist\n padding_tmp_bed = os.path.join(tmp_dir, \n \"{}.{}.ins.padding{}.tmp.bed\".format(prefix, db_id, padding))\n \n with open(padding_tmp_bed, \"w\") as padding_io:\n with open(bedA, \"r\") as bedA_io:\n for line in bedA_io: \n line = line.strip()\n if line[0] == \"#\":\n print(line, file = padding_io)\n else:\n fields = line.split(\"\\t\")\n bed_start = int(fields[1])\n bed_end = int(fields[2])\n if bed_start > padding: # make sure start not less than 1\n bed_start = bed_start - padding\n else:\n bed_start = 1\n bed_end = bed_end + padding\n\n fields[1] = str(bed_start)\n fields[2] = str(bed_end)\n\n print(\"\\t\".join(fields), file = padding_io)\n\n intersect_tmp_bed = os.path.join(tmp_dir,\n \"{}.{}.ins.intersect.tmp.bed\".format(prefix, db_id))\n\n # bedtools intersect\n with open(intersect_tmp_bed,\"w\") as io:\n subprocess.run([bedtools, \"intersect\", \"-a\", padding_tmp_bed, \"-b\",\n bedB,\"-wo\"], stdout = io)\n\n # read intersect file\n # chrom start end svtype svid svlen re info;\n # svid is a unique identifier for the sv\n with open(intersect_tmp_bed, \"r\") as io:\n lines = io.readlines()\n for line in lines:\n fields = line.strip().split(\"\\t\")\n query_fields = fields[:query_field_num]\n db_fields = fields[query_field_num:-1]\n\n intersect_field = intersect_f(fields, query_field_num)\n \n _db_svtype = intersect_field.db_svtype\n\n _query_svid = intersect_field.query_svid\n\n # WILD database SV type matchs any query SV type\n if (_db_svtype == \"INS\" or _db_svtype == \"WILD\"):\n intersect_result.setdefault(_query_svid, []).append(db_fields)\n\n return intersect_result\n"
},
{
"alpha_fraction": 0.48771458864212036,
"alphanum_fraction": 0.5062268376350403,
"avg_line_length": 32.755680084228516,
"blob_id": "1c5d99df3f12efb3cfae6d4b6833e51be7386728",
"content_id": "8bf1765a80af150afc1eaece3dbfe7a0becf9d16",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5942,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 176,
"path": "/local_database_prepare.py",
"repo_name": "Archieyoung/SVAN",
"src_encoding": "UTF-8",
"text": "\"\"\"\nAuthor: ArchieYoung <[email protected]>\nTime: Thu Jul 5 09:24:07 CST 2018\n\"\"\"\nimport sys\nimport argparse\nimport os\nfrom multiprocessing import Pool\nfrom glob import iglob\n\nfrom sv_vcf import SV\n\ndef vcf_to_db_bed(_args):\n \n vcf, min_support_reads, out_dir, sv_id_prefix = _args\n with open(vcf, \"r\") as io:\n lines = io.readlines()\n\n # chromosomes to be kept\n main_chr = ([str(i) for i in range(1, 23)] + [\"X\", \"Y\", \"MT\", \"M\", \"chrX\", \"chrY\",\n \"chrM\", \"chrMT\"] + [\"chr\" + str(i) for i in range(1, 23)])\n\n # output bedlines\n bed_lines = []\n\n # check if id is unique\n id_dict = {}\n #chrom1,pos1,chrom2,pos2\n previous_sv_breakpoint = [\"NA\", \"NA\", \"NA\", \"NA\"]\n for line in lines:\n #skip comment lines\n if line.strip()[0] == \"#\":\n continue\n sv = SV(line)\n\n # filter\n if sv.chrom1 not in main_chr or sv.chrom2 not in main_chr:\n continue\n\n if int(sv.re) < min_support_reads:\n continue\n\n # remove 'chr' in chromosome id\n sv.chrom1 = sv.chrom1.replace(\"chr\", \"\")\n sv.chrom2 = sv.chrom2.replace(\"chr\", \"\")\n\n # rename sv id\n if sv_id_prefix:\n sv.id = \"_\".join([sv_id_prefix, sv.id])\n\n if sv.id not in id_dict:\n id_dict[sv.id] = 1\n else:\n raise RuntimeError(\"Duplicated SV ID in you VCF \"\n \"file {}\".format(sv.id))\n \n sv_breakpoint = [sv.chrom1, sv.pos1, sv.chrom2, sv.pos2]\n # remove duplicate adjacency BND record in picky vcf\n # Exactly the same\n if ((sv.svtype == \"TRA\" or sv.svtype == \"INV\") and\n sv_breakpoint[:4] == previous_sv_breakpoint[:4]):\n continue\n # just swap breakpoint1 and breakpoint2, still the same\n if ((sv.svtype == \"TRA\" or sv.svtype == \"INV\") and\n sv_breakpoint[:2] == previous_sv_breakpoint[2:] and\n sv_breakpoint[2:] == previous_sv_breakpoint[:2]):\n previous_sv_breakpoint = sv_breakpoint\n continue\n\n previous_sv_breakpoint = sv_breakpoint\n # convert to bed format\n # chrom,start,end,svtype,id,svlen,re,info\n if sv.chrom1 == sv.chrom2:\n if int(sv.pos1) > 1:\n sv.pos1 = str(int(sv.pos1)-1)\n bed_line = \"\\t\".join([sv.chrom1,sv.pos1,sv.pos2,sv.svtype,\n sv.id,sv.svlen,sv.re])+\"\\n\"\n else: #TRA\n if int(sv.pos1) > 1:\n pos1_1 = str(int(sv.pos1)-1)\n pos1_2 = sv.pos1\n elif int(sv.pos1) == 1:\n pos1_1 = \"1\"\n pos1_2 = \"1\"\n else:\n continue # invalid position\n if int(sv.pos2) > 1:\n pos2_1 = str(int(sv.pos2)-1)\n pos2_2 = sv.pos2\n elif int(sv.pos2) == 1:\n pos2_1 = \"1\"\n pos2_2 = \"1\"\n else:\n continue # invalid position\n bed_line1 = \"\\t\".join([sv.chrom1,pos1_1,pos1_2,sv.svtype,\n sv.id+\"_1\",sv.svlen,sv.re])+\"\\n\"\n bed_line2 = \"\\t\".join([sv.chrom2,pos2_1,pos2_2,sv.svtype,\n sv.id+\"_2\",sv.svlen,sv.re])+\"\\n\"\n bed_line = bed_line1+bed_line2\n bed_lines.append(bed_line)\n \n out_bed_path = os.path.join(out_dir,\n \"{}.sv.database.bed\".format(sv_id_prefix))\n with open(out_bed_path, \"w\") as out_hd:\n out_hd.writelines(bed_lines)\n\n\ndef db_check(vcf_list, db_bed_list):\n \"\"\"\n return vcf list if it have not been added to the database\n \"\"\"\n db_sample_ids = dict()\n for i in db_bed_list:\n basename = os.path.basename(i)\n sample_id = basename.split(\".\")[0]\n if sample_id not in db_sample_ids:\n db_sample_ids[sample_id] = 1\n else:\n raise RuntimeError(\"Duplicated sample {} in your database\".format(sample_id))\n \n vcf_tobe_add = []\n for i in vcf_list:\n basename = os.path.basename(i)\n sample_id = basename.split(\".\")[0]\n if sample_id not in db_sample_ids:\n vcf_tobe_add.append(i)\n\n return vcf_tobe_add\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Prepare Local SV Database\",\n usage=\"usage: %(prog)s [options]\")\n parser.add_argument(\"--vcf_dir\",\n help=\"vcf file directory [default %(default)s]\", metavar=\"STR\")\n parser.add_argument(\"--db_dir\",\n help=\"database directory [default %(default)s]\", metavar=\"STR\")\n parser.add_argument(\"--min_re\",\n help=\"minimum support reads number [default %(default)s]\", type=float,\n default=2, metavar=\"INT\")\n parser.add_argument(\"--threads\",\n help=\"number of threads [default %(default)s]\", type=int,\n default=4, metavar=\"INT\")\n \n if len(sys.argv) <= 1:\n parser.print_help()\n exit()\n return parser.parse_args()\n\n\ndef main():\n args = get_args()\n # vcf file list\n vcfs = iglob(os.path.join(args.vcf_dir, \"*.vcf\"))\n\n db_beds = []\n if not os.path.exists(args.db_dir):\n os.mkdir(args.db_dir)\n else:\n db_beds = iglob(os.path.join(args.db_dir, \"*.bed\"))\n\n vcf_tobe_add = db_check(vcfs, db_beds)\n #for i in vcf_tobe_add:\n # print(\"add {} to local SV database\".format(i))\n if len(vcf_tobe_add) == 0:\n print(\"database is the newest.\")\n sys.exit(0)\n\n work_args_list = [(i, args.min_re, args.db_dir,\n os.path.basename(i)[:-4]) for i in vcf_tobe_add]\n with Pool(processes=args.threads) as pool:\n pool.map(vcf_to_db_bed, work_args_list)\n\nif __name__ == \"__main__\":\n main()\n\n"
}
] | 11 |
dnabb/bokeh-server-on-azure-web-app | https://github.com/dnabb/bokeh-server-on-azure-web-app | 74f3055b535313a51f7e236dbde8a870d1a63acd | cf82e46e4f94073880e7905556119c3241dffaa5 | ba9c6a3d5acfb089a08ab23469adc93b83a1ad6e | refs/heads/main | 2023-07-18T22:49:36.603558 | 2021-09-06T11:42:11 | 2021-09-06T11:42:11 | 400,506,105 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.632612943649292,
"alphanum_fraction": 0.664047122001648,
"avg_line_length": 30.8125,
"blob_id": "53cf3600920e3b296e493fbe009f348c407e56c8",
"content_id": "6d5d5adac2d90735d8192e1ecd3849947382b2ae",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1527,
"license_type": "permissive",
"max_line_length": 135,
"num_lines": 48,
"path": "/wedge.py",
"repo_name": "dnabb/bokeh-server-on-azure-web-app",
"src_encoding": "UTF-8",
"text": "\nfrom math import pi\nimport pandas as pd\n\nfrom bokeh.io import curdoc\nfrom bokeh.models import ColumnDataSource, Select\nfrom bokeh.layouts import row\nfrom bokeh.palettes import Category10\nfrom bokeh.plotting import figure\nfrom bokeh.transform import cumsum\n\nx1 = {'A': 157, 'B': 93, 'C': 89}\n\nx2 = {'A': 34, 'B': 58, 'C': 27, 'D': 192 } # Adding a new category \"D\" breaks the plot\n\ndef make_df(x):\n df = pd.DataFrame.from_dict(x, orient='index').reset_index()\n df.rename(columns={0:'value', 'index':'country'}, inplace=True)\n df['angle'] = df['value']/df['value'].sum() * 2*pi\n df['color'] = Category10[len(df['value'])]\n return df\n\ndf1 = make_df(x1)\ndf2 = make_df(x2)\n\nsrc = ColumnDataSource(df1)\n\nregion = figure(height=350, toolbar_location=None, outline_line_color=None, sizing_mode=\"scale_both\", name=\"region\", x_range=(-0.4, 1))\nrr = region.annular_wedge(x=-0, y=1, inner_radius=0.2, outer_radius=0.32,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', source=src)\n\noptions = ['x1', 'x2']\nselect = Select(value=options[0], title='Select here:', options=options)\n\nregion.axis.axis_label=None\nregion.axis.visible=False\nregion.grid.grid_line_color = None\n\ndef update(attr, old, new):\n if new == 'x2':\n src.data = ColumnDataSource.from_df(df2)\n else:\n src.data = ColumnDataSource.from_df(df1)\n print('Updated!')\n\nselect.on_change('value', update)\n\ncurdoc().add_root(row(select, region))"
},
{
"alpha_fraction": 0.6530933976173401,
"alphanum_fraction": 0.6707291007041931,
"avg_line_length": 38.18258285522461,
"blob_id": "6dcf3e5b1552f0ee27644046bd40e8b3058472d1",
"content_id": "c16c95bd017b3d03dc515caa62f03247b593fd02",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13949,
"license_type": "permissive",
"max_line_length": 179,
"num_lines": 356,
"path": "/app.py",
"repo_name": "dnabb/bokeh-server-on-azure-web-app",
"src_encoding": "UTF-8",
"text": "# %%\nfrom bokeh.models.ranges import Range1d\nimport pandas as pd\nfrom bokeh.layouts import column, row, gridplot\nfrom bokeh.models import Panel, Tabs, Div\nfrom bokeh.models import ColumnDataSource, HoverTool, DatetimeTickFormatter, Legend, Label, DateRangeSlider, HTMLTemplateFormatter, DataTable, TableColumn\nfrom bokeh.palettes import Category10 as colors\nfrom bokeh.plotting import figure, curdoc, output_file, show\nfrom bokeh.transform import cumsum\nfrom math import pi\nfrom datetime import datetime\n\noutput_file(\"line.html\")\n\n# %%\n# Import the data\nbds = pd.read_csv('boards_clean.csv', decimal=\".\", index_col=0, parse_dates=['CreationDate'])\nbds.set_index('CreationDate', inplace=True)\n\n# Actualize the timestamps\nstart_time = datetime.now()\nshift = start_time - bds.index.max()\nbds.index = bds.index + shift\nlive_data_start = pd.Timestamp('2021-08-26 05:58') + shift\nlive_data_end = pd.Timestamp('2021-08-26 12:30') + shift\n\n# %%\ndimensions = sorted(bds['NearestDimension'].unique().tolist())\nqualities = sorted(bds['QualityDescr'].unique().tolist())\ndim_colors_mapping = dict(zip(dimensions, colors[10]))\nqual_colors_mapping = dict(zip(qualities, [ '#fee0d2', '#31a354', '#a1d99b', '#e5f5e0', '#de2d26' ]))\nqualities = bds['QualityDescr'].unique().tolist()\nbds['dim_color'] = bds['NearestDimension'].map(dim_colors_mapping)\nbds['qual_color'] = bds['QualityDescr'].map(qual_colors_mapping)\nbds['speed'] = bds['BoardID'].rolling('1min', min_periods=1).count()\nlive = bds.loc[live_data_start:live_data_end]\nlive_speed = live.resample('1s').count().rolling(60, min_periods=0).sum()['speed'].to_frame()\nfirst_board = live.index.min()\n\n#%%\n### DIMENSION ANALYSIS\n# Create plots\nplot_width = 600\nplot_height = 300\navg_thick = figure(x_axis_type=\"datetime\", title='Thickness (hourly average)', width=plot_width, height=plot_height)\navg_width = figure(x_axis_type=\"datetime\", title='Width (hourly average)', width = plot_width, height=plot_height)\nstd_thick = figure(x_axis_type=\"datetime\", title='Thickness (hourly standard deviation)', width = plot_width, height=plot_height)\nstd_width = figure(x_axis_type=\"datetime\", title='Width (hourly standard deviation)', width = plot_width, height=plot_height)\n\nplots = [avg_thick, avg_width, std_thick, std_width]\n\n# Add a slider and adjust the ranges\nxRangeStart = bds.index.min().floor('60min')\nxRangeEnd = bds.index.max().ceil('60min')\nxRange_selected = (xRangeEnd - pd.Timedelta('1 day'), xRangeEnd)\nxRange = Range1d(start=xRangeEnd - pd.Timedelta('1 day'), end=xRangeEnd, bounds=(xRangeStart, xRangeEnd))\n\nplots_slider = DateRangeSlider(value=xRange_selected, start=bds.index.min(), end=bds.index.max(), title='Select timeframe')\ndtFormatter = DatetimeTickFormatter(days=\"%d %b\", months='%b %Y')\n\n# Add renderers\nlw = 5\nrenderers = {}\nfor d, c in zip(dimensions, colors[10]):\n data = bds[bds['NearestDimension']==d]\n data=data.resample('60min').agg({'BoardID':'count', \n 'MeasuredWidth': ['mean', 'std'], \n 'MeasuredThickness': ['mean', 'std']})\n cds = ColumnDataSource(data=data)\n at = avg_thick.line(x='CreationDate', y='MeasuredThickness_mean', source=cds, name=d, color=c, line_width=lw, visible=False)\n aw = avg_width.line(x='CreationDate', y='MeasuredWidth_mean', source=cds, name=d, color=c, line_width=lw, visible=False)\n st = std_thick.line(x='CreationDate', y='MeasuredThickness_std', source=cds, name=d, color=c, line_width=lw, visible=False)\n sw = std_width.line(x='CreationDate', y='MeasuredWidth_std', source=cds, name=d, color=c, line_width=lw, visible=False)\n renderers[d] = [at, aw, st, sw]\n\n# Prepare the hovers\nhover = HoverTool(\n tooltips= [\n ('Date', '@CreationDate{%a %F %H:%M}'),\n ('Dimension', '$name'),\n ('Sample size', \"@BoardID_count\"),\n ('Average thickness', '@MeasuredThickness_mean'),\n ('Average width', '@MeasuredWidth_mean'),\n ('Thickness stDev', '@MeasuredThickness_std'),\n ('Width stDev', '@MeasuredWidth_std'),\n ], \n formatters={\n '@CreationDate' : 'datetime',\n },\n renderers=[item for sublist in renderers.values() for item in sublist], # This needs to be a list of renderers\n toggleable=False # This is to prevent multiple hover buttons\n) \n\n# Add legend\nlegend_items = [(k, v) for k, v in renderers.items()]\nlegend = Legend(items=legend_items)\nlegend.click_policy=\"hide\"\navg_thick.add_layout(legend, 'left')\n\nfor p in plots:\n p.xaxis.formatter = dtFormatter\n p.x_range = xRange\n p.y_range.only_visible=True\n p.add_tools(hover)\n\n# Make one dimension visible\nfor r in renderers['16x75']:\n r.visible=True\n\n# Prepare layout\ngrid = gridplot(plots, ncols=2, sizing_mode='stretch_width', toolbar_location='right')\n\n#%%\n### TIME STUDY\nf = 15\nbar_width = f*60*1000\ngrouper = bds.groupby([pd.Grouper(freq=str(f) + 'T'), 'QualityDescr', 'NearestDimension'])\nresampled_bds = grouper.agg({'BoardID':'count'}).reset_index()\nresampled_bds['QualityDescr']= pd.Categorical(resampled_bds['QualityDescr'], [\"SF1\", \"SF3\", \"SF4\", \"Omkantning\", \"Vrak\"])\nresampled_bds['NearestDimension']= pd.Categorical(resampled_bds['NearestDimension'])\n\nspeed_df = resampled_bds.groupby('CreationDate').sum()\nspeed_df['speed'] = speed_df['BoardID']/f\n#%%\nspeed_cds = ColumnDataSource(speed_df)\n\nspeed_hist = figure(x_axis_type=\"datetime\", title='Speed (pcs/min)', height=350, width=1200, tools = \"tap,box_select,wheel_zoom,box_zoom,pan,reset,save\", active_drag=\"box_select\")\n\nspeed_renderer = speed_hist.vbar(x='CreationDate', top='speed', source=speed_cds, width=bar_width)\n\n# Slider to select the timeframe:\nts_slider = DateRangeSlider(value=xRange_selected, start=bds.index.min(), end=bds.index.max(), title='Select timeframe')\nspeed_hist.x_range.start = xRange_selected[0]\nspeed_hist.x_range.end = xRange_selected[1]\nspeed_hist.y_range.bounds = (-5,100)\n\nspeed_hover = HoverTool(\n tooltips= [\n ('Date', '@CreationDate{%a %F %H:%M}'),\n ('Speed', '@speed{0} pcs/min'),\n ('Total boards', '@BoardID{0} pcs'),\n ], \n formatters={\n '@CreationDate' : 'datetime',\n },\n renderers=[speed_renderer], # This needs to be a list of renderers\n toggleable=False # This is to prevent multiple hover buttons\n)\nspeed_hist.add_tools(speed_hover) \n\n#%%\nqs = figure(height=350, toolbar_location=None, outline_line_color=None, sizing_mode=\"scale_both\", x_range=(0, 1), y_range=(0,1))\nqs_text = qs.text(x=0.5, y=0.5, text=['Select a bar to show qualities'], align='center')\n\nqs.toolbar.active_tap = None\nqs.toolbar.active_scroll = None\nqs.toolbar.active_drag = None\n\ndef make_qualities_df(i):\n qdf = resampled_bds.groupby(['CreationDate','QualityDescr']).sum().reset_index('QualityDescr').loc[speed_df.iloc[i].index.values]\n qdf = qdf.groupby('QualityDescr').sum().reset_index()\n qdf['angle'] = qdf['BoardID']/qdf['BoardID'].sum() * 2*pi\n qdf['color'] = qdf['QualityDescr'].map(qual_colors_mapping)\n qdf['perc'] = qdf['BoardID']/qdf['BoardID'].sum()\n return qdf\n\nqualities_df = make_qualities_df([1])\nquality_cds = ColumnDataSource(data=qualities_df)\n#%%\nqs_rend = qs.annular_wedge(x=0.5, y=0.5, inner_radius=0.12, outer_radius=0.22,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', legend_group='QualityDescr', source=quality_cds, visible=False)\n\nqualities_order = [1, 2, 3, 0, 4]\nqs.legend.items = [qs.legend.items[i] for i in qualities_order]\n\nqs.axis.axis_label=None\nqs.axis.visible=False\nqs.grid.grid_line_color = None\n\nqualities_hover = HoverTool(\n tooltips= [\n ('Quality', '@QualityDescr'),\n ('Percentage', '@perc{0.00%}'),\n ], \n formatters={\n '@CreationDate' : 'datetime',\n },\n renderers=[qs_rend], # This needs to be a list of renderers\n toggleable=False # This is to prevent multiple hover buttons\n)\nqs.add_tools(qualities_hover) \n\n#%%\nds = figure(height=350, toolbar_location=None, outline_line_color=None, sizing_mode=\"scale_both\", x_range=(0, 1), y_range=(0, 1))\nds_text = ds.text(x=0.5, y=0.5, text=['Select a bar to show dimensions'], align='center')\n\nds.toolbar.active_tap = None\nds.toolbar.active_scroll = None\nds.toolbar.active_drag = None\n\ndef make_dim_df(i):\n ddf = resampled_bds.groupby(['CreationDate','NearestDimension']).sum().reset_index('NearestDimension').loc[speed_df.iloc[i].index.values]\n ddf = ddf.groupby('NearestDimension').sum().reset_index()\n ddf['angle'] = ddf['BoardID']/ddf['BoardID'].sum() * 2*pi\n ddf['color'] = ddf['NearestDimension'].map(dim_colors_mapping)\n ddf['perc'] = ddf['BoardID']/ddf['BoardID'].sum()\n return ddf\n\ndimensions_df = make_dim_df([1])\ndimensions_cds = ColumnDataSource(data=dimensions_df)\n#%%\nds_rend = ds.annular_wedge(x=0.5, y=0.5, inner_radius=0.12, outer_radius=0.22,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', legend_group='NearestDimension', source=dimensions_cds, visible=False)\n\nds.axis.axis_label=None\nds.axis.visible=False\nds.grid.grid_line_color = None\n\ndimensions_hover = HoverTool(\n tooltips= [\n ('Dimension', '@NearestDimension'),\n ('Percentage', '@perc{0.00%}'),\n ], \n formatters={\n '@CreationDate' : 'datetime',\n },\n renderers=[ds_rend], # This needs to be a list of renderers\n toggleable=False # This is to prevent multiple hover buttons\n)\nds.add_tools(dimensions_hover) \n\n#%%\n### LIVE DATA\n# Current speed\ncs_df = live_speed.loc[first_board:first_board + pd.Timedelta(\"1 minute\")]\ncs_cds = ColumnDataSource(cs_df)\nspeed_str = '{:.0f}'.format(cs_df['speed'].iloc[-1])\nspeed_x = cs_df.index[-1] - pd.Timedelta(\"30 second\")\n\ncs = figure(x_axis_type=\"datetime\", height=400, width=400, toolbar_location=None)\ncs.x_range.range_padding = 0\ncs.y_range = Range1d(start=0, end=100, bounds=(0,100))\ncs.toolbar.active_tap = None\ncs.toolbar.active_scroll = None\ncs.toolbar.active_drag = None\n\ncs_label = Label(x=180, y=200, x_units='screen', y_units='screen', text=speed_str, text_align='center', text_baseline='middle', text_font_size=\"200px\")\ncs.add_layout(cs_label)\n\ncs_title = Div(text='''<header>\n <span style=\"color:#5B5B5B;font-size:1.25em;font-family:Calibri Light; font-weight: bold\">Current speed</span>''')\n\ncs_r1 = cs.varea(x='CreationDate', y1=0, y2='speed', fill_alpha=0.5, source=cs_cds)\ncs_r2 = cs.line(x='CreationDate', y='speed', line_width=5, line_color='black', source=cs_cds)\n\ncc = column(cs_title, cs)\n\n\n#%%\n# Latest boards table\nlb_df = live.iloc[0:14].copy()\nlb_df.sort_values('CreationDate', ascending=False, inplace=True)\nlb_cds = ColumnDataSource(lb_df)\n\ntemplate = \"\"\" \n <div style=\"background:<%= qual_color %>;\">\n  \n </div>\n \"\"\"\nformatter = HTMLTemplateFormatter(template=template)\ncolumns = [\n TableColumn(field='qual_color', title='', formatter=formatter, width=35),\n TableColumn(field='MeasuredThickness', title='Thickness', width=100),\n TableColumn(field='MeasuredWidth', title='Width', width=100),\n TableColumn(field='QualityDescr', title='Quality', width=100),\n]\ntable = DataTable(source=lb_cds, columns=columns, index_position=None, autosize_mode='none', height=400)\ntable_title = Div(text='''<header>\n <span style=\"color:#5B5B5B;font-size:1.25em;font-family:Calibri Light; font-weight: bold\">Latest boards</span>''')\n\ntc = column(table_title, table)\n\n#%%\n# CALLBACKS\ndef update_speed_stats(attr, old, new):\n if new == []:\n qs_rend.visible=False\n qs_text.visible=True\n else:\n qs_rend.visible=True\n qs_text.visible=False\n qualities_df = make_qualities_df(new)\n qualities_dict = ColumnDataSource.from_df(qualities_df)\n quality_cds.data= qualities_dict\n\ndef update_dim_stats(attr, old, new):\n if new == []:\n ds_rend.visible=False\n ds_text.visible=True\n else:\n ds_rend.visible=True\n ds_text.visible=False\n dimensions_df = make_dim_df(new)\n dimensions_dict = ColumnDataSource.from_df(dimensions_df)\n dimensions_cds.data= dimensions_dict\n\ndef update_stats(attr, old, new):\n update_speed_stats(attr, old, new)\n update_dim_stats(attr, old, new)\n#%%\ndef update_cs(elapsed):\n global first_board\n cs_df = live_speed.loc[first_board+elapsed:first_board+elapsed+pd.Timedelta('1 minute')]\n cs_label.text = ('{:.0f}'.format(cs_df['speed'].iloc[-1]))\n cs_cds.data = ColumnDataSource.from_df(cs_df)\n#%%\n\ndef update_table(elapsed):\n global first_board\n lb_df = live.loc[first_board+elapsed:live.index.max()].iloc[0:14].copy()\n lb_df.sort_values('CreationDate', ascending=False, inplace=True)\n lb_cds.data = ColumnDataSource.from_df(lb_df)\n\ndef update_live(*e):\n global start_time\n elapsed = datetime.now() - start_time\n update_cs(elapsed)\n update_table(elapsed)\n\nspeed_cds.selected.on_change('indices', update_stats)\ndimensions_cds.selected.on_change('indices', update_stats)\n# Sliders callbacks. Not bidirectional.\nplots_slider.js_link('value', xRange, 'start', attr_selector=0)\nplots_slider.js_link('value', xRange, 'end', attr_selector=1)\nts_slider.js_link('value', speed_hist.x_range, 'start', attr_selector=0)\nts_slider.js_link('value', speed_hist.x_range, 'end', attr_selector=1)\n\ncurdoc().add_periodic_callback(update_live, 1000)\n\n#%%\n### LAYOUTING\ntab1 = Panel(child=row(cc, tc), title='Live data')\ntab2 = Panel(child=column(plots_slider, grid), title=\"Dimension analysis\")\ntab3 = Panel(child=column(ts_slider, speed_hist, row(qs, ds)), title='Production analysis')\n\n# %%\nlayout = row(Tabs(tabs=[tab1, tab2, tab3]))\nshow(layout)\n\n# %%\n\ncurdoc().add_root(layout)\ncurdoc().title = \"Example dashboard\"\n# %%\n"
}
] | 2 |
acba/crawler-bnmp | https://github.com/acba/crawler-bnmp | 867782192528b2c0769a36efcb55fe4a48c034d6 | 3b400ea968572de97ab38209411388b964b1ea9d | a3d55a040ed2558e67f01ebd0c63d546fa774a1b | refs/heads/master | 2021-01-20T09:45:44.433705 | 2017-05-04T16:25:58 | 2017-05-04T16:25:58 | 90,283,322 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.657192051410675,
"alphanum_fraction": 0.6632213592529297,
"avg_line_length": 23.723403930664062,
"blob_id": "8ae2b553ac820d5c900f407aef973ff68ba326da",
"content_id": "582ee5387f2a50d71dc53e6f28d925b38d4c1a2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1162,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 47,
"path": "/getMandadosDetalhes.py",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "import requests\nfrom requests import Request\nimport json\nfrom pprint import pprint\nfrom time import sleep\nimport os \nimport random\n\nurlDetalhar = \"http://www.cnj.jus.br/bnmp/rest/detalhar\"\nufs = [\"PB\", \"PE\", \"RN\"]\n# ufs = [\"PB\"]\n\ndef getData(data):\n\tresponse = requests.post(urlDetalhar, json=data);\t\n\n\tif response.status_code == 200:\n\t\tdataResponse = response.json()\n\n\t\twith open(\"resultado/dataID/\"+str(uf)+\"/data_\"+str(data[\"id\"])+\".json\", \"w\") as out:\n\t\t json.dump(dataResponse, out)\n\n\t\treturn dataResponse\n\telse:\n\t\treturn None\n\ndef request(uf, id):\n\tif not os.path.isfile(\"resultado/dataID/\"+str(uf)+\"/data_\"+str(id)+\".json\"):\n\t\tsleep(0.5 + (random.random()/10))\n\t\tdata = {\"id\": id}\n\t\tres = getData(data)\n\n\t\tif res is not None:\n\t\t\tprint(\"Download \"+uf+\" - \"+str(id)+\" concluído.\")\n\t\telse:\n\t\t\tprint(\"Erro: Download \"+uf+\" - \"+str(id)+\".\")\n\t\n## SCRIPT\n\nwith open('requestDetalheCompletoTemplate.json') as requestFile: \n requestTemplate = json.load(requestFile)\n\nfor uf in ufs:\n\twith open(\"resultado/JSON/bnmp_mandados_\"+uf+\".json\") as dataFile: \n\t jsonMandados = json.load(dataFile)\n\n\tfor m in jsonMandados[\"mandados\"]:\n\t\trequest(uf, m[\"id\"])"
},
{
"alpha_fraction": 0.563503623008728,
"alphanum_fraction": 0.5708029270172119,
"avg_line_length": 21.850000381469727,
"blob_id": "82d7c819202cadb886e77830e1235376dbcf25ab",
"content_id": "41e88b75a95c818c4defdd8d2cd51503fc3bbb89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1370,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 60,
"path": "/checkAttributes.py",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "import json\nimport os \nfrom pprint import pprint\n\n\ni = 0\natributosGeral = set([])\natributosDetalhes = set([])\n\nufs = [\"PB\"]\n# ufs = [\"PB\", \"PE\", \"RN\"]\npiorCaso = dict();\n\nfor uf in ufs:\n\twhile os.path.isfile(\"resultado/\"+str(uf)+\"/bnmp_response\"+str(i+1)+\".json\"):\n\t\twith open(\"resultado/\"+str(uf)+\"/bnmp_response\"+str(i+1)+\".json\", \"r\") as dataFile: \n\t\t\tdata = json.load(dataFile)\n\n\t\t\tfor j in range(len(data[\"mandados\"])):\n\t\t\t\tatts = list(data[\"mandados\"][j].keys())\n\n\t\t\t\tatributosGeral |= set(atts)\n\n\t\t\t\tfor att in atts:\n\t\t\t\t\tattAtual = str(data[\"mandados\"][j][att])\n\n\t\t\t\t\tif att in piorCaso:\n\t\t\t\t\t\tif len(attAtual) > piorCaso[att]:\n\t\t\t\t\t\t\tpiorCaso[att] = len(attAtual)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpiorCaso[att] = len(attAtual)\n\n\t\t\t\t\t# if \"numeroMandado\" in piorCaso:\n\t\t\t\t\t# \tif piorCaso[\"numeroMandado\"] == 30:\n\t\t\t\t\t# \t\tpprint(data[\"mandados\"][j])\n\t\t\t\t\t# \t\texit()\n\n\t\t\t\tfor k in range(len(data[\"mandados\"][j][\"detalhes\"])):\n\t\t\t\t\tdetalhe = data[\"mandados\"][j][\"detalhes\"][k].split(\":\")\n\t\t\t\t\tatt = detalhe[0]\n\n\t\t\t\t\tatributosDetalhes |= set([att])\n\n\t\t\t\t\tif att in piorCaso:\n\t\t\t\t\t\tif len(detalhe[1]) > piorCaso[att]:\n\t\t\t\t\t\t\tpiorCaso[att] = len(detalhe[1])\n\t\t\t\t\telse:\n\t\t\t\t\t\tpiorCaso[att] = len(detalhe[1])\n\t\ti+=1\n\nprint(\"\\n\\n###################\")\npprint(piorCaso)\n\n\nprint(\"\\n\\n###################\")\npprint(atributosGeral)\n\n\nprint(\"\\n\\n###################\")\npprint(atributosDetalhes)"
},
{
"alpha_fraction": 0.5658436417579651,
"alphanum_fraction": 0.623971164226532,
"avg_line_length": 28.923076629638672,
"blob_id": "373d303c7df385e1de4e0ebad645b073ce1427bc",
"content_id": "e57f054cf27b9ed1f59169c8f1eb387cc17477e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1963,
"license_type": "no_license",
"max_line_length": 448,
"num_lines": 65,
"path": "/convert.py",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "import sys\nimport json\nimport os \nfrom pprint import pprint\nfrom dicttoxml import dicttoxml\n\ndataFile = \"\"\"{\n \"sucesso\": true,\n \"mensagem\": null,\n \"mandado\": {\n \"id\": 632242,\n \"situacao\": \"Aguardando Cumprimento\",\n \"numero\": \"5884-32.2013.8.15.0011.0003\",\n \"data\": \"29/04/2013\",\n \"validade\": \"27/10/2032\",\n \"processo\": \"5884-32.2013.8.15.0011\",\n \"classe\": \"Pedido de Prisão Temporária\",\n \"assuntos\": [\n \"Homicídio Simples\"\n ],\n \"procedimentos\": [\n \"Outro N°00058843220138150011\"\n ],\n \"magistrado\": \"ALBERTO QUARESMA\",\n \"orgao\": \"Tribunal de Justiça do Estado da Paraíba, 2° TRIBUNAL DO JURI\",\n \"municipio\": \"CAMPINA GRANDE\",\n \"nomes\": [\n \"FRANCISCO HENRIQUE DA SILVA\"\n ],\n \"alcunhas\": null,\n \"sexos\": [\n \"MASCULINO\"\n ],\n \"documentos\": null,\n \"genitores\": null,\n \"genitoras\": null,\n \"nacionalidades\": null,\n \"naturalidades\": null,\n \"datasNascimentos\": null,\n \"aspectosFisicos\": null,\n \"profissoes\": null,\n \"enderecos\": [\n \"Rua Maestro Vila Lobos N°: 43 Cidade: Campina Grande/PB \"\n ],\n \"dataDelito\": \"28/10/2012\",\n \"assuntoDelito\": \"\",\n \"motivo\": \"Preventiva\",\n \"prazo\": \"\",\n \"recaptura\": \"Não\",\n \"sintese\": \"DIANTE DO EXPOSTO, com base nos arts. 311 e 312 do CPP, e em hamonia com o parecer ministerial de fls. 49/51, por conveniencia da instrução criminal e para resguardar a aplicação da lei penal, DECRETO A PRISÃO PREVENTIVA de Leandro Santos da Silva, Francisco Henrique da Silva e Tiago Bezerra da Silva, qualificaddos nos autos, os quais deverão ser recolhidos ao Predsidio Regional do Serrtão, ficando a disposição deste Juízo. C. Grande, 18 de abril de 2013. Alberto Quaresma - Juiz de Direito.\",\n \"pena\": null,\n \"regime\": null,\n \"codigoCertidao\": null\n }\n}\"\"\"\n# fileName = sys.argv[1]\n\n# with open(fileName+\".json\", \"r\") as dataFile: \ndata = json.loads(dataFile)\n\n\nf = open(\"data02_1.xml\", 'w', encoding='utf8')\ndataXML = dicttoxml(data)\nprint(str(dataXML, 'utf-8'), file=f)\nf.close()"
},
{
"alpha_fraction": 0.6506110429763794,
"alphanum_fraction": 0.6592379808425903,
"avg_line_length": 28,
"blob_id": "ea49c4f43d54c14e5b8b3609c70b9da4a63bc643",
"content_id": "b26d7176717c1a274ca633f5db29f8613c0ffd7a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1391,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 48,
"path": "/convertToSingleJSON.py",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "import json\nimport os \nfrom pprint import pprint\nfrom dicttoxml import dicttoxml\n\nufs = [\"PB\", \"RN\", \"PE\"]\n\nfor uf in ufs:\n\ti=0\n\tjsonMandados = {\"mandados\": []}\n\tjsonMandadosDetalhes = {\"detalhes\": []}\n\n\tprint(\"Convertendo - \", uf, \"\\n\")\n\n\twhile os.path.isfile(\"resultado/RESPONSE/\"+str(uf)+\"/bnmp_response_\"+str(format(i+1, \"05d\"))+\".json\"):\n\t\twith open(\"resultado/RESPONSE/\"+str(uf)+\"/bnmp_response_\"+str(format(i+1, \"05d\"))+\".json\", \"r\") as dataFile: \n\t\t\tdata = json.load(dataFile)\n\n\t\t\tmandados = data[\"mandados\"]\n\t\t\tfor mandado in mandados:\n\t\t\t\tlistDetalhesElement = mandado.pop(\"detalhes\")\n\t\t\t\tmandadoElement = mandado\n\n\t\t\t\tjsonMandados[\"mandados\"].append(mandadoElement)\n\n\t\t\t\tdictDetalhesElement = dict()\n\t\t\t\tfor d in listDetalhesElement:\n\t\t\t\t\tdetalhes \t= d.split(\":\")\n\t\t\t\t\tatributo \t= detalhes[0].replace(\" \", \"\")\n\t\t\t\t\tvalue \t\t= detalhes[1]\n\n\t\t\t\t\tdictDetalhesElement[atributo] = value\n\n\t\t\t\tdictDetalhesElement[\"id\"] = mandadoElement[\"id\"]\n\t\t\t\tjsonMandadosDetalhes[\"detalhes\"].append(dictDetalhesElement)\n\t\ti+=1\n\n\tif jsonMandados != []:\n\t\tf = open(\"resultado/JSON/bnmp_mandados_\"+str(uf)+\".json\", 'w', encoding='utf8')\n\t\tprint(json.dumps(jsonMandados), file=f)\n\t\tf.close()\n\n\tif jsonMandadosDetalhes != []:\t\n\t\tf = open(\"resultado/JSON/bnmp_detalhes_\"+str(uf)+\".json\", 'w', encoding='utf8')\n\t\tprint(json.dumps(jsonMandadosDetalhes), file=f)\n\t\tf.close()\n\n\tprint(\"Finalizado\\n\\n\")"
},
{
"alpha_fraction": 0.7655172348022461,
"alphanum_fraction": 0.7655172348022461,
"avg_line_length": 17.25,
"blob_id": "a48a60912e584748c38312397c010a39fabdd385",
"content_id": "80c59df80cc700ea617fb24cf6debf267e70b4a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 145,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 8,
"path": "/README.md",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "# crawler-bnmp\n\nDiversos scripts para pegar e tratar os dados da base do BNMP/CNJ.\n\n## TODO\n\n* Documentar scripts\n* Consertar estrutura de pastas"
},
{
"alpha_fraction": 0.6776025295257568,
"alphanum_fraction": 0.6908517479896545,
"avg_line_length": 23.78125,
"blob_id": "c7cb226306d0ad09fc77d3ed8763e207e7d208c8",
"content_id": "05290f10bec92a9384da5bcdd438ea5bda3e526a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1586,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 64,
"path": "/getMandados.py",
"repo_name": "acba/crawler-bnmp",
"src_encoding": "UTF-8",
"text": "import requests\nfrom requests import Request\nimport json\nfrom pprint import pprint\nfrom time import sleep\nimport os \nimport random\n\nurlMandados = \"http://www.cnj.jus.br/bnmp/rest/pesquisar\"\nufs = [\"PB\", \"PE\", \"RN\"]\n\ndef firstRequest(data):\n\tfirstResponse = requestData(data)\n\tnumPaginas = firstResponse[\"paginador\"][\"totalPaginas\"]\n\treturn numPaginas\n\ndef requestData(data):\n\tresponse = requests.post(urlMandados, json=data);\t\n\n\tif response.status_code == 200:\n\t\tdataResponse = response.json()\n\t\tpg = dataResponse[\"paginador\"][\"paginaAtual\"]\n\n\t\twith open(\"resultado/RESPONSE/\"+str(uf)+\"/bnmp_response_\"+str(format(pg, \"05d\"))+\".json\", \"w\") as out:\n\t\t json.dump(dataResponse, out)\n\n\t\treturn dataResponse\n\telse:\n\t\treturn None\n\ndef requestUF(uf, dataTemplate, offset=0):\n\n\tdataTemplate[\"criterio\"][\"orgaoJulgador\"][\"uf\"] = uf\n\n\tnumPaginas = firstRequest(dataTemplate)\n\tfor r in range(1+offset, numPaginas+1):\n\t\tsleep(0.5 + (random.random()/10))\n\t\t\n\t\tdata = dataTemplate\n\t\tdata[\"paginador\"][\"paginaAtual\"] = r\n\t\trequestData(data)\n\n\t\tprint(\"Download (\"+str(r)+\"/\"+ str(numPaginas)+\"): \", format(100 * (r)/numPaginas, \".4f\"), \"% concluído.\")\n\ndef checkOffset(uf):\n\ti = 0;\n\twhile os.path.isfile(\"resultado/RESPONSE/\"+str(uf)+\"/bnmp_response_\"+str(format(i+1, \"05d\"))+\".json\"):\n\t\ti+=1\n\t\tprint(i)\n\n\treturn i\n\n\n## SCRIPT\n\nwith open('requestTemplate.json') as dataFile: \n dataTemplate = json.load(dataFile)\n\nfor uf in ufs:\n\toffset = checkOffset(uf)\n\tprint(\"Iniciando captura de \", uf, \"\\n\")\n\tprint(\"Iniciando em : \", offset)\n\trequestUF(uf, dataTemplate, offset)\n\tprint(\"Finalizado\\n\\n\")"
}
] | 6 |
ProdRyan/Devine-Tool | https://github.com/ProdRyan/Devine-Tool | 5f8bc15d621100713f8ee3f10429d8930197dcf6 | c96d5e28d32babfb6268ef57694349a11be32b14 | 6c7486cbe3c22e256577133f1283a081a54ee26f | refs/heads/main | 2023-06-08T14:58:32.533737 | 2021-07-08T13:33:40 | 2021-07-08T13:33:40 | 384,128,053 | 0 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.3577255308628082,
"alphanum_fraction": 0.36562585830688477,
"avg_line_length": 39.9775276184082,
"blob_id": "1c0ce0c09b5fdce34756b820ab2cd0672aef02ba",
"content_id": "c90affc6aa5b2d21da922afe9d9e08a010de8695",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 70651,
"license_type": "no_license",
"max_line_length": 302,
"num_lines": 1424,
"path": "/Devine-Tool.py",
"repo_name": "ProdRyan/Devine-Tool",
"src_encoding": "UTF-8",
"text": "################################################################\n# #\n# [ Creditos ] #\n# #\n################################################################\n# #\n# Codigo hecho por xNetting # \n# #\n# Dev: xNetting / Grupo: Panic Squad #\n# #\n################################################################\n\n# Dev: xNetting / xFullCode\n# PanicSquad\n# Version - 1.0.0\n\nfrom dns.tsig import _digest\nimport nmap\nimport requests\nimport socket\nimport dns.resolver\nfrom urllib import request\nimport re\nimport hashlib\nimport string\nimport json\nfrom itertools import product\nfrom colorama import *\nimport time\nimport ctypes\nimport os\nimport sys\n\nos.system('cls || clear')\nprint(f'''\n\n{Fore.LIGHTCYAN_EX} ┌──────────────────────────────────────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │ \n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ██████╗░{Fore.LIGHTGREEN_EX}███████╗{Fore.LIGHTRED_EX}██╗░░░██╗{Fore.LIGHTGREEN_EX}██╗{Fore.LIGHTCYAN_EX}███╗░░██╗{Fore.LIGHTRED_EX}███████╗ {Fore.LIGHTGREEN_EX}████████╗{Fore.LIGHTRED_EX}░█████╗░░█████╗░{Fore.LIGHTGREEN_EX}██╗░░░░░ {Fore.LIGHTCYAN_EX}│ \n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ██╔══██╗{Fore.LIGHTGREEN_EX}██╔════╝{Fore.LIGHTRED_EX}██║░░░██║{Fore.LIGHTGREEN_EX}██║{Fore.LIGHTCYAN_EX}████╗░██║{Fore.LIGHTRED_EX}██╔════╝ {Fore.LIGHTGREEN_EX}╚══██╔══╝{Fore.LIGHTRED_EX}██╔══██╗██╔══██╗{Fore.LIGHTGREEN_EX}██║░░░░░ {Fore.LIGHTCYAN_EX}│\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ██║░░██║{Fore.LIGHTGREEN_EX}█████╗░░{Fore.LIGHTRED_EX}╚██╗░██╔╝{Fore.LIGHTGREEN_EX}██║{Fore.LIGHTCYAN_EX}██╔██╗██║{Fore.LIGHTRED_EX}█████╗░░ {Fore.LIGHTGREEN_EX}░░░██║░░░{Fore.LIGHTRED_EX}██║░░██║██║░░██║{Fore.LIGHTGREEN_EX}██║░░░░░ {Fore.LIGHTCYAN_EX}│\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ██║░░██║{Fore.LIGHTGREEN_EX}██╔══╝░░{Fore.LIGHTRED_EX}░╚████╔╝░{Fore.LIGHTGREEN_EX}██║{Fore.LIGHTCYAN_EX}██║╚████║{Fore.LIGHTRED_EX}██╔══╝░░ {Fore.LIGHTGREEN_EX}░░░██║░░░{Fore.LIGHTRED_EX}██║░░██║██║░░██║{Fore.LIGHTGREEN_EX}██║░░░░░ {Fore.LIGHTCYAN_EX}│\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ██████╔╝{Fore.LIGHTGREEN_EX}███████╗{Fore.LIGHTRED_EX}░░╚██╔╝░░{Fore.LIGHTGREEN_EX}██║{Fore.LIGHTCYAN_EX}██║░╚███║{Fore.LIGHTRED_EX}███████╗ {Fore.LIGHTGREEN_EX}░░░██║░░░{Fore.LIGHTRED_EX}╚█████╔╝╚█████╔╝{Fore.LIGHTGREEN_EX}███████╗ {Fore.LIGHTCYAN_EX}│\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} ╚═════╝░{Fore.LIGHTGREEN_EX}╚══════╝{Fore.LIGHTRED_EX}░░░╚═╝░░░{Fore.LIGHTGREEN_EX}╚═╝{Fore.LIGHTCYAN_EX}╚═╝░░╚══╝{Fore.LIGHTRED_EX}╚══════╝ {Fore.LIGHTGREEN_EX}░░░╚═╝░░░{Fore.LIGHTRED_EX}░╚════╝░░╚════╝░{Fore.LIGHTGREEN_EX}╚══════╝ {Fore.LIGHTCYAN_EX}│\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Dev:{Fore.LIGHTGREEN_EX} xNetting / {Fore.LIGHTWHITE_EX}Grupo: {Fore.LIGHTGREEN_EX}Panic Squad {Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └──────────────────────────────────────────────────────────────────────────────────────┘ \n\n ''')\n\ndef searchGoogle(requete='', requete2=''):\n\n\tencodeDic = {\n\t\t\"%21\": \"!\",\n\t\t\"%23\": \"#\",\n\t\t\"%24\": \"$\",\n\t\t\"%26\": \"&\",\n\t\t\"%27\": \"'\",\n\t\t\"%28\": \"(\",\n\t\t\"%29\": \")\",\n\t\t\"%2A\": \"*\",\n\t\t\"%2B\": \"+\",\n\t\t\"%2C\": \",\",\n\t\t\"%2F\": \"/\",\n\t\t\"%3A\": \":\",\n\t\t\"%3B\": \";\",\n\t\t\"%3D\": \"=\",\n\t\t\"%3F\": \"?\",\n\t\t\"%40\": \"@\",\n\t\t\"%5B\": \"[\",\n\t\t\"%5D\": \"]\", \n\t\t\"%20\": \" \",\n\t\t\"%22\": \"\\\"\",\n\t\t\"%25\": \"%\",\n\t\t\"%2D\": \"-\",\n\t\t\"%2E\": \".\",\n\t\t\"%3C\": \"<\",\n\t\t\"%3E\": \">\",\n\t\t\"%5C\": \"\\\\\",\n\t\t\"%5E\": \"^\",\n\t\t\"%5F\": \"_\",\n\t\t\"%60\": \"`\",\n\t\t\"%7B\": \"{\",\n\t\t\"%7C\": \"|\",\n\t\t\"%7D\": \"}\",\n\t\t\"%7E\": \"~\",\n\t}\n\n\tif requete2 != '':\n\t\tcontent = requete2.text\n\t\turls = re.findall('url\\\\?q=(.*?)&', content)\n\t\tfor url in urls:\n\t\t\tfor char in encodeDic:\n\t\t\t\tfind = re.search(char, url)\n\t\t\t\tif find:\n\t\t\t\t\tcharDecode = encodeDic.get(char)\n\t\t\t\t\turl = url.replace(char, charDecode)\n\t\t\tif not \"googleusercontent\" in url:\n\t\t\t\tif not \"/settings/ads\" in url:\n\t\t\t\t\tif not \"/policies/faq\" in url:\n\t\t\t\t\t\tprint(str(f\"\"\"\n \n {Fore.LIGHTCYAN_EX}[ + ] Posible conexion : {Fore.LIGHTWHITE_EX}{url}\"\"\"))\n\telse:\n\t\tpass\n\n\tcontent = requete.text\n\turls = re.findall('url\\\\?q=(.*?)&', content)\n\tfor url in urls:\n\t\tfor char in encodeDic:\n\t\t\tfind = re.search(char, url)\n\t\t\tif find:\n\t\t\t\tcharDecode = encodeDic.get(char)\n\t\t\t\turl = url.replace(char, charDecode)\n\t\tif not \"googleusercontent\" in url:\n\t\t\tif not \"/settings/ads\" in url:\n\t\t\t\tif not \"/policies/faq\" in url:\n\t\t\t\t\tprint(str(f\"\"\"\n \n {Fore.LIGHTCYAN_EX}[ + ] Posible conexion : {Fore.LIGHTWHITE_EX}{url}\"\"\"))\n\ndef google():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}Ingrese el nombre{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n nombre = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Buscando informacion de : {Fore.LIGHTWHITE_EX}{nombre}'''))\n \n url = \"https://www.google.com/search?num=20&q=\\\\%s\\\\\"\n try:\n lista = \"\"\n nom2 = nombre.split()\n if len(nom2) == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}Faltan argumentos''')\n return\n longi = str(nom2[-1])\n for argumento in nom2:\n if argumento == longi:\n lista += str(argumento)\n continue\n lista += str(argumento) + \"+\"\n except:\n pass\n requete = requests.get(url % (lista))\n searchGoogle(requete=requete)\n\n\ndef searchUserName():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.MAGENTA}Ingrese el Nick{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n \n name = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Buscando informacion de : {Fore.LIGHTWHITE_EX}{name}'''))\n url = \"https://www.google.com/search?num=100&q=\\\\%s\\\\\"\n url2 = \"https://www.google.com/search?num=100&q=\\\\intitle:\\\"%s\\\"\\\\\"\n requete = requests.get(url % (name))\n requete2 = requests.get(url2 % (name))\n searchGoogle(requete=requete, requete2=requete2)\n\ndef deleterequest(url):\n\theaders = {\"Content-Type\":\"application/json\",\"User-Agent\":\"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11\"}\n\treq = request.Request(url,headers=headers,method=\"DELETE\")\n\trequest.urlopen(req)\n\ndef nmapscan():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}Ponga la IP que desea escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_2 = str(input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}'''))\n\n nm = nmap.PortScanner()\n results = nm.scan(hosts=target_2, arguments='-sT -n -Pn -T4')\n open_ports = '-p '\n\n num = 0\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] Host : {Fore.LIGHTWHITE_EX}%s''' % target_2)\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] Estado : {Fore.LIGHTWHITE_EX}%s''' % nm[target_2].state())\n\n for protocolo in nm[target_2].all_protocols():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Protocolo : {Fore.LIGHTWHITE_EX}%s''' % protocolo)\n puerto = nm[target_2][protocolo].keys()\n sorted(puerto)\n\n for port in puerto:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Puerto : {Fore.LIGHTWHITE_EX}%s, {Fore.LIGHTCYAN_EX}[ + ] Estado : {Fore.LIGHTWHITE_EX}%s''' % (port, nm[target_2][protocolo][port]['state']))\n if num == 0:\n open_ports = open_ports+str(port)\n num = 1\n else:\n open_ports = open_ports+\", \"+str(port)\n\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Puertos abiertos : {Fore.LIGHTWHITE_EX}{open_ports} en {target_2}''') \n\ndef scan5():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTRED_EX}Ingrese la url que quiere escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_7 = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n obj = requests.get(url=target_7)\n ca = dict(obj.headers)\n for x in ca:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{x} {ca[x]}''')\n \n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro informacion ''')\n\ndef dnsscan4():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}Ingrese el dominio que quiere escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_6 = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n scan = dns.resolver.resolve(target_6, 'MX')\n for a in scan:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{a}''')\n\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro informacion ''')\n\ndef dnsscan3():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTRED_EX}Ingrese el dominio que quiere escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_5 = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n scan = dns.resolver.resolve(target_5, 'SOA')\n for a in scan:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{a}''')\n\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro informacion ''')\n\ndef dnsscan2():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTWHITE_EX}Ingrese el dominio que quiere escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_4 = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n scan = dns.resolver.resolve(target_4, 'NS')\n for a in scan:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{a}''')\n \n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro informacion ''')\n\ndef dnsscan1():\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}Ingrese el dominio que quiere escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n target_3 = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n scan = dns.resolver.resolve(target_3, 'A')\n for a in scan:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{a}''')\n\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro informacion ''') \n\ndef otrosscan():\n print(f'''\n\n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTWHITE_EX}Eliga su tipo de scan{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}1 - Direccion Host{Fore.LIGHTCYAN_EX} │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTRED_EX}2 - Obtener DNS{Fore.LIGHTCYAN_EX} │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTCYAN_EX}3 - Informacion DNS de la zona{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}4 - Informacion de Intercambio{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTRED_EX}5 - All Info{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n\n ''')\n\n opcion = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opcion == '1':\n dnsscan1()\n elif opcion == '2':\n dnsscan2()\n elif opcion == '3':\n dnsscan3()\n elif opcion == '4':\n dnsscan4()\n elif opcion == '5':\n scan5()\n else:\n sys.exit()\n\ndef portscan():\n open_ports = []\n port_min = 0\n port_max = 65535\n patrones_puertos = re.compile(\"([0-9]+)-([0-9]+)\")\n\n while True:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTGREEN_EX}Ponga la IP que desea escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n \n ''')\n\n target_1 = str(input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}'''))\n break\n\n while True:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}┌─────────────────────────────────────────────────────┐\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ {Fore.LIGHTRED_EX}Ponga el rango de Puertos para escanear{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}│ │\n {Fore.LIGHTCYAN_EX}└─────────────────────────────────────────────────────┘\n \n ''')\n\n port_1 = str(input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}'''))\n\n port_validacion = patrones_puertos.search(port_1.replace(\" \",\"\"))\n if port_validacion:\n port_min = int(port_validacion.group(1))\n port_max = int(port_validacion.group(2))\n break\n\n for port in range(port_min, port_max + 1):\n try:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as scan:\n scan.settimeout(0.5)\n scan.connect((target_1, port))\n open_ports.append(port)\n except:\n pass\n for port in open_ports:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}El puerto {port} esta abierto en {target_1}''')\n\ndef scanning():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Eliga el tipo de scan que quiere realizar{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.MAGENTA} 1 - Port Scan{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX} 2 - Nmap Scan{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTCYAN_EX} 3 - Otros Scans{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n op_scan = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if op_scan == '1':\n portscan()\n elif op_scan == '2':\n nmapscan()\n elif op_scan == '3':\n otrosscan()\n else:\n sys.exit() \n\ndef wordlistgen():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}Ingrese el minimo de letras de las contraseñas{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n min_let = int(input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}'''))\n\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Ingrese el maximo de letras de las contraseñas{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n \n ''')\n\n max_let = int(input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}'''))\n\n contador = 0\n\n caracter = string.ascii_lowercase+string.ascii_uppercase+string.digits+string.punctuation\n\n archivo = open('wordlist.txt', 'w')\n\n for i in range(min_let, max_let+1):\n for j in product(caracter, repeat=i):\n let = ''.join(j) \n archivo.write(let)\n archivo.write('\\n')\n contador += 1\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}WordList ha sido creado, genero {contador} contraseñas''') \n\ndef decode_sha1():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Ingrese el hash en SHA1{Fore.LIGHTCYAN_EX} │ \n {Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha1_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha1_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(sha1_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.sha1(le.strip()).hexdigest()\n\n if d == sha1_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\ndef decode_sha256():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Ingrese el hash en SHA256{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha256_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha256_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(sha256_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.sha256(le.strip()).hexdigest()\n\n if d == sha256_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\ndef decode_sha224():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Ingrese el hash en SHA224{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha224_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha224_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(sha224_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.sha224(le.strip()).hexdigest()\n\n if d == sha224_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\ndef decode_sha3_256():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Ingrese el hash en SHA3_256{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha3_256_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha3_256_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(sha3_256_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.sha3_256(le.strip()).hexdigest()\n\n if d == sha3_256_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\ndef decode_blakeb2():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Ingrese el hash en blake 2b{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n blakeb2_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n blakeb2_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(blakeb2_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.blake2b(le.strip()).hexdigest()\n\n if d == blakeb2_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\ndef decode_md5():\n f = 0\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Ingrese el hash en MD5{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n md5_hash = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Escriba la wordlist (.txt){Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n md5_wordlist = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n try:\n archivo = open(md5_wordlist, 'r')\n except:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n for l in archivo:\n le = l.encode('utf-8')\n d = hashlib.md5(le.strip()).hexdigest()\n\n if d == md5_hash:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Hash : {Fore.LIGHTWHITE_EX}{l}''')\n f = 1\n\n if f == 0:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] : {Fore.LIGHTWHITE_EX}No se encontro la wordlist ''')\n\n\ndef encode_sha3_256():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Escriba el texto que quiere encriptar en SHA3_256{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha3_256_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.sha3_256(sha3_256_encrypted.encode('utf-8')).hexdigest())\n\ndef encode_blake2b():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Escriba el texto que quiere encriptar en blake2b{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n blake2b_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.blake2b(blake2b_encrypted.encode('utf-8')).hexdigest())\n\ndef algoritmos():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Aqui tiene la lista de algoritmos{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX}{hashlib.algorithms_available}''')\n\ndef encode_sha224():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Escriba el texto que quiere encriptar en SHA224{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha224_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.sha224(sha224_encrypted.encode('utf-8')).hexdigest())\n\ndef encode_sha256():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Escriba el texto que quiere encriptar en SHA265{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha256_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.sha256(sha256_encrypted.encode('utf-8')).hexdigest())\n\ndef encode_sha1():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}Escriba el texto que quiere encriptar en SHA1{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n sha1_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.sha1(sha1_encrypted.encode('utf-8')).hexdigest())\n\n\ndef encode_md5():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Escriba el texto que quiere encriptar en MD5{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n md5_encrypted = input(f'''\n\n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n\n {Fore.LIGHTCYAN_EX}[ + ] : {Fore.LIGHTWHITE_EX} ''' + hashlib.md5(md5_encrypted.encode('utf-8')).hexdigest())\n\ndef tans():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Eliga el metodo que quiere{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} 1 - Encrypt{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}2 - Decrypt{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} 3 - Generar diccionario{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opcion = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''') \n\n if opcion == '1':\n encrypt()\n elif opcion == '2':\n decrypt()\n elif opcion == '3':\n wordlistgen()\n else:\n sys.exit()\n\ndef decrypt():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Eliga el metodo que quiere para su desencriptacion{Fore.LIGHTCYAN_EX}│ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}1 - MD5{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} 2 - SHA1{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}3 - SHA256{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} 4 - SHA224{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}5 - blake2b{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} 6 - SHA3_256{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opcion = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opcion == '1':\n decode_md5()\n elif opcion == '2':\n decode_sha1()\n elif opcion == '3':\n decode_sha256()\n elif opcion == '4':\n decode_sha224()\n elif opcion == '5':\n decode_blakeb2()\n elif opcion == '6':\n decode_sha3_256()\n else:\n sys.exit()\n\ndef encrypt():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} Eliga el metodo que quiere para su encriptacion{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}1 - MD5{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX} 2 - SHA1{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} 3 - SHA256{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} 4 - SHA224{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} 5 - blake2b{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}6 - SHA3_256{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX} 10 - Todos los Algoritmos{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opcion = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opcion == '1':\n encode_md5()\n elif opcion == '2':\n encode_sha1()\n elif opcion == '3':\n encode_sha256()\n elif opcion == '4':\n encode_sha224()\n elif opcion == '5':\n encode_blake2b()\n elif opcion == '6':\n encode_sha3_256()\n elif opcion == '10':\n algoritmos()\n else:\n sys.exit()\n\ndef webhook():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Ingrese la URL de su webhook{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n webhookurl = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX} Ingrese el nombre para su webhook{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n webhooknombre = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX} Ingrese el contenido de su webhook {Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n webhookcontenido = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n data = {\n \"content\" : webhookcontenido,\n \"username\" : webhooknombre\n }\n\n def send(i):\n res = requests.post(webhookurl, data=data)\n try:\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] Tiempo en rehabilitacion, espere :{Fore.LIGHTWHITE_EX} {str(res.json()[\"retry_after\"])} ms''')\n \n time.sleep(res.json()[\"retry_after\"]/1000)\n res = f'''\n \n {Fore.LIGHTCYAN_EX}[ ! ] Espere : {str(res.json()[\"retry_after\"])} ms'''\n except:\n i += 1\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Cantidad de mensajes enviados :{Fore.LIGHTWHITE_EX} {str(i)}''')\n return i\n i = 0\n while True:\n i = send(i)\n\ndef discord():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Eliga el tipo de mensaje webhook que quiere{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}1 - Spammer{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opciones = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opciones == '1':\n webhook()\n else:\n sys.exit()\n\ndef ddos():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Eliga su tipo de DDoS{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}1 - DDoS Thread {Fore.LIGHTCYAN_EX}[{Fore.LIGHTWHITE_EX} PREMIUM{Fore.LIGHTCYAN_EX} ]{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.MAGENTA}2 - DDoS Proxies {Fore.LIGHTCYAN_EX}[{Fore.LIGHTWHITE_EX} PREMIUM{Fore.LIGHTCYAN_EX} ]{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opciones = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opciones == '1':\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ X ] : {Fore.RED}Al parecer tu no has comprado la Devine Tool Premium{Fore.LIGHTWHITE_EX}''')\n elif opciones == '2':\n print(f'''\n \n {Fore.LIGHTCYAN_EX}[ X ] : {Fore.RED}Al parecer tu no has comprado la Devine Tool Premium{Fore.LIGHTWHITE_EX}''')\n else:\n sys.exit()\n\ndef ipinfo():\n print(f'''\n \n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}Ingrese el IP{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n aipi = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n url = (\"http://ip-api.com/json/\")\n response = requests.get(url + aipi)\n data = response.text\n jso = json.loads(data)\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] IP : {Fore.LIGHTWHITE_EX}{aipi}'''))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] ISP : {Fore.LIGHTWHITE_EX}'''+(jso[\"isp\"])))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Pais : {Fore.LIGHTWHITE_EX}'''+(jso[\"country\"])))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] TimeZone : {Fore.LIGHTWHITE_EX}'''+(jso[\"timezone\"])))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Region : {Fore.LIGHTWHITE_EX}'''+(jso[\"regionName\"])))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Zip : {Fore.LIGHTWHITE_EX}'''+(jso[\"zip\"])))\n print(str(f'''\n \n {Fore.LIGHTCYAN_EX}[ + ] Cuidad : {Fore.LIGHTWHITE_EX}'''+(jso[\"city\"])))\n\ndef doxing():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Eliga su tipo de Dox{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTRED_EX}1 - Redes{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX}2 - Nick{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}3 - IP Info{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n \n opciones = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opciones == '1':\n searchUserName()\n elif opciones == '2':\n google()\n elif opciones == '3':\n ipinfo()\n else:\n sys.exit()\n\ndef main():\n print(f'''\n\n{Fore.LIGHTCYAN_EX} ┌─────────────────────────────────────────────────────┐\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX}Eliga la herramienta que quiere usar{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTGREEN_EX} 1 - Scanning{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTWHITE_EX} 2 - Encrypt & Decrypt{Fore.LIGHTCYAN_EX} │ \n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.YELLOW} 3 - Discord{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.LIGHTCYAN_EX} 4 - DDoS & DoS{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ {Fore.MAGENTA} 5 - Doxing{Fore.LIGHTCYAN_EX} │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} │ │\n{Fore.LIGHTCYAN_EX} └─────────────────────────────────────────────────────┘\n\n ''')\n\n opciones = input(f'''\n \n {Fore.LIGHTCYAN_EX}[ ? ] : {Fore.LIGHTWHITE_EX}''')\n\n if opciones == '1':\n scanning()\n elif opciones == '2':\n tans()\n elif opciones == '3':\n discord()\n elif opciones == '4':\n ddos()\n elif opciones == '5':\n doxing()\n else:\n sys.exit()\n\nmain()\n"
},
{
"alpha_fraction": 0.7206623554229736,
"alphanum_fraction": 0.7624189853668213,
"avg_line_length": 31.302326202392578,
"blob_id": "7d864f0c84e9fce108c7d28634e41b6b5f60a64a",
"content_id": "85c956a9560857c497293e0174d5dde7e68f39e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1402,
"license_type": "no_license",
"max_line_length": 296,
"num_lines": 43,
"path": "/README.md",
"repo_name": "ProdRyan/Devine-Tool",
"src_encoding": "UTF-8",
"text": "# 💥 - Devine-Tool\n\nEsta herramienta te ayudara en muchas tareas de hacking - xNetting\n\n# ♟ - Uso \n\n```\n\ngit clone https://github.com/xNetting/Devine-Tool\n\ncd Devine-Tool\n\npip install -r requirements.txt\n\npython3 Devine-Tool.py\n\n```\n\n\n# ⚡ - Funciones\n\nDevine Tool proporciona varias funciones y con ella mas funciones, como esta es una version de uso libre por eso he limitado varias funciones como DDoS & otras que sesupone que esta Tool deberia tener, pero sin mas que decirles les dejo la descripcion de las funciones de esta Herramienta Divina.\n\n- Scanning\n\n3 Tipos de Scan, Port Scan basico, Nmap Scan & otros Scans como Scan de DNS.\n- Encrypt & Decrypt\n\n3 Funciones, generar diccionarios para ataques de fuerza bruta, encriptar datos con utf-8 & desencriptar hashes con wordlist (no incluye wordlist & si generas te recomiendo no excederte con generar con mas de 3 digitos [ PELIGROSO ]).\n- Discord \n\nUna Funcion para spamear algun server atravez de webhooks.\n- Doxing\n\n3 Funciones, saber informacion de alguna IP, Buscar redes de algun nick o de algun nombre.\n\n# ☘ - Imagenes\n\n\n\n# 🛎 - ¿Fallas, Sugerencias o Ayuda?\n\nConctactame en Whatsapp como +1 (561) 421-3457 o en Discord como Netting#2021 || Fundador de [Panic Squad](https://discord.gg/b2WDdTnGbA) & Miembro de Xanax Squad\n"
},
{
"alpha_fraction": 0.4939759075641632,
"alphanum_fraction": 0.6867470145225525,
"avg_line_length": 15.600000381469727,
"blob_id": "c7b2da57bf26a6e8bee4a67ac0be6f2b464dd96e",
"content_id": "2624faace408c7931764ae8295a9d89640dc402d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 83,
"license_type": "no_license",
"max_line_length": 18,
"num_lines": 5,
"path": "/requirements.txt",
"repo_name": "ProdRyan/Devine-Tool",
"src_encoding": "UTF-8",
"text": "python-nmap==0.6.4\nrequests==2.25.1\ncolorama==0.4.4\ndigest==1.0.2\ndnspython==2.1.0\n"
}
] | 3 |
jplock/tweet_purge | https://github.com/jplock/tweet_purge | 95d22eced8760049689c331a954608ab5fddde27 | 2db59dfd33556f019b6635e39414b5221364e907 | ca050cea89836d0db06f67763a7a09a900b0cd74 | refs/heads/master | 2021-09-03T14:57:14.088435 | 2018-01-10T00:13:05 | 2018-01-10T00:13:05 | 115,932,126 | 3 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5647368431091309,
"alphanum_fraction": 0.5989473462104797,
"avg_line_length": 25.760562896728516,
"blob_id": "a97e27acabffa2676fcbe2476c1dcdf53371b5af",
"content_id": "20367244b59866c5e3e32d3b024b05b853a7f5ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1900,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 71,
"path": "/tweet_purge.py",
"repo_name": "jplock/tweet_purge",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport csv\nfrom datetime import datetime, timedelta\nimport twitter\n\nimport config\n\nfields = [\n 'tweet_id',\n 'in_reply_to_status_id',\n 'in_reply_to_user_id',\n 'timestamp',\n 'source',\n 'text',\n 'retweeted_status_id',\n 'retweeted_status_user_id',\n 'retweeted_status_timestamp',\n 'expanded_urls'\n]\n\napi = twitter.Api(\n consumer_key=config.CONSUMER_KEY,\n consumer_secret=config.CONSUMER_SECRET,\n access_token_key=config.ACCESS_TOKEN_KEY,\n access_token_secret=config.ACCESS_TOKEN_SECRET,\n sleep_on_rate_limit=True\n)\n\nnow = datetime.utcnow()\nprint 'NOW: {}'.format(now)\n\ndelta = timedelta(days=30)\noldest = now - delta\nprint 'OLDEST: {}'.format(oldest)\n\nKEEP_TWEET_IDS = [\n '814131260784312325', # keybase verification\n '947874760096063488', # announcing tweet_purge\n '947890779468500993', # final tweet\n]\n\nwith open('tweets.csv', 'r') as csvfile:\n header = False\n reader = csv.DictReader(csvfile, fieldnames=fields)\n for row in reader:\n if not header:\n header = True\n continue\n\n timestamp = datetime.strptime(\n row['timestamp'][0:19], '%Y-%m-%d %H:%M:%S')\n delete = timestamp < oldest\n\n if row['tweet_id'] in KEEP_TWEET_IDS:\n print 'Not deleting tweet {} (skipped)'.format(row['tweet_id'])\n continue\n\n if not delete:\n print 'Not deleting tweet {} created on {}'.format(\n row['tweet_id'], timestamp)\n continue\n\n try:\n status = api.DestroyStatus(row['tweet_id'])\n print 'Deleted {} created on {}'.format(\n status.id, status.created_at)\n except twitter.error.TwitterError as ex:\n errors = ex.message\n if len(errors) and errors[0].get('code', 0) != 144:\n print 'ERROR: {}'.format(errors[0].get('message'))\n"
},
{
"alpha_fraction": 0.6499999761581421,
"alphanum_fraction": 0.75,
"avg_line_length": 19,
"blob_id": "e6ed045c9b77a03b572812dbf727f12d262ceab1",
"content_id": "f8b90fc3f5032c53c8fbeaf0bf12eedef98afc4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 20,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 1,
"path": "/requirements.txt",
"repo_name": "jplock/tweet_purge",
"src_encoding": "UTF-8",
"text": "python-twitter==3.3\n"
},
{
"alpha_fraction": 0.7312661409378052,
"alphanum_fraction": 0.7338501214981079,
"avg_line_length": 19.91891860961914,
"blob_id": "e76f070feabf02ebb53ef4ded65006785af9db19",
"content_id": "4bcbd910482023a3f5103556da2003a36c154a95",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 774,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 37,
"path": "/README.md",
"repo_name": "jplock/tweet_purge",
"src_encoding": "UTF-8",
"text": "Usage\n=====\n\nRequest your Twitter archive at https://twitter.com/settings/your_twitter_data. Extract the archive and checkout these files into the archive directory.\n\n```\ncd <extracted archive>\ngit clone https://github.com/jplock/tweet_purge.git\nvirtualenv venv\nsource venv/bin/activate\npip install -r requirements.txt\n```\n\nCreate a new application on https://apps.twitter.com to get your Consumer Key, Consumer Secret, and generate an Access Token Key and Access Token Secret.\n\nCreate config.py\n\n```\n#!/usr/bin/env python\n\nCONSUMER_KEY = ''\nCONSUMER_SECRET = ''\nACCESS_TOKEN_KEY = ''\nACCESS_TOKEN_SECRET = ''\n```\n\nAdjust the number of days of tweets to delete in `tweet_purge.py`\n\n```\ndelta = timedelta(days=30)\n```\n\nThen execute the script:\n\n```\npython tweet_purge.py\n```\n"
}
] | 3 |
Anarchid/uberserver | https://github.com/Anarchid/uberserver | db6f050d324a1215b873d3fdd1499e346921f57e | 312b69e379e8999c440f1dd6e5c0b00a9932e7b1 | ad0d3787ef31dbb6e2d8645bba276fe550ddb67f | refs/heads/master | 2021-01-15T14:42:19.517723 | 2015-02-09T13:55:14 | 2015-02-09T13:55:14 | 25,297,934 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.703377366065979,
"alphanum_fraction": 0.7084119915962219,
"avg_line_length": 24.907608032226562,
"blob_id": "cf5089ae05ba1d1e4ec9cf7e34b73cc48d5b6c15",
"content_id": "0bb4e071b198427f0d78f4379228343b8bf3b84f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4767,
"license_type": "permissive",
"max_line_length": 107,
"num_lines": 184,
"path": "/server.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding=utf-8\n\ntry:\n\timport thread\nexcept:\n\t# thread was renamed to _thread in python 3\n\timport _thread\n\nimport traceback, signal, socket, sys\n\ntry:\n\tfrom urllib2 import urlopen\nexcept:\n\t# The urllib2 module has been split across several modules in Python 3.0\n\tfrom urllib.request import urlopen\n\nsys.path.append(\"protocol\")\nsys.path.append(\".\")\n\nfrom DataHandler import DataHandler\nfrom Client import Client\nfrom NATServer import NATServer\nfrom Dispatcher import Dispatcher\nfrom XmlRpcServer import XmlRpcServer\n\nimport ip2country # just to make sure it's downloaded\nimport ChanServ\n\n# uncomment for debugging deadlocks, creates a stacktrace at the given interval to stdout\n#import stacktracer\n#stacktracer.trace_start(\"trace.html\",interval=5,auto=True) # Set auto flag to always update file!\n\n\n_root = DataHandler()\n_root.parseArgv(sys.argv)\n\ntry:\n\tsignal.SIGHUP\n\t\n\tdef sighup(sig, frame):\n\t\t_root.console_write('Received SIGHUP.')\n\t\tif _root.sighup:\n\t\t\t_root.reload()\n\n\tsignal.signal(signal.SIGHUP, sighup)\nexcept AttributeError:\n\tpass\n\n_root.console_write('-'*40)\n_root.console_write('Starting uberserver...\\n')\n\nhost = ''\nport = _root.port\nnatport = _root.natport\nbacklog = 100\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,\n\t\t\t\tserver.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 )\n\t\t\t\t# fixes TIME_WAIT :D\nserver.bind((host,port))\nserver.listen(backlog)\n\ntry:\n\tnatserver = NATServer(natport)\n\ttry:\n\t\tthread.start_new_thread(natserver.start,())\n\texcept NameError:\n\t\t_thread.start_new_thread(natserver.start,())\n\tnatserver.bind(_root)\nexcept socket.error:\n\tprint('Error: Could not start NAT server - hole punching will be unavailable.')\n\n_root.console_write()\n_root.console_write('Detecting local IP:')\ntry: local_addr = socket.gethostbyname(socket.gethostname())\nexcept: local_addr = '127.0.0.1'\n_root.console_write(local_addr)\n\n_root.console_write('Detecting online IP:')\ntry:\n\ttimeout = socket.getdefaulttimeout()\n\tsocket.setdefaulttimeout(5)\n\tweb_addr = urlopen('http://springrts.com/lobby/getip.php').read()\n\tsocket.setdefaulttimeout(timeout)\n\t_root.console_write(web_addr)\nexcept:\n\tweb_addr = local_addr\n\t_root.console_write('not online')\n_root.console_write()\n\n_root.local_ip = local_addr\n_root.online_ip = web_addr\n\n_root.console_write('Using %i client handling thread(s).'%_root.max_threads)\n\ndispatcher = Dispatcher(_root, server)\n_root.dispatcher = dispatcher\n\nchanserv = True\nif chanserv:\n\taddress = ((web_addr or local_addr), 0)\n\tchanserv = ChanServ.ChanServClient(_root, address, _root.session_id)\n\tdispatcher.addClient(chanserv)\n\t_root.chanserv = chanserv\n\ntry:\n\txmlrpcserver = XmlRpcServer(_root, _root.xmlhost, _root.xmlport)\n\ttry:\n\t\tthread.start_new_thread(xmlrpcserver.start,())\n\texcept NameError:\n\t\t_thread.start_new_thread(xmlrpcserver.start,())\n\t_root.console_write('Listening for XMLRPC clients on %s:%d' % (_root.xmlhost, _root.xmlport))\nexcept socket.error:\n\tprint('Error: Could not start XmlRpcServer.')\n\ntry:\n\tdispatcher.pump()\nexcept KeyboardInterrupt:\n\t_root.console_write()\n\t_root.console_write('Server killed by keyboard interrupt.')\nexcept:\n\t_root.error(traceback.format_exc())\n\t_root.console_write('Deep error, exiting...')\n\t_root.console_print_step() # try to flush output buffer to log file\n\n# _root.console_write('Killing handlers.')\n# for handler in _root.clienthandlers:\n# \thandler.running = False\n_root.console_write('Killing clients.')\nfor client in dict(_root.clients):\n\ttry:\n\t\tconn = _root.clients[client].conn\n\t\tif conn: conn.close()\n\texcept: pass # for good measure\nserver.close()\n\n_root.running = False\n_root.console_print_step()\n\nmemdebug = False\nif memdebug:\n\trecursion = []\n\tnames = {}\n\t\n\tdef dump(obj, tabs=''):\n\t\tif obj in recursion: return str(obj)\n\t\telse: recursion.append(obj)\n\t\ttry:\n\t\t\tif type(obj) == (list, set):\n\t\t\t\treturn [dump(var) for var in obj]\n\t\t\telif type(obj) in (str, unicode, int, float):\n\t\t\t\treturn obj\n\t\t\telif type(obj) == dict:\n\t\t\t\toutput = {}\n\t\t\t\tfor key in obj:\n\t\t\t\t\toutput[key] = dump(obj[key], tabs+'\\t')\n\t\t\telse:\n\t\t\t\toutput = {}\n\t\t\t\tovars = vars(obj)\n\t\t\t\tfor key in ovars:\n\t\t\t\t\tif key in names: names[key] += 1\n\t\t\t\t\telse: names[key] = 1\n\t\t\t\t\toutput[key] = dump(ovars[key], tabs+'\\t')\n\t\t\treturn '\\n'.join(['%s%s:\\n%s\\t%s' % (tabs, key, tabs, output[key]) for key in output]) if output else {}\n\t\texcept: return 'no __dict__'\n\t\n\tprint('Dumping memleak info.')\n\tf = open('dump.txt', 'w')\n\tf.write(dump(_root))\n\tf.close()\n\t\n\tcounts = {}\n\tfor name in names:\n\t\tcount = names[name]\n\t\tif count in counts:\n\t\t\tcounts[count].append(name)\n\t\telse:\n\t\t\tcounts[count] = [name]\n\t\n\tf = open('counts.txt', 'w')\n\tfor key in reversed(sorted(counts)):\n\t\tf.write('%s: %s\\n' % (key, counts[key]))\n\tf.close()\n"
},
{
"alpha_fraction": 0.6584330201148987,
"alphanum_fraction": 0.6657661199569702,
"avg_line_length": 27.944133758544922,
"blob_id": "1c677d57ecc0df6786ad20764b6ff5057f3b7bdb",
"content_id": "bd038ee4b2605d8b6548bcee1cf55f99c9496810",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5182,
"license_type": "permissive",
"max_line_length": 160,
"num_lines": 179,
"path": "/SayHooks.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "import inspect, sys, os, types, time, string\n\n_permissionlist = ['admin', 'adminchan', 'mod', 'modchan', 'chanowner', 'chanadmin', 'chanpublic', 'public', 'battlehost', 'battlepublic']\n_permissiondocs = {\n\t\t\t\t\t'admin':'Admin Commands', \n\t\t\t\t\t'adminchan':'Admin Commands (channel)', \n\t\t\t\t\t'mod':'Moderator Commands', \n\t\t\t\t\t'modchan':'Moderator Commands (channel)', \n\t\t\t\t\t'chanowner':'Channel Owner Commands (channel)', \n\t\t\t\t\t'chanadmin':'Channel Admin Commands (channel)', \n\t\t\t\t\t'chanpublic':'Public Commands (channel)', \n\t\t\t\t\t'public':'Public Commands', \n\t\t\t\t\t'battlepublic':'Public Commands (battle)', \n\t\t\t\t\t'battlehost':'Battle Host Commands', \n\t\t\t\t\t}\n\ndef _erase():\n\tl = dict(globals())\n\tfor iter in l:\n\t\tif not iter == '_erase':\n\t\t\tdel globals()[iter]\n\nglobal bad_word_dict\nglobal bad_site_list\nbad_word_dict = {}\nbad_site_list = []\n\ndef _update_lists():\n\ttry:\n\t\tf = open('bad_words.txt', 'r')\n\t\tfor line in f.readlines():\n\t\t\tif line.count(' ') < 1:\n\t\t\t\tbad_word_dict[line.strip()] = '***'\n\t\t\telse:\n\t\t\t\tsline = line.strip().split(' ', 1)\n\t\t\t\tbad_word_dict[sline[0]] = ' '.join(sline[1:])\n\t\tf.close()\n\texcept Exception as e:\n\t\tprint('Error parsing profanity list: %s' %(e))\n\ttry:\n\t\tf = open('bad_sites.txt', 'r')\n\t\tfor line in f.readlines():\n\t\t\tline = line.strip()\n\t\t\tif line and not line in bad_site_list: bad_site_list.append(line)\n\t\tf.close()\n\texcept Exception as e:\n\t\tprint('Error parsing shock site list: %s' %(e))\n\t\t\t\t\ndef _clear_lists():\n\tglobal bad_word_dict\n\tglobal bad_site_list\n\tbad_word_dict = {}\n\tbad_site_list = []\n\n_update_lists()\n\nchars = string.ascii_letters + string.digits\n\ndef _process_word(word):\n\tif word == word.upper(): uppercase = True\n\telse: uppercase = False\n\tlword = word.lower()\n\tif lword in bad_word_dict:\n\t\tword = bad_word_dict[lword]\n\tif uppercase: word = word.upper()\n\treturn word\n\ndef _nasty_word_censor(msg):\n\tmsg = msg.lower()\n\tfor word in bad_word_dict.keys():\n\t\tif word.lower() in msg: return False\n\treturn True\n\ndef _word_censor(msg):\n\twords = []\n\tword = ''\n\tletters = True\n\tfor letter in msg:\n\t\tif bool(letter in chars) == bool(letters): word += letter\n\t\telse:\n\t\t\tletters = not bool(letters)\n\t\t\twords.append(word)\n\t\t\tword = letter\n\twords.append(word)\n\tnewmsg = []\n\tfor word in words:\n\t\tnewmsg.append(_process_word(word))\n\treturn ''.join(newmsg)\n\ndef _site_censor(msg):\n\ttestmsg1 = ''\n\ttestmsg2 = ''\n\tfor letter in msg:\n\t\tif not letter: continue\n\t\tif letter.isalnum():\n\t\t\ttestmsg1 += letter\n\t\t\ttestmsg2 += letter\n\t\telif letter in './%':\n\t\t\ttestmsg2 += letter\n\tfor site in bad_site_list:\n\t\tif site in msg or site in testmsg1 or site in testmsg2:\n\t\t\treturn # 'I think I can post shock sites, but I am wrong.'\n\treturn msg\n\ndef _spam_enum(client, chan):\n\tnow = time.time()\n\tbonus = 0\n\talready = []\n\ttimes = [now]\n\tfor when in dict(client.lastsaid[chan]):\n\t\tt = float(when)\n\t\tif t > now-5: # check the last five seconds # can check a longer period of time if old bonus decay is included, good for 2-3 second spam, which is still spam.\n\t\t\tfor message in client.lastsaid[chan][when]:\n\t\t\t\ttimes.append(t)\n\t\t\t\tif message in already:\n\t\t\t\t\tbonus += 2 * already.count(message) # repeated message\n\t\t\t\tif len(message) > 50:\n\t\t\t\t\tbonus += min(len(message), 200) * 0.01 # long message: 0-2 bonus points based linearly on length 0-200\n\t\t\t\tbonus += 1 # something was said\n\t\t\t\talready.append(message)\n\t\telse: del client.lastsaid[chan][when]\n\t\n\ttimes.sort()\n\tlast_time = None\n\tfor t in times:\n\t\tif last_time:\n\t\t\tdiff = t - last_time\n\t\t\tif diff < 1:\n\t\t\t\tbonus += (1 - diff) * 1.5\n\t\tlast_time = t\n\t\n\tif bonus > 7: return True\n\telse: return False\n\ndef _spam_rec(client, chan, msg):\n\tnow = str(time.time())\n\tif not chan in client.lastsaid: client.lastsaid[chan] = {}\n\tif not now in client.lastsaid[chan]:\n\t\tclient.lastsaid[chan][now] = [msg]\n\telse:\n\t\tclient.lastsaid[chan][now].append(msg)\n\ndef _chan_msg_filter(self, client, chan, msg):\n\tusername = client.username\n\tchannel = self._root.channels[chan]\n\t\n\tif channel.isMuted(client): return msg # client is muted, no use doing anything else\n\tif channel.antispam and not channel.isOp(client): # don't apply antispam to ops\n\t\t_spam_rec(client, chan, msg)\n\t\tif _spam_enum(client, chan):\n\t\t\tchannel.muteUser(self._root.chanserv, client, 15, ip=True, quiet=True)\n\t\t\t# this next line is necessary, because users aren't always muted i.e. you can't mute channel founders or moderators\n\t\t\tif channel.isMuted(client):\n\t\t\t\tchannel.channelMessage('%s was muted for spamming.' % username)\n\t\t\t\t#if quiet: # maybe make quiet a channel-wide setting, so mute/kick/op/etc would be silent\n\t\t\t\t#\tclient.Send('CHANNELMESAGE %s You were quietly muted for spamming.'%chan)\n\t\t\t\treturn ''\n\t\t\t\n\tif channel.censor:\n\t\tmsg = _word_censor(msg)\n\tif channel.antishock:\n\t\tmsg = _site_censor(msg)\n\treturn msg\n\ndef hook_SAY(self, client, chan, msg):\n\tuser = client.username\n\tchannel = self._root.channels[chan]\n\tmsg = _chan_msg_filter(self, client, chan, msg)\n\treturn msg\n\ndef hook_SAYEX(self, client, chan, msg):\n\tmsg = _chan_msg_filter(self, client, chan, msg)\n\treturn msg\n\ndef hook_SAYPRIVATE(self, client, target, msg):\n\treturn _site_censor(msg)\n\ndef hook_SAYBATTLE(self, client, battle_id, msg):\n\treturn msg # no way to respond in battles atm\n\n"
},
{
"alpha_fraction": 0.6402156949043274,
"alphanum_fraction": 0.6625577807426453,
"avg_line_length": 19.603174209594727,
"blob_id": "56d88efb3de765e30ea8bf66c1d72f2340017887",
"content_id": "ad14510794eeb7287373d920d1413ab46f7bb0f4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1298,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 63,
"path": "/ip2country.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "from pygeoip import pygeoip\nimport traceback\n\ndbfile = 'GeoIP.dat'\n\ndef update():\n\tgzipfile = dbfile + \".gz\"\n\tf = open(gzipfile, 'w')\n\tdburl = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz'\n\timport urllib2\n\timport gzip\n\tprint(\"Downloading %s ...\" %(dburl))\n\tresponse = urllib2.urlopen(dburl)\n\tf.write(response.read())\n\tf.close()\n\tprint(\"done!\")\n\tf = gzip.open(gzipfile)\n\tdb = open(dbfile, 'w')\n\tdb.write(f.read())\n\tf.close()\n\tdb.close()\n\ntry:\n\tf=open(dbfile,'r')\n\tf.close()\nexcept:\n\tprint(\"%s doesn't exist, downloading...\" % (dbfile))\n\tupdate()\n\ndef loaddb():\n\tglobal geoip\n\ttry:\n\t\tgeoip = pygeoip.Database(dbfile)\n\t\treturn True\n\texcept Exception as e:\n\t\tprint(\"Couldn't load %s: %s\" % (dbfile, str(e)))\n\t\tprint(traceback.format_exc())\n\t\treturn False\n\nworking = loaddb()\n\n\ndef lookup(ip):\n\tif not working: return '??'\n\taddrinfo = geoip.lookup(ip)\n\tif not addrinfo.country: return '??'\n\treturn addrinfo.country\n\ndef reloaddb():\n\tif not working: return\n\tloaddb()\n\"\"\"\nprint lookup(\"37.187.59.77\")\nprint lookup(\"77.64.139.108\")\nprint lookup(\"8.8.8.8\")\nprint lookup(\"0.0.0.0\")\nimport csv\nwith open('/tmp/test.csv', 'rb') as csvfile:\n\treader = csv.reader(csvfile, delimiter=' ', quotechar='\"')\n\tfor row in reader:\n\t\tip = row[0]\n\t\tprint(\"%s %s\" %(ip, lookup(row[0])))\n\"\"\"\n"
},
{
"alpha_fraction": 0.6855528354644775,
"alphanum_fraction": 0.6870800256729126,
"avg_line_length": 34.97252655029297,
"blob_id": "70f084de1a8e95f6a8ca5e6e9a2b082cbe28e06b",
"content_id": "ec615257f773d92f9143b8760b084827f0900a52",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6548,
"license_type": "permissive",
"max_line_length": 146,
"num_lines": 182,
"path": "/protocol/Channel.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "from AutoDict import AutoDict\nimport time\n\nclass Channel(AutoDict):\n\tdef __init__(self, root, name, id = 0, users=[], admins=[],\n\t\t\t\t\t\tban={}, allow=[], autokick='ban', chanserv=False,\n\t\t\t\t\t\towner='', mutelist={}, antispam=False,\n\t\t\t\t\t\tcensor=False, antishock=False, topic=None,\n\t\t\t\t\t\tkey=None, history=False, **kwargs):\n\t\tself.id = id\n\t\tself._root = root\n\t\tself.name = name\n\t\tself.users = users\n\t\tself.admins = admins\n\t\tself.ban = ban\n\t\tself.allow = allow\n\t\tself.autokick = autokick\n\t\tself.chanserv = chanserv\n\t\tself.owner = owner\n\t\tself.mutelist = mutelist\n\t\tself.antispam = antispam\n\t\tself.censor = censor\n\t\tself.antishock = antishock\n\t\tself.topic = topic\n\t\tself.key = key\n\t\tself.history = history\n\t\tself.__AutoDictInit__()\n\n\t\tif self._root and chanserv and self._root.chanserv and not name in self._root.channels:\n\t\t\tself._root.chanserv.Send('JOIN %s' % self.name)\n\n\tdef broadcast(self, message):\n\t\tself._root.broadcast(message, self.name)\n\n\tdef channelMessage(self, message):\n\t\tself.broadcast('CHANNELMESSAGE %s %s' % (self.name, message))\n\n\tdef register(self, client, owner):\n\t\tself.owner = owner.db_id\n\n\tdef addUser(self, client):\n\t\tusername = client.username\n\t\tif not username in self.users:\n\t\t\tself.users.append(username)\n\t\t\tself.broadcast('JOINED %s %s' % (self.name, username))\n\n\tdef removeUser(self, client, reason=None):\n\t\tchan = self.name\n\t\tusername = client.username\n\n\t\tif username in self.users:\n\t\t\tself.users.remove(username)\n\n\t\t\tif self.name in client.channels:\n\t\t\t\tclient.channels.remove(chan)\n\t\t\tif reason and len(reason) > 0:\n\t\t\t\tself._root.broadcast('LEFT %s %s %s' % (chan, username, reason), chan)\n\t\t\telse:\n\t\t\t\tself._root.broadcast('LEFT %s %s' % (chan, username), chan)\n\n\tdef isAdmin(self, client):\n\t\treturn client and ('admin' in client.accesslevels)\n\n\tdef isMod(self, client):\n\t\treturn client and (('mod' in client.accesslevels) or self.isAdmin(client))\n\n\tdef isFounder(self, client):\n\t\treturn client and ((client.db_id == self.owner) or self.isMod(client))\n\n\tdef isOp(self, client):\n\t\treturn client and ((client.db_id in self.admins) or self.isFounder(client))\n\n\tdef getAccess(self, client): # return client's security clearance\n\t\treturn 'mod' if self.isMod(client) else\\\n\t\t\t\t('founder' if self.isFounder(client) else\\\n\t\t\t\t('op' if self.isOp(client) else\\\n\t\t\t\t'normal'))\n\n\tdef isMuted(self, client):\n\t\treturn client.db_id in self.mutelist\n\n\tdef getMuteMessage(self, client):\n\t\tif self.isMuted(client):\n\t\t\tm = self.mutelist[client.db_id]\n\t\t\tif m['expires'] == 0:\n\t\t\t\treturn 'muted forever'\n\t\t\telse:\n\t\t\t\t # TODO: move format_time, bin2dec, etc to a utilities class or module\n\t\t\t\treturn 'muted for the next %s.' % (client._protocol._time_until(m['expires']))\n\t\telse:\n\t\t\treturn 'not muted'\n\n\tdef isAllowed(self, client):\n\t\tif self.autokick == 'allow':\n\t\t\treturn (self.isOp(client) or (client.db_id in self.allow)) or 'not allowed here'\n\t\telif self.autokick == 'ban':\n\t\t\treturn (self.isOp(client) or (client.db_id not in self.ban)) or self.ban[client.db_id]\n\n\tdef setTopic(self, client, topic):\n\t\tself.topic = topic\n\n\t\tif topic in ('*', None):\n\t\t\tif self.topic:\n\t\t\t\tself.channelMessage('Topic disabled.')\n\t\t\t\ttopicdict = {}\n\t\telse:\n\t\t\tself.channelMessage('Topic changed.')\n\t\t\ttopicdict = {'user':client.username, 'text':topic, 'time':time.time()}\n\t\t\tself.broadcast('CHANNELTOPIC %s %s %s %s'%(self.name, client.username, topicdict['time'], topic))\n\t\tself.topic = topicdict\n\n\tdef setKey(self, client, key):\n\t\tif key in ('*', None):\n\t\t\tif self.key:\n\t\t\t\tself.key = None\n\t\t\t\tself.channelMessage('<%s> unlocked this channel' % client.username)\n\t\telse:\n\t\t\tself.key = key\n\t\t\tself.channelMessage('<%s> locked this channel with a password' % client.username)\n\n\tdef setFounder(self, client, target):\n\t\tif not target: return\n\t\tself.owner = target.db_id\n\t\tself.channelMessage(\"<%s> has just been set as this channel's founder by <%s>\" % (target.username, client.username))\n\n\tdef opUser(self, client, target):\n\t\tif target and not target.db_id in self.admins:\n\t\t\tself.admins.append(target.db_id)\n\t\t\tself.channelMessage(\"<%s> has just been added to this channel's operator list by <%s>\" % (target.username, client.username))\n\n\tdef deopUser(self, client, target):\n\t\tif target and target.db_id in self.admins:\n\t\t\tself.admins.remove(target.db_id)\n\t\t\tself.channelMessage(\"<%s> has just been removed from this channel's operator list by <%s>\" % (target.username, client.username))\n\n\tdef kickUser(self, client, target, reason=''):\n\t\tif self.isFounder(target): return\n\t\tif target and target.username in self.users:\n\t\t\ttarget.Send('FORCELEAVECHANNEL %s %s %s' % (self.name, client.username, reason))\n\t\t\tself.channelMessage('<%s> has kicked <%s> from the channel%s' % (client.username, target.username, (' (reason: %s)'%reason if reason else '')))\n\t\t\tself.removeUser(target, 'kicked from channel%s' % (' (reason: %s)'%reason if reason else ''))\n\n\tdef banUser(self, client, target, reason=''):\n\t\tif self.isFounder(target): return\n\t\tif target and not target.db_id in self.ban:\n\t\t\tself.ban[target.db_id] = reason\n\t\t\tself.kickUser(client, target, reason)\n\t\t\tself.channelMessage('<%s> has been banned from this channel by <%s>' % (target.username, client.username))\n\n\tdef unbanUser(self, client, target):\n\t\tif target and target.db_id in self.ban:\n\t\t\tdel self.ban[target.db_id]\n\t\t\tself.channelMessage('<%s> has been unbanned from this channel by <%s>' % (target.username, client.username))\n\n\tdef allowUser(self, client, target):\n\t\tif target and not client.db_id in self.allow:\n\t\t\tself.allow.append(client.db_id)\n\t\t\tself.channelMessage('<%s> has been allowed in this channel by <%s>' % (target.username, client.username))\n\n\tdef disallowUser(self, client, target):\n\t\tif target and client.db_id in self.allow:\n\t\t\tself.allow.remove(client.db_id)\n\t\t\tself.channelMessage('<%s> has been disallowed in this channel by <%s>' % (target.username, client.username))\n\n\tdef muteUser(self, client, target, duration=0, ip=False, quiet=False):\n\t\tif self.isFounder(target): return\n\t\tif target and not client.db_id in self.mutelist:\n\t\t\tif not quiet:\n\t\t\t\tself.channelMessage('<%s> has muted <%s>' % (client.username, target.username))\n\t\t\ttry:\n\t\t\t\tduration = float(duration)*60\n\t\t\t\tif duration < 1:\n\t\t\t\t\tduration = 0\n\t\t\t\telse:\n\t\t\t\t\tduration = time.time() + duration\n\t\t\texcept: duration = 0\n\t\t\tself.mutelist[target.db_id] = {'expires':duration, 'ip':ip, 'quiet':quiet}\n\n\tdef unmuteUser(self, client, target):\n\t\tif target and target.db_id in self.mutelist:\n\t\t\tdel self.mutelist[target.db_id]\n\t\t\tself.channelMessage('<%s> has unmuted <%s>' % (client.username, target.username))\n\n"
},
{
"alpha_fraction": 0.6929429173469543,
"alphanum_fraction": 0.6944444179534912,
"avg_line_length": 28.577777862548828,
"blob_id": "a667312250872fe49416af4bd3a367ae0588243e",
"content_id": "ba507418c195cd43c24176b352b277a40e0d59c5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1332,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 45,
"path": "/protocol/Battle.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "from AutoDict import AutoDict\n\nclass Battle(AutoDict):\n\tdef __init__(self, root, id, type, natType, password, port, maxplayers,\n\t\t\t\t\t\thashcode, rank, maphash, map, title, modname,\n\t\t\t\t\t\tpassworded, host, users, spectators=0,\n\t\t\t\t\t\tstartrects={}, disabled_units=[], pending_users=set(),\n\t\t\t\t\t\tauthed_users=set(), bots={}, script_tags={},\n\t\t\t\t\t\treplay_script={}, replay=False,\n\t\t\t\t\t\tsending_replay_script=False, locked=False,\n\t\t\t\t\t\tengine=None, version=None):\n\t\tself._root = root\n\t\tself.id = id\n\t\tself.type = type\n\t\tself.natType = natType\n\t\tself.password = password\n\t\tself.port = port\n\t\tself.maxplayers = maxplayers\n\t\tself.spectators = spectators\n\t\tself.hashcode = hashcode\n\t\tself.rank = rank\n\t\tself.maphash = maphash\n\t\tself.map = map\n\t\tself.title = title\n\t\tself.modname = modname\n\t\tself.passworded = passworded\n\t\tself.users = users\n\t\tself.host = host\n\t\tself.startrects = startrects\n\t\tself.disabled_units = disabled_units\n\n\t\tself.pending_users = pending_users\n\t\tself.authed_users = authed_users\n\n\t\tself.engine = (engine or 'spring').lower()\n\t\tself.version = version or root.latestspringversion\n\n\t\tself.bots = bots\n\t\tself.script_tags = script_tags\n\t\tself.replay_script = replay_script\n\t\tself.replay = replay\n\t\tself.sending_replay_script = sending_replay_script\n\t\tself.locked = locked\n\t\tself.spectators = 0\n\t\tself.__AutoDictInit__()\n\n"
},
{
"alpha_fraction": 0.7436399459838867,
"alphanum_fraction": 0.7455968856811523,
"avg_line_length": 19.440000534057617,
"blob_id": "c1c9b1a2ae97df6812b925e779a7376a4440a123",
"content_id": "03ffaab70f64aecd4ad94720df22846ee39415d5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 511,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 25,
"path": "/README.md",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "# Requirements\n- sqlalchemy\n- ip2c\n\n# Installation\n```\n# git clone [email protected]:spring/uberserver.git\n# virtualenv ~/virtenvs/uberserver\n# source ~/virtenvs/uberserver/bin/activate\n# pip install pycrypto\n# pip install SQLAlchemy\n```\n\nWithout further configuration this will create a SQLite database (server.db).\nPerformance will be OK for testing and small setups. For production use,\nsetup MySQL/PostgreSQL/etc.\n\n# Usage\n```\n# source ~/virtenvs/uberserver/bin/activate\n# ./server.py\n```\n\n# Logs\n- `$PWD/server.log`\n"
},
{
"alpha_fraction": 0.6316090226173401,
"alphanum_fraction": 0.6356101632118225,
"avg_line_length": 33.30392074584961,
"blob_id": "02dfa48280794fd751dfd4279b936e8422fb4f36",
"content_id": "4a67cc63829f0e94a3acf02d45f97d7f92664aa3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3499,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 102,
"path": "/XmlRpcServer.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "#\n# xmlrpc class for auth of replays.springrts.com\n#\n# TODO:\n# - remove dependency to Protocol.py\n# - move SQLAlchemy calls to SQLUsers.py\n# -> remove _FakeClient\n\nimport BaseHTTPServer\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nfrom base64 import b64encode\nimport os.path\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\nfrom protocol import Protocol\nfrom CryptoHandler import MD5LEG_HASH_FUNC as LEGACY_HASH_FUNC\nfrom SQLUsers import User\n\n# logging\nxmlrpc_logfile = os.path.join(os.path.dirname(__file__), \"xmlrpc.log\")\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nfh = TimedRotatingFileHandler(xmlrpc_logfile, when=\"midnight\", backupCount=6)\nformatter = logging.Formatter(fmt='%(asctime)s %(levelname)-5s %(module)s.%(funcName)s:%(lineno)d %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S')\nfh.setFormatter(formatter)\nfh.setLevel(logging.DEBUG)\nlogger.addHandler(fh)\n\n\ndef _xmlrpclog(self, format, *args):\n logger.debug(\"%s - %s\" , self.client_address[0], format%args)\n\n# overwrite default logger, because it will otherwise spam main server log\nBaseHTTPServer.BaseHTTPRequestHandler.log_message = _xmlrpclog\n\n\nclass XmlRpcServer(object):\n \"\"\"\n XMLRPC service, exported functions are in class _RpcFuncs\n \"\"\"\n def __init__(self, root, host, port):\n self._root = root\n self.host = host\n self.port = port\n self._server = SimpleXMLRPCServer((self.host, self.port))\n self._server.register_introspection_functions()\n self._server.register_instance(_RpcFuncs(self._root))\n\n def start(self):\n logger.info('Listening for XMLRPC clients on %s:%d', self.host, self.port)\n self._server.serve_forever()\n\n def shutdown(self):\n self._server.shutdown()\n\n\nclass _RpcFuncs(object):\n \"\"\"\n All methods of this class will be exposed via XMLRPC.\n \"\"\"\n def __init__(self, root):\n self._root = root\n self._proto = Protocol.Protocol(self._root)\n\n def get_account_info(self, username, password):\n password_enc = unicode(b64encode(LEGACY_HASH_FUNC(password).digest()))\n client = _FakeClient(self._root)\n self._proto.in_TESTLOGIN(client, unicode(username), password_enc) # FIXME: don't use Protocol.py\n logger.debug(\"client.reply: %s\", client.reply)\n if client.reply.startswith(\"TESTLOGINACCEPT %s\" % username):\n session = self._root.userdb.sessionmaker() # FIXME: move to SQLUsers.py\n db_user = session.query(User).filter(User.username == username).first()\n renames = list()\n for rename in db_user.renames:\n renames.append(rename.original)\n if db_user.renames:\n renames.append(db_user.renames[-1].new)\n renames = set(renames)\n result = {\"status\": 0, \"accountid\": int(db_user.id), \"username\": str(db_user.username),\n \"ingame_time\": int(db_user.ingame_time), \"email\": str(db_user.email),\n \"aliases\": list(renames)}\n try:\n result[\"country\"] = db_user.logins[-1].country\n except:\n result[\"country\"] = \"\"\n return result\n else:\n return {\"status\": 1}\n\n\nclass _FakeClient(object):\n \"\"\"\n Protocol.Protocol uses this object for communication.\n \"\"\"\n def __init__(self, root):\n self._root = root\n self.reply = \"\"\n\n def Send(self, reply):\n self.reply = reply\n"
},
{
"alpha_fraction": 0.7454545497894287,
"alphanum_fraction": 0.7454545497894287,
"avg_line_length": 54,
"blob_id": "ae6efb5b9f99953e47440884b5065c2456151968",
"content_id": "da6c1b9af56d478ed4f4ebc9f5fc46f21ff34177",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 55,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 1,
"path": "/pygeoip/__init__.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "# pygeoip from https://code.google.com/p/python-geoip/\n"
},
{
"alpha_fraction": 0.6910946369171143,
"alphanum_fraction": 0.6948052048683167,
"avg_line_length": 27,
"blob_id": "72a5090b161acac8fa2fe0ae1282a8574d06ccd5",
"content_id": "9bf92279b50119d0997d6946b4899039b52b5f90",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2156,
"license_type": "permissive",
"max_line_length": 135,
"num_lines": 77,
"path": "/Multiplexer.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "import time\nfrom select import * # eww hack but saves the other hack of selectively importing constants\n\nclass EpollMultiplexer:\n\n\tdef __init__(self):\n\t\tself.filenoToSocket = {}\n\t\tself.socketToFileno = {}\n\t\tself.sockets = set([])\n\t\tself.output = set([])\n\n\t\tself.inMask = EPOLLIN | EPOLLPRI\n\t\tself.outMask = EPOLLOUT\n\t\tself.errMask = EPOLLERR | EPOLLHUP\n\n\t\tself.poller = epoll()\n\n\tdef register(self, s):\n\t\ts.setblocking(0)\n\t\tfileno = s.fileno()\n\t\tself.filenoToSocket[fileno] = s\n\t\tself.socketToFileno[s] = fileno # gotta maintain this because fileno() lookups aren't possible on closed sockets\n\t\tself.sockets.add(s)\n\t\tself.poller.register(fileno, self.inMask | self.errMask)\n\n\tdef unregister(self, s):\n\t\tif s in self.sockets:\n\t\t\tself.sockets.remove(s)\n\t\tif s in self.output:\n\t\t\tself.output.remove(s)\n\t\tif s in self.socketToFileno:\n\t\t\tfileno = self.socketToFileno[s]\n\t\t\tself.poller.unregister(fileno)\n\t\t\tdel self.socketToFileno[s]\n\t\t\tdel self.filenoToSocket[fileno]\n\n\tdef setoutput(self, s, ready):\n\t\t# this if structure means it only scans output once.\n\t\tif not ready and s in self.output:\n\t\t\tself.output.remove(s)\n\t\telif not ready:\n\t\t\treturn\n\t\telif ready and s in self.sockets:\n\t\t\tself.output.add(s)\n\t\tif not s in self.socketToFileno: return\n\t\teventmask = self.inMask | self.errMask | (self.outMask if ready else 0)\n\t\tself.poller.modify(s, eventmask) # not valid for select.poll before python 2.6, might need to replace with register() in this context\n\n\tdef pump(self, callback):\n\t\twhile True:\n\t\t\tinputs, outputs, errors = self.poll()\n\t\t\tcallback(inputs, outputs, errors)\n\n\tdef poll(self):\n\t\tresults = []\n\t\ttry:\n\t\t\tresults = self.poller.poll(10)\n\t\texcept IOError as e:\n\t\t\tif e[0] == 4:\n\t\t\t\t# interrupted system call - this happens when any signal is triggered\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\traise e\n\n\t\tinputs = []\n\t\toutputs = []\n\t\terrors = []\n\n\t\tfor fd, mask in results:\n\t\t\ttry:\n\t\t\t\ts = self.filenoToSocket[fd]\n\t\t\texcept: # FIXME: socket was already deleted, shouldn't happen, but does!\n\t\t\t\tcontinue\n\t\t\tif mask & self.inMask: inputs.append(s)\n\t\t\tif mask & self.outMask: outputs.append(s)\n\t\t\tif mask & self.errMask: errors.append(s)\n\t\treturn inputs, outputs, errors\n"
},
{
"alpha_fraction": 0.6638556122779846,
"alphanum_fraction": 0.6763574481010437,
"avg_line_length": 29.2393741607666,
"blob_id": "61c87775ce6b577841d4ab628140fef6e0bcd8aa",
"content_id": "317b93120b795ca90f6986be4c78f941ed62f1a8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13518,
"license_type": "permissive",
"max_line_length": 125,
"num_lines": 447,
"path": "/Client.py",
"repo_name": "Anarchid/uberserver",
"src_encoding": "UTF-8",
"text": "import socket, time, sys, thread, ip2country, errno\nfrom collections import defaultdict\n\nfrom BaseClient import BaseClient\n\nimport CryptoHandler\n\nfrom CryptoHandler import encrypt_sign_message\nfrom CryptoHandler import decrypt_auth_message\nfrom CryptoHandler import int32_to_str\nfrom CryptoHandler import str_to_int32\n\nfrom CryptoHandler import DATA_MARKER_BYTE\nfrom CryptoHandler import DATA_PARTIT_BYTE\nfrom CryptoHandler import UNICODE_ENCODING\n\n\nclass Client(BaseClient):\n\t'this object represents one server-side connected client'\n\n\tdef __init__(self, root, connection, address, session_id):\n\t\t'initial setup for the connected client'\n\t\tself._root = root\n\t\tself.conn = connection\n\n\t\t# detects if the connection is from this computer\n\t\tif address[0].startswith('127.'):\n\t\t\tif root.online_ip:\n\t\t\t\taddress = (root.online_ip, address[1])\n\t\t\telif root.local_ip:\n\t\t\t\taddress = (root.local_ip, address[1])\n\t\t\n\t\tself.ip_address = address[0]\n\t\tself.local_ip = address[0]\n\t\tself.port = address[1]\n\t\t\n\t\tself.setFlagByIP(self.ip_address)\n\t\t\n\t\tself.session_id = session_id\n\t\tself.db_id = session_id\n\t\t\n\t\tself.handler = None\n\t\tself.static = False\n\t\tself._protocol = None\n\t\tself.removing = False\n\t\tself.sendError = False\n\t\tself.msg_id = ''\n\t\tself.msg_sendbuffer = []\n\t\tself.enc_sendbuffer = []\n\t\tself.sendingmessage = ''\n\n\t\t## time-stamps for encrypted data\n\t\tself.incoming_msg_ctr = 0\n\t\tself.outgoing_msg_ctr = 1\n\n\t\t## note: this NEVER becomes false after LOGIN!\n\t\tself.logged_in = False\n\n\t\tself.status = '12'\n\t\tself.is_ingame = False\n\t\tself.cpu = 0\n\t\tself.access = 'fresh'\n\t\tself.accesslevels = ['fresh','everyone']\n\t\tself.channels = []\n\t\t\n\t\tself.battle_bots = {}\n\t\tself.current_battle = None\n\t\tself.battle_bans = []\n\t\tself.ingame_time = 0\n\t\tself.went_ingame = 0\n\t\tself.spectator = False\n\t\tself.battlestatus = {'ready':'0', 'id':'0000', 'ally':'0000', 'mode':'0', 'sync':'00', 'side':'00', 'handicap':'0000000'}\n\t\tself.teamcolor = '0'\n\n\t\t## copies of the DB User values, set on successful LOGIN\n\t\tself.set_user_pwrd_salt(\"\", (\"\", \"\"))\n\n\t\tself.email = ''\n\t\tself.hostport = None\n\t\tself.udpport = 0\n\t\tself.bot = 0\n\t\tself.floodlimit = {\n\t\t\t'fresh':{'msglength':1024*32, 'bytespersecond':1024*32, 'seconds':2},\n\t\t\t'user':{'msglength':1024*32, 'bytespersecond':1024*32, 'seconds':10},\n\t\t\t'bot':{'msglength':1024, 'bytespersecond':10000, 'seconds':5},\n\t\t\t'mod':{'msglength':10000, 'bytespersecond':10000, 'seconds':10},\n\t\t\t'admin':{'msglength':10000, 'bytespersecond':100000, 'seconds':10},\n\t\t}\n\t\tself.msg_length_history = {}\n\t\tself.lastsaid = {}\n\t\tself.current_channel = ''\n\t\t\n\t\tself.debug = False\n\t\tself.data = ''\n\n\t\t# holds compatibility flags - will be set by Protocol as necessary\n\t\tself.compat = defaultdict(lambda: False)\n\t\tself.scriptPassword = None\n\t\t\n\t\tnow = time.time()\n\t\tself.last_login = now\n\t\tself.failed_logins = 0\n\t\tself.register_date = now\n\t\tself.lastdata = now\n\t\tself.last_id = 0\n\t\t\n\t\tself.users = set([]) # session_id\n\t\tself.battles = set([]) # [battle_id] = [user1, user2, user3, etc]\n\n\t\tself.ignored = {}\n\t\t\n\t\tself._root.console_write('Client connected from %s:%s, session ID %s.' % (self.ip_address, self.port, session_id))\n\n\t\t## AES cipher used for encrypted protocol communication\n\t\t## with this client; starts with a NULL session-key and\n\t\t## becomes active when client sends SETSHAREDKEY\n\t\tself.set_aes_cipher_obj(CryptoHandler.aes_cipher(\"\"))\n\t\tself.set_session_key(\"\")\n\n\t\tself.set_session_key_received_ack(False)\n\n\n\tdef set_aes_cipher_obj(self, obj): self.aes_cipher_obj = obj\n\tdef get_aes_cipher_obj(self): return self.aes_cipher_obj\n\n\tdef set_session_key_received_ack(self, b): self.session_key_received_ack = b\n\tdef get_session_key_received_ack(self): return self.session_key_received_ack\n\n\tdef set_session_key(self, key): self.aes_cipher_obj.set_key(key)\n\tdef get_session_key(self): return (self.aes_cipher_obj.get_key())\n\n\tdef use_secure_session(self): return (len(self.get_session_key()) != 0)\n\tdef use_msg_auth_codes(self): return (self._root.use_message_authent_codes)\n\n\tdef set_msg_id(self, msg):\n\t\tself.msg_id = \"\"\n\n\t\tif (not msg.startswith('#')):\n\t\t\treturn msg\n\n\t\ttest = msg.split(' ')[0][1:]\n\n\t\tif (not test.isdigit()):\n\t\t\treturn msg\n\n\t\tself.msg_id = '#%s ' % test\n\t\treturn (' '.join(msg.split(' ')[1:]))\n\n\n\tdef setFlagByIP(self, ip, force=True):\n\t\tcc = ip2country.lookup(ip)\n\t\tif force or cc != '??':\n\t\t\tself.country_code = cc\n\n\tdef Bind(self, handler=None, protocol=None):\n\t\tif handler:\tself.handler = handler\n\t\tif protocol:\n\t\t\tif not self._protocol:\n\t\t\t\tprotocol._new(self)\n\t\t\tself._protocol = protocol\n\n\n\t##\n\t## handle data from client\n\t##\n\tdef Handle(self, data):\n\t\tif (self.access in self.floodlimit):\n\t\t\tmsg_limits = self.floodlimit[self.access]\n\t\telse:\n\t\t\tmsg_limits = self.floodlimit['user']\n\n\t\tnow = int(time.time())\n\t\tself.lastdata = now # data received, store time to detect disconnects\n\n\t\tbytespersecond = msg_limits['bytespersecond']\n\t\tseconds = msg_limits['seconds']\n\n\t\tif (now in self.msg_length_history):\n\t\t\tself.msg_length_history[now] += len(data)\n\t\telse:\n\t\t\tself.msg_length_history[now] = len(data)\n\n\t\ttotal = 0\n\n\t\tfor iter in dict(self.msg_length_history):\n\t\t\tif (iter < now - (seconds - 1)):\n\t\t\t\tdel self.msg_length_history[iter]\n\t\t\telse:\n\t\t\t\ttotal += self.msg_length_history[iter]\n\n\t\tif total > (bytespersecond * seconds):\n\t\t\tif not self.access in ('admin', 'mod'):\n\t\t\t\tif (self.bot != 1):\n\t\t\t\t\t# FIXME: no flood limit for these atm, need to do server-side shaping/bandwith limiting\n\t\t\t\t\tself.Send('SERVERMSG No flooding (over %s per second for %s seconds)' % (bytespersecond, seconds))\n\t\t\t\t\tself.Remove('Kicked for flooding (%s)' % (self.access))\n\t\t\t\t\treturn\n\n\t\t## keep appending until we see at least one newline\n\t\tself.data += data\n\n\t\t## if too much data has accumulated without a newline, clear\n\t\tif (len(self.data) > (msg_limits['msglength'] * 32)):\n\t\t\tdel self.data; self.data = \"\"; return\n\t\tif (self.data.count('\\n') == 0):\n\t\t\treturn\n\n\t\tself.HandleProtocolCommands(self.data.split(DATA_PARTIT_BYTE), msg_limits)\n\n\n\tdef HandleProtocolCommands(self, split_data, msg_limits):\n\t\tassert(type(split_data) == list)\n\t\tassert(type(split_data[-1]) == str)\n\n\t\tmsg_length_limit = msg_limits['msglength']\n\t\tcheck_msg_limits = (not ('disabled' in msg_limits))\n\n\t\t## either a list of commands, or a list of encrypted data\n\t\t## blobs which may contain embedded (post-decryption) NLs\n\t\t##\n\t\t## note: will be empty if len(split_data) == 1\n\t\traw_data_blobs = split_data[: len(split_data) - 1]\n\n\t\t## will be a single newline in most cases, or an incomplete\n\t\t## command which should be saved for a later time when more\n\t\t## data is in buffer\n\t\tself.data = split_data[-1]\n\n\t\tcommands_buffer = []\n\n\t\tdef check_message_timestamp(msg):\n\t\t\tctr = str_to_int32(msg)\n\n\t\t\tif (ctr <= self.incoming_msg_ctr):\n\t\t\t\treturn False\n\n\t\t\tself.incoming_msg_ctr = ctr\n\t\t\treturn True\n\n\t\tfor raw_data_blob in raw_data_blobs:\n\t\t\tif (len(raw_data_blob) == 0):\n\t\t\t\tcontinue\n\n\t\t\tif (self.use_secure_session()):\n\t\t\t\tdec_data_blob = decrypt_auth_message(self.aes_cipher_obj, raw_data_blob, self.use_msg_auth_codes())\n\n\t\t\t\t## can only happen in case of an invalid MAC or missing timestamp\n\t\t\t\tif (len(dec_data_blob) < 4):\n\t\t\t\t\tcontinue\n\n\t\t\t\t## handle an encrypted client command, using the AES session key\n\t\t\t\t## previously exchanged between client and server by SETSHAREDKEY\n\t\t\t\t## (this includes LOGIN and REGISTER, key can be set before login)\n\t\t\t\t##\n\t\t\t\t## this assumes (!) a client message to be of the form\n\t\t\t\t## ENCODE(ENCRYPT_AES(\"CMD ARG1 ARG2 ...\", AES_KEY))\n\t\t\t\t## where ENCODE is the standard base64 encoding scheme\n\t\t\t\t##\n\t\t\t\t## if this is not the case (e.g. if a command was sent UNENCRYPTED\n\t\t\t\t## by client after session-key exchange) the decryption will yield\n\t\t\t\t## garbage and command will be rejected\n\t\t\t\t##\n\t\t\t\t## NOTE:\n\t\t\t\t## blocks of encrypted data are always base64-encoded and will be\n\t\t\t\t## separated by newlines, but after decryption might contain more\n\t\t\t\t## embedded newlines themselves (e.g. if encryption was performed\n\t\t\t\t## over *batches* of plaintext commands)\n\t\t\t\t##\n\t\t\t\t## client --> C=ENCODE(ENCRYPT(\"CMD1 ARG11 ARG12 ...\\nCMD2 ARG21 ...\\n\"))\n\t\t\t\t## server --> DECRYPT(DECODE(C))=\"CMD1 ARG11 ARG12 ...\\nCMD2 ARG21 ...\\n\"\n\t\t\t\t##\n\t\t\t\t## ignore any replayed messages\n\t\t\t\tif (not check_message_timestamp(dec_data_blob[0: 4])):\n\t\t\t\t\tcontinue\n\n\t\t\t\tsplit_commands = dec_data_blob[4: ].split(DATA_PARTIT_BYTE)\n\t\t\t\tstrip_commands = [(cmd.rstrip('\\r')).lstrip(' ') for cmd in split_commands]\n\t\t\telse:\n\t\t\t\tif (raw_data_blob[0] == DATA_MARKER_BYTE):\n\t\t\t\t\tcontinue\n\n\t\t\t\t## strips leading spaces and trailing carriage returns\n\t\t\t\tstrip_commands = [(raw_data_blob.rstrip('\\r')).lstrip(' ')]\n\n\t\t\tcommands_buffer += strip_commands\n\n\t\tfor command in commands_buffer:\n\t\t\tif (check_msg_limits and (len(command) > msg_length_limit)):\n\t\t\t\tself.Send('SERVERMSG message-length limit (%d) exceeded: command \\\"%s...\\\" dropped.' % (msg_length_limit, command[0: 8]))\n\t\t\telse:\n\t\t\t\tself.HandleProtocolCommand(command)\n\n\tdef HandleProtocolCommand(self, cmd):\n\t\t## probably caused by trailing newline (\"abc\\n\".split(\"\\n\") == [\"abc\", \"\"])\n\t\tif (len(cmd) <= 1):\n\t\t\treturn\n\n\t\tself._protocol._handle(self, cmd)\n\n\n\tdef Remove(self, reason='Quit'):\n\t\twhile self.msg_sendbuffer:\n\t\t\tself.FlushBuffer()\n\t\tself.handler.finishRemove(self, reason)\n\n\t##\n\t## send data to client\n\t##\n\tdef Send(self, data, batch = True):\n\t\t## don't append new data to buffer when client gets removed\n\t\tif ((not data) or self.removing):\n\t\t\treturn\n\n\t\tif (self.handler.thread == thread.get_ident()):\n\t\t\tdata = self.msg_id + data\n\n\t\t## this *must* always succeed (protocol operates on\n\t\t## unicode internally, but is otherwise fully ASCII\n\t\t## and will never send raw binary data)\n\t\tif (type(data) == unicode):\n\t\t\tdata = data.encode(UNICODE_ENCODING)\n\n\t\tassert(type(data) == str)\n\n\t\tdef wrap_encrypt_sign_message(raw_msg):\n\t\t\traw_msg = int32_to_str(self.outgoing_msg_ctr) + raw_msg\n\t\t\tenc_msg = encrypt_sign_message(self.aes_cipher_obj, raw_msg, self.use_msg_auth_codes())\n\n\t\t\tself.outgoing_msg_ctr += 1\n\t\t\treturn enc_msg\n\n\t\tbuf = \"\"\n\n\t\tif (self.use_secure_session()):\n\t\t\t## buffer encrypted data until we get client ACK\n\t\t\t## (the most recent message will be at the back)\n\t\t\t##\n\t\t\t## note: should not normally contain anything of\n\t\t\t## value, server has little to send before LOGIN\n\t\t\tself.enc_sendbuffer.append(data)\n\n\t\t\tif (self.get_session_key_received_ack()):\n\t\t\t\tself.enc_sendbuffer.reverse()\n\n\t\t\t\t## encrypt everything in the queue\n\t\t\t\t## message order in reversed queue is newest to\n\t\t\t\t## oldest, but we pop() from the back so client\n\t\t\t\t## receives in proper order\n\t\t\t\tif (batch):\n\t\t\t\t\twhile (len(self.enc_sendbuffer) > 0):\n\t\t\t\t\t\tbuf += (self.enc_sendbuffer.pop() + DATA_PARTIT_BYTE)\n\n\t\t\t\t\t## batch-encrypt into one blob (more efficient)\n\t\t\t\t\tbuf = wrap_encrypt_sign_message(buf)\n\t\t\t\telse:\n\t\t\t\t\twhile (len(self.enc_sendbuffer) > 0):\n\t\t\t\t\t\tbuf += wrap_encrypt_sign_message(self.enc_sendbuffer.pop() + DATA_PARTIT_BYTE)\n\n\t\telse:\n\t\t\tbuf = data + DATA_PARTIT_BYTE\n\n\t\tif (len(buf) == 0):\n\t\t\treturn\n\n\t\tself.msg_sendbuffer.append(buf)\n\t\tself.handler.poller.setoutput(self.conn, True)\n\n\n\tdef FlushBuffer(self):\n\t\t# client gets removed, delete buffers\n\t\tif self.removing:\n\t\t\tself.msg_sendbuffer = []\n\t\t\tself.sendingmessage = None\n\t\t\treturn\n\t\tif not self.sendingmessage:\n\t\t\tmessage = ''\n\t\t\twhile not message:\n\t\t\t\tif not self.msg_sendbuffer: # just in case, since it returns before going to the end...\n\t\t\t\t\tself.handler.poller.setoutput(self.conn, False)\n\t\t\t\t\treturn\n\t\t\t\tmessage = self.msg_sendbuffer.pop(0)\n\t\t\tself.sendingmessage = message\n\t\tsenddata = self.sendingmessage# [:64] # smaller chunks interpolate better, maybe base this off of number of clients?\n\t\ttry:\n\t\t\tsent = self.conn.send(senddata)\n\t\t\tself.sendingmessage = self.sendingmessage[sent:] # only removes the number of bytes sent\n\t\texcept UnicodeDecodeError:\n\t\t\tself.sendingmessage = None\n\t\t\tself._root.console_write('Error sending unicode string, message dropped.')\n\t\texcept socket.error, e:\n\t\t\tif e == errno.EAGAIN:\n\t\t\t\treturn\n\t\t\tself.msg_sendbuffer = []\n\t\t\tself.sendingmessage = None\n\t\t\n\t\tself.handler.poller.setoutput(self.conn, bool(self.msg_sendbuffer or self.sendingmessage))\n\t\n\t# Queuing\n\t\n\tdef AddUser(self, user):\n\t\tif type(user) in (str, unicode):\n\t\t\ttry: user = self._root.usernames[user]\n\t\t\texcept: return\n\t\tsession_id = user.session_id\n\t\tif session_id in self.users: return\n\t\tself.users.add(session_id)\n\t\tself._protocol.client_AddUser(self, user)\n\t\n\tdef RemoveUser(self, user):\n\t\tif type(user) in (str, unicode):\n\t\t\ttry: user = self._root.usernames[user]\n\t\t\texcept: return\n\t\tsession_id = user.session_id\n\t\tif session_id in self.users:\n\t\t\tself.users.remove(session_id)\n\t\t\tself._protocol.client_RemoveUser(self, user)\n\t\n\tdef SendUser(self, user, data):\n\t\tif type(user) in (str, unicode):\n\t\t\ttry: user = self._root.usernames[user]\n\t\t\texcept: return\n\t\tsession_id = user.session_id\n\t\tif session_id in self.users:\n\t\t\tself.Send(data)\n\t\n\tdef AddBattle(self, battle):\n\t\tbattle_id = battle.id\n\t\tif battle_id in self.battles: return\n\t\tself.battles.add(battle_id)\n\t\tself._protocol.client_AddBattle(self, battle)\n\t\n\tdef RemoveBattle(self, battle):\n\t\tbattle_id = battle.id\n\t\tif battle_id in self.battles:\n\t\t\tself.battles.remove(battle_id)\n\t\t\tself._protocol.client_RemoveBattle(self, battle)\n\t\n\tdef SendBattle(self, battle, data):\n\t\tbattle_id = battle.id\n\t\tif battle_id in self.battles:\n\t\t\tself.Send(data)\n\t\n\tdef isAdmin(self):\n\t\treturn ('admin' in self.accesslevels)\n\t\n\tdef isMod(self):\n\t\treturn self.isAdmin() or ('mod' in self.accesslevels) # maybe cache these\n\n"
}
] | 10 |
EstaticShark/Manga-Scraper | https://github.com/EstaticShark/Manga-Scraper | fc44d8b0f1c347bbb31f2b0ff33f3791c3f47227 | c26764e9176ece099ad44c61decbd0c550841661 | 6ac14f47e9d35b424d9c30a0da682a9de93e85bc | refs/heads/master | 2020-04-04T20:28:14.730796 | 2018-11-10T04:08:30 | 2018-11-10T04:08:30 | 156,247,902 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6480686664581299,
"alphanum_fraction": 0.6875536441802979,
"avg_line_length": 25.785715103149414,
"blob_id": "254ddf670c40a34da3cc32a868e5b8c24c33e920",
"content_id": "8db33dcae360a0a73dfa2b57bcfd046c8fbe6679",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1165,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 42,
"path": "/Manga Scraper.py",
"repo_name": "EstaticShark/Manga-Scraper",
"src_encoding": "UTF-8",
"text": "'''\r\nThis current structure for the code won't work and needs to be further thought about\r\n'''\r\n\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport time\r\n\r\nurl = 'http://kissmanga.com/Manga/Kumika-no-Mikaku/Vol--003-Ch-021----Infectious-Fluttering?id=450419'\r\nheaders = {'User Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}\r\nbrowser = webdriver.Chrome()\r\n\r\nbrowser.get(url)\r\n\r\ntime.sleep(5)\r\n\r\nprint(\"Start Soup\")\r\n\r\nsource = browser.page_source\r\n#print(source)\r\n\r\n\r\nhtml_index = source.find('<img onerror=\"onErrorImg(this)\" onload=\"onLoadImg(this);\" src=\"')\r\nshort_source = source[html_index:]\r\n\r\nprint(html_index)\r\n\r\nif html_index != -1:\r\n html_index = 0\r\n\r\nwhile html_index != -1:\r\n link_index = html_index+len('<img onerror=\"onErrorImg(this)\" onload=\"onLoadImg(this);\" src=\"')\r\n print('Link:',short_source[link_index:short_source.find('\"',link_index)])\r\n\r\n html_index = short_source.find('<img onerror=\"onErrorImg(this)\" onload=\"onLoadImg(this);\" src=\"', link_index)\r\n\r\n\r\n#print(html_index)\r\n#print(short_source)\r\n\r\nprint('End Soup')"
}
] | 1 |
mtt5179/pythontextgame | https://github.com/mtt5179/pythontextgame | 692de21099cc2fbe6df4793631c653b325af1c8f | bdce60917158e1ecb229a4c708b4bdb8d711a49f | 00246369c24491390395978f66fb223d62dc33b6 | refs/heads/master | 2021-01-01T18:50:12.187799 | 2017-07-27T13:51:50 | 2017-07-27T13:51:50 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5721992254257202,
"alphanum_fraction": 0.5885632038116455,
"avg_line_length": 35.110389709472656,
"blob_id": "86bf08a07753bcfe21fde8d971c8463777dbe666",
"content_id": "90501d1edb586cc3c4ccb57e8bb79a9fa1c7ec62",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5561,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 154,
"path": "/rewrite.py",
"repo_name": "mtt5179/pythontextgame",
"src_encoding": "UTF-8",
"text": "import random\n\nclass Monster():\n def __init__(self, name, health, attack, defense, level):\n self.name = name\n self.health = health\n self.attack = attack\n self.defense = defense\n self.level = level\n\n\n# This is where you define the monsters\nGreen_Blob = Monster(\"Green Blob\", 100, 5, 2, \"1\")\nRed_Blob = Monster(\"Red Blob\", 100, 5, 2, \"2\")\nBlue_Blob = Monster(\"Blue Blob\", 100, 5, 2, \"3\")\nYellow_Blob = Monster(\"Yellow Blob\", 100, 5, 2, \"4\")\nBlack_Blob = Monster(\"Black Blob\", 100, 5, 2, \"5\")\n\n# Monster loop this will define if there's a monster in the room or not\n\ndef make_monster():\n monster_in = random.randrange(3)\n if monster_in == (0 or 1):\n return 0\n monster = random.randrange(5)\n if monster == 0:\n monster = Green_Blob\n elif monster == 1:\n monster = Red_Blob\n elif monster == 2:\n monster = Blue_Blob\n elif monster == 3:\n monster = Yellow_Blob\n elif monster == 4:\n monster = Black_Blob\n return monster\n\n# Currently in working progress the battle system\ndef attack_emeny():\n monster = make_monster()\n while mychar.health > 0:\n print(\"what move you like to make?\")\n answer = input()\n if answer == \"attack\":\n if monster.health <= 0:\n break\n monster.health = monster.health - (5 + mychar.attack - monster.defense)\n mychar.health = mychar.health - (monster.attack - mychar.defense)\n print(\"Monster health:\",monster.health);print(\"Character health:\",mychar.health)\n elif answer == \"flee\":\n print(\"you ran.. fgt\")\n break\n\nclass Room(object):\n def __init__(self, name, description, monster_y_n):\n self.name = name\n self.description = description\n self.monster_y_n = monster_y_n\n if self.monster_y_n == \"y\":\n monster = make_monster()\n self.monster = monster\n\n# Room coordinates are as follows (north, east, south, west)\nroom1 = Room(\"Bedroom\", \"You are you in your own bedroom.\\nTo the south, there is a garden past the back door.\", \"n\")\nroom2 = Room(\"Garden\",\n \"You are in a garden with many flowers and a narrow stone path. \\nTo the north, you see the backdoor of your house that enters your bedroom.\\nA pathway leads west.\",\n \"y\")\nroom3 = Room(\"Pathway\",\n \"You are in a narrow stone path with hedges on both sides of you.\\nTo the east, there is a garden.\", \"y\")\n# Room coordinates (had to create all the rooms to assign them to coordinates)\nroom1.coordinates = [0, 0, room2, 0]\nroom2.coordinates = [room1, 0, 0, room3]\nroom3.coordinates = [0, room2, 0, 0]\n\nclass Character(object):\n def __init__(self, name, health, attack, defense, location = room1):\n self.name = name\n self.health = health\n self.attack = attack\n self.defense = defense\n self.location = location\n self.inv = []\n\n def look(self):\n place = self.location\n print(place.description)\n if place.monster_y_n == \"y\":\n if place.monster != 0:\n room_monster = place.monster\n print(\"There is a\", room_monster.name, \"in the room\\n\")\n attack_emeny()\n\n# This is where the main loop starts\nwhoami = input(\"input name:\\n\")\nprint(\"choose a class:\")\nprint(\"warrior: HP: high - Atk: mid - Def: mid\")\nprint(\"mage: HP: low - Atk: high - Def: mid\")\nprint(\"theif: HP: mid - Atk: mid - Def: low\")\ncondition = True\nwhile condition:\n pickclass = input()\n if pickclass == \"warrior\":\n mychar = Character(whoami, 150, 5, 5)\n condition = False\n elif pickclass == \"mage\":\n mychar = Character(whoami, 100, 10, 5)\n condition = False\n elif pickclass == \"theif\":\n mychar = Character(whoami, 120, 5, 3)\n condition = False\n elif pickclass != \"warrior\" or pickclass != \"mage\" or pickclass != \"theif\":\n print(\"Please input again\")\n\nprint(\"hello\", mychar.name)\nprint(\"Welcome to a very simple python text based game\")\nprint(\"Type commands for a list of commands.\")\nprint(\"good luck!\")\nwhile True:\n command = input(\"\")\n if command == \"commands\" or command == \"command\":\n print('\"n\",\"e\",\"s\", and \"w\" make your character go north, east, south, and west respectively')\n print('\"end\" to break')\n print('\"look\" to look around the room')\n print('\"players\" to see the player list')\n print(\"if there's a monster just type attack or flee\")\n if command == \"look\":\n mychar.look()\n if command == (\"n\" or \"north\"):\n if mychar.location.coordinates[0] == 0:\n print(\"You cannot go that way.\")\n else:\n mychar.location = mychar.location.coordinates[0]\n mychar.look()\n if command == (\"e\" or \"east\"):\n if mychar.location.coordinates[1] == 0:\n print(\"You cannot go that way.\")\n else:\n mychar.location = mychar.location.coordinates[1]\n mychar.look()\n if command == (\"s\" or \"south\"):\n if mychar.location.coordinates[2] == 0:\n print(\"You cannot go that way.\")\n else:\n mychar.location = mychar.location.coordinates[2]\n mychar.look()\n if command == (\"w\" or \"west\"):\n if mychar.location.coordinates[3] == 0:\n print(\"You cannot go that way.\")\n else:\n mychar.location = mychar.location.coordinates[3]\n mychar.look()\n if command == \"end\":\n print(\"Thanks for playing!\")\n break\n"
}
] | 1 |
chris-hutch/DBScanDroid | https://github.com/chris-hutch/DBScanDroid | 5950e21c2873914670eca187364680b4140cbfa7 | 561dac627f86c0e34c6bf329226e29c2f98ee995 | e902b20c096457d509f256bf118f6d2a5b98c178 | refs/heads/master | 2020-03-27T02:28:56.511462 | 2018-08-23T05:47:34 | 2018-08-23T05:47:34 | 145,793,628 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6483539342880249,
"alphanum_fraction": 0.6626127362251282,
"avg_line_length": 41.96396255493164,
"blob_id": "562896d4cc8e7d8a5d7b2319f131117a1e91e859",
"content_id": "7c5a6b344527dbe9b923df40032f110eaa91b1fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4769,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 111,
"path": "/dbscan_android_malware.py",
"repo_name": "chris-hutch/DBScanDroid",
"src_encoding": "UTF-8",
"text": "from scipy.spatial.distance import pdist, squareform\nfrom sklearn.decomposition import TruncatedSVD\n\nimport utils\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import vstack, csr_matrix\nfrom collections import OrderedDict\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.feature_extraction import DictVectorizer\n\n\ndef create_sha256_dict(ground_truth_dest):\n apk_sha256_dict = dict()\n\n with open(ground_truth_dest, mode='r') as family_sha256_csv:\n reader = csv.DictReader(family_sha256_csv)\n for row in reader:\n apk_sha256_dict[row['sha256']] = row['family']\n\n return apk_sha256_dict\n\n\ndef construct_feature_vector_matrix(vocab: OrderedDict,\n feature_vector_hashes: list,\n apk_sha256_map: dict,\n feature_vector_parent: str):\n feature_vectors = csr_matrix((1, len(vocab)), dtype=bool)\n # Transform vectorizer over vocab to effectively generate a dictionary\n vectorizer = DictVectorizer(sort=False)\n vectorizer.fit_transform(vocab)\n\n #### Necessary to create the ground_truth indexes\n n_families = []\n for hashes in feature_vector_hashes:\n n_families.append(apk_sha256_map.get(hashes))\n n_families_without_none = list(filter(None.__ne__, n_families))\n family_mapping = {\"Benign\": 0}\n family_mapping_n = ({family: v for v, family in enumerate(np.unique(n_families_without_none), 1)})\n family_mapping.update(family_mapping_n)\n y_ground_truth = []\n for idx, apk in enumerate(feature_vector_hashes):\n apk_feature_data = utils.build_feature_vectors(apk, feature_vector_parent)\n # Assign value of 1 in dictionary for feature vectors\n apk_feature_dictionary = {feature: 1 for feature in apk_feature_data}\n\n # Transform feature dictionary over fitted to produce a binary feature vector\n # 1 means that the feature is there, otherwise a 0\n feature_vector = vectorizer.transform(apk_feature_dictionary)\n\n feature_vectors = vstack([feature_vectors, feature_vector])\n if apk not in apk_sha256_map:\n y_ground_truth.append(family_mapping[\"Benign\"])\n else:\n y_ground_truth.append(family_mapping[apk_sha256_map[apk]])\n # Delete the first row as it was required to create the csr_matrix\n utils.delete_row_csr(feature_vectors, 0)\n\n return feature_vectors, y_ground_truth\n\n\ndef compute_jaccard_distance_matrix(feature_vectors: csr_matrix):\n return squareform(pdist(feature_vectors.todense(), metric='jaccard'))\n\n'''\n Run DBSCAN\n'''\ndef run_dbscan_and_plot(eps, min_pts, distance_matrix, y_ground_truth):\n db = DBSCAN(eps=eps, min_samples=min_pts, metric='precomputed').fit(distance_matrix)\n labels = db.labels_\n core_samples = np.zeros_like(labels, dtype=bool)\n core_samples[db.core_sample_indices_] = True\n n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n print('Estimated number of clusters: %d' % n_clusters_)\n unique_labels = set(labels)\n colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))\n X_embedded = TruncatedSVD(n_components=2).fit_transform(distance_matrix)\n for k, col in zip(unique_labels, colors):\n if k == -1:\n # Black used for noise.\n col = 'k'\n class_member_mask = (labels == k)\n xy = X_embedded[class_member_mask & ~core_samples]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=6)\n xy = X_embedded[class_member_mask & core_samples]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,\n markeredgecolor='k', markersize=8)\n plt.title('Estimated number of clusters: {}. MinPts: {}, Epsilon: {}'.format(n_clusters_, min_pts, eps))\n plt.show()\n print(\"Adjusted Rand Index: %0.3f\"\n % metrics.adjusted_rand_score(y_ground_truth, labels))\n print(\"Adjusted Mutual Information: %0.3f\"\n % metrics.adjusted_mutual_info_score(y_ground_truth, labels))\n print(\"Purity: %0.3f\"\n % utils.purity_score(np.asarray(y_ground_truth), labels))\n print(\"Silhouette Coefficient: %0.3f\"\n % metrics.silhouette_score(distance_matrix, labels))\n\n\ndef print_dataset_stats(feature_vector_hashes, apk_sha256_dict, vocab):\n n_families = []\n for hashes in feature_vector_hashes:\n n_families.append(apk_sha256_dict.get(hashes))\n n_families = [x for x in n_families if x is not None]\n print(np.unique(n_families))\n print(\"Malware families in ground truth {}\".format(len(np.unique(n_families))))\n print(\"Malicious Apps: {}\".format(len(n_families)))\n print(\"Features: {}\".format(len(vocab)))\n"
},
{
"alpha_fraction": 0.469696968793869,
"alphanum_fraction": 0.6818181872367859,
"avg_line_length": 15.5,
"blob_id": "8aeddf0d362d37acf7fd2606b4fea0abe5167f47",
"content_id": "ab6c6361d87f141b02fa37a807bbce38e895fbd4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 66,
"license_type": "no_license",
"max_line_length": 20,
"num_lines": 4,
"path": "/requirements.txt",
"repo_name": "chris-hutch/DBScanDroid",
"src_encoding": "UTF-8",
"text": "matplotlib==2.2.3\nnumpy==1.15.1\nscipy==1.1.0\nscikit_learn==0.19.2\n"
},
{
"alpha_fraction": 0.6006020903587341,
"alphanum_fraction": 0.6106372475624084,
"avg_line_length": 45.348838806152344,
"blob_id": "6bacecf3fcdf559e3529a427f3db4f8853fe25c6",
"content_id": "ce7698d59adb48cb3f6562248cd6cc7dd1d3d94b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1993,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 43,
"path": "/main.py",
"repo_name": "chris-hutch/DBScanDroid",
"src_encoding": "UTF-8",
"text": "\nimport dbscan_android_malware as dbs\nimport utils\nimport argparse\n\n\ndef main(data_hashes_dest, percentage_sample, ground_truth_dest, feature_vector_parent):\n\n apk_sha256_dict = dbs.create_sha256_dict(ground_truth_dest)\n\n feature_vector_hashes = utils.get_feature_vector_hashes(data_hashes_dest,\n percentage_sample,\n apk_sha256_dict,\n ground_truth_dest,\n leave_out_benign=False,\n only_fake_installer=False,\n top_three_malware=False)\n\n vocabulary = utils.build_vocab(feature_vector_hashes, feature_vector_parent)\n\n feature_vector_matrix, ground_truth = dbs.construct_feature_vector_matrix(\n vocabulary, feature_vector_hashes, apk_sha256_dict, feature_vector_parent\n )\n jaccard_distance_matrix = dbs.compute_jaccard_distance_matrix(feature_vector_matrix)\n\n min_pts = 30\n eps = 0.46\n\n utils.plot_knn_values(jaccard_distance_matrix, [min_pts], eps)\n\n dbs.run_dbscan_and_plot(eps, min_pts, jaccard_distance_matrix, ground_truth)\n\n dbs.print_dataset_stats(feature_vector_hashes, apk_sha256_dict, vocabulary)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Run DBScanDroid')\n parser.add_argument(\"data_hashes_dest\", help=\"Destination of application hash list\")\n parser.add_argument(\"percentage_sample\", help=\"Percentage of data sample to take\")\n parser.add_argument(\"ground_truth_dest\", help=\"Destination of ground truth csv\")\n parser.add_argument(\"feature_vector_parent\", help=\"Directory name where feature vector parent\")\n\n args = parser.parse_args()\n\n main(args.data_hashes_dest, args.percentage_sample, args.ground_truth_dest, args.feature_vector_parent)"
},
{
"alpha_fraction": 0.7974388599395752,
"alphanum_fraction": 0.8044237494468689,
"avg_line_length": 56.33333206176758,
"blob_id": "73ba18157b68568354e846e76eca33a6e88b38e5",
"content_id": "da39bdeda9c26b49db06994a16092157fe61e5ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 859,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 15,
"path": "/README.md",
"repo_name": "chris-hutch/DBScanDroid",
"src_encoding": "UTF-8",
"text": "# DBScanDroid\n####Shedding light on the application of Density-Based Clustering to Android Malware\n\nThis repository contains the code necessary to run DBScan against the Drebin Dataset\n\n##Usage\nThe following parameters are required to run this program (in order):\n* data_hashes_destination = file destination of text file containing sha256 hash identifers for apks\n* percentage_sample = (currently not optional) what percentage of the passed data_hashes would you like to use\n* grouth_truth_dest = file destination of sah256 to malware family\n* feature_vector_parent = containing directory of the location of feature vectors for each application\n\nThis application requires access to the Drebin dataset and must be accessible to this script.\n\nNB: The Drebin dataset has not been included and should be requested from https://www.sec.cs.tu-bs.de/~danarp/drebin/"
},
{
"alpha_fraction": 0.5556384325027466,
"alphanum_fraction": 0.5785154700279236,
"avg_line_length": 42.71195602416992,
"blob_id": "afcdc3a5cea0a70073d6b2edc382cd01d1804dec",
"content_id": "787076ea7f9f6362003672dc42c3df5c251813a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8043,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 184,
"path": "/utils.py",
"repo_name": "chris-hutch/DBScanDroid",
"src_encoding": "UTF-8",
"text": "import operator\nfrom collections import OrderedDict\nfrom itertools import dropwhile\nfrom sklearn.neighbors import NearestNeighbors\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\nimport numpy as np\n\ndef get_feature_vector_hashes(data_split: str,\n percent_to_retrieve: float,\n apk_sha256_dict: dict,\n ground_truth_dest: str,\n leave_out_benign=False,\n only_fake_installer=False,\n top_three_malware=False,\n minimum_applications_per_malware_family=10):\n\n\n ground_truth = np.loadtxt(ground_truth_dest, delimiter=\",\", skiprows=1, dtype=str)\n\n def _top_three_malware():\n with open(data_split, mode='r') as data:\n feature_vector_hashes = []\n\n for line in data:\n if len(feature_vector_hashes) >= (128994 * percent_to_retrieve):\n break\n\n if line.rsplit() in ground_truth[:, 0]:\n feature_vector_hashes.append(line.rsplit()[0])\n\n apk_sha256_dict_adjust = {k: apk_sha256_dict[k] for k in feature_vector_hashes if k in apk_sha256_dict}\n family_count = Counter(apk_sha256_dict_adjust.values())\n\n family_count = sorted(family_count.items(), key=operator.itemgetter(1), reverse=True)\n family_count = family_count[0:3]\n apk_sha256_dict_adjust = {\n k: apk_sha256_dict_adjust[k] for k in apk_sha256_dict_adjust.keys()\n if apk_sha256_dict_adjust[k] in\n [i[0] for i in family_count]\n }\n\n return list(apk_sha256_dict_adjust.keys())\n\n def _weighted_benign_fake_installer():\n with open(data_split, mode='r') as split_1:\n feature_vector_hashes = []\n\n for line in split_1:\n if len(feature_vector_hashes) >= (128994 * percent_to_retrieve):\n break\n\n if line.rsplit() not in ground_truth[:, 0]:\n feature_vector_hashes.append(line.rsplit()[0])\n\n apk_sha256_dict_adjust = {k: apk_sha256_dict[k] for k, v in apk_sha256_dict.items() if v == \"FakeInstaller\"}\n apk_sha256_dict_adjust = {k: apk_sha256_dict_adjust[k] for k in sorted(apk_sha256_dict_adjust.keys())[:50]}\n feature_vector_hashes.extend(list(apk_sha256_dict_adjust.keys()))\n return feature_vector_hashes\n\n if only_fake_installer:\n return _weighted_benign_fake_installer()\n elif top_three_malware:\n return _top_three_malware()\n else:\n with open(data_split, mode='r') as split_1:\n feature_vector_hashes = []\n\n for line in split_1:\n if len(feature_vector_hashes) >= (128994 * percent_to_retrieve):\n break\n\n feature_vector_hashes.append(line.rsplit()[0])\n\n apk_sha256_dict_adjust = {k: apk_sha256_dict[k] for k in feature_vector_hashes if k in apk_sha256_dict}\n family_count = Counter(apk_sha256_dict_adjust.values())\n\n for key, count in dropwhile(lambda key_count: key_count[1] >= minimum_applications_per_malware_family, family_count.most_common()):\n del family_count[key]\n\n if leave_out_benign:\n return list(apk_sha256_dict_adjust.keys())\n else:\n for hash in feature_vector_hashes:\n if hash in ground_truth[:, 0]:\n if hash not in apk_sha256_dict_adjust:\n feature_vector_hashes.remove(hash)\n\n return feature_vector_hashes\n\n\ndef build_feature_vectors(file: str, feature_vector_parent: str):\n application_feature_set = []\n\n with open(feature_vector_parent + \"/\" + file) as file_feature_vectors:\n for line in [line.rstrip() for line in file_feature_vectors]:\n split_line = line.split(\"::\")\n # Avoid operating on empty lines which don't contain feature and identifier\n if not len(split_line) == 2:\n continue\n\n if split_line[0] in [\"activity\", \"service_receiver\", \"provider\", \"intent\", \"permission\", \"feature\"]:\n application_feature_set.append(split_line[1])\n\n return application_feature_set\n\n\ndef build_vocab(*files, feature_vector_parent=None):\n\n hardware_comp_dict = {} # S1\n requested_perms_dict = {} # S2\n app_components = {} # S3\n intent_filter_dict = {} # S4\n all_feature_dict = OrderedDict()\n\n for idxx, arg in enumerate(files):\n for idxy, file in enumerate(arg):\n with open(feature_vector_parent + \"/\" + file) as file_feature_vectors:\n for line in [line.rstrip() for line in file_feature_vectors]:\n split_line = line.split(\"::\")\n feature_set_identifier = split_line[0]\n # Avoid operating on empty lines which don't contain feature and identifier\n if not len(split_line) == 2:\n continue\n if feature_set_identifier == \"activity\" and split_line[1] not in app_components:\n app_components[split_line[1]] = 1\n elif feature_set_identifier == \"service_receiver\" and split_line[1] not in app_components:\n app_components[split_line[1]] = 1\n elif feature_set_identifier == \"provider\" and split_line[1] not in app_components:\n app_components[split_line[1]] = 1\n elif feature_set_identifier == \"intent\" and split_line[1] not in intent_filter_dict:\n intent_filter_dict[split_line[1]] = 1\n elif feature_set_identifier == \"permission\" and split_line[1] not in requested_perms_dict:\n requested_perms_dict[split_line[1]] = 1\n elif feature_set_identifier == \"feature\" and split_line[1] not in hardware_comp_dict:\n hardware_comp_dict[split_line[1]] = 1\n\n all_feature_dict.update(hardware_comp_dict)\n all_feature_dict.update(requested_perms_dict)\n all_feature_dict.update(app_components)\n all_feature_dict.update(intent_filter_dict)\n print(\"Analysed from set ({}) {}/{}\".format(idxx + 1, idxy + 1, len(arg)))\n\n return all_feature_dict\n\n\ndef plot_knn_values(X, k_values, eps=None):\n for k in k_values:\n # K + 1 as neighbours does not count index point whilst DSBSCAN range query does\n nbrs = NearestNeighbors(n_neighbors=k + 1, n_jobs=-1).fit(X)\n distances, indicies = nbrs.kneighbors(X)\n distances = np.sort(distances, axis=0)\n distances = distances[:, k - 1]\n # distances = distances[::-1]\n plt.ylabel('{}-NN Distance'.format(k_values[0]))\n plt.xlabel('Points (application) sorted by distance')\n plt.plot(distances, label=\"k (minPts) = {}\".format(k))\n plt.axhline(y=eps, xmin=0.0, xmax=1.0, linestyle='--', color='k', linewidth=0.8)\n plt.legend()\n plt.show()\n\n\ndef delete_row_csr(mat, i):\n n = mat.indptr[i + 1] - mat.indptr[i]\n if n > 0:\n mat.data[mat.indptr[i]:-n] = mat.data[mat.indptr[i + 1]:]\n mat.data = mat.data[:-n]\n mat.indices[mat.indptr[i]:-n] = mat.indices[mat.indptr[i + 1]:]\n mat.indices = mat.indices[:-n]\n mat.indptr[i:-1] = mat.indptr[i + 1:]\n mat.indptr[i:] -= n\n mat.indptr = mat.indptr[:-1]\n mat._shape = (mat._shape[0] - 1, mat._shape[1])\n\n'''\n Purity score impl -> https://stackoverflow.com/questions/34047540/python-clustering-purity-metric/51672699#51672699\n'''\ndef purity_score(y_true, y_pred):\n # compute contingency matrix (also called confusion matrix)\n confusion_matrix = metrics.confusion_matrix(y_true, y_pred)\n # return purity\n return np.sum(np.amax(confusion_matrix, axis=0)) / np.sum(confusion_matrix)\n"
}
] | 5 |
josevictor95/proyectofinal | https://github.com/josevictor95/proyectofinal | 8ae34c3ddcfc4797b6ad758ca06e12d910edb4e0 | 1b18623897dea4ac2812d228516f2d0cc3e18849 | d3909e247f2fdc85db70a24652316e970ba99d22 | refs/heads/master | 2020-05-25T01:58:30.301704 | 2019-05-20T14:43:08 | 2019-05-20T14:43:08 | 187,568,081 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6262626051902771,
"alphanum_fraction": 0.7020202279090881,
"avg_line_length": 37.79999923706055,
"blob_id": "9b5f4891933c87b4cd12875bfa1bdc17b5f3303b",
"content_id": "91779293f6cd0af9107767acde59f2cf06fa0e61",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 198,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 5,
"path": "/main.py",
"repo_name": "josevictor95/proyectofinal",
"src_encoding": "UTF-8",
"text": "import requests\r\n\r\npayload = {'nombre' : 'Jose', 'apellido':'solares', 'telefono' : '23465709'}\r\nr = requests.post('https://demo2452794.mockable.io/finalprograufm_get', json=payload)\r\nprint(r.text) "
},
{
"alpha_fraction": 0.48840540647506714,
"alphanum_fraction": 0.5049505233764648,
"avg_line_length": 30.61276626586914,
"blob_id": "5997167e2ef6dacc967f72c54c1f53d3892ec5a5",
"content_id": "7f2210a99e15d9e89818e2a745a45a87340fa219",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7676,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 235,
"path": "/proyectofinal(FINAL1).py",
"repo_name": "josevictor95/proyectofinal",
"src_encoding": "UTF-8",
"text": "from operator import itemgetter\r\nimport csv\r\nimport time\r\n\r\nn = itemgetter('nombre')\r\na = itemgetter('apellido')\r\nt = itemgetter('telefono')\r\ni = itemgetter('id')\r\n\r\nwith open(r'C:\\Users\\Jose Victor Miron\\Documents\\proyectofinalprogra\\contactos.csv') as csvfile:\r\n\r\n contactos = []\r\n\r\n reader = csv.reader(csvfile)\r\n\r\n for row in reader:\r\n\r\n user = {}\r\n\r\n user[\"id\"] = row[0]\r\n user[\"nombre\"] = row[1]\r\n user[\"apellido\"] = row[2]\r\n user[\"telefono\"] = row[3]\r\n\r\n contactos.append(user)\r\n\r\n\r\nclass C:\r\n def ListContacts(self):\r\n contactos.sort(key = a)\r\n for item in contactos:\r\n print(item['id'],'.', item['nombre'], item['apellido'], item['telefono'])\r\nc = C()\r\n\r\nclass B:\r\n def AddContacts(self):\r\n d = {}\r\n for i in range(1):\r\n keys = 'id'\r\n keys1 = 'nombre'\r\n keys2 = 'apellido'\r\n keys3 = 'telefono'\r\n values = input('ingrese un id: ')\r\n values1 = input(\"ingrese nombre: \")\r\n values2 = input(\"ingrese apellido: \")\r\n values3 = input(\"ingrese telefono: \") \r\n d[keys] = values\r\n d[keys1] = values1\r\n d[keys2] = values2\r\n d[keys3] = values3\r\n contactos.append(d)\r\nb = B()\r\n\r\nclass D:\r\n def DelContacts(self):\r\n delnombre = input(\"ingrese el nombre de la persona que desea eliminar: \")\r\n delapellido = input(\"ingrese el apellido de la persona que desea eliminar: \")\r\n for i in range(len(contactos)): \r\n if (contactos[i]['nombre'] == delnombre) and (contactos[i]['apellido'] == delapellido): \r\n del contactos[i] \r\n break\r\nd = D()\r\n\r\nclass E:\r\n def CallContact(self):\r\n seleccion = input(\"seleccione el id del contacto que desea llamar: \")\r\n for i in range(len(contactos)): \r\n if contactos[i]['id'] == seleccion: \r\n print(\"llamando a: \",contactos[i]['nombre'],contactos[i]['apellido'])\r\n print(\"telefono:\",contactos[i]['telefono'])\r\n print(\"Llamando... \")\r\n time.sleep(10)\r\n break\r\ne = E()\r\n\r\nclass F:\r\n def MsgContacts(self):\r\n seleccion = input(\"seleccione el id del contacto al que desea mandar un mensaje: \")\r\n for i in range(len(contactos)): \r\n if contactos[i]['id'] == seleccion: \r\n print(\"To: \",contactos[i]['nombre'],contactos[i]['apellido'],\"(\",contactos[i]['telefono'],\")\")\r\n print(\"Msg: Feliz Dia!\")\r\n print(\"enviando mensaje... \")\r\n time.sleep(5)\r\n break\r\nf = F()\r\n\r\nclass G:\r\n def AddToFavorites(self):\r\n \r\n lst = [] \r\n n = int(input(\"Ingrese el numero de personas que desea agregar a favoritos(maximo 5): \")) \r\n\r\n for i in range(0, n): \r\n ele = input(\"ingrese el nombre del contacto: \")\r\n \r\n lst.append(ele) \r\n \r\n if n == 5:\r\n var1, var2, var3, var4, var5 = itemgetter(0, 1, 2, 3, 4)(lst)\r\n a = [d for d in contactos if d['nombre'] == lst[0]]\r\n b = [d for d in contactos if d['nombre'] == lst[1]] \r\n c = [d for d in contactos if d['nombre'] == lst[2]] \r\n d = [d for d in contactos if d['nombre'] == lst[3]] \r\n e = [d for d in contactos if d['nombre'] == lst[4]]\r\n nueva_lista = [a,b,c,d,e]\r\n print(\"Lista de Favoritos: \")\r\n print(nueva_lista) \r\n elif n == 4:\r\n var1, var2, var3, var4 = itemgetter(0, 1, 2, 3)(lst)\r\n a = [d for d in contactos if d['nombre'] == lst[0]]\r\n b = [d for d in contactos if d['nombre'] == lst[1]] \r\n c = [d for d in contactos if d['nombre'] == lst[2]] \r\n d = [d for d in contactos if d['nombre'] == lst[3]] \r\n nueva_lista = [a,b,c,d]\r\n print(\"Lista de Favoritos: \")\r\n print(nueva_lista) \r\n elif n == 3:\r\n var1, var2, var3 = itemgetter(0, 1, 2)(lst)\r\n a = [d for d in contactos if d['nombre'] == lst[0]]\r\n b = [d for d in contactos if d['nombre'] == lst[1]] \r\n c = [d for d in contactos if d['nombre'] == lst[2]] \r\n nueva_lista = [a,b,c]\r\n print(\"Lista de Favoritos: \")\r\n print(nueva_lista) \r\n elif n == 2:\r\n var1, var2 = itemgetter(0, 1)(lst)\r\n a = [d for d in contactos if d['nombre'] == lst[0]]\r\n b = [d for d in contactos if d['nombre'] == lst[1]] \r\n nueva_lista = a,b\r\n print(\"Lista de Favoritos: \")\r\n print(nueva_lista) \r\n elif n == 1:\r\n var1 = itemgetter(0)(lst)\r\n a = [d for d in contactos if d['nombre'] == lst[0]] \r\n nueva_lista = [a]\r\n print(\"Lista de Favoritos: \")\r\n print(nueva_lista) \r\ng = G()\r\n\r\nclass H:\r\n def GetFavoriteList(self):\r\n nueva_lista.sort(key = a)\r\n for item in nueva_lista:\r\n print(item['id'],'.', item['nombre'], item['apellido'], item['telefono'])\r\nh = H()\r\n\r\nclass I:\r\n def RemoveFromFavorite(self):\r\n delnombre = input(\"ingrese el nombre de la persona que desea eliminar: \")\r\n delapellido = input(\"ingrese el apellido de la persona que desea eliminar: \")\r\n for i in range(len(nueva_lista)): \r\n if (nueva_lista[i]['nombre'] == delnombre) and (nueva_lista[i]['apellido'] == delapellido): \r\n del nueva_lista[i] \r\n break\r\ni = I()\r\n\r\nclass J:\r\n def loadFromFile(self):\r\n with open(r'C:\\Users\\Jose Victor Miron\\Documents\\proyectofinalprogra\\contactos2.csv') as csvfile:\r\n\r\n reader = csv.reader(csvfile)\r\n\r\n for row in reader:\r\n\r\n user2 = {}\r\n\r\n user2[\"id\"] = row[0]\r\n user2[\"nombre\"] = row[1]\r\n user2[\"apellido\"] = row[2]\r\n user2[\"telefono\"] = row[3]\r\n\r\n contactos.append(user2)\r\nj = J()\r\n\r\nclass K:\r\n def PostToHTTP(self):\r\n import requests\r\n\r\n payload = contactos\r\n r = requests.post('https://demo2452794.mockable.io/finalprograufm_get', json=payload)\r\n print(r.text)\r\nk = K() \r\n\r\nclass Q:\r\n def GetHTTP(self):\r\n import requests\r\n\r\n payload = contactos\r\n r = requests.get('https://demo2452794.mockable.io/finalprograufm_get', json=payload)\r\nq = Q()\r\n\r\n\r\nhdt = False\r\nwhile hdt == False:\r\n print(\"CONTACT MANAGER\")\r\n print(\"Que desea hacer? \")\r\n print(\"1. Ver lista de contactos.\")\r\n print(\"2. Agregar contacto.\")\r\n print(\"3. Eliminar contacto.\")\r\n print(\"4. Llamar contacto.\")\r\n print(\"5. Enviar mensaje a contacto.\")\r\n print(\"6. Agregar a lista de favoritos.\")\r\n print(\"7. Ver lista favoritos.\")\r\n print(\"8. Eliminar favoritos.\")\r\n print(\"9. Agregar archivo externo a lista.\")\r\n print(\"10. POST to HTTP.\")\r\n print(\"11. GET HTTP\")\r\n print(\"12. Salir.\")\r\n seleccion = int(input())\r\n \r\n if seleccion == 1:\r\n c.ListContacts()\r\n if seleccion == 2:\r\n b.AddContacts()\r\n if seleccion == 3:\r\n d.DelContacts()\r\n if seleccion == 4:\r\n e.CallContact()\r\n if seleccion == 5:\r\n f.MsgContacts()\r\n if seleccion == 6:\r\n g.AddToFavorites()\r\n if seleccion == 7:\r\n h.GetFavoriteList()\r\n if seleccion == 8:\r\n i.RemoveFromFavorite()\r\n if seleccion == 9:\r\n j.loadFromFile()\r\n if seleccion == 10:\r\n k.PostToHTTP()\r\n if seleccion == 11:\r\n q.GetHTTP()\r\n if seleccion == 12:\r\n hdt = True\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
}
] | 2 |
ddalton002/ddalton002stuff | https://github.com/ddalton002/ddalton002stuff | 0b17c99a85b51cf5cac88d27bd3d3c4648a5f55b | 41f0bda0c1d36e58d9013fda31a54ade3a7d0d9a | 4861a8dbfcf861ef202a42403b628c5f85fdcec1 | refs/heads/master | 2022-12-09T18:16:25.233267 | 2017-12-15T06:08:33 | 2017-12-15T06:08:33 | 50,391,186 | 0 | 2 | null | 2016-01-26T00:29:29 | 2017-12-15T06:09:21 | 2022-12-08T00:43:11 | Python | [
{
"alpha_fraction": 0.6115657687187195,
"alphanum_fraction": 0.6306601166725159,
"avg_line_length": 20.821428298950195,
"blob_id": "3e8bf302ade8df643d717f1d5debb58b3f80f8a7",
"content_id": "bfb93ec1e347152a489e5cb3054d5da00fd83511",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1833,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 84,
"path": "/Topic 4/Lab 3/lab_23_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_23_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #23 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include \"bst_node.h\"\n// To test for correct header guards\n#include \"bst_node.h\"\n\nTEST_CASE(\"Default Constructor\") {\n const BSTNode const_node;\n BSTNode node;\n BSTNode* p_node = &node;\n SECTION(\"Contents const Accessor\") {\n CHECK(const_node.contents() == 0);\n }\n\n SECTION(\"Contents Accessor (Editable)\") {\n node.contents() = 10;\n CHECK(node.contents() == 10);\n }\n\n SECTION(\"Left Child const Accessor\") {\n CHECK(const_node.left_child() == NULL);\n }\n\n SECTION(\"Left Child Accessor (Editable)\") {\n node.left_child() = &node;\n CHECK(node.left_child() == p_node);\n }\n\n SECTION(\"Right Child const Accessor\") {\n CHECK(const_node.right_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor (Editable\") {\n node.right_child() = &node;\n CHECK(node.right_child() == p_node);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor\") {\n BSTNode node(99);\n SECTION(\"Contents Accessor\") {\n CHECK(node.contents() == 99);\n }\n\n SECTION(\"Left Child Accessor\") {\n CHECK(node.left_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor\") {\n CHECK(node.right_child() == NULL);\n }\n}\n\n\nTEST_CASE(\"Testing Pointers\") {\n BSTNode node1;\n BSTNode node2(99);\n BSTNode node3(-1);\n // node 2 is leftChild, node 3 is rightChild\n node1.set_left_child(&node2);\n node1.set_right_child(&node3);\n SECTION(\"Left Child Mutator\") {\n CHECK(node1.left_child() == &node2);\n }\n\n SECTION(\"Right Child Mutator\") {\n CHECK(node1.right_child() == &node3);\n }\n\n // Change the contents of left child via root\n node1.left_child()->set_contents(10);\n\n SECTION(\"Contents Mutator\") {\n CHECK(node2.contents() == 10);\n }\n}\n"
},
{
"alpha_fraction": 0.5866108536720276,
"alphanum_fraction": 0.5907949805259705,
"avg_line_length": 25.962406158447266,
"blob_id": "38e28978112b1a38e476d94fafe95cf2d5225ebd",
"content_id": "373c053dd16f92e7e5b776cf2a2deb10c19766a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3585,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 133,
"path": "/Topic 2/Assignment 2/bank_account.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bank_account.h\n * Author : David Dalton\n * Description : Bank Account class header file\n */\n \n#ifndef BANK_H\n#define BANK_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::stringstream;\nusing std::setfill;\nusing std::setw;\nusing std::setprecision;\nusing std::fixed;\n\nclass BankAccount\n{\n public:\n /*\n * Constructor, uses default values if none given on creation\n */\n BankAccount(string account_name = \"account\", long dollars = 0, \n int cents = 0, string last_transaction = \"none\");\n /*\n * Destructor\n *unused\n */\n virtual ~BankAccount();\n /*\n * Mutator\n *sets all values in the recent_transactions array to \"none\"\n *sets the value of last_transaction to 0, 0 and \"none\"\n */\n void ClearRecentTransactions();\n /*\n * Mutator\n *sets the value of account_name_ to the input string\n */\n void SetAccountName(string account_name);\n /*\n * Mutator\n *sets the value of dollars_ to the input long value\n */\n void SetDollars(long dollars);\n /*\n * Mutator\n *sets the value of _cents to the input int value\n */\n void SetCents(int cents);\n /*\n * Mutator\n *sets the value of of last_transaction to the input long, int and string\n *values\n */\n void SetLastTransaction(long transaction_dollars, \n int transaction_cents, \n string last_transaction);\n /*\n * Mutator\n *sets the recent_transaction array at a designated location to the input\n *long, int and string value\n */\n void SetRecentTransactions(long transaction_dollars = 0, \n int transaction_cents = 0, \n string transaction = \"\");\n /*\n * Mutator\n *adds the input long to the current value of dollars_ and the input int\n *to the current value of the input int then stores the new values back\n *into the dollars_ and cents_\n */\n void DepositAccount(long dollars = 0, int cents = 0);\n /*\n * Mutator\n *subtracts the value of the input long from dollars_ and subtracts the \n *value of the input int from cents_ then stores the updated values back\n *into dollars_ and cents_\n */\n void WithdrawAccount(long dollars = 0, int cents = 0);\n /*\n * Accessor\n *gets the value of account_name_ and returns it\n */\n string GetAccountName();\n /*\n * Accessor\n *gets the value of dollars_ and returns it\n */\n long GetDollars();\n /*\n * Accessor\n *gets the value of cents_ and returns it\n */\n int GetCents();\n /*\n * Accessor\n *gets the value of last_transaction_ and returns it\n */\n string GetLastTransaction();\n /*\n * Accessor\n *gets the value of recent_transaction_ and the specified index and \n *returns it\n */\n string GetRecentTransactions(int transaction_id = 0);\n /*\n * Accessor\n *combines the value of dollars_ and cents_ into a string stream with\n *specified characters then returns the string\n */\n string ShowBalance();\n \n private:\n const int kArray_size_ = 10;\n string account_name_;\n long dollars_;\n int cents_;\n string last_transaction_;\n string recent_transactions_[10];\n};\n\n#endif"
},
{
"alpha_fraction": 0.48158496618270874,
"alphanum_fraction": 0.5712471604347229,
"avg_line_length": 25.97260284423828,
"blob_id": "9a59c67ab3550fc846714074edda6a87e6367f44",
"content_id": "02131320b3564f875b56d1f8c3dc22d8b00d35ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3937,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 146,
"path": "/Topic 2/lab 3/lab_11_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_11_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #11 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <sstream>\n#include <streambuf>\nusing std::cout;\nusing std::endl;\n\n#include \"money.h\"\n// To test for correct Header Guards\n#include \"money.h\"\n\nTEST_CASE(\"Overloaded + Operator\") {\n Money amount1(123, 45), amount2(10, 9);\n SECTION(\"Money(123, 45) + Money(10, 9), i.e $123.45 + $10.09\") {\n Money sum = amount1 + amount2;\n CHECK(sum.dollars() == 133);\n CHECK(sum.cents() == 54);\n }\n\n SECTION(\"Money(-8, -75) + Money(0, 50), i.e $-8.75 + $0.50\") {\n amount1.set_dollars(-8);\n amount1.set_cents(-75);\n amount2.set_dollars(0);\n amount2.set_cents(50);\n Money sum = amount1 + amount2;\n CHECK(sum.dollars() == -8);\n CHECK(sum.cents() == -25);\n }\n}\n\nTEST_CASE(\"Overloaded Binary - Operator\") {\n Money amount1(123, 45), amount2(10, 9);\n\n SECTION(\"Money(123, 45) - Money(10, 9), i.e $123.45 - $10.09\") {\n Money diff = amount1 - amount2;\n CHECK(diff.dollars() == 113);\n CHECK(diff.cents() == 36);\n }\n\n SECTION(\"Money(10, 9) - Money(123, 45), i.e $10.09 - $123.45\") {\n Money diff = amount2 - amount1;\n CHECK(diff.dollars() == -113);\n CHECK(diff.cents() == -36);\n }\n\n SECTION(\"Money(-8, -75) - Money(0, 50), i.e $-8.75 - $0.50\") {\n amount1.set_dollars(-8);\n amount1.set_cents(-75);\n amount2.set_dollars(0);\n amount2.set_cents(50);\n Money diff = amount1 - amount2;\n CHECK(diff.dollars() == -9);\n CHECK(diff.cents() == -25);\n }\n\n SECTION(\"Money(0, 50) - Money(-8, -75), i.e $0.50 - $-8.75\") {\n amount1.set_dollars(-8);\n amount1.set_cents(-75);\n amount2.set_dollars(0);\n amount2.set_cents(50);\n Money diff = amount2 - amount1;\n CHECK(diff.dollars() == 9);\n CHECK(diff.cents() == 25);\n }\n}\n\nTEST_CASE(\"Overloaded Unary - Operator\") {\n SECTION(\"-Money(123, 45), i.e -$123.45\") {\n Money amount(123, 45);\n amount = -amount;\n CHECK(amount.dollars() == -123);\n CHECK(amount.cents() == -45);\n }\n\n SECTION(\"-Money(9, 25), i.e -$-9.25\") {\n Money amount(-9, -25);\n amount = -amount;\n CHECK(amount.dollars() == 9);\n CHECK(amount.cents() == 25);\n }\n}\n\nTEST_CASE(\"Overloaded == Operator\") {\n SECTION(\"Money(10, 55) == Money(10, 55), i.e $10.55 == $10.55\") {\n Money amount1(10, 55), amount2(10, 55);\n CHECK(amount1 == amount2);\n }\n\n SECTION(\"Money(-10, -55) == Money(-10, -55), i.e $-10.55 == $-10.55\") {\n Money amount1(-10, -55), amount2(-10, -55);\n CHECK(amount1 == amount2);\n }\n\n SECTION(\"Money(10, 55) == Money(-10, -55), i.e $10.55 == $-10.55\") {\n Money amount1(10, 55), amount2(-10, -55);\n CHECK((amount1 == amount2) == false);\n }\n}\n\nTEST_CASE(\"Overloaded << Operator\") {\n SECTION(\"cout << Money(0, 10), i.e $0.10\") {\n Money money(0, 10);\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream capture_cout;\n cout.rdbuf(capture_cout.rdbuf());\n cout << money;\n cout.rdbuf(old_cout);\n CHECK(capture_cout.str() == \"$0.10\");\n }\n\n SECTION(\"cout << Money(0, -10), i.e $-0.10\") {\n Money money(0, -10);\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream capture_cout;\n cout.rdbuf(capture_cout.rdbuf());\n cout << money;\n cout.rdbuf(old_cout);\n CHECK(capture_cout.str() == \"$-0.10\");\n }\n\n SECTION(\"cout << Money(100, 2), i.e $100.02\") {\n Money money(100, 2);\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream capture_cout;\n cout.rdbuf(capture_cout.rdbuf());\n cout << money;\n cout.rdbuf(old_cout);\n CHECK(capture_cout.str() == \"$100.02\");\n }\n\n SECTION(\"cout << Money(-100, -2), i.e $-100.02\") {\n Money money(-100, -2);\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream capture_cout;\n cout.rdbuf(capture_cout.rdbuf());\n cout << money;\n cout.rdbuf(old_cout);\n CHECK(capture_cout.str() == \"$-100.02\");\n }\n}"
},
{
"alpha_fraction": 0.6514851450920105,
"alphanum_fraction": 0.6851485371589661,
"avg_line_length": 24.299999237060547,
"blob_id": "fa37e98886127ac04c513d013b310b15ae84ff2f",
"content_id": "a31af2fc956f38db6b95497599a72f076fcfdcf8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 505,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 20,
"path": "/Topic 1/lab 2/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "# makefile example for CSCI 21\n# uses the catch unit test framework to test lab 2\n\n#name of the executable file\nall: lab2test\n\n#creates the executable from the object files\nlab2test: lab_2_unit_test.o lab_2.o\n g++ -Wall -g -o lab2test lab_2.o lab_2_unit_test.o\n \n#creates the lab2 object file\nlab2: lab2.cpp\n g++ -Wall -g -c lab_2.cpp\n \n# creates the unit test object file\nlab2_unittest: lab2_unittest.cpp\n g++ -Wall -g -c lab_2_unit_test.cpp\n \n \n# to run the make file,t ype inmake."
},
{
"alpha_fraction": 0.5258620977401733,
"alphanum_fraction": 0.5637931227684021,
"avg_line_length": 27,
"blob_id": "3a8a93597fc38a4a1a8d79e015900042d313244a",
"content_id": "d0d7ad2006928770173cd3015db7e42c69529d59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 580,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 20,
"path": "/CSCI465v5old/firstapp/migrations/0006_suggestion_choice_field.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.5 on 2017-12-04 08:41\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('firstapp', '0005_remove_suggestion_choice_field'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='suggestion',\r\n name='choice_field',\r\n field=models.CharField(choices=[('LFG', 'Lfg'), ('LFM', 'Lfm'), ('WTB', 'Wtb'), ('WTS', 'Wts')], default='LFG', max_length=3),\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.5547511577606201,
"alphanum_fraction": 0.6036199331283569,
"avg_line_length": 20.456310272216797,
"blob_id": "01805a15cd3e93d6a3c28e488ebaeed26097893b",
"content_id": "1ce53441d28deab3a975493bdd20130d23b5f698",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2210,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 103,
"path": "/Topic 4/Lab 2/lab_22_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_22_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #22 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_22.h\"\n\n\n\nTEST_CASE(\"Factorial\") {\n SECTION(\"Factorial(0)\") {\n CHECK(Factorial(0) == 1);\n }\n\n SECTION(\"Factorial(1)\") {\n CHECK(Factorial(1) == 1);\n }\n\n SECTION(\"Factorial(2)\") {\n CHECK(Factorial(2) == 2);\n }\n\n SECTION(\"Factorial(5)\") {\n CHECK(Factorial(5) == 120);\n }\n}\n\nTEST_CASE(\"Fibonacci\") {\n SECTION(\"Fibonacci(0)\") {\n CHECK(Fibonacci(0) == 0);\n }\n\n SECTION(\"Fibonacci(1)\") {\n CHECK(Fibonacci(1) == 1);\n }\n\n SECTION(\"Fibonacci(2)\") {\n CHECK(Fibonacci(2) == 1);\n }\n\n SECTION(\"Fibonacci(3)\") {\n CHECK(Fibonacci(3) == 2);\n }\n\n SECTION(\"Fibonacci(15)\") {\n CHECK(Fibonacci(15) == 610);\n }\n}\n\nTEST_CASE(\"Palindrome\") {\n SECTION(\"WordIsPalindrome(\\\"\\\")\") {\n CHECK(WordIsPalindrome(\"\") == true);\n }\n\n SECTION(\"WordIsPalindrome(\\\"a\\\")\") {\n CHECK(WordIsPalindrome(\"a\") == true);\n }\n\n SECTION(\"WordIsPalindrome(\\\"racecar\\\")\") {\n CHECK(WordIsPalindrome(\"racecar\") == true);\n }\n\n SECTION(\"WordIsPalindrome(\\\"sitonapotatopanotis\\\")\") {\n CHECK(WordIsPalindrome(\"sitonapotatopanotis\") == true);\n }\n\n SECTION(\"WordIsPalindrome(\\\"baseball\\\")\") {\n CHECK(WordIsPalindrome(\"baseball\") == false);\n }\n}\n\nTEST_CASE(\"Array Forwards\") {\n int numbers[5] = { 5, 10, 15, 20, 25 };\n SECTION(\"ArrayForwardsAsString(numbers, 0, 5)\") {\n CHECK(ArrayForwardsAsString(numbers, 0, 5) == \"5 10 15 20 25 \");\n }\n\n SECTION(\"ArrayForwardsAsString(numbers, 3, 5)\") {\n CHECK(ArrayForwardsAsString(numbers, 3, 5) == \"20 25 \");\n }\n\n SECTION(\"ArrayForwardsAsString(numbers, 5, 5)\") {\n CHECK(ArrayForwardsAsString(numbers, 5, 5) == \"\");\n }\n}\n\nTEST_CASE(\"Array Backwards\") {\n int numbers[5] = { 5, 10, 15, 20, 25 };\n SECTION(\"ArrayBackwardsAsString(numbers, 4, 5)\") {\n CHECK(ArrayBackwardsAsString(numbers, 4, 5) == \"25 20 15 10 5 \");\n }\n\n SECTION(\"ArrayBackwardsAsString(numbers, 1, 5)\") {\n CHECK(ArrayBackwardsAsString(numbers, 1, 5) == \"10 5 \");\n }\n\n SECTION(\"ArrayBackwardsAsString(numbers, -1, 5)\") {\n CHECK(ArrayBackwardsAsString(numbers, -1, 5) == \"\");\n }\n}\n"
},
{
"alpha_fraction": 0.7009174227714539,
"alphanum_fraction": 0.7192660570144653,
"avg_line_length": 27.736841201782227,
"blob_id": "b86bb37e928ad5136939d47dda281c5256f0a968",
"content_id": "206765a7066e5c2446b9a4d40bfd57b3ad1bb327",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 545,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 19,
"path": "/Topic 4/Assignment 5/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from objects\nlab25test: assignment_5_unit_test.o bst_node.o bs_tree.o\n\tg++ -Wall -g -o lab2test assignment_5_unit_test.o bst_node.o bs_tree.o\n\n#creates the bs_tree object\nbs_tree: bs_tree.cpp bs_tree.h\n\tg++ -Wall -g -c bs_tree.cpp\n\t\n#creates the bst_node object file\nbst_node: bst_node.cpp bst_node.h\n\tg++ -Wall -g -c bst_node.cpp\n\t\n#creates the lab24 unit test object\nassignment_5_unit_test: assignment_5_unit_test.cpp\n\tg++ -Wall -g -c assignment_5_unit_test.cpp\n\t\n#removes all object files and exe\t\nclean:\n\trm *.o *test"
},
{
"alpha_fraction": 0.5786802172660828,
"alphanum_fraction": 0.5793147087097168,
"avg_line_length": 15.427083015441895,
"blob_id": "df29b67427109b3ba35e3cde785467cc6654ca26",
"content_id": "ea50d1b30900d32d5ebfdea88fb8e6252fe7ec74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1576,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 96,
"path": "/Topic 4/Lab 3/bst_node.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bst_node.h\n * Author : David Dalton\n * Description : Tree lab\n */\n\n#ifndef NODE_H\n#define NODE_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\nclass BSTNode\n{\n public:\n /**\n * sets left_child_ to NULL\n * sets right_child_ to NULL\n * sets contents_ to 0\n */\n BSTNode();\n\n /**\n * \n * has one int parameter for contents\n * sets left_child_ to NULL\n * sets right_child_ to NULL\n * sets contents_ to the value of the parameter\n */\n BSTNode(int value);\n /**\n *\n * sets right_child_ to NULL\n * sets left_child_ to NULL\n */\n ~BSTNode();\n \n /**\n * mutator for contents_\n */\n void set_contents(int contents);\n \n /**\n * accessors for contents_\n */\n int contents() const;\n \n /**\n * accessors for contents_\n */\n int& contents();\n \n /**\n * mutator for left_child_\n */\n void set_left_child(BSTNode* left_child);\n \n /**\n * mutator for right_child_\n */\n void set_right_child(BSTNode* right_child);\n \n /**\n * accessors for left_child_\n */\n BSTNode* left_child() const;\n /**\n * accessors for left_child_\n */\n BSTNode*& left_child();\n \n /**\n * accessors for right_child_\n */\n BSTNode* right_child() const;\n /**\n * accessors for right_child_\n */\n BSTNode*& right_child();\n \n private:\n //points to a left child\n BSTNode* left_child_;\n //points to a right child\n BSTNode* right_child_;\n //used to store the data contents of a BSTNode\n int contents_;\n \n};\n\n#endif"
},
{
"alpha_fraction": 0.529356062412262,
"alphanum_fraction": 0.529356062412262,
"avg_line_length": 14.54411792755127,
"blob_id": "ad02be6348881d8ddc483b867fa247cf1eb70d74",
"content_id": "3472d94857f6c991b7892e169ed31ae231d0aa4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1056,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 68,
"path": "/Topic 3/Assignment 4/dl_node.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: dl_node.h\n * Author: David Dalton\n * Sources:\n */\n \n#ifndef NODE_H\n#define NODE_h\n\n#include <iostream>\n#include <string>\n#include <cstring>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::istream;\n \n/**\n * A DLNode Class for a double linked list\n */\nclass DLNode \n{\n public:\n /**\n * initialize contents to zero, next and previous to NULL\n */\n DLNode();\n /**\n * initialize contents to newContents, next and previous to NULL\n */\n DLNode(int newContents);\n /**\n * nothing to be done\n */\n virtual ~DLNode();\n /**\n * \n */\n void setContents(int newContents);\n /**\n * \n */\n void setNext(DLNode* newNext);\n /**\n * \n */\n void setPrevious(DLNode* newPrevious);\n /**\n * \n */\n int getContents() const;\n /**\n * \n */\n DLNode* getNext() const;\n /**\n * \n */\n DLNode* getPrevious() const;\n \n private:\n DLNode* next_node_;\n DLNode* previous_node_;\n int contents_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6818675398826599,
"alphanum_fraction": 0.684581995010376,
"avg_line_length": 24.943662643432617,
"blob_id": "0e0fe99673cdbf0d43bbb11d92c1da609c8d08b0",
"content_id": "28eadabec67bb95f165eb83f2fe048122aa9753c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1842,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 71,
"path": "/Topic 1/lab 5/lab_5.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_5.h\n * Author : David Dalton\n * Description : Practicing Functions. Use this file to write your\n * Function Prototypes (what goes above main()).\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <streambuf>\n#include <sstream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n/*\n * Function Name: Hello\n *\n * Displays \"Hello world!\" to stdout (cout) (no newline character after)\n */\nvoid Hello();\n\n/*\n * Function Name: PrintMessage\n *\n * Displays the string parameter to stdout (no newline character)\n * @param const string& - The string to display to stdout\n */\nstring PrintMessage(const string& kMessage);\n\n/*\n * Function Name: GetAnswer\n *\n * Returns the integer value 42.\n * @return int - The value 42\n */\nint GetAnswer();\n\n/*\n * Function Name: FindLarger\n *\n * Returns the larger of the two parameter values. Should work correctly\n * if the values are equivalent (returns either one)\n * @param int - The first value\n * @param int - The second value\n * @return int - The larger of the two values, or either one if they are equal\n */\nint FindLarger(int first_value, int second_value);\n\n/*\n * Function Name: BuildMessage\n *\n * Return the string \"Message: STRING\", where STRING is replaced by the value of\n * the first parameter (string). If second parameter (bool) is true, convert\n * first parameter (string) to all uppercase letters before concatenating it\n * with \"Message: \". If first parameter is the empty string, return\n * \"Message: empty\".\n * @param string - A message.\n * - Defaults to \"\" (empty string)\n * @param bool - To indicate if we should uppercase letters or not\n * - Defaults to false\n */\nstring BuildMessage(string message = \"\", bool upper_case = false);\n\n#endif\n"
},
{
"alpha_fraction": 0.5875017642974854,
"alphanum_fraction": 0.6145671010017395,
"avg_line_length": 33.930694580078125,
"blob_id": "d45ceda1705ca88319243d3fb076a4093056602e",
"content_id": "2ff8c467065c5a66bb3235c7380f697d6767f2de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7057,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 202,
"path": "/Topic 4/Assignment 5/assignment_5_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : assignment_5_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test for Templated Binary Search Tree\n */\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include \"bs_tree.h\"\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n// For testing (DO NOT ALTER)\nvoid Test(bool test, string more_info = \"\", string yours = \"!\", string actual =\n \"!\");\nvoid UnitTest();\nunsigned int ut_passed = 0, ut_failed = 0, ut_total = 0;\n\n// Program Execution Starts Here\nint main() {\n // To test your code (DO NOT ALTER)\n UnitTest();\n // This ends program execution\n return 0;\n}\n\n// For testing (DO NOT ALTER)\nvoid UnitTest() {\n string temp = \"This unit test will test some of your code:\\n\";\n cout << temp << \"There are 59 tests.\\n\" << string(temp.length() - 1, '-')\n << endl;\n // Tests\n cout << \"******BSTNodeT<int>******\" << endl;\n BSTNodeT<int> inode1;\n BSTNodeT<int> inode2(99);\n BSTNodeT<int> inode3(-1);\n\n Test(inode1.GetContents() == 0, \"Default Constructor / GetContents()\");\n Test(inode1.GetLeft() == NULL, \"Default Constructor / GetLeft()\");\n Test(inode1.GetRight() == NULL, \"Default Constructor / GetRight()\");\n\n Test(inode2.GetContents() == 99, \"Constructor(99) / GetContents()\");\n Test(inode2.GetLeft() == NULL, \"Constructor(99) / GetLeft()\");\n Test(inode2.GetRight() == NULL, \"Constructor(99) / GetRight()\");\n\n // node 2 is leftChild, node 3 is rightChild\n inode1.SetLeft(&inode2);\n Test(inode1.GetLeft() == &inode2, \"SetLeft() / GetLeft()\");\n inode1.SetRight(&inode3);\n Test(inode1.GetRight() == &inode3, \"SetRight() / GetRight()\");\n\n cout << \"******BSTNodeT<char>******\" << endl;\n BSTNodeT<char> cnode1;\n BSTNodeT<char> cnode2('A');\n BSTNodeT<char> cnode3('a');\n\n Test(cnode1.GetContents() == '\\0', \"Default Constructor / GetContents()\");\n Test(cnode1.GetLeft() == NULL, \"Default Constructor / GetLeft()\");\n Test(cnode1.GetRight() == NULL, \"Default Constructor / GetRight()\");\n\n Test(cnode2.GetContents() == 'A', \"Constructor('A') / GetContents()\");\n Test(cnode2.GetLeft() == NULL, \"Constructor('A') / GetLeft()\");\n Test(cnode2.GetRight() == NULL, \"Constructor('A') / GetRight()\");\n\n // node 2 is leftChild, node 3 is rightChild\n cnode1.SetLeft(&cnode2);\n Test(cnode1.GetLeft() == &cnode2, \"SetLeft() / GetLeft()\");\n cnode1.SetRight(&cnode3);\n Test(cnode1.GetRight() == &cnode3, \"SetRight() / GetRight()\");\n\n cout << \"******BSTNodeT<string>******\" << endl;\n BSTNodeT<string> snode1;\n BSTNodeT<string> snode2(\"Hello\");\n BSTNodeT<string> snode3(\"Goodbye\");\n\n Test(snode1.GetContents() == \"\", \"Default Constructor / GetContents()\");\n Test(snode1.GetLeft() == NULL, \"Default Constructor / GetLeft()\");\n Test(snode1.GetRight() == NULL, \"Default Constructor / GetRight()\");\n\n Test(snode2.GetContents() == \"Hello\",\n \"Constructor(\\\"Hello\\\") / GetContents()\");\n Test(snode2.GetLeft() == NULL, \"Constructor(\\\"Hello\\\") / GetLeft()\");\n Test(snode2.GetRight() == NULL, \"Constructor(\\\"Hello\\\") / GetRight()\");\n\n // node 2 is leftChild, node 3 is rightChild\n snode1.SetLeft(&snode2);\n Test(snode1.GetLeft() == &snode2, \"SetLeft() / GetLeft()\");\n snode1.SetRight(&snode3);\n Test(snode1.GetRight() == &snode3, \"SetRight() / GetRight()\");\n\n cout << \"******BSTreeT<int>******\" << endl;\n\n // Setup the BST\n BSTreeT<int> tree;\n BSTNodeT<int> *tree_pointer;\n string actual = \"\";\n Test(tree.GetSize() == 0, \"Default Constructor / GetSize()\");\n\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n Test(tree.Insert(50) == 1, \"Insert(50)\");\n Test(tree.GetSize() == 1, \"GetSize()\");\n actual = \"50\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n Test(tree.Insert(20) == 1, \"Insert(20)\");\n Test(tree.GetSize() == 2, \"GetSize()\");\n actual = \"20, 50\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n actual = \"50, 20\";\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n Test(tree.Insert(80) == 1, \"Insert(80)\");\n Test(tree.GetSize() == 3, \"GetSize()\");\n actual = \"20, 50, 80\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n actual = \"80, 50, 20\";\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n Test(tree.Insert(80) == 2, \"Insert(80)\");\n Test(tree.GetSize() == 3, \"GetSize()\");\n actual = \"20, 50, 80\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n actual = \"80, 50, 20\";\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n Test(tree.Exists(50) == true, \"Exists(50)\");\n Test(tree.Exists(0) == false, \"Exists(0)\");\n\n tree_pointer = tree.Get(50);\n Test(tree_pointer->GetContents() == 50, \"Get(50)\");\n\n tree_pointer = tree.Get(0);\n Test(tree_pointer == NULL, \"Get(0)\");\n\n Test(tree.Remove(80) == 1, \"Remove(80)\");\n Test(tree.GetSize() == 3, \"GetSize()\");\n actual = \"20, 50, 80\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n actual = \"80, 50, 20\";\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n Test(tree.Remove(80) == 0, \"Remove(80)\");\n Test(tree.GetSize() == 2, \"GetSize()\");\n actual = \"20, 50\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n actual = \"50, 20\";\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n Test(tree.Remove(80) == -1, \"Remove(80)\");\n\n tree.Clear();\n Test(tree.GetSize() == 0, \"Clear() / GetSize()\");\n actual = \"\";\n Test(tree.ToStringForwards() == actual, \"ToStringForwards()\",\n tree.ToStringForwards(), actual);\n Test(tree.ToStringBackwards() == actual, \"ToStringBackwards()\",\n tree.ToStringBackwards(), actual);\n\n cout << string(temp.length() - 1, '-') << endl;\n cout << \"Unit Test Complete!\\n\" << \"Passed: \" << ut_passed << \" / \"\n << ut_total << endl << \"Failed: \" << ut_failed << \" / \" << ut_total\n << endl << endl;\n}\n\n// For testing (DO NOT ALTER)\nvoid Test(bool test, string more_info, string yours, string actual) {\n static int test_number = 1;\n if (test) {\n cout << \"PASSSED TEST \";\n ut_passed++;\n } else {\n cout << \"FAILED TEST \";\n ut_failed++;\n }\n cout << test_number << \" \" << more_info << \"!\" << endl;\n if (!test) {\n if (yours != \"!\")\n cout << \"Yours: \\\"\" << yours << '\"' << endl;\n if (actual != \"!\")\n cout << \"Actual: \\\"\" << actual << '\"' << endl;\n }\n ut_total++;\n test_number++;\n}\n\n"
},
{
"alpha_fraction": 0.6788321137428284,
"alphanum_fraction": 0.7177615761756897,
"avg_line_length": 26.46666717529297,
"blob_id": "147fcf2b63413b7e808ff268a0c0f1605f8efc46",
"content_id": "54c5e29ea2404c7a8e21e62275aad4682265188e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 411,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 15,
"path": "/Topic 4/Lab 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from objects\nlab23test: lab_23_unit_test.o bst_node.o\n\tg++ -Wall -g -o lab2test lab_23_unit_test.o bst_node.o\n\n#creates the bst_node object file\nbst_node: bst_node.cpp bst_node.h\n\tg++ -Wall -g -c bst_node.cpp\n\t\n#creates the lab23 unit test object\nlab_23_unit_test: lab_23_unit_test.cpp\n\tg++ -Wall -g -c lab_23_unit_test.cpp\n\t\n#removes all object files and exe\t\nclean:\n\trm *.o assign4test"
},
{
"alpha_fraction": 0.5143240690231323,
"alphanum_fraction": 0.5572963356971741,
"avg_line_length": 19.69444465637207,
"blob_id": "57590699eb17ab6efb91e88250c79a02ebd1cd8c",
"content_id": "a932f73c1cab309a97fbbe9c56d4b6acf625b6e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2234,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 108,
"path": "/Topic 1/lab 7/lab_8_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_8_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #8 Functionality\n */\n#define CATCH_CONFIG_RUNNER\n#include \"catch.hpp\"\n#include \"lab_7.h\"\nmap<int, int> counters;\nchar* global_argv[8];\nint global_argc;\n\nint main(int argc, char* const argv[]) {\n if (argc > 1 && argc < 9 && strcmp(argv[1], \"teacher\") == 0\n && CheckArgs(argc, argv)) {\n // Put argv values into global array\n for (int i = 0; i < argc; i++) {\n global_argv[i] = argv[i];\n }\n global_argc = argc;\n argc = 2;\n strcpy(argv[1], \"-s\");\n\n // global setup...\n int result = Catch::Session().run(argc, argv);\n\n // global clean-up...\n return result;\n } else {\n cout << \"\\nRun program with the following argument list:\\n\";\n cout << \"\\n\\t\\\"teacher 10 20 30 40 50 60\\\"\\n\";\n cout << \"\\nto run the UNIT TEST.\\n\\n\";\n }\n}\n\nTEST_CASE(\"Counting Command Line Arguments\") {\n counters[10] = 0, counters[20] = 0, counters[30] = 0, counters[40] = 0,\n counters[50] = 0;\n counters[99] = 0;\n ProcessArguments(global_argc, global_argv);\n SECTION(\"Counting 10s\") {\n CHECK(counters[10] == 1);\n }\n SECTION(\"Counting 20s\") {\n CHECK(counters[20] == 1);\n }\n SECTION(\"Counting 30s\") {\n CHECK(counters[30] == 1);\n }\n SECTION(\"Counting 40s\") {\n CHECK(counters[40] == 1);\n }\n SECTION(\"Counting 50s\") {\n CHECK(counters[50] == 1);\n }\n SECTION(\"Counting Errors\") {\n CHECK(counters[99] == 2);\n }\n}\n\nbool CheckArgs(int argc, char* const argv[]) {\n if (argc == 8) {\n // convert the argv[2] to argv[7] contents to integers\n int *temps = new int[6];\n stringstream ss;\n for (int i = 0, j = 2; i < 6; i++, j++) {\n ss.str(argv[j]);\n ss >> temps[i];\n ss.clear();\n }\n\n // check to see that argv[2] to argv[7] match the expected launch\n // UNIT TEST values\n for (int i = 0, j = 10; i < 6; i++, j += 10) {\n if (temps[i] != j)\n return false;\n }\n\n delete[] temps;\n\n return true;\n }\n return false;\n}\n\nvoid OnTen() {\n counters[10]++;\n}\n\nvoid OnTwenty() {\n counters[20]++;\n}\n\nvoid OnThirty() {\n counters[30]++;\n}\n\nvoid OnForty() {\n counters[40]++;\n}\n\nvoid OnFifty() {\n counters[50]++;\n}\n\nvoid OnError() {\n counters[99]++;\n}"
},
{
"alpha_fraction": 0.6623522639274597,
"alphanum_fraction": 0.6674169898033142,
"avg_line_length": 20.95061683654785,
"blob_id": "186bcad84e916a874fc2a8b65dc1646d6f8ed2b3",
"content_id": "a47a8ab07f418b6fdbec74bd13ef8fe68f98b147",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1777,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 81,
"path": "/Topic 2/lab 4/magic_item.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : item.h\n * Author : David Dalton\n * Description : Class Header File\n */\n\n#include \"magic_item.h\"\n\n/*\n * Constructor\n *takes four parameters, one for each private member variable and two for the\n *base class\n *defaults name_ to \"magicitem\"\n *defaults value_ to 0\n *defaults description_ to \"no description\"\n *defaults mana_required_ to 0\n */\nMagicItem::MagicItem(string name, unsigned int value, \n string description, unsigned int mana_required) \n{\n Item::set_name(name);\n Item::set_value(value);\n desciption_ = description;\n mana_required_ = mana_required;\n}\n/*\n *Destructor\n */\nMagicItem::~MagicItem() \n{\n \n}\n/*\n * \n * Mutator #1\n *sets the value of description to the input string\n */\nvoid MagicItem::set_description(string description) \n{\n desciption_ = description;\n}\n/*\n * Mutator #2\n *sets the value of mana_required_ to the input int\n */\nvoid MagicItem::set_mana_required(unsigned int mana_required) \n{\n mana_required_ = mana_required;\n}\n/*\n * Accessor #1\n *retrieves the value of description_\n */\nstring MagicItem::description() \n{\n return desciption_; \n}\n/*\n * Accessor #2\n *retrieves the value of mana_required_\n */\nunsigned int MagicItem::mana_required()\n{\n return mana_required_;\n}\n/*\n *string ToString()\n *returns a string containing name_, value_, desciption_, and\n *mana_required_\n *(uses Item::ToString in its implementation)\n *Format -- name_, $value_, description_, requires mana_required_ mana\n *EXAMPLE -- hat, $10, made of felt, requires 2 mana\n */\nstring MagicItem::ToString()\n{\n stringstream returned_string;\n string base_string = Item::ToString();\n returned_string << base_string << \", \" << desciption_ << \", requires \" \n << mana_required_ << \" mana\";\n return returned_string.str();\n}"
},
{
"alpha_fraction": 0.606501042842865,
"alphanum_fraction": 0.6091437339782715,
"avg_line_length": 31.913043975830078,
"blob_id": "98cdc404dfefb97d7c454af362895981fbee1262",
"content_id": "0cec81d3244a80f3ca7163b543798e1458e751d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3784,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 115,
"path": "/Topic 3/Lab 1/lab_12.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_12.cpp\n * Author : David Dalton\n * Description : Working with Pointers and Dynamic Variables / Arrays\n */\n#include \"lab_12.h\"\n\n/*\n * Allocate memory for a dynamic array of integers.\n * @param unsigned int size - The desired size of the dynamic array\n * @return int* - A pointer to the newly allocated integer array\n */\nint* MakeDynoIntArray(unsigned int size) \n{\n //Creates a dynamic array of a specified size\n int *dyno_array;\n dyno_array = new int[size];\n}\n\n/*\n * Compute the sum of an array.\n * @param int* the_array - The array for which the sum will be computed\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the sum of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Sum(int* the_array, unsigned int array_size) \n{\n //Checks to see if the array is null and throws an error if it is\n if(the_array == NULL)\n {\n throw \"NULL ARRAY REFERENCE\"; \n } else {\n //Creates the variable that holds the sum of the array\n int sum = 0;\n /*\n *Loops through each index in the array and adds it to the sum variable\n */\n for(int i = 0; i < array_size; i++)\n {\n sum += the_array[i];\n }\n //Returns the value of sum\n return sum;\n }\n}\n\n/*\n * Identify the max value in an array.\n * @param int* the_array - The array for which the max value will be identified\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the max value of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Max(int* the_array, unsigned int array_size) \n{\n //Checks to see if the array is null and throws an error if it is\n if(the_array == NULL)\n {\n throw \"NULL ARRAY REFERENCE\"; \n } else {\n //Creates the variable that holds the maximum value of the array\n int max_value = the_array[0];\n /*\n *Loops through each index in the array and compares the value of the \n *current location to the value of max_value. If it is greater it stores\n *it into max value, otherwise it continues looping through the array\n */\n for(int i = 0;i < array_size;i++)\n {\n if(the_array[i] > max_value)\n {\n max_value = the_array[i];\n }\n }\n //Returns the highest value of the array\n return max_value;\n }\n}\n\n/*\n * Identify the min value in an array.\n * @param int* the_array - The array for which the min value will be identified\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the min value of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Min(int* the_array, unsigned int array_size) \n{\n //Checks to see if the array is null and throws an error if it is\n if(the_array == NULL)\n {\n throw \"NULL ARRAY REFERENCE\"; \n } else {\n //Creates the variable that holds the minimum value of the array\n int min_value = the_array[0];\n /*\n *Loops through each index in the array and compares the value of the \n *current location to the value of min_value. If it is smaller it stores\n *it into max value, otherwise it continues looping through the array\n */\n for(int i = 0;i < array_size;i++)\n {\n if(the_array[i] < min_value)\n {\n min_value = the_array[i];\n }\n }\n //Returns the smallest value of the array\n return min_value;\n }\n}"
},
{
"alpha_fraction": 0.6470967531204224,
"alphanum_fraction": 0.6574193835258484,
"avg_line_length": 36.75,
"blob_id": "a94c380cebaca3f7129d39df6d7ed61c353167f6",
"content_id": "09be8e71da534039ba2043e23ecbdc79e7051e3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1550,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 40,
"path": "/CSCI465v5/firstapp/models.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django.db import models\r\nfrom django import forms\r\nfrom django.contrib.auth.models import User\r\nfrom django.db.models.signals import post_save\r\nfrom django.dispatch import receiver\r\n\r\n# Create your models here.\r\nCHOICES = (('LFG', 'Lfg',), ('LFM', 'Lfm',),('WTB', 'Wtb',), ('WTS', 'Wts',))\r\nclass suggestion(models.Model):\r\n suggestion = models.CharField(max_length=141)\r\n author = models.ForeignKey(User, on_delete=models.CASCADE)\r\n authored = models.DateTimeField(auto_now=True)\r\n # LFG = 'Lfg'\r\n # LFM = 'Lfm'\r\n # WTB = 'Wtb'\r\n # WTS = 'Wts'\r\n # CHOICES = ((LFG, 'Lfg',), (LFM, 'Lfm',),(WTB, 'Wtb',), (WTS, 'Wts',))\r\n choice_field = models.CharField(max_length=3, choices=CHOICES,default='LFG')\r\n image = models.ImageField(max_length=144, upload_to='uploads/%Y/%m/%d/')\r\n idescription = models.CharField(max_length=144)\r\n def __str__(self):\r\n return self.suggestion\r\n\r\nclass profile(models.Model):\r\n user = models.OneToOneField(User, on_delete=models.CASCADE)\r\n bio = models.TextField(null=True, max_length=500, blank=True)\r\n games = models.CharField(null=True, max_length=140, blank=True)\r\n birth_date = models.DateField(null=True, blank=True)\r\n\r\n # def __str__(self):\r\n # return self.profile\r\n\r\n@receiver(post_save, sender=User)\r\ndef create_user_profile(sender, instance, created, **kwargs):\r\n if created:\r\n profile.objects.create(user=instance)\r\n\r\n@receiver(post_save, sender=User)\r\ndef save_user_profile(sender, instance, **kwargs):\r\n instance.profile.save()\r\n"
},
{
"alpha_fraction": 0.7308838367462158,
"alphanum_fraction": 0.7428004145622253,
"avg_line_length": 36.296295166015625,
"blob_id": "8b76220771803aacda6c8d3b2b51557a916cf7ad",
"content_id": "d21901e3ad437400d0f16a321b40a9069e23e28d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1007,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 27,
"path": "/Topic 2/Assignment 2/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\natmtest: atm.o bank_account.o checking_account.o savings_account.o credit_account.o\n\tg++ -std=c++11 -Wall -g -o atmtest atm.o bank_account.o checking_account.o savings_account.o credit_account.o\n\n#creates the bank_account object file\t\nbank_account.o: bank_account.cpp bank_account.h\n\tg++ -std=c++11 -Wall -g -c bank_account.cpp\n\n#creates the checking_account object file\nchecking_account.o: checking_account.cpp checking_account.h\n\tg++ -std=c++11 -Wall -g -c checking_account.cpp\n\t\n#creates the savings_account object file\nsavings_account.o: savings_account.cpp savings_account.h\n\tg++ -std=c++11 -Wall -g -c savings_account.cpp\n\n#creates the credit_account object file\ncredit_account.o: credit_account.cpp credit_account.h\n\tg++ -std=c++11 -Wall -g -c credit_account.cpp\n\n#creates the unit test object file\natm.o: atm.cpp CinReader.cpp CinReader.h atm.cpp\n\tg++ -std=c++11 -Wall -g -c atm.cpp CinReader.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6654275059700012,
"alphanum_fraction": 0.6858736276626587,
"avg_line_length": 26.58974266052246,
"blob_id": "e50ed45c6d0699c3a38e06e3a57eff05298689fe",
"content_id": "47ca3266bce93d8fba8bc97ca04d5a9da1f22570",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1076,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 39,
"path": "/Topic 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\n#sl_nodetest: lab_20_unit_test.o sl_list.o sl_node.o\n#\tg++ -Wall -g -o lab2test sl_node.o sl_list.o lab_20_unit_test_luke.o\n\n#creates the node object file\t\n#sl_node.o: sl_node.cpp sl_node.h\n#\tg++ -Wall -g -c sl_node.cpp\n\t\n#creates the list object file\n#sl_list.o: sl_list.cpp sl_list.h\n#\tg++ -Wall -g -c sl_list.cpp\n\n#creates the lab unit test object file\n#lab_20_unit_test.o: lab_20_unit_test_luke.cpp\n#\tg++ -Wall -g -c lab_20_unit_test_luke.cpp\n\n#cleans up old .o files\t\n#clean:\n#\trm *.o *test \n\t\n#creates the executable from all of the object files\nsl_nodetest: lab_20_unit_test.o sl_list.o sl_node.o\n\tg++ -Wall -g -o lab2test sl_node.o sl_list.o lab_20_unit_test.o\n\n#creates the node object file\t\nsl_node.o: sl_node.cpp sl_node.h\n\tg++ -Wall -g -c sl_node.cpp\n\t\n#creates the list object file\nsl_list.o: sl_list.cpp sl_list.h\n\tg++ -Wall -g -c sl_list.cpp\n\n#creates the lab unit test object file\nlab_20_unit_test.o: lab_20_unit_test.cpp\n\tg++ -Wall -g -c lab_20_unit_test.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6728624701499939,
"alphanum_fraction": 0.6776951551437378,
"avg_line_length": 34.880001068115234,
"blob_id": "371721e03be34dc49f71709e9fd1aa2163fde5fc",
"content_id": "737a31ddba55a9a401e52cd08dffcabde837cb86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2690,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 75,
"path": "/Topic 1/lab 6/lab_6.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_6.cpp\n * Author : Luke Sathrum\n * Description : Header File for Lab #6. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n/*\n * Create a string containing the contents of an array, each element separated\n * by a specified character. For example, if the array contents\n * are {1, 2, 3} and the separator character is ':', the string returned\n * will be \"1:2:3\".\n * @uses stringstream\n * @param int values[] - An array of integers\n * @param int size - The size of the integer array\n * @param char separator - The separator character to use in the returned\n * string.\n * Defaults to ','\n * @return string - A string containing the contents of values separated by the\n * specified separator character\n */\nstring PrepareForDisplay(int values[], int size, char separator = ',');\n\n/*\n * Test to see if an array contains a specified value.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int value - The value to search for within the array\n * @return bool - true if value is found in the array, otherwise false\n */\nbool HasValue(int values[], int size, int value);\n\n/*\n * Return the value from an array at a specified index.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int index - The position in the array from which to return a value\n * @param bool &error - A flag that will be set to true if index is invalid for\n * the array, else it will be set to false\n * @return int - The value at the specified index in the array when error is set\n * to false. if index is invalid, returns 0 and sets error to true\n */\nint ValueAt(int values[], int size, int index, bool &error);\n\n/*\n * Return the sum of the values in an integer array.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @return int - The sum of the values in the array\n */\nint Sum(int values[], int size);\n\n/*\n * Swap the positions of two values in an integer array. The two\n * index values must be valid for the array.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int index1 - The position of the first value to be swapped\n * @param int index2 - The position of the second value to be swapped\n * @return bool - true if the swap was successful, otherwise false\n */\nbool SwapValues(int values[], int size, int index1, int index2);\n\n#endif"
},
{
"alpha_fraction": 0.757017970085144,
"alphanum_fraction": 0.76023930311203,
"avg_line_length": 29.19444465637207,
"blob_id": "bba151c48a9bd0144cd88ab3c962e51d764c799e",
"content_id": "11261b362ccaa4730db3cdead726d47c11198ada",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2173,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 72,
"path": "/Topic 1/Assignment 1/assignment_1.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : assignment_1.h\n * Author : David Dalton\n * Description : A program that performs operations on strings and arrays.\n */\n\n#ifndef ASSIGNMENT_1_H\n#define ASSIGNMENT_1_H\n\n// Add any includes and using statements Here\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <streambuf>\n#include <sstream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n\n// Declare Function Prototypes Here (What goes above main)\n/*\nThis function will check to make sure all characters in a given string are\nalphabetic. It returns true if the string is alla lphabetic, otherwise it\nreturns false. The empty string should also return false.\n*/\nbool CheckAlphabetic(const string& kAlphabetic);\n\n/*\nThis function will count the number of words (delimited by space characters) in\na string. Assume the parameter will never have multiple spaces back-to-back and \nwill never begin or end with spaces).\n*/\nint CountWords(string words);\n\n/*\nThis function will perform a Caesar Cipher Shift \n(http://en.wikipedia.org/wiki/Caesar_cipher). If the string contains any \nnon-alpha characters do not performt he encryption and return false. Otherwise\nperform the encryption and return true.\n*/\nbool EncryptString(string& string_encrypted, int characters_shifted);\n\n/*\nThis function decrypts a Caesar Cipher shift. If the string contains any\nnon-alpha characters do not perform the encryption and return false.\nOtherwise perform the encryption and return true.\n*/\nbool DecryptString(string& string_unencrypted, int characters_shifted);\n\n/*\nThis function will compute the mean average of the values in the array. The \narray will always be at least size of 1.\n*/\ndouble ComputeAverage(double input_array[], unsigned int array_size);\n\n/*\nThis function will find and return the smallest value in an array. The array\nwill always be at least of size 1.\n*/\ndouble FindMinValue(double input_array[], unsigned int array_size);\n\n/*\nThis function will find and return the largest value in an array. The array\nwill always be at least of size 1.\n*/\ndouble FindMaxValue(double input[], unsigned int array_size);\n\n\n#endif /* ASSIGNMENT_1_H */"
},
{
"alpha_fraction": 0.6465517282485962,
"alphanum_fraction": 0.6473013758659363,
"avg_line_length": 20.682926177978516,
"blob_id": "582e91f26de270eea23bdcbff3ae98b08c9f1a27",
"content_id": "33b321f18c8cda32410d8e045d340e3c7efe3135",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2668,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 123,
"path": "/Topic 2/lab 5/lab_5.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_5.h\n * Author : David Dalton\n * Description : Class Template Header File and function definition\n */\n \n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <iomanip>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::setfill;\nusing std::setw;\n\n\n/*\nDefine a \"header only\" template class name Box with:\n- one data member -- contents (data type template)\n- overloaded constructor -- one parameter newContents to be assigned to contents\n- getter (getContents) and setter (setContents)\n- friend overloaded operator <<\n*/\n\ntemplate<typename Type>\nclass Box \n{ public:\n /*\n * Constructor\n * @param Type newContents - An initial value to give\n */\n Box(Type newContents);\n /*\n * Accessor\n * @return T - The value of contents_\n */\n Type getContents();\n /*\n * Mutator\n * @param T value - A value to set contents_ to\n */\n void setContents(Type newContents);\n /*\n * Overload of << operator.\n * Outputs the contents to the output stream then retrieves\n * the stream and returns it\n * @param ostream &out - The ostream object to output to\n * @param Box contents - The Box object to output from.\n * @return ostream& - The ostream object to allow for chaining of <<\n */\n friend ostream& operator <<(ostream& out, const Box<Type> &contents) \n {\n out << contents.contents_;\n return out;\n }\n \n \n \n private:\n Type contents_;\n \n \n};\n\n/*\n * Constructor\n * Creates an instance of the class and sets the value of contents_ to the \n * input value, newContents\n * @param Type newContents - An initial value to give\n */\n\ntemplate<typename Type>\nBox<Type>::Box(Type newContents)\n{\n contents_ = newContents;\n}\n/*\n * Accessor\n * retrieves the value of contents_ and returns it\n * @return Type - The value of contents_\n */\ntemplate<typename Type>\nType Box<Type>::getContents() \n{\n return contents_;\n}\n/*\n * Mutator\n * Sets the value of contents_ to the input value, newContents\n * @param Type value - A value to set contents_ to\n */\ntemplate<typename Type>\nvoid Box<Type>::setContents(Type newContents) \n{\n contents_ = newContents;\n}\n\n/*\n * Function Name: Sum\n * Returns the \"sum\" of the values in the array.\n * @param T values - An array of any type\n * @param unsigned int size - The size of the array\n * @return T - The sum of the values in the array\n */\n\ntemplate<typename Type>\nType Sum(Type input_array[], unsigned int array_size)\n{\n Type sum = Type();\n for(int i=0;i<array_size;i++)\n {\n sum += input_array[i];\n }\n return sum;\n}\n\n\n#endif\n\n"
},
{
"alpha_fraction": 0.5627118349075317,
"alphanum_fraction": 0.6058551669120789,
"avg_line_length": 19.66878890991211,
"blob_id": "d23ca9bd2930b8a316799b1acbfc7e2df95f65c6",
"content_id": "1f7cc45843d0681926be73466d5acd709c0db979",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3245,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 157,
"path": "/Topic 3/Assignment 3/assign_3_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : assign_3_unit_test.cpp\n * Author : April Browne\n * Description : Unit test to test Assignment #3 Functionality\n *\t\t\t adaped from Boyd Trolinger\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n//#include \"prize.h\"\n#include \"box.h\"\n\n\nTEST_CASE(\"Make default Box\"){\n Box b1;\n\n SECTION(\"getBoxNumber()\"){\n\tCHECK(b1.getBoxNumber() == 0);\n }\n SECTION(\"getBoxColor()\"){\n \tCHECK(b1.getBoxColor() == \"NO COLOR\");\n }\n SECTION (\"getPrizeCapacity()\"){\n\tCHECK(b1.getPrizeCapacity() == 5);\n }\n SECTION (\"getPrizeCount()\"){\n\tCHECK(b1.getPrizeCount() == 0);\n }\n}\n\nTEST_CASE(\"Default Box Functions\"){\n Box b1;\n b1.setBoxNumber(99);\n b1.setBoxColor(\"red\");\n\n SECTION(\"setBoxNumber(99)\"){\n\tCHECK(b1.getBoxNumber() == 99);\n }\n SECTION(\"setBoxColor(\\\"red\\\")\"){\n\tCHECK(b1.getBoxColor() == \"red\");\n }\t\n}\n\nTEST_CASE(\"Constructor Custom Box\"){\n Box b2(42, \"blue\", 3);\n SECTION (\"getBoxNumber()\"){\n \t CHECK (b2.getBoxNumber() == 42);\n }\n SECTION (\"getBoxColor()\"){\n\t CHECK (b2.getBoxColor() == \"blue\");\n }\n SECTION (\"getPrizeCapacity()\"){\n\t CHECK (b2.getPrizeCapacity() == 3);\n }\n SECTION (\"getPrizeCount()\"){\n \tCHECK (b2.getPrizeCount() == 0);\n }\n}\n\nTEST_CASE (\"Test Prizes\"){\n Box b2(42, \"blue\", 3);\n \n SECTION(\"removePrize(0)\"){\n \tCHECK (b2.removePrize(0) == Prize());\n } \t\n \n b2.addPrize(Prize(\"BRONZE PRIZE\", 1));\n SECTION(\"addPrize(\\\"Bronze\\\")\"){\n\tCHECK (b2.getPrizeCount() == 1);\n }\n \n\tb2.addPrize(Prize(\"SILVER PRIZE\", 100));\n SECTION(\"addPrize(\\\"Silver\\\")\"){\n\tCHECK (b2.getPrizeCount() == 2);\n }\n \n\tb2.addPrize(Prize(\"GOLD PRIZE\", 10000));\n SECTION(\"addPrize(\\\"Gold\\\")\"){\n\tCHECK(b2.getPrizeCount() == 3);\n }\n\n SECTION(\"addPrize(\\\"Diamond\\\")\"){\n\tCHECK(b2.addPrize(Prize(\"DIAMOND PRIZE\", 999)) == false);\n }\n}\n\nTEST_CASE(\"Test Remove and Add Prizes\"){\n\n\n SECTION(\"remove prize and add new prize\"){\n\t Box b2(42, \"blue\", 3);\n b2.addPrize(Prize(\"BRONZE PRIZE\", 1));\n b2.addPrize(Prize(\"SILVER PRIZE\", 100));\n b2.addPrize(Prize(\"GOLD PRIZE\", 10000));\n CHECK(b2.removePrize(2) == Prize(\"GOLD PRIZE\", 10000));\n \tCHECK(b2.addPrize(Prize(\"RUBY PRIZE\", 9999)) == true);\n\tCHECK(b2.getPrizeCount() == 3);\n\t\tCHECK (b2.getPrizeCapacity() == 3);\n }\n \n\n}\n\nTEST_CASE(\"Prize default constructor\"){\n Prize p1;\n\n SECTION(\"getPrizeName()\"){\n\tCHECK(p1.getPrizeName() == \"NO NAME\");\n }\n SECTION(\"getPrizeValue()\"){\n\tCHECK(p1.getPrizeValue() == 0);\n }\n}\n\nTEST_CASE (\"Prize functions\"){\n Prize p1;\n SECTION (\"setPrizeName(\\\"FOOD PRIZE\\\")\"){\n\t p1.setPrizeName(\"FOOD PRIZE\");\n\t CHECK (p1.getPrizeName() == \"FOOD PRIZE\");\n }\n SECTION (\"setPrizeValue(17)\"){\n\t p1.setPrizeValue(17);\n\t CHECK (p1.getPrizeValue() == 17);\n }\n}\n\nTEST_CASE (\"HAT prize\"){\n Prize p2(\"HAT PRIZE\", 50);\n SECTION (\"getPrizeName()\"){\n\t CHECK (p2.getPrizeName() == \"HAT PRIZE\");\n }\n SECTION (\"getPrizeValue()\"){\n\t CHECK (p2.getPrizeValue() == 50);\n }\n}\n\nTEST_CASE (\"Prize 1 vs Prize 2\"){\n\n\n SECTION (\"==\"){\n Prize p1;\n\tp1.setPrizeName(\"FOOD PRIZE\");\n\tp1.setPrizeValue(17);\n Prize p2(\"HAT PRIZE\", 50);\n\tCHECK ((p1 == p2) == false);\n }\n\n\n SECTION (\"== again\"){\n Prize p1;\n\tp1.setPrizeName(\"FOOD PRIZE\");\n\tp1.setPrizeValue(17);\n Prize p2(\"HAT PRIZE\", 50);\n p2.setPrizeValue(1);\n\tCHECK ((p1 == p2) == false);\n }\n}\n"
},
{
"alpha_fraction": 0.5925639271736145,
"alphanum_fraction": 0.5948876738548279,
"avg_line_length": 18.876922607421875,
"blob_id": "97c71b5bb64c3f4f6cb3ed88d979b656217ba14e",
"content_id": "74f070058aefffbd743b115a8d92303df83cfe6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1291,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 65,
"path": "/Topic 3/Assignment 3/prize.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: prize.h\n * Author: David Dalton\n * Sources:\n */\n\n#ifndef PRIZE_H\n#define PRIZE_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\nclass Prize\n{\n public:\n /**\n * Default constructor\n * initial values itemName (\"NO NAME\"), itemValue (0)\n */\n Prize();\n /**\n * Overloaded constructor\n * parameters for all data members\n */\n Prize(string name, unsigned int value);\n /**\n * Deconstructor\n * empty\n */\n ~Prize();\n /**\n * Mutator for prizeName_\n */\n void setPrizeName(string name);\n /**\n * Mutator for prizeValue_\n */\n void setPrizeValue(unsigned int value);\n /**\n * Accessor for prizeName_\n */\n string getPrizeName();\n /**\n * Accessor for prizeValue_\n */\n unsigned int getPrizeValue();\n /**\n * Overloaded operator\n * returns true if the prizeName and prizeValue of the two Prizes being \n * compared are equivalent, else return false\n */\n friend bool operator ==(Prize first_prize, Prize second_prize);\n //friend bool operator ==(const Prize &prize1, const Prize &prize2);\n \n private:\n string prizeName_;\n unsigned int prizeValue_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.5184959769248962,
"alphanum_fraction": 0.5597503185272217,
"avg_line_length": 31.35960578918457,
"blob_id": "bfe6feb3aab1200ab9e8c1499905c84f0ebd09ef",
"content_id": "ff3ac3d2e9bfff0d12596660f1cf404025c4cd0f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6569,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 203,
"path": "/Topic 3/lab_20_unit_test_luke.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_20.cpp\n * Author : Luke Sathrum\n * Description : Unit Test for class SList.\n * THIS FILE SHOUD NOT BE ALTERED, UNLESS DEBUGGING IN MAIN\n */\n\n#include \"sl_list.h\"\n#include \"sl_node.h\"\n\n#include <iostream>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n// For testing (DO NOT ALTER)\n#include <cctype>\n#include <vector>\nvoid UnitTest();\nvoid Test(bool test, int line_number, string more_info = \"\", string yours = \"!\",\n string actual = \"!\");\nvoid OutputFailedTests();\nunsigned int ut_passed = 0, ut_failed = 0, ut_total = 0, num_of_tests = 46;\nstd::vector<int> failed_tests;\n\n// Program Execution Starts Here\nint main() {\n // To test your code (DO NOT ALTER)\n UnitTest();\n // This ends program execution\n return 0;\n}\n\n// For testing (DO NOT ALTER)\nvoid UnitTest() {\n cout << string(40, '-') << endl;\n cout << \"UNIT TEST:\\n\" << string(40, '-') << endl;\n if (num_of_tests != 0)\n cout << \"Total Number of Tests: \" << num_of_tests << endl;\n string yours = \"\", actual = \"\";\n // Tests\n SLList list;\n\n Test(list.size() == 0, __LINE__, \"Default Constructor & size()\");\n yours = list.ToString();\n actual = \"\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n Test(list.GetHead() == 0, __LINE__, \"GetHead()\");\n Test(list.GetTail() == 0, __LINE__, \"GetTail()\");\n\n list.Insert(10);\n Test(list.size() == 1, __LINE__, \"Insert(10) & size()\");\n yours = list.ToString();\n actual = \"10\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(50);\n Test(list.size() == 2, __LINE__, \"Insert(50) & size()\");\n yours = list.ToString();\n actual = \"10, 50\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(30);\n Test(list.size() == 3, __LINE__, \"Insert(30) & size()\");\n yours = list.ToString();\n actual = \"10, 30, 50\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n Test(list.GetHead() == 10, __LINE__, \"GetHead()\");\n Test(list.GetTail() == 50, __LINE__, \"GetTail()\");\n\n list.Insert(5);\n Test(list.size() == 4, __LINE__, \"Insert(5) & size()\");\n yours = list.ToString();\n actual = \"5, 10, 30, 50\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(55);\n Test(list.size() == 5, __LINE__, \"Insert(55) & size()\");\n yours = list.ToString();\n actual = \"5, 10, 30, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(20);\n Test(list.size() == 6, __LINE__, \"Insert(20) & size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 30, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(40);\n Test(list.size() == 7, __LINE__, \"Insert(40) & size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 30, 40, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(30);\n Test(list.size() == 8, __LINE__, \"Insert(30) & size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 30, 30, 40, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(5);\n Test(list.size() == 9, __LINE__, \"Insert(5) & size()\");\n yours = list.ToString();\n actual = \"5, 5, 10, 20, 30, 30, 40, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n list.Insert(55);\n Test(list.size() == 10, __LINE__, \"Insert(55) & size()\");\n yours = list.ToString();\n actual = \"5, 5, 10, 20, 30, 30, 40, 50, 55, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n cout << \"\\nYour List: \" << list.ToString() << endl << endl;\n\n Test(list.RemoveFirstOccurence(1) == false, __LINE__,\n \"RemoveFirstOccurence(1)\");\n\n Test(list.RemoveFirstOccurence(5) == true, __LINE__,\n \"RemoveFirstOccurence(5)\");\n Test(list.size() == 9, __LINE__, \"size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 30, 30, 40, 50, 55, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n Test(list.RemoveFirstOccurence(30) == true, __LINE__,\n \"RemoveFirstOccurence(30)\");\n Test(list.size() == 8, __LINE__, \"size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 30, 40, 50, 55, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n Test(list.RemoveFirstOccurence(30) == true, __LINE__,\n \"RemoveFirstOccurence(30)\");\n Test(list.size() == 7, __LINE__, \"size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 40, 50, 55, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n Test(list.RemoveFirstOccurence(55) == true, __LINE__,\n \"RemoveFirstOccurence(55)\");\n Test(list.size() == 6, __LINE__, \"size()\");\n yours = list.ToString();\n actual = \"5, 10, 20, 40, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n Test(list.RemoveFirstOccurence(10) == true, __LINE__,\n \"RemoveFirstOccurence(10)\");\n Test(list.size() == 5, __LINE__, \"size()\");\n yours = list.ToString();\n actual = \"5, 20, 40, 50, 55\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n Test(list.GetHead() == 5, __LINE__, \"GetHead()\");\n Test(list.GetTail() == 55, __LINE__, \"GetTail()\");\n\n list.Clear();\n Test(list.size() == 0, __LINE__, \"Clear() & size()\");\n yours = list.ToString();\n actual = \"\";\n Test(yours == actual, __LINE__, \"ToString()\", yours, actual);\n\n cout << string(40, '-') << endl;\n cout << \"Passed: \" << ut_passed << \" / \" << ut_total << endl;\n OutputFailedTests();\n cout << string(40, '-') << endl;\n cout << \"END OF UNIT TEST!\\n\";\n cout << string(40, '-') << endl;\n cout << \"Be sure to run 'make style' to check for any style errors.\\n\"\n << \"Please note that 'make style' does NOT check variable names or\"\n << \" indentation\" << endl << endl;\n}\n\n// For testing (DO NOT ALTER)\nvoid Test(bool test, int line_number, string more_info, string yours,\n string actual) {\n ut_total++;\n if (test) {\n cout << \"PASSED TEST \";\n ut_passed++;\n } else {\n cout << \"FAILED TEST \";\n ut_failed++;\n failed_tests.push_back(ut_total);\n }\n cout << ut_total << \" \" << more_info << \"!\" << endl;\n if (!test) {\n if (yours != \"!\")\n cout << \"Yours: \\\"\" << yours << '\"' << endl;\n if (actual != \"!\")\n cout << \"Actual: \\\"\" << actual << '\"' << endl;\n cout << \" Check Line \" << line_number << \" for more info\" << endl;\n }\n}\n\nvoid OutputFailedTests() {\n if (failed_tests.size()) {\n cout << \"Failed test number(s): \";\n for (unsigned int i = 0; i < failed_tests.size() - 1; i++)\n cout << failed_tests.at(i) << \", \";\n cout << failed_tests.at(failed_tests.size() - 1) << endl;\n }\n}\n"
},
{
"alpha_fraction": 0.6977099180221558,
"alphanum_fraction": 0.7129771113395691,
"avg_line_length": 27.434782028198242,
"blob_id": "2ccfe2baee06555d07528b323d2e408deb0b80cc",
"content_id": "8224ba72f06095907abb4baf43f2dda171f49760",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 655,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 23,
"path": "/Topic 2/lab 4/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "\n#creates the executable from both of the object files\nitemtest: lab_10_unit_test.o item.o food_item.o magic_item.o\n\tg++ -Wall -g -o itemtest lab_10_unit_test.o item.o food_item.o magic_item.o\n\n#creates the item object file\t\nitem.o: item.cpp item.h\n\tg++ -Wall -g -c item.cpp\n\n#creates the fooditem object file\nfooditem.o: food_item.cpp food_item.h\n\tg++ -Wall -g -c food_item.cpp\n\t\n#creates the magicitem object file\nmagicitem.o: magic_item.cpp magic_item.h\n\tg++ -Wall -g -c magic_item.cpp\n\n#creates the unit test object file\nlab_10_unit_test.o: lab_10_unit_test.cpp\n\tg++ -Wall -g -c lab_10_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o itemtest "
},
{
"alpha_fraction": 0.6488016843795776,
"alphanum_fraction": 0.6572293639183044,
"avg_line_length": 29.3799991607666,
"blob_id": "dd65c305e01534604f91441cc7deca4b3b080323",
"content_id": "32c9fbdef3dc022a7a002e4c9be717cf6f87cd46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7594,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 250,
"path": "/Topic 2/Assignment 2/bank_account.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bank_account.cpp\n * Author : David Dalton\n * Description : BankAccount function definition\n * Source : Luke Sathrum, modified portions of money lab and item lab\n */\n \n#include \"bank_account.h\"\n \n/*\n * Constructor, uses default values if none given on creation\n */\nBankAccount::BankAccount(string account_name, long dollars, int cents, \n string last_transaction) \n{\n account_name_ = account_name;\n dollars_ = dollars;\n cents_ = cents;\n SetLastTransaction(0,0, last_transaction);\n ClearRecentTransactions();\n}\n/*\n * Destructor, unused\n */\nBankAccount::~BankAccount() \n{\n \n}\n/*\n * Mutator\n *sets all values in the recent_transactions array to \"none\"\n *sets the value of last_transaction to 0, 0 and \"none\"\n */\nvoid BankAccount::ClearRecentTransactions()\n{\n for(int i=0;i<kArray_size_;i++)\n {\n recent_transactions_[i] = \"\";\n }\n SetLastTransaction(0,0,\"none\");\n}\n/*\n * Mutator\n *sets the value of account_name_ to the input string\n */\nvoid BankAccount::SetAccountName(string account_name) \n{\n account_name_ = account_name;\n}\n/*\n * Mutator\n *sets the value of dollars_ to the input long value\n */\nvoid BankAccount::SetDollars(long dollars) \n{\n dollars_ = dollars;\n}\n/*\n * Mutator\n *sets the value of _cents to the input int value\n */\nvoid BankAccount::SetCents(int cents) \n{\n cents_ = cents;\n}\n/*\n * Mutator\n *sets the value of of last_transaction to the input long, int and string\n *values\n */\nvoid BankAccount::SetLastTransaction(long transaction_dollars, \n int transaction_cents, \n string last_transaction) \n{\n stringstream transaction;\n transaction << \"$\" << transaction_dollars << \".\" << transaction_cents \n << \". Transaction type: \" << last_transaction;\n last_transaction_ = transaction.str();\n}\n/*\n * Mutator\n *sets the recent_transaction array at a designated location to the input\n *long, int and string value\n */\nvoid BankAccount::SetRecentTransactions(long transaction_dollars, \n int transaction_cents, string transaction) \n{\n /*\n *creates a storage array to store the current values of recent_transaction\n *in an offset pattern, so that index 0 is empty, index 1 is the value of\n *index 0 in the original array, and the value that was at index 9 in the \n *original array is dropped. It then stores the new transaction value\n *into index 0 of the original array, and sets the rest of the array\n *equal to its matching index value of the storage array\n */\n string storage_array[kArray_size_];\n stringstream transaction_record;\n int transaction_length = (kArray_size_ - 1);\n for(int i = 0; i<transaction_length; i++)\n {\n storage_array[(i+1)] = recent_transactions_[i];\n }\n transaction_record << \"$\" << transaction_dollars << \".\" << transaction_cents \n << \". Transaction type: \" << transaction;\n storage_array[0] = transaction_record.str();\n for(int i = 0;i<kArray_size_;i++)\n {\n recent_transactions_[i] = storage_array[i];\n }\n}\n/*\n * Mutator\n *adds the input long to the current value of dollars_ and the input int\n *to the current value of the input int then stores the new values back\n *into the dollars_ and cents_\n */\nvoid BankAccount::DepositAccount(long dollars, int cents) \n{\n long current_dollars = GetDollars();\n int current_cents = GetCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of deposited amount\n long all_cents2 = cents + dollars * 100;\n // Add all the cents together\n long sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n /* Sets the variables to the new values, and adds them to the transaction\n * record variable\n */\n SetDollars(final_dollars);\n SetCents(final_cents);\n SetLastTransaction(dollars, cents, \"Deposit\");\n SetRecentTransactions(dollars, cents, \"Deposit\");\n \n}\n/*\n * Mutator\n *subtracts the value of the input long from dollars_ and subtracts the \n *value of the input int from cents_ then stores the updated values back\n *into dollars_ and cents_\n */\nvoid BankAccount::WithdrawAccount(long dollars, int cents) \n{\n long current_dollars = GetDollars();\n int current_cents = GetCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of withdrawn amount\n long all_cents2 = cents + dollars * 100;\n //Subtracts object 2 all cents from object 1 all cents\n long sum_all_cents = all_cents1 - all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) \n {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n /* Sets the variables to the new values, and adds them to the transaction\n * record variable\n */\n SetDollars(final_dollars);\n SetCents(final_cents);\n SetLastTransaction(dollars, cents, \"Withdrawl\");\n SetRecentTransactions(dollars, cents, \"Withdrawl\");\n}\n/*\n * Accessor\n *gets the value of account_name_ and returns it\n */\nstring BankAccount::GetAccountName() \n{\n return account_name_;\n}\n/*\n * Accessor\n *gets the value of dollars_ and returns it\n */\nlong BankAccount::GetDollars() \n{\n return dollars_;\n}\n/*\n * Accessor\n *gets the value of cents_ and returns it\n */\nint BankAccount::GetCents() \n{\n return cents_;\n}\n/*\n * Accessor\n *gets the value of last_transaction_ and returns it\n */\nstring BankAccount::GetLastTransaction() \n{\n return last_transaction_;\n}\n/*\n * Accessor\n *gets the value of recent_transaction_ and the specified index and \n *returns it\n */\nstring BankAccount::GetRecentTransactions(int transaction_id) \n{\n return recent_transactions_[transaction_id];\n}\n/*\n * Accessor\n *combines the value of dollars_ and cents_ into a string stream with\n *specified characters then returns the string\n */\nstring BankAccount::ShowBalance() \n{\n /*\n *Gets the absolute value of the objects cents value and stores it into a \n *variable. It then gets the value of the objects dollars_ and cents_\n *variables and checks to see if they are equal to and less than 0. If\n *they are then they send them to an output stream with a negative character\n *otherwise it sends it to the output stream without the negative character.\n *Adds the values of dollars and cents to the output stream separated by a \n *then returns the output stream\n */\n stringstream balance;\n long dollars = GetDollars();\n int cents = GetCents();\n int absolute_cents = abs(cents);\n if((dollars == 0) && (cents < 0))\n {\n balance << \"Your balance is: $-\" << setw(1) << setfill('0') << dollars<< \".\" \n << setfill('0') << setw(2) << absolute_cents;\n } else\n {\n balance << \"Your balance is: $\" << setw(1) << setfill('0') << dollars << \".\" \n << setfill('0') << setw(2) << cents;\n }\n return balance.str();\n}"
},
{
"alpha_fraction": 0.517292857170105,
"alphanum_fraction": 0.5210251212120056,
"avg_line_length": 18.900989532470703,
"blob_id": "eb2e612e525fc9a1dca550188a01dae2995594bf",
"content_id": "36d9d19732eed7259701685db12c493921672e38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4019,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 202,
"path": "/Topic 3/Lab 4/sl_list.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_list.cpp\n * Author : David Dalton\n * Description : Node list lab.\n */\n \n#include \"sl_list.h\"\n /*\n Default Constructor\n --sets head_ to NULL\n --sets tail_ to NULL\n --sets size_ to 0\n */\n SLList::SLList() \n {\n head_ = NULL;\n tail_ = NULL;\n size_ = 0;\n }\n /*\n Destructor\n --calls Clear()\n */\n SLList::~SLList() \n {\n Clear();\n }\n /*\n void InsertHead(int) (*MODIFY*)\n\n\t\t(*NEW*) - Handle tail_ when the first node in the list is added\n void InsertHead(int)\n --creates a new dynamic SLNode with the contents of \n the parameter and attaches as the new head of the list\n */\n void SLList::InsertHead(int insert) \n {\n SLNode* new_node = new SLNode(insert);\n new_node->set_next_node(head_);\n head_ = new_node;\n size_ = size_ + 1;\n /*\n if(tail_ == 1)\n {\n tail_ = head_;\n }*/\n if (tail_ == NULL)\n {\n tail_ = head_;\n }\n }\n /*\n\t--creates a new dynamic SLNode with the contents of \n\t\tthe parameter and attaches as the last node (tail) of the list\n\t */\n void SLList::InsertTail(int insert) \n {\n if(head_ != NULL)\n {\n SLNode* new_node, *newNode = new SLNode(insert);\n new_node = head_;\n while(new_node->next_node() != NULL)\n {\n new_node = new_node->next_node();\n }\n new_node->set_next_node(newNode);\n tail_ = newNode;\n size_ = size_ + 1;\n } else \n {\n InsertHead(insert);\n }\n }\n /*\n void RemoveHead()\n --removes the head node from the list,\n or does nothing if the list is empty\n\t !!Handle tail_ when the last remaining node in the list is removed\n */\n void SLList::RemoveHead() \n {\n if(head_ != NULL)\n {\n if(head_ == tail_)\n {\n tail_ = NULL;\n }\n SLNode* temp_node = head_;\n head_ = head_->next_node();\n delete temp_node;\n temp_node = NULL;\n size_ = size_ - 1;\n }\n }\n /*\n --removes the last node (tail) from the list,\n\t or does nothing if the list is empty\n\t */\n\tvoid SLList::RemoveTail()\n\t{\n\t if(head_ != NULL)\n {\n if(head_ != tail_)\n {\n SLNode* temp_node = head_;\n while(temp_node->next_node() != tail_)\n {\n temp_node = temp_node->next_node();\n }\n temp_node->set_next_node(NULL);\n delete tail_;\n tail_ = temp_node;\n size_ = size_ - 1;\n } else \n {\n RemoveHead();\n }\n }\n\t}\n /*\n --clears the entire contents of the list,\n freeing all memory associated with all nodes\n (*NEW*) - sets tail_ to NULL\n */\n void SLList::Clear() \n {\n while(head_ != NULL)\n {\n RemoveHead();\n }\n delete head_;\n head_ = NULL;\n tail_ = NULL;\n }\n /*\n\t-- Returns the contents of the head node\n (The node head_ is pointing to)\n Returns 0 if the list is empty\n */\n int SLList::GetHead() const \n {\n //if(head_ != NULL)\n if(size_ != 0)\n {\n return head_->contents();\n } else \n {\n return 0;\n }\n \n }\n /*\n -- Returns the contents of the tail node\n (The node tail_ is pointing to)\n Returns 0 if the list is empty\n */\n int SLList::GetTail() const \n {\n //if(head_ != NULL)\n if(size_ != 0)\n {\n return tail_->contents();\n } else \n {\n return 0;\n }\n }\n /*\n unsigned int size() const\n --accessor for size_\n */\n unsigned int SLList::size() const \n {\n return size_;\n }\n /*\n string ToString() const\n --returns a string representation of the contents\n of all nodes in the list, in the format\n NUM1, NUM2, ..., LASTNUM\n returns the empty string on an empty list (i.e. returns \"\")\n */\n string SLList::ToString() \n {\n if(head_ != NULL)\n {\n stringstream stream;\n SLNode* temp_node = head_;\n while(temp_node != NULL)\n {\n stream << temp_node->contents();\n if(temp_node->next_node() != NULL)\n {\n stream << \", \";\n }\n temp_node = temp_node->next_node();\n }\n return stream.str();\n } else {\n return \"\";\n }\n }"
},
{
"alpha_fraction": 0.7063196897506714,
"alphanum_fraction": 0.7174721360206604,
"avg_line_length": 25.064516067504883,
"blob_id": "90466f56feb21b22e96f5a07d753c09e2f760edc",
"content_id": "d66f1f69823e7b39e8eb8334d7619d15a5a6a10e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 807,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 31,
"path": "/Topic 3/Assignment 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nlab2play: driver.o box.o prize.o\n\tg++ -Wall -g -o lab2play prize.o box.o driver.o\n\n#creates the driver functions\ncinreader: CinReader.cpp CinReader.h\n\tg++ -Wall -g -c CinReader.cpp\n\n#creates the driver functions\ndriver: driver.cpp\n\tg++ -Wall -g -c driver.cpp \n\n#creates the executable from all of the object files\nlab2test: assign_3_unit_test.o prize.o box.o\n\tg++ -Wall -g -o lab2test prize.o box.o assign_3_unit_test.o\n\n#creates the prize object file\nprize: prize.cpp.cpp prize.h\n\tg++ -Wall -g -c prize.cpp\n\n#creates the box object file\nbox: box.cpp box.h\n\tg++ -Wall -g -c box.cpp\n\n#creates the unit test object file\nassign_3_unit_test: assign_3_unit_test.cpp\n\tg++ -Wall -g -c assign_3_unit_test.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test *play"
},
{
"alpha_fraction": 0.5205096006393433,
"alphanum_fraction": 0.5335200428962708,
"avg_line_length": 35.29180145263672,
"blob_id": "b2d6af826aaae2e8ece3e22ab12b19481ce9b97f",
"content_id": "f5bb900cfae8ead529cb79de3de110598c96d761",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11068,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 305,
"path": "/Topic 1/Assignment 1/assignment_1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : assignment_1.cpp\n * Author : David Dalton\n * Description : A program that performs operations on strings and arrays.\n * Sources : Dustin Miner lines 116, 117, 199, 200\n */\n\n#include \"assignment_1.h\"\n\n// Declare Function Prototypes Here (What goes above main)\n/*\n*This function will check to make sure all characters in a given string are\n*alphabetic. It returns true if the string is all alphabetic, otherwise it\n*returns false. The empty string should also return false.\n*/\nbool CheckAlphabetic (const string& kAlphabetic) \n{\n bool is_alphabetic = false;\n int i;\n int currentLetter;\n int length = kAlphabetic.length();\n /*\n *Loops through the array and gets the ascii value of the character at the\n *specified location in the string then compares it to the ascii value range\n *of both upper and lower case letters and returns a true if the value falls\n *within those ranges. If the value doesn't fall in those ranges then it \n *returns false\n */\n for(i = 0; i<length;i++) {\n currentLetter = kAlphabetic[i];\n if (((currentLetter > 64) && (currentLetter < 91))\n || ((currentLetter > 96) && (currentLetter < 123)))\n {\n is_alphabetic = true;\n } else \n {\n is_alphabetic = false;\n return is_alphabetic;\n }\n }\n return is_alphabetic;\n}\n\n/*\n*This function will count the number of words (delimited by space characters) in\n*a string. Assume the parameter will never have multiple spaces back-to-back and will\n*never begin or end with spaces).\n*/\nint CountWords(string words) \n{\n int counter = 0;\n if(words == \"\")\n {\n return counter;\n } else \n {\n char delimiter = ' ';\n int i;\n int currentLetter;\n int length = words.length();\n /*\n *Loops through a string and checks each character in the string. When\n *it encounters a character that is equal to the delimiter character\n *then it increases the word counter by 1. When the loop has finished \n *running then increments the counter by 1 to indicate the end of the\n *string.\n */\n for(i=0;i<length;i++) \n {\n if(words[i] == delimiter) \n {\n counter = (counter + 1);\n }\n }\n counter = (counter + 1);\n return counter;\n }\n}\n\n/*\n*This function will perform a Caesar Cipher Shift. If the string contains any \n*non-alpha characters do not perform the encryption and return false. Otherwise\n*perform the encryption and return true.\n*/\nbool EncryptString(string& string_encrypted, int characters_shifted) \n{\n bool encrypted = false;\n int i;\n int currentLetter;\n int length = string_encrypted.length();\n char alphabet_upper[] = {'A','B','C','D','E','F','G','H','I','J','K','L',\n 'M','N','O','P','Q','R','S','T','U','V','W','X',\n 'Y','Z'};\n char alphabet_lower[] = {'a','b','c','d','e','f','g','h','i','j','k','l',\n 'm','n','o','p','q','r','s','t','u','v','w','x',\n 'y','z'};\n /*\n *Uses the CheckAlphabetic function on the string to verify that all\n *characters in the string are alpha characters. If the string contains\n *non-alpha characters then returns false\n */\n if(CheckAlphabetic(string_encrypted) == true) \n {\n /*\n *Loops through a string and checks the ascii value of the specified\n *character\n */\n for(i=0; i<length; i++) \n {\n /*\n *Checks to see if the value of the characters_shifted is below\n *0. If it is it converts it to a positive value and subtracts 2\n */\n if(characters_shifted < 0)\n {\n characters_shifted = (characters_shifted * -1);\n characters_shifted = (characters_shifted - 2);\n \n }\n /*\n *If the ascii value of the specified character is uppercase\n *then it subtracts 65. If it is lower case then it subrtracts \n *97. It then adds the value to characters_shifted. If the \n *value of the specified character is outside of the range of 0 \n *and 25 then it subracts 26. It then divides the value by \n *modulus 26 to get the value of the index of the upper or lower \n *case alphabet array to set the specified character t then \n *returns true.\n */\n currentLetter = string_encrypted[i];\n if((currentLetter > 64) && (currentLetter < 91))\n {\n currentLetter = (string_encrypted[i] - 65);\n currentLetter = (currentLetter + characters_shifted);\n if((currentLetter > 25) || (currentLetter <0))\n {\n currentLetter = ((currentLetter - 26) % 26);\n } else\n {\n currentLetter = (currentLetter % 26);\n }\n string_encrypted[i] = alphabet_upper[currentLetter];\n } else if((currentLetter > 96) && (currentLetter < 123))\n {\n currentLetter = (string_encrypted[i] - 97);\n currentLetter = (currentLetter + characters_shifted);\n if((currentLetter > 25) || (currentLetter <0))\n {\n currentLetter = ((currentLetter - 26) % 26);\n } else\n {\n currentLetter = (currentLetter % 26);\n }\n string_encrypted[i] = alphabet_lower[currentLetter];\n }\n }\n encrypted = true;\n }\n return encrypted;\n}\n\n/*\n*This function decrypts a Caesar Cipher shift. If the string contains any\n*non-alpha characters do not perform the encryption and return false.\n*Otherwise perform the encryption and return true.\n*/\nbool DecryptString(string& string_unencrypted, int characters_shifted) \n{\n bool decrypted = false;\n int i;\n int currentLetter;\n int length = string_unencrypted.length();\n char alphabet_upper[] = {'A','B','C','D','E','F','G','H','I','J','K','L',\n 'M','N','O','P','Q','R','S','T','U','V','W','X',\n 'Y','Z'};\n char alphabet_lower[] = {'a','b','c','d','e','f','g','h','i','j','k','l',\n 'm','n','o','p','q','r','s','t','u','v','w','x',\n 'y','z'};\n /*\n *Uses the CheckAlphabetic function on the string to verify that all\n *characters in the string are alpha characters. If the string contains\n *non-alpha characters then returns false\n */\n if(CheckAlphabetic(string_unencrypted) == true)\n {\n /*\n *Loops through a string and checks the ascii value of the specified\n *character\n */\n for(i=0; i<length; i++) \n {\n /*\n *Checks to see if the value of the characters_shifted is greater\n *than 999999. If it is it converts it to a positive value and \n *adds 2\n */\n if(characters_shifted > 999999)\n {\n characters_shifted = (characters_shifted * -1);\n characters_shifted = (characters_shifted + 2);\n \n }\n /*\n *If the ascii value of the specified character is uppercase\n *then it subtracts 65. If it is lower case then it subrtracts \n *97. It then subracts characters_shifted from the value. If \n *the value of the specified character is outside of the range \n *of 0 and 25 then it subracts 26. It then divides the value by \n *modulus 26 to get the value of the index of the upper or lower \n *case alphabet array to set the specified character t then \n *returns true.\n */\n currentLetter = string_unencrypted[i];\n if((currentLetter > 64) && (currentLetter < 91))\n {\n currentLetter = (string_unencrypted[i] - 65);\n currentLetter = (currentLetter - characters_shifted);\n if((currentLetter > 25) || (currentLetter <0))\n {\n currentLetter = ((currentLetter + 26) % 26);\n } else\n {\n currentLetter = (currentLetter % 26);\n }\n string_unencrypted[i] = alphabet_upper[currentLetter];\n } else if((currentLetter > 96) && (currentLetter < 123))\n {\n currentLetter = (string_unencrypted[i] - 97);\n currentLetter = (currentLetter - characters_shifted);\n if((currentLetter > 25) || (currentLetter <0))\n {\n currentLetter = ((currentLetter + 26) % 26);\n } else\n {\n currentLetter = (currentLetter % 26);\n }\n string_unencrypted[i] = alphabet_lower[currentLetter];\n }\n }\n decrypted = true;\n }\n return decrypted;\n}\n\n/*\n*This function will compute the mean average of the values in the array. The \n*array will always be at least size of 1.\n*/\ndouble ComputeAverage(double input_array[], unsigned int array_size) \n{ \n /*\n *Adds together all the values in an array using a for loop then returns the \n *value\n */\n double sum = 0;\n double average = 0;\n int i;\n for(i=0;i<array_size;i++) {\n sum += input_array[i];\n }\n average = (sum/array_size);\n return average;\n}\n\n/*\n*This function will find and return the smallest value in an array. The array\n*will always be at least of size 1.\n*/\ndouble FindMinValue(double input_array[], unsigned int array_size) \n{\n int i;\n double min_value = input_array[i];\n /*\n *Uses a for loop to loop through an array and compare each value\n to determine the lowest value in the array then returns that value\n */\n for(i = 0; i<array_size;i++) {\n if(input_array[i] < min_value) \n {\n min_value = input_array[i];\n }\n }\n return min_value;\n}\n\n/*\n*This function will find and return the largest value in an array. The array\n*will always be at least of size 1.\n*/\ndouble FindMaxValue(double input_array[], unsigned int array_size) \n{\n int i;\n double max_value = input_array[i];\n /*\n *Uses a for loop to loop through an array and compare each value\n to determine the greatest value in the array then returns that value\n */\n for(i = 0; i<array_size;i++) {\n if(input_array[i] > max_value) \n {\n max_value = input_array[i];\n }\n }\n return max_value;\n}"
},
{
"alpha_fraction": 0.5441218018531799,
"alphanum_fraction": 0.5452495217323303,
"avg_line_length": 20.119047164916992,
"blob_id": "ad55d60eaa1dc9e4128c5b3ccdd4370a0bcedd96",
"content_id": "55ce5eea2366c6cb63dc383de7dc02b1ba6bc2cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3547,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 168,
"path": "/Topic 4/Lab 4/bs_tree.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bst_tree.h\n * Author : David Dalton\n * Description : Tree lab\n */\n \n#include \"bs_tree.h\"\n\n/**\n * sets root_ to NULL\n * sets size_ to 0\n */\nBSTree::BSTree() \n{\n root_ = NULL;\n size_ = 0;\n}\n\n/**\n * calls Clear()\n */\nBSTree::~BSTree()\n{\n Clear();\n}\n\n/**\n * calls private function Insert(int, root)\n */\nbool BSTree::Insert(int value) \n{\n return Insert(value,root_);\n}\n\n/** \n * calls private function Clear(root)\n */\nvoid BSTree::Clear() \n{\n Clear(root_);\n}\n\n/**\n * Accessor for size_\n */\nunsigned int BSTree::size() const \n{\n return size_;\n}\n\n/**\n * calls private function InOrder(root)\n */\nstring BSTree::InOrder() \n{\n return InOrder(root_);\n}\n\n/**\n * creates a new BSTNode, inserts it into the tree, and returns true\n * if the integer is already in the tree, does not insert, and\n * returns false\n */\nbool BSTree::Insert(int value, BSTNode*& node) \n{\n BSTNode* insertNode = new BSTNode(value);\n /**\n * Checks if the root is null, and creates a new node if it is\n */\n if(node == NULL)\n {\n node = insertNode;\n size_ = size_ + 1;\n return true;\n /**\n * Checks if the contents of root are greater then the contents of the \n * new node\n */\n } else if(node->contents() > value)\n {\n /**\n * Checks if the left child of root is null and inserts the node\n * there if it is, else it calls the insert function with the value\n * and the contents of the roots left child\n */\n Insert(value, node->left_child());\n /**\n * Checks if the contents of root are less than the contents of the\n * new node\n */\n } else if(node->contents() < value)\n {\n /**\n * Checks if the right child of root is null and inserts the node\n * there if it is, else it calls the insert function with the value\n * and the contents of the roots right child\n */\n Insert(value, node->right_child());\n } \n /**\n * Checks if the contents of root is equal to the insure value\n */\n else\n {\n return false;\n }\n}\n\n/**\n * clears the entire contents of the tree,\n * freeing all memory associated with all nodes\n */\nvoid BSTree::Clear(BSTNode*& node) \n{\n /**\n * Checks to make sure that the tree is not already empty\n */\n if (node != NULL)\n {\n /**\n * Checks if both childs of the root are null and deletes the root\n * if they are\n */\n if (node->left_child() == NULL && node->right_child() == NULL)\n {\n delete node;\n node = NULL;\n /**\n * If either of the roots child nodes has contents then it calls the\n * Clear function again on the current node in the tree being looked at\n */\n } else\n {\n if (node->left_child())\n {\n Clear(node->left_child());\n } \n if (node->right_child())\n {\n Clear(node->right_child());\n }\n }\n size_ = size_ - 1;\n node = NULL;\n }\n}\n\n/**\n * creates a string of the data in all nodes in the tree, in\n * ascending order\n * separate by spaces (there should be a space after the last output\n * value)\n */\nstring BSTree::InOrder(BSTNode* node) \n{\n stringstream output;\n if (node == NULL)\n {\n return output.str();\n }\n else \n {\n output << InOrder(node->left_child());\n output << node->contents() << \" \";\n output << InOrder(node->right_child());\n return output.str();\n }\n}"
},
{
"alpha_fraction": 0.7015810012817383,
"alphanum_fraction": 0.7035573124885559,
"avg_line_length": 25.63157844543457,
"blob_id": "f1b795064e98372da5af962a09585a75faa005a1",
"content_id": "440dd1edcc626c525edbbecf28282a8498883209",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 506,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 19,
"path": "/Topic 3/Assignment 4/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nchairstest: chairs.o dl_list.o dl_node.o\n\tg++ -Wall -g -o lab2test dl_node.o dl_list.o chairs.o\n\n#creates the node object file\t\ndl_node.o: dl_node.cpp dl_node.h\n\tg++ -Wall -g -c dl_node.cpp\n\t\n#creates the list object file\ndl_list.o: dl_list.cpp dl_list.h\n\tg++ -Wall -g -c dl_list.cpp\n\n#creates the chair object file\nchairs.o: chairs.cpp CinReader.cpp CinReader.h \n\tg++ -Wall -g -c chairs.cpp CinReader.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.611484944820404,
"alphanum_fraction": 0.6132795214653015,
"avg_line_length": 23.2391300201416,
"blob_id": "4371e5de4f5e63600779687ce7834a06308984ea",
"content_id": "f43611b142891027a4bc6d091a31cab23cda55aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2229,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 92,
"path": "/Topic 3/Assignment 3/box.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: box.h\n * Author: David Dalton\n * Sources:\n */\n\n#ifndef BOX_H\n#define BOX_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include \"prize.h\"\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\nclass Box\n{\n public:\n /**\n * Default constructor\n * initial values boxNumber (0), boxColor (\"NO COLOR\"), prizeCapacity (5), \n * prizeCount(0); in the definition, prizes array must be initialized to \n * match prizeCapacity\n */\n Box();\n /**\n * Overloaded constructor\n * parameters for boxNumber, boxColor, prizeCapacity; in the definition, \n * prizes array must be initialized to match prizeCapacity\n */\n Box(unsigned int number,string color,\n unsigned int capacity, unsigned int count = 0);\n /**\n * Deconstructor\n * free memory associated with prizes\n */\n ~Box();\n /**\n * Mutator for boxNumber_\n */\n void setBoxNumber(unsigned int number);\n /**\n * Mutator for boxColor_\n */\n void setBoxColor(string color);\n /**\n * Accessor for boxNumber_\n */\n unsigned int getBoxNumber();\n /**\n * Accessor for boxColor_\n */\n string getBoxColor();\n /**\n * Accessor for prizeCapacity_\n */\n unsigned int getPrizeCapacity();\n /**\n * Accessor for prizeCount_\n */\n unsigned int getPrizeCount();\n /**\n * parameters prize (Prize), return value (bool); place prize in prizes \n * array if there is space and return true, else return false\n */\n bool addPrize(Prize prize);\n /**\n * parameters index (unsigned int), return value Prize&; return a Prize if \n * index is valid, else return scratch (data member declared in class \n * header)\n */\n Prize getPrize(unsigned int index);\n /**\n * parameters index (unsigned int), return value Prize; remove and return \n * Prize if index is valid, else return scratch (data member declared in \n * class header)\n */\n Prize removePrize(unsigned int index);\n \n private:\n unsigned int boxNumber_;\n string boxColor_;\n Prize scratch_;\n Prize* prizes_;\n unsigned int prizeCapacity_;\n unsigned int prizeCount_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6587156057357788,
"alphanum_fraction": 0.6659844517707825,
"avg_line_length": 35.90364456176758,
"blob_id": "c85b3245928bb77ecc330d7932fe89728b4acebc",
"content_id": "5aca0be0cedc59eb9bb34dcc09df81a33365676f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 14170,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 384,
"path": "/Topic 2/Assignment 2/credit_account.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : credit_account.cpp\n * Author : David Dalton\n * Description : CreditAccount function definition\n * Source : Luke Sathrum, modified portions of money lab and item lab\n */\n \n#include \"credit_account.h\"\n\n/*\n * Constructor, uses default values if none given on creation\n */\nCreditAccount::CreditAccount(string account_name, long dollars, \n int cents, double interest_rate,\n long max_balance_dollars, \n int max_balance_cents,\n string last_transaction,\n string interest_accumulated_month, \n string interest_accumulated_year) \n{\n BankAccount::SetAccountName(account_name);\n BankAccount::SetDollars(dollars);\n BankAccount::SetCents(cents) ;\n BankAccount::SetLastTransaction(0, 0, last_transaction);\n BankAccount::ClearRecentTransactions();\n SetMaxBalanceDollars(max_balance_dollars);\n SetMaxBalanceCents(max_balance_cents);\n interest_rate_ = interest_rate;\n interest_accumulated_month_ = interest_accumulated_month;\n interest_accumulated_year_ = interest_accumulated_year;;\n}\n/*\n * Destructor, unused\n */\nCreditAccount::~CreditAccount() \n{\n \n}\n/*\n * Mutator\n *sets the value of interest_rate_ to the given value\n */\nvoid CreditAccount::SetInterestRate(double interest_rate) \n{\n interest_rate_ = interest_rate;\n}\n/*\n * Mutator\n *sets the value of max_balance_dollars_ to the given value\n */\nvoid CreditAccount::SetMaxBalanceDollars(long max_balance_dollars) \n{\n max_balance_dollars_ = max_balance_dollars;\n}\n/*\n * Mutator\n *sets the value of max_balance_cents_ to the given value\n */\nvoid CreditAccount::SetMaxBalanceCents(int max_balance_cents) \n{\n max_balance_cents_ = max_balance_cents;\n}\n/*\n * Mutator\n *gets the current interest accumulated for the month and stores it, then \n *adds the amount of interested earned to the amount accumulated for the month\n */\nvoid CreditAccount::SetInterestAccumulatedMonth(long accumulated_dollars, \n int accumulated_cents) \n{\n stringstream interest;\n int string_length = interest_accumulated_month_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_length;i++)\n {\n if(interest_accumulated_month_[i] != ('$' || '-'))\n {\n interest << interest_accumulated_month_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double current_interest = stoi(interest.str());\n // Splits the value into the dollars and cents value\n long current_dollars = current_interest;\n int current_cents = ((current_interest - current_dollars) *100);\n // Adds the amount accrued to the current amount\n accumulated_dollars = accumulated_dollars + current_dollars;\n accumulated_cents = accumulated_cents + current_cents;\n // Adds to the string stream to convert back into a string\n interest << '$' << setw(1) << setfill('0') << accumulated_dollars << \".\" \n << setfill('0') << setw(2) << accumulated_cents;\n // Sets the interest_accumulated_month_ string to the stringstream\n interest_accumulated_month_ = interest.str();\n}\n/*\n * Mutator\n *gets the current interest accumulated for the year and stores it, then \n *adds the amount of interested earned to the amount accumulated for the year\n */\nvoid CreditAccount::SetInterestAccumulatedYear(long accumulated_dollars, \n int accumulated_cents) \n{\n stringstream interest;\n int string_length = interest_accumulated_year_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_length;i++)\n {\n if(interest_accumulated_year_[i] != ('$' || '-'))\n {\n interest << interest_accumulated_year_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double current_interest = stoi(interest.str());\n // Splits the value into the dollars and cents value\n long current_dollars = current_interest;\n int current_cents = ((current_interest - current_dollars) *100);\n // Adds the amount accrued to the current amount\n accumulated_dollars = accumulated_dollars + current_dollars;\n accumulated_cents = accumulated_cents + current_cents;\n // Adds to the string stream to convert back into a string\n interest << '$' << setw(1) << setfill('0') << accumulated_dollars << \".\" \n << setfill('0') << setw(2) << accumulated_cents;\n // Sets the interest_accumulated_month_ string to the stringstream\n interest_accumulated_year_ = interest.str();\n}\n/*\n * Mutator\n *makes a payment on the current balance\n */\nvoid CreditAccount::MakePayment(long payment_dollars, int payment_cents) \n{\n long current_dollars = GetDollars();\n int current_cents = GetCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of withdrawn amount\n long all_cents2 = payment_cents + payment_dollars * 100;\n /*\n *Checks to see if the payment amount is less than or equal to the current \n *balance\n */\n if(all_cents1 >= all_cents2)\n {\n //Subtracts object 2 all cents from object 1 all cents\n long sum_all_cents = all_cents1 - all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) \n {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n // Sets the current balance to the new balance and records the transaction\n BankAccount::SetDollars(final_dollars);\n BankAccount::SetCents(final_cents);\n SetLastTransaction(final_dollars, final_cents, \"Credit Card Payment\");\n SetRecentTransactions(final_dollars, final_cents, \"Credit Card Payment\");\n } else \n {\n /*\n *If payment amount is greater than the current balance then it\n *cancels the payment and records an error message\n */\n BankAccount::SetDollars(0);\n BankAccount::SetCents(0);\n SetLastTransaction(current_dollars, current_cents, \"Invalid Credit Payment Amount\");\n SetRecentTransactions(current_dollars, current_cents, \"Invalid Credit Payment Amount\");\n }\n}\n/*\n * Mutator\n *makes a charge to the card in a given amount with the given transaction\n *id number. It then adds this amount to the current balance\n */\nvoid CreditAccount::ChargeCard(long transaction_number, long charge_dollars, \n int charge_cents) \n{\n stringstream charge;\n long current_dollars = GetDollars();\n int current_cents = GetCents();\n long max_balance_dollars = GetMaxBalanceDollars();\n int max_balance_cents = GetMaxBalanceCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of deposited amount\n long all_cents2 = charge_cents + charge_dollars * 100;\n // Add all the cents together\n long sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n /*\n *checks to see if the charge will result in a balance greater than the\n *max balance\n */\n if((final_dollars <= max_balance_dollars) || \n (final_dollars == max_balance_dollars && final_cents <= max_balance_cents))\n {\n /*\n *if the result of the operation was negative, negate final dollars and \n *cents\n */\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n //Sets the new balance and records the transaction\n BankAccount::SetDollars(final_dollars);\n BankAccount::SetCents(final_cents);\n charge << \"Transaction #\" << transaction_number;\n BankAccount::SetLastTransaction(final_dollars, final_cents, charge.str());\n BankAccount::SetRecentTransactions(final_dollars, final_cents, charge.str());\n } else\n {\n /*\n *if the charge results in an amount greater then the max balance,\n *cancels transaction and records an error message to the transaction\n *record\n */\n BankAccount::SetLastTransaction(0,0,\"CARD ERROR: INSUFFICIENT FUNDS\");\n BankAccount::SetRecentTransactions(0,0,\"CARD ERROR: INSUFFICIENT FUNDS\");\n }\n}\n/*\n * Mutator\n *retrieves the current balance then calculates the amount of interest earned\n *then adds it to the current balance\n */\nvoid CreditAccount::CalculateInterest() \n{\n // Retrieves the needed variables\n long dollars = BankAccount::GetDollars();\n int cents = BankAccount::GetCents();\n double interest_rate = GetInterestRate();\n string interest_month_generated = GetInterestAccumulatedMonth();\n string interest_year_generated = GetInterestAccumulatedYear();\n \n stringstream interest_month;\n int string_month_length = interest_accumulated_month_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_month_length;i++)\n {\n if(interest_accumulated_month_[i] != ('$' || '-'))\n {\n interest_month << interest_accumulated_month_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double monthly_interest = stoi(interest_month.str());\n // Splits the value into the dollars and cents value\n long monthly_dollars = monthly_interest;\n int monthly_cents = ((monthly_interest - monthly_dollars) *100);\n // Gets the needed information on interest accumulated for the month\n stringstream interest_year;\n int string_year_length = interest_accumulated_year_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_year_length;i++)\n {\n if(interest_accumulated_year_[i] != ('$' || '-'))\n {\n interest_year << interest_accumulated_year_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double yearly_interest = stoi(interest_year.str());\n // Splits the value into the dollars and cents value\n long yearly_dollars = yearly_interest;\n int yearly_cents = ((yearly_interest - yearly_dollars) * 100);\n \n // Get all the cents of object 1\n long all_cents1 = monthly_cents + monthly_dollars * 100;\n // Get all the cents of object 2\n long all_cents2 = yearly_cents + yearly_dollars * 100;\n // Add all the cents together\n long sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n //Sets interest accumulated for the year to calculated values\n SetInterestAccumulatedYear(final_dollars, final_cents);\n /*\n *uses the current balance and subtracts that from the accumulated interest\n *to determine the amount accumulated for the month and sets it to the value\n */\n double current_balance = (dollars + (cents / 100));\n double updated_balance = current_balance + (current_balance * interest_rate);\n double gained_balance = updated_balance - current_balance;\n long updated_balance_dollars = updated_balance;\n int updated_balance_cents = ((updated_balance - updated_balance_dollars) * 100);\n long gained_balance_dollars = gained_balance;\n int gained_balance_cents = ((gained_balance - gained_balance_dollars) * 100);\n BankAccount::SetDollars(updated_balance_dollars);\n BankAccount::SetCents(updated_balance_cents);\n SetInterestAccumulatedMonth(gained_balance_dollars, gained_balance_cents);\n}\n/*\n * Accessor\n *gets the value of interest and returns it\n */\ndouble CreditAccount::GetInterestRate() \n{\n return interest_rate_;\n}\n/*\n * Accessor\n *gets the value of max_balance_dollars_ and returns it\n */\nlong CreditAccount::GetMaxBalanceDollars() \n{\n return max_balance_dollars_;\n}\n/*\n * Accessor\n *gets the value of max_balance_cents_ and returns it\n */\nint CreditAccount::GetMaxBalanceCents() \n{\n return max_balance_cents_;\n}\n/*\n * Accessor\n *calls the GetMaxBalanceDollars() and GetMaxBalanceCents() functions to get\n *the values of their variables. It then stores the values of those variables\n *and sends them to a stringstream along with default characters. It then\n *returns the string\n */\nstring CreditAccount::GetMaxBalance() \n{\n /*\n *Gets the absolute value of the objects cents value and stores it into a \n *variable. It then gets the value of the objects dollars_ and cents_\n *variables and checks to see if they are equal to and less than 0. If\n *they are then they send them to an output stream with a negative character\n *otherwise it sends it to the output stream without the negative character\n *then returns the output stream\n */\n stringstream max_balance;\n long dollars = GetMaxBalanceDollars();\n int cents = GetMaxBalanceCents();\n {\n max_balance << \"Your balance is: $\" << setw(1) << setfill('0') << dollars << \".\" \n << setfill('0') << setw(2) << cents;\n }\n return max_balance.str();\n}\n/*\n * Accessor\n *gets the value of interest_accumulated_month_ and returns it\n */\nstring CreditAccount::GetInterestAccumulatedMonth() \n{\n return interest_accumulated_month_;\n}\n/*\n * Accessor\n *gets the value of interest_accumulated_year_ and returns it\n */\nstring CreditAccount::GetInterestAccumulatedYear() \n{\n return interest_accumulated_year_;\n}"
},
{
"alpha_fraction": 0.6661500334739685,
"alphanum_fraction": 0.6698697805404663,
"avg_line_length": 31.25,
"blob_id": "3458c88f72b145ac92e0b90caf63592e23610b69",
"content_id": "acb43cb4776d8b91d70b874610c81ce01c83df7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3226,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 100,
"path": "/Topic 5/Lab 1/sorting.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_14.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #14. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n// For Testing, DO NOT ALTER!\nextern bool GRADER;\nbool CompareArrays(int array_one[], int array_two[], unsigned int size);\n/*\n * Apply the bubble sort algorithm to sort an array of integers.\n * @param int[] the_array - The integer array to be sorted\n * @param unsigned int size - The size of the_array\n * @return int - The number of passes the algorithm does. In this case \"pass\" is\n * defined as the number of times the outside loop runs. You\n * should increment your variable once you enter the outside loop.\n */\nint BubbleSort(int the_array[], unsigned int size) \n{\n \n}\n\n/*\n * Apply the optimized bubble sort algorithm to sort an array of integers.\n * @param int[] the_array - The integer array to be sorted\n * @param unsigned int size - The size of the_array\n * @return int - The number of passes the algorithm does. In this case \"pass\" is\n * defined as the number of times the outside loop runs. You\n * should increment your variable once you enter the outside loop.\n */\nint OptimizedBubbleSort(int the_array[], unsigned int size) \n{\n \n}\n\n/*\n * Apply the selection sort algorithm to sort an array of integers.\n * @param int[] the_array - The integer array to be sorted\n * @param unsigned int size - The size of the_array\n * @return int - The number of passes the algorithm does. In this case \"pass\" is\n * defined as the number of times the outside loop runs. You\n * should increment your variable once you enter the outside loop.\n */\nint SelectionSort(int the_array[], unsigned int size) \n{\n \n}\n\n/*\n * Apply the insertion sort algorithm to sort an array of integers.\n * @param int[] the_array - The integer array to be sorted\n * @param unsigned int size - The size of the_array\n * @return int - The number of passes the algorithm does. In this case \"pass\" is\n * defined as the number of times the outside loop runs. You\n * should increment your variable once you enter the outside loop.\n */\nint InsertionSort(int the_array[], unsigned int size) \n{\n \n}\n\n/*\n * Apply the shell sort algorithm to sort an array of integers.\n * NOTE: At the end of each iteration of the for loop you will need to call\n * DisplayArray(the_array);\n * @param int[] the_array - The integer array to be sorted\n * @param unsigned int size - The size of the_array\n * @return int - The number of passes the algorithm does. In this case \"pass\" is\n * defined as the number of times the outside loop runs. You\n * should increment your variable once you enter the outside loop.\n */\nint ShellSort(int the_array[], unsigned int size) \n{\n \n}\n\n\n/*\n * Swap the values of two integer variables.\n * @param int &value_1 - The first value to be swapped.\n * @param int &value_2 - The second value to be swapped.\n */\nvoid SwapValues(int &value_1, int &value_2) \n{\n int temp_value;\n temp_value = value_1;\n value_1 = value_2;\n value_2 = temp_value;\n}\n\n#endif\n\n"
},
{
"alpha_fraction": 0.5951456427574158,
"alphanum_fraction": 0.6087378859519958,
"avg_line_length": 21.413043975830078,
"blob_id": "65394c07a93441c065e5268daa7f53da60ef35fd",
"content_id": "681ea34e30cc30fcdc0571cb74f52eee98ebd8b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1030,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 46,
"path": "/ICE/ICE1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <string>\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nint Biggest (int first_number, int second_number) {\n if (first_number > second_number) {\n return first_number;\n } else {\n return second_number;\n }\n}\n\nint Biggest (int first_number, int second_number, int third_number) {\n if ((first_number > second_number) && first_number < third_number) {\n return third_number;\n } else if ((first_number > second_number) && (first_number > third_number)){\n return first_number;\n } else {\n return second_number;\n }\n}\n\nvoid Swap (int &first_number, int &second_number) {\n int temp;\n temp = first_number;\n first_number = second_number;\n second_number = temp;\n}\n\nint main(){\n string full_Name;\n int number_list_1 = {17,21,3};\n int number_list_2 = {13,33};\n \n cout << \"What is your name?\" << endl;\n cin >> full_Name;\n\n cout << Biggest(number_list_1);\n cout << Biggest(number_list_2);\n return 0;\n}"
},
{
"alpha_fraction": 0.6737864017486572,
"alphanum_fraction": 0.7029126286506653,
"avg_line_length": 26.157894134521484,
"blob_id": "9e2003447aecb9eb31befda0ed1fb43116d1a8c9",
"content_id": "0201bd0cc16d7130c928dc6d3b372515455cea6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 515,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 19,
"path": "/Topic 4/Lab 4/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from objects\nlab24test: lab_24_unit_test.o bst_node.o bs_tree.o\n\tg++ -Wall -g -o lab2test lab_24_unit_test.o bst_node.o bs_tree.o\n\n#creates the bs_tree object\nbs_tree: bs_tree.cpp bs_tree.h\n\tg++ -Wall -g -c bs_tree.cpp\n\t\n#creates the bst_node object file\nbst_node: bst_node.cpp bst_node.h\n\tg++ -Wall -g -c bst_node.cpp\n\t\n#creates the lab24 unit test object\nlab_24_unit_test: lab_24_unit_test.cpp\n\tg++ -Wall -g -c lab_24_unit_test.cpp\n\t\n#removes all object files and exe\t\nclean:\n\trm *.o *test"
},
{
"alpha_fraction": 0.506302535533905,
"alphanum_fraction": 0.5073529481887817,
"avg_line_length": 14.622950553894043,
"blob_id": "d278416d1eefb3d174c9a79b2576508cdadfa15d",
"content_id": "4485e697c6f98ef49c06eb033fb1310aa1dcd6e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 952,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 61,
"path": "/Topic 3/Lab 4/sl_node.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_node.cpp\n * Author : David Dalton\n * Description : Node lab.\n */\n \n#include \"sl_node.h\"\n\n/*\n *Default Constructor\n */\n SLNode::SLNode()\n {\n next_node_ = NULL;\n contents_ = 0;\n }\n /*\n *Overloaded Constructor\n */\n SLNode::SLNode(int contents) \n {\n next_node_ = NULL;\n contents_ = contents;\n }\n /*\n *Destructor\n */\n SLNode::~SLNode() \n {\n \n }\n /*\n *Mutator for contents_\n */\n void SLNode::set_contents(int contents) \n {\n contents_ = contents;\n }\n /*\n *Accessor for contents_\n */\n int SLNode::contents() \n {\n return contents_;\n }\n /*\n *void set_next_node(SLNode*)\n *--mutator for next_node_\n */\n void SLNode::set_next_node(SLNode* next_node) \n {\n next_node_ = next_node;\n }\n /*\n *SLNode* next_node() const\n *--accessor for next_node_\n */\n SLNode* SLNode::next_node() const\n {\n return next_node_;\n }"
},
{
"alpha_fraction": 0.616981565952301,
"alphanum_fraction": 0.6309773921966553,
"avg_line_length": 25.469135284423828,
"blob_id": "4ca27a2119b7513180096170f65186880bf9be93",
"content_id": "ac1caac7572910f4878206698b758821025229a7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4287,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 162,
"path": "/Topic 5/Lab 3/lab_3.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Programming Challenge 30\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <array>\n#include <list>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\nusing namespace std;\n\n/*\n * An Item to be stored in a HashTable.\n */\nstruct Item {\n\tItem (string newContents)\n\t: count(1), contents(newContents) {}\n\n\tunsigned int count;\n\tstring contents;\n};\n\n/*\n * A class representing a hash table\n */\nclass HashTable {\n\tpublic:\n\t\n\t\t/**\n\t\t * Insert an item into the hash table.\n\t\t * @param i the Item to be inserted\n\t\t */\n\t\tvoid insert (Item i);\n\n\t\t/**\n\t\t * Remove an item from the hash table.\n\t\t * @param contents the contents of the Item to remove\n\t\t * @return true if an Item with the contents was removed, or false if no matching Item is found\n\t\t */\n\t\tbool remove (string contents);\n\n\t\t/**\n\t\t * Return a pointer to an Item in the hash table, by contents.\n\t\t * @param contents the contents of the Item to return\n\t\t * @return a pointer to the Item with the contents, or NULL if no Item matches the contents\n\t\t */\n\t\tItem* getItem (string contents);\n\n\t\t/**\n\t\t * Return the number of items currently stored in the hash table.\n\t\t * @return an unsigned int containing the number of items stored in the hash table\n\t\t */\n\t\tunsigned int size ();\n\n\t\t/**\n\t\t * Compute the hash value for an Item object. Uses the string contents \n\t\t * member of Item to compute the hash. Uses the private hash function on \n\t\t * string contents.\n\t\t * @param Item the Item for which to compute the hash\n\t\t * @return an unsigned integer containing the hash computed by the private hash function\n\t\t */\n\t\tunsigned int hash (Item i);\n\n\t\t/**\n\t\t * Display a detailed view of the contents of the hash table. Format should be as follows:\n\t\t *\n\t\t * Items in hash table: hash_table_size\n\t\t * [array_index] item_contents (item_count)\n\t\t *\n\t\t * NOTE: insert a TAB character after [array_index] and output item_contents into a field of \n\t\t * width 10\n\t\t *\n\t\t * EXAMPLE:\n\t\t *\n\t\t * Items in hash table: 4\n\t\t * [0]\t apple (1) banana (2)\n\t\t * [1]\n\t\t * [2]\t blueberry (1) \n\t\t * [3]\n\t\t * [4]\t pear (1) \n\t\t *\n\t\t * @return a string containing a detailed view of the contents of the hash table.\n\t\t */\n\t\tstring printDetail ();\n\n\tprivate:\n\t\tarray<list<Item>, 5> items;\n\n\t\t/**\n\t\t * Compute a hash value (unsigned integer) by summing the ASCII values \n\t\t * of the characters in a string and modding to fit the hash table size.\n\t\t * @param s the string to hash\n\t\t * @return an unsigned int containing the has value for the string\n\t\t */\n\t\tunsigned int hash (string s);\n};\n\n// FUNCTION DEFINITIONS GO HERE\n\nTEST_CASE (\"hash function and hash table functionality\") {\n\tItem items[15] = {Item(\"apple\"), Item(\"banana\"), Item(\"grape\"), Item(\"lemon\"), \n\t\t\t\t\t Item(\"melon\"), Item(\"orange\"), Item(\"strawberry\"),\n\t\t\t\t\t Item(\"pear\"), Item(\"blueberry\"), Item(\"grapefruit\"),\n\t\t\t\t\t Item(\"apple\"), Item(\"banana\"), Item(\"grape\"), Item(\"lemon\"), \n\t\t\t\t\t Item(\"melon\")};\n\tHashTable ht;\n\n\tCHECK(ht.size() == 0);\n\tCHECK(ht.printDetail() == \n\t\t\"Items in hash table: 0\\n[0]\\t\\n[1]\\t\\n[2]\\t\\n[3]\\t\\n[4]\\t\\n\");\n\n\tCHECK(ht.hash(items[0]) == 0);\n\tCHECK(ht.hash(items[4]) == 4);\n\tCHECK(ht.hash(items[8]) == 2);\n\tCHECK(ht.hash(items[12]) == 2);\n\tCHECK(ht.hash(items[14]) == 4);\n\n\tfor (Item i : items) {\n\t\tht.insert(i);\n\t}\n\n\tCHECK(ht.size() == 10);\n\n\tstringstream output;\n\toutput << \"Items in hash table: 10\\n\" << \"[0]\\t apple (2) \\n\";\n\toutput << \"[1]\\t orange (1) grapefruit (1) \\n\" << \"[2]\\t grape (2) blueberry (1) \\n\";\n\toutput << \"[3]\\t\\n\";\n\toutput << \"[4]\\t banana (2) lemon (2) melon (2) strawberry (1) pear (1) \\n\";\n\tCHECK(ht.printDetail() == output.str());\n\n\tItem* tempItem = ht.getItem(\"shoe\");\n\tCHECK(tempItem == NULL);\n\n\ttempItem = ht.getItem(\"apple\");\n\tCHECK(tempItem != NULL);\n\tCHECK(tempItem->count == 2);\n\n\ttempItem = ht.getItem(\"pear\");\n\tCHECK(tempItem != NULL);\n\tCHECK(tempItem->count == 1);\n\n\tCHECK(!ht.remove(\"shoe\"));\n\n\tCHECK(ht.remove(\"apple\"));\n\tCHECK(ht.size() == 9);\n\n\tCHECK(!ht.remove(\"apple\"));\n\n\tCHECK(ht.remove(\"orange\"));\n\tCHECK(ht.remove(\"grapefruit\"));\n\tCHECK(ht.remove(\"grape\"));\n\tCHECK(ht.remove(\"blueberry\"));\n\tCHECK(ht.remove(\"banana\"));\n\tCHECK(ht.remove(\"lemon\"));\n\tCHECK(ht.remove(\"melon\"));\n\tCHECK(ht.remove(\"strawberry\"));\n\tCHECK(ht.remove(\"pear\"));\n\n\tCHECK(ht.size() == 0);\n}"
},
{
"alpha_fraction": 0.6924418807029724,
"alphanum_fraction": 0.694767415523529,
"avg_line_length": 30.851852416992188,
"blob_id": "9355c5376e1cf11efeb2dffcfb7948841bc1cc7b",
"content_id": "3a2101338b176a9f396af16089b4e8cbc48b9437",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1720,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 54,
"path": "/Topic 3/Lab 1/lab_12.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_12.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #12. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <cstring>\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n/*\n * Allocate memory for a dynamic array of integers.\n * @param unsigned int size - The desired size of the dynamic array\n * @return int* - A pointer to the newly allocated integer array\n */\nint* MakeDynoIntArray(unsigned int size);\n\n/*\n * Compute the sum of an array.\n * @param int* the_array - The array for which the sum will be computed\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the sum of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Sum(int* the_array, unsigned int array_size);\n\n/*\n * Identify the max value in an array.\n * @param int* the_array - The array for which the max value will be identified\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the max value of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Max(int* the_array, unsigned int array_size);\n\n/*\n * Identify the min value in an array.\n * @param int* the_array - The array for which the min value will be identified\n * @param unsigned int array_size - The size of the_array\n * @return int - An integer containing the min value of the array\n * @throw The message \"NULL ARRAY REFERENCE\" if the_array is NULL\n * Syntax: throw \"The Message to throw\";\n */\nint Min(int* the_array, unsigned int array_size);\n\n#endif\n"
},
{
"alpha_fraction": 0.5670731663703918,
"alphanum_fraction": 0.5914633870124817,
"avg_line_length": 17.22222137451172,
"blob_id": "f0f7979b1d4a0f0fcf34bf2575435466f5dfa4f6",
"content_id": "6e3648df950e285af86b597005d548a45bd1248e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 164,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 9,
"path": "/Topic 5/Lab 2/lab_27.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_27.cpp\n * Author : YOUR NAME\n * Description : Using the STL\n */\n\n#include \"lab_27.h\"\n\n// CLASS (and regular) FUNCTION DEFINITIONS GO HERE\n"
},
{
"alpha_fraction": 0.555446445941925,
"alphanum_fraction": 0.5573126673698425,
"avg_line_length": 25.04092025756836,
"blob_id": "9990ac15e12bea1a1ba8d2518edcd25a4d9a0b7b",
"content_id": "8e5cbe4210be378f096087bec25b6e7d983aec70",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 10181,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 391,
"path": "/Topic 3/Lab 5/sl_list.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_list.cpp\n * Author : David Dalton\n * Description : Node list lab.\n */\n \n#include \"sl_list.h\"\n /*\n Default Constructor\n --sets head_ to NULL\n --sets tail_ to NULL\n --sets size_ to 0\n */\n SLList::SLList() \n {\n head_ = NULL;\n tail_ = NULL;\n size_ = 0;\n }\n /*\n Destructor\n --calls Clear()\n */\n SLList::~SLList() \n {\n Clear();\n }\n /*\n --clears the entire contents of the list,\n freeing all memory associated with all nodes\n (*NEW*) - sets tail_ to NULL\n */\n void SLList::Clear() \n {\n while(head_ != NULL)\n {\n RemoveHead();\n }\n delete head_;\n head_ = NULL;\n tail_ = NULL;\n }\n /*\n --creates a new SLNode with the contents of the parameter and\n inserts it into the correct position in the list. The list\n will be sorted with the lowest values in the front (head) and the\n largest values in the back (tail).\n */\n void SLList::Insert(int insert) \n {\n /**\n * Checks to see if head_ is null or if the contents of head_ are greater\n * then the parameter being inserted. If it is then calls the \n * InsertHead() function, otherwise continues to next check\n */\n if(head_ == NULL || head_->contents() > insert)\n {\n InsertHead(insert);\n /**\n * Checks if the contents of tail_ are less then the parameter being\n * inserted. If so, calls InsertTail() function, otherwise continues\n * to next check\n */\n } else if (tail_->contents() < insert)\n {\n InsertTail(insert);\n /**\n * Inserts the parameter into the correct location in the list\n */\n } else \n {\n SLNode* iterator;\n iterator = head_;\n /**\n * Checks whether the contents of the next node is less then the parameter\n * and that the next node is not the tail. If they are not, then it \n * advances the iterator to the next node in the list\n */\n while(insert > iterator->next_node()->contents() && iterator->next_node() != tail_)\n {\n iterator = iterator->next_node();\n }\n /**\n * Checks if the iterator is located at the tail\n */\n if(iterator != tail_)\n {\n /**\n * If the iterator is not located at the tail, it creates a new node\n * and inserts it at the iterators current location, then increases\n * the size variable by 1\n */\n SLNode* new_node = new SLNode(insert);\n new_node->set_next_node(iterator->next_node());\n iterator->set_next_node(new_node);\n size_ = size_ + 1;\n } else\n {\n /**\n * If the iterator is located at the tail, then calls the InsertTail()\n * function\n */\n InsertTail(insert);\n }\n }\n }\n /*\n --remove the first occurence of the supplied parameter\n found as the data of a node. Return true on successful\n removal or false if the list is empty or if the value\n is not found.\n */\n bool SLList::RemoveFirstOccurence(int parameter) \n { \n /**\n * Checks if the head is null and returns false if it is\n */\n if(head_ == NULL)\n {\n return false;\n /**\n * Checks if the contents of head_ are equal to the parameter, then\n * calls the RemoveHead() function and returns true if it is\n */\n } else if(head_->contents() == parameter)\n {\n RemoveHead();\n return true;\n /**\n * Checks if the contents of tail_ are equal to the parameter, then\n * calls the RemoveTail() function and returns true if it is\n */\n } else if(tail_->contents() == parameter)\n {\n RemoveTail();\n return true;\n /**\n * checks if the list contains only two nodes, if it does not then\n * it checks for the specified parameter, otherwise it returns false\n */\n } else if(head_->next_node() != tail_)\n {\n SLNode* iterator = head_->next_node();\n SLNode* temp_node = head_;\n /**\n * Loops through the node list checking the contents of the current\n * node to the parameter and if the next node is the tail, if neither\n * statement is true then it iterates to the next node\n */\n while(iterator->contents() != parameter && iterator->next_node() != tail_)\n {\n temp_node = iterator;\n iterator = iterator->next_node();\n }\n /**\n * Checks if the contents of the current node are equal to the parameter,\n * if not then returns false\n */\n if(iterator->contents() == parameter)\n {\n /**\n * Sets the placeholder node to the node that the iterator is pointing\n * to then deletes the iterator node, reduces the size variable\n * then returns true\n */\n temp_node->set_next_node(iterator->next_node());\n delete iterator;\n iterator = NULL;\n size_ = size_ - 1;\n return true;\n } else\n {\n return false;\n }\n } else\n {\n return false;\n }\n }\n /*\n\t-- Returns the contents of the head node\n (The node head_ is pointing to)\n Returns 0 if the list is empty\n */\n int SLList::GetHead() const \n {\n if(size_ != 0)\n {\n return head_->contents();\n } else \n {\n return 0;\n }\n \n }\n /*\n -- Returns the contents of the tail node\n (The node tail_ is pointing to)\n Returns 0 if the list is empty\n */\n int SLList::GetTail() const \n {\n if(size_ != 0)\n {\n return tail_->contents();\n } else \n {\n return 0;\n }\n }\n /*\n unsigned int size() const\n --accessor for size_\n */\n unsigned int SLList::size() const \n {\n return size_;\n }\n /*\n string ToString() const\n --returns a string representation of the contents\n of all nodes in the list, in the format\n NUM1, NUM2, ..., LASTNUM\n returns the empty string on an empty list (i.e. returns \"\")\n */\n string SLList::ToString() \n {\n /**\n * Checks if the node list is empty and returns an empty string if it is\n */\n if(head_ != NULL)\n {\n stringstream stream;\n SLNode* temp_node = head_;\n /**\n * Using a while loop, checks every node if it is null, if it is not\n * then it adds its contents to a stringstream and then checks if the\n * next node is null, if not adds a separator string\n */\n while(temp_node != NULL)\n {\n stream << temp_node->contents();\n if(temp_node->next_node() != NULL)\n {\n stream << \", \";\n }\n temp_node = temp_node->next_node();\n }\n // Returns the stringstream\n return stream.str();\n } else {\n return \"\";\n }\n }\n /*\n void InsertHead(int)\n\n\t- Handle tail_ when the first node in the list is added\n void InsertHead(int)\n --creates a new dynamic SLNode with the contents of \n the parameter and attaches as the new head of the list\n */\n void SLList::InsertHead(int insert) \n {\n /**\n * Creates a new node with the specified contents, then inserts it at the\n * start of the list. Increases the size variable and points tail to \n * head if it was currently null\n */\n SLNode* new_node = new SLNode(insert);\n new_node->set_next_node(head_);\n head_ = new_node;\n size_ = size_ + 1;\n if (tail_ == NULL)\n {\n tail_ = head_;\n }\n }\n /*\n\t--creates a new dynamic SLNode with the contents of \n\t\tthe parameter and attaches as the last node (tail) of the list\n\t */\n void SLList::InsertTail(int insert) \n {\n /**\n * Checks if the list is empty, if so calls the InsertHead() function\n */\n if(head_ != NULL)\n {\n /**\n * Creates a new node of the specified value and a iterator node, then\n * sets the iterator node to head_\n */\n SLNode* temp_node, *newNode = new SLNode(insert);\n temp_node = head_;\n /**\n * Loops through the list to check if the next node is null, if not it\n * iterates to the next node\n */\n while(temp_node->next_node() != NULL)\n {\n temp_node = temp_node->next_node();\n }\n /**\n * Inserts the node at the end of the list, points the tail to it and\n * increases the size variable by 1\n */\n temp_node->set_next_node(newNode);\n tail_ = newNode;\n size_ = size_ + 1;\n } else \n {\n InsertHead(insert);\n }\n }\n /*\n void RemoveHead()\n --removes the head node from the list,\n or does nothing if the list is empty\n\t !!Handle tail_ when the last remaining node in the list is removed\n */\n void SLList::RemoveHead() \n {\n /**\n * Checks if the list is empty\n */\n if(head_ != NULL)\n {\n /**\n * Checks if head_ is equal to tail_ and sets tail_ to null if it is\n */\n if(head_ == tail_)\n {\n tail_ = NULL;\n }\n /**\n * Creates a temporary node and points it to head, then points head to \n * the next node\n */\n SLNode* temp_node = head_;\n head_ = head_->next_node();\n // Delets the temporary node and sets it to null, then decreases size by 1\n delete temp_node;\n temp_node = NULL;\n size_ = size_ - 1;\n }\n }\n /*\n --removes the last node (tail) from the list,\n\t or does nothing if the list is empty\n\t */\n\tvoid SLList::RemoveTail()\n\t{\n\t /**\n\t * Checks if list is empty\n\t */\n\t if(head_ != NULL)\n {\n /**\n * Checks if head_ is equal to tail_ and calls the RemoveHead() function\n * if it is\n */\n if(head_ != tail_)\n {\n /**\n * Creates a temporary node and points it to head\n */\n SLNode* temp_node = head_;\n /**\n * Loops through the list and checks if the next node is the tail,\n * if it is not then it iterates to the next node\n */\n while(temp_node->next_node() != tail_)\n {\n temp_node = temp_node->next_node();\n }\n /**\n * Sets the last node in the list to null and deletes the tail,\n * then sets tail equal to the temp node and decreases the size \n * variable\n */\n temp_node->set_next_node(NULL);\n delete tail_;\n tail_ = temp_node;\n size_ = size_ - 1;\n } else \n {\n RemoveHead();\n }\n }\n\t}"
},
{
"alpha_fraction": 0.6526315808296204,
"alphanum_fraction": 0.692105233669281,
"avg_line_length": 24.399999618530273,
"blob_id": "ca145df38ba0e2e346121d3ec4251459b08c507e",
"content_id": "032f22cf568c3999e923cbcd7781aa1481073379",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 380,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 15,
"path": "/Topic 1/lab 4/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\nlab4test: lab_4_unit_test.o lab_4.o\n\tg++ -Wall -g -o lab4test lab_4.o lab_4_unit_test.o\n\n#creates the lab4 object file\t\nlab4: lab_4.cpp lab_4.h\n\tg++ -Wall -g -c lab_4.cpp\n\n#creates the unit test object file\nlab_4_unit_test: lab_4_unit_test.cpp\n\tg++ -Wall -g -c lab_4_unit_test.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o lab4"
},
{
"alpha_fraction": 0.5777632594108582,
"alphanum_fraction": 0.5874427556991577,
"avg_line_length": 31.675212860107422,
"blob_id": "4d44e17ce7c646306d8c179476e5d146315852f2",
"content_id": "74a6cb53c7ddd10ef0527cb59c010a84089c2f74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7645,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 234,
"path": "/Topic 1/lab 3/lab_3.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "no/*\n * Name : lab_3.cpp\n * Author : David Dalton\n * Description : Using branching statements, looping statements and string and\n * character functions complete the functions\n */\n\n#include \"lab_3.h\"\n\n\n/*\n * Return the input string with all characters converted to lowercase.\n * @param string input - The string that will be converted to all lowercase\n * @return string - a string containing the converted input string\n */\nstring ToLower(string input) {\n int i;\n int length = input.length();\n int currentLetter;\n/*\n Loops through input string and compares the ASCII values of each char to check\n if it is upper or lower case. If it is upper case then it adds 32\n */\n for (i=0; i<length;i++){\n currentLetter = input[i];\n if (( currentLetter > 64) && (currentLetter < 91)) {\n currentLetter = (currentLetter + 32);\n input[i] = currentLetter;\n \n }\n }\n //Takes result of loop and puts it into input variable, then returns input\n \n return input;\n}\n\n/*\n * Return the input string with all characters converted to uppercase.\n * @param string input - The string that will be converted to all uppercase\n * @return string - a string containing the converted input string\n */\nstring ToUpper(string input) {\n int i;\n int length = input.length();\n int currentLetter;\n/*\n Loops through input string and compares the ASCII values of each char to check\n if it is upper or lower case. If it is lower case then it subracts 32\n */\n for (i=0; i<length;i++){\n currentLetter = input[i];\n if (( currentLetter > 96) && (currentLetter < 123)) {\n currentLetter = (currentLetter - 32);\n input[i] = currentLetter;\n }\n }\n //Takes result of loop and puts it into input variable, then returns input\n return input;\n}\n\n/*\n * Tell the story of Goldilocks. For example, if item is \"bed\" and number is 1,\n * the story will say \"This bed is too soft\". \"item\" parameter will be passed\n * in as all lowercase characters\n * Cases:\n * -item: \"porridge\", number: 1, return \"This porridge is too hot\"\n * -item: \"porridge\", number: 2, return \"This porridge is too cold\"\n * -item: \"porridge\", number: 3, return \"This porridge is just right\"\n * -item: \"chair\", number: 1, return \"This chair is too big\"\n * -item: \"chair\", number: 2, return \"This chair is too small\"\n * -item: \"chair\", number: 3, return \"This chair is just right\"\n * -item: \"bed\", number: 1, return \"This bed is too hard\"\n * -item: \"bed\", number: 2, return \"This bed is too soft\"\n * -item: \"bed\", number: 3, return \"This bed is just right\"\n * @param string item - Represents the item in the story (\"porridge\", \"chair\",\n * and \"bed\" are the only legal values -- will default to\n * \"bed\" on invalid argument)\n * @param int number - which item (1, 2, and 3 are the only legal values -- will\n * default to 3 on invalid argument)\n * @return string - The output string specified in the documentation above\n */\n\nstring Goldilocks(string item, int number) {\n ToLower(item);\n string storyLine;\n /*\n Takes user input, number, and uses it as a case for a switch. It then compares\n the second input, item to determine which string to return\n */\n switch (number) {\n case 1:\n if (item == \"porridge\") {\n storyLine = \"This porridge is too hot\";\n } else if (item == \"chair\"){\n storyLine = \"This chair is too big\";\n } else if (item == \"bed\"){\n storyLine = \"This bed is too hard\";\n }\n break;\n case 2:\n if (item == \"porridge\") {\n storyLine = \"This porridge is too cold\";\n } else if (item == \"chair\"){\n storyLine = \"This chair is too small\";\n } else if (item == \"bed\"){\n storyLine = \"This bed is to softt\";\n }\n break;\n case 3:\n if (item == \"porridge\") {\n storyLine = \"This porridge is just right\";\n } else if (item == \"chair\"){\n storyLine = \"This chair is just right\";\n } else if (item == \"bed\"){\n storyLine = \"This bed is just right\";\n }\n }\n //Returns value of string stroyLine\n return storyLine;\n}\n\n/*\n * Compute the outcome of a round of a rock-scissor-paper game. Lowercase or\n * uppercase values for player_one and player_two arguments are acceptable.\n * Possible inputs: 'R' rock, 'S' scissor, 'P' paper\n * Conditions\n * -rocks beats scissors\n * -scissors beats paper\n * -paper beats rock\n * @param char player_one - Represents player one's \"play\" ('R', 'S', or 'P')\n * @param char player_two - Represents player two's \"play\" ('R', 'S', or 'P')\n * @return int - 1 if player one wins, 2 if player two wins, 3 on a draw,\n * 0 if invalud inputs\n */\n \nint RockScissorPaper(char player_one, char player_two) {\n //Takes input param of player_one and player_two and converts them to uppercase\n player_one = toupper(player_one);\n player_two = toupper(player_two);\n /*\n Uses input of player_one as a argument for a switch to determine results.\n Compares input of player_one to input of player_two to determine results and\n return those results.\n */\n switch (player_one) {\n case 'R':\n if ((player_two == 'S') || (player_two == 'L')) {\n return 1;\n } else if ((player_two == 'R')){\n return 3;\n } else if ((player_two == 'P') || (player_two == 'K')){\n return 2;\n } else {\n return 0;\n }\n break;\n case 'P':\n if ((player_two == 'R') || (player_two == 'P')) {\n return 1;\n } else if ((player_two == 'P')){\n return 3;\n } else if ((player_two == 'S') || (player_two == 'L')){\n return 2;\n } else {\n return 0;\n }\n break;\n case 'S':\n if ((player_two == 'P') || (player_two == 'L')) {\n return 1;\n } else if ((player_two == 'S')){\n return 3;\n } else if ((player_two == 'R') || (player_two == 'K')){\n return 2;\n } else {\n return 0;\n }\n break;\n case 'L':\n if ((player_two == 'P') || (player_two == 'K')) {\n return 1;\n } else if ((player_two == 'L')){\n return 3;\n } else if ((player_two == 'R') || (player_two == 'S')){\n return 2;\n } else {\n return 0;\n }\n break;\n case 'K':\n if ((player_two == 'S') || (player_two == 'R')) {\n return 1;\n } else if ((player_two == 'K')){\n return 3;\n } else if ((player_two == 'P') || (player_two == 'L')){\n return 2;\n } else {\n return 0;\n }\n break;\n default:\n return 0;\n }\n \n}\n\n//Main for testing purposes only!!!\nint main() {\n string lowercase = \"lowercase!H\";\n lowercase = ToUpper(lowercase);\n cout << lowercase << endl;\n string uppercase = \"UPPERCASE!h\";\n uppercase = ToLower(uppercase);\n cout << uppercase << endl;\n cout << Goldilocks(\"porridge\", 1) << endl;\n cout << Goldilocks(\"porridge\", 2) << endl;\n cout << Goldilocks(\"porridge\", 3) << endl;\n cout << Goldilocks(\"chair\", 1) << endl;\n cout << Goldilocks(\"chair\", 2) << endl;\n cout << Goldilocks(\"chair\", 3) << endl;\n cout << Goldilocks(\"bed\", 1) << endl;\n cout << Goldilocks(\"bed\", 2) << endl;\n cout << Goldilocks(\"bed\", 3) << endl;\n cout << \"Lets play Rock, Paper, Scissors, Lizard, Spock!\" << endl;\n cout << \"Player 1 enter your selection:\" << endl;\n cout << \"R - Rock P - Paper S - Scissors L - Lizard K - Spock.\" << endl;\n char player_one;\n cin >> player_one;\n cout << \"Player 2 enter your selection:\" << endl;\n cout << \"R - Rock P - Paper S - Scissors L - Lizard K - Spock.\" << endl;\n char player_two;\n cin >> player_two;\n cout << RockScissorPaper(player_one, player_two) << endl;\n}"
},
{
"alpha_fraction": 0.6226279735565186,
"alphanum_fraction": 0.6242391467094421,
"avg_line_length": 33.80769348144531,
"blob_id": "91a66413eb2f9914dd1278b354eff0ff402341de",
"content_id": "ea422f4c532135616c6b95eb4c4397c87e1b55de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5586,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 156,
"path": "/CSCI465v3/firstapp/views.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, redirect\r\nfrom django.contrib.auth.models import User\r\nfrom django.http import HttpResponse, JsonResponse\r\nfrom .models import *\r\nfrom .forms import *\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.db import transaction\r\nfrom django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector\r\nfrom django.views.generic import ListView\r\n\r\n# from django.contrib.auth.forms import UserCreationForm\r\n\r\n# Create your views here.\r\ndef index(request):\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.all().order_by('-authored')\r\n to_return = []\r\n for suggest in suggestions:\r\n data = {}\r\n data[\"suggestion\"]=suggest.suggestion\r\n data[\"image\"]=suggest.image\r\n data[\"idescription\"]=suggest.idescription\r\n data[\"author\"]=suggest.author\r\n # data[\"comments\"]=[]\r\n data[\"id\"]=suggest.id\r\n # comments = comment.objects.all().filter(suggestion=suggest).order_by('-authored')\r\n # for comm in comments:\r\n # data[\"comments\"]+=[{\"comment\":comm.comment, \"author\":comm.author}]\r\n # , \"comment_form\":c_form\r\n to_return+=[data]\r\n context = {\"suggestions\":to_return, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\n\r\ndef page2(request):\r\n suggestions = suggestion.objects.all()\r\n toReturn = \"\"\r\n for sugg in suggestions:\r\n toReturn += sugg.suggestion + \" \"\r\n context = {\"variable\":toReturn}\r\n return render(request,\"default.html\",context)\r\n\r\ndef register(request):\r\n if request.method == 'POST':\r\n form = registration_form(request.POST)\r\n if form.is_valid():\r\n form.save(commit=True)\r\n return redirect(\"/\")\r\n else:\r\n form = registration_form()\r\n context = {\"form\":form}\r\n return render(request,\"register.html\",context)\r\n\r\ndef lfg(request):\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.filter(suggestion='hat')\r\n to_return = []\r\n for suggest in suggestions:\r\n data = {}\r\n data[\"suggestion\"]=suggest.suggestion\r\n data[\"image\"]=suggest.image\r\n data[\"idescription\"]=suggest.idescription\r\n data[\"author\"]=suggest.author\r\n data[\"id\"]=suggest.id\r\n to_return+=[data]\r\n context = {\"suggestions\":to_return, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\ndef lfm(request):\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.filter(suggestion='hat')\r\n to_return = []\r\n for suggest in suggestions:\r\n data = {}\r\n data[\"suggestion\"]=suggest.suggestion\r\n data[\"image\"]=suggest.image\r\n data[\"idescription\"]=suggest.idescription\r\n data[\"author\"]=suggest.author\r\n data[\"id\"]=suggest.id\r\n to_return+=[data]\r\n context = {\"suggestions\":to_return, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\ndef wtb(request):\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.filter(suggestion='hat')\r\n to_return = []\r\n for suggest in suggestions:\r\n data = {}\r\n data[\"suggestion\"]=suggest.suggestion\r\n data[\"image\"]=suggest.image\r\n data[\"idescription\"]=suggest.idescription\r\n data[\"author\"]=suggest.author\r\n data[\"id\"]=suggest.id\r\n to_return+=[data]\r\n context = {\"suggestions\":to_return, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\ndef wts(request):\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.filter(suggestion='hat')\r\n to_return = []\r\n for suggest in suggestions:\r\n data = {}\r\n data[\"suggestion\"]=suggest.suggestion\r\n data[\"image\"]=suggest.image\r\n data[\"idescription\"]=suggest.idescription\r\n data[\"author\"]=suggest.author\r\n data[\"id\"]=suggest.id\r\n to_return+=[data]\r\n context = {\"suggestions\":to_return, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\n# Source https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html\r\n@login_required\r\ndef profile(request):\r\n if request.method == 'POST':\r\n user_form = UserForm(request.POST, instance=request.user)\r\n profile_form = ProfileForm(request.POST, instance=request.user.profile)\r\n if user_form.is_valid() and profile_form.is_valid():\r\n user_form.save()\r\n profile_form.save()\r\n return redirect('.')\r\n # else:\r\n # messages.error(request, _('Please correct the error below.'))\r\n else:\r\n user_form = UserForm(instance=request.user)\r\n profile_form = ProfileForm(instance=request.user.profile)\r\n return render(request, 'profile.html', {\r\n 'user_form': user_form,\r\n 'profile_form': profile_form\r\n })\r\n\r\n@login_required\r\ndef suggestion_view(request):\r\n if request.method == 'POST':\r\n if request.user.is_authenticated:\r\n form = suggestion_form(request.POST, request.FILES)\r\n if form.is_valid():\r\n form.save(request)\r\n return redirect(\"/\")\r\n else:\r\n form=suggestion_form()\r\n else:\r\n form = suggestion_form()\r\n context = {\"form\":form}\r\n return render(request,\"suggest.html\",context)\r\n\r\ndef suggestions(request):\r\n suggestions = suggestion.objects.all() #.order_by('-authored')\r\n toReturn = {}\r\n toReturn[\"suggestions\"]=[]\r\n # toReturn[\"haha\"]=[]\r\n for sugg in suggestions:\r\n toReturn[\"suggestions\"]+=[{\"suggest\":sugg.suggestion}]\r\n return JsonResponse(toReturn)\r\n"
},
{
"alpha_fraction": 0.6592844724655151,
"alphanum_fraction": 0.6655309200286865,
"avg_line_length": 21.303796768188477,
"blob_id": "70cba34021f456d596f7f23c3ef29e294dceb770",
"content_id": "485a718d806ac9e42c4269a05f561e055064dfc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1761,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 79,
"path": "/Topic 2/lab 4/magic_item.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : magic_item.h\n * Author : David Dalton\n * Description : Derived Class Header File\n */\n\n#ifndef MAGIC_H\n#define MAGIC_H\n\n#include \"item.h\"\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::string;\nusing std::stringstream;\nusing std::setprecision;\nusing std::fixed;\nusing std::setfill;\nusing std::setw;\n\n/*\n * Class Item.\n */\nclass MagicItem : public Item {\n public:\n /*\n * Constructor\n *takes four parameters, one for each private member variable and two for the\n *base class\n *defaults name_ to \"magicitem\"\n *defaults value_ to 0\n *defaults description_ to \"no description\"\n *defaults mana_required_ to 0\n */\n MagicItem(string name = \"magicitem\", unsigned int value = 0, \n string description = \"no description\", unsigned int mana_required = 0);\n /*\n *Destructor\n */\n virtual ~MagicItem();\n /*\n * Mutator #1\n *sets the value of description to the input string\n */\n void set_description(string description);\n /*\n * Mutator #2\n *sets the value of mana_required_ to the input int\n */\n void set_mana_required(unsigned int mana_required);\n /*\n * Acessor #1\n *retrieves the value of description_\n */\n string description();\n /*\n * Acessor #2\n *retrieves the value of mana_required_\n */\n unsigned int mana_required();\n /*\n *string ToString()\n *returns a string containing name_, value_, desciption_, and\n *mana_required_\n *(uses Item::ToString in its implementation)\n *Format -- name_, $value_, description_, requires mana_required_ mana\n *EXAMPLE -- hat, $10, made of felt, requires 2 mana\n */\n string ToString();\n private:\n string desciption_;\n unsigned int mana_required_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6395147442817688,
"alphanum_fraction": 0.6481802463531494,
"avg_line_length": 27.38524627685547,
"blob_id": "fb11e6033f287bfab3a825bb010eb51c788eff51",
"content_id": "d6910cfc93e6b64e5e6765db5d1f8818131ba598",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3462,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 122,
"path": "/Topic 2/lab 2/temperature.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : temperature.h\n * Author : David Dalton\n * Description : Class Header File\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::string;\nusing std::stringstream;\nusing std::setprecision;\nusing std::fixed;\n\n/*\n * Class Temperature.\n * A class that converts temperatures. It will always internally store the value\n * in kelvin.\n */\nclass Temperature {\n public:\n /*\n * Constructor #1.\n * Sets kelvin_ to 0\n */\n Temperature();\n\n /*\n * Constructor #2.\n * Sets kelvin_ to the supplied value\n * @param double kelvin - The value to set the internal kelvin to\n */\n Temperature(double kelvin);\n\n /*\n * Constructor #3.\n * Converts the supplied temperature to kelvin and internally stores it.\n * The temperature's unit will be provided in the second argument.\n * If the second argument is not value (i.e. not 'F' or 'C') assume the\n * temperature is in kelvin\n * @param double temp - The value to set the internal kelvin to once\n * - converted.\n * @param char unit - The type of unit temp is. Will be either 'F' or 'C',\n * case-insensitive\n */\n Temperature(double temp, char unit);\n\n /*\n * The temperature will come in as kelvin and this function will set the\n * internal temp to this value\n * @param double kelvin - The value to set the internal kelvin to.\n */\n void SetTempFromKelvin(double kelvin);\n\n\n /*\n * The temperature will come in as Celsius and this function will set the\n * internal temp to this value, once converted to kelvin\n * Formula: k = c + 273.15\n * @param double celsius - The value (in celsius) to set the internal kelvin\n * - to.\n */\n void SetTempFromCelsius(double celsius);\n\n\n /*\n * The temperature will come in as Fahrenheit and this function will set the\n * internal temp to this value, once converted to kelvin\n * Formula: k = (5.0 * (f - 32) / 9) + 273.15\n * @param double fahrenheit - The value (in fahrenheit) to set the internal\n * - kelvin to.\n */\n void SetTempFromFahrenheit(double fahrenheit);\n\n /*\n * Gets the internal temperature in Kelvin.\n * @return double - The temperature in Kelvin\n */\n double GetTempAsKelvin() const;\n\n /*\n * Returns the internal temp converted to Celsius\n * Formula: k - 273.15\n * @return double - The temperature in Celsius\n */\n double GetTempAsCelsius() const;\n\n /*\n * Returns the internal temp converted to Fahrenheit\n * Formula: ((c * 9.0) / 5) + 32;\n * @return double - The temperature in Fahrenheit\n */\n double GetTempAsFahrenheit() const;\n\n /*\n * Get a string representation of the temperature.\n * The string will be formatted as:\n * \"TEMP UNIT\"\n * where TEMP is the temperature to 2 decimal places and UNIT is either\n * \"Kelvin\", \"Celsius\", or \"Fahrenheit\".\n * The conversion to perform is denoted by the parameter.\n * If the unit given through the argument is invalid, set the string to:\n * \"Invalid Unit\"\n * @uses stringstream\n * @param char unit - The conversion to perform, either 'K', 'C' or 'F',\n * defaults to 'K' and is case-insensitive\n * @return string - A string representation of the temperature or invalid if\n * the provided unit is not recognized\n */\n string ToString(char unit = 'K') const;\n\n private:\n double kelvin_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6378446221351624,
"alphanum_fraction": 0.6382623314857483,
"avg_line_length": 32.69565200805664,
"blob_id": "3bfd455ed6b4480e2d74c91fc4660ee61895e1d4",
"content_id": "a63bc4443be9e88745355cc726827b4545ca7d8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2394,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 69,
"path": "/CSCI465/firstapp/views.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, redirect\r\nfrom django.contrib.auth.models import User\r\nfrom django.http import HttpResponse, JsonResponse\r\nfrom .models import *\r\nfrom .forms import *\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.db import transaction\r\n\r\n# from django.contrib.auth.forms import UserCreationForm\r\n\r\n# Create your views here.\r\ndef index(request):\r\n if request.method == 'POST':\r\n form = suggestion_form(request.POST)\r\n if form.is_valid():\r\n modentry = suggestion(suggestion=form.cleaned_data['suggestion'])\r\n modentry.save()\r\n else:\r\n form = suggestion_form()\r\n suggestions = suggestion.objects.all()\r\n context = {\"variable\":suggestions, \"form\":form}\r\n return render(request,\"default.html\",context)\r\n\r\ndef page2(request):\r\n suggestions = suggestion.objects.all()\r\n toReturn = \"\"\r\n for sugg in suggestions:\r\n toReturn += sugg.suggestion + \" \"\r\n context = {\"variable\":toReturn}\r\n return render(request,\"default.html\",context)\r\n\r\ndef register(request):\r\n if request.method == 'POST':\r\n form = registration_form(request.POST)\r\n if form.is_valid():\r\n form.save(commit=True)\r\n return redirect(\"/\")\r\n else:\r\n form = registration_form()\r\n context = {\"form\":form}\r\n return render(request,\"register.html\",context)\r\n\r\ndef suggestions(request):\r\n suggestions = suggestion.objects.all()\r\n toReturn = {}\r\n toReturn[\"suggestions\"]=[]\r\n for sugg in suggestions:\r\n toReturn[\"suggestions\"]+=[{\"suggest\":sugg.suggestion}]\r\n return JsonResponse(toReturn)\r\n\r\n@login_required\r\n# @transaction.atomic\r\ndef profile(request):\r\n if request.method == 'POST':\r\n user_form = UserForm(request.POST, instance=request.user)\r\n profile_form = ProfileForm(request.POST, instance=request.user.profile)\r\n if user_form.is_valid() and profile_form.is_valid():\r\n user_form.save()\r\n profile_form.save()\r\n return redirect('.')\r\n # else:\r\n # messages.error(request, _('Please correct the error below.'))\r\n else:\r\n user_form = UserForm(instance=request.user)\r\n profile_form = ProfileForm(instance=request.user.profile)\r\n return render(request, 'profile.html', {\r\n 'user_form': user_form,\r\n 'profile_form': profile_form\r\n })\r\n"
},
{
"alpha_fraction": 0.6699507236480713,
"alphanum_fraction": 0.697044312953949,
"avg_line_length": 24.375,
"blob_id": "717b19bc3196249142bfc3aaa565131c90dcce10",
"content_id": "9ea33859a560b8fbd60813e3684941a837f25c23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 406,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 16,
"path": "/Topic 3/Lab 2/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nsl_nodetest: lab_17_unit_test.o sl_node.o\n\tg++ -Wall -g -o lab2test sl_node.o lab_17_unit_test.o\n\n#creates the lab object file\t\nsl_node: sl_node.cpp sl_node.h\n\tg++ -Wall -g -c sl_node.cpp\n\n#creates the lab unit test object file\nlab_17_unit_test: lab_17_unit_test.cpp\n\tg++ -Wall -g -c lab_17_unit_test.cpp\n\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6496163606643677,
"alphanum_fraction": 0.6905370950698853,
"avg_line_length": 23.4375,
"blob_id": "8d24a0d269a08b77110317ec1ecab4a840c34c3e",
"content_id": "07e5c9aed62bc20382621c01631f4dc9c70a0bd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 391,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 16,
"path": "/Topic 2/lab 1/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nlab1test: lab_1_unit_test.o lab_1.o\n\tg++ -Wall -g -o lab7test lab_7.o lab_7_unit_test.o\n\n#creates the lab1 object file\t\nlab1: lab_1.cpp lab_1.h\n\tg++ -Wall -g -c lab_1.cpp\n\n#creates the lab 1 unit test object file\nlab_1_unit_test: lab_1_unit_test.cpp\n\tg++ -Wall -g -c lab_1_unit_test.cpp\n\n\n#cleans up old .o files\t\nclean:\n\trm *.o lab1test "
},
{
"alpha_fraction": 0.4801003932952881,
"alphanum_fraction": 0.4933668076992035,
"avg_line_length": 19.217391967773438,
"blob_id": "e67650e1f73df2e1d0ac98ce55ac39c1f57991aa",
"content_id": "561b9fa9e88d8ee6668e9dd16aa2c927cca82ed7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2789,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 138,
"path": "/ICE/team1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Team 1 code\n */\n#include<iostream>\n#include <array>\n/*\n * Outputs the scores in the array\n * @param int[] scores - The array to fill up\n * @param const int &size - The size of the array\n */\nvoid Output(int scores[], const int &size)\n{\n for (int i = 0; i < scores[].size; i++)\n {\n cout << scores[i] << endl;\n }\n}\n\n //1.1 (Hunter and Nick)\n void Reverse(int &scores[])\n {\n int length=scores.size();\n \n scoreH[length];\n \n for (int i=0;i<=length;i++)\n {\n scoreH[i]=scores[i];\n }\n \n for (int i=0;i<=length;i++)\n {\n scores[i]=scoreH[length-i];\n }\n }\n\n //1.2 (Marie)\n void mfunc(int &mlarge, int &msmall, int marray[], int msize)\n {\n int i;\n for (i=0; i<msize; i++)\n {\n if (marray[i] > mlarge)\n {\n mlarge = marray[i];\n }\n }\n for (i=0; i<msize; i++)\n {\n if (marray[i] < msmall)\n {\n msmall = marray[i];\n }\n }\n }\n \n \n //1.3 River and Evan's Bit\n bool HighToLow(int array[])//function declaration\n {\n int size = array.size();\n for (int i = 0; i < size; i++ )//for loop, incriments int i\n {\n if (array[i] < array[i + 1])//checks to ensure that i < i + 1\n {\n return false;//if not it returns false\n exit;\n }\n }P\n return true;//if all passes, it will return true\n }\n \n //Russ and David 1.4\nint ReverseArray(int Palendrome)\n{\n int i= 0;\n int j = Palendrome.size();\n bool PaleTrue = true;\n while(PaleTrue)\n {\n if(Palendrome[i]==Palendrome[j])\n {\n i++;\n \tj--;\n \tif (i>j)\n \t {\n cout << \"Its a Palendrome\"<<endl;\n PaleTrue = false;\n }\n }\n else\n { \n PaleTrue = false;\n cout << \"It's not a Palendrome.\"<<endl;\n }\n}\n //Ends here\n \n \n /*\n * Create a main function that uses the following array:\n * int scores[] = { 1, 2, 3, 4, 5 };\n * and uses all of the functions provided (as well as output).\n * 1. Output all values of the array\n * followed by the numbers on your sheets. Output all returned\n * answers with appropriate verbage.\n */\n \n \n int main ()\n {\n int large = 0;\n int small =0;\n \n int scores[] = { 1, 2, 3, 4, 5 };\n \n Reverse(scores)\n cout<<\"Reversed array is \";\n for (int i=0; i<5; i++)\n {\n cout<<scores[i]<<\", \";\n }\n cout<<endl;\n \n mfunc(large, small, scores, 5);\n cout << \"Largest: \" << large;\n cout << endl << \"Smallest: \" << small;\n \n \n bool high_to_low_check;\n high_to_low_check = HighToLow(scores[]);\n cout << \"High to low check returned : \" << high_to_low_check << endl;\n \n cout << ReverseArray(scores)<<\"1.4\\n\";\n \n \n return 0;\n }"
},
{
"alpha_fraction": 0.3503313958644867,
"alphanum_fraction": 0.35958680510520935,
"avg_line_length": 43.07368469238281,
"blob_id": "144982365bc92443bb3d18daf64d31acd8de050d",
"content_id": "bb4786e30a870406e9b910d29c2914f88a9b2292",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 16747,
"license_type": "no_license",
"max_line_length": 222,
"num_lines": 380,
"path": "/Topic 2/Assignment 2/atm.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : atm.cpp\n * Author : David Dalton\n * Description : Program to test the account programs\n */\n \n#include \"CinReader.cpp\"\n#include \"bank_account.h\"\n#include \"checking_account.h\"\n#include \"savings_account.h\"\n#include \"credit_account.h\"\n#include <typeinfo>\n\nint atm()\n{\n CinReader reader;\n BankAccount myBanking;\n bool end_program = false;\n bool done = false;\n long dollars;\n int cents;\n do\n {\n cout << \"Select the type of account you wish to create\" << endl;\n cout << \"1 Bank Account 2 - Checking 3 - Savings 4 - Credit\\n\" << endl;\n int choice = reader.readInt(1,4);\n string account_name;\n long balance_dollars;\n int balance_cents;\n double interest_rate;\n switch(choice)\n { \n //Bank account options\n case 1:\n {\n cout << \"Set the dollar amount of your account balance\\n\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\\n\" << endl;\n balance_cents = reader.readInt(0,99);\n myBanking.SetDollars(balance_dollars);\n myBanking.SetCents(balance_cents);\n cout << \"Please select from the following options.\" << endl;\n while(!done)\n {\n cout << \"1 - Show account balance\\n2 - Deposit\\n3 - Withdraw\\n4 - Show recent transactions\\n5 - Clear Transaction history\\n6 - Exit ATM\\n\" << endl;\n int choice = reader.readInt(1,6);\n switch(choice)\n {\n case 1:\n {\n cout << myBanking.ShowBalance() << endl;\n break;\n }\n \n case 2:\n {\n cout << \"Please enter the amount in dollars you would like to deposit, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myBanking.DepositAccount(dollars, cents);\n break;\n }\n \n case 3:\n {\n cout << \"Please enter the amount in dollars you would like to withdraw, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myBanking.WithdrawAccount(dollars, cents);\n break;\n }\n \n case 4:\n {\n for(int i = 0;i<10;i++)\n {\n if(myBanking.GetRecentTransactions(i) == \"\")\n {\n cout << \"none\" << endl;\n }else\n {\n cout << myBanking.GetRecentTransactions(i) << endl;\n }\n }\n \n cout << \"Your last transaction was: \" << myBanking.GetLastTransaction() << endl;\n break;\n }\n \n case 5:\n {\n myBanking.ClearRecentTransactions();\n break;\n }\n \n case 6:\n {\n done = true;\n }\n }\n }\n break;\n }\n \n //Checking account options\n case 2:\n {\n CheckingAccount myChecking;\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\\n\" << endl;\n balance_cents = reader.readInt(0,99);\n myChecking.SetDollars(balance_dollars);\n myChecking.SetCents(balance_cents);\n cout << \"Please select from the following options.\" << endl;\n \n while(!done)\n {\n cout << \"1 - Show account balance\\n2 - Deposit Money/Check\\n3 - Withdraw/Write a check\\n4 - Show recent transactions\\n5 - Clear Transaction history\\n6 - Exit ATM\\n\" << endl;\n int choice = reader.readInt(1,6);\n switch(choice)\n {\n case 1:\n {\n cout << myChecking.ShowBalance() << endl;\n break;\n }\n \n case 2:\n {\n cout << \"Would you like to deposit money into your account or cash a check?\" << endl;\n cout << \"Press 1 to deposit money and 2 to cash a check\" << endl;\n int choice = reader.readInt(1,2);\n if(choice == 1)\n {\n cout << \"Please enter the amount in dollars you would like to deposit, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myChecking.DepositAccount(dollars, cents);\n } else \n {\n cout << \"Please enter the dollar value of the check you are cashing, followed by the cent value\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n cout << \"Please enter the amount you'd like to keep in dollars, followed by cents\\n\" << endl;\n long kept_dollars = reader.readInt(0);\n int kept_cents = reader.readInt(0,99);\n myChecking.CashCheck(dollars, cents, kept_dollars, kept_cents);\n }\n break;\n }\n \n case 3:\n {\n cout << \"Please enter the check number that you are writing\" << endl;\n int check_number = reader.readInt(0);\n cout << \"Please enter the amount the check is for in dollars, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myChecking.WriteCheck(check_number, dollars, cents);\n break;\n }\n \n case 4:\n {\n for(int i = 0;i<10;i++)\n {\n if(myChecking.GetRecentTransactions(i) == \"\")\n {\n cout << \"none\" << endl;\n }else\n {\n cout << myChecking.GetRecentTransactions(i) << endl;\n }\n }\n \n break;\n }\n \n case 5:\n {\n myChecking.ClearRecentTransactions();\n break;\n }\n case 6:\n {\n done = true;\n }\n }\n }\n break;\n }\n \n //Savings account options\n case 3:\n {\n SavingAccount mySavings;\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\" << endl;\n balance_cents = reader.readInt(0,99);\n cout << \"Select your interest rate\\n\" << endl;\n interest_rate = reader.readDouble();\n mySavings.SetDollars(balance_dollars);\n mySavings.SetCents(balance_cents);\n mySavings.SetInterestRate(interest_rate);\n cout << \"Please select from the following options.\" << endl;\n while(!done)\n {\n cout << \"1 - Show account balance\\n2 - Deposit\\n3 - Withdraw\\n4 - Show recent transactions\\n5 - Clear Transaction history\\n6 - Calculate Interest\\n7 - Show interest accumulated\\n8 - Exit ATM\\n\" << endl;\n int choice = reader.readInt(1,8);\n switch(choice)\n {\n case 1:\n {\n cout << mySavings.ShowBalance() << endl;\n break;\n }\n \n case 2:\n {\n cout << \"Please enter the amount in dollars you would like to deposit, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n mySavings.DepositAccount(dollars, cents);\n break;\n }\n \n case 3:\n {\n cout << \"Please enter the amount in dollars you would like to withdraw, followed by the amount in cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n mySavings.WithdrawAccount(dollars, cents);\n break;\n }\n \n case 4:\n {\n for(int i = 0;i<10;i++)\n {\n if(mySavings.GetRecentTransactions(i) == \"\")\n {\n cout << \"none\" << endl;\n }else\n {\n cout << mySavings.GetRecentTransactions(i) << endl;\n }\n }\n \n break;\n }\n \n case 5:\n {\n mySavings.ClearRecentTransactions();\n break;\n }\n \n case 6:\n {\n mySavings.CalculateInterest();\n break;\n }\n \n case 7:\n {\n cout << \"Interest accumulated this month: \" << mySavings.GetInterestAccumulatedMonth() << endl;\n cout << \"Interest accumulated this year: \" << mySavings.GetInterestAccumulatedYear() << \"\\n\" << endl;\n break;\n }\n \n case 8:\n {\n done = true;\n }\n }\n }\n break;\n }\n \n //Credit Account options\n case 4:\n {\n CreditAccount myCredit;\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\" << endl;\n balance_cents = reader.readInt(0,99);\n cout << \"Select your interest rate. NOTE: Must be greater or equal to 0.0\" << endl;\n interest_rate = reader.readDouble();\n cout << \"Set the dollar amount for your max balance\" << endl;\n long max_dollars = reader.readInt(0);\n cout << \"Set the cent amount for your max balance\\n\" << endl;\n int max_cents = reader.readInt(0, 99);\n myCredit.SetDollars(balance_dollars);\n myCredit.SetCents(balance_cents);\n myCredit.SetMaxBalanceDollars(max_dollars);\n myCredit.SetMaxBalanceCents(max_cents);\n myCredit.SetInterestRate(interest_rate);\n \n cout << \"Please select from the following options.\" << endl;\n while(!done)\n {\n cout << \"1 - Show account balance\\n2 - Deposit\\n3 - Withdraw\\n4 - Calculate Interest\\n5 - Clear Transaction history\\n6 - Calculate interest\\n7 - Show interest accumulated\\n8 - Exit ATM\\n\" << endl;\n int choice = reader.readInt(1,8);\n switch(choice)\n {\n case 1:\n {\n cout << myCredit.ShowBalance() << endl;\n break;\n }\n \n case 2:\n {\n cout << \"Please enter the amount you would like pay towards your balance in dollars, followed by cents\\n\" << endl << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myCredit.MakePayment(dollars, cents);\n break;\n }\n \n case 3:\n {\n cout << \"Please enter the transaction number for the charge\" << endl;\n int transaction = reader.readInt(0);\n cout << \"Please enter the amount of the transaction in dollars, followed by cents\\n\" << endl;\n dollars = reader.readInt(0);\n cents = reader.readInt(0,99);\n myCredit.ChargeCard(transaction, dollars, cents);\n break;\n }\n \n case 4:\n {\n for(int i = 0;i<10;i++)\n {\n if(myCredit.GetRecentTransactions(i) == \"\")\n {\n cout << \"none\" << endl;\n }else\n {\n cout << myCredit.GetRecentTransactions(i) << endl;\n }\n }\n \n break;\n }\n \n case 5:\n {\n myCredit.ClearRecentTransactions();\n break;\n }\n \n case 6:\n {\n myCredit.CalculateInterest();\n break;\n }\n \n case 7:\n {\n cout << \"Interest accumulated this month: \" << myCredit.GetInterestAccumulatedMonth() << endl;\n cout << \"Interest accumulated this year: \" << myCredit.GetInterestAccumulatedYear() << \"\\n\" << endl;\n break;\n }\n \n \n case 8:\n {\n done = true;\n }\n }\n }\n }//break\n }\n }while(!end_program);\n}"
},
{
"alpha_fraction": 0.5223880410194397,
"alphanum_fraction": 0.5251865386962891,
"avg_line_length": 17.982301712036133,
"blob_id": "a10fbaff3776fa21cd6a8553cbbac2f452b55445",
"content_id": "742639dfcc9dc78b657ae624175c2c3f12b2b019",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2144,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 113,
"path": "/Topic 3/Lab 3/sl_list.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_list.cpp\n * Author : David Dalton\n * Description : Node list lab.\n */\n \n#include \"sl_list.h\"\n\n/*\n Default Constructor\n --sets head_ to NULL\n --sets size_ to 0\n */\n SLList::SLList() \n {\n head_ = NULL;\n tail_ = NULL;\n size_ = 0;\n }\n /*\n Destructor\n --calls Clear()\n */\n SLList::~SLList() \n {\n SLList::Clear();\n }\n /*\n void InsertHead(int)\n --creates a new dynamic SLNode with the contents of \n the parameter and attaches as the new head of the list\n */\n void SLList::InsertHead(int insert) \n {\n SLNode* new_node = new SLNode(insert);\n new_node->set_next_node(head_);\n head_ = new_node;\n size_ = size_ + 1;\n if(tail == NULL)\n {\n tail_ = head_;\n }\n }\n /*\n void RemoveHead()\n --removes the head node from the list,\n or does nothing if the list is empty\n */\n void SLList::RemoveHead() \n {\n if(head_ != NULL)\n {\n if(head_ != tail_)\n {\n SLNode* temp_node = head_;\n head_ = head_->next_node();\n delete temp_node;\n temp_node = NULL;\n size_ = size_ - 1;\n } else {\n tail_ = NULL;\n }\n }\n }\n /*\n void Clear()\n --clears the entire contents of the list,\n freeing all memory associated with all nodes\n */\n void SLList::Clear() \n {\n while(head_ != NULL)\n {\n RemoveHead();\n }\n delete head_;\n head_ = NULL;\n }\n /*\n unsigned int size() const\n --accessor for size_\n */\n unsigned int SLList::size() const \n {\n return size_;\n }\n /*\n string ToString() const\n --returns a string representation of the contents\n of all nodes in the list, in the format\n NUM1, NUM2, ..., LASTNUM\n returns the empty string on an empty list (i.e. returns \"\")\n */\n string SLList::ToString() \n {\n if(head_ != NULL)\n {\n stringstream stream;\n SLNode* temp_node = head_;\n while(temp_node != NULL)\n {\n stream << temp_node->contents();\n if(temp_node->next_node() != NULL)\n {\n stream << \", \";\n }\n temp_node = temp_node->next_node();\n }\n return stream.str();\n } else {\n return \"\";\n }\n }"
},
{
"alpha_fraction": 0.6019417643547058,
"alphanum_fraction": 0.6073786616325378,
"avg_line_length": 26.698925018310547,
"blob_id": "7b94c3a5efca5818101baa4490012ef09fe0a27b",
"content_id": "8e2dabeb592034e511c65aa9839f9e6738354881",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2575,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 93,
"path": "/Topic 2/Assignment 2/savings_account.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : savings_account.h\n * Author : David Dalton\n * Description : Savings Account class header file\n */\n \n#ifndef SAVE_H\n#define SAVE_H\n\n#include \"bank_account.h\"\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::setfill;\nusing std::setw;\nusing std::setprecision;\nusing std::fixed;\n\nclass SavingAccount : public BankAccount\n{\n public:\n /*\n * Constructor\n *uses default values if none given\n */\n SavingAccount(string account_name = \"account\", long dollars = 0, \n int cents = 0, double interest_rate = 0.0, \n string last_transaction = \"none\",\n string interest_accumulated_month = \"$0.0\", \n string interest_accumulated_year = \"$0.0\");\n /*\n * Destructor \n *unused\n */\n virtual ~SavingAccount();\n /*\n * Mutator\n *sets the value of interest_rate_ to the input double\n */\n void SetInterestRate(double interest_rate = 0.0);\n /*\n * Mutator\n *uses stringstream to set the value of interest_accumulated_month_ to the\n *input values, separated by a decimal\n */\n void SetInterestAccumulatedMonth(long accumulated_dollars = 0, \n int accumulated_cents = 0);\n /*\n * Mutator\n *uses stringstream to set the value of interest_accumulated_year_ to the\n *input values, separated by a decimal\n */\n void SetInterestAccumulatedYear(long accumulated_dollars = 0, \n int accumulated_cents = 0);\n /*\n * Mutator\n *gets the interest rate and current value of dollars_ and cents_ and then\n *calculates the amount of interest based off of the interest rate. Then\n *adds the amount accruded by interest and adds it to the values of\n *dollars_W and cents_\n */\n void CalculateInterest();\n /*\n * Accessor\n *gets the value of interest_rate_ and returns it\n */\n double GetInterestRate();\n /*\n * Accessor\n *gets the value of interest_accumulated_month_ and returns it\n */\n string GetInterestAccumulatedMonth();\n /*\n * Accessor\n *gets the value of interest_accumulated_year_ and returns it\n */\n string GetInterestAccumulatedYear();\n \n private:\n double interest_rate_;\n string interest_accumulated_month_;\n string interest_accumulated_year_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6063058972358704,
"alphanum_fraction": 0.6126970648765564,
"avg_line_length": 32.01449203491211,
"blob_id": "14d80f9d8420c0562eda96da13d40235f88c8bfb",
"content_id": "03860ca40185a93d202e92378d4d47f27490db03",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2347,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 69,
"path": "/CSCI465v5old/firstapp/forms.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django import forms\r\nfrom django.core.validators import validate_unicode_slug\r\nfrom firstapp.models import CHOICES\r\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\r\nfrom django.contrib.auth.models import User\r\nfrom .models import *\r\n\r\nclass suggestion_form(forms.Form):\r\n suggestion = forms.CharField(label='Post Title', max_length=140)\r\n image=forms.ImageField(label=\"Image File\")\r\n # CHOICES = (('LFG', 'Lfg',), ('LFM', 'Lfm',),('WTS', 'Wtb',), ('WTS', 'Wts',))\r\n choice_field = forms.ChoiceField(widget=forms.Select(), choices=CHOICES)\r\n image_description=forms.CharField(label=\"Image Description\", max_length=144)\r\n\r\n def save(self, request , commit=True):\r\n suggest = suggestion()\r\n suggest.suggestion=self.cleaned_data['suggestion']\r\n suggest.choice_field=self.cleaned_data['choice_field']\r\n suggest.image=self.cleaned_data['image']\r\n suggest.idescription=self.cleaned_data['image_description']\r\n suggest.author=request.user\r\n if commit:\r\n suggest.save()\r\n return suggest\r\n # work in progress\r\n # CHOICES = (('1', 'LFG',), ('2', 'LFM',), ('3', 'WTB',), ('4', 'WTS',))\r\n # choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)\r\n\r\nclass LoginForm(AuthenticationForm):\r\n username=forms.CharField(\r\n label=\"Username\",\r\n max_length=30,\r\n widget=forms.TextInput(attrs={\r\n 'name':'username'\r\n })\r\n )\r\n password=forms.CharField(\r\n label=\"Password\",\r\n max_length=32,\r\n widget=forms.PasswordInput()\r\n )\r\n\r\nclass registration_form(UserCreationForm):\r\n email = forms.EmailField(\r\n label=\"Email\",\r\n required=True\r\n )\r\n\r\n class Meta:\r\n model = User\r\n fields = (\"username\", \"email\",\r\n \"password1\", \"password2\")\r\n\r\n def save(self, commit=True):\r\n user=super(registration_form,self).save(commit=False)\r\n user.email=self.cleaned_data[\"email\"]\r\n if commit:\r\n user.save()\r\n return user\r\n\r\nclass UserForm(forms.ModelForm):\r\n class Meta:\r\n model = User\r\n fields = ('first_name', 'last_name', 'email')\r\n\r\nclass ProfileForm(forms.ModelForm):\r\n class Meta:\r\n model = profile\r\n fields = ('bio', 'games', 'birth_date')\r\n"
},
{
"alpha_fraction": 0.5872092843055725,
"alphanum_fraction": 0.5891472697257996,
"avg_line_length": 15.396825790405273,
"blob_id": "59fda335a8c9d7538bcf769cb271f36dbca4bb8d",
"content_id": "0d498b5c9e0ea7397a37440c0b84cd19133732b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1032,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 63,
"path": "/Topic 3/Lab 3/sl_node.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_node.h\n * Author : David Dalton\n * Description : Header File for Lab 2.\n */\n\n#ifndef NODE_H\n#define NODE_H\n\n#include <iostream>\n#include <string>\n#include <cstring>\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nclass SLNode \n{\n public:\n /*\n *Default Constructor\n *--sets next_node_ to NULL\n *--sets contents_ to 0\n */\n SLNode();\n /*\n *Overloaded Constructor\n *--int parameter assigned to contents_\n *--sets next_node to NULL\n */\n SLNode(int contents);\n /*\n *Destructor\n *--does nothing\n */\n ~SLNode();\n /*\n *void set_contents(int)\n *--mutator for contents_\n */\n void set_contents(int contents);\n /*\n *int contents() const\n *--accessor for contents_\n */\n int contents();\n /*\n *void set_next_node(SLNode*)\n *--mutator for next_node_\n */\n void set_next_node(SLNode* next_node);\n /*\n *SLNode* next_node() const\n *--accessor for next_node_\n */\n SLNode* next_node() const;\n \n private:\n SLNode* next_node_;\n int contents_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6545454263687134,
"alphanum_fraction": 0.6935064792633057,
"avg_line_length": 24.733333587646484,
"blob_id": "98e561df201dcffe6eab18c5ee31e359c6799a00",
"content_id": "b625ecaa4e471c071071d24d3393d961e066fe82",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 15,
"path": "/Topic 1/lab 5/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\nlab5test: lab_5_unit_test.o lab_5.o\n\tg++ -Wall -g -o lab5test lab_5.o lab_5_unit_test.o\n\n#creates the lab5 object file\t\nlab5: lab_5.cpp lab_5.h\n\tg++ -Wall -g -c lab_5.cpp\n\n#creates the unit test object file\nlab_5_unit_test: lab_5_unit_test.cpp\n\tg++ -Wall -g -c lab_5_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o lab5test"
},
{
"alpha_fraction": 0.47962483763694763,
"alphanum_fraction": 0.5523932576179504,
"avg_line_length": 24.121952056884766,
"blob_id": "08335feadd1fc8393d4bbb54dfa3de74019b0dda",
"content_id": "94ce9bdbce1f7bcb62f8442ed15b0e45aa430677",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3092,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 123,
"path": "/Topic 3/Lab 1/lab_12_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_12_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #12 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_12.h\"\n\nTEST_CASE(\"Make Dynamic Integer Array\") {\n SECTION(\"MakeDynoIntArray(3)\") {\n int* my_array = MakeDynoIntArray(3);\n CHECK(my_array != NULL);\n }\n}\n\nTEST_CASE(\"Sum Array Values\") {\n int* my_array = MakeDynoIntArray(3);\n unsigned int my_array_size = 3;\n\n SECTION(\"Sum({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Sum(my_array, my_array_size) == 60);\n }\n\n SECTION(\"Sum({30, 10, 20})\") {\n my_array[0] = 30, my_array[1] = 10, my_array[2] = 20;\n CHECK(Sum(my_array, my_array_size) == 60);\n }\n\n SECTION(\"Sum({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Sum(my_array, my_array_size) == 60);\n }\n\n SECTION(\"Sum({20, 10, 30})\") {\n my_array[0] = 20, my_array[1] = 10, my_array[2] = 30;\n CHECK(Sum(my_array, my_array_size) == 60);\n }\n}\n\nTEST_CASE(\"Max Value in Array\") {\n int* my_array = MakeDynoIntArray(3);\n unsigned int my_array_size = 3;\n\n SECTION(\"Max({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Max(my_array, my_array_size) == 30);\n }\n\n SECTION(\"Max({30, 10, 20})\") {\n my_array[0] = 30, my_array[1] = 10, my_array[2] = 20;\n CHECK(Max(my_array, my_array_size) == 30);\n }\n\n SECTION(\"Max({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Max(my_array, my_array_size) == 30);\n }\n\n SECTION(\"Sum({20, 10, 30})\") {\n my_array[0] = 20, my_array[1] = 10, my_array[2] = 30;\n CHECK(Sum(my_array, my_array_size) == 60);\n }\n}\n\nTEST_CASE(\"Minimum Value in Array\") {\n int* my_array = MakeDynoIntArray(3);\n unsigned int my_array_size = 3;\n\n SECTION(\"Min({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Min(my_array, my_array_size) == 10);\n }\n\n SECTION(\"Min({30, 10, 20})\") {\n my_array[0] = 30, my_array[1] = 10, my_array[2] = 20;\n CHECK(Min(my_array, my_array_size) == 10);\n }\n\n SECTION(\"Min({30, 20, 10})\") {\n my_array[0] = 30, my_array[1] = 20, my_array[2] = 10;\n CHECK(Min(my_array, my_array_size) == 10);\n }\n\n SECTION(\"Min({20, 10, 30})\") {\n my_array[0] = 20, my_array[1] = 10, my_array[2] = 30;\n CHECK(Min(my_array, my_array_size) == 10);\n }\n}\n\nTEST_CASE(\"Testing Exception Handling\") {\n int* my_array = NULL;\n unsigned int my_array_size = 0;\n\n SECTION(\"Sum() EXCEPTION HANDLING\") {\n try {\n Sum(my_array, my_array_size);\n CHECK(1 == 0);\n } catch (const char* e) {\n CHECK(!strcmp(e, \"NULL ARRAY REFERENCE\"));\n }\n }\n\n SECTION(\"Max() EXCEPTION HANDLING\") {\n try {\n Max(my_array, my_array_size);\n CHECK(1 == 0);\n } catch (const char* e) {\n CHECK(!strcmp(e, \"NULL ARRAY REFERENCE\"));\n }\n }\n\n SECTION(\"Min() EXCEPTION HANDLING\") {\n try {\n Min(my_array, my_array_size);\n CHECK(1 == 0);\n } catch (const char* e) {\n CHECK(!strcmp(e, \"NULL ARRAY REFERENCE\"));\n }\n }\n}\n\n\n"
},
{
"alpha_fraction": 0.6018518805503845,
"alphanum_fraction": 0.6075498461723328,
"avg_line_length": 25.52941131591797,
"blob_id": "490390636f89af036eb79a139e8b84d2f66bd5e2",
"content_id": "cc0b9d04570cbb5c9339ff4e6bce4c86fa1da972",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1404,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 51,
"path": "/CSCI465/firstapp/forms.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django import forms\r\nfrom django.core.validators import validate_unicode_slug\r\n\r\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\r\nfrom django.contrib.auth.models import User\r\nfrom .models import *\r\n\r\nclass suggestion_form(forms.Form):\r\n suggestion = forms.CharField(label='Suggestion', max_length=140)\r\n\r\nclass LoginForm(AuthenticationForm):\r\n username=forms.CharField(\r\n label=\"Username\",\r\n max_length=30,\r\n widget=forms.TextInput(attrs={\r\n 'name':'username'\r\n })\r\n )\r\n password=forms.CharField(\r\n label=\"Password\",\r\n max_length=32,\r\n widget=forms.PasswordInput()\r\n )\r\n\r\nclass registration_form(UserCreationForm):\r\n email = forms.EmailField(\r\n label=\"Email\",\r\n required=True\r\n )\r\n\r\n class Meta:\r\n model = User\r\n fields = (\"username\", \"email\",\r\n \"password1\", \"password2\")\r\n\r\n def save(self, commit=True):\r\n user=super(registration_form,self).save(commit=False)\r\n user.email=self.cleaned_data[\"email\"]\r\n if commit:\r\n user.save()\r\n return user\r\n\r\nclass UserForm(forms.ModelForm):\r\n class Meta:\r\n model = User\r\n fields = ('first_name', 'last_name', 'email')\r\n\r\nclass ProfileForm(forms.ModelForm):\r\n class Meta:\r\n model = profile\r\n fields = ('bio', 'games', 'birth_date')\r\n"
},
{
"alpha_fraction": 0.6426917910575867,
"alphanum_fraction": 0.6524471044540405,
"avg_line_length": 38.78947448730469,
"blob_id": "1234a7f0da6244ee00aa570f47b7cc116238c94f",
"content_id": "1f34e00d8938fd3998c8f8e08cabd1ee5afcf344",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6048,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 152,
"path": "/Topic 2/Assignment 2/checking_account.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : checking_account.cpp\n * Author : David Dalton\n * Description : CheckingAccount function definition\n * Source : Luke Sathrum, modified portions of money lab and item lab\n */\n \n#include \"checking_account.h\"\n\n/*\n * Constructor, uses default values if none given on creation\n */\nCheckingAccount::CheckingAccount(string account_name ,long dollars, int cents, \n string last_transaction, string amount_kept) \n{\n BankAccount::SetAccountName(account_name);\n BankAccount::SetDollars(dollars);\n BankAccount::SetCents(cents) ;\n BankAccount::SetLastTransaction(0, 0, last_transaction);\n amount_kept_ = amount_kept;\n BankAccount::ClearRecentTransactions();\n}\n/*\n * Destructor, unused\n */\nCheckingAccount::~CheckingAccount() \n{\n \n}\n/*\n * Mutator\n *sets all values in the recent_transactions array to \"none\"\n *sets the value of last_transaction to 0, 0 and \"none\"\n */\nvoid CheckingAccount::SetAmountKept(long kept_dollars, int kept_cents) \n{\n stringstream kept;\n kept << '$' << setw(1) << setfill('0') << kept_dollars << \".\" \n << setfill('0') << setw(2) << kept_cents;\n}\n/*\n * Mutator\n *calls the GetDollars() and GetCents() function and stores the results in \n *separate variables. Then it adds the values of those two variables together\n *and adds the values the two input variables together and multiples each\n *resulting sum by 100. Subtracts second value from the original value\n *unless the second value is larger.\n */\nvoid CheckingAccount::WriteCheck(int check_number, long check_dollars, \n int check_cents) \n{\n stringstream check;\n long current_dollars = BankAccount::GetDollars();\n int current_cents = BankAccount::GetCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of withdrawn amount\n long all_cents2 = check_cents + check_dollars * 100;\n if(all_cents1 >= all_cents2)\n {\n //Subtracts object 2 all cents from object 1 all cents\n long sum_all_cents = all_cents1 - all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) \n {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n // Sets the value of dollars_ and cents_ to the resulting values\n BankAccount::SetDollars(final_dollars);\n BankAccount::SetCents(final_cents);\n check << \"Check #\" << check_number;\n // Writes the transaction to the last_transaction_ and\n // recent_transaction_[0]\n BankAccount::SetLastTransaction(final_dollars, final_cents, check.str());\n BankAccount::SetRecentTransactions(final_dollars, final_cents, check.str());\n } else\n {\n /*\n *If the second value is greater then the original balance value, \n *writes and error message to the transaction recrod value and negates\n *the transaction.\n */\n BankAccount::SetLastTransaction(0,0,\"CHECK ERROR: INSUFFICIENT FUNDS\");\n BankAccount::SetRecentTransactions(0,0,\"CHECK ERROR: INSUFFICIENT FUNDS\");\n }\n}\n/*\n * Mutator\n *adds a specified amount of the check_dollars and check_cents variable\n *to the dollars_ and cents_ values.\n */\nvoid CheckingAccount::CashCheck(long check_dollars, int check_cents, \n long check_dollars_deposited,\n int check_cents_deposited) \n{\n /*\n *checksthat the amount specified to be kept is less then or equal to \n *the total amount of the original check value.\n */\n if ((check_dollars_deposited <= check_dollars) || \n (check_dollars_deposited == 0 && check_cents_deposited <= check_cents))\n {\n stringstream money_kept;\n long current_dollars = BankAccount::GetDollars();\n int current_cents = BankAccount::GetCents();\n // Get all the cents of current balance\n long all_cents1 = current_cents + current_dollars * 100;\n // Get all the cents of deposited amount\n long all_cents2 = check_cents_deposited + check_dollars_deposited * 100;\n // Add all the cents together\n long sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n // Subtracts the amount specified to be kept from the original values\n long kept_dollars = check_dollars - check_dollars_deposited;\n int kept_cents = check_cents - check_cents_deposited;\n // Stores the kept amount into the amount_kept_ variable\n SetAmountKept(kept_dollars, kept_cents);\n money_kept << \"Cashed Check, \" << GetAmountedKept() << \" kept.\";\n // Sets dollars_ and cents_ to the results of the final amounts\n BankAccount::SetDollars(final_dollars);\n BankAccount::SetCents(final_cents);\n // Adds the results to the transactional record variable\n BankAccount::SetLastTransaction(final_dollars, final_cents, money_kept.str());\n BankAccount::SetRecentTransactions(final_dollars, final_cents, money_kept.str());\n } else\n {\n //Sets the transaction record variables to a error message\n BankAccount::SetLastTransaction(0, 0, \"CHECK CASHING ERROR\");\n BankAccount::SetRecentTransactions(0, 0, \"CHECK CASHING ERROR\");\n }\n}\n/*\n * Accessor\n *gets the value of amount_kept_ and returns it\n */\nstring CheckingAccount::GetAmountedKept() \n{\n return amount_kept_;\n}\n"
},
{
"alpha_fraction": 0.49408984184265137,
"alphanum_fraction": 0.5721040368080139,
"avg_line_length": 20.263158798217773,
"blob_id": "2eea8ff3fed109328b21d26881765034938d0b3d",
"content_id": "7f884122dba38f5001df0e310c4e8aab4acc18db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 423,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 19,
"path": "/CSCI465v5/firstapp/migrations/0005_remove_suggestion_choice_field.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.5 on 2017-12-04 08:37\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('firstapp', '0004_auto_20171204_0035'),\r\n ]\r\n\r\n operations = [\r\n migrations.RemoveField(\r\n model_name='suggestion',\r\n name='choice_field',\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.6737864017486572,
"alphanum_fraction": 0.7029126286506653,
"avg_line_length": 26.157894134521484,
"blob_id": "9c3226b613721f6e1c87302a6126805783c3494b",
"content_id": "fc2f0e812269ec7a276aa9ebb48f4613df3e7ff4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 515,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 19,
"path": "/Topic 4/Lab 5/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from objects\nlab25test: lab_25_unit_test.o bst_node.o bs_tree.o\n\tg++ -Wall -g -o lab2test lab_25_unit_test.o bst_node.o bs_tree.o\n\n#creates the bs_tree object\nbs_tree: bs_tree.cpp bs_tree.h\n\tg++ -Wall -g -c bs_tree.cpp\n\t\n#creates the bst_node object file\nbst_node: bst_node.cpp bst_node.h\n\tg++ -Wall -g -c bst_node.cpp\n\t\n#creates the lab24 unit test object\nlab_25_unit_test: lab_25_unit_test.cpp\n\tg++ -Wall -g -c lab_25_unit_test.cpp\n\t\n#removes all object files and exe\t\nclean:\n\trm *.o *test"
},
{
"alpha_fraction": 0.6704761981964111,
"alphanum_fraction": 0.691428542137146,
"avg_line_length": 25.25,
"blob_id": "eebd59b9b7b2fe8458458e034b5689a4f333c0b9",
"content_id": "a260abaea888f7f2387892730738b95c0a01582d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 525,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 20,
"path": "/Topic 3/Lab 4/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nsl_nodetest: lab_19_unit_test.o sl_list.o sl_node.o\n\tg++ -Wall -g -o lab2test sl_node.o sl_list.o lab_19_unit_test.o\n\n#creates the node object file\t\nsl_node.o: sl_node.cpp sl_node.h\n\tg++ -Wall -g -c sl_node.cpp\n\t\n#creates the list object file\nsl_list.o: sl_list.cpp sl_list.h\n\tg++ -Wall -g -c sl_list.cpp\n\n#creates the lab unit test object file\nlab_19_unit_test.o: lab_19_unit_test.cpp\n\tg++ -Wall -g -c lab_19_unit_test.cpp\n\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6694236397743225,
"alphanum_fraction": 0.6771775484085083,
"avg_line_length": 32.64347839355469,
"blob_id": "332ab96007664196e06e3fce76994a22c4b6f2e5",
"content_id": "c024c30c98d105bf3dd0999f8d36e70c7f1a6cbf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3869,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 115,
"path": "/Topic 1/lab 4/lab_4.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_4.cpp\n * Author : David Dalton\n * Description : Use branching statements, looping statements and string and\n * character functions to complete the functions\n */\n\n#include \"lab_4.h\"\n\n/*\n * Return a string comprised of a label, followed by a space, followed by a\n * separator character, followed by a space, followed by a floating-point value.\n * For example, label=\"Temperature\", value=41.7, separator=':' will return\n * \"Temperature : 41.7\".\n * @uses stringstream.\n * @param string label - The label for the value\n * @param double value - The value associated with the label\n * @param char separator - The character that separates the label and the value\n * @return string - Comprised of a label, followed by a space, followed by a\n * separator character, followed by a space, followed by a\n * floating-point value\n */\n\nstring MakeString(string label, double value, char separator) {\n stringstream returnedString;\n returnedString << label << \" \" << separator << \" \" << value;\n return returnedString.str();\n}\n\n/*\n * Useful when accepting input from stdin using the getline function.\n * Return the first character of a length 1 string. If the value is of\n * length 0 or of length > 1, return the null character ('\\0').\n * @param string value - The expected single character\n * @return char - The first character of the string or null character ('\\0')\n * when value is length 0 or value is length > 1\n */\nchar StringToChar(string value) {\n char returnedChar = value[0];\n if ((value.length() < 1) || (value.length() > 1)) {\n returnedChar = '\\0';\n return returnedChar;\n } else {\n return returnedChar;\n }\n}\n\n/*\n * Useful when accepting input from stdin using the getline function.\n * Convert a string containing an expected integer value (such as a string\n * captured from stdin) into an integer. If value is not valid as an integer,\n * return 0.\n * @uses stringstream\n * @param string value - The expected integer value\n * @return int - An integer representing the value, or 0 on failure\n */\nint StringToInt(string value) {\n // THIS FUNCTION PROVIDED AS AN EXAMPLE AND IS ALREADY COMPLETE!\n int ivalue = 0;\n stringstream converter(value);\n converter.exceptions(ios_base::failbit);\n\n try {\n converter >> ivalue;\n } catch (ios_base::failure f) {\n }\n\n return ivalue;\n}\n\n/*\n * Useful when accepting input from stdin using the getline function.\n * Convert a string containing an expected floating-point value (such as a\n * string captured from stdin) into a double. If value is not valid as a double\n * return 0.\n * @uses stringstream\n * @param string value - The expected floating-point value\n * @return double - A double representing the value, or 0 on failure\n */\n\ndouble StringToDouble(string value) {\n double returnedDouble = 0.0;\n stringstream converter(value);\n converter.exceptions(ios_base::failbit);\n\n try {\n converter >> returnedDouble;\n } catch (ios_base::failure f) {\n }\n\n return returnedDouble;\n}\n\n/*\n * Useful when accepting input from stdin using the getline function.\n * Convert a string containing an boolean value (such as a string captured from\n * stdin) into a bool. Return true if the first character is 'T'\n * (case-insensitive), false if the first character is 'F' (case-insensitive),\n * and false on anything else.\n * @param string value - The expected string to start with either 'T' or 'F'\n * @return bool - If the first character is 'T' (case-insensitive) return true.\n * If the first character is 'F' (case-insensitive) return false.\n * Return false on anything else.\n */\n\nbool StringToBool(string value) {\n\n if((value[0] == 'T') || (value[0] == 't')) {\n return true;\n } else if((value[0] == 'F') || (value[0] == 'f')) {\n return false;\n } else {\n return false;\n }\n}\n"
},
{
"alpha_fraction": 0.36015963554382324,
"alphanum_fraction": 0.36614567041397095,
"avg_line_length": 38.058441162109375,
"blob_id": "555b1a1c6803f1692f1e354046b36970277b8211",
"content_id": "7b5a37e632764b0c2a34ffffa8651ee868561670",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6018,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 154,
"path": "/Topic 3/Assignment 3/driver.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: driver.cpp\n * Author: David Dalton\n * Sources:\n */\n \n/*\ndriver\n instances of Prize and Box\n menu containing options to exercise all public functions in Prize and Box\nclasses\n*/\n\n#include \"CinReader.cpp\"\n#include \"box.h\"\n\n#include <iostream>\n#include <map>\n#include <string>\n#include <sstream>\n#include <cstring>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::map;\nusing std::stringstream;\n\nint main()\n{\n bool end_program = false;\n do\n {\n CinReader reader;\n bool done = false;\n string name = \"\";\n string color = \"\";\n unsigned int prizeNum = 0;\n unsigned int value = 0;\n unsigned int number = 0;\n unsigned int action = 0;\n \n cout << \"Lets put together some prizes!\" << endl;\n cout << \"Enter a number for the box\" << endl;\n number = reader.readInt(0);\n cout << \"Enter the color of the box\" << endl;\n color = reader.readString(false);\n cout << \"How many prizes will the box hold?\" << endl;\n prizeNum = reader.readInt(0);\n Box newBox(number, color, prizeNum);\n cout << \"Here's the prize you can win!\" << endl;\n cout << \"The box number is: \" << number << \". The color is: \" << color\n << \". The number of prizes in the box is: \" << prizeNum << \".\\n\" \n << endl;\n int change_attribute;\n do\n {\n cout << \"Lets get some prizes!\\n\" << endl;\n cout << \"What do you want to do?\\n\" << endl;\n \n cout << \"1 - See what's in the box\\n2 - Inspect the box\\n3 - Change the box\\n4 - Quit\\n\";\n action = 0;\n action = reader.readInt(0,4);\n \n switch(action)\n {\n case 1:\n cout << \"The box contains the following prizes.\" << endl;\n for (unsigned int i = 0; i < newBox.getPrizeCount();i++)\n {\n cout << \"Prize # \" << i + 1 << \" \" \n << newBox.getPrize(i).getPrizeName() \n << \" with a value of $\" \n << newBox.getPrize(i).getPrizeValue() << \".\\n\" \n << endl;\n }\n break;\n \n case 2:\n cout << \"Box number: \" << newBox.getBoxNumber() \n << \". Box Color: \" << newBox.getBoxColor() \n << \". Prize Capacity: \" \n << \". \" << newBox.getPrizeCapacity() << \".\\n\" << endl;\n break;\n \n case 3:\n cout << \"What would you like to change?\" << endl;\n cout << \"1 - Box Number 2 - Box Color 3 - Add a prize 4 - Remove a prize\" << endl;\n change_attribute = reader.readInt(0, 4);\n switch(change_attribute)\n {\n case 1:\n cout << \"Enter the new number of the box\" << endl;\n number = reader.readInt(0);\n newBox.setBoxNumber(number);\n cout << \"The box is now the number: \" \n << number << \".\\n\" << endl;\n break;\n \n case 2:\n cout << \"Enter the new color of the box\" << endl;\n color = reader.readString(false);\n newBox.setBoxColor(color);\n cout << \"The box is now the color: \" \n << color << \".\\n\" << endl;\n break;\n \n case 3:\n cout << \"Enter the name of the prize you are adding\" << endl;\n name = reader.readString(false);\n cout << \"Enter the prizes value\" << endl;\n value = reader.readFloat();\n if(value < 0)\n {\n value = 0;\n }\n if(!newBox.addPrize(Prize(name, value)))\n {\n cout << \"No more room for prizes, this box is loaded!\\n\" << endl;\n }\n break;\n \n case 4:\n cout << \"Which prize will you be keeping for yourself? Enter the prize number now\" << endl;\n number = reader.readInt(0);\n if (newBox.getPrize(number -1).getPrizeValue() == 0)\n {\n cout << \"No prize: You walk away empty-handed\" << endl;\n } else\n {\n newBox.removePrize(number);\n }\n break;\n }\n break;\n \n case 4:\n done = true;\n break;\n }\n }while(!done);\n \n cout << \"Do you want to make a new box? Enter Y or N\" << endl;\n char make_new_box;\n make_new_box = reader.readChar(\"YyNn\");\n if(make_new_box == 'Y' || make_new_box == 'y')\n {\n end_program = false;\n } else\n {\n end_program = true;\n }\n }while(!end_program);\n return 0;\n}"
},
{
"alpha_fraction": 0.5687732100486755,
"alphanum_fraction": 0.5795771479606628,
"avg_line_length": 30.30545425415039,
"blob_id": "d712fe0508402d99453b11e6085442c18ae26fec",
"content_id": "c75d8c039ad181983c43909df580856cab41d8f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8608,
"license_type": "no_license",
"max_line_length": 200,
"num_lines": 275,
"path": "/Topic 2/atm_advanced.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : atm_test.cpp\n * Author : David Dalton\n * Description : Program to test an atm program\n */\n \n#include \"CinReader.cpp\"\n#include \"bank_account.h\"\n#include \"checking_account.h\"\n#include \"savings_account.h\"\n#include \"credit_account.h\"\n#include <typeinfo>\n\nclass ATM \n{\n public:\n void CreateAccount();\n void Menu();\n void ShowBalance();\n void ClearTransactionHistory();\n void ShowTransactionHistory();\n void Deposit();\n void Withdraw();\n void CalculateInterest();\n void ShowInterest();\n void SetBool(bool done);\n \n bool GetBool();\n \n private:\n bool done_;\n string current_account_;\n CinReader reader;\n};\n\nint main()\n{\n ATM myATM;\n myATM.Menu();\n}\n\n\nvoid ATM::CreateAccount()\n{\n cout << \"Select the type of account you wish to create\" << endl;\n cout << \"1 Bank Account 2 - Checking 3 - Savings 4 - Credit\\n\" << endl;\n int choice = reader.readInt(1,4);\n string account_name;\n long balance_dollars;\n int balance_cents;\n double interest_rate;\n switch(choice)\n { \n case 1:\n cout << \"Enter the name of your account\" << endl;\n account_name = reader.readString();\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\\n\" << endl;\n balance_cents = reader.readInt(0,99);\n CheckingAccount(account_name, balance_dollars, balance_cents);\n Menu();\n break;\n \n case 2:\n cout << \"Enter the name of your account\" << endl;\n account_name = reader.readString();\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\\n\" << endl;\n balance_cents = reader.readInt(0,99);\n CheckingAccount(account_name, balance_dollars, balance_cents);\n Menu();\n break;\n \n case 3:\n cout << \"Enter the name of your account\" << endl;\n account_name = reader.readString();\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\" << endl;\n balance_cents = reader.readInt(0,99);\n cout << \"Select your interest rate\\n\" << endl;\n interest_rate = reader.readDouble();\n SavingAccount(account_name, balance_dollars,balance_cents, interest_rate);\n Menu();\n break;\n \n case 4:\n cout << \"Enter the name of your account\" << endl;\n account_name = reader.readString();\n cout << \"Set the dollar amount of your account balance\" << endl;\n balance_dollars = reader.readInt(0);\n cout << \"Set the cent amount of your account balance\" << endl;\n balance_cents = reader.readInt(0,99);\n cout << \"Select your interest rate. NOTE: Must be greater or equal to 0.0\" << endl;\n interest_rate = reader.readDouble();\n cout << \"Set the dollar amount for your max balance\" << endl;\n long max_dollars = reader.readInt(0);\n cout << \"Set the cent amount for your max balance\\n\" << endl;\n int max_cents = reader.readInt(0, 99);\n CreditAccount(account_name, balance_dollars, balance_cents, max_dollars, max_cents, interest_rate);\n Menu();\n }\n}\n\nvoid ATM::Menu() \n{\n cout << \"Enter the name of the account you would like to use\" << endl;\n current_account_ = reader.readString();\n cout << \"Please select from the following options.\" << endl;\n cout << \"1 - Create an account\\n2 - Show account balance\\n3 - Deposit\\n4 - Withdraw\\n5 - Clear Transaction history\\n6 - Calculate Interest\\n 7 - Show interest accumulated\\n8 - Exit ATM\\n\" << endl;\n int choice = reader.readInt(1,6);\n switch(choice)\n {\n case 1:\n CreateAccount();\n break;\n\n case 2:\n ShowBalance();\n break;\n \n case 3:\n Deposit();\n break;\n \n case 4:\n Withdraw();\n break;\n \n case 5:\n ClearTransactionHistory();\n break;\n \n case 6:\n CalculateInterest();\n break;\n \n case 7:\n ShowInterest();\n break;\n \n case 8:\n exit(0);\n }\n \n}\n\nvoid ATM::ShowBalance() \n{\n \n cout << current_account_.ShowBalance() << endl;\n Menu();\n}\n\nvoid ATM::ClearTransactionHistory() \n{\n current_account_.ClearRecentTransactions();\n Menu();\n}\n\nvoid ATM::ShowTransactionHistory() \n{\n for(int i = 0;i<10;i++)\n {\n cout << current_account_.GetLastTransaction(i) << endl;\n }\n Menu();\n}\n\nvoid ATM::Deposit() \n{\n long dollars;\n int cents;\n string type = typeid(account_name_).name()\n if(type == \"CheckingAccount\")\n {\n cout << \"Would you like to deposit money into your account or cash a check?\" << endl;\n cout << \"Press 1 to deposit money and 2 to cash a check\" << endl;\n int choice = reader.readInt(1,2);\n if(choice == 1)\n {\n cout << \"Please enter the amount in dollars you would like to deposit, followed by the amount in cents\\n\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readint(0,99);\n CheckingAccount.DepositAccount(dollars, cents);\n Menu();\n } else \n {\n cout << \"Please enter the dollar value of the check you are cashing, followed by the cent value\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readInt(0,99);\n cout << \"Please enter the amount you'd like to keep in dollars, followed by cents\\n\" << endl\n long kept_dollars = reader.readLong(0);\n int kept_cents = reader.readInt(0,99);\n CheckingAccountCashCheck(dollars, cents, kept_dollars, kept_cents);\n Menu();\n }\n } else if(type == \"CreditAccount\") \n {\n cout << \"Please enter the amount you would like pay towards your balance in dollars, followed by cents\\n\" << endl; << endl;\n dollars = reader.readLong(0);\n cents = reader.readint(0,99);\n CreditAccount.MakePayment(dollars, cents);\n Menu();\n } else\n {\n cout << \"Please enter the amount in dollars you would like to deposit, followed by the amount in cents\\n\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readint(0,99);\n account_name_.DepositAccount(dollars, cents);\n Menu();\n}\n\nvoid ATM::Withdraw() \n{\n string type = typeid(account_name_).name()\n long dollars;\n int cents;\n if(type == \"CheckingAccount\")\n {\n cout << \"Please enter the check number that you are writing\" << endl;\n int check_number = reader.readInt(0);\n cout << \"Please enter the amount the check is for in dollars, followed by the amount in cents\\n\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readInt(0,99);\n CheckingAccount.WriteCheck(dollars, cents);\n Menu();\n } else if(type == \"CreditAccount\") \n {\n cout << \"Please enter the transaction number for the charge\" << endl;\n int transaction = reader.readInt(0);\n cout << \"Please enter the amount of the transaction in dollars, followed by cents\\n\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readCents(0,99);\n CreditAccountMakePayment(transaction, dollars, cents);\n Menu();\n } else \n {\n cout << \"Please enter the amount in dollars you would like to withdraw, followed by the amount in cents\\n\" << endl;\n dollars = reader.readLong(0);\n cents = reader.readint(0,99);\n account_name_.WithdrawAccount(dollars, cents);\n Menu();\n }\n}\n\nvoid ATM::CalculateInterest() \n{\n string type = typeid(account_name_).name()\n if(type == \"CheckingAccount\" || type == \"SavingAccount\") \n {\n account_name_.CalculateInterest\n } else \n {\n cout << \"ERROR: Incorrect account type\\n\" << endl;\n }\n Menu();\n}\n\nvoid ATM::ShowInterest() \n{\n cout << \"Interest accumulated this month: \" << account_name_.GetInterestAccumulatedMonth() << endl;\n cout << \"Interest accumulated this year: \" << account_name_.GetInterestAccumulatedYear() << \"\\n\" << endl;\n Menu();\n}\nvoid SetBool(bool done)\n{\n done_ = done;\n}\nbool GetBool() \n{\n return done_;\n}"
},
{
"alpha_fraction": 0.5461309552192688,
"alphanum_fraction": 0.5847222208976746,
"avg_line_length": 24.78005027770996,
"blob_id": "0d8cbeef1433f9354b3e048426691a9a8ad2abd6",
"content_id": "fba785f53030eb5a186b3191ec4e2cb3c0dd0547",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 10080,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 391,
"path": "/Topic 4/Lab 5/lab_25_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_25_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #25 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include \"bs_tree.h\"\n// To test for correct header guards\n#include \"bst_node.h\"\n#include \"bst_node.h\"\n#include \"bs_tree.h\"\n\nTEST_CASE(\"Default Constructor for BSTNode\") {\n const BSTNode const_node;\n BSTNode node;\n BSTNode* p_node = &node;\n SECTION(\"Contents const Accessor\") {\n CHECK(const_node.contents() == 0);\n }\n\n SECTION(\"Contents Accessor (Editable)\") {\n node.contents() = 10;\n CHECK(node.contents() == 10);\n }\n\n SECTION(\"Left Child const Accessor\") {\n CHECK(const_node.left_child() == NULL);\n }\n\n SECTION(\"Left Child Accessor (Editable)\") {\n node.left_child() = &node;\n CHECK(node.left_child() == p_node);\n }\n\n SECTION(\"Right Child const Accessor\") {\n CHECK(const_node.right_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor (Editable\") {\n node.right_child() = &node;\n CHECK(node.right_child() == p_node);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor for BSTNode\") {\n BSTNode node(99);\n SECTION(\"Contents Accessor\") {\n CHECK(node.contents() == 99);\n }\n\n SECTION(\"Left Child Accessor\") {\n CHECK(node.left_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor\") {\n CHECK(node.right_child() == NULL);\n }\n}\n\n\nTEST_CASE(\"Testing Pointers for BSTNode\") {\n BSTNode node1;\n BSTNode node2(99);\n BSTNode node3(-1);\n // node 2 is leftChild, node 3 is rightChild\n node1.set_left_child(&node2);\n node1.set_right_child(&node3);\n SECTION(\"Left Child Mutator\") {\n CHECK(node1.left_child() == &node2);\n }\n\n SECTION(\"Right Child Mutator\") {\n CHECK(node1.right_child() == &node3);\n }\n\n // Change the contents of left child via root\n node1.left_child()->set_contents(10);\n\n SECTION(\"Contents Mutator\") {\n CHECK(node2.contents() == 10);\n }\n}\n\nTEST_CASE(\"Default Constructor for BSTree\") {\n BSTree tree;\n SECTION(\"Size Accessor\") {\n CHECK(tree.size() == 0);\n }\n\n SECTION(\"InOrder() on an Empty Tree\") {\n CHECK(tree.InOrder() == \"\");\n }\n\n SECTION(\"Remove() on an Empty Tree\") {\n CHECK(tree.Remove(1) == false);\n }\n\n SECTION(\"FindMin() on an Empty Tree\") {\n CHECK(tree.FindMin() == 0);\n }\n\n SECTION(\"Clear() on an Empty Tree\") {\n tree.Clear();\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n }\n}\n\nTEST_CASE(\"Building a Tree\") {\n BSTree tree;\n bool return_bool = false;\n return_bool = tree.Insert(50);\n SECTION(\"Insert(50) (the root)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 1);\n CHECK(tree.InOrder() == \"50 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(20);\n SECTION(\"Insert(20) (the left child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"20 50 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(80);\n SECTION(\"Insert(80) (the right child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"20 50 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(30);\n SECTION(\"Insert(30) (the right child of node 20)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 4);\n CHECK(tree.InOrder() == \"20 30 50 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(70);\n SECTION(\"Insert(70) (the left child of node 80)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 5);\n CHECK(tree.InOrder() == \"20 30 50 70 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(0);\n SECTION(\"Insert(0) (the left child of node 10)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 6);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(100);\n SECTION(\"Insert(100) (the right child of node 80)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 7);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 100 \");\n }\n\n SECTION(\"Inserting Duplicate Values\") {\n CHECK(tree.Insert(50) == false);\n CHECK(tree.Insert(20) == false);\n CHECK(tree.Insert(80) == false);\n CHECK(tree.Insert(30) == false);\n CHECK(tree.Insert(70) == false);\n CHECK(tree.Insert(0) == false);\n CHECK(tree.Insert(100) == false);\n CHECK(tree.size() == 7);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 100 \");\n }\n\n tree.Clear();\n SECTION(\"Clear()\") {\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n CHECK(tree.FindMin() == 0);\n CHECK(tree.Remove(1) == false);\n }\n\n SECTION(\"Insert() Stress Test\") {\n CHECK(tree.Insert(50) == true);\n CHECK(tree.Insert(50) == false);\n CHECK(tree.Insert(25) == true);\n CHECK(tree.Insert(25) == false);\n CHECK(tree.Insert(75) == true);\n CHECK(tree.Insert(75) == false);\n CHECK(tree.Insert(30) == true);\n CHECK(tree.Insert(30) == false);\n CHECK(tree.Insert(29) == true);\n CHECK(tree.Insert(29) == false);\n CHECK(tree.Insert(31) == true);\n CHECK(tree.Insert(31) == false);\n CHECK(tree.Insert(32) == true);\n CHECK(tree.Insert(32) == false);\n CHECK(tree.Insert(33) == true);\n CHECK(tree.Insert(33) == false);\n CHECK(tree.Insert(34) == true);\n CHECK(tree.Insert(34) == false);\n CHECK(tree.size() == 9);\n CHECK(tree.FindMin() == 25);\n CHECK(tree.InOrder() == \"25 29 30 31 32 33 34 50 75 \");\n }\n}\n\nTEST_CASE(\"Building a Tree to test FindMin() and Remove()\") {\n BSTree tree;\n bool return_bool = false;\n return_bool = tree.Insert(10);\n SECTION(\"Insert(10) (the root)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 1);\n CHECK(tree.InOrder() == \"10 \");\n CHECK(tree.FindMin() == 10);\n }\n\n return_bool = false;\n return_bool = tree.Remove(10);\n SECTION(\"Remove(10) (the root)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n CHECK(tree.FindMin() == 0);\n }\n\n tree.Insert(10), tree.Insert(5), tree.Insert(15);\n SECTION(\"Insert(10) (the root), Insert(5) (left child), Insert(15) (right child\") {\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"5 10 15 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = true;\n return_bool = tree.Remove(1);\n SECTION(\"Remove(1) (non-existent)\") {\n CHECK(return_bool == false);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"5 10 15 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = false;\n return_bool = tree.Remove(5);\n SECTION(\"Remove(5) (no children)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"10 15 \");\n CHECK(tree.FindMin() == 10);\n }\n\n return_bool = false;\n return_bool = tree.Insert(5);\n SECTION(\"Insert(5) (left child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"5 10 15 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = false;\n return_bool = tree.Remove(15);\n SECTION(\"Remove(15) (no children)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"5 10 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = false;\n return_bool = tree.Insert(15);\n SECTION(\"Insert(15) (right child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"5 10 15 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = false;\n return_bool = tree.Remove(10);\n SECTION(\"Remove(10) (two children)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"5 15 \");\n CHECK(tree.FindMin() == 5);\n }\n\n return_bool = false;\n return_bool = tree.Insert(2);\n SECTION(\"Insert(2) (left child of node 5, which is a left child of node 15)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"2 5 15 \");\n CHECK(tree.FindMin() == 2);\n }\n\n return_bool = false;\n return_bool = tree.Remove(15);\n SECTION(\"Remove(15) (one left child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"2 5 \");\n CHECK(tree.FindMin() == 2);\n }\n\n return_bool = false;\n return_bool = tree.Insert(3);\n SECTION(\"Insert(3) (right child of node 2, which is a left child of node 5)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"2 3 5 \");\n CHECK(tree.FindMin() == 2);\n }\n\n return_bool = false;\n return_bool = tree.Remove(2);\n SECTION(\"Remove(2) (one right child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"3 5 \");\n CHECK(tree.FindMin() == 3);\n }\n\n return_bool = false;\n return_bool = tree.Insert(10);\n SECTION(\"Insert(10) (right child of node 5, which is the root)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"3 5 10 \");\n CHECK(tree.FindMin() == 3);\n }\n\n SECTION(\"Testing to remove non-existent values\") {\n CHECK(tree.Remove(1) == false);\n CHECK(tree.Remove(4) == false);\n CHECK(tree.Remove(8) == false);\n CHECK(tree.Remove(100) == false);\n }\n\n return_bool = false;\n return_bool = tree.Remove(5);\n SECTION(\"Remove(5) (two children)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"3 10 \");\n CHECK(tree.FindMin() == 3);\n }\n\n return_bool = false;\n return_bool = tree.Remove(10);\n SECTION(\"Remove(10) (one left child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 1);\n CHECK(tree.InOrder() == \"3 \");\n CHECK(tree.FindMin() == 3);\n }\n\n return_bool = false;\n return_bool = tree.Remove(3);\n SECTION(\"Remove(3) (no children)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n CHECK(tree.FindMin() == 0);\n }\n\n return_bool = true;\n return_bool = tree.Remove(1);\n SECTION(\"Remove(1) (non-existent)\") {\n CHECK(return_bool == false);\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n CHECK(tree.FindMin() == 0);\n }\n\n tree.Clear();\n SECTION(\"Clear() on an empty list\") {\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n CHECK(tree.FindMin() == 0);\n }\n}\n"
},
{
"alpha_fraction": 0.6088795065879822,
"alphanum_fraction": 0.6194503307342529,
"avg_line_length": 21.5238094329834,
"blob_id": "3b3973045933776d1f7fd9e654e73f1bf93b1b65",
"content_id": "b036019fc6ac2df3fc291b03e57151d14d071ca3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1892,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 84,
"path": "/Topic 1/lab 5/lab_5_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_5_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #3 Functionality\n * Sources :\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <sstream>\n#include <iostream>\n#include <string>\n#include \"lab_5.h\"\nusing std::string;\n\nTEST_CASE(\"Hello Function\") {\n string cout_output;\n std::streambuf* oldCout = cout.rdbuf();\n std::ostringstream captureCout;\n cout.rdbuf(captureCout.rdbuf());\n Hello();\n cout.rdbuf(oldCout);\n cout_output = captureCout.str();\n SECTION(\"Hello()\") {\n CHECK(cout_output == \"Hello world!\");\n }\n captureCout.str(\"\");\n}\n\nTEST_CASE(\"Print Message Function\") {\n string cout_output;\n std::streambuf* oldCout = cout.rdbuf();\n std::ostringstream captureCout;\n cout.rdbuf(captureCout.rdbuf());\n PrintMessage(\"Hello again!\");\n cout.rdbuf(oldCout);\n cout_output = captureCout.str();\n SECTION(\"PrintMessage(\\\"Hello again!\\\")\") {\n CHECK(cout_output == \"Hello again!\");\n }\n captureCout.str(\"\");\n}\n\nTEST_CASE(\"Get Answer Function\") {\n SECTION(\"GetAnswer()\") {\n CHECK(GetAnswer() == 42);\n }\n}\n\nTEST_CASE(\"Find the Larger Integer\") {\n SECTION(\"FindLarger(-1, 1)\") {\n CHECK(FindLarger(-1, 1) == 1);\n }\n\n SECTION(\"FindLarger(1, -1)\") {\n CHECK(FindLarger(1, -1) == 1);\n }\n\n SECTION(\"FindLarger(1, 1)\") {\n CHECK(FindLarger(1, 1) == 1);\n }\n}\n\nTEST_CASE(\"Build A Message\") {\n SECTION(\"BuildMessage(\\\"hello\\\")\") {\n CHECK(BuildMessage(\"hello\") == \"Message: hello\");\n }\n\n SECTION(\"BuildMessage(\\\"hello\\\", true)\") {\n CHECK(BuildMessage(\"hello\", true) == \"Message: HELLO\");\n }\n\n SECTION(\"BuildMessage(\\\"HELLO\\\", false)\") {\n CHECK(BuildMessage(\"HELLO\", false) == \"Message: HELLO\");\n }\n\n SECTION(\"BuildMessage(\\\"HELLO\\\", true)\") {\n CHECK(BuildMessage(\"HELLO\", true) == \"Message: HELLO\");\n }\n\n SECTION(\"BuildMessage()\") {\n CHECK(BuildMessage() == \"Message: empty\");\n }\n}\n"
},
{
"alpha_fraction": 0.53125,
"alphanum_fraction": 0.6015625,
"avg_line_length": 11.899999618530273,
"blob_id": "6851b6e58b8d5dc26ea2f95ae20055c67904eb01",
"content_id": "7f03e3261351ceddf981efde178fdc9f95d0feff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 128,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 10,
"path": "/Topic 1/lab 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "all: lab3test\n\nlab3test: lab_3.o\n\tg++ -Wall -g -o lab3 lab_3.o\n\nlab3: lab_3.cpp\n\tg++ -Wall -g -c lab_3.cpp\n\t\nclean:\n\trm *.o lab3"
},
{
"alpha_fraction": 0.5270344018936157,
"alphanum_fraction": 0.5417804718017578,
"avg_line_length": 29.781513214111328,
"blob_id": "7f002b3bb9bb583e4ef5aa3b1843194987aaf376",
"content_id": "81f8eccb2aafa0c8d6457412ef3d9ec5c47e7ed1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3662,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 119,
"path": "/Topic 1/lab 7/lab_7.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_7.cpp\n * Author : David Dalton\n * Description : Working with File I/O\n */\n#include \"lab_7.h\"\n\n// CODE HERE -- FUNCTION DEFINITION FOR ProcessFile()\n/*\n * Open and read the contents of a text file. Each line of the\n * file will contain a single integer of possible values 10, 20,\n * 30, 40, or 50. Perform the following operations on the input values:\n * 10 -- invoke the function OnTen\n * 20 -- invoke the function OnTwenty\n * 30 -- invoke the function OnThirty\n * 40 -- invoke the function OnForty\n * 50 -- invoke the function OnFifty\n * any other value -- invoke the function OnError\n * DON'T FORGET TO CLOSE YOUR FILE BEFORE YOUR FUNCTION ENDS!!!\n * @param string filename - A string containing the name of the file to\n * be processed\n * @return bool - True if filename was successfully opened and processed,\n * else false\n */\n\nbool ProcessFile(string filename) \n{\n string current_line;\n //Opens the file in the file stream\n ifstream fin (filename.c_str());\n /*\n *Uses the if statement to verify the filename and returns false if the \n *filename is invalid\n */\n if(fin.fail()) \n {\n return false;\n } else \n {\n /*\n *Uses a do/while loop to check every line in the file. It stores the\n *current line in a string then compares the value of the string to\n *set values to determine which counter function to call. When the \n *end of the file is reached it returns true.\n */\n do {\n fin >> current_line;\n if(current_line == \"10\")\n {\n OnTen();\n } else if(current_line ==\"20\") \n {\n OnTwenty();\n } else if(current_line == \"30\") \n {\n OnThirty();\n } else if(current_line == \"40\") \n {\n OnForty();\n } else if(current_line == \"50\")\n {\n OnFifty();\n } else \n {\n OnError();\n }\n } while(!fin.eof());\n return true;\n }\n //Closes the file\n fin.close();\n}\n\n/*\n * Process the argv array (command-line arguments to the program). Ignore\n * argv[0] as that is the program name. Perform the following operations on\n * the input values:\n * 10 -- invoke the function OnTen\n * 20 -- invoke the function OnTwenty\n * 30 -- invoke the function OnThirty\n * 40 -- invoke the function OnForty\n * 50 -- invoke the function OnFifty\n * any other value -- invoke the function OnError\n * @param int argc - Contains the number of arguments passed to the program\n * on the command-line\n * @param char *argv[] - An array containing the command-line arguments\n */\nvoid ProcessArguments(int argc, char* argv[]) \n{\n int i;\n /*\n *Loops through the argument array and stores the value of the current\n *array location into a string, then compares the string to preset\n *values to determine which counter function to call.\n */\n for(i=1;i<argc;i++)\n {\n string current_argument = argv[i];\n if(current_argument == \"10\")\n {\n OnTen();\n } else if(current_argument == \"20\") \n {\n OnTwenty();\n } else if(current_argument == \"30\")\n {\n OnThirty();\n } else if(current_argument == \"40\") \n {\n OnForty();\n } else if(current_argument == \"50\") \n {\n OnFifty();\n } else \n {\n OnError();\n }\n }\n}"
},
{
"alpha_fraction": 0.5107418894767761,
"alphanum_fraction": 0.5138928890228271,
"avg_line_length": 23.0827579498291,
"blob_id": "6707b11825b9a8bff190b144a4088dd0c7622a80",
"content_id": "f2eec1c013e0f54f5583aeab66f7ec267e5c599b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3491,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 145,
"path": "/Topic 3/Assignment 3/box.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: box.h\n * Author: David Dalton\n * Sources:\n */\n\n#include \"box.h\"\n\n /**\n * Default constructor\n * initial values boxNumber (0), boxColor (\"NO COLOR\"), prizeCapacity (5), \n * prizeCount(0); in the definition, prizes array must be initialized to \n * match prizeCapacity\n */\n Box::Box() \n {\n boxNumber_ = 0;\n boxColor_ = \"NO COLOR\";\n prizeCapacity_ = 5;\n prizeCount_ = 0;\n prizes_ = new Prize[prizeCapacity_];\n for(unsigned int i = 0;i < prizeCapacity_; i++)\n {\n prizes_[i] = scratch_;\n }\n }\n /**\n * Overloaded constructor\n * parameters for boxNumber, boxColor, prizeCapacity; in the definition, \n * prizes array must be initialized to match prizeCapacity\n */\n Box::Box(unsigned int number,string color,\n unsigned int capacity, unsigned int count ) \n {\n boxNumber_ = number;\n boxColor_ = color;\n prizeCapacity_ = capacity;\n prizeCount_ = count;\n prizes_ = new Prize[prizeCapacity_];\n for(unsigned int i = 0;i < prizeCapacity_; i++)\n {\n prizes_[i] = scratch_;\n }\n }\n /**\n * Deconstructor\n * free memory associated with prizes\n */\n Box::~Box() \n {\n delete[] prizes_;\n }\n /**\n * Mutator for boxNumber_\n */\n void Box::setBoxNumber(unsigned int number) \n {\n boxNumber_ = number;\n }\n /**\n * Mutator for boxColor_\n */\n void Box::setBoxColor(string color) \n {\n boxColor_ = color;\n }\n /**\n * Accessor for boxNumber_\n */\n unsigned int Box::getBoxNumber() \n {\n return boxNumber_;\n }\n /**\n * Accessor for boxColor_\n */\n string Box::getBoxColor() \n {\n return boxColor_;\n }\n /**\n * Accessor for prizeCapacity_\n */\n unsigned int Box::getPrizeCapacity() \n {\n return prizeCapacity_;\n }\n /**\n * Accessor for prizeCount_\n */\n unsigned int Box::getPrizeCount() \n {\n return prizeCount_;\n }\n /**\n * parameters prize (Prize), return value (bool); place prize in prizes \n * array if there is space and return true, else return false\n */\n bool Box::addPrize(Prize prize) \n {\n for(unsigned int i = 0;i < prizeCapacity_; i++)\n {\n if(prizes_[i] == scratch_)\n {\n prizes_[i] = prize;\n prizeCount_ = prizeCount_ + 1;\n return true;\n }\n }\n return false;\n }\n /**\n * parameters index (unsigned int), return value Prize&; return a Prize if \n * index is valid, else return scratch (data member declared in class \n * header)\n */\n Prize Box::getPrize(unsigned int index) \n {\n if(prizes_[index] == scratch_)\n {\n return prizes_[index];\n } else\n {\n return prizes_[index];\n //return scratch_;\n }\n }\n /**\n * parameters index (unsigned int), return value Prize; remove and return \n * Prize if index is valid, else return scratch (data member declared in \n * class header)\n */\n Prize Box::removePrize(unsigned int index) \n {\n if(index == prizeCapacity_)\n {\n return scratch_;\n } else\n {\n Prize prize = prizes_[index];\n prizes_[index] = scratch_;\n prizeCount_ = prizeCount_ - 1;\n return prize;\n }\n }"
},
{
"alpha_fraction": 0.6487376689910889,
"alphanum_fraction": 0.6545920372009277,
"avg_line_length": 25.038095474243164,
"blob_id": "aa1eb89f48938453b0e80d2c6177a6c70d831ec5",
"content_id": "668cf198dca73035cf01edea11f8fd72393e33fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2733,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 105,
"path": "/Topic 2/lab 3/money.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : money.h\n * Author : David Dalton\n * Description : Class Header File\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <string>\n#include <iostream>\n#include <cstdlib>\n#include <iomanip>\nusing std::string;\nusing std::ostream;\nusing std::setfill;\nusing std::setw;\n\n/*\n * Class Money.\n * A class that handles amounts of money in U.S. Currency.\n */\nclass Money {\n public:\n /*\n * Constructor #1.\n * Sets dollars and cents to the supplied values. Defaults to 0\n * @param int dollars - The value to set dollars_ to\n * @param int cents - The value to set cents_ to\n */\n Money(int dollars = 0, int cents = 0);\n\n /*\n * Accessor for dollars_\n * @return int - The dollars_ value\n */\n int dollars() const;\n\n /*\n * Accessor for cents_\n * @return int - The cents_ value\n */\n int cents() const;\n\n /*\n * Mutator for dollars_\n * @param int dollars - The value to set dollars_ to\n */\n void set_dollars(int dollars);\n\n /*\n * Mutator for cents_\n * @param int cents - The value to set cents_ to\n */\n void set_cents(int cents);\n\n /*\n * Overload of + operator. This is a friend function.\n * @param Money amount1 - The first object to add\n * @param Money amount2 - The second object to add\n * @return Money - The two objects added together\n */\n friend const Money operator +(const Money& amount1, const Money& amount2);\n\n /*\n * Overload of binary - operator. This is a friend function.\n * @param Money amount1 - The object to subtract from\n * @param Money amount2 - The object to be subtracted\n * @return Money - The result of the subtraction\n */\n friend const Money operator -(const Money& amount1, const Money& amount2);\n\n /*\n * Overload of == operator. This is a friend function.\n * @param Money amount1 - The first object to compare\n * @param Money amount2 - The second object to compare\n * @return bool - True if the objects have the same values, otherwise false\n */\n friend bool operator ==(const Money &amount1, const Money &amount2);\n\n /*\n * Overload of unary - operator. This is a friend function.\n * @param Money amount - The object to negate\n * @return Money - The result of the negation of the two member variables\n */\n friend const Money operator -(const Money &amount);\n\n /*\n * Overload of << operator.\n * Outputs the money values to the output stream.\n * Should be in the form $x.xx\n * @uses setw()\n * @uses setfill()\n * @param ostream &out - The ostream object to output to\n * @param Money amount - The Money object to output from.\n * @return ostream& - The ostream object to allow for chaining of <<\n */\n friend ostream& operator <<(ostream &out, const Money &amount);\n\n private:\n int dollars_;\n int cents_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6075494289398193,
"alphanum_fraction": 0.6087477803230286,
"avg_line_length": 13.77876091003418,
"blob_id": "1dfa73ce0a7005f104ceb360c488ed6bfc1b7299",
"content_id": "c71d4bd1863941b09d4b30cdd0c1b892b7d794f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1669,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 113,
"path": "/Topic 4/Lab 3/bst_node.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bst_node.cpp\n * Author : David Dalton\n * Description : Tree lab\n */\n \n#include \"bst_node.h\"\n\n/**\n * sets left_child_ to NULL\n * sets right_child_ to NULL\n * sets contents_ to 0\n */\nBSTNode::BSTNode ()\n{\n set_left_child(NULL);\n set_right_child(NULL);\n set_contents(0);\n}\n\n/** \n * \n * has one int parameter for contents\n * sets left_child_ to NULL\n * sets right_child_ to NULL\n * sets contents_ to the value of the parameter\n */\nBSTNode::BSTNode(int value) \n{\n set_left_child(NULL);\n set_right_child(NULL);\n set_contents(value);\n}\n/**\n *\n * sets right_child_ to NULL\n * sets left_child_ to NULL\n */\nBSTNode::~BSTNode()\n{\n set_left_child(NULL);\n set_right_child(NULL);\n}\n \n/**\n * mutator for contents_\n */\nvoid BSTNode::set_contents(int contents) \n{\n contents_ = contents;\n}\n \n/**\n * accessors for contents_\n */\nint BSTNode::contents() const \n{\n return contents_;\n}\n \n/**\n * accessors for contents_\n */\nint& BSTNode::contents() \n{\n return contents_;\n}\n \n/**\n * mutator for left_child_\n */\nvoid BSTNode::set_left_child(BSTNode* left_child)\n{\n left_child_ = left_child;\n}\n \n/**\n * mutator for right_child_\n */\nvoid BSTNode::set_right_child(BSTNode* right_child) \n{\n right_child_ = right_child;\n}\n \n/**\n * accessors for left_child_\n */\nBSTNode* BSTNode::left_child() const \n{\n return left_child_;\n}\n/**\n * accessors for left_child_\n */\nBSTNode*& BSTNode::left_child() \n{\n return left_child_;\n}\n \n/**\n * accessors for right_child_\n */\nBSTNode* BSTNode::right_child() const \n{\n return right_child_;\n}\n/**\n * accessors for right_child_\n */\nBSTNode*& BSTNode::right_child() \n{\n return right_child_;\n}"
},
{
"alpha_fraction": 0.6835442781448364,
"alphanum_fraction": 0.7113924026489258,
"avg_line_length": 25.33333396911621,
"blob_id": "b9f1a735deaa704fa72df4ba6628b514e08214d1",
"content_id": "ec1bf4cce93352665e08d0f8fe1c87aecd63709b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 395,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 15,
"path": "/Topic 2/lab 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\nmoneytest: lab_11_unit_test.o money.o\n\tg++ -Wall -g -o moneytest money.o lab_11_unit_test.o\n\n#creates the lab6 object file\t\nmoney: money.cpp money.h\n\tg++ -Wall -g -c money.cpp\n\n#creates the unit test object file\nlab_11_unit_test: lab_11_unit_test.cpp\n\tg++ -Wall -g -c lab_11_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o moneytest "
},
{
"alpha_fraction": 0.5351170301437378,
"alphanum_fraction": 0.5928093791007996,
"avg_line_length": 15.85915470123291,
"blob_id": "17293247b3e3f1f5b598bb768f283ffb9b6a706d",
"content_id": "b09dcd77dbb2f8516aa35544d870fd41512c8e59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1196,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 71,
"path": "/Topic 1/lab 7/lab_7_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_7_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #7 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_7.h\"\n\nmap<int, int> counters;\n\nvoid OnTen() {\n counters[10]++;\n}\n\nvoid OnTwenty() {\n counters[20]++;\n}\n\nvoid OnThirty() {\n counters[30]++;\n}\n\nvoid OnForty() {\n counters[40]++;\n}\n\nvoid OnFifty() {\n counters[50]++;\n}\n\nvoid OnError() {\n counters[99]++;\n}\n\nTEST_CASE(\"Processing File \\\"lab_7_input.txt\\\"\") {\n counters[10] = 0, counters[20] = 0, counters[30] = 0, counters[40] = 0,\n counters[50] = 0, counters[99] = 0;\n ProcessFile(\"lab_7_input.txt\");\n\n SECTION(\"Counting 10s\") {\n CHECK(counters[10] == 15);\n }\n\n SECTION(\"Counting 20s\") {\n CHECK(counters[20] == 14);\n }\n\n SECTION(\"Counting 30s\") {\n CHECK(counters[30] == 13);\n }\n\n SECTION(\"Counting 40s\") {\n CHECK(counters[40] == 12);\n }\n\n SECTION(\"Counting 50s\") {\n CHECK(counters[50] == 11);\n }\n\n SECTION(\"Counting Errors\") {\n CHECK(counters[99] == 35);\n }\n}\n\nTEST_CASE(\"Processing File \\\"non-existent-file.txt\\\"\") {\n SECTION(\"Processing non-existent file\") {\n CHECK(ProcessFile(\"non-existent-file.txt\") == false);\n }\n}"
},
{
"alpha_fraction": 0.5508559942245483,
"alphanum_fraction": 0.5941591262817383,
"avg_line_length": 21.325841903686523,
"blob_id": "108a33f13d1085527a082f6dc1ea4e1449530c65",
"content_id": "b7da3a8f46f590dcf3e5d65faeb325c43acbbdc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1986,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 89,
"path": "/Topic 2/lab 5/lab_13_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Programming Challenge 21 - UNIT TEST\n */\n\n#include \"lab_5.h\"\n\n/*\n * Programming Challenge 13\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n #include <iostream>\n using std::ostringstream;\n\nTEST_CASE (\"Box<int> class functionality\", \"[Box]\") {\n\tBox<int> intBox(99);\n\n\tCHECK(intBox.getContents() == 99);\n\n\tintBox.setContents(42);\n\tCHECK(intBox.getContents() == 42);\n\n\tostringstream ss;\n\tss << intBox;\n\tCHECK(ss.str() == \"42\");\n}\n\nTEST_CASE (\"Box<bool> class functionality\", \"[Box]\") {\n\tBox<bool> boolBox(false);\n\n\tCHECK(boolBox.getContents() == false);\n\n\tboolBox.setContents(true);\n\tCHECK(boolBox.getContents() == true);\n\n\tostringstream ss;\n\tss << boolBox;\n\tCHECK(ss.str() == \"1\");\n}\n\nTEST_CASE (\"Box<float> class functionality\", \"[Box]\") {\n\tBox<float> floatBox(1.23f);\n\n\tCHECK(floatBox.getContents() == 1.23f);\n\n\tfloatBox.setContents(3.21f);\n\tCHECK(floatBox.getContents() == 3.21f);\n\n\tostringstream ss;\n\tss << floatBox;\n\tCHECK(ss.str() == \"3.21\");\n}\n\nTEST_CASE (\"Box<string> class functionality\", \"[Box]\") {\n\tBox<string> stringBox(\"hello\");\n\n\tCHECK(stringBox.getContents() == \"hello\");\n\n\tstringBox.setContents(\"goodbye\");\n\tCHECK(stringBox.getContents() == \"goodbye\");\n\n\tostringstream ss;\n\tss << stringBox;\n\tCHECK(ss.str() == \"goodbye\");\n}\n\nTEST_CASE(\"Sum()\") {\n SECTION(\"Integers. Array: { 3, 5, 7, 9, 11 }\") {\n int int_values[] = { 3, 5, 7, 9, 11 };\n CHECK(Sum(int_values, 5) == 35);\n CHECK(Sum(int_values, 1) == 3);\n CHECK(Sum(int_values, 0) == 0);\n }\n\n SECTION(\"Doubles. Array: { 3.1, 5.2, 7.3, 9.4, 11.5 }\") {\n double double_values[] = { 3.1, 5.2, 7.3, 9.4, 11.5 };\n CHECK(Sum(double_values, 5) == 36.5);\n CHECK(Sum(double_values, 1) == 3.10);\n CHECK(Sum(double_values, 0) == 0.0);\n }\n\n SECTION(\"Strings. Array: { \\\"A\\\", \\\"B\\\", \\\"C\\\", \\\"D\\\", \\\"E\\\" }\") {\n string string_values[] = { \"A\", \"B\", \"C\", \"D\", \"E\" };\n CHECK(Sum(string_values, 5) == \"ABCDE\");\n CHECK(Sum(string_values, 1) == \"A\");\n CHECK(Sum(string_values, 0) == \"\");\n }\n}"
},
{
"alpha_fraction": 0.6297435760498047,
"alphanum_fraction": 0.6328204870223999,
"avg_line_length": 27.676469802856445,
"blob_id": "d8524ee563e7ffe0d45fa2a373785b44c11954f3",
"content_id": "7badfb10d670560abcf9a92ff12da2286f476eb9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2925,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 102,
"path": "/Topic 1/lab 5/lab_5.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_5.cpp\n * Author : David Dalton\n * Description : Practicing Functions. Use this file to write your\n * Function Definitions (what goes below main()).\n */\n\n#include \"lab_5.h\"\n\n/*\n * Function Name: Hello\n *\n * Displays \"Hello world!\" to stdout (cout) (no newline character after)\n */\nvoid Hello() {\n cout << \"Hello world!\";\n}\n\n/*\n * Function Name: PrintMessage\n *\n * Displays the string parameter to stdout (no newline character)\n * @param const string& - The string to display to stdout\n */\nstring PrintMessage(const string& kMessage) {\n cout << kMessage;\n return kMessage;\n}\n\n/*\n * Function Name: GetAnswer\n *\n * Returns the integer value 42.\n * @return int - The value 42\n */\nint GetAnswer(){\n return 42;\n}\n\n/*\n * Function Name: FindLarger\n *\n * Returns the larger of the two parameter values. Should work correctly\n * if the values are equivalent (returns either one)\n * @param int - The first value\n * @param int - The second value\n * @return int - The larger of the two values, or either one if they are equal\n */\nint FindLarger(int first_value, int second_value) {\n /*Compares the values of the two ints, then returns an int depending on the\n results\n */\n if(first_value > second_value) {\n return first_value;\n } else if(first_value < second_value) {\n return second_value;\n } else {\n return first_value;\n }\n}\n\n/*\n * Function Name: BuildMessage\n *\n * Return the string \"Message: STRING\", where STRING is replaced by the value of\n * the first parameter (string). If second parameter (bool) is true, convert\n * first parameter (string) to all uppercase letters before concatenating it\n * with \"Message: \". If first parameter is the empty string, return\n * \"Message: empty\".\n * @param string - A message.\n * - Defaults to \"\" (empty string)\n * @param bool - To indicate if we should uppercase letters or not\n * - Defaults to false\n */\nstring BuildMessage(string message, bool upper_case) {\n /*checks to see if the message string is empty\n If string is empty then it stores \"empty\", then concatenates it into the\n the variable and returns the concatenated string\n */\n if(message == \"\") {\n message = \"empty\";\n stringstream returnedString;\n returnedString << \"Message: \" << message;\n return returnedString.str();\n /*\n If string is not empty then it checks to see if the bool is set to true\n If it is, then it changes the string to uppercase\n */\n } else {\n if (upper_case == true) {\n int i;\n int length = message.length();\n for (i=0; i<length;i++){\n message[i] = toupper(message[i]);\n }\n //Concatenates the strings together and returns them\n }\n stringstream returnedString;\n returnedString << \"Message: \" << message;\n return returnedString.str();\n }\n}\n"
},
{
"alpha_fraction": 0.6408071517944336,
"alphanum_fraction": 0.6484304666519165,
"avg_line_length": 20.872549057006836,
"blob_id": "bb068ced4b69af7e7d48901a9afc9256ff51f3f2",
"content_id": "5ee0baf8c47db52be8784f4916baed08a9d32a01",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2230,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 102,
"path": "/Topic 2/lab 4/food_item.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : item.h\n * Author : David Dalton\n * Description : Class Header File\n */\n \n#include \"food_item.h\"\n \n/*\n * Constructor\n *takes five parameters, one for each private member variable and two for the \n *base class\n *defaults name_ to \"fooditem\"\n *defaults value_ to 0\n *defaults calories_ to 0\n *defaults unit_of_measure_ to \"nounits\"\n *defaults units_ to 0\n */\n FoodItem::FoodItem(string name, unsigned int value, unsigned int calories,\n string unit_of_measure, double units)\n{\n Item::set_name(name);\n Item::set_value(value);\n calories_ = calories;\n unit_of_measure_ = unit_of_measure;\n units_ = units;\n}\n/*\n * \n *Destructor\n */\nFoodItem::~FoodItem() \n{\n \n}\n/*\n * Mutator #1 *sets the value of calories_ to the input int\n */\nvoid FoodItem::set_calories(unsigned int calories) \n{\n calories_ = calories;\n}\n/*\n * Mutator #2\n *sets the value of units_of_measure_ to the input string\n */\nvoid FoodItem::set_unit_of_measure(string units_of_measure) \n{\n unit_of_measure_ = units_of_measure;\n}\n/*\n * Mutator #3\n *sets the value of units_ to the input double\n */\nvoid FoodItem::set_units(double units) \n{\n units_ = units;\n}\n/*\n * Accessor #1\n *retrieves the value of calories_\n */\nunsigned int FoodItem::calories() \n{\n return calories_;\n}\n/*\n * Accessor #2\n *retrieves the value of units_of_measure_\n */\nstring FoodItem::unit_of_measure() \n{\n return unit_of_measure_;\n}\n/*\n * Accessor #3\n *retrieves the value of units_\n */\ndouble FoodItem::units() \n{\n return units_;\n}\n/*\n *string ToString()\n *returns a string containing name_, value_, units_, unit_of_measure_,\n *and calories_\n *(uses Item::ToString in its implementation)\n *units_ formatted to exactly two decimal places\n *Format -- name_, $value_, units_ unit_of_measure_, calories_\n *calories\n *EXAMPLE -- cookie, $1, 2.50 cookie(s), 250 calories\n */\nstring FoodItem::ToString() \n{\n stringstream returned_string;\n string base_string = Item::ToString();\n returned_string.setf(std::ios::fixed|std::ios::showpoint);\n returned_string.precision(2);\n returned_string << base_string << \", \" << units_ << \" \" \n << unit_of_measure_ << \", \"<< calories_ << \" calories\";\n return returned_string.str();\n}"
},
{
"alpha_fraction": 0.657575786113739,
"alphanum_fraction": 0.6984848380088806,
"avg_line_length": 27.7391300201416,
"blob_id": "27c6050e3ba1eeb607025965f357f7e26456816f",
"content_id": "899826b60f306493b85a2509a5149007212ebdc0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 660,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 23,
"path": "/Topic 1/lab 7/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nlab7test: lab_7_unit_test.o lab_7.o\n\tg++ -Wall -g -o lab7test lab_7.o lab_7_unit_test.o\n\n#creates the lab7 object file\t\nlab7: lab_7.cpp lab_7.h\n\tg++ -Wall -g -c lab_7.cpp\n\n#creates the lab 7 unit test object file\nlab_7_unit_test: lab_7_unit_test.cpp\n\tg++ -Wall -g -c lab_7_unit_test.cpp\n\t\n#creates the executable from all of the object files\nlab8test: lab_8_unit_test.o lab_7.o\n\tg++ -Wall -g -o lab8test lab_7.o lab_8_unit_test.o\n\t\n#creates the lab 8 unit test object file\nlab_8_unit_test: lab_8_unit_test.cpp\n\tg++ -Wall -g -c lab_8_unit_test.cpp\t\n\n#cleans up old .o files\t\nclean:\n\trm *.o lab7test lab8test"
},
{
"alpha_fraction": 0.5968084931373596,
"alphanum_fraction": 0.6202127933502197,
"avg_line_length": 21.650602340698242,
"blob_id": "500ed463c6347ca715fec5edf457b4ad362f44c6",
"content_id": "6a1a8ee77ca5203b94e95e7da99da9b0a5e8fa4b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1880,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 83,
"path": "/Topic 3/Lab 2/lab_17_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_17_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #17 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include \"sl_node.h\"\n// To test for correct header guards\n#include \"sl_node.h\"\n\nTEST_CASE(\"Default Constructor\") {\n SLNode node, node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 0);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor\") {\n SLNode node(1), node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 1);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Testing Pointers\") {\n SLNode* node = new SLNode(1);\n SLNode* node2 = new SLNode();\n node->set_next_node(node2);\n node2->set_next_node(node);\n // node and node2 now connect each to the other -- not something you should\n // ever do outside of a testing situation\n SECTION(\"Node 1 Points to Node 2\") {\n CHECK(node->next_node() == node2);\n }\n\n SECTION(\"Node 2 Points to Node 1\") {\n CHECK(node2->next_node() == node);\n }\n\n SECTION(\"Node 1 Points to NULL\") {\n node->set_next_node(NULL);\n CHECK(node->next_node() == NULL);\n }\n\n SECTION(\"Node 2 Points to NULL\") {\n node2->set_next_node(NULL);\n CHECK(node2->next_node() == NULL);\n }\n}\n"
},
{
"alpha_fraction": 0.665859580039978,
"alphanum_fraction": 0.6823244690895081,
"avg_line_length": 27.69444465637207,
"blob_id": "7010c982658e9931a58dc4d16c61fba91275b081",
"content_id": "f52079a1893051eb04aca65545067cccde820bfc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2065,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 72,
"path": "/Topic 1/lab 7/lab_7.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_7.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #7. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <sstream>\n#include <cstring>\nusing std::cout;\nusing std::ifstream;\nusing std::endl;\nusing std::string;\nusing std::map;\nusing std::stringstream;\n\n\n\n/*\n * Open and read the contents of a text file. Each line of the\n * file will contain a single integer of possible values 10, 20,\n * 30, 40, or 50. Perform the following operations on the input values:\n * 10 -- invoke the function OnTen\n * 20 -- invoke the function OnTwenty\n * 30 -- invoke the function OnThirty\n * 40 -- invoke the function OnForty\n * 50 -- invoke the function OnFifty\n * any other value -- invoke the function OnError\n * DON'T FORGET TO CLOSE YOUR FILE BEFORE YOUR FUNCTION ENDS!!!\n * @param string filename - A string containing the name of the file to\n * be processed\n * @return bool - True if filename was successfully opened and processed,\n * else false\n */\nbool ProcessFile(string filename);\n/*\n * Process the argv array (command-line arguments to the program). Ignore\n * argv[0] as that is the program name. Perform the following operations on\n * the input values:\n * 10 -- invoke the function OnTen\n * 20 -- invoke the function OnTwenty\n * 30 -- invoke the function OnThirty\n * 40 -- invoke the function OnForty\n * 50 -- invoke the function OnFifty\n * any other value -- invoke the function OnError\n * @param int argc - Contains the number of arguments passed to the program\n * on the command-line\n * @param char *argv[] - An array containing the command-line arguments\n */\nvoid ProcessArguments(int argc, char* argv[]);\n\n// For testing (DO NOT ALTER)\nextern map<int, int> counters;\nextern char* global_argv[8];\nextern int global_argc;\nbool CheckArgs(int argc, char* const argv[]);\nvoid OnTen();\nvoid OnTwenty();\nvoid OnThirty();\nvoid OnForty();\nvoid OnFifty();\nvoid OnError();\n\n\n\n#endif"
},
{
"alpha_fraction": 0.5658363103866577,
"alphanum_fraction": 0.626334547996521,
"avg_line_length": 24.545454025268555,
"blob_id": "574eb17cb147a1eba49273d06f029b97d3d9eecc",
"content_id": "40a4e2c69066c0f4ed321be351b55c5caef5b04f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 281,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 11,
"path": "/Topic 2/lab 5/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "labtest: lab_13_unit_test.o\n\tg++ -Wall -g -o labtest lab_13_unit_test.o\n\t\n#lab_5.o: lab_5.cpp lab_5.h lab_5.o - lab_5.cpp DEPRECATED FILE\n\t#g++ -Wall -g -c lab_5.cpp lab_5.o\n\t\nlab_13_unit_test.o: lab_13_unit_test.cpp\n\tg++ -Wall -g -c lab_13_unit_test.cpp\n\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6674008965492249,
"alphanum_fraction": 0.6688693165779114,
"avg_line_length": 20.935483932495117,
"blob_id": "2d21a284fcc0567d7976ae132ebddb24272f5e30",
"content_id": "9bb4440a78ba9d26a62dcd9a7ea68e6e432b00c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1362,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 62,
"path": "/Topic 2/lab 5/lab_5.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "//NOT USED FOR LAB IN FINAL VERSION!!!\n\n/*\n * Name : lab_5.cpp\n * Author : David Dalton\n * Description : A template program\n */\n \n#include \"lab_5.h\"\n \n/*\n * Constructor\n * @param Type newContents - An initial value to give\n */\ntemplate<typename Type>\nBox<Type>::Box(Type newContents)\n{\n contents_ = newContents;\n}\n/*\n * Accessor\n * @return Type - The value of contents_\n */\ntemplate<typename Type>\nType Box<Type>::getContents() \n{\n return contents_;\n}\n/*\n * Mutator\n * @param Type value - A value to set contents_ to\n */\ntemplate<typename Type>\nvoid Box<Type>::setContents(Type newContents) \n{\n contents_ = newContents;\n}\n/*\n* Overload of << operator.\n* Outputs the contents to the output stream\n* @param ostream &out - The ostream object to output to\n* @param Box contents - The Box object to output from.\n* @return ostream& - The ostream object to allow for chaining of <<\n\n\ntemplate<typename Type>\nostream& operator <<(ostream &out, Box<Type> &contents) \n{\n out << contents.contents_;\n return out;\n}\n*/\n/*\nCreate a template function\n\n * Function Name: Sum\n * Return the \"sum\" of the values in the array. Your initial sum \tshould be set\n * to \"zero\" in your algorithm. To do this use T().\n * @param T values - An array of any type\n * @param unsigned int size - The size of the array\n * @return T - The sum of the values in the array\n */\n\n\n"
},
{
"alpha_fraction": 0.5396977066993713,
"alphanum_fraction": 0.5704057216644287,
"avg_line_length": 21.366548538208008,
"blob_id": "ad26e062e21fab6ba32571395ab11628895b23cb",
"content_id": "ce6bf358c1595328701678ba112dcdfbd48e89bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6285,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 281,
"path": "/Topic 3/Lab 4/lab_19_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_19_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #19 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include <sstream>\n\n#include \"sl_list.h\"\n// To test for Header guards\n#include \"sl_list.h\"\n#include \"sl_node.h\"\n#include \"sl_node.h\"\n\nTEST_CASE(\"Default Constructor for SLNode\") {\n SLNode node, node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 0);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor for SLNode\") {\n SLNode node(1), node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 1);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Testing Pointers for SLNode\") {\n SLNode* node = new SLNode(1);\n SLNode* node2 = new SLNode();\n node->set_next_node(node2);\n node2->set_next_node(node);\n // node and node2 now connect each to the other -- not something you should\n // ever do outside of a testing situation\n SECTION(\"Node 1 Points to Node 2\") {\n CHECK(node->next_node() == node2);\n }\n\n SECTION(\"Node 2 Points to Node 1\") {\n CHECK(node2->next_node() == node);\n }\n\n SECTION(\"Node 1 Points to NULL\") {\n node->set_next_node(NULL);\n CHECK(node->next_node() == NULL);\n }\n\n SECTION(\"Node 2 Points to NULL\") {\n node2->set_next_node(NULL);\n CHECK(node2->next_node() == NULL);\n }\n}\n\n\nTEST_CASE(\"Default Constructor for SLList\") {\n SLList list;\n SECTION(\"Accessor for Size\") {\n CHECK(list.size() == 0);\n }\n\n SECTION(\"ToString()\") {\n CHECK(list.ToString() == \"\");\n }\n\n SECTION(\"GetHead()\") {\n CHECK(list.GetHead() == 0);\n }\n\n SECTION(\"GetTail()\") {\n CHECK(list.GetTail() == 0);\n }\n\n SECTION(\"RemoveHead() on an Empty List\") {\n list.RemoveHead();\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n SECTION(\"RemoveTail() on an Empty List\") {\n list.RemoveTail();\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n}\n\nTEST_CASE(\"Building your Linked List\") {\n SLList list;\n list.InsertHead(1);\n SECTION(\"InsertHead(1)\") {\n CHECK(list.size() == 1);\n CHECK(list.ToString() == \"1\");\n }\n\n list.RemoveHead();\n SECTION(\"RemoveHead()\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n list.InsertTail(5);\n SECTION(\"InsertTail(5)\") {\n CHECK(list.size() == 1);\n CHECK(list.ToString() == \"5\");\n }\n\n list.RemoveTail();\n SECTION(\"RemoveTail()\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n SECTION(\"InsertHead(1) && RemoveTail()\") {\n list.InsertHead(1);\n list.RemoveTail();\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n SECTION(\"InsertTail(1) && RemoveHead()\") {\n list.InsertTail(1);\n list.RemoveHead();\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n list.InsertHead(10), list.InsertHead(20);\n SECTION(\"InsertHead(10), InsertHead(20)\") {\n CHECK(list.size() == 2);\n CHECK(list.ToString() == \"20, 10\");\n }\n\n list.RemoveHead();\n SECTION(\"RemoveHead()\") {\n CHECK(list.size() == 1);\n CHECK(list.ToString() == \"10\");\n }\n\n list.InsertHead(20);\n list.RemoveTail();\n SECTION(\"InsertHead(20) && RemoveTail()\") {\n CHECK(list.size() == 1);\n CHECK(list.ToString() == \"20\");\n }\n\n list.InsertHead(5);\n SECTION(\"InsertHead(5)\") {\n CHECK(list.size() == 2);\n CHECK(list.ToString() == \"5, 20\");\n }\n\n list.Clear();\n SECTION(\"Clear()\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n list.InsertHead(10);\n list.InsertHead(5);\n list.InsertTail(20);\n list.InsertTail(25);\n SECTION(\"InsertHead(10), InsertHead(5), InsertTail(20), InsertTail(25)\") {\n CHECK(list.size() == 4);\n CHECK(list.ToString() == \"5, 10, 20, 25\");\n }\n\n SECTION(\"GetHead()\") {\n CHECK(list.GetHead() == 5);\n }\n\n SECTION(\"GetTail()\") {\n CHECK(list.GetTail() == 25);\n }\n\n list.RemoveHead();\n list.RemoveTail();\n list.RemoveHead();\n list.RemoveTail();\n SECTION(\"RemoveHead(), RemoveTail(), RemoveHead(), RemoveTail()\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n std::stringstream full_head_list, half_head_list, full_tail_list,\n half_tail_list;\n for (int i = 999; i > 0; i--) {\n full_head_list << i << \", \";\n if (i < 500)\n half_head_list << i << \", \";\n }\n full_head_list << 0;\n half_head_list << 0;\n\n for (int i = 0; i < 999; i++) {\n full_tail_list << i << \", \";\n if (i < 499)\n half_tail_list << i << \", \";\n }\n full_tail_list << 999;\n half_tail_list << 499;\n\n for (unsigned int i = 0; i < 1000; i++)\n list.InsertHead(i);\n SECTION(\"InsertHead() \\\"HIGH LOAD\\\"\") {\n CHECK(list.size() == 1000);\n CHECK(list.ToString() == full_head_list.str());\n }\n\n for (unsigned int i = 0; i < 500; i++) {\n list.RemoveHead();\n }\n SECTION(\"RemoveHead() \\\"HIGH LOAD\\\" 1/2\") {\n CHECK(list.size() == 500);\n CHECK(list.ToString() == half_head_list.str());\n }\n\n for (unsigned int i = 0; i < 600; i++) {\n list.RemoveHead();\n }\n SECTION(\"RemoveHead() \\\"HIGH LOAD\\\" 2/2\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n\n for (unsigned int i = 0; i < 1000; i++)\n list.InsertTail(i);\n SECTION(\"InsertTail() \\\"HIGH LOAD\\\"\") {\n CHECK(list.size() == 1000);\n CHECK(list.ToString() == full_tail_list.str());\n }\n\n for (unsigned int i = 0; i < 500; i++) {\n list.RemoveTail();\n }\n SECTION(\"RemoveTail() \\\"HIGH LOAD\\\" 1/2\") {\n CHECK(list.size() == 500);\n CHECK(list.ToString() == half_tail_list.str());\n }\n\n for (unsigned int i = 0; i < 600; i++) {\n list.RemoveTail();\n }\n SECTION(\"RemoveTail() \\\"HIGH LOAD\\\" 2/2\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n}\n"
},
{
"alpha_fraction": 0.43783536553382874,
"alphanum_fraction": 0.5513186454772949,
"avg_line_length": 30.39426612854004,
"blob_id": "0674139019667c92524fc2b1ed00a8a94d3fbe9d",
"content_id": "2f81dd0b39f6b0e01bef8f590f3a03c41d09318f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8759,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 279,
"path": "/Topic 5/Lab 1/lab_15_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_15_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #15 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"sorting.h\"\nbool GRADER = false;\n\nTEST_CASE(\"Bubble Sort\") {\n int main[5] = { 10, 20, 30, 40, 50 };\n int test[5] = { 50, 40, 30, 20, 10 };\n int passes = -1;\n\n SECTION(\"BubbleSort({50, 40, 30, 20, 10})\") {\n passes = BubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n\n SECTION(\"BubbleSort({10, 20, 30, 40, 50})\") {\n test[0] = 10, test[1] = 20, test[2] = 30, test[3] = 40, test[4] = 50;\n passes = BubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n\n SECTION(\"BubbleSort({10, 30, 20, 50, 40})\") {\n test[0] = 10, test[1] = 30, test[2] = 20, test[3] = 50, test[4] = 40;\n passes = BubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n\n SECTION(\"BubbleSort({50, 30, 10, 30, 50})\") {\n main[0] = 10, main[1] = 30, main[2] = 30, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 30, test[2] = 10, test[3] = 30, test[4] = 50;\n passes = BubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n\n SECTION(\"BubbleSort({50, 50, 50, 50, 50})\") {\n main[0] = 50, main[1] = 50, main[2] = 50, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 50, test[2] = 50, test[3] = 50, test[4] = 50;\n passes = BubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n}\n\nTEST_CASE(\"Optimized Bubble Sort\") {\n int main[5] = { 10, 20, 30, 40, 50 };\n int test[5] = { 50, 40, 30, 20, 10 };\n int passes = -1;\n\n SECTION(\"OptimizedBubbleSort({50, 40, 30, 20, 10})\") {\n passes = OptimizedBubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 4);\n }\n\n SECTION(\"OptimizedBubbleSort({10, 20, 30, 40, 50})\") {\n test[0] = 10, test[1] = 20, test[2] = 30, test[3] = 40, test[4] = 50;\n passes = OptimizedBubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 1);\n }\n\n SECTION(\"OptimizedBubbleSort({10, 30, 20, 50, 40})\") {\n test[0] = 10, test[1] = 30, test[2] = 20, test[3] = 50, test[4] = 40;\n passes = OptimizedBubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n\n SECTION(\"OptimizedBubbleSort({50, 30, 10, 30, 50})\") {\n main[0] = 10, main[1] = 30, main[2] = 30, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 30, test[2] = 10, test[3] = 30, test[4] = 50;\n passes = OptimizedBubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 3);\n }\n\n SECTION(\"OptimizedBubbleSort({50, 50, 50, 50, 50})\") {\n main[0] = 50, main[1] = 50, main[2] = 50, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 50, test[2] = 50, test[3] = 50, test[4] = 50;\n passes = OptimizedBubbleSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 1);\n }\n}\n\nTEST_CASE(\"Selection Sort\") {\n int main[5] = { 10, 20, 30, 40, 50 };\n int test[5] = { 50, 40, 30, 20, 10 };\n int passes = -1;\n\n SECTION(\"SelectionSort({50, 40, 30, 20, 10})\") {\n passes = SelectionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"SelectionSort({10, 20, 30, 40, 50})\") {\n test[0] = 10, test[1] = 20, test[2] = 30, test[3] = 40, test[4] = 50;\n passes = SelectionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"SelectionSort({10, 30, 20, 50, 40})\") {\n test[0] = 10, test[1] = 30, test[2] = 20, test[3] = 50, test[4] = 40;\n passes = SelectionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"SelectionSort({50, 30, 10, 30, 50})\") {\n main[0] = 10, main[1] = 30, main[2] = 30, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 30, test[2] = 10, test[3] = 30, test[4] = 50;\n passes = SelectionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"SelectionSort({50, 50, 50, 50, 50})\") {\n main[0] = 50, main[1] = 50, main[2] = 50, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 50, test[2] = 50, test[3] = 50, test[4] = 50;\n passes = SelectionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n}\n\nTEST_CASE(\"Algorithmic Test (For correct SWAPS, etc.)\") {\n int main[5] = { 9, 1, 5, 2, 7 };\n GRADER = true;\n SECTION(\"BubbleSort({9, 1, 5, 2, 7})\") {\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream your_swaps;\n cout.rdbuf(your_swaps.rdbuf());\n BubbleSort(main, 5);\n cout.rdbuf(old_cout);\n CHECK(your_swaps.str() == \"9 1\\n9 5\\n9 2\\n9 7\\n5 2\\n\");\n }\n\n SECTION(\"SelectionSort({9, 1, 5, 2, 7})\") {\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream your_swaps;\n cout.rdbuf(your_swaps.rdbuf());\n SelectionSort(main, 5);\n cout.rdbuf(old_cout);\n CHECK(your_swaps.str() == \"9 1\\n9 2\\n9 7\\n\");\n }\n}\n\nTEST_CASE(\"Insertion Sort\") {\n int main[5] = { 10, 20, 30, 40, 50 };\n int test[5] = { 50, 40, 30, 20, 10 };\n int passes = -1;\n\n SECTION(\"InsertionSort({50, 40, 30, 20, 10})\") {\n passes = InsertionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"InsertionSort({10, 20, 30, 40, 50})\") {\n test[0] = 10, test[1] = 20, test[2] = 30, test[3] = 40, test[4] = 50;\n passes = InsertionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"InsertionSort({10, 30, 20, 50, 40})\") {\n test[0] = 10, test[1] = 30, test[2] = 20, test[3] = 50, test[4] = 40;\n passes = InsertionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"InsertionSort({50, 30, 10, 30, 50})\") {\n main[0] = 10, main[1] = 30, main[2] = 30, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 30, test[2] = 10, test[3] = 30, test[4] = 50;\n passes = InsertionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n\n SECTION(\"InsertionSort({50, 50, 50, 50, 50})\") {\n main[0] = 50, main[1] = 50, main[2] = 50, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 50, test[2] = 50, test[3] = 50, test[4] = 50;\n passes = InsertionSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 5);\n }\n}\n\nTEST_CASE(\"Shell Sort\") {\n int main[5] = { 10, 20, 30, 40, 50 };\n int test[5] = { 50, 40, 30, 20, 10 };\n int passes = -1;\n\n SECTION(\"ShellSort({50, 40, 30, 20, 10})\") {\n passes = ShellSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n\n SECTION(\"ShellSort({10, 20, 30, 40, 50})\") {\n test[0] = 10, test[1] = 20, test[2] = 30, test[3] = 40, test[4] = 50;\n passes = ShellSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n\n SECTION(\"ShellSort({10, 30, 20, 50, 40})\") {\n test[0] = 10, test[1] = 30, test[2] = 20, test[3] = 50, test[4] = 40;\n passes = ShellSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n\n SECTION(\"ShellSort({50, 30, 10, 30, 50})\") {\n main[0] = 10, main[1] = 30, main[2] = 30, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 30, test[2] = 10, test[3] = 30, test[4] = 50;\n passes = ShellSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n\n SECTION(\"ShellSort({50, 50, 50, 50, 50})\") {\n main[0] = 50, main[1] = 50, main[2] = 50, main[3] = 50, main[4] = 50;\n test[0] = 50, test[1] = 50, test[2] = 50, test[3] = 50, test[4] = 50;\n passes = ShellSort(test, 5);\n CHECK(CompareArrays(main, test, 5));\n CHECK(passes == 2);\n }\n}\n\nTEST_CASE(\"Algorithmic Test (For correct SWAPS, etc.)\") {\n int main[5] = { 9, 1, 5, 2, 7 };\n GRADER = true;\n SECTION(\"InsertionSort({9, 1, 5, 2, 7})\") {\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream your_swaps;\n cout.rdbuf(your_swaps.rdbuf());\n InsertionSort(main, 5);\n cout.rdbuf(old_cout);\n CHECK(your_swaps.str() == \"1 9\\n5 9\\n2 9\\n2 5\\n7 9\\n\");\n }\n\n SECTION(\"ShellSort({9, 1, 5, 2, 7})\") {\n std::streambuf* old_cout = cout.rdbuf();\n std::ostringstream your_swaps;\n cout.rdbuf(your_swaps.rdbuf());\n ShellSort(main, 5);\n cout.rdbuf(old_cout);\n CHECK(your_swaps.str() == \"5 1 9 2 7 \\n5 1 9 2 7 \\n5 1 7 2 9 \\n1 5 7 2 9 \\n1 5 7 2 9 \\n1 2 5 7 9 \\n1 2 5 7 9 \\n\");\n }\n}\n\nbool CompareArrays(int array_one[], int array_two[], unsigned int size) {\n for (unsigned int i = 0; i < size; i++)\n if (array_one[i] != array_two[i])\n return false;\n return true;\n}\n\nvoid DisplayArray(int values[]) {\n if (GRADER) {\n for (unsigned int i = 0; i < 5; i++)\n cout << values[i] << ' ';\n cout << endl;\n }\n}\n"
},
{
"alpha_fraction": 0.5958012938499451,
"alphanum_fraction": 0.645180344581604,
"avg_line_length": 24.81679344177246,
"blob_id": "7bc5932169429350a50b1f21c1c740ab8eff959d",
"content_id": "7575501c6930a4c81a7001e4be9299d136d4d389",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3382,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 131,
"path": "/Topic 2/lab 2/lab_10_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_10_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #10 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"temperature.h\"\n// Double Include to Check for Header Guards\n#include \"temperature.h\"\n\nTEST_CASE(\"Temperature Using Default Constuctor\") {\n Temperature temp;\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() == 0);\n }\n\n temp.SetTempFromKelvin(50);\n SECTION(\"SetTempFromKelvin(50) / GetTempAsCelsius()\") {\n CHECK(temp.GetTempAsKelvin() == 50);\n }\n\n temp.SetTempFromCelsius(5);\n SECTION(\"SetTempFromCelsius(5) / GetTempAsFarenheit()\") {\n CHECK(temp.GetTempAsFahrenheit() >= 40.99);\n CHECK(temp.GetTempAsFahrenheit() <= 41.01);\n }\n\n temp.SetTempFromFahrenheit(5);\n SECTION(\"SetTempFromFahrenheit(5) / GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 258.149);\n CHECK(temp.GetTempAsKelvin() <= 258.151);\n }\n\n SECTION(\"ToString()\") {\n CHECK(temp.ToString() == \"258.15 Kelvin\");\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 1 Parameter: Temperature(50)\") {\n Temperature temp(50);\n\n SECTION(\"GetTempAsFahrenheit()\") {\n CHECK(temp.GetTempAsFahrenheit() >= -369.68);\n CHECK(temp.GetTempAsFahrenheit() <= -369.66);\n }\n\n SECTION(\"ToString('C')\") {\n CHECK(temp.ToString('C') == \"-223.15 Celsius\");\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, 'F')\") {\n Temperature temp(5, 'F');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 258.14);\n CHECK(temp.GetTempAsFahrenheit() <= 258.16);\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, 'f')\") {\n Temperature temp(5, 'f');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 258.14);\n CHECK(temp.GetTempAsKelvin() <= 258.16);\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, 'C')\") {\n Temperature temp(5, 'C');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 278.14);\n CHECK(temp.GetTempAsKelvin() <= 278.16);\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, 'c')\") {\n Temperature temp(5, 'c');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 278.14);\n CHECK(temp.GetTempAsKelvin() <= 278.16);\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, 'K')\") {\n Temperature temp(5, 'K');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 4.99999);\n CHECK(temp.GetTempAsKelvin() <= 5.00001);\n }\n}\n\nTEST_CASE(\"Temperature Using Overloaded Constuctor w/ 2 Parameters: Temperature(5, '5')\") {\n Temperature temp(5, '5');\n\n SECTION(\"GetTempAsKelvin()\") {\n CHECK(temp.GetTempAsKelvin() >= 4.99999);\n CHECK(temp.GetTempAsKelvin() <= 5.00001);\n }\n\n SECTION(\"ToString('c')\") {\n CHECK(temp.ToString('c') == \"-268.15 Celsius\");\n }\n\n SECTION(\"ToString('K')\") {\n CHECK(temp.ToString('K') == \"5.00 Kelvin\");\n }\n\n SECTION(\"ToString('k')\") {\n CHECK(temp.ToString('k') == \"5.00 Kelvin\");\n }\n\n SECTION(\"ToString('F')\") {\n CHECK(temp.ToString('F') == \"-450.67 Fahrenheit\");\n }\n\n SECTION(\"ToString('f')\") {\n CHECK(temp.ToString('f') == \"-450.67 Fahrenheit\");\n }\n\n SECTION(\"ToString('1')\") {\n CHECK(temp.ToString('1') == \"Invalid Unit\");\n }\n}\n"
},
{
"alpha_fraction": 0.6306532621383667,
"alphanum_fraction": 0.69597989320755,
"avg_line_length": 23.875,
"blob_id": "547ad9a10d3e4691ed2eddd3b4dfb340b5b35ad2",
"content_id": "4534ca5d86ff352ce73c1f29a331494770e519c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 398,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 16,
"path": "/Topic 3/Lab 1/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nlab12test: lab_12_unit_test.o lab_12.o\n\tg++ -Wall -g -o lab12test lab_12.o lab_12_unit_test.o\n\n#creates the lab object file\t\nlab12: lab_12.cpp lab_12.h\n\tg++ -Wall -g -c lab_12.cpp\n\n#creates the lab unit test object file\nlab_12_unit_test: lab_12_unit_test.cpp\n\tg++ -Wall -g -c lab_12_unit_test.cpp\n\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.5490368008613586,
"alphanum_fraction": 0.5770577788352966,
"avg_line_length": 26.85365867614746,
"blob_id": "824691f06ac20062e90446026cef8a1efc8c6334",
"content_id": "87b01292da7d01dfd349741ffb555978f0d22b54",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1142,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 41,
"path": "/Topic 2/lab 1/lab_1_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_9_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #9 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_1.h\"\n\nTEST_CASE(\"Creating a Spaceship\") {\n Spaceship enterprise;\n\n enterprise.set_name(\"USS Enterprise-D\");\n SECTION(\"set_name(\\\"USS Enterprise-D\\\")/name()\") {\n CHECK(enterprise.name() == \"USS Enterprise-D\");\n }\n\n enterprise.set_top_speed(9.6);\n SECTION(\"set_top_speed(9.6)/top_speed()\") {\n CHECK(enterprise.top_speed() >= 9.59);\n CHECK(enterprise.top_speed() <= 9.61);\n }\n\n enterprise.set_fuel_source(\"Plasma\");\n SECTION(\"set_fuel_source(\\\"Plasma\\\")/fuel_source()\") {\n CHECK(enterprise.fuel_source() == \"Plasma\");\n }\n\n enterprise.set_crew_capacity(5000);\n SECTION(\"set_crew_capacity(5000)/crew_capacity()\") {\n CHECK(enterprise.crew_capacity() == 5000);\n }\n\n SECTION(\"ToString\") {\n CHECK(enterprise.ToString() == \"USS Enterprise-D\\n\"\n \"Top Speed: Warp 9.60\\n\"\n \"Fuel Source: Plasma\\n\"\n \"Crew Capacity: 5000\");\n }\n}\n"
},
{
"alpha_fraction": 0.6243885159492493,
"alphanum_fraction": 0.6254367828369141,
"avg_line_length": 25.509260177612305,
"blob_id": "4d94b7b074d8833601eaeec88d3b68bacb81a7ea",
"content_id": "fc5aba211825b61063b1f1532e025883274f76a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2862,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 108,
"path": "/Topic 2/lab 1/lab_1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_1.cpp\n * Author : David Dalton\n * Description : Building a Spaceship Class\n */\n#include \"lab_1.h\"\n\n /*\n * Set the name of this Spaceship.\n * @param string name - The name for this Spaceship\n */\n void Spaceship::set_name(string name) \n {\n name_ = name;\n }\n\n /*\n * Set the top speed of this Spaceship.\n * @param double top_speed - The top speed for this Spaceship in warp\n */\n void Spaceship::set_top_speed(double top_speed) \n {\n top_speed_ = top_speed;\n }\n\n /*\n * Set the fuel source of this Spaceship.\n * @param string fuel_source - A fuel source for this Spaceship\n */\n void Spaceship::set_fuel_source(string fuel_source) \n {\n fuel_source_ = fuel_source;\n }\n\n /*\n * Set the crew capacity of this Spaceship.\n * @param int crew_capacity - A crew capacity for this Spaceship\n */\n void Spaceship::set_crew_capacity(int crew_capacity) \n {\n crew_capacity_ = crew_capacity;\n }\n\n /*\n * Get the name of this Spaceship.\n * @return string - The name of this Spaceship\n */\n string Spaceship::name() const \n {\n return name_;\n }\n\n /*\n * Get the top speed of this Spaceship.\n * @return double - The top speed of this Spaceship\n */\n double Spaceship::top_speed() const \n {\n return top_speed_;\n }\n\n /*\n * Get the fuel source of this Spaceship.\n * @return string - The fuel source of this Spaceship\n */\n string Spaceship::fuel_source() const \n {\n return fuel_source_;\n }\n\n /*\n * Get the crew capacity of this Spaceship.\n * @return int - The crew capacity of this Spaceship\n */\n int Spaceship::crew_capacity() const \n {\n return crew_capacity_;\n }\n\n /*\n * Get a string representation of this Spaceship's specifications.\n * The string will be formatted as\n * \"NAME\\n\n * Top Speed: Warp TOP_SPEED\\n\n * Fuel Source: FUEL_SOURCE\\n\n * Crew Capacity: CREW_CAPACITY\"\n * where NAME, TOP_SPEED (to two decimal places), FUEL_SOURCE, and\n * CREW_CAPACITY contain the values of the associated member variables.\n * @uses stringstream\n * @return string - A representation of this Spaceship's specifications\n */\n string Spaceship::ToString() const \n {\n /*\n *Uses stringstream to retrieve all of the class variables and stores them\n *into the stream along with additional descriptive strings. Once they are\n *all combined in the stringstream it then retrieves the combined string and\n *returns it.\n */\n stringstream ship_description;\n ship_description.setf(std::ios::fixed|std::ios::showpoint);\n ship_description.precision(2);\n ship_description << name_ << \"\\n\" << \"Top Speed: Warp \"\n << top_speed_ << \"\\n\" << \"Fuel Source: \" \n << fuel_source_ << \"\\n\" << \"Crew Capacity: \" \n << crew_capacity_;\n return ship_description.str();\n }"
},
{
"alpha_fraction": 0.6388888955116272,
"alphanum_fraction": 0.6440972089767456,
"avg_line_length": 15.45714282989502,
"blob_id": "b25651b55fdbb097cd3fc9980b78d0f4ccc200e5",
"content_id": "a39a8f2faf96c9c6e22910fe29c803b3f3e7bbe1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 576,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 35,
"path": "/Topic 4/Lab 1/lab_recursion.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_recursion.cpp\n * Author : David Dalton\n * Description : Recursive Functions\n */\n\n#include \"lab_recursion.h\"\n\n#include <stdio.h> \n#include <stdlib.h>\n#include <math.h>\n\n// CODE FUNCTION DEFINITIONS HERE\n\n\n/*\n * Convert a binary number to decimal\n * @param number to be converted\n * @return an unsigned int\n */\nunsigned int binToDec(int num) \n{\n\t\n\tstring convert_int = num;\n\tint byte_size = convert_int.length();\n\n\tunsigned int i = 0;\n\tunsigned int total = 0;\n\tif(i < byte_size)\n\t{\n\t\ttotal = pow(2, i);\n\t\treturn total + binTodec(num);\n\t}\n\treturn total;\n}\n"
},
{
"alpha_fraction": 0.7216035723686218,
"alphanum_fraction": 0.7461024522781372,
"avg_line_length": 28.933332443237305,
"blob_id": "7ab43324b2d9d3c2dbd9c448a2fbeab79c2a5be5",
"content_id": "9524f810aab226d41fc2e8e6fb658317515fef56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 15,
"path": "/Topic 2/lab 2/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\ntemperaturetest: lab_10_unit_test.o temperature.o\n\tg++ -Wall -g -o temperaturetest temperature.o lab_10_unit_test.o\n\n#creates the lab6 object file\t\ntemperature: temperature.cpp temperature.h\n\tg++ -Wall -g -c temperature.cpp\n\n#creates the unit test object file\nlab_10_unit_test: lab_10_unit_test.cpp\n\tg++ -Wall -g -c lab_10_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o temperaturetest "
},
{
"alpha_fraction": 0.6717557311058044,
"alphanum_fraction": 0.6927480697631836,
"avg_line_length": 26.578947067260742,
"blob_id": "8d860d2c24b4b0aadfa411451451846fbaf49f67",
"content_id": "88e6bfe20811f7d4a2feea6c8aa4c56d1a363f9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 524,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 19,
"path": "/Topic 3/Lab 5/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nsl_nodetest: lab_20_unit_test.o sl_list.o sl_node.o\n\tg++ -Wall -g -o lab2test sl_node.o sl_list.o lab_20_unit_test.o\n\n#creates the node object file\t\nsl_node.o: sl_node.cpp sl_node.h\n\tg++ -Wall -g -c sl_node.cpp\n\t\n#creates the list object file\nsl_list.o: sl_list.cpp sl_list.h\n\tg++ -Wall -g -c sl_list.cpp\n\n#creates the lab unit test object file\nlab_20_unit_test.o: lab_20_unit_test.cpp\n\tg++ -Wall -g -c lab_20_unit_test.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.6443974375724792,
"alphanum_fraction": 0.6490486264228821,
"avg_line_length": 27.85365867614746,
"blob_id": "64182183cf56a9e42db38c032fecc39cb23ea34c",
"content_id": "d73d4787a1cc6a4893aea47232c504d9f7340865",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2365,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 82,
"path": "/Topic 1/lab 1/lab_1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_1.cpp\n * Author : David\n * Date : Dalton\n * Description : Our First Lab of the Semester!\n */\n#include <iostream>\n#include <string>\n#include <cctype>\n#include <vector>\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\n\n/*\n * Create a string message based upon whether or not a user has \n * programming experience.\n * @param hasExperience a char ('y'es or 'n'o) representing whether\n * or not a user has programming experience\n * @return \"Welcome back\" when hasExperience is 'y', else \"Get ready to\n * have some fun\"\n */\nstring checkExperience (char hasExperience) \n{\n //CODE HERE\n if (hasExperience == 'y' || hasExperience == 'Y') {\n return string(\"Welcome back\");\n //cout << \"Welcome back\" << endl;\n } else {\n return string(\"Get ready to have some fun\");\n //cout << \"Get ready to have some fun\" << endl;\n }\n \n}\n\n/*\n * Create a program based on the comments below\n * @param none\n * @return none\n */\nvoid FirstLab() {\n // (1) Declare a string variable named first_name\n string first_name;\n\n // (2) Declare a character variable named programmed_before and another named\n // my_character. Initialize both of them to the value 'z'\n char programmed_before = 'z';\n char my_character = 'z';\n\n // (3) Display a welcome message to standard output\n cout << \"Welcome to the machine.\" << endl;\n\n // (4) Prompt the user for their first name\n cout << \"Please enter your name.\" << endl;\n\n // (5) Read the name from standard input and store in the variable first_name\n cin >> first_name;\n\n // (6) Display the message \"Nice to meet you, NAME\" where NAME is replacedgrr\n // with the value of first_name\n cout << \"Nice to meet you, \" << first_name << \".\" << endl;\n \n // (7) Ask the user if they have programmed before. Make sure you inform them\n // that you want the answer as a single character (y/n)\n cout << \"Have you ever programmed before? Please enter \\\"Y\\\" for yes or \\\"N\\\" for no.\" << endl;\n\n // (8): Read in the answer from standard input and store in the variable\n // programmed_before\n cin >> programmed_before;\n\n // (9): Call the function checkExperience appropriately so that the message will display\n string testvar = checkExperience(programmed_before);\n cout << testvar << endl;\n \n}\n\nint main()\n{\n FirstLab();\n return 0;\n}"
},
{
"alpha_fraction": 0.6568284034729004,
"alphanum_fraction": 0.6583291888237,
"avg_line_length": 26.57241439819336,
"blob_id": "b9e3fc2ca102c8eb5d2288d75e560794995ba735",
"content_id": "534975bb6b970b94ad41de73c58f3fde62d6f0c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3998,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 145,
"path": "/Topic 5/Lab 2/lab_27.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_27.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #27. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <algorithm> // for sort\n#include <cstddef> // for NULL\n#include <iostream> // for operator<<\n#include <string>\n#include <vector>\n#include <sstream>\nusing std::string;\nusing std::ostream;\nusing std::vector;\nusing std::stringstream;\nusing std::sort;\n\nstruct Item {\n Item(string name = \"noname\", unsigned int value = 0,\n unsigned int quantity = 0)\n : name_(name),\n value_(value),\n quantity_(quantity) {\n }\n\n friend ostream& operator<<(ostream& outs, const Item& src) {\n outs << src.name_;\n return outs;\n }\n\n string name_;\n unsigned int value_;\n unsigned int quantity_;\n};\n\nclass TreasureChest {\n public:\n /*\n * Add an item to the end of the chest.\n * @param Item& item_to_add - The item to be added to the end of the chest\n */\n void AddItem(const Item& item_to_add);\n\n /*\n * Insert an item at the specified zero-indexed position in the chest. If\n * position is not valid for the chest, add the item to the end of the chest.\n * Note this function inserts, not replaces.\n * @param Item& item_to_add - The item to be inserted into the chest\n * @param u-int position - The zero-indexed position where the insertion is\n * to take place.\n */\n void InsertItem(const Item& item_to_add, unsigned int position);\n\n /*\n * Get a pointer to an item at a specified zero-indexed position in the chest.\n * @param u-int position - The zero-indexed position of the item\n * @return const Item* - A pointer to the item if position is valid, else NULL\n */\n const Item* GetItem(unsigned int position);\n\n /*\n * Remove an item from the chest at a specified zero-indexed position.\n * @param u-int position - The zero-indexed position of the item\n * @return Item - A copy of the Item removed from the chest\n * @throw string(\"ERROR: Remove at invalid position\") if position is not valid\n */\n Item RemoveItem(unsigned int position);\n\n /*\n * Clear the chest of all items.\n */\n void Clear();\n\n /*\n * Check to see if the chest is empty.\n * @return bool - True if the chest is empty, else false\n */\n bool Empty() const;\n\n /*\n * Get the size/number of items currently in the chest.\n * @return u-int - The current size of the chest\n */\n unsigned int GetSize() const;\n\n /*\n * Sort the items in the chest by name, using the sort function\n * from the C++ standard algorithm library.\n */\n void SortByName();\n\n /*\n * Sort the items in the chest by value, using the sort function\n * from the C++ standard algorithm library.\n */\n void SortByValue();\n\n /*\n * Sort the items in the chest by quantity, using the sort function\n * from the C++ standard algorithm library.\n */\n void SortByQuantity();\n\n /*\n * Place the names of the items in the chest on the specified stream,\n * formatted as ITEM_NAME, ITEM_NAME, ..., ITEM_NAME\n * Places \"Chest Empty!\" on the stream if the chest is empty\n */\n friend ostream& operator<<(ostream& outs, const TreasureChest& src);\n\n /*\n * Returns a string representation of what the overloaded << operator would\n * output. Remember: 'this' is a keyword that points to the current object\n * @uses Overloaded << Operator\n * @return string - A string in the format ITEM_NAME, ... or \"Chest Empty!\"\n */\n string ToString();\n\n private:\n vector<Item> chest_;\n};\n\n/*\n * Compare two items by name.\n * @return true if lsrc.name_ < rsrc.name_, else false\n */\nbool CompareItemsByName(const Item& lsrc, const Item& rsrc);\n\n/*\n * Compare two items by value.\n * @return true if lsrc.value_ < rsrc.value_, else false\n */\nbool CompareItemsByValue(const Item& lsrc, const Item& rsrc);\n\n/*\n * Compare two items by quantity.\n * @return true if lsrc.quantity_ < rsrc.quantity_, else false\n */\nbool CompareItemsByQuantity(const Item& lsrc, const Item& rsrc);\n\n#endif /* TREASURE_CHEST_H_ */\n"
},
{
"alpha_fraction": 0.6059451103210449,
"alphanum_fraction": 0.6070883870124817,
"avg_line_length": 23.532711029052734,
"blob_id": "80d37660d52154798fbc7df7cdbd929e49586c45",
"content_id": "121561d1eec6b60d7a66ec8a9886468dd7042133",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2624,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 107,
"path": "/Topic 3/Assignment 4/dl_list.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: dl_list.h\n * Author: David Dalton\n * Sources:\n */\n \n#ifndef LIST_H\n#define LIST_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include \"dl_node.h\"\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\nusing std::ostream;\nusing std::istream;\n\n \n/**\n * A DLList class to contain all of the functionality of a doubly-linked list: \n * push front, pushback, pop front, pop back, insert (sorted), remove, \n * retrieve, overloaded operator <<,constructor, destructor, clear, size\n */\nclass DLList\n{\n public:\n /**\n * Default Constructor\n * initialize count to zero, head and tail to NULL\n */\n DLList();\n /**\n * Destructor\n * call clear function\n */\n ~DLList();\n /**\n * Accessor for count_\n * return count\n */\n unsigned int getSize() const;\n /**\n * create new DLNode with newContents and attach at head\n */\n void pushFront(int newContents);\n /**\n * create new DLNode with newContents and attach at tail\n */\n void pushBack(int newContents);\n /**\n * create new DLNode with newContents and insert in ascending (based on \n * newContents) order\n */\n void insert(int newContents);\n /**\n * return the value of the contents of the head node; throw an exception \n * (throw \"LIST EMPTY\") if the list is empty\n */\n int getFront() const;\n /**\n * return the value of the contents of the tail node; throw an exception \n * (throw \"LIST EMPTY\") if the list is empty\n */\n int getBack() const;\n /**\n * return true if target is in list, else return false\n */\n bool get(int target) const;\n /**\n * remove current head node; do nothing if list is empty\n */\n void popFront();\n /**\n * remove current tail node; do nothing if list is empty\n */\n void popBack();\n /**\n * remove the first instance of a DLNode containing target; do nothing if \n * target is not found\n */\n bool removeFirst(int target);\n /**\n * remove all instances of DLNode containing target; do nothing if target \n * is not found\n */\n bool removeAll(int target);\n /**\n * clear all nodes from list, reset count to zero, set head and tail to NULL\n */\n void clear();\n /**\n * display the contents of each node in the list, formatted per the \n * program specification (\"NUM1,NUM2,NUM3,...,NUMX\"), to the output stream \n * out\n */\n friend ostream& operator <<(ostream &out, const DLList &src);\n \n private:\n DLNode* head_;\n DLNode* tail_;\n unsigned int count_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.5980740189552307,
"alphanum_fraction": 0.6033958196640015,
"avg_line_length": 28.022058486938477,
"blob_id": "82f800ab5a1592cdbedcc531a5f222134ecb5f20",
"content_id": "f36869b9546c7e4ce07eb72d45e121983a3eee9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3946,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 136,
"path": "/Topic 2/Assignment 2/credit_account.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : credit_account.h\n * Author : David Dalton\n * Description : Credit Account class header file\n */\n \n#ifndef CREDIT_H\n#define CREDIT_H\n\n#include \"bank_account.h\"\n#include \"savings_account.h\"\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::setfill;\nusing std::setw;\nusing std::setprecision;\nusing std::fixed;\n\nclass CreditAccount : public BankAccount\n{\n public:\n /*\n * Constructor\n *uses default values if none given\n */\n CreditAccount(string account_name = \"account\", long dollars = 0, \n int cents = 0, double interest_rate = 0.0,\n long max_balance_dollars = 0, \n int max_balance_cents = 0,\n string last_transaction = \"none\",\n string interest_accumulated_month = \"$0.0\", \n string interest_accumulated_year = \"$0.0\");\n /*\n * Destructor \n *unused\n */\n virtual ~CreditAccount();\n /*\n * Mutator\n *sets the value of interset_rate_ to the given double\n */\n void SetInterestRate(double = 0.0);\n /*\n * Mutator\n *sets the value of max_balance_dollars_ to the given long\n */\n void SetMaxBalanceDollars(long max_balance_dollars);\n /*\n * Mutator\n *sets the value of max_balance_cents_ to the given int\n */\n void SetMaxBalanceCents(int max_balance_cents);\n /*\n * Mutator\n *sets the value of interest_accumulated_month_ to the input values\n */\n void SetInterestAccumulatedMonth(long accumulated_dollars = 0, \n int accumulated_cents = 0);\n /*\n * Mutator\n *sets the value of interest_accumulated_year_ to the input values\n */\n void SetInterestAccumulatedYear(long accumulated_dollars = 0, \n int accumulated_cents = 0);\n /*\n * Mutator\n *makes a payment in the given amount on the current balance by \n *subtracting the given amount from the current balance then setting\n *the balance to the result\n */\n void MakePayment(long payment_dollars = 0, int payment_cents = 0);\n /*\n * Mutator\n *makes a charge to the card in a given amount with the given transaction\n *id number. It then adds this amount to the current balance\n */\n void ChargeCard(long transaction_number = 0, long charge_dollars = 0, \n int charge_cents = 0);\n /*\n * Mutator\n *calculates interest on the current balance for the month and the year\n */\n void CalculateInterest();\n /*\n * Accessor\n *gets the value of interest_rate_ and returns it\n */\n double GetInterestRate();\n /*\n * Accessor\n *gets the value of max_balance_dollars_ and returns it\n */\n long GetMaxBalanceDollars();\n /*\n * Accessor\n *gets the value of max_balance_cents_ and returns it\n */\n int GetMaxBalanceCents();\n /*\n * Accessor\n *calls the GetMaxBalanceDollars() and GetMaxBalanceCents() functions to get\n *the values of their variables. It then stores the values of those variables\n *and sends them to a stringstream along with default characters. It then\n *returns the string\n */\n string GetMaxBalance();\n /*\n * Accessor\n *gets the value of interest_accumulated_month_ and returns it\n */\n string GetInterestAccumulatedMonth();\n /*\n * Accessor\n *gets the value of interest_accumulated_year_ and returns it\n */\n string GetInterestAccumulatedYear();\n \n \n private:\n double interest_rate_;\n long max_balance_dollars_;\n int max_balance_cents_;\n string interest_accumulated_month_;\n string interest_accumulated_year_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6596939563751221,
"alphanum_fraction": 0.6773194074630737,
"avg_line_length": 29.922155380249023,
"blob_id": "6eb39dffae202db2969275579f7319d130a3d1d0",
"content_id": "cb87727ebd052280ca3b7547031e1b8bca7fe471",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5163,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 167,
"path": "/Topic 2/lab 3/money.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : money.cpp\n * Author : David Dalton\n * Description : Program that retrieves and manipulates values from an object\n */\n \n#include \"money.h\"\nusing std::cout;\nusing std::endl;\n\n\n/*\n * Constructor #1.\n * Sets dollars and cents to the supplied values. Defaults to 0\n * @param int dollars - The value to set dollars_ to\n * @param int cents - The value to set cents_ to\n */\n/*\nMoney(int dollars, int cents)\n\n/*\n * Overload of + operator. This is a friend function.\n * @param Money amount1 - The first object to add\n * @param Money amount2 - The second object to add\n * @return Money - The two objects added together\n *\nfriend const Money operator +(const Money& amount1, const Money& amount2)\n*/\n\n// The Constructor, Accessors and Mutators have been defined for you\nMoney::Money(int dollars, int cents)\n : dollars_(dollars),\n cents_(cents) {\n}\n\nint Money::dollars() const {\n return dollars_;\n}\n\nint Money::cents() const {\n return cents_;\n}\n\nvoid Money::set_dollars(int dollars) {\n dollars_ = dollars;\n}\n\nvoid Money::set_cents(int cents) {\n cents_ = cents;\n}\n\n// This function definition provided as an example and is FULLY COMPLETE\nconst Money operator +(const Money& amount1, const Money& amount2) {\n // Get all the cents of object 1\n int all_cents1 = amount1.cents_ + amount1.dollars_ * 100;\n // Get all the cents of object 2\n int all_cents2 = amount2.cents_ + amount2.dollars_ * 100;\n // Add all the cents together\n int sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n int abs_all_cents = abs(sum_all_cents);\n int final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n return Money(final_dollars, final_cents);\n}\n\n// REST OF CLASS FUNCTION DEFINITIONS GO HERE\n\n/*\n * Overload of binary - operator. This is a friend function.\n * @param Money amount1 - The object to subtract from\n * @param Money amount2 - The object to be subtracted\n * @return Money - The result of the subtraction\n */\n\nconst Money operator -(const Money& amount1, const Money& amount2) \n{\n // Get all the cents of object 1\n int all_cents1 = amount1.cents_ + amount1.dollars_ * 100;\n // Get all the cents of object 2\n int all_cents2 = amount2.cents_ + amount2.dollars_ * 100;\n //Subtracts object 2 all cents from object 1 all cents\n int sum_all_cents = all_cents1 - all_cents2;\n // Handle the fact that money can be negative\n int abs_all_cents = abs(sum_all_cents);\n int final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) \n {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n return Money(final_dollars, final_cents);\n}\n\n/*\n * Overload of == operator. This is a friend function.\n * @param Money amount1 - The first object to compare\n * @param Money amount2 - The second object to compare\n * @return bool - True if the objects have the same values, otherwise false\n */\nbool operator ==(const Money &amount1, const Money &amount2)\n{\n // Get all the cents of object 1\n int all_cents1 = amount1.cents_ + amount1.dollars_ * 100;\n // Get all the cents of object 2\n int all_cents2 = amount2.cents_ + amount2.dollars_ * 100;\n // Compares the two values. If they are equal returns true, otherwise\n // returns false\n if(all_cents1 == all_cents2)\n {\n return true;\n } else\n {\n return false;\n }\n}\n\n/*\n * Overload of unary - operator. This is a friend function.\n * @param Money amount - The object to negate\n * @return Money - The result of the negation of the two member variables\n */\nconst Money operator -(const Money &amount)\n{\n //Gets the dollars and cents of an object and makes them negative\n return Money(-amount.dollars_, -amount.cents_);\n}\n\n/*\n * Overload of << operator.\n * Outputs the money values to the output stream.\n * Should be in the form $x.xx\n * @uses setw()\n * @uses setfill()\n * @param ostream &out - The ostream object to output to\n * @param Money amount - The Money object to output from.\n * @return ostream& - The ostream object to allow for chaining of <<\n */\nostream& operator <<(ostream &out, const Money &amount)\n{\n int absolute_cents = abs(amount.cents_);\n /*\n *Gets the absolute value of the objects cents value and stores it into a \n *variable. It then gets the value of the objects dollars_ and cents_\n *variables and checks to see if they are equal to and less than 0. If\n *they are then they send them to an output stream with a negative character\n *otherwise it sends it to the output stream without the negative character\n *then returns the output stream\n */\n if ((amount.dollars_ == 0) && (amount.cents_ < 0))\n {\n out << \"$-\" << setw(1) << setfill('0') << amount.dollars_ << '.' \n << setfill('0') << setw(2) << absolute_cents;\n } else\n {\n out << '$' << setw(1) << setfill('0') << amount.dollars_ << '.' \n << setfill('0') << setw(2) << absolute_cents;\n }\n return out;\n}"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.699999988079071,
"avg_line_length": 18,
"blob_id": "02822ed0671b56510a2b34b67ecbdb0cd060fc6f",
"content_id": "882bdbe1c069f01fc0ff7d05379b83d594aa976f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 80,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 4,
"path": "/CSCI465/requirements.txt",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "Django==1.11.5\r\npytz==2017.2\r\nvirtualenv==15.1.0\r\nvirtualenvwrapper-win==1.2.1\r\n"
},
{
"alpha_fraction": 0.5980861186981201,
"alphanum_fraction": 0.6028708219528198,
"avg_line_length": 32.83333206176758,
"blob_id": "a998d99e033340a9e40c0261be733860428d8c25",
"content_id": "b4e9011bac0613ef0952909d94de6fa73809e935",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 627,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 18,
"path": "/CSCI465v5/firstapp/urls.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^$',views.index, name='index'),\r\n url(r'page2$',views.page2, name='page2'),\r\n url(r'register/$',views.register, name='register'),\r\n url(r'suggestions/$',views.suggestions, name='suggestions'),\r\n url(r'^suggest/$',views.suggestion_view, name='suggest'),\r\n url(r'profile/$',views.profile, name='profile'),\r\n url(r'about/$',views.about, name='about'),\r\n url(r'lfg/$',views.lfg, name='lfg'),\r\n url(r'lfm/$',views.lfm, name='lfm'),\r\n url(r'wtb/$',views.wtb, name='wtb'),\r\n url(r'wts/$',views.wts, name='wts'),\r\n\r\n]\r\n"
},
{
"alpha_fraction": 0.6528497338294983,
"alphanum_fraction": 0.6917098164558411,
"avg_line_length": 24.733333587646484,
"blob_id": "07f19b8e180fdcc5a930e5ba6f5ffa69297ca3f4",
"content_id": "b7df3054a314b88bb1bfe1f83c774caab1770125",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 386,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 15,
"path": "/Topic 1/lab 6/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\nlab6test: lab_6_unit_test.o lab_6.o\n\tg++ -Wall -g -o lab6test lab_6.o lab_6_unit_test.o\n\n#creates the lab6 object file\t\nlab6: lab_6.cpp lab_6.h\n\tg++ -Wall -g -c lab_6.cpp\n\n#creates the unit test object file\nlab_6_unit_test: lab_6_unit_test.cpp\n\tg++ -Wall -g -c lab_6_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o lab6test "
},
{
"alpha_fraction": 0.6440678238868713,
"alphanum_fraction": 0.6468926668167114,
"avg_line_length": 18.68055534362793,
"blob_id": "bbe9249dbb4aad37762714d99642b36bee6c1f37",
"content_id": "a6da185c8529bf7c3b4765916d034b7c621afec9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1416,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 72,
"path": "/Topic 3/Lab 3/sl_list.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_list.h\n * Author : David Dalton\n * Description : Header File for lab 3 sl_list.\n */\n\n#ifndef LIST_H\n#define LIST_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include \"sl_node.h\"\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\nclass SLList \n{\n public:\n /*\n Default Constructor\n --sets head_ to NULL\n --sets size_ to 0\n */\n SLList();\n /*\n Destructor\n --calls Clear()\n */\n ~SLList();\n /*\n void InsertHead(int)\n --creates a new dynamic SLNode with the contents of \n the parameter and attaches as the new head of the list\n */\n void InsertHead(int insert);\n /*\n void RemoveHead()\n --removes the head node from the list,\n or does nothing if the list is empty\n */\n void RemoveHead();\n /*\n void Clear()\n --clears the entire contents of the list,\n freeing all memory associated with all nodes\n */\n void Clear();\n /*\n unsigned int size() const\n --accessor for size_\n */\n unsigned int size() const;\n /*\n string ToString() const\n --returns a string representation of the contents\n of all nodes in the list, in the format\n NUM1, NUM2, ..., LASTNUM\n returns the empty string on an empty list (i.e. returns \"\")\n */\n string ToString();\n \n private:\n //points to the first node in a singly-linked list\n SLNode* head_;\n //stores the count of the number of nodes in the list\n unsigned int size_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.5528476238250732,
"alphanum_fraction": 0.5638788938522339,
"avg_line_length": 31.223140716552734,
"blob_id": "bc760d9756f3c8ba1460801bf1d9886f8506358c",
"content_id": "513885532fe5ae441c08d8e9f8aa0ed800f156c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3898,
"license_type": "no_license",
"max_line_length": 151,
"num_lines": 121,
"path": "/ICE/team2.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Team 2 (worse than 1) code\n */\n #include <iostream>\n #include <sstream>\n using namespace std;\n // Line 5 and we already failed\n \n int Average(int array[],int length){\n int total=0, average=0;\n for(int i=0; i<length; i++){\n total+=array[i];\n }\n average = total/length;\n return average;\n}\n/*\n * Outputs the scores in the array\n * @param int[] scores - The array to fill up\n * @param const int &size - The size of the array\n */\nvoid Output(int scores[], const int &size)\n{\n \n}\n//2.1 Reversing the order of an array(Dustin/Tyler)\nvoid Reversal (int (&input)[100])\n{\n int temp[100];\n for (int i=0;i<sizeof(input);i++ )\n {\n temp[i]=input[il\n \n }\n for (int i=sizeof(input);i>=0;i--)\n {\n input[sizeof(input)-i]=temp[i];\n }\n}\n\nbool HightoLow(int num_array[]) // 2.3 High-to-Low (Harris/Knight)\n{\n bool check_math = true; // Create a boolean variable since return would end the function\n for(int i = 0; i < num_array.size(); i++) // For loop to check the values of each slot\n { \n int first = num_array[i]; // The first variable will hold the current place of the loop (the one that comes right now).\n int next = num_array[i+1]; // The second variable will hold the second place of the loop (the one right after the current place).\n if(first < next) //test if the first array slot is less than the array slot after\n { \n bool check_math = false; //if true then the array isnt from Highest to Lowest and assigns false for the bool variable\n i = num_array.size(); // End the loop as soon as we get a false statement\n } \n } \n return check_math; // Return the boolean\n}\n\n// 2.4 Reversible Array Check (Jason/Philip)\nbool IsReversible(int[] intArray, unsigned arraySize)\n{\n bool Result = true;\n arraySize -= 1;\n unsigned i = 0;\n\n while (Result && (i < arraySize))\n {\n Result = (intArray[i] == intArray[arraySize - i]);\n i += 1;\n }\n\n return Result;\n}\n\nbool LargestSmallest (int array[])//is this supposed to be a bool function to return a string?\n{\n int largest;\n int smallest;\n //int number = array.size();\n stringstream ss;\n for (int i = 0; i < array.size() - 1; i++)//searches for largest number\n {\n if (array[i + 1] < array[i])//checks which array slot the largest\n {\n largest = array[i];//saves largest number\n }\n }\n \n for (int i = 0; i < array.size() - 1; i++)//searches for smallest number\n {\n if (array[i + 1] > array[i])//checks which array slot is the smallest\n {\n smallest = array[i];//saves smallest number\n }\n }\n \n ss << \"Largest score: \" << largest << \" Smallest score: \" << smallest;\n string str = ss.str();\n return str;\n}\n/*\n * Create a main function that uses the following array:\n * int scores[] = { 1, 2, 3, 4, 5 };\n * and uses all of the functions provided (as well as output).\n * 1. Output all values of the array\n * followed by the numbers on your sheets. Output all returned\n * answers with appropriate verbage.\n */\n\nint main(int argc, char** argv)//really good main function ;)\n{\n int scores[] = { 1, 2, 3, 4, 5 };\n int length=5;\n int ScoreAverage = Average(scores, length);\n Reversal(scores);\n bool reversible = IsReversible(scores, length);\n cout << \"Score is reversible: \" << boolalpha << reversible << endl;\n \n //Team Rocket (blast off at the speed of light, meouth thats right!)\n string largest_smallest = \"\";\n largest_smallest = LargestSmallest (scores[]);\n cout << largest_smallest;\n}"
},
{
"alpha_fraction": 0.4809989035129547,
"alphanum_fraction": 0.5157437324523926,
"avg_line_length": 19.04347801208496,
"blob_id": "d6ede85c609531db2084b3cfcc88721e132fc140",
"content_id": "10bdb9fdd3b47adbf2d954ccd4b1153fce616c01",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 921,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 46,
"path": "/test1.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <string>\n#include <cctype>\n#include <vector>\n#include <cstdlib>\nusing std::cout;\nusing std::cin;\nusing std::endl;\nusing std::string;\n\nint main() \n{\n double f, c =20;\n f=(9/5);\n cout << f << endl;\n f = f*c;\n cout << f << endl;\n f = f + 32;\n cout << f << endl;\n f= (9/5) * c + 32;\n cout << f << endl;\n double a = 1.5;\n cout << a << endl;\n a = (3/2);\n cout << a << endl;\n double b = (3.0/2.0);\n cout << b << endl;\n return 0;\n}\n\n\n/*int bintodec(string binary, unsigned int i = 0)\n{\n int tot = 0;\n if (i < binary.length())\n {\n if (binary[i] == '1')\n tot = pow(2, i);\n else if (!binary[i] == '0')\n throw \"String is not formatted in binary\";\n return tot + bintodec(binary, ++i);\n }\n return tot;\n}\nhttp://stackoverflow.com/questions/26701548/recursion-binary-to-decimal-completely-stuck#\n */"
},
{
"alpha_fraction": 0.5594550967216492,
"alphanum_fraction": 0.5606865286827087,
"avg_line_length": 25.518367767333984,
"blob_id": "3e76adad89fd3fbb9ba338bb1e6a32def58174d9",
"content_id": "9595cc1b628dbc1c1870cb00462baae74cf8c0ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 12993,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 490,
"path": "/Topic 3/Assignment 4/dl_list.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : dl_list.cpp\n * Author : David Dalton\n * Description : Node list lab.\n */\n\n#include \"dl_list.h\"\n\n/**\n * initialize count to zero, head and tail to NULL\n */\n DLList::DLList() \n {\n count_ = 0;\n head_ = NULL;\n tail_ = NULL;\n }\n/**\n * call clear function\n */\n DLList::~DLList() \n {\n clear();\n }\n/**\n * return count\n */\n unsigned int DLList::getSize() const \n {\n return count_;\n }\n/**\n * create new DLNode with newContents and attach at head\n */\n void DLList::pushFront(int newContents) \n {\n /**\n * Creates a new node with the specified contents, then inserts it at the\n * start of the list. Increases the size variable and points tail to \n * head if it was currently null\n */\n DLNode* new_node = new DLNode(newContents);\n new_node->setNext(head_);\n new_node->setPrevious(tail_);\n head_ = new_node;\n count_ = count_ + 1;\n if (tail_ == NULL)\n {\n tail_ = head_;\n }\n }\n/**\n * create new DLNode with newContents and attach at tail\n */\n void DLList::pushBack(int newContents) \n {\n /**\n * Checks if the list is empty, if so calls the InsertHead() function\n */\n if(head_ != NULL)\n {\n /**\n * Creates a new node of the specified value and a iterator node, then\n * sets the iterator node to head_\n */\n DLNode* temp_node, *newNode = new DLNode(newContents);\n temp_node = head_;\n /**\n * Loops through the list to check if the next node is null, if not it\n * iterates to the next node\n */\n while(temp_node->getNext() != NULL)\n {\n temp_node = temp_node->getNext();\n }\n /**\n * Inserts the node at the end of the list, points the tail to it and\n * increases the size variable by 1\n */\n temp_node->setNext(newNode);\n //head_->setPrevious(newNode);\n tail_ = newNode;\n count_ = count_ + 1;\n } else \n {\n pushFront(newContents);\n }\n }\n/**\n * create new DLNode with newContents and insert in ascending (based on \n * newContents) order\n */\n void DLList::insert(int newContents) \n {\n /**\n * Checks to see if head_ is null or if the contents of head_ are greater\n * then the parameter being inserted. If it is then calls the \n * pushFront() function, otherwise continues to next check\n */\n if(head_ == NULL || head_->getContents() > newContents)\n {\n pushFront(newContents);\n /**\n * Checks if the contents of tail_ are less then the parameter being\n * inserted. If so, calls pushBack() function, otherwise continues\n * to next check\n */\n } else if (tail_->getContents() < newContents)\n {\n pushBack(newContents);\n /**\n * Inserts the parameter into the correct location in the list\n */\n } else \n {\n DLNode* iterator;\n iterator = head_;\n /**\n * Checks whether the contents of the next node is less then the parameter\n * and that the next node is not the tail. If they are not, then it \n * advances the iterator to the next node in the list\n */\n while(newContents > iterator->getNext()->getContents() && iterator->getNext() != tail_)\n {\n iterator = iterator->getNext();\n }\n /**\n * Checks if the iterator is located at the tail\n */\n if(iterator != tail_)\n {\n /**\n * If the iterator is not located at the tail, it creates a new node\n * and inserts it at the iterators current location, then increases\n * the size variable by 1\n */\n DLNode* new_node = new DLNode(newContents);\n new_node->setNext(iterator->getNext());\n //new_node->setPrevious(iterator);\n iterator->setNext(new_node);\n count_ = count_ + 1;\n } else\n {\n /**\n * If the iterator is located at the tail, then calls the InsertTail()\n * function\n */\n pushBack(newContents);\n }\n }\n }\n/**\n * return the value of the contents of the head node; throw an exception \n * (throw \"LIST EMPTY\") if the list is empty\n */\n int DLList::getFront() const \n {\n if(count_ != 0)\n {\n return head_->getContents();\n }\n throw \"LIST EMPTY\";\n }\n/**\n * return the value of the contents of the tail node; throw an exception \n * (throw \"LIST EMPTY\") if the list is empty\n */\n int DLList::getBack() const \n {\n if(count_ != 0)\n {\n return tail_->getContents();\n }\n throw \"LIST EMPTY\";\n }\n/**\n * return true if target is in list, else return false\n */\n bool DLList::get(int target) const \n {\n /**\n * Checks if the head is null and returns false if it is\n */\n if(head_ == NULL)\n {\n return false;\n /**\n * Checks if the contents of head_ are equal to the parameter and returns true if it is\n */\n } else if(head_->getContents() == target)\n {\n return true;\n /**\n * Checks if the contents of tail_ are equal to the parameter and returns true if it is\n */\n } else if(tail_->getContents() == target)\n {\n return true;\n /**\n * checks if the list contains only two nodes, if it does not then\n * it checks for the specified parameter, otherwise it returns false\n */\n } else if(head_->getNext() != tail_)\n {\n DLNode* iterator = head_->getNext();\n /**\n * Loops through the node list checking the contents of the current\n * node to the parameter and if the next node is the tail, if neither\n * statement is true then it iterates to the next node\n */\n while(iterator->getContents() != target && iterator->getNext() != tail_)\n {\n iterator = iterator->getNext();\n }\n /**\n * Checks if the contents of the current node are equal to the parameter\n * and returns true, if not then returns false\n */\n if(iterator->getContents() == target)\n {\n return true;\n } else\n {\n return false;\n }\n } else\n {\n return false;\n }\n }\n/**\n * remove current head node; do nothing if list is empty\n */\n void DLList::popFront() \n {\n /**\n * Checks if the list is empty\n */\n if(head_ != NULL)\n {\n /**\n * Checks if head_ is equal to tail_ and sets tail_ to null if it is\n */\n if(head_ == tail_)\n {\n tail_ = NULL;\n }\n /**\n * Creates a temporary node and points it to head, then points head to \n * the next node\n */\n DLNode* temp_node = head_;\n head_ = head_->getNext();\n // head_->setPrevious(tail_);\n // Delets the temporary node and sets it to null, then decreases size by 1\n delete temp_node;\n temp_node = NULL;\n count_ = count_ - 1;\n }\n }\n/**\n * remove current tail node; do nothing if list is empty\n */\n void DLList::popBack() \n {\n /**\n\t * Checks if list is empty\n\t */\n\t if(head_ != NULL)\n {\n /**\n * Checks if head_ is equal to tail_ and calls the RemoveHead() function\n * if it is\n */\n if(head_ != tail_)\n {\n /**\n * Creates a temporary node and points it to head\n */\n DLNode* temp_node = head_;\n /**\n * Loops through the list and checks if the next node is the tail,\n * if it is not then it iterates to the next node\n */\n while(temp_node->getNext() != tail_)\n {\n temp_node = temp_node->getNext();\n }\n /**\n * Sets the last node in the list to null and deletes the tail,\n * then sets tail equal to the temp node and decreases the size \n * variable\n */\n temp_node->setNext(NULL);\n delete tail_;\n tail_ = temp_node;\n count_ = count_ - 1;\n } else \n {\n popFront();\n }\n }\n }\n/**\n * remove the first instance of a DLNode containing target; do nothing if \n * target is not found\n */\n bool DLList::removeFirst(int target) \n {\n /**\n * Checks if the head is null and returns false if it is\n */\n if(head_ == NULL)\n {\n return false;\n /**\n * Checks if the contents of head_ are equal to the parameter, then\n * calls the popBack() function and returns true if it is\n */\n } else if(head_->getContents() == target)\n {\n popBack();\n return true;\n /**\n * Checks if the contents of tail_ are equal to the parameter, then\n * calls the popBack() function and returns true if it is\n */\n } else if(tail_->getContents() == target)\n {\n popBack();\n return true;\n /**\n * checks if the list contains only two nodes, if it does not then\n * it checks for the specified parameter, otherwise it returns false\n */\n } else if(head_->getNext() != tail_)\n {\n DLNode* iterator = head_->getNext();\n DLNode* temp_node = head_;\n /**\n * Loops through the node list checking the contents of the current\n * node to the parameter and if the next node is the tail, if neither\n * statement is true then it iterates to the next node\n */\n while(iterator->getContents() != target && iterator->getNext() != tail_)\n {\n temp_node = iterator;\n iterator = iterator->getNext();\n }\n /**\n * Checks if the contents of the current node are equal to the parameter,\n * if not then returns false\n */\n if(iterator->getContents() == target)\n {\n /**\n * Sets the placeholder node to the node that the iterator is pointing\n * to then deletes the iterator node, reduces the size variable\n * then returns true\n */\n temp_node->setNext(iterator->getNext());\n delete iterator;\n iterator = NULL;\n count_ = count_ - 1;\n return true;\n } else\n {\n return false;\n }\n } else\n {\n return false;\n }\n }\n/**\n * remove all instances of DLNode containing target; do nothing if target \n * is not found\n */\n bool DLList::removeAll(int target) \n {\n /**\n * Checks if the head is null and returns false if it is\n */\n if(head_ == NULL)\n {\n return false;\n /**\n * Checks if the contents of head_ are equal to the parameter, then\n * calls the popBack() function and returns true if it is\n */\n } else if(head_->getContents() == target)\n {\n popBack();\n /**\n * Checks if the contents of tail_ are equal to the parameter, then\n * calls the popBack() function and returns true if it is\n */\n } else if(tail_->getContents() == target)\n {\n popBack();\n /**\n * checks if the list contains only two nodes, if it does not then\n * it checks for the specified parameter, otherwise it returns false\n */\n } else if(head_->getNext() != tail_)\n {\n DLNode* iterator = head_->getNext();\n DLNode* temp_node = head_;\n /**\n * Loops through the node list checking the contents of the current\n * node to the parameter and if the next node is the tail, if neither\n * statement is true then it iterates to the next node\n */\n while(iterator->getContents() != target && iterator->getNext() != tail_)\n {\n temp_node = iterator;\n iterator = iterator->getNext();\n }\n /**\n * Checks if the contents of the current node are equal to the parameter,\n * if not then returns false\n */\n if(iterator->getContents() == target)\n {\n /**\n * Sets the placeholder node to the node that the iterator is pointing\n * to then deletes the iterator node, reduces the size variable\n * then returns true\n */\n temp_node->setNext(iterator->getNext());\n delete iterator;\n iterator = NULL;\n count_ = count_ - 1;\n } else\n {\n return false;\n }\n } else\n {\n return false;\n }\n return true;\n }\n/**\n * clear all nodes from list, reset count to zero, set head and tail to NULL\n */\n void DLList::clear() \n {\n while(head_ != NULL)\n {\n popFront();\n }\n delete head_;\n head_ = NULL;\n tail_ = NULL;\n }\n/**\n * display the contents of each node in the list, formatted per the \n * program specification (\"NUM1,NUM2,NUM3,...,NUMX\"), to the output stream \n * out\n */\n ostream& operator <<(ostream &out, const DLList &src) \n {\n /**\n * Checks if the node list is empty and returns an empty string if it is\n */\n DLNode* temp_node = src.head_;\n if(temp_node != NULL)\n {\n /**\n * Using a while loop, checks every node if it is null, if it is not\n * then it adds its contents to a stringstream and then checks if the\n * next node is null, if not adds a separator string\n */\n while(temp_node != NULL)\n {\n out << temp_node->getContents();\n if(temp_node->getNext() != NULL)\n {\n out << \", \";\n }\n temp_node = temp_node->getNext();\n }\n //return out;\n } else {\n out << \"\";\n }\n // Returns the stringstream\n return out;\n }"
},
{
"alpha_fraction": 0.5137614607810974,
"alphanum_fraction": 0.5668414235115051,
"avg_line_length": 21.2281551361084,
"blob_id": "5649d2f0fc9c46754ae86abfbc0829ff9d046807",
"content_id": "4b9ff076b632956a1ece47c4eddac58230ff6314",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4578,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 206,
"path": "/Topic 1/Assignment 1/assignment_1_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_3_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #3 Functionality\n * Sources :\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"assignment_1.h\"\n\nTEST_CASE(\"CountWords(\\\"\\\")\") {\n SECTION(\"CountWords(\\\"\\\")\") {\n CHECK(CountWords(\"\") == 0);\n }\n\n SECTION(\"CountWords(\\\"hello\\\")\") {\n CHECK(CountWords(\"hello\") == 1);\n }\n \n SECTION(\"CountWords(\\\"hello,world\\\")\") {\n CHECK(CountWords(\"hello,world\") == 1);\n }\n \n SECTION(\"CountWords(\\\"hello world\\\")\") {\n CHECK(CountWords(\"hello world\") == 2);\n }\n \n SECTION(\"CountWords(\\\"hello, world\\\")\") {\n CHECK(CountWords(\"hello, world\") == 2);\n }\n\n SECTION(\"CountWords(\\\"testing a large large sentence\\\")\") {\n CHECK(CountWords(\"testing a large large sentence\") == 5);\n }\n}\n\nTEST_CASE(\"CheckAlphabetic(\\\"\\\")\"){\n SECTION(\"CheckAlphabetic(\\\"\\\")\"){\n CHECK(CheckAlphabetic(\"\") == 0);\n }\n SECTION(\"CheckAlphabetic(\\\"ABC123\\\")\"){\n CHECK(CheckAlphabetic(\"ABC123\") == 0);\n }\n SECTION(\"CheckAlphabetic(\\\"ABC\\\")\"){\n CHECK(CheckAlphabetic(\"ABC\") == 1);\n }\n SECTION(\"CheckAlphabetic(\\\"ABCxyz\\\")\"){\n CHECK(CheckAlphabetic(\"ABCxyz\") == 1);\n }\n SECTION(\"CheckAlphabetic(\\\"ABC\\t\\\")\"){\n CHECK(CheckAlphabetic(\"ABC\\t\") == 0);\n }\n}\n\nTEST_CASE(\"EncryptString(\\\"\\\", 5)\"){\n string s = \"\";\n SECTION(\"EncryptString(s, 5)\"){\n CHECK(EncryptString(s,5) == 0);\n CHECK(s == \"\");\n }\n \n s = \"Hello World\";\n SECTION(\"EncryptString(s, 5)\"){\n CHECK(EncryptString(s, 5) == 0);\n }\n}\nTEST_CASE(\"EncryptString(\\\"HelloWorld\\\", 5)\"){\n string s = \"HelloWorld\";\n SECTION(\"EncryptString(s,5)\"){\n CHECK(EncryptString(s, 5) == 1);\n CHECK(s == \"MjqqtBtwqi\");\n }\n SECTION(\"EncryptString(s, 25)\"){\n CHECK(EncryptString(s, 25) == 1);\n CHECK(s == \"GdkknVnqkc\");\n }\n SECTION(\"EncryptString(s, 1000000)\"){\n CHECK(EncryptString(s, 1000000) == 1);\n CHECK(s == \"VszzcKcfzr\");\n }\n SECTION(\"EncryptString(s, -1000000)\"){\n CHECK(EncryptString(s, -1000000) == 1);\n CHECK(s == \"TqxxaIadxp\");\n }\n}\n\nTEST_CASE(\"DecryptString(\\\"\\\", 5)\"){\n string s = \"\";\n SECTION(\"EncryptString(s, 5)\"){\n CHECK(EncryptString(s,5) == 0);\n CHECK(s == \"\");\n }\n \n s = \"Hello World\";\n SECTION(\"DecryptString(s, 5)\"){\n CHECK(EncryptString(s, 5) == 0);\n }\n}\nTEST_CASE(\"DecryptString(\\\"HelloWorld\\\", 5)\"){\n string s = \"MjqqtBtwqi\";\n SECTION(\"DecryptString(s,5)\"){\n CHECK(DecryptString(s, 5) == 1);\n CHECK(s == \"HelloWorld\");\n }\n s = \"GdkknVnqkc\";\n SECTION(\"DecryptString(s, 25)\"){\n CHECK(DecryptString(s, 25) == 1);\n CHECK(s == \"HelloWorld\");\n }\n s = \"VszzcKcfzr\";\n SECTION(\"DecryptString(s, 1000000)\"){\n CHECK(DecryptString(s, 1000000) == 1);\n CHECK(s == \"HelloWorld\");\n }\n s = \"TqxxaIadxp\";\n SECTION(\"DecryptString(s, -1000000)\"){\n CHECK(DecryptString(s, -1000000) == 1);\n CHECK(s == \"HelloWorld\");\n }\n}\n\nTEST_CASE(\"ComputeAverage({0}, 0)\"){\n double values[] = {10.5, 20.3, 30.2, 12.5};\n \n SECTION(\"ComputeAverage(values, 4\"){\n CHECK(ComputeAverage(values, 4) == 18.375);\n }\n \n for(int i = 0; i<4; i++)\n {\n values[i] = 0;\n }\n SECTION(\"ComputeAverage(values, 4)\"){\n CHECK(ComputeAverage(values, 4) == 0);\n }\n \n values[0] = 5;\n values[1] = 7;\n values[2] = 11;\n values[3] = 7;\n SECTION(\"ComputeAverage(values, 4)\"){\n CHECK(ComputeAverage(values, 4) == 7.5);\n }\n \n values[0] = -10.5;\n values[1] = -20.3;\n values[2] = -30.2;\n values[3] = -12.5;\n SECTION(\"ComputeAverage(values, 4\"){\n CHECK(ComputeAverage(values, 4) == -18.375);\n }\n}\n\nTEST_CASE(\"FindMinValue(values, 3)\"){\n double values[] = {-1.1, 0, 1.1};\n SECTION(\"FindMinValue(values, 3)\"){\n CHECK(FindMinValue(values, 3) == -1.1);\n }\n \n for(int i = 0; i<3; i++)\n {\n values[i] = 0;\n }\n \n SECTION(\"FindMinValue(values, 3\"){\n CHECK(FindMinValue(values, 3) == 0);\n }\n \n values[0] = -3.1;\n values[1] = -3.2;\n values[2] = -3.3;\n SECTION(\"FindMinValue(values, 3\"){\n CHECK(FindMinValue(values, 3) == -3.3);\n }\n \n values[0] = 0;\n values[1] = 1;\n values[2] = 2.2;\n SECTION(\"FindMinValue(values, 3)\"){\n CHECK(FindMinValue(values,3) == 0);\n }\n}\n\nTEST_CASE(\"FindMaxValue({0}, 0)\"){\n double values[] = {1.1, 0, -1.1};\n \n SECTION(\"FindMaxValue(values, 3)\"){\n CHECK(FindMaxValue(values, 3) == 1.1);\n }\n \n for(int i = 0; i<3; i++)\n {\n values[i] = 0;\n }\n SECTION(\"FindMaxValue(values, 3)\"){\n CHECK(FindMaxValue(values, 3) == 0);\n }\n \n values[0] = 0;\n values[1] = 1.1;\n values[2] = 2.2;\n SECTION(\"FindMaxValue(values, 3)\"){\n CHECK (FindMaxValue(values, 3) == 2.2);\n }\n}"
},
{
"alpha_fraction": 0.4592592716217041,
"alphanum_fraction": 0.6740740537643433,
"avg_line_length": 16.133333206176758,
"blob_id": "35765077dc37484b3da02f2d2f5a1473f79dabb0",
"content_id": "92fff3668e0330ffbf41dd1a1c136250b4ff3654",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 270,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 15,
"path": "/CSCI465v5old/requirements.txt",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "certifi==2017.7.27.1\r\nchardet==3.0.4\r\nDjango==1.11.5\r\ngunicorn==19.7.1\r\nidna==2.6\r\noauthlib==2.0.4\r\nolefile==0.44\r\nPillow==4.3.0\r\npsycopg2==2.7.3.2\r\npytz==2017.2\r\nrequests==2.18.4\r\nrequests-oauthlib==0.8.0\r\nurllib3==1.22\r\nvirtualenv==15.1.0\r\nvirtualenvwrapper-win==1.2.1"
},
{
"alpha_fraction": 0.5280373692512512,
"alphanum_fraction": 0.577102780342102,
"avg_line_length": 20.526315689086914,
"blob_id": "121b00a5fc69ce55cfd40468f8460ddb1dca8e71",
"content_id": "213905a57e13667215de72750615b8cf0c6a6a0f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 428,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 19,
"path": "/CSCI465v5old/firstapp/migrations/0007_remove_suggestion_choice_field.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.5 on 2017-12-04 08:46\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('firstapp', '0006_suggestion_choice_field'),\r\n ]\r\n\r\n operations = [\r\n migrations.RemoveField(\r\n model_name='suggestion',\r\n name='choice_field',\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.5952631831169128,
"alphanum_fraction": 0.6021052598953247,
"avg_line_length": 25.041095733642578,
"blob_id": "0fa59c93f2fc5a4cc691e961d84708c0fdee8d1d",
"content_id": "7a0b638b494e7e5a3c4b60a62405afc7c291257e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1900,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 73,
"path": "/Topic 2/Assignment 2/checking_account.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : checking_account.h\n * Author : David Dalton\n * Description : Checking Account class header file\n */\n \n#ifndef CHECK_H\n#define CHECK_H\n\n#include \"bank_account.h\"\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::ostream;\nusing std::setfill;\nusing std::setw;\nusing std::setprecision;\nusing std::fixed;\n\nclass CheckingAccount : public BankAccount\n{\n public:\n /*\n * Constructor\n *uses default values if none given\n */\n CheckingAccount(string account_name = \"account\", long dollars = 0, \n int cents = 0, string last_transaction = \"none\", \n string amount_kept = \"$0.0\");\n /*\n * Destructor \n *unused\n */\n virtual ~CheckingAccount();\n /*\n * Mutator\n *sets the values of ammount kept to the input long and int\n */\n void SetAmountKept(long kept_dollars = 0, int kept_cents = 0);\n /*\n * Mutator\n *deducts the input long and int from the current value of dollars_ and\n *cents_, then stores the deducted values and the inputed check_number\n *into the transaction record variable\n */\n void WriteCheck(int check_number = 0, long check_dollars = 0, \n int check_cents = 0);\n /*\n * Mutator\n *adds the specified deposit amounts to the values of dollars_ and cents_\n *and then adds the values to the transaction record variable\n */\n void CashCheck(long check_dollars = 0, int check_cents = 0, \n long check_dollars_deposited = 0,\n int check_cents_deposited = 0);\n /*\n * Accessor\n *gets the value of ammount_kept and returns it\n */\n string GetAmountedKept();\n \n private:\n string amount_kept_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6942148804664612,
"alphanum_fraction": 0.6983470916748047,
"avg_line_length": 19.20833396911621,
"blob_id": "a9923edd0e491bc40ba746e41896413556d2b58c",
"content_id": "eeb38b57d9afea7e3f7893b85c3d811332571ff3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 484,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 24,
"path": "/Topic 1/lab 3/lab_3.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_3.cpp\n * Author : Luke Sathrum\n * Description : Header File for Lab #3. Do NOT Alter this file.\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <cctype>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n// Function Prototypes (DO NOT ALTER)\nstring Goldilocks(string item, int number);\nint RockScissorPaper(char player_one, char player_two);\nstring ToLower(string input);\nstring ToUpper(string input);\n\n#endif"
},
{
"alpha_fraction": 0.5699028968811035,
"alphanum_fraction": 0.5708737969398499,
"avg_line_length": 12.74666690826416,
"blob_id": "069a1bdf27ac5fe2b1e99bcd8eb461f064a132c0",
"content_id": "db33a162860d1c9697abcf3faaaf2c811c60dc96",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1030,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 75,
"path": "/Topic 3/Assignment 4/dl_node.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : sl_node.cpp\n * Author : David Dalton\n * Description : Node list lab.\n */\n\n#include \"dl_node.h\"\n\n/**\n * initialize contents to zero, next and previous to NULL\n */\n DLNode::DLNode() \n {\n contents_ = 0;\n previous_node_ = NULL;\n next_node_ = NULL;\n }\n/**\n * initialize contents to newContents, next and previous to NULL\n */\n DLNode::DLNode(int newContents) \n {\n contents_ = newContents;\n previous_node_ = NULL;\n next_node_ = NULL;\n }\n/**\n * nothing to be done\n */\n DLNode::~DLNode() \n {\n\n }\n/**\n * \n */\n void DLNode::setContents(int newContents) \n {\n contents_ = newContents;\n }\n/**\n * \n */\n void DLNode::setNext(DLNode* newNext) \n {\n next_node_ = newNext;\n }\n/**\n * \n */\n void DLNode::setPrevious(DLNode* newPrevious) \n {\n previous_node_ = newPrevious;\n }\n/**\n * \n */\n int DLNode::getContents() const \n {\n return contents_;\n }\n/**\n * \n */\n DLNode* DLNode::getNext() const \n {\n return next_node_;\n }\n/**\n * \n */\n DLNode* DLNode::getPrevious() const \n {\n return previous_node_;\n }"
},
{
"alpha_fraction": 0.7390577793121338,
"alphanum_fraction": 0.7407283782958984,
"avg_line_length": 41.154930114746094,
"blob_id": "e9a8b8039ffa1d7845bde38546131ee45707765f",
"content_id": "94459fa994c9e6e5217ad87beed8a4e525eb2a50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2993,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 71,
"path": "/Topic 4/Lab 2/lab_22.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_22.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #22. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n\n/*\n * Compute and return the factorial of a value, using a recursive algorithm. Zero factorial\n * will return 1.\n * @param value an unsigned integer containing the value for which the factorial will be computed\n * @return an unsigned integer containing the computed factorial of the value\n */\nunsigned int Factorial(unsigned int value);\n\n/*\n * Return a specified value in a Fibonacci sequence. The lowest value requested in the sequence\n * must never be less than one.\n * @param fibValue an unsigned integer specifying which value in the Fibonacci sequence to return\n * @return an unsigned integer containing the requested value in the Fibonacci sequence\n */\nunsigned int Fibonacci(unsigned int fib_value);\n\n/*\n * Test a single word to see if it is a palindrome. The word must be all in the same case\n * (upper or lower) and cannot contain spaces, digits, or punctuation.\n * @param word a string containing the word to be tested\n * @return true of word is a palindrome, else false; empty string and single character strings\n * are considered palindromes\n */\nbool WordIsPalindrome(string word);\n\n/*\n * Produce a string containing the contents of an array, separated by single spaces,\n * starting at a specified index and going forward to the end of the array. The returned\n * string will contain an extra space character after the last value added.\n * @param array an integer array containing the values to be added to the string\n * @param start an unsigned integer containing the index of the first value in the array to be added\n * to the output string\n * @param size an unsigned integer containing the number of elements in the array\n * @return a string containing the contents of the array, separated by spaces; returns empty string\n * if the startIndex is >= the size of the array\n */\nstring ArrayForwardsAsString(int array[], unsigned int start,\n unsigned int size);\n\n/*\n * Produce a string containing the contents of an array, separated by single spaces,\n * starting at a specified index and going backward to the beginning of the array. The returned\n * string will contain an extra space character after the last value added.\n * @param array an integer array containing the values to be added to the string\n * @param start an integer containing the index of the first value in the array to be added\n * to the output string\n * @param size an unsigned integer containing the number of elements in the array\n * @return a string containing the contents of the array, separated by spaces, in reverse order; returns empty string\n * if the startIndex is < zero\n */\nstring ArrayBackwardsAsString(int array[], int start, unsigned int size);\n\n#endif\n"
},
{
"alpha_fraction": 0.7100694179534912,
"alphanum_fraction": 0.7135416865348816,
"avg_line_length": 19.571428298950195,
"blob_id": "62cb20e099638c4fd758e3ecefe32547ac53661d",
"content_id": "a9bba86135bf2991d3ffe0ca0146681b9ced4a12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 576,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 28,
"path": "/Topic 1/lab 4/lab_4.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_4.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #4. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <sstream>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\nusing std::ios_base;\n\n// Function Prototypes (DO NOT ALTER)\nstring MakeString(string label, double value, char separator);\nchar StringToChar(string value);\nint StringToInt(string value);\ndouble StringToDouble(string value);\nbool StringToBool(string value);\n\n#endif\n"
},
{
"alpha_fraction": 0.6349129676818848,
"alphanum_fraction": 0.6441006064414978,
"avg_line_length": 21.010639190673828,
"blob_id": "cce49b67a4c6eae690083d91f79fbd510259ff94",
"content_id": "25d809e4da5aff8c3b1eb69b0e2d85c93416d9ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2068,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 94,
"path": "/Topic 2/lab 4/food_item.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : food_item.h\n * Author : David Dalton\n * Description : Derived Class Header File\n */\n\n#ifndef FOOD_H\n#define FOOD_H\n\n#include \"item.h\"\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <cstdlib>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::string;\nusing std::stringstream;\nusing std::setprecision;\nusing std::fixed;\nusing std::setfill;\nusing std::setw;\n\n/*\n * Class Item.\n */\nclass FoodItem : public Item {\n public:\n /*\n * Constructor\n *takes five parameters, one for each private member variable and two for the \n *base class\n *defaults name_ to \"fooditem\"\n *defaults value_ to 0\n *defaults calories_ to 0\n *defaults unit_of_measure_ to \"nounits\"\n *defaults units_ to 0\n */\n FoodItem(string name = \"fooditem\", unsigned int value = 0, \n unsigned int calories = 0, string unit_of_measure = \"nounits\", \n double units = 0);\n /*\n *Destructor\n */\n virtual ~FoodItem();\n /*\n * Accessors #1\n *sets the value of calories_ to the input int\n */\n void set_calories(unsigned int calories);\n /*\n * Mutator #2\n *sets the value of units_of_measure_ to the input string\n */\n void set_unit_of_measure(string units_of_measure);\n /*\n * Mutator #3\n *sets the value of units_ to the input double\n */\n void set_units(double units);\n /*\n * Acessor #1\n *retrieves the value of calories_\n */\n unsigned int calories();\n /*\n * Acessor #2\n *retrieves the value of units_of_measure_\n */\n string unit_of_measure();\n /*\n * Acessor #3\n *retrieves the value of units_\n */\n double units();\n /*\n *string ToString()\n *returns a string containing name_, value_, units_, unit_of_measure_,\n *and calories_\n *(uses Item::ToString in its implementation)\n *units_ formatted to exactly two decimal places\n *Format -- name_, $value_, units_ unit_of_measure_, calories_\n *calories\n *EXAMPLE -- cookie, $1, 2.50 cookie(s), 250 calories\n */\n string ToString();\n private:\n unsigned int calories_;\n string unit_of_measure_;\n double units_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.5559268593788147,
"alphanum_fraction": 0.5991743803024292,
"avg_line_length": 24.059112548828125,
"blob_id": "20a100d78223e051b9f7ca199772e45e1f643320",
"content_id": "060286c9f1fc9765e43537b5190645258c28939e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5087,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 203,
"path": "/Topic 4/Lab 4/lab_24_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_24_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #24 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include \"bs_tree.h\"\n// To test for correct header guards\n#include \"bst_node.h\"\n#include \"bst_node.h\"\n#include \"bs_tree.h\"\n\nTEST_CASE(\"Default Constructor for BSTNode\") {\n const BSTNode const_node;\n BSTNode node;\n BSTNode* p_node = &node;\n SECTION(\"Contents const Accessor\") {\n CHECK(const_node.contents() == 0);\n }\n\n SECTION(\"Contents Accessor (Editable)\") {\n node.contents() = 10;\n CHECK(node.contents() == 10);\n }\n\n SECTION(\"Left Child const Accessor\") {\n CHECK(const_node.left_child() == NULL);\n }\n\n SECTION(\"Left Child Accessor (Editable)\") {\n node.left_child() = &node;\n CHECK(node.left_child() == p_node);\n }\n\n SECTION(\"Right Child const Accessor\") {\n CHECK(const_node.right_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor (Editable\") {\n node.right_child() = &node;\n CHECK(node.right_child() == p_node);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor for BSTNode\") {\n BSTNode node(99);\n SECTION(\"Contents Accessor\") {\n CHECK(node.contents() == 99);\n }\n\n SECTION(\"Left Child Accessor\") {\n CHECK(node.left_child() == NULL);\n }\n\n SECTION(\"Right Child Accessor\") {\n CHECK(node.right_child() == NULL);\n }\n}\n\n\nTEST_CASE(\"Testing Pointers for BSTNode\") {\n BSTNode node1;\n BSTNode node2(99);\n BSTNode node3(-1);\n // node 2 is leftChild, node 3 is rightChild\n node1.set_left_child(&node2);\n node1.set_right_child(&node3);\n SECTION(\"Left Child Mutator\") {\n CHECK(node1.left_child() == &node2);\n }\n\n SECTION(\"Right Child Mutator\") {\n CHECK(node1.right_child() == &node3);\n }\n\n // Change the contents of left child via root\n node1.left_child()->set_contents(10);\n\n SECTION(\"Contents Mutator\") {\n CHECK(node2.contents() == 10);\n }\n}\n\nTEST_CASE(\"Default Constructor for BSTree\") {\n BSTree tree;\n SECTION(\"Size Accessor\") {\n CHECK(tree.size() == 0);\n }\n\n SECTION(\"InOrder() on an Empty Tree\") {\n CHECK(tree.InOrder() == \"\");\n }\n\n SECTION(\"Clear() on an Empty Tree\") {\n tree.Clear();\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n }\n}\n\nTEST_CASE(\"Building a Tree\") {\n BSTree tree;\n bool return_bool = false;\n return_bool = tree.Insert(50);\n SECTION(\"Insert(50) (the root)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 1);\n CHECK(tree.InOrder() == \"50 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(20);\n SECTION(\"Insert(20) (the left child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 2);\n CHECK(tree.InOrder() == \"20 50 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(80);\n SECTION(\"Insert(80) (the right child)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 3);\n CHECK(tree.InOrder() == \"20 50 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(30);\n SECTION(\"Insert(30) (the right child of node 20)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 4);\n CHECK(tree.InOrder() == \"20 30 50 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(70);\n SECTION(\"Insert(70) (the left child of node 80)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 5);\n CHECK(tree.InOrder() == \"20 30 50 70 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(0);\n SECTION(\"Insert(0) (the left child of node 10)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 6);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 \");\n }\n\n return_bool = false;\n return_bool = tree.Insert(100);\n SECTION(\"Insert(100) (the right child of node 80)\") {\n CHECK(return_bool == true);\n CHECK(tree.size() == 7);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 100 \");\n }\n\n SECTION(\"Inserting Duplicate Values\") {\n CHECK(tree.Insert(50) == false);\n CHECK(tree.Insert(20) == false);\n CHECK(tree.Insert(80) == false);\n CHECK(tree.Insert(30) == false);\n CHECK(tree.Insert(70) == false);\n CHECK(tree.Insert(0) == false);\n CHECK(tree.Insert(100) == false);\n CHECK(tree.size() == 7);\n CHECK(tree.InOrder() == \"0 20 30 50 70 80 100 \");\n }\n\n tree.Clear();\n SECTION(\"Clear()\") {\n CHECK(tree.size() == 0);\n CHECK(tree.InOrder() == \"\");\n }\n\n SECTION(\"Insert() Stress Test\") {\n CHECK(tree.Insert(50) == true);\n CHECK(tree.Insert(50) == false);\n CHECK(tree.Insert(25) == true);\n CHECK(tree.Insert(25) == false);\n CHECK(tree.Insert(75) == true);\n CHECK(tree.Insert(75) == false);\n CHECK(tree.Insert(30) == true);\n CHECK(tree.Insert(30) == false);\n CHECK(tree.Insert(29) == true);\n CHECK(tree.Insert(29) == false);\n CHECK(tree.Insert(31) == true);\n CHECK(tree.Insert(31) == false);\n CHECK(tree.Insert(32) == true);\n CHECK(tree.Insert(32) == false);\n CHECK(tree.Insert(33) == true);\n CHECK(tree.Insert(33) == false);\n CHECK(tree.Insert(34) == true);\n CHECK(tree.Insert(34) == false);\n CHECK(tree.size() == 9);\n CHECK(tree.InOrder() == \"25 29 30 31 32 33 34 50 75 \");\n }\n}\n"
},
{
"alpha_fraction": 0.6704761981964111,
"alphanum_fraction": 0.691428542137146,
"avg_line_length": 25.25,
"blob_id": "df0a1f4bb49c6f5ba3a9bd974c040249c42383c2",
"content_id": "28553744d5a36c2b70c06129d965bcab67a91841",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 525,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 20,
"path": "/Topic 3/Lab 3/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nsl_nodetest: lab_18_unit_test.o sl_list.o sl_node.o\n\tg++ -Wall -g -o lab2test sl_node.o sl_list.o lab_18_unit_test.o\n\n#creates the node object file\t\nsl_node.o: sl_node.cpp sl_node.h\n\tg++ -Wall -g -c sl_node.cpp\n\t\n#creates the list object file\nsl_list.o: sl_list.cpp sl_list.h\n\tg++ -Wall -g -c sl_list.cpp\n\n#creates the lab unit test object file\nlab_18_unit_test.o: lab_18_unit_test.cpp\n\tg++ -Wall -g -c lab_18_unit_test.cpp\n\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.5249110460281372,
"alphanum_fraction": 0.5762582421302795,
"avg_line_length": 24.380645751953125,
"blob_id": "8e410430fa24db86cd9b46525d7f55be0e28ab5a",
"content_id": "b2d9ba6d0fc28a6dd794025af3d2ada1e6a5fce4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7868,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 310,
"path": "/Topic 3/Lab 5/lab_20_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_20_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #20 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n// For NULL\n#include <cstddef>\n#include <sstream>\n\n#include \"sl_list.h\"\n// To test for Header guards\n#include \"sl_list.h\"\n#include \"sl_node.h\"\n#include \"sl_node.h\"\n\nTEST_CASE(\"Default Constructor for SLNode\") {\n SLNode node, node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 0);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Overloaded Constructor for SLNode\") {\n SLNode node(1), node2;\n SLNode* p_node2 = &node2;\n SECTION(\"Accessor for Contents\") {\n CHECK(node.contents() == 1);\n }\n\n SECTION(\"Accessor for Next Node\") {\n CHECK(node.next_node() == NULL);\n }\n\n SECTION(\"Mutator for Contents\") {\n node.set_contents(100);\n CHECK(node.contents() == 100);\n }\n\n SECTION(\"Mutator for Next Node\") {\n node.set_next_node(&node2);\n CHECK(node.next_node() == p_node2);\n }\n}\n\nTEST_CASE(\"Testing Pointers for SLNode\") {\n SLNode* node = new SLNode(1);\n SLNode* node2 = new SLNode();\n node->set_next_node(node2);\n node2->set_next_node(node);\n // node and node2 now connect each to the other -- not something you should\n // ever do outside of a testing situation\n SECTION(\"Node 1 Points to Node 2\") {\n CHECK(node->next_node() == node2);\n }\n\n SECTION(\"Node 2 Points to Node 1\") {\n CHECK(node2->next_node() == node);\n }\n\n SECTION(\"Node 1 Points to NULL\") {\n node->set_next_node(NULL);\n CHECK(node->next_node() == NULL);\n }\n\n SECTION(\"Node 2 Points to NULL\") {\n node2->set_next_node(NULL);\n CHECK(node2->next_node() == NULL);\n }\n}\n\n\nTEST_CASE(\"Default Constructor for SLList\") {\n SLList list;\n SECTION(\"Accessor for Size\") {\n CHECK(list.size() == 0);\n }\n\n SECTION(\"ToString()\") {\n CHECK(list.ToString() == \"\");\n }\n\n SECTION(\"GetHead()\") {\n CHECK(list.GetHead() == 0);\n }\n\n SECTION(\"GetTail()\") {\n CHECK(list.GetTail() == 0);\n }\n\n SECTION(\"RemoveFirstOccurence(0) on an Empty List\") {\n list.RemoveFirstOccurence(0);\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n}\n\nTEST_CASE(\"Building your Linked List\") {\n SLList list;\n list.Insert(10);\n SECTION(\"Insert(10) (As the first Node)\") {\n CHECK(list.size() == 1);\n CHECK(list.ToString() == \"10\");\n CHECK(list.GetHead() == 10);\n CHECK(list.GetTail() == 10);\n }\n\n list.Insert(50);\n SECTION(\"Insert(50) (As the last Node)\") {\n CHECK(list.size() == 2);\n CHECK(list.ToString() == \"10, 50\");\n CHECK(list.GetHead() == 10);\n CHECK(list.GetTail() == 50);\n }\n\n list.Insert(30);\n SECTION(\"Insert(30) (As the middle Node)\") {\n CHECK(list.size() == 3);\n CHECK(list.ToString() == \"10, 30, 50\");\n CHECK(list.GetHead() == 10);\n CHECK(list.GetTail() == 50);\n }\n\n list.Insert(5);\n SECTION(\"Insert(5) (As the first Node)\") {\n CHECK(list.size() == 4);\n CHECK(list.ToString() == \"5, 10, 30, 50\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 50);\n }\n\n list.Insert(55);\n SECTION(\"Insert(55) (As the last Node)\") {\n CHECK(list.size() == 5);\n CHECK(list.ToString() == \"5, 10, 30, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n list.Insert(20);\n SECTION(\"Insert(20) (As the third (middle) Node)\") {\n CHECK(list.size() == 6);\n CHECK(list.ToString() == \"5, 10, 20, 30, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n list.Insert(40);\n SECTION(\"Insert(40) (As the fifth (middle) Node)\") {\n CHECK(list.size() == 7);\n CHECK(list.ToString() == \"5, 10, 20, 30, 40, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n list.Insert(30);\n SECTION(\"Insert(40) (As the third/fourth (middle) Node)\") {\n CHECK(list.size() == 8);\n CHECK(list.ToString() == \"5, 10, 20, 30, 30, 40, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n list.Insert(5);\n SECTION(\"Insert(5) (As the first/second Node)\") {\n CHECK(list.size() == 9);\n CHECK(list.ToString() == \"5, 5, 10, 20, 30, 30, 40, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n list.Insert(55);\n SECTION(\"Insert(55) (As the last/second to last Node)\") {\n CHECK(list.size() == 10);\n CHECK(list.ToString() == \"5, 5, 10, 20, 30, 30, 40, 50, 55, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n SECTION(\"RemoveFirstOccurence(1)\") {\n CHECK(list.RemoveFirstOccurence(1) == false);\n }\n\n bool result = false;\n result = list.RemoveFirstOccurence(5);\n SECTION(\"RemoveFirstOccurence(5) (Front of the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 9);\n CHECK(list.ToString() == \"5, 10, 20, 30, 30, 40, 50, 55, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n result = false;\n result = list.RemoveFirstOccurence(30);\n SECTION(\"RemoveFirstOccurence(30) (Middle of the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 8);\n CHECK(list.ToString() == \"5, 10, 20, 30, 40, 50, 55, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n result = false;\n result = list.RemoveFirstOccurence(30);\n SECTION(\"RemoveFirstOccurence(30) (Middle of the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 7);\n CHECK(list.ToString() == \"5, 10, 20, 40, 50, 55, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n result = false;\n result = list.RemoveFirstOccurence(55);\n SECTION(\"RemoveFirstOccurence(55) (Last/Second to Last of the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 6);\n CHECK(list.ToString() == \"5, 10, 20, 40, 50, 55\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 55);\n }\n\n result = false;\n result = list.RemoveFirstOccurence(55);\n SECTION(\"RemoveFirstOccurence(55) (Last Node in the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 5);\n CHECK(list.ToString() == \"5, 10, 20, 40, 50\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 50);\n }\n\n result = false;\n result = list.RemoveFirstOccurence(10);\n SECTION(\"RemoveFirstOccurence(10) (Middle of the list)\") {\n CHECK(result == true);\n CHECK(list.size() == 4);\n CHECK(list.ToString() == \"5, 20, 40, 50\");\n CHECK(list.GetHead() == 5);\n CHECK(list.GetTail() == 50);\n }\n\n list.Clear();\n SECTION(\"Clear()\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n CHECK(list.GetHead() == 0);\n CHECK(list.GetTail() == 0);\n }\n\n std::stringstream full_head_list, half_head_list, full_tail_list,\n half_tail_list;\n int count = -1;\n for (int i = 0; i < 999; i++) {\n if (i % 100 == 0)\n count++;\n full_head_list << count << \", \";\n }\n full_head_list << 9;\n\n count = -1;\n for (int i = 0; i < 499; i++) {\n if (i % 50 == 0)\n count++;\n half_head_list << count << \", \";\n }\n half_head_list << 9;\n\n for (unsigned int i = 0; i < 1000; i++) {\n list.Insert(i % 10);\n }\n SECTION(\"Insert() \\\"HIGH LOAD\\\"\") {\n CHECK(list.size() == 1000);\n CHECK(list.ToString() == full_head_list.str());\n }\n\n for (unsigned int i = 0; i < 500; i++) {\n list.RemoveFirstOccurence(i % 10);\n }\n SECTION(\"RemoveFirstOccurence() \\\"HIGH LOAD\\\" 1/2\") {\n CHECK(list.size() == 500);\n CHECK(list.ToString() == half_head_list.str());\n }\n\n for (unsigned int i = 0; i < 600; i++) {\n list.RemoveFirstOccurence(i % 10);\n }\n SECTION(\"RemoveFirstOccurence() \\\"HIGH LOAD\\\" 2/2\") {\n CHECK(list.size() == 0);\n CHECK(list.ToString() == \"\");\n }\n}\n"
},
{
"alpha_fraction": 0.5282360911369324,
"alphanum_fraction": 0.5293092131614685,
"avg_line_length": 24.02013397216797,
"blob_id": "5ec7f70a994d43e4d7a159b066f164877ce83da5",
"content_id": "7fc0f9c61e27718d2caf61f65bd63e3a37bd400d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 7455,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 298,
"path": "/Topic 4/Assignment 5/bs_tree.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bst_tree.h\n * Author : David Dalton\n * Description : Tree lab\n */\n \n#include \"bs_tree.h\"\n\n/**\n * sets root_ to NULL\n * sets size_ to 0\n */\nBSTree::BSTree() \n{\n root_ = NULL;\n size_ = 0;\n}\n\n/**\n * calls Clear()\n */\nBSTree::~BSTree()\n{\n Clear();\n}\n\n/**\n * calls private function Insert(int, root)\n */\nbool BSTree::Insert(int value) \n{\n return Insert(value,root_);\n}\n\n/**\n * calls private function Remove(int, root)\n */\nbool BSTree::Remove(int num)\n{\n return Remove(num, root_);\n}\n\n/**\n * calls private function FindMin(root)\n */\nint BSTree::FindMin()\n{\n return FindMin(root_);\n}\n\n/** \n * calls private function Clear(root)\n */\nvoid BSTree::Clear() \n{\n Clear(root_);\n}\n\n/**\n * Accessor for size_\n */\nunsigned int BSTree::size() const \n{\n return size_;\n}\n\n/**\n * calls private function InOrder(root)\n */\nstring BSTree::InOrder() \n{\n return InOrder(root_);\n}\n\n/**\n * creates a new BSTNode, inserts it into the tree, and returns true\n * if the integer is already in the tree, does not insert, and\n * returns false\n */\nbool BSTree::Insert(int value, BSTNode*& node) \n{\n BSTNode* insertNode = new BSTNode(value);\n /**\n * Checks if the root is null, and creates a new node if it is\n */\n if(node == NULL)\n {\n node = insertNode;\n size_ = size_ + 1;\n return true;\n /**\n * Checks if the contents of root are greater then the contents of the \n * new node\n */\n } else if(node->contents() > value)\n {\n /**\n * Checks if the left child of root is null and inserts the node\n * there if it is, else it calls the insert function with the value\n * and the contents of the roots left child\n */\n Insert(value, node->left_child());\n /**\n * Checks if the contents of root are less than the contents of the\n * new node\n */\n } else if(node->contents() < value)\n {\n /**\n * Checks if the right child of root is null and inserts the node\n * there if it is, else it calls the insert function with the value\n * and the contents of the roots right child\n */\n Insert(value, node->right_child());\n } \n /**\n * Checks if the contents of root is equal to the insure value\n */\n else\n {\n return false;\n }\n}\n\n/**\n * clears the entire contents of the tree,\n * freeing all memory associated with all nodes\n */\nvoid BSTree::Clear(BSTNode*& node) \n{\n /**\n * Checks to make sure that the tree is not already empty\n */\n if (node != NULL)\n {\n /**\n * Checks if both childs of the root are null and deletes the root\n * if they are\n */\n if (node->left_child() == NULL && node->right_child() == NULL)\n {\n delete node;\n node = NULL;\n /**\n * If either of the roots child nodes has contents then it calls the\n * Clear function again on the current node in the tree being looked at\n */\n } else\n {\n if (node->left_child())\n {\n Clear(node->left_child());\n } \n if (node->right_child())\n {\n Clear(node->right_child());\n }\n }\n size_ = size_ - 1;\n node = NULL;\n }\n}\n\n/**\n * creates a string of the data in all nodes in the tree, in\n * ascending order\n * separate by spaces (there should be a space after the last output\n * value)\n */\nstring BSTree::InOrder(BSTNode* node) \n{\n stringstream output;\n if (node == NULL)\n {\n return output.str();\n }\n else \n {\n output << InOrder(node->left_child());\n output << node->contents() << \" \";\n output << InOrder(node->right_child());\n return output.str();\n }\n}\n\n/**\n * traverses the tree and removes the node containing the target\n * integer if present and returns true\n * return false if target integer is not in tree (or the tree is empty)\n */\nbool BSTree::Remove(int value, BSTNode*& node)\n{\n /**\n * Creates an iterator to traverse the tree\n */\n BSTNode* iterator = node;\n /**\n * Checks if the current node is null and returns false if it is\n */\n if (node == NULL)\n return false;\n else\n {\n /**\n * Checks if the contents of the node are greater than the value being\n * removed, calls the itself with the current node and value\n * being looked for if it is\n */\n if (value < node->contents())\n Remove(value, node->left_child());\n \n /**\n * Checks if the contents of the node are less than the value being\n * removed, calls the itself with the current node and value\n * being looked for if it is\n */\n else if (value > node->contents())\n Remove(value, node->right_child());\n \n /**\n * Checks if the contents of the node are equal to the value being\n * looked for\n */\n else if (node ->contents() == value)\n {\n /**\n * If the node has no left or right children then it sets the node\n * equal to null, deletes the iterator and reduces size_\n */\n if (!node->left_child() && !node->right_child())\n {\n node = NULL;\n delete iterator;\n size_ = size_ - 1;\n /**\n * Checks if the node doesn't have a left child. If it doesn't\n * then it replaces the node with the nodes right child, deletes\n * the iterator and reduces size_\n */\n } else if (!node->left_child())\n {\n node = node->right_child();\n delete iterator;\n size_ = size_ - 1;\n /**\n * Checks if the node doesn't have a right child. If it doesn't\n * then it replaces the node with the nodes left child, deletes\n * the iterator and reduces size_\n */\n } else if (!node->right_child())\n {\n node = node->left_child();\n delete iterator;\n size_ = size_ - 1;\n \n /**\n * Checks if the node has left and right children\n */\n } else \n {\n /**\n * Sets the node equal to the lowest value in the right side\n * of the tree, then calls the remove function on the\n * right side of the tree with the contents of the node\n * and the nodes right child to remove the original lowest\n * value node\n */\n node->set_contents(FindMin(node->right_child()));\n Remove(node->contents(), node->right_child());\n }\n return true;\n }\n }\n}\n\n/**\n * returns the value of the smallest node in the tree\n * helper function for private Remove()\n */\nint BSTree::FindMin(BSTNode* node) const\n{\n /**\n * Checks if the node is empty\n */\n if (node == NULL)\n return 0;\n /**\n * Loops through the left side of the tree until it finds the lowest value\n * in the tree by location the left child where it's left child is \n * equal to null\n */\n while (node->left_child() != NULL)\n node = node->left_child();\n /**\n * Returns the contents of that node\n */\n return node->contents();\n}"
},
{
"alpha_fraction": 0.6878980994224548,
"alphanum_fraction": 0.7261146306991577,
"avg_line_length": 30.399999618530273,
"blob_id": "39d0369832a366323ad0cefbf884155c9bcfc54b",
"content_id": "605a7a0ad921c5f0caeeae58f79439216fdb5abb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 157,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 5,
"path": "/venv/bin/django-admin.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#!/home/ddalton86/ddalton002stuff/venv/bin/python3\nfrom django.core import management\n\nif __name__ == \"__main__\":\n management.execute_from_command_line()\n"
},
{
"alpha_fraction": 0.6615811586380005,
"alphanum_fraction": 0.6671289801597595,
"avg_line_length": 16.16666603088379,
"blob_id": "4f296cc168f3af02c5b6a065683a72ff8e9b3f44",
"content_id": "05126e29818737330727923f0a0df66a4991fbc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 721,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 42,
"path": "/Topic 4/Lab 1/lab_recursion.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_recursion.h\n * Author : April Browne\n * Description : Header File for Lab Recursion. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\n\n/*\n * Convert a decimal number to binary\n * @param number to be converted.\n * @return a stringstream.\n */\nstringstream decToBin(int num)\n{\n\tif (num > 1) //note this makes the base case num = 0\n\t{\n\t\tdecToBin(num/2); //recursive call\n\t}\n\n\tcout<<(num%2); //outputs in correct order\n}\n\n/*\n * Convert a binary number to decimal\n * @param number to be converted\n * @return an unsigned int\n */\nunsigned int binToDec(int num);\n\n\n#endif\n"
},
{
"alpha_fraction": 0.5529116988182068,
"alphanum_fraction": 0.553537905216217,
"avg_line_length": 17.581396102905273,
"blob_id": "3590613a7c884be35af16ffaed6809fa0567bcbe",
"content_id": "6cbcbacfe041e9e4e7b3d862ca85210b95666b6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1597,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 86,
"path": "/Topic 4/Lab 4/bs_tree.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : bst_tree.h\n * Author : David Dalton\n * Description : Tree lab\n */\n\n#ifndef TREE_H\n#define TREE_H\n\n#include \"bst_node.h\"\n#include <iostream>\n#include <string>\n#include <sstream>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\n\nclass BSTree \n{\n public:\n /**\n * sets root_ to NULL\n * sets size_ to 0\n */\n BSTree();\n \n /**\n * calls Clear()\n */\n ~BSTree();\n \n /**\n * calls private function Insert(int, root)\n */\n bool Insert(int value);\n \n /** \n * calls private function Clear(root)\n */\n void Clear();\n \n /**\n * Accessor for size_\n */\n unsigned int size() const;\n \n /**\n * calls private function InOrder(root)\n */\n string InOrder();\n \n private:\n /**\n * creates a new BSTNode, inserts it into the tree, and returns true\n * if the integer is already in the tree, does not insert, and\n * returns false\n */\n bool Insert(int value, BSTNode*& node);\n \n /**\n * clears the entire contents of the tree,\n * freeing all memory associated with all nodes\n */\n void Clear(BSTNode*& node);\n \n /**\n * creates a string of the data in all nodes in the tree, in\n * ascending order\n * separate by spaces (there should be a space after the last output\n * value)\n */\n string InOrder(BSTNode* node);\n \n /**\n * points to the root node of a binary search tree\n */\n BSTNode* root_;\n \n /**\n * holds the number of nodes in the tree\n */\n unsigned int size_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6482203602790833,
"alphanum_fraction": 0.65943443775177,
"avg_line_length": 36.6422004699707,
"blob_id": "905623cd15e358e146aea14e00920879963dd553",
"content_id": "08977f49f3f2314c2e43a5d372e089e79d742960",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4102,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 109,
"path": "/Topic 1/lab 2/lab_2.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_2.cpp\n * Author : David Dalton\n * Description : Using Arithmetic to finish the functions MakeChange() and\n * LaunchHumanCannonball()\n * Sources : \n */\n\n// Please note the header above. You need to include the name of the file, the\n// author, a description of the program and any sources used\n#include \"lab_2.h\"\n\n\n/*\n * Given an initial integer value (representing change to be given, such as in a\n * financial transaction), break the value down into the number of quarters,\n * dimes, nickels, and pennies that would be given as change.\n * @param int initial_value - The amount of change to be broken down in pennies.\n * @param int quarters - The number of quarters that come out of initial_value\n * @param int dimes - The number of dimes that come out of initial_value,\n * after quarters have been taken out\n * @param int nickels - The number of nickels that come out of initial_value,\n * after quarters and dimes have been taken out\n * @param int pennies - The number of pennies that come out of initial_value,\n * after quarters, dimes, and nickels have been taken out\n */\nvoid MakeChange(int initial_value, int &quarters, int &dimes, int &nickels,\n int &pennies) {\n int quartersRemainder = 0;\n int dimesRemainder = 0;\n int nickelsRemainder = 0;\n int penniesRemainder = 0;\n quartersRemainder = initial_value % 25;\n quarters = (initial_value - quartersRemainder) / 25;\n dimesRemainder = quartersRemainder % 10;\n dimes = (quartersRemainder - dimesRemainder) / 10;\n nickelsRemainder = dimesRemainder % 5;\n nickels = (dimesRemainder - nickelsRemainder) / 5;\n penniesRemainder = nickelsRemainder % 1;\n pennies = (nickelsRemainder - penniesRemainder) / 1;\n}\n\n/*\n * Computes the horizontal distance traveled by a human cannonball given an\n * initial velocity and launch angle. Simplified -- does not account for many\n * factors that affect projectile motion.\n * @param double initial_velocity - Represents the initial velocity of the\n * human cannonball in meters/second\n * @param double launch_angle - Represents the launch angle of the human\n * cannonball in degrees\n * @return double - Represents the horizontal distance the human cannonball\n * will travel\n */\ndouble LaunchHumanCannonball(double initial_velocity, double launch_angle) {\n // (1) Convert launch_angle from degrees to radians\n // [radian_angle = launch_angle * (kPI/180)]\n double radian_angle = (launch_angle * (kPI/180));\n\n // (2) Compute final horizontal/x velocity\n // [x_velocity = initial_velocity * cos(radian_angle)]\n double x_velocity = (initial_velocity * cos(radian_angle));\n\n // (3) Compute final vertical/y velocity\n // [y_velocity = initial_velocity * sin(radian_angle) * -1]\n double y_velocity = (initial_velocity * sin(radian_angle) * -1);\n\n // (4) Compute time of flight\n // [flight_time = (y_velocity) * 2 / -9.8]\n double flight_time = ((y_velocity) * 2 / -9.8);\n\n // (5) Compute horizontal/x distance traveled\n // [x_distance = x_velocity * flight_time]\n double x_distance = (x_velocity * flight_time);\n\n // (6) Return horizontal/x distance\n return x_distance;\n\n\n \n \n}\n\n/*\n//Main for testing purposes only!!!\nint main()\n{\n int initial_value = 0;\n int quarters = 0;\n int dimes = 0;\n int nickels = 0;\n int pennies = 0;\n cout << \"Enter an initial value\" << endl;\n cin >> initial_value;\n MakeChange(initial_value, quarters, dimes, nickels, pennies);\n cout << \"You gave \" << initial_value << \" to me.\" << endl;\n cout << \"You get \" << quarters << \" quarters, \" << dimes << \" dimes, \" << nickels << \" nickels, and \" << pennies << \" pennies in change\" << endl;\n \n double initial_velocity = 0;\n double launch_angle = 0;\n cout << \"Enter initial velocity\" << endl;\n cin >> initial_velocity;\n cout << \"Enter launch angle\" << endl;\n cin >> launch_angle;\n cout << \"You traveled \" << LaunchHumanCannonball(initial_velocity, launch_angle) << endl;\n\n \n return 0;\n}\n*/"
},
{
"alpha_fraction": 0.6131305694580078,
"alphanum_fraction": 0.6164688467979431,
"avg_line_length": 28.315217971801758,
"blob_id": "e5c1cadd1c223b9dcfa0bf6b428e0392078901a0",
"content_id": "218386b0f421892bf1fb67f43646421f3221ff3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2696,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 92,
"path": "/Topic 3/Assignment 4/chairs.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : chairs.cpp\n * Author : David Dalton\n * Description : Program to musical chairs list programs\n */\n \n/**\n * Your driver will be tested against a series of input files. The input file \n * will include a list of students playing the game. Then a list of numbers for \n * how long the song plays each round. Use this number to go through the list \n * to determine which player is eliminated from this round of the game \n * starting at the player currently at the front of the list. The player after \n * the eliminated player becomes the front of the list. Eliminated players are \n * removed from the list.\n * Output the following:\n * A list of the players in the sorted order of input.\n * For each round until there is a winner\n * - The ordinal number of the player eliminated and their name\n * - A space separate list of the players still playing with the current front \n * player first.\n * The name of who won.\n */\n\n#include \"CinReader.cpp\"\n#include \"dl_list.h\"\n\n#include <typeinfo>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <string>\n#include <sstream>\n#include <cstring>\nusing std::cout;\nusing std::ifstream;\nusing std::endl;\nusing std::string;\nusing std::map;\nusing std::stringstream;\n\nint main()\n{\n CinReader reader;\n bool end_program = false;\n bool done = false;\n // Asks the user for the name of the file\n cout << \"Enter the name of the file being used including the file extension\" \n << endl;\n string filename = reader.readString(false);\n // Opens the file to the stream\n ifstream fin (filename.c_str());\n string current_line;\n string players;\n int games[4];\n int iterator_players = 0;\n int iterator_games = 0;\n /**\n * Loops through the file and sorts the lines into either a string array\n * or an integer array based on the contents of the lines\n */\n do {\n fin >> current_line;\n if(isdigit(current_line))\n {\n players[iterator_players] = current_line;\n iterator_players = iterator_players + 1;\n } else\n {\n games[iterator_games] = current_line;\n iterator_games = iterator_games + 1;\n }\n } while(!fin.eof());\n /**\n * Creates the list of players using a node list where the contents\n * of each node equals the index of the player array + 1;\n */\n \n DLList list;\n for(int i = 0; i < 4; i++)\n {\n list.insert(i+1);\n }\n do\n {\n cout << \"End game?\" << endl;\n int end = reader.readChar();\n if(end == 'Y' || end == 'y')\n {\n end_program = true;\n }\n }while(!end_program);\n}"
},
{
"alpha_fraction": 0.5092063546180725,
"alphanum_fraction": 0.5104761719703674,
"avg_line_length": 18.6875,
"blob_id": "a16b14c6d0aece82006e45461e4dfcf2ce3d5994",
"content_id": "64596c9d8f64b371722ab6af5f329e2d92014318",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1575,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 80,
"path": "/Topic 3/Assignment 3/prize.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/**\n * Name: prize.h\n * Author: David Dalton\n * Sources:\n */\n \n#include \"prize.h\"\n\n /**\n * Default constructor\n * initial values itemName (\"NO NAME\"), itemValue (0)\n */\n Prize::Prize() \n {\n prizeName_ = \"NO NAME\";\n prizeValue_ = 0;\n }\n /**\n * Overloaded constructor\n * parameters for all data members\n */\n Prize::Prize(string name, unsigned int value) \n {\n prizeName_ = name;\n prizeValue_ = value;\n }\n /**\n * Deconstructor\n * empty\n */\n Prize::~Prize() \n {\n \n }\n /**\n * Mutator for prizeName_\n */\n void Prize::setPrizeName(string name) \n {\n prizeName_ = name;\n }\n /**\n * Mutator for prizeValue_\n */\n void Prize::setPrizeValue(unsigned int value) \n {\n prizeValue_ = value;\n }\n /**\n * Accessor for prizeName_\n */\n string Prize::getPrizeName() \n {\n return prizeName_;\n }\n /**\n * Accessor for prizeValue_\n */\n unsigned int Prize::getPrizeValue() \n {\n return prizeValue_;\n }\n /**\n * Overloaded operator\n * returns true if the prizeName and prizeValue of the two Prizes being \n * compared are equivalent, else return false\n */\n \n bool operator ==(Prize first_prize, Prize second_prize) \n {\n \n if (first_prize.getPrizeName() == second_prize.getPrizeName() &&\n first_prize.getPrizeValue() == second_prize.getPrizeValue())\n {\n return true;\n } else \n {\n return false;\n }\n }\n"
},
{
"alpha_fraction": 0.6283602118492126,
"alphanum_fraction": 0.6355286836624146,
"avg_line_length": 31.830883026123047,
"blob_id": "fe1bb0f434b1bc1353eeba3bc8da58b7b2165b0c",
"content_id": "da16a3a0f33868fc090c80ec8fc737510ece41a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4464,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 136,
"path": "/Topic 1/lab 6/lab_6.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_6.cpp\n * Author : David Dalton\n * Description : Working with Arrays\n */\n\n#include \"lab_6.h\"\n\n/*\n * Create a string containing the contents of an array, each element separated\n * by a specified character. For example, if the array contents\n * are {1, 2, 3} and the separator character is ':', the string returned\n * will be \"1:2:3\".\n * @uses stringstream\n * @param int values[] - An array of integers\n * @param int size - The size of the integer array\n * @param char separator - The separator character to use in the returned\n * string.\n * Defaults to ','\n * @return string - A string containing the contents of values separated by the\n * specified separator character\n */\nstring PrepareForDisplay(int values[], int size, char separator) {\n /*\n Uses a for loop to add separating character between each number in an integer\n array and then stores the result into a string using stringstream, then\n returns the string\n */\n stringstream returnedString;\n int i=0;\n for(i=0;i<(size - 1);i++) {\n returnedString << values[i] << separator;\n }\n returnedString << values[i];\n return returnedString.str();\n}\n\n/*\n * Test to see if an array contains a specified value.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int value - The value to search for within the array\n * @return bool - true if value is found in the array, otherwise false\n */\nbool HasValue(int values[], int size, int value) {\n /*\n uses a for loop to check each value in an array and compares it to a specific\n value to see if the specified value is present in the array. If the value\n is not present it returns a false value, if the value is found it returns\n a true value\n */\n bool value_present = false;\n int i=0;\n for(i=0;i<size;i++) {\n if(values[i] == value) {\n value_present = true;\n }\n }\n \n if(value_present == true) {\n return true;\n } else {\n return false;\n }\n}\n\n/*\n * Return the value from an array at a specified index.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int index - The position in the array from which to return a value\n * @param bool &error - A flag that will be set to true if index is invalid for\n * the array, else it will be set to false\n * @return int - The value at the specified index in the array when error is set\n * to false. if index is invalid, returns 0 and sets error to true\n */\nint ValueAt(int values[], int size, int index, bool &error) {\n /*\n checks an array at a specified index and retrieves the value from the array\n if no value is present it returns null\n */\n if (index < size) {\n error = false;\n return values[index];\n } else {\n error = true;\n return 0;\n }\n \n}\n\n/*\n * Return the sum of the values in an integer array.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @return int - The sum of the values in the array\n */\nint Sum(int values[], int size) {\n /*\n Takes an array and adds all of the values together and stores the value\n into an integer, then returns the integer to the user\n */\n int sum = 0;\n int i=0;\n for(i=0;i<size;i++) {\n sum += values[i];\n }\n return sum;\n}\n\n/*\n * Swap the positions of two values in an integer array. The two\n * index values must be valid for the array.\n * @param int values - An array of integers\n * @param int size - The size of the integer array\n * @param int index1 - The position of the first value to be swapped\n * @param int index2 - The position of the second value to be swapped\n * @return bool - true if the swap was successful, otherwise false\n */\nbool SwapValues(int values[], int size, int index1, int index2) {\n /*\n Takes two specified positions within an array and swaps the values stored\n at those positions, then returns a true value when the swap is complete. If\n the specified locations are not valid indexes it returns false\n */\n if(((index1 < size) && (index1 >= 0)) && ((index2 < size) && (index2 >= 0))) \n {\n int tempVar = values[index1];\n values[index1] = values[index2];\n values[index2] = tempVar;\n return true;\n } else {\n return false;\n }\n \n}"
},
{
"alpha_fraction": 0.44674375653266907,
"alphanum_fraction": 0.5270845890045166,
"avg_line_length": 23.714284896850586,
"blob_id": "1f968faeaad4dbf3d7bb8dd82584dc89cc0f16ca",
"content_id": "4bcbb2aa7a6a0c76f18a7c6c211d6ea366b2d656",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3286,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 133,
"path": "/Topic 1/lab 6/lab_6_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_6_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #6 Functionality\n * Sources :\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_6.h\"\n\nTEST_CASE(\"Prepare Array For Display Function\") {\n int values[] = { 3, 5, 7, 9, 11 };\n int size = 5;\n\n SECTION(\"PrepareForDisplay({3, 5, 7, 9, 11}, 5)\") {\n CHECK(PrepareForDisplay(values, size) == \"3,5,7,9,11\");\n }\n\n SECTION(\"PrepareForDisplay({3, 5, 7, 9, 11}, 5, ' ')\") {\n CHECK(PrepareForDisplay(values, size, ' ') == \"3 5 7 9 11\");\n }\n\n SECTION(\"PrepareForDisplay({3, 5, 7, 9, 11}, 5, ':')\") {\n CHECK(PrepareForDisplay(values, size, ':') == \"3:5:7:9:11\");\n }\n}\n\nTEST_CASE(\"Array Has Specified Value Function\") {\n int values[] = { 3, 5, 7, 9, 11 };\n int size = 5;\n\n SECTION(\"HasValue({3, 5, 7, 9, 11}, 5, 0)\") {\n CHECK(HasValue(values, size, 0) == false);\n }\n\n SECTION(\"HasValue({3, 5, 7, 9, 11}, 5, 3)\") {\n CHECK(HasValue(values, size, 3) == true);\n }\n\n SECTION(\"HasValue({3, 5, 7, 9, 11}, 5, 11)\") {\n CHECK(HasValue(values, size, 11) == true);\n }\n}\n\nTEST_CASE(\"Value at Sepcified Index in Array Function\") {\n int values[] = { 3, 5, 7, 9, 11 };\n int size = 5;\n bool error = true;\n\n SECTION(\"ValueAt({3, 5, 7, 9, 11}, 5, 0, error)\") {\n CHECK(ValueAt(values, size, 0, error) == 3);\n CHECK(error == false);\n }\n\n SECTION(\"ValueAt({3, 5, 7, 9, 11}, 5, 5, error)\") {\n CHECK(ValueAt(values, size, 5, error) == 0);\n CHECK(error == true);\n }\n\n SECTION(\"ValueAt({3, 5, 7, 9, 11}, 5, 4, error)\") {\n CHECK(ValueAt(values, size, 4, error) == 11);\n CHECK(error == false);\n }\n}\n\nTEST_CASE(\"Sum Array Function\") {\n int values[] = {3, 5, 7, 9, 11};\n int size = 5;\n\n SECTION(\"Sum({3, 5, 7, 9, 11}, 5)\") {\n CHECK(Sum(values, size) == 35);\n }\n\n SECTION(\"Sum({3}, 1)\") {\n CHECK(Sum(values, 1) == 3);\n }\n\n SECTION(\"Sum({}, 0)\") {\n CHECK(Sum(values, 0) == 0);\n }\n}\n\nTEST_CASE(\"Swap Value in Array Function\") {\n int values[] = { 3, 5, 7, 9, 11 };\n int size = 5;\n bool success = false;\n\n SECTION(\"SwapValues({3, 5, 7, 9, 11}, 5, 0, 4)\") {\n CHECK(SwapValues(values, size, 0, 4) == true);\n CHECK(values[0] == 11);\n CHECK(values[1] == 5);\n CHECK(values[2] == 7);\n CHECK(values[3] == 9);\n CHECK(values[4] == 3);\n }\n\n SECTION(\"SwapValues({3, 5, 7, 9, 11}, 5, 1, 3)\") {\n CHECK(SwapValues(values, size, 1, 3) == true);\n CHECK(values[0] == 3);\n CHECK(values[1] == 9);\n CHECK(values[2] == 7);\n CHECK(values[3] == 5);\n CHECK(values[4] == 11);\n }\n\n SECTION(\"SwapValues({3, 5, 7, 9, 11}, 5, 2, 2)\") {\n CHECK(SwapValues(values, size, 2, 2) == true);\n CHECK(values[0] == 3);\n CHECK(values[1] == 5);\n CHECK(values[2] == 7);\n CHECK(values[3] == 9);\n CHECK(values[4] == 11);\n }\n\n SECTION(\"SwapValues({3, 5, 7, 9, 11}, 5, -2, 2)\") {\n CHECK(SwapValues(values, size, -2, 2) == false);\n CHECK(values[0] == 3);\n CHECK(values[1] == 5);\n CHECK(values[2] == 7);\n CHECK(values[3] == 9);\n CHECK(values[4] == 11);\n }\n\n SECTION(\"SwapValues({3, 5, 7, 9, 11}, 5, 2, 10)\") {\n CHECK(SwapValues(values, size, 2, 5) == false);\n CHECK(values[0] == 3);\n CHECK(values[1] == 5);\n CHECK(values[2] == 7);\n CHECK(values[3] == 9);\n CHECK(values[4] == 11);\n }\n}"
},
{
"alpha_fraction": 0.6027149558067322,
"alphanum_fraction": 0.607239842414856,
"avg_line_length": 14.800000190734863,
"blob_id": "222f9ba0eaf0bc03f6e73c11d128d40102be5d5c",
"content_id": "3497cf2284b28090b61e3d9ed8eaef52a14ad3c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1105,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 70,
"path": "/Topic 2/lab 4/item.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : item.h\n * Author : David Dalton\n * Description : Class Header File\n */\n\n#include \"item.h\"\n\n/*\n * Constructor\n *takes two parameters, one for each private member variable\n *defaults name_ to \"item\"\n *defaults value_ to 0\n */\nItem::Item(string name, unsigned int value) \n{\n \n name_ = name;\n value_ = value;\n}\n/*\n *Destructor\n */\nItem::~Item() \n{\n \n}\n/*\n * Mutator #1\n *sets the value of name_ to be equal to the input string\n */\nvoid Item::set_name(string name) \n{\n name_ = name;\n}\n/*\n * Mutator #2\n *sets the value of value_ to be equal to the input int\n */\nvoid Item::set_value(unsigned int value) \n{\n value_ = value;\n}\n/*\n * Accessor #1\n *retrieves the value of name_\n */ \nstring Item::name() \n{\n return name_;\n}\n/*\n * Accessor #2\n *retrieves the value of value_\n */\nunsigned int Item::value() \n{\n return value_;\n}\n/*\n *string ToString()\n *returns a string containing name_ and value_\n *Format -- name_, $value_\n */\nstring Item::ToString() \n{\n stringstream returned_string;\n returned_string << name_ << \", $\" << value_;\n return returned_string.str();\n}"
},
{
"alpha_fraction": 0.5158398151397705,
"alphanum_fraction": 0.5481171607971191,
"avg_line_length": 19.912500381469727,
"blob_id": "02ef2c3547c892ca2a068afc1263df6517523ab9",
"content_id": "3955f4edb3e12db222ee32f40ff9dc24ae56bc6e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1673,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 80,
"path": "/Topic 1/lab 4/lab_4_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_4_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #4 Functionality\n * Sources :\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"lab_4.h\"\n\nTEST_CASE(\"MakeString()\") {\n SECTION(\"MakeString(\\\"Temperature\\\", 42.6, ':')\") {\n CHECK(MakeString(\"Temperature\", 42.6, ':') == \"Temperature : 42.6\");\n }\n\n SECTION(\"MakeString(\\\"\\\", 75, ',')\") {\n CHECK(MakeString(\"\", 75, ',') == \" , 75\");\n }\n\n SECTION(\"MakeString(\\\"Total\\\", 100.05, '=')\") {\n CHECK(MakeString(\"Total\", 100.05, '=') == \"Total = 100.05\");\n }\n}\n\nTEST_CASE(\"StringToChar()\") {\n SECTION(\"StringToChar(\\\"\\\")\") {\n CHECK(StringToChar(\"\") == '\\0');\n }\n\n SECTION(\"StringToChar(\\\"yn\\\")\") {\n CHECK(StringToChar(\"yn\") == '\\0');\n }\n\n SECTION(\"StringToChar(\\\"X\\\")\") {\n CHECK(StringToChar(\"X\") == 'X');\n }\n}\n\nTEST_CASE(\"StringToInt()\") {\n SECTION(\"StringToInt(\\\"42\\\")\") {\n CHECK(StringToInt(\"42\") == 42);\n }\n\n SECTION(\"StringToInt(\\\"hello\\\")\") {\n CHECK(StringToInt(\"hello\") == 0);\n }\n\n SECTION(\"StringToInt(\\\"\\\")\") {\n CHECK(StringToInt(\"\") == 0);\n }\n}\n\nTEST_CASE(\"StringToDouble()\") {\n SECTION(\"StringToDouble(\\\"\\\")\") {\n CHECK(StringToDouble(\"\") == 0);\n }\n\n SECTION(\"StringToDouble(\\\"3.14\\\")\") {\n CHECK(StringToDouble(\"3.14\") == 3.14);\n }\n\n SECTION(\"StringToDouble(\\\"hello\\\")\") {\n CHECK(StringToDouble(\"hello\") == 0);\n }\n}\n\nTEST_CASE(\"StringToBool()\") {\n SECTION(\"StringToBool(\\\"\\\")\") {\n CHECK(StringToBool(\"\") == false);\n }\n\n SECTION(\"StringToBool(\\\"TrUe\\\")\") {\n CHECK(StringToBool(\"TrUe\") == true);\n }\n\n SECTION(\"StringToBool(\\\"FALSE\\\")\") {\n CHECK(StringToBool(\"FALSE\") == false);\n }\n}\n"
},
{
"alpha_fraction": 0.6140797138214111,
"alphanum_fraction": 0.619168758392334,
"avg_line_length": 16.611940383911133,
"blob_id": "52e7e95788775b0f17f7c8cd779bf78b6d87cace",
"content_id": "0fa0929eb0fce9f9bcfe993258601a3e6ad1bd9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1179,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 67,
"path": "/Topic 2/lab 4/item.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : item.h\n * Author : David Dalton\n * Description : Class Header File\n */\n\n#ifndef ITEM_H\n#define ITEM_H\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <stdio.h>\n#include <ctype.h>\nusing std::string;\nusing std::stringstream;\nusing std::setprecision;\nusing std::fixed;\n\n/*\n * Class Item.\n */\nclass Item {\n public:\n /*\n * Constructor\n *takes two parameters, one for each private member variable\n *defaults name_ to \"item\"\n *defaults value_ to 0\n */\n Item(string name = \"item\", unsigned int value = 0);\n /*\n *Destructor\n */\n virtual ~Item();\n /*\n * Mutator #1\n *sets the value of name_ to be equal to the input string\n */\n void set_name(string name);\n /*\n * Mutator #2\n *sets the value of value_ to be equal to the input int\n */\n void set_value(unsigned int value);\n /*\n * Acessor #1\n *retrieves the value of name_\n */\n string name();\n /*\n * Acessor #2\n *retrieves the value of value_\n */\n unsigned int value();\n /*\n *string ToString()\n *returns a string containing name_ and value_\n *Format -- name_, $value_\n */\n string ToString();\n private:\n string name_;\n unsigned int value_;\n};\n\n#endif"
},
{
"alpha_fraction": 0.6306532621383667,
"alphanum_fraction": 0.69597989320755,
"avg_line_length": 25.53333282470703,
"blob_id": "642815c9d39efc143729208338ea51911e33fc25",
"content_id": "5bbcd752d72587cea3d92a4c499a25cb2d91dd6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 398,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 15,
"path": "/Topic 4/Lab 2/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from all of the object files\nlab2test: lab_22_unit_test.o lab_22.o\n\tg++ -Wall -g -o lab22test lab_22.o lab_22_unit_test.o\n\n#creates the lab1 object file\t\nlab22: lab_22.cpp lab_22.h\n\tg++ -Wall -g -c lab_1.cpp\n\n#creates the lab 1 unit test object file\nlab_22_unit_test: lab_22_unit_test.cpp\n\tg++ -Wall -g -c lab_22_unit_test.cpp\n\n#cleans up old .o files\t\nclean:\n\trm *.o *test "
},
{
"alpha_fraction": 0.560946524143219,
"alphanum_fraction": 0.577848494052887,
"avg_line_length": 26.037633895874023,
"blob_id": "5855a4198c94bee0e0e57fcaf9a30e31aeff8e18",
"content_id": "3f8a3c27aeb0ba3790553784aebc775da43c6549",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5029,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 186,
"path": "/Topic 5/Lab 2/lab_27_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_27_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #27 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n#include \"lab_27.h\"\n\nTEST_CASE(\"Treasure Chest Default Constructor\") {\n TreasureChest chest;\n SECTION(\"GetSize()\") {\n CHECK(chest.GetSize() == 0);\n }\n\n SECTION(\"Empty()\") {\n CHECK(chest.Empty() == true);\n }\n\n SECTION(\"GetItem(0)\") {\n CHECK(chest.GetItem(0) == NULL);\n }\n\n SECTION(\"RemoveItem(0)\") {\n try {\n chest.RemoveItem(0);\n CHECK(false);\n } catch (string &s) {\n CHECK(s == \"ERROR: Remove at invalid position\");\n }\n }\n\n SECTION(\"ToString()\") {\n CHECK(chest.ToString() == \"Chest Empty!\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n}\n\nTEST_CASE(\"Adding to the Chest\") {\n TreasureChest chest;\n Item item;\n Item testItems[5] = { Item(\"ruby\", 100, 1), Item(\"gold\", 5, 100), Item(\n \"emerald\", 50, 2), Item(\"silver\", 2, 200), Item() };\n\n chest.AddItem(testItems[0]);\n SECTION(\"AddItem(ruby)\") {\n CHECK(chest.GetSize() == 1);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n chest.AddItem(testItems[1]);\n SECTION(\"AddItem(gold)\") {\n CHECK(chest.GetSize() == 2);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby, gold\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n chest.InsertItem(testItems[2], 1);\n SECTION(\"InsertItem(emerald, 1)\") {\n CHECK(chest.GetSize() == 3);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby, emerald, gold\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n chest.InsertItem(testItems[3], 2);\n SECTION(\"InsertItem(silver, 2)\") {\n CHECK(chest.GetSize() == 4);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby, emerald, silver, gold\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n chest.InsertItem(testItems[4], 10);\n SECTION(\"InsertItem(noname, 10)\") {\n CHECK(chest.GetSize() == 5);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby, emerald, silver, gold, noname\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n item = chest.RemoveItem(0);\n SECTION(\"RemoveItem(0)\") {\n CHECK(item.name_ == \"ruby\");\n CHECK(item.value_ == 100);\n CHECK(item.quantity_ == 1);\n CHECK(chest.GetSize() == 4);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"emerald, silver, gold, noname\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n item = chest.RemoveItem(3);\n SECTION(\"RemoveItem(3)\") {\n CHECK(item.name_ == \"noname\");\n CHECK(item.value_ == 0);\n CHECK(item.quantity_ == 0);\n CHECK(chest.GetSize() == 3);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"emerald, silver, gold\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n SECTION(\"RemoveItem(3)\") {\n try {\n chest.RemoveItem(3);\n CHECK(false);\n } catch (string &s) {\n CHECK(s == \"ERROR: Remove at invalid position\");\n }\n }\n\n chest.Clear();\n SECTION(\"Clear()\") {\n CHECK(chest.GetSize() == 0);\n CHECK(chest.Empty() == true);\n CHECK(chest.GetItem(0) == NULL);\n CHECK(chest.ToString() == \"Chest Empty!\");\n }\n\n for (unsigned int i = 0; i < 5; i++)\n chest.AddItem(testItems[i]);\n SECTION(\"Adding 5 Items\") {\n CHECK(chest.GetSize() == 5);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"ruby, gold, emerald, silver, noname\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n chest.SortByName();\n SECTION(\"SortByName()\") {\n CHECK(chest.GetSize() == 5);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"emerald, gold, noname, ruby, silver\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n const Item* ptr_item = chest.GetItem(0);\n SECTION(\"GetItem(0)\") {\n CHECK(ptr_item->name_ == \"emerald\");\n CHECK(ptr_item->quantity_ == 2);\n CHECK(ptr_item->value_ == 50);\n }\n\n chest.SortByValue();\n SECTION(\"SortByValue()\") {\n CHECK(chest.GetSize() == 5);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"noname, silver, gold, emerald, ruby\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n ptr_item = chest.GetItem(0);\n SECTION(\"GetItem(0)\") {\n CHECK(ptr_item->name_ == \"noname\");\n CHECK(ptr_item->quantity_ == 0);\n CHECK(ptr_item->value_ == 0);\n }\n\n chest.SortByQuantity();\n SECTION(\"SortByQuantity()\") {\n CHECK(chest.GetSize() == 5);\n CHECK(chest.Empty() == false);\n CHECK(chest.ToString() == \"noname, ruby, emerald, gold, silver\");\n }\n cout << \"Chest Contents: \" << chest << endl << endl;\n\n ptr_item = chest.GetItem(4);\n SECTION(\"GetItem(4)\") {\n CHECK(ptr_item->name_ == \"silver\");\n CHECK(ptr_item->quantity_ == 200);\n CHECK(ptr_item->value_ == 2);\n }\n\n ptr_item = chest.GetItem(5);\n SECTION(\"GetItem(5)\") {\n CHECK(ptr_item == NULL);\n }\n}\n"
},
{
"alpha_fraction": 0.6113730072975159,
"alphanum_fraction": 0.6196228861808777,
"avg_line_length": 23.424461364746094,
"blob_id": "3c26b1cea1d40a9cbb7c6c92c348a223ccee78b1",
"content_id": "ef2ff894837140ef9999e1b53c2035074e21d59c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3394,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 139,
"path": "/Topic 2/lab 2/temperature.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : temperature.cpp\n * Author : David Dalton\n * Description : Program to convert function between various temperatures\n */\n \n#include \"temperature.h\"\n\n /*\n * Sets kelvin_ to 0\n */\n Temperature::Temperature()\n {\n kelvin_ = 0;\n }\n\n /*\n * Sets kelvin_ to the supplied value using the SetTempFromKelvin() function\n */\n Temperature::Temperature(double kelvin) \n {\n SetTempFromKelvin(kelvin);\n }\n\n /*\n * Converts the supplied temperature to kelvin using the appropriate function\n * and internally stores it.\n * Uses an if statement to check the unit to convert to the correct\n * temperature unit type\n */\n Temperature::Temperature(double temp, char unit) \n {\n unit = toupper(unit);\n if(unit == 'F') \n {\n SetTempFromFahrenheit(temp);\n } else if(unit == 'C') \n {\n SetTempFromCelsius(temp);\n } else \n {\n SetTempFromKelvin(temp);\n }\n }\n\n /*\n * The temperature will come in as kelvin and this function will set the\n * internal temp to this value\n */\n void Temperature::SetTempFromKelvin(double kelvin) \n {\n kelvin_ = kelvin;\n }\n\n\n /*\n * Converts the value from Celsius to kelvin then sets\n * the temperature to the converted value\n */\n void Temperature::SetTempFromCelsius(double celsius) \n {\n kelvin_ = (celsius + 273.15);\n }\n\n\n /*\n *Converts the value from Fahrenheit to kelvin then sets\n *the temperature to the converted value\n */\n void Temperature::SetTempFromFahrenheit(double fahrenheit) \n {\n kelvin_ = (5.0 * (fahrenheit - 32) /9) + 273.15;\n }\n\n /*\n * Gets the internal temperature in Kelvin and returns it.\n */\n double Temperature::GetTempAsKelvin() const \n {\n return kelvin_;\n }\n\n /*\n * Converts the internal temperature from kelvin to celsius using the\n * GetTempAsCelsius() function then returns the value\n */\n double Temperature::GetTempAsCelsius() const \n {\n return (kelvin_ - 273.15);\n \n }\n\n /*\n * Converts the internal temperature from kelvin to fahrenheit using the\n * GetTempAsFahrenheit() function then returns the value\n\n */\n double Temperature::GetTempAsFahrenheit() const \n {\n double temperature = GetTempAsCelsius();\n return ((temperature * 9.0 / 5 ) + 32);\n \n }\n\n /*\n * Get a string representation of the temperature.\n * Uses an if statement to check which unit is needed then call the \n * appropriate conversion function to convert the temperature as needed and\n * stores it into a temporary value.\n * Uses stringstream to return the converted value plus the appropriate\n * unit type.\n */\n string Temperature::ToString(char unit) const \n {\n stringstream temp;\n temp.setf(std::ios::fixed|std::ios::showpoint);\n temp.precision(2);\n double current_temp;\n string current_temp_unit;\n unit = toupper(unit);\n if(unit == 'K') \n {\n current_temp_unit = \"Kelvin\";\n current_temp = GetTempAsKelvin();\n } else if(unit == 'C') \n {\n current_temp_unit = \"Celsius\";\n current_temp = GetTempAsCelsius();\n } else if(unit == 'F')\n {\n current_temp_unit = \"Fahrenheit\";\n current_temp = GetTempAsFahrenheit();\n } else \n {\n return \"Invalid Unit\";\n }\n temp << current_temp << \" \" << current_temp_unit;\n return temp.str();\n }"
},
{
"alpha_fraction": 0.6620903611183167,
"alphanum_fraction": 0.662976086139679,
"avg_line_length": 22.278350830078125,
"blob_id": "74594edec556376d62fc8122199a0defd23fd324",
"content_id": "62820acc818e88f5f4f9f4d1f93ca18b76c2e069",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2258,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 97,
"path": "/Topic 2/lab 1/lab_1.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_1.h\n * Author : Luke Sathrum\n * Description : Header File for Lab #1. DO NOT ALTER!\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <iomanip>\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::stringstream;\nusing std::setprecision;\nusing std::fixed;\n\n/*\n * Class Spaceship.\n * A class to model a simple spaceship for a science fiction\n * game or story.\n */\nclass Spaceship {\n public:\n /*\n * Set the name of this Spaceship.\n * @param string name - The name for this Spaceship\n */\n void set_name(string name);\n\n /*\n * Set the top speed of this Spaceship.\n * @param double top_speed - The top speed for this Spaceship in warp\n */\n void set_top_speed(double top_speed);\n\n /*\n * Set the fuel source of this Spaceship.\n * @param string fuel_source - A fuel source for this Spaceship\n */\n void set_fuel_source(string fuel_source);\n\n /*\n * Set the crew capacity of this Spaceship.\n * @param int crew_capacity - A crew capacity for this Spaceship\n */\n void set_crew_capacity(int crew_capacity);\n\n /*\n * Get the name of this Spaceship.\n * @return string - The name of this Spaceship\n */\n string name() const;\n\n /*\n * Get the top speed of this Spaceship.\n * @return double - The top speed of this Spaceship\n */\n double top_speed() const;\n\n /*\n * Get the fuel source of this Spaceship.\n * @return string - The fuel source of this Spaceship\n */\n string fuel_source() const;\n\n /*\n * Get the crew capacity of this Spaceship.\n * @return int - The crew capacity of this Spaceship\n */\n int crew_capacity() const;\n\n /*\n * Get a string representation of this Spaceship's specifications.\n * The string will be formatted as\n * \"NAME\\n\n * Top Speed: Warp TOP_SPEED\\n\n * Fuel Source: FUEL_SOURCE\\n\n * Crew Capacity: CREW_CAPACITY\"\n * where NAME, TOP_SPEED (to two decimal places), FUEL_SOURCE, and\n * CREW_CAPACITY contain the values of the associated member variables.\n * @uses stringstream\n * @return string - A representation of this Spaceship's specifications\n */\n string ToString() const;\n\n private:\n string name_;\n float top_speed_;\n string fuel_source_;\n int crew_capacity_;\n};\n\n#endif\n"
},
{
"alpha_fraction": 0.7135134935379028,
"alphanum_fraction": 0.7189189195632935,
"avg_line_length": 17.600000381469727,
"blob_id": "69191a43b6108767e2a1f95d87434094bcf4eab7",
"content_id": "aa52e330790af3605bdbc3b599c524c8348977fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 185,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 10,
"path": "/Topic 4/Lab 1/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "all: labrecursiontest\n\nlabrecursiontest: lab_recursion.o\n\tg++ -Wall -g -o lab1 lab_recursion.o\n\nlabrecursion: lab_recursion.cpp\n\tg++ -Wall -g -c lab_recursion.cpp\n\t\nclean:\n\trm *.o *test"
},
{
"alpha_fraction": 0.6630212664604187,
"alphanum_fraction": 0.6697512269020081,
"avg_line_length": 36.15178680419922,
"blob_id": "9a82290fb652002d9816b639e41e3488b84261d4",
"content_id": "f1b6392cceda4554dd7afac0c6e39f058a9c312a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8321,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 224,
"path": "/Topic 2/Assignment 2/savings_account.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : savings_account.cpp\n * Author : David Dalton\n * Description : SavingsAccount function definition\n * Source : Luke Sathrum, modified portions of money lab and item lab\n */\n \n#include \"savings_account.h\"\n\n/*\n * Constructor, uses default values if none given on creation\n */\nSavingAccount::SavingAccount(string account_name, long dollars, \n int cents, double interest_rate, string last_transaction, \n string interest_accumulated_month, \n string interest_accumulated_year) \n{\n BankAccount::SetAccountName(account_name);\n BankAccount::SetDollars(dollars);\n BankAccount::SetCents(cents) ;\n BankAccount::SetLastTransaction(0, 0, last_transaction);\n BankAccount::ClearRecentTransactions();\n SetInterestRate(interest_rate);\n}\n/*\n * Destructor, unused\n */\nSavingAccount::~SavingAccount() \n{\n \n}\n/*\n * Mutator\n *Sets the interest_rate_ to the specified double. If the specified value\n *is less than 0 then it sets it to 0\n */\nvoid SavingAccount::SetInterestRate(double interest_rate) \n{\n if(interest_rate < 0)\n {\n interest_rate = 0;\n interest_rate_ = interest_rate;\n } else \n {\n interest_rate_ = interest_rate;\n }\n}\n/*\n * Mutator\n *gets the current interest accumulated for the month and stores it, then \n *adds the amount of interested earned to the amount accumulated for the month\n */\nvoid SavingAccount::SetInterestAccumulatedMonth(long accumulated_dollars, \n int accumulated_cents) \n{\n stringstream interest;\n int string_length = interest_accumulated_month_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_length;i++)\n {\n if(interest_accumulated_month_[i] != ('$' || '-'))\n {\n interest << interest_accumulated_month_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double current_interest = stoi(interest.str());\n // Splits the value into the dollars and cents value\n long current_dollars = current_interest;\n int current_cents = ((current_interest - current_dollars) *100);\n // Adds the amount accrued to the current amount\n accumulated_dollars = accumulated_dollars + current_dollars;\n accumulated_cents = accumulated_cents + current_cents;\n // Adds to the string stream to convert back into a string\n interest << '$' << setw(1) << setfill('0') << accumulated_dollars << \".\" \n << setfill('0') << setw(2) << accumulated_cents;\n // Sets the interest_accumulated_month_ string to the stringstream\n interest_accumulated_month_ = interest.str();\n}\n/*\n * Mutator\n *gets the current interest accumulated for the year and stores it, then \n *adds the amount of interested earned to the amount accumulated for the year\n */\nvoid SavingAccount::SetInterestAccumulatedYear(long accumulated_dollars, \n int accumulated_cents) \n{\n stringstream interest;\n int string_length = interest_accumulated_year_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_length;i++)\n {\n if(interest_accumulated_year_[i] != ('$' || '-'))\n {\n interest << interest_accumulated_year_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double current_interest = stoi(interest.str());\n // Splits the value into the dollars and cents value\n long current_dollars = current_interest;\n int current_cents = ((current_interest - current_dollars) *100);\n // Adds the amount accrued to the current amount\n accumulated_dollars = accumulated_dollars + current_dollars;\n accumulated_cents = accumulated_cents + current_cents;\n // Adds to the string stream to convert back into a string\n interest << '$' << setw(1) << setfill('0') << accumulated_dollars << \".\" \n << setfill('0') << setw(2) << accumulated_cents;\n // Sets the interest_accumulated_year_ string to the stringstream\n interest_accumulated_year_ = interest.str();\n}\n/*\n * Mutator\n *retrieves the current balance then calculates the amount of interest earned\n *then adds it to the current balance\n */\nvoid SavingAccount::CalculateInterest() \n{\n // Retrieves the needed variables\n long dollars = BankAccount::GetDollars();\n int cents = BankAccount::GetCents();\n double interest_rate = GetInterestRate();\n string interest_month_generated = GetInterestAccumulatedMonth();\n string interest_year_generated = GetInterestAccumulatedYear();\n // Gets the needed information on interest accumulated for the month\n stringstream interest_month;\n int string_month_length = interest_accumulated_month_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_month_length;i++)\n {\n if(interest_accumulated_month_[i] != ('$' || '-'))\n {\n interest_month << interest_accumulated_month_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double monthly_interest = stoi(interest_month.str());\n // Splits the value into the dollars and cents value\n long monthly_dollars = monthly_interest;\n int monthly_cents = ((monthly_interest - monthly_dollars) *100);\n // Gets the needed information on interest accumulated for the month\n stringstream interest_year;\n int string_year_length = interest_accumulated_year_.length();\n /* \n *uses a for loop to extract the integer amounts from the interest \n *accumulated string\n */\n for(int i=0;i<string_year_length;i++)\n {\n if(interest_accumulated_year_[i] != ('$' || '-'))\n {\n interest_year << interest_accumulated_year_[i]; \n } \n }\n // Uses stoi to convert the string into a double\n double yearly_interest = stoi(interest_year.str());\n // Splits the value into the dollars and cents value\n long yearly_dollars = yearly_interest;\n int yearly_cents = ((yearly_interest - yearly_dollars) * 100);\n // Get all the cents of interest for the month\n long all_cents1 = monthly_cents + monthly_dollars * 100;\n // Get all the cents of interest for the year\n long all_cents2 = yearly_cents + yearly_dollars * 100;\n // Add all the cents together\n long sum_all_cents = all_cents1 + all_cents2;\n // Handle the fact that money can be negative\n long abs_all_cents = abs(sum_all_cents);\n long final_dollars = abs_all_cents / 100;\n int final_cents = abs_all_cents % 100;\n // If the result of the operation was negative, negate final dollars and cents\n if (sum_all_cents < 0) {\n final_dollars = -final_dollars;\n final_cents = -final_cents;\n }\n //Sets interest accumulated for the year to calculated values\n SetInterestAccumulatedYear(final_dollars, final_cents);\n /*\n *uses the current balance and subtracts that from the accumulated interest\n *to determine the amount accumulated for the month and sets it to the value\n */\n double current_balance = (dollars + (cents / 100));\n double updated_balance = current_balance + (current_balance * interest_rate);\n double gained_balance = updated_balance - current_balance;\n long updated_balance_dollars = updated_balance;\n int updated_balance_cents = ((updated_balance - updated_balance_dollars) * 100);\n long gained_balance_dollars = gained_balance;\n int gained_balance_cents = ((gained_balance - gained_balance_dollars) * 100);\n BankAccount::SetDollars(updated_balance_dollars);\n BankAccount::SetCents(updated_balance_cents);\n SetInterestAccumulatedMonth(gained_balance_dollars, gained_balance_cents);\n \n}\n/*\n * Accessor\n *gets the value of interest_rate_ and returns it\n */\ndouble SavingAccount::GetInterestRate() \n{\n return interest_rate_;\n}\n/*\n * Accessor\n *gets the value of interest_accumulated_month_ and returns it\n */\nstring SavingAccount::GetInterestAccumulatedMonth() \n{\n return interest_accumulated_month_;\n}/*\n * Accessor\n *gets the value of interest_accumulated_year_ and returns it\n */\nstring SavingAccount::GetInterestAccumulatedYear() \n{\n return interest_accumulated_year_;\n}"
},
{
"alpha_fraction": 0.7207392454147339,
"alphanum_fraction": 0.7515400648117065,
"avg_line_length": 31.46666717529297,
"blob_id": "990276e4b202bc1275e2e793ce669e92ed896781",
"content_id": "db8da9f49ca3d692e4cb9ef6aa0682703b67c56d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 15,
"path": "/Topic 1/Assignment 1/makefile",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "#creates the executable from both of the object files\nassignment1test: assignment_1_unit_test.o assignment_1.o\n\tg++ -Wall -g -o assignment1test assignment_1.o assignment_1_unit_test.o\n\n#creates the assignment_1.o object file\t\nlab5: assignment_1.cpp assignment_1.h\n\tg++ -Wall -g -c assignment_1.cpp\n\n#creates the unit test object file\nassignment_1_unit_test: assignment_1_unit_test.cpp\n\tg++ -Wall -g -c assignment_1_unit_test.cpp\n\t\n#cleans up old .o files\t\nclean:\n\trm *.o assignment1test "
},
{
"alpha_fraction": 0.4933774769306183,
"alphanum_fraction": 0.5529801249504089,
"avg_line_length": 23.16666603088379,
"blob_id": "88eb5157be8edb005c6a7169ba31b3b82b62764a",
"content_id": "4a91ecacd4cc8c46b6d0f0b8c87fef1393270d0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 24,
"path": "/CSCI465/firstapp/migrations/0003_auto_20171114_1718.py",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Generated by Django 1.11.5 on 2017-11-15 01:18\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('firstapp', '0002_auto_20171114_1056'),\r\n ]\r\n\r\n operations = [\r\n migrations.RemoveField(\r\n model_name='profile',\r\n name='location',\r\n ),\r\n migrations.AddField(\r\n model_name='profile',\r\n name='games',\r\n field=models.CharField(blank=True, max_length=140, null=True),\r\n ),\r\n ]\r\n"
},
{
"alpha_fraction": 0.6711990237236023,
"alphanum_fraction": 0.6922125816345215,
"avg_line_length": 25.96666717529297,
"blob_id": "12d485ac2b8806f4cb05e1c62a32a1e720ef18fc",
"content_id": "dd6950c103420e0043a41aaf1bdf16c134add4f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 809,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 30,
"path": "/Topic 1/lab 2/lab_2.h",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_2.h\n * Author : FILL IN\n * Description : Using Arithmetic to finish the functions MakeChange() and\n * LaunchHumanCannonball()\n * Sources :\n */\n\n#ifndef LAB_H\n#define LAB_H\n\n// Please note the header above. You need to include the name of the file, the\n// author, a description of the program and any sources used\n#include <iostream>\n#include <cmath>\n#include <string>\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n// Function Prototypes (DO NOT ALTER)\nvoid MakeChange(int initial_value, int &quarters, int &dimes, int &nickels,\n int &pennies);\ndouble LaunchHumanCannonball(double initial_velocity, double launch_angle);\n\n// Create a Constant named kPI which is initialized to 3.1415927\nconst double kPI = 3.1415927;\n\n#endif\n"
},
{
"alpha_fraction": 0.5562403798103333,
"alphanum_fraction": 0.5956856608390808,
"avg_line_length": 28.509090423583984,
"blob_id": "17a4651e407e955377edb6fd44a140c275187f10",
"content_id": "51124251df0e5dec1f7e90af1ba00693049927f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3245,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 110,
"path": "/Topic 2/lab 4/lab_10_unit_test.cpp",
"repo_name": "ddalton002/ddalton002stuff",
"src_encoding": "UTF-8",
"text": "/*\n * Name : lab_10_unit_test.cpp\n * Author : Luke Sathrum\n * Description : Unit test to test Lab #26 Functionality\n */\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"item.h\"\n#include \"food_item.h\"\n#include \"magic_item.h\"\n// To Test for Correct Header Guards\n#include \"item.h\"\n#include \"food_item.h\"\n#include \"magic_item.h\"\n\nTEST_CASE(\"Item Class\") {\n SECTION(\"Default Constructor\") {\n Item item;\n CHECK(item.name() == \"item\");\n CHECK(item.value() == 0);\n CHECK(item.ToString() == \"item, $0\");\n }\n\n SECTION(\"Overloaded Constructor\") {\n Item item(\"game\", 25);\n CHECK(item.name() == \"game\");\n CHECK(item.value() == 25);\n CHECK(item.ToString() == \"game, $25\");\n }\n\n SECTION(\"Accessors / Mutators\") {\n Item item;\n item.set_name(\"car\");\n item.set_value(35000);\n CHECK(item.name() == \"car\");\n CHECK(item.value() == 35000);\n CHECK(item.ToString() == \"car, $35000\");\n }\n}\n\nTEST_CASE(\"FoodItem Class\") {\n SECTION(\"Default Constructor\") {\n FoodItem item;\n CHECK(item.name() == \"fooditem\");\n CHECK(item.value() == 0);\n CHECK(item.calories() == 0);\n CHECK(item.unit_of_measure() == \"nounits\");\n CHECK(item.units() == 0);\n CHECK(item.ToString() == \"fooditem, $0, 0.00 nounits, 0 calories\");\n }\n\n SECTION(\"Overloaded Constructor(\\\"coffee\\\", 1, 10, \\\"ounces\\\", 10.25)\") {\n FoodItem item(\"coffee\", 1, 10, \"ounces\", 10.25);\n CHECK(item.name() == \"coffee\");\n CHECK(item.value() == 1);\n CHECK(item.calories() == 10);\n CHECK(item.unit_of_measure() == \"ounces\");\n CHECK(item.units() == 10.25);\n CHECK(item.ToString() == \"coffee, $1, 10.25 ounces, 10 calories\");\n }\n\n SECTION(\"Accessors / Mutators\") {\n FoodItem item;\n item.set_name(\"cupcake\");\n item.set_value(5);\n item.set_calories(200);\n item.set_unit_of_measure(\"cake(s)\");\n item.set_units(1.5);\n CHECK(item.name() == \"cupcake\");\n CHECK(item.value() == 5);\n CHECK(item.calories() == 200);\n CHECK(item.unit_of_measure() == \"cake(s)\");\n CHECK(item.units() == 1.5);\n CHECK(item.ToString() == \"cupcake, $5, 1.50 cake(s), 200 calories\");\n }\n}\n\nTEST_CASE(\"MagicItem Class\") {\n SECTION(\"Default Constructor\") {\n MagicItem item;\n CHECK(item.name() == \"magicitem\");\n CHECK(item.value() == 0);\n CHECK(item.description() == \"no description\");\n CHECK(item.mana_required() == 0);\n CHECK(item.ToString() == \"magicitem, $0, no description, requires 0 mana\");\n }\n\n SECTION(\"Overloaded Constructor(\\\"staff\\\", 999, \\\"carved wood\\\", 125)\") {\n MagicItem item(\"staff\", 999, \"carved wood\", 125);\n CHECK(item.name() == \"staff\");\n CHECK(item.value() == 999);\n CHECK(item.description() == \"carved wood\");\n CHECK(item.mana_required() == 125);\n CHECK(item.ToString() == \"staff, $999, carved wood, requires 125 mana\");\n }\n\n SECTION(\"Accessors / Mutators\") {\n MagicItem item;\n item.set_name(\"wand\");\n item.set_value(1000);\n item.set_description(\"jewel-encrusted\");\n item.set_mana_required(50);\n CHECK(item.name() == \"wand\");\n CHECK(item.value() == 1000);\n CHECK(item.description() == \"jewel-encrusted\");\n CHECK(item.mana_required() == 50);\n CHECK(item.ToString() == \"wand, $1000, jewel-encrusted, requires 50 mana\");\n }\n}"
}
] | 137 |
fiozzi/fiozzi.github.io | https://github.com/fiozzi/fiozzi.github.io | 2a84e37f08a7e39e94d47f4e5a5e24ce384fa7f5 | a8fe631e39659288aa337e68c00706f87cb8a341 | ac0ebaa7d5b74c6019191d6f853ad5e863ae0244 | refs/heads/main | 2023-03-20T15:56:18.939495 | 2023-03-18T12:30:03 | 2023-03-18T12:30:03 | 332,681,268 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5522648096084595,
"alphanum_fraction": 0.6149826049804688,
"avg_line_length": 15.911765098571777,
"blob_id": "c35bb5b334f173b846a765728b646cd6e000c93b",
"content_id": "cb033e82f9e9d3eb591f3ed9d74919cd06497ca6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 574,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 34,
"path": "/iulm/03/lista01.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 10 12:34:37 2023\n\n@author: Iozzi\n\"\"\"\n\nlista1 = [44,76,23,68,54,99]\nsoglia = 50\n\nfor el in lista1:\n if el < soglia:\n print(el)\n\nprint('fine della lista')\n\nfor i in range(12):\n print(i)\n \nfor elemento in range(3,12):\n print(elemento)\n\nlistacitta = []\nlistacitta.append(['Milano', 'Italia'])\nlistacitta.append(['roma', 'italia'])\nlistacitta.append(['london', 'uk'])\n# print(listacitta)\n\nfor citta in listacitta:\n if citta[1].upper() == 'ITALIA':\n print(citta)\n\nfor i in range(5):\n print('fabrizio')"
},
{
"alpha_fraction": 0.6056337952613831,
"alphanum_fraction": 0.658450722694397,
"avg_line_length": 16.6875,
"blob_id": "498d67398918a9ff09eb6a9eac2185c65a000d21",
"content_id": "4acea56cf2aba5159d63cc41db67d478303e084c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 284,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 16,
"path": "/iulm/01/ex_01.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 3 11:03:55 2023\n\n@author: Iozzi\n\"\"\"\n\n# dati\ncapacita_aule = 50\n\n# input numero studenti\nn_studenti = int(input('Quanti sono gli studenti?'))\n\nn_aule = n_studenti // capacita_aule + 1\n\nprint(f'Per questo esame occorrono {n_aule} aule')\n\n"
},
{
"alpha_fraction": 0.5509803891181946,
"alphanum_fraction": 0.5676470398902893,
"avg_line_length": 27.33333396911621,
"blob_id": "9aef6fe87cddac0ea16d6dc8ca376942a7c070b9",
"content_id": "45dd4db05fd4390eed390ecc3e1fb82caf7d83d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1020,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 36,
"path": "/iulm/05/person.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 17 11:39:49 2023\n\n@author: Iozzi\n\"\"\"\n\nimport datetime\n\nclass Person:\n def __init__(self, \\\n firstname = 'Unknown', \\\n lastname = 'Unknown', \\\n birthdate = 'Unknown'):\n self.firstname = firstname\n self.lastname = lastname\n self.birthdate = birthdate\n \n def age(self):\n age = datetime.datetime.today() - self.birthdate\n return age.days // 365\n \n def person_2_dict(self):\n d={}\n d['firstname']=self.firstname\n d['lastname']=self.lastname\n d['birthdate']=self.birthdate\n return d\n\nclass Student(Person):\n def __init__(self, firstname = 'Unknown', lastname='Unknown', \\\n birthdate='Unknown', academic_program = 'PhD'):\n # creo una persona con nome, cognome e data di nascita\n # usando i parametri forniti\n super().__init__(firstname, lastname, birthdate)\n self.academic_program = academic_program\n"
},
{
"alpha_fraction": 0.4479166567325592,
"alphanum_fraction": 0.4921875,
"avg_line_length": 22.75,
"blob_id": "b61db37d47c10766c9accfc9a544c11d77091e68",
"content_id": "0ed732bc43793cdbeeddd64356961740ab798d32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 16,
"path": "/iulm/04/dict_01.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 13 11:28:44 2023\n\n@author: Iozzi\n\"\"\"\n\nphd_student = [{'name': 'sara', 'eta': 26, \\\n 'laurea': 'comunicazione'}, \\\n {'name': 'marco', 'eta': 35, \\\n 'laurea': 'ingegneria'}]\n\nfor student in phd_student:\n eta = student['eta']\n nome = student['name']\n print(f\"{nome} ha {eta} anni.\")\n "
},
{
"alpha_fraction": 0.6974128484725952,
"alphanum_fraction": 0.6985377073287964,
"avg_line_length": 28.600000381469727,
"blob_id": "e4b2e3518c0fe72666bb02aa0825c305206ebad3",
"content_id": "bfa5672a1aadc631bced92ea3d56cf1c08c60bbf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 893,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 30,
"path": "/iulm/assignment/vlookup_start.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Iozzi\n\"\"\"\nimport csv\n\ndef vlookup(nomefile, campo, valore, output):\n\n pass\n\nrisultato = vlookup(nomefile = 'bridges.data', campo = 'MATERIAL', valore = 'WOOD', output = 'IDENTIF')\nprint()\nprint('lista di IDENTIF per i ponti il cui MATERIAL è WOOD')\nprint(risultato)\n\nrisultato = vlookup(nomefile = 'bridges.data', campo = 'PURPOSE', valore = 'HIGHWAY', output = 'IDENTIF')\nprint()\nprint('lista di IDENTIF per i ponti il cui PURPOSE è HIGHWAY')\nprint(risultato)\n\nrisultato = vlookup(nomefile = 'bridges.data', campo = 'PURPOSE', valore = 'HIGHWAY', output = 'LENGTH')\nprint()\nprint('lista di LENGTH per i ponti il cui PURPOSE è HIGHWAY')\nprint(risultato)\n\nrisultato = vlookup(nomefile = 'bridges.data', campo = 'MATERIAL', valore = 'PAPER', output = 'IDENTIF')\nprint()\nprint('lista di IDENTIF per i ponti il cui MATERIAL è PAPER')\nprint(risultato)\n\n"
},
{
"alpha_fraction": 0.5538461804389954,
"alphanum_fraction": 0.620512843132019,
"avg_line_length": 18.5,
"blob_id": "4a1d549f7ea10bed7da91a92ed74271ad25bc078",
"content_id": "d0a3b2db481dd5009fc22349e8576b0028ffda83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 195,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 10,
"path": "/iulm/01/utilita.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 3 11:03:55 2023\n\n@author: Iozzi\n\"\"\"\n\ndef calcola_n_aule(n_studenti, capacita_aule):\n n_aule = n_studenti // capacita_aule + 1\n return n_aule\n"
},
{
"alpha_fraction": 0.5852311849594116,
"alphanum_fraction": 0.6356107592582703,
"avg_line_length": 29.02083396911621,
"blob_id": "84f15b1e87898fd7d32e9b3fedd0db091d1b68b8",
"content_id": "33e1151622122adae092c5f9e06d424b4d0d346c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1449,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 48,
"path": "/iulm/05/person01.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 17 10:43:07 2023\n\n@author: Iozzi\n\"\"\"\nimport datetime\n\nimport person \nimport csv\n\n# from person import Person\n\np1 = person.Person('Marco', 'Bilucaglia', \\\n datetime.datetime.strptime('27061988', '%d%m%Y'))\nprint(p1.firstname)\np2 = person.Person(lastname='Conti', firstname='Sara', \\\n birthdate=datetime.datetime.strptime('18051996', '%d%m%Y'))\nprint(p1.birthdate)\nprint(p1.age())\nprint(p2.firstname)\nprint(p2.birthdate)\nprint(p2.age())\n\np3 = person.Person(lastname='Casiraghi', firstname='Chiara', \\\n birthdate=datetime.datetime.strptime('31121997', '%d%m%Y'))\n\ns1 = person.Student(firstname='Francesco', \\\n lastname='Minetti', \\\n birthdate=datetime.datetime.strptime('30081985', '%d%m%Y'))\nprint(s1.firstname)\nprint(s1.age())\ns2 = person.Student(lastname='Ignoto', \\\n birthdate=datetime.datetime.strptime('30081985', '%d%m%Y'))\nprint(s2)\n\npersons_list = []\npersons_list.append(p1)\npersons_list.append(p2)\npersons_list.append(p3)\n\nwith open('persone.csv','w', newline='') as f_output:\n # dict_writer = csv.DictWriter(f_output, ['firstname', 'lastname', 'birthdate'])\n dict_writer = csv.DictWriter(f_output, \\\n persons_list[0].person_2_dict().keys())\n dict_writer.writeheader()\n for persona in persons_list:\n dict_writer.writerow(persona.person_2_dict())\n "
},
{
"alpha_fraction": 0.6037735939025879,
"alphanum_fraction": 0.6226415038108826,
"avg_line_length": 11.15384578704834,
"blob_id": "ae837df44e0e8c1d116ca57a800d7ceb9a1cb754",
"content_id": "407c4d78036744fb611428abe5db85178ad4b24f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 159,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 13,
"path": "/iulm/02/test_biglietto.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport work\n\ntb = 'A'\neta = 12\npb = work.prezzo_biglietto(eta, tb)\nprint(pb)\n\n"
},
{
"alpha_fraction": 0.5410235524177551,
"alphanum_fraction": 0.5540211200714111,
"avg_line_length": 29.774999618530273,
"blob_id": "c825cff57d5d4b6d5e94eeea1109ff0f2e0ef34c",
"content_id": "5dc208ea7ee1fbecd6ba5348eeeb22ca3cbc8cc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2462,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 80,
"path": "/iulm/04/bridges.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 20 10:43:12 2020\n\n@author: Iozzi\n\"\"\"\n\nimport csv\n\ndef bridges_per_year(filename, year_field_name):\n bridges_per_year = {}\n with open(filename,'r') as fp:\n dict_reader = csv.DictReader(fp, delimiter=',')\n for row in dict_reader:\n year = int(row[year_field_name])\n if year in bridges_per_year.keys():\n bridges_per_year[year] += 1\n else:\n bridges_per_year[year] = 1\n return bridges_per_year\n\ndef invert_dict(d):\n inverse = dict()\n for key in d.keys():\n val = d[key]\n if val not in inverse:\n inverse[val] = [key]\n else:\n inverse[val].append(key)\n return inverse\n\ndef materials(filename, material_field_name, unknown):\n materials = {}\n with open(filename,'r') as fp:\n dict_reader = csv.DictReader(fp, delimiter=',')\n for row in dict_reader:\n mat = row[material_field_name]\n if mat == '?':\n mat = unknown\n if mat in materials.keys():\n materials[mat] = materials[mat] + 1\n else:\n materials[mat] = 1\n return materials\n\nif __name__ == '__main__':\n bridges_per_year = bridges_per_year('bridges.data', 'ERECTED')\n bridges = sum(bridges_per_year.values())\n print(f'{bridges} bridges built in Pittsburgh, PA.')\n print('Bridges per year of construction.')\n for i in sorted(bridges_per_year.keys()):\n if bridges_per_year[i] == 1:\n str1 = f'Year {i}: 1 bridge.'\n else:\n str1 = f'Year {i}: {bridges_per_year[i]} bridges.'\n print(str1)\n \n year_per_bridges = invert_dict(bridges_per_year)\n \n print('Years per number of bridges built.')\n for i in sorted(year_per_bridges.keys()):\n if i == 1:\n str1 = 'During the following year(s) 1 bridge was built:'\n else:\n str1 = f'During the following year(s) {i} bridges were built.'\n print(str1,year_per_bridges[i])\n \n \n materials = materials('bridges.data', 'MATERIAL', 'UNKNOWN')\n print('Bridges per material:')\n for i in sorted(materials.keys()):\n if materials[i] == 1:\n str1 = f'Material {i}: 1 bridge.'\n else:\n str1 = f'Material {i}: {materials[i]} bridges.'\n print(str1)\n \n import matplotlib.pyplot as plt\n \n plt.bar(materials.keys(),materials.values())\n"
},
{
"alpha_fraction": 0.47432762384414673,
"alphanum_fraction": 0.5464547872543335,
"avg_line_length": 21.08108139038086,
"blob_id": "bf4baf408463665de9210c2e90c296d643e137f1",
"content_id": "75f5d079f436dc15171b53204e94981e5d98dba0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 818,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 37,
"path": "/iulm/05/libro01.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 16 18:42:51 2023\n\n@author: fabri\n\"\"\"\n\nfrom libro import Libro\n\nlibro1 = Libro(autore='Graham Green', \\\n titolo='Our man in Havana', \\\n lingua='EN', \\\n isbn='0140017909')\n\nlibro2 = Libro(autore='Stanislaw Lem', \\\n titolo='Cyberiade', \\\n lingua='IT', \\\n isbn='9771120528002')\n\n# ho modificato il 5 codice di libro2\n\nlibro3 = Libro(autore='Fabrizio Iozzi', \\\n titolo='Il libro che non ho scritto', \\\n lingua='IT', \\\n isbn='9771120628002')\n\nlibri = []\nlibri.append(libro1)\nlibri.append(libro2)\nlibri.append(libro3)\n\nfor libro in libri:\n print(libro.autore, libro.titolo)\n if libro.ISBNValido()[0]:\n \tprint('Valido')\n else:\n \tprint(libro.ISBNValido()[1])\n\n"
},
{
"alpha_fraction": 0.4175029993057251,
"alphanum_fraction": 0.6696106195449829,
"avg_line_length": 21.64545440673828,
"blob_id": "5e6792eef555d6e2bc83d5188e84b76eadd30478",
"content_id": "dc1d82d4fa03633cb57e9ef6204708b92fc4fc0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2491,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 110,
"path": "/iulm/04/citta_marco.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "citta_grandi = [\n[\"Tokyo\",37339804],\n[\"Delhi\",31181376],\n[\"Shanghai\",27795702],\n[\"Sao Paulo\",22237472],\n[\"Mexico City\",21918936],\n[\"Dhaka\",21741090],\n[\"Cairo\",21322750],\n[\"Beijing\",20896820],\n[\"Mumbai\",20667656],\n[\"Osaka\",19110616],\n[\"Karachi\",16459472],\n[\"Chongqing\",16382376],\n[\"Istanbul\",15415197],\n[\"Buenos Aires\",15257673],\n[\"Kolkata\",14974073],\n[\"Kinshasa\",14970460],\n[\"Lagos\",14862111],\n[\"Manila\",14158573],\n[\"Tianjin\",13794450],\n[\"Guangzhou\",13635397],\n[\"Rio de Janeiro\",13544462],\n[\"Lahore\",13095166],\n[\"Bangalore\",12764935],\n[\"Moscow\",12593252],\n[\"Shenzhen\",12591696],\n[\"Chennai\",11235018],\n[\"Bogota\",11167392],\n[\"Paris\",11078546],\n[\"Jakarta\",10915364],\n[\"Lima\",10882757],\n[\"Bangkok\",10722815],\n[\"Hyderabad\",10268653],\n[\"Seoul\",9967677],\n[\"Nagoya\",9565642],\n[\"London\",9425622],\n[\"Chengdu\",9305116],\n[\"Tehran\",9259009],\n[\"Nanjing\",9143980],\n[\"Ho Chi Minh City\",8837544],\n[\"Luanda\",8631876],\n[\"Wuhan\",8473405],\n[\"Xi-an Shaanxi\",8274651],\n[\"Ahmedabad\",8253226],\n[\"New York City\",8230290],\n[\"Kuala Lumpur\",8210745],\n[\"Hangzhou\",7845501],\n[\"Hong Kong\",7598189],\n[\"Surat\",7489742],\n[\"Dongguan\",7451889],\n[\"Suzhou\",7427096],\n[\"Foshan\",7406751],\n[\"Riyadh\",7387817],\n[\"Shenyang\",7373655],\n[\"Baghdad\",7323079],\n[\"Dar es Salaam\",7046892],\n[\"Santiago\",6811595],\n[\"Pune\",6807984],\n[\"Madrid\",6668865],\n[\"Haerbin\",6526439],\n[\"Toronto\",6254571],\n[\"Belo Horizonte\",6139774],\n[\"Singapore\",5991801],\n[\"Khartoum\",5989024],\n[\"Johannesburg\",5926668],\n[\"Dalian\",5775938],\n[\"Qingdao\",5742486],\n[\"Barcelona\",5624498],\n[\"Fukuoka\",5516158],\n[\"Ji-nan Shandong\",5513597],\n[\"Zhengzhou\",5510341],\n[\"Saint Petersburg\",5504305],\n[\"Yangon\",5421806],\n[\"Alexandria\",5381101],\n[\"Abidjan\",5354826],\n[\"Guadalajara\",5259296],\n[\"Ankara\",5215747],\n[\"Chittagong\",5132751],\n[\"Melbourne\",5061439],\n[\"Addis Ababa\",5005524]]\n\ndef citta_pop_min(listacitta, minpop = 7000000):\n\n lista_out=[]\n for citta in listacitta:\n if citta[1]>minpop:\n lista_out.append(citta[0])\n\n return lista_out\n\n\ndef citta_per_intervallo_popolazione(listacitta, intervallo):\n lista_out=[]\n for citta in listacitta:\n if citta[1]>intervallo[0] and citta[1]<intervallo[1]:\n lista_out.append(citta[0])\n\n return lista_out\n\nlista = citta_pop_min(minpop = 10000000, listacitta = citta_grandi)\nprint(len(lista))\nprint(lista)\n\nintervallo67 = [6000000, 7000000]\n\nlista = citta_per_intervallo_popolazione(citta_grandi, intervallo67)\nprint(len(lista))\nprint(lista)\n\nl1 = citta_per_intervallo_popolazione(listacitta = citta_grandi, intervallo = intervallo67)\n"
},
{
"alpha_fraction": 0.45826348662376404,
"alphanum_fraction": 0.6627556085586548,
"avg_line_length": 26.37614631652832,
"blob_id": "091764e8e474ed5d68fdd72ed3d3edde00392b90",
"content_id": "5c457428ae21c78ee973f7a697c766df6f45b6b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2987,
"license_type": "no_license",
"max_line_length": 638,
"num_lines": 109,
"path": "/iulm/03/citta_0.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "citta_grandi = [\n[\"Tokyo\",37339804],\n[\"Delhi\",31181376],\n[\"Shanghai\",27795702],\n[\"Sao Paulo\",22237472],\n[\"Mexico City\",21918936],\n[\"Dhaka\",21741090],\n[\"Cairo\",21322750],\n[\"Beijing\",20896820],\n[\"Mumbai\",20667656],\n[\"Osaka\",19110616],\n[\"Karachi\",16459472],\n[\"Chongqing\",16382376],\n[\"Istanbul\",15415197],\n[\"Buenos Aires\",15257673],\n[\"Kolkata\",14974073],\n[\"Kinshasa\",14970460],\n[\"Lagos\",14862111],\n[\"Manila\",14158573],\n[\"Tianjin\",13794450],\n[\"Guangzhou\",13635397],\n[\"Rio de Janeiro\",13544462],\n[\"Lahore\",13095166],\n[\"Bangalore\",12764935],\n[\"Moscow\",12593252],\n[\"Shenzhen\",12591696],\n[\"Chennai\",11235018],\n[\"Bogota\",11167392],\n[\"Paris\",11078546],\n[\"Jakarta\",10915364],\n[\"Lima\",10882757],\n[\"Bangkok\",10722815],\n[\"Hyderabad\",10268653],\n[\"Seoul\",9967677],\n[\"Nagoya\",9565642],\n[\"London\",9425622],\n[\"Chengdu\",9305116],\n[\"Tehran\",9259009],\n[\"Nanjing\",9143980],\n[\"Ho Chi Minh City\",8837544],\n[\"Luanda\",8631876],\n[\"Wuhan\",8473405],\n[\"Xi-an Shaanxi\",8274651],\n[\"Ahmedabad\",8253226],\n[\"New York City\",8230290],\n[\"Kuala Lumpur\",8210745],\n[\"Hangzhou\",7845501],\n[\"Hong Kong\",7598189],\n[\"Surat\",7489742],\n[\"Dongguan\",7451889],\n[\"Suzhou\",7427096],\n[\"Foshan\",7406751],\n[\"Riyadh\",7387817],\n[\"Shenyang\",7373655],\n[\"Baghdad\",7323079],\n[\"Dar es Salaam\",7046892],\n[\"Santiago\",6811595],\n[\"Pune\",6807984],\n[\"Madrid\",6668865],\n[\"Haerbin\",6526439],\n[\"Toronto\",6254571],\n[\"Belo Horizonte\",6139774],\n[\"Singapore\",5991801],\n[\"Khartoum\",5989024],\n[\"Johannesburg\",5926668],\n[\"Dalian\",5775938],\n[\"Qingdao\",5742486],\n[\"Barcelona\",5624498],\n[\"Fukuoka\",5516158],\n[\"Ji-nan Shandong\",5513597],\n[\"Zhengzhou\",5510341],\n[\"Saint Petersburg\",5504305],\n[\"Yangon\",5421806],\n[\"Alexandria\",5381101],\n[\"Abidjan\",5354826],\n[\"Guadalajara\",5259296],\n[\"Ankara\",5215747],\n[\"Chittagong\",5132751],\n[\"Melbourne\",5061439],\n[\"Addis Ababa\",5005524]]\n\ndef citta_pop_min(listacitta, minpop=0):\n # restituisce una lista\n # delle città la cui popolazione è\n # almeno minpop\n return []\n\nlista = citta_pop_min(citta_grandi, 7000000)\nprint(len(lista))\nprint(lista)\n\nintervallo = [6000000, 7000000]\n\ndef citta_per_intervallo_popolazione(listacitta, intervallo):\n # restituisce una lista\n # delle città la cui popolazione è\n # nell'intervallo indicato\n return []\n\nlista = citta_per_intervallo_popolazione(citta_grandi, intervallo)\nprint(len(lista))\nprint(lista)\n\n'''\n55\n['Tokyo', 'Delhi', 'Shanghai', 'Sao Paulo', 'Mexico City', 'Dhaka', 'Cairo', 'Beijing', 'Mumbai', 'Osaka', 'Karachi', 'Chongqing', 'Istanbul', 'Buenos Aires', 'Kolkata', 'Kinshasa', 'Lagos', 'Manila', 'Tianjin', 'Guangzhou', 'Rio de Janeiro', 'Lahore', 'Bangalore', 'Moscow', 'Shenzhen', 'Chennai', 'Bogota', 'Paris', 'Jakarta', 'Lima', 'Bangkok', 'Hyderabad', 'Seoul', 'Nagoya', 'London', 'Chengdu', 'Tehran', 'Nanjing', 'Ho Chi Minh City', 'Luanda', 'Wuhan', 'Xi-an Shaanxi', 'Ahmedabad', 'New York City', 'Kuala Lumpur', 'Hangzhou', 'Hong Kong', 'Surat', 'Dongguan', 'Suzhou', 'Foshan', 'Riyadh', 'Shenyang', 'Baghdad', 'Dar es Salaam']\n6\n['Santiago', 'Pune', 'Madrid', 'Haerbin', 'Toronto', 'Belo Horizonte']\n'''"
},
{
"alpha_fraction": 0.5233644843101501,
"alphanum_fraction": 0.5934579372406006,
"avg_line_length": 21.578947067260742,
"blob_id": "887c74fd41be66cf1b2dd36a1430c4a4d396b207",
"content_id": "639fa4009d5547da09e2c6cb9c30369ad592de23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 429,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 19,
"path": "/iulm/02/junior_senior.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 6 12:08:17 2023\n\n@author: Iozzi\n\"\"\"\n\nprint(\"Benvenuto al cinema!\")\nage = int(input(\"Quanti anni hai? \"))\n\nif age < 18:\n ticket_price = 10 * 0.8 # applica lo sconto del 20%\nelse:\n if age < 65:\n ticket_price = 10 # prezzo pieno\n else:\n ticket_price = 10 * 0.7 # applica lo sconto del 30%\n \nprint(f\"Il prezzo del tuo biglietto è {ticket_price} euro.\")"
},
{
"alpha_fraction": 0.5845845937728882,
"alphanum_fraction": 0.6116116046905518,
"avg_line_length": 23.390243530273438,
"blob_id": "49ca3282c4f46e8bbd9c74d43e822f27e7d35446",
"content_id": "8cbf2aa6924540c0d2b49f0b52329ae16f1aa0db",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 999,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 41,
"path": "/iulm/03/work_marco.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 1 16:58:34 2021\n\n@author: Iozzi\n\"\"\"\n\ndef prezzo_biglietto(eta, tipo_biglietto):\n prezzo_pieno = prezzo_per_tipo(tipo_biglietto)\n sconto = riduzione(tipo_biglietto, prezzo_pieno, eta)\n prezzo_finale = prezzo_pieno - sconto\n \n return prezzo_finale\n\ndef prezzo_per_tipo(tipo_biglietto):\n if tipo_biglietto == 'A' or tipo_biglietto =='B' \\\n or tipo_biglietto=='C':\n prezzo_intero = 12\n else:\n prezzo_intero = 10\n return prezzo_intero\n\ndef riduzione(tipo_biglietto, prezzo, eta):\n perc_sconto = 0\n if tipo_biglietto in 'AB':\n if eta < 18:\n perc_sconto = 0.3\n else:\n if eta > 60:\n perc_sconto = 0.2\n return prezzo * perc_sconto\n\ntipo = 'A'\nprezzo = prezzo_per_tipo(tipo)\nprint(f'prezzo per biglietto {tipo}: {prezzo}')\ntipo = 'F'\nprezzo = prezzo_per_tipo(tipo)\nprint(f'prezzo per biglietto {tipo}: {prezzo}')\n\np = prezzo_biglietto(15, 'A')\nprint(p)"
},
{
"alpha_fraction": 0.4667101800441742,
"alphanum_fraction": 0.4885770380496979,
"avg_line_length": 36.14634323120117,
"blob_id": "4d35ff3d2495af3a79e5e007128e7440af1ca1fb",
"content_id": "47ee270377627bcb19340f623ec76d3623719f1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3082,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 82,
"path": "/iulm/05/libro.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 16 18:42:51 2023\n\n@author: fabri\n\"\"\"\n\nclass Libro:\n def __init__(self, isbn, autore, titolo, lingua = 'IT'):\n self.isbn = isbn\n self.autore = autore\n self.titolo = titolo\n self.lingua = lingua\n\n def ISBNValido(self):\n '''\n La funzione ISBNValido restituisce una coppia di valori,\n cioè una t-upla (è come una lista ma non modificabile).\n Il primo valore è True/False se il codice è corretto o meno,\n il secondo valore è 'OK', se il codice è valido, o\n un messaggio di errore se il codice non è valido.\n \n La sintassi \n \n return a,b\n \n è un modo sintetico di restituire due valori.\n '''\n isbn = self.isbn\n # non valido se non ha 10 o 13 caratteri\n if len(isbn) == 10:\n # Somma pesata delle prime 9 cifre\n # 10 x (prima cifra) + 9 x (seconda cifra) + 8 x (terza cifra) ...\n # fino a 1 x (nona cifra)\n somma = 0\n for i in range(9):\n # sommo solo se il carattere è una cifra\n # altrimenti c'è un errore\n if isbn[i].isdigit():\n somma += int(isbn[i]) * (10 - i)\n else:\n return False, 'Errore: alcuni caratteri non numerici'\n # per l'ultimo carattere, posso avere una X che\n # rappresenta 10 quindi devo distinguere i casi\n # se è X aggiungo 10\n # se è una cifra, aggiungo la cifra\n if isbn[9] == 'X':\n somma += 10\n elif isbn[9].isdigit():\n somma += int(isbn[9])\n else:\n return False, 'Ultimo carattere non numerico e diverso da X'\n # se l'ISBN è corretto, la somma deve essere \n # un multiplo di 11\n if somma % 11 == 0:\n return True, 'OK'\n else:\n return False, 'Il codice non è corretto'\n elif len(isbn) == 13:\n # Somma pesata di tutte le cifre\n # 1 x (prima cifra) + 3 x (seconda cifra) + 1 x (terza cifra) ...\n # alternativamente 1 e 3 fino a 1 x (tredicesima cifra)\n somma = 0\n for i in range(13):\n # sommo solo se il carattere è una cifra\n # altrimenti c'è un errore\n if isbn[i].isdigit():\n if i % 2 == 0:\n moltiplicatore = 1\n else:\n moltiplicatore = 3\n somma += int(isbn[i]) * moltiplicatore\n else:\n return False, 'Errore: alcuni caratteri non numerici'\n # se l'ISBN è corretto, la somma deve essere \n # un multiplo di 10\n if somma % 10 == 0:\n return True, 'OK'\n else:\n return False, 'Il codice non è corretto'\n else:\n return False, 'Lunghezza codice non uguale a 10 o 13'\n \n \n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6600000262260437,
"avg_line_length": 15.666666984558105,
"blob_id": "35929aa3b329a71bdedb7e25b44ecd5be178d115",
"content_id": "9c38381cbcd90323a95079af596967ba33c4bb68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 250,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 15,
"path": "/iulm/02/work.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 1 16:58:34 2021\n\n@author: Iozzi\n\"\"\"\n\ndef prezzo_biglietto(eta, tipo_biglietto):\n return 0\n\ndef prezzo_per_tipo(tipo_biglietto):\n return 0\n\ndef riduzione(tipo_biglietto, prezzo, eta):\n return 0\n"
},
{
"alpha_fraction": 0.6418337821960449,
"alphanum_fraction": 0.676217794418335,
"avg_line_length": 18.33333396911621,
"blob_id": "96a7e172b7a207d77123e72b245503c093266cfa",
"content_id": "367df5e2a60e8906f8402f393d40c0422a392cc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 350,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 18,
"path": "/iulm/01/ex_02.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 3 11:03:55 2023\n\n@author: Iozzi\n\"\"\"\n\nimport utilita\n \n# dati\ncapacita_aule = int(input('Capacità aule: '))\n\n# input numero studenti\nn_studenti = int(input('Quanti sono gli studenti?'))\n\nn_aule = utilita.calcola_n_aule(n_studenti, capacita_aule)\n\nprint(f'Per questo esame occorrono {n_aule} aule')\n\n"
},
{
"alpha_fraction": 0.6041055917739868,
"alphanum_fraction": 0.6422287225723267,
"avg_line_length": 19.058822631835938,
"blob_id": "2817d4a43239b8d3ec96722983e63898232c821d",
"content_id": "15ce595d788626c2d88dce4cd7909e4b4344245f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 17,
"path": "/iulm/03/salgari.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 25 12:11:23 2022\n\n@author: fabrizio\n\"\"\"\n\nwith open('salgari.txt', 'r') as f:\n testo = f.read()\n\nparole = testo.split(' ')\nprint(len(parole))\nparole_distinte = []\nfor parola in parole:\n if not (parola in parole_distinte):\n parole_distinte.append(parola)\nprint(len(parole_distinte))\n"
},
{
"alpha_fraction": 0.5791925191879272,
"alphanum_fraction": 0.6040372848510742,
"avg_line_length": 25.83333396911621,
"blob_id": "89e4f013e0b273c5cf1e146c9830794cc63b83c8",
"content_id": "b60aa01cde713dd81d0d5d3d93583198345d092e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 24,
"path": "/iulm/04/ponti.py",
"repo_name": "fiozzi/fiozzi.github.io",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 13 11:48:41 2023\n\n@author: Iozzi\n\"\"\"\n\nimport csv\n\ndef file_stat(filename, fieldname):\n with open(filename,'r', encoding='utf-8') as f_input:\n dict_reader = csv.DictReader(f_input, delimiter=',')\n column_dict = {}\n for riga in dict_reader:\n if riga[fieldname] in column_dict.keys():\n column_dict[riga[fieldname]] += 1\n else:\n column_dict[riga[fieldname]] = 1\n return column_dict\n\ncolumn_dict = file_stat('bridges.data', 'MATERIAL')\nprint(column_dict)\ncolumn_dict = file_stat('Artists.csv', 'Gender')\nprint(column_dict)\n"
}
] | 19 |
renewang/datasciencecoursera | https://github.com/renewang/datasciencecoursera | cd583050cf6e489bc2fdedd1c3876fb3319e2bb1 | 37e678f5878f9240b9d6f8ad6f7e0bacc8dd07ef | ff9a9918018e06c9a22e2bdd36aaa5687c216daf | refs/heads/master | 2015-08-11T15:56:32.932540 | 2014-11-07T04:15:30 | 2014-11-07T04:15:30 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7547862529754639,
"alphanum_fraction": 0.7697350978851318,
"avg_line_length": 39.54255294799805,
"blob_id": "5351f1b21fc85bb4d720976f97386c6ca1897f6e",
"content_id": "668838c2d4f36423c8d5e6cf53c92e295f08317b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3813,
"license_type": "no_license",
"max_line_length": 653,
"num_lines": 94,
"path": "/getdataCourseProject/CodeBook.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "# Human Activity Recognition Using Smartphones Dataset (Version 1.0) \n### Adopted from John Hopkins Coursera Get and Clean Data course \n## Data Citation: \n[1] Davide Anguita, Alessandro Ghio, Luca Oneto, Xavier Parra and Jorge L. Reyes-Ortiz. Human Activity Recognition on Smartphones using a Multiclass Hardware-Friendly Support Vector Machine. International Workshop of Ambient Assisted Living (IWAAL 2012). Vitoria-Gasteiz, Spain. Dec 2012 \n[Source Web Site](http://www.smartlab.ws) \n\n## Abstract \n[Excert from the SmartLab](https://sites.google.com/site/smartlabunige/software-datasets/har-dataset)\nThe experiments have been carried out with a group of 30 volunteers within an age bracket of 19-48 years. Each person performed six activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING) wearing a smartphone (Samsung Galaxy S II) on the waist. Using its embedded accelerometer and gyroscope, we captured 3-axial linear acceleration and 3-axial angular velocity at a constant rate of 50Hz. The experiments have been video-recorded to label the data manually. The obtained dataset has been randomly partitioned into two sets, where 70% of the volunteers was selected for generating the training data and 30% the test data. \n\n## Attributes of Original Dataset: \n- Triaxial acceleration from the accelerometer (total acceleration) and the estimated body acceleration.\n- Triaxial Angular velocity from the gyroscope. \n- A 561-feature vector with time and frequency domain variables. \n- Six activity label. \n- An identifier of the subject who carried out the experiment.\n\n## Tidy Dataset Processed Steps \n**(Instructions provided by course project page)**: \n1. Merges the training and the test sets to create one data set. \n2. Extracts only the measurements on the mean and standard deviation for each measurement. \n3. Uses descriptive activity names to name the activities in the data set. \n4. Appropriately labels the data set with descriptive variable names. \n5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject. \n\n## Code Book: \n### Activity\n>ACTIVITIES MEASURED BY SMART PHONE SENSORS\n\nVALUE LABEL \n\n1. WALKING\n2. WALKING_UPSTAIRS\n3. WALKING_DOWNSTAIRS\n4. SITTING\n5. STANDING\n6. LAYING\n\nDataType: Categorical, encoding as integer. \n### SubjectID \n>IDENTIFIER FOR PARTICIPANT SUBJECTS \n\nDataType: Numeric, range from 1 to 30\n\n### DomainSignal \n>THE DOMAIN IN WHICH FEATURES ARE COLLECTED \n\n1. Time: time domain \n2. Frequency: frequency domain (after Fast Fourier Transform) \n\nDataType: Categorial, encoding as integer \n\n### Apparutus \n>THE APPARUTUS USED FOR MEASURMENT \n\n1. Accelerometer \n2. Gyroscope \n\nDataType: Categorial, encoding as integer \n\n### SignalType \n>WHICH ACCELERATION SIGNAL (BODY, GRAVITY, OR JERK) \n\n1. Body: Body acceleration signals \n2. Gravity: Gravity acceleration signals \n3. Jerk: Jerk signals obtained by the body linear acceleration and angular velocity measured in time \n\nDataType: Categorial, encoding as integer \n\n*Note: There is fBodyBody(Gyro|Acc)JerkMag features in features.txt. Should be typo and need to be classified as Jerk signal type.* \n\n### MeasurementType \n>MEASUREMENT METHODS AS MEAN OR STANDARD DEVIATION \n\n1. MEAN: Mean value\n2. STD: Standard deviation \n3. MEANFREQ: Weighted average of the frequency components to obtain a mean frequency \n\nDataType: Categorial, encoding as integer \n\n### Direction \n>WHICH DIRECTION OR MAGNITUDE CALCULATED BY THE EUCLIDEAN NORM IS MEASURED \n\n1. X\n2. Y\n3. Z\n4. Magnitude: The magnitude of these three-dimensional signals were calculated using the Euclidean norm \n\nDataType: Categorial, encoding as integer \n\n### Average \n>THE AVERAGE MEASURED VALUES \n\nDataType: numeric, no missing value present \n\n"
},
{
"alpha_fraction": 0.599580705165863,
"alphanum_fraction": 0.6226415038108826,
"avg_line_length": 42.3636360168457,
"blob_id": "03beea3ca827a20da7c6a4a895a30d796ea9e58b",
"content_id": "eab35ce3e4eadd80a05faed4f69f7a17483c3158",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 477,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 11,
"path": "/ExData_Plotting1/plot3.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plotSubMeter<-function(x, genPNG=TRUE, ...){\n\tcolors<-c(\"black\",\"red\",\"blue\");\n\twith(x, plot(Sub_metering_1~Date, type=\"l\", col=colors[1], ylab=\"Energy sub metering\", xlab=\"\"));\n\twith(x, lines(Sub_metering_2~Date, type=\"l\", col=colors[2]));\n\twith(x, lines(Sub_metering_3~Date, type=\"l\", col=colors[3]));\n\tlegend(x=\"topright\", legend=names(x)[7:9], lty=1, col=colors,...);\n if(genPNG){\n\t\tdev.copy(png,file=\"./figure/plot3.png\", pointsize = 8);\n\t\ton.exit(dev.off());\n\t}\n}\n"
},
{
"alpha_fraction": 0.6516393423080444,
"alphanum_fraction": 0.6618852615356445,
"avg_line_length": 43.3636360168457,
"blob_id": "f3655e54c0c67cde852a0429b583c6be8e3b5dc1",
"content_id": "3cdc3c28165b5e0b9425d912f3087027cb0d330a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 488,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 11,
"path": "/ExData_Plotting1/plot4.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plotAll<-function(x){\n if(!exists(\"plotLine\")) source(\"plot2.R\");\n if(!exists(\"plotSubMeter\")) source(\"plot3.R\");\n par(mfcol=c(2,2));\n plotLine(x, genPNG=FALSE);\n plotSubMeter(x, genPNG=FALSE, bty=\"n\");\n with(x, plot(Voltage~Date, type=\"l\", xlab=\"datetime\", ylab=\"Voltage\"));\n with(x, plot(Global_reactive_power~Date, type=\"l\", xlab=\"datetime\", ylab=\"Global_reactive_power\"), ylim=range(Global_reactive_power)); \n dev.copy(png,file=\"./figure/plot4.png\");\n on.exit(dev.off());\n}\n"
},
{
"alpha_fraction": 0.6355555653572083,
"alphanum_fraction": 0.6399999856948853,
"avg_line_length": 31.14285659790039,
"blob_id": "6ded1037bfea5cfdf9a829883fc8a182e12aaa1b",
"content_id": "88dc37b305b5f4b3d687647227580577b677ac1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 225,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 7,
"path": "/ExData_Plotting1/plot2.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plotLine<-function(x, genPNG=TRUE){\n with(x, plot(Global_active_power~Date, type=\"l\", ylab=\"Global Active Power (kilowatts)\", xlab=\"\"));\n if(genPNG){\n \tdev.copy(png,file=\"./figure/plot2.png\");\n \ton.exit(dev.off());\n }\n}\n"
},
{
"alpha_fraction": 0.6178175806999207,
"alphanum_fraction": 0.6336320638656616,
"avg_line_length": 35.480770111083984,
"blob_id": "7629d78b07fdeb1ca9b528a0e5e636b99c4ef7eb",
"content_id": "1841a76f6873053035db5a398252e29c7f73e57a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 1897,
"license_type": "no_license",
"max_line_length": 182,
"num_lines": 52,
"path": "/ExData_Plotting1/readdata.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "## main function to generate png figures\nmainfunc<-function(filename = \"\"){\n defaultlocale<-Sys.getlocale(\"LC_TIME\");\t\n on.exit(Sys.setlocale(\"LC_TIME\",defaultlocale));\n Sys.setlocale(\"LC_TIME\",\"en_US.UTF-8\")\n require(dplyr);\n require(data.table);\n source(\"plot1.R\");\n source(\"plot2.R\");\n source(\"plot3.R\");\n source(\"plot4.R\");\n filename<-ifelse(filename == \"\", \"household_power_consumption.txt\", filename);\n powerconsum <- freadata(filename); \n powerconsum <- process(powerconsum, colnames);\n ## calling plot1.R\n if(exists(\"plotHist\")) plotHist(powerconsum); \n ## calling plot2.R\n if(exists(\"plotLine\")) plotLine(powerconsum);\n ## calling plot3.R\n if(exists(\"plotSubMeter\")) plotSubMeter(powerconsum); \n ## calling plot4.R\n if(exists(\"plotAll\")) plotAll(powerconsum);\n return(powerconsum);\n}\n## processing data, combine date and time\nprocess<-function(x, colnames){\n x<-select(mutate(x, Date=paste(Date, Time, sep=\" \"),Date=as.POSIXct(Date, \"%d/%m/%Y %X\",tz=\"GMT\")),Date:Sub_metering_3);\n x<-mutate(x, weekdays=weekdays(Date, abbreviate=TRUE));\n return(x);\n}\n## freadata way\nfreadata<-function(filename = \"\"){\n powerconsum<-tbl_df(fread(paste(\"grep -e \\'^[A-Z,a-z]\\\\|^[1,2]/2/2007\\'\", filename), header=TRUE, na.strings = \"?\", sep=\";\", colClasses=c(rep(\"character\",2), rep(\"numeric\",7))));\n return(powerconsum);\n}\n## looping way\nreaddata<-function(filename = \"\"){\n fh<-file(filename,\"r\");\n contents <- character();\n record <- readLines(fh, n = 1);\n while(length(record)){\n if(grepl(\"^[1,2]/2/2007\",record)){\n\t\tcontents<-rbind(contents, record);\n\t}\n\trecord<-readLines(fh, n = 1);\n }\n powerconsum<-tbl_df(read.table(text = contents, na.strings = \"?\", sep=\";\", colClasses=c(rep(\"character\",2), rep(\"numeric\",7))));\n close(fh);\n return(powerconsum);\n} \n## execute mainfunc\n#mainfunc();\n"
},
{
"alpha_fraction": 0.6454043388366699,
"alphanum_fraction": 0.7056755423545837,
"avg_line_length": 89.5,
"blob_id": "3c16aa84c7b3129c3cd703a9000c8219b3b13917",
"content_id": "4668b974e34d5a9732579feec56bd6ee0209d522",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3982,
"license_type": "no_license",
"max_line_length": 497,
"num_lines": 44,
"path": "/statinference-PeerAssignment/statCourseProjectA1.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "# Statistical Inference Course Project\nRene Wang \n9/21/2014 \n\n### Assignment Part 1 \n#####Assignment Description \nThe exponential distribution can be simulated in R with rexp(n, $\\lambda$) where $\\lambda$ is the rate parameter. The mean of exponential distribution is $\\frac{1}{\\lambda}$ and the standard deviation is also also $\\frac{1}{\\lambda}$. Set $\\lambda = 0.2$ for all of the simulations. Illustrate via simulation and associated explanatory text the properties of the distribution of the mean of 40 exponential(0.2)s. \n**Goals** \n\n1. Show where the distribution is centered at and compare it to the theoretical center of the distribution.\n2. Show how variable it is and compare it to the theoretical variance of the distribution.\n3. Show that the distribution is approximately normal.\n4. Evaluate the coverage of the confidence interval for $\\frac{1}{\\lambda}=\\bar X \\pm 1.96 \\frac{S}{\\sqrt{n}}$\n\n#####Result \nFirst, I would like to validate if sample size 40 is feasible for this simulation. The left figure is the theoretical distribution which use $\\lambda = 0.2$ as the rate parameter. We can see when x within the range 0 - 20 occurs with higher probabilites; The right figure is a rather simple example to illustrate how sample mean fluctuates with sample size. The actual theoretical mean is 5 ($\\frac{1}{\\lambda}$). We can see that n = 40 is fairly proper sample size to estimate theoretical mean. \n\n<img src=\"figures/preanlyz.png\" title=\"plot of chunk preanlyz\" alt=\"plot of chunk preanlyz\" style=\"display: block; margin: auto;\" />\n\nI used sample size = 40 and conducted 1,000 and 10,000 simulations. I ploted the normal distribution in bold black line by centering at $\\frac{1}{\\lambda}$ with sample standard deviation which equals to population standard deviation ($\\sigma=\\frac{1}{\\lambda}$) divided by the square root of sample size. $\\frac{\\sigma}{\\sqrt(n)}$. And the estimated confidence interval is marked as red dashed lines. \n\n<img src=\"figures/expsim.png\" title=\"plot of chunk expsim\" alt=\"plot of chunk expsim\" style=\"display: block; margin: auto;\" />\n\nAs we can see in the above figures, the distribution of sample mean is fairly close to normal. And I compare the two simulation results in the following table. \n\n| # of replicates | Simulation Center (Median) | Estimated Sample Mean (Error) | Standard Error | Sample SD | Estimated Sample Variance (Error) | Confidence Interval |\n|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|\n|1000|5.009|5.043 ( 0.043465)|0.7915| 0.7906|25.68 ( 0.68415)|[ 3.492 , 6.595 ]| \n|10000|4.962|5.004 ( 0.004124)|0.7855| 0.7906|24.97 ( 0.02791)|[ 3.465 , 6.544 ]| \n\nAs expected, greater number of replicates would give close sample mean and variance estimation. The distribution is less variable and much closer to normal distribution.\n\n<img src=\"figures/extra.png\" title=\"plot of chunk extra\" alt=\"plot of chunk extra\" style=\"display: block; margin: auto;\" />\n\nI also wonder if the simulation result will be similar if I increase the sample size but decrease number of replicates. The result is shown in the following. \n\n| # of replicates | # of sample size | Simulation Center (Median) | Estimated Sample Mean (Error) | Standard Error | Sample SD | Estimated Sample Variance (Error) | Confidence Interval |\n|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|\n|1000|40|5.009|5.043 ( 0.043465)|0.7915| 0.7906|25.68 ( 0.68415)|[ 3.492 , 6.595 ]| \n|40|100|4.801|4.837 ( 0.163144)|0.5782| 0.50|23.27 ( 1.73033)|[ 3.704 , 5.970 ]|\n\nAs you can see in the above table. The greater sample size can introduce strict confidence interval and less variable. But overall speaking, it is not very helpful to estimate sample mean. \n\nThe souce code can be available in [statCourseProjectA1.md](https://github.com/renewang/datasciencecoursera/blob/master/statinference-PeerAssignment/statCourseProjectA1.md)\n"
},
{
"alpha_fraction": 0.7132353186607361,
"alphanum_fraction": 0.7279411554336548,
"avg_line_length": 37.85714340209961,
"blob_id": "977d00ae6134082e753d6c02e3aec979064f114e",
"content_id": "0979b9de50b5143844e44f9ccce52064cb805344",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 544,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 14,
"path": "/ExData_Plotting2/plot5.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot5<-function(code = \"24510\", srcLnum=1, srcLname=\"Mobile\", pngfilename=\"plot5.png\"){\n\tsource('procdata.R');\n\tproc <- procdata();\n\tNEI <- proc$getNEI();\n\tSCCD <- proc$getSCCD();\n\tPMESrcLevel <- FilterEmitBySrcLevel(NEI, SCCD, srcLnum, srcLname);\n\tPMEmitbyCY <- FilterByCounty(PMESrcLevel, code);\n\tPMEmitbyYear <- SumByYear(group_by(PMEmitbyCY, year));\t\t\n\tplotTTLEmitByYear(PMEmitbyYear, pngfilename, sub=\"From Motor Vehicle sources in Baltimore City\");\n\t#plot SCC.Level.One\n\t#plot SCC.Level.Two\n\t#plot SCC.Level.Three\n\t#plot SCC.Level.Four\n}\n"
},
{
"alpha_fraction": 0.7686148881912231,
"alphanum_fraction": 0.7710168361663818,
"avg_line_length": 82.13333129882812,
"blob_id": "784d71896d495c7f15aa8b4174a0971e01c6d859",
"content_id": "06cbb3ca21a93fdd20936e8eec12abb21ce01863",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1249,
"license_type": "no_license",
"max_line_length": 251,
"num_lines": 15,
"path": "/getdataCourseProject/README.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "### Getting and Cleaning Data Course Project\nThis file explains how all of the scripts work and how they are connected.\n### Execution\n**ensure the source script and data are in the same directory** \nsource('run_analysis.R', chdir=TRUE); \ntidydata<-run_analysis(); \n### Program\nThe main program in run_analysis.R which contains two functions. In the main function run_analysis, the data will be loaded and processed the original variable names as meaningful variable name and values according to the CodeBook (see CodeBook.md). \n### File Content/Check list \n1. A tidy data set \n [x] upload your data set as a txt file created with write.table() using row.name=FALSE. (Store as **[tidydata.txt](https://github.com/renewang/datasciencecoursera/blob/master/getdataCourseProject/tidydata.txt)**)\n2. A link to a Github repository with your script for performing the analysis \n [x] [Where you are!](https://github.com/renewang/datasciencecoursera/getdataCourseProject)\n3. A code book that describes the variables, the data, and any transformations or work that you performed to clean up the data called CodeBook.md. \n [x] Please see [CodeBook.md](https://github.com/renewang/datasciencecoursera/blob/master/getdataCourseProject/CodeBook.md) \n"
},
{
"alpha_fraction": 0.681614339351654,
"alphanum_fraction": 0.6860986351966858,
"avg_line_length": 43.599998474121094,
"blob_id": "04ad5128e9b2820c6aded674bc83fe7241e387e7",
"content_id": "6c729238914d462659d9322d4d04238d797d3992",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 223,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 5,
"path": "/ExData_Plotting1/plot1.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plotHist<-function(x){\n\twith(x, hist(Global_active_power, main = \"Global Active Power\", xlab=\"Global Active Power (kilowatts)\", ylab=\"Frequency\",col=\"red\"));\n\tdev.copy(png,file=\"./figure/plot1.png\");\n\ton.exit(dev.off());\n}\n"
},
{
"alpha_fraction": 0.6251915693283081,
"alphanum_fraction": 0.6512411832809448,
"avg_line_length": 36.5057487487793,
"blob_id": "d6469bd26a1a65acaf98160598e982637c1aaf1d",
"content_id": "62c795fe317a10810e3f60bd0dc23c9a98b6e8d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 3263,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 87,
"path": "/statinference-PeerAssignment/statsim.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "statsim<-function(){\n require(ggplot2)\n calstat<-function(n, lambda){\n samp<-rexp(n, lambda);\n #return(c(mean(samp),var(samp), min(samp), max(samp)))\n return(c(mean(samp),var(samp)));\n };\n #set.seed(5); #for debugging\n lambda <- 0.2;\n # plot distribution of exp(1/lambda);\n x<-10^seq(-3,2,length.out=1000);\n plot(x, dexp(x, lambda), type=\"l\");\n # plot running means\n n <- 100;\n runsamp<-rexp(n, lambda); \n runmeans<-cumsum(runsamp)/seq_along(runsamp);\n plot(seq_along(runsamp),runmeans, type=\"l\");\n abline(h=(1/lambda), col=\"red\", lty=2, lwd=3);\n n <- 40;\n analysis<-function(numofrep){\n represult<-replicate(numofrep, calstat(n, lambda));\n #1a. Show where the distribution is centered at \n #1b. compare it to the theoretical center of the distribution\n midofsim<-median(represult[1,]);\n meanofsim<-mean(represult[1,]);\n # compare with theoretical mean (1/lambda)\n # calculate error terms\n cenerror <- abs(midofsim - meanofsim);\n barerror <- abs(meanofsim - 1/lambda);\n se <- sd(represult[1,]);\n #2. compare with theoretical varation (1/lambda)\n varofsim<-var(represult[1,]);\n mse <- sqrt((represult[1,] - 1/lambda)^2);\n estofvar<-mean(represult[2,]);\n # compare with theoretical var (1/lambda)^2\n # calculate error terms\n estvarerror<-abs(estofvar-(1/lambda)^2);\n mse2 <- sqrt((represult[2,] - (1/lambda)^2)^2);\n #3. Show that the distribution is approximately normal.\n ## qqplot + hist\n qqnorm(represult[1,], col=\"blue\");\n qqline(represult[1,],col=\"red\");\n z<-seq(2,8,length.out=1000);\n p<-dnorm(z, mean=1/lambda, sd=sqrt(varofsim));\n hist(represult[1,], freq=FALSE, breaks=20, col=\"lightblue\");\n lines(z, p, lwd=3);\n #4. Evaluate the coverage of thee confidence interval for 1/lambda\n conf <- meanofsim + c(-1, 1)*1.96*se/sqrt(numofrep);\n abline(v=conf[1], col=\"red\", lty=2, lwd=3);\n abline(v=conf[2], col=\"red\", lty=2, lwd=3);\n }\n # trying different replicate number\n repnum <- c(1000, 10000);\n for(i in seq_along(repnum)){\n analysis(repnum[i]);\n }\n}\nhtanalysis<-function(){\n require(dplyr);\n require(ggplot2);\n data(ToothGrowth);\n # perform some basic exploratory data analyses \n ToothGrowth$dose <- as.factor(ToothGrowth$dose);\n ToothGrowth<-tbl_df(ToothGrowth);\n summary(ToothGrowth);\n ToothGrowth<-group_by(ToothGrowth, dose, supp);\n #blox plot here\n with(ToothGrowth, boxplot(len~supp));\n with(ToothGrowth, boxplot(len~dose));\n # plot dose*supp (3*2) groups\n ggplot(ToothGrowth,aes(x=interaction(supp,dose), y=len))+geom_boxplot(); \n #2. Provide a basic summary of the data.\n ToothTable<-summarize(ToothGrowth, sum=sum(len), mean=mean(len), \n std=sd(len), num=length(len));\n #3. hypothesis tests\n # paired t on different supplements\n # mixed \n t.test(x=filter(ToothGrowth, supp==\"VC\")$len, \n y=filter(ToothGrowth, supp==\"OJ\")$len, var.equal=TRUE);\n testfunc<-function(amount, obj=ToothGrowth){\n x<-filter(obj, supp==\"VC\" & dose==amount)$len;\n y<-filter(obj, supp==\"OJ\" & dose==amount)$len;\n return(unclass(t.test(x, y, var.equal=TRUE)));\n }\n # test supp method difference given the same dose level\n testresult <-sapply(as.list(levels(ToothGrowth$dose)), testfunc);\n}\n"
},
{
"alpha_fraction": 0.6436766386032104,
"alphanum_fraction": 0.6710560917854309,
"avg_line_length": 58.0076904296875,
"blob_id": "72496de68ca35d4f331441e0222c6fa800b69c5a",
"content_id": "d0e19fb1a46d9af7826741c2295ebfdf4d116deb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "RMarkdown",
"length_bytes": 7670,
"license_type": "no_license",
"max_line_length": 497,
"num_lines": 130,
"path": "/statinference-PeerAssignment/statCourseProjectA1.Rmd",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Statistical Inference Course Project\"\nauthor: \"Rene Wang\"\ndate: \"9/21/2014\"\noutput:\n html_document:\n keep_md: yes\n pdf_document:\n keep_tex: yes\n---\n```{r defaultsetting, echo=FALSE, message=FALSE}\nrequire(knitr);\nrequire(dplyr);\nrequire(ggplot2);\nopts_chunk$set(echo=TRUE, message=FALSE, tidy=FALSE, comment=NA,\n fig.path=\"figures/\", fig.keep=\"high\", fig.align=\"center\",\n fig.show=\"asis\", fig.width = 8, fig.height = 5, dev=\"png\");\n#defaultpar<-par();\n#on.exit(par(defaultpar));\n#opts_knit$set(verbose=TRUE, latex.option.graphicx=\"graphicx\");\n```\n### Assignment Part 1 \n#####Assignment Description \nThe exponential distribution can be simulated in R with rexp(n, $\\lambda$) where $\\lambda$ is the rate parameter. The mean of exponential distribution is $\\frac{1}{\\lambda}$ and the standard deviation is also also $\\frac{1}{\\lambda}$. Set $\\lambda = 0.2$ for all of the simulations. Illustrate via simulation and associated explanatory text the properties of the distribution of the mean of 40 exponential(0.2)s. \n**Goals** \n\n1. Show where the distribution is centered at and compare it to the theoretical center of the distribution.\n2. Show how variable it is and compare it to the theoretical variance of the distribution.\n3. Show that the distribution is approximately normal.\n4. Evaluate the coverage of the confidence interval for $\\frac{1}{\\lambda}=\\bar X \\pm 1.96 \\frac{S}{\\sqrt{n}}$\n\n#####Result \nFirst, I would like to validate if sample size 40 is feasible for this simulation. The left figure is the theoretical distribution which use $\\lambda = 0.2$ as the rate parameter. We can see when x within the range 0 - 20 occurs with higher probabilites; The right figure is a rather simple example to illustrate how sample mean fluctuates with sample size. The actual theoretical mean is 5 ($\\frac{1}{\\lambda}$). We can see that n = 40 is fairly proper sample size to estimate theoretical mean. \n\n```{r preanlyz}\n calstat<-function(n, lambda){\n samp<-rexp(n, lambda);\n #return(c(mean(samp),var(samp), min(samp), max(samp)))\n return(c(mean(samp),var(samp)));\n };\n set.seed(5); #for debugging\n lambda <- 0.2;\n par(mfrow=c(1,2));\n # plot distribution of exp(1/lambda);\n x<-10^seq(-3,1.5,length.out=1000);\n plot(x, dexp(x, lambda), type=\"l\", ylab=\"Density of Exponential with lambda=0.2\"\n ,main=\"The Theoretical Distribution\");\n # plot the running means\n n <- 100;\n runsamp<-rexp(n, lambda);\n plot(x=seq_along(runsamp), y=cumsum(runsamp)/seq_along(runsamp), \n type=\"l\", col=\"blue\", xlab=\"sample size\", ylab=\"sample mean\",\n main=\"Impact on Sample Size\");\n abline(h=(1/lambda), col=\"red\", lty=2, lwd=3);\n #mtext(text=\"\", side=4, col=\"red\", outer=TRUE);\n```\n\nI used sample size = 40 and conducted 1,000 and 10,000 simulations. I ploted the normal distribution in bold black line by centering at $\\frac{1}{\\lambda}$ with sample standard deviation which equals to population standard deviation ($\\sigma=\\frac{1}{\\lambda}$) divided by the square root of sample size. $\\frac{\\sigma}{\\sqrt(n)}$. And the estimated confidence interval is marked as red dashed lines. \n\n```{r expsim}\n n <- 40;\n par(mfrow=c(2,2));\n analysis<-function(numofrep, n){\n represult<-replicate(numofrep, calstat(n, lambda));\n #1a. Show where the distribution is centered at \n #1b. compare it to the theoretical center of the distribution\n midofsim<-median(represult[1,]);\n meanofsim<-mean(represult[1,]);\n # compare with theoretical mean (1/lambda)\n # calculate error terms\n cenerror <- abs(midofsim - meanofsim);\n barerror <- abs(meanofsim - 1/lambda);\n # standard error\n ese<-1/(lambda*sqrt(n));\n se<-sd(represult[1,]);\n #2. compare with theoretical varation (1/lambda)\n varofsim<-var(represult[1,]);\n mse <- sqrt((represult[1,] - 1/lambda)^2);\n estofvar<-mean(represult[2,]);\n # compare with theoretical var (1/lambda)^2\n # calculate error terms\n estvarerror<-abs(estofvar-(1/lambda)^2);\n mse2 <- sqrt((represult[2,] - (1/lambda)^2)^2);\n z<-seq(2,8,length.out=1000);\n p<-dnorm(z, mean=1/lambda, sd=ese);\n conf <- meanofsim + c(-1, 1)*1.96*se;\n #3. Show that the distribution is approximately normal.\n #qqplot + hist\n qqnorm(represult[1,], col=\"blue\");\n qqline(represult[1,],col=\"red\");\n hist(represult[1,], freq=FALSE, breaks=\"scott\", col=\"lightblue\", xlab=\"Sample Mean\", main=paste(numofrep,\"Simulations\"));\n lines(z, p, lwd=3);\n #4. Evaluate the coverage of thee confidence interval for 1/lambda\n abline(v=conf[1], col=\"red\", lty=2, lwd=3);\n abline(v=conf[2], col=\"red\", lty=2, lwd=3);\n return(data.frame(replicate=numofrep, sampsize=n, mid=midofsim, mean=meanofsim, center=cenerror, bar=barerror, se=se, var=estofvar, varerr=estvarerror,conf1=conf[1],conf2=conf[2]));\n }\n repnum <- c(1000, 10000);\n report<-data.frame();\n for(i in seq_along(repnum)){\n report<-rbind(report, analysis(repnum[i], n));\n }\n freport<-format(report, nsmall=2);\n```\n\nAs we can see in the above figures, the distribution of sample mean is fairly close to normal. And I compare the two simulation results in the following table. \n\n| # of replicates | Simulation Center (Median) | Estimated Sample Mean (Error) | Standard Error | Sample SD | Estimated Sample Variance (Error) | Confidence Interval |\n|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|\n|`r report$replicate[1]`|`r freport$mid[1]`|`r freport$mean[1]` ( `r freport$bar[1]`)|`r freport$se[1]`| `r format(1/(lambda*sqrt(report$sampsize[1])),nsmall=2)`|`r freport$var[1]` ( `r freport$varerr[1]`)|[ `r freport$conf1[1]` , `r freport$conf2[1]` ]| \n|`r format(report$replicate[2], scientific=FALSE)`|`r freport$mid[2]`|`r freport$mean[2]` ( `r freport$bar[2]`)|`r freport$se[2]`| `r format(1/(lambda*sqrt(report$sampsize[2])),nsmall=2)`|`r freport$var[2]` ( `r freport$varerr[2]`)|[ `r freport$conf1[2]` , `r freport$conf2[2]` ]| \n\nAs expected, greater number of replicates would give close sample mean and variance estimation. The distribution is less variable and much closer to normal distribution.\n\n```{r extra}\n par(mfrow=c(1,2));\n report<-rbind(report, analysis(40,100));\n freport<-format(report, nsmall=2);\n```\n\nI also wonder if the simulation result will be similar if I increase the sample size but decrease number of replicates. The result is shown in the following. \n\n| # of replicates | # of sample size | Simulation Center (Median) | Estimated Sample Mean (Error) | Standard Error | Sample SD | Estimated Sample Variance (Error) | Confidence Interval |\n|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|:-----------:|\n|`r report$replicate[1]`|`r report$sampsize[1]`|`r freport$mid[1]`|`r freport$mean[1]` ( `r freport$bar[1]`)|`r freport$se[1]`| `r format(1/(lambda*sqrt(report$sampsize[1])),nsmall=2)`|`r freport$var[1]` ( `r freport$varerr[1]`)|[ `r freport$conf1[1]` , `r freport$conf2[1]` ]| \n|`r report$replicate[3]`|`r report$sampsize[3]`|`r freport$mid[3]`|`r freport$mean[3]` ( `r freport$bar[3]`)|`r freport$se[3]`| `r format(1/(lambda*sqrt(report$sampsize[3])),nsmall=2)`|`r freport$var[3]` ( `r freport$varerr[3]`)|[ `r freport$conf1[3]` , `r freport$conf2[3]` ]|\n\nAs you can see in the above table. The greater sample size can introduce strict confidence interval and less variable. But overall speaking, it is not very helpful to estimate sample mean. \n\nThe souce code can be available in [statCourseProjectA1.md](https://github.com/renewang/datasciencecoursera/blob/master/statinference-PeerAssignment/statCourseProjectA1.md)"
},
{
"alpha_fraction": 0.6789297461509705,
"alphanum_fraction": 0.6822742223739624,
"avg_line_length": 26.18181800842285,
"blob_id": "e3dd4c17a3aa60a6d7a101bbd3fb1f684f60fd52",
"content_id": "8686241d7e061d5ba81eb54bce0a37763a1fb5eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 299,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 11,
"path": "/repdataPeerAssignment2/extractPDF.py",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "import sys;\nfrom pyPDF2 import *;\n\ndef main(filename, pagenumi, startword, stopword):\n myreader = PdfFileReader(filename);\n page = myreader.getPage(pagenum);\n content = extractText();\n events = content[content.find(startword):content.find(stopword)]\n\nif __name__ == '__main__': \n main();\n"
},
{
"alpha_fraction": 0.6585983633995056,
"alphanum_fraction": 0.6726744771003723,
"avg_line_length": 52.70399856567383,
"blob_id": "6316e1e2d32a43937fee7b5c802dede2759bc05b",
"content_id": "7616753032d0f190d4a94ee6c8967e0d8cd3c947",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 13427,
"license_type": "no_license",
"max_line_length": 724,
"num_lines": 250,
"path": "/repdataPeerAssignment1/PA1_template.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Reproducible Research\"\nsubtitle: \"Peer Assessment 1\"\nauthor: \"Rene Wang\"\ndate: \"09/09/2014\"\nkeepmd: true\noutput: html_document\n---\n\n###Introduction: \n**Personal activity monitoring** is thriving through the use of smart phones and wearable devices. It raises *the awareness of personal health* through collecting and analyzing daily activity pattern. In this assignment, a data set was collectcted from an anonymous person whose daily activities were recorded in 5 minute interval from Octorber to November 2012.\n\n[The git source of assignment](https://github.com/rdpeng/RepData_PeerAssessment1)\n\n## Loading and preprocessing the data\n### Information of data \n* File name: activity.csv \n* Variables included in this dataset are: \n -**steps**: Number of steps taking in a 5-minute interval \n -**date**: The date on which the measurement was taken in YYYY-MM--DD format \n -**interval**: Identifier for the 5-minute interval in which measurement was taken \n\n```r\n filename<-'activity.csv';\n if(!file.exists(filename)){\n zipurl<-\"https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip\";\n download.file(zipurl, destfile=\"activity.zip\", method=\"curl\");\n datedownload<-date();\n unzip(\"activity.zip\");\n }\n activity<-read.csv(filename,header=TRUE, colClasses= c(\"numeric\",\"Date\",\"numeric\"));\n good<-complete.cases(activity);\n cleanactivity<-activity[good,];\n```\n\n## What is mean total number of steps taken per day?\n#### Figure: \nA histogram of the total number of steps taken each day is shown: \n\n```r\n ## group data\n stepsumbydate<-ddply(cleanactivity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n ## Make a histogram of the total number of steps taken each day\n ggplot(stepsumbydate,aes(sum.steps))+geom_histogram(stat=\"bin\")+\n labs(list(title=\"Histogram of Total Sum of Steps per day (NA imputing)\",\n x=\"Sum of steps per day\", y=\"Count\"))+\n theme(title=element_text(size=14));\n```\n\n<img src=\"figures/sumhist.png\" title=\"plot of chunk sumhist\" alt=\"plot of chunk sumhist\" style=\"display: block; margin: auto;\" />\n\n```r\n ## Calculate the mean and median of total steps per day\n meanofdaystepsum<-mean(stepsumbydate$sum.step,na.rm=TRUE);\n medianofdaystepsum<-median(stepsumbydate$sum.step,na.rm=TRUE);\n```\n\n\n\n#### Report Mean and Median: \nThe mean of total steps taken per day is **10766.19** and median of total steps taken per day is **10765.00** when NA cases are completely removed. \n\n## What is the average daily activity pattern? \nTwo figures below show: \n1. A time series plot of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis). \n2. The plot of mean and median time series plots of the 5-minute interval across all days. \n\n\n```r\n ## make time series plot of the 5-minute interval\n stepsumbyint<-ddply(cleanactivity, .(interval), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n \n ggplot(stepsumbyint,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval without Missing Value Replacement\",\n x=\"time\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14));\n```\n\n<img src=\"figures/timeseries1.png\" title=\"plot of chunk timeseries\" alt=\"plot of chunk timeseries\" style=\"display: block; margin: auto;\" />\n\n```r\n maxinterval<- which.max(stepsumbyint$mean.steps);\n maxintminute<-stepsumbyint[maxinterval,1];\n maxsteps<-format(stepsumbyint[maxinterval,3],nsamll=2);\n\n ## Calculate the median of steps per 5-minute interval\n stepmeasurebyint<-cbind(stack(stepsumbyint[,3:4],),stepsumbyint$interval);\n colnames(stepmeasurebyint)<-c(\"values\",\"type\",\"interval\");\n ggplot(stepmeasurebyint,aes(x=interval,y=values,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean/Median of Steps Every 5 minute interval without Missing Value Replacement\",\n x=\"time\", y=\"Mean/Median of steps\"))+\n theme(title=element_text(size=14))+\n scale_color_discrete(name=\"measurement\",labels=c(\"mean\",\"median\"));\n```\n\n<img src=\"figures/timeseries2.png\" title=\"plot of chunk timeseries\" alt=\"plot of chunk timeseries\" style=\"display: block; margin: auto;\" />\n\n```r\n maxmidinterval<- which.max(stepsumbyint$median.steps);\n maxmidminute<-stepsumbyint[maxmidinterval,1];\n maxmidsteps<-format(stepsumbyint[maxmidinterval,4], nsamll=2);\n maxavgsteps<-format(stepsumbyint[maxmidinterval,3], nsamll=2);\n```\n\n### Summary: \n1. On average across all the days in the dataset, the maximum number of steps is **206.2 steps** within **104 th** 5-minute interval, corresponding to time starting at **08:45** (in 24 hour format). \n2. Median shows a shift of 10 minutes (from **08:35** to **08:45**) and from **206.2 steps** to **60 steps** (average steps lowers to **179.6 steps**). \n\n## Imputing missing values\n1. The total number of missing values in the dataset is **2304** ( about **13.115**%) and there are **53** are valid days out of **61**. \n2. Below a historgram of the total number of steps taken each day with different imputing methods are shown: \n\n\n```r\n ## replace missing values with the mean of the same interval\n imputactivitybymean<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n mean(steps, na.rm=TRUE)));\n imputactivitybymid<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n median(steps, na.rm=TRUE)));\n ## use median \n midimputstepsumbydate<-ddply(imputactivitybymid, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n ## use mean\n avgimputstepsumbydate<-ddply(imputactivitybymean, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputactivitybydate<-ddply(activity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps), \n median.steps=median(steps,na.rm=TRUE));\n ## compare histogram\n df<-data.frame(sum.steps=c(imputactivitybydate$sum.steps,avgimputstepsumbydate$sum.steps, \n midimputstepsumbydate$sum.steps),\n mean.steps=c(imputactivitybydate$mean.steps,avgimputstepsumbydate$mean.steps, \n midimputstepsumbydate$mean.steps), \n median.steps=c(imputactivitybydate$median.steps,avgimputstepsumbydate$median.steps,\n midimputstepsumbydate$median.steps), \n date=c(imputactivitybydate$date,avgimputstepsumbydate$date, \n midimputstepsumbydate$date), \n type=c(rep(\"deleting\", nrow(imputactivitybydate)),\n rep(\"mean-replacement\",nrow(avgimputstepsumbydate)),\n rep(\"mid-replacement\",nrow(midimputstepsumbydate))));\n # drawing histogram\n ggplot(df,aes(sum.steps, fill=type, alpha=0.5))+geom_histogram(stat=\"bin\", position=\"dodge\")+\n labs(list(title=\"Histogram of Sum of Steps per day without Missing Value Replacement\",\n x = \"Sum of steps per day\", y=\"Counts\"))+\n theme(title=element_text(size=14));\n```\n\n<img src=\"figures/imputingna.png\" title=\"plot of chunk imputingna\" alt=\"plot of chunk imputingna\" style=\"display: block; margin: auto;\" />\n\n```r\n ## report mean & median\n repmmeandaystepsum<-mean(df[df$type==\"deleting\",\"sum.steps\"]);\n repmmediandaystepsum<-median(df[df$type==\"deleting\",\"sum.steps\"]);\n repameandaystepsum<-mean(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repamedianofdaystepsum<-median(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repdmeandaystepsum<-mean(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n repdmedianofdaystepsum<-median(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n```\n\n### Report Mean and Median with different missing values replacement strategies: \n| Missing Value Replacement Strategies | Mean | Median |\n| :------------------------------------:|:------------------:|:----------------------:|\n| No Imputing Strategy |9354.23|10395.00|\n| Deleting Missing Values |10766.19 |10765.00 |\n| Replace with Mean of 5-min interval |10766.19|10766.19|\n| Replace with Median of 5-min interval |9503.87|10395.00|\n\n### Summary: \n1. Do these values differ from the estimates from the first part of the assignment? \nBecause there are dates on which the collected steps measurements across all time interval are not available, I used two simple strategies to replace missing values with mean or median of the same 5-min interval and compared the result. The difference between these two strategies is small in most of the days. However, for the days with more missing values, using mean replacement tended to give greater values than median (mean value are affected by extreme values as shown in time series plot of the 5-minute interval) and gave similar values as deletion. But mean replacement overesitmate total sum of stpes per day without imputing strategy. Overall speaking, median replacement gives more conservative estimation. \n2. What is the impact of imputing missing data on the estimates of the total daily number of steps? \nThe impact of imputing missing data on the estimates of the total daily number of steps is to over-estimate the total daily number of steps as using mean-replacement strategy. \n\n\n\n## Are there differences in activity patterns between weekdays and weekends?\n\n```r\n ## group by weekday and weekend using mean replacement\n imputactivitybymean$weekday=weekdays(imputactivitybymean[,2]);\n imputactivitybymean$isweekend=imputactivitybymean$weekday==\"Saturday\"|\n imputactivitybymean$weekday==\"Sunday\";\n imputactbymeanweekday<-imputactivitybymean[imputactivitybymean$isweekend==FALSE,];\n imputactbymeanweekend<-imputactivitybymean[imputactivitybymean$isweekend==TRUE,];\n\n imputsumbymeanweekday<-ddply(imputactbymeanweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n\n imputsumbymeanweekend<-ddply(imputactbymeanweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymean<-rbind(imputsumbymeanweekday,imputsumbymeanweekend);\n imputsumbymean$isweekend<-c(rep(\"Weekday\",nrow(imputsumbymeanweekday)),\n rep(\"Weekend\",nrow(imputsumbymeanweekend)));\n\n ggplot(imputsumbymean,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Mean Replacement) over days\",\n x=\"Interval\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n```\n\n<img src=\"figures/compweek1.png\" title=\"plot of chunk compweek\" alt=\"plot of chunk compweek\" style=\"display: block; margin: auto;\" />\n\n```r\n ## group by weekday and weekend using median replacement\n imputactivitybymid$weekday=weekdays(imputactivitybymid[,2]);\n imputactivitybymid$isweekend=imputactivitybymid$weekday==\"Saturday\"|\n imputactivitybymid$weekday==\"Sunday\";\n imputactbymidweekday<-imputactivitybymid[imputactivitybymid$isweekend==FALSE,];\n imputactbymidweekend<-imputactivitybymid[imputactivitybymid$isweekend==TRUE,];\n \n imputsumbymidweekday<-ddply(imputactbymidweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n \n imputsumbymidweekend<-ddply(imputactbymidweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymid<-rbind(imputsumbymidweekday,imputsumbymidweekend);\n imputsumbymid$isweekend<-c(rep(\"Weekday\",nrow(imputsumbymidweekday)),\n rep(\"Weekend\",nrow(imputsumbymidweekend)));\n \n ggplot(imputsumbymid,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Median Replacement) over days\",\n x=\"Interval\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n```\n\n<img src=\"figures/compweek2.png\" title=\"plot of chunk compweek\" alt=\"plot of chunk compweek\" style=\"display: block; margin: auto;\" />\n\n### Summary: \nThe activities during weekends tends to be late in the mornging and also more active in the late hours of evening. But overall trends of both time series curves are similar. Using different missing value replacement strategies does not make any difference by observing the overall trends. \n"
},
{
"alpha_fraction": 0.6534726619720459,
"alphanum_fraction": 0.6589613556861877,
"avg_line_length": 55.73053741455078,
"blob_id": "3b2969c92f5c1fb032e8c6b2ee5dee9dab85c5d7",
"content_id": "0de81e70a0276b4731962989efde602597a474de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 9474,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 167,
"path": "/repdataPeerAssignment1/analysis.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "analysis<-function(filename){\n ## Load the data and process/transform the data into suitable format \n activity<-read.csv(filename,header=TRUE, colClasses=\n c(\"numeric\",\"Date\",\"numeric\"));\n good<-complete.cases(activity);\n cleanactivity<-activity[good,];\n\n ## group data\n stepsumbydate<-ddply(cleanactivity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n \n ## Make a histogram of the total number of steps taken each day\n ggplot(stepsumbydate,aes(x=date,y=sum.steps))+geom_bar(stat=\"identity\")+\n labs(list(title=\"Sum of Steps per day without Missing Value Replacement\",y=\"sum of steps\"))+\n theme(title=element_text(size=14));\n \n ggplot(stepsumbydate,aes(sum.steps))+geom_histogram(stat=\"bin\")+\n labs(list(title=\"Histogram of Total Sum of Steps per day without Missing Value Replacement\",y=\"Frequency\"))+\n theme(title=element_text(size=14));\n \n ## Calculate the mean and median of steps per day\n stepmeasurebydate<-cbind(stack(stepsumbydate[,3:4],),stepsumbydate$date);\n colnames(stepmeasurebydate)<-c(\"values\",\"type\",\"date\");\n ggplot(stepmeasurebydate,aes(x=date,y=values,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean/Median of Steps per day without Missing Value Replacement\",y=\"Mean/Median of steps\"))+\n theme(title=element_texttheme(title=element_text(size=14));\n(size=14))+scale_color_discrete(name=\"measurement\",labels=c(\"mean\",\"median\"));\n \n ## report mean & median\n meanofdaystepsum<-mean(stepsumbydate$sum.step);\n medianofdaystepsum<-median(stepsumbydate$sum.step,na.rm=TRUE);\n \n ## make time series plot of the 5-minute interval\n stepsumbyint<-ddply(cleanactivity, .(interval), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n \n ggplot(stepsumbyint,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval without Missing Value Replacement\",x=\"time (minutes)\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14));\n \n maxinterval<- which.max(stepsumbyint$mean.steps);\n maxintminute<-stepsumbyint[maxinterval,1];\n maxsteps<-format(stepsumbyint[maxinterval,3],digits=5);\n \n ## Calculate the median of steps per 5-minute interval\n stepmeasurebyint<-cbind(stack(stepsumbyint[,3:4],),stepsumbyint$interval);\n colnames(stepmeasurebyint)<-c(\"values\",\"type\",\"interval\");\n ggplot(stepmeasurebyint,aes(x=interval,y=values,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean/Median of Steps Every 5 minute interval without Missing Value Replacement\",x=\"time (minutes)\", y=\"Mean/Median of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"measurement\",labels=c(\"mean\",\"median\"));\n maxmidinterval<- which.max(stepsumbyint$median.steps);\n maxmidminute<-stepsumbyint[maxmidinterval,1];\n maxmidsteps<-format(stepsumbyint[maxmidinterval,4],digits=5);\n maxavgsteps<-format(stepsumbyint[maxmidinterval,3],digits=5);\n \n ## replace missing values with the mean of the same interval\n imputactivitybymean<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n mean(steps, na.rm=TRUE)));\n imputactivitybymid<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n median(steps, na.rm=TRUE)));\n ## use median \n midimputstepsumbydate<-ddply(imputactivitybymid, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n ## use mean\n avgimputstepsumbydate<-ddply(imputactivitybymean, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n\n imputactivitybydate<-ddply(activity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps), \n median.steps=median(steps,na.rm=TRUE));\n ## compare histogram\n df<-data.frame(sum.steps=c(imputactivitybydate$sum.steps,avgimputstepsumbydate$sum.steps, \n midimputstepsumbydate$sum.steps),\n mean.steps=c(imputactivitybydate$mean.steps,avgimputstepsumbydate$mean.steps, \n midimputstepsumbydate$mean.steps), \n median.steps=c(imputactivitybydate$median.steps,avgimputstepsumbydate$median.steps, \n midimputstepsumbydate$median.steps), \n date=c(imputactivitybydate$date,avgimputstepsumbydate$date, \n midimputstepsumbydate$date), \n type=c(rep(\"imputing\", nrow(imputactivitybydate)),\n rep(\"mean-replacement\",nrow(avgimputstepsumbydate)),\n rep(\"mid-replacement\",nrow(midimputstepsumbydate))));\n \n ggplot(df,aes(x=date,y=sum.steps, fill=type, alpha=0.5))+geom_bar(stat=\"identity\",position=\"dodge\")+\n labs(list(title=\"Sum of Steps per day\",y=\"sum of steps\"))+\n theme(title=element_text(size=14))+scale_fill_discrete(name=\"imputing method\");\n \n #drawing histogram\n ggplot(df,aes(sum.steps, fill=type, alpha=0.5))+geom_histogram(stat=\"bin\", position=\"dodge\")+\n labs(list(title=\"Histogram of Sum of Steps per day without Missing Value Replacement\",y=\"Frequency\"))+\n theme(title=element_text(size=14));\n\n ## report mean & median\n repmmeandaystepsum<-mean(df[df$type==\"imputing\",\"sum.steps\"]);\n repmmediandaystepsum<-median(df[df$type==\"imputing\",\"sum.steps\"]);\n repameandaystepsum<-mean(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repamedianofdaystepsum<-median(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repdmeandaystepsum<-mean(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n repdmedianofdaystepsum<-median(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n\n ggplot(df,aes(x=date,y=mean.steps,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps per day\",y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"imputing method\");\n\n ggplot(df,aes(x=date,y=median.steps,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Median of Steps per day\",y=\"Median of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"imputing method\");\n\n ## group by weekday and weekend using mean replacement\n imputactivitybymean$weekday=weekdays(imputactivitybymean[,2]);\n imputactivitybymean$isweekend=imputactivitybymean$weekday==\"Saturday\"|\n imputactivitybymean$weekday==\"Sunday\";\n imputactbymeanweekday<-imputactivitybymean[imputactivitybymean$isweekend==FALSE,];\n imputactbymeanweekend<-imputactivitybymean[imputactivitybymean$isweekend==TRUE,];\n\n imputsumbymeanweekday<-ddply(imputactbymeanweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n\n imputsumbymeanweekend<-ddply(imputactbymeanweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymean<-rbind(imputsumbymeanweekday,imputsumbymeanweekend);\n imputsumbymean$isweekend<-c(rep(\"Weekday\",dim(imputsumbymeanweekday)[1]),\n rep(\"Weekend\",dim(imputsumbymeanweekend)[1]));\n\n ggplot(imputsumbymean,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Mean Replacement) over days\",x=\"time (minutes)\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n \n ## group by weekday and weekend using median replacement\n imputactivitybymid$weekday=weekdays(imputactivitybymid[,2]);\n imputactivitybymid$isweekend=imputactivitybymid$weekday==\"Saturday\"|\n imputactivitybymid$weekday==\"Sunday\";\n imputactbymidweekday<-imputactivitybymid[imputactivitybymid$isweekend==FALSE,];\n imputactbymidweekend<-imputactivitybymid[imputactivitybymid$isweekend==TRUE,];\n \n imputsumbymidweekday<-ddply(imputactbymidweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n \n imputsumbymidweekend<-ddply(imputactbymidweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymid<-rbind(imputsumbymidweekday,imputsumbymidweekend);\n imputsumbymid$isweekend<-c(rep(\"Weekday\",dim(imputsumbymidweekday)[1]),\n rep(\"Weekend\",dim(imputsumbymidweekend)[1]));\n \n ggplot(imputsumbymid,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Median Replacement) over days\",x=\"time (minutes)\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n}\n"
},
{
"alpha_fraction": 0.707732617855072,
"alphanum_fraction": 0.7247706651687622,
"avg_line_length": 68.36363983154297,
"blob_id": "c1cfda3c95db43cd2951221d19538bc3bf945b6b",
"content_id": "ccf64248c797cd7a4df4a76a5521c3e5afefe2c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 1526,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 22,
"path": "/ExData_Plotting2/plot6.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot6<-function(srcLnum=1, srcLname=\"Mobile\", pngfilename=\"plot6.png\"){\n\tsource('procdata.R');\n\tproc <- procdata();\n\tNEI <- proc$getNEI();\n\tSCCD <- proc$getSCCD();\n\tPMESrcLevel <- FilterEmitBySrcLevel(NEI, SCCD, srcLnum, srcLname);\n\tPMEmitbyBM <- FilterByCounty(PMESrcLevel, \"24510\"); # motor vehicle in Baltimore City\n\tPMEmitbyLA <- FilterByCounty(PMESrcLevel, \"06037\"); # motor vehicle in les County, California\n\tPMEmitbyBMYear <- SumByYear(group_by(PMEmitbyBM, year)) %>% mutate(city=\"Baltimore City\");\t\n\tPMEmitbyBMYear$diffemit <- with(PMEmitbyBMYear, abs(ttlemit-ttlemit[1]));\n\tPMEmitbyLAYear <- SumByYear(group_by(PMEmitbyLA, year))\t%>% mutate(city=\"Los Angeles\");\n\tPMEmitbyLAYear$diffemit <- with(PMEmitbyLAYear, abs(ttlemit-ttlemit[1]));\n\tPMEmitbyYear<-rbind(PMEmitbyBMYear,PMEmitbyLAYear);\n\tggplot(PMEmitbyYear) + geom_line(aes(year, ttlemit, color=city)) + labs(list(title=\"Total Emission Change with Year (Motor Vehicle)\",x=\"Year\",\n\t\t\t\t\t\t\t\t\t\t y=\"Total Emissions Change from Fine Particulate Matter (PM2.5)\")) \n\t#ggplot(PMEmitbyYear, aes(year, diffemit, color=city)) + geom_bar(stat=\"identity\",position=\"dodge\"); \n\t#\t\t\t\t\t\t\t\t\t y=\"Total Emissions Change from Fine Particulate Matter (PM2.5)\")) \n\tggsave(paste0(\"./figure/\", pngfilename), width=6, height=6, dpi=80, units=\"in\");\n\t#par(mfrow=c(2,1));\n\t#plotTTLEmitByYear(PMEmitbyBMYear, pngfilename, sub=\"From Motor Vehicle sources in Baltimore City\");\n\t#plotTTLEmitByYear(PMEmitbyLAYear, pngfilename, sub=\"From Motor Vehicle sources in Los Angeles City\");\n}\n"
},
{
"alpha_fraction": 0.47660818696022034,
"alphanum_fraction": 0.5526315569877625,
"avg_line_length": 27.5,
"blob_id": "1705c905bc338c47d3c49ba1a5cf9a4705994a3b",
"content_id": "d2a130bf9620ddcab01686826ab51091e91f7961",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 342,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 12,
"path": "/repdataPeerAssignment2/splitRepStormData.sh",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nif [ ! -e \"./split\" ]\nthen\n\tmkdir -p ./split\nfi\nyear=1950;\nfor((year=1950; year<=2011; year=year+1))\ndo\n\techo \"Processing $year data!\"\n\tgrep -E \"^[0-9]+[0-9.]+,[0-9]+/[0-9]+/$year\" repdataStormData.csv | sed -r ':pat; s/(\"[^\",]+),+([^\",]*)/\\1 \\2/g; tpat' | cut -d , -f1-35 > \"./split/repdataStoremDatta-$year.csv\";\n\techo $?;\ndone\n"
},
{
"alpha_fraction": 0.6478873491287231,
"alphanum_fraction": 0.6866196990013123,
"avg_line_length": 55.79999923706055,
"blob_id": "06249caf7ee3b6d10f3d1b8027975b8248b2aae2",
"content_id": "1724641e05aedcad1687482874110cb77a00eadb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 568,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 10,
"path": "/ExData_Plotting2/plot3.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot3<-function(code=\"24510\", pngfilename='plot3.png'){\n\tsource('procdata.R');\n\tproc<-procdata();\n\tNEI <- proc$getNEI();\n\tPMEmitbyCY <- FilterByCounty(NEI, code);\n\tPMEmitbycity<-summarize(group_by(PMEmitbyCY,year,type), ttlemit=sum(Emissions));\n\tggplot(PMEmitbycity, aes(year, ttlemit, color=type)) + geom_line() + labs(list(title=\"Figure of Total Emission Change with Year\",x=\"Year\",\n\t\t\t\t\t\t\t\t\t\t y=\"Total Emissions from Fine Particulate Matter (PM2.5)\")) + xlim(c(1999,2008)); \n\tggsave(paste0(\"./figure/\", pngfilename), width=6, height=6, dpi=80, units=\"in\");\n}\n"
},
{
"alpha_fraction": 0.6957831382751465,
"alphanum_fraction": 0.7168674468994141,
"avg_line_length": 35.88888931274414,
"blob_id": "c6bd511f15e793f33366eb503b92621bca4179f5",
"content_id": "fbef07914cb1fee14bc5beb6d00b380cf83b7a15",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 332,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 9,
"path": "/ExData_Plotting2/plot2.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot2<-function(code=\"24510\", pngfilename=\"plot2.png\"){\n\tsource('procdata.R');\n\tproc<-procdata();\n\tNEI <- proc$getNEI();\n\tNEI <- group_by(NEI, year);\n\tPMEmitbyCY <- FilterByCounty(NEI, code);\n\tPMEmitbyYear <- SumByYear(PMEmitbyCY);\t\t\n\tplotTTLEmitByYear(PMEmitbyYear, pngfilename, sub=\"From Total Sources in Baltimore City Only\");\n}\n"
},
{
"alpha_fraction": 0.696989119052887,
"alphanum_fraction": 0.7133888602256775,
"avg_line_length": 73.34285736083984,
"blob_id": "2a086a71321c647a79b597c336bbf3e0631090e8",
"content_id": "832a3542ff17f9c1c73b237390dc1014391d0fee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "RMarkdown",
"length_bytes": 7805,
"license_type": "no_license",
"max_line_length": 699,
"num_lines": 105,
"path": "/statinference-PeerAssignment/statCourseProjectA2.Rmd",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Statistical Inference Course Project\"\nauthor: \"Rene Wang\"\ndate: \"9/21/2014\"\noutput:\n html_document:\n keep_md: yes\n pdf_document:\n keep_tex: yes\n---\n```{r defaultsetting, echo=FALSE, message=FALSE}\nrequire(knitr);\nrequire(dplyr);\nrequire(ggplot2);\nopts_chunk$set(echo=TRUE, message=FALSE, tidy=FALSE, comment=NA,\n fig.path=\"figures/\", fig.keep=\"high\", fig.env=\"marginfigure\",\n fig.width=8, fig.height=5, fig.align=\"center\",dev=\"png\");\n#opts_knit$set(verbose=TRUE, latex.option.graphicx=\"graphicx\");\n```\n\n### Assignment Part 2\nIn the second portion of the class, we're going to analyze the ToothGrowth data in the R datasets package. \n\n**Goals:** \n\n1. Load the ToothGrowth data and perform some basic exploratory data analyses \n2. Provide a basic summary of the data.\n3. Use confidence intervals and hypothesis tests to compare tooth growth by supp and dose. (Use the techniques from class even if there's other approaches worth considering)\n4. State your conclusions and the assumptions needed for your conclusions. \n\n### Initial Exploratory Data Analyses: \nThe statistics of ToothGroth data are summarized in the following table without any separate analysis. The overall distribution is close to symmetric shape with very few outliers. \n\n```{r dataload, results='hide'}\n data(ToothGrowth);\n # perform some basic exploratory data analyses \n #hist(ToothGrowth$len, breaks=10, col=\"pink\", xlab=\"Length of Tooth (mm)\", ylab=\"Count\", main=\"Histogram of Tooth Length\");\n ToothGrowth$ssupp<-ToothGrowth$supp;\n ToothGrowth$supp<-relevel(gl(2, 30, labels=c(\"Ascorbic Acid\",\"Orange Juice\")),ref=\"Orange Juice\");\n ToothGrowth$dose <- as.factor(ToothGrowth$dose);\n ToothGrowth<-tbl_df(ToothGrowth);\n summary(ToothGrowth[,1:3]);\n````\n\nFurther to examine each category, below are the boxplot for different supplement types and different doses. As we can see, there seems to be no greater difference between supplement types if we group different dose levels together. However, we can see the greater difference in different does levels when the supplement types are grouped. \n\n```{r explot}\n par(mfrow=c(1,2))\n ToothGrowth<-group_by(ToothGrowth, dose, supp);\n #blox plot here\n with(ToothGrowth, boxplot(len~supp, xlab=\"Supplement Types\", ylab=\"Length of Tooth (mm)\", col=\"lightgreen\"));\n with(ToothGrowth, boxplot(len~dose, xlab=\"Dose (milligrams)\", ylab=\"Length of Tooth (mm)\", col=\"snow\"));\n par(mfrow=c(1,1))\n ggplot(ToothGrowth, aes(y=len, x=interaction(dose,ssupp),fill=supp))+geom_boxplot()+scale_x_discrete(breaks=c(\"0.5.OJ\",\"1.OJ\",\"2.OJ\",\"0.5.VC\",\"1.VC\",\"2.VC\"),name=\"Supplement Type (Dose)\", labels=c(\"Orange Juice (0.5)\",\"Orange Juice (1)\",\"Orange Juice (2)\",\"Ascorbic Acid (0.5)\",\"Ascorbic Acid (1)\",\"Ascorbic Acid (2)\"))+scale_y_continuous(name=\"Length of Tooth (mm)\")+theme(axis.text.x=element_text(angle=30, hjust=1,vjust=1));\n #2. Provide a basic summary of the data.\n ToothTable<-summarize(ToothGrowth, sum=sum(len), mean=mean(len), \n std=sd(len), num=length(len));\n```\n\nAnd The table below show the simple summary statistics of these six category: \n\n| Supplement Type | Dose Level | Mean | Standard Deviation |\n|:---------------:|:----------:|:-----:|:------------------:|\n| `r ToothTable$supp[1]` | `r ToothTable$dose[1]`|`r ToothTable$mean[1]`|`r format(ToothTable$std[1],nsmall=2)`|\n| `r ToothTable$supp[2]` | `r ToothTable$dose[2]`|`r ToothTable$mean[2]`|`r format(ToothTable$std[2],nsmall=2)`|\n| `r ToothTable$supp[3]` | `r ToothTable$dose[3]`|`r ToothTable$mean[3]`|`r format(ToothTable$std[3],nsmall=2)`|\n| `r ToothTable$supp[4]` | `r ToothTable$dose[4]`|`r ToothTable$mean[4]`|`r format(ToothTable$std[4],nsmall=2)`|\n| `r ToothTable$supp[5]` | `r ToothTable$dose[5]`|`r ToothTable$mean[5]`|`r format(ToothTable$std[5],nsmall=2)`|\n| `r ToothTable$supp[6]` | `r ToothTable$dose[6]`|`r ToothTable$mean[6]`|`r format(ToothTable$std[6],nsmall=2)`|\n| All Supplement Types | All Dose Levels |`r mean(ToothGrowth$len)`|`r format(sd(ToothGrowth$len),nsmall=2)`|\n\n### Hypothesis Testing: \nI conducted two sample t-test with equal variance to test the null hypothesis that the means of tooth growth from different supplement types are equal. I used the mixed dose levels, and separate the dose levels. The test result is listed in the following table: \n\n```{r htest, results='hide'}\n #3. hypothesis tests\n # t on different supplements\n # mixed \n mixtest<-unclass(t.test(x=filter(ToothGrowth, ssupp==\"VC\")$len, \n y=filter(ToothGrowth, ssupp==\"OJ\")$len, var.equal=TRUE));\n testfunc<-function(amount, obj=ToothGrowth){\n x<-filter(obj, ssupp==\"VC\" & dose==amount)$len;\n y<-filter(obj, ssupp==\"OJ\" & dose==amount)$len;\n return(unclass(t.test(x, y, var.equal=TRUE)));\n }\n # test supp method difference given the same dose level\n testresult <-sapply(as.list(levels(ToothGrowth$dose)), testfunc);\n #4. try ANOVA to compare the means of diffferent doses but with same supplements\n aov.out = aov(len ~ ssupp * dose, data=ToothGrowth);\n```\n\n| Dose Level | p-value | Confidence Interval | t-statistic (df) |\n|:----------:|:--------:|:-------------------:|:----------------:|\n|0.5 (LOW)|`r format(testresult[,1]$p.value, nsmall=4)`|[ `r format(testresult[,1]$conf.int[1],nsmall=2)` , `r format(testresult[,1]$conf.int[2],nsmall=2)`]| `r format(testresult[,1]$statistic,nsmall=2)` ( `r testresult[,1]$parameter[\"df\"]` )|\n|1 (MEDIUM)|`r format(testresult[,2]$p.value, nsmall=4)`|[ `r format(testresult[,2]$conf.int[1],nsmall=2)` , `r format(testresult[,2]$conf.int[2],nsmall=2)`]| `r format(testresult[,2]$statistic,nsmall=2)` ( `r testresult[,2]$parameter[\"df\"]` )|\n|2 (HIGH)|`r format(testresult[,3]$p.value, nsmall=4)`|[ `r format(testresult[,3]$conf.int[1],nsmall=2)` , `r format(testresult[,3]$conf.int[2],nsmall=2)`]| `r format(testresult[,3]$statistic,nsmall=2)` ( `r testresult[,3]$parameter[\"df\"]` )|\n| All Dose Levels |`r format(mixtest$p.value,nsmall=4)`| [ `r format(mixtest$conf.int[1],nsmall=2)` , `r format(mixtest$conf.int[2],nsmall=2)`]| `r format(mixtest$statistic,nsmall=2)` ( `r mixtest$parameter[\"df\"]` )| \n\n### Summary and Conclusion: \n1. We can see from the initial data analyses, the tooth length is highly correlated with dose level. The teeth grows with incresing dose regardless of supplement types. \nHowever, the teeth lenghts are more variable in Ascorbic Acid supplement types than in Orange Juice. \n2. As expected the difference of tooth growth between two supplement types are not statistically significant, when testing on mixed dose levels via two sample t-test (assumed the variances of two groups are equal). When testing the mean differences between two supplement types on different dose levels separately, surprisingly the highest dose level has no significant result as the low and medium levels. The test results showed no difference if the equal variance assumption is not held. \n3. If the data are correctly collected, the not statistically significant result of the highest dose level might be due to the limit of maximal tooth growth for a guinea pig. Because in the highest dose level, there might be no room for tooth to grow and results in the similar mean tooth growth (all reach the maximal capacity for tooth growth). On the other hand, the lowest level of dose might not be as sufficient to facilitate tooth growth as medium dose level. Therefore, the result of lowest level is not as significant as medium one. This conclusion if there is tooth growth difference in two supplement types would be much supported if more sample on medium dose level could be collected. \n\nThe souce code can be available in [statCourseProjectA2.md](https://github.com/renewang/datasciencecoursera/blob/master/statinference-PeerAssignment/statCourseProjectA2.md)"
},
{
"alpha_fraction": 0.672886312007904,
"alphanum_fraction": 0.6818270087242126,
"avg_line_length": 60.49003982543945,
"blob_id": "ed31710570f30e2ba488d2f433b081dbc02014af",
"content_id": "06855e3a755f7ad4cefd2ab785c180743cbb6b59",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "RMarkdown",
"length_bytes": 15435,
"license_type": "no_license",
"max_line_length": 724,
"num_lines": 251,
"path": "/repdataPeerAssignment1/PA1_template.Rmd",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "---\ntitle: \"Reproducible Research\"\nsubtitle: \"Peer Assessment 1\"\nauthor: \"Rene Wang\"\ndate: \"09/09/2014\"\nkeepmd: true\noutput: html_document\n---\n```{r defaultsetting, echo=FALSE, message=FALSE}\nrequire(knitr);\nrequire(plyr);\nrequire(ggplot2);\nopts_chunk$set(echo=TRUE, message=FALSE, tidy=FALSE, comment=NA,\n fig.path=\"figures/\", fig.keep=\"high\", fig.width=10, fig.height=6,\n fig.align=\"center\");\n```\n###Introduction: \n**Personal activity monitoring** is thriving through the use of smart phones and wearable devices. It raises *the awareness of personal health* through collecting and analyzing daily activity pattern. In this assignment, a data set was collectcted from an anonymous person whose daily activities were recorded in 5 minute interval from Octorber to November 2012.\n\n[The git source of assignment](https://github.com/rdpeng/RepData_PeerAssessment1)\n\n## Loading and preprocessing the data\n### Information of data \n* File name: activity.csv \n* Variables included in this dataset are: \n -**steps**: Number of steps taking in a 5-minute interval \n -**date**: The date on which the measurement was taken in YYYY-MM--DD format \n -**interval**: Identifier for the 5-minute interval in which measurement was taken \n```{r dataprocess, cache=TRUE}\n filename<-'activity.csv';\n if(!file.exists(filename)){\n zipurl<-\"https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip\";\n download.file(zipurl, destfile=\"activity.zip\", method=\"curl\");\n datedownload<-date();\n unzip(\"activity.zip\");\n }\n activity<-read.csv(filename,header=TRUE, colClasses= c(\"numeric\",\"Date\",\"numeric\"));\n good<-complete.cases(activity);\n cleanactivity<-activity[good,];\n```\n\n## What is mean total number of steps taken per day?\n#### Figure: \nA histogram of the total number of steps taken each day is shown: \n```{r sumhist, echo=TRUE}\n ## group data\n stepsumbydate<-ddply(cleanactivity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n ## Make a histogram of the total number of steps taken each day\n ggplot(stepsumbydate,aes(sum.steps))+geom_histogram(stat=\"bin\")+\n labs(list(title=\"Histogram of Total Sum of Steps per day (NA imputing)\",\n x=\"Sum of steps per day\", y=\"Count\"))+\n theme(title=element_text(size=14));\n ## Calculate the mean and median of total steps per day\n meanofdaystepsum<-mean(stepsumbydate$sum.step,na.rm=TRUE);\n medianofdaystepsum<-median(stepsumbydate$sum.step,na.rm=TRUE);\n```\n\n```{r sumtime, echo=FALSE, eval=FALSE}\n ## Make a bar plot of the total number of steps taken each day\n ggplot(stepsumbydate,aes(x=date,y=sum.steps))+geom_bar(stat=\"identity\")+\n labs(list(title=\"Sum of Steps per day without Missing Value Replacement\",y=\"sum of steps\"))+\n theme(title=element_text(size=14));\n ## Calculate the mean and median of steps per day\n stepmeasurebydate<-cbind(stack(stepsumbydate[,3:4],),stepsumbydate$date);\n colnames(stepmeasurebydate)<-c(\"values\",\"type\",\"date\");\n ggplot(stepmeasurebydate,aes(x=date,y=values,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean/Median of Steps per day without Missing Value Replacement\",y=\"Mean/Median of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"measurement\",labels=c(\"mean\",\"median\"));\n```\n\n#### Report Mean and Median: \nThe mean of total steps taken per day is **`r format(meanofdaystepsum,scientific=FALSE,nsmall=2)`** and median of total steps taken per day is **`r format(medianofdaystepsum,scientific=FALSE,nsmall=2)`** when NA cases are completely removed. \n\n## What is the average daily activity pattern? \nTwo figures below show: \n1. A time series plot of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis). \n2. The plot of mean and median time series plots of the 5-minute interval across all days. \n\n```{r timeseries}\n ## make time series plot of the 5-minute interval\n stepsumbyint<-ddply(cleanactivity, .(interval), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps,na.rm=TRUE), \n median.steps=median(steps,na.rm=TRUE));\n \n ggplot(stepsumbyint,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval without Missing Value Replacement\",\n x=\"time\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14));\n\n maxinterval<- which.max(stepsumbyint$mean.steps);\n maxintminute<-stepsumbyint[maxinterval,1];\n maxsteps<-format(stepsumbyint[maxinterval,3],nsamll=2);\n\n ## Calculate the median of steps per 5-minute interval\n stepmeasurebyint<-cbind(stack(stepsumbyint[,3:4],),stepsumbyint$interval);\n colnames(stepmeasurebyint)<-c(\"values\",\"type\",\"interval\");\n ggplot(stepmeasurebyint,aes(x=interval,y=values,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean/Median of Steps Every 5 minute interval without Missing Value Replacement\",\n x=\"time\", y=\"Mean/Median of steps\"))+\n theme(title=element_text(size=14))+\n scale_color_discrete(name=\"measurement\",labels=c(\"mean\",\"median\"));\n maxmidinterval<- which.max(stepsumbyint$median.steps);\n maxmidminute<-stepsumbyint[maxmidinterval,1];\n maxmidsteps<-format(stepsumbyint[maxmidinterval,4], nsamll=2);\n maxavgsteps<-format(stepsumbyint[maxmidinterval,3], nsamll=2);\n```\n\n### Summary: \n1. On average across all the days in the dataset, the maximum number of steps is **`r maxsteps` steps** within **`r maxinterval` th** 5-minute interval, corresponding to time starting at **`r formatC(maxmidminute%/%100,width=2,flag=\"0\")`:`r formatC(maxmidminute%%100,width=2,flag=\"0\")`** (in 24 hour format). \n2. Median shows a shift of 10 minutes (from **`r formatC(maxintminute%/%100,width=2,flag=\"0\")`:`r formatC(maxintminute%%100,width=2,flag=\"0\")`** to **`r formatC(maxmidminute%/%100,width=2,flag=\"0\")`:`r formatC(maxmidminute%%100,width=2,flag=\"0\")`**) and from **`r maxsteps` steps** to **`r maxmidsteps` steps** (average steps lowers to **`r maxavgsteps` steps**). \n\n## Imputing missing values\n1. The total number of missing values in the dataset is **`r length(which(!good))`** ( about **`r format(length(which(!good))/length(good)*100,digit=5)`**%) and there are **`r length(unique(cleanactivity$date))`** are valid days out of **`r length(unique(activity$date))`**. \n2. Below a historgram of the total number of steps taken each day with different imputing methods are shown: \n\n```{r imputingna}\n ## replace missing values with the mean of the same interval\n imputactivitybymean<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n mean(steps, na.rm=TRUE)));\n imputactivitybymid<-ddply(activity, .(interval), transform,\n steps=replace(steps, which(is.na(steps)), \n median(steps, na.rm=TRUE)));\n ## use median \n midimputstepsumbydate<-ddply(imputactivitybymid, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n ## use mean\n avgimputstepsumbydate<-ddply(imputactivitybymean, .(date), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputactivitybydate<-ddply(activity, .(date), summarize,\n sum.steps=sum(steps,na.rm=TRUE),\n mean.steps=mean(steps), \n median.steps=median(steps,na.rm=TRUE));\n ## compare histogram\n df<-data.frame(sum.steps=c(imputactivitybydate$sum.steps,avgimputstepsumbydate$sum.steps, \n midimputstepsumbydate$sum.steps),\n mean.steps=c(imputactivitybydate$mean.steps,avgimputstepsumbydate$mean.steps, \n midimputstepsumbydate$mean.steps), \n median.steps=c(imputactivitybydate$median.steps,avgimputstepsumbydate$median.steps,\n midimputstepsumbydate$median.steps), \n date=c(imputactivitybydate$date,avgimputstepsumbydate$date, \n midimputstepsumbydate$date), \n type=c(rep(\"deleting\", nrow(imputactivitybydate)),\n rep(\"mean-replacement\",nrow(avgimputstepsumbydate)),\n rep(\"mid-replacement\",nrow(midimputstepsumbydate))));\n # drawing histogram\n ggplot(df,aes(sum.steps, fill=type, alpha=0.5))+geom_histogram(stat=\"bin\", position=\"dodge\")+\n labs(list(title=\"Histogram of Sum of Steps per day without Missing Value Replacement\",\n x = \"Sum of steps per day\", y=\"Counts\"))+\n theme(title=element_text(size=14));\n\n ## report mean & median\n repmmeandaystepsum<-mean(df[df$type==\"deleting\",\"sum.steps\"]);\n repmmediandaystepsum<-median(df[df$type==\"deleting\",\"sum.steps\"]);\n repameandaystepsum<-mean(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repamedianofdaystepsum<-median(df[df$type==\"mean-replacement\",\"sum.steps\"]);\n repdmeandaystepsum<-mean(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n repdmedianofdaystepsum<-median(df[df$type==\"mid-replacement\",\"sum.steps\"]);\n```\n\n### Report Mean and Median with different missing values replacement strategies: \n| Missing Value Replacement Strategies | Mean | Median |\n| :------------------------------------:|:------------------:|:----------------------:|\n| No Imputing Strategy |`r format(repmmeandaystepsum,scientific=FALSE,nsmall=2)`|`r format(repmmediandaystepsum,scientific=FALSE,nsmall=2)`|\n| Deleting Missing Values |`r format(meanofdaystepsum,scientific=FALSE,nsmall=2)` |`r format(medianofdaystepsum,scientific=FALSE,nsmall=2)` |\n| Replace with Mean of 5-min interval |`r format(repameandaystepsum,scientific=FALSE,nsmall=2)`|`r format(repamedianofdaystepsum,scientific=FALSE,nsmall=2)`|\n| Replace with Median of 5-min interval |`r format(repdmeandaystepsum,scientific=FALSE,nsmall=2)`|`r format(repdmedianofdaystepsum,scientific=FALSE,nsmall=2)`|\n\n### Summary: \n1. Do these values differ from the estimates from the first part of the assignment? \nBecause there are dates on which the collected steps measurements across all time interval are not available, I used two simple strategies to replace missing values with mean or median of the same 5-min interval and compared the result. The difference between these two strategies is small in most of the days. However, for the days with more missing values, using mean replacement tended to give greater values than median (mean value are affected by extreme values as shown in time series plot of the 5-minute interval) and gave similar values as deletion. But mean replacement overesitmate total sum of stpes per day without imputing strategy. Overall speaking, median replacement gives more conservative estimation. \n2. What is the impact of imputing missing data on the estimates of the total daily number of steps? \nThe impact of imputing missing data on the estimates of the total daily number of steps is to over-estimate the total daily number of steps as using mean-replacement strategy. \n\n```{r sumtime2, echo=FALSE, eval=FALSE} \n ggplot(df,aes(x=date,y=sum.steps, fill=type, alpha=0.5))+geom_bar(stat=\"identity\",position=\"dodge\")+\n labs(list(title=\"Sum of Steps per day\",y=\"sum of steps\"))+\n theme(title=element_text(size=14))+scale_fill_discrete(name=\"imputing method\");\n \n ggplot(df,aes(x=date,y=mean.steps,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps per day\",y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"imputing method\");\n\nggplot(df,aes(x=date,y=median.steps,color=type))+geom_line(stat=\"identity\")+\n labs(list(title=\"Median of Steps per day\",y=\"Median of steps\"))+\n theme(title=element_text(size=14))+scale_color_discrete(name=\"imputing method\");\n```\n\n## Are there differences in activity patterns between weekdays and weekends?\n```{r compweek}\n ## group by weekday and weekend using mean replacement\n imputactivitybymean$weekday=weekdays(imputactivitybymean[,2]);\n imputactivitybymean$isweekend=imputactivitybymean$weekday==\"Saturday\"|\n imputactivitybymean$weekday==\"Sunday\";\n imputactbymeanweekday<-imputactivitybymean[imputactivitybymean$isweekend==FALSE,];\n imputactbymeanweekend<-imputactivitybymean[imputactivitybymean$isweekend==TRUE,];\n\n imputsumbymeanweekday<-ddply(imputactbymeanweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n\n imputsumbymeanweekend<-ddply(imputactbymeanweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymean<-rbind(imputsumbymeanweekday,imputsumbymeanweekend);\n imputsumbymean$isweekend<-c(rep(\"Weekday\",nrow(imputsumbymeanweekday)),\n rep(\"Weekend\",nrow(imputsumbymeanweekend)));\n\n ggplot(imputsumbymean,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Mean Replacement) over days\",\n x=\"Interval\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n \n ## group by weekday and weekend using median replacement\n imputactivitybymid$weekday=weekdays(imputactivitybymid[,2]);\n imputactivitybymid$isweekend=imputactivitybymid$weekday==\"Saturday\"|\n imputactivitybymid$weekday==\"Sunday\";\n imputactbymidweekday<-imputactivitybymid[imputactivitybymid$isweekend==FALSE,];\n imputactbymidweekend<-imputactivitybymid[imputactivitybymid$isweekend==TRUE,];\n \n imputsumbymidweekday<-ddply(imputactbymidweekday, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n \n imputsumbymidweekend<-ddply(imputactbymidweekend, .(interval), summarize,\n sum.steps=sum(steps),\n mean.steps=mean(steps), \n median.steps=median(steps));\n imputsumbymid<-rbind(imputsumbymidweekday,imputsumbymidweekend);\n imputsumbymid$isweekend<-c(rep(\"Weekday\",nrow(imputsumbymidweekday)),\n rep(\"Weekend\",nrow(imputsumbymidweekend)));\n \n ggplot(imputsumbymid,aes(x=interval,y=mean.steps))+geom_line(stat=\"identity\")+\n labs(list(title=\"Mean of Steps Every 5 minute interval (Median Replacement) over days\",\n x=\"Interval\", y=\"Mean of steps\"))+\n theme(title=element_text(size=14))+facet_grid(isweekend~.);\n```\n\n### Summary: \nThe activities during weekends tends to be late in the mornging and also more active in the late hours of evening. But overall trends of both time series curves are similar. Using different missing value replacement strategies does not make any difference by observing the overall trends. \n"
},
{
"alpha_fraction": 0.6768060922622681,
"alphanum_fraction": 0.6844106316566467,
"avg_line_length": 31.875,
"blob_id": "2c7c7bd00c783294107ca7722cbe63c33841a53c",
"content_id": "3239c63209b2a628518ed1dbda5fb3116389b6ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 263,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 8,
"path": "/ExData_Plotting2/plot1.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot1<-function(pngfilename=\"plot1.png\", ...){\n\tsource('procdata.R');\n\tproc <- procdata();\n\tNEI <- proc$getNEI();\n\tNEI <- group_by(NEI, year);\n\tPMEmitbyYear <- SumByYear(NEI);\t\t\n\tplotTTLEmitByYear(PMEmitbyYear, pngfilename, sub=\"From Total Sources across US\");\n}\n"
},
{
"alpha_fraction": 0.714031994342804,
"alphanum_fraction": 0.7193605899810791,
"avg_line_length": 36.53333282470703,
"blob_id": "efb710db6fdb7a319ecf42e75c973fbc082f24cf",
"content_id": "3350e3ca4d1cac200b21251a0bc51a8995839943",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 563,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 15,
"path": "/ExData_Plotting2/plot4.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "plot4<-function(srcLnum=1, srcLname=\"Coal\", pngfilename=\"plot4.png\"){\n\tsource('procdata.R');\n\tproc <- procdata();\n\tNEI <- proc$getNEI();\n\tSCCD <- proc$getSCCD();\n\tPMESrcLevel <- FilterEmitBySrcLevel(NEI, SCCD, srcLnum, srcLname);\n\tPMEmitbyYear <- SumByYear(group_by(PMESrcLevel,year));\t\t\n\t# plot all\n\tplotTTLEmitByYear(PMEmitbyYear, pngfilename, sub=\"From Coal Combustion-related sources across US\");\n\t# plot SCC.Level.One\n\t# ggplot(PMEmitbyYear,ase(x=year, stack=SCC.Level.One))+geom_bar();\n\t# plot SCC.Level.Two\n\t# plot SCC.Level.Three\n\t# plot SCC.Level.Four\n}\n"
},
{
"alpha_fraction": 0.6768569350242615,
"alphanum_fraction": 0.6854549646377563,
"avg_line_length": 49.44578170776367,
"blob_id": "96c272bbd84f415825b43433265d5de61df0e304",
"content_id": "0d7dac4ea67ec67affe82364a5ffa83f8da9fc2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 4187,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 83,
"path": "/getdataCourseProject/run_analysis.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "## main part to generate tidy data\nrun_analysis<-function(){\n require(reshape2);\n ## 2. Extracts only the measurements on the mean and standard deviation \n ## for each measurement.n\n features <- read.table(\"UCI HAR Dataset/features.txt\", colClass=c(\"numeric\",\"character\"));\n extFeaturesIdx<-which(grepl(\"mean|std\", features[,2]));\n colclasses<-rep(\"NULL\", nrow(features));\n colclasses[extFeaturesIdx]=\"numeric\";\n ## 1. Merges the training and the test sets to create one data set.\n xtrain<-read.table(\"UCI HAR Dataset/train/X_train.txt\", colClass=colclasses);\n xtest<-read.table(\"UCI HAR Dataset/test/X_test.txt\", colClass=colclasses);\n xdata<-rbind(xtrain, xtest);\n rm(xtrain);\n rm(xtest);\n #For testing on bigmemory\n #bmxdata<-as.big.matrix(xdata, type = options()$bigmemory.default.type, \n # backingfile=\"xdata.bin\", backingpath=\".\", descriptorfile=\"xdata.desc\", \n # binarydescriptor=TRUE);\n #bmxdata<-read.big.matrix(\"xdata.csv\", type=\"double\", header=TRUE, \n # backingfile=\"xdata.bin\", descriptorfile=\"xdata.desc\");\n ytrain<-read.table(\"UCI HAR Dataset/train/y_train.txt\",colClass=\"numeric\");\n ytest<-read.table(\"UCI HAR Dataset/test/y_test.txt\",colClass=\"numeric\");\n ydata<-rbind(ytrain, ytest);\n rm(ytrain)\n rm(ytest)\n ## 3. Uses descriptive activity names to name the activities in the data set\n activity_labels<-as.matrix(read.table(\"UCI HAR Dataset/activity_labels.txt\",colClass=c(\"NULL\",\"character\"))); \n ydata<-activity_labels[ydata[,1]]; \n ## 4. Appropriately labels the data set with descriptive variable names. \n features[extFeaturesIdx,2]<-as.character(gsub(\"\\\\(\\\\)\",\"\",as.matrix(features[extFeaturesIdx,2])));\n ## 5. Creates a second, independent tidy data set with the average of each \n ## variable for each activity and each subject. \n subtrain<-read.table(\"UCI HAR Dataset/train/subject_train.txt\", colClass=\"numeric\");\n subtest<-read.table(\"UCI HAR Dataset/test/subject_test.txt\", colClass=\"numeric\");\n subject<-rbind(subtrain, subtest);\n rm(subtrain);\n rm(subtest);\n ydata<-factor(ydata, levels=c(\"WALKING\",\"WALKING_UPSTAIRS\",\"WALKING_DOWNSTAIRS\",\n \"SITTING\",\"STANDING\",\"LAYING\"));\n tidydata <- aggregate(x = xdata, by = list(ydata, as.factor(subject[,])), FUN=\"mean\");\n names(tidydata)<-c(\"Activity\",\"SubjectID\", features[extFeaturesIdx,2]);\n tidydata <- melt(tidydata, id=names(tidydata)[1:2], measure.var=names(tidydata)[-(1:2)]);\n pat<-\"(t|f)(Body|Gravity){1,2}(Acc|Gyro)(Jerk)?(Mag)?\";\n finalvarnames<-processvariable(as.character(tidydata$variable),pat);\n average <- tidydata$value;\n tidydata<-data.frame(Activity=tidydata$Activity, SubjectID=tidydata$SubjectID);\n tidydata<-cbind(tidydata,finalvarnames);\n tidydata$Average<-average;\n rm(xdata);\n rm(ydata);\n rm(subject);\n write.table(tidydata, row.name=FALSE, file=\"tidydata.txt\"); \n invisible();\n return(tidydata);\n}\n# function to be called within run_analysis in order to split variable to meaningful names.\nprocessvariable<-function(varnames=NULL, pattern=\"\", \n replacement=\"\\\\1\\t\\\\2\\t\\\\3\\t\\\\4\\t\\\\5\"){\n if(missing(varnames)){\n stop(\"No variable names for processing\");\n }\n initsplit <- sapply(varnames, strsplit, \"-\");\n procvarname <- sapply(initsplit, function(varnames){\n ## process MeasurementType and Direction\n measuretype<-toupper(varnames[2]);\n direction<-\"Magnitude\";\n if(length(varnames)==3){\n direction<-varnames[3];\n }\n ## process DomainSignal, Apparutus and SignalType\n firstvars<-unlist(strsplit(gsub(pattern, replacement, varnames[1], \n perl=TRUE, ignore.case = TRUE),\"\\t\"));\n domainsignal<-ifelse(firstvars[1]==\"t\",\"Time\", \"Frequency\");\n signaltype<-ifelse(firstvars[4]==\"Jerk\",firstvars[4],firstvars[2]);\n apparutus<-ifelse(firstvars[3]==\"Gyro\", \"Gyroscope\", \"Accelerometer\");\n return(c(domainsignal, apparutus, signaltype, measuretype, direction));\n });\n finalvars <-data.frame(DomainSignal=procvarname[1,],Apparutus=procvarname[2,],\n SignalType=procvarname[3,],MeasurementType=procvarname[4,],\n Direction=procvarname[5,]);\n return(finalvars);\n}\n"
},
{
"alpha_fraction": 0.723071277141571,
"alphanum_fraction": 0.7444301247596741,
"avg_line_length": 76.55714416503906,
"blob_id": "2a630eb564689d3daaae13ca4ffad3f59435a2cb",
"content_id": "3e23845edf25f8dde00c80f461a21d2758f01a89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "RMarkdown",
"length_bytes": 5431,
"license_type": "no_license",
"max_line_length": 781,
"num_lines": 70,
"path": "/repdataPeerAssignment2/storm_analysis.Rmd",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "---\ntitle: Compare Impact of Severe Weather Events on Population Health and Economics in US\nsubtitle: \"Reproducible Research: Storm Data Analysis\"\nauthor: \"Rene Wang\"\ndate: \"09/20/2014\"\noutput: html_document\n---\n```{r defaultsetting, echo=FALSE, message=FALSE}\nrequire(knitr);\nrequire(data.table);\nrequire(dplyr);\nopts_chunk$set(echo=TRUE, message=FALSE, tidy=FALSE, comment=NA,\n fig.path=\"figures/\", fig.keep=\"high\", fig.width=10, fig.height=6,\n fig.align=\"center\");\n```\n## Synopsis \n\n## Data Processing \n###Steps: \n1. **Access Data**: The complete data was provided and can be downladed from [course website](https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2FStormData.csv.bz2) in bzip2 format . Once unzipping the compressed data, the storm data are in csv format (about 536 Mb) containing major storms events and associated damage from the beginning of 1950 to 2011 November and were collected by U.S. **[National Oceanic and Atmospheric Administration](http://www.noaa.gov/) (NOAA)**. \n```{r download}\n inputfile<-'repdataStormData.csv';\n if(!file.exists(inputfile)){\n zipurl<-\"https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2FStormData.csv.bz2\";\n download.file(zipurl, destfile=\"repdataStormData.bz2\", method=\"curl\");\n datedownload<-date();\n require(R.utils)\n bunzip2(\"repdataStormData.bz2\",destname=inputfile);\n }\n```\n2. **Preprocessing Data**: Because the data is mixed with arbitrary line breaks in \"REMARKS\", a shell command will be invoked inside R code to extract and summarize the annual causualities, injureis and the properties damage with regular expression. In addition, the leading and trailing white spaces of EVTYPE (stands for severe event type) are removed. EVTYPE are converted to all upper cases in order to map 48 permitted storm events mentioned in step 3. \n```{r procanul, cache=TRUE, results='asis', warning=FALSE}\nstormdata<-storm_analysis(inputfile);\n```\n3. **Preprocessing Event Types**: \nAccording to the [National Weather Service Storm Data Documentation](https://d396qusza40orc.cloudfront.net/repdata%2Fpeer2_doc%2Fpd01016005curr.pdf), only 48 events are permitted and listed in **Table 1** of *section 2.1.1*. I used a python one-liner command to extract the table from pdf file, processing the table and then redirect output to stadard output and then into R read.csv function. \nHowever, after using exact matching (cost = 0) to compare these 49 permitted severe weather event types, I found there were only 40 unique events can be distinguished without any ambiguity. Other 9 evnets can be further merge into a larger category. \n\n```{r validevent}\n# change to read file\n# validevents <- read.table(\"\");\nvalidevents<-toupper(c('Astronomical Low Tide', 'Avalanche', 'Blizzard', 'Coastal Flood', 'Cold/Wind Chill', 'Debris Flow', 'Dense Fog', 'Dense Smoke', 'Drought', 'Dust Devil', 'Dust Storm', 'Excessive Heat', 'Extreme Cold/Wind Chill', 'Flash Flood', 'Flood', 'Frost/Freeze', 'Funnel Cloud', 'Freezing Fog', 'Hail', 'Heat', 'Heavy Rain', 'Heavy Snow', 'High Surf', 'High Wind', 'Hurricane (Typhoon)', 'Ice Storm', 'Lake-Effect Snow', 'Lakeshore Flood', 'Lightning', 'Marine Hail', 'Marine High Wind', 'Marine Strong Wind', 'Marine Thunderstorm Wind', 'Rip Current', 'Seiche', 'Sleet', 'Storm Surge/Tide', 'Strong Wind', 'Thunderstorm Wind', 'Tornado', 'Tropical Depression', 'Tropical Storm', 'Tsunami', 'Volcanic Ash', 'Waterspout', 'Wildfire', 'Winter Storm', 'Winter Weather'));\nvalidevents<-c(validevents,\"OTHER\");\nvalidevents<-mergevalidevents(validevents);\neventsFuzzyMatch(validevents,validevents, max.dist=0);\n```\n\n3. There are ??? severe event types repsented as EVTYPE in the preprocessed data after executing step 2. Compared to \nAmong the ??? events extracted from raw data, I conducted the following steps to clean up data. \n a. Firstly, remove ??? evnets have no impact on population health and properties loss (the total damage estimate is zero). After examine the summary of remaining data, I found the distribution is highly skewed. Nearly < 81% of total estimated damage is smaller than about 1,000,000 US Dollars. I consider the skewed distribution should be caused by inaccurate EVTYPE descriptions. I split the data into two groups: one with total loss is less than 1,000,000 US Dollars and the other is otherwise.\n b. I used **\"fuzzy string matching\"** the group with total loss not less than 1,000,000 in order to map those events to 49 permitted ones. \n \nAn unknown event type ('?'). Add one more category into the 48 permitted severe weather events. Combine NON-xxx events into OTHERS category. \n## TODO\nHIGH => amgibuous\ngradient wind => strange\nOTHER + NON...=> keep (combine to other)\nDROWNING => Rip currents\n```{r matchvalid}\n\n# remove no damage events\nprocevents<-group_by(stormdata,EVTYPE)%>%summarize(ttlf=sum(TotalFatalities), ttli=sum(TotalInjuries), ttlp=sum(TotalPROPDMG), ttlc=sum(TotalCROPDMG), ttl=ttlf+ttli+ttlp+ttlc)%>%filter(ttl!=0);\nless1M<-procevents[procevents$ttl<1e6,];\ngreater1M<-procevents[procevents$ttl>=1e6,];\n```\n### Results \n1. There are different severe weather events are collected in this data. \n### Discussion \n1. Across the United States, which types of events (as indicated in the EVTYPE variable) are most harmful with respect to population health? \n2. Across the United States, which types of events have the greatest economic consequences? \n"
},
{
"alpha_fraction": 0.6857779622077942,
"alphanum_fraction": 0.7177894711494446,
"avg_line_length": 59.96116638183594,
"blob_id": "5e6c4222fd6239880b4bd77e787472961992b0bb",
"content_id": "8fbcdb8b2ebc38f1cd148832c8f63549f66db4aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6279,
"license_type": "no_license",
"max_line_length": 699,
"num_lines": 103,
"path": "/statinference-PeerAssignment/statCourseProjectA2.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "# Statistical Inference Course Project\nRene Wang \n9/21/2014 \n\n\n### Assignment Part 2\nIn the second portion of the class, we're going to analyze the ToothGrowth data in the R datasets package. \n\n**Goals:** \n\n1. Load the ToothGrowth data and perform some basic exploratory data analyses \n2. Provide a basic summary of the data.\n3. Use confidence intervals and hypothesis tests to compare tooth growth by supp and dose. (Use the techniques from class even if there's other approaches worth considering)\n4. State your conclusions and the assumptions needed for your conclusions. \n\n### Initial Exploratory Data Analyses: \nThe statistics of ToothGroth data are summarized in the following table without any separate analysis. The overall distribution is close to symmetric shape with very few outliers. \n\n\n```r\n data(ToothGrowth);\n # perform some basic exploratory data analyses \n #hist(ToothGrowth$len, breaks=10, col=\"pink\", xlab=\"Length of Tooth (mm)\", ylab=\"Count\", main=\"Histogram of Tooth Length\");\n ToothGrowth$ssupp<-ToothGrowth$supp;\n ToothGrowth$supp<-relevel(gl(2, 30, labels=c(\"Ascorbic Acid\",\"Orange Juice\")),ref=\"Orange Juice\");\n ToothGrowth$dose <- as.factor(ToothGrowth$dose);\n ToothGrowth<-tbl_df(ToothGrowth);\n summary(ToothGrowth[,1:3]);\n```\n\nFurther to examine each category, below are the boxplot for different supplement types and different doses. As we can see, there seems to be no greater difference between supplement types if we group different dose levels together. However, we can see the greater difference in different does levels when the supplement types are grouped. \n\n\n```r\n par(mfrow=c(1,2))\n ToothGrowth<-group_by(ToothGrowth, dose, supp);\n #blox plot here\n with(ToothGrowth, boxplot(len~supp, xlab=\"Supplement Types\", ylab=\"Length of Tooth (mm)\", col=\"lightgreen\"));\n with(ToothGrowth, boxplot(len~dose, xlab=\"Dose (milligrams)\", ylab=\"Length of Tooth (mm)\", col=\"snow\"));\n```\n\n<img src=\"figures/explot1.png\" title=\"plot of chunk explot\" alt=\"plot of chunk explot\" style=\"display: block; margin: auto;\" />\n\n```r\n par(mfrow=c(1,1))\n ggplot(ToothGrowth, aes(y=len, x=interaction(dose,ssupp),fill=supp))+geom_boxplot()+scale_x_discrete(breaks=c(\"0.5.OJ\",\"1.OJ\",\"2.OJ\",\"0.5.VC\",\"1.VC\",\"2.VC\"),name=\"Supplement Type (Dose)\", labels=c(\"Orange Juice (0.5)\",\"Orange Juice (1)\",\"Orange Juice (2)\",\"Ascorbic Acid (0.5)\",\"Ascorbic Acid (1)\",\"Ascorbic Acid (2)\"))+scale_y_continuous(name=\"Length of Tooth (mm)\")+theme(axis.text.x=element_text(angle=30, hjust=1,vjust=1));\n```\n\n<img src=\"figures/explot2.png\" title=\"plot of chunk explot\" alt=\"plot of chunk explot\" style=\"display: block; margin: auto;\" />\n\n```r\n #2. Provide a basic summary of the data.\n ToothTable<-summarize(ToothGrowth, sum=sum(len), mean=mean(len), \n std=sd(len), num=length(len));\n```\n\nAnd The table below show the simple summary statistics of these six category: \n\n| Supplement Type | Dose Level | Mean | Standard Deviation |\n|:---------------:|:----------:|:-----:|:------------------:|\n| Orange Juice | 0.5|13.23|4.46|\n| Ascorbic Acid | 0.5|7.98|2.747|\n| Orange Juice | 1|22.7|3.911|\n| Ascorbic Acid | 1|16.77|2.515|\n| Orange Juice | 2|26.06|2.655|\n| Ascorbic Acid | 2|26.14|4.798|\n| All Supplement Types | All Dose Levels |18.8133|7.649|\n\n### Hypothesis Testing: \nI conducted two sample t-test with equal variance to test the null hypothesis that the means of tooth growth from different supplement types are equal. I used the mixed dose levels, and separate the dose levels. The test result is listed in the following table: \n\n\n```r\n #3. hypothesis tests\n # t on different supplements\n # mixed \n mixtest<-unclass(t.test(x=filter(ToothGrowth, ssupp==\"VC\")$len, \n y=filter(ToothGrowth, ssupp==\"OJ\")$len, var.equal=TRUE));\n testfunc<-function(amount, obj=ToothGrowth){\n x<-filter(obj, ssupp==\"VC\" & dose==amount)$len;\n y<-filter(obj, ssupp==\"OJ\" & dose==amount)$len;\n return(unclass(t.test(x, y, var.equal=TRUE)));\n }\n # test supp method difference given the same dose level\n testresult <-sapply(as.list(levels(ToothGrowth$dose)), testfunc);\n #4. try ANOVA to compare the means of diffferent doses but with same supplements\n aov.out = aov(len ~ ssupp * dose, data=ToothGrowth);\n```\n\n| Dose Level | p-value | Confidence Interval | t-statistic (df) |\n|:----------:|:--------:|:-------------------:|:----------------:|\n|0.5 (LOW)|0.005304|[ -8.73 , -1.77]| -3.17 ( 18 )|\n|1 (MEDIUM)|0.0007807|[ -9.019 , -2.841]| -4.033 ( 18 )|\n|2 (HIGH)|0.9637|[ -3.563 , 3.723]| 0.04614 ( 18 )|\n| All Dose Levels |0.06039| [ -7.567 , 0.167]| -1.915 ( 58 )| \n\n### Summary and Conclusion: \n1. We can see from the initial data analyses, the tooth length is highly correlated with dose level. The teeth grows with incresing dose regardless of supplement types. \nHowever, the teeth lenghts are more variable in Ascorbic Acid supplement types than in Orange Juice. \n2. As expected the difference of tooth growth between two supplement types are not statistically significant, when testing on mixed dose levels via two sample t-test (assumed the variances of two groups are equal). When testing the mean differences between two supplement types on different dose levels separately, surprisingly the highest dose level has no significant result as the low and medium levels. The test results showed no difference if the equal variance assumption is not held. \n3. If the data are correctly collected, the not statistically significant result of the highest dose level might be due to the limit of maximal tooth growth for a guinea pig. Because in the highest dose level, there might be no room for tooth to grow and results in the similar mean tooth growth (all reach the maximal capacity for tooth growth). On the other hand, the lowest level of dose might not be as sufficient to facilitate tooth growth as medium dose level. Therefore, the result of lowest level is not as significant as medium one. This conclusion if there is tooth growth difference in two supplement types would be much supported if more sample on medium dose level could be collected. \n\nThe souce code can be available in [statCourseProjectA2.md](https://github.com/renewang/datasciencecoursera/blob/master/statinference-PeerAssignment/statCourseProjectA2.md)\n"
},
{
"alpha_fraction": 0.7457002401351929,
"alphanum_fraction": 0.7800982594490051,
"avg_line_length": 53.06666564941406,
"blob_id": "b9b1e50f6cf203e213b84c191e634480e785ed8e",
"content_id": "1b04825e9e3b5a3ba3f0a05505064f4e2f4202f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 814,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 15,
"path": "/README.md",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "# Coursera Data Science Course Assignments \n## Johin Hopsking Data Science Specialization \n#### Exploratory Data Analysis (exdata-006) \n1. Peer Assignment 1 in ExData_Plotting1 directory. Please see README.md in ExData_Plotting1 for more information. \n2. Peer Assignment 2 in ExData_Plotting2 directory. Please see README.md in ExData_Plotting2 for more information. \n\n#### Reproducible Research (repdata-006) \n1. Peer Assignment 1 in repdataPeerAssignment1 directory. \n2. Peer Assignment 2 in repdataPeerAssignment2 directory. \n\n#### Getting and Cleaning Data (getdata-007) \n1. Course Project in getdataCourseProject directory. Please see README.md in getdataCourseProject for more information. \n\n#### Statistical Inference (statinference-005) \n1. Course Project in statinference-PeerAssignment directory. \n\n"
},
{
"alpha_fraction": 0.6521739363670349,
"alphanum_fraction": 0.6664291024208069,
"avg_line_length": 32.380950927734375,
"blob_id": "ff55b81db14f239a66b3c7d6f70ceff89bfd5003",
"content_id": "038cd38cf645aa6df6772a8837402f182ead9a44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 1403,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 42,
"path": "/ExData_Plotting2/procdata.R",
"repo_name": "renewang/datasciencecoursera",
"src_encoding": "UTF-8",
"text": "procdata<-function(datards=\"summarySCC_PM25.rds\",clsrds=\"Source_Classification_Code.rds\"){\n require(ggplot2);\n require(dplyr);\n \tNEI<-NULL;\n \tSCCD<-NULL;\n getNEI<-function(){\n\tif(is.null(NEI)){\n\t NEI <<- tbl_df(readRDS(datards));\n\t}\n\treturn(NEI);\n }\n getSCCD<-function(){\n\tif(is.null(SCCD)){\n \t SCCD <<- tbl_df(readRDS(clsrds));\n\t}\t\n \treturn(SCCD);\n }\n list(getNEI=getNEI, getSCCD=getSCCD); \n}\nFilterByCounty<-function(x, code){\n\treturn(PMEmitbycity<-filter(x,fips==code));\n}\nSumByYear<-function(x){\n\treturn(PMEmitbyYear<-summarize(x, ttlemit=sum(Emissions)));\n}\nFilterEmitBySrcLevel<-function(stat, srcls, srcLnum=1, srcLname=\"Mobile\"){\n\tbase = 3;\n\tDesireSrc<-grep(srcLname,levels(srcls[,base + srcLnum]),ignore.case=TRUE);\n\tSCCType<-filter(srcls, unclass(srcls[,base+srcLnum]) %in% DesireSrc);\n\tPMEmitbySrc<-filter(stat, unclass(SCC) %in% SCCType$SCC); \n\treturn(left_join(PMEmitbySrc,SCCType, by=\"SCC\")); \n}\t\nplotTTLEmitByYear<-function(x, pngfilename=NULL, ...){\n\ton.exit(dev.off());\n\twith(x, plot(ttlemit~year, type='l', xlab=\"Year\", ylab=\"Total Emissions from Fine Particulate Matter (PM2.5)\", \n\tmain=\"Figure of Total Emission Chagne with Year\",lwd=2, lty=2, xaxp=c(1999, 2008, 3), ...));\n\twith(x, points(ttlemit~year, pch='o', col=\"red\",cex=2),...);\n\tif(!is.null(pngfilename)){\n\t\tdev.copy(png,file=paste0(\"./figure/\",pngfilename));\n\t\ton.exit(dev.off());\n\t}\n}\n\n"
}
] | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.